From 94c7cd208a7779aafc645ec2acbce0e485ab0b27 Mon Sep 17 00:00:00 2001 From: gagik Date: Fri, 12 Dec 2025 13:00:34 +0100 Subject: [PATCH 1/9] chore: use erasable syntax --- package.json | 10 +- scripts/check-vsix-size.ts | 3 + scripts/generate-constants.ts | 4 +- scripts/generate-icon-font.ts | 8 +- scripts/precommit.ts | 8 +- scripts/update-grammar.ts | 3 + src/commands/index.ts | 167 +++++++++--------- src/connectionController.ts | 45 +++-- src/documentSource.ts | 15 +- src/editors/editDocumentCodeLensProvider.ts | 10 +- src/editors/mongoDBDocumentService.ts | 4 +- .../queryWithCopilotCodeLensProvider.ts | 4 +- src/explorer/collectionTreeItem.ts | 12 +- src/explorer/documentListTreeItem.ts | 19 +- src/explorer/explorerController.ts | 8 +- src/explorer/explorerTreeController.ts | 13 +- src/explorer/fieldTreeItem.ts | 88 ++++----- src/explorer/helpExplorer.ts | 5 +- src/explorer/indexTreeItem.ts | 35 ++-- src/explorer/playgroundsExplorer.ts | 4 +- src/extensionConstants.ts | 7 +- src/language/diagnosticCodes.ts | 9 +- src/language/languageServerController.ts | 42 +++-- src/language/mongoDBService.ts | 12 +- src/language/server.ts | 14 +- src/language/serverCommands.ts | 31 ++-- src/language/worker.ts | 8 +- src/mdbExtensionController.ts | 20 +-- src/participant/participant.ts | 16 +- src/participant/participantErrorTypes.ts | 17 +- src/participant/prompts/promptHistory.ts | 6 +- src/storage/connectionStorage.ts | 80 +++++---- src/storage/index.ts | 7 +- src/storage/storageController.ts | 80 +++++---- src/telemetry/connectionTelemetry.ts | 11 +- src/telemetry/telemetryEvents.ts | 10 +- src/telemetry/telemetryService.ts | 15 +- src/test/setup-webview.ts | 31 +++- src/test/suite/connectionController.test.ts | 152 ++++++++-------- .../collectionDocumentsProvider.test.ts | 23 ++- .../editDocumentCodeLensProvider.test.ts | 11 +- .../editors/mongoDBDocumentService.test.ts | 16 +- .../suite/explorer/collectionTreeItem.test.ts | 12 +- .../explorer/documentListTreeItem.test.ts | 10 +- .../suite/explorer/explorerController.test.ts | 22 +-- src/test/suite/explorer/indexTreeItem.test.ts | 4 +- .../suite/explorer/schemaTreeItem.test.ts | 4 +- .../suite/language/mongoDBService.test.ts | 4 +- .../mcp/mcpConnectionErrorHandler.test.ts | 13 +- src/test/suite/mdbExtensionController.test.ts | 38 ++-- .../suite/participant/participant.test.ts | 18 +- .../suite/storage/connectionStorage.test.ts | 92 +++++----- .../suite/storage/storageController.test.ts | 18 +- src/test/suite/stubbableMdbExtension.ts | 13 +- .../telemetry/connectionTelemetry.test.ts | 38 ++-- .../suite/telemetry/telemetryService.test.ts | 14 +- src/utils/playground.ts | 6 +- .../extension-app-message-constants.ts | 87 ++++----- src/views/webview-app/use-connection-form.ts | 13 +- .../webview-app/use-connection-status.ts | 5 +- src/views/webviewController.ts | 4 +- tsconfig.json | 3 +- tsconfig.test.json | 10 ++ 63 files changed, 834 insertions(+), 677 deletions(-) create mode 100644 tsconfig.test.json diff --git a/package.json b/package.json index 111fbca3d..d64f9eed3 100644 --- a/package.json +++ b/package.json @@ -42,10 +42,10 @@ "scripts": { "clean": "rimraf -g ./out/* ./dist/*", "lint": "eslint . && prettier --check .", - "update-grammar": "ts-node ./scripts/update-grammar.ts", + "update-grammar": "node ./scripts/update-grammar.ts", "precompile": "pnpm run clean", "compile": "npm-run-all compile:*", - "compile:constants": "ts-node ./scripts/generate-constants.ts", + "compile:constants": "node ./scripts/generate-constants.ts", "compile:resources": "pnpm run update-grammar", "compile:extension": "tsc -p ./", "compile:extension-bundles": "webpack --mode development", @@ -63,15 +63,15 @@ "depcheck": "depcheck", "package": "cross-env NODE_OPTIONS='--require ./scripts/no-npm-list-fail.js' vsce package --githubBranch main", "local-install": "pnpm run package && code --install-extension ./mongodb-vscode-*.vsix", - "check-vsix-size": "ts-node ./scripts/check-vsix-size.ts", + "check-vsix-size": "node ./scripts/check-vsix-size.ts", "release-draft": "node ./scripts/release-draft.js", "reformat": "prettier --write .", "snyk-test": "node scripts/snyk-test.js", - "generate-icon-font": "ts-node ./scripts/generate-icon-font.ts", + "generate-icon-font": "node ./scripts/generate-icon-font.ts", "generate-vulnerability-report": "mongodb-sbom-tools generate-vulnerability-report --snyk-reports=.sbom/snyk-test-result.json --dependencies=.sbom/dependencies.json --fail-on=high", "create-vulnerability-tickets": "mongodb-sbom-tools generate-vulnerability-report --snyk-reports=.sbom/snyk-test-result.json --dependencies=.sbom/dependencies.json --create-jira-issues", "prepare": "husky", - "precommit": "ts-node ./scripts/precommit.ts" + "precommit": "node --experimental-strip-types ./scripts/precommit.ts" }, "engines": { "vscode": "^1.101.1", diff --git a/scripts/check-vsix-size.ts b/scripts/check-vsix-size.ts index 0a84981ee..bcbda1cc1 100644 --- a/scripts/check-vsix-size.ts +++ b/scripts/check-vsix-size.ts @@ -1,5 +1,8 @@ import fs from 'fs'; import path from 'path'; +import { fileURLToPath } from 'url'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); const version = JSON.parse( fs.readFileSync(path.resolve(__dirname, '..', 'package.json')).toString(), diff --git a/scripts/generate-constants.ts b/scripts/generate-constants.ts index 4da51b7dc..552b02bea 100644 --- a/scripts/generate-constants.ts +++ b/scripts/generate-constants.ts @@ -1,4 +1,4 @@ -#! /usr/bin/env ts-node +#! /usr/bin/env node import ora from 'ora'; import fs from 'fs'; @@ -6,8 +6,10 @@ import path from 'path'; import { resolve } from 'path'; import { config } from 'dotenv'; import { promisify } from 'util'; +import { fileURLToPath } from 'url'; const writeFile = promisify(fs.writeFile); +const __dirname = path.dirname(fileURLToPath(import.meta.url)); const ROOT_DIR = path.join(__dirname, '..'); const ui = ora('Generate constants file').start(); diff --git a/scripts/generate-icon-font.ts b/scripts/generate-icon-font.ts index 290479c5c..363f2e4b1 100644 --- a/scripts/generate-icon-font.ts +++ b/scripts/generate-icon-font.ts @@ -1,7 +1,7 @@ -import webfont from 'webfont'; +import { webfont } from 'webfont'; import fs from 'fs/promises'; -import { GlyphData } from 'webfont/dist/src/types'; import prettier from 'prettier'; +import path from 'path'; /** Icons to include in the generated icon font */ const INCLUDED_ICONS = [ @@ -61,14 +61,14 @@ async function main(): Promise { const prettierConfig = await prettier.resolveConfig('./.prettierrc.json'); await fs.writeFile( './package.json', - prettier.format(JSON.stringify(currentConfiguration), { + await prettier.format(JSON.stringify(currentConfiguration), { ...prettierConfig, parser: 'json-stringify', }), ); } -function getUnicodeHex(glyph: GlyphData): string { +function getUnicodeHex(glyph: any): string { if (glyph.metadata?.unicode == undefined) { throw new Error('No unicode defined'); } diff --git a/scripts/precommit.ts b/scripts/precommit.ts index 34492dbb5..7afcc5449 100644 --- a/scripts/precommit.ts +++ b/scripts/precommit.ts @@ -1,11 +1,15 @@ -#! /usr/bin/env ts-node +#! /usr/bin/env node /* eslint-disable no-console */ import path from 'path'; import { promisify } from 'util'; import { execFile } from 'child_process'; +import prettier from '@mongodb-js/prettier-config-devtools/.prettierrc.json' with { type: 'json' }; const execFileAsync = promisify(execFile); +import { createRequire } from 'module'; +const require = createRequire(import.meta.url); + async function main(fileList: string[]) { if (fileList.length === 0) { console.log('No files to re-format. Skipping ...'); @@ -20,7 +24,7 @@ async function main(fileList: string[]) { await execFileAsync('npx', [ 'prettier', '--config', - require.resolve('@mongodb-js/prettier-config-devtools/.prettierrc.json'), + require.resolve(prettier), // Silently ignore files that are of format that is not supported by prettier. '--ignore-unknown', '--write', diff --git a/scripts/update-grammar.ts b/scripts/update-grammar.ts index d6c470e43..d783e13e4 100644 --- a/scripts/update-grammar.ts +++ b/scripts/update-grammar.ts @@ -3,6 +3,7 @@ import mkdirp from 'mkdirp'; import ora from 'ora'; import fs from 'fs'; import { promisify } from 'util'; +import { fileURLToPath } from 'url'; import { ACCUMULATORS, @@ -12,6 +13,8 @@ import { STAGE_OPERATORS, } from '@mongodb-js/mongodb-constants'; +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + const writeFile = promisify(fs.writeFile); const SYNTAXES_DIR = path.join(__dirname, '..', 'syntaxes'); diff --git a/src/commands/index.ts b/src/commands/index.ts index 6d0439853..ac020be2f 100644 --- a/src/commands/index.ts +++ b/src/commands/index.ts @@ -1,96 +1,105 @@ -enum EXTENSION_COMMANDS { - MDB_CONNECT = 'mdb.connect', - MDB_CONNECT_WITH_URI = 'mdb.connectWithURI', - MDB_OPEN_OVERVIEW_PAGE = 'mdb.openOverviewPage', - MDB_DISCONNECT = 'mdb.disconnect', - MDB_REMOVE_CONNECTION = 'mdb.removeConnection', +const EXTENSION_COMMANDS = { + MDB_CONNECT: 'mdb.connect', + MDB_CONNECT_WITH_URI: 'mdb.connectWithURI', + MDB_OPEN_OVERVIEW_PAGE: 'mdb.openOverviewPage', + MDB_DISCONNECT: 'mdb.disconnect', + MDB_REMOVE_CONNECTION: 'mdb.removeConnection', - OPEN_MONGODB_ISSUE_REPORTER = 'mdb.openMongoDBIssueReporter', + OPEN_MONGODB_ISSUE_REPORTER: 'mdb.openMongoDBIssueReporter', - MDB_OPEN_MDB_SHELL = 'mdb.openMongoDBShell', - MDB_OPEN_MDB_SHELL_FROM_TREE_VIEW = 'mdb.treeViewOpenMongoDBShell', + MDB_OPEN_MDB_SHELL: 'mdb.openMongoDBShell', + MDB_OPEN_MDB_SHELL_FROM_TREE_VIEW: 'mdb.treeViewOpenMongoDBShell', - MDB_CREATE_PLAYGROUND = 'mdb.createPlayground', - MDB_CREATE_PLAYGROUND_FROM_OVERVIEW_PAGE = 'mdb.createNewPlaygroundFromOverviewPage', - MDB_RUN_SELECTED_PLAYGROUND_BLOCKS = 'mdb.runSelectedPlaygroundBlocks', - MDB_RUN_ALL_PLAYGROUND_BLOCKS = 'mdb.runAllPlaygroundBlocks', - MDB_RUN_ALL_OR_SELECTED_PLAYGROUND_BLOCKS = 'mdb.runPlayground', - MDB_EXPORT_CODE_TO_PLAYGROUND = 'mdb.exportCodeToPlayground', + MDB_CREATE_PLAYGROUND: 'mdb.createPlayground', + MDB_CREATE_PLAYGROUND_FROM_OVERVIEW_PAGE: + 'mdb.createNewPlaygroundFromOverviewPage', + MDB_RUN_SELECTED_PLAYGROUND_BLOCKS: 'mdb.runSelectedPlaygroundBlocks', + MDB_RUN_ALL_PLAYGROUND_BLOCKS: 'mdb.runAllPlaygroundBlocks', + MDB_RUN_ALL_OR_SELECTED_PLAYGROUND_BLOCKS: 'mdb.runPlayground', + MDB_EXPORT_CODE_TO_PLAYGROUND: 'mdb.exportCodeToPlayground', - MDB_FIX_THIS_INVALID_INTERACTIVE_SYNTAX = 'mdb.fixThisInvalidInteractiveSyntax', - MDB_FIX_ALL_INVALID_INTERACTIVE_SYNTAX = 'mdb.fixAllInvalidInteractiveSyntax', + MDB_FIX_THIS_INVALID_INTERACTIVE_SYNTAX: + 'mdb.fixThisInvalidInteractiveSyntax', + MDB_FIX_ALL_INVALID_INTERACTIVE_SYNTAX: 'mdb.fixAllInvalidInteractiveSyntax', - MDB_SELECT_TARGET_FOR_EXPORT_TO_LANGUAGE = 'mdb.selectTargetForExportToLanguage', - MDB_EXPORT_TO_LANGUAGE = 'mdb.exportToLanguage', - MDB_CHANGE_DRIVER_SYNTAX_FOR_EXPORT_TO_LANGUAGE = 'mdb.changeDriverSyntaxForExportToLanguage', + MDB_SELECT_TARGET_FOR_EXPORT_TO_LANGUAGE: + 'mdb.selectTargetForExportToLanguage', + MDB_EXPORT_TO_LANGUAGE: 'mdb.exportToLanguage', + MDB_CHANGE_DRIVER_SYNTAX_FOR_EXPORT_TO_LANGUAGE: + 'mdb.changeDriverSyntaxForExportToLanguage', - MDB_OPEN_MONGODB_DOCUMENT_FROM_CODE_LENS = 'mdb.openMongoDBDocumentFromCodeLens', - MDB_OPEN_MONGODB_DOCUMENT_FROM_TREE = 'mdb.openMongoDBDocumentFromTree', - MDB_SAVE_MONGODB_DOCUMENT = 'mdb.saveMongoDBDocument', + MDB_OPEN_MONGODB_DOCUMENT_FROM_CODE_LENS: + 'mdb.openMongoDBDocumentFromCodeLens', + MDB_OPEN_MONGODB_DOCUMENT_FROM_TREE: 'mdb.openMongoDBDocumentFromTree', + MDB_SAVE_MONGODB_DOCUMENT: 'mdb.saveMongoDBDocument', - MDB_CHANGE_ACTIVE_CONNECTION = 'mdb.changeActiveConnection', + MDB_CHANGE_ACTIVE_CONNECTION: 'mdb.changeActiveConnection', - MDB_CODELENS_SHOW_MORE_DOCUMENTS = 'mdb.codeLens.showMoreDocumentsClicked', + MDB_CODELENS_SHOW_MORE_DOCUMENTS: 'mdb.codeLens.showMoreDocumentsClicked', // Commands from the tree view. - MDB_ADD_CONNECTION = 'mdb.addConnection', - MDB_ADD_CONNECTION_WITH_URI = 'mdb.addConnectionWithURI', - MDB_REFRESH_PLAYGROUNDS_FROM_TREE_VIEW = 'mdb.refreshPlaygroundsFromTreeView', - MDB_OPEN_PLAYGROUND_FROM_TREE_VIEW = 'mdb.openPlaygroundFromTreeView', - MDB_CONNECT_TO_CONNECTION_TREE_VIEW = 'mdb.connectToConnectionTreeItem', - MDB_CREATE_PLAYGROUND_FROM_TREE_VIEW = 'mdb.createNewPlaygroundFromTreeView', - MDB_CREATE_PLAYGROUND_FROM_TREE_ITEM = 'mdb.createNewPlaygroundFromTreeItem', - MDB_DISCONNECT_FROM_CONNECTION_TREE_VIEW = 'mdb.disconnectFromConnectionTreeItem', - MDB_EDIT_CONNECTION = 'mdb.editConnection', - MDB_REFRESH_CONNECTION = 'mdb.refreshConnection', - MDB_COPY_CONNECTION_STRING = 'mdb.copyConnectionString', - MDB_EDIT_PRESET_CONNECTIONS = 'mdb.editPresetConnections', - MDB_REMOVE_CONNECTION_TREE_VIEW = 'mdb.treeItemRemoveConnection', - MDB_RENAME_CONNECTION = 'mdb.renameConnection', - MDB_ADD_DATABASE = 'mdb.addDatabase', - MDB_SEARCH_FOR_DOCUMENTS = 'mdb.searchForDocuments', - MDB_COPY_DATABASE_NAME = 'mdb.copyDatabaseName', - MDB_DROP_DATABASE = 'mdb.dropDatabase', - MDB_REFRESH_DATABASE = 'mdb.refreshDatabase', - MDB_ADD_COLLECTION = 'mdb.addCollection', - MDB_COPY_COLLECTION_NAME = 'mdb.copyCollectionName', - MDB_DROP_COLLECTION = 'mdb.dropCollection', - MDB_VIEW_COLLECTION_DOCUMENTS = 'mdb.viewCollectionDocuments', - MDB_REFRESH_COLLECTION = 'mdb.refreshCollection', - MDB_REFRESH_DOCUMENT_LIST = 'mdb.refreshDocumentList', - MDB_INSERT_DOCUMENT_FROM_TREE_VIEW = 'mdb.insertDocumentFromTreeView', - MDB_REFRESH_SCHEMA = 'mdb.refreshSchema', - MDB_COPY_SCHEMA_FIELD_NAME = 'mdb.copySchemaFieldName', - MDB_REFRESH_INDEXES = 'mdb.refreshIndexes', - MDB_CREATE_INDEX_TREE_VIEW = 'mdb.createIndexFromTreeView', - MDB_INSERT_OBJECTID_TO_EDITOR = 'mdb.insertObjectIdToEditor', - MDB_GENERATE_OBJECTID_TO_CLIPBOARD = 'mdb.generateObjectIdToClipboard', - MDB_COPY_DOCUMENT_CONTENTS_FROM_TREE_VIEW = 'mdb.copyDocumentContentsFromTreeView', - MDB_CLONE_DOCUMENT_FROM_TREE_VIEW = 'mdb.cloneDocumentFromTreeView', - MDB_DELETE_DOCUMENT_FROM_TREE_VIEW = 'mdb.deleteDocumentFromTreeView', - MDB_ADD_STREAM_PROCESSOR = 'mdb.addStreamProcessor', - MDB_START_STREAM_PROCESSOR = 'mdb.startStreamProcessor', - MDB_STOP_STREAM_PROCESSOR = 'mdb.stopStreamProcessor', - MDB_DROP_STREAM_PROCESSOR = 'mdb.dropStreamProcessor', + MDB_ADD_CONNECTION: 'mdb.addConnection', + MDB_ADD_CONNECTION_WITH_URI: 'mdb.addConnectionWithURI', + MDB_REFRESH_PLAYGROUNDS_FROM_TREE_VIEW: 'mdb.refreshPlaygroundsFromTreeView', + MDB_OPEN_PLAYGROUND_FROM_TREE_VIEW: 'mdb.openPlaygroundFromTreeView', + MDB_CONNECT_TO_CONNECTION_TREE_VIEW: 'mdb.connectToConnectionTreeItem', + MDB_CREATE_PLAYGROUND_FROM_TREE_VIEW: 'mdb.createNewPlaygroundFromTreeView', + MDB_CREATE_PLAYGROUND_FROM_TREE_ITEM: 'mdb.createNewPlaygroundFromTreeItem', + MDB_DISCONNECT_FROM_CONNECTION_TREE_VIEW: + 'mdb.disconnectFromConnectionTreeItem', + MDB_EDIT_CONNECTION: 'mdb.editConnection', + MDB_REFRESH_CONNECTION: 'mdb.refreshConnection', + MDB_COPY_CONNECTION_STRING: 'mdb.copyConnectionString', + MDB_EDIT_PRESET_CONNECTIONS: 'mdb.editPresetConnections', + MDB_REMOVE_CONNECTION_TREE_VIEW: 'mdb.treeItemRemoveConnection', + MDB_RENAME_CONNECTION: 'mdb.renameConnection', + MDB_ADD_DATABASE: 'mdb.addDatabase', + MDB_SEARCH_FOR_DOCUMENTS: 'mdb.searchForDocuments', + MDB_COPY_DATABASE_NAME: 'mdb.copyDatabaseName', + MDB_DROP_DATABASE: 'mdb.dropDatabase', + MDB_REFRESH_DATABASE: 'mdb.refreshDatabase', + MDB_ADD_COLLECTION: 'mdb.addCollection', + MDB_COPY_COLLECTION_NAME: 'mdb.copyCollectionName', + MDB_DROP_COLLECTION: 'mdb.dropCollection', + MDB_VIEW_COLLECTION_DOCUMENTS: 'mdb.viewCollectionDocuments', + MDB_REFRESH_COLLECTION: 'mdb.refreshCollection', + MDB_REFRESH_DOCUMENT_LIST: 'mdb.refreshDocumentList', + MDB_INSERT_DOCUMENT_FROM_TREE_VIEW: 'mdb.insertDocumentFromTreeView', + MDB_REFRESH_SCHEMA: 'mdb.refreshSchema', + MDB_COPY_SCHEMA_FIELD_NAME: 'mdb.copySchemaFieldName', + MDB_REFRESH_INDEXES: 'mdb.refreshIndexes', + MDB_CREATE_INDEX_TREE_VIEW: 'mdb.createIndexFromTreeView', + MDB_INSERT_OBJECTID_TO_EDITOR: 'mdb.insertObjectIdToEditor', + MDB_GENERATE_OBJECTID_TO_CLIPBOARD: 'mdb.generateObjectIdToClipboard', + MDB_COPY_DOCUMENT_CONTENTS_FROM_TREE_VIEW: + 'mdb.copyDocumentContentsFromTreeView', + MDB_CLONE_DOCUMENT_FROM_TREE_VIEW: 'mdb.cloneDocumentFromTreeView', + MDB_DELETE_DOCUMENT_FROM_TREE_VIEW: 'mdb.deleteDocumentFromTreeView', + MDB_ADD_STREAM_PROCESSOR: 'mdb.addStreamProcessor', + MDB_START_STREAM_PROCESSOR: 'mdb.startStreamProcessor', + MDB_STOP_STREAM_PROCESSOR: 'mdb.stopStreamProcessor', + MDB_DROP_STREAM_PROCESSOR: 'mdb.dropStreamProcessor', // Chat participant. - OPEN_PARTICIPANT_CODE_IN_PLAYGROUND = 'mdb.openParticipantCodeInPlayground', - SEND_MESSAGE_TO_PARTICIPANT = 'mdb.sendMessageToParticipant', - SEND_MESSAGE_TO_PARTICIPANT_FROM_INPUT = 'mdb.sendMessageToParticipantFromInput', - ASK_COPILOT_FROM_TREE_ITEM = 'mdb.askCopilotFromTreeItem', - RUN_PARTICIPANT_CODE = 'mdb.runParticipantCode', - CONNECT_WITH_PARTICIPANT = 'mdb.connectWithParticipant', - SELECT_DATABASE_WITH_PARTICIPANT = 'mdb.selectDatabaseWithParticipant', - SELECT_COLLECTION_WITH_PARTICIPANT = 'mdb.selectCollectionWithParticipant', - PARTICIPANT_OPEN_RAW_SCHEMA_OUTPUT = 'mdb.participantViewRawSchemaOutput', - SHOW_EXPORT_TO_LANGUAGE_RESULT = 'mdb.showExportToLanguageResult', + OPEN_PARTICIPANT_CODE_IN_PLAYGROUND: 'mdb.openParticipantCodeInPlayground', + SEND_MESSAGE_TO_PARTICIPANT: 'mdb.sendMessageToParticipant', + SEND_MESSAGE_TO_PARTICIPANT_FROM_INPUT: + 'mdb.sendMessageToParticipantFromInput', + ASK_COPILOT_FROM_TREE_ITEM: 'mdb.askCopilotFromTreeItem', + RUN_PARTICIPANT_CODE: 'mdb.runParticipantCode', + CONNECT_WITH_PARTICIPANT: 'mdb.connectWithParticipant', + SELECT_DATABASE_WITH_PARTICIPANT: 'mdb.selectDatabaseWithParticipant', + SELECT_COLLECTION_WITH_PARTICIPANT: 'mdb.selectCollectionWithParticipant', + PARTICIPANT_OPEN_RAW_SCHEMA_OUTPUT: 'mdb.participantViewRawSchemaOutput', + SHOW_EXPORT_TO_LANGUAGE_RESULT: 'mdb.showExportToLanguageResult', // MCP Server commands. - START_MCP_SERVER = 'mdb.startMCPServer', - STOP_MCP_SERVER = 'mdb.stopMCPServer', - GET_MCP_SERVER_CONFIG = 'mdb.getMCPServerConfig', -} + START_MCP_SERVER: 'mdb.startMCPServer', + STOP_MCP_SERVER: 'mdb.stopMCPServer', + GET_MCP_SERVER_CONFIG: 'mdb.getMCPServerConfig', +} as const; -export type ExtensionCommand = EXTENSION_COMMANDS; +export type ExtensionCommand = + (typeof EXTENSION_COMMANDS)[keyof typeof EXTENSION_COMMANDS]; export default EXTENSION_COMMANDS; diff --git a/src/connectionController.ts b/src/connectionController.ts index 87c7ecf15..8108fa0a4 100644 --- a/src/connectionController.ts +++ b/src/connectionController.ts @@ -14,7 +14,10 @@ import { mongoLogId } from 'mongodb-log-writer'; import { extractSecrets } from '@mongodb-js/connection-info'; import { adjustConnectionOptionsBeforeConnect } from '@mongodb-js/connection-form'; -import { CONNECTION_STATUS } from './views/webview-app/extension-app-message-constants'; +import { + CONNECTION_STATUS, + type ConnectionStatus, +} from './views/webview-app/extension-app-message-constants'; import { createLogger } from './logging'; import formatError from './utils/formatError'; import type { StorageController } from './storage'; @@ -44,16 +47,22 @@ interface DataServiceEventTypes { ACTIVE_CONNECTION_CHANGED: []; } -export enum ConnectionTypes { - CONNECTION_FORM = 'CONNECTION_FORM', - CONNECTION_STRING = 'CONNECTION_STRING', - CONNECTION_ID = 'CONNECTION_ID', -} +export const CONNECTION_TYPES = { + CONNECTION_FORM: 'CONNECTION_FORM', + CONNECTION_STRING: 'CONNECTION_STRING', + CONNECTION_ID: 'CONNECTION_ID', +} as const; -export enum NewConnectionType { - NEW_CONNECTION = 'NEW_CONNECTION', - SAVED_CONNECTION = 'SAVED_CONNECTION', -} +export type ConnectionTypes = + (typeof CONNECTION_TYPES)[keyof typeof CONNECTION_TYPES]; + +export const NEW_CONNECTION_TYPE = { + NEW_CONNECTION: 'NEW_CONNECTION', + SAVED_CONNECTION: 'SAVED_CONNECTION', +} as const; + +export type NewConnectionType = + (typeof NEW_CONNECTION_TYPE)[keyof typeof NEW_CONNECTION_TYPE]; interface ConnectionAttemptResult { successfullyConnected: boolean; @@ -341,7 +350,7 @@ export default class ConnectionController { connectionOptions: { connectionString: connectionStringData.toString(), }, - connectionType: ConnectionTypes.CONNECTION_STRING, + connectionType: CONNECTION_TYPES.CONNECTION_STRING, name, })); @@ -689,7 +698,7 @@ export default class ConnectionController { const result = await this._connect( connectionId, - ConnectionTypes.CONNECTION_ID, + CONNECTION_TYPES.CONNECTION_ID, ); /** After successfully connecting with an overridden connection @@ -1148,7 +1157,7 @@ export default class ConnectionController { return url.toString(); } - getConnectionStatus(): CONNECTION_STATUS { + getConnectionStatus(): ConnectionStatus { if (this.isCurrentlyConnected()) { if (this.isDisconnecting()) { return CONNECTION_STATUS.DISCONNECTING; @@ -1209,7 +1218,7 @@ export default class ConnectionController { { label: 'Add new connection', data: { - type: NewConnectionType.NEW_CONNECTION, + type: NEW_CONNECTION_TYPE.NEW_CONNECTION, }, }, ]; @@ -1219,7 +1228,7 @@ export default class ConnectionController { { label: 'Add new connection', data: { - type: NewConnectionType.NEW_CONNECTION, + type: NEW_CONNECTION_TYPE.NEW_CONNECTION, }, }, ...Object.values(this._connections) @@ -1229,7 +1238,7 @@ export default class ConnectionController { .map((item: LoadedConnection) => ({ label: item.name, data: { - type: NewConnectionType.SAVED_CONNECTION, + type: NEW_CONNECTION_TYPE.SAVED_CONNECTION, connectionId: item.id, }, })), @@ -1248,7 +1257,9 @@ export default class ConnectionController { return false; } - if (selectedQuickPickItem.data.type === NewConnectionType.NEW_CONNECTION) { + if ( + selectedQuickPickItem.data.type === NEW_CONNECTION_TYPE.NEW_CONNECTION + ) { return this.connectWithURI(); } diff --git a/src/documentSource.ts b/src/documentSource.ts index 066c96cb6..1797080b7 100644 --- a/src/documentSource.ts +++ b/src/documentSource.ts @@ -1,8 +1,11 @@ -export enum DocumentSource { - DOCUMENT_SOURCE_TREEVIEW = 'treeview', - DOCUMENT_SOURCE_PLAYGROUND = 'playground', - DOCUMENT_SOURCE_COLLECTIONVIEW = 'collectionview', - DOCUMENT_SOURCE_CODELENS = 'codelens', -} +export const DOCUMENT_SOURCE = { + DOCUMENT_SOURCE_TREEVIEW: 'treeview', + DOCUMENT_SOURCE_PLAYGROUND: 'playground', + DOCUMENT_SOURCE_COLLECTIONVIEW: 'collectionview', + DOCUMENT_SOURCE_CODELENS: 'codelens', +} as const; + +export type DocumentSource = + (typeof DOCUMENT_SOURCE)[keyof typeof DOCUMENT_SOURCE]; export type DocumentSourceDetails = 'database' | 'collection' | undefined; diff --git a/src/editors/editDocumentCodeLensProvider.ts b/src/editors/editDocumentCodeLensProvider.ts index ea541dbfc..1f362a678 100644 --- a/src/editors/editDocumentCodeLensProvider.ts +++ b/src/editors/editDocumentCodeLensProvider.ts @@ -3,9 +3,9 @@ import { EJSON } from 'bson'; import type { Document } from 'bson'; import type ConnectionController from '../connectionController'; -import { DocumentSource } from '../documentSource'; +import { DOCUMENT_SOURCE, type DocumentSource } from '../documentSource'; import type { EditDocumentInfo } from '../types/editDocumentInfoType'; -import EXTENSION_COMMANDS from '../commands'; +import EXTENSION_COMMANDS, { type ExtensionCommand } from '../commands'; import { PLAYGROUND_RESULT_URI } from './playgroundResultProvider'; import type { PlaygroundRunResult } from '../types/playgroundType'; @@ -38,14 +38,14 @@ export default class EditDocumentCodeLensProvider resultCodeLensesInfo = this._updateCodeLensesForCursor({ ...data, - source: DocumentSource.DOCUMENT_SOURCE_COLLECTIONVIEW, + source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_COLLECTIONVIEW, }); this._codeLensesInfo[data.uri.toString()] = resultCodeLensesInfo; } updateCodeLensesForPlayground(playgroundResult: PlaygroundRunResult): void { - const source = DocumentSource.DOCUMENT_SOURCE_PLAYGROUND; + const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_PLAYGROUND; let resultCodeLensesInfo: EditDocumentInfo[] = []; if (!playgroundResult || !playgroundResult.content) { @@ -144,7 +144,7 @@ export default class EditDocumentCodeLensProvider const range = new vscode.Range(position, position); const command: { title: string; - command: EXTENSION_COMMANDS; + command: ExtensionCommand; arguments: EditDocumentInfo[]; } = { title: 'Edit Document', diff --git a/src/editors/mongoDBDocumentService.ts b/src/editors/mongoDBDocumentService.ts index 14e955b74..769be2c33 100644 --- a/src/editors/mongoDBDocumentService.ts +++ b/src/editors/mongoDBDocumentService.ts @@ -3,7 +3,7 @@ import type { Document } from 'bson'; import type ConnectionController from '../connectionController'; import { createLogger } from '../logging'; -import { DocumentSource } from '../documentSource'; +import { DOCUMENT_SOURCE, type DocumentSource } from '../documentSource'; import type { EditDocumentInfo } from '../types/editDocumentInfoType'; import formatError from '../utils/formatError'; import type { StatusView } from '../views'; @@ -53,7 +53,7 @@ export default class MongoDBDocumentService { this._telemetryService.track( new DocumentUpdatedTelemetryEvent( - DocumentSource.DOCUMENT_SOURCE_TREEVIEW, + DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW, false, ), ); diff --git a/src/editors/queryWithCopilotCodeLensProvider.ts b/src/editors/queryWithCopilotCodeLensProvider.ts index d1a95c7f7..b07eb54c3 100644 --- a/src/editors/queryWithCopilotCodeLensProvider.ts +++ b/src/editors/queryWithCopilotCodeLensProvider.ts @@ -3,7 +3,7 @@ import EXTENSION_COMMANDS from '../commands'; import type { SendMessageToParticipantFromInputOptions } from '../participant/participantTypes'; import { isPlayground } from '../utils/playground'; import { COPILOT_EXTENSION_ID } from '../participant/constants'; -import { DocumentSource } from '../documentSource'; +import { DOCUMENT_SOURCE } from '../documentSource'; export class QueryWithCopilotCodeLensProvider implements vscode.CodeLensProvider @@ -34,7 +34,7 @@ export class QueryWithCopilotCodeLensProvider command: 'query', isNewChat: true, telemetry: { - source: DocumentSource.DOCUMENT_SOURCE_CODELENS, + source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_CODELENS, source_details: undefined, }, }; diff --git a/src/explorer/collectionTreeItem.ts b/src/explorer/collectionTreeItem.ts index 72993bce9..9aa088693 100644 --- a/src/explorer/collectionTreeItem.ts +++ b/src/explorer/collectionTreeItem.ts @@ -3,7 +3,7 @@ import path from 'path'; import type { DataService } from 'mongodb-data-service'; import DocumentListTreeItem, { - CollectionTypes, + COLLECTION_TYPES, MAX_DOCUMENTS_VISIBLE, } from './documentListTreeItem'; import formatError from '../utils/formatError'; @@ -19,12 +19,12 @@ function getIconPath( const LIGHT = path.join(getImagesPath(), 'light'); const DARK = path.join(getImagesPath(), 'dark'); - if (type === CollectionTypes.timeseries) { + if (type === COLLECTION_TYPES.timeseries) { return { light: vscode.Uri.file(path.join(LIGHT, 'collection-timeseries.svg')), dark: vscode.Uri.file(path.join(DARK, 'collection-timeseries.svg')), }; - } else if (type === CollectionTypes.collection) { + } else if (type === COLLECTION_TYPES.collection) { if (isExpanded) { return { light: vscode.Uri.file(path.join(LIGHT, 'collection-folder-open.svg')), @@ -158,7 +158,7 @@ export default class CollectionTreeItem }); this.tooltip = - collection.type === CollectionTypes.view + collection.type === COLLECTION_TYPES.view ? 'Read only view' : collection.name; this.iconPath = getIconPath(collection.type, isExpanded); @@ -321,8 +321,8 @@ export default class CollectionTreeItem refreshDocumentCount = async (): Promise => { // Skip the count on views and time-series collections since it will error. if ( - this._type === CollectionTypes.view || - this._type === CollectionTypes.timeseries + this._type === COLLECTION_TYPES.view || + this._type === COLLECTION_TYPES.timeseries ) { this.documentCount = null; return 0; diff --git a/src/explorer/documentListTreeItem.ts b/src/explorer/documentListTreeItem.ts index d9d511620..f37fb0339 100644 --- a/src/explorer/documentListTreeItem.ts +++ b/src/explorer/documentListTreeItem.ts @@ -17,11 +17,14 @@ const log = createLogger('documents tree item'); export const MAX_DOCUMENTS_VISIBLE = 10; export const DOCUMENT_LIST_ITEM = 'documentListTreeItem'; -export enum CollectionTypes { - collection = 'collection', - view = 'view', - timeseries = 'timeseries', -} +export const COLLECTION_TYPES = { + collection: 'collection', + view: 'view', + timeseries: 'timeseries', +} as const; + +export type CollectionTypes = + (typeof COLLECTION_TYPES)[keyof typeof COLLECTION_TYPES]; const ITEM_LABEL = 'Documents'; @@ -53,7 +56,7 @@ const getCollapsableStateForDocumentList = ( isExpanded: boolean, type: string, ): vscode.TreeItemCollapsibleState => { - if (type === CollectionTypes.view) { + if (type === COLLECTION_TYPES.view) { return vscode.TreeItemCollapsibleState.None; } @@ -78,7 +81,7 @@ function getIconPath(): { light: vscode.Uri; dark: vscode.Uri } { } function getTooltip(type: string, documentCount: number | null): string { - const typeString = type === CollectionTypes.view ? 'View' : 'Collection'; + const typeString = type === COLLECTION_TYPES.view ? 'View' : 'Collection'; if (documentCount !== null) { return `${typeString} Documents - ${documentCount}`; } @@ -178,7 +181,7 @@ export default class DocumentListTreeItem } async getChildren(): Promise { - if (!this.isExpanded || this.type === CollectionTypes.view) { + if (!this.isExpanded || this.type === COLLECTION_TYPES.view) { return []; } diff --git a/src/explorer/explorerController.ts b/src/explorer/explorerController.ts index f29154d92..8caff6a10 100644 --- a/src/explorer/explorerController.ts +++ b/src/explorer/explorerController.ts @@ -6,13 +6,17 @@ import { createTrackedTreeView } from '../utils/treeViewHelper'; import type { TelemetryService } from '../telemetry'; export default class ExplorerController { + private _connectionController: ConnectionController; + private _telemetryService: TelemetryService; private _treeController: ExplorerTreeController; private _treeView?: vscode.TreeView; constructor( - private _connectionController: ConnectionController, - private _telemetryService: TelemetryService, + connectionController: ConnectionController, + telemetryService: TelemetryService, ) { + this._connectionController = connectionController; + this._telemetryService = telemetryService; this._treeController = new ExplorerTreeController( this._connectionController, this._telemetryService, diff --git a/src/explorer/explorerTreeController.ts b/src/explorer/explorerTreeController.ts index 135e9a923..fc83ee88b 100644 --- a/src/explorer/explorerTreeController.ts +++ b/src/explorer/explorerTreeController.ts @@ -4,7 +4,7 @@ import type ConnectionController from '../connectionController'; import ConnectionTreeItem from './connectionTreeItem'; import { createLogger } from '../logging'; import { DOCUMENT_ITEM } from './documentTreeItem'; -import { DOCUMENT_LIST_ITEM, CollectionTypes } from './documentListTreeItem'; +import { DOCUMENT_LIST_ITEM, COLLECTION_TYPES } from './documentListTreeItem'; import EXTENSION_COMMANDS from '../commands'; import { sortTreeItemsByLabel } from './treeItemUtils'; import type { LoadedConnection } from '../storage/connectionStorage'; @@ -20,11 +20,16 @@ export default class ExplorerTreeController implements vscode.TreeDataProvider { private _connectionTreeItems: { [key: string]: ConnectionTreeItem }; + private _connectionController: ConnectionController; + private _telemetryService: TelemetryService; constructor( - private _connectionController: ConnectionController, - private _telemetryService: TelemetryService, + connectionController: ConnectionController, + telemetryService: TelemetryService, ) { + this._connectionController = connectionController; + this._telemetryService = telemetryService; + this._onDidChangeTreeData = new vscode.EventEmitter(); this.onDidChangeTreeData = this._onDidChangeTreeData.event; @@ -122,7 +127,7 @@ export default class ExplorerTreeController if ( selectedItem.contextValue === DOCUMENT_LIST_ITEM && - selectedItem.type === CollectionTypes.view + selectedItem.type === COLLECTION_TYPES.view ) { await vscode.commands.executeCommand( EXTENSION_COMMANDS.MDB_VIEW_COLLECTION_DOCUMENTS, diff --git a/src/explorer/fieldTreeItem.ts b/src/explorer/fieldTreeItem.ts index 392c5af26..af73e8151 100644 --- a/src/explorer/fieldTreeItem.ts +++ b/src/explorer/fieldTreeItem.ts @@ -8,25 +8,27 @@ import type TreeItemParent from './treeItemParentInterface'; // types returned by `parseSchema` with `mongodb-schema`. // We have types for elements we have special handing for (icons). // https://docs.mongodb.com/manual/reference/bson-types/ -export enum FieldType { - array = 'Array', - binary = 'Binary', - bool = 'Boolean', - date = 'Date', - decimal = 'Decimal128', - document = 'Document', - int = '32-bit integer', - javascript = 'Javascript', - long = '64-bit integer', - null = 'Null', - number = 'Number', - object = 'Object', - objectId = 'ObjectID', - regex = 'Regular Expression', - string = 'String', - timestamp = 'Timestamp', - undefined = 'Undefined', -} +export const FIELD_TYPES = { + array: 'Array', + binary: 'Binary', + bool: 'Boolean', + date: 'Date', + decimal: 'Decimal128', + document: 'Document', + int: '32-bit integer', + javascript: 'Javascript', + long: '64-bit integer', + null: 'Null', + number: 'Number', + object: 'Object', + objectId: 'ObjectID', + regex: 'Regular Expression', + string: 'String', + timestamp: 'Timestamp', + undefined: 'Undefined', +} as const; + +export type FieldType = (typeof FIELD_TYPES)[keyof typeof FIELD_TYPES]; export type SchemaFieldType = { name: string; @@ -42,10 +44,10 @@ export type SchemaFieldType = { export const fieldIsExpandable = (field: SchemaFieldType): boolean => { return ( field.probability === 1 && - (field.type === FieldType.document || - field.type === FieldType.array || - field.bsonType === FieldType.document || - field.bsonType === FieldType.array) + (field.type === FIELD_TYPES.document || + field.type === FIELD_TYPES.array || + field.bsonType === FIELD_TYPES.document || + field.bsonType === FIELD_TYPES.array) ); }; @@ -75,44 +77,44 @@ export const getIconFileNameForField = ( // The field has polymorphic data types. return 'mixed-type'; } - if (fieldType === FieldType.array) { + if (fieldType === FIELD_TYPES.array) { return 'array'; } - if (fieldType === FieldType.binary) { + if (fieldType === FIELD_TYPES.binary) { return 'binary'; } - if (fieldType === FieldType.bool) { + if (fieldType === FIELD_TYPES.bool) { return 'boolean'; } - if (fieldType === FieldType.date) { + if (fieldType === FIELD_TYPES.date) { return 'date'; } - if (fieldType === FieldType.decimal) { + if (fieldType === FIELD_TYPES.decimal) { return 'double'; } - if (fieldType === FieldType.null) { + if (fieldType === FIELD_TYPES.null) { return 'null'; } if ( - fieldType === FieldType.int || - fieldType === FieldType.long || - fieldType === FieldType.number + fieldType === FIELD_TYPES.int || + fieldType === FIELD_TYPES.long || + fieldType === FIELD_TYPES.number ) { return 'number'; } - if (fieldType === FieldType.object || fieldType === FieldType.document) { + if (fieldType === FIELD_TYPES.object || fieldType === FIELD_TYPES.document) { return 'object'; } - if (fieldType === FieldType.objectId) { + if (fieldType === FIELD_TYPES.objectId) { return 'object-id'; } - if (fieldType === FieldType.regex) { + if (fieldType === FIELD_TYPES.regex) { return 'regex'; } - if (fieldType === FieldType.string) { + if (fieldType === FIELD_TYPES.string) { return 'string'; } - if (fieldType === FieldType.timestamp) { + if (fieldType === FIELD_TYPES.timestamp) { return 'timestamp'; } @@ -210,13 +212,13 @@ export default class FieldTreeItem this._childrenCache = {}; if ( - this.field.bsonType === FieldType.document || - this.field.type === FieldType.document + this.field.bsonType === FIELD_TYPES.document || + this.field.type === FIELD_TYPES.document ) { let subDocumentFields; - if (this.field.type === FieldType.document && this.field.types) { + if (this.field.type === FIELD_TYPES.document && this.field.types) { subDocumentFields = this.field.types[0].fields; - } else if (this.field.bsonType === FieldType.document) { + } else if (this.field.bsonType === FIELD_TYPES.document) { subDocumentFields = this.field.fields; } @@ -239,8 +241,8 @@ export default class FieldTreeItem }); } } else if ( - (this.field.type === FieldType.array || - this.field.bsonType === FieldType.array) && + (this.field.type === FIELD_TYPES.array || + this.field.bsonType === FIELD_TYPES.array) && this.field.types ) { const arrayElement = this.field.types[0]; diff --git a/src/explorer/helpExplorer.ts b/src/explorer/helpExplorer.ts index 9e1e61f99..73b6687f0 100644 --- a/src/explorer/helpExplorer.ts +++ b/src/explorer/helpExplorer.ts @@ -6,8 +6,9 @@ import { createTrackedTreeView } from '../utils/treeViewHelper'; export default class HelpExplorer { _treeController: HelpTree; _treeView?: vscode.TreeView; - - constructor(private _telemetryService: TelemetryService) { + private _telemetryService: TelemetryService; + constructor(telemetryService: TelemetryService) { + this._telemetryService = telemetryService; this._treeController = new HelpTree(); } diff --git a/src/explorer/indexTreeItem.ts b/src/explorer/indexTreeItem.ts index a4a2c6b5b..40e50c158 100644 --- a/src/explorer/indexTreeItem.ts +++ b/src/explorer/indexTreeItem.ts @@ -4,15 +4,18 @@ import path from 'path'; import { getImagesPath } from '../extensionConstants'; import type TreeItemParent from './treeItemParentInterface'; -export enum IndexKeyType { - ASCENDING = 1, - DESCENDING = -1, - TEXT = 'text', - HASHED = 'hashed', - GEO = '2d', // flat, cartesian geometry - GEOSPHERE = '2dsphere', // index assuming a spherical geometry - GEOHAYSTACK = 'geoHaystack', -} +export const INDEX_KEY_TYPES = { + ASCENDING: 1, + DESCENDING: -1, + TEXT: 'text', + HASHED: 'hashed', + GEO: '2d', // flat, cartesian geometry + GEOSPHERE: '2dsphere', // index assuming a spherical geometry + GEOHAYSTACK: 'geoHaystack', +} as const; + +export type IndexKeyType = + (typeof INDEX_KEY_TYPES)[keyof typeof INDEX_KEY_TYPES]; export type IndexModel = { v: number; @@ -24,26 +27,26 @@ export type IndexModel = { }; function getIconNameForIndexKeyType(indexKeyType: IndexKeyType): string { - if (indexKeyType === IndexKeyType.ASCENDING) { + if (indexKeyType === INDEX_KEY_TYPES.ASCENDING) { return 'ascending'; } - if (indexKeyType === IndexKeyType.DESCENDING) { + if (indexKeyType === INDEX_KEY_TYPES.DESCENDING) { return 'descending'; } - if (indexKeyType === IndexKeyType.TEXT) { + if (indexKeyType === INDEX_KEY_TYPES.TEXT) { return 'text'; } - if (indexKeyType === IndexKeyType.HASHED) { + if (indexKeyType === INDEX_KEY_TYPES.HASHED) { return 'hashed'; } if ( - indexKeyType === IndexKeyType.GEO || - indexKeyType === IndexKeyType.GEOHAYSTACK || - indexKeyType === IndexKeyType.GEOSPHERE + indexKeyType === INDEX_KEY_TYPES.GEO || + indexKeyType === INDEX_KEY_TYPES.GEOHAYSTACK || + indexKeyType === INDEX_KEY_TYPES.GEOSPHERE ) { return 'geospatial'; } diff --git a/src/explorer/playgroundsExplorer.ts b/src/explorer/playgroundsExplorer.ts index 84444cd02..c8fbe4f7f 100644 --- a/src/explorer/playgroundsExplorer.ts +++ b/src/explorer/playgroundsExplorer.ts @@ -6,8 +6,10 @@ import { createTrackedTreeView } from '../utils/treeViewHelper'; export default class PlaygroundsExplorer { private _treeController: PlaygroundsTree; private _treeView?: vscode.TreeView; + private _telemetryService: TelemetryService; - constructor(private _telemetryService: TelemetryService) { + constructor(telemetryService: TelemetryService) { + this._telemetryService = telemetryService; this._treeController = new PlaygroundsTree(); } diff --git a/src/extensionConstants.ts b/src/extensionConstants.ts index d9ab184a0..d4914f55e 100644 --- a/src/extensionConstants.ts +++ b/src/extensionConstants.ts @@ -1,9 +1,8 @@ import type { ExtensionContext } from 'vscode'; -// eslint-disable-next-line @typescript-eslint/no-namespace -export namespace ext { - export let context: ExtensionContext; -} +export const ext = { + context: undefined as unknown as ExtensionContext, +}; export function getImagesPath(): string { return ext.context.asAbsolutePath('images'); diff --git a/src/language/diagnosticCodes.ts b/src/language/diagnosticCodes.ts index 872310790..4166871f6 100644 --- a/src/language/diagnosticCodes.ts +++ b/src/language/diagnosticCodes.ts @@ -1,5 +1,8 @@ -enum DIAGNOSTIC_CODES { - invalidInteractiveSyntaxes = 'playground.invalidInteractiveSyntaxes', -} +export const DIAGNOSTIC_CODES = { + invalidInteractiveSyntaxes: 'playground.invalidInteractiveSyntaxes', +} as const; + +export type DiagnosticCodes = + (typeof DIAGNOSTIC_CODES)[keyof typeof DIAGNOSTIC_CODES]; export default DIAGNOSTIC_CODES; diff --git a/src/language/languageServerController.ts b/src/language/languageServerController.ts index fa1b26ed3..1b31d7f69 100644 --- a/src/language/languageServerController.ts +++ b/src/language/languageServerController.ts @@ -16,7 +16,7 @@ import type { ShellEvaluateResult, } from '../types/playgroundType'; import type { ClearCompletionsCache } from '../types/completionsCache'; -import { ServerCommands } from './serverCommands'; +import { SERVER_COMMANDS } from './serverCommands'; const log = createLogger('language server controller'); @@ -111,7 +111,7 @@ export default class LanguageServerController { // If the connection to server got closed, server will restart, // but we also need to re-send default configurations // https://jira.mongodb.org/browse/VSCODE-448 - this._client.onNotification(ServerCommands.MONGODB_SERVICE_CREATED, () => { + this._client.onNotification(SERVER_COMMANDS.MONGODB_SERVICE_CREATED, () => { const msg = this._currentConnectionId ? 'MongoDBService restored from an internal error' : 'MongoDBService initialized'; @@ -123,21 +123,27 @@ export default class LanguageServerController { hasConnectionOptions: !!this._currentConnectionOptions, })}`, ); - void this._client.sendRequest(ServerCommands.INITIALIZE_MONGODB_SERVICE, { - extensionPath: this._context.extensionPath, - connectionId: this._currentConnectionId, - connectionString: this._currentConnectionString, - connectionOptions: this._currentConnectionOptions, - }); + void this._client.sendRequest( + SERVER_COMMANDS.INITIALIZE_MONGODB_SERVICE, + { + extensionPath: this._context.extensionPath, + connectionId: this._currentConnectionId, + connectionString: this._currentConnectionString, + connectionOptions: this._currentConnectionOptions, + }, + ); }); - this._client.onNotification(ServerCommands.SHOW_INFO_MESSAGE, (message) => { - log.info('The info message shown to a user', message); - void vscode.window.showInformationMessage(message); - }); + this._client.onNotification( + SERVER_COMMANDS.SHOW_INFO_MESSAGE, + (message) => { + log.info('The info message shown to a user', message); + void vscode.window.showInformationMessage(message); + }, + ); this._client.onNotification( - ServerCommands.SHOW_ERROR_MESSAGE, + SERVER_COMMANDS.SHOW_ERROR_MESSAGE, (message) => { log.info('The error message shown to a user', message); void vscode.window.showErrorMessage(message); @@ -145,7 +151,7 @@ export default class LanguageServerController { ); this._client.onNotification( - ServerCommands.SHOW_CONSOLE_OUTPUT, + SERVER_COMMANDS.SHOW_CONSOLE_OUTPUT, (outputs) => { for (const line of outputs) { this._consoleOutputChannel.appendLine( @@ -184,7 +190,7 @@ export default class LanguageServerController { // to the language server instance to execute scripts from a playground // and return results to the playground controller when ready. const res: ShellEvaluateResult = await this._client.sendRequest( - ServerCommands.EXECUTE_CODE_FROM_PLAYGROUND, + SERVER_COMMANDS.EXECUTE_CODE_FROM_PLAYGROUND, playgroundExecuteParameters, token, ); @@ -217,7 +223,7 @@ export default class LanguageServerController { this._currentConnectionOptions = connectionOptions; const res = await this._client.sendRequest( - ServerCommands.ACTIVE_CONNECTION_CHANGED, + SERVER_COMMANDS.ACTIVE_CONNECTION_CHANGED, { connectionId, connectionString, @@ -230,14 +236,14 @@ export default class LanguageServerController { async resetCache(clear: ClearCompletionsCache): Promise { log.info('Resetting MongoDBService cache...', clear); await this._client.sendRequest( - ServerCommands.CLEAR_CACHED_COMPLETIONS, + SERVER_COMMANDS.CLEAR_CACHED_COMPLETIONS, clear, ); } async updateCurrentSessionFields(params): Promise { await this._client.sendRequest( - ServerCommands.UPDATE_CURRENT_SESSION_FIELDS, + SERVER_COMMANDS.UPDATE_CURRENT_SESSION_FIELDS, params, ); } diff --git a/src/language/mongoDBService.ts b/src/language/mongoDBService.ts index f6b0e102a..7e767c01b 100644 --- a/src/language/mongoDBService.ts +++ b/src/language/mongoDBService.ts @@ -25,7 +25,7 @@ import { isAtlasStream } from 'mongodb-build-info'; import { Worker as WorkerThreads } from 'worker_threads'; import formatError from '../utils/formatError'; -import { ServerCommands } from './serverCommands'; +import { SERVER_COMMANDS } from './serverCommands'; import type { ShellEvaluateResult, PlaygroundEvaluateParams, @@ -227,7 +227,7 @@ export default class MongoDBService { return new Promise((resolve) => { if (this._currentConnectionId !== params.connectionId) { void this._connection.sendNotification( - ServerCommands.SHOW_ERROR_MESSAGE, + SERVER_COMMANDS.SHOW_ERROR_MESSAGE, "The playground's active connection does not match the extension's active connection. Please reconnect and try again.", ); return resolve(null); @@ -267,11 +267,11 @@ export default class MongoDBService { ); worker?.on('message', ({ name, payload }) => { - if (name === ServerCommands.SHOW_CONSOLE_OUTPUT) { + if (name === SERVER_COMMANDS.SHOW_CONSOLE_OUTPUT) { void this._connection.sendNotification(name, payload); } - if (name === ServerCommands.CODE_EXECUTION_RESULT) { + if (name === SERVER_COMMANDS.CODE_EXECUTION_RESULT) { const { error, data } = payload as { data: ShellEvaluateResult | null; error?: any; @@ -281,7 +281,7 @@ export default class MongoDBService { `WORKER error: ${util.inspect(error)}`, ); void this._connection.sendNotification( - ServerCommands.SHOW_ERROR_MESSAGE, + SERVER_COMMANDS.SHOW_ERROR_MESSAGE, formatError(error).message, ); } @@ -292,7 +292,7 @@ export default class MongoDBService { }); worker.postMessage({ - name: ServerCommands.EXECUTE_CODE_FROM_PLAYGROUND, + name: SERVER_COMMANDS.EXECUTE_CODE_FROM_PLAYGROUND, data: { codeToEvaluate: params.codeToEvaluate, filePath: params.filePath, diff --git a/src/language/server.ts b/src/language/server.ts index 5717f7512..2f45a22e3 100644 --- a/src/language/server.ts +++ b/src/language/server.ts @@ -16,7 +16,7 @@ import { import { TextDocument } from 'vscode-languageserver-textdocument'; import MongoDBService from './mongoDBService'; -import { ServerCommands } from './serverCommands'; +import { SERVER_COMMANDS } from './serverCommands'; import type { PlaygroundEvaluateParams } from '../types/playgroundType'; import type { ClearCompletionsCache } from '../types/completionsCache'; @@ -78,7 +78,7 @@ connection.onInitialize((params: InitializeParams) => { connection.onInitialized(() => { void connection.sendNotification( - ServerCommands.MONGODB_SERVICE_CREATED, + SERVER_COMMANDS.MONGODB_SERVICE_CREATED, 'An instance of MongoDBService is created', ); @@ -158,25 +158,25 @@ connection.onDidChangeWatchedFiles((/* _change */) => { // Execute a playground. connection.onRequest( - ServerCommands.EXECUTE_CODE_FROM_PLAYGROUND, + SERVER_COMMANDS.EXECUTE_CODE_FROM_PLAYGROUND, (evaluateParams: PlaygroundEvaluateParams, token: CancellationToken) => { return mongoDBService.evaluate(evaluateParams, token); }, ); // Send default configurations to mongoDBService. -connection.onRequest(ServerCommands.INITIALIZE_MONGODB_SERVICE, (settings) => { +connection.onRequest(SERVER_COMMANDS.INITIALIZE_MONGODB_SERVICE, (settings) => { mongoDBService.initialize(settings); }); // Change NodeDriverServiceProvider active connection. -connection.onRequest(ServerCommands.ACTIVE_CONNECTION_CHANGED, (params) => { +connection.onRequest(SERVER_COMMANDS.ACTIVE_CONNECTION_CHANGED, (params) => { return mongoDBService.activeConnectionChanged(params); }); // Set fields for tests. connection.onRequest( - ServerCommands.UPDATE_CURRENT_SESSION_FIELDS, + SERVER_COMMANDS.UPDATE_CURRENT_SESSION_FIELDS, ({ namespace, schemaFields }) => { return mongoDBService.cacheFields(namespace, schemaFields); }, @@ -184,7 +184,7 @@ connection.onRequest( // Clear cached completions by provided cache names. connection.onRequest( - ServerCommands.CLEAR_CACHED_COMPLETIONS, + SERVER_COMMANDS.CLEAR_CACHED_COMPLETIONS, (clear: ClearCompletionsCache) => { return mongoDBService.clearCachedCompletions(clear); }, diff --git a/src/language/serverCommands.ts b/src/language/serverCommands.ts index 3a7822422..9f629f3e3 100644 --- a/src/language/serverCommands.ts +++ b/src/language/serverCommands.ts @@ -1,17 +1,20 @@ -export enum ServerCommands { - ACTIVE_CONNECTION_CHANGED = 'ACTIVE_CONNECTION_CHANGED', - EXECUTE_CODE_FROM_PLAYGROUND = 'EXECUTE_CODE_FROM_PLAYGROUND', - EXECUTE_RANGE_FROM_PLAYGROUND = 'EXECUTE_RANGE_FROM_PLAYGROUND', - SHOW_ERROR_MESSAGE = 'SHOW_ERROR_MESSAGE', - SHOW_INFO_MESSAGE = 'SHOW_INFO_MESSAGE', - GET_EXPORT_TO_LANGUAGE_MODE = 'GET_EXPORT_TO_LANGUAGE_MODE', - UPDATE_CURRENT_SESSION_FIELDS = 'UPDATE_CURRENT_SESSION_FIELDS', - CLEAR_CACHED_COMPLETIONS = 'CLEAR_CACHED_COMPLETIONS', - MONGODB_SERVICE_CREATED = 'MONGODB_SERVICE_CREATED', - INITIALIZE_MONGODB_SERVICE = 'INITIALIZE_MONGODB_SERVICE', - CODE_EXECUTION_RESULT = 'CODE_EXECUTION_RESULT', - SHOW_CONSOLE_OUTPUT = 'SHOW_CONSOLE_OUTPUT', -} +export const SERVER_COMMANDS = { + ACTIVE_CONNECTION_CHANGED: 'ACTIVE_CONNECTION_CHANGED', + EXECUTE_CODE_FROM_PLAYGROUND: 'EXECUTE_CODE_FROM_PLAYGROUND', + EXECUTE_RANGE_FROM_PLAYGROUND: 'EXECUTE_RANGE_FROM_PLAYGROUND', + SHOW_ERROR_MESSAGE: 'SHOW_ERROR_MESSAGE', + SHOW_INFO_MESSAGE: 'SHOW_INFO_MESSAGE', + GET_EXPORT_TO_LANGUAGE_MODE: 'GET_EXPORT_TO_LANGUAGE_MODE', + UPDATE_CURRENT_SESSION_FIELDS: 'UPDATE_CURRENT_SESSION_FIELDS', + CLEAR_CACHED_COMPLETIONS: 'CLEAR_CACHED_COMPLETIONS', + MONGODB_SERVICE_CREATED: 'MONGODB_SERVICE_CREATED', + INITIALIZE_MONGODB_SERVICE: 'INITIALIZE_MONGODB_SERVICE', + CODE_EXECUTION_RESULT: 'CODE_EXECUTION_RESULT', + SHOW_CONSOLE_OUTPUT: 'SHOW_CONSOLE_OUTPUT', +} as const; + +export type ServerCommands = + (typeof SERVER_COMMANDS)[keyof typeof SERVER_COMMANDS]; export type PlaygroundRunParameters = { codeToEvaluate: string; diff --git a/src/language/worker.ts b/src/language/worker.ts index 0fea36a93..f93e935dc 100644 --- a/src/language/worker.ts +++ b/src/language/worker.ts @@ -1,7 +1,7 @@ import { NodeDriverServiceProvider } from '@mongosh/service-provider-node-driver'; import { ElectronRuntime } from '@mongosh/browser-runtime-electron'; import { parentPort } from 'worker_threads'; -import { ServerCommands } from './serverCommands'; +import { SERVER_COMMANDS } from './serverCommands'; import type { ShellEvaluateResult, @@ -44,7 +44,7 @@ type ExecuteCodeOptions = { function handleEvalPrint(values: EvaluationResult[]): void { parentPort?.postMessage({ - name: ServerCommands.SHOW_CONSOLE_OUTPUT, + name: SERVER_COMMANDS.SHOW_CONSOLE_OUTPUT, payload: values.map((v) => { return typeof v.printable === 'string' ? v.printable @@ -124,9 +124,9 @@ export const execute = async ({ }; const handleMessageFromParentPort = async ({ name, data }): Promise => { - if (name === ServerCommands.EXECUTE_CODE_FROM_PLAYGROUND) { + if (name === SERVER_COMMANDS.EXECUTE_CODE_FROM_PLAYGROUND) { parentPort?.postMessage({ - name: ServerCommands.CODE_EXECUTION_RESULT, + name: SERVER_COMMANDS.CODE_EXECUTION_RESULT, payload: await execute(data), }); } diff --git a/src/mdbExtensionController.ts b/src/mdbExtensionController.ts index d83db3bb3..f8e9c0d52 100644 --- a/src/mdbExtensionController.ts +++ b/src/mdbExtensionController.ts @@ -12,7 +12,7 @@ import ConnectionController from './connectionController'; import type ConnectionTreeItem from './explorer/connectionTreeItem'; import type DatabaseTreeItem from './explorer/databaseTreeItem'; import type DocumentListTreeItem from './explorer/documentListTreeItem'; -import { DocumentSource } from './documentSource'; +import { DOCUMENT_SOURCE } from './documentSource'; import type DocumentTreeItem from './explorer/documentTreeItem'; import EditDocumentCodeLensProvider from './editors/editDocumentCodeLensProvider'; import { EditorsController, PlaygroundController } from './editors'; @@ -32,7 +32,7 @@ import { LanguageServerController } from './language'; import launchMongoShell from './commands/launchMongoShell'; import type SchemaTreeItem from './explorer/schemaTreeItem'; import { StatusView } from './views'; -import { StorageController, StorageVariables } from './storage'; +import { StorageController, STORAGE_VARIABLES } from './storage'; import { DeepLinkTelemetryEvent, TelemetryService } from './telemetry'; import type PlaygroundsTreeItem from './explorer/playgroundsTreeItem'; import PlaygroundResultProvider from './editors/playgroundResultProvider'; @@ -340,9 +340,7 @@ export default class MDBExtensionController implements vscode.Disposable { try { if ( - !Object.values(EXTENSION_COMMANDS).includes( - command as EXTENSION_COMMANDS, - ) + !Object.values(EXTENSION_COMMANDS).includes(command as ExtensionCommand) ) { throw new Error( `Unable to execute command '${command}' since it is not registered by the MongoDB extension.`, @@ -350,9 +348,9 @@ export default class MDBExtensionController implements vscode.Disposable { } if ( - ( - DEEP_LINK_DISALLOWED_COMMANDS as readonly EXTENSION_COMMANDS[] - ).includes(command as EXTENSION_COMMANDS) + (DEEP_LINK_DISALLOWED_COMMANDS as readonly ExtensionCommand[]).includes( + command as ExtensionCommand, + ) ) { throw new Error( `Command '${command}' cannot be invoked via deep links.`, @@ -873,7 +871,7 @@ export default class MDBExtensionController implements vscode.Disposable { EXTENSION_COMMANDS.MDB_OPEN_MONGODB_DOCUMENT_FROM_TREE, (element: DocumentTreeItem): Promise => { return this._editorsController.openMongoDBDocument({ - source: DocumentSource.DOCUMENT_SOURCE_TREEVIEW, + source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW, documentId: element.documentId, namespace: element.namespace, connectionId: this._connectionController.getActiveConnectionId(), @@ -1161,7 +1159,7 @@ export default class MDBExtensionController implements vscode.Disposable { } const hasBeenShownViewAlready = !!this._storageController.get( - StorageVariables.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, + STORAGE_VARIABLES.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, ); if (hasBeenShownViewAlready) { @@ -1177,7 +1175,7 @@ export default class MDBExtensionController implements vscode.Disposable { } void this._storageController.update( - StorageVariables.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, + STORAGE_VARIABLES.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, true, ); } diff --git a/src/participant/participant.ts b/src/participant/participant.ts index 42f95c6b7..04181140d 100644 --- a/src/participant/participant.ts +++ b/src/participant/participant.ts @@ -9,7 +9,7 @@ import type ConnectionController from '../connectionController'; import type { LoadedConnection } from '../storage/connectionStorage'; import EXTENSION_COMMANDS from '../commands'; import type { StorageController } from '../storage'; -import { StorageVariables } from '../storage'; +import { STORAGE_VARIABLES } from '../storage'; import { getContentLength, Prompts } from './prompts'; import type { ChatResult } from './constants'; import { @@ -54,7 +54,7 @@ import type { PromptIntent } from './prompts/intent'; import { isPlayground, getSelectedText, getAllText } from '../utils/playground'; import type { DataService } from 'mongodb-data-service'; import { - ParticipantErrorTypes, + PARTICIPANT_ERROR_TYPES, type ExportToPlaygroundError, } from './participantErrorTypes'; import type PlaygroundResultProvider from '../editors/playgroundResultProvider'; @@ -69,7 +69,7 @@ import type { import { DEFAULT_EXPORT_TO_LANGUAGE_DRIVER_SYNTAX } from '../editors/exportToLanguageCodeLensProvider'; import { EXPORT_TO_LANGUAGE_ALIASES } from '../editors/playgroundSelectionCodeActionProvider'; import { CollectionTreeItem, DatabaseTreeItem } from '../explorer'; -import { DocumentSource } from '../documentSource'; +import { DOCUMENT_SOURCE } from '../documentSource'; const log = createLogger('participant'); @@ -241,7 +241,7 @@ export default class ParticipantController { message: `I want to ask questions about the \`${databaseName}\` database.`, isNewChat: true, telemetry: { - source: DocumentSource.DOCUMENT_SOURCE_TREEVIEW, + source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW, source_details: 'database', }, }); @@ -252,7 +252,7 @@ export default class ParticipantController { message: `I want to ask questions about the \`${databaseName}\` database's \`${collectionName}\` collection.`, isNewChat: true, telemetry: { - source: DocumentSource.DOCUMENT_SOURCE_TREEVIEW, + source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW, source_details: 'collection', }, }); @@ -1779,7 +1779,7 @@ export default class ParticipantController { this._telemetryService.track( new ParticipantResponseFailedTelemetryEvent( 'docs', - ParticipantErrorTypes.DOCS_CHATBOT_API, + PARTICIPANT_ERROR_TYPES.DOCS_CHATBOT_API, ), ); @@ -1973,7 +1973,7 @@ export default class ParticipantController { const [request, , stream] = args; try { const hasBeenShownWelcomeMessageAlready = !!this._storageController.get( - StorageVariables.COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE, + STORAGE_VARIABLES.COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE, ); if (!hasBeenShownWelcomeMessageAlready) { stream.markdown( @@ -1988,7 +1988,7 @@ Please see our [FAQ](https://www.mongodb.com/docs/generative-ai-faq/) for more i ); await this._storageController.update( - StorageVariables.COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE, + STORAGE_VARIABLES.COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE, true, ); } diff --git a/src/participant/participantErrorTypes.ts b/src/participant/participantErrorTypes.ts index d83ce8598..221116f9a 100644 --- a/src/participant/participantErrorTypes.ts +++ b/src/participant/participantErrorTypes.ts @@ -1,10 +1,13 @@ -export enum ParticipantErrorTypes { - CHAT_MODEL_OFF_TOPIC = 'Chat Model Off Topic', - INVALID_PROMPT = 'Invalid Prompt', - FILTERED = 'Filtered by Responsible AI Service', - OTHER = 'Other', - DOCS_CHATBOT_API = 'Docs Chatbot API Issue', -} +export const PARTICIPANT_ERROR_TYPES = { + CHAT_MODEL_OFF_TOPIC: 'Chat Model Off Topic', + INVALID_PROMPT: 'Invalid Prompt', + FILTERED: 'Filtered by Responsible AI Service', + OTHER: 'Other', + DOCS_CHATBOT_API: 'Docs Chatbot API Issue', +} as const; + +export type ParticipantErrorType = + (typeof PARTICIPANT_ERROR_TYPES)[keyof typeof PARTICIPANT_ERROR_TYPES]; export type ExportToPlaygroundError = | 'cancelled' diff --git a/src/participant/prompts/promptHistory.ts b/src/participant/prompts/promptHistory.ts index 86226d71d..0804cfb9d 100644 --- a/src/participant/prompts/promptHistory.ts +++ b/src/participant/prompts/promptHistory.ts @@ -1,5 +1,5 @@ import * as vscode from 'vscode'; -import { ParticipantErrorTypes } from '../participantErrorTypes'; +import { PARTICIPANT_ERROR_TYPES } from '../participantErrorTypes'; import type { ChatResult } from '../constants'; import type { ParticipantResponseType } from '../participantTypes'; @@ -13,7 +13,7 @@ export class PromptHistory { }): vscode.LanguageModelChatMessage | undefined { if ( currentTurn.result.errorDetails?.message === - ParticipantErrorTypes.FILTERED + PARTICIPANT_ERROR_TYPES.FILTERED ) { return undefined; } @@ -83,7 +83,7 @@ export class PromptHistory { if ( nextTurn instanceof vscode.ChatResponseTurn && - nextTurn.result.errorDetails?.message === ParticipantErrorTypes.FILTERED + nextTurn.result.errorDetails?.message === PARTICIPANT_ERROR_TYPES.FILTERED ) { // If the response to this request led to a filtered error, // we do not want to include it in the history diff --git a/src/storage/connectionStorage.ts b/src/storage/connectionStorage.ts index be0d59ac8..50ca7abd2 100644 --- a/src/storage/connectionStorage.ts +++ b/src/storage/connectionStorage.ts @@ -8,12 +8,15 @@ import type { ConnectionOptions } from 'mongodb-data-service'; import { createLogger } from '../logging'; import type StorageController from './storageController'; -import type { SecretStorageLocationType } from './storageController'; -import { - DefaultSavingLocations, - SecretStorageLocation, +import type { + SecretStorageLocationType, StorageLocation, - StorageVariables, +} from './storageController'; +import { + DEFAULT_SAVING_LOCATIONS, + SECRET_STORAGE_LOCATIONS, + STORAGE_LOCATIONS, + STORAGE_VARIABLES, } from './storageController'; import { v4 as uuidv4 } from 'uuid'; @@ -42,11 +45,11 @@ export type PresetSavedConnectionWithSource = PresetSavedConnection & { type StoreConnectionInfoWithConnectionOptions = StoreConnectionInfo & Required>; -type StoreConnectionInfoWithSecretStorageLocation = StoreConnectionInfo & +type StoreConnectionInfoWithSECRET_STORAGE_LOCATIONS = StoreConnectionInfo & Required>; export type LoadedConnection = StoreConnectionInfoWithConnectionOptions & - StoreConnectionInfoWithSecretStorageLocation; + StoreConnectionInfoWithSECRET_STORAGE_LOCATIONS; export class ConnectionStorage { _storageController: StorageController; @@ -133,9 +136,12 @@ export class ConnectionStorage { async saveConnection(connection: LoadedConnection): Promise { if ( - ![StorageLocation.GLOBAL, StorageLocation.WORKSPACE].includes( - connection.storageLocation, - ) + !( + [ + STORAGE_LOCATIONS.GLOBAL, + STORAGE_LOCATIONS.WORKSPACE, + ] as StorageLocation[] + ).includes(connection.storageLocation) ) { return; } @@ -157,9 +163,9 @@ export class ConnectionStorage { connectionWithoutSecrets: StoreConnectionInfo, ): Promise { const variableName = - connectionWithoutSecrets.storageLocation === StorageLocation.GLOBAL - ? StorageVariables.GLOBAL_SAVED_CONNECTIONS - : StorageVariables.WORKSPACE_SAVED_CONNECTIONS; + connectionWithoutSecrets.storageLocation === STORAGE_LOCATIONS.GLOBAL + ? STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS + : STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS; // Get the current saved connections. let savedConnections = this._storageController.get( @@ -211,8 +217,8 @@ export class ConnectionStorage { connectionString: presetConnection.connectionString, }, source: presetConnection.source, - storageLocation: StorageLocation.NONE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.NONE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, }) satisfies LoadedConnection, ); } @@ -220,12 +226,12 @@ export class ConnectionStorage { async loadConnections(): Promise { const globalAndWorkspaceConnections = Object.values({ ...this._storageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ), ...this._storageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ), }); @@ -265,21 +271,21 @@ export class ConnectionStorage { // See if the connection exists in the saved global or workspace connections // and remove it if it is. const globalStoredConnections = this._storageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ); if (globalStoredConnections && globalStoredConnections[connectionId]) { delete globalStoredConnections[connectionId]; void this._storageController.update( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, globalStoredConnections, - StorageLocation.GLOBAL, + STORAGE_LOCATIONS.GLOBAL, ); } const workspaceStoredConnections = this._storageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); if ( workspaceStoredConnections && @@ -287,21 +293,21 @@ export class ConnectionStorage { ) { delete workspaceStoredConnections[connectionId]; void this._storageController.update( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, workspaceStoredConnections, - StorageLocation.WORKSPACE, + STORAGE_LOCATIONS.WORKSPACE, ); } } hasSavedConnections(): boolean { const savedWorkspaceConnections = this._storageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); const savedGlobalConnections = this._storageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ); return !!( @@ -316,15 +322,17 @@ export class ConnectionStorage { .getConfiguration('mdb.connectionSaving') .get('defaultConnectionSavingLocation'); - if (defaultConnectionSavingLocation === DefaultSavingLocations.Workspace) { - return StorageLocation.WORKSPACE; + if ( + defaultConnectionSavingLocation === DEFAULT_SAVING_LOCATIONS.Workspace + ) { + return STORAGE_LOCATIONS.WORKSPACE; } - if (defaultConnectionSavingLocation === DefaultSavingLocations.Global) { - return StorageLocation.GLOBAL; + if (defaultConnectionSavingLocation === DEFAULT_SAVING_LOCATIONS.Global) { + return STORAGE_LOCATIONS.GLOBAL; } - return StorageLocation.NONE; + return STORAGE_LOCATIONS.NONE; } getUserAnonymousId(): string { diff --git a/src/storage/index.ts b/src/storage/index.ts index 0c0fcf6ff..e8a426b7e 100644 --- a/src/storage/index.ts +++ b/src/storage/index.ts @@ -1,3 +1,6 @@ -import StorageController, { StorageVariables } from './storageController'; +import StorageController, { + STORAGE_VARIABLES, + STORAGE_LOCATIONS, +} from './storageController'; -export { StorageController, StorageVariables }; +export { StorageController, STORAGE_VARIABLES, STORAGE_LOCATIONS }; diff --git a/src/storage/storageController.ts b/src/storage/storageController.ts index 5d0d389fc..1f4d971a1 100644 --- a/src/storage/storageController.ts +++ b/src/storage/storageController.ts @@ -3,31 +3,41 @@ import { v4 as uuidv4 } from 'uuid'; import type { StoreConnectionInfo } from './connectionStorage'; -export enum StorageVariables { +export const STORAGE_VARIABLES = { // Only exists on globalState. - GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW = 'GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW', - GLOBAL_SAVED_CONNECTIONS = 'GLOBAL_SAVED_CONNECTIONS', + GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW: 'GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW', + GLOBAL_SAVED_CONNECTIONS: 'GLOBAL_SAVED_CONNECTIONS', // Analytics user identify. - GLOBAL_USER_ID = 'GLOBAL_USER_ID', - GLOBAL_ANONYMOUS_ID = 'GLOBAL_ANONYMOUS_ID', + GLOBAL_USER_ID: 'GLOBAL_USER_ID', + GLOBAL_ANONYMOUS_ID: 'GLOBAL_ANONYMOUS_ID', // Only exists on workspaceState. - WORKSPACE_SAVED_CONNECTIONS = 'WORKSPACE_SAVED_CONNECTIONS', - COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE = 'COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE', -} + WORKSPACE_SAVED_CONNECTIONS: 'WORKSPACE_SAVED_CONNECTIONS', + COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE: + 'COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE', +} as const; + +export type StorageVariables = + (typeof STORAGE_VARIABLES)[keyof typeof STORAGE_VARIABLES]; // Typically variables default to 'GLOBAL' scope. -export enum StorageLocation { - GLOBAL = 'GLOBAL', - WORKSPACE = 'WORKSPACE', - NONE = 'NONE', -} +export const STORAGE_LOCATIONS = { + GLOBAL: 'GLOBAL', + WORKSPACE: 'WORKSPACE', + NONE: 'NONE', +} as const; + +export type StorageLocation = + (typeof STORAGE_LOCATIONS)[keyof typeof STORAGE_LOCATIONS]; // Coupled with the `defaultConnectionSavingLocation` configuration in `package.json`. -export enum DefaultSavingLocations { - 'Workspace' = 'Workspace', - 'Global' = 'Global', - 'Session Only' = 'Session Only', -} +export const DEFAULT_SAVING_LOCATIONS = { + Workspace: 'Workspace', + Global: 'Global', + 'Session Only': 'Session Only', +} as const; + +export type DefaultSavingLocations = + (typeof DEFAULT_SAVING_LOCATIONS)[keyof typeof DEFAULT_SAVING_LOCATIONS]; export type ConnectionsFromStorage = { [connectionId: string]: StoreConnectionInfo; @@ -35,7 +45,7 @@ export type ConnectionsFromStorage = { // Keytar is deprecated and no longer used. All new // connections use 'SecretStorage'. -export const SecretStorageLocation = { +export const SECRET_STORAGE_LOCATIONS = { Keytar: 'vscode.Keytar', KeytarSecondAttempt: 'vscode.KeytarSecondAttempt', @@ -43,40 +53,38 @@ export const SecretStorageLocation = { } as const; export type SecretStorageLocationType = - | typeof SecretStorageLocation.Keytar - | typeof SecretStorageLocation.KeytarSecondAttempt - | typeof SecretStorageLocation.SecretStorage; + (typeof SECRET_STORAGE_LOCATIONS)[keyof typeof SECRET_STORAGE_LOCATIONS]; interface StorageVariableContents { - [StorageVariables.GLOBAL_USER_ID]: string; - [StorageVariables.GLOBAL_ANONYMOUS_ID]: string; - [StorageVariables.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW]: boolean; - [StorageVariables.GLOBAL_SAVED_CONNECTIONS]: ConnectionsFromStorage; - [StorageVariables.WORKSPACE_SAVED_CONNECTIONS]: ConnectionsFromStorage; - [StorageVariables.COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE]: boolean; + [STORAGE_VARIABLES.GLOBAL_USER_ID]: string; + [STORAGE_VARIABLES.GLOBAL_ANONYMOUS_ID]: string; + [STORAGE_VARIABLES.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW]: boolean; + [STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS]: ConnectionsFromStorage; + [STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS]: ConnectionsFromStorage; + [STORAGE_VARIABLES.COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE]: boolean; } type StoredVariableName = keyof StorageVariableContents; type StoredItem = StorageVariableContents[T]; export default class StorageController { _storage: { - [StorageLocation.GLOBAL]: vscode.Memento; - [StorageLocation.WORKSPACE]: vscode.Memento; + [STORAGE_LOCATIONS.GLOBAL]: vscode.Memento; + [STORAGE_LOCATIONS.WORKSPACE]: vscode.Memento; }; _secretStorage: vscode.SecretStorage; constructor(context: vscode.ExtensionContext) { this._storage = { - [StorageLocation.GLOBAL]: context.globalState, - [StorageLocation.WORKSPACE]: context.workspaceState, + [STORAGE_LOCATIONS.GLOBAL]: context.globalState, + [STORAGE_LOCATIONS.WORKSPACE]: context.workspaceState, }; this._secretStorage = context.secrets; } get( variableName: T, - storageLocation: StorageLocation = StorageLocation.GLOBAL, + storageLocation: StorageLocation = STORAGE_LOCATIONS.GLOBAL, ): StoredItem { return this._storage[storageLocation].get(variableName); } @@ -85,19 +93,19 @@ export default class StorageController { update( variableName: T, value: StoredItem, - storageLocation: StorageLocation = StorageLocation.GLOBAL, + storageLocation: StorageLocation = STORAGE_LOCATIONS.GLOBAL, ): Thenable { this._storage[storageLocation].update(variableName, value); return Promise.resolve(); } getUserIdentity(): { anonymousId: string } { - let anonymousId = this.get(StorageVariables.GLOBAL_ANONYMOUS_ID); + let anonymousId = this.get(STORAGE_VARIABLES.GLOBAL_ANONYMOUS_ID); // The anonymousId becomes required with analytics-node v6. if (!anonymousId) { anonymousId = uuidv4(); - void this.update(StorageVariables.GLOBAL_ANONYMOUS_ID, anonymousId); + void this.update(STORAGE_VARIABLES.GLOBAL_ANONYMOUS_ID, anonymousId); } return { anonymousId }; diff --git a/src/telemetry/connectionTelemetry.ts b/src/telemetry/connectionTelemetry.ts index 14ad8681f..46dbd7ed5 100644 --- a/src/telemetry/connectionTelemetry.ts +++ b/src/telemetry/connectionTelemetry.ts @@ -1,9 +1,12 @@ import type { DataService } from 'mongodb-data-service'; import mongoDBBuildInfo from 'mongodb-build-info'; -import { ConnectionTypes } from '../connectionController'; import { createLogger } from '../logging'; import type { TopologyType } from 'mongodb'; +import { + CONNECTION_TYPES, + type ConnectionTypes, +} from '../connectionController'; const log = createLogger('connection telemetry helper'); // eslint-disable-next-line @typescript-eslint/no-var-requires @@ -123,10 +126,10 @@ export async function getConnectionTelemetryProperties( connectionType: ConnectionTypes, ): Promise { let preparedProperties: NewConnectionTelemetryEventProperties = { - is_used_connect_screen: connectionType === ConnectionTypes.CONNECTION_FORM, + is_used_connect_screen: connectionType === CONNECTION_TYPES.CONNECTION_FORM, is_used_command_palette: - connectionType === ConnectionTypes.CONNECTION_STRING, - is_used_saved_connection: connectionType === ConnectionTypes.CONNECTION_ID, + connectionType === CONNECTION_TYPES.CONNECTION_STRING, + is_used_saved_connection: connectionType === CONNECTION_TYPES.CONNECTION_ID, vscode_mdb_extension_version: version, }; diff --git a/src/telemetry/telemetryEvents.ts b/src/telemetry/telemetryEvents.ts index cfe9a23b3..875907b16 100644 --- a/src/telemetry/telemetryEvents.ts +++ b/src/telemetry/telemetryEvents.ts @@ -1,9 +1,9 @@ import type { ExtensionCommand } from '../commands'; import type { DocumentSourceDetails } from '../documentSource'; -import { DocumentSource } from '../documentSource'; +import { DOCUMENT_SOURCE, type DocumentSource } from '../documentSource'; import type { ExportToPlaygroundError, - ParticipantErrorTypes, + ParticipantErrorType, } from '../participant/participantErrorTypes'; import type { ParticipantCommandType, @@ -422,7 +422,7 @@ export class ParticipantResponseFailedTelemetryEvent error_code?: string; /** The name of the error that caused the failure */ - error_name: ParticipantErrorTypes; + error_name: ParticipantErrorType; /** Additional details about the error if any. */ error_details?: string; @@ -430,7 +430,7 @@ export class ParticipantResponseFailedTelemetryEvent constructor( command: ParticipantResponseType, - errorName: ParticipantErrorTypes, + errorName: ParticipantErrorType, errorCode?: string, errorDetails?: string, ) { @@ -628,7 +628,7 @@ export class PresetConnectionEditedTelemetryEvent constructor(sourceDetails: 'tree_item' | 'header') { this.properties = { - source: DocumentSource.DOCUMENT_SOURCE_TREEVIEW, + source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW, source_details: sourceDetails, }; } diff --git a/src/telemetry/telemetryService.ts b/src/telemetry/telemetryService.ts index 12ecc5b89..8fcc39484 100644 --- a/src/telemetry/telemetryService.ts +++ b/src/telemetry/telemetryService.ts @@ -10,7 +10,10 @@ import type { ConnectionTypes } from '../connectionController'; import { createLogger } from '../logging'; import { getConnectionTelemetryProperties } from './connectionTelemetry'; import type { StorageController } from '../storage'; -import { ParticipantErrorTypes } from '../participant/participantErrorTypes'; +import { + PARTICIPANT_ERROR_TYPES, + type ParticipantErrorType, +} from '../participant/participantErrorTypes'; import type { ParticipantResponseType } from '../participant/participantTypes'; import type { TelemetryEvent } from './telemetryEvents'; import { @@ -197,7 +200,7 @@ export class TelemetryService { trackParticipantError(err: any, command: ParticipantResponseType): void { let errorCode: string | undefined; - let errorName: ParticipantErrorTypes; + let errorName: ParticipantErrorType; // Making the chat request might fail because // - model does not exist // - user consent not given @@ -214,13 +217,13 @@ export class TelemetryService { const message: string = err.message || err.toString(); if (message.includes('off_topic')) { - errorName = ParticipantErrorTypes.CHAT_MODEL_OFF_TOPIC; + errorName = PARTICIPANT_ERROR_TYPES.CHAT_MODEL_OFF_TOPIC; } else if (message.includes('Filtered by Responsible AI Service')) { - errorName = ParticipantErrorTypes.FILTERED; + errorName = PARTICIPANT_ERROR_TYPES.FILTERED; } else if (message.includes('Prompt failed validation')) { - errorName = ParticipantErrorTypes.INVALID_PROMPT; + errorName = PARTICIPANT_ERROR_TYPES.INVALID_PROMPT; } else { - errorName = ParticipantErrorTypes.OTHER; + errorName = PARTICIPANT_ERROR_TYPES.OTHER; } this.track( diff --git a/src/test/setup-webview.ts b/src/test/setup-webview.ts index 5fb7c7af6..37a05d2ea 100644 --- a/src/test/setup-webview.ts +++ b/src/test/setup-webview.ts @@ -5,6 +5,31 @@ chai.use(sinonChai); // JSDom import { JSDOM, VirtualConsole } from 'jsdom'; +import { createRequire } from 'module'; + +// Create a require function that works in both ESM and CommonJS contexts +const requireModule = (() => { + if (typeof require !== 'undefined' && typeof require.cache === 'object') { + // We're in CommonJS context + return require; + } + + // We're in ESM context, create require from import.meta.url + // @ts-expect-error import.meta is not available in CommonJS context + if (typeof import.meta !== 'undefined' && import.meta.url) { + // @ts-expect-error import.meta is not available in CommonJS context + return createRequire(import.meta.url); + } + + // Fallback: try to create require from current file location + if (typeof __filename !== 'undefined') { + return createRequire(__filename); + } + + throw new Error( + 'Unable to create require function - neither ESM nor CommonJS context detected', + ); +})(); /** * NB: focus-trap and tabbable require special overrides to work in jsdom environments as per @@ -12,8 +37,7 @@ import { JSDOM, VirtualConsole } from 'jsdom'; * * @see {@link https://github.com/focus-trap/tabbable?tab=readme-ov-file#testing-in-jsdom} */ -// eslint-disable-next-line @typescript-eslint/no-var-requires -const tabbable = require('tabbable'); +const tabbable = requireModule('tabbable'); const origTabbable = { ...tabbable }; @@ -28,8 +52,7 @@ Object.assign(tabbable, { origTabbable.isTabbable(node, { ...options, displayCheck: 'none' }), }); -// eslint-disable-next-line @typescript-eslint/no-var-requires -const focusTrap = require('focus-trap'); +const focusTrap = requireModule('focus-trap'); Object.assign(focusTrap, { ...focusTrap, diff --git a/src/test/suite/connectionController.test.ts b/src/test/suite/connectionController.test.ts index 0d4f5dc6c..19d2f2e37 100644 --- a/src/test/suite/connectionController.test.ts +++ b/src/test/suite/connectionController.test.ts @@ -8,15 +8,18 @@ import { expect } from 'chai'; import ConnectionString from 'mongodb-connection-string-url'; import ConnectionController, { - ConnectionTypes, + CONNECTION_TYPES, getNotifyDeviceFlowForConnectionAttempt, } from '../../connectionController'; import formatError from '../../utils/formatError'; -import { StorageController, StorageVariables } from '../../storage'; import { - StorageLocation, - DefaultSavingLocations, - SecretStorageLocation, + StorageController, + STORAGE_VARIABLES, + STORAGE_LOCATIONS, +} from '../../storage'; +import { + DEFAULT_SAVING_LOCATIONS, + SECRET_STORAGE_LOCATIONS, } from '../../storage/storageController'; import { StatusView } from '../../views'; import { TelemetryService } from '../../telemetry'; @@ -269,8 +272,8 @@ suite('Connection Controller Test Suite', function () { ): void => { testConnectionController._connections[id] = { connectionOptions: { connectionString }, - storageLocation: StorageLocation.NONE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.NONE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, name, id, ...otherOptions, @@ -547,8 +550,8 @@ suite('Connection Controller Test Suite', function () { connectionOptions: { connectionString: 'localhost:3000', }, - storageLocation: StorageLocation.NONE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.NONE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, }; // Should persist as this is a saved connection. @@ -565,7 +568,10 @@ suite('Connection Controller Test Suite', function () { test('the connection model loads both global and workspace stored connection models', async () => { await vscode.workspace .getConfiguration('mdb.connectionSaving') - .update('defaultConnectionSavingLocation', DefaultSavingLocations.Global); + .update( + 'defaultConnectionSavingLocation', + DEFAULT_SAVING_LOCATIONS.Global, + ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); @@ -576,7 +582,7 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DEFAULT_SAVING_LOCATIONS.Workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, @@ -604,14 +610,17 @@ suite('Connection Controller Test Suite', function () { await testConnectionController.loadSavedConnections(); await vscode.workspace .getConfiguration('mdb.connectionSaving') - .update('defaultConnectionSavingLocation', DefaultSavingLocations.Global); + .update( + 'defaultConnectionSavingLocation', + DEFAULT_SAVING_LOCATIONS.Global, + ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const globalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ); expect(Object.keys(globalStoreConnections)).to.have.lengthOf(1); @@ -623,7 +632,7 @@ suite('Connection Controller Test Suite', function () { ); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, ); expect(workspaceStoreConnections).to.be.undefined; @@ -635,15 +644,15 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DEFAULT_SAVING_LOCATIONS.Workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); expect(Object.keys(workspaceStoreConnections)).to.have.lengthOf(1); @@ -655,8 +664,8 @@ suite('Connection Controller Test Suite', function () { ); const globalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ); expect(globalStoreConnections).to.be.undefined; @@ -668,8 +677,8 @@ suite('Connection Controller Test Suite', function () { id: '25', name: 'tester', connectionOptions: { connectionString: TEST_DATABASE_URI }, - storageLocation: StorageLocation.NONE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.NONE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, }, }; @@ -686,15 +695,15 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DEFAULT_SAVING_LOCATIONS.Workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); expect(Object.keys(workspaceStoreConnections)).to.have.lengthOf(1); @@ -748,7 +757,7 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations['Session Only'], + DEFAULT_SAVING_LOCATIONS['Session Only'], ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, @@ -756,15 +765,15 @@ suite('Connection Controller Test Suite', function () { const objectString = JSON.stringify(undefined); const globalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ); expect(JSON.stringify(globalStoreConnections)).to.equal(objectString); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); expect(JSON.stringify(workspaceStoreConnections)).to.equal(objectString); @@ -809,15 +818,15 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DEFAULT_SAVING_LOCATIONS.Workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); expect(Object.keys(workspaceStoreConnections)).to.have.lengthOf(1); @@ -829,8 +838,8 @@ suite('Connection Controller Test Suite', function () { await testConnectionController.removeSavedConnection(connectionId); const postWorkspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); expect(Object.keys(postWorkspaceStoreConnections)).to.have.lengthOf(0); @@ -840,14 +849,17 @@ suite('Connection Controller Test Suite', function () { await testConnectionController.loadSavedConnections(); await vscode.workspace .getConfiguration('mdb.connectionSaving') - .update('defaultConnectionSavingLocation', DefaultSavingLocations.Global); + .update( + 'defaultConnectionSavingLocation', + DEFAULT_SAVING_LOCATIONS.Global, + ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const globalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ); expect(Object.keys(globalStoreConnections)).to.have.lengthOf(1); @@ -857,8 +869,8 @@ suite('Connection Controller Test Suite', function () { await testConnectionController.removeSavedConnection(connectionId); const postGlobalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ); expect(Object.keys(postGlobalStoreConnections)).to.have.lengthOf(0); @@ -885,15 +897,15 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DEFAULT_SAVING_LOCATIONS.Workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); expect(Object.keys(workspaceStoreConnections)).to.have.lengthOf(1); @@ -933,15 +945,15 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DEFAULT_SAVING_LOCATIONS.Workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); expect(Object.keys(workspaceStoreConnections)).to.have.lengthOf(1); @@ -1009,7 +1021,7 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DEFAULT_SAVING_LOCATIONS.Workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, @@ -1079,8 +1091,8 @@ suite('Connection Controller Test Suite', function () { id, name: `test${i}`, connectionOptions: { connectionString: TEST_DATABASE_URI }, - storageLocation: StorageLocation.NONE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.NONE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, }; } @@ -1141,8 +1153,8 @@ suite('Connection Controller Test Suite', function () { id: connectionId, name: 'asdfasdg', connectionOptions: { connectionString: testDatabaseURI2WithTimeout }, - storageLocation: StorageLocation.NONE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.NONE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, }; void testConnectionController.connectWithConnectionId(connectionId); @@ -1165,8 +1177,8 @@ suite('Connection Controller Test Suite', function () { id: connectionId, name: 'asdfasdg', connectionOptions: { connectionString: TEST_DATABASE_URI }, - storageLocation: StorageLocation.NONE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.NONE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, }; sandbox.replace( @@ -1196,8 +1208,8 @@ suite('Connection Controller Test Suite', function () { const connectionInfo = { id: '1d700f37-ba57-4568-9552-0ea23effea89', name: 'localhost:27017', - storageLocation: StorageLocation.GLOBAL, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.GLOBAL, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, connectionOptions: { connectionString: 'mongodb://lena:secrer@localhost:27017/?readPreference=primary&ssl=false', @@ -1297,7 +1309,7 @@ suite('Connection Controller Test Suite', function () { expect( savedConnections.every( ({ secretStorageLocation }) => - secretStorageLocation === SecretStorageLocation.SecretStorage, + secretStorageLocation === SECRET_STORAGE_LOCATIONS.SecretStorage, ), ).to.be.true; @@ -1349,7 +1361,7 @@ suite('Connection Controller Test Suite', function () { id: 'random-connection-4', name: 'localhost:27089', storageLocation: 'GLOBAL', - secretStorageLocation: SecretStorageLocation.SecretStorage, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, connectionOptions: { connectionString: 'mongodb://localhost:27080/?readPreference=primary&ssl=false', @@ -1357,8 +1369,8 @@ suite('Connection Controller Test Suite', function () { }; testSandbox.replace(testStorageController, 'get', (key, storage) => { if ( - storage === StorageLocation.WORKSPACE || - key === StorageVariables.WORKSPACE_SAVED_CONNECTIONS + storage === STORAGE_LOCATIONS.WORKSPACE || + key === STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS ) { return {}; } @@ -1368,7 +1380,7 @@ suite('Connection Controller Test Suite', function () { id: 'random-connection-1', name: 'localhost:27017', storageLocation: 'GLOBAL', - secretStorageLocation: SecretStorageLocation.Keytar, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.Keytar, connectionOptions: { connectionString: 'mongodb://localhost:27017/?readPreference=primary&ssl=false', @@ -1378,7 +1390,7 @@ suite('Connection Controller Test Suite', function () { id: 'random-connection-2', name: 'localhost:27017', storageLocation: 'GLOBAL', - secretStorageLocation: SecretStorageLocation.KeytarSecondAttempt, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.KeytarSecondAttempt, connectionOptions: { connectionString: 'mongodb://localhost:27017/?readPreference=primary&ssl=false', @@ -1412,8 +1424,8 @@ suite('Connection Controller Test Suite', function () { test.skip('should track SAVED_CONNECTIONS_LOADED event on load of saved connections', async () => { testSandbox.replace(testStorageController, 'get', (key, storage) => { if ( - storage === StorageLocation.WORKSPACE || - key === StorageVariables.WORKSPACE_SAVED_CONNECTIONS + storage === STORAGE_LOCATIONS.WORKSPACE || + key === STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS ) { return {}; } @@ -1423,7 +1435,7 @@ suite('Connection Controller Test Suite', function () { id: 'random-connection-1', name: 'localhost:27017', storageLocation: 'GLOBAL', - secretStorageLocation: SecretStorageLocation.SecretStorage, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, connectionOptions: { connectionString: 'mongodb://localhost:27017/?readPreference=primary&ssl=false', @@ -1433,7 +1445,7 @@ suite('Connection Controller Test Suite', function () { id: 'random-connection-2', name: 'localhost:27088', storageLocation: 'GLOBAL', - secretStorageLocation: SecretStorageLocation.SecretStorage, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, connectionOptions: { connectionString: 'mongodb://localhost:27088/?readPreference=primary&ssl=false', @@ -1443,7 +1455,7 @@ suite('Connection Controller Test Suite', function () { id: 'random-connection-3', name: 'localhost:27088', storageLocation: 'GLOBAL', - secretStorageLocation: SecretStorageLocation.Keytar, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.Keytar, connectionOptions: { connectionString: 'mongodb://localhost:27088/?readPreference=primary&ssl=false', @@ -1453,7 +1465,7 @@ suite('Connection Controller Test Suite', function () { id: 'random-connection-4', name: 'localhost:27088', storageLocation: 'GLOBAL', - secretStorageLocation: SecretStorageLocation.KeytarSecondAttempt, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.KeytarSecondAttempt, connectionOptions: { connectionString: 'mongodb://localhost:27088/?readPreference=primary&ssl=false', @@ -1557,14 +1569,14 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Global, + DEFAULT_SAVING_LOCATIONS.Global, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI_USER, }); const workspaceStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, ); expect(workspaceStoreConnections).to.not.be.empty; @@ -1687,7 +1699,7 @@ suite('Connection Controller Test Suite', function () { }); expect(fakeConnect).to.have.been.calledWith( connections[0].id, - ConnectionTypes.CONNECTION_ID, + CONNECTION_TYPES.CONNECTION_ID, ); connections = testConnectionController.getSavedConnections(); expect(connections).to.have.lengthOf(1); diff --git a/src/test/suite/editors/collectionDocumentsProvider.test.ts b/src/test/suite/editors/collectionDocumentsProvider.test.ts index a4a2e0d03..5ce610b7a 100644 --- a/src/test/suite/editors/collectionDocumentsProvider.test.ts +++ b/src/test/suite/editors/collectionDocumentsProvider.test.ts @@ -3,8 +3,7 @@ import assert from 'assert'; import { beforeEach, afterEach } from 'mocha'; import sinon from 'sinon'; import type { DataService } from 'mongodb-data-service'; - -import { DocumentSource } from '../../../documentSource'; +import { DOCUMENT_SOURCE } from '../../../documentSource'; import CollectionDocumentsOperationsStore from '../../../editors/collectionDocumentsOperationsStore'; import CollectionDocumentsProvider, { VIEW_COLLECTION_SCHEME, @@ -14,8 +13,8 @@ import EditDocumentCodeLensProvider from '../../../editors/editDocumentCodeLensP import { StatusView } from '../../../views'; import { StorageController } from '../../../storage'; import { - SecretStorageLocation, - StorageLocation, + SECRET_STORAGE_LOCATIONS, + STORAGE_LOCATIONS, } from '../../../storage/storageController'; import { TelemetryService } from '../../../telemetry'; import { TEST_DATABASE_URI } from '../dbTestHelper'; @@ -288,7 +287,7 @@ suite('Collection Documents Provider Test Suite', () => { assert(!!firstCollectionFirstCommandArguments); assert( firstCollectionFirstCommandArguments[0].source === - DocumentSource.DOCUMENT_SOURCE_COLLECTIONVIEW, + DOCUMENT_SOURCE.DOCUMENT_SOURCE_COLLECTIONVIEW, ); assert( firstCollectionFirstCommandArguments[0].namespace === @@ -358,7 +357,7 @@ suite('Collection Documents Provider Test Suite', () => { assert(!!secondCollectionFirstCommandArguments); assert( secondCollectionFirstCommandArguments[0].source === - DocumentSource.DOCUMENT_SOURCE_COLLECTIONVIEW, + DOCUMENT_SOURCE.DOCUMENT_SOURCE_COLLECTIONVIEW, ); assert( secondCollectionFirstCommandArguments[0].namespace === @@ -419,15 +418,15 @@ suite('Collection Documents Provider Test Suite', () => { id: firstConnectionId, name: 'localhost', connectionOptions: { connectionString: TEST_DATABASE_URI }, - storageLocation: StorageLocation.NONE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.NONE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, }, [secondConnectionId]: { id: secondConnectionId, name: 'compass', connectionOptions: { connectionString: TEST_DATABASE_URI }, - storageLocation: StorageLocation.NONE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.NONE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, }, }; @@ -477,7 +476,7 @@ suite('Collection Documents Provider Test Suite', () => { assert(!!firstCollectionFirstCommandArguments); assert( firstCollectionFirstCommandArguments[0].source === - DocumentSource.DOCUMENT_SOURCE_COLLECTIONVIEW, + DOCUMENT_SOURCE.DOCUMENT_SOURCE_COLLECTIONVIEW, ); assert( firstCollectionFirstCommandArguments[0].namespace === @@ -552,7 +551,7 @@ suite('Collection Documents Provider Test Suite', () => { assert(!!secondCollectionFirstCommandArguments); assert( secondCollectionFirstCommandArguments[0].source === - DocumentSource.DOCUMENT_SOURCE_COLLECTIONVIEW, + DOCUMENT_SOURCE.DOCUMENT_SOURCE_COLLECTIONVIEW, ); assert( secondCollectionFirstCommandArguments[0].namespace === diff --git a/src/test/suite/editors/editDocumentCodeLensProvider.test.ts b/src/test/suite/editors/editDocumentCodeLensProvider.test.ts index b82b313c4..0645a5f4f 100644 --- a/src/test/suite/editors/editDocumentCodeLensProvider.test.ts +++ b/src/test/suite/editors/editDocumentCodeLensProvider.test.ts @@ -6,7 +6,7 @@ import sinon from 'sinon'; import util from 'util'; import ConnectionController from '../../../connectionController'; -import { DocumentSource } from '../../../documentSource'; +import { DOCUMENT_SOURCE } from '../../../documentSource'; import EditDocumentCodeLensProvider from '../../../editors/editDocumentCodeLensProvider'; import { mockTextEditor } from '../stubs'; import { StatusView } from '../../../views'; @@ -56,7 +56,7 @@ suite('Edit Document Code Lens Provider Test Suite', () => { }, ], namespace: 'db.coll', - source: DocumentSource.DOCUMENT_SOURCE_PLAYGROUND, + source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_PLAYGROUND, }; const fakeActiveConnectionId = sandbox.fake.returns('tasty_sandwhich'); @@ -90,7 +90,7 @@ suite('Edit Document Code Lens Provider Test Suite', () => { name: 'test name', }, namespace: 'db.coll', - source: DocumentSource.DOCUMENT_SOURCE_PLAYGROUND, + source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_PLAYGROUND, }; const fakeActiveConnectionId = sandbox.fake.returns('tasty_sandwhich'); @@ -99,8 +99,9 @@ suite('Edit Document Code Lens Provider Test Suite', () => { 'getActiveConnectionId', fakeActiveConnectionId, ); - const result = - testCodeLensProvider._updateCodeLensesForDocument(playgroundResult); + const result = testCodeLensProvider._updateCodeLensesForDocument( + playgroundResult as any, + ); assert(!!result); const codeLensesInfo = result[0]; diff --git a/src/test/suite/editors/mongoDBDocumentService.test.ts b/src/test/suite/editors/mongoDBDocumentService.test.ts index 5dd1e47cd..3ed87a982 100644 --- a/src/test/suite/editors/mongoDBDocumentService.test.ts +++ b/src/test/suite/editors/mongoDBDocumentService.test.ts @@ -5,7 +5,7 @@ import { EJSON } from 'bson'; import sinon from 'sinon'; import ConnectionController from '../../../connectionController'; -import { DocumentSource } from '../../../documentSource'; +import { DOCUMENT_SOURCE } from '../../../documentSource'; import formatError from '../../../utils/formatError'; import MongoDBDocumentService from '../../../editors/mongoDBDocumentService'; @@ -52,7 +52,7 @@ suite('MongoDB Document Service Test Suite', () => { const documentId = '93333a0d-83f6-4e6f-a575-af7ea6187a4a'; const document: { _id: string; price?: number } = { _id: '123' }; const newDocument = { _id: '123', price: 5000 }; - const source = DocumentSource.DOCUMENT_SOURCE_TREEVIEW; + const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW; const fakeActiveConnectionId = sandbox.fake.returns('tasty_sandwhich'); sandbox.replace( @@ -103,7 +103,7 @@ suite('MongoDB Document Service Test Suite', () => { }, }, }; - const source = DocumentSource.DOCUMENT_SOURCE_TREEVIEW; + const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW; const fakeActiveConnectionId = sandbox.fake.returns('tasty_sandwhich'); sandbox.replace( @@ -144,7 +144,7 @@ suite('MongoDB Document Service Test Suite', () => { const documentId = '93333a0d-83f6-4e6f-a575-af7ea6187a4a'; const line = 1; const documents = [{ _id: '123' }]; - const source = DocumentSource.DOCUMENT_SOURCE_PLAYGROUND; + const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_PLAYGROUND; const fakeGetActiveDataService = sandbox.fake.returns({ find: () => { @@ -194,7 +194,7 @@ suite('MongoDB Document Service Test Suite', () => { }, }, ]; - const source = DocumentSource.DOCUMENT_SOURCE_PLAYGROUND; + const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_PLAYGROUND; const fakeGetActiveDataService = sandbox.fake.returns({ find: () => { @@ -236,7 +236,7 @@ suite('MongoDB Document Service Test Suite', () => { const connectionId = 'tasty_sandwhich'; const documentId = '93333a0d-83f6-4e6f-a575-af7ea6187a4a'; const newDocument = { _id: '123', price: 5000 }; - const source = DocumentSource.DOCUMENT_SOURCE_TREEVIEW; + const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW; const fakeActiveConnectionId = sandbox.fake.returns(null); sandbox.replace( @@ -273,7 +273,7 @@ suite('MongoDB Document Service Test Suite', () => { const connectionId = 'tasty_sandwhich'; const documentId = '93333a0d-83f6-4e6f-a575-af7ea6187a4a'; const newDocument = { _id: '123', price: 5000 }; - const source = DocumentSource.DOCUMENT_SOURCE_PLAYGROUND; + const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_PLAYGROUND; const fakeActiveConnectionId = sandbox.fake.returns('berlin.coctails'); sandbox.replace( @@ -310,7 +310,7 @@ suite('MongoDB Document Service Test Suite', () => { const connectionId = '123'; const documentId = '93333a0d-83f6-4e6f-a575-af7ea6187a4a'; const line = 1; - const source = DocumentSource.DOCUMENT_SOURCE_PLAYGROUND; + const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_PLAYGROUND; const fakeGetActiveConnectionId = sandbox.fake.returns('345'); sandbox.replace( diff --git a/src/test/suite/explorer/collectionTreeItem.test.ts b/src/test/suite/explorer/collectionTreeItem.test.ts index b90d5caa8..cade03be9 100644 --- a/src/test/suite/explorer/collectionTreeItem.test.ts +++ b/src/test/suite/explorer/collectionTreeItem.test.ts @@ -3,7 +3,7 @@ import type { DataService } from 'mongodb-data-service'; import CollectionTreeItem from '../../../explorer/collectionTreeItem'; import type { CollectionDetailsType } from '../../../explorer/collectionTreeItem'; -import { CollectionTypes } from '../../../explorer/documentListTreeItem'; +import { COLLECTION_TYPES } from '../../../explorer/documentListTreeItem'; import { ext } from '../../../extensionConstants'; import { ExtensionContextStub, DataServiceStub } from '../stubs'; @@ -16,7 +16,7 @@ function getTestCollectionTreeItem( return new CollectionTreeItem({ collection: { name: 'testColName', - type: CollectionTypes.collection, + type: COLLECTION_TYPES.collection, } as unknown as CollectionDetailsType, databaseName: 'testDbName', dataService: {} as DataService, @@ -81,7 +81,7 @@ suite('CollectionTreeItem Test Suite', () => { const testCollectionViewTreeItem = getTestCollectionTreeItem({ collection: { name: 'mock_collection_name_1', - type: CollectionTypes.view, + type: COLLECTION_TYPES.view, } as unknown as CollectionDetailsType, }); @@ -98,7 +98,7 @@ suite('CollectionTreeItem Test Suite', () => { const testCollectionCollectionTreeItem = getTestCollectionTreeItem({ collection: { name: 'mock_collection_name_1', - type: CollectionTypes.collection, + type: COLLECTION_TYPES.collection, } as unknown as CollectionDetailsType, }); const collectionIconPath = testCollectionCollectionTreeItem.iconPath; @@ -120,7 +120,7 @@ suite('CollectionTreeItem Test Suite', () => { const testCollectionTimeSeriesTreeItem = getTestCollectionTreeItem({ collection: { name: 'mock_collection_name_1', - type: CollectionTypes.timeseries, + type: COLLECTION_TYPES.timeseries, } as unknown as CollectionDetailsType, }); const viewIconPath = testCollectionTimeSeriesTreeItem.iconPath; @@ -136,7 +136,7 @@ suite('CollectionTreeItem Test Suite', () => { const testCollectionCollectionTreeItem = getTestCollectionTreeItem({ collection: { name: 'mock_collection_name_1', - type: CollectionTypes.collection, + type: COLLECTION_TYPES.collection, } as unknown as CollectionDetailsType, }); const collectionIconPath = testCollectionCollectionTreeItem.iconPath; diff --git a/src/test/suite/explorer/documentListTreeItem.test.ts b/src/test/suite/explorer/documentListTreeItem.test.ts index f60e6396f..168ec31e1 100644 --- a/src/test/suite/explorer/documentListTreeItem.test.ts +++ b/src/test/suite/explorer/documentListTreeItem.test.ts @@ -6,7 +6,7 @@ import type { DataService } from 'mongodb-data-service'; const { contributes } = require('../../../../package.json'); import DocumentListTreeItem, { - CollectionTypes, + COLLECTION_TYPES, formatDocCount, MAX_DOCUMENTS_VISIBLE, } from '../../../explorer/documentListTreeItem'; @@ -21,7 +21,7 @@ function getTestDocumentListTreeItem( return new DocumentListTreeItem({ collectionName: 'collectionName', databaseName: 'mock_db_name', - type: CollectionTypes.collection, + type: COLLECTION_TYPES.collection, dataService: dataServiceStub as unknown as DataService, isExpanded: false, maxDocumentsToShow: MAX_DOCUMENTS_VISIBLE, @@ -82,7 +82,7 @@ suite('DocumentListTreeItem Test Suite', () => { test('a "view" type of document list does not show a dropdown', () => { const testDocumentListTreeItem = getTestDocumentListTreeItem({ - type: CollectionTypes.view, + type: COLLECTION_TYPES.view, }); assert.strictEqual( @@ -181,7 +181,7 @@ suite('DocumentListTreeItem Test Suite', () => { test('it shows a documents icon', () => { const testCollectionViewTreeItem = getTestDocumentListTreeItem({ collectionName: 'mock_collection_name_4', - type: CollectionTypes.view, + type: COLLECTION_TYPES.view, }); const viewIconPath = testCollectionViewTreeItem.iconPath; @@ -192,7 +192,7 @@ suite('DocumentListTreeItem Test Suite', () => { const testDocumentListTreeItem = getTestDocumentListTreeItem({ collectionName: 'mock_collection_name_4', - type: CollectionTypes.collection, + type: COLLECTION_TYPES.collection, }); const collectionIconPath = testDocumentListTreeItem.iconPath; diff --git a/src/test/suite/explorer/explorerController.test.ts b/src/test/suite/explorer/explorerController.test.ts index 4f6a516fa..82e5b44f4 100644 --- a/src/test/suite/explorer/explorerController.test.ts +++ b/src/test/suite/explorer/explorerController.test.ts @@ -6,9 +6,9 @@ import { connect, createConnectionAttempt } from 'mongodb-data-service'; import { mongoLogId } from 'mongodb-log-writer'; import { - DefaultSavingLocations, - SecretStorageLocation, - StorageLocation, + DEFAULT_SAVING_LOCATIONS, + SECRET_STORAGE_LOCATIONS, + STORAGE_LOCATIONS, } from '../../../storage/storageController'; import { mdbTestExtension } from '../stubbableMdbExtension'; import { TEST_DATABASE_URI } from '../dbTestHelper'; @@ -31,7 +31,7 @@ suite('Explorer Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations['Session Only'], + DEFAULT_SAVING_LOCATIONS['Session Only'], ); sandbox.stub(vscode.window, 'showInformationMessage'); sandbox.stub(vscode.window, 'showErrorMessage'); @@ -47,7 +47,7 @@ suite('Explorer Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DEFAULT_SAVING_LOCATIONS.Workspace, ); // Reset our connections. await mdbTestExtension.testExtensionController._connectionController.disconnect(); @@ -68,8 +68,8 @@ suite('Explorer Controller Test Suite', function () { id: 'testConnectionId', connectionOptions: { connectionString: 'mongodb://localhost' }, name: 'testConnectionName', - storageLocation: StorageLocation.NONE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.NONE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, }, }; testConnectionController._connectionAttempt = createConnectionAttempt({ @@ -213,8 +213,8 @@ suite('Explorer Controller Test Suite', function () { testConnectionController._connections[connectionId].connectionOptions, name: 'aaa', id: 'aaa', - storageLocation: StorageLocation.WORKSPACE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.WORKSPACE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, }; testConnectionController._connections.zzz = { @@ -222,8 +222,8 @@ suite('Explorer Controller Test Suite', function () { testConnectionController._connections[connectionId].connectionOptions, name: 'zzz', id: 'zzz', - storageLocation: StorageLocation.WORKSPACE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.WORKSPACE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, }; const connectionsItems = await treeController.getChildren(); diff --git a/src/test/suite/explorer/indexTreeItem.test.ts b/src/test/suite/explorer/indexTreeItem.test.ts index c440ca33e..2f834cecb 100644 --- a/src/test/suite/explorer/indexTreeItem.test.ts +++ b/src/test/suite/explorer/indexTreeItem.test.ts @@ -2,7 +2,7 @@ import assert from 'assert'; import IndexTreeItem, { IndexFieldTreeItem, - IndexKeyType, + INDEX_KEY_TYPES, } from '../../../explorer/indexTreeItem'; import type * as vscode from 'vscode'; @@ -33,7 +33,7 @@ suite('IndexTreeItem Test Suite', () => { test('it has an icon for the index type', () => { const testIndexFieldTreeItem = new IndexFieldTreeItem({ indexKey: 'locations', - indexKeyType: IndexKeyType.GEOSPHERE, + indexKeyType: INDEX_KEY_TYPES.GEOSPHERE, }); const iconPath = testIndexFieldTreeItem.iconPath as { diff --git a/src/test/suite/explorer/schemaTreeItem.test.ts b/src/test/suite/explorer/schemaTreeItem.test.ts index 66e964b75..5626f5c04 100644 --- a/src/test/suite/explorer/schemaTreeItem.test.ts +++ b/src/test/suite/explorer/schemaTreeItem.test.ts @@ -188,10 +188,10 @@ suite('SchemaTreeItem Test Suite', function () { "Unable to parse schema: Cannot use 'in' operator to search for 'Symbol(Symbol.iterator)' in invalid schema to parse"; assert.strictEqual( - (error).message, + (error as Error).message, expectedMessage, `Expected error message to be "${expectedMessage}" found "${ - (error).message + (error as Error).message }"`, ); } diff --git a/src/test/suite/language/mongoDBService.test.ts b/src/test/suite/language/mongoDBService.test.ts index 95339be6d..a44a8c47b 100644 --- a/src/test/suite/language/mongoDBService.test.ts +++ b/src/test/suite/language/mongoDBService.test.ts @@ -22,7 +22,7 @@ import MongoDBService, { import { mdbTestExtension } from '../stubbableMdbExtension'; import { StreamStub } from '../stubs'; import DIAGNOSTIC_CODES from '../../../language/diagnosticCodes'; -import { ServerCommands } from '../../../language/serverCommands'; +import { SERVER_COMMANDS } from '../../../language/serverCommands'; import LINKS from '../../../utils/links'; import Sinon from 'sinon'; @@ -2965,7 +2965,7 @@ suite('MongoDBService Test Suite', () => { consoleOutputs = []; Sinon.stub(connection, 'sendNotification') - .withArgs(ServerCommands.SHOW_CONSOLE_OUTPUT) + .withArgs(SERVER_COMMANDS.SHOW_CONSOLE_OUTPUT) .callsFake((_, params) => Promise.resolve(void consoleOutputs.push(...params)), ); diff --git a/src/test/suite/mcp/mcpConnectionErrorHandler.test.ts b/src/test/suite/mcp/mcpConnectionErrorHandler.test.ts index 95ff3ac57..94ff0d5ea 100644 --- a/src/test/suite/mcp/mcpConnectionErrorHandler.test.ts +++ b/src/test/suite/mcp/mcpConnectionErrorHandler.test.ts @@ -12,14 +12,15 @@ import type { } from 'mongodb-mcp-server'; import { ErrorCodes } from 'mongodb-mcp-server'; +type MongoDBErrorCode = + | typeof ErrorCodes.NotConnectedToMongoDB + | typeof ErrorCodes.MisconfiguredConnectionString; + class MongoDBError extends Error { - constructor( - public code: - | ErrorCodes.NotConnectedToMongoDB - | ErrorCodes.MisconfiguredConnectionString, - message: string, - ) { + code: MongoDBErrorCode; + constructor(code: MongoDBErrorCode, message: string) { super(message); + this.code = code; } } diff --git a/src/test/suite/mdbExtensionController.test.ts b/src/test/suite/mdbExtensionController.test.ts index 2a94e05f5..4c1aab7d5 100644 --- a/src/test/suite/mdbExtensionController.test.ts +++ b/src/test/suite/mdbExtensionController.test.ts @@ -9,27 +9,27 @@ import type { Document, Filter } from 'mongodb'; import { CollectionTreeItem, - CollectionTypes, ConnectionTreeItem, DatabaseTreeItem, DocumentTreeItem, SchemaTreeItem, StreamProcessorTreeItem, } from '../../explorer'; -import EXTENSION_COMMANDS from '../../commands'; +import EXTENSION_COMMANDS, { ExtensionCommand } from '../../commands'; import FieldTreeItem from '../../explorer/fieldTreeItem'; import IndexListTreeItem from '../../explorer/indexListTreeItem'; import { mdbTestExtension } from './stubbableMdbExtension'; import { mockTextEditor } from './stubs'; import { - SecretStorageLocation, - StorageLocation, - StorageVariables, + STORAGE_LOCATIONS, + SECRET_STORAGE_LOCATIONS, + STORAGE_VARIABLES, } from '../../storage/storageController'; import { VIEW_COLLECTION_SCHEME } from '../../editors/collectionDocumentsProvider'; import type { CollectionDetailsType } from '../../explorer/collectionTreeItem'; import { expect } from 'chai'; import { DeepLinkTelemetryEvent } from '../../telemetry'; +import { COLLECTION_TYPES } from '../../explorer/documentListTreeItem'; import { DEEP_LINK_ALLOWED_COMMANDS, DEEP_LINK_DISALLOWED_COMMANDS, @@ -59,7 +59,7 @@ function getTestCollectionTreeItem( return new CollectionTreeItem({ collection: { name: 'testColName', - type: CollectionTypes.collection, + type: COLLECTION_TYPES.collection, } as unknown as CollectionDetailsType, databaseName: 'testDbName', dataService: {} as DataService, @@ -145,10 +145,10 @@ suite('MDBExtensionController Test Suite', function () { suite('Deep link command lists validation', () => { test('allowed and disallowed lists are disjoint', () => { const allowedSet = new Set( - DEEP_LINK_ALLOWED_COMMANDS as readonly EXTENSION_COMMANDS[], + DEEP_LINK_ALLOWED_COMMANDS as readonly ExtensionCommand[], ); const disallowedSet = new Set( - DEEP_LINK_DISALLOWED_COMMANDS as readonly EXTENSION_COMMANDS[], + DEEP_LINK_DISALLOWED_COMMANDS as readonly ExtensionCommand[], ); const overlap = [...allowedSet].filter((cmd) => disallowedSet.has(cmd)); @@ -162,10 +162,10 @@ suite('MDBExtensionController Test Suite', function () { test('allowed and disallowed lists are complete', () => { const allCommands = new Set(Object.values(EXTENSION_COMMANDS)); const allowedSet = new Set( - DEEP_LINK_ALLOWED_COMMANDS as readonly EXTENSION_COMMANDS[], + DEEP_LINK_ALLOWED_COMMANDS as readonly ExtensionCommand[], ); const disallowedSet = new Set( - DEEP_LINK_DISALLOWED_COMMANDS as readonly EXTENSION_COMMANDS[], + DEEP_LINK_DISALLOWED_COMMANDS as readonly ExtensionCommand[], ); const combinedSet = new Set([...allowedSet, ...disallowedSet]); @@ -764,7 +764,7 @@ suite('MDBExtensionController Test Suite', function () { const testCollectionTreeItem = getTestCollectionTreeItem({ collection: { name: 'doesntExistColName', - type: CollectionTypes.collection, + type: COLLECTION_TYPES.collection, } as unknown as CollectionDetailsType, dataService: testConnectionController.getActiveDataService() ?? undefined, @@ -795,7 +795,7 @@ suite('MDBExtensionController Test Suite', function () { const testCollectionTreeItem = getTestCollectionTreeItem({ collection: { name: 'orange', - type: CollectionTypes.collection, + type: COLLECTION_TYPES.collection, } as unknown as CollectionDetailsType, }); const inputBoxResolvesStub = sandbox.stub(); @@ -904,8 +904,8 @@ suite('MDBExtensionController Test Suite', function () { id: 'blueBerryPancakesAndTheSmellOfBacon', connectionOptions: { connectionString: 'mongodb://localhost' }, name: 'NAAAME', - storageLocation: StorageLocation.NONE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.NONE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, }; const testTreeItem = getTestConnectionTreeItem({ @@ -935,8 +935,8 @@ suite('MDBExtensionController Test Suite', function () { id: 'blueBerryPancakesAndTheSmellOfBacon', name: 'NAAAME', connectionOptions: { connectionString: 'mongodb://localhost' }, - storageLocation: StorageLocation.NONE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.NONE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, }; const testTreeItem = getTestConnectionTreeItem({ @@ -1357,7 +1357,7 @@ suite('MDBExtensionController Test Suite', function () { const collectionTreeItem = getTestCollectionTreeItem({ collection: { name: 'pineapple', - type: CollectionTypes.collection, + type: COLLECTION_TYPES.collection, } as unknown as CollectionDetailsType, databaseName: 'plants', }); @@ -1690,7 +1690,7 @@ suite('MDBExtensionController Test Suite', function () { assert(fakeUpdate.called); assert.strictEqual( fakeUpdate.firstCall.args[0], - StorageVariables.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, + STORAGE_VARIABLES.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, ); assert.strictEqual( fakeUpdate.firstCall.args[0], @@ -1735,7 +1735,7 @@ suite('MDBExtensionController Test Suite', function () { assert(fakeUpdate.called); assert.strictEqual( fakeUpdate.firstCall.args[0], - StorageVariables.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, + STORAGE_VARIABLES.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, ); assert.strictEqual( fakeUpdate.firstCall.args[0], diff --git a/src/test/suite/participant/participant.test.ts b/src/test/suite/participant/participant.test.ts index 3ecafbfa5..d7bced565 100644 --- a/src/test/suite/participant/participant.test.ts +++ b/src/test/suite/participant/participant.test.ts @@ -23,8 +23,8 @@ import { TEST_DATABASE_URI } from '../dbTestHelper'; import type { ChatResult } from '../../../participant/constants'; import { CHAT_PARTICIPANT_ID } from '../../../participant/constants'; import { - SecretStorageLocation, - StorageLocation, + SECRET_STORAGE_LOCATIONS, + STORAGE_LOCATIONS, } from '../../../storage/storageController'; import type { LoadedConnection } from '../../../storage/connectionStorage'; import { ChatMetadataStore } from '../../../participant/chatMetadata'; @@ -34,7 +34,7 @@ import { Prompts } from '../../../participant/prompts'; import { createMarkdownLink } from '../../../participant/markdown'; import EXTENSION_COMMANDS from '../../../commands'; import { getContentLength } from '../../../participant/prompts/promptBase'; -import { ParticipantErrorTypes } from '../../../participant/participantErrorTypes'; +import { PARTICIPANT_ERROR_TYPES } from '../../../participant/participantErrorTypes'; import * as model from '../../../participant/model'; import { createChatRequestTurn, @@ -47,8 +47,8 @@ import type { ParticipantRequestType, SendMessageToParticipantOptions, } from '../../../participant/participantTypes'; -import { DocumentSource } from '../../../documentSource'; import { TelemetryService } from '../../../telemetry'; +import { DOCUMENT_SOURCE } from '../../../documentSource'; // The Copilot's model in not available in tests, // therefore we need to mock its methods and returning values. @@ -57,8 +57,8 @@ const MAX_TOTAL_PROMPT_LENGTH_MOCK = 16000; const loadedConnection = { id: 'id', name: 'localhost', - storageLocation: StorageLocation.NONE, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.NONE, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, connectionOptions: { connectionString: 'mongodb://localhost' }, }; @@ -1942,7 +1942,7 @@ Schema: message: `I want to ask questions about the \`${mockDatabaseItem.databaseName}\` database.`, isNewChat: true, telemetry: { - source: DocumentSource.DOCUMENT_SOURCE_TREEVIEW, + source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW, source_details: 'database', }, }, @@ -1973,7 +1973,7 @@ Schema: message: `I want to ask questions about the \`${mockCollectionItem.databaseName}\` database's \`${mockCollectionItem.collectionName}\` collection.`, isNewChat: true, telemetry: { - source: DocumentSource.DOCUMENT_SOURCE_TREEVIEW, + source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW, source_details: 'collection', }, }, @@ -2638,7 +2638,7 @@ Schema: createChatResponseTurn('/query', undefined, { result: { errorDetails: { - message: ParticipantErrorTypes.FILTERED, + message: PARTICIPANT_ERROR_TYPES.FILTERED, }, metadata: {}, }, diff --git a/src/test/suite/storage/connectionStorage.test.ts b/src/test/suite/storage/connectionStorage.test.ts index d2338b449..9b5b49385 100644 --- a/src/test/suite/storage/connectionStorage.test.ts +++ b/src/test/suite/storage/connectionStorage.test.ts @@ -3,11 +3,14 @@ import * as vscode from 'vscode'; import { afterEach, beforeEach } from 'mocha'; import { expect } from 'chai'; -import { StorageController, StorageVariables } from '../../../storage'; import { - StorageLocation, - DefaultSavingLocations, - SecretStorageLocation, + StorageController, + STORAGE_VARIABLES, + STORAGE_LOCATIONS, +} from '../../../storage'; +import { + DEFAULT_SAVING_LOCATIONS, + SECRET_STORAGE_LOCATIONS, } from '../../../storage/storageController'; import { ExtensionContextStub } from '../stubs'; import { @@ -66,7 +69,10 @@ suite('Connection Storage Test Suite', function () { test('it loads both global and workspace stored connections', async () => { await vscode.workspace .getConfiguration('mdb.connectionSaving') - .update('defaultConnectionSavingLocation', DefaultSavingLocations.Global); + .update( + 'defaultConnectionSavingLocation', + DEFAULT_SAVING_LOCATIONS.Global, + ); await testConnectionStorage.saveConnection( newTestConnection(testConnectionStorage, '1'), @@ -78,7 +84,7 @@ suite('Connection Storage Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DEFAULT_SAVING_LOCATIONS.Workspace, ); await testConnectionStorage.saveConnection( @@ -104,15 +110,18 @@ suite('Connection Storage Test Suite', function () { test('when a connection is added it is saved to the global storage', async () => { await vscode.workspace .getConfiguration('mdb.connectionSaving') - .update('defaultConnectionSavingLocation', DefaultSavingLocations.Global); + .update( + 'defaultConnectionSavingLocation', + DEFAULT_SAVING_LOCATIONS.Global, + ); await testConnectionStorage.saveConnection( newTestConnection(testConnectionStorage, '1'), ); const globalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ); expect(Object.keys(globalStoreConnections).length).to.equal(1); @@ -124,7 +133,7 @@ suite('Connection Storage Test Suite', function () { ); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, ); expect(workspaceStoreConnections).to.equal(undefined); @@ -135,15 +144,15 @@ suite('Connection Storage Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DEFAULT_SAVING_LOCATIONS.Workspace, ); await testConnectionStorage.saveConnection( newTestConnection(testConnectionStorage, '1'), ); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); expect(Object.keys(workspaceStoreConnections).length).to.equal(1); @@ -155,8 +164,8 @@ suite('Connection Storage Test Suite', function () { ); const globalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ); expect(globalStoreConnections).to.equal(undefined); @@ -168,7 +177,7 @@ suite('Connection Storage Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations['Session Only'], + DEFAULT_SAVING_LOCATIONS['Session Only'], ); await testConnectionStorage.saveConnection( newTestConnection(testConnectionStorage, '1'), @@ -176,15 +185,15 @@ suite('Connection Storage Test Suite', function () { const objectString = JSON.stringify(undefined); const globalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ); expect(JSON.stringify(globalStoreConnections)).to.equal(objectString); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); expect(JSON.stringify(workspaceStoreConnections)).to.equal(objectString); @@ -195,7 +204,7 @@ suite('Connection Storage Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DEFAULT_SAVING_LOCATIONS.Workspace, ); const connectionId = 'pie'; await testConnectionStorage.saveConnection( @@ -203,8 +212,8 @@ suite('Connection Storage Test Suite', function () { ); const workspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); expect(Object.keys(workspaceStoreConnections).length).to.equal(1); @@ -212,8 +221,8 @@ suite('Connection Storage Test Suite', function () { await testConnectionStorage.removeConnection(connectionId); const postWorkspaceStoreConnections = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); expect(Object.keys(postWorkspaceStoreConnections).length).to.equal(0); }); @@ -221,15 +230,18 @@ suite('Connection Storage Test Suite', function () { test('when a connection is removed it is also removed from global storage', async () => { await vscode.workspace .getConfiguration('mdb.connectionSaving') - .update('defaultConnectionSavingLocation', DefaultSavingLocations.Global); + .update( + 'defaultConnectionSavingLocation', + DEFAULT_SAVING_LOCATIONS.Global, + ); const connectionId = 'pineapple'; await testConnectionStorage.saveConnection( newTestConnection(testConnectionStorage, connectionId), ); const globalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ); expect(Object.keys(globalStoreConnections).length).to.equal(1); @@ -237,8 +249,8 @@ suite('Connection Storage Test Suite', function () { await testConnectionStorage.removeConnection(connectionId); const postGlobalStoreConnections = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ); expect(Object.keys(postGlobalStoreConnections).length).to.equal(0); @@ -263,7 +275,7 @@ suite('Connection Storage Test Suite', function () { const oldSavedConnectionInfo = { id: '1d700f37-ba57-4568-9552-0ea23effea89', name: 'localhost:27017', - storageLocation: StorageLocation.GLOBAL, + storageLocation: STORAGE_LOCATIONS.GLOBAL, connectionModel: { _id: '4', isFavorite: false, @@ -295,8 +307,8 @@ suite('Connection Storage Test Suite', function () { const connectionInfo = { id: '1d700f37-ba57-4568-9552-0ea23effea89', name: 'localhost:27017', - storageLocation: StorageLocation.GLOBAL, - secretStorageLocation: SecretStorageLocation.SecretStorage, + storageLocation: STORAGE_LOCATIONS.GLOBAL, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, connectionOptions: { connectionString: 'mongodb://localhost:27017/?readPreference=primary&ssl=false', @@ -475,7 +487,7 @@ suite('Connection Storage Test Suite', function () { expect( savedConnections.every( ({ secretStorageLocation }) => - secretStorageLocation === SecretStorageLocation.SecretStorage, + secretStorageLocation === SECRET_STORAGE_LOCATIONS.SecretStorage, ), ).to.equal(true); @@ -491,7 +503,7 @@ suite('Connection Storage Test Suite', function () { id: 'random-connection-4', name: 'localhost:27089', storageLocation: 'GLOBAL', - secretStorageLocation: SecretStorageLocation.SecretStorage, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, connectionOptions: { connectionString: 'mongodb://localhost:27080/?readPreference=primary&ssl=false', @@ -499,8 +511,8 @@ suite('Connection Storage Test Suite', function () { }; testSandbox.replace(testStorageController, 'get', (key, storage) => { if ( - storage === StorageLocation.WORKSPACE || - key === StorageVariables.WORKSPACE_SAVED_CONNECTIONS + storage === STORAGE_LOCATIONS.WORKSPACE || + key === STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS ) { return {}; } @@ -510,7 +522,7 @@ suite('Connection Storage Test Suite', function () { id: 'random-connection-1', name: 'localhost:27017', storageLocation: 'GLOBAL', - secretStorageLocation: SecretStorageLocation.Keytar, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.Keytar, connectionOptions: { connectionString: 'mongodb://localhost:27017/?readPreference=primary&ssl=false', @@ -520,7 +532,7 @@ suite('Connection Storage Test Suite', function () { id: 'random-connection-2', name: 'localhost:27017', storageLocation: 'GLOBAL', - secretStorageLocation: SecretStorageLocation.KeytarSecondAttempt, + secretStorageLocation: SECRET_STORAGE_LOCATIONS.KeytarSecondAttempt, connectionOptions: { connectionString: 'mongodb://localhost:27017/?readPreference=primary&ssl=false', @@ -552,7 +564,7 @@ suite('Connection Storage Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DefaultSavingLocations.Workspace, + DEFAULT_SAVING_LOCATIONS.Workspace, ); await testConnectionStorage.saveConnection( diff --git a/src/test/suite/storage/storageController.test.ts b/src/test/suite/storage/storageController.test.ts index 6d0c4f20c..1cb621e15 100644 --- a/src/test/suite/storage/storageController.test.ts +++ b/src/test/suite/storage/storageController.test.ts @@ -1,8 +1,8 @@ import assert from 'assert'; import StorageController, { - StorageVariables, - StorageLocation, + STORAGE_VARIABLES, + STORAGE_LOCATIONS, } from '../../../storage/storageController'; import { ExtensionContextStub } from '../stubs'; @@ -10,14 +10,14 @@ suite('Storage Controller Test Suite', () => { test('getting a variable gets it from the global context store', () => { const extensionContextStub = new ExtensionContextStub(); extensionContextStub._globalState = { - [StorageVariables.GLOBAL_SAVED_CONNECTIONS]: { + [STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS]: { collOne: { name: 'this_gonna_get_saved' }, }, }; const testStorageController = new StorageController(extensionContextStub); const testVal = testStorageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL, + STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.GLOBAL, ); assert( testVal.collOne.name === 'this_gonna_get_saved', @@ -28,14 +28,14 @@ suite('Storage Controller Test Suite', () => { test('getting a variable from the workspace state gets it from the workspace context store', () => { const extensionContextStub = new ExtensionContextStub(); extensionContextStub._workspaceState = { - [StorageVariables.WORKSPACE_SAVED_CONNECTIONS]: { + [STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS]: { collTwo: { name: 'i_cant_believe_its_gonna_save_this' }, }, }; const testStorageController = new StorageController(extensionContextStub); const testVal = testStorageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE, + STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + STORAGE_LOCATIONS.WORKSPACE, ); assert( testVal.collTwo.name === 'i_cant_believe_its_gonna_save_this', @@ -51,7 +51,7 @@ suite('Storage Controller Test Suite', () => { test('getUserIdentity adds anonymousId to the global storage and returns it to telemetry', () => { const userIdentity = testStorageController.getUserIdentity(); const anonymousId = testStorageController.get( - StorageVariables.GLOBAL_ANONYMOUS_ID, + STORAGE_VARIABLES.GLOBAL_ANONYMOUS_ID, ); assert.deepStrictEqual(userIdentity, { anonymousId }); }); diff --git a/src/test/suite/stubbableMdbExtension.ts b/src/test/suite/stubbableMdbExtension.ts index ce6dd7161..a3143e901 100644 --- a/src/test/suite/stubbableMdbExtension.ts +++ b/src/test/suite/stubbableMdbExtension.ts @@ -1,12 +1,7 @@ import type MDBExtensionController from '../../mdbExtensionController'; import type { ExtensionContextStub } from './stubs'; -// This interface has the instance of the extension we use for testing. -// This should be used for integration tests and higher level extension -// command testing that cannot be done on a more isolated level. - -// eslint-disable-next-line @typescript-eslint/no-namespace -export namespace mdbTestExtension { - export let extensionContextStub: ExtensionContextStub; - export let testExtensionController: MDBExtensionController; -} +export const mdbTestExtension = {} as { + extensionContextStub: ExtensionContextStub; + testExtensionController: MDBExtensionController; +}; diff --git a/src/test/suite/telemetry/connectionTelemetry.test.ts b/src/test/suite/telemetry/connectionTelemetry.test.ts index 7f61ea761..0ac623baa 100644 --- a/src/test/suite/telemetry/connectionTelemetry.test.ts +++ b/src/test/suite/telemetry/connectionTelemetry.test.ts @@ -4,7 +4,7 @@ import { expect } from 'chai'; import sinon from 'sinon'; import type { DataService } from 'mongodb-data-service'; -import { ConnectionTypes } from '../../../connectionController'; +import { CONNECTION_TYPES } from '../../../connectionController'; import { getConnectionTelemetryProperties } from '../../../telemetry/connectionTelemetry'; import { TEST_DATABASE_URI } from '../dbTestHelper'; @@ -62,7 +62,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_FORM, + CONNECTION_TYPES.CONNECTION_FORM, ); expect(instanceTelemetry.is_public_cloud).to.equal(true); expect(instanceTelemetry.public_cloud_name).to.equal('Azure'); @@ -95,7 +95,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_FORM, + CONNECTION_TYPES.CONNECTION_FORM, ); expect(instanceTelemetry.is_public_cloud).to.equal(false); }); @@ -130,7 +130,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_FORM, + CONNECTION_TYPES.CONNECTION_FORM, ); expect(instanceTelemetry.is_atlas).to.equal(false); expect(instanceTelemetry.atlas_hostname).to.equal(null); @@ -168,7 +168,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_FORM, + CONNECTION_TYPES.CONNECTION_FORM, ); expect(instanceTelemetry.is_atlas).to.equal(true); expect(instanceTelemetry.atlas_hostname).to.equal( @@ -208,7 +208,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_FORM, + CONNECTION_TYPES.CONNECTION_FORM, ); expect(instanceTelemetry.is_atlas).to.equal(true); expect(instanceTelemetry.atlas_hostname).to.equal( @@ -247,7 +247,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_FORM, + CONNECTION_TYPES.CONNECTION_FORM, ); expect(instanceTelemetry.is_localhost).to.equal(true); }); @@ -281,7 +281,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_STRING, + CONNECTION_TYPES.CONNECTION_STRING, ); expect(instanceTelemetry.is_localhost).to.equal(false); expect(instanceTelemetry.is_atlas_url).to.equal(false); @@ -316,7 +316,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_FORM, + CONNECTION_TYPES.CONNECTION_FORM, ); expect(instanceTelemetry.is_used_connect_screen).to.equal(true); expect(instanceTelemetry.is_used_command_palette).to.equal(false); @@ -350,7 +350,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_STRING, + CONNECTION_TYPES.CONNECTION_STRING, ); expect(instanceTelemetry.is_used_connect_screen).to.equal(false); expect(instanceTelemetry.is_used_command_palette).to.equal(true); @@ -384,7 +384,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_ID, + CONNECTION_TYPES.CONNECTION_ID, ); expect(instanceTelemetry.is_used_connect_screen).to.equal(false); expect(instanceTelemetry.is_used_command_palette).to.equal(false); @@ -420,7 +420,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_STRING, + CONNECTION_TYPES.CONNECTION_STRING, ); expect(instanceTelemetry.is_localhost).to.equal(false); }); @@ -452,7 +452,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_STRING, + CONNECTION_TYPES.CONNECTION_STRING, ); expect(instanceTelemetry.is_localhost).to.equal(true); }); @@ -490,7 +490,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_STRING, + CONNECTION_TYPES.CONNECTION_STRING, ); expect(instanceTelemetry.server_version).to.equal('4.3.9'); expect(instanceTelemetry.server_arch).to.equal('debian'); @@ -530,7 +530,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_STRING, + CONNECTION_TYPES.CONNECTION_STRING, ); expect(instanceTelemetry.server_version).to.equal('4.3.2'); expect(instanceTelemetry.server_arch).to.equal('darwin'); @@ -564,7 +564,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_STRING, + CONNECTION_TYPES.CONNECTION_STRING, ); expect(instanceTelemetry.auth_strategy).to.equal('DEFAULT'); }); @@ -596,7 +596,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_STRING, + CONNECTION_TYPES.CONNECTION_STRING, ); expect(instanceTelemetry.auth_strategy).to.equal('NONE'); }); @@ -630,7 +630,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { const instanceTelemetry = await getConnectionTelemetryProperties( dataServiceStub, - ConnectionTypes.CONNECTION_STRING, + CONNECTION_TYPES.CONNECTION_STRING, ); expect(instanceTelemetry.auth_strategy).to.equal('SCRAM-SHA-1'); }); @@ -655,7 +655,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { test('track new connection event fetches the connection instance information', async () => { const instanceTelemetry = await getConnectionTelemetryProperties( dataServ, - ConnectionTypes.CONNECTION_STRING, + CONNECTION_TYPES.CONNECTION_STRING, ); expect(instanceTelemetry.is_localhost).to.equal(true); diff --git a/src/test/suite/telemetry/telemetryService.test.ts b/src/test/suite/telemetry/telemetryService.test.ts index 07b325dc4..955e59b8d 100644 --- a/src/test/suite/telemetry/telemetryService.test.ts +++ b/src/test/suite/telemetry/telemetryService.test.ts @@ -9,8 +9,7 @@ import sinon from 'sinon'; import type { SinonSpy } from 'sinon'; import sinonChai from 'sinon-chai'; -import { ConnectionTypes } from '../../../connectionController'; -import { DocumentSource } from '../../../documentSource'; +import { DOCUMENT_SOURCE } from '../../../documentSource'; import { mdbTestExtension } from '../stubbableMdbExtension'; import { DatabaseTreeItem, DocumentTreeItem } from '../../../explorer'; import { DataServiceStub } from '../stubs'; @@ -25,6 +24,7 @@ import { SavedConnectionsLoadedTelemetryEvent, } from '../../../telemetry'; import type { SegmentProperties } from '../../../telemetry/telemetryService'; +import { CONNECTION_TYPES } from '../../../connectionController'; // eslint-disable-next-line @typescript-eslint/no-var-requires const { version } = require('../../../../package.json'); @@ -157,7 +157,7 @@ suite('Telemetry Controller Test Suite', () => { test('track new connection event when connecting via connection string', async () => { await testTelemetryService.trackNewConnection( dataServiceStub, - ConnectionTypes.CONNECTION_STRING, + CONNECTION_TYPES.CONNECTION_STRING, ); sandbox.assert.calledWith( fakeSegmentAnalyticsTrack, @@ -178,7 +178,7 @@ suite('Telemetry Controller Test Suite', () => { test('track new connection event when connecting via connection form', async () => { await testTelemetryService.trackNewConnection( dataServiceStub, - ConnectionTypes.CONNECTION_FORM, + CONNECTION_TYPES.CONNECTION_FORM, ); sandbox.assert.calledWith( fakeSegmentAnalyticsTrack, @@ -199,7 +199,7 @@ suite('Telemetry Controller Test Suite', () => { test('track new connection event when connecting via saved connection', async () => { await testTelemetryService.trackNewConnection( dataServiceStub, - ConnectionTypes.CONNECTION_ID, + CONNECTION_TYPES.CONNECTION_ID, ); sandbox.assert.calledWith( fakeSegmentAnalyticsTrack, @@ -218,7 +218,7 @@ suite('Telemetry Controller Test Suite', () => { }); test('track document saved form a tree-view event', () => { - const source = DocumentSource.DOCUMENT_SOURCE_TREEVIEW; + const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW; testTelemetryService.track( new DocumentUpdatedTelemetryEvent(source, true), ); @@ -237,7 +237,7 @@ suite('Telemetry Controller Test Suite', () => { }); test('track document opened form playground results', () => { - const source = DocumentSource.DOCUMENT_SOURCE_PLAYGROUND; + const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_PLAYGROUND; testTelemetryService.track(new DocumentEditedTelemetryEvent(source)); sandbox.assert.calledWith( fakeSegmentAnalyticsTrack, diff --git a/src/utils/playground.ts b/src/utils/playground.ts index 4099d3794..2421f1b9a 100644 --- a/src/utils/playground.ts +++ b/src/utils/playground.ts @@ -8,7 +8,11 @@ import { createLogger } from '../logging'; const log = createLogger('playground utils'); export class FileStat implements vscode.FileStat { - constructor(private fsStat: fs.Stats) {} + private fsStat: fs.Stats; + + constructor(fsStat: fs.Stats) { + this.fsStat = fsStat; + } get type(): vscode.FileType { if (this.fsStat.isFile()) { diff --git a/src/views/webview-app/extension-app-message-constants.ts b/src/views/webview-app/extension-app-message-constants.ts index 80a197347..7e49d5cbb 100644 --- a/src/views/webview-app/extension-app-message-constants.ts +++ b/src/views/webview-app/extension-app-message-constants.ts @@ -1,13 +1,16 @@ import type { ConnectionOptions } from 'mongodb-data-service'; import type { FileChooserOptions } from './use-connection-form'; -export enum CONNECTION_STATUS { - LOADING = 'LOADING', // When the connection status has not yet been shared from the extension. - CONNECTED = 'CONNECTED', - CONNECTING = 'CONNECTING', - DISCONNECTING = 'DISCONNECTING', - DISCONNECTED = 'DISCONNECTED', -} +export const CONNECTION_STATUS = { + LOADING: 'LOADING', // When the connection status has not yet been shared from the extension. + CONNECTED: 'CONNECTED', + CONNECTING: 'CONNECTING', + DISCONNECTING: 'DISCONNECTING', + DISCONNECTED: 'DISCONNECTED', +} as const; + +export type ConnectionStatus = + (typeof CONNECTION_STATUS)[keyof typeof CONNECTION_STATUS]; export const VSCODE_EXTENSION_SEGMENT_ANONYMOUS_ID = 'VSCODE_EXTENSION_SEGMENT_ANONYMOUS_ID'; @@ -15,45 +18,45 @@ export const VSCODE_EXTENSION_SEGMENT_ANONYMOUS_ID = export const VSCODE_EXTENSION_OIDC_DEVICE_AUTH_ID = 'VSCODE_EXTENSION_OIDC_DEVICE_AUTH_ID'; -export enum MESSAGE_TYPES { - CONNECT = 'CONNECT', - CANCEL_CONNECT = 'CANCEL_CONNECT', - CONNECT_RESULT = 'CONNECT_RESULT', - CONNECTION_FORM_OPENED = 'CONNECTION_FORM_OPENED', - OPEN_FILE_CHOOSER = 'OPEN_FILE_CHOOSER', - OPEN_FILE_CHOOSER_RESULT = 'OPEN_FILE_CHOOSER_RESULT', - CONNECTION_STATUS_MESSAGE = 'CONNECTION_STATUS_MESSAGE', - OPEN_EDIT_CONNECTION = 'OPEN_EDIT_CONNECTION', - EDIT_CONNECTION_AND_CONNECT = 'EDIT_CONNECTION_AND_CONNECT', - EXTENSION_LINK_CLICKED = 'EXTENSION_LINK_CLICKED', - CREATE_NEW_PLAYGROUND = 'CREATE_NEW_PLAYGROUND', - GET_CONNECTION_STATUS = 'GET_CONNECTION_STATUS', - OPEN_CONNECTION_STRING_INPUT = 'OPEN_CONNECTION_STRING_INPUT', - OPEN_TRUSTED_LINK = 'OPEN_TRUSTED_LINK', - RENAME_ACTIVE_CONNECTION = 'RENAME_ACTIVE_CONNECTION', - THEME_CHANGED = 'THEME_CHANGED', -} +export const MESSAGE_TYPES = { + CONNECT: 'CONNECT', + CANCEL_CONNECT: 'CANCEL_CONNECT', + CONNECT_RESULT: 'CONNECT_RESULT', + CONNECTION_FORM_OPENED: 'CONNECTION_FORM_OPENED', + OPEN_FILE_CHOOSER: 'OPEN_FILE_CHOOSER', + OPEN_FILE_CHOOSER_RESULT: 'OPEN_FILE_CHOOSER_RESULT', + CONNECTION_STATUS_MESSAGE: 'CONNECTION_STATUS_MESSAGE', + OPEN_EDIT_CONNECTION: 'OPEN_EDIT_CONNECTION', + EDIT_CONNECTION_AND_CONNECT: 'EDIT_CONNECTION_AND_CONNECT', + EXTENSION_LINK_CLICKED: 'EXTENSION_LINK_CLICKED', + CREATE_NEW_PLAYGROUND: 'CREATE_NEW_PLAYGROUND', + GET_CONNECTION_STATUS: 'GET_CONNECTION_STATUS', + OPEN_CONNECTION_STRING_INPUT: 'OPEN_CONNECTION_STRING_INPUT', + OPEN_TRUSTED_LINK: 'OPEN_TRUSTED_LINK', + RENAME_ACTIVE_CONNECTION: 'RENAME_ACTIVE_CONNECTION', + THEME_CHANGED: 'THEME_CHANGED', +} as const; interface BasicWebviewMessage { command: string; } export interface CreateNewPlaygroundMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.CREATE_NEW_PLAYGROUND; + command: typeof MESSAGE_TYPES.CREATE_NEW_PLAYGROUND; } export interface ConnectionFormOpenedMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.CONNECTION_FORM_OPENED; + command: typeof MESSAGE_TYPES.CONNECTION_FORM_OPENED; } export interface ConnectionStatusMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.CONNECTION_STATUS_MESSAGE; - connectionStatus: CONNECTION_STATUS; + command: typeof MESSAGE_TYPES.CONNECTION_STATUS_MESSAGE; + connectionStatus: ConnectionStatus; activeConnectionName: string; } export interface OpenEditConnectionMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.OPEN_EDIT_CONNECTION; + command: typeof MESSAGE_TYPES.OPEN_EDIT_CONNECTION; connection: { id: string; name: string; @@ -62,7 +65,7 @@ export interface OpenEditConnectionMessage extends BasicWebviewMessage { } export interface EditConnectionAndConnectMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.EDIT_CONNECTION_AND_CONNECT; + command: typeof MESSAGE_TYPES.EDIT_CONNECTION_AND_CONNECT; connectionInfo: { id: string; connectionOptions: ConnectionOptions; @@ -70,13 +73,13 @@ export interface EditConnectionAndConnectMessage extends BasicWebviewMessage { } export interface OpenFileChooserMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.OPEN_FILE_CHOOSER; + command: typeof MESSAGE_TYPES.OPEN_FILE_CHOOSER; fileChooserOptions: FileChooserOptions; requestId: string; } export interface ConnectMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.CONNECT; + command: typeof MESSAGE_TYPES.CONNECT; connectionInfo: { id: string; connectionOptions: ConnectionOptions; @@ -84,11 +87,11 @@ export interface ConnectMessage extends BasicWebviewMessage { } export interface CancelConnectMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.CANCEL_CONNECT; + command: typeof MESSAGE_TYPES.CANCEL_CONNECT; } export interface ConnectResultsMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.CONNECT_RESULT; + command: typeof MESSAGE_TYPES.CONNECT_RESULT; connectionSuccess: boolean; connectionMessage: string; connectionId: string; @@ -99,36 +102,36 @@ export type FileChooserResult = | { canceled: false; filePath?: string }; export interface OpenFileChooserResultMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.OPEN_FILE_CHOOSER_RESULT; + command: typeof MESSAGE_TYPES.OPEN_FILE_CHOOSER_RESULT; fileChooserResult: FileChooserResult; requestId: string; } export interface GetConnectionStatusMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.GET_CONNECTION_STATUS; + command: typeof MESSAGE_TYPES.GET_CONNECTION_STATUS; } export interface OpenConnectionStringInputMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.OPEN_CONNECTION_STRING_INPUT; + command: typeof MESSAGE_TYPES.OPEN_CONNECTION_STRING_INPUT; } export interface LinkClickedMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.EXTENSION_LINK_CLICKED; + command: typeof MESSAGE_TYPES.EXTENSION_LINK_CLICKED; screen: string; linkId: string; } export interface OpenTrustedLinkMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.OPEN_TRUSTED_LINK; + command: typeof MESSAGE_TYPES.OPEN_TRUSTED_LINK; linkTo: string; } export interface RenameConnectionMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.RENAME_ACTIVE_CONNECTION; + command: typeof MESSAGE_TYPES.RENAME_ACTIVE_CONNECTION; } export interface ThemeChangedMessage extends BasicWebviewMessage { - command: MESSAGE_TYPES.THEME_CHANGED; + command: typeof MESSAGE_TYPES.THEME_CHANGED; darkMode: boolean; } diff --git a/src/views/webview-app/use-connection-form.ts b/src/views/webview-app/use-connection-form.ts index c36c40219..cd0bc746e 100644 --- a/src/views/webview-app/use-connection-form.ts +++ b/src/views/webview-app/use-connection-form.ts @@ -13,14 +13,17 @@ import { MESSAGE_TYPES } from './extension-app-message-constants'; import type { MessageFromExtensionToWebview } from './extension-app-message-constants'; import type { ElectronFileDialogOptions } from '@mongodb-js/compass-components'; -export enum FILE_CHOOSER_MODE { - OPEN = 'open', - SAVE = 'save', -} +export const FILE_CHOOSER_MODE = { + OPEN: 'open', + SAVE: 'save', +} as const; + +type FileChooserMode = + (typeof FILE_CHOOSER_MODE)[keyof typeof FILE_CHOOSER_MODE]; export type FileChooserOptions = { electronFileDialogOptions?: Partial; - mode: FILE_CHOOSER_MODE; + mode: FileChooserMode; }; type ConnectionInfo = { diff --git a/src/views/webview-app/use-connection-status.ts b/src/views/webview-app/use-connection-status.ts index e7cfe3b38..ab163de69 100644 --- a/src/views/webview-app/use-connection-status.ts +++ b/src/views/webview-app/use-connection-status.ts @@ -3,16 +3,17 @@ import { CONNECTION_STATUS, type MessageFromExtensionToWebview, MESSAGE_TYPES, + type ConnectionStatus, } from './extension-app-message-constants'; import vscode from './vscode-api'; const CONNECTION_STATUS_POLLING_FREQ_MS = 1000; const useConnectionStatus = (): { - connectionStatus: CONNECTION_STATUS; + connectionStatus: ConnectionStatus; connectionName: string; } => { - const [connectionStatus, setConnectionStatus] = useState( + const [connectionStatus, setConnectionStatus] = useState( CONNECTION_STATUS.LOADING, ); const [connectionName, setConnectionName] = useState(''); diff --git a/src/views/webviewController.ts b/src/views/webviewController.ts index 8c4d6f80d..a337f7980 100644 --- a/src/views/webviewController.ts +++ b/src/views/webviewController.ts @@ -4,7 +4,7 @@ import crypto from 'crypto'; import type { ConnectionOptions } from 'mongodb-data-service'; import type ConnectionController from '../connectionController'; -import { ConnectionTypes } from '../connectionController'; +import { CONNECTION_TYPES } from '../connectionController'; import { createLogger } from '../logging'; import EXTENSION_COMMANDS from '../commands'; import type { MessageFromWebviewToExtension } from './webview-app/extension-app-message-constants'; @@ -201,7 +201,7 @@ export default class WebviewController { : await this._connectionController.saveNewConnectionAndConnect({ connectionId: connection.id, connectionOptions: connection.connectionOptions, - connectionType: ConnectionTypes.CONNECTION_FORM, + connectionType: CONNECTION_TYPES.CONNECTION_FORM, }); try { diff --git a/tsconfig.json b/tsconfig.json index 7d774cb4c..f1c6b804f 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -11,7 +11,8 @@ "rootDir": "src", "esModuleInterop": true, "skipLibCheck": true, - "strict": true /* enable all strict type-checking options */ + "strict": true /* enable all strict type-checking options */, + "erasableSyntaxOnly": true /* Additional Checks */ // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ diff --git a/tsconfig.test.json b/tsconfig.test.json new file mode 100644 index 000000000..94d139f03 --- /dev/null +++ b/tsconfig.test.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "ts-node": { + "transpileOnly": true, + "compilerOptions": { + "module": "commonjs", + "jsx": "react" + } + } +} From 78a7d54e9cadf8cceee0dc52182398ef86238dfc Mon Sep 17 00:00:00 2001 From: gagik Date: Fri, 12 Dec 2025 13:45:00 +0100 Subject: [PATCH 2/9] chore: remove workarounds --- package.json | 2 +- src/test/setup-webview.ts | 31 ++++--------------------------- tsconfig.test.json | 10 ---------- 3 files changed, 5 insertions(+), 38 deletions(-) delete mode 100644 tsconfig.test.json diff --git a/package.json b/package.json index d64f9eed3..f51e20db3 100644 --- a/package.json +++ b/package.json @@ -71,7 +71,7 @@ "generate-vulnerability-report": "mongodb-sbom-tools generate-vulnerability-report --snyk-reports=.sbom/snyk-test-result.json --dependencies=.sbom/dependencies.json --fail-on=high", "create-vulnerability-tickets": "mongodb-sbom-tools generate-vulnerability-report --snyk-reports=.sbom/snyk-test-result.json --dependencies=.sbom/dependencies.json --create-jira-issues", "prepare": "husky", - "precommit": "node --experimental-strip-types ./scripts/precommit.ts" + "precommit": "node ./scripts/precommit.ts" }, "engines": { "vscode": "^1.101.1", diff --git a/src/test/setup-webview.ts b/src/test/setup-webview.ts index 37a05d2ea..5fb7c7af6 100644 --- a/src/test/setup-webview.ts +++ b/src/test/setup-webview.ts @@ -5,31 +5,6 @@ chai.use(sinonChai); // JSDom import { JSDOM, VirtualConsole } from 'jsdom'; -import { createRequire } from 'module'; - -// Create a require function that works in both ESM and CommonJS contexts -const requireModule = (() => { - if (typeof require !== 'undefined' && typeof require.cache === 'object') { - // We're in CommonJS context - return require; - } - - // We're in ESM context, create require from import.meta.url - // @ts-expect-error import.meta is not available in CommonJS context - if (typeof import.meta !== 'undefined' && import.meta.url) { - // @ts-expect-error import.meta is not available in CommonJS context - return createRequire(import.meta.url); - } - - // Fallback: try to create require from current file location - if (typeof __filename !== 'undefined') { - return createRequire(__filename); - } - - throw new Error( - 'Unable to create require function - neither ESM nor CommonJS context detected', - ); -})(); /** * NB: focus-trap and tabbable require special overrides to work in jsdom environments as per @@ -37,7 +12,8 @@ const requireModule = (() => { * * @see {@link https://github.com/focus-trap/tabbable?tab=readme-ov-file#testing-in-jsdom} */ -const tabbable = requireModule('tabbable'); +// eslint-disable-next-line @typescript-eslint/no-var-requires +const tabbable = require('tabbable'); const origTabbable = { ...tabbable }; @@ -52,7 +28,8 @@ Object.assign(tabbable, { origTabbable.isTabbable(node, { ...options, displayCheck: 'none' }), }); -const focusTrap = requireModule('focus-trap'); +// eslint-disable-next-line @typescript-eslint/no-var-requires +const focusTrap = require('focus-trap'); Object.assign(focusTrap, { ...focusTrap, diff --git a/tsconfig.test.json b/tsconfig.test.json deleted file mode 100644 index 94d139f03..000000000 --- a/tsconfig.test.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "extends": "./tsconfig.json", - "ts-node": { - "transpileOnly": true, - "compilerOptions": { - "module": "commonjs", - "jsx": "react" - } - } -} From b7b0b8d571ea9bf70d3831d9b51a149fd8c4a8d9 Mon Sep 17 00:00:00 2001 From: gagik Date: Fri, 12 Dec 2025 13:47:20 +0100 Subject: [PATCH 3/9] chore: use newer Node --- .github/workflows/test-and-build.yaml | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/.github/workflows/test-and-build.yaml b/.github/workflows/test-and-build.yaml index 68c37f732..4708cbe73 100644 --- a/.github/workflows/test-and-build.yaml +++ b/.github/workflows/test-and-build.yaml @@ -31,13 +31,18 @@ jobs: with: fetch-depth: 0 - - name: Setup pnpm - uses: pnpm/action-setup@v4 + - name: Get VS Code Node.js version + id: get-vscode-node-version + run: | + # Fetch Node.js version from VS Code's .nvmrc, default to 22.20.0 if unavailable + export NODE_VERSION=$(curl -fsSL https://raw.githubusercontent.com/microsoft/vscode/refs/heads/main/.nvmrc | tr -d '[:space:]' || echo "22.20.0") + echo "Using Node.js version for VS Code extension tests: $NODE_VERSION" + echo "vscode-node-version=$NODE_VERSION" >> $GITHUB_OUTPUT - name: Setup Node.js Environment uses: actions/setup-node@v4 with: - node-version: 22.15.1 + node-version: ${{ steps.get-vscode-node-version.outputs.vscode-node-version }} cache: pnpm - name: Run tests and build From 476f7e210287c98baa138cefc1a5c1c3c6206147 Mon Sep 17 00:00:00 2001 From: gagik Date: Fri, 12 Dec 2025 13:48:43 +0100 Subject: [PATCH 4/9] chore: pnpm --- .github/workflows/test-and-build.yaml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/test-and-build.yaml b/.github/workflows/test-and-build.yaml index 4708cbe73..41cc67101 100644 --- a/.github/workflows/test-and-build.yaml +++ b/.github/workflows/test-and-build.yaml @@ -39,6 +39,9 @@ jobs: echo "Using Node.js version for VS Code extension tests: $NODE_VERSION" echo "vscode-node-version=$NODE_VERSION" >> $GITHUB_OUTPUT + - name: Setup pnpm + uses: pnpm/action-setup@v4 + - name: Setup Node.js Environment uses: actions/setup-node@v4 with: From 867657f37858bfcb687f9a32e9be8631d1808512 Mon Sep 17 00:00:00 2001 From: gagik Date: Fri, 12 Dec 2025 13:51:05 +0100 Subject: [PATCH 5/9] chore: fixup action --- .github/workflows/test-and-build.yaml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test-and-build.yaml b/.github/workflows/test-and-build.yaml index 41cc67101..0e4b4e13c 100644 --- a/.github/workflows/test-and-build.yaml +++ b/.github/workflows/test-and-build.yaml @@ -33,9 +33,13 @@ jobs: - name: Get VS Code Node.js version id: get-vscode-node-version + shell: bash run: | # Fetch Node.js version from VS Code's .nvmrc, default to 22.20.0 if unavailable - export NODE_VERSION=$(curl -fsSL https://raw.githubusercontent.com/microsoft/vscode/refs/heads/main/.nvmrc | tr -d '[:space:]' || echo "22.20.0") + NODE_VERSION=$(curl -fsSL https://raw.githubusercontent.com/microsoft/vscode/main/.nvmrc | tr -d '[:space:]') + if [ -z "$NODE_VERSION" ]; then + NODE_VERSION="22.20.0" + fi echo "Using Node.js version for VS Code extension tests: $NODE_VERSION" echo "vscode-node-version=$NODE_VERSION" >> $GITHUB_OUTPUT From 959878d18b59123abf783989daa23996addd41f3 Mon Sep 17 00:00:00 2001 From: gagik Date: Fri, 12 Dec 2025 13:55:15 +0100 Subject: [PATCH 6/9] chore: fix lint --- src/test/suite/mdbExtensionController.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/suite/mdbExtensionController.test.ts b/src/test/suite/mdbExtensionController.test.ts index 4c1aab7d5..0f32d0ffe 100644 --- a/src/test/suite/mdbExtensionController.test.ts +++ b/src/test/suite/mdbExtensionController.test.ts @@ -15,7 +15,7 @@ import { SchemaTreeItem, StreamProcessorTreeItem, } from '../../explorer'; -import EXTENSION_COMMANDS, { ExtensionCommand } from '../../commands'; +import EXTENSION_COMMANDS, { type ExtensionCommand } from '../../commands'; import FieldTreeItem from '../../explorer/fieldTreeItem'; import IndexListTreeItem from '../../explorer/indexListTreeItem'; import { mdbTestExtension } from './stubbableMdbExtension'; From 2176e4bcd7f9016fec01b94cf8ed4b9e5d246580 Mon Sep 17 00:00:00 2001 From: gagik Date: Fri, 12 Dec 2025 17:03:15 +0100 Subject: [PATCH 7/9] chore: combine type and definition --- src/commands/index.ts | 6 +- src/documentSource.ts | 12 +- .../activeConnectionCodeLensProvider.ts | 4 +- .../collectionDocumentsCodeLensProvider.ts | 4 +- src/editors/editDocumentCodeLensProvider.ts | 10 +- src/editors/editorsController.ts | 6 +- .../exportToLanguageCodeLensProvider.ts | 4 +- src/editors/mongoDBDocumentService.ts | 6 +- ...playgroundDiagnosticsCodeActionProvider.ts | 13 +- .../playgroundSelectionCodeActionProvider.ts | 6 +- .../queryWithCopilotCodeLensProvider.ts | 8 +- src/explorer/collectionTreeItem.ts | 12 +- src/explorer/documentListTreeItem.ts | 12 +- src/explorer/explorerTreeController.ts | 10 +- src/explorer/fieldTreeItem.ts | 52 +-- src/explorer/index.ts | 4 +- src/explorer/indexTreeItem.ts | 19 +- src/explorer/playgroundsTree.ts | 4 +- src/language/diagnosticCodes.ts | 6 +- src/language/languageServerController.ts | 51 ++- src/language/mongoDBService.ts | 16 +- src/language/server.ts | 14 +- src/language/serverCommands.ts | 5 +- src/language/worker.ts | 8 +- src/mdbExtensionController.ts | 327 +++++++++--------- src/participant/participant.ts | 42 +-- src/participant/participantErrorTypes.ts | 4 +- src/participant/prompts/promptHistory.ts | 7 +- src/storage/connectionStorage.ts | 77 ++--- src/storage/index.ts | 6 +- src/storage/storageController.ts | 50 +-- src/telemetry/telemetryEvents.ts | 8 +- src/telemetry/telemetryService.ts | 13 +- src/test/suite/connectionController.test.ts | 147 ++++---- .../collectionDocumentsProvider.test.ts | 22 +- .../editDocumentCodeLensProvider.test.ts | 6 +- .../editors/mongoDBDocumentService.test.ts | 16 +- .../queryWithCopilotCodeLensProvider.test.ts | 4 +- .../suite/explorer/collectionTreeItem.test.ts | 12 +- .../explorer/documentListTreeItem.test.ts | 10 +- .../suite/explorer/explorerController.test.ts | 22 +- src/test/suite/explorer/indexTreeItem.test.ts | 4 +- src/test/suite/extension.test.ts | 4 +- .../suite/language/mongoDBService.test.ts | 40 +-- src/test/suite/mdbExtensionController.test.ts | 36 +- .../suite/participant/participant.test.ts | 24 +- .../suite/storage/connectionStorage.test.ts | 89 +++-- .../suite/storage/storageController.test.ts | 18 +- .../suite/telemetry/telemetryService.test.ts | 8 +- src/views/webviewController.ts | 6 +- 50 files changed, 625 insertions(+), 669 deletions(-) diff --git a/src/commands/index.ts b/src/commands/index.ts index ac020be2f..a3b4d1521 100644 --- a/src/commands/index.ts +++ b/src/commands/index.ts @@ -1,4 +1,4 @@ -const EXTENSION_COMMANDS = { +export const ExtensionCommand = { MDB_CONNECT: 'mdb.connect', MDB_CONNECT_WITH_URI: 'mdb.connectWithURI', MDB_OPEN_OVERVIEW_PAGE: 'mdb.openOverviewPage', @@ -100,6 +100,6 @@ const EXTENSION_COMMANDS = { } as const; export type ExtensionCommand = - (typeof EXTENSION_COMMANDS)[keyof typeof EXTENSION_COMMANDS]; + (typeof ExtensionCommand)[keyof typeof ExtensionCommand]; -export default EXTENSION_COMMANDS; +export default ExtensionCommand; diff --git a/src/documentSource.ts b/src/documentSource.ts index 1797080b7..3955a6cf6 100644 --- a/src/documentSource.ts +++ b/src/documentSource.ts @@ -1,11 +1,11 @@ -export const DOCUMENT_SOURCE = { - DOCUMENT_SOURCE_TREEVIEW: 'treeview', - DOCUMENT_SOURCE_PLAYGROUND: 'playground', - DOCUMENT_SOURCE_COLLECTIONVIEW: 'collectionview', - DOCUMENT_SOURCE_CODELENS: 'codelens', +export const DocumentSource = { + DocumentSource_TREEVIEW: 'treeview', + DocumentSource_PLAYGROUND: 'playground', + DocumentSource_COLLECTIONVIEW: 'collectionview', + DocumentSource_CODELENS: 'codelens', } as const; export type DocumentSource = - (typeof DOCUMENT_SOURCE)[keyof typeof DOCUMENT_SOURCE]; + (typeof DocumentSource)[keyof typeof DocumentSource]; export type DocumentSourceDetails = 'database' | 'collection' | undefined; diff --git a/src/editors/activeConnectionCodeLensProvider.ts b/src/editors/activeConnectionCodeLensProvider.ts index f22c5db15..a3c00b91b 100644 --- a/src/editors/activeConnectionCodeLensProvider.ts +++ b/src/editors/activeConnectionCodeLensProvider.ts @@ -1,6 +1,6 @@ import * as vscode from 'vscode'; -import EXTENSION_COMMANDS from '../commands'; +import ExtensionCommand from '../commands'; import type ConnectionController from '../connectionController'; import { isPlayground } from '../utils/playground'; import { getDBFromConnectionString } from '../utils/connection-string-db'; @@ -57,7 +57,7 @@ export default class ActiveConnectionCodeLensProvider codeLens.command = { title: message, - command: EXTENSION_COMMANDS.MDB_CHANGE_ACTIVE_CONNECTION, + command: ExtensionCommand.MDB_CHANGE_ACTIVE_CONNECTION, arguments: [], }; diff --git a/src/editors/collectionDocumentsCodeLensProvider.ts b/src/editors/collectionDocumentsCodeLensProvider.ts index ad41bc93e..d5c157ec7 100644 --- a/src/editors/collectionDocumentsCodeLensProvider.ts +++ b/src/editors/collectionDocumentsCodeLensProvider.ts @@ -1,6 +1,6 @@ import { URLSearchParams } from 'url'; import * as vscode from 'vscode'; -import EXTENSION_COMMANDS from '../commands'; +import ExtensionCommand from '../commands'; import type CollectionDocumentsOperationStore from './collectionDocumentsOperationsStore'; import { @@ -91,7 +91,7 @@ export default class CollectionDocumentsCodeLensProvider codeLens.command = { title: commandTitle, tooltip: commandTooltip, - command: EXTENSION_COMMANDS.MDB_CODELENS_SHOW_MORE_DOCUMENTS, + command: ExtensionCommand.MDB_CODELENS_SHOW_MORE_DOCUMENTS, arguments: [{ operationId, connectionId, namespace }], }; diff --git a/src/editors/editDocumentCodeLensProvider.ts b/src/editors/editDocumentCodeLensProvider.ts index 1f362a678..3681fde98 100644 --- a/src/editors/editDocumentCodeLensProvider.ts +++ b/src/editors/editDocumentCodeLensProvider.ts @@ -3,9 +3,9 @@ import { EJSON } from 'bson'; import type { Document } from 'bson'; import type ConnectionController from '../connectionController'; -import { DOCUMENT_SOURCE, type DocumentSource } from '../documentSource'; +import { DocumentSource } from '../documentSource'; import type { EditDocumentInfo } from '../types/editDocumentInfoType'; -import EXTENSION_COMMANDS, { type ExtensionCommand } from '../commands'; +import { ExtensionCommand } from '../commands'; import { PLAYGROUND_RESULT_URI } from './playgroundResultProvider'; import type { PlaygroundRunResult } from '../types/playgroundType'; @@ -38,14 +38,14 @@ export default class EditDocumentCodeLensProvider resultCodeLensesInfo = this._updateCodeLensesForCursor({ ...data, - source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_COLLECTIONVIEW, + source: DocumentSource.DocumentSource_COLLECTIONVIEW, }); this._codeLensesInfo[data.uri.toString()] = resultCodeLensesInfo; } updateCodeLensesForPlayground(playgroundResult: PlaygroundRunResult): void { - const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_PLAYGROUND; + const source = DocumentSource.DocumentSource_PLAYGROUND; let resultCodeLensesInfo: EditDocumentInfo[] = []; if (!playgroundResult || !playgroundResult.content) { @@ -148,7 +148,7 @@ export default class EditDocumentCodeLensProvider arguments: EditDocumentInfo[]; } = { title: 'Edit Document', - command: EXTENSION_COMMANDS.MDB_OPEN_MONGODB_DOCUMENT_FROM_CODE_LENS, + command: ExtensionCommand.MDB_OPEN_MONGODB_DOCUMENT_FROM_CODE_LENS, arguments: [item], }; diff --git a/src/editors/editorsController.ts b/src/editors/editorsController.ts index 6a01a341b..5b697dd9f 100644 --- a/src/editors/editorsController.ts +++ b/src/editors/editorsController.ts @@ -24,7 +24,7 @@ import formatError from '../utils/formatError'; import { MemoryFileSystemProvider } from './memoryFileSystemProvider'; import MongoDBDocumentService, { DOCUMENT_ID_URI_IDENTIFIER, - DOCUMENT_SOURCE_URI_IDENTIFIER, + DocumentSource_URI_IDENTIFIER, VIEW_DOCUMENT_SCHEME, } from './mongoDBDocumentService'; import type PlaygroundController from './playgroundController'; @@ -196,7 +196,7 @@ export default class EditorsController { const connectionIdUriQuery = `${CONNECTION_ID_URI_IDENTIFIER}=${activeConnectionId}`; const documentIdReference = this._documentIdStore.add(data.documentId); const documentIdUriQuery = `${DOCUMENT_ID_URI_IDENTIFIER}=${documentIdReference}`; - const documentSourceUriQuery = `${DOCUMENT_SOURCE_URI_IDENTIFIER}=${data.source}`; + const documentSourceUriQuery = `${DocumentSource_URI_IDENTIFIER}=${data.source}`; const fileTitle = encodeURIComponent( getFileDisplayNameForDocument(data.documentId, data.namespace), @@ -235,7 +235,7 @@ export default class EditorsController { const documentIdReference = uriParams.get(DOCUMENT_ID_URI_IDENTIFIER) || ''; const documentId = this._documentIdStore.get(documentIdReference); const source = uriParams.get( - DOCUMENT_SOURCE_URI_IDENTIFIER, + DocumentSource_URI_IDENTIFIER, ) as DocumentSource; if ( diff --git a/src/editors/exportToLanguageCodeLensProvider.ts b/src/editors/exportToLanguageCodeLensProvider.ts index 126890199..18893442d 100644 --- a/src/editors/exportToLanguageCodeLensProvider.ts +++ b/src/editors/exportToLanguageCodeLensProvider.ts @@ -1,6 +1,6 @@ import * as vscode from 'vscode'; -import EXTENSION_COMMANDS from '../commands'; +import ExtensionCommand from '../commands'; import { isExportToLanguageResult } from '../types/playgroundType'; import type PlaygroundResultProvider from './playgroundResultProvider'; @@ -52,7 +52,7 @@ export default class ExportToLanguageCodeLensProvider ? 'Exclude Driver Syntax' : 'Include Driver Syntax', command: - EXTENSION_COMMANDS.MDB_CHANGE_DRIVER_SYNTAX_FOR_EXPORT_TO_LANGUAGE, + ExtensionCommand.MDB_CHANGE_DRIVER_SYNTAX_FOR_EXPORT_TO_LANGUAGE, arguments: [ !this._playgroundResultProvider._playgroundResult.includeDriverSyntax, ], diff --git a/src/editors/mongoDBDocumentService.ts b/src/editors/mongoDBDocumentService.ts index 769be2c33..bc07e4ee0 100644 --- a/src/editors/mongoDBDocumentService.ts +++ b/src/editors/mongoDBDocumentService.ts @@ -3,7 +3,7 @@ import type { Document } from 'bson'; import type ConnectionController from '../connectionController'; import { createLogger } from '../logging'; -import { DOCUMENT_SOURCE, type DocumentSource } from '../documentSource'; +import { DocumentSource } from '../documentSource'; import type { EditDocumentInfo } from '../types/editDocumentInfoType'; import formatError from '../utils/formatError'; import type { StatusView } from '../views'; @@ -15,7 +15,7 @@ const log = createLogger('document controller'); export const DOCUMENT_ID_URI_IDENTIFIER = 'documentId'; -export const DOCUMENT_SOURCE_URI_IDENTIFIER = 'source'; +export const DocumentSource_URI_IDENTIFIER = 'source'; export const VIEW_DOCUMENT_SCHEME = 'VIEW_DOCUMENT_SCHEME'; @@ -53,7 +53,7 @@ export default class MongoDBDocumentService { this._telemetryService.track( new DocumentUpdatedTelemetryEvent( - DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW, + DocumentSource.DocumentSource_TREEVIEW, false, ), ); diff --git a/src/editors/playgroundDiagnosticsCodeActionProvider.ts b/src/editors/playgroundDiagnosticsCodeActionProvider.ts index 5a1dd6d66..d6a43d1b6 100644 --- a/src/editors/playgroundDiagnosticsCodeActionProvider.ts +++ b/src/editors/playgroundDiagnosticsCodeActionProvider.ts @@ -2,8 +2,8 @@ import * as vscode from 'vscode'; import type { Diagnostic } from 'vscode-languageserver/node'; -import EXTENSION_COMMANDS from '../commands'; -import DIAGNOSTIC_CODES from './../language/diagnosticCodes'; +import ExtensionCommand from '../commands'; +import DiagnosticCode from './../language/diagnosticCodes'; export default class PlaygroundDiagnosticsCodeActionProvider implements vscode.CodeActionProvider @@ -32,15 +32,14 @@ export default class PlaygroundDiagnosticsCodeActionProvider for (const diagnostic of diagnostics) { switch (diagnostic.code) { - case DIAGNOSTIC_CODES.invalidInteractiveSyntaxes: + case DiagnosticCode.invalidInteractiveSyntaxes: { const fix = new vscode.CodeAction( 'Fix this interactive syntax problem', vscode.CodeActionKind.QuickFix, ); fix.command = { - command: - EXTENSION_COMMANDS.MDB_FIX_THIS_INVALID_INTERACTIVE_SYNTAX, + command: ExtensionCommand.MDB_FIX_THIS_INVALID_INTERACTIVE_SYNTAX, title: 'Fix invalid interactive syntax', arguments: [ { @@ -60,7 +59,7 @@ export default class PlaygroundDiagnosticsCodeActionProvider const allDiagnostics = vscode.languages .getDiagnostics(document.uri) - .filter((d) => d.code === DIAGNOSTIC_CODES.invalidInteractiveSyntaxes); + .filter((d) => d.code === DiagnosticCode.invalidInteractiveSyntaxes); if (allDiagnostics.length > 1) { const fix = new vscode.CodeAction( @@ -69,7 +68,7 @@ export default class PlaygroundDiagnosticsCodeActionProvider ); fix.command = { - command: EXTENSION_COMMANDS.MDB_FIX_ALL_INVALID_INTERACTIVE_SYNTAX, + command: ExtensionCommand.MDB_FIX_ALL_INVALID_INTERACTIVE_SYNTAX, title: 'Fix invalid interactive syntax', arguments: [ { diff --git a/src/editors/playgroundSelectionCodeActionProvider.ts b/src/editors/playgroundSelectionCodeActionProvider.ts index 59361c003..abf324714 100644 --- a/src/editors/playgroundSelectionCodeActionProvider.ts +++ b/src/editors/playgroundSelectionCodeActionProvider.ts @@ -1,6 +1,6 @@ import * as vscode from 'vscode'; -import EXTENSION_COMMANDS from '../commands'; +import ExtensionCommand from '../commands'; import { isPlayground, getSelectedText } from '../utils/playground'; import { COPILOT_CHAT_EXTENSION_ID } from '../participant/constants'; @@ -47,7 +47,7 @@ export default class PlaygroundSelectionCodeActionProvider let codeActions: vscode.CodeAction[] = [ this.createCodeAction({ title: 'Run selected playground blocks', - command: EXTENSION_COMMANDS.MDB_RUN_SELECTED_PLAYGROUND_BLOCKS, + command: ExtensionCommand.MDB_RUN_SELECTED_PLAYGROUND_BLOCKS, }), ]; @@ -61,7 +61,7 @@ export default class PlaygroundSelectionCodeActionProvider ...EXPORT_TO_LANGUAGE_ALIASES.map(({ id, alias }) => this.createCodeAction({ title: `Export To ${alias}`, - command: EXTENSION_COMMANDS.MDB_EXPORT_TO_LANGUAGE, + command: ExtensionCommand.MDB_EXPORT_TO_LANGUAGE, arguments: [id], }), ), diff --git a/src/editors/queryWithCopilotCodeLensProvider.ts b/src/editors/queryWithCopilotCodeLensProvider.ts index b07eb54c3..221835d07 100644 --- a/src/editors/queryWithCopilotCodeLensProvider.ts +++ b/src/editors/queryWithCopilotCodeLensProvider.ts @@ -1,9 +1,9 @@ import * as vscode from 'vscode'; -import EXTENSION_COMMANDS from '../commands'; +import ExtensionCommand from '../commands'; import type { SendMessageToParticipantFromInputOptions } from '../participant/participantTypes'; import { isPlayground } from '../utils/playground'; import { COPILOT_EXTENSION_ID } from '../participant/constants'; -import { DOCUMENT_SOURCE } from '../documentSource'; +import { DocumentSource } from '../documentSource'; export class QueryWithCopilotCodeLensProvider implements vscode.CodeLensProvider @@ -34,7 +34,7 @@ export class QueryWithCopilotCodeLensProvider command: 'query', isNewChat: true, telemetry: { - source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_CODELENS, + source: DocumentSource.DocumentSource_CODELENS, source_details: undefined, }, }; @@ -42,7 +42,7 @@ export class QueryWithCopilotCodeLensProvider return [ new vscode.CodeLens(new vscode.Range(0, 0, 0, 0), { title: '✨ Generate query with MongoDB Copilot', - command: EXTENSION_COMMANDS.SEND_MESSAGE_TO_PARTICIPANT_FROM_INPUT, + command: ExtensionCommand.SEND_MESSAGE_TO_PARTICIPANT_FROM_INPUT, arguments: [options], }), ]; diff --git a/src/explorer/collectionTreeItem.ts b/src/explorer/collectionTreeItem.ts index 9aa088693..d87d221f3 100644 --- a/src/explorer/collectionTreeItem.ts +++ b/src/explorer/collectionTreeItem.ts @@ -3,7 +3,7 @@ import path from 'path'; import type { DataService } from 'mongodb-data-service'; import DocumentListTreeItem, { - COLLECTION_TYPES, + CollectionType, MAX_DOCUMENTS_VISIBLE, } from './documentListTreeItem'; import formatError from '../utils/formatError'; @@ -19,12 +19,12 @@ function getIconPath( const LIGHT = path.join(getImagesPath(), 'light'); const DARK = path.join(getImagesPath(), 'dark'); - if (type === COLLECTION_TYPES.timeseries) { + if (type === CollectionType.timeseries) { return { light: vscode.Uri.file(path.join(LIGHT, 'collection-timeseries.svg')), dark: vscode.Uri.file(path.join(DARK, 'collection-timeseries.svg')), }; - } else if (type === COLLECTION_TYPES.collection) { + } else if (type === CollectionType.collection) { if (isExpanded) { return { light: vscode.Uri.file(path.join(LIGHT, 'collection-folder-open.svg')), @@ -158,7 +158,7 @@ export default class CollectionTreeItem }); this.tooltip = - collection.type === COLLECTION_TYPES.view + collection.type === CollectionType.view ? 'Read only view' : collection.name; this.iconPath = getIconPath(collection.type, isExpanded); @@ -321,8 +321,8 @@ export default class CollectionTreeItem refreshDocumentCount = async (): Promise => { // Skip the count on views and time-series collections since it will error. if ( - this._type === COLLECTION_TYPES.view || - this._type === COLLECTION_TYPES.timeseries + this._type === CollectionType.view || + this._type === CollectionType.timeseries ) { this.documentCount = null; return 0; diff --git a/src/explorer/documentListTreeItem.ts b/src/explorer/documentListTreeItem.ts index f37fb0339..3d5d7b2b4 100644 --- a/src/explorer/documentListTreeItem.ts +++ b/src/explorer/documentListTreeItem.ts @@ -17,14 +17,14 @@ const log = createLogger('documents tree item'); export const MAX_DOCUMENTS_VISIBLE = 10; export const DOCUMENT_LIST_ITEM = 'documentListTreeItem'; -export const COLLECTION_TYPES = { +export const CollectionType = { collection: 'collection', view: 'view', timeseries: 'timeseries', } as const; -export type CollectionTypes = - (typeof COLLECTION_TYPES)[keyof typeof COLLECTION_TYPES]; +export type CollectionType = + (typeof CollectionType)[keyof typeof CollectionType]; const ITEM_LABEL = 'Documents'; @@ -56,7 +56,7 @@ const getCollapsableStateForDocumentList = ( isExpanded: boolean, type: string, ): vscode.TreeItemCollapsibleState => { - if (type === COLLECTION_TYPES.view) { + if (type === CollectionType.view) { return vscode.TreeItemCollapsibleState.None; } @@ -81,7 +81,7 @@ function getIconPath(): { light: vscode.Uri; dark: vscode.Uri } { } function getTooltip(type: string, documentCount: number | null): string { - const typeString = type === COLLECTION_TYPES.view ? 'View' : 'Collection'; + const typeString = type === CollectionType.view ? 'View' : 'Collection'; if (documentCount !== null) { return `${typeString} Documents - ${documentCount}`; } @@ -181,7 +181,7 @@ export default class DocumentListTreeItem } async getChildren(): Promise { - if (!this.isExpanded || this.type === COLLECTION_TYPES.view) { + if (!this.isExpanded || this.type === CollectionType.view) { return []; } diff --git a/src/explorer/explorerTreeController.ts b/src/explorer/explorerTreeController.ts index fc83ee88b..f1614bd3c 100644 --- a/src/explorer/explorerTreeController.ts +++ b/src/explorer/explorerTreeController.ts @@ -4,8 +4,8 @@ import type ConnectionController from '../connectionController'; import ConnectionTreeItem from './connectionTreeItem'; import { createLogger } from '../logging'; import { DOCUMENT_ITEM } from './documentTreeItem'; -import { DOCUMENT_LIST_ITEM, COLLECTION_TYPES } from './documentListTreeItem'; -import EXTENSION_COMMANDS from '../commands'; +import { DOCUMENT_LIST_ITEM, CollectionType } from './documentListTreeItem'; +import ExtensionCommand from '../commands'; import { sortTreeItemsByLabel } from './treeItemUtils'; import type { LoadedConnection } from '../storage/connectionStorage'; import { @@ -120,17 +120,17 @@ export default class ExplorerTreeController if (selectedItem.contextValue === DOCUMENT_ITEM) { await vscode.commands.executeCommand( - EXTENSION_COMMANDS.MDB_OPEN_MONGODB_DOCUMENT_FROM_TREE, + ExtensionCommand.MDB_OPEN_MONGODB_DOCUMENT_FROM_TREE, event.selection[0], ); } if ( selectedItem.contextValue === DOCUMENT_LIST_ITEM && - selectedItem.type === COLLECTION_TYPES.view + selectedItem.type === CollectionType.view ) { await vscode.commands.executeCommand( - EXTENSION_COMMANDS.MDB_VIEW_COLLECTION_DOCUMENTS, + ExtensionCommand.MDB_VIEW_COLLECTION_DOCUMENTS, event.selection[0], ); } diff --git a/src/explorer/fieldTreeItem.ts b/src/explorer/fieldTreeItem.ts index af73e8151..18f7fec71 100644 --- a/src/explorer/fieldTreeItem.ts +++ b/src/explorer/fieldTreeItem.ts @@ -8,7 +8,7 @@ import type TreeItemParent from './treeItemParentInterface'; // types returned by `parseSchema` with `mongodb-schema`. // We have types for elements we have special handing for (icons). // https://docs.mongodb.com/manual/reference/bson-types/ -export const FIELD_TYPES = { +export const FieldType = { array: 'Array', binary: 'Binary', bool: 'Boolean', @@ -28,7 +28,7 @@ export const FIELD_TYPES = { undefined: 'Undefined', } as const; -export type FieldType = (typeof FIELD_TYPES)[keyof typeof FIELD_TYPES]; +export type FieldType = (typeof FieldType)[keyof typeof FieldType]; export type SchemaFieldType = { name: string; @@ -44,10 +44,10 @@ export type SchemaFieldType = { export const fieldIsExpandable = (field: SchemaFieldType): boolean => { return ( field.probability === 1 && - (field.type === FIELD_TYPES.document || - field.type === FIELD_TYPES.array || - field.bsonType === FIELD_TYPES.document || - field.bsonType === FIELD_TYPES.array) + (field.type === FieldType.document || + field.type === FieldType.array || + field.bsonType === FieldType.document || + field.bsonType === FieldType.array) ); }; @@ -77,44 +77,44 @@ export const getIconFileNameForField = ( // The field has polymorphic data types. return 'mixed-type'; } - if (fieldType === FIELD_TYPES.array) { + if (fieldType === FieldType.array) { return 'array'; } - if (fieldType === FIELD_TYPES.binary) { + if (fieldType === FieldType.binary) { return 'binary'; } - if (fieldType === FIELD_TYPES.bool) { + if (fieldType === FieldType.bool) { return 'boolean'; } - if (fieldType === FIELD_TYPES.date) { + if (fieldType === FieldType.date) { return 'date'; } - if (fieldType === FIELD_TYPES.decimal) { + if (fieldType === FieldType.decimal) { return 'double'; } - if (fieldType === FIELD_TYPES.null) { + if (fieldType === FieldType.null) { return 'null'; } if ( - fieldType === FIELD_TYPES.int || - fieldType === FIELD_TYPES.long || - fieldType === FIELD_TYPES.number + fieldType === FieldType.int || + fieldType === FieldType.long || + fieldType === FieldType.number ) { return 'number'; } - if (fieldType === FIELD_TYPES.object || fieldType === FIELD_TYPES.document) { + if (fieldType === FieldType.object || fieldType === FieldType.document) { return 'object'; } - if (fieldType === FIELD_TYPES.objectId) { + if (fieldType === FieldType.objectId) { return 'object-id'; } - if (fieldType === FIELD_TYPES.regex) { + if (fieldType === FieldType.regex) { return 'regex'; } - if (fieldType === FIELD_TYPES.string) { + if (fieldType === FieldType.string) { return 'string'; } - if (fieldType === FIELD_TYPES.timestamp) { + if (fieldType === FieldType.timestamp) { return 'timestamp'; } @@ -212,13 +212,13 @@ export default class FieldTreeItem this._childrenCache = {}; if ( - this.field.bsonType === FIELD_TYPES.document || - this.field.type === FIELD_TYPES.document + this.field.bsonType === FieldType.document || + this.field.type === FieldType.document ) { let subDocumentFields; - if (this.field.type === FIELD_TYPES.document && this.field.types) { + if (this.field.type === FieldType.document && this.field.types) { subDocumentFields = this.field.types[0].fields; - } else if (this.field.bsonType === FIELD_TYPES.document) { + } else if (this.field.bsonType === FieldType.document) { subDocumentFields = this.field.fields; } @@ -241,8 +241,8 @@ export default class FieldTreeItem }); } } else if ( - (this.field.type === FIELD_TYPES.array || - this.field.bsonType === FIELD_TYPES.array) && + (this.field.type === FieldType.array || + this.field.bsonType === FieldType.array) && this.field.types ) { const arrayElement = this.field.types[0]; diff --git a/src/explorer/index.ts b/src/explorer/index.ts index 849da95a3..abef82889 100644 --- a/src/explorer/index.ts +++ b/src/explorer/index.ts @@ -2,7 +2,7 @@ import CollectionTreeItem from './collectionTreeItem'; import ExplorerController from './explorerController'; import ConnectionTreeItem from './connectionTreeItem'; import DatabaseTreeItem from './databaseTreeItem'; -import { CollectionTypes } from './documentListTreeItem'; +import { CollectionType } from './documentListTreeItem'; import DocumentTreeItem from './documentTreeItem'; import HelpExplorer from './helpExplorer'; import SchemaTreeItem from './schemaTreeItem'; @@ -11,7 +11,7 @@ import StreamProcessorTreeItem from './streamProcessorTreeItem'; export { CollectionTreeItem, - CollectionTypes, + CollectionType, ConnectionTreeItem, DatabaseTreeItem, DocumentTreeItem, diff --git a/src/explorer/indexTreeItem.ts b/src/explorer/indexTreeItem.ts index 40e50c158..f05569291 100644 --- a/src/explorer/indexTreeItem.ts +++ b/src/explorer/indexTreeItem.ts @@ -4,7 +4,7 @@ import path from 'path'; import { getImagesPath } from '../extensionConstants'; import type TreeItemParent from './treeItemParentInterface'; -export const INDEX_KEY_TYPES = { +export const IndexKeyType = { ASCENDING: 1, DESCENDING: -1, TEXT: 'text', @@ -14,8 +14,7 @@ export const INDEX_KEY_TYPES = { GEOHAYSTACK: 'geoHaystack', } as const; -export type IndexKeyType = - (typeof INDEX_KEY_TYPES)[keyof typeof INDEX_KEY_TYPES]; +export type IndexKeyType = (typeof IndexKeyType)[keyof typeof IndexKeyType]; export type IndexModel = { v: number; @@ -27,26 +26,26 @@ export type IndexModel = { }; function getIconNameForIndexKeyType(indexKeyType: IndexKeyType): string { - if (indexKeyType === INDEX_KEY_TYPES.ASCENDING) { + if (indexKeyType === IndexKeyType.ASCENDING) { return 'ascending'; } - if (indexKeyType === INDEX_KEY_TYPES.DESCENDING) { + if (indexKeyType === IndexKeyType.DESCENDING) { return 'descending'; } - if (indexKeyType === INDEX_KEY_TYPES.TEXT) { + if (indexKeyType === IndexKeyType.TEXT) { return 'text'; } - if (indexKeyType === INDEX_KEY_TYPES.HASHED) { + if (indexKeyType === IndexKeyType.HASHED) { return 'hashed'; } if ( - indexKeyType === INDEX_KEY_TYPES.GEO || - indexKeyType === INDEX_KEY_TYPES.GEOHAYSTACK || - indexKeyType === INDEX_KEY_TYPES.GEOSPHERE + indexKeyType === IndexKeyType.GEO || + indexKeyType === IndexKeyType.GEOHAYSTACK || + indexKeyType === IndexKeyType.GEOSPHERE ) { return 'geospatial'; } diff --git a/src/explorer/playgroundsTree.ts b/src/explorer/playgroundsTree.ts index 69df02ee6..dae61b3c6 100644 --- a/src/explorer/playgroundsTree.ts +++ b/src/explorer/playgroundsTree.ts @@ -3,7 +3,7 @@ import PlaygroundsTreeHeader from './playgroundsTreeHeader'; import { PLAYGROUND_ITEM } from './playgroundsTreeItem'; import { createLogger } from '../logging'; import PlaygroundsTreeItem from './playgroundsTreeItem'; -import EXTENSION_COMMANDS from '../commands'; +import ExtensionCommand from '../commands'; import { getPlaygrounds } from '../utils/playground'; const log = createLogger('playgrounds tree'); @@ -75,7 +75,7 @@ export default class PlaygroundsTree if (selectedItem.contextValue === PLAYGROUND_ITEM) { await vscode.commands.executeCommand( - EXTENSION_COMMANDS.MDB_OPEN_PLAYGROUND_FROM_TREE_VIEW, + ExtensionCommand.MDB_OPEN_PLAYGROUND_FROM_TREE_VIEW, selectedItem, ); } diff --git a/src/language/diagnosticCodes.ts b/src/language/diagnosticCodes.ts index 4166871f6..57cb759b7 100644 --- a/src/language/diagnosticCodes.ts +++ b/src/language/diagnosticCodes.ts @@ -1,8 +1,8 @@ -export const DIAGNOSTIC_CODES = { +export const DiagnosticCode = { invalidInteractiveSyntaxes: 'playground.invalidInteractiveSyntaxes', } as const; export type DiagnosticCodes = - (typeof DIAGNOSTIC_CODES)[keyof typeof DIAGNOSTIC_CODES]; + (typeof DiagnosticCode)[keyof typeof DiagnosticCode]; -export default DIAGNOSTIC_CODES; +export default DiagnosticCode; diff --git a/src/language/languageServerController.ts b/src/language/languageServerController.ts index 1b31d7f69..687b4efb7 100644 --- a/src/language/languageServerController.ts +++ b/src/language/languageServerController.ts @@ -16,7 +16,7 @@ import type { ShellEvaluateResult, } from '../types/playgroundType'; import type { ClearCompletionsCache } from '../types/completionsCache'; -import { SERVER_COMMANDS } from './serverCommands'; +import { ServerCommand } from './serverCommands'; const log = createLogger('language server controller'); @@ -111,7 +111,7 @@ export default class LanguageServerController { // If the connection to server got closed, server will restart, // but we also need to re-send default configurations // https://jira.mongodb.org/browse/VSCODE-448 - this._client.onNotification(SERVER_COMMANDS.MONGODB_SERVICE_CREATED, () => { + this._client.onNotification(ServerCommand.MONGODB_SERVICE_CREATED, () => { const msg = this._currentConnectionId ? 'MongoDBService restored from an internal error' : 'MongoDBService initialized'; @@ -123,35 +123,26 @@ export default class LanguageServerController { hasConnectionOptions: !!this._currentConnectionOptions, })}`, ); - void this._client.sendRequest( - SERVER_COMMANDS.INITIALIZE_MONGODB_SERVICE, - { - extensionPath: this._context.extensionPath, - connectionId: this._currentConnectionId, - connectionString: this._currentConnectionString, - connectionOptions: this._currentConnectionOptions, - }, - ); + void this._client.sendRequest(ServerCommand.INITIALIZE_MONGODB_SERVICE, { + extensionPath: this._context.extensionPath, + connectionId: this._currentConnectionId, + connectionString: this._currentConnectionString, + connectionOptions: this._currentConnectionOptions, + }); }); - this._client.onNotification( - SERVER_COMMANDS.SHOW_INFO_MESSAGE, - (message) => { - log.info('The info message shown to a user', message); - void vscode.window.showInformationMessage(message); - }, - ); + this._client.onNotification(ServerCommand.SHOW_INFO_MESSAGE, (message) => { + log.info('The info message shown to a user', message); + void vscode.window.showInformationMessage(message); + }); - this._client.onNotification( - SERVER_COMMANDS.SHOW_ERROR_MESSAGE, - (message) => { - log.info('The error message shown to a user', message); - void vscode.window.showErrorMessage(message); - }, - ); + this._client.onNotification(ServerCommand.SHOW_ERROR_MESSAGE, (message) => { + log.info('The error message shown to a user', message); + void vscode.window.showErrorMessage(message); + }); this._client.onNotification( - SERVER_COMMANDS.SHOW_CONSOLE_OUTPUT, + ServerCommand.SHOW_CONSOLE_OUTPUT, (outputs) => { for (const line of outputs) { this._consoleOutputChannel.appendLine( @@ -190,7 +181,7 @@ export default class LanguageServerController { // to the language server instance to execute scripts from a playground // and return results to the playground controller when ready. const res: ShellEvaluateResult = await this._client.sendRequest( - SERVER_COMMANDS.EXECUTE_CODE_FROM_PLAYGROUND, + ServerCommand.EXECUTE_CODE_FROM_PLAYGROUND, playgroundExecuteParameters, token, ); @@ -223,7 +214,7 @@ export default class LanguageServerController { this._currentConnectionOptions = connectionOptions; const res = await this._client.sendRequest( - SERVER_COMMANDS.ACTIVE_CONNECTION_CHANGED, + ServerCommand.ACTIVE_CONNECTION_CHANGED, { connectionId, connectionString, @@ -236,14 +227,14 @@ export default class LanguageServerController { async resetCache(clear: ClearCompletionsCache): Promise { log.info('Resetting MongoDBService cache...', clear); await this._client.sendRequest( - SERVER_COMMANDS.CLEAR_CACHED_COMPLETIONS, + ServerCommand.CLEAR_CACHED_COMPLETIONS, clear, ); } async updateCurrentSessionFields(params): Promise { await this._client.sendRequest( - SERVER_COMMANDS.UPDATE_CURRENT_SESSION_FIELDS, + ServerCommand.UPDATE_CURRENT_SESSION_FIELDS, params, ); } diff --git a/src/language/mongoDBService.ts b/src/language/mongoDBService.ts index 7e767c01b..161c189f1 100644 --- a/src/language/mongoDBService.ts +++ b/src/language/mongoDBService.ts @@ -25,7 +25,7 @@ import { isAtlasStream } from 'mongodb-build-info'; import { Worker as WorkerThreads } from 'worker_threads'; import formatError from '../utils/formatError'; -import { SERVER_COMMANDS } from './serverCommands'; +import { ServerCommand } from './serverCommands'; import type { ShellEvaluateResult, PlaygroundEvaluateParams, @@ -36,7 +36,7 @@ import { Visitor } from './visitor'; import type { CompletionState, NamespaceState } from './visitor'; import LINKS from '../utils/links'; -import DIAGNOSTIC_CODES from './diagnosticCodes'; +import DiagnosticCode from './diagnosticCodes'; import { getDBFromConnectionString } from '../utils/connection-string-db'; const PROJECT = '$project'; @@ -227,7 +227,7 @@ export default class MongoDBService { return new Promise((resolve) => { if (this._currentConnectionId !== params.connectionId) { void this._connection.sendNotification( - SERVER_COMMANDS.SHOW_ERROR_MESSAGE, + ServerCommand.SHOW_ERROR_MESSAGE, "The playground's active connection does not match the extension's active connection. Please reconnect and try again.", ); return resolve(null); @@ -267,11 +267,11 @@ export default class MongoDBService { ); worker?.on('message', ({ name, payload }) => { - if (name === SERVER_COMMANDS.SHOW_CONSOLE_OUTPUT) { + if (name === ServerCommand.SHOW_CONSOLE_OUTPUT) { void this._connection.sendNotification(name, payload); } - if (name === SERVER_COMMANDS.CODE_EXECUTION_RESULT) { + if (name === ServerCommand.CODE_EXECUTION_RESULT) { const { error, data } = payload as { data: ShellEvaluateResult | null; error?: any; @@ -281,7 +281,7 @@ export default class MongoDBService { `WORKER error: ${util.inspect(error)}`, ); void this._connection.sendNotification( - SERVER_COMMANDS.SHOW_ERROR_MESSAGE, + ServerCommand.SHOW_ERROR_MESSAGE, formatError(error).message, ); } @@ -292,7 +292,7 @@ export default class MongoDBService { }); worker.postMessage({ - name: SERVER_COMMANDS.EXECUTE_CODE_FROM_PLAYGROUND, + name: ServerCommand.EXECUTE_CODE_FROM_PLAYGROUND, data: { codeToEvaluate: params.codeToEvaluate, filePath: params.filePath, @@ -1163,7 +1163,7 @@ export default class MongoDBService { diagnostics.push({ severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: i, character: startCharacter }, end: { line: i, character: endCharacter }, diff --git a/src/language/server.ts b/src/language/server.ts index 2f45a22e3..78b366301 100644 --- a/src/language/server.ts +++ b/src/language/server.ts @@ -16,7 +16,7 @@ import { import { TextDocument } from 'vscode-languageserver-textdocument'; import MongoDBService from './mongoDBService'; -import { SERVER_COMMANDS } from './serverCommands'; +import { ServerCommand } from './serverCommands'; import type { PlaygroundEvaluateParams } from '../types/playgroundType'; import type { ClearCompletionsCache } from '../types/completionsCache'; @@ -78,7 +78,7 @@ connection.onInitialize((params: InitializeParams) => { connection.onInitialized(() => { void connection.sendNotification( - SERVER_COMMANDS.MONGODB_SERVICE_CREATED, + ServerCommand.MONGODB_SERVICE_CREATED, 'An instance of MongoDBService is created', ); @@ -158,25 +158,25 @@ connection.onDidChangeWatchedFiles((/* _change */) => { // Execute a playground. connection.onRequest( - SERVER_COMMANDS.EXECUTE_CODE_FROM_PLAYGROUND, + ServerCommand.EXECUTE_CODE_FROM_PLAYGROUND, (evaluateParams: PlaygroundEvaluateParams, token: CancellationToken) => { return mongoDBService.evaluate(evaluateParams, token); }, ); // Send default configurations to mongoDBService. -connection.onRequest(SERVER_COMMANDS.INITIALIZE_MONGODB_SERVICE, (settings) => { +connection.onRequest(ServerCommand.INITIALIZE_MONGODB_SERVICE, (settings) => { mongoDBService.initialize(settings); }); // Change NodeDriverServiceProvider active connection. -connection.onRequest(SERVER_COMMANDS.ACTIVE_CONNECTION_CHANGED, (params) => { +connection.onRequest(ServerCommand.ACTIVE_CONNECTION_CHANGED, (params) => { return mongoDBService.activeConnectionChanged(params); }); // Set fields for tests. connection.onRequest( - SERVER_COMMANDS.UPDATE_CURRENT_SESSION_FIELDS, + ServerCommand.UPDATE_CURRENT_SESSION_FIELDS, ({ namespace, schemaFields }) => { return mongoDBService.cacheFields(namespace, schemaFields); }, @@ -184,7 +184,7 @@ connection.onRequest( // Clear cached completions by provided cache names. connection.onRequest( - SERVER_COMMANDS.CLEAR_CACHED_COMPLETIONS, + ServerCommand.CLEAR_CACHED_COMPLETIONS, (clear: ClearCompletionsCache) => { return mongoDBService.clearCachedCompletions(clear); }, diff --git a/src/language/serverCommands.ts b/src/language/serverCommands.ts index 9f629f3e3..ecdb7153c 100644 --- a/src/language/serverCommands.ts +++ b/src/language/serverCommands.ts @@ -1,4 +1,4 @@ -export const SERVER_COMMANDS = { +export const ServerCommand = { ACTIVE_CONNECTION_CHANGED: 'ACTIVE_CONNECTION_CHANGED', EXECUTE_CODE_FROM_PLAYGROUND: 'EXECUTE_CODE_FROM_PLAYGROUND', EXECUTE_RANGE_FROM_PLAYGROUND: 'EXECUTE_RANGE_FROM_PLAYGROUND', @@ -13,8 +13,7 @@ export const SERVER_COMMANDS = { SHOW_CONSOLE_OUTPUT: 'SHOW_CONSOLE_OUTPUT', } as const; -export type ServerCommands = - (typeof SERVER_COMMANDS)[keyof typeof SERVER_COMMANDS]; +export type ServerCommands = (typeof ServerCommand)[keyof typeof ServerCommand]; export type PlaygroundRunParameters = { codeToEvaluate: string; diff --git a/src/language/worker.ts b/src/language/worker.ts index f93e935dc..5fe2dca47 100644 --- a/src/language/worker.ts +++ b/src/language/worker.ts @@ -1,7 +1,7 @@ import { NodeDriverServiceProvider } from '@mongosh/service-provider-node-driver'; import { ElectronRuntime } from '@mongosh/browser-runtime-electron'; import { parentPort } from 'worker_threads'; -import { SERVER_COMMANDS } from './serverCommands'; +import { ServerCommand } from './serverCommands'; import type { ShellEvaluateResult, @@ -44,7 +44,7 @@ type ExecuteCodeOptions = { function handleEvalPrint(values: EvaluationResult[]): void { parentPort?.postMessage({ - name: SERVER_COMMANDS.SHOW_CONSOLE_OUTPUT, + name: ServerCommand.SHOW_CONSOLE_OUTPUT, payload: values.map((v) => { return typeof v.printable === 'string' ? v.printable @@ -124,9 +124,9 @@ export const execute = async ({ }; const handleMessageFromParentPort = async ({ name, data }): Promise => { - if (name === SERVER_COMMANDS.EXECUTE_CODE_FROM_PLAYGROUND) { + if (name === ServerCommand.EXECUTE_CODE_FROM_PLAYGROUND) { parentPort?.postMessage({ - name: SERVER_COMMANDS.CODE_EXECUTION_RESULT, + name: ServerCommand.CODE_EXECUTION_RESULT, payload: await execute(data), }); } diff --git a/src/mdbExtensionController.ts b/src/mdbExtensionController.ts index f8e9c0d52..a29f411d7 100644 --- a/src/mdbExtensionController.ts +++ b/src/mdbExtensionController.ts @@ -12,7 +12,7 @@ import ConnectionController from './connectionController'; import type ConnectionTreeItem from './explorer/connectionTreeItem'; import type DatabaseTreeItem from './explorer/databaseTreeItem'; import type DocumentListTreeItem from './explorer/documentListTreeItem'; -import { DOCUMENT_SOURCE } from './documentSource'; +import { DocumentSource } from './documentSource'; import type DocumentTreeItem from './explorer/documentTreeItem'; import EditDocumentCodeLensProvider from './editors/editDocumentCodeLensProvider'; import { EditorsController, PlaygroundController } from './editors'; @@ -25,14 +25,13 @@ import { } from './explorer'; import ExportToLanguageCodeLensProvider from './editors/exportToLanguageCodeLensProvider'; import { type ExportToLanguageResult } from './types/playgroundType'; -import type { ExtensionCommand } from './commands'; import type FieldTreeItem from './explorer/fieldTreeItem'; import type IndexListTreeItem from './explorer/indexListTreeItem'; import { LanguageServerController } from './language'; import launchMongoShell from './commands/launchMongoShell'; import type SchemaTreeItem from './explorer/schemaTreeItem'; import { StatusView } from './views'; -import { StorageController, STORAGE_VARIABLES } from './storage'; +import { StorageController, StorageVariable } from './storage'; import { DeepLinkTelemetryEvent, TelemetryService } from './telemetry'; import type PlaygroundsTreeItem from './explorer/playgroundsTreeItem'; import PlaygroundResultProvider from './editors/playgroundResultProvider'; @@ -49,7 +48,7 @@ import type { SendMessageToParticipantFromInputOptions, ParticipantCommand, } from './participant/participantTypes'; -import EXTENSION_COMMANDS from './commands'; +import ExtensionCommand from './commands'; import { COPILOT_EXTENSION_ID } from './participant/constants'; import { CommandRunTelemetryEvent, @@ -62,92 +61,92 @@ import { MCPController } from './mcp/mcpController'; // Deep link command filtering: Commands are explicitly categorized as allowed or disallowed. // We use tests in mdbExtensionController.test.ts to enforce these lists being disjoint and complete. export const DEEP_LINK_ALLOWED_COMMANDS = [ - EXTENSION_COMMANDS.MDB_CONNECT, - EXTENSION_COMMANDS.MDB_CONNECT_WITH_URI, - EXTENSION_COMMANDS.MDB_OPEN_OVERVIEW_PAGE, - EXTENSION_COMMANDS.MDB_DISCONNECT, - EXTENSION_COMMANDS.OPEN_MONGODB_ISSUE_REPORTER, - EXTENSION_COMMANDS.MDB_OPEN_MDB_SHELL, - EXTENSION_COMMANDS.MDB_CREATE_PLAYGROUND, - EXTENSION_COMMANDS.MDB_RUN_SELECTED_PLAYGROUND_BLOCKS, - EXTENSION_COMMANDS.MDB_RUN_ALL_PLAYGROUND_BLOCKS, - EXTENSION_COMMANDS.MDB_RUN_ALL_OR_SELECTED_PLAYGROUND_BLOCKS, - EXTENSION_COMMANDS.MDB_EXPORT_CODE_TO_PLAYGROUND, - EXTENSION_COMMANDS.MDB_FIX_THIS_INVALID_INTERACTIVE_SYNTAX, - EXTENSION_COMMANDS.MDB_FIX_ALL_INVALID_INTERACTIVE_SYNTAX, - EXTENSION_COMMANDS.MDB_SELECT_TARGET_FOR_EXPORT_TO_LANGUAGE, - EXTENSION_COMMANDS.MDB_EXPORT_TO_LANGUAGE, - EXTENSION_COMMANDS.MDB_CHANGE_DRIVER_SYNTAX_FOR_EXPORT_TO_LANGUAGE, - EXTENSION_COMMANDS.MDB_SAVE_MONGODB_DOCUMENT, - EXTENSION_COMMANDS.MDB_CHANGE_ACTIVE_CONNECTION, - EXTENSION_COMMANDS.MDB_CODELENS_SHOW_MORE_DOCUMENTS, - EXTENSION_COMMANDS.MDB_ADD_CONNECTION, - EXTENSION_COMMANDS.MDB_ADD_CONNECTION_WITH_URI, - EXTENSION_COMMANDS.MDB_EDIT_CONNECTION, - EXTENSION_COMMANDS.MDB_REFRESH_CONNECTION, - EXTENSION_COMMANDS.MDB_COPY_CONNECTION_STRING, - EXTENSION_COMMANDS.MDB_EDIT_PRESET_CONNECTIONS, - EXTENSION_COMMANDS.MDB_RENAME_CONNECTION, - EXTENSION_COMMANDS.MDB_ADD_DATABASE, - EXTENSION_COMMANDS.MDB_SEARCH_FOR_DOCUMENTS, - EXTENSION_COMMANDS.MDB_COPY_DATABASE_NAME, - EXTENSION_COMMANDS.MDB_REFRESH_DATABASE, - EXTENSION_COMMANDS.MDB_ADD_COLLECTION, - EXTENSION_COMMANDS.MDB_COPY_COLLECTION_NAME, - EXTENSION_COMMANDS.MDB_VIEW_COLLECTION_DOCUMENTS, - EXTENSION_COMMANDS.MDB_REFRESH_COLLECTION, - EXTENSION_COMMANDS.MDB_REFRESH_DOCUMENT_LIST, - - EXTENSION_COMMANDS.MDB_REFRESH_SCHEMA, - EXTENSION_COMMANDS.MDB_COPY_SCHEMA_FIELD_NAME, - EXTENSION_COMMANDS.MDB_REFRESH_INDEXES, - EXTENSION_COMMANDS.MDB_INSERT_OBJECTID_TO_EDITOR, - EXTENSION_COMMANDS.MDB_GENERATE_OBJECTID_TO_CLIPBOARD, - - EXTENSION_COMMANDS.MDB_ADD_STREAM_PROCESSOR, - EXTENSION_COMMANDS.MDB_START_STREAM_PROCESSOR, - EXTENSION_COMMANDS.MDB_STOP_STREAM_PROCESSOR, - - EXTENSION_COMMANDS.START_MCP_SERVER, - EXTENSION_COMMANDS.STOP_MCP_SERVER, - EXTENSION_COMMANDS.GET_MCP_SERVER_CONFIG, + ExtensionCommand.MDB_CONNECT, + ExtensionCommand.MDB_CONNECT_WITH_URI, + ExtensionCommand.MDB_OPEN_OVERVIEW_PAGE, + ExtensionCommand.MDB_DISCONNECT, + ExtensionCommand.OPEN_MONGODB_ISSUE_REPORTER, + ExtensionCommand.MDB_OPEN_MDB_SHELL, + ExtensionCommand.MDB_CREATE_PLAYGROUND, + ExtensionCommand.MDB_RUN_SELECTED_PLAYGROUND_BLOCKS, + ExtensionCommand.MDB_RUN_ALL_PLAYGROUND_BLOCKS, + ExtensionCommand.MDB_RUN_ALL_OR_SELECTED_PLAYGROUND_BLOCKS, + ExtensionCommand.MDB_EXPORT_CODE_TO_PLAYGROUND, + ExtensionCommand.MDB_FIX_THIS_INVALID_INTERACTIVE_SYNTAX, + ExtensionCommand.MDB_FIX_ALL_INVALID_INTERACTIVE_SYNTAX, + ExtensionCommand.MDB_SELECT_TARGET_FOR_EXPORT_TO_LANGUAGE, + ExtensionCommand.MDB_EXPORT_TO_LANGUAGE, + ExtensionCommand.MDB_CHANGE_DRIVER_SYNTAX_FOR_EXPORT_TO_LANGUAGE, + ExtensionCommand.MDB_SAVE_MONGODB_DOCUMENT, + ExtensionCommand.MDB_CHANGE_ACTIVE_CONNECTION, + ExtensionCommand.MDB_CODELENS_SHOW_MORE_DOCUMENTS, + ExtensionCommand.MDB_ADD_CONNECTION, + ExtensionCommand.MDB_ADD_CONNECTION_WITH_URI, + ExtensionCommand.MDB_EDIT_CONNECTION, + ExtensionCommand.MDB_REFRESH_CONNECTION, + ExtensionCommand.MDB_COPY_CONNECTION_STRING, + ExtensionCommand.MDB_EDIT_PRESET_CONNECTIONS, + ExtensionCommand.MDB_RENAME_CONNECTION, + ExtensionCommand.MDB_ADD_DATABASE, + ExtensionCommand.MDB_SEARCH_FOR_DOCUMENTS, + ExtensionCommand.MDB_COPY_DATABASE_NAME, + ExtensionCommand.MDB_REFRESH_DATABASE, + ExtensionCommand.MDB_ADD_COLLECTION, + ExtensionCommand.MDB_COPY_COLLECTION_NAME, + ExtensionCommand.MDB_VIEW_COLLECTION_DOCUMENTS, + ExtensionCommand.MDB_REFRESH_COLLECTION, + ExtensionCommand.MDB_REFRESH_DOCUMENT_LIST, + + ExtensionCommand.MDB_REFRESH_SCHEMA, + ExtensionCommand.MDB_COPY_SCHEMA_FIELD_NAME, + ExtensionCommand.MDB_REFRESH_INDEXES, + ExtensionCommand.MDB_INSERT_OBJECTID_TO_EDITOR, + ExtensionCommand.MDB_GENERATE_OBJECTID_TO_CLIPBOARD, + + ExtensionCommand.MDB_ADD_STREAM_PROCESSOR, + ExtensionCommand.MDB_START_STREAM_PROCESSOR, + ExtensionCommand.MDB_STOP_STREAM_PROCESSOR, + + ExtensionCommand.START_MCP_SERVER, + ExtensionCommand.STOP_MCP_SERVER, + ExtensionCommand.GET_MCP_SERVER_CONFIG, ] as const; export const DEEP_LINK_DISALLOWED_COMMANDS = [ // Participant commands - internal APIs designed for chat UI only - EXTENSION_COMMANDS.RUN_PARTICIPANT_CODE, - EXTENSION_COMMANDS.OPEN_PARTICIPANT_CODE_IN_PLAYGROUND, - EXTENSION_COMMANDS.CONNECT_WITH_PARTICIPANT, - EXTENSION_COMMANDS.SELECT_DATABASE_WITH_PARTICIPANT, - EXTENSION_COMMANDS.SELECT_COLLECTION_WITH_PARTICIPANT, - EXTENSION_COMMANDS.PARTICIPANT_OPEN_RAW_SCHEMA_OUTPUT, - EXTENSION_COMMANDS.SEND_MESSAGE_TO_PARTICIPANT, - EXTENSION_COMMANDS.SEND_MESSAGE_TO_PARTICIPANT_FROM_INPUT, - EXTENSION_COMMANDS.SHOW_EXPORT_TO_LANGUAGE_RESULT, + ExtensionCommand.RUN_PARTICIPANT_CODE, + ExtensionCommand.OPEN_PARTICIPANT_CODE_IN_PLAYGROUND, + ExtensionCommand.CONNECT_WITH_PARTICIPANT, + ExtensionCommand.SELECT_DATABASE_WITH_PARTICIPANT, + ExtensionCommand.SELECT_COLLECTION_WITH_PARTICIPANT, + ExtensionCommand.PARTICIPANT_OPEN_RAW_SCHEMA_OUTPUT, + ExtensionCommand.SEND_MESSAGE_TO_PARTICIPANT, + ExtensionCommand.SEND_MESSAGE_TO_PARTICIPANT_FROM_INPUT, + ExtensionCommand.SHOW_EXPORT_TO_LANGUAGE_RESULT, // Destructive operations - EXTENSION_COMMANDS.MDB_DROP_DATABASE, - EXTENSION_COMMANDS.MDB_DROP_COLLECTION, - EXTENSION_COMMANDS.MDB_DROP_STREAM_PROCESSOR, - EXTENSION_COMMANDS.MDB_REMOVE_CONNECTION, + ExtensionCommand.MDB_DROP_DATABASE, + ExtensionCommand.MDB_DROP_COLLECTION, + ExtensionCommand.MDB_DROP_STREAM_PROCESSOR, + ExtensionCommand.MDB_REMOVE_CONNECTION, // Location-specific items - not intended to be accessed in other ways - EXTENSION_COMMANDS.MDB_DELETE_DOCUMENT_FROM_TREE_VIEW, - EXTENSION_COMMANDS.MDB_REMOVE_CONNECTION_TREE_VIEW, - EXTENSION_COMMANDS.MDB_OPEN_MDB_SHELL_FROM_TREE_VIEW, - EXTENSION_COMMANDS.MDB_REFRESH_PLAYGROUNDS_FROM_TREE_VIEW, - EXTENSION_COMMANDS.MDB_OPEN_PLAYGROUND_FROM_TREE_VIEW, - EXTENSION_COMMANDS.MDB_CONNECT_TO_CONNECTION_TREE_VIEW, - EXTENSION_COMMANDS.MDB_CREATE_PLAYGROUND_FROM_TREE_VIEW, - EXTENSION_COMMANDS.MDB_CREATE_PLAYGROUND_FROM_TREE_ITEM, - EXTENSION_COMMANDS.MDB_DISCONNECT_FROM_CONNECTION_TREE_VIEW, - EXTENSION_COMMANDS.MDB_OPEN_MONGODB_DOCUMENT_FROM_TREE, - EXTENSION_COMMANDS.MDB_INSERT_DOCUMENT_FROM_TREE_VIEW, - EXTENSION_COMMANDS.MDB_COPY_DOCUMENT_CONTENTS_FROM_TREE_VIEW, - EXTENSION_COMMANDS.MDB_CLONE_DOCUMENT_FROM_TREE_VIEW, - EXTENSION_COMMANDS.ASK_COPILOT_FROM_TREE_ITEM, - EXTENSION_COMMANDS.MDB_CREATE_INDEX_TREE_VIEW, - EXTENSION_COMMANDS.MDB_OPEN_MONGODB_DOCUMENT_FROM_CODE_LENS, - EXTENSION_COMMANDS.MDB_CREATE_PLAYGROUND_FROM_OVERVIEW_PAGE, + ExtensionCommand.MDB_DELETE_DOCUMENT_FROM_TREE_VIEW, + ExtensionCommand.MDB_REMOVE_CONNECTION_TREE_VIEW, + ExtensionCommand.MDB_OPEN_MDB_SHELL_FROM_TREE_VIEW, + ExtensionCommand.MDB_REFRESH_PLAYGROUNDS_FROM_TREE_VIEW, + ExtensionCommand.MDB_OPEN_PLAYGROUND_FROM_TREE_VIEW, + ExtensionCommand.MDB_CONNECT_TO_CONNECTION_TREE_VIEW, + ExtensionCommand.MDB_CREATE_PLAYGROUND_FROM_TREE_VIEW, + ExtensionCommand.MDB_CREATE_PLAYGROUND_FROM_TREE_ITEM, + ExtensionCommand.MDB_DISCONNECT_FROM_CONNECTION_TREE_VIEW, + ExtensionCommand.MDB_OPEN_MONGODB_DOCUMENT_FROM_TREE, + ExtensionCommand.MDB_INSERT_DOCUMENT_FROM_TREE_VIEW, + ExtensionCommand.MDB_COPY_DOCUMENT_CONTENTS_FROM_TREE_VIEW, + ExtensionCommand.MDB_CLONE_DOCUMENT_FROM_TREE_VIEW, + ExtensionCommand.ASK_COPILOT_FROM_TREE_ITEM, + ExtensionCommand.MDB_CREATE_INDEX_TREE_VIEW, + ExtensionCommand.MDB_OPEN_MONGODB_DOCUMENT_FROM_CODE_LENS, + ExtensionCommand.MDB_CREATE_PLAYGROUND_FROM_OVERVIEW_PAGE, ] as const; // This class is the top-level controller for our extension. @@ -340,7 +339,7 @@ export default class MDBExtensionController implements vscode.Disposable { try { if ( - !Object.values(EXTENSION_COMMANDS).includes(command as ExtensionCommand) + !Object.values(ExtensionCommand).includes(command as ExtensionCommand) ) { throw new Error( `Unable to execute command '${command}' since it is not registered by the MongoDB extension.`, @@ -369,29 +368,29 @@ export default class MDBExtensionController implements vscode.Disposable { // Register our extension's commands. These are the event handlers and // control the functionality of our extension. // ------ CONNECTION ------ // - this.registerCommand(EXTENSION_COMMANDS.MDB_OPEN_OVERVIEW_PAGE, () => { + this.registerCommand(ExtensionCommand.MDB_OPEN_OVERVIEW_PAGE, () => { this._webviewController.openWebview(this._context); return Promise.resolve(true); }); - this.registerCommand(EXTENSION_COMMANDS.MDB_CONNECT, () => { + this.registerCommand(ExtensionCommand.MDB_CONNECT, () => { this._webviewController.openWebview(this._context); return Promise.resolve(true); }); - this.registerCommand(EXTENSION_COMMANDS.MDB_CONNECT_WITH_URI, (params) => { + this.registerCommand(ExtensionCommand.MDB_CONNECT_WITH_URI, (params) => { return this._connectionController.connectWithURI(params); }); - this.registerCommand(EXTENSION_COMMANDS.MDB_DISCONNECT, () => + this.registerCommand(ExtensionCommand.MDB_DISCONNECT, () => this._connectionController.disconnect(), ); - this.registerCommand(EXTENSION_COMMANDS.MDB_REMOVE_CONNECTION, (params) => + this.registerCommand(ExtensionCommand.MDB_REMOVE_CONNECTION, (params) => this._connectionController.onRemoveMongoDBConnection(params), ); - this.registerCommand(EXTENSION_COMMANDS.MDB_CHANGE_ACTIVE_CONNECTION, () => + this.registerCommand(ExtensionCommand.MDB_CHANGE_ACTIVE_CONNECTION, () => this._connectionController.changeActiveConnection(), ); this.registerCommand( - EXTENSION_COMMANDS.OPEN_MONGODB_ISSUE_REPORTER, + ExtensionCommand.OPEN_MONGODB_ISSUE_REPORTER, async () => { return await vscode.commands.executeCommand( 'workbench.action.openIssueReporter', @@ -404,67 +403,67 @@ export default class MDBExtensionController implements vscode.Disposable { ); // ------ SHELL ------ // - this.registerCommand(EXTENSION_COMMANDS.MDB_OPEN_MDB_SHELL, () => + this.registerCommand(ExtensionCommand.MDB_OPEN_MDB_SHELL, () => launchMongoShell(this._connectionController), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_OPEN_MDB_SHELL_FROM_TREE_VIEW, + ExtensionCommand.MDB_OPEN_MDB_SHELL_FROM_TREE_VIEW, () => launchMongoShell(this._connectionController), ); // ------ PLAYGROUND ------ // - this.registerCommand(EXTENSION_COMMANDS.MDB_CREATE_PLAYGROUND, () => + this.registerCommand(ExtensionCommand.MDB_CREATE_PLAYGROUND, () => this._playgroundController.createPlayground(), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_CREATE_PLAYGROUND_FROM_OVERVIEW_PAGE, + ExtensionCommand.MDB_CREATE_PLAYGROUND_FROM_OVERVIEW_PAGE, () => this._playgroundController.createPlayground(), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_RUN_SELECTED_PLAYGROUND_BLOCKS, + ExtensionCommand.MDB_RUN_SELECTED_PLAYGROUND_BLOCKS, () => this._playgroundController.runSelectedPlaygroundBlocks(), ); - this.registerCommand(EXTENSION_COMMANDS.MDB_RUN_ALL_PLAYGROUND_BLOCKS, () => + this.registerCommand(ExtensionCommand.MDB_RUN_ALL_PLAYGROUND_BLOCKS, () => this._playgroundController.runAllPlaygroundBlocks(), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_RUN_ALL_OR_SELECTED_PLAYGROUND_BLOCKS, + ExtensionCommand.MDB_RUN_ALL_OR_SELECTED_PLAYGROUND_BLOCKS, () => this._playgroundController.runAllOrSelectedPlaygroundBlocks(), ); - this.registerCommand(EXTENSION_COMMANDS.MDB_EXPORT_CODE_TO_PLAYGROUND, () => + this.registerCommand(ExtensionCommand.MDB_EXPORT_CODE_TO_PLAYGROUND, () => this._participantController.exportCodeToPlayground(), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_FIX_THIS_INVALID_INTERACTIVE_SYNTAX, + ExtensionCommand.MDB_FIX_THIS_INVALID_INTERACTIVE_SYNTAX, (data) => this._playgroundController.fixThisInvalidInteractiveSyntax(data), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_FIX_ALL_INVALID_INTERACTIVE_SYNTAX, + ExtensionCommand.MDB_FIX_ALL_INVALID_INTERACTIVE_SYNTAX, (data) => this._playgroundController.fixAllInvalidInteractiveSyntax(data), ); // ------ EXPORT TO LANGUAGE ------ // this.registerCommand( - EXTENSION_COMMANDS.MDB_SELECT_TARGET_FOR_EXPORT_TO_LANGUAGE, + ExtensionCommand.MDB_SELECT_TARGET_FOR_EXPORT_TO_LANGUAGE, () => this._participantController.selectTargetForExportToLanguage(), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_EXPORT_TO_LANGUAGE, + ExtensionCommand.MDB_EXPORT_TO_LANGUAGE, (language: string) => this._participantController.exportPlaygroundToLanguage(language), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_CHANGE_DRIVER_SYNTAX_FOR_EXPORT_TO_LANGUAGE, + ExtensionCommand.MDB_CHANGE_DRIVER_SYNTAX_FOR_EXPORT_TO_LANGUAGE, (includeDriverSyntax: boolean) => this._participantController.changeDriverSyntaxForExportToLanguage( includeDriverSyntax, ), ); this.registerParticipantCommand( - EXTENSION_COMMANDS.SHOW_EXPORT_TO_LANGUAGE_RESULT, + ExtensionCommand.SHOW_EXPORT_TO_LANGUAGE_RESULT, (data: ExportToLanguageResult) => { return this._playgroundController.showExportToLanguageResult(data); }, @@ -472,7 +471,7 @@ export default class MDBExtensionController implements vscode.Disposable { // ------ DOCUMENTS ------ // this.registerCommand( - EXTENSION_COMMANDS.MDB_OPEN_MONGODB_DOCUMENT_FROM_CODE_LENS, + ExtensionCommand.MDB_OPEN_MONGODB_DOCUMENT_FROM_CODE_LENS, (data: EditDocumentInfo) => { this._telemetryService.track( new DocumentEditedTelemetryEvent(data.source), @@ -481,7 +480,7 @@ export default class MDBExtensionController implements vscode.Disposable { return this._editorsController.openMongoDBDocument(data); }, ); - this.registerCommand(EXTENSION_COMMANDS.MDB_SAVE_MONGODB_DOCUMENT, () => + this.registerCommand(ExtensionCommand.MDB_SAVE_MONGODB_DOCUMENT, () => this._editorsController.saveMongoDBDocument(), ); @@ -490,7 +489,7 @@ export default class MDBExtensionController implements vscode.Disposable { // ------ CHAT PARTICIPANT ------ // this.registerParticipantCommand( - EXTENSION_COMMANDS.OPEN_PARTICIPANT_CODE_IN_PLAYGROUND, + ExtensionCommand.OPEN_PARTICIPANT_CODE_IN_PLAYGROUND, ({ runnableContent }: RunParticipantCodeCommandArgs) => { return this._playgroundController.createPlaygroundFromParticipantCode({ text: runnableContent, @@ -498,14 +497,14 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerParticipantCommand( - EXTENSION_COMMANDS.SEND_MESSAGE_TO_PARTICIPANT, + ExtensionCommand.SEND_MESSAGE_TO_PARTICIPANT, async (options: SendMessageToParticipantOptions) => { await this._participantController.sendMessageToParticipant(options); return true; }, ); this.registerParticipantCommand( - EXTENSION_COMMANDS.SEND_MESSAGE_TO_PARTICIPANT_FROM_INPUT, + ExtensionCommand.SEND_MESSAGE_TO_PARTICIPANT_FROM_INPUT, async (options: SendMessageToParticipantFromInputOptions) => { await this._participantController.sendMessageToParticipantFromInput( options, @@ -514,14 +513,14 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerParticipantCommand( - EXTENSION_COMMANDS.ASK_COPILOT_FROM_TREE_ITEM, + ExtensionCommand.ASK_COPILOT_FROM_TREE_ITEM, async (treeItem: DatabaseTreeItem | CollectionTreeItem) => { await this._participantController.askCopilotFromTreeItem(treeItem); return true; }, ); this.registerParticipantCommand( - EXTENSION_COMMANDS.RUN_PARTICIPANT_CODE, + ExtensionCommand.RUN_PARTICIPANT_CODE, ({ runnableContent }: RunParticipantCodeCommandArgs) => { return this._playgroundController.evaluateParticipantCode( runnableContent, @@ -529,13 +528,13 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.CONNECT_WITH_PARTICIPANT, + ExtensionCommand.CONNECT_WITH_PARTICIPANT, (data: { id?: string; command?: string }) => { return this._participantController.connectWithParticipant(data); }, ); this.registerCommand( - EXTENSION_COMMANDS.SELECT_DATABASE_WITH_PARTICIPANT, + ExtensionCommand.SELECT_DATABASE_WITH_PARTICIPANT, (data: { chatId: string; command: ParticipantCommand; @@ -545,7 +544,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.SELECT_COLLECTION_WITH_PARTICIPANT, + ExtensionCommand.SELECT_COLLECTION_WITH_PARTICIPANT, (data: any) => { return this._participantController.selectCollectionWithParticipant( data, @@ -553,7 +552,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.PARTICIPANT_OPEN_RAW_SCHEMA_OUTPUT, + ExtensionCommand.PARTICIPANT_OPEN_RAW_SCHEMA_OUTPUT, async ({ schema }: OpenSchemaCommandArgs) => { const document = await vscode.workspace.openTextDocument({ language: 'json', @@ -601,7 +600,7 @@ export default class MDBExtensionController implements vscode.Disposable { registerEditorCommands(): void { this.registerCommand( - EXTENSION_COMMANDS.MDB_CODELENS_SHOW_MORE_DOCUMENTS, + ExtensionCommand.MDB_CODELENS_SHOW_MORE_DOCUMENTS, ({ operationId, connectionId, namespace }) => { return this._editorsController.onViewMoreCollectionDocuments( operationId, @@ -613,15 +612,15 @@ export default class MDBExtensionController implements vscode.Disposable { } registerTreeViewCommands(): void { - this.registerCommand(EXTENSION_COMMANDS.MDB_ADD_CONNECTION, () => { + this.registerCommand(ExtensionCommand.MDB_ADD_CONNECTION, () => { this._webviewController.openWebview(this._context); return Promise.resolve(true); }); - this.registerCommand(EXTENSION_COMMANDS.MDB_ADD_CONNECTION_WITH_URI, () => + this.registerCommand(ExtensionCommand.MDB_ADD_CONNECTION_WITH_URI, () => this._connectionController.connectWithURI(), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_CONNECT_TO_CONNECTION_TREE_VIEW, + ExtensionCommand.MDB_CONNECT_TO_CONNECTION_TREE_VIEW, async (connectionTreeItem: ConnectionTreeItem) => { const { successfullyConnected } = await this._connectionController.connectWithConnectionId( @@ -631,7 +630,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_DISCONNECT_FROM_CONNECTION_TREE_VIEW, + ExtensionCommand.MDB_DISCONNECT_FROM_CONNECTION_TREE_VIEW, () => { // In order for this command to be activated, the connection must // be the active connection, so we can just generally disconnect. @@ -639,7 +638,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_REFRESH_CONNECTION, + ExtensionCommand.MDB_REFRESH_CONNECTION, async (connectionTreeItem: ConnectionTreeItem): Promise => { connectionTreeItem.resetCache(); this._explorerController.refresh(); @@ -654,14 +653,14 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_EDIT_PRESET_CONNECTIONS, + ExtensionCommand.MDB_EDIT_PRESET_CONNECTIONS, async (element: ConnectionTreeItem | undefined) => { await this._connectionController.openPresetConnectionsSettings(element); return true; }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_COPY_CONNECTION_STRING, + ExtensionCommand.MDB_COPY_CONNECTION_STRING, async (element: ConnectionTreeItem): Promise => { const connectionString = this._connectionController.copyConnectionStringByConnectionId( @@ -675,14 +674,14 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_REMOVE_CONNECTION_TREE_VIEW, + ExtensionCommand.MDB_REMOVE_CONNECTION_TREE_VIEW, (element: ConnectionTreeItem) => this._connectionController.onRemoveMongoDBConnection({ id: element.connectionId, }), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_EDIT_CONNECTION, + ExtensionCommand.MDB_EDIT_CONNECTION, (element: ConnectionTreeItem) => { const connectionOptions = this._connectionController.getConnectionConnectionOptions( @@ -707,12 +706,12 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_RENAME_CONNECTION, + ExtensionCommand.MDB_RENAME_CONNECTION, (element: ConnectionTreeItem) => this._connectionController.renameConnection(element.connectionId), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_ADD_DATABASE, + ExtensionCommand.MDB_ADD_DATABASE, async (element: ConnectionTreeItem): Promise => { if (!element) { void vscode.window.showErrorMessage( @@ -755,7 +754,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_COPY_DATABASE_NAME, + ExtensionCommand.MDB_COPY_DATABASE_NAME, async (element: DatabaseTreeItem) => { await vscode.env.clipboard.writeText(element.databaseName); void vscode.window.showInformationMessage('Copied to clipboard.'); @@ -764,7 +763,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_DROP_DATABASE, + ExtensionCommand.MDB_DROP_DATABASE, async (element: DatabaseTreeItem): Promise => { const successfullyDroppedDatabase = await element.onDropDatabaseClicked(); @@ -783,7 +782,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_REFRESH_DATABASE, + ExtensionCommand.MDB_REFRESH_DATABASE, async (databaseTreeItem: DatabaseTreeItem): Promise => { databaseTreeItem.resetCache(); this._explorerController.refresh(); @@ -796,7 +795,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_ADD_COLLECTION, + ExtensionCommand.MDB_ADD_COLLECTION, async (element: DatabaseTreeItem): Promise => { if (this._connectionController.isDisconnecting()) { void vscode.window.showErrorMessage( @@ -812,7 +811,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_COPY_COLLECTION_NAME, + ExtensionCommand.MDB_COPY_COLLECTION_NAME, async (element: CollectionTreeItem): Promise => { await vscode.env.clipboard.writeText(element.collectionName); void vscode.window.showInformationMessage('Copied to clipboard.'); @@ -821,7 +820,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_DROP_COLLECTION, + ExtensionCommand.MDB_DROP_COLLECTION, async (element: CollectionTreeItem): Promise => { const successfullyDroppedCollection = await element.onDropCollectionClicked(); @@ -840,7 +839,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_VIEW_COLLECTION_DOCUMENTS, + ExtensionCommand.MDB_VIEW_COLLECTION_DOCUMENTS, ( element: CollectionTreeItem | DocumentListTreeItem, ): Promise => { @@ -850,7 +849,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_REFRESH_COLLECTION, + ExtensionCommand.MDB_REFRESH_COLLECTION, async (collectionTreeItem: CollectionTreeItem): Promise => { collectionTreeItem.resetCache(); this._explorerController.refresh(); @@ -860,7 +859,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_SEARCH_FOR_DOCUMENTS, + ExtensionCommand.MDB_SEARCH_FOR_DOCUMENTS, (element: DocumentListTreeItem): Promise => this._playgroundController.createPlaygroundForSearch( element.databaseName, @@ -868,10 +867,10 @@ export default class MDBExtensionController implements vscode.Disposable { ), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_OPEN_MONGODB_DOCUMENT_FROM_TREE, + ExtensionCommand.MDB_OPEN_MONGODB_DOCUMENT_FROM_TREE, (element: DocumentTreeItem): Promise => { return this._editorsController.openMongoDBDocument({ - source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW, + source: DocumentSource.DocumentSource_TREEVIEW, documentId: element.documentId, namespace: element.namespace, connectionId: this._connectionController.getActiveConnectionId(), @@ -880,7 +879,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_REFRESH_DOCUMENT_LIST, + ExtensionCommand.MDB_REFRESH_DOCUMENT_LIST, async (documentsListTreeItem: DocumentListTreeItem): Promise => { await documentsListTreeItem.resetCache(); this._explorerController.refresh(); @@ -890,7 +889,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_INSERT_DOCUMENT_FROM_TREE_VIEW, + ExtensionCommand.MDB_INSERT_DOCUMENT_FROM_TREE_VIEW, async ( documentsListTreeItem: DocumentListTreeItem | CollectionTreeItem, ): Promise => { @@ -901,7 +900,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_REFRESH_SCHEMA, + ExtensionCommand.MDB_REFRESH_SCHEMA, async (schemaTreeItem: SchemaTreeItem): Promise => { schemaTreeItem.resetCache(); this._explorerController.refresh(); @@ -911,7 +910,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_COPY_SCHEMA_FIELD_NAME, + ExtensionCommand.MDB_COPY_SCHEMA_FIELD_NAME, async (fieldTreeItem: FieldTreeItem): Promise => { await vscode.env.clipboard.writeText(fieldTreeItem.getFieldName()); void vscode.window.showInformationMessage('Copied to clipboard.'); @@ -920,7 +919,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_REFRESH_INDEXES, + ExtensionCommand.MDB_REFRESH_INDEXES, (indexListTreeItem: IndexListTreeItem): Promise => { indexListTreeItem.resetCache(); this._explorerController.refresh(); @@ -929,7 +928,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_CREATE_INDEX_TREE_VIEW, + ExtensionCommand.MDB_CREATE_INDEX_TREE_VIEW, (indexListTreeItem: IndexListTreeItem): Promise => { return this._playgroundController.createPlaygroundForNewIndex( indexListTreeItem.databaseName, @@ -938,25 +937,25 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_CREATE_PLAYGROUND_FROM_TREE_VIEW, + ExtensionCommand.MDB_CREATE_PLAYGROUND_FROM_TREE_VIEW, () => this._playgroundController.createPlayground(), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_CREATE_PLAYGROUND_FROM_TREE_ITEM, + ExtensionCommand.MDB_CREATE_PLAYGROUND_FROM_TREE_ITEM, (treeItem: DatabaseTreeItem | CollectionTreeItem) => this._playgroundController.createPlaygroundFromTreeItem(treeItem), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_REFRESH_PLAYGROUNDS_FROM_TREE_VIEW, + ExtensionCommand.MDB_REFRESH_PLAYGROUNDS_FROM_TREE_VIEW, () => this._playgroundsExplorer.refresh(), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_OPEN_PLAYGROUND_FROM_TREE_VIEW, + ExtensionCommand.MDB_OPEN_PLAYGROUND_FROM_TREE_VIEW, (playgroundsTreeItem: PlaygroundsTreeItem) => this._playgroundController.openPlayground(playgroundsTreeItem.filePath), ); this.registerCommand( - EXTENSION_COMMANDS.MDB_COPY_DOCUMENT_CONTENTS_FROM_TREE_VIEW, + ExtensionCommand.MDB_COPY_DOCUMENT_CONTENTS_FROM_TREE_VIEW, async (documentTreeItem: DocumentTreeItem): Promise => { const documentContents = await documentTreeItem.getStringifiedEJSONDocumentContents(); @@ -967,7 +966,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_CLONE_DOCUMENT_FROM_TREE_VIEW, + ExtensionCommand.MDB_CLONE_DOCUMENT_FROM_TREE_VIEW, async (documentTreeItem: DocumentTreeItem): Promise => { const documentContents = await documentTreeItem.getJSStringDocumentContents(); @@ -983,7 +982,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_DELETE_DOCUMENT_FROM_TREE_VIEW, + ExtensionCommand.MDB_DELETE_DOCUMENT_FROM_TREE_VIEW, async (documentTreeItem: DocumentTreeItem): Promise => { const successfullyDropped = await documentTreeItem.onDeleteDocumentClicked(); @@ -1002,7 +1001,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_INSERT_OBJECTID_TO_EDITOR, + ExtensionCommand.MDB_INSERT_OBJECTID_TO_EDITOR, async (): Promise => { const editor = vscode.window.activeTextEditor; @@ -1026,7 +1025,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_GENERATE_OBJECTID_TO_CLIPBOARD, + ExtensionCommand.MDB_GENERATE_OBJECTID_TO_CLIPBOARD, async (): Promise => { await vscode.env.clipboard.writeText(generateId().toHexString()); void vscode.window.showInformationMessage('Copied to clipboard.'); @@ -1037,7 +1036,7 @@ export default class MDBExtensionController implements vscode.Disposable { this.registerAtlasStreamsTreeViewCommands(); this.registerCommand( - EXTENSION_COMMANDS.START_MCP_SERVER, + ExtensionCommand.START_MCP_SERVER, async (): Promise => { await this._mcpController.startServer(); return true; @@ -1045,7 +1044,7 @@ export default class MDBExtensionController implements vscode.Disposable { ); this.registerCommand( - EXTENSION_COMMANDS.STOP_MCP_SERVER, + ExtensionCommand.STOP_MCP_SERVER, async (): Promise => { await this._mcpController.stopServer(); return true; @@ -1053,7 +1052,7 @@ export default class MDBExtensionController implements vscode.Disposable { ); this.registerCommand( - EXTENSION_COMMANDS.GET_MCP_SERVER_CONFIG, + ExtensionCommand.GET_MCP_SERVER_CONFIG, (): Promise => { return this._mcpController.openServerConfig(); }, @@ -1062,7 +1061,7 @@ export default class MDBExtensionController implements vscode.Disposable { registerAtlasStreamsTreeViewCommands(): void { this.registerCommand( - EXTENSION_COMMANDS.MDB_ADD_STREAM_PROCESSOR, + ExtensionCommand.MDB_ADD_STREAM_PROCESSOR, async (element: ConnectionTreeItem): Promise => { if (!element) { void vscode.window.showErrorMessage( @@ -1105,7 +1104,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_START_STREAM_PROCESSOR, + ExtensionCommand.MDB_START_STREAM_PROCESSOR, async (element: StreamProcessorTreeItem): Promise => { const started = await element.onStartClicked(); if (started) { @@ -1119,7 +1118,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_STOP_STREAM_PROCESSOR, + ExtensionCommand.MDB_STOP_STREAM_PROCESSOR, async (element: StreamProcessorTreeItem): Promise => { const stopped = await element.onStopClicked(); if (stopped) { @@ -1133,7 +1132,7 @@ export default class MDBExtensionController implements vscode.Disposable { }, ); this.registerCommand( - EXTENSION_COMMANDS.MDB_DROP_STREAM_PROCESSOR, + ExtensionCommand.MDB_DROP_STREAM_PROCESSOR, async (element: StreamProcessorTreeItem): Promise => { const dropped = await element.onDropClicked(); if (dropped) { @@ -1159,7 +1158,7 @@ export default class MDBExtensionController implements vscode.Disposable { } const hasBeenShownViewAlready = !!this._storageController.get( - STORAGE_VARIABLES.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, + StorageVariable.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, ); if (hasBeenShownViewAlready) { @@ -1170,12 +1169,12 @@ export default class MDBExtensionController implements vscode.Disposable { if (!this._connectionStorage.hasSavedConnections()) { // Only show the overview page if there are no saved connections. void vscode.commands.executeCommand( - EXTENSION_COMMANDS.MDB_OPEN_OVERVIEW_PAGE, + ExtensionCommand.MDB_OPEN_OVERVIEW_PAGE, ); } void this._storageController.update( - STORAGE_VARIABLES.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, + StorageVariable.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, true, ); } diff --git a/src/participant/participant.ts b/src/participant/participant.ts index 04181140d..e59d018aa 100644 --- a/src/participant/participant.ts +++ b/src/participant/participant.ts @@ -7,9 +7,9 @@ import util from 'util'; import { createLogger } from '../logging'; import type ConnectionController from '../connectionController'; import type { LoadedConnection } from '../storage/connectionStorage'; -import EXTENSION_COMMANDS from '../commands'; +import ExtensionCommand from '../commands'; import type { StorageController } from '../storage'; -import { STORAGE_VARIABLES } from '../storage'; +import { StorageVariable } from '../storage'; import { getContentLength, Prompts } from './prompts'; import type { ChatResult } from './constants'; import { @@ -54,7 +54,7 @@ import type { PromptIntent } from './prompts/intent'; import { isPlayground, getSelectedText, getAllText } from '../utils/playground'; import type { DataService } from 'mongodb-data-service'; import { - PARTICIPANT_ERROR_TYPES, + ParticipantErrorType, type ExportToPlaygroundError, } from './participantErrorTypes'; import type PlaygroundResultProvider from '../editors/playgroundResultProvider'; @@ -69,7 +69,7 @@ import type { import { DEFAULT_EXPORT_TO_LANGUAGE_DRIVER_SYNTAX } from '../editors/exportToLanguageCodeLensProvider'; import { EXPORT_TO_LANGUAGE_ALIASES } from '../editors/playgroundSelectionCodeActionProvider'; import { CollectionTreeItem, DatabaseTreeItem } from '../explorer'; -import { DOCUMENT_SOURCE } from '../documentSource'; +import { DocumentSource } from '../documentSource'; const log = createLogger('participant'); @@ -241,7 +241,7 @@ export default class ParticipantController { message: `I want to ask questions about the \`${databaseName}\` database.`, isNewChat: true, telemetry: { - source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW, + source: DocumentSource.DocumentSource_TREEVIEW, source_details: 'database', }, }); @@ -252,7 +252,7 @@ export default class ParticipantController { message: `I want to ask questions about the \`${databaseName}\` database's \`${collectionName}\` collection.`, isNewChat: true, telemetry: { - source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW, + source: DocumentSource.DocumentSource_TREEVIEW, source_details: 'collection', }, }); @@ -340,12 +340,12 @@ export default class ParticipantController { runnableContent, }; stream.button({ - command: EXTENSION_COMMANDS.RUN_PARTICIPANT_CODE, + command: ExtensionCommand.RUN_PARTICIPANT_CODE, title: vscode.l10n.t('▶️ Run'), arguments: [commandArgs], }); stream.button({ - command: EXTENSION_COMMANDS.OPEN_PARTICIPANT_CODE_IN_PLAYGROUND, + command: ExtensionCommand.OPEN_PARTICIPANT_CODE_IN_PLAYGROUND, title: vscode.l10n.t('Open in playground'), arguments: [commandArgs], }); @@ -615,7 +615,7 @@ export default class ParticipantController { .slice(0, MAX_MARKDOWN_LIST_LENGTH) .map((conn: LoadedConnection) => createMarkdownLink({ - commandId: EXTENSION_COMMANDS.CONNECT_WITH_PARTICIPANT, + commandId: ExtensionCommand.CONNECT_WITH_PARTICIPANT, data: { id: conn.id, command, @@ -624,7 +624,7 @@ export default class ParticipantController { }), ), createMarkdownLink({ - commandId: EXTENSION_COMMANDS.CONNECT_WITH_PARTICIPANT, + commandId: ExtensionCommand.CONNECT_WITH_PARTICIPANT, name: 'Show more', data: { command, @@ -785,7 +785,7 @@ export default class ParticipantController { databases.slice(0, MAX_MARKDOWN_LIST_LENGTH).forEach((db) => stream.markdown( createMarkdownLink({ - commandId: EXTENSION_COMMANDS.SELECT_DATABASE_WITH_PARTICIPANT, + commandId: ExtensionCommand.SELECT_DATABASE_WITH_PARTICIPANT, data: { command, chatId: ChatMetadataStore.getChatIdFromHistoryOrNewChatId( @@ -807,7 +807,7 @@ export default class ParticipantController { context.history, ), }, - commandId: EXTENSION_COMMANDS.SELECT_DATABASE_WITH_PARTICIPANT, + commandId: ExtensionCommand.SELECT_DATABASE_WITH_PARTICIPANT, name: 'Show more', }), ); @@ -830,7 +830,7 @@ export default class ParticipantController { collections.slice(0, MAX_MARKDOWN_LIST_LENGTH).forEach((coll) => stream.markdown( createMarkdownLink({ - commandId: EXTENSION_COMMANDS.SELECT_COLLECTION_WITH_PARTICIPANT, + commandId: ExtensionCommand.SELECT_COLLECTION_WITH_PARTICIPANT, data: { command, chatId: ChatMetadataStore.getChatIdFromHistoryOrNewChatId( @@ -846,7 +846,7 @@ export default class ParticipantController { if (collections.length > MAX_MARKDOWN_LIST_LENGTH) { stream.markdown( createMarkdownLink({ - commandId: EXTENSION_COMMANDS.SELECT_COLLECTION_WITH_PARTICIPANT, + commandId: ExtensionCommand.SELECT_COLLECTION_WITH_PARTICIPANT, data: { command, chatId: ChatMetadataStore.getChatIdFromHistoryOrNewChatId( @@ -1434,7 +1434,7 @@ export default class ParticipantController { }); stream.button({ - command: EXTENSION_COMMANDS.PARTICIPANT_OPEN_RAW_SCHEMA_OUTPUT, + command: ExtensionCommand.PARTICIPANT_OPEN_RAW_SCHEMA_OUTPUT, title: vscode.l10n.t('Open JSON Output'), arguments: [ { @@ -1779,7 +1779,7 @@ export default class ParticipantController { this._telemetryService.track( new ParticipantResponseFailedTelemetryEvent( 'docs', - PARTICIPANT_ERROR_TYPES.DOCS_CHATBOT_API, + ParticipantErrorType.DOCS_CHATBOT_API, ), ); @@ -1814,7 +1814,7 @@ export default class ParticipantController { return false; } await vscode.commands.executeCommand( - EXTENSION_COMMANDS.MDB_EXPORT_TO_LANGUAGE, + ExtensionCommand.MDB_EXPORT_TO_LANGUAGE, language.id, ); return true; @@ -1893,7 +1893,7 @@ export default class ParticipantController { const content = contentOrError.value; await vscode.commands.executeCommand( - EXTENSION_COMMANDS.OPEN_PARTICIPANT_CODE_IN_PLAYGROUND, + ExtensionCommand.OPEN_PARTICIPANT_CODE_IN_PLAYGROUND, { runnableContent: content, }, @@ -1973,7 +1973,7 @@ export default class ParticipantController { const [request, , stream] = args; try { const hasBeenShownWelcomeMessageAlready = !!this._storageController.get( - STORAGE_VARIABLES.COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE, + StorageVariable.COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE, ); if (!hasBeenShownWelcomeMessageAlready) { stream.markdown( @@ -1988,7 +1988,7 @@ Please see our [FAQ](https://www.mongodb.com/docs/generative-ai-faq/) for more i ); await this._storageController.update( - STORAGE_VARIABLES.COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE, + StorageVariable.COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE, true, ); } @@ -2158,7 +2158,7 @@ Please see our [FAQ](https://www.mongodb.com/docs/generative-ai-faq/) for more i ); await vscode.commands.executeCommand( - EXTENSION_COMMANDS.SHOW_EXPORT_TO_LANGUAGE_RESULT, + ExtensionCommand.SHOW_EXPORT_TO_LANGUAGE_RESULT, { prompt, content: transpiledContent, diff --git a/src/participant/participantErrorTypes.ts b/src/participant/participantErrorTypes.ts index 221116f9a..da3f53d7b 100644 --- a/src/participant/participantErrorTypes.ts +++ b/src/participant/participantErrorTypes.ts @@ -1,4 +1,4 @@ -export const PARTICIPANT_ERROR_TYPES = { +export const ParticipantErrorType = { CHAT_MODEL_OFF_TOPIC: 'Chat Model Off Topic', INVALID_PROMPT: 'Invalid Prompt', FILTERED: 'Filtered by Responsible AI Service', @@ -7,7 +7,7 @@ export const PARTICIPANT_ERROR_TYPES = { } as const; export type ParticipantErrorType = - (typeof PARTICIPANT_ERROR_TYPES)[keyof typeof PARTICIPANT_ERROR_TYPES]; + (typeof ParticipantErrorType)[keyof typeof ParticipantErrorType]; export type ExportToPlaygroundError = | 'cancelled' diff --git a/src/participant/prompts/promptHistory.ts b/src/participant/prompts/promptHistory.ts index 0804cfb9d..12cb0a79f 100644 --- a/src/participant/prompts/promptHistory.ts +++ b/src/participant/prompts/promptHistory.ts @@ -1,5 +1,5 @@ import * as vscode from 'vscode'; -import { PARTICIPANT_ERROR_TYPES } from '../participantErrorTypes'; +import { ParticipantErrorType } from '../participantErrorTypes'; import type { ChatResult } from '../constants'; import type { ParticipantResponseType } from '../participantTypes'; @@ -12,8 +12,7 @@ export class PromptHistory { namespaceIsKnown: boolean; }): vscode.LanguageModelChatMessage | undefined { if ( - currentTurn.result.errorDetails?.message === - PARTICIPANT_ERROR_TYPES.FILTERED + currentTurn.result.errorDetails?.message === ParticipantErrorType.FILTERED ) { return undefined; } @@ -83,7 +82,7 @@ export class PromptHistory { if ( nextTurn instanceof vscode.ChatResponseTurn && - nextTurn.result.errorDetails?.message === PARTICIPANT_ERROR_TYPES.FILTERED + nextTurn.result.errorDetails?.message === ParticipantErrorType.FILTERED ) { // If the response to this request led to a filtered error, // we do not want to include it in the history diff --git a/src/storage/connectionStorage.ts b/src/storage/connectionStorage.ts index 50ca7abd2..9419f29e7 100644 --- a/src/storage/connectionStorage.ts +++ b/src/storage/connectionStorage.ts @@ -8,15 +8,11 @@ import type { ConnectionOptions } from 'mongodb-data-service'; import { createLogger } from '../logging'; import type StorageController from './storageController'; -import type { - SecretStorageLocationType, - StorageLocation, -} from './storageController'; +import { StorageLocation } from './storageController'; import { - DEFAULT_SAVING_LOCATIONS, - SECRET_STORAGE_LOCATIONS, - STORAGE_LOCATIONS, - STORAGE_VARIABLES, + DefaultSavingLocation, + SecretStorageLocation, + StorageVariable, } from './storageController'; import { v4 as uuidv4 } from 'uuid'; @@ -27,7 +23,7 @@ export interface StoreConnectionInfo { id: string; // Connection model id or a new uuid. name: string; // Possibly user given name, not unique. storageLocation: StorageLocation; - secretStorageLocation?: SecretStorageLocationType; + secretStorageLocation?: SecretStorageLocation; connectionOptions?: ConnectionOptions; source?: ConnectionSource; lastUsed?: Date; // Date and time when the connection was last used, i.e. connected with. @@ -45,11 +41,11 @@ export type PresetSavedConnectionWithSource = PresetSavedConnection & { type StoreConnectionInfoWithConnectionOptions = StoreConnectionInfo & Required>; -type StoreConnectionInfoWithSECRET_STORAGE_LOCATIONS = StoreConnectionInfo & +type StoreConnectionInfoWithSecretStorageLocation = StoreConnectionInfo & Required>; export type LoadedConnection = StoreConnectionInfoWithConnectionOptions & - StoreConnectionInfoWithSECRET_STORAGE_LOCATIONS; + StoreConnectionInfoWithSecretStorageLocation; export class ConnectionStorage { _storageController: StorageController; @@ -137,10 +133,7 @@ export class ConnectionStorage { async saveConnection(connection: LoadedConnection): Promise { if ( !( - [ - STORAGE_LOCATIONS.GLOBAL, - STORAGE_LOCATIONS.WORKSPACE, - ] as StorageLocation[] + [StorageLocation.GLOBAL, StorageLocation.WORKSPACE] as StorageLocation[] ).includes(connection.storageLocation) ) { return; @@ -163,9 +156,9 @@ export class ConnectionStorage { connectionWithoutSecrets: StoreConnectionInfo, ): Promise { const variableName = - connectionWithoutSecrets.storageLocation === STORAGE_LOCATIONS.GLOBAL - ? STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS - : STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS; + connectionWithoutSecrets.storageLocation === StorageLocation.GLOBAL + ? StorageVariable.GLOBAL_SAVED_CONNECTIONS + : StorageVariable.WORKSPACE_SAVED_CONNECTIONS; // Get the current saved connections. let savedConnections = this._storageController.get( @@ -217,8 +210,8 @@ export class ConnectionStorage { connectionString: presetConnection.connectionString, }, source: presetConnection.source, - storageLocation: STORAGE_LOCATIONS.NONE, - secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, + storageLocation: StorageLocation.NONE, + secretStorageLocation: SecretStorageLocation.SecretStorage, }) satisfies LoadedConnection, ); } @@ -226,12 +219,12 @@ export class ConnectionStorage { async loadConnections(): Promise { const globalAndWorkspaceConnections = Object.values({ ...this._storageController.get( - STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.GLOBAL, + StorageVariable.GLOBAL_SAVED_CONNECTIONS, + StorageLocation.GLOBAL, ), ...this._storageController.get( - STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.WORKSPACE, + StorageVariable.WORKSPACE_SAVED_CONNECTIONS, + StorageLocation.WORKSPACE, ), }); @@ -271,21 +264,21 @@ export class ConnectionStorage { // See if the connection exists in the saved global or workspace connections // and remove it if it is. const globalStoredConnections = this._storageController.get( - STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.GLOBAL, + StorageVariable.GLOBAL_SAVED_CONNECTIONS, + StorageLocation.GLOBAL, ); if (globalStoredConnections && globalStoredConnections[connectionId]) { delete globalStoredConnections[connectionId]; void this._storageController.update( - STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + StorageVariable.GLOBAL_SAVED_CONNECTIONS, globalStoredConnections, - STORAGE_LOCATIONS.GLOBAL, + StorageLocation.GLOBAL, ); } const workspaceStoredConnections = this._storageController.get( - STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.WORKSPACE, + StorageVariable.WORKSPACE_SAVED_CONNECTIONS, + StorageLocation.WORKSPACE, ); if ( workspaceStoredConnections && @@ -293,21 +286,21 @@ export class ConnectionStorage { ) { delete workspaceStoredConnections[connectionId]; void this._storageController.update( - STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + StorageVariable.WORKSPACE_SAVED_CONNECTIONS, workspaceStoredConnections, - STORAGE_LOCATIONS.WORKSPACE, + StorageLocation.WORKSPACE, ); } } hasSavedConnections(): boolean { const savedWorkspaceConnections = this._storageController.get( - STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.WORKSPACE, + StorageVariable.WORKSPACE_SAVED_CONNECTIONS, + StorageLocation.WORKSPACE, ); const savedGlobalConnections = this._storageController.get( - STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.GLOBAL, + StorageVariable.GLOBAL_SAVED_CONNECTIONS, + StorageLocation.GLOBAL, ); return !!( @@ -322,17 +315,15 @@ export class ConnectionStorage { .getConfiguration('mdb.connectionSaving') .get('defaultConnectionSavingLocation'); - if ( - defaultConnectionSavingLocation === DEFAULT_SAVING_LOCATIONS.Workspace - ) { - return STORAGE_LOCATIONS.WORKSPACE; + if (defaultConnectionSavingLocation === DefaultSavingLocation.Workspace) { + return StorageLocation.WORKSPACE; } - if (defaultConnectionSavingLocation === DEFAULT_SAVING_LOCATIONS.Global) { - return STORAGE_LOCATIONS.GLOBAL; + if (defaultConnectionSavingLocation === DefaultSavingLocation.Global) { + return StorageLocation.GLOBAL; } - return STORAGE_LOCATIONS.NONE; + return StorageLocation.NONE; } getUserAnonymousId(): string { diff --git a/src/storage/index.ts b/src/storage/index.ts index e8a426b7e..0517a7856 100644 --- a/src/storage/index.ts +++ b/src/storage/index.ts @@ -1,6 +1,6 @@ import StorageController, { - STORAGE_VARIABLES, - STORAGE_LOCATIONS, + StorageVariable, + StorageLocation, } from './storageController'; -export { StorageController, STORAGE_VARIABLES, STORAGE_LOCATIONS }; +export { StorageController, StorageVariable, StorageLocation }; diff --git a/src/storage/storageController.ts b/src/storage/storageController.ts index 1f4d971a1..266fa9d3a 100644 --- a/src/storage/storageController.ts +++ b/src/storage/storageController.ts @@ -3,7 +3,7 @@ import { v4 as uuidv4 } from 'uuid'; import type { StoreConnectionInfo } from './connectionStorage'; -export const STORAGE_VARIABLES = { +export const StorageVariable = { // Only exists on globalState. GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW: 'GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW', GLOBAL_SAVED_CONNECTIONS: 'GLOBAL_SAVED_CONNECTIONS', @@ -16,28 +16,28 @@ export const STORAGE_VARIABLES = { 'COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE', } as const; -export type StorageVariables = - (typeof STORAGE_VARIABLES)[keyof typeof STORAGE_VARIABLES]; +export type StorageVariable = + (typeof StorageVariable)[keyof typeof StorageVariable]; // Typically variables default to 'GLOBAL' scope. -export const STORAGE_LOCATIONS = { +export const StorageLocation = { GLOBAL: 'GLOBAL', WORKSPACE: 'WORKSPACE', NONE: 'NONE', } as const; export type StorageLocation = - (typeof STORAGE_LOCATIONS)[keyof typeof STORAGE_LOCATIONS]; + (typeof StorageLocation)[keyof typeof StorageLocation]; // Coupled with the `defaultConnectionSavingLocation` configuration in `package.json`. -export const DEFAULT_SAVING_LOCATIONS = { +export const DefaultSavingLocation = { Workspace: 'Workspace', Global: 'Global', 'Session Only': 'Session Only', } as const; -export type DefaultSavingLocations = - (typeof DEFAULT_SAVING_LOCATIONS)[keyof typeof DEFAULT_SAVING_LOCATIONS]; +export type DefaultSavingLocation = + (typeof DefaultSavingLocation)[keyof typeof DefaultSavingLocation]; export type ConnectionsFromStorage = { [connectionId: string]: StoreConnectionInfo; @@ -45,46 +45,46 @@ export type ConnectionsFromStorage = { // Keytar is deprecated and no longer used. All new // connections use 'SecretStorage'. -export const SECRET_STORAGE_LOCATIONS = { +export const SecretStorageLocation = { Keytar: 'vscode.Keytar', KeytarSecondAttempt: 'vscode.KeytarSecondAttempt', SecretStorage: 'vscode.SecretStorage', } as const; -export type SecretStorageLocationType = - (typeof SECRET_STORAGE_LOCATIONS)[keyof typeof SECRET_STORAGE_LOCATIONS]; +export type SecretStorageLocation = + (typeof SecretStorageLocation)[keyof typeof SecretStorageLocation]; interface StorageVariableContents { - [STORAGE_VARIABLES.GLOBAL_USER_ID]: string; - [STORAGE_VARIABLES.GLOBAL_ANONYMOUS_ID]: string; - [STORAGE_VARIABLES.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW]: boolean; - [STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS]: ConnectionsFromStorage; - [STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS]: ConnectionsFromStorage; - [STORAGE_VARIABLES.COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE]: boolean; + [StorageVariable.GLOBAL_USER_ID]: string; + [StorageVariable.GLOBAL_ANONYMOUS_ID]: string; + [StorageVariable.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW]: boolean; + [StorageVariable.GLOBAL_SAVED_CONNECTIONS]: ConnectionsFromStorage; + [StorageVariable.WORKSPACE_SAVED_CONNECTIONS]: ConnectionsFromStorage; + [StorageVariable.COPILOT_HAS_BEEN_SHOWN_WELCOME_MESSAGE]: boolean; } type StoredVariableName = keyof StorageVariableContents; type StoredItem = StorageVariableContents[T]; export default class StorageController { _storage: { - [STORAGE_LOCATIONS.GLOBAL]: vscode.Memento; - [STORAGE_LOCATIONS.WORKSPACE]: vscode.Memento; + [StorageLocation.GLOBAL]: vscode.Memento; + [StorageLocation.WORKSPACE]: vscode.Memento; }; _secretStorage: vscode.SecretStorage; constructor(context: vscode.ExtensionContext) { this._storage = { - [STORAGE_LOCATIONS.GLOBAL]: context.globalState, - [STORAGE_LOCATIONS.WORKSPACE]: context.workspaceState, + [StorageLocation.GLOBAL]: context.globalState, + [StorageLocation.WORKSPACE]: context.workspaceState, }; this._secretStorage = context.secrets; } get( variableName: T, - storageLocation: StorageLocation = STORAGE_LOCATIONS.GLOBAL, + storageLocation: StorageLocation = StorageLocation.GLOBAL, ): StoredItem { return this._storage[storageLocation].get(variableName); } @@ -93,19 +93,19 @@ export default class StorageController { update( variableName: T, value: StoredItem, - storageLocation: StorageLocation = STORAGE_LOCATIONS.GLOBAL, + storageLocation: StorageLocation = StorageLocation.GLOBAL, ): Thenable { this._storage[storageLocation].update(variableName, value); return Promise.resolve(); } getUserIdentity(): { anonymousId: string } { - let anonymousId = this.get(STORAGE_VARIABLES.GLOBAL_ANONYMOUS_ID); + let anonymousId = this.get(StorageVariable.GLOBAL_ANONYMOUS_ID); // The anonymousId becomes required with analytics-node v6. if (!anonymousId) { anonymousId = uuidv4(); - void this.update(STORAGE_VARIABLES.GLOBAL_ANONYMOUS_ID, anonymousId); + void this.update(StorageVariable.GLOBAL_ANONYMOUS_ID, anonymousId); } return { anonymousId }; diff --git a/src/telemetry/telemetryEvents.ts b/src/telemetry/telemetryEvents.ts index 875907b16..56986d199 100644 --- a/src/telemetry/telemetryEvents.ts +++ b/src/telemetry/telemetryEvents.ts @@ -1,6 +1,6 @@ import type { ExtensionCommand } from '../commands'; import type { DocumentSourceDetails } from '../documentSource'; -import { DOCUMENT_SOURCE, type DocumentSource } from '../documentSource'; +import { DocumentSource } from '../documentSource'; import type { ExportToPlaygroundError, ParticipantErrorType, @@ -332,7 +332,7 @@ export class SavedConnectionsLoadedTelemetryEvent connections_with_secrets_in_keytar: number; /** Total number of connections that have secrets stored in secret storage */ - connections_with_secrets_in_secret_storage: number; + connections_with_secrets_in_SecretStorage: number; }; constructor({ @@ -353,7 +353,7 @@ export class SavedConnectionsLoadedTelemetryEvent preset_connections: presetConnections, loaded_connections: loadedConnections, connections_with_secrets_in_keytar: connectionsWithSecretsInKeytar, - connections_with_secrets_in_secret_storage: + connections_with_secrets_in_SecretStorage: connectionsWithSecretsInSecretStorage, }; } @@ -628,7 +628,7 @@ export class PresetConnectionEditedTelemetryEvent constructor(sourceDetails: 'tree_item' | 'header') { this.properties = { - source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW, + source: DocumentSource.DocumentSource_TREEVIEW, source_details: sourceDetails, }; } diff --git a/src/telemetry/telemetryService.ts b/src/telemetry/telemetryService.ts index 8fcc39484..7099f507d 100644 --- a/src/telemetry/telemetryService.ts +++ b/src/telemetry/telemetryService.ts @@ -10,10 +10,7 @@ import type { ConnectionTypes } from '../connectionController'; import { createLogger } from '../logging'; import { getConnectionTelemetryProperties } from './connectionTelemetry'; import type { StorageController } from '../storage'; -import { - PARTICIPANT_ERROR_TYPES, - type ParticipantErrorType, -} from '../participant/participantErrorTypes'; +import { ParticipantErrorType } from '../participant/participantErrorTypes'; import type { ParticipantResponseType } from '../participant/participantTypes'; import type { TelemetryEvent } from './telemetryEvents'; import { @@ -217,13 +214,13 @@ export class TelemetryService { const message: string = err.message || err.toString(); if (message.includes('off_topic')) { - errorName = PARTICIPANT_ERROR_TYPES.CHAT_MODEL_OFF_TOPIC; + errorName = ParticipantErrorType.CHAT_MODEL_OFF_TOPIC; } else if (message.includes('Filtered by Responsible AI Service')) { - errorName = PARTICIPANT_ERROR_TYPES.FILTERED; + errorName = ParticipantErrorType.FILTERED; } else if (message.includes('Prompt failed validation')) { - errorName = PARTICIPANT_ERROR_TYPES.INVALID_PROMPT; + errorName = ParticipantErrorType.INVALID_PROMPT; } else { - errorName = PARTICIPANT_ERROR_TYPES.OTHER; + errorName = ParticipantErrorType.OTHER; } this.track( diff --git a/src/test/suite/connectionController.test.ts b/src/test/suite/connectionController.test.ts index 19d2f2e37..376fd9f82 100644 --- a/src/test/suite/connectionController.test.ts +++ b/src/test/suite/connectionController.test.ts @@ -14,12 +14,12 @@ import ConnectionController, { import formatError from '../../utils/formatError'; import { StorageController, - STORAGE_VARIABLES, - STORAGE_LOCATIONS, + StorageVariable, + StorageLocation, } from '../../storage'; import { - DEFAULT_SAVING_LOCATIONS, - SECRET_STORAGE_LOCATIONS, + DefaultSavingLocation, + SecretStorageLocation, } from '../../storage/storageController'; import { StatusView } from '../../views'; import { TelemetryService } from '../../telemetry'; @@ -272,8 +272,8 @@ suite('Connection Controller Test Suite', function () { ): void => { testConnectionController._connections[id] = { connectionOptions: { connectionString }, - storageLocation: STORAGE_LOCATIONS.NONE, - secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, + storageLocation: StorageLocation.NONE, + secretStorageLocation: SecretStorageLocation.SecretStorage, name, id, ...otherOptions, @@ -550,8 +550,8 @@ suite('Connection Controller Test Suite', function () { connectionOptions: { connectionString: 'localhost:3000', }, - storageLocation: STORAGE_LOCATIONS.NONE, - secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, + storageLocation: StorageLocation.NONE, + secretStorageLocation: SecretStorageLocation.SecretStorage, }; // Should persist as this is a saved connection. @@ -568,10 +568,7 @@ suite('Connection Controller Test Suite', function () { test('the connection model loads both global and workspace stored connection models', async () => { await vscode.workspace .getConfiguration('mdb.connectionSaving') - .update( - 'defaultConnectionSavingLocation', - DEFAULT_SAVING_LOCATIONS.Global, - ); + .update('defaultConnectionSavingLocation', DefaultSavingLocation.Global); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); @@ -582,7 +579,7 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DEFAULT_SAVING_LOCATIONS.Workspace, + DefaultSavingLocation.Workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, @@ -610,17 +607,14 @@ suite('Connection Controller Test Suite', function () { await testConnectionController.loadSavedConnections(); await vscode.workspace .getConfiguration('mdb.connectionSaving') - .update( - 'defaultConnectionSavingLocation', - DEFAULT_SAVING_LOCATIONS.Global, - ); + .update('defaultConnectionSavingLocation', DefaultSavingLocation.Global); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const globalStoreConnections = testStorageController.get( - STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.GLOBAL, + StorageVariable.GLOBAL_SAVED_CONNECTIONS, + StorageLocation.GLOBAL, ); expect(Object.keys(globalStoreConnections)).to.have.lengthOf(1); @@ -632,7 +626,7 @@ suite('Connection Controller Test Suite', function () { ); const workspaceStoreConnections = testStorageController.get( - STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + StorageVariable.WORKSPACE_SAVED_CONNECTIONS, ); expect(workspaceStoreConnections).to.be.undefined; @@ -644,15 +638,15 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DEFAULT_SAVING_LOCATIONS.Workspace, + DefaultSavingLocation.Workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const workspaceStoreConnections = testStorageController.get( - STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.WORKSPACE, + StorageVariable.WORKSPACE_SAVED_CONNECTIONS, + StorageLocation.WORKSPACE, ); expect(Object.keys(workspaceStoreConnections)).to.have.lengthOf(1); @@ -664,8 +658,8 @@ suite('Connection Controller Test Suite', function () { ); const globalStoreConnections = testStorageController.get( - STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.GLOBAL, + StorageVariable.GLOBAL_SAVED_CONNECTIONS, + StorageLocation.GLOBAL, ); expect(globalStoreConnections).to.be.undefined; @@ -677,8 +671,8 @@ suite('Connection Controller Test Suite', function () { id: '25', name: 'tester', connectionOptions: { connectionString: TEST_DATABASE_URI }, - storageLocation: STORAGE_LOCATIONS.NONE, - secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, + storageLocation: StorageLocation.NONE, + secretStorageLocation: SecretStorageLocation.SecretStorage, }, }; @@ -695,15 +689,15 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DEFAULT_SAVING_LOCATIONS.Workspace, + DefaultSavingLocation.Workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const workspaceStoreConnections = testStorageController.get( - STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.WORKSPACE, + StorageVariable.WORKSPACE_SAVED_CONNECTIONS, + StorageLocation.WORKSPACE, ); expect(Object.keys(workspaceStoreConnections)).to.have.lengthOf(1); @@ -757,7 +751,7 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DEFAULT_SAVING_LOCATIONS['Session Only'], + DefaultSavingLocation['Session Only'], ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, @@ -765,15 +759,15 @@ suite('Connection Controller Test Suite', function () { const objectString = JSON.stringify(undefined); const globalStoreConnections = testStorageController.get( - STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.GLOBAL, + StorageVariable.GLOBAL_SAVED_CONNECTIONS, + StorageLocation.GLOBAL, ); expect(JSON.stringify(globalStoreConnections)).to.equal(objectString); const workspaceStoreConnections = testStorageController.get( - STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.WORKSPACE, + StorageVariable.WORKSPACE_SAVED_CONNECTIONS, + StorageLocation.WORKSPACE, ); expect(JSON.stringify(workspaceStoreConnections)).to.equal(objectString); @@ -818,15 +812,15 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DEFAULT_SAVING_LOCATIONS.Workspace, + DefaultSavingLocation.Workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const workspaceStoreConnections = testStorageController.get( - STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.WORKSPACE, + StorageVariable.WORKSPACE_SAVED_CONNECTIONS, + StorageLocation.WORKSPACE, ); expect(Object.keys(workspaceStoreConnections)).to.have.lengthOf(1); @@ -838,8 +832,8 @@ suite('Connection Controller Test Suite', function () { await testConnectionController.removeSavedConnection(connectionId); const postWorkspaceStoreConnections = testStorageController.get( - STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.WORKSPACE, + StorageVariable.WORKSPACE_SAVED_CONNECTIONS, + StorageLocation.WORKSPACE, ); expect(Object.keys(postWorkspaceStoreConnections)).to.have.lengthOf(0); @@ -849,17 +843,14 @@ suite('Connection Controller Test Suite', function () { await testConnectionController.loadSavedConnections(); await vscode.workspace .getConfiguration('mdb.connectionSaving') - .update( - 'defaultConnectionSavingLocation', - DEFAULT_SAVING_LOCATIONS.Global, - ); + .update('defaultConnectionSavingLocation', DefaultSavingLocation.Global); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const globalStoreConnections = testStorageController.get( - STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.GLOBAL, + StorageVariable.GLOBAL_SAVED_CONNECTIONS, + StorageLocation.GLOBAL, ); expect(Object.keys(globalStoreConnections)).to.have.lengthOf(1); @@ -869,8 +860,8 @@ suite('Connection Controller Test Suite', function () { await testConnectionController.removeSavedConnection(connectionId); const postGlobalStoreConnections = testStorageController.get( - STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.GLOBAL, + StorageVariable.GLOBAL_SAVED_CONNECTIONS, + StorageLocation.GLOBAL, ); expect(Object.keys(postGlobalStoreConnections)).to.have.lengthOf(0); @@ -897,15 +888,15 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DEFAULT_SAVING_LOCATIONS.Workspace, + DefaultSavingLocation.Workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const workspaceStoreConnections = testStorageController.get( - STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.WORKSPACE, + StorageVariable.WORKSPACE_SAVED_CONNECTIONS, + StorageLocation.WORKSPACE, ); expect(Object.keys(workspaceStoreConnections)).to.have.lengthOf(1); @@ -945,15 +936,15 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DEFAULT_SAVING_LOCATIONS.Workspace, + DefaultSavingLocation.Workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, }); const workspaceStoreConnections = testStorageController.get( - STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.WORKSPACE, + StorageVariable.WORKSPACE_SAVED_CONNECTIONS, + StorageLocation.WORKSPACE, ); expect(Object.keys(workspaceStoreConnections)).to.have.lengthOf(1); @@ -1021,7 +1012,7 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DEFAULT_SAVING_LOCATIONS.Workspace, + DefaultSavingLocation.Workspace, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI, @@ -1091,8 +1082,8 @@ suite('Connection Controller Test Suite', function () { id, name: `test${i}`, connectionOptions: { connectionString: TEST_DATABASE_URI }, - storageLocation: STORAGE_LOCATIONS.NONE, - secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, + storageLocation: StorageLocation.NONE, + secretStorageLocation: SecretStorageLocation.SecretStorage, }; } @@ -1153,8 +1144,8 @@ suite('Connection Controller Test Suite', function () { id: connectionId, name: 'asdfasdg', connectionOptions: { connectionString: testDatabaseURI2WithTimeout }, - storageLocation: STORAGE_LOCATIONS.NONE, - secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, + storageLocation: StorageLocation.NONE, + secretStorageLocation: SecretStorageLocation.SecretStorage, }; void testConnectionController.connectWithConnectionId(connectionId); @@ -1177,8 +1168,8 @@ suite('Connection Controller Test Suite', function () { id: connectionId, name: 'asdfasdg', connectionOptions: { connectionString: TEST_DATABASE_URI }, - storageLocation: STORAGE_LOCATIONS.NONE, - secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, + storageLocation: StorageLocation.NONE, + secretStorageLocation: SecretStorageLocation.SecretStorage, }; sandbox.replace( @@ -1208,8 +1199,8 @@ suite('Connection Controller Test Suite', function () { const connectionInfo = { id: '1d700f37-ba57-4568-9552-0ea23effea89', name: 'localhost:27017', - storageLocation: STORAGE_LOCATIONS.GLOBAL, - secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, + storageLocation: StorageLocation.GLOBAL, + secretStorageLocation: SecretStorageLocation.SecretStorage, connectionOptions: { connectionString: 'mongodb://lena:secrer@localhost:27017/?readPreference=primary&ssl=false', @@ -1309,7 +1300,7 @@ suite('Connection Controller Test Suite', function () { expect( savedConnections.every( ({ secretStorageLocation }) => - secretStorageLocation === SECRET_STORAGE_LOCATIONS.SecretStorage, + secretStorageLocation === SecretStorageLocation.SecretStorage, ), ).to.be.true; @@ -1361,7 +1352,7 @@ suite('Connection Controller Test Suite', function () { id: 'random-connection-4', name: 'localhost:27089', storageLocation: 'GLOBAL', - secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, + secretStorageLocation: SecretStorageLocation.SecretStorage, connectionOptions: { connectionString: 'mongodb://localhost:27080/?readPreference=primary&ssl=false', @@ -1369,8 +1360,8 @@ suite('Connection Controller Test Suite', function () { }; testSandbox.replace(testStorageController, 'get', (key, storage) => { if ( - storage === STORAGE_LOCATIONS.WORKSPACE || - key === STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS + storage === StorageLocation.WORKSPACE || + key === StorageVariable.WORKSPACE_SAVED_CONNECTIONS ) { return {}; } @@ -1380,7 +1371,7 @@ suite('Connection Controller Test Suite', function () { id: 'random-connection-1', name: 'localhost:27017', storageLocation: 'GLOBAL', - secretStorageLocation: SECRET_STORAGE_LOCATIONS.Keytar, + secretStorageLocation: SecretStorageLocation.Keytar, connectionOptions: { connectionString: 'mongodb://localhost:27017/?readPreference=primary&ssl=false', @@ -1390,7 +1381,7 @@ suite('Connection Controller Test Suite', function () { id: 'random-connection-2', name: 'localhost:27017', storageLocation: 'GLOBAL', - secretStorageLocation: SECRET_STORAGE_LOCATIONS.KeytarSecondAttempt, + secretStorageLocation: SecretStorageLocation.KeytarSecondAttempt, connectionOptions: { connectionString: 'mongodb://localhost:27017/?readPreference=primary&ssl=false', @@ -1424,8 +1415,8 @@ suite('Connection Controller Test Suite', function () { test.skip('should track SAVED_CONNECTIONS_LOADED event on load of saved connections', async () => { testSandbox.replace(testStorageController, 'get', (key, storage) => { if ( - storage === STORAGE_LOCATIONS.WORKSPACE || - key === STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS + storage === StorageLocation.WORKSPACE || + key === StorageVariable.WORKSPACE_SAVED_CONNECTIONS ) { return {}; } @@ -1435,7 +1426,7 @@ suite('Connection Controller Test Suite', function () { id: 'random-connection-1', name: 'localhost:27017', storageLocation: 'GLOBAL', - secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, + secretStorageLocation: SecretStorageLocation.SecretStorage, connectionOptions: { connectionString: 'mongodb://localhost:27017/?readPreference=primary&ssl=false', @@ -1445,7 +1436,7 @@ suite('Connection Controller Test Suite', function () { id: 'random-connection-2', name: 'localhost:27088', storageLocation: 'GLOBAL', - secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, + secretStorageLocation: SecretStorageLocation.SecretStorage, connectionOptions: { connectionString: 'mongodb://localhost:27088/?readPreference=primary&ssl=false', @@ -1455,7 +1446,7 @@ suite('Connection Controller Test Suite', function () { id: 'random-connection-3', name: 'localhost:27088', storageLocation: 'GLOBAL', - secretStorageLocation: SECRET_STORAGE_LOCATIONS.Keytar, + secretStorageLocation: SecretStorageLocation.Keytar, connectionOptions: { connectionString: 'mongodb://localhost:27088/?readPreference=primary&ssl=false', @@ -1465,7 +1456,7 @@ suite('Connection Controller Test Suite', function () { id: 'random-connection-4', name: 'localhost:27088', storageLocation: 'GLOBAL', - secretStorageLocation: SECRET_STORAGE_LOCATIONS.KeytarSecondAttempt, + secretStorageLocation: SecretStorageLocation.KeytarSecondAttempt, connectionOptions: { connectionString: 'mongodb://localhost:27088/?readPreference=primary&ssl=false', @@ -1491,7 +1482,7 @@ suite('Connection Controller Test Suite', function () { expect(trackStub.lastCall.args).to.deep.equal([ { connections_with_secrets_in_keytar: 2, - connections_with_secrets_in_secret_storage: 2, + connections_with_secrets_in_SecretStorage: 2, saved_connections: 4, loaded_connections: 4, }, @@ -1569,14 +1560,14 @@ suite('Connection Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DEFAULT_SAVING_LOCATIONS.Global, + DefaultSavingLocation.Global, ); await testConnectionController.addNewConnectionStringAndConnect({ connectionString: TEST_DATABASE_URI_USER, }); const workspaceStoreConnections = testStorageController.get( - STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, + StorageVariable.GLOBAL_SAVED_CONNECTIONS, ); expect(workspaceStoreConnections).to.not.be.empty; diff --git a/src/test/suite/editors/collectionDocumentsProvider.test.ts b/src/test/suite/editors/collectionDocumentsProvider.test.ts index 5ce610b7a..523089d8a 100644 --- a/src/test/suite/editors/collectionDocumentsProvider.test.ts +++ b/src/test/suite/editors/collectionDocumentsProvider.test.ts @@ -3,7 +3,7 @@ import assert from 'assert'; import { beforeEach, afterEach } from 'mocha'; import sinon from 'sinon'; import type { DataService } from 'mongodb-data-service'; -import { DOCUMENT_SOURCE } from '../../../documentSource'; +import { DocumentSource } from '../../../documentSource'; import CollectionDocumentsOperationsStore from '../../../editors/collectionDocumentsOperationsStore'; import CollectionDocumentsProvider, { VIEW_COLLECTION_SCHEME, @@ -13,8 +13,8 @@ import EditDocumentCodeLensProvider from '../../../editors/editDocumentCodeLensP import { StatusView } from '../../../views'; import { StorageController } from '../../../storage'; import { - SECRET_STORAGE_LOCATIONS, - STORAGE_LOCATIONS, + SecretStorageLocation, + StorageLocation, } from '../../../storage/storageController'; import { TelemetryService } from '../../../telemetry'; import { TEST_DATABASE_URI } from '../dbTestHelper'; @@ -287,7 +287,7 @@ suite('Collection Documents Provider Test Suite', () => { assert(!!firstCollectionFirstCommandArguments); assert( firstCollectionFirstCommandArguments[0].source === - DOCUMENT_SOURCE.DOCUMENT_SOURCE_COLLECTIONVIEW, + DocumentSource.DocumentSource_COLLECTIONVIEW, ); assert( firstCollectionFirstCommandArguments[0].namespace === @@ -357,7 +357,7 @@ suite('Collection Documents Provider Test Suite', () => { assert(!!secondCollectionFirstCommandArguments); assert( secondCollectionFirstCommandArguments[0].source === - DOCUMENT_SOURCE.DOCUMENT_SOURCE_COLLECTIONVIEW, + DocumentSource.DocumentSource_COLLECTIONVIEW, ); assert( secondCollectionFirstCommandArguments[0].namespace === @@ -418,15 +418,15 @@ suite('Collection Documents Provider Test Suite', () => { id: firstConnectionId, name: 'localhost', connectionOptions: { connectionString: TEST_DATABASE_URI }, - storageLocation: STORAGE_LOCATIONS.NONE, - secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, + storageLocation: StorageLocation.NONE, + secretStorageLocation: SecretStorageLocation.SecretStorage, }, [secondConnectionId]: { id: secondConnectionId, name: 'compass', connectionOptions: { connectionString: TEST_DATABASE_URI }, - storageLocation: STORAGE_LOCATIONS.NONE, - secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, + storageLocation: StorageLocation.NONE, + secretStorageLocation: SecretStorageLocation.SecretStorage, }, }; @@ -476,7 +476,7 @@ suite('Collection Documents Provider Test Suite', () => { assert(!!firstCollectionFirstCommandArguments); assert( firstCollectionFirstCommandArguments[0].source === - DOCUMENT_SOURCE.DOCUMENT_SOURCE_COLLECTIONVIEW, + DocumentSource.DocumentSource_COLLECTIONVIEW, ); assert( firstCollectionFirstCommandArguments[0].namespace === @@ -551,7 +551,7 @@ suite('Collection Documents Provider Test Suite', () => { assert(!!secondCollectionFirstCommandArguments); assert( secondCollectionFirstCommandArguments[0].source === - DOCUMENT_SOURCE.DOCUMENT_SOURCE_COLLECTIONVIEW, + DocumentSource.DocumentSource_COLLECTIONVIEW, ); assert( secondCollectionFirstCommandArguments[0].namespace === diff --git a/src/test/suite/editors/editDocumentCodeLensProvider.test.ts b/src/test/suite/editors/editDocumentCodeLensProvider.test.ts index 0645a5f4f..030458fcc 100644 --- a/src/test/suite/editors/editDocumentCodeLensProvider.test.ts +++ b/src/test/suite/editors/editDocumentCodeLensProvider.test.ts @@ -6,7 +6,7 @@ import sinon from 'sinon'; import util from 'util'; import ConnectionController from '../../../connectionController'; -import { DOCUMENT_SOURCE } from '../../../documentSource'; +import { DocumentSource } from '../../../documentSource'; import EditDocumentCodeLensProvider from '../../../editors/editDocumentCodeLensProvider'; import { mockTextEditor } from '../stubs'; import { StatusView } from '../../../views'; @@ -56,7 +56,7 @@ suite('Edit Document Code Lens Provider Test Suite', () => { }, ], namespace: 'db.coll', - source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_PLAYGROUND, + source: DocumentSource.DocumentSource_PLAYGROUND, }; const fakeActiveConnectionId = sandbox.fake.returns('tasty_sandwhich'); @@ -90,7 +90,7 @@ suite('Edit Document Code Lens Provider Test Suite', () => { name: 'test name', }, namespace: 'db.coll', - source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_PLAYGROUND, + source: DocumentSource.DocumentSource_PLAYGROUND, }; const fakeActiveConnectionId = sandbox.fake.returns('tasty_sandwhich'); diff --git a/src/test/suite/editors/mongoDBDocumentService.test.ts b/src/test/suite/editors/mongoDBDocumentService.test.ts index 3ed87a982..c759b8876 100644 --- a/src/test/suite/editors/mongoDBDocumentService.test.ts +++ b/src/test/suite/editors/mongoDBDocumentService.test.ts @@ -5,7 +5,7 @@ import { EJSON } from 'bson'; import sinon from 'sinon'; import ConnectionController from '../../../connectionController'; -import { DOCUMENT_SOURCE } from '../../../documentSource'; +import { DocumentSource } from '../../../documentSource'; import formatError from '../../../utils/formatError'; import MongoDBDocumentService from '../../../editors/mongoDBDocumentService'; @@ -52,7 +52,7 @@ suite('MongoDB Document Service Test Suite', () => { const documentId = '93333a0d-83f6-4e6f-a575-af7ea6187a4a'; const document: { _id: string; price?: number } = { _id: '123' }; const newDocument = { _id: '123', price: 5000 }; - const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW; + const source = DocumentSource.DocumentSource_TREEVIEW; const fakeActiveConnectionId = sandbox.fake.returns('tasty_sandwhich'); sandbox.replace( @@ -103,7 +103,7 @@ suite('MongoDB Document Service Test Suite', () => { }, }, }; - const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW; + const source = DocumentSource.DocumentSource_TREEVIEW; const fakeActiveConnectionId = sandbox.fake.returns('tasty_sandwhich'); sandbox.replace( @@ -144,7 +144,7 @@ suite('MongoDB Document Service Test Suite', () => { const documentId = '93333a0d-83f6-4e6f-a575-af7ea6187a4a'; const line = 1; const documents = [{ _id: '123' }]; - const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_PLAYGROUND; + const source = DocumentSource.DocumentSource_PLAYGROUND; const fakeGetActiveDataService = sandbox.fake.returns({ find: () => { @@ -194,7 +194,7 @@ suite('MongoDB Document Service Test Suite', () => { }, }, ]; - const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_PLAYGROUND; + const source = DocumentSource.DocumentSource_PLAYGROUND; const fakeGetActiveDataService = sandbox.fake.returns({ find: () => { @@ -236,7 +236,7 @@ suite('MongoDB Document Service Test Suite', () => { const connectionId = 'tasty_sandwhich'; const documentId = '93333a0d-83f6-4e6f-a575-af7ea6187a4a'; const newDocument = { _id: '123', price: 5000 }; - const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW; + const source = DocumentSource.DocumentSource_TREEVIEW; const fakeActiveConnectionId = sandbox.fake.returns(null); sandbox.replace( @@ -273,7 +273,7 @@ suite('MongoDB Document Service Test Suite', () => { const connectionId = 'tasty_sandwhich'; const documentId = '93333a0d-83f6-4e6f-a575-af7ea6187a4a'; const newDocument = { _id: '123', price: 5000 }; - const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_PLAYGROUND; + const source = DocumentSource.DocumentSource_PLAYGROUND; const fakeActiveConnectionId = sandbox.fake.returns('berlin.coctails'); sandbox.replace( @@ -310,7 +310,7 @@ suite('MongoDB Document Service Test Suite', () => { const connectionId = '123'; const documentId = '93333a0d-83f6-4e6f-a575-af7ea6187a4a'; const line = 1; - const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_PLAYGROUND; + const source = DocumentSource.DocumentSource_PLAYGROUND; const fakeGetActiveConnectionId = sandbox.fake.returns('345'); sandbox.replace( diff --git a/src/test/suite/editors/queryWithCopilotCodeLensProvider.test.ts b/src/test/suite/editors/queryWithCopilotCodeLensProvider.test.ts index 65c7231e6..6dbe1ea75 100644 --- a/src/test/suite/editors/queryWithCopilotCodeLensProvider.test.ts +++ b/src/test/suite/editors/queryWithCopilotCodeLensProvider.test.ts @@ -4,7 +4,7 @@ import { expect } from 'chai'; import sinon from 'sinon'; import path from 'path'; import { QueryWithCopilotCodeLensProvider } from '../../../editors/queryWithCopilotCodeLensProvider'; -import EXTENSION_COMMANDS from '../../../commands'; +import ExtensionCommand from '../../../commands'; suite('Query with Copilot CodeLens Provider Test Suite', () => { let testCodeLensProvider: QueryWithCopilotCodeLensProvider; @@ -77,7 +77,7 @@ suite('Query with Copilot CodeLens Provider Test Suite', () => { expect(codeLens[0].range.start.line).to.be.equal(0); expect(codeLens[0].range.end.line).to.be.equal(0); expect(codeLens[0].command?.command).to.be.equal( - EXTENSION_COMMANDS.SEND_MESSAGE_TO_PARTICIPANT_FROM_INPUT, + ExtensionCommand.SEND_MESSAGE_TO_PARTICIPANT_FROM_INPUT, ); }); }); diff --git a/src/test/suite/explorer/collectionTreeItem.test.ts b/src/test/suite/explorer/collectionTreeItem.test.ts index cade03be9..a550f53c4 100644 --- a/src/test/suite/explorer/collectionTreeItem.test.ts +++ b/src/test/suite/explorer/collectionTreeItem.test.ts @@ -3,7 +3,7 @@ import type { DataService } from 'mongodb-data-service'; import CollectionTreeItem from '../../../explorer/collectionTreeItem'; import type { CollectionDetailsType } from '../../../explorer/collectionTreeItem'; -import { COLLECTION_TYPES } from '../../../explorer/documentListTreeItem'; +import { CollectionType } from '../../../explorer/documentListTreeItem'; import { ext } from '../../../extensionConstants'; import { ExtensionContextStub, DataServiceStub } from '../stubs'; @@ -16,7 +16,7 @@ function getTestCollectionTreeItem( return new CollectionTreeItem({ collection: { name: 'testColName', - type: COLLECTION_TYPES.collection, + type: CollectionType.collection, } as unknown as CollectionDetailsType, databaseName: 'testDbName', dataService: {} as DataService, @@ -81,7 +81,7 @@ suite('CollectionTreeItem Test Suite', () => { const testCollectionViewTreeItem = getTestCollectionTreeItem({ collection: { name: 'mock_collection_name_1', - type: COLLECTION_TYPES.view, + type: CollectionType.view, } as unknown as CollectionDetailsType, }); @@ -98,7 +98,7 @@ suite('CollectionTreeItem Test Suite', () => { const testCollectionCollectionTreeItem = getTestCollectionTreeItem({ collection: { name: 'mock_collection_name_1', - type: COLLECTION_TYPES.collection, + type: CollectionType.collection, } as unknown as CollectionDetailsType, }); const collectionIconPath = testCollectionCollectionTreeItem.iconPath; @@ -120,7 +120,7 @@ suite('CollectionTreeItem Test Suite', () => { const testCollectionTimeSeriesTreeItem = getTestCollectionTreeItem({ collection: { name: 'mock_collection_name_1', - type: COLLECTION_TYPES.timeseries, + type: CollectionType.timeseries, } as unknown as CollectionDetailsType, }); const viewIconPath = testCollectionTimeSeriesTreeItem.iconPath; @@ -136,7 +136,7 @@ suite('CollectionTreeItem Test Suite', () => { const testCollectionCollectionTreeItem = getTestCollectionTreeItem({ collection: { name: 'mock_collection_name_1', - type: COLLECTION_TYPES.collection, + type: CollectionType.collection, } as unknown as CollectionDetailsType, }); const collectionIconPath = testCollectionCollectionTreeItem.iconPath; diff --git a/src/test/suite/explorer/documentListTreeItem.test.ts b/src/test/suite/explorer/documentListTreeItem.test.ts index 168ec31e1..d753ac8c0 100644 --- a/src/test/suite/explorer/documentListTreeItem.test.ts +++ b/src/test/suite/explorer/documentListTreeItem.test.ts @@ -6,7 +6,7 @@ import type { DataService } from 'mongodb-data-service'; const { contributes } = require('../../../../package.json'); import DocumentListTreeItem, { - COLLECTION_TYPES, + CollectionType, formatDocCount, MAX_DOCUMENTS_VISIBLE, } from '../../../explorer/documentListTreeItem'; @@ -21,7 +21,7 @@ function getTestDocumentListTreeItem( return new DocumentListTreeItem({ collectionName: 'collectionName', databaseName: 'mock_db_name', - type: COLLECTION_TYPES.collection, + type: CollectionType.collection, dataService: dataServiceStub as unknown as DataService, isExpanded: false, maxDocumentsToShow: MAX_DOCUMENTS_VISIBLE, @@ -82,7 +82,7 @@ suite('DocumentListTreeItem Test Suite', () => { test('a "view" type of document list does not show a dropdown', () => { const testDocumentListTreeItem = getTestDocumentListTreeItem({ - type: COLLECTION_TYPES.view, + type: CollectionType.view, }); assert.strictEqual( @@ -181,7 +181,7 @@ suite('DocumentListTreeItem Test Suite', () => { test('it shows a documents icon', () => { const testCollectionViewTreeItem = getTestDocumentListTreeItem({ collectionName: 'mock_collection_name_4', - type: COLLECTION_TYPES.view, + type: CollectionType.view, }); const viewIconPath = testCollectionViewTreeItem.iconPath; @@ -192,7 +192,7 @@ suite('DocumentListTreeItem Test Suite', () => { const testDocumentListTreeItem = getTestDocumentListTreeItem({ collectionName: 'mock_collection_name_4', - type: COLLECTION_TYPES.collection, + type: CollectionType.collection, }); const collectionIconPath = testDocumentListTreeItem.iconPath; diff --git a/src/test/suite/explorer/explorerController.test.ts b/src/test/suite/explorer/explorerController.test.ts index 82e5b44f4..775d7d2bc 100644 --- a/src/test/suite/explorer/explorerController.test.ts +++ b/src/test/suite/explorer/explorerController.test.ts @@ -6,9 +6,9 @@ import { connect, createConnectionAttempt } from 'mongodb-data-service'; import { mongoLogId } from 'mongodb-log-writer'; import { - DEFAULT_SAVING_LOCATIONS, - SECRET_STORAGE_LOCATIONS, - STORAGE_LOCATIONS, + DefaultSavingLocation, + SecretStorageLocation, + StorageLocation, } from '../../../storage/storageController'; import { mdbTestExtension } from '../stubbableMdbExtension'; import { TEST_DATABASE_URI } from '../dbTestHelper'; @@ -31,7 +31,7 @@ suite('Explorer Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DEFAULT_SAVING_LOCATIONS['Session Only'], + DefaultSavingLocation['Session Only'], ); sandbox.stub(vscode.window, 'showInformationMessage'); sandbox.stub(vscode.window, 'showErrorMessage'); @@ -47,7 +47,7 @@ suite('Explorer Controller Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DEFAULT_SAVING_LOCATIONS.Workspace, + DefaultSavingLocation.Workspace, ); // Reset our connections. await mdbTestExtension.testExtensionController._connectionController.disconnect(); @@ -68,8 +68,8 @@ suite('Explorer Controller Test Suite', function () { id: 'testConnectionId', connectionOptions: { connectionString: 'mongodb://localhost' }, name: 'testConnectionName', - storageLocation: STORAGE_LOCATIONS.NONE, - secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, + storageLocation: StorageLocation.NONE, + secretStorageLocation: SecretStorageLocation.SecretStorage, }, }; testConnectionController._connectionAttempt = createConnectionAttempt({ @@ -213,8 +213,8 @@ suite('Explorer Controller Test Suite', function () { testConnectionController._connections[connectionId].connectionOptions, name: 'aaa', id: 'aaa', - storageLocation: STORAGE_LOCATIONS.WORKSPACE, - secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, + storageLocation: StorageLocation.WORKSPACE, + secretStorageLocation: SecretStorageLocation.SecretStorage, }; testConnectionController._connections.zzz = { @@ -222,8 +222,8 @@ suite('Explorer Controller Test Suite', function () { testConnectionController._connections[connectionId].connectionOptions, name: 'zzz', id: 'zzz', - storageLocation: STORAGE_LOCATIONS.WORKSPACE, - secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, + storageLocation: StorageLocation.WORKSPACE, + secretStorageLocation: SecretStorageLocation.SecretStorage, }; const connectionsItems = await treeController.getChildren(); diff --git a/src/test/suite/explorer/indexTreeItem.test.ts b/src/test/suite/explorer/indexTreeItem.test.ts index 2f834cecb..c440ca33e 100644 --- a/src/test/suite/explorer/indexTreeItem.test.ts +++ b/src/test/suite/explorer/indexTreeItem.test.ts @@ -2,7 +2,7 @@ import assert from 'assert'; import IndexTreeItem, { IndexFieldTreeItem, - INDEX_KEY_TYPES, + IndexKeyType, } from '../../../explorer/indexTreeItem'; import type * as vscode from 'vscode'; @@ -33,7 +33,7 @@ suite('IndexTreeItem Test Suite', () => { test('it has an icon for the index type', () => { const testIndexFieldTreeItem = new IndexFieldTreeItem({ indexKey: 'locations', - indexKeyType: INDEX_KEY_TYPES.GEOSPHERE, + indexKeyType: IndexKeyType.GEOSPHERE, }); const iconPath = testIndexFieldTreeItem.iconPath as { diff --git a/src/test/suite/extension.test.ts b/src/test/suite/extension.test.ts index a321d58b9..442193bfc 100644 --- a/src/test/suite/extension.test.ts +++ b/src/test/suite/extension.test.ts @@ -1,6 +1,6 @@ import assert from 'assert'; import * as vscode from 'vscode'; -import EXTENSION_COMMANDS from '../../commands'; +import ExtensionCommand from '../../commands'; // eslint-disable-next-line @typescript-eslint/no-var-requires const { contributes } = require('../../../package.json'); @@ -63,7 +63,7 @@ suite('Extension Test Suite', () => { // Editor commands. 'mdb.codeLens.showMoreDocumentsClicked', - ...Object.values(EXTENSION_COMMANDS), + ...Object.values(ExtensionCommand), ]; for (const expectedCommand of expectedCommands) { diff --git a/src/test/suite/language/mongoDBService.test.ts b/src/test/suite/language/mongoDBService.test.ts index a44a8c47b..6ab7c6a97 100644 --- a/src/test/suite/language/mongoDBService.test.ts +++ b/src/test/suite/language/mongoDBService.test.ts @@ -21,8 +21,8 @@ import MongoDBService, { } from '../../../language/mongoDBService'; import { mdbTestExtension } from '../stubbableMdbExtension'; import { StreamStub } from '../stubs'; -import DIAGNOSTIC_CODES from '../../../language/diagnosticCodes'; -import { SERVER_COMMANDS } from '../../../language/serverCommands'; +import DiagnosticCode from '../../../language/diagnosticCodes'; +import { ServerCommand } from '../../../language/serverCommands'; import LINKS from '../../../utils/links'; import Sinon from 'sinon'; @@ -2965,7 +2965,7 @@ suite('MongoDBService Test Suite', () => { consoleOutputs = []; Sinon.stub(connection, 'sendNotification') - .withArgs(SERVER_COMMANDS.SHOW_CONSOLE_OUTPUT) + .withArgs(ServerCommand.SHOW_CONSOLE_OUTPUT) .callsFake((_, params) => Promise.resolve(void consoleOutputs.push(...params)), ); @@ -3105,7 +3105,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 3 }, @@ -3124,7 +3124,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 8 }, @@ -3143,7 +3143,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 8 }, @@ -3162,7 +3162,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 10 }, @@ -3181,7 +3181,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 10 }, @@ -3200,7 +3200,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 14 }, @@ -3219,7 +3219,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 8 }, @@ -3238,7 +3238,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 16 }, @@ -3257,7 +3257,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 11 }, @@ -3276,7 +3276,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 12 }, @@ -3295,7 +3295,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 10 }, @@ -3314,7 +3314,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 10 }, @@ -3333,7 +3333,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 9 }, @@ -3352,7 +3352,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 8 }, @@ -3371,7 +3371,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 8 }, @@ -3390,7 +3390,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 17 }, @@ -3409,7 +3409,7 @@ suite('MongoDBService Test Suite', () => { { severity: DiagnosticSeverity.Error, source: 'mongodb', - code: DIAGNOSTIC_CODES.invalidInteractiveSyntaxes, + code: DiagnosticCode.invalidInteractiveSyntaxes, range: { start: { line: 0, character: 0 }, end: { line: 0, character: 26 }, diff --git a/src/test/suite/mdbExtensionController.test.ts b/src/test/suite/mdbExtensionController.test.ts index 0f32d0ffe..727126553 100644 --- a/src/test/suite/mdbExtensionController.test.ts +++ b/src/test/suite/mdbExtensionController.test.ts @@ -15,21 +15,21 @@ import { SchemaTreeItem, StreamProcessorTreeItem, } from '../../explorer'; -import EXTENSION_COMMANDS, { type ExtensionCommand } from '../../commands'; +import { ExtensionCommand } from '../../commands'; import FieldTreeItem from '../../explorer/fieldTreeItem'; import IndexListTreeItem from '../../explorer/indexListTreeItem'; import { mdbTestExtension } from './stubbableMdbExtension'; import { mockTextEditor } from './stubs'; import { - STORAGE_LOCATIONS, - SECRET_STORAGE_LOCATIONS, - STORAGE_VARIABLES, + StorageLocation, + SecretStorageLocation, + StorageVariable, } from '../../storage/storageController'; import { VIEW_COLLECTION_SCHEME } from '../../editors/collectionDocumentsProvider'; import type { CollectionDetailsType } from '../../explorer/collectionTreeItem'; import { expect } from 'chai'; import { DeepLinkTelemetryEvent } from '../../telemetry'; -import { COLLECTION_TYPES } from '../../explorer/documentListTreeItem'; +import { CollectionType } from '../../explorer/documentListTreeItem'; import { DEEP_LINK_ALLOWED_COMMANDS, DEEP_LINK_DISALLOWED_COMMANDS, @@ -59,7 +59,7 @@ function getTestCollectionTreeItem( return new CollectionTreeItem({ collection: { name: 'testColName', - type: COLLECTION_TYPES.collection, + type: CollectionType.collection, } as unknown as CollectionDetailsType, databaseName: 'testDbName', dataService: {} as DataService, @@ -160,7 +160,7 @@ suite('MDBExtensionController Test Suite', function () { }); test('allowed and disallowed lists are complete', () => { - const allCommands = new Set(Object.values(EXTENSION_COMMANDS)); + const allCommands = new Set(Object.values(ExtensionCommand)); const allowedSet = new Set( DEEP_LINK_ALLOWED_COMMANDS as readonly ExtensionCommand[], ); @@ -178,7 +178,7 @@ suite('MDBExtensionController Test Suite', function () { ); expect(extra).to.deep.equal( [], - `Commands in allowed/disallowed lists but not in EXTENSION_COMMANDS: ${extra.join(', ')}`, + `Commands in allowed/disallowed lists but not in ExtensionCommand: ${extra.join(', ')}`, ); }); }); @@ -764,7 +764,7 @@ suite('MDBExtensionController Test Suite', function () { const testCollectionTreeItem = getTestCollectionTreeItem({ collection: { name: 'doesntExistColName', - type: COLLECTION_TYPES.collection, + type: CollectionType.collection, } as unknown as CollectionDetailsType, dataService: testConnectionController.getActiveDataService() ?? undefined, @@ -795,7 +795,7 @@ suite('MDBExtensionController Test Suite', function () { const testCollectionTreeItem = getTestCollectionTreeItem({ collection: { name: 'orange', - type: COLLECTION_TYPES.collection, + type: CollectionType.collection, } as unknown as CollectionDetailsType, }); const inputBoxResolvesStub = sandbox.stub(); @@ -904,8 +904,8 @@ suite('MDBExtensionController Test Suite', function () { id: 'blueBerryPancakesAndTheSmellOfBacon', connectionOptions: { connectionString: 'mongodb://localhost' }, name: 'NAAAME', - storageLocation: STORAGE_LOCATIONS.NONE, - secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, + storageLocation: StorageLocation.NONE, + secretStorageLocation: SecretStorageLocation.SecretStorage, }; const testTreeItem = getTestConnectionTreeItem({ @@ -935,8 +935,8 @@ suite('MDBExtensionController Test Suite', function () { id: 'blueBerryPancakesAndTheSmellOfBacon', name: 'NAAAME', connectionOptions: { connectionString: 'mongodb://localhost' }, - storageLocation: STORAGE_LOCATIONS.NONE, - secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, + storageLocation: StorageLocation.NONE, + secretStorageLocation: SecretStorageLocation.SecretStorage, }; const testTreeItem = getTestConnectionTreeItem({ @@ -1357,7 +1357,7 @@ suite('MDBExtensionController Test Suite', function () { const collectionTreeItem = getTestCollectionTreeItem({ collection: { name: 'pineapple', - type: COLLECTION_TYPES.collection, + type: CollectionType.collection, } as unknown as CollectionDetailsType, databaseName: 'plants', }); @@ -1682,7 +1682,7 @@ suite('MDBExtensionController Test Suite', function () { ); assert.strictEqual( executeCommandStub.firstCall.args[0], - EXTENSION_COMMANDS.MDB_OPEN_OVERVIEW_PAGE, + ExtensionCommand.MDB_OPEN_OVERVIEW_PAGE, ); }); @@ -1690,7 +1690,7 @@ suite('MDBExtensionController Test Suite', function () { assert(fakeUpdate.called); assert.strictEqual( fakeUpdate.firstCall.args[0], - STORAGE_VARIABLES.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, + StorageVariable.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, ); assert.strictEqual( fakeUpdate.firstCall.args[0], @@ -1735,7 +1735,7 @@ suite('MDBExtensionController Test Suite', function () { assert(fakeUpdate.called); assert.strictEqual( fakeUpdate.firstCall.args[0], - STORAGE_VARIABLES.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, + StorageVariable.GLOBAL_HAS_BEEN_SHOWN_INITIAL_VIEW, ); assert.strictEqual( fakeUpdate.firstCall.args[0], diff --git a/src/test/suite/participant/participant.test.ts b/src/test/suite/participant/participant.test.ts index d7bced565..5287e813d 100644 --- a/src/test/suite/participant/participant.test.ts +++ b/src/test/suite/participant/participant.test.ts @@ -23,8 +23,8 @@ import { TEST_DATABASE_URI } from '../dbTestHelper'; import type { ChatResult } from '../../../participant/constants'; import { CHAT_PARTICIPANT_ID } from '../../../participant/constants'; import { - SECRET_STORAGE_LOCATIONS, - STORAGE_LOCATIONS, + SecretStorageLocation, + StorageLocation, } from '../../../storage/storageController'; import type { LoadedConnection } from '../../../storage/connectionStorage'; import { ChatMetadataStore } from '../../../participant/chatMetadata'; @@ -32,9 +32,9 @@ import { getFullRange } from '../suggestTestHelpers'; import { isPlayground } from '../../../utils/playground'; import { Prompts } from '../../../participant/prompts'; import { createMarkdownLink } from '../../../participant/markdown'; -import EXTENSION_COMMANDS from '../../../commands'; +import ExtensionCommand from '../../../commands'; import { getContentLength } from '../../../participant/prompts/promptBase'; -import { PARTICIPANT_ERROR_TYPES } from '../../../participant/participantErrorTypes'; +import { ParticipantErrorType } from '../../../participant/participantErrorTypes'; import * as model from '../../../participant/model'; import { createChatRequestTurn, @@ -48,7 +48,7 @@ import type { SendMessageToParticipantOptions, } from '../../../participant/participantTypes'; import { TelemetryService } from '../../../telemetry'; -import { DOCUMENT_SOURCE } from '../../../documentSource'; +import { DocumentSource } from '../../../documentSource'; // The Copilot's model in not available in tests, // therefore we need to mock its methods and returning values. @@ -57,8 +57,8 @@ const MAX_TOTAL_PROMPT_LENGTH_MOCK = 16000; const loadedConnection = { id: 'id', name: 'localhost', - storageLocation: STORAGE_LOCATIONS.NONE, - secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, + storageLocation: StorageLocation.NONE, + secretStorageLocation: SecretStorageLocation.SecretStorage, connectionOptions: { connectionString: 'mongodb://localhost' }, }; @@ -1942,7 +1942,7 @@ Schema: message: `I want to ask questions about the \`${mockDatabaseItem.databaseName}\` database.`, isNewChat: true, telemetry: { - source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW, + source: DocumentSource.DocumentSource_TREEVIEW, source_details: 'database', }, }, @@ -1973,7 +1973,7 @@ Schema: message: `I want to ask questions about the \`${mockCollectionItem.databaseName}\` database's \`${mockCollectionItem.collectionName}\` collection.`, isNewChat: true, telemetry: { - source: DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW, + source: DocumentSource.DocumentSource_TREEVIEW, source_details: 'collection', }, }, @@ -2566,12 +2566,12 @@ Schema: `Looks like you aren't currently connected, first let's get you connected to the cluster we'd like to create this query to run against. ${createMarkdownLink({ - commandId: EXTENSION_COMMANDS.CONNECT_WITH_PARTICIPANT, + commandId: ExtensionCommand.CONNECT_WITH_PARTICIPANT, name: 'localhost', data: {}, })} ${createMarkdownLink({ - commandId: EXTENSION_COMMANDS.CONNECT_WITH_PARTICIPANT, + commandId: ExtensionCommand.CONNECT_WITH_PARTICIPANT, name: 'atlas', data: {}, })}`, @@ -2638,7 +2638,7 @@ Schema: createChatResponseTurn('/query', undefined, { result: { errorDetails: { - message: PARTICIPANT_ERROR_TYPES.FILTERED, + message: ParticipantErrorType.FILTERED, }, metadata: {}, }, diff --git a/src/test/suite/storage/connectionStorage.test.ts b/src/test/suite/storage/connectionStorage.test.ts index 9b5b49385..2a02fa007 100644 --- a/src/test/suite/storage/connectionStorage.test.ts +++ b/src/test/suite/storage/connectionStorage.test.ts @@ -5,12 +5,12 @@ import { expect } from 'chai'; import { StorageController, - STORAGE_VARIABLES, - STORAGE_LOCATIONS, + StorageVariable, + StorageLocation, } from '../../../storage'; import { - DEFAULT_SAVING_LOCATIONS, - SECRET_STORAGE_LOCATIONS, + DefaultSavingLocation, + SecretStorageLocation, } from '../../../storage/storageController'; import { ExtensionContextStub } from '../stubs'; import { @@ -69,10 +69,7 @@ suite('Connection Storage Test Suite', function () { test('it loads both global and workspace stored connections', async () => { await vscode.workspace .getConfiguration('mdb.connectionSaving') - .update( - 'defaultConnectionSavingLocation', - DEFAULT_SAVING_LOCATIONS.Global, - ); + .update('defaultConnectionSavingLocation', DefaultSavingLocation.Global); await testConnectionStorage.saveConnection( newTestConnection(testConnectionStorage, '1'), @@ -84,7 +81,7 @@ suite('Connection Storage Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DEFAULT_SAVING_LOCATIONS.Workspace, + DefaultSavingLocation.Workspace, ); await testConnectionStorage.saveConnection( @@ -110,18 +107,15 @@ suite('Connection Storage Test Suite', function () { test('when a connection is added it is saved to the global storage', async () => { await vscode.workspace .getConfiguration('mdb.connectionSaving') - .update( - 'defaultConnectionSavingLocation', - DEFAULT_SAVING_LOCATIONS.Global, - ); + .update('defaultConnectionSavingLocation', DefaultSavingLocation.Global); await testConnectionStorage.saveConnection( newTestConnection(testConnectionStorage, '1'), ); const globalStoreConnections = testStorageController.get( - STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.GLOBAL, + StorageVariable.GLOBAL_SAVED_CONNECTIONS, + StorageLocation.GLOBAL, ); expect(Object.keys(globalStoreConnections).length).to.equal(1); @@ -133,7 +127,7 @@ suite('Connection Storage Test Suite', function () { ); const workspaceStoreConnections = testStorageController.get( - STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, + StorageVariable.WORKSPACE_SAVED_CONNECTIONS, ); expect(workspaceStoreConnections).to.equal(undefined); @@ -144,15 +138,15 @@ suite('Connection Storage Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DEFAULT_SAVING_LOCATIONS.Workspace, + DefaultSavingLocation.Workspace, ); await testConnectionStorage.saveConnection( newTestConnection(testConnectionStorage, '1'), ); const workspaceStoreConnections = testStorageController.get( - STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.WORKSPACE, + StorageVariable.WORKSPACE_SAVED_CONNECTIONS, + StorageLocation.WORKSPACE, ); expect(Object.keys(workspaceStoreConnections).length).to.equal(1); @@ -164,8 +158,8 @@ suite('Connection Storage Test Suite', function () { ); const globalStoreConnections = testStorageController.get( - STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.GLOBAL, + StorageVariable.GLOBAL_SAVED_CONNECTIONS, + StorageLocation.GLOBAL, ); expect(globalStoreConnections).to.equal(undefined); @@ -177,7 +171,7 @@ suite('Connection Storage Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DEFAULT_SAVING_LOCATIONS['Session Only'], + DefaultSavingLocation['Session Only'], ); await testConnectionStorage.saveConnection( newTestConnection(testConnectionStorage, '1'), @@ -185,15 +179,15 @@ suite('Connection Storage Test Suite', function () { const objectString = JSON.stringify(undefined); const globalStoreConnections = testStorageController.get( - STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.GLOBAL, + StorageVariable.GLOBAL_SAVED_CONNECTIONS, + StorageLocation.GLOBAL, ); expect(JSON.stringify(globalStoreConnections)).to.equal(objectString); const workspaceStoreConnections = testStorageController.get( - STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.WORKSPACE, + StorageVariable.WORKSPACE_SAVED_CONNECTIONS, + StorageLocation.WORKSPACE, ); expect(JSON.stringify(workspaceStoreConnections)).to.equal(objectString); @@ -204,7 +198,7 @@ suite('Connection Storage Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DEFAULT_SAVING_LOCATIONS.Workspace, + DefaultSavingLocation.Workspace, ); const connectionId = 'pie'; await testConnectionStorage.saveConnection( @@ -212,8 +206,8 @@ suite('Connection Storage Test Suite', function () { ); const workspaceStoreConnections = testStorageController.get( - STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.WORKSPACE, + StorageVariable.WORKSPACE_SAVED_CONNECTIONS, + StorageLocation.WORKSPACE, ); expect(Object.keys(workspaceStoreConnections).length).to.equal(1); @@ -221,8 +215,8 @@ suite('Connection Storage Test Suite', function () { await testConnectionStorage.removeConnection(connectionId); const postWorkspaceStoreConnections = testStorageController.get( - STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.WORKSPACE, + StorageVariable.WORKSPACE_SAVED_CONNECTIONS, + StorageLocation.WORKSPACE, ); expect(Object.keys(postWorkspaceStoreConnections).length).to.equal(0); }); @@ -230,18 +224,15 @@ suite('Connection Storage Test Suite', function () { test('when a connection is removed it is also removed from global storage', async () => { await vscode.workspace .getConfiguration('mdb.connectionSaving') - .update( - 'defaultConnectionSavingLocation', - DEFAULT_SAVING_LOCATIONS.Global, - ); + .update('defaultConnectionSavingLocation', DefaultSavingLocation.Global); const connectionId = 'pineapple'; await testConnectionStorage.saveConnection( newTestConnection(testConnectionStorage, connectionId), ); const globalStoreConnections = testStorageController.get( - STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.GLOBAL, + StorageVariable.GLOBAL_SAVED_CONNECTIONS, + StorageLocation.GLOBAL, ); expect(Object.keys(globalStoreConnections).length).to.equal(1); @@ -249,8 +240,8 @@ suite('Connection Storage Test Suite', function () { await testConnectionStorage.removeConnection(connectionId); const postGlobalStoreConnections = testStorageController.get( - STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.GLOBAL, + StorageVariable.GLOBAL_SAVED_CONNECTIONS, + StorageLocation.GLOBAL, ); expect(Object.keys(postGlobalStoreConnections).length).to.equal(0); @@ -275,7 +266,7 @@ suite('Connection Storage Test Suite', function () { const oldSavedConnectionInfo = { id: '1d700f37-ba57-4568-9552-0ea23effea89', name: 'localhost:27017', - storageLocation: STORAGE_LOCATIONS.GLOBAL, + storageLocation: StorageLocation.GLOBAL, connectionModel: { _id: '4', isFavorite: false, @@ -307,8 +298,8 @@ suite('Connection Storage Test Suite', function () { const connectionInfo = { id: '1d700f37-ba57-4568-9552-0ea23effea89', name: 'localhost:27017', - storageLocation: STORAGE_LOCATIONS.GLOBAL, - secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, + storageLocation: StorageLocation.GLOBAL, + secretStorageLocation: SecretStorageLocation.SecretStorage, connectionOptions: { connectionString: 'mongodb://localhost:27017/?readPreference=primary&ssl=false', @@ -487,7 +478,7 @@ suite('Connection Storage Test Suite', function () { expect( savedConnections.every( ({ secretStorageLocation }) => - secretStorageLocation === SECRET_STORAGE_LOCATIONS.SecretStorage, + secretStorageLocation === SecretStorageLocation.SecretStorage, ), ).to.equal(true); @@ -503,7 +494,7 @@ suite('Connection Storage Test Suite', function () { id: 'random-connection-4', name: 'localhost:27089', storageLocation: 'GLOBAL', - secretStorageLocation: SECRET_STORAGE_LOCATIONS.SecretStorage, + secretStorageLocation: SecretStorageLocation.SecretStorage, connectionOptions: { connectionString: 'mongodb://localhost:27080/?readPreference=primary&ssl=false', @@ -511,8 +502,8 @@ suite('Connection Storage Test Suite', function () { }; testSandbox.replace(testStorageController, 'get', (key, storage) => { if ( - storage === STORAGE_LOCATIONS.WORKSPACE || - key === STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS + storage === StorageLocation.WORKSPACE || + key === StorageVariable.WORKSPACE_SAVED_CONNECTIONS ) { return {}; } @@ -522,7 +513,7 @@ suite('Connection Storage Test Suite', function () { id: 'random-connection-1', name: 'localhost:27017', storageLocation: 'GLOBAL', - secretStorageLocation: SECRET_STORAGE_LOCATIONS.Keytar, + secretStorageLocation: SecretStorageLocation.Keytar, connectionOptions: { connectionString: 'mongodb://localhost:27017/?readPreference=primary&ssl=false', @@ -532,7 +523,7 @@ suite('Connection Storage Test Suite', function () { id: 'random-connection-2', name: 'localhost:27017', storageLocation: 'GLOBAL', - secretStorageLocation: SECRET_STORAGE_LOCATIONS.KeytarSecondAttempt, + secretStorageLocation: SecretStorageLocation.KeytarSecondAttempt, connectionOptions: { connectionString: 'mongodb://localhost:27017/?readPreference=primary&ssl=false', @@ -564,7 +555,7 @@ suite('Connection Storage Test Suite', function () { .getConfiguration('mdb.connectionSaving') .update( 'defaultConnectionSavingLocation', - DEFAULT_SAVING_LOCATIONS.Workspace, + DefaultSavingLocation.Workspace, ); await testConnectionStorage.saveConnection( diff --git a/src/test/suite/storage/storageController.test.ts b/src/test/suite/storage/storageController.test.ts index 1cb621e15..b86db7ee5 100644 --- a/src/test/suite/storage/storageController.test.ts +++ b/src/test/suite/storage/storageController.test.ts @@ -1,8 +1,8 @@ import assert from 'assert'; import StorageController, { - STORAGE_VARIABLES, - STORAGE_LOCATIONS, + StorageVariable, + StorageLocation, } from '../../../storage/storageController'; import { ExtensionContextStub } from '../stubs'; @@ -10,14 +10,14 @@ suite('Storage Controller Test Suite', () => { test('getting a variable gets it from the global context store', () => { const extensionContextStub = new ExtensionContextStub(); extensionContextStub._globalState = { - [STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS]: { + [StorageVariable.GLOBAL_SAVED_CONNECTIONS]: { collOne: { name: 'this_gonna_get_saved' }, }, }; const testStorageController = new StorageController(extensionContextStub); const testVal = testStorageController.get( - STORAGE_VARIABLES.GLOBAL_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.GLOBAL, + StorageVariable.GLOBAL_SAVED_CONNECTIONS, + StorageLocation.GLOBAL, ); assert( testVal.collOne.name === 'this_gonna_get_saved', @@ -28,14 +28,14 @@ suite('Storage Controller Test Suite', () => { test('getting a variable from the workspace state gets it from the workspace context store', () => { const extensionContextStub = new ExtensionContextStub(); extensionContextStub._workspaceState = { - [STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS]: { + [StorageVariable.WORKSPACE_SAVED_CONNECTIONS]: { collTwo: { name: 'i_cant_believe_its_gonna_save_this' }, }, }; const testStorageController = new StorageController(extensionContextStub); const testVal = testStorageController.get( - STORAGE_VARIABLES.WORKSPACE_SAVED_CONNECTIONS, - STORAGE_LOCATIONS.WORKSPACE, + StorageVariable.WORKSPACE_SAVED_CONNECTIONS, + StorageLocation.WORKSPACE, ); assert( testVal.collTwo.name === 'i_cant_believe_its_gonna_save_this', @@ -51,7 +51,7 @@ suite('Storage Controller Test Suite', () => { test('getUserIdentity adds anonymousId to the global storage and returns it to telemetry', () => { const userIdentity = testStorageController.getUserIdentity(); const anonymousId = testStorageController.get( - STORAGE_VARIABLES.GLOBAL_ANONYMOUS_ID, + StorageVariable.GLOBAL_ANONYMOUS_ID, ); assert.deepStrictEqual(userIdentity, { anonymousId }); }); diff --git a/src/test/suite/telemetry/telemetryService.test.ts b/src/test/suite/telemetry/telemetryService.test.ts index 955e59b8d..c3f5ab993 100644 --- a/src/test/suite/telemetry/telemetryService.test.ts +++ b/src/test/suite/telemetry/telemetryService.test.ts @@ -9,7 +9,7 @@ import sinon from 'sinon'; import type { SinonSpy } from 'sinon'; import sinonChai from 'sinon-chai'; -import { DOCUMENT_SOURCE } from '../../../documentSource'; +import { DocumentSource } from '../../../documentSource'; import { mdbTestExtension } from '../stubbableMdbExtension'; import { DatabaseTreeItem, DocumentTreeItem } from '../../../explorer'; import { DataServiceStub } from '../stubs'; @@ -218,7 +218,7 @@ suite('Telemetry Controller Test Suite', () => { }); test('track document saved form a tree-view event', () => { - const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_TREEVIEW; + const source = DocumentSource.DocumentSource_TREEVIEW; testTelemetryService.track( new DocumentUpdatedTelemetryEvent(source, true), ); @@ -237,7 +237,7 @@ suite('Telemetry Controller Test Suite', () => { }); test('track document opened form playground results', () => { - const source = DOCUMENT_SOURCE.DOCUMENT_SOURCE_PLAYGROUND; + const source = DocumentSource.DocumentSource_PLAYGROUND; testTelemetryService.track(new DocumentEditedTelemetryEvent(source)); sandbox.assert.calledWith( fakeSegmentAnalyticsTrack, @@ -556,7 +556,7 @@ suite('Telemetry Controller Test Suite', () => { loaded_connections: 3, preset_connections: 3, connections_with_secrets_in_keytar: 0, - connections_with_secrets_in_secret_storage: 3, + connections_with_secrets_in_SecretStorage: 3, }, }), ); diff --git a/src/views/webviewController.ts b/src/views/webviewController.ts index a337f7980..3b96677eb 100644 --- a/src/views/webviewController.ts +++ b/src/views/webviewController.ts @@ -6,7 +6,7 @@ import type { ConnectionOptions } from 'mongodb-data-service'; import type ConnectionController from '../connectionController'; import { CONNECTION_TYPES } from '../connectionController'; import { createLogger } from '../logging'; -import EXTENSION_COMMANDS from '../commands'; +import ExtensionCommand from '../commands'; import type { MessageFromWebviewToExtension } from './webview-app/extension-app-message-constants'; import { MESSAGE_TYPES, @@ -263,7 +263,7 @@ export default class WebviewController { return; case MESSAGE_TYPES.CREATE_NEW_PLAYGROUND: void vscode.commands.executeCommand( - EXTENSION_COMMANDS.MDB_CREATE_PLAYGROUND_FROM_OVERVIEW_PAGE, + ExtensionCommand.MDB_CREATE_PLAYGROUND_FROM_OVERVIEW_PAGE, ); return; case MESSAGE_TYPES.CONNECTION_FORM_OPENED: @@ -281,7 +281,7 @@ export default class WebviewController { return; case MESSAGE_TYPES.OPEN_CONNECTION_STRING_INPUT: void vscode.commands.executeCommand( - EXTENSION_COMMANDS.MDB_CONNECT_WITH_URI, + ExtensionCommand.MDB_CONNECT_WITH_URI, ); return; case MESSAGE_TYPES.OPEN_TRUSTED_LINK: From 0f0c687667542d55123cc638888a41fe5a9b5404 Mon Sep 17 00:00:00 2001 From: gagik Date: Fri, 12 Dec 2025 17:07:39 +0100 Subject: [PATCH 8/9] chore: messagetypes --- .../views/webview-app/atlas-cta.test.tsx | 8 ++--- .../views/webview-app/connect-helper.test.tsx | 4 +-- .../webview-app/connection-status.test.tsx | 16 ++++----- .../views/webview-app/overview-page.test.tsx | 19 +++++----- .../webview-app/resources-panel.test.tsx | 8 ++--- .../suite/views/webviewController.test.ts | 22 ++++++------ .../extension-app-message-constants.ts | 34 +++++++++--------- src/views/webview-app/overview-page.tsx | 4 +-- src/views/webview-app/use-connection-form.ts | 6 ++-- .../webview-app/use-connection-status.ts | 6 ++-- .../use-detect-vscode-dark-mode.tsx | 4 +-- src/views/webview-app/vscode-api.ts | 22 ++++++------ src/views/webviewController.ts | 36 +++++++++---------- 13 files changed, 94 insertions(+), 95 deletions(-) diff --git a/src/test/suite/views/webview-app/atlas-cta.test.tsx b/src/test/suite/views/webview-app/atlas-cta.test.tsx index f6e4cf40b..a15496bef 100644 --- a/src/test/suite/views/webview-app/atlas-cta.test.tsx +++ b/src/test/suite/views/webview-app/atlas-cta.test.tsx @@ -4,7 +4,7 @@ import AtlasCta from '../../../../views/webview-app/atlas-cta'; import { expect } from 'chai'; import Sinon from 'sinon'; import vscode from '../../../../views/webview-app/vscode-api'; -import { MESSAGE_TYPES } from '../../../../views/webview-app/extension-app-message-constants'; +import { MessageType } from '../../../../views/webview-app/extension-app-message-constants'; describe('AtlasCta test suite', function () { afterEach(function () { @@ -23,7 +23,7 @@ describe('AtlasCta test suite', function () { render(); screen.getByTestId('link-atlas').click(); expect(postMessageStub).to.be.calledWithExactly({ - command: MESSAGE_TYPES.EXTENSION_LINK_CLICKED, + command: MessageType.EXTENSION_LINK_CLICKED, screen: 'overviewPage', linkId: 'atlasLanding', }); @@ -35,10 +35,10 @@ describe('AtlasCta test suite', function () { screen.getByText('Create free cluster').click(); expect(postMessageStub).calledTwice; expect(postMessageStub.firstCall.args[0].command).to.equal( - MESSAGE_TYPES.OPEN_TRUSTED_LINK, + MessageType.OPEN_TRUSTED_LINK, ); expect(postMessageStub.secondCall.args[0].command).to.equal( - MESSAGE_TYPES.EXTENSION_LINK_CLICKED, + MessageType.EXTENSION_LINK_CLICKED, ); }); }); diff --git a/src/test/suite/views/webview-app/connect-helper.test.tsx b/src/test/suite/views/webview-app/connect-helper.test.tsx index b3318fb20..ac5a7a3e2 100644 --- a/src/test/suite/views/webview-app/connect-helper.test.tsx +++ b/src/test/suite/views/webview-app/connect-helper.test.tsx @@ -4,7 +4,7 @@ import { render, screen } from '@testing-library/react'; import ConnectHelper from '../../../../views/webview-app/connect-helper'; import Sinon from 'sinon'; import vscode from '../../../../views/webview-app/vscode-api'; -import { MESSAGE_TYPES } from '../../../../views/webview-app/extension-app-message-constants'; +import { MessageType } from '../../../../views/webview-app/extension-app-message-constants'; describe('ConnectHelper test suite', function () { it('when rendered it should show both connection options', function () { @@ -31,7 +31,7 @@ describe('ConnectHelper test suite', function () { ); screen.getByLabelText('Connect with connection string').click(); expect(postMessageStub).to.have.been.calledWithExactly({ - command: MESSAGE_TYPES.OPEN_CONNECTION_STRING_INPUT, + command: MessageType.OPEN_CONNECTION_STRING_INPUT, }); }); }); diff --git a/src/test/suite/views/webview-app/connection-status.test.tsx b/src/test/suite/views/webview-app/connection-status.test.tsx index 85a75bc85..5d953fce0 100644 --- a/src/test/suite/views/webview-app/connection-status.test.tsx +++ b/src/test/suite/views/webview-app/connection-status.test.tsx @@ -5,7 +5,7 @@ import { act, cleanup, render, screen } from '@testing-library/react'; import ConnectionStatus from '../../../../views/webview-app/connection-status'; import { CONNECTION_STATUS, - MESSAGE_TYPES, + MessageType, } from '../../../../views/webview-app/extension-app-message-constants'; import vscode from '../../../../views/webview-app/vscode-api'; @@ -24,7 +24,7 @@ describe('ConnectionStatus test suite', function () { const postMessageStub = Sinon.stub(vscode, 'postMessage'); render(); expect(postMessageStub).to.have.been.calledWithExactly({ - command: MESSAGE_TYPES.GET_CONNECTION_STATUS, + command: MessageType.GET_CONNECTION_STATUS, }); }); @@ -35,7 +35,7 @@ describe('ConnectionStatus test suite', function () { window.dispatchEvent( new MessageEvent('message', { data: { - command: MESSAGE_TYPES.CONNECTION_STATUS_MESSAGE, + command: MessageType.CONNECTION_STATUS_MESSAGE, connectionStatus: CONNECTION_STATUS.DISCONNECTING, activeConnectionName: '', }, @@ -53,7 +53,7 @@ describe('ConnectionStatus test suite', function () { window.dispatchEvent( new MessageEvent('message', { data: { - command: MESSAGE_TYPES.CONNECTION_STATUS_MESSAGE, + command: MessageType.CONNECTION_STATUS_MESSAGE, connectionStatus: CONNECTION_STATUS.DISCONNECTED, activeConnectionName: '', }, @@ -71,7 +71,7 @@ describe('ConnectionStatus test suite', function () { window.dispatchEvent( new MessageEvent('message', { data: { - command: MESSAGE_TYPES.CONNECTION_STATUS_MESSAGE, + command: MessageType.CONNECTION_STATUS_MESSAGE, connectionStatus: CONNECTION_STATUS.CONNECTING, activeConnectionName: '', }, @@ -89,7 +89,7 @@ describe('ConnectionStatus test suite', function () { window.dispatchEvent( new MessageEvent('message', { data: { - command: MESSAGE_TYPES.CONNECTION_STATUS_MESSAGE, + command: MessageType.CONNECTION_STATUS_MESSAGE, connectionStatus: CONNECTION_STATUS.CONNECTED, activeConnectionName: 'vscode-connection', }, @@ -108,7 +108,7 @@ describe('ConnectionStatus test suite', function () { screen.getByLabelText('Rename connection').click(); expect(postMessageStub).to.be.calledWithExactly({ - command: MESSAGE_TYPES.RENAME_ACTIVE_CONNECTION, + command: MessageType.RENAME_ACTIVE_CONNECTION, }); }); @@ -117,7 +117,7 @@ describe('ConnectionStatus test suite', function () { screen.getByLabelText('Create playground').click(); expect(postMessageStub).to.be.calledWithExactly({ - command: MESSAGE_TYPES.CREATE_NEW_PLAYGROUND, + command: MessageType.CREATE_NEW_PLAYGROUND, }); }); }); diff --git a/src/test/suite/views/webview-app/overview-page.test.tsx b/src/test/suite/views/webview-app/overview-page.test.tsx index 10901a3a8..6f68b8813 100644 --- a/src/test/suite/views/webview-app/overview-page.test.tsx +++ b/src/test/suite/views/webview-app/overview-page.test.tsx @@ -7,7 +7,7 @@ import userEvent from '@testing-library/user-event'; import OverviewPage from '../../../../views/webview-app/overview-page'; import vscode from '../../../../views/webview-app/vscode-api'; import type { MessageFromWebviewToExtension } from '../../../../views/webview-app/extension-app-message-constants'; -import { MESSAGE_TYPES } from '../../../../views/webview-app/extension-app-message-constants'; +import { MessageType } from '../../../../views/webview-app/extension-app-message-constants'; const connectionFormTestId = 'connection-form-modal'; @@ -55,7 +55,7 @@ describe('OverviewPage test suite', function () { expect(screen.getByTestId(connectionFormTestId)).to.exist; const message = postMessageSpy.firstCall.args[0]; expect(message).to.deep.equal({ - command: MESSAGE_TYPES.CONNECTION_FORM_OPENED, + command: MessageType.CONNECTION_FORM_OPENED, }); await userEvent.click(screen.getByLabelText('Close modal')); @@ -72,7 +72,7 @@ describe('OverviewPage test suite', function () { .null; await userEvent.click(screen.getByTestId('connect-button')); const argsWithoutConnectId = postMessageSpy.lastCall.args[0] as any; - expect(argsWithoutConnectId.command).to.equal(MESSAGE_TYPES.CONNECT); + expect(argsWithoutConnectId.command).to.equal(MessageType.CONNECT); expect( argsWithoutConnectId.connectionInfo.connectionOptions.connectionString, ).to.equal('mongodb://localhost:27017'); @@ -90,7 +90,7 @@ describe('OverviewPage test suite', function () { window.dispatchEvent( new MessageEvent('message', { data: { - command: MESSAGE_TYPES.CONNECT_RESULT, + command: MessageType.CONNECT_RESULT, connectionId, connectionSuccess: false, connectionMessage: 'server not found', @@ -113,7 +113,7 @@ describe('OverviewPage test suite', function () { window.dispatchEvent( new MessageEvent('message', { data: { - command: MESSAGE_TYPES.CONNECT_RESULT, + command: MessageType.CONNECT_RESULT, connectionId, connectionSuccess: true, connectionMessage: '', @@ -135,7 +135,7 @@ describe('OverviewPage test suite', function () { window.dispatchEvent( new MessageEvent('message', { data: { - command: MESSAGE_TYPES.OPEN_EDIT_CONNECTION, + command: MessageType.OPEN_EDIT_CONNECTION, connection: { id: 'pear', name: 'pineapple', @@ -160,8 +160,7 @@ describe('OverviewPage test suite', function () { .getCalls() .filter( (call) => - call.args[0].command === - MESSAGE_TYPES.EDIT_CONNECTION_AND_CONNECT, + call.args[0].command === MessageType.EDIT_CONNECTION_AND_CONNECT, ); }; expect(getConnectMessages()).to.have.length(0); @@ -189,7 +188,7 @@ describe('OverviewPage test suite', function () { window.dispatchEvent( new MessageEvent('message', { data: { - command: MESSAGE_TYPES.CONNECT_RESULT, + command: MessageType.CONNECT_RESULT, connectionId: 1, // different from the attempt id generated by our click connectionSuccess: true, connectionMessage: '', @@ -204,7 +203,7 @@ describe('OverviewPage test suite', function () { window.dispatchEvent( new MessageEvent('message', { data: { - command: MESSAGE_TYPES.CONNECT_RESULT, + command: MessageType.CONNECT_RESULT, connectionId: 2, // different from the attempt id generated by our click connectionSuccess: false, connectionMessage: 'something bad happened', diff --git a/src/test/suite/views/webview-app/resources-panel.test.tsx b/src/test/suite/views/webview-app/resources-panel.test.tsx index ff8b4e43f..d1de2a46e 100644 --- a/src/test/suite/views/webview-app/resources-panel.test.tsx +++ b/src/test/suite/views/webview-app/resources-panel.test.tsx @@ -5,7 +5,7 @@ import { cleanup, render, screen } from '@testing-library/react'; import ResourcesPanel, { TELEMETRY_SCREEN_ID, } from '../../../../views/webview-app/resources-panel/panel'; -import { MESSAGE_TYPES } from '../../../../views/webview-app/extension-app-message-constants'; +import { MessageType } from '../../../../views/webview-app/extension-app-message-constants'; import vscode from '../../../../views/webview-app/vscode-api'; describe('Resources panel test suite', function () { @@ -38,7 +38,7 @@ describe('Resources panel test suite', function () { screen.getAllByTestId(/^link-\w+/).forEach((link) => { link.click(); expect(postMessageStub).to.have.been.calledWithExactly({ - command: MESSAGE_TYPES.EXTENSION_LINK_CLICKED, + command: MessageType.EXTENSION_LINK_CLICKED, screen: TELEMETRY_SCREEN_ID, linkId: link.getAttribute('data-testid')?.replace('link-', ''), }); @@ -47,7 +47,7 @@ describe('Resources panel test suite', function () { screen.getAllByTestId(/^footer-feature-\w+/).forEach((link) => { link.click(); expect(postMessageStub).to.have.been.calledWithExactly({ - command: MESSAGE_TYPES.EXTENSION_LINK_CLICKED, + command: MessageType.EXTENSION_LINK_CLICKED, screen: TELEMETRY_SCREEN_ID, linkId: link .getAttribute('data-testid') @@ -58,7 +58,7 @@ describe('Resources panel test suite', function () { screen.getAllByTestId(/^footer-link-\w+/).forEach((link) => { link.click(); expect(postMessageStub).to.have.been.calledWithExactly({ - command: MESSAGE_TYPES.EXTENSION_LINK_CLICKED, + command: MessageType.EXTENSION_LINK_CLICKED, screen: TELEMETRY_SCREEN_ID, linkId: link.getAttribute('data-testid')?.replace('footer-link-', ''), }); diff --git a/src/test/suite/views/webviewController.test.ts b/src/test/suite/views/webviewController.test.ts index a6cdf6ae2..406931092 100644 --- a/src/test/suite/views/webviewController.test.ts +++ b/src/test/suite/views/webviewController.test.ts @@ -7,7 +7,7 @@ import path from 'path'; import ConnectionController from '../../../connectionController'; import { mdbTestExtension } from '../stubbableMdbExtension'; -import { MESSAGE_TYPES } from '../../../views/webview-app/extension-app-message-constants'; +import { MessageType } from '../../../views/webview-app/extension-app-message-constants'; import { StatusView } from '../../../views'; import { StorageController } from '../../../storage'; import { TelemetryService } from '../../../telemetry'; @@ -223,7 +223,7 @@ suite('Webview Test Suite', () => { // Mock a connection call. messageReceived({ - command: MESSAGE_TYPES.CONNECT, + command: MessageType.CONNECT, connectionInfo: { id: 2, connectionOptions: { @@ -264,7 +264,7 @@ suite('Webview Test Suite', () => { // Mock a connection call. messageReceived({ - command: MESSAGE_TYPES.CONNECT, + command: MessageType.CONNECT, connectionInfo: { id: 'pineapple', connectionOptions: { @@ -302,7 +302,7 @@ suite('Webview Test Suite', () => { // Mock a connection call. messageReceived({ - command: MESSAGE_TYPES.CONNECT, + command: MessageType.CONNECT, connectionInfo: { id: 'pineapple', connectionOptions: { @@ -346,7 +346,7 @@ suite('Webview Test Suite', () => { // Mock a connection call. messageReceived({ - command: MESSAGE_TYPES.CONNECT, + command: MessageType.CONNECT, connectionInfo: { id: 'pineapple', connectionOptions: { @@ -384,7 +384,7 @@ suite('Webview Test Suite', () => { ); messageReceived({ - command: MESSAGE_TYPES.OPEN_CONNECTION_STRING_INPUT, + command: MessageType.OPEN_CONNECTION_STRING_INPUT, }); await waitFor(() => { @@ -424,7 +424,7 @@ suite('Webview Test Suite', () => { // Mock a connection status request call. messageReceived({ - command: MESSAGE_TYPES.GET_CONNECTION_STATUS, + command: MessageType.GET_CONNECTION_STATUS, }); }); @@ -459,7 +459,7 @@ suite('Webview Test Suite', () => { .then(() => { // Mock a connection status request call. messageReceived({ - command: MESSAGE_TYPES.GET_CONNECTION_STATUS, + command: MessageType.GET_CONNECTION_STATUS, }); }); }); @@ -498,7 +498,7 @@ suite('Webview Test Suite', () => { // Mock a connection status request call. messageReceived({ - command: MESSAGE_TYPES.RENAME_ACTIVE_CONNECTION, + command: MessageType.RENAME_ACTIVE_CONNECTION, }); expect(mockRenameConnectionOnConnectionController).to.be.calledOnce; @@ -538,7 +538,7 @@ suite('Webview Test Suite', () => { // Mock a connection status request call. messageReceived({ - command: MESSAGE_TYPES.EDIT_CONNECTION_AND_CONNECT, + command: MessageType.EDIT_CONNECTION_AND_CONNECT, connectionInfo: { id: 'pineapple', connectionOptions: { @@ -644,7 +644,7 @@ suite('Webview Test Suite', () => { sandbox.replace(linkHelper, 'openLink', stubOpenLink); messageReceived({ - command: MESSAGE_TYPES.OPEN_TRUSTED_LINK, + command: MessageType.OPEN_TRUSTED_LINK, linkTo: 'https://mongodb.com/test', }); diff --git a/src/views/webview-app/extension-app-message-constants.ts b/src/views/webview-app/extension-app-message-constants.ts index 7e49d5cbb..9035d5e27 100644 --- a/src/views/webview-app/extension-app-message-constants.ts +++ b/src/views/webview-app/extension-app-message-constants.ts @@ -18,7 +18,7 @@ export const VSCODE_EXTENSION_SEGMENT_ANONYMOUS_ID = export const VSCODE_EXTENSION_OIDC_DEVICE_AUTH_ID = 'VSCODE_EXTENSION_OIDC_DEVICE_AUTH_ID'; -export const MESSAGE_TYPES = { +export const MessageType = { CONNECT: 'CONNECT', CANCEL_CONNECT: 'CANCEL_CONNECT', CONNECT_RESULT: 'CONNECT_RESULT', @@ -42,21 +42,21 @@ interface BasicWebviewMessage { } export interface CreateNewPlaygroundMessage extends BasicWebviewMessage { - command: typeof MESSAGE_TYPES.CREATE_NEW_PLAYGROUND; + command: MessageType.CREATE_NEW_PLAYGROUND; } export interface ConnectionFormOpenedMessage extends BasicWebviewMessage { - command: typeof MESSAGE_TYPES.CONNECTION_FORM_OPENED; + command: MessageType.CONNECTION_FORM_OPENED; } export interface ConnectionStatusMessage extends BasicWebviewMessage { - command: typeof MESSAGE_TYPES.CONNECTION_STATUS_MESSAGE; + command: MessageType.CONNECTION_STATUS_MESSAGE; connectionStatus: ConnectionStatus; activeConnectionName: string; } export interface OpenEditConnectionMessage extends BasicWebviewMessage { - command: typeof MESSAGE_TYPES.OPEN_EDIT_CONNECTION; + command: MessageType.OPEN_EDIT_CONNECTION; connection: { id: string; name: string; @@ -65,7 +65,7 @@ export interface OpenEditConnectionMessage extends BasicWebviewMessage { } export interface EditConnectionAndConnectMessage extends BasicWebviewMessage { - command: typeof MESSAGE_TYPES.EDIT_CONNECTION_AND_CONNECT; + command: MessageType.EDIT_CONNECTION_AND_CONNECT; connectionInfo: { id: string; connectionOptions: ConnectionOptions; @@ -73,13 +73,13 @@ export interface EditConnectionAndConnectMessage extends BasicWebviewMessage { } export interface OpenFileChooserMessage extends BasicWebviewMessage { - command: typeof MESSAGE_TYPES.OPEN_FILE_CHOOSER; + command: MessageType.OPEN_FILE_CHOOSER; fileChooserOptions: FileChooserOptions; requestId: string; } export interface ConnectMessage extends BasicWebviewMessage { - command: typeof MESSAGE_TYPES.CONNECT; + command: MessageType.CONNECT; connectionInfo: { id: string; connectionOptions: ConnectionOptions; @@ -87,11 +87,11 @@ export interface ConnectMessage extends BasicWebviewMessage { } export interface CancelConnectMessage extends BasicWebviewMessage { - command: typeof MESSAGE_TYPES.CANCEL_CONNECT; + command: MessageType.CANCEL_CONNECT; } export interface ConnectResultsMessage extends BasicWebviewMessage { - command: typeof MESSAGE_TYPES.CONNECT_RESULT; + command: MessageType.CONNECT_RESULT; connectionSuccess: boolean; connectionMessage: string; connectionId: string; @@ -102,36 +102,36 @@ export type FileChooserResult = | { canceled: false; filePath?: string }; export interface OpenFileChooserResultMessage extends BasicWebviewMessage { - command: typeof MESSAGE_TYPES.OPEN_FILE_CHOOSER_RESULT; + command: MessageType.OPEN_FILE_CHOOSER_RESULT; fileChooserResult: FileChooserResult; requestId: string; } export interface GetConnectionStatusMessage extends BasicWebviewMessage { - command: typeof MESSAGE_TYPES.GET_CONNECTION_STATUS; + command: MessageType.GET_CONNECTION_STATUS; } export interface OpenConnectionStringInputMessage extends BasicWebviewMessage { - command: typeof MESSAGE_TYPES.OPEN_CONNECTION_STRING_INPUT; + command: MessageType.OPEN_CONNECTION_STRING_INPUT; } export interface LinkClickedMessage extends BasicWebviewMessage { - command: typeof MESSAGE_TYPES.EXTENSION_LINK_CLICKED; + command: MessageType.EXTENSION_LINK_CLICKED; screen: string; linkId: string; } export interface OpenTrustedLinkMessage extends BasicWebviewMessage { - command: typeof MESSAGE_TYPES.OPEN_TRUSTED_LINK; + command: MessageType.OPEN_TRUSTED_LINK; linkTo: string; } export interface RenameConnectionMessage extends BasicWebviewMessage { - command: typeof MESSAGE_TYPES.RENAME_ACTIVE_CONNECTION; + command: MessageType.RENAME_ACTIVE_CONNECTION; } export interface ThemeChangedMessage extends BasicWebviewMessage { - command: typeof MESSAGE_TYPES.THEME_CHANGED; + command: MessageType.THEME_CHANGED; darkMode: boolean; } diff --git a/src/views/webview-app/overview-page.tsx b/src/views/webview-app/overview-page.tsx index 15d1ec47e..a41a22e47 100644 --- a/src/views/webview-app/overview-page.tsx +++ b/src/views/webview-app/overview-page.tsx @@ -22,7 +22,7 @@ import useConnectionForm, { type FileChooserOptions, } from './use-connection-form'; import type { MessageFromExtensionToWebview } from './extension-app-message-constants'; -import { MESSAGE_TYPES } from './extension-app-message-constants'; +import { MessageType } from './extension-app-message-constants'; const pageStyles = css({ width: '90%', @@ -76,7 +76,7 @@ const OverviewPage: React.FC = () => { ): void => { const message = event.data; if ( - message.command === MESSAGE_TYPES.OPEN_FILE_CHOOSER_RESULT && + message.command === MessageType.OPEN_FILE_CHOOSER_RESULT && message.requestId === requestId ) { window.removeEventListener('message', messageHandler); diff --git a/src/views/webview-app/use-connection-form.ts b/src/views/webview-app/use-connection-form.ts index cd0bc746e..fdafcbf86 100644 --- a/src/views/webview-app/use-connection-form.ts +++ b/src/views/webview-app/use-connection-form.ts @@ -9,7 +9,7 @@ import { sendEditConnectionToExtension, sendOpenFileChooserToExtension, } from './vscode-api'; -import { MESSAGE_TYPES } from './extension-app-message-constants'; +import { MessageType } from './extension-app-message-constants'; import type { MessageFromExtensionToWebview } from './extension-app-message-constants'; import type { ElectronFileDialogOptions } from '@mongodb-js/compass-components'; @@ -163,7 +163,7 @@ export default function useConnectionForm(): { const handleConnectResultResponse = (event): void => { const message: MessageFromExtensionToWebview = event.data; if ( - message.command === MESSAGE_TYPES.CONNECT_RESULT && + message.command === MessageType.CONNECT_RESULT && message.connectionId === initialConnectionInfo.id ) { dispatch({ @@ -182,7 +182,7 @@ export default function useConnectionForm(): { useEffect(() => { const handleConnectResultResponse = (event): void => { const message: MessageFromExtensionToWebview = event.data; - if (message.command === MESSAGE_TYPES.OPEN_EDIT_CONNECTION) { + if (message.command === MessageType.OPEN_EDIT_CONNECTION) { dispatch({ type: 'open-edit-connection', connectionInfo: { diff --git a/src/views/webview-app/use-connection-status.ts b/src/views/webview-app/use-connection-status.ts index ab163de69..0b620f037 100644 --- a/src/views/webview-app/use-connection-status.ts +++ b/src/views/webview-app/use-connection-status.ts @@ -2,7 +2,7 @@ import { useState, useEffect } from 'react'; import { CONNECTION_STATUS, type MessageFromExtensionToWebview, - MESSAGE_TYPES, + MessageType, type ConnectionStatus, } from './extension-app-message-constants'; import vscode from './vscode-api'; @@ -20,7 +20,7 @@ const useConnectionStatus = (): { useEffect(() => { const handleConnectionStatusResponse = (event): void => { const message: MessageFromExtensionToWebview = event.data; - if (message.command === MESSAGE_TYPES.CONNECTION_STATUS_MESSAGE) { + if (message.command === MessageType.CONNECTION_STATUS_MESSAGE) { setConnectionStatus(message.connectionStatus); setConnectionName(message.activeConnectionName); } @@ -29,7 +29,7 @@ const useConnectionStatus = (): { const requestConnectionStatus = (): void => vscode.postMessage({ - command: MESSAGE_TYPES.GET_CONNECTION_STATUS, + command: MessageType.GET_CONNECTION_STATUS, }); requestConnectionStatus(); diff --git a/src/views/webview-app/use-detect-vscode-dark-mode.tsx b/src/views/webview-app/use-detect-vscode-dark-mode.tsx index fa58dec62..f62bc80a4 100644 --- a/src/views/webview-app/use-detect-vscode-dark-mode.tsx +++ b/src/views/webview-app/use-detect-vscode-dark-mode.tsx @@ -1,7 +1,7 @@ import { useEffect, useState } from 'react'; import { type MessageFromExtensionToWebview, - MESSAGE_TYPES, + MessageType, } from './extension-app-message-constants'; export const useDetectVsCodeDarkMode = (): boolean => { @@ -12,7 +12,7 @@ export const useDetectVsCodeDarkMode = (): boolean => { useEffect(() => { const onThemeChanged = (event): void => { const message: MessageFromExtensionToWebview = event.data; - if (message.command === MESSAGE_TYPES.THEME_CHANGED) { + if (message.command === MessageType.THEME_CHANGED) { setDarkModeDetected(message.darkMode); } }; diff --git a/src/views/webview-app/vscode-api.ts b/src/views/webview-app/vscode-api.ts index 2073c849b..b8ff7fd6b 100644 --- a/src/views/webview-app/vscode-api.ts +++ b/src/views/webview-app/vscode-api.ts @@ -1,5 +1,5 @@ import { - MESSAGE_TYPES, + MessageType, type MessageFromWebviewToExtension, type ConnectMessage, } from './extension-app-message-constants'; @@ -16,7 +16,7 @@ export const sendEditConnectionToExtension = ( connectionInfo: ConnectMessage['connectionInfo'], ): void => { vscode.postMessage({ - command: MESSAGE_TYPES.EDIT_CONNECTION_AND_CONNECT, + command: MessageType.EDIT_CONNECTION_AND_CONNECT, connectionInfo, }); }; @@ -25,7 +25,7 @@ export const sendConnectToExtension = ( connectionInfo: ConnectMessage['connectionInfo'], ): void => { vscode.postMessage({ - command: MESSAGE_TYPES.CONNECT, + command: MessageType.CONNECT, connectionInfo, }); }; @@ -35,7 +35,7 @@ export const sendOpenFileChooserToExtension = ( requestId: string, ): void => { vscode.postMessage({ - command: MESSAGE_TYPES.OPEN_FILE_CHOOSER, + command: MessageType.OPEN_FILE_CHOOSER, fileChooserOptions, requestId, }); @@ -43,7 +43,7 @@ export const sendOpenFileChooserToExtension = ( export const sendCancelConnectToExtension = (): void => { vscode.postMessage({ - command: MESSAGE_TYPES.CANCEL_CONNECT, + command: MessageType.CANCEL_CONNECT, }); }; @@ -51,25 +51,25 @@ export const sendCancelConnectToExtension = (): void => { // input if it's open, so we message the extension. export const sendFormOpenedToExtension = (): void => { vscode.postMessage({ - command: MESSAGE_TYPES.CONNECTION_FORM_OPENED, + command: MessageType.CONNECTION_FORM_OPENED, }); }; export const renameActiveConnection = (): void => { vscode.postMessage({ - command: MESSAGE_TYPES.RENAME_ACTIVE_CONNECTION, + command: MessageType.RENAME_ACTIVE_CONNECTION, }); }; export const createNewPlayground = (): void => { vscode.postMessage({ - command: MESSAGE_TYPES.CREATE_NEW_PLAYGROUND, + command: MessageType.CREATE_NEW_PLAYGROUND, }); }; export const connectWithConnectionString = (): void => { vscode.postMessage({ - command: MESSAGE_TYPES.OPEN_CONNECTION_STRING_INPUT, + command: MessageType.OPEN_CONNECTION_STRING_INPUT, }); }; @@ -78,7 +78,7 @@ export const trackExtensionLinkClicked = ( linkId: string, ): void => { vscode.postMessage({ - command: MESSAGE_TYPES.EXTENSION_LINK_CLICKED, + command: MessageType.EXTENSION_LINK_CLICKED, screen, linkId, }); @@ -86,7 +86,7 @@ export const trackExtensionLinkClicked = ( export const openTrustedLink = (linkTo: string): void => { vscode.postMessage({ - command: MESSAGE_TYPES.OPEN_TRUSTED_LINK, + command: MessageType.OPEN_TRUSTED_LINK, linkTo, }); }; diff --git a/src/views/webviewController.ts b/src/views/webviewController.ts index 3b96677eb..a8d0b58dc 100644 --- a/src/views/webviewController.ts +++ b/src/views/webviewController.ts @@ -9,7 +9,7 @@ import { createLogger } from '../logging'; import ExtensionCommand from '../commands'; import type { MessageFromWebviewToExtension } from './webview-app/extension-app-message-constants'; import { - MESSAGE_TYPES, + MessageType, VSCODE_EXTENSION_OIDC_DEVICE_AUTH_ID, VSCODE_EXTENSION_SEGMENT_ANONYMOUS_ID, } from './webview-app/extension-app-message-constants'; @@ -164,7 +164,7 @@ export default class WebviewController { } void panel.webview.postMessage({ - command: MESSAGE_TYPES.OPEN_FILE_CHOOSER_RESULT, + command: MessageType.OPEN_FILE_CHOOSER_RESULT, fileChooserResult: { canceled: false, ...(Array.isArray(files) @@ -207,7 +207,7 @@ export default class WebviewController { try { // The webview may have been closed in which case this will throw. void panel.webview.postMessage({ - command: MESSAGE_TYPES.CONNECT_RESULT, + command: MessageType.CONNECT_RESULT, connectionId: connection.id, connectionSuccess: successfullyConnected, connectionMessage: successfullyConnected @@ -223,7 +223,7 @@ export default class WebviewController { ); void panel.webview.postMessage({ - command: MESSAGE_TYPES.CONNECT_RESULT, + command: MessageType.CONNECT_RESULT, connectionId: connection.id, connectionSuccess: false, connectionMessage: `Unable to load connection: ${error}`, @@ -237,16 +237,16 @@ export default class WebviewController { panel: vscode.WebviewPanel, ): Promise => { switch (message.command) { - case MESSAGE_TYPES.CONNECT: + case MessageType.CONNECT: await this.handleWebviewConnectAttempt({ panel, connection: message.connectionInfo, }); return; - case MESSAGE_TYPES.CANCEL_CONNECT: + case MessageType.CANCEL_CONNECT: this._connectionController.cancelConnectionAttempt(); return; - case MESSAGE_TYPES.EDIT_CONNECTION_AND_CONNECT: + case MessageType.EDIT_CONNECTION_AND_CONNECT: await this.handleWebviewConnectAttempt({ panel, connection: message.connectionInfo, @@ -254,37 +254,37 @@ export default class WebviewController { }); this._telemetryService.track(new ConnectionEditedTelemetryEvent()); return; - case MESSAGE_TYPES.OPEN_FILE_CHOOSER: + case MessageType.OPEN_FILE_CHOOSER: await this.handleWebviewOpenFileChooserAttempt({ panel, fileChooserOptions: message.fileChooserOptions, requestId: message.requestId, }); return; - case MESSAGE_TYPES.CREATE_NEW_PLAYGROUND: + case MessageType.CREATE_NEW_PLAYGROUND: void vscode.commands.executeCommand( ExtensionCommand.MDB_CREATE_PLAYGROUND_FROM_OVERVIEW_PAGE, ); return; - case MESSAGE_TYPES.CONNECTION_FORM_OPENED: + case MessageType.CONNECTION_FORM_OPENED: // If the connection string input is open we want to close it // when the user opens the form. this._connectionController.closeConnectionStringInput(); return; - case MESSAGE_TYPES.GET_CONNECTION_STATUS: + case MessageType.GET_CONNECTION_STATUS: void panel.webview.postMessage({ - command: MESSAGE_TYPES.CONNECTION_STATUS_MESSAGE, + command: MessageType.CONNECTION_STATUS_MESSAGE, connectionStatus: this._connectionController.getConnectionStatus(), activeConnectionName: this._connectionController.getActiveConnectionName(), }); return; - case MESSAGE_TYPES.OPEN_CONNECTION_STRING_INPUT: + case MessageType.OPEN_CONNECTION_STRING_INPUT: void vscode.commands.executeCommand( ExtensionCommand.MDB_CONNECT_WITH_URI, ); return; - case MESSAGE_TYPES.OPEN_TRUSTED_LINK: + case MessageType.OPEN_TRUSTED_LINK: try { await openLink(message.linkTo); } catch (err) { @@ -295,12 +295,12 @@ export default class WebviewController { ); } return; - case MESSAGE_TYPES.EXTENSION_LINK_CLICKED: + case MessageType.EXTENSION_LINK_CLICKED: this._telemetryService.track( new LinkClickedTelemetryEvent(message.screen, message.linkId), ); return; - case MESSAGE_TYPES.RENAME_ACTIVE_CONNECTION: + case MessageType.RENAME_ACTIVE_CONNECTION: if (this._connectionController.isCurrentlyConnected()) { void this._connectionController.renameConnection( this._connectionController.getActiveConnectionId() as string, @@ -339,7 +339,7 @@ export default class WebviewController { for (const panel of this._activeWebviewPanels) { void panel.webview .postMessage({ - command: MESSAGE_TYPES.THEME_CHANGED, + command: MessageType.THEME_CHANGED, darkMode: darkModeDetected, }) .then(undefined, (error) => { @@ -369,7 +369,7 @@ export default class WebviewController { this._telemetryService.track(new OpenEditConnectionTelemetryEvent()); void webviewPanel.webview.postMessage({ - command: MESSAGE_TYPES.OPEN_EDIT_CONNECTION, + command: MessageType.OPEN_EDIT_CONNECTION, connection, }); }; From 0a7b4038f7a9ff9b13c2cb45020e2617f2b46e09 Mon Sep 17 00:00:00 2001 From: gagik Date: Fri, 12 Dec 2025 17:14:03 +0100 Subject: [PATCH 9/9] chore: bring back typeof --- .../extension-app-message-constants.ts | 34 ++++++++++--------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/src/views/webview-app/extension-app-message-constants.ts b/src/views/webview-app/extension-app-message-constants.ts index 9035d5e27..dbfd65851 100644 --- a/src/views/webview-app/extension-app-message-constants.ts +++ b/src/views/webview-app/extension-app-message-constants.ts @@ -37,26 +37,28 @@ export const MessageType = { THEME_CHANGED: 'THEME_CHANGED', } as const; +export type MessageType = (typeof MessageType)[keyof typeof MessageType]; + interface BasicWebviewMessage { command: string; } export interface CreateNewPlaygroundMessage extends BasicWebviewMessage { - command: MessageType.CREATE_NEW_PLAYGROUND; + command: typeof MessageType.CREATE_NEW_PLAYGROUND; } export interface ConnectionFormOpenedMessage extends BasicWebviewMessage { - command: MessageType.CONNECTION_FORM_OPENED; + command: typeof MessageType.CONNECTION_FORM_OPENED; } export interface ConnectionStatusMessage extends BasicWebviewMessage { - command: MessageType.CONNECTION_STATUS_MESSAGE; + command: typeof MessageType.CONNECTION_STATUS_MESSAGE; connectionStatus: ConnectionStatus; activeConnectionName: string; } export interface OpenEditConnectionMessage extends BasicWebviewMessage { - command: MessageType.OPEN_EDIT_CONNECTION; + command: typeof MessageType.OPEN_EDIT_CONNECTION; connection: { id: string; name: string; @@ -65,7 +67,7 @@ export interface OpenEditConnectionMessage extends BasicWebviewMessage { } export interface EditConnectionAndConnectMessage extends BasicWebviewMessage { - command: MessageType.EDIT_CONNECTION_AND_CONNECT; + command: typeof MessageType.EDIT_CONNECTION_AND_CONNECT; connectionInfo: { id: string; connectionOptions: ConnectionOptions; @@ -73,13 +75,13 @@ export interface EditConnectionAndConnectMessage extends BasicWebviewMessage { } export interface OpenFileChooserMessage extends BasicWebviewMessage { - command: MessageType.OPEN_FILE_CHOOSER; + command: typeof MessageType.OPEN_FILE_CHOOSER; fileChooserOptions: FileChooserOptions; requestId: string; } export interface ConnectMessage extends BasicWebviewMessage { - command: MessageType.CONNECT; + command: typeof MessageType.CONNECT; connectionInfo: { id: string; connectionOptions: ConnectionOptions; @@ -87,11 +89,11 @@ export interface ConnectMessage extends BasicWebviewMessage { } export interface CancelConnectMessage extends BasicWebviewMessage { - command: MessageType.CANCEL_CONNECT; + command: typeof MessageType.CANCEL_CONNECT; } export interface ConnectResultsMessage extends BasicWebviewMessage { - command: MessageType.CONNECT_RESULT; + command: typeof MessageType.CONNECT_RESULT; connectionSuccess: boolean; connectionMessage: string; connectionId: string; @@ -102,36 +104,36 @@ export type FileChooserResult = | { canceled: false; filePath?: string }; export interface OpenFileChooserResultMessage extends BasicWebviewMessage { - command: MessageType.OPEN_FILE_CHOOSER_RESULT; + command: typeof MessageType.OPEN_FILE_CHOOSER_RESULT; fileChooserResult: FileChooserResult; requestId: string; } export interface GetConnectionStatusMessage extends BasicWebviewMessage { - command: MessageType.GET_CONNECTION_STATUS; + command: typeof MessageType.GET_CONNECTION_STATUS; } export interface OpenConnectionStringInputMessage extends BasicWebviewMessage { - command: MessageType.OPEN_CONNECTION_STRING_INPUT; + command: typeof MessageType.OPEN_CONNECTION_STRING_INPUT; } export interface LinkClickedMessage extends BasicWebviewMessage { - command: MessageType.EXTENSION_LINK_CLICKED; + command: typeof MessageType.EXTENSION_LINK_CLICKED; screen: string; linkId: string; } export interface OpenTrustedLinkMessage extends BasicWebviewMessage { - command: MessageType.OPEN_TRUSTED_LINK; + command: typeof MessageType.OPEN_TRUSTED_LINK; linkTo: string; } export interface RenameConnectionMessage extends BasicWebviewMessage { - command: MessageType.RENAME_ACTIVE_CONNECTION; + command: typeof MessageType.RENAME_ACTIVE_CONNECTION; } export interface ThemeChangedMessage extends BasicWebviewMessage { - command: MessageType.THEME_CHANGED; + command: typeof MessageType.THEME_CHANGED; darkMode: boolean; }