diff --git a/.depcheckrc b/.depcheckrc index 72997752..e775a4df 100644 --- a/.depcheckrc +++ b/.depcheckrc @@ -1,10 +1,12 @@ ignores: - - "vscode" - - "keytar" + - "@babel/core" + - "@mongodb-js/prettier-config-compass" - "@types/jest" + - "eslint-config-mongodb-js" + - "keytar" - "mocha-junit-reporter" - "mocha-multi" - "pre-commit" - - "webpack-cli" - "vscode-languageserver-textdocument" - - "@babel/core" + - "vscode" + - "webpack-cli" diff --git a/.eslintrc.js b/.eslintrc.js index 859dfcfd..b6758506 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,8 +1,11 @@ const typescriptEslintEslintPlugin = require('@typescript-eslint/eslint-plugin'); // Overrides do not work with extends. -const ruleOverridesForJs = Object.keys(typescriptEslintEslintPlugin.rules).reduce( - (overrides, rule) => ({ ...overrides, [`@typescript-eslint/${rule}`]: 0 }), {} +const ruleOverridesForJs = Object.keys( + typescriptEslintEslintPlugin.rules +).reduce( + (overrides, rule) => ({ ...overrides, [`@typescript-eslint/${rule}`]: 0 }), + {} ); module.exports = { @@ -11,15 +14,13 @@ module.exports = { parserOptions: { ecmaVersion: 2018, sourceType: 'module', - project: [ - './tsconfig.json' - ] + project: ['./tsconfig.json'], }, extends: [ 'eslint-config-mongodb-js/react', 'plugin:@typescript-eslint/eslint-recommended', 'plugin:@typescript-eslint/recommended', - 'plugin:@typescript-eslint/recommended-requiring-type-checking' + 'plugin:@typescript-eslint/recommended-requiring-type-checking', ], rules: { 'chai-friendly/no-unused-expressions': 0, @@ -36,7 +37,7 @@ module.exports = { '@typescript-eslint/ban-types': 0, 'mocha/no-skipped-tests': 1, 'mocha/no-exclusive-tests': 2, - 'semi': 0, + semi: 0, '@typescript-eslint/semi': [2, 'always'], 'no-console': [1, { allow: ['warn', 'error', 'info'] }], 'no-shadow': 0, @@ -54,13 +55,15 @@ module.exports = { '@typescript-eslint/no-unsafe-assignment': 0, '@typescript-eslint/no-unsafe-member-access': 0, '@typescript-eslint/no-unsafe-call': 0, - '@typescript-eslint/no-unsafe-return': 0 + '@typescript-eslint/no-unsafe-return': 0, }, - overrides: [{ - files: ['**/*.js'], - rules: { - ...ruleOverridesForJs, - semi: [2, 'always'] - } - }] + overrides: [ + { + files: ['**/*.js'], + rules: { + ...ruleOverridesForJs, + semi: [2, 'always'], + }, + }, + ], }; diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 00000000..419d6ade --- /dev/null +++ b/.prettierignore @@ -0,0 +1,14 @@ +.github +.vscode +.vscode-test +dist +images +languages +node_modules +out +playgrounds +resources +snippets +syntaxes +CHANGELOG.md +README.md diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 00000000..18853d15 --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1 @@ +"@mongodb-js/prettier-config-compass" diff --git a/jest.config.js b/jest.config.js index 51a1a597..77acb8a9 100644 --- a/jest.config.js +++ b/jest.config.js @@ -2,15 +2,18 @@ module.exports = { roots: ['/src/test/suite/views/webview-app'], transform: { '^.+\\.tsx?$': 'ts-jest', - '.+\\.(less|svg)$': 'jest-transform-stub' + '.+\\.(less|svg)$': 'jest-transform-stub', }, reporters: [ 'default', - ['jest-junit', { - outputName: 'test-webview-results.xml' - }] + [ + 'jest-junit', + { + outputName: 'test-webview-results.xml', + }, + ], ], testRegex: '(/test/suite/views/webview-app/.*|(\\.|/)(test|spec))\\.tsx?$', moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], - setupFiles: ['/src/test/suite/views/webview-app/jest-setup.js'] + setupFiles: ['/src/test/suite/views/webview-app/jest-setup.js'], }; diff --git a/package-lock.json b/package-lock.json index ecf0a06d..ce417c08 100644 --- a/package-lock.json +++ b/package-lock.json @@ -47,6 +47,7 @@ "vscode-languageserver-textdocument": "^1.0.4" }, "devDependencies": { + "@mongodb-js/prettier-config-compass": "^1.0.0", "@types/analytics-node": "^3.1.7", "@types/babel__core": "^7.1.18", "@types/babel__traverse": "^7.14.2", @@ -103,6 +104,7 @@ "ora": "^5.4.1", "postcss-loader": "^3.0.0", "pre-commit": "^1.2.2", + "prettier": "^2.7.1", "semver": "^7.3.5", "sinon": "^9.2.4", "sinon-chai": "^3.7.0", @@ -1606,6 +1608,15 @@ "mongodb-log-writer": "^1.1.3" } }, + "node_modules/@mongodb-js/prettier-config-compass": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@mongodb-js/prettier-config-compass/-/prettier-config-compass-1.0.0.tgz", + "integrity": "sha512-7lQkEANuuhx2pvX1xPeWcSecsQW4lQS2FMHmTgxhanvxlemTEBG9IOoflspCenHFCxrDuv6vKJa797hUtNfXqg==", + "dev": true, + "peerDependencies": { + "prettier": "^2.7.1" + } + }, "node_modules/@mongodb-js/ssh-tunnel": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/@mongodb-js/ssh-tunnel/-/ssh-tunnel-1.4.0.tgz", @@ -5299,6 +5310,17 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/cli": { + "version": "0.4.5", + "resolved": "https://registry.npmjs.org/cli/-/cli-0.4.5.tgz", + "integrity": "sha512-dbn5HyeJWSOU58RwOEiF1VWrl7HRvDsKLpu0uiI/vExH6iNoyUzjB5Mr3IJY5DVUfnbpe9793xw4DFJVzC9nWQ==", + "dependencies": { + "glob": ">= 3.1.4" + }, + "engines": { + "node": ">=0.2.5" + } + }, "node_modules/cli-color": { "version": "0.3.2", "resolved": "https://registry.npmjs.org/cli-color/-/cli-color-0.3.2.tgz", @@ -5564,6 +5586,19 @@ "node": ">= 10" } }, + "node_modules/cliff": { + "version": "0.1.10", + "resolved": "https://registry.npmjs.org/cliff/-/cliff-0.1.10.tgz", + "integrity": "sha512-roZWcC2Cxo/kKjRXw7YUpVNtxJccbvcl7VzTjUYgLQk6Ot0R8bm2netbhSZYWWNrKlOO/7HD6GXHl8dtzE6SiQ==", + "dependencies": { + "colors": "~1.0.3", + "eyes": "~0.1.8", + "winston": "0.8.x" + }, + "engines": { + "node": ">= 0.4.0" + } + }, "node_modules/cliui": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/cliui/-/cliui-3.2.0.tgz", @@ -5670,7 +5705,6 @@ "version": "1.0.3", "resolved": "https://registry.npmjs.org/colors/-/colors-1.0.3.tgz", "integrity": "sha1-BDP0TYCWgP3rYO0mDxsMJi6CpAs=", - "optional": true, "engines": { "node": ">=0.1.90" } @@ -6140,6 +6174,14 @@ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.0.9.tgz", "integrity": "sha512-rpw6JPxK6Rfg1zLOYCSwle2GFOOsnjmDYDaBwEcwoOg4qlsIVCN789VkBZDJAGi4T07gI4YSutR43t9Zz4Lzuw==" }, + "node_modules/cycle": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/cycle/-/cycle-1.0.3.tgz", + "integrity": "sha512-TVF6svNzeQCOpjCqsy0/CSy8VgObG3wXusJ73xW2GbG5rGx7lC8zxDSURicsXI2UsGdi2L0QNRCi745/wUDvsA==", + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/cyclist": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/cyclist/-/cyclist-1.0.1.tgz", @@ -8949,6 +8991,14 @@ "node >=0.6.0" ] }, + "node_modules/eyes": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/eyes/-/eyes-0.1.8.tgz", + "integrity": "sha512-GipyPsXO1anza0AOZdy69Im7hGFCNB7Y/NGjDlZGJ3GJJLtwNSb2vrzYrTYJRrRloVx7pl+bhUaTB8yiccPvFQ==", + "engines": { + "node": "> 0.1.90" + } + }, "node_modules/facepaint": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/facepaint/-/facepaint-1.2.1.tgz", @@ -18787,6 +18837,14 @@ "node": ">=8" } }, + "node_modules/pkginfo": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/pkginfo/-/pkginfo-0.3.1.tgz", + "integrity": "sha512-yO5feByMzAp96LtP58wvPKSbaKAi/1C4kV9XpTctr6EepnP6F33RBNOiVrdz9BrPA98U2BMFsTNHo44TWcbQ2A==", + "engines": { + "node": ">= 0.4.0" + } + }, "node_modules/please-upgrade-node": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/please-upgrade-node/-/please-upgrade-node-3.2.0.tgz", @@ -19245,6 +19303,21 @@ "node": ">=4" } }, + "node_modules/prettier": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.7.1.tgz", + "integrity": "sha512-ujppO+MkdPqoVINuDFDRLClm7D78qbDt0/NR+wp5FqEZOoTNAjPHWj17QRhu7geIHJfcNhRk1XVQmF8Bp3ye+g==", + "dev": true, + "bin": { + "prettier": "bin-prettier.js" + }, + "engines": { + "node": ">=10.13.0" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, "node_modules/process": { "version": "0.11.10", "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", @@ -21105,6 +21178,14 @@ "figgy-pudding": "^3.5.1" } }, + "node_modules/stack-trace": { + "version": "0.0.10", + "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", + "integrity": "sha512-KGzahc7puUKkzyMt+IqAep+TVNbKP+k2Lmwhub39m1AsTSkaDutx56aDCo+HLDzf/D26BIHTJWNiTG1KAJiQCg==", + "engines": { + "node": "*" + } + }, "node_modules/stack-utils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.3.tgz", @@ -24032,6 +24113,36 @@ "node": ">= 0.10.0" } }, + "node_modules/winston": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/winston/-/winston-0.8.3.tgz", + "integrity": "sha512-fPoamsHq8leJ62D1M9V/f15mjQ1UHe4+7j1wpAT3fqgA5JqhJkk4aIfPEjfMTI9x6ZTjaLOpMAjluLtmgO5b6g==", + "dependencies": { + "async": "0.2.x", + "colors": "0.6.x", + "cycle": "1.0.x", + "eyes": "0.1.x", + "isstream": "0.1.x", + "pkginfo": "0.3.x", + "stack-trace": "0.0.x" + }, + "engines": { + "node": ">= 0.6.0" + } + }, + "node_modules/winston/node_modules/async": { + "version": "0.2.10", + "resolved": "https://registry.npmjs.org/async/-/async-0.2.10.tgz", + "integrity": "sha512-eAkdoKxU6/LkKDBzLpT+t6Ff5EtfSF4wx1WfJiPEEV7WNLnDaRXk0oVysiEPm262roaachGexwUv94WhSgN5TQ==" + }, + "node_modules/winston/node_modules/colors": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/colors/-/colors-0.6.2.tgz", + "integrity": "sha512-OsSVtHK8Ir8r3+Fxw/b4jS1ZLPXkV6ZxDRJQzeD7qo0SqMXWrHDM71DgYzPMHY8SFJ0Ao+nNU2p1MmwdzKqPrw==", + "engines": { + "node": ">=0.1.90" + } + }, "node_modules/wolfy87-eventemitter": { "version": "5.2.9", "resolved": "https://registry.npmjs.org/wolfy87-eventemitter/-/wolfy87-eventemitter-5.2.9.tgz", @@ -25616,6 +25727,12 @@ "system-ca": "^1.0.2" } }, + "@mongodb-js/prettier-config-compass": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@mongodb-js/prettier-config-compass/-/prettier-config-compass-1.0.0.tgz", + "integrity": "sha512-7lQkEANuuhx2pvX1xPeWcSecsQW4lQS2FMHmTgxhanvxlemTEBG9IOoflspCenHFCxrDuv6vKJa797hUtNfXqg==", + "dev": true + }, "@mongodb-js/ssh-tunnel": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/@mongodb-js/ssh-tunnel/-/ssh-tunnel-1.4.0.tgz", @@ -28736,6 +28853,14 @@ } } }, + "cli": { + "version": "0.4.5", + "resolved": "https://registry.npmjs.org/cli/-/cli-0.4.5.tgz", + "integrity": "sha512-dbn5HyeJWSOU58RwOEiF1VWrl7HRvDsKLpu0uiI/vExH6iNoyUzjB5Mr3IJY5DVUfnbpe9793xw4DFJVzC9nWQ==", + "requires": { + "glob": ">= 3.1.4" + } + }, "cli-color": { "version": "0.3.2", "resolved": "https://registry.npmjs.org/cli-color/-/cli-color-0.3.2.tgz", @@ -28941,6 +29066,16 @@ "integrity": "sha512-FxqpkPPwu1HjuN93Omfm4h8uIanXofW0RxVEW3k5RKx+mJJYSthzNhp32Kzxxy3YAEZ/Dc/EWN1vZRY0+kOhbw==", "dev": true }, + "cliff": { + "version": "0.1.10", + "resolved": "https://registry.npmjs.org/cliff/-/cliff-0.1.10.tgz", + "integrity": "sha512-roZWcC2Cxo/kKjRXw7YUpVNtxJccbvcl7VzTjUYgLQk6Ot0R8bm2netbhSZYWWNrKlOO/7HD6GXHl8dtzE6SiQ==", + "requires": { + "colors": "~1.0.3", + "eyes": "~0.1.8", + "winston": "0.8.x" + } + }, "cliui": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/cliui/-/cliui-3.2.0.tgz", @@ -29032,8 +29167,7 @@ "colors": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/colors/-/colors-1.0.3.tgz", - "integrity": "sha1-BDP0TYCWgP3rYO0mDxsMJi6CpAs=", - "optional": true + "integrity": "sha1-BDP0TYCWgP3rYO0mDxsMJi6CpAs=" }, "combined-stream": { "version": "1.0.8", @@ -29449,6 +29583,11 @@ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.0.9.tgz", "integrity": "sha512-rpw6JPxK6Rfg1zLOYCSwle2GFOOsnjmDYDaBwEcwoOg4qlsIVCN789VkBZDJAGi4T07gI4YSutR43t9Zz4Lzuw==" }, + "cycle": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/cycle/-/cycle-1.0.3.tgz", + "integrity": "sha512-TVF6svNzeQCOpjCqsy0/CSy8VgObG3wXusJ73xW2GbG5rGx7lC8zxDSURicsXI2UsGdi2L0QNRCi745/wUDvsA==" + }, "cyclist": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/cyclist/-/cyclist-1.0.1.tgz", @@ -31787,6 +31926,11 @@ "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=" }, + "eyes": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/eyes/-/eyes-0.1.8.tgz", + "integrity": "sha512-GipyPsXO1anza0AOZdy69Im7hGFCNB7Y/NGjDlZGJ3GJJLtwNSb2vrzYrTYJRrRloVx7pl+bhUaTB8yiccPvFQ==" + }, "facepaint": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/facepaint/-/facepaint-1.2.1.tgz", @@ -39866,6 +40010,11 @@ } } }, + "pkginfo": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/pkginfo/-/pkginfo-0.3.1.tgz", + "integrity": "sha512-yO5feByMzAp96LtP58wvPKSbaKAi/1C4kV9XpTctr6EepnP6F33RBNOiVrdz9BrPA98U2BMFsTNHo44TWcbQ2A==" + }, "please-upgrade-node": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/please-upgrade-node/-/please-upgrade-node-3.2.0.tgz", @@ -40228,6 +40377,12 @@ "integrity": "sha1-6SQ0v6XqjBn0HN/UAddBo8gZ2Jc=", "dev": true }, + "prettier": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.7.1.tgz", + "integrity": "sha512-ujppO+MkdPqoVINuDFDRLClm7D78qbDt0/NR+wp5FqEZOoTNAjPHWj17QRhu7geIHJfcNhRk1XVQmF8Bp3ye+g==", + "dev": true + }, "process": { "version": "0.11.10", "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", @@ -41797,6 +41952,11 @@ "figgy-pudding": "^3.5.1" } }, + "stack-trace": { + "version": "0.0.10", + "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", + "integrity": "sha512-KGzahc7puUKkzyMt+IqAep+TVNbKP+k2Lmwhub39m1AsTSkaDutx56aDCo+HLDzf/D26BIHTJWNiTG1KAJiQCg==" + }, "stack-utils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.3.tgz", @@ -44248,6 +44408,32 @@ "resolved": "https://registry.npmjs.org/window-size/-/window-size-0.2.0.tgz", "integrity": "sha1-tDFbtCFKPXBY6+7okuE/ok2YsHU=" }, + "winston": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/winston/-/winston-0.8.3.tgz", + "integrity": "sha512-fPoamsHq8leJ62D1M9V/f15mjQ1UHe4+7j1wpAT3fqgA5JqhJkk4aIfPEjfMTI9x6ZTjaLOpMAjluLtmgO5b6g==", + "requires": { + "async": "0.2.x", + "colors": "0.6.x", + "cycle": "1.0.x", + "eyes": "0.1.x", + "isstream": "0.1.x", + "pkginfo": "0.3.x", + "stack-trace": "0.0.x" + }, + "dependencies": { + "async": { + "version": "0.2.10", + "resolved": "https://registry.npmjs.org/async/-/async-0.2.10.tgz", + "integrity": "sha512-eAkdoKxU6/LkKDBzLpT+t6Ff5EtfSF4wx1WfJiPEEV7WNLnDaRXk0oVysiEPm262roaachGexwUv94WhSgN5TQ==" + }, + "colors": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/colors/-/colors-0.6.2.tgz", + "integrity": "sha512-OsSVtHK8Ir8r3+Fxw/b4jS1ZLPXkV6ZxDRJQzeD7qo0SqMXWrHDM71DgYzPMHY8SFJ0Ao+nNU2p1MmwdzKqPrw==" + } + } + }, "wolfy87-eventemitter": { "version": "5.2.9", "resolved": "https://registry.npmjs.org/wolfy87-eventemitter/-/wolfy87-eventemitter-5.2.9.tgz", diff --git a/package.json b/package.json index 6f8b1ca4..eb47938e 100644 --- a/package.json +++ b/package.json @@ -35,7 +35,7 @@ "main": "./dist/extension.js", "scripts": { "clean": "rimraf ./out/* ./dist/* ", - "lint": "eslint --cache '**/*.{js,ts,tsx}'", + "lint": "eslint . && prettier --check .", "update-grammar": "ts-node ./scripts/update-grammar.ts", "update-snippets": "ts-node ./scripts/update-snippets.ts", "precompile": "npm run clean", @@ -58,7 +58,8 @@ "package": "npm list --production --parseable --depth=99999 --loglevel=info || true && vsce package --githubBranch main", "local-install": "npm run package && code --install-extension ./mongodb-vscode-*.vsix", "check-vsix-size": "ts-node ./scripts/check-vsix-size.ts", - "release-draft": "node ./scripts/release-draft.js" + "release-draft": "node ./scripts/release-draft.js", + "reformat": "prettier --write ." }, "engines": { "vscode": "^1.65.2", @@ -954,6 +955,7 @@ "vscode-languageserver-textdocument": "^1.0.4" }, "devDependencies": { + "@mongodb-js/prettier-config-compass": "^1.0.0", "@types/analytics-node": "^3.1.7", "@types/babel__core": "^7.1.18", "@types/babel__traverse": "^7.14.2", @@ -1010,6 +1012,7 @@ "ora": "^5.4.1", "postcss-loader": "^3.0.0", "pre-commit": "^1.2.2", + "prettier": "^2.7.1", "semver": "^7.3.5", "sinon": "^9.2.4", "sinon-chai": "^3.7.0", diff --git a/scripts/check-vsix-size.ts b/scripts/check-vsix-size.ts index d801e154..02bd717e 100644 --- a/scripts/check-vsix-size.ts +++ b/scripts/check-vsix-size.ts @@ -1,15 +1,23 @@ import fs from 'fs'; import path from 'path'; -const version = JSON.parse(fs.readFileSync(path.resolve(__dirname, '..', 'package.json')).toString()).version; +const version = JSON.parse( + fs.readFileSync(path.resolve(__dirname, '..', 'package.json')).toString() +).version; -const vsixFileName = path.resolve(__dirname, '..', `./mongodb-vscode-${version}.vsix`); +const vsixFileName = path.resolve( + __dirname, + '..', + `./mongodb-vscode-${version}.vsix` +); const size = fs.statSync(vsixFileName).size; const maxSize = 7 * 1000000; // 7 MB if (size >= maxSize) { - throw new Error(`vsix bundle too big expected max ${maxSize} bytes, got ${size}.`); + throw new Error( + `vsix bundle too big expected max ${maxSize} bytes, got ${size}.` + ); } console.info(`vsix size ok: ${size} bytes.`); diff --git a/scripts/generate-keyfile.ts b/scripts/generate-keyfile.ts index c8bcf31d..889a1c74 100644 --- a/scripts/generate-keyfile.ts +++ b/scripts/generate-keyfile.ts @@ -25,4 +25,4 @@ config({ path: resolve(__dirname, '../.env') }); } })().catch((error) => { ui.fail(`Failed to generate segment constants file: ${error.message}`); -}) +}); diff --git a/scripts/no-npm-list-fail.js b/scripts/no-npm-list-fail.js index 4c2923e5..02d68da3 100644 --- a/scripts/no-npm-list-fail.js +++ b/scripts/no-npm-list-fail.js @@ -5,7 +5,9 @@ const child_process = require('child_process'); const origExec = child_process.exec; child_process.exec = (cmd, options, cb) => { - if (cmd === 'npm list --production --parseable --depth=99999 --loglevel=error') { + if ( + cmd === 'npm list --production --parseable --depth=99999 --loglevel=error' + ) { origExec(cmd, options, (err, stdout, stderr) => { cb(null, stdout, stderr); }); @@ -13,4 +15,3 @@ child_process.exec = (cmd, options, cb) => { origExec(cmd, options, cb); } }; - diff --git a/scripts/release-draft.js b/scripts/release-draft.js index deba7ed6..fd7f0b7d 100644 --- a/scripts/release-draft.js +++ b/scripts/release-draft.js @@ -40,7 +40,7 @@ async function pushTags() { async function main() { const args = yargsParser(process.argv.slice(2)); - if (await getCurrentBranch() !== 'main') { + if ((await getCurrentBranch()) !== 'main') { fail('You can only run this script from the main branch'); } @@ -48,9 +48,14 @@ async function main() { fail('You have untracked or staged changes.'); } - if (!args.skipCheckHead && await revParse('HEAD') !== await revParse('origin/HEAD')) { - fail('The current commit is not up to date with origin/HEAD.' + - ' Rerun this script with --skipCheckHead to suppress this check'); + if ( + !args.skipCheckHead && + (await revParse('HEAD')) !== (await revParse('origin/HEAD')) + ) { + fail( + 'The current commit is not up to date with origin/HEAD.' + + ' Rerun this script with --skipCheckHead to suppress this check' + ); } if (args._.length !== 1) { @@ -62,11 +67,16 @@ async function main() { const lastReleaseVersion = await getLastReleaseVersion(); if (['major', 'minor', 'patch'].includes(versionOrBumpType)) { - return await startRelease(semver.inc(lastReleaseVersion, versionOrBumpType)) + return await startRelease( + semver.inc(lastReleaseVersion, versionOrBumpType) + ); } - if(semver.valid(versionOrBumpType) && !semver.prerelease(versionOrBumpType)) { - return await startRelease(new semver.SemVer(versionOrBumpType).version) + if ( + semver.valid(versionOrBumpType) && + !semver.prerelease(versionOrBumpType) + ) { + return await startRelease(new semver.SemVer(versionOrBumpType).version); } fail(USAGE); @@ -81,7 +91,8 @@ async function getLastReleaseVersion() { async function startRelease(version) { const answer = await cli.confirm( - `Are you sure you want to create the release ${chalk.bold(version)}?`); + `Are you sure you want to create the release ${chalk.bold(version)}?` + ); if (!answer) { return; } @@ -100,8 +111,7 @@ ${chalk.green('Done!')} A release draft will be created at https://github.com/${REPO}/releases You can follow the build at https://github.com/${REPO}/actions/workflows/test-and-build.yaml -`) +`); } main(); - diff --git a/scripts/update-grammar.ts b/scripts/update-grammar.ts index d010ce61..c838da41 100755 --- a/scripts/update-grammar.ts +++ b/scripts/update-grammar.ts @@ -32,26 +32,27 @@ const cli = meow( { flags: { dest: { - default: DEFAULT_DEST + default: DEFAULT_DEST, }, url: { - default: languageURL - } - } + default: languageURL, + }, + }, } ); (async () => { await mkdirp(DEFAULT_DEST); - const ui = ora() - .info('Downlading latest mongodb.tmLanguage.json') - .start(); + const ui = ora().info('Downlading latest mongodb.tmLanguage.json').start(); try { await download(cli.flags.url, cli.flags.dest); ui.succeed( - `Downloaded to ${path.join(cli.flags.dest as string, 'mongodb.tmLanguage.json')}` + `Downloaded to ${path.join( + cli.flags.dest as string, + 'mongodb.tmLanguage.json' + )}` ); } catch (error) { ui.fail(`Download failed: ${formatError(error).message}`); diff --git a/src/commands/index.ts b/src/commands/index.ts index cd70669c..5502471d 100644 --- a/src/commands/index.ts +++ b/src/commands/index.ts @@ -59,7 +59,7 @@ enum EXTENSION_COMMANDS { 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_GENERATE_OBJECTID_TO_CLIPBOARD = 'mdb.generateObjectIdToClipboard', } export default EXTENSION_COMMANDS; diff --git a/src/commands/launchMongoShell.ts b/src/commands/launchMongoShell.ts index 9c09ada5..7d3dcf63 100644 --- a/src/commands/launchMongoShell.ts +++ b/src/commands/launchMongoShell.ts @@ -10,13 +10,11 @@ const launchMongoDBShellWithEnv = ( const mongoDBShell = vscode.window.createTerminal({ name: 'MongoDB Shell', env: { - MDB_CONNECTION_STRING: mdbConnectionString - } + MDB_CONNECTION_STRING: mdbConnectionString, + }, }); - mongoDBShell.sendText( - `${shellCommand} ${envVariableString};` - ); + mongoDBShell.sendText(`${shellCommand} ${envVariableString};`); mongoDBShell.show(); }; @@ -24,34 +22,50 @@ const launchMongoDBShellOnPowershell = ( shellCommand: string, mdbConnectionString: string ): void => { - launchMongoDBShellWithEnv(shellCommand, mdbConnectionString, '$Env:MDB_CONNECTION_STRING'); + launchMongoDBShellWithEnv( + shellCommand, + mdbConnectionString, + '$Env:MDB_CONNECTION_STRING' + ); }; const launchMongoDBShellOnCmd = ( shellCommand: string, mdbConnectionString: string ): void => { - launchMongoDBShellWithEnv(shellCommand, mdbConnectionString, '%MDB_CONNECTION_STRING%'); + launchMongoDBShellWithEnv( + shellCommand, + mdbConnectionString, + '%MDB_CONNECTION_STRING%' + ); }; const launchMongoDBShellOnGitBash = ( shellCommand: string, mdbConnectionString: string ): void => { - launchMongoDBShellWithEnv(shellCommand, mdbConnectionString, '$MDB_CONNECTION_STRING'); + launchMongoDBShellWithEnv( + shellCommand, + mdbConnectionString, + '$MDB_CONNECTION_STRING' + ); }; const launchMongoDBShellOnBash = ( shellCommand: string, mdbConnectionString: string ): void => { - launchMongoDBShellWithEnv(shellCommand, mdbConnectionString, '$MDB_CONNECTION_STRING'); + launchMongoDBShellWithEnv( + shellCommand, + mdbConnectionString, + '$MDB_CONNECTION_STRING' + ); }; -const openMongoDBShell = (connectionController: ConnectionController): Promise => { - if ( - !connectionController.isCurrentlyConnected() - ) { +const openMongoDBShell = ( + connectionController: ConnectionController +): Promise => { + if (!connectionController.isCurrentlyConnected()) { void vscode.window.showErrorMessage( 'You need to be connected before launching the MongoDB Shell.' ); @@ -60,7 +74,9 @@ const openMongoDBShell = (connectionController: ConnectionController): Promise>; +type StoreConnectionInfoWithConnectionOptions = StoreConnectionInfo & + Required>; export default class ConnectionController { // This is a map of connection ids to their configurations. // These connections can be saved on the session (runtime), // on the workspace, or globally in vscode. - _connections: { [connectionId: string]: StoreConnectionInfoWithConnectionOptions } = {}; + _connections: { + [connectionId: string]: StoreConnectionInfoWithConnectionOptions; + } = {}; _activeDataService: DataService | null = null; _storageController: StorageController; @@ -111,18 +117,22 @@ export default class ConnectionController { savedConnectionInfo: StoreConnectionInfo ): Promise { if (!savedConnectionInfo.connectionModel) { - throw new Error('The connectionModel object is missing in saved connection info.'); + throw new Error( + 'The connectionModel object is missing in saved connection info.' + ); } // Transform a raw connection model from storage to an ampersand model. - const newConnectionInfoWithSecrets = convertConnectionModelToInfo(savedConnectionInfo.connectionModel); + const newConnectionInfoWithSecrets = convertConnectionModelToInfo( + savedConnectionInfo.connectionModel + ); // Further use connectionOptions instead of connectionModel. const newSavedConnectionInfoWithSecrets = { id: savedConnectionInfo.id, name: savedConnectionInfo.name, storageLocation: savedConnectionInfo.storageLocation, - connectionOptions: newConnectionInfoWithSecrets.connectionOptions + connectionOptions: newConnectionInfoWithSecrets.connectionOptions, }; await this._saveConnection(newSavedConnectionInfoWithSecrets); @@ -132,7 +142,7 @@ export default class ConnectionController { async _getConnectionInfoWithSecrets( savedConnectionInfo: StoreConnectionInfo - ): Promise { + ): Promise { // Migrate previously saved connections to a new format. // Save only secrets to keychain. // Remove connectionModel and use connectionOptions instead. @@ -152,7 +162,9 @@ export default class ConnectionController { // If connection has a new format already and keytar module is undefined. // Return saved connection as it is. if (!ext.keytarModule) { - log.error('Load saved connections failed: VSCode extension keytar module is undefined.'); + log.error( + 'Load saved connections failed: VSCode extension keytar module is undefined.' + ); return savedConnectionInfo as StoreConnectionInfoWithConnectionOptions; } @@ -172,19 +184,21 @@ export default class ConnectionController { const connectionInfoWithSecrets = mergeSecrets( { id: savedConnectionInfo.id, - connectionOptions + connectionOptions, } as ConnectionInfo, secrets ); return { ...savedConnectionInfo, - connectionOptions: connectionInfoWithSecrets.connectionOptions + connectionOptions: connectionInfoWithSecrets.connectionOptions, }; } catch (error) { // Here we're lenient when loading connections in case their // connections have become corrupted. - log.error(`Merging connection with secrets failed: ${formatError(error).message}`); + log.error( + `Merging connection with secrets failed: ${formatError(error).message}` + ); return; } } @@ -203,9 +217,10 @@ export default class ConnectionController { await Promise.all( Object.keys(savedConnections).map(async (connectionId) => { // Get connection info from vscode storage and merge with secrets. - const connectionInfoWithSecrets = await this._getConnectionInfoWithSecrets( - savedConnections[connectionId] - ); + const connectionInfoWithSecrets = + await this._getConnectionInfoWithSecrets( + savedConnections[connectionId] + ); // Save connection info with secrets to extension memory. if (connectionInfoWithSecrets) { @@ -218,21 +233,24 @@ export default class ConnectionController { } async loadSavedConnections(): Promise { - await Promise.all([(async() => { - // Try to pull in the connections previously saved in the global storage of vscode. - const existingGlobalConnections = this._storageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS, - StorageLocation.GLOBAL - ); - await this._loadSavedConnectionsByStore(existingGlobalConnections); - })(), (async() => { - // Try to pull in the connections previously saved in the workspace storage of vscode. - const existingWorkspaceConnections = this._storageController.get( - StorageVariables.WORKSPACE_SAVED_CONNECTIONS, - StorageLocation.WORKSPACE - ); - await this._loadSavedConnectionsByStore(existingWorkspaceConnections); - })()]); + await Promise.all([ + (async () => { + // Try to pull in the connections previously saved in the global storage of vscode. + const existingGlobalConnections = this._storageController.get( + StorageVariables.GLOBAL_SAVED_CONNECTIONS, + StorageLocation.GLOBAL + ); + await this._loadSavedConnectionsByStore(existingGlobalConnections); + })(), + (async () => { + // Try to pull in the connections previously saved in the workspace storage of vscode. + const existingWorkspaceConnections = this._storageController.get( + StorageVariables.WORKSPACE_SAVED_CONNECTIONS, + StorageLocation.WORKSPACE + ); + await this._loadSavedConnectionsByStore(existingWorkspaceConnections); + })(), + ]); } async connectWithURI(): Promise { @@ -248,7 +266,10 @@ export default class ConnectionController { 'e.g. mongodb+srv://username:password@cluster0.mongodb.net/admin', prompt: 'Enter your connection string (SRV or standard)', validateInput: (uri: string) => { - if (!uri.startsWith('mongodb://') && !uri.startsWith('mongodb+srv://')) { + if ( + !uri.startsWith('mongodb://') && + !uri.startsWith('mongodb+srv://') + ) { return 'MongoDB connection strings begin with "mongodb://" or "mongodb+srv://"'; } @@ -260,7 +281,7 @@ export default class ConnectionController { } return null; - } + }, }); } catch (e) { return false; @@ -285,15 +306,18 @@ export default class ConnectionController { // TODO: Allow overriding appname + use driverInfo instead // (https://jira.mongodb.org/browse/MONGOSH-1015) - connectionStringData.searchParams.set('appname', `${packageJSON.name} ${packageJSON.version}`); + connectionStringData.searchParams.set( + 'appname', + `${packageJSON.name} ${packageJSON.version}` + ); try { const connectResult = await this.saveNewConnectionAndConnect( { id: uuidv4(), connectionOptions: { - connectionString: connectionStringData.toString() - } + connectionString: connectionStringData.toString(), + }, }, ConnectionTypes.CONNECTION_STRING ); @@ -302,26 +326,37 @@ export default class ConnectionController { } catch (error) { const printableError = formatError(error); log.error('Failed to connect', printableError); - void vscode.window.showErrorMessage(`Unable to connect: ${printableError.message}`); + void vscode.window.showErrorMessage( + `Unable to connect: ${printableError.message}` + ); return false; } } - public sendTelemetry(newDataService: DataService, connectionType: ConnectionTypes): void { - void this._telemetryService.trackNewConnection(newDataService, connectionType); + public sendTelemetry( + newDataService: DataService, + connectionType: ConnectionTypes + ): void { + void this._telemetryService.trackNewConnection( + newDataService, + connectionType + ); } - parseNewConnection(rawConnectionModel: LegacyConnectionModel): ConnectionInfo { + parseNewConnection( + rawConnectionModel: LegacyConnectionModel + ): ConnectionInfo { return convertConnectionModelToInfo({ ...rawConnectionModel, - appname: `${packageJSON.name} ${packageJSON.version}` // Override the default connection appname. + appname: `${packageJSON.name} ${packageJSON.version}`, // Override the default connection appname. }); } - private async _saveSecretsToKeychain( - { connectionId, secrets }: ConnectionSecretsInfo - ): Promise { + private async _saveSecretsToKeychain({ + connectionId, + secrets, + }: ConnectionSecretsInfo): Promise { if (!ext.keytarModule) { return; } @@ -344,12 +379,12 @@ export default class ConnectionController { ); const savedConnectionInfo = await this._storageController.saveConnection({ ...newStoreConnectionInfoWithSecrets, - connectionOptions: safeConnectionInfo.connectionOptions // The connection info without secrets. + connectionOptions: safeConnectionInfo.connectionOptions, // The connection info without secrets. }); await this._saveSecretsToKeychain({ connectionId: savedConnectionInfo.id, - secrets // Only secrets. + secrets, // Only secrets. }); return savedConnectionInfo; @@ -366,17 +401,19 @@ export default class ConnectionController { // To begin we just store it on the session, the storage controller // handles changing this based on user preference. storageLocation: StorageLocation.NONE, - connectionOptions: originalConnectionInfo.connectionOptions + connectionOptions: originalConnectionInfo.connectionOptions, }; const savedConnectionInfo = await this._saveConnection(newConnectionInfo); this._connections[savedConnectionInfo.id] = { ...savedConnectionInfo, - connectionOptions: originalConnectionInfo.connectionOptions // The connection options with secrets. + connectionOptions: originalConnectionInfo.connectionOptions, // The connection options with secrets. }; - log.info(`Connect called to connect to instance: ${savedConnectionInfo.name}`); + log.info( + `Connect called to connect to instance: ${savedConnectionInfo.name}` + ); return this._connect(savedConnectionInfo.id, connectionType); } @@ -414,12 +451,16 @@ export default class ConnectionController { connectError = error; } - const shouldEndPrevConnectAttempt = this._endPrevConnectAttempt({ connectionId, connectingAttemptVersion, newDataService }); + const shouldEndPrevConnectAttempt = this._endPrevConnectAttempt({ + connectionId, + connectingAttemptVersion, + newDataService, + }); if (shouldEndPrevConnectAttempt) { return { successfullyConnected: false, - connectionErrorMessage: 'connection attempt overriden' + connectionErrorMessage: 'connection attempt overriden', }; } @@ -447,14 +488,14 @@ export default class ConnectionController { return { successfullyConnected: true, - connectionErrorMessage: '' + connectionErrorMessage: '', }; } - private _endPrevConnectAttempt (attempt: { - connectionId: string, - connectingAttemptVersion: null | string, - newDataService: DataService + private _endPrevConnectAttempt(attempt: { + connectionId: string; + connectingAttemptVersion: null | string; + newDataService: DataService; }): boolean { const { connectionId, connectingAttemptVersion, newDataService } = attempt; @@ -465,7 +506,9 @@ export default class ConnectionController { // If the current attempt is no longer the most recent attempt // or the connection no longer exists we silently end the connection // and return. - void newDataService.disconnect().catch(() => { /* ignore */ }); + void newDataService.disconnect().catch(() => { + /* ignore */ + }); return true; } @@ -485,7 +528,9 @@ export default class ConnectionController { } catch (error) { const printableError = formatError(error); log.error('Failed to connect', printableError); - void vscode.window.showErrorMessage(`Unable to connect: ${printableError.message}`); + void vscode.window.showErrorMessage( + `Unable to connect: ${printableError.message}` + ); return false; } @@ -555,11 +600,12 @@ export default class ConnectionController { return false; } - const removeConfirmationResponse = await vscode.window.showInformationMessage( - `Are you sure to want to remove connection ${this._connections[connectionId].name}?`, - { modal: true }, - 'Yes' - ); + const removeConfirmationResponse = + await vscode.window.showInformationMessage( + `Are you sure to want to remove connection ${this._connections[connectionId].name}?`, + { modal: true }, + 'Yes' + ); if (removeConfirmationResponse !== 'Yes') { return false; @@ -599,14 +645,13 @@ export default class ConnectionController { // There is more than 1 possible connection to remove. // We attach the index of the connection so that we can infer their pick. - const connectionNameToRemove: - | string - | undefined = await vscode.window.showQuickPick( + const connectionNameToRemove: string | undefined = + await vscode.window.showQuickPick( connectionIds.map( (id, index) => `${index + 1}: ${this._connections[id].name}` ), { - placeHolder: 'Choose a connection to remove...' + placeHolder: 'Choose a connection to remove...', } ); @@ -639,7 +684,7 @@ export default class ConnectionController { } return null; - } + }, }); } catch (e) { throw new Error(`An error occured parsing the connection name: ${e}`); @@ -653,7 +698,9 @@ export default class ConnectionController { this.eventEmitter.emit(DataServiceEventTypes.CONNECTIONS_DID_CHANGE); this.eventEmitter.emit(DataServiceEventTypes.ACTIVE_CONNECTION_CHANGED); - await this._storageController.saveConnection(this._connections[connectionId]); + await this._storageController.saveConnection( + this._connections[connectionId] + ); // No storing needed. return true; @@ -713,23 +760,40 @@ export default class ConnectionController { : ''; } - _getConnectionStringWithProxy(mongoClientConnectionOptions: { url: string; options: MongoClientOptions; }): string { - const connectionStringData = new ConnectionString(mongoClientConnectionOptions.url); + _getConnectionStringWithProxy(mongoClientConnectionOptions: { + url: string; + options: MongoClientOptions; + }): string { + const connectionStringData = new ConnectionString( + mongoClientConnectionOptions.url + ); if (mongoClientConnectionOptions.options.proxyHost) { - connectionStringData.searchParams.set('proxyHost', mongoClientConnectionOptions.options.proxyHost); + connectionStringData.searchParams.set( + 'proxyHost', + mongoClientConnectionOptions.options.proxyHost + ); } if (mongoClientConnectionOptions.options.proxyPassword) { - connectionStringData.searchParams.set('proxyPassword', mongoClientConnectionOptions.options.proxyPassword); + connectionStringData.searchParams.set( + 'proxyPassword', + mongoClientConnectionOptions.options.proxyPassword + ); } if (mongoClientConnectionOptions.options.proxyPort) { - connectionStringData.searchParams.set('proxyPort', `${mongoClientConnectionOptions.options.proxyPort}`); + connectionStringData.searchParams.set( + 'proxyPort', + `${mongoClientConnectionOptions.options.proxyPort}` + ); } if (mongoClientConnectionOptions.options.proxyUsername) { - connectionStringData.searchParams.set('proxyUsername', mongoClientConnectionOptions.options.proxyUsername); + connectionStringData.searchParams.set( + 'proxyUsername', + mongoClientConnectionOptions.options.proxyUsername + ); } return connectionStringData.toString(); @@ -754,7 +818,9 @@ export default class ConnectionController { return this._activeDataService; } - getMongoClientConnectionOptions(): { url: string; options: MongoClientOptions; } | undefined { + getMongoClientConnectionOptions(): + | { url: string; options: MongoClientOptions } + | undefined { return this._activeDataService?.getMongoClientConnectionOptions(); } @@ -763,7 +829,9 @@ export default class ConnectionController { const connectionOptions = this._connections[connectionId].connectionOptions; if (!connectionOptions) { - throw new Error('Copy connection string failed: connectionOptions are missing.'); + throw new Error( + 'Copy connection string failed: connectionOptions are missing.' + ); } const url = new ConnectionString(connectionOptions.connectionString); @@ -839,9 +907,9 @@ export default class ConnectionController { { label: 'Add new connection', data: { - type: NewConnectionType.NEW_CONNECTION - } - } + type: NewConnectionType.NEW_CONNECTION, + }, + }, ]; } @@ -849,20 +917,23 @@ export default class ConnectionController { { label: 'Add new connection', data: { - type: NewConnectionType.NEW_CONNECTION - } + type: NewConnectionType.NEW_CONNECTION, + }, }, ...Object.values(this._connections) - .sort((connectionA: StoreConnectionInfo, connectionB: StoreConnectionInfo) => - (connectionA.name || '').localeCompare(connectionB.name || '') + .sort( + ( + connectionA: StoreConnectionInfo, + connectionB: StoreConnectionInfo + ) => (connectionA.name || '').localeCompare(connectionB.name || '') ) .map((item: StoreConnectionInfo) => ({ label: item.name, data: { type: NewConnectionType.SAVED_CONNECTION, - connectionId: item.id - } - })) + connectionId: item.id, + }, + })), ]; } @@ -870,7 +941,7 @@ export default class ConnectionController { const selectedQuickPickItem = await vscode.window.showQuickPick( this.getConnectionQuickPicks(), { - placeHolder: 'Select new connection...' + placeHolder: 'Select new connection...', } ); @@ -886,6 +957,8 @@ export default class ConnectionController { return true; } - return this.connectWithConnectionId(selectedQuickPickItem.data.connectionId); + return this.connectWithConnectionId( + selectedQuickPickItem.data.connectionId + ); } } diff --git a/src/documentSource.ts b/src/documentSource.ts index 82db4eeb..171e3e48 100644 --- a/src/documentSource.ts +++ b/src/documentSource.ts @@ -1,5 +1,5 @@ export enum DocumentSource { DOCUMENT_SOURCE_TREEVIEW = 'treeview', DOCUMENT_SOURCE_PLAYGROUND = 'playground', - DOCUMENT_SOURCE_COLLECTIONVIEW = 'collectionview' + DOCUMENT_SOURCE_COLLECTIONVIEW = 'collectionview', } diff --git a/src/editors/activeConnectionCodeLensProvider.ts b/src/editors/activeConnectionCodeLensProvider.ts index cdd4edf8..0013db8e 100644 --- a/src/editors/activeConnectionCodeLensProvider.ts +++ b/src/editors/activeConnectionCodeLensProvider.ts @@ -3,12 +3,14 @@ import EXTENSION_COMMANDS from '../commands'; import ConnectionController from '../connectionController'; export default class ActiveConnectionCodeLensProvider -implements vscode.CodeLensProvider { + implements vscode.CodeLensProvider +{ _connectionController: ConnectionController; - _onDidChangeCodeLenses: vscode.EventEmitter = new vscode.EventEmitter(); + _onDidChangeCodeLenses: vscode.EventEmitter = + new vscode.EventEmitter(); - readonly onDidChangeCodeLenses: vscode.Event = this - ._onDidChangeCodeLenses.event; + readonly onDidChangeCodeLenses: vscode.Event = + this._onDidChangeCodeLenses.event; constructor(connectionController: ConnectionController) { this._connectionController = connectionController; @@ -37,7 +39,7 @@ implements vscode.CodeLensProvider { codeLens.command = { title: message, command: EXTENSION_COMMANDS.MDB_CHANGE_ACTIVE_CONNECTION, - arguments: [] + arguments: [], }; return [codeLens]; diff --git a/src/editors/codeActionProvider.ts b/src/editors/codeActionProvider.ts index d21924ea..453339f6 100644 --- a/src/editors/codeActionProvider.ts +++ b/src/editors/codeActionProvider.ts @@ -4,7 +4,8 @@ import EXTENSION_COMMANDS from '../commands'; import { ExportToLanguageMode } from '../types/playgroundType'; export default class CodeActionProvider implements vscode.CodeActionProvider { - _onDidChangeCodeCodeAction: vscode.EventEmitter = new vscode.EventEmitter(); + _onDidChangeCodeCodeAction: vscode.EventEmitter = + new vscode.EventEmitter(); selection?: vscode.Selection; mode?: ExportToLanguageMode; @@ -16,10 +17,16 @@ export default class CodeActionProvider implements vscode.CodeActionProvider { }); } - readonly onDidChangeCodeLenses: vscode.Event = this - ._onDidChangeCodeCodeAction.event; + readonly onDidChangeCodeLenses: vscode.Event = + this._onDidChangeCodeCodeAction.event; - refresh({ selection, mode }: { selection?: vscode.Selection, mode?: ExportToLanguageMode }): void { + refresh({ + selection, + mode, + }: { + selection?: vscode.Selection; + mode?: ExportToLanguageMode; + }): void { this.selection = selection; this.mode = mode; this._onDidChangeCodeCodeAction.fire(); @@ -31,52 +38,73 @@ export default class CodeActionProvider implements vscode.CodeActionProvider { } const codeActions: vscode.CodeAction[] = []; - const runSelectedPlaygroundBlockCommand = new vscode.CodeAction('Run selected playground blocks', vscode.CodeActionKind.Empty); + const runSelectedPlaygroundBlockCommand = new vscode.CodeAction( + 'Run selected playground blocks', + vscode.CodeActionKind.Empty + ); runSelectedPlaygroundBlockCommand.command = { command: EXTENSION_COMMANDS.MDB_RUN_SELECTED_PLAYGROUND_BLOCKS, title: 'Run selected playground blocks', - tooltip: 'Run selected playground blocks' + tooltip: 'Run selected playground blocks', }; codeActions.push(runSelectedPlaygroundBlockCommand); - if (this.mode === ExportToLanguageMode.QUERY || this.mode === ExportToLanguageMode.AGGREGATION) { - const exportToPythonCommand = new vscode.CodeAction('Export To Python 3', vscode.CodeActionKind.Empty); + if ( + this.mode === ExportToLanguageMode.QUERY || + this.mode === ExportToLanguageMode.AGGREGATION + ) { + const exportToPythonCommand = new vscode.CodeAction( + 'Export To Python 3', + vscode.CodeActionKind.Empty + ); exportToPythonCommand.command = { command: EXTENSION_COMMANDS.MDB_EXPORT_TO_PYTHON, title: 'Export To Python 3', - tooltip: 'Export To Python 3' + tooltip: 'Export To Python 3', }; codeActions.push(exportToPythonCommand); - const exportToJavaCommand = new vscode.CodeAction('Export To Java', vscode.CodeActionKind.Empty); + const exportToJavaCommand = new vscode.CodeAction( + 'Export To Java', + vscode.CodeActionKind.Empty + ); exportToJavaCommand.command = { command: EXTENSION_COMMANDS.MDB_EXPORT_TO_JAVA, title: 'Export To Java', - tooltip: 'Export To Java' + tooltip: 'Export To Java', }; codeActions.push(exportToJavaCommand); - const exportToCsharpCommand = new vscode.CodeAction('Export To C#', vscode.CodeActionKind.Empty); + const exportToCsharpCommand = new vscode.CodeAction( + 'Export To C#', + vscode.CodeActionKind.Empty + ); exportToCsharpCommand.command = { command: EXTENSION_COMMANDS.MDB_EXPORT_TO_CSHARP, title: 'Export To C#', - tooltip: 'Export To C#' + tooltip: 'Export To C#', }; codeActions.push(exportToCsharpCommand); - const exportToJSCommand = new vscode.CodeAction('Export To Node.js', vscode.CodeActionKind.Empty); + const exportToJSCommand = new vscode.CodeAction( + 'Export To Node.js', + vscode.CodeActionKind.Empty + ); exportToJSCommand.command = { command: EXTENSION_COMMANDS.MDB_EXPORT_TO_NODE, title: 'Export To Node.js', - tooltip: 'Export To Node.js' + tooltip: 'Export To Node.js', }; codeActions.push(exportToJSCommand); - const exportToRubyCommand = new vscode.CodeAction('Export To Ruby', vscode.CodeActionKind.Empty); + const exportToRubyCommand = new vscode.CodeAction( + 'Export To Ruby', + vscode.CodeActionKind.Empty + ); exportToRubyCommand.command = { command: EXTENSION_COMMANDS.MDB_EXPORT_TO_RUBY, title: 'Export To Ruby', - tooltip: 'Export To Ruby' + tooltip: 'Export To Ruby', }; codeActions.push(exportToRubyCommand); } diff --git a/src/editors/collectionDocumentsCodeLensProvider.ts b/src/editors/collectionDocumentsCodeLensProvider.ts index 26b3e27d..508203aa 100644 --- a/src/editors/collectionDocumentsCodeLensProvider.ts +++ b/src/editors/collectionDocumentsCodeLensProvider.ts @@ -6,18 +6,19 @@ import CollectionDocumentsOperationStore from './collectionDocumentsOperationsSt import { CONNECTION_ID_URI_IDENTIFIER, NAMESPACE_URI_IDENTIFIER, - OPERATION_ID_URI_IDENTIFIER + OPERATION_ID_URI_IDENTIFIER, } from './collectionDocumentsProvider'; -export default class CollectionDocumentsCodeLensProvider implements vscode.CodeLensProvider { +export default class CollectionDocumentsCodeLensProvider + implements vscode.CodeLensProvider +{ _codeLenses: vscode.CodeLens[] = []; _activeOperationsStore: CollectionDocumentsOperationStore; _uri: vscode.Uri = vscode.Uri.parse(''); - _onDidChangeCodeLenses: vscode.EventEmitter< - void - > = new vscode.EventEmitter(); - readonly onDidChangeCodeLenses: vscode.Event = this - ._onDidChangeCodeLenses.event; + _onDidChangeCodeLenses: vscode.EventEmitter = + new vscode.EventEmitter(); + readonly onDidChangeCodeLenses: vscode.Event = + this._onDidChangeCodeLenses.event; constructor(operationsStore: CollectionDocumentsOperationStore) { this._activeOperationsStore = operationsStore; @@ -50,7 +51,7 @@ export default class CollectionDocumentsCodeLensProvider implements vscode.CodeL new vscode.Position(document.lineCount - 1, 0), new vscode.Position(document.lineCount, 0) ) - ) + ), ]; this._uri = document.uri; @@ -91,7 +92,7 @@ export default class CollectionDocumentsCodeLensProvider implements vscode.CodeL title: commandTitle, tooltip: commandTooltip, command: EXTENSION_COMMANDS.MDB_CODELENS_SHOW_MORE_DOCUMENTS, - arguments: [{ operationId, connectionId, namespace }] + arguments: [{ operationId, connectionId, namespace }], }; return codeLens; diff --git a/src/editors/collectionDocumentsProvider.ts b/src/editors/collectionDocumentsProvider.ts index aaa2a76f..857bfff0 100644 --- a/src/editors/collectionDocumentsProvider.ts +++ b/src/editors/collectionDocumentsProvider.ts @@ -15,7 +15,8 @@ export const CONNECTION_ID_URI_IDENTIFIER = 'connectionId'; export const VIEW_COLLECTION_SCHEME = 'VIEW_COLLECTION_SCHEME'; export default class CollectionViewProvider -implements vscode.TextDocumentContentProvider { + implements vscode.TextDocumentContentProvider +{ _context: vscode.ExtensionContext; _connectionController: ConnectionController; _operationsStore: CollectionDocumentsOperationsStore; @@ -81,9 +82,7 @@ implements vscode.TextDocumentContentProvider { } try { - const find = util.promisify( - dataservice.find.bind(dataservice) - ); + const find = util.promisify(dataservice.find.bind(dataservice)); const documents = await find( namespace, {}, // No filter. @@ -100,12 +99,14 @@ implements vscode.TextDocumentContentProvider { this._editDocumentCodeLensProvider.updateCodeLensesForCollection({ content: documents, namespace, - uri + uri, }); return JSON.stringify(documents, null, 2); } catch (error) { - const errorMessage = `Unable to list documents: ${formatError(error).message}`; + const errorMessage = `Unable to list documents: ${ + formatError(error).message + }`; void vscode.window.showErrorMessage(errorMessage); diff --git a/src/editors/documentIdStore.ts b/src/editors/documentIdStore.ts index cf8212a2..2971a109 100644 --- a/src/editors/documentIdStore.ts +++ b/src/editors/documentIdStore.ts @@ -25,7 +25,7 @@ export default class DocumentIdStore { documentId: EJSON.SerializableTypes; } = { documentIdReference: uuidv4(), - documentId + documentId, }; this._documents.push(newDocument); diff --git a/src/editors/editDocumentCodeLensProvider.ts b/src/editors/editDocumentCodeLensProvider.ts index e71a06c5..41aa446f 100644 --- a/src/editors/editDocumentCodeLensProvider.ts +++ b/src/editors/editDocumentCodeLensProvider.ts @@ -9,14 +9,16 @@ import { PLAYGROUND_RESULT_URI } from './playgroundResultProvider'; import type { PlaygroundResult } from '../types/playgroundType'; export default class EditDocumentCodeLensProvider -implements vscode.CodeLensProvider { - _onDidChangeCodeLenses: vscode.EventEmitter = new vscode.EventEmitter(); + implements vscode.CodeLensProvider +{ + _onDidChangeCodeLenses: vscode.EventEmitter = + new vscode.EventEmitter(); _codeLenses: vscode.CodeLens[] = []; _codeLensesInfo: { [name: string]: EditDocumentInfo[] } | {} = {}; _connectionController: ConnectionController; - readonly onDidChangeCodeLenses: vscode.Event = this - ._onDidChangeCodeLenses.event; + readonly onDidChangeCodeLenses: vscode.Event = + this._onDidChangeCodeLenses.event; constructor(connectionController: ConnectionController) { this._connectionController = connectionController; @@ -27,15 +29,15 @@ implements vscode.CodeLensProvider { } updateCodeLensesForCollection(data: { - content: EJSON.SerializableTypes, - namespace: string | null, - uri: vscode.Uri + content: EJSON.SerializableTypes; + namespace: string | null; + uri: vscode.Uri; }) { let resultCodeLensesInfo: EditDocumentInfo[] = []; resultCodeLensesInfo = this._updateCodeLensesForCursor({ ...data, - source: DocumentSource.DOCUMENT_SOURCE_COLLECTIONVIEW + source: DocumentSource.DOCUMENT_SOURCE_COLLECTIONVIEW, }); this._codeLensesInfo[data.uri.toString()] = resultCodeLensesInfo; @@ -62,13 +64,14 @@ implements vscode.CodeLensProvider { resultCodeLensesInfo = this._updateCodeLensesForDocument(data); } - this._codeLensesInfo[PLAYGROUND_RESULT_URI.toString()] = resultCodeLensesInfo; + this._codeLensesInfo[PLAYGROUND_RESULT_URI.toString()] = + resultCodeLensesInfo; } _updateCodeLensesForCursor(data: { - content: any, - namespace: string | null, - source: DocumentSource + content: any; + namespace: string | null; + source: DocumentSource; }): EditDocumentInfo[] { const resultCodeLensesInfo: EditDocumentInfo[] = []; @@ -89,7 +92,7 @@ implements vscode.CodeLensProvider { source, line, namespace, - connectionId + connectionId, }); // To calculate the position of the next open curly bracket, @@ -104,9 +107,9 @@ implements vscode.CodeLensProvider { } _updateCodeLensesForDocument(data: { - content: any, - namespace: string | null, - source: DocumentSource + content: any; + namespace: string | null; + source: DocumentSource; }): EditDocumentInfo[] { const { content, namespace, source } = data; const resultCodeLensesInfo: EditDocumentInfo[] = []; @@ -121,7 +124,7 @@ implements vscode.CodeLensProvider { source, line: 1, namespace, - connectionId + connectionId, }); } @@ -131,7 +134,8 @@ implements vscode.CodeLensProvider { provideCodeLenses(): vscode.CodeLens[] { this._codeLenses = []; - const activeEditorUri = vscode.window.activeTextEditor?.document.uri.toString(); + const activeEditorUri = + vscode.window.activeTextEditor?.document.uri.toString(); if (activeEditorUri && this._codeLensesInfo[activeEditorUri]) { this._codeLensesInfo[activeEditorUri].forEach((item) => { @@ -144,7 +148,7 @@ implements vscode.CodeLensProvider { } = { title: 'Edit Document', command: EXTENSION_COMMANDS.MDB_OPEN_MONGODB_DOCUMENT_FROM_CODE_LENS, - arguments: [item] + arguments: [item], }; this._codeLenses.push(new vscode.CodeLens(range, command)); diff --git a/src/editors/editorsController.ts b/src/editors/editorsController.ts index 6357b22d..8595a217 100644 --- a/src/editors/editorsController.ts +++ b/src/editors/editorsController.ts @@ -11,7 +11,7 @@ import CollectionDocumentsProvider, { CONNECTION_ID_URI_IDENTIFIER, OPERATION_ID_URI_IDENTIFIER, NAMESPACE_URI_IDENTIFIER, - VIEW_COLLECTION_SCHEME + VIEW_COLLECTION_SCHEME, } from './collectionDocumentsProvider'; import { createLogger } from '../logging'; import DocumentIdStore from './documentIdStore'; @@ -23,11 +23,11 @@ import { MemoryFileSystemProvider } from './memoryFileSystemProvider'; import MongoDBDocumentService, { DOCUMENT_ID_URI_IDENTIFIER, DOCUMENT_SOURCE_URI_IDENTIFIER, - VIEW_DOCUMENT_SCHEME + VIEW_DOCUMENT_SCHEME, } from './mongoDBDocumentService'; import PlaygroundController from './playgroundController'; import PlaygroundResultProvider, { - PLAYGROUND_RESULT_SCHEME + PLAYGROUND_RESULT_SCHEME, } from './playgroundResultProvider'; import { StatusView } from '../views'; import TelemetryService from '../telemetry/telemetryService'; @@ -42,13 +42,12 @@ export function getFileDisplayNameForDocument( // Encode special file uri characters to ensure VSCode handles // it correctly in a uri while avoiding collisions. - displayName = displayName.replace(/[\\/%]/gi, function(c) { + displayName = displayName.replace(/[\\/%]/gi, function (c) { return `%${c.charCodeAt(0).toString(16)}`; }); - displayName = displayName.length > 200 - ? displayName.substring(0, 200) - : displayName; + displayName = + displayName.length > 200 ? displayName.substring(0, 200) : displayName; return displayName; } @@ -68,7 +67,7 @@ export function getViewCollectionDocumentsUri( // Encode special file uri characters to ensure VSCode handles // it correctly in a uri while avoiding collisions. const namespaceDisplayName = encodeURIComponent( - namespace.replace(/[\\/%]/gi, function(c) { + namespace.replace(/[\\/%]/gi, function (c) { return `%${c.charCodeAt(0).toString(16)}`; }) ); @@ -87,7 +86,8 @@ export default class EditorsController { _codeActionProvider: CodeActionProvider; _connectionController: ConnectionController; _playgroundController: PlaygroundController; - _collectionDocumentsOperationsStore = new CollectionDocumentsOperationsStore(); + _collectionDocumentsOperationsStore = + new CollectionDocumentsOperationsStore(); _collectionViewProvider: CollectionDocumentsProvider; _context: vscode.ExtensionContext; _statusView: StatusView; @@ -140,9 +140,10 @@ export default class EditorsController { this._playgroundResultViewProvider = playgroundResultViewProvider; this._activeConnectionCodeLensProvider = activeConnectionCodeLensProvider; this._exportToLanguageCodeLensProvider = exportToLanguageCodeLensProvider; - this._collectionDocumentsCodeLensProvider = new CollectionDocumentsCodeLensProvider( - this._collectionDocumentsOperationsStore - ); + this._collectionDocumentsCodeLensProvider = + new CollectionDocumentsCodeLensProvider( + this._collectionDocumentsOperationsStore + ); this._codeActionProvider = codeActionProvider; vscode.workspace.onDidCloseTextDocument((e) => { @@ -164,7 +165,9 @@ export default class EditorsController { if (mdbDocument === null) { void vscode.window.showErrorMessage(` - Unable to open mongodb document: document ${JSON.stringify(data.documentId)} not found + Unable to open mongodb document: document ${JSON.stringify( + data.documentId + )} not found `); return false; @@ -178,14 +181,13 @@ export default class EditorsController { const documentIdUriQuery = `${DOCUMENT_ID_URI_IDENTIFIER}=${documentIdReference}`; const documentSourceUriQuery = `${DOCUMENT_SOURCE_URI_IDENTIFIER}=${data.source}`; - const fileTitle = encodeURIComponent(getFileDisplayNameForDocument( - data.documentId, - data.namespace - )); + const fileTitle = encodeURIComponent( + getFileDisplayNameForDocument(data.documentId, data.namespace) + ); const fileName = `${VIEW_DOCUMENT_SCHEME}:/${fileTitle}.json`; const fileUri = vscode.Uri.parse(fileName, true).with({ - query: `?${namespaceUriQuery}&${connectionIdUriQuery}&${documentIdUriQuery}&${documentSourceUriQuery}` + query: `?${namespaceUriQuery}&${connectionIdUriQuery}&${documentIdUriQuery}&${documentSourceUriQuery}`, }); this._saveDocumentToMemoryFileSystem(fileUri, mdbDocument); @@ -216,7 +218,9 @@ export default class EditorsController { const connectionId = uriParams.get(CONNECTION_ID_URI_IDENTIFIER); const documentIdReference = uriParams.get(DOCUMENT_ID_URI_IDENTIFIER) || ''; const documentId = this._documentIdStore.get(documentIdReference); - const source = uriParams.get(DOCUMENT_SOURCE_URI_IDENTIFIER) as DocumentSource; + const source = uriParams.get( + DOCUMENT_SOURCE_URI_IDENTIFIER + ) as DocumentSource; // If not MongoDB document save to disk instead of MongoDB. if ( @@ -240,7 +244,7 @@ export default class EditorsController { connectionId, documentId, newDocument, - source + source, }); // Save document changes to active editor. @@ -261,7 +265,8 @@ export default class EditorsController { async onViewCollectionDocuments(namespace: string): Promise { log.info('view collection documents', namespace); - const operationId = this._collectionDocumentsOperationsStore.createNewOperation(); + const operationId = + this._collectionDocumentsOperationsStore.createNewOperation(); const activeConnectionId = this._connectionController.getActiveConnectionId() || ''; const uri = getViewCollectionDocumentsUri( @@ -298,9 +303,7 @@ export default class EditorsController { this._collectionDocumentsOperationsStore.operations[operationId] .isCurrentlyFetchingMoreDocuments ) { - void vscode.window.showErrorMessage( - 'Already fetching more documents...' - ); + void vscode.window.showErrorMessage('Already fetching more documents...'); return Promise.resolve(false); } @@ -365,7 +368,7 @@ export default class EditorsController { VIEW_DOCUMENT_SCHEME, this._memoryFileSystemProvider, { - isCaseSensitive: true + isCaseSensitive: true, } ) ); @@ -387,7 +390,7 @@ export default class EditorsController { vscode.languages.registerCodeLensProvider( { scheme: VIEW_COLLECTION_SCHEME, - language: 'json' + language: 'json', }, this._collectionDocumentsCodeLensProvider ) @@ -401,7 +404,7 @@ export default class EditorsController { this._context.subscriptions.push( vscode.languages.registerCodeLensProvider( { - scheme: PLAYGROUND_RESULT_SCHEME + scheme: PLAYGROUND_RESULT_SCHEME, }, this._exportToLanguageCodeLensProvider ) @@ -410,7 +413,7 @@ export default class EditorsController { vscode.languages.registerCodeLensProvider( { scheme: PLAYGROUND_RESULT_SCHEME, - language: 'json' + language: 'json', }, this._editDocumentCodeLensProvider ) @@ -419,15 +422,19 @@ export default class EditorsController { vscode.languages.registerCodeLensProvider( { scheme: VIEW_COLLECTION_SCHEME, - language: 'json' + language: 'json', }, this._editDocumentCodeLensProvider ) ); this._context.subscriptions.push( - vscode.languages.registerCodeActionsProvider('mongodb', this._codeActionProvider, { - providedCodeActionKinds: CodeActionProvider.providedCodeActionKinds - }) + vscode.languages.registerCodeActionsProvider( + 'mongodb', + this._codeActionProvider, + { + providedCodeActionKinds: CodeActionProvider.providedCodeActionKinds, + } + ) ); } diff --git a/src/editors/exportToLanguageCodeLensProvider.ts b/src/editors/exportToLanguageCodeLensProvider.ts index 94141180..3e2f01ad 100644 --- a/src/editors/exportToLanguageCodeLensProvider.ts +++ b/src/editors/exportToLanguageCodeLensProvider.ts @@ -4,23 +4,25 @@ import EXTENSION_COMMANDS from '../commands'; import { ExportToLanguageMode, ExportToLanguageAddons, - ExportToLanguages + ExportToLanguages, } from '../types/playgroundType'; export default class ExportToLanguageCodeLensProvider -implements vscode.CodeLensProvider { - _onDidChangeCodeLenses: vscode.EventEmitter = new vscode.EventEmitter(); + implements vscode.CodeLensProvider +{ + _onDidChangeCodeLenses: vscode.EventEmitter = + new vscode.EventEmitter(); _exportToLanguageAddons: ExportToLanguageAddons; - readonly onDidChangeCodeLenses: vscode.Event = this - ._onDidChangeCodeLenses.event; + readonly onDidChangeCodeLenses: vscode.Event = + this._onDidChangeCodeLenses.event; constructor() { this._exportToLanguageAddons = { importStatements: false, driverSyntax: false, builders: false, - language: 'shell' + language: 'shell', }; vscode.workspace.onDidChangeConfiguration(() => { @@ -44,23 +46,31 @@ implements vscode.CodeLensProvider { const exportToLanguageCodeLenses: vscode.CodeLens[] = []; importStatementsCodeLens.command = { - title: this._exportToLanguageAddons.importStatements ? 'Exclude Import Statements' : 'Include Import Statements', + title: this._exportToLanguageAddons.importStatements + ? 'Exclude Import Statements' + : 'Include Import Statements', command: EXTENSION_COMMANDS.MDB_CHANGE_EXPORT_TO_LANGUAGE_ADDONS, - arguments: [{ - ...this._exportToLanguageAddons, - importStatements: !this._exportToLanguageAddons.importStatements - }] + arguments: [ + { + ...this._exportToLanguageAddons, + importStatements: !this._exportToLanguageAddons.importStatements, + }, + ], }; exportToLanguageCodeLenses.push(importStatementsCodeLens); if (this._exportToLanguageAddons.language !== ExportToLanguages.CSHARP) { driverSyntaxCodeLens.command = { - title: this._exportToLanguageAddons.driverSyntax ? 'Exclude Driver Syntax' : 'Include Driver Syntax', + title: this._exportToLanguageAddons.driverSyntax + ? 'Exclude Driver Syntax' + : 'Include Driver Syntax', command: EXTENSION_COMMANDS.MDB_CHANGE_EXPORT_TO_LANGUAGE_ADDONS, - arguments: [{ - ...this._exportToLanguageAddons, - driverSyntax: !this._exportToLanguageAddons.driverSyntax - }] + arguments: [ + { + ...this._exportToLanguageAddons, + driverSyntax: !this._exportToLanguageAddons.driverSyntax, + }, + ], }; exportToLanguageCodeLenses.push(driverSyntaxCodeLens); } @@ -70,12 +80,16 @@ implements vscode.CodeLensProvider { this._exportToLanguageAddons.mode === ExportToLanguageMode.QUERY ) { buildersCodeLens.command = { - title: this._exportToLanguageAddons.builders ? 'Use Raw Query' : 'Use Builders', + title: this._exportToLanguageAddons.builders + ? 'Use Raw Query' + : 'Use Builders', command: EXTENSION_COMMANDS.MDB_CHANGE_EXPORT_TO_LANGUAGE_ADDONS, - arguments: [{ - ...this._exportToLanguageAddons, - builders: !this._exportToLanguageAddons.builders - }] + arguments: [ + { + ...this._exportToLanguageAddons, + builders: !this._exportToLanguageAddons.builders, + }, + ], }; exportToLanguageCodeLenses.push(buildersCodeLens); } diff --git a/src/editors/memoryFileSystemProvider.ts b/src/editors/memoryFileSystemProvider.ts index 84d8d14e..9157c298 100644 --- a/src/editors/memoryFileSystemProvider.ts +++ b/src/editors/memoryFileSystemProvider.ts @@ -221,8 +221,8 @@ export class MemoryFileSystemProvider implements vscode.FileSystemProvider { _bufferedEvents: vscode.FileChangeEvent[] = []; _fireSoonHandle?: NodeJS.Timer; - readonly onDidChangeFile: vscode.Event = this - ._emitter.event; + readonly onDidChangeFile: vscode.Event = + this._emitter.event; watch(/* _resource: vscode.Uri */): vscode.Disposable { // Ignore, fires for all changes... diff --git a/src/editors/mongoDBDocumentService.ts b/src/editors/mongoDBDocumentService.ts index c820f5ea..3b6aee3f 100644 --- a/src/editors/mongoDBDocumentService.ts +++ b/src/editors/mongoDBDocumentService.ts @@ -50,7 +50,8 @@ export default class MongoDBDocumentService { const errorMessage = `Unable to save document: ${message}`; this._telemetryService.trackDocumentUpdated( - DocumentSource.DOCUMENT_SOURCE_TREEVIEW, false + DocumentSource.DOCUMENT_SOURCE_TREEVIEW, + false ); throw new Error(errorMessage); @@ -66,10 +67,10 @@ export default class MongoDBDocumentService { log.info('replace document in MongoDB', data); const { documentId, namespace, connectionId, newDocument, source } = data; - const activeConnectionId = this._connectionController.getActiveConnectionId(); - const connectionName = this._connectionController.getSavedConnectionName( - connectionId - ); + const activeConnectionId = + this._connectionController.getActiveConnectionId(); + const connectionName = + this._connectionController.getSavedConnectionName(connectionId); if (activeConnectionId !== connectionId) { return this._saveDocumentFailed( @@ -113,7 +114,8 @@ export default class MongoDBDocumentService { log.info('fetch document from MongoDB', data); const { documentId, namespace, connectionId } = data; - const activeConnectionId = this._connectionController.getActiveConnectionId(); + const activeConnectionId = + this._connectionController.getActiveConnectionId(); const connectionName = connectionId ? this._connectionController.getSavedConnectionName(connectionId) : ''; diff --git a/src/editors/playgroundController.ts b/src/editors/playgroundController.ts index 43485caa..c3550224 100644 --- a/src/editors/playgroundController.ts +++ b/src/editors/playgroundController.ts @@ -4,10 +4,14 @@ import vm from 'vm'; import ActiveConnectionCodeLensProvider from './activeConnectionCodeLensProvider'; import CodeActionProvider from './codeActionProvider'; import ConnectionController, { - DataServiceEventTypes + DataServiceEventTypes, } from '../connectionController'; import { createLogger } from '../logging'; -import { ExplorerController, ConnectionTreeItem, DatabaseTreeItem } from '../explorer'; +import { + ExplorerController, + ConnectionTreeItem, + DatabaseTreeItem, +} from '../explorer'; import ExportToLanguageCodeLensProvider from './exportToLanguageCodeLensProvider'; import formatError from '../utils/formatError'; import { LanguageServerController } from '../language'; @@ -19,11 +23,11 @@ import { ShellExecuteAllResult, ExportToLanguageAddons, ExportToLanguageNamespace, - ExportToLanguageMode + ExportToLanguageMode, } from '../types/playgroundType'; import PlaygroundResultProvider, { PLAYGROUND_RESULT_SCHEME, - PLAYGROUND_RESULT_URI + PLAYGROUND_RESULT_URI, } from './playgroundResultProvider'; import playgroundSearchTemplate from '../templates/playgroundSearchTemplate'; import playgroundTemplate from '../templates/playgroundTemplate'; @@ -37,10 +41,10 @@ interface ToCompile { filter?: string; aggregation?: string; options: { - collection: string|null; - database: string|null; + collection: string | null; + database: string | null; uri?: string; - } + }; } let dummySandbox; @@ -52,19 +56,35 @@ const countAggregationStagesInString = (str: string) => { if (!dummySandbox) { dummySandbox = vm.createContext(Object.create(null), { codeGeneration: { strings: false, wasm: false }, - microtaskMode: 'afterEvaluate' + microtaskMode: 'afterEvaluate', }); - vm.runInContext([ - 'BSONRegExp', 'DBRef', 'Decimal128', 'Double', 'Int32', - 'Long', 'Int64', 'MaxKey', 'MinKey', 'ObjectID', 'ObjectId', - 'BSONSymbol', 'Timestamp', 'Code', 'Buffer', 'Binary' - ].map(name => `function ${name}() {}`).join('\n'), dummySandbox); + vm.runInContext( + [ + 'BSONRegExp', + 'DBRef', + 'Decimal128', + 'Double', + 'Int32', + 'Long', + 'Int64', + 'MaxKey', + 'MinKey', + 'ObjectID', + 'ObjectId', + 'BSONSymbol', + 'Timestamp', + 'Code', + 'Buffer', + 'Binary', + ] + .map((name) => `function ${name}() {}`) + .join('\n'), + dummySandbox + ); } - return vm.runInContext( - '(' + str + ')', - dummySandbox, - { timeout: 100 }).length; + return vm.runInContext('(' + str + ')', dummySandbox, { timeout: 100 }) + .length; }; /** @@ -108,9 +128,8 @@ export default class PlaygroundController { this._telemetryService = telemetryService; this._statusView = statusView; this._playgroundResultViewProvider = playgroundResultViewProvider; - this._outputChannel = vscode.window.createOutputChannel( - 'Playground output' - ); + this._outputChannel = + vscode.window.createOutputChannel('Playground output'); this._activeConnectionCodeLensProvider = activeConnectionCodeLensProvider; this._exportToLanguageCodeLensProvider = exportToLanguageCodeLensProvider; this._codeActionProvider = codeActionProvider; @@ -142,23 +161,26 @@ export default class PlaygroundController { vscode.window.onDidChangeTextEditorSelection( async (changeEvent: vscode.TextEditorSelectionChangeEvent) => { - if ( - changeEvent?.textEditor?.document?.languageId === 'mongodb' - ) { + if (changeEvent?.textEditor?.document?.languageId === 'mongodb') { // Sort lines selected as the may be mis-ordered from alt+click. - const sortedSelections = (changeEvent.selections as Array) - .sort((a, b) => (a.start.line > b.start.line ? 1 : -1)); + const sortedSelections = ( + changeEvent.selections as Array + ).sort((a, b) => (a.start.line > b.start.line ? 1 : -1)); this._selectedText = sortedSelections .map((item) => this._getSelectedText(item)) .join('\n'); - const mode = await this._languageServerController.getExportToLanguageMode({ - textFromEditor: this._getAllText(), - selection: sortedSelections[0] - }); + const mode = + await this._languageServerController.getExportToLanguageMode({ + textFromEditor: this._getAllText(), + selection: sortedSelections[0], + }); - this._codeActionProvider.refresh({ selection: sortedSelections[0], mode }); + this._codeActionProvider.refresh({ + selection: sortedSelections[0], + mode, + }); } } ); @@ -177,7 +199,8 @@ export default class PlaygroundController { return; } - const mongoClientOption = this._connectionController.getMongoClientConnectionOptions(); + const mongoClientOption = + this._connectionController.getMongoClientConnectionOptions(); if (!mongoClientOption) { this._activeConnectionCodeLensProvider.refresh(); @@ -188,7 +211,7 @@ export default class PlaygroundController { await this._languageServerController.connectToServiceProvider({ connectionId, connectionString: mongoClientOption.url, - connectionOptions: mongoClientOption.options + connectionOptions: mongoClientOption.options, }); this._activeConnectionCodeLensProvider.refresh(); @@ -200,7 +223,7 @@ export default class PlaygroundController { try { const document = await vscode.workspace.openTextDocument({ language: 'mongodb', - content + content, }); await vscode.window.showTextDocument(document); @@ -261,7 +284,7 @@ export default class PlaygroundController { try { const document = await vscode.workspace.openTextDocument({ language: 'mongodb', - content: useDefaultTemplate ? playgroundTemplate : '' + content: useDefaultTemplate ? playgroundTemplate : '', }); await vscode.window.showTextDocument(document); @@ -280,16 +303,19 @@ export default class PlaygroundController { const connectionId = this._connectionController.getActiveConnectionId(); if (!connectionId) { - throw new Error('Please connect to a database before running a playground.'); + throw new Error( + 'Please connect to a database before running a playground.' + ); } this._statusView.showMessage('Getting results...'); // Send a request to the language server to execute scripts from a playground. - const result: ShellExecuteAllResult = await this._languageServerController.executeAll({ - codeToEvaluate, - connectionId - }); + const result: ShellExecuteAllResult = + await this._languageServerController.executeAll({ + codeToEvaluate, + connectionId, + }); this._statusView.hideMessage(); this._telemetryService.trackPlaygroundCodeExecuted( @@ -311,7 +337,9 @@ export default class PlaygroundController { async _evaluateWithCancelModal(): Promise { if (!this._connectionController.isCurrentlyConnected()) { - throw new Error('Please connect to a database before running a playground.'); + throw new Error( + 'Please connect to a database before running a playground.' + ); } try { @@ -319,7 +347,7 @@ export default class PlaygroundController { { location: ProgressLocation.Notification, title: 'Running MongoDB playground...', - cancellable: true + cancellable: true, }, async (progress, token) => { token.onCancellationRequested(() => { @@ -344,7 +372,7 @@ export default class PlaygroundController { return { outputLines: undefined, - result: undefined + result: undefined, }; } } @@ -380,15 +408,14 @@ export default class PlaygroundController { await vscode.window.showTextDocument(PLAYGROUND_RESULT_URI, { preview: false, preserveFocus: true, - viewColumn: this._playgroundResultViewColumn || vscode.ViewColumn.Beside + viewColumn: this._playgroundResultViewColumn || vscode.ViewColumn.Beside, }); } async _openResultAsVirtualDocument(): Promise { try { - this._playgroundResultTextDocument = await vscode.workspace.openTextDocument( - PLAYGROUND_RESULT_URI - ); + this._playgroundResultTextDocument = + await vscode.workspace.openTextDocument(PLAYGROUND_RESULT_URI); } catch (error) { void vscode.window.showErrorMessage( `Unable to open a result document: ${formatError(error).message}` @@ -424,7 +451,8 @@ export default class PlaygroundController { this._outputChannel.clear(); - const evaluateResponse: ShellExecuteAllResult = await this._evaluateWithCancelModal(); + const evaluateResponse: ShellExecuteAllResult = + await this._evaluateWithCancelModal(); if (evaluateResponse?.outputLines?.length) { for (const line of evaluateResponse.outputLines) { @@ -528,7 +556,9 @@ export default class PlaygroundController { } } - changeExportToLanguageAddons(exportToLanguageAddons: ExportToLanguageAddons): Promise { + changeExportToLanguageAddons( + exportToLanguageAddons: ExportToLanguageAddons + ): Promise { this._exportToLanguageCodeLensProvider.refresh(exportToLanguageAddons); return this._transpile(); @@ -541,24 +571,26 @@ export default class PlaygroundController { selectedText: this._selectedText, selection: this._codeActionProvider.selection, language, - mode: this._codeActionProvider.mode + mode: this._codeActionProvider.mode, }); return this._transpile(); } - async getTranspiledContent(): Promise<{ namespace: ExportToLanguageNamespace, expression: string } | undefined> { + async getTranspiledContent(): Promise< + { namespace: ExportToLanguageNamespace; expression: string } | undefined + > { const { textFromEditor, selectedText, selection, driverSyntax, builders, - language + language, } = this._exportToLanguageCodeLensProvider._exportToLanguageAddons; let namespace: ExportToLanguageNamespace = { databaseName: 'DATABASE_NAME', - collectionName: 'COLLECTION_NAME' + collectionName: 'COLLECTION_NAME', }; let expression = ''; @@ -571,12 +603,14 @@ export default class PlaygroundController { let driverUrl = 'mongodb://localhost:27017'; if (connectionId) { - namespace = await this._languageServerController.getNamespaceForSelection({ - textFromEditor, - selection - }); + namespace = + await this._languageServerController.getNamespaceForSelection({ + textFromEditor, + selection, + }); - const mongoClientOptions = this._connectionController.getMongoClientConnectionOptions(); + const mongoClientOptions = + this._connectionController.getMongoClientConnectionOptions(); driverUrl = mongoClientOptions?.url || ''; } @@ -584,8 +618,8 @@ export default class PlaygroundController { options: { collection: namespace.collectionName, database: namespace.databaseName, - uri: driverUrl - } + uri: driverUrl, + }, }; if (this._codeActionProvider.mode === ExportToLanguageMode.AGGREGATION) { @@ -594,22 +628,24 @@ export default class PlaygroundController { toCompile.filter = selectedText; } - expression = transpiler.shell[language].compileWithDriver(toCompile, builders); + expression = transpiler.shell[language].compileWithDriver( + toCompile, + builders + ); } else { - expression = transpiler.shell[language].compile(selectedText, builders, false); + expression = transpiler.shell[language].compile( + selectedText, + builders, + false + ); } return { namespace, expression }; } async _transpile(): Promise { - const { - selectedText, - importStatements, - driverSyntax, - builders, - language - } = this._exportToLanguageCodeLensProvider._exportToLanguageAddons; + const { selectedText, importStatements, driverSyntax, builders, language } = + this._exportToLanguageCodeLensProvider._exportToLanguageAddons; log.info(`Start export to ${language} language`); @@ -632,12 +668,13 @@ export default class PlaygroundController { } this._playgroundResult = { - namespace: namespace.databaseName && namespace.collectionName - ? `${namespace.databaseName}.${namespace.collectionName}` - : null, + namespace: + namespace.databaseName && namespace.collectionName + ? `${namespace.databaseName}.${namespace.collectionName}` + : null, type: null, content: imports ? `${imports}\n\n${expression}` : expression, - language + language, }; log.info(`Export to ${language} language result`, this._playgroundResult); @@ -646,10 +683,12 @@ export default class PlaygroundController { if (this._codeActionProvider.mode === ExportToLanguageMode.AGGREGATION) { const aggExportedProps = { language, - num_stages: selectedText ? countAggregationStagesInString(selectedText) : null, + num_stages: selectedText + ? countAggregationStagesInString(selectedText) + : null, with_import_statements: importStatements, with_builders: builders, - with_driver_syntax: driverSyntax + with_driver_syntax: driverSyntax, }; this._telemetryService.trackAggregationExported(aggExportedProps); @@ -658,7 +697,7 @@ export default class PlaygroundController { language, with_import_statements: importStatements, with_builders: builders, - with_driver_syntax: driverSyntax + with_driver_syntax: driverSyntax, }; this._telemetryService.trackQueryExported(queryExportedProps); diff --git a/src/editors/playgroundResultProvider.ts b/src/editors/playgroundResultProvider.ts index 00548282..185f18b6 100644 --- a/src/editors/playgroundResultProvider.ts +++ b/src/editors/playgroundResultProvider.ts @@ -11,7 +11,8 @@ export const PLAYGROUND_RESULT_URI = vscode.Uri.parse( ); export default class PlaygroundResultProvider -implements vscode.TextDocumentContentProvider { + implements vscode.TextDocumentContentProvider +{ _connectionController: ConnectionController; _editDocumentCodeLensProvider: EditDocumentCodeLensProvider; _playgroundResult: PlaygroundResult; @@ -26,7 +27,7 @@ implements vscode.TextDocumentContentProvider { namespace: null, type: null, content: undefined, - language: null + language: null, }; } @@ -54,7 +55,13 @@ implements vscode.TextDocumentContentProvider { return 'undefined'; } - if (type === 'string' || (language && Object.values(ExportToLanguages).includes(language as ExportToLanguages))) { + if ( + type === 'string' || + (language && + Object.values(ExportToLanguages).includes( + language as ExportToLanguages + )) + ) { return this._playgroundResult.content; } diff --git a/src/explorer/collectionTreeItem.ts b/src/explorer/collectionTreeItem.ts index 0184fdd7..88646f18 100644 --- a/src/explorer/collectionTreeItem.ts +++ b/src/explorer/collectionTreeItem.ts @@ -4,7 +4,7 @@ import path from 'path'; import DocumentListTreeItem, { CollectionTypes, - MAX_DOCUMENTS_VISIBLE + MAX_DOCUMENTS_VISIBLE, } from './documentListTreeItem'; import formatError from '../utils/formatError'; import { getImagesPath } from '../extensionConstants'; @@ -22,23 +22,23 @@ function getIconPath( if (type === CollectionTypes.timeseries) { return { light: path.join(LIGHT, 'collection-timeseries.svg'), - dark: path.join(DARK, 'collection-timeseries.svg') + dark: path.join(DARK, 'collection-timeseries.svg'), }; } else if (type === CollectionTypes.collection) { if (isExpanded) { return { light: path.join(LIGHT, 'collection-folder-open.svg'), - dark: path.join(DARK, 'collection-folder-open.svg') + dark: path.join(DARK, 'collection-folder-open.svg'), }; } return { light: path.join(LIGHT, 'collection-folder-closed.svg'), - dark: path.join(DARK, 'collection-folder-closed.svg') + dark: path.join(DARK, 'collection-folder-closed.svg'), }; } return { light: path.join(LIGHT, 'view-folder.svg'), - dark: path.join(DARK, 'view-folder.svg') + dark: path.join(DARK, 'view-folder.svg'), }; } @@ -57,8 +57,10 @@ function isChildCacheOutOfSync( : collapsibleState !== vscode.TreeItemCollapsibleState.Collapsed; } -export default class CollectionTreeItem extends vscode.TreeItem - implements TreeItemParent, vscode.TreeDataProvider { +export default class CollectionTreeItem + extends vscode.TreeItem + implements TreeItemParent, vscode.TreeDataProvider +{ contextValue = 'collectionTreeItem' as const; private _documentListChild: DocumentListTreeItem; @@ -110,43 +112,44 @@ export default class CollectionTreeItem extends vscode.TreeItem this._documentListChild = existingDocumentListChild ? existingDocumentListChild : new DocumentListTreeItem( - this.collectionName, - this.databaseName, - this._type, - this._dataService, - false, // Collapsed. - MAX_DOCUMENTS_VISIBLE, - this.documentCount, - this.refreshDocumentCount, - false, // Cache is not up to date. - [] // Empty cache. - ); + this.collectionName, + this.databaseName, + this._type, + this._dataService, + false, // Collapsed. + MAX_DOCUMENTS_VISIBLE, + this.documentCount, + this.refreshDocumentCount, + false, // Cache is not up to date. + [] // Empty cache. + ); this._schemaChild = existingSchemaChild ? existingSchemaChild : new SchemaTreeItem( - this.collectionName, - this.databaseName, - this._dataService, - false, // Collapsed. - false, // Hasn't been clicked to show more documents. - false, // No more fields to show. - false, // Cached is not up to date. - {} // Empty cache. - ); + this.collectionName, + this.databaseName, + this._dataService, + false, // Collapsed. + false, // Hasn't been clicked to show more documents. + false, // No more fields to show. + false, // Cached is not up to date. + {} // Empty cache. + ); this._indexListChild = existingIndexListChild ? existingIndexListChild : new IndexListTreeItem( - this.collectionName, - this.databaseName, - this._dataService, - false, // Collapsed. - false, // Cache is not up to date. - [] // Empty cache. - ); - - this.tooltip = collection.type === CollectionTypes.view - ? 'Read only view' - : collection.name; + this.collectionName, + this.databaseName, + this._dataService, + false, // Collapsed. + false, // Cache is not up to date. + [] // Empty cache. + ); + + this.tooltip = + collection.type === CollectionTypes.view + ? 'Read only view' + : collection.name; this.iconPath = getIconPath(collection.type, isExpanded); } @@ -351,7 +354,7 @@ export default class CollectionTreeItem extends vscode.TreeItem } return null; - } + }, }); } catch (error) { return Promise.reject( diff --git a/src/explorer/connectionTreeItem.ts b/src/explorer/connectionTreeItem.ts index 64ca8465..6159c0c4 100644 --- a/src/explorer/connectionTreeItem.ts +++ b/src/explorer/connectionTreeItem.ts @@ -12,21 +12,28 @@ export enum ConnectionItemContextValues { connected = 'connectedConnectionTreeItem', } -function getIconPath(isActiveConnection: boolean): { light: string; dark: string } { +function getIconPath(isActiveConnection: boolean): { + light: string; + dark: string; +} { const LIGHT = path.join(getImagesPath(), 'light'); const DARK = path.join(getImagesPath(), 'dark'); - return isActiveConnection ? { - light: path.join(LIGHT, 'connection-active.svg'), - dark: path.join(DARK, 'connection-active.svg') - } : { - light: path.join(LIGHT, 'connection-inactive.svg'), - dark: path.join(DARK, 'connection-inactive.svg') - }; + return isActiveConnection + ? { + light: path.join(LIGHT, 'connection-active.svg'), + dark: path.join(DARK, 'connection-active.svg'), + } + : { + light: path.join(LIGHT, 'connection-inactive.svg'), + dark: path.join(DARK, 'connection-inactive.svg'), + }; } -export default class ConnectionTreeItem extends vscode.TreeItem - implements TreeItemParent, vscode.TreeDataProvider { +export default class ConnectionTreeItem + extends vscode.TreeItem + implements TreeItemParent, vscode.TreeDataProvider +{ contextValue = ConnectionItemContextValues.disconnected; private _childrenCache: { [key: string]: DatabaseTreeItem }; @@ -68,10 +75,13 @@ export default class ConnectionTreeItem extends vscode.TreeItem // (Without an id it treats this tree item like a previous tree item with the same label). this.id = `${connectionId}-${Date.now()}`; - this.tooltip = connectionController.getSavedConnectionName(this.connectionId); - this.description = connectionController.getConnectionStatusStringForConnection( + this.tooltip = connectionController.getSavedConnectionName( this.connectionId ); + this.description = + connectionController.getConnectionStatusStringForConnection( + this.connectionId + ); this.iconPath = getIconPath( connectionController.getActiveConnectionId() === this.connectionId ); @@ -91,9 +101,11 @@ export default class ConnectionTreeItem extends vscode.TreeItem try { const dbs = await dataService.listDatabases(); - return dbs.map(dbItem => dbItem.name); + return dbs.map((dbItem) => dbItem.name); } catch (error) { - throw new Error(`Unable to list databases: ${formatError(error).message}`); + throw new Error( + `Unable to list databases: ${formatError(error).message}` + ); } } diff --git a/src/explorer/databaseTreeItem.ts b/src/explorer/databaseTreeItem.ts index 99ee5f48..5cff71aa 100644 --- a/src/explorer/databaseTreeItem.ts +++ b/src/explorer/databaseTreeItem.ts @@ -13,12 +13,14 @@ function getIconPath(): { light: string; dark: string } { return { light: path.join(LIGHT, 'database.svg'), - dark: path.join(DARK, 'database.svg') + dark: path.join(DARK, 'database.svg'), }; } -export default class DatabaseTreeItem extends vscode.TreeItem - implements TreeItemParent, vscode.TreeDataProvider { +export default class DatabaseTreeItem + extends vscode.TreeItem + implements TreeItemParent, vscode.TreeDataProvider +{ contextValue = 'databaseTreeItem' as const; cacheIsUpToDate: boolean; @@ -94,7 +96,9 @@ export default class DatabaseTreeItem extends vscode.TreeItem } // List collections and build tree items. - const collections = await this._dataService.listCollections(this.databaseName); + const collections = await this._dataService.listCollections( + this.databaseName + ); this.cacheIsUpToDate = true; @@ -107,7 +111,7 @@ export default class DatabaseTreeItem extends vscode.TreeItem const systemCollections: string[] = []; const otherCollections: string[] = []; - collections.forEach(collection => { + collections.forEach((collection) => { if (collection.name.startsWith('system.')) { systemCollections.push(collection); } else { @@ -115,38 +119,38 @@ export default class DatabaseTreeItem extends vscode.TreeItem } }); - const sortFunction = (collectionA: any, collectionB: any) => (collectionA.name || '').localeCompare(collectionB.name || ''); + const sortFunction = (collectionA: any, collectionB: any) => + (collectionA.name || '').localeCompare(collectionB.name || ''); const collectionTreeEntries = [ ...otherCollections.sort(sortFunction), - ...systemCollections.sort(sortFunction) + ...systemCollections.sort(sortFunction), ]; - collectionTreeEntries - .forEach((collection: any) => { - if (pastChildrenCache[collection.name]) { - this._childrenCache[collection.name] = new CollectionTreeItem( - collection, - this.databaseName, - this._dataService, - pastChildrenCache[collection.name].isExpanded, - pastChildrenCache[collection.name].cacheIsUpToDate, - pastChildrenCache[collection.name].documentCount, - pastChildrenCache[collection.name].getDocumentListChild(), - pastChildrenCache[collection.name].getSchemaChild(), - pastChildrenCache[collection.name].getIndexListChild() - ); - } else { - this._childrenCache[collection.name] = new CollectionTreeItem( - collection, - this.databaseName, - this._dataService, - false, // Not expanded. - false, // No cache. - null // No document count yet. - ); - } - }); + collectionTreeEntries.forEach((collection: any) => { + if (pastChildrenCache[collection.name]) { + this._childrenCache[collection.name] = new CollectionTreeItem( + collection, + this.databaseName, + this._dataService, + pastChildrenCache[collection.name].isExpanded, + pastChildrenCache[collection.name].cacheIsUpToDate, + pastChildrenCache[collection.name].documentCount, + pastChildrenCache[collection.name].getDocumentListChild(), + pastChildrenCache[collection.name].getSchemaChild(), + pastChildrenCache[collection.name].getIndexListChild() + ); + } else { + this._childrenCache[collection.name] = new CollectionTreeItem( + collection, + this.databaseName, + this._dataService, + false, // Not expanded. + false, // No cache. + null // No document count yet. + ); + } + }); } else { this._childrenCache = {}; } @@ -193,7 +197,7 @@ export default class DatabaseTreeItem extends vscode.TreeItem } return null; - } + }, }); } catch (e) { return Promise.reject( @@ -209,9 +213,7 @@ export default class DatabaseTreeItem extends vscode.TreeItem const dropDatabase = util.promisify( this._dataService.dropDatabase.bind(this._dataService) ); - const successfullyDroppedDatabase = await dropDatabase( - databaseName - ); + const successfullyDroppedDatabase = await dropDatabase(databaseName); this.isDropped = successfullyDroppedDatabase; diff --git a/src/explorer/documentListTreeItem.ts b/src/explorer/documentListTreeItem.ts index 3ea86205..5846abc7 100644 --- a/src/explorer/documentListTreeItem.ts +++ b/src/explorer/documentListTreeItem.ts @@ -20,7 +20,7 @@ export const DOCUMENT_LIST_ITEM = 'documentListTreeItem'; export enum CollectionTypes { collection = 'collection', view = 'view', - timeseries = 'timeseries' + timeseries = 'timeseries', } const ITEM_LABEL = 'Documents'; @@ -65,11 +65,14 @@ function getIconPath(): { light: string; dark: string } { return { light: path.join(LIGHT, 'documents.svg'), - dark: path.join(DARK, 'documents.svg') + dark: path.join(DARK, 'documents.svg'), }; } -function getTooltip(type: CollectionTypes, documentCount: number | null): string { +function getTooltip( + type: CollectionTypes, + documentCount: number | null +): string { const typeString = type === CollectionTypes.view ? 'View' : 'Collection'; if (documentCount !== null) { return `${typeString} Documents - ${documentCount}`; @@ -77,12 +80,13 @@ function getTooltip(type: CollectionTypes, documentCount: number | null): string return `${typeString} Documents`; } -export default class DocumentListTreeItem extends vscode.TreeItem - implements TreeItemParent, vscode.TreeDataProvider { +export default class DocumentListTreeItem + extends vscode.TreeItem + implements TreeItemParent, vscode.TreeDataProvider +{ cacheIsUpToDate = false; - private _childrenCache: Array< - DocumentTreeItem | ShowMoreDocumentsTreeItem - > = []; + private _childrenCache: Array = + []; contextValue = DOCUMENT_LIST_ITEM; @@ -182,7 +186,7 @@ export default class DocumentListTreeItem extends vscode.TreeItem this.namespace, () => this.onShowMoreClicked(), this._maxDocumentsToShow - ) + ), ]; } @@ -195,7 +199,9 @@ export default class DocumentListTreeItem extends vscode.TreeItem let documents; try { - const find = util.promisify(this._dataService.find.bind(this._dataService)); + const find = util.promisify( + this._dataService.find.bind(this._dataService) + ); documents = await find( this.namespace, {}, // No filter. @@ -223,7 +229,7 @@ export default class DocumentListTreeItem extends vscode.TreeItem this.namespace, () => this.onShowMoreClicked(), this._maxDocumentsToShow - ) + ), ]; } diff --git a/src/explorer/documentTreeItem.ts b/src/explorer/documentTreeItem.ts index 31f66a1c..84210bea 100644 --- a/src/explorer/documentTreeItem.ts +++ b/src/explorer/documentTreeItem.ts @@ -3,8 +3,10 @@ import * as vscode from 'vscode'; export const DOCUMENT_ITEM = 'documentTreeItem'; -export default class DocumentTreeItem extends vscode.TreeItem - implements vscode.TreeDataProvider { +export default class DocumentTreeItem + extends vscode.TreeItem + implements vscode.TreeDataProvider +{ contextValue = DOCUMENT_ITEM; namespace: string; diff --git a/src/explorer/explorerController.ts b/src/explorer/explorerController.ts index 966635f2..2cb7f994 100644 --- a/src/explorer/explorerController.ts +++ b/src/explorer/explorerController.ts @@ -1,7 +1,7 @@ import * as vscode from 'vscode'; import ConnectionController, { - DataServiceEventTypes + DataServiceEventTypes, } from '../connectionController'; import ExplorerTreeController from './explorerTreeController'; @@ -32,7 +32,7 @@ export default class ExplorerController { this._treeView = vscode.window.createTreeView( 'mongoDBConnectionExplorer', { - treeDataProvider: this._treeController + treeDataProvider: this._treeController, } ); this._treeController.activateTreeViewEventHandlers(this._treeView); diff --git a/src/explorer/explorerTreeController.ts b/src/explorer/explorerTreeController.ts index 5741b074..3abb7045 100644 --- a/src/explorer/explorerTreeController.ts +++ b/src/explorer/explorerTreeController.ts @@ -2,7 +2,7 @@ import * as vscode from 'vscode'; import ConnectionController, { DataServiceEventTypes, - StoreConnectionInfo + StoreConnectionInfo, } from '../connectionController'; import ConnectionTreeItem from './connectionTreeItem'; import { createLogger } from '../logging'; @@ -14,7 +14,8 @@ import { sortTreeItemsByLabel } from './treeItemUtils'; const log = createLogger('explorer controller'); export default class ExplorerTreeController -implements vscode.TreeDataProvider { + implements vscode.TreeDataProvider +{ private _connectionController: ConnectionController; private _connectionTreeItems: { [key: string]: ConnectionTreeItem }; @@ -62,34 +63,32 @@ implements vscode.TreeDataProvider { this._onTreeItemUpdate(); }); - treeView.onDidExpandElement( - (event: any): Promise => { - log.info('Tree item was expanded:', event.element.label); + treeView.onDidExpandElement((event: any): Promise => { + log.info('Tree item was expanded:', event.element.label); - return new Promise((resolve, reject) => { - if (!event.element.onDidExpand) { - return resolve(); - } + return new Promise((resolve, reject) => { + if (!event.element.onDidExpand) { + return resolve(); + } - event.element.onDidExpand().then( - () => { - if (event.element.doesNotRequireTreeUpdate) { - // When the element is already loaded (synchronous), we do not - // need to fully refresh the tree. - return resolve(); - } + event.element.onDidExpand().then( + () => { + if (event.element.doesNotRequireTreeUpdate) { + // When the element is already loaded (synchronous), we do not + // need to fully refresh the tree. + return resolve(); + } - this._onTreeItemUpdate(); + this._onTreeItemUpdate(); - resolve(); - }, - (err: Error) => { - reject(err); - } - ); - }); - } - ); + resolve(); + }, + (err: Error) => { + reject(err); + } + ); + }); + }); treeView.onDidChangeSelection(async (event: any) => { if (event.selection && event.selection.length === 1) { diff --git a/src/explorer/fieldTreeItem.ts b/src/explorer/fieldTreeItem.ts index 5f72f7b8..ff3ed09c 100644 --- a/src/explorer/fieldTreeItem.ts +++ b/src/explorer/fieldTreeItem.ts @@ -133,7 +133,9 @@ function getFieldTypeString(field: SchemaFieldType): string { return fieldType; } -function getIconPath(field: SchemaFieldType): string | { light: string; dark: string } { +function getIconPath( + field: SchemaFieldType +): string | { light: string; dark: string } { const LIGHT = path.join(getImagesPath(), 'light'); const DARK = path.join(getImagesPath(), 'dark'); @@ -146,14 +148,16 @@ function getIconPath(field: SchemaFieldType): string | { light: string; dark: st return { light: path.join(LIGHT, 'schema', `${iconFileName}.svg`), - dark: path.join(DARK, 'schema', `${iconFileName}.svg`) + dark: path.join(DARK, 'schema', `${iconFileName}.svg`), }; } export const FIELD_TREE_ITEM_CONTEXT_VALUE = 'fieldTreeItem'; -export default class FieldTreeItem extends vscode.TreeItem - implements vscode.TreeDataProvider, TreeItemParent { +export default class FieldTreeItem + extends vscode.TreeItem + implements vscode.TreeDataProvider, TreeItemParent +{ // This is a flag which notes that when this tree element is updated, // the tree view does not have to fully update like it does with // asynchronous resources. diff --git a/src/explorer/helpExplorer.ts b/src/explorer/helpExplorer.ts index 05a5920b..e7810b98 100644 --- a/src/explorer/helpExplorer.ts +++ b/src/explorer/helpExplorer.ts @@ -17,7 +17,7 @@ export default class HelpExplorer { activateHelpTreeView(telemetryService: TelemetryService): void { if (!this._treeView) { this._treeView = vscode.window.createTreeView('mongoDBHelpExplorer', { - treeDataProvider: this._treeController + treeDataProvider: this._treeController, }); this._treeController.activateTreeViewEventHandlers( this._treeView, diff --git a/src/explorer/helpTree.ts b/src/explorer/helpTree.ts index ae478476..b3c9e74d 100644 --- a/src/explorer/helpTree.ts +++ b/src/explorer/helpTree.ts @@ -7,9 +7,9 @@ import { TelemetryService } from '../telemetry'; const HELP_LINK_CONTEXT_VALUE = 'HELP_LINK'; -function getIconPath(iconName?: string): - | string - | { light: string; dark: string } { +function getIconPath( + iconName?: string +): string | { light: string; dark: string } { if (!iconName || iconName === '') { return ''; } @@ -19,7 +19,7 @@ function getIconPath(iconName?: string): return { light: path.join(LIGHT, 'help', `${iconName}.svg`), - dark: path.join(DARK, 'help', `${iconName}.svg`) + dark: path.join(DARK, 'help', `${iconName}.svg`), }; } @@ -30,7 +30,13 @@ export class HelpLinkTreeItem extends vscode.TreeItem { url: string; useRedirect: boolean; - constructor(title: string, url: string, linkId: string, iconName?: string, useRedirect = false) { + constructor( + title: string, + url: string, + linkId: string, + iconName?: string, + useRedirect = false + ) { super(title, vscode.TreeItemCollapsibleState.None); this.linkId = linkId; @@ -41,7 +47,9 @@ export class HelpLinkTreeItem extends vscode.TreeItem { } } -export default class HelpTree implements vscode.TreeDataProvider { +export default class HelpTree + implements vscode.TreeDataProvider +{ contextValue = 'helpTree' as const; _telemetryService?: TelemetryService; @@ -67,7 +75,7 @@ export default class HelpTree implements vscode.TreeDataProvider { + async onClickHelpItem( + helpItem: HelpLinkTreeItem, + telemetryService: TelemetryService + ): Promise { if (helpItem.contextValue === HELP_LINK_CONTEXT_VALUE) { - telemetryService.trackLinkClicked( - 'helpPanel', - helpItem.linkId - ); + telemetryService.trackLinkClicked('helpPanel', helpItem.linkId); if (helpItem.useRedirect) { try { diff --git a/src/explorer/index.ts b/src/explorer/index.ts index 46c0f787..dd67393e 100644 --- a/src/explorer/index.ts +++ b/src/explorer/index.ts @@ -17,5 +17,5 @@ export { ExplorerController, HelpExplorer, PlaygroundsExplorer, - SchemaTreeItem + SchemaTreeItem, }; diff --git a/src/explorer/indexListTreeItem.ts b/src/explorer/indexListTreeItem.ts index 000a4651..c4faca9d 100644 --- a/src/explorer/indexListTreeItem.ts +++ b/src/explorer/indexListTreeItem.ts @@ -17,12 +17,14 @@ function getIconPath(): { light: string; dark: string } { return { light: path.join(LIGHT, 'indexes.svg'), - dark: path.join(DARK, 'indexes.svg') + dark: path.join(DARK, 'indexes.svg'), }; } -export default class IndexListTreeItem extends vscode.TreeItem - implements TreeItemParent, vscode.TreeDataProvider { +export default class IndexListTreeItem + extends vscode.TreeItem + implements TreeItemParent, vscode.TreeDataProvider +{ collectionName: string; databaseName: string; isExpanded: boolean; @@ -112,7 +114,11 @@ export default class IndexListTreeItem extends vscode.TreeItem if (indexes) { this._childrenCache = sortTreeItemsByLabel( indexes.map((index: IndexModel) => { - return new IndexTreeItem(index, this._namespace, false /* Not expanded. */); + return new IndexTreeItem( + index, + this._namespace, + false /* Not expanded. */ + ); }) ) as IndexTreeItem[]; } else { diff --git a/src/explorer/indexTreeItem.ts b/src/explorer/indexTreeItem.ts index d8fcaa76..2bebba92 100644 --- a/src/explorer/indexTreeItem.ts +++ b/src/explorer/indexTreeItem.ts @@ -11,7 +11,7 @@ export enum IndexKeyType { HASHED = 'hashed', GEO = '2d', // flat, cartesian geometry GEOSPHERE = '2dsphere', // index assuming a spherical geometry - GEOHAYSTACK = 'geoHaystack' + GEOHAYSTACK = 'geoHaystack', } export type IndexModel = { @@ -51,7 +51,10 @@ function getIconNameForIndexKeyType(indexKeyType: IndexKeyType): string { return ''; } -function getIndexFieldIconPath(indexKeyType: IndexKeyType): { light: string; dark: string } { +function getIndexFieldIconPath(indexKeyType: IndexKeyType): { + light: string; + dark: string; +} { const LIGHT = path.join(getImagesPath(), 'light'); const DARK = path.join(getImagesPath(), 'dark'); @@ -59,12 +62,14 @@ function getIndexFieldIconPath(indexKeyType: IndexKeyType): { light: string; dar return { light: path.join(LIGHT, 'index', `${iconName}.svg`), - dark: path.join(DARK, 'index', `${iconName}.svg`) + dark: path.join(DARK, 'index', `${iconName}.svg`), }; } -export class IndexFieldTreeItem extends vscode.TreeItem - implements vscode.TreeDataProvider { +export class IndexFieldTreeItem + extends vscode.TreeItem + implements vscode.TreeDataProvider +{ indexKey: string; indexKeyType: IndexKeyType; @@ -87,8 +92,10 @@ export class IndexFieldTreeItem extends vscode.TreeItem } } -export default class IndexTreeItem extends vscode.TreeItem - implements vscode.TreeDataProvider, TreeItemParent { +export default class IndexTreeItem + extends vscode.TreeItem + implements vscode.TreeDataProvider, TreeItemParent +{ contextValue = 'indexTreeItem' as const; index: IndexModel; diff --git a/src/explorer/playgroundsExplorer.ts b/src/explorer/playgroundsExplorer.ts index c56f51ae..afe91865 100644 --- a/src/explorer/playgroundsExplorer.ts +++ b/src/explorer/playgroundsExplorer.ts @@ -18,7 +18,7 @@ export default class PlaygroundsExplorer { this._treeView = vscode.window.createTreeView( 'mongoDBPlaygroundsExplorer', { - treeDataProvider: this._treeController + treeDataProvider: this._treeController, } ); this._treeController.activateTreeViewEventHandlers(this._treeView); diff --git a/src/explorer/playgroundsTree.ts b/src/explorer/playgroundsTree.ts index d7fecd9b..39603182 100644 --- a/src/explorer/playgroundsTree.ts +++ b/src/explorer/playgroundsTree.ts @@ -53,7 +53,8 @@ export class FileStat implements vscode.FileStat { } export default class PlaygroundsTree -implements vscode.TreeDataProvider { + implements vscode.TreeDataProvider +{ public excludeFromPlaygroundsSearch: string[]; private _playgroundsTreeHeaders: PlaygroundsTreeHeader[]; private _onDidChangeTreeData: vscode.EventEmitter; @@ -92,34 +93,32 @@ implements vscode.TreeDataProvider { this.onTreeItemUpdate(); }); - treeView.onDidExpandElement( - (event: any): Promise => { - log.info('Tree item was expanded:', event.element.label); + treeView.onDidExpandElement((event: any): Promise => { + log.info('Tree item was expanded:', event.element.label); - return new Promise((resolve, reject) => { - if (!event.element.onDidExpand) { - return resolve(); - } + return new Promise((resolve, reject) => { + if (!event.element.onDidExpand) { + return resolve(); + } - event.element.onDidExpand().then( - () => { - if (event.element.doesNotRequireTreeUpdate) { - // When the element is already loaded (synchronous), we do not - // need to fully refresh the tree. - return resolve(); - } + event.element.onDidExpand().then( + () => { + if (event.element.doesNotRequireTreeUpdate) { + // When the element is already loaded (synchronous), we do not + // need to fully refresh the tree. + return resolve(); + } - this.onTreeItemUpdate(); + this.onTreeItemUpdate(); - resolve(); - }, - (err: Error) => { - reject(err); - } - ); - }); - } - ); + resolve(); + }, + (err: Error) => { + reject(err); + } + ); + }); + }); treeView.onDidChangeSelection(async (event: any) => { if (event.selection && event.selection.length === 1) { @@ -208,7 +207,9 @@ implements vscode.TreeDataProvider { ) { await this.readDirectory(fileUri); } - } catch (error) { /* */ } + } catch (error) { + /* */ + } } } diff --git a/src/explorer/playgroundsTreeHeader.ts b/src/explorer/playgroundsTreeHeader.ts index c6f303ff..fe4eb9bb 100644 --- a/src/explorer/playgroundsTreeHeader.ts +++ b/src/explorer/playgroundsTreeHeader.ts @@ -3,8 +3,10 @@ import TreeItemParent from './treeItemParentInterface'; import PlaygroundsTreeItem from './playgroundsTreeItem'; import { sortTreeItemsByLabel } from './treeItemUtils'; -export default class PlaygroundsTreeHeader extends vscode.TreeItem - implements TreeItemParent, vscode.TreeDataProvider { +export default class PlaygroundsTreeHeader + extends vscode.TreeItem + implements TreeItemParent, vscode.TreeDataProvider +{ private _playgroundsTreeItems: { [key: string]: PlaygroundsTreeItem }; contextValue = 'playgroundsTreeHeader' as const; diff --git a/src/explorer/playgroundsTreeItem.ts b/src/explorer/playgroundsTreeItem.ts index 6a5fb657..fa64e16d 100644 --- a/src/explorer/playgroundsTreeItem.ts +++ b/src/explorer/playgroundsTreeItem.ts @@ -10,12 +10,14 @@ function getIconPath(): { light: string; dark: string } { return { light: path.join(LIGHT, 'file-light.svg'), - dark: path.join(DARK, 'file-light.svg') + dark: path.join(DARK, 'file-light.svg'), }; } -export default class PlaygroundsTreeItem extends vscode.TreeItem - implements vscode.TreeDataProvider { +export default class PlaygroundsTreeItem + extends vscode.TreeItem + implements vscode.TreeDataProvider +{ public filePath: string; contextValue = PLAYGROUND_ITEM; diff --git a/src/explorer/schemaTreeItem.ts b/src/explorer/schemaTreeItem.ts index 5e3913db..389e5331 100644 --- a/src/explorer/schemaTreeItem.ts +++ b/src/explorer/schemaTreeItem.ts @@ -36,12 +36,14 @@ function getIconPath(): { light: string; dark: string } { return { light: path.join(LIGHT, 'schema.svg'), - dark: path.join(DARK, 'schema.svg') + dark: path.join(DARK, 'schema.svg'), }; } -export default class SchemaTreeItem extends vscode.TreeItem - implements TreeItemParent, vscode.TreeDataProvider { +export default class SchemaTreeItem + extends vscode.TreeItem + implements TreeItemParent, vscode.TreeDataProvider +{ cacheIsUpToDate: boolean; childrenCache: { [fieldName: string]: FieldTreeItem }; @@ -98,7 +100,9 @@ export default class SchemaTreeItem extends vscode.TreeItem const namespace = `${this.databaseName}.${this.collectionName}`; let documents; try { - const find = util.promisify(this._dataService.find.bind(this._dataService)); + const find = util.promisify( + this._dataService.find.bind(this._dataService) + ); documents = await find( namespace, {}, // No filter. @@ -182,7 +186,7 @@ export default class SchemaTreeItem extends vscode.TreeItem if (!this.hasClickedShowMoreFields && this.hasMoreFieldsToShow) { return [ ...Object.values(this.childrenCache), - new ShowAllFieldsTreeItem(() => this.onShowMoreClicked()) + new ShowAllFieldsTreeItem(() => this.onShowMoreClicked()), ]; } @@ -218,7 +222,7 @@ export default class SchemaTreeItem extends vscode.TreeItem this.hasMoreFieldsToShow = true; return [ ...Object.values(this.childrenCache), - new ShowAllFieldsTreeItem(() => this.onShowMoreClicked()) + new ShowAllFieldsTreeItem(() => this.onShowMoreClicked()), ]; } diff --git a/src/explorer/treeItemUtils.ts b/src/explorer/treeItemUtils.ts index e6a1866d..f8ccb985 100644 --- a/src/explorer/treeItemUtils.ts +++ b/src/explorer/treeItemUtils.ts @@ -1,10 +1,9 @@ import * as vscode from 'vscode'; -export function sortTreeItemsByLabel(treeItems: vscode.TreeItem[]): vscode.TreeItem[] { - return treeItems.sort( - ( - a: vscode.TreeItem, - b: vscode.TreeItem - ) => (a.label?.toString() || '').localeCompare(b.label?.toString() || '') +export function sortTreeItemsByLabel( + treeItems: vscode.TreeItem[] +): vscode.TreeItem[] { + return treeItems.sort((a: vscode.TreeItem, b: vscode.TreeItem) => + (a.label?.toString() || '').localeCompare(b.label?.toString() || '') ); } diff --git a/src/extension.ts b/src/extension.ts index 837afa94..d62cdffb 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -24,7 +24,9 @@ let mdbExtension: MDBExtensionController; // Called when our extension is activated. // See "activationEvents" in `package.json` for the events that cause activation. -export async function activate(context: vscode.ExtensionContext): Promise { +export async function activate( + context: vscode.ExtensionContext +): Promise { log.info('activate extension called'); ext.context = context; @@ -36,7 +38,7 @@ export async function activate(context: vscode.ExtensionContext): Promise } mdbExtension = new MDBExtensionController(context, { - shouldTrackTelemetry: true + shouldTrackTelemetry: true, }); await mdbExtension.activate(); diff --git a/src/language/languageServerController.ts b/src/language/languageServerController.ts index 8a243b05..4fff848a 100644 --- a/src/language/languageServerController.ts +++ b/src/language/languageServerController.ts @@ -6,7 +6,7 @@ import { LanguageClientOptions, ServerOptions, TransportKind, - CancellationTokenSource + CancellationTokenSource, } from 'vscode-languageclient/node'; import { workspace, ExtensionContext } from 'vscode'; @@ -16,7 +16,7 @@ import { ShellExecuteAllResult, ExportToLanguageMode, ExportToLanguageNamespace, - PlaygroundTextAndSelection + PlaygroundTextAndSelection, } from '../types/playgroundType'; import { ServerCommands } from './serverCommands'; @@ -53,8 +53,8 @@ export default class LanguageServerController { debug: { module: serverModule, transport: TransportKind.ipc, - options: debugOptions - } + options: debugOptions, + }, }; // Options to control the language client @@ -62,20 +62,20 @@ export default class LanguageServerController { // Register the server for mongodb documents documentSelector: [ { scheme: 'untitled', language: 'mongodb' }, - { scheme: 'file', language: 'mongodb' } + { scheme: 'file', language: 'mongodb' }, ], synchronize: { // Notify the server about file changes in the workspace - fileEvents: workspace.createFileSystemWatcher('**/*') + fileEvents: workspace.createFileSystemWatcher('**/*'), }, outputChannel: vscode.window.createOutputChannel( 'MongoDB Language Server' - ) + ), }; log.info('Creating MongoDB Language Server', { serverOptions, - clientOptions + clientOptions, }); // Create the language server client @@ -102,13 +102,19 @@ export default class LanguageServerController { this._context.extensionPath ); - this._client.onNotification(ServerCommands.SHOW_INFO_MESSAGE, (messsage) => { - void vscode.window.showInformationMessage(messsage); - }); + this._client.onNotification( + ServerCommands.SHOW_INFO_MESSAGE, + (messsage) => { + void vscode.window.showInformationMessage(messsage); + } + ); - this._client.onNotification(ServerCommands.SHOW_ERROR_MESSAGE, (messsage) => { - void vscode.window.showErrorMessage(messsage); - }); + this._client.onNotification( + ServerCommands.SHOW_ERROR_MESSAGE, + (messsage) => { + void vscode.window.showErrorMessage(messsage); + } + ); } deactivate(): void { @@ -165,9 +171,9 @@ export default class LanguageServerController { } async connectToServiceProvider(params: { - connectionId: string, + connectionId: string; connectionString: string; - connectionOptions: MongoClientOptions + connectionOptions: MongoClientOptions; }): Promise { await this._client.onReady(); await this._client.sendRequest( diff --git a/src/language/mongoDBService.ts b/src/language/mongoDBService.ts index 5f6e6340..57a54a3c 100644 --- a/src/language/mongoDBService.ts +++ b/src/language/mongoDBService.ts @@ -6,7 +6,7 @@ import { Connection, CompletionItem, MarkupContent, - MarkupKind + MarkupKind, } from 'vscode-languageserver/node'; import type { MongoClientOptions } from 'mongodb'; import path from 'path'; @@ -21,7 +21,7 @@ import { PlaygroundExecuteParameters, ExportToLanguageMode, ExportToLanguageNamespace, - PlaygroundTextAndSelection + PlaygroundTextAndSelection, } from '../types/playgroundType'; import { Visitor } from './visitor'; @@ -30,13 +30,13 @@ export const languageServerWorkerFileName = 'languageServerWorker.js'; export type CollectionItem = { name: string; type?: string; - options?: object, - info?: { readOnly: boolean; uuid: object[] }, - idIndex?: { v: number; key: object[]; name: string; ns: string } + options?: object; + info?: { readOnly: boolean; uuid: object[] }; + idIndex?: { v: number; key: object[]; name: string; ns: string }; }; export type ShellCompletionItem = { - [symbol: string]: CompletionItem[] | [] + [symbol: string]: CompletionItem[] | []; }; export default class MongoDBService { @@ -68,7 +68,9 @@ export default class MongoDBService { setExtensionPath(extensionPath: string): void { if (!extensionPath) { - this._connection.console.error('Set extensionPath error: extensionPath is undefined'); + this._connection.console.error( + 'Set extensionPath error: extensionPath is undefined' + ); } else { this._extensionPath = extensionPath; } @@ -121,7 +123,9 @@ export default class MongoDBService { return new Promise((resolve) => { if (!this._extensionPath) { - this._connection.console.error('MONGOSH execute all error: extensionPath is undefined'); + this._connection.console.error( + 'MONGOSH execute all error: extensionPath is undefined' + ); return resolve(undefined); } @@ -129,7 +133,7 @@ export default class MongoDBService { if (this._connectionId !== executionParameters.connectionId) { this._connection.sendNotification( ServerCommands.SHOW_ERROR_MESSAGE, - 'The playground\'s active connection does not match the extension\'s active connection. Please reconnect and try again.' + "The playground's active connection does not match the extension's active connection. Please reconnect and try again." ); return resolve(undefined); @@ -146,14 +150,18 @@ export default class MongoDBService { // TODO: After webpackifying the extension replace // the workaround with some similar 3rd-party plugin. const worker = new WorkerThreads( - path.resolve(this._extensionPath, 'dist', languageServerWorkerFileName), + path.resolve( + this._extensionPath, + 'dist', + languageServerWorkerFileName + ), { // The workerData parameter sends data to the created worker. workerData: { codeToEvaluate: executionParameters.codeToEvaluate, connectionString: this._connectionString, - connectionOptions: this._connectionOptions - } + connectionOptions: this._connectionOptions, + }, } ); @@ -165,25 +173,28 @@ export default class MongoDBService { worker.postMessage(ServerCommands.EXECUTE_ALL_FROM_PLAYGROUND); // Listen for results from the worker thread. - worker.on('message', (response: [Error, ShellExecuteAllResult | undefined]) => { - const [error, result] = response; - - if (error) { - const printableError = formatError(error); + worker.on( + 'message', + (response: [Error, ShellExecuteAllResult | undefined]) => { + const [error, result] = response; + + if (error) { + const printableError = formatError(error); + + this._connection.console.error( + `MONGOSH execute all error: ${util.inspect(printableError)}` + ); + this._connection.sendNotification( + ServerCommands.SHOW_ERROR_MESSAGE, + printableError.message + ); + } - this._connection.console.error( - `MONGOSH execute all error: ${util.inspect(printableError)}` - ); - this._connection.sendNotification( - ServerCommands.SHOW_ERROR_MESSAGE, - printableError.message - ); + void worker.terminate().then(() => { + resolve(result); + }); } - - void worker.terminate().then(() => { - resolve(result); - }); - }); + ); // Listen for cancellation request from the language server client. token.onCancellationRequested(async () => { @@ -224,7 +235,9 @@ export default class MongoDBService { // ------ GET DATA FOR COMPLETION ------ // _getDatabasesCompletionItems(): void { if (!this._extensionPath) { - this._connection.console.error('MONGOSH get list databases error: extensionPath is undefined'); + this._connection.console.error( + 'MONGOSH get list databases error: extensionPath is undefined' + ); return; } @@ -235,8 +248,8 @@ export default class MongoDBService { { workerData: { connectionString: this._connectionString, - connectionOptions: this._connectionOptions - } + connectionOptions: this._connectionOptions, + }, } ); @@ -253,7 +266,9 @@ export default class MongoDBService { } void worker.terminate().then(() => { - this._connection.console.log(`MONGOSH found ${result.length} databases`); + this._connection.console.log( + `MONGOSH found ${result.length} databases` + ); this._updateCurrentSessionDatabases(result); }); }); @@ -267,20 +282,26 @@ export default class MongoDBService { _getCollectionsCompletionItems(databaseName: string): Promise { return new Promise((resolve) => { if (!this._extensionPath) { - this._connection.console.log('MONGOSH get list collections error: extensionPath is undefined'); + this._connection.console.log( + 'MONGOSH get list collections error: extensionPath is undefined' + ); return resolve(false); } try { const worker = new WorkerThreads( - path.resolve(this._extensionPath, 'dist', languageServerWorkerFileName), + path.resolve( + this._extensionPath, + 'dist', + languageServerWorkerFileName + ), { workerData: { connectionString: this._connectionString, connectionOptions: this._connectionOptions, - databaseName - } + databaseName, + }, } ); @@ -321,7 +342,9 @@ export default class MongoDBService { ): Promise { return new Promise((resolve) => { if (!this._extensionPath) { - this._connection.console.log('SCHEMA error: extensionPath is undefined'); + this._connection.console.log( + 'SCHEMA error: extensionPath is undefined' + ); return resolve(false); } @@ -329,14 +352,18 @@ export default class MongoDBService { try { const namespace = `${databaseName}.${collectionName}`; const worker = new WorkerThreads( - path.resolve(this._extensionPath, 'dist', languageServerWorkerFileName), + path.resolve( + this._extensionPath, + 'dist', + languageServerWorkerFileName + ), { workerData: { connectionString: this._connectionString, connectionOptions: this._connectionOptions, databaseName, - collectionName - } + collectionName, + }, } ); @@ -347,11 +374,15 @@ export default class MongoDBService { const [error, result] = response; if (error) { - this._connection.console.log(`SCHEMA error: ${util.inspect(error)}`); + this._connection.console.log( + `SCHEMA error: ${util.inspect(error)}` + ); } void worker.terminate().then(() => { - this._connection.console.log(`SCHEMA found ${result.length} fields`); + this._connection.console.log( + `SCHEMA found ${result.length} fields` + ); this._updateCurrentSessionFields(namespace, result); return resolve(true); @@ -373,20 +404,31 @@ export default class MongoDBService { shellSymbols[symbol] = Object.keys( signatures[symbol].attributes || {} ).map((item) => { - const documentation = translator.translate(`shell-api.classes.${symbol}.help.attributes.${item}.description`) || ''; - const link = translator.translate(`shell-api.classes.${symbol}.help.attributes.${item}.link`) || ''; - const detail = translator.translate(`shell-api.classes.${symbol}.help.attributes.${item}.example`) || ''; + const documentation = + translator.translate( + `shell-api.classes.${symbol}.help.attributes.${item}.description` + ) || ''; + const link = + translator.translate( + `shell-api.classes.${symbol}.help.attributes.${item}.link` + ) || ''; + const detail = + translator.translate( + `shell-api.classes.${symbol}.help.attributes.${item}.example` + ) || ''; const markdownDocumentation: MarkupContent = { kind: MarkupKind.Markdown, - value: link ? `${documentation}\n\n[Read More](${link})` : documentation + value: link + ? `${documentation}\n\n[Read More](${link})` + : documentation, }; return { label: item, kind: CompletionItemKind.Method, documentation: markdownDocumentation, - detail + detail, }; }); }); @@ -415,7 +457,7 @@ export default class MongoDBService { if (this._isValidPropertyName(item.name)) { return { label: item.name, - kind: CompletionItemKind.Folder + kind: CompletionItemKind.Folder, }; } @@ -429,31 +471,35 @@ export default class MongoDBService { filterText: [ filterText.slice(0, position.character), `.${item.name}`, - filterText.slice(position.character, filterText.length) + filterText.slice(position.character, filterText.length), ].join(''), textEdit: { range: { start: { line: position.line, character: 0 }, end: { line: position.line, - character: filterText.length - } + character: filterText.length, + }, }, // Replace with array-like format newText: [ filterText.slice(0, position.character - 1), `['${item.name}']`, - filterText.slice(position.character, filterText.length) - ].join('') - } + filterText.slice(position.character, filterText.length), + ].join(''), + }, }; }); } - getExportToLanguageMode(params: PlaygroundTextAndSelection): ExportToLanguageMode { + getExportToLanguageMode( + params: PlaygroundTextAndSelection + ): ExportToLanguageMode { const state = this._visitor.parseAST(params); - this._connection.console.log(`EXPORT TO LANGUAGE state: ${util.inspect(state)}`); + this._connection.console.log( + `EXPORT TO LANGUAGE state: ${util.inspect(state)}` + ); if (state.isArray) { return ExportToLanguageMode.AGGREGATION; @@ -466,10 +512,15 @@ export default class MongoDBService { return ExportToLanguageMode.OTHER; } - getNamespaceForSelection(params: PlaygroundTextAndSelection): ExportToLanguageNamespace { + getNamespaceForSelection( + params: PlaygroundTextAndSelection + ): ExportToLanguageNamespace { try { const state = this._visitor.parseAST(params); - return { databaseName: state.databaseName, collectionName: state.collectionName }; + return { + databaseName: state.databaseName, + collectionName: state.collectionName, + }; } catch (error) { this._connection.console.error( `Get namespace for selection error: ${util.inspect(error)}` @@ -481,7 +532,7 @@ export default class MongoDBService { // eslint-disable-next-line complexity async provideCompletionItems( textFromEditor: string, - position: { line: number, character: number } + position: { line: number; character: number } ): Promise { // eslint-disable-next-line complexity this._connection.console.log( @@ -491,13 +542,20 @@ export default class MongoDBService { `LS current symbol position: ${util.inspect(position)}` ); - const state = this._visitor.parseASTWithPlaceholder(textFromEditor, position); + const state = this._visitor.parseASTWithPlaceholder( + textFromEditor, + position + ); this._connection.console.log( `VISITOR completion state: ${util.inspect(state)}` ); - if (this.connectionString && state.databaseName && !this._cachedCollections[state.databaseName]) { + if ( + this.connectionString && + state.databaseName && + !this._cachedCollections[state.databaseName] + ) { await this._getCollectionsCompletionItems(state.databaseName); } @@ -543,7 +601,9 @@ export default class MongoDBService { } if (state.isDbCallExpression) { - let dbCompletions: CompletionItem[] = [...this._cachedShellSymbols.Database]; + let dbCompletions: CompletionItem[] = [ + ...this._cachedShellSymbols.Database, + ]; if (state.databaseName) { this._connection.console.log( @@ -594,7 +654,10 @@ export default class MongoDBService { this._cachedFields = {}; } - _updateCurrentSessionFields(namespace: string, fields: CompletionItem[]): void { + _updateCurrentSessionFields( + namespace: string, + fields: CompletionItem[] + ): void { if (namespace) { this._cachedFields[namespace] = fields ? fields : []; } @@ -612,7 +675,10 @@ export default class MongoDBService { this._cachedCollections = {}; } - _updateCurrentSessionCollections(database: string, collections: CollectionItem[]): void { + _updateCurrentSessionCollections( + database: string, + collections: CollectionItem[] + ): void { if (database) { this._cachedCollections[database] = collections ? collections : []; } diff --git a/src/language/server.ts b/src/language/server.ts index 4f3f3adc..9e27007e 100644 --- a/src/language/server.ts +++ b/src/language/server.ts @@ -8,13 +8,16 @@ import { TextDocumentPositionParams, RequestType, TextDocumentSyncKind, - Connection + Connection, } from 'vscode-languageserver/node'; import { TextDocument } from 'vscode-languageserver-textdocument'; import MongoDBService from './mongoDBService'; import { ServerCommands } from './serverCommands'; -import { PlaygroundExecuteParameters, PlaygroundTextAndSelection } from '../types/playgroundType'; +import { + PlaygroundExecuteParameters, + PlaygroundTextAndSelection, +} from '../types/playgroundType'; // Create a connection for the server. The connection uses Node's IPC as a transport. // Also include all preview / proposed LSP features. @@ -54,14 +57,14 @@ connection.onInitialize((params: InitializeParams) => { // Tell the client that the server supports code completion completionProvider: { resolveProvider: true, - triggerCharacters: ['.'] - } + triggerCharacters: ['.'], + }, // documentFormattingProvider: true, // documentRangeFormattingProvider: true, // codeLensProvider: { // resolveProvider: true // } - } + }, }; }); @@ -160,13 +163,19 @@ connection.onRequest(ServerCommands.DISCONNECT_TO_SERVICE_PROVIDER, () => { return mongoDBService.disconnectFromServiceProvider(); }); -connection.onRequest(ServerCommands.GET_EXPORT_TO_LANGUAGE_MODE, (params: PlaygroundTextAndSelection) => { - return mongoDBService.getExportToLanguageMode(params); -}); +connection.onRequest( + ServerCommands.GET_EXPORT_TO_LANGUAGE_MODE, + (params: PlaygroundTextAndSelection) => { + return mongoDBService.getExportToLanguageMode(params); + } +); -connection.onRequest(ServerCommands.GET_NAMESPACE_FOR_SELECTION, (params: PlaygroundTextAndSelection) => { - return mongoDBService.getNamespaceForSelection(params); -}); +connection.onRequest( + ServerCommands.GET_NAMESPACE_FOR_SELECTION, + (params: PlaygroundTextAndSelection) => { + return mongoDBService.getNamespaceForSelection(params); + } +); // This handler provides the list of the completion items. connection.onCompletion((params: TextDocumentPositionParams) => { @@ -180,21 +189,19 @@ connection.onCompletion((params: TextDocumentPositionParams) => { // This handler resolves additional information for the item selected in // the completion list. -connection.onCompletionResolve( - (item: CompletionItem): CompletionItem => { - // connection.console.log(`onCompletionResolve: ${JSON.stringify(item)}`); - - // if (item.data === 1) { - // item.detail = 'TypeScript details'; - // item.documentation = 'TypeScript documentation'; - // } else if (item.data === 2) { - // item.detail = 'JavaScript details'; - // item.documentation = 'JavaScript documentation'; - // } - - return item; - } -); +connection.onCompletionResolve((item: CompletionItem): CompletionItem => { + // connection.console.log(`onCompletionResolve: ${JSON.stringify(item)}`); + + // if (item.data === 1) { + // item.detail = 'TypeScript details'; + // item.documentation = 'TypeScript documentation'; + // } else if (item.data === 2) { + // item.detail = 'JavaScript details'; + // item.documentation = 'JavaScript documentation'; + // } + + return item; +}); connection.onRequest('textDocument/rangeFormatting', (event) => { // connection.console.log( diff --git a/src/language/serverCommands.ts b/src/language/serverCommands.ts index 12a60925..78758455 100644 --- a/src/language/serverCommands.ts +++ b/src/language/serverCommands.ts @@ -10,7 +10,7 @@ export enum ServerCommands { SHOW_ERROR_MESSAGE = 'SHOW_ERROR_MESSAGE', SHOW_INFO_MESSAGE = 'SHOW_INFO_MESSAGE', GET_NAMESPACE_FOR_SELECTION = 'GET_NAMESPACE_FOR_SELECTION', - GET_EXPORT_TO_LANGUAGE_MODE = 'GET_EXPORT_TO_LANGUAGE_MODE' + GET_EXPORT_TO_LANGUAGE_MODE = 'GET_EXPORT_TO_LANGUAGE_MODE', } export type PlaygroundRunParameters = { diff --git a/src/language/visitor.ts b/src/language/visitor.ts index 06946e84..34d6faef 100644 --- a/src/language/visitor.ts +++ b/src/language/visitor.ts @@ -7,8 +7,8 @@ import * as util from 'util'; const PLACEHOLDER = 'TRIGGER_CHARACTER'; export interface VisitorSelection { - start: { line: number, character: number }; - end: { line: number, character: number }; + start: { line: number; character: number }; + end: { line: number; character: number }; } export interface VisitorTextAndSelection { @@ -39,7 +39,7 @@ export class Visitor { this._state = this._getDefaultNodesValues(); this._selection = { start: { line: 0, character: 0 }, - end: { line: 0, character: 0 } + end: { line: 0, character: 0 }, }; this._console = console; } @@ -125,17 +125,20 @@ export class Visitor { textFromEditor: string, position: { line: number; character: number } ): CompletionState { - const selection: VisitorSelection = { start: position, end: { line: 0, character: 0 } }; + const selection: VisitorSelection = { + start: position, + end: { line: 0, character: 0 }, + }; - textFromEditor = this._handleTriggerCharacter( - textFromEditor, - position - ); + textFromEditor = this._handleTriggerCharacter(textFromEditor, position); return this.parseAST({ textFromEditor, selection }); } - parseAST({ textFromEditor, selection }: VisitorTextAndSelection): CompletionState { + parseAST({ + textFromEditor, + selection, + }: VisitorTextAndSelection): CompletionState { let ast: any; this._state = this._getDefaultNodesValues(); @@ -144,7 +147,7 @@ export class Visitor { try { ast = parser.parse(textFromEditor, { // Parse in strict mode and allow module declarations - sourceType: 'module' + sourceType: 'module', }); } catch (error) { this._console.error(`parseAST error: ${util.inspect(error)}`); @@ -160,7 +163,7 @@ export class Visitor { this._visitArrayExpression(path.node); this._visitVariableDeclarator(path.node); this._visitObjectProperty(path.node); - } + }, }); return this._state; @@ -178,7 +181,7 @@ export class Visitor { isDbCallExpression: false, isCollectionName: false, isAggregationCursor: false, - isFindCursor: false + isFindCursor: false, }; } @@ -233,15 +236,13 @@ export class Visitor { _isParentAroundSelection(node: babel.types.Node): boolean { if ( node.loc?.start?.line && - ( - node.loc.start.line - 1 < this._selection.start?.line || - node.loc.start.line - 1 === this._selection.start?.line && node.loc.start.column < this._selection.start?.character - ) && + (node.loc.start.line - 1 < this._selection.start?.line || + (node.loc.start.line - 1 === this._selection.start?.line && + node.loc.start.column < this._selection.start?.character)) && node.loc?.end?.line && - ( - node.loc.end.line - 1 > this._selection.end?.line || - node.loc.end.line - 1 === this._selection.end?.line && node.loc.end.column > this._selection.end?.character - ) + (node.loc.end.line - 1 > this._selection.end?.line || + (node.loc.end.line - 1 === this._selection.end?.line && + node.loc.end.column > this._selection.end?.character)) ) { return true; } @@ -252,13 +253,9 @@ export class Visitor { _isObjectPropBeforeSelection(node: babel.types.ObjectProperty): boolean { if ( node.key.loc?.end && - ( - node.key.loc?.end.line - 1 < this._selection.start?.line || - ( - node.key.loc?.end.line - 1 === this._selection.start?.line && - node.key.loc?.end.column < this._selection.start?.character - ) - ) + (node.key.loc?.end.line - 1 < this._selection.start?.line || + (node.key.loc?.end.line - 1 === this._selection.start?.line && + node.key.loc?.end.column < this._selection.start?.character)) ) { return true; } @@ -266,16 +263,14 @@ export class Visitor { return false; } - _isVariableIdentifierBeforeSelection(node: babel.types.VariableDeclarator): boolean { + _isVariableIdentifierBeforeSelection( + node: babel.types.VariableDeclarator + ): boolean { if ( node.id.loc?.end && - ( - node.id.loc?.end.line - 1 < this._selection.start?.line || - ( - node.id.loc?.end.line - 1 === this._selection.start?.line && - node.id.loc?.end.column < this._selection.start?.character - ) - ) + (node.id.loc?.end.line - 1 < this._selection.start?.line || + (node.id.loc?.end.line - 1 === this._selection.start?.line && + node.id.loc?.end.column < this._selection.start?.character)) ) { return true; } @@ -313,7 +308,11 @@ export class Visitor { } _checkIsBSONSelectionInArray(node: babel.types.Node): void { - if (node.type === 'ArrayExpression' && node.elements && this._isParentAroundSelection(node)) { + if ( + node.type === 'ArrayExpression' && + node.elements && + this._isParentAroundSelection(node) + ) { node.elements.forEach((item) => { if (item) { this._checkIsObjectWithinSelection(item); @@ -324,7 +323,11 @@ export class Visitor { } _checkIsBSONSelectionInFunction(node: babel.types.Node): void { - if (node.type === 'CallExpression' && node.arguments && this._isParentAroundSelection(node)) { + if ( + node.type === 'CallExpression' && + node.arguments && + this._isParentAroundSelection(node) + ) { node.arguments.forEach((item) => { if (item) { this._checkIsObjectWithinSelection(item); @@ -376,12 +379,17 @@ export class Visitor { } _checkIsCollectionNameAsCallExpression(node: babel.types.Node): void { - if (node.type === 'CallExpression' && node.callee.type === 'MemberExpression') { + if ( + node.type === 'CallExpression' && + node.callee.type === 'MemberExpression' + ) { this._checkIsCollectionName(node.callee); } } - _checkIsCollectionName(node: babel.types.CallExpression | babel.types.MemberExpression): void { + _checkIsCollectionName( + node: babel.types.CallExpression | babel.types.MemberExpression + ): void { this._checkIsCollectionNameAsMemberExpression(node); this._checkIsCollectionNameAsCallExpression(node); } @@ -436,7 +444,9 @@ export class Visitor { node.object.object.type === 'Identifier' && node.object.object.name === 'db' ) { - this._state.collectionName = (node.object.property as babel.types.Identifier).name; + this._state.collectionName = ( + node.object.property as babel.types.Identifier + ).name; } } diff --git a/src/language/worker.ts b/src/language/worker.ts index a4b85e8b..189635e1 100644 --- a/src/language/worker.ts +++ b/src/language/worker.ts @@ -4,11 +4,17 @@ import { EJSON, Document } from 'bson'; import { ElectronRuntime } from '@mongosh/browser-runtime-electron'; import parseSchema = require('mongodb-schema'); import { parentPort, workerData } from 'worker_threads'; -import { PlaygroundResult, PlaygroundDebug, ShellExecuteAllResult } from '../types/playgroundType'; +import { + PlaygroundResult, + PlaygroundDebug, + ShellExecuteAllResult, +} from '../types/playgroundType'; import { ServerCommands } from './serverCommands'; // MongoClientOptions is the second argument of CliServiceProvider.connect(connectionStr, options) -type MongoClientOptions = NonNullable[1]>; +type MongoClientOptions = NonNullable< + Parameters[1] +>; interface EvaluationResult { printable: any; @@ -23,7 +29,7 @@ const getContent = ({ type, printable }: EvaluationResult) => { return JSON.parse(EJSON.stringify(printable.documents)); } - return (typeof printable !== 'object' || printable === null) + return typeof printable !== 'object' || printable === null ? printable : JSON.parse(EJSON.stringify(printable)); }; @@ -48,10 +54,8 @@ const executeAll = async ( // // TODO: update when `mongosh` will start to support cancellationToken. // See: https://github.com/mongodb/node-mongodb-native/commit/2014b7b/#diff-46fff96a6e12b2b0b904456571ce308fR132 - const serviceProvider: CliServiceProvider = await CliServiceProvider.connect( - connectionString, - connectionOptions - ); + const serviceProvider: CliServiceProvider = + await CliServiceProvider.connect(connectionString, connectionOptions); const outputLines: PlaygroundDebug = []; // Create a new instance of the runtime and evaluate code from a playground. @@ -64,20 +68,21 @@ const executeAll = async ( type, content: printable, namespace: null, - language: null + language: null, }); } - } + }, }); const { source, type, printable } = await runtime.evaluate(codeToEvaluate); - const namespace = (source && source.namespace) - ? `${source.namespace.db}.${source.namespace.collection}` - : null; + const namespace = + source && source.namespace + ? `${source.namespace.db}.${source.namespace.collection}` + : null; const result: PlaygroundResult = { namespace, type: type ? type : typeof printable, content: getContent({ type, printable }), - language: getLanguage({ type, printable }) + language: getLanguage({ type, printable }), }; return [null, { outputLines, result }]; @@ -111,7 +116,7 @@ const findAndParse = async ( const fields = schema.fields.map((item) => ({ label: item.name, - kind: CompletionItemKind.Field + kind: CompletionItemKind.Field, })); return resolve(fields); @@ -126,10 +131,8 @@ const getFieldsFromSchema = async ( collectionName: string ): Promise => { try { - const serviceProvider: CliServiceProvider = await CliServiceProvider.connect( - connectionString, - connectionOptions - ); + const serviceProvider: CliServiceProvider = + await CliServiceProvider.connect(connectionString, connectionOptions); const result = await findAndParse( serviceProvider, @@ -150,7 +153,7 @@ const prepareCompletionItems = (result: Document) => { return result.databases.map((item) => ({ label: item.name, - kind: CompletionItemKind.Value + kind: CompletionItemKind.Value, })); }; @@ -159,10 +162,8 @@ const getListDatabases = async ( connectionOptions: any ) => { try { - const serviceProvider: CliServiceProvider = await CliServiceProvider.connect( - connectionString, - connectionOptions - ); + const serviceProvider: CliServiceProvider = + await CliServiceProvider.connect(connectionString, connectionOptions); // TODO: There is a mistake in the service provider interface // Use `admin` as arguments to get list of dbs @@ -182,10 +183,8 @@ const getListCollections = async ( databaseName: string ) => { try { - const serviceProvider: CliServiceProvider = await CliServiceProvider.connect( - connectionString, - connectionOptions - ); + const serviceProvider: CliServiceProvider = + await CliServiceProvider.connect(connectionString, connectionOptions); const result = await serviceProvider.listCollections(databaseName); const collections = result ? result : []; @@ -195,7 +194,7 @@ const getListCollections = async ( } }; -const handleMessageFromParentPort = async(message: string): Promise => { +const handleMessageFromParentPort = async (message: string): Promise => { if (message === ServerCommands.EXECUTE_ALL_FROM_PLAYGROUND) { parentPort?.postMessage( await executeAll( @@ -238,9 +237,6 @@ const handleMessageFromParentPort = async(message: string): Promise => { }; // parentPort allows communication with the parent thread. -parentPort?.once( - 'message', - (message: string): void => { - void handleMessageFromParentPort(message); - } -); +parentPort?.once('message', (message: string): void => { + void handleMessageFromParentPort(message); +}); diff --git a/src/logging.ts b/src/logging.ts index 46b75453..070e3618 100644 --- a/src/logging.ts +++ b/src/logging.ts @@ -3,9 +3,8 @@ import * as vscode from 'vscode'; import * as util from 'util'; class Logger implements ILogger { - static channel: vscode.OutputChannel = vscode.window.createOutputChannel( - 'mongodb' - ); + static channel: vscode.OutputChannel = + vscode.window.createOutputChannel('mongodb'); private name: string; diff --git a/src/mdbExtensionController.ts b/src/mdbExtensionController.ts index 6be9bd49..d36122c3 100644 --- a/src/mdbExtensionController.ts +++ b/src/mdbExtensionController.ts @@ -21,7 +21,7 @@ import { ExplorerController, PlaygroundsExplorer, HelpExplorer, - CollectionTreeItem + CollectionTreeItem, } from './explorer'; import ExportToLanguageCodeLensProvider from './editors/exportToLanguageCodeLensProvider'; import { ExportToLanguages } from './types/playgroundType'; @@ -92,10 +92,10 @@ export default class MDBExtensionController implements vscode.Disposable { this._connectionController, this._editDocumentCodeLensProvider ); - this._activeConnectionCodeLensProvider = new ActiveConnectionCodeLensProvider( - this._connectionController - ); - this._exportToLanguageCodeLensProvider = new ExportToLanguageCodeLensProvider(); + this._activeConnectionCodeLensProvider = + new ActiveConnectionCodeLensProvider(this._connectionController); + this._exportToLanguageCodeLensProvider = + new ExportToLanguageCodeLensProvider(); this._codeActionProvider = new CodeActionProvider(); this._playgroundController = new PlaygroundController( this._connectionController, @@ -215,8 +215,12 @@ export default class MDBExtensionController implements vscode.Disposable { this.registerCommand(EXTENSION_COMMANDS.MDB_EXPORT_TO_RUBY, () => this._playgroundController.exportToLanguage(ExportToLanguages.RUBY) ); - this.registerCommand(EXTENSION_COMMANDS.MDB_CHANGE_EXPORT_TO_LANGUAGE_ADDONS, (exportToLanguageAddons) => - this._playgroundController.changeExportToLanguageAddons(exportToLanguageAddons) + this.registerCommand( + EXTENSION_COMMANDS.MDB_CHANGE_EXPORT_TO_LANGUAGE_ADDONS, + (exportToLanguageAddons) => + this._playgroundController.changeExportToLanguageAddons( + exportToLanguageAddons + ) ); // ------ DOCUMENTS ------ // @@ -300,9 +304,10 @@ export default class MDBExtensionController implements vscode.Disposable { this.registerCommand( EXTENSION_COMMANDS.MDB_COPY_CONNECTION_STRING, async (element: ConnectionTreeItem): Promise => { - const connectionString = this._connectionController.copyConnectionStringByConnectionId( - element.connectionId - ); + const connectionString = + this._connectionController.copyConnectionStringByConnectionId( + element.connectionId + ); await vscode.env.clipboard.writeText(connectionString); void vscode.window.showInformationMessage('Copied to clipboard.'); @@ -358,8 +363,9 @@ export default class MDBExtensionController implements vscode.Disposable { return false; } - return this._playgroundController - .createPlaygroundForCreateCollection(element); + return this._playgroundController.createPlaygroundForCreateCollection( + element + ); } ); this.registerCommand( @@ -374,7 +380,8 @@ export default class MDBExtensionController implements vscode.Disposable { this.registerCommand( EXTENSION_COMMANDS.MDB_DROP_DATABASE, async (element: DatabaseTreeItem): Promise => { - const successfullyDroppedDatabase = await element.onDropDatabaseClicked(); + const successfullyDroppedDatabase = + await element.onDropDatabaseClicked(); if (successfullyDroppedDatabase) { void vscode.window.showInformationMessage( @@ -409,8 +416,9 @@ export default class MDBExtensionController implements vscode.Disposable { return false; } - return this._playgroundController - .createPlaygroundForCreateCollection(element); + return this._playgroundController.createPlaygroundForCreateCollection( + element + ); } ); this.registerCommand( @@ -425,7 +433,8 @@ export default class MDBExtensionController implements vscode.Disposable { this.registerCommand( EXTENSION_COMMANDS.MDB_DROP_COLLECTION, async (element: CollectionTreeItem): Promise => { - const successfullyDroppedCollection = await element.onDropCollectionClicked(); + const successfullyDroppedCollection = + await element.onDropCollectionClicked(); if (successfullyDroppedCollection) { void vscode.window.showInformationMessage( @@ -475,7 +484,7 @@ export default class MDBExtensionController implements vscode.Disposable { documentId: element.documentId, namespace: element.namespace, connectionId: this._connectionController.getActiveConnectionId(), - line: 1 + line: 1, }); } ); @@ -547,7 +556,9 @@ export default class MDBExtensionController implements vscode.Disposable { const editor = vscode.window.activeTextEditor; if (!editor) { - void vscode.window.showInformationMessage('No active editor to insert to.'); + void vscode.window.showInformationMessage( + 'No active editor to insert to.' + ); return false; } diff --git a/src/storage/index.ts b/src/storage/index.ts index ad557d45..0c0fcf6f 100644 --- a/src/storage/index.ts +++ b/src/storage/index.ts @@ -1,6 +1,3 @@ import StorageController, { StorageVariables } from './storageController'; -export { - StorageController, - StorageVariables -}; +export { StorageController, StorageVariables }; diff --git a/src/storage/storageController.ts b/src/storage/storageController.ts index 6b1f91a1..2773c05f 100644 --- a/src/storage/storageController.ts +++ b/src/storage/storageController.ts @@ -11,25 +11,25 @@ export enum StorageVariables { GLOBAL_USER_ID = 'GLOBAL_USER_ID', GLOBAL_ANONYMOUS_ID = 'GLOBAL_ANONYMOUS_ID', // Only exists on workspaceState. - WORKSPACE_SAVED_CONNECTIONS = 'WORKSPACE_SAVED_CONNECTIONS' + WORKSPACE_SAVED_CONNECTIONS = 'WORKSPACE_SAVED_CONNECTIONS', } // Typically variables default to 'GLOBAL' scope. export enum StorageLocation { GLOBAL = 'GLOBAL', WORKSPACE = 'WORKSPACE', - NONE = 'NONE' + NONE = 'NONE', } // Coupled with the `defaultConnectionSavingLocation` configuration in `package.json`. export enum DefaultSavingLocations { 'Workspace' = 'Workspace', 'Global' = 'Global', - 'Session Only' = 'Session Only' + 'Session Only' = 'Session Only', } export type ConnectionsFromStorage = { - [connectionId: string]: StoreConnectionInfo + [connectionId: string]: StoreConnectionInfo; }; interface StorageVariableContents { @@ -43,16 +43,22 @@ type StoredVariableName = keyof StorageVariableContents; type StoredItem = StorageVariableContents[T]; export default class StorageController { - _storage: { [StorageLocation.GLOBAL]: vscode.Memento, [StorageLocation.WORKSPACE]: vscode.Memento }; + _storage: { + [StorageLocation.GLOBAL]: vscode.Memento; + [StorageLocation.WORKSPACE]: vscode.Memento; + }; constructor(context: vscode.ExtensionContext) { this._storage = { [StorageLocation.GLOBAL]: context.globalState, - [StorageLocation.WORKSPACE]: context.workspaceState + [StorageLocation.WORKSPACE]: context.workspaceState, }; } - get(variableName: T, storageLocation: StorageLocation = StorageLocation.GLOBAL): StoredItem { + get( + variableName: T, + storageLocation: StorageLocation = StorageLocation.GLOBAL + ): StoredItem { return this._storage[storageLocation].get(variableName); } @@ -75,13 +81,13 @@ export default class StorageController { // We keep sending `userId` to Segment for old users though to preserve their analytics. if (globalUserId && typeof globalUserId === 'string') { return { - userId: globalUserId + userId: globalUserId, }; } if (globalAnonymousId && typeof globalAnonymousId === 'string') { return { - anonymousId: globalAnonymousId + anonymousId: globalAnonymousId, }; } @@ -90,13 +96,19 @@ export default class StorageController { return { anonymousId }; } - async saveConnectionToStore(storeConnectionInfo: StoreConnectionInfo): Promise { - const variableName = (storeConnectionInfo.storageLocation === StorageLocation.GLOBAL) - ? StorageVariables.GLOBAL_SAVED_CONNECTIONS - : StorageVariables.WORKSPACE_SAVED_CONNECTIONS; + async saveConnectionToStore( + storeConnectionInfo: StoreConnectionInfo + ): Promise { + const variableName = + storeConnectionInfo.storageLocation === StorageLocation.GLOBAL + ? StorageVariables.GLOBAL_SAVED_CONNECTIONS + : StorageVariables.WORKSPACE_SAVED_CONNECTIONS; // Get the current saved connections. - let savedConnections = this.get(variableName, storeConnectionInfo.storageLocation); + let savedConnections = this.get( + variableName, + storeConnectionInfo.storageLocation + ); if (!savedConnections) { savedConnections = {}; @@ -113,7 +125,9 @@ export default class StorageController { ); } - async saveConnection(storeConnectionInfo: StoreConnectionInfo): Promise { + async saveConnection( + storeConnectionInfo: StoreConnectionInfo + ): Promise { const dontShowSaveLocationPrompt = vscode.workspace .getConfiguration('mdb.connectionSaving') .get('hideOptionToChooseWhereToSaveNewConnections'); @@ -121,12 +135,18 @@ export default class StorageController { if (dontShowSaveLocationPrompt === true) { // The user has chosen not to show the message on where to save the connection. // Save the connection in their default preference. - storeConnectionInfo.storageLocation = this.getPreferedStorageLocationFromConfiguration(); + storeConnectionInfo.storageLocation = + this.getPreferedStorageLocationFromConfiguration(); } else { - storeConnectionInfo.storageLocation = await this.getStorageLocationFromPrompt(); + storeConnectionInfo.storageLocation = + await this.getStorageLocationFromPrompt(); } - if ([StorageLocation.GLOBAL, StorageLocation.WORKSPACE].includes(storeConnectionInfo.storageLocation)) { + if ( + [StorageLocation.GLOBAL, StorageLocation.WORKSPACE].includes( + storeConnectionInfo.storageLocation + ) + ) { await this.saveConnectionToStore(storeConnectionInfo); } @@ -141,11 +161,11 @@ export default class StorageController { [ storeOnWorkspace, storeGlobally, - "Don't save this connection (it will be lost when the session is closed)" + "Don't save this connection (it will be lost when the session is closed)", ], { placeHolder: - 'Where would you like to save this new connection? (This message can be disabled in the extension settings.)' + 'Where would you like to save this new connection? (This message can be disabled in the extension settings.)', } ); @@ -194,11 +214,18 @@ export default class StorageController { } hasSavedConnections(): boolean { - const savedWorkspaceConnections = this.get(StorageVariables.WORKSPACE_SAVED_CONNECTIONS, StorageLocation.WORKSPACE); - const savedGlobalConnections = this.get(StorageVariables.GLOBAL_SAVED_CONNECTIONS, StorageLocation.GLOBAL); + const savedWorkspaceConnections = this.get( + StorageVariables.WORKSPACE_SAVED_CONNECTIONS, + StorageLocation.WORKSPACE + ); + const savedGlobalConnections = this.get( + StorageVariables.GLOBAL_SAVED_CONNECTIONS, + StorageLocation.GLOBAL + ); return ( - (savedWorkspaceConnections && Object.keys(savedWorkspaceConnections).length > 0) || + (savedWorkspaceConnections && + Object.keys(savedWorkspaceConnections).length > 0) || (savedGlobalConnections && Object.keys(savedGlobalConnections).length > 0) ); } diff --git a/src/telemetry/connectionTelemetry.ts b/src/telemetry/connectionTelemetry.ts index f38402aa..c8a4b41d 100644 --- a/src/telemetry/connectionTelemetry.ts +++ b/src/telemetry/connectionTelemetry.ts @@ -40,33 +40,33 @@ async function getCloudInfoFromDataService( ): Promise { try { const cloudInfo: { - isAws?: boolean, - isAzure?: boolean, - isGcp?: boolean + isAws?: boolean; + isAzure?: boolean; + isGcp?: boolean; } = await getCloudInfo(firstServerHostname); if (cloudInfo.isAws) { return { isPublicCloud: true, - publicCloudName: 'aws' + publicCloudName: 'aws', }; } if (cloudInfo.isGcp) { return { isPublicCloud: true, - publicCloudName: 'gcp' + publicCloudName: 'gcp', }; } if (cloudInfo.isAzure) { return { isPublicCloud: true, - publicCloudName: 'azure' + publicCloudName: 'azure', }; } return { isPublicCloud: false, - publicCloudName: null + publicCloudName: null, }; } catch (error) { log.error('TELEMETRY cloud info error', error); @@ -101,13 +101,11 @@ export async function getConnectionTelemetryProperties( server_version: instance.build.version, server_arch: instance.host.arch, server_os: instance.host.os, - is_used_connect_screen: - connectionType === ConnectionTypes.CONNECTION_FORM, + is_used_connect_screen: connectionType === ConnectionTypes.CONNECTION_FORM, is_used_command_palette: connectionType === ConnectionTypes.CONNECTION_STRING, - is_used_saved_connection: - connectionType === ConnectionTypes.CONNECTION_ID, - vscode_mdb_extension_version: version + is_used_saved_connection: connectionType === ConnectionTypes.CONNECTION_ID, + vscode_mdb_extension_version: version, }; return preparedProperties; diff --git a/src/telemetry/telemetryService.ts b/src/telemetry/telemetryService.ts index a5b6636c..1dbaa53d 100644 --- a/src/telemetry/telemetryService.ts +++ b/src/telemetry/telemetryService.ts @@ -10,7 +10,7 @@ import { createLogger } from '../logging'; import { DocumentSource } from '../documentSource'; import { getConnectionTelemetryProperties, - NewConnectionTelemetryEventProperties + NewConnectionTelemetryEventProperties, } from './connectionTelemetry'; import type { ShellExecuteAllResult } from '../types/playgroundType'; import { StorageController } from '../storage'; @@ -78,7 +78,7 @@ export enum TelemetryEventTypes { DOCUMENT_UPDATED = 'Document Updated', DOCUMENT_EDITED = 'Document Edited', QUERY_EXPORTED = 'Query Exported', - AGGREGATION_EXPORTED = 'Aggregation Exported' + AGGREGATION_EXPORTED = 'Aggregation Exported', } /** @@ -154,7 +154,7 @@ export default class TelemetryService { flushAt: process.env.MODE === 'development' ? 1 : 20, // The number of milliseconds to wait // before flushing the queue automatically. - flushInterval: 10000 // 10 seconds is the default libraries' value. + flushInterval: 10000, // 10 seconds is the default libraries' value. }); const segmentProperties = this.getTelemetryUserIdentity(); @@ -199,8 +199,8 @@ export default class TelemetryService { event: eventType, properties: { ...properties, - extension_version: `${version}` - } + extension_version: `${version}`, + }, }; log.info('TELEMETRY track', segmentProperties); @@ -224,12 +224,13 @@ export default class TelemetryService { return; } - const connectionTelemetryProperties = await getConnectionTelemetryProperties( - dataService, - connectionType - ); + const connectionTelemetryProperties = + await getConnectionTelemetryProperties(dataService, connectionType); - this.track(TelemetryEventTypes.NEW_CONNECTION, connectionTelemetryProperties); + this.track( + TelemetryEventTypes.NEW_CONNECTION, + connectionTelemetryProperties + ); } catch (error) { log.error('TELEMETRY track new connection', error); } @@ -269,12 +270,12 @@ export default class TelemetryService { getTelemetryUserIdentity() { if (this._segmentUserId) { return { - userId: this._segmentUserId + userId: this._segmentUserId, }; } return { - anonymousId: this._segmentAnonymousId + anonymousId: this._segmentAnonymousId, }; } @@ -286,14 +287,14 @@ export default class TelemetryService { this.track(TelemetryEventTypes.PLAYGROUND_CODE_EXECUTED, { type: result ? this.getPlaygroundResultType(result) : null, partial, - error + error, }); } trackLinkClicked(screen: string, linkId: string): void { this.track(TelemetryEventTypes.EXTENSION_LINK_CLICKED, { screen, - link_id: linkId + link_id: linkId, }); } @@ -313,11 +314,15 @@ export default class TelemetryService { this.track(TelemetryEventTypes.DOCUMENT_EDITED, { source }); } - trackQueryExported(queryExportedProps: QueryExportedTelemetryEventProperties): void { + trackQueryExported( + queryExportedProps: QueryExportedTelemetryEventProperties + ): void { this.track(TelemetryEventTypes.QUERY_EXPORTED, queryExportedProps); } - trackAggregationExported(aggExportedProps: QueryExportedTelemetryEventProperties): void { + trackAggregationExported( + aggExportedProps: QueryExportedTelemetryEventProperties + ): void { this.track(TelemetryEventTypes.AGGREGATION_EXPORTED, aggExportedProps); } } diff --git a/src/test/runTest.ts b/src/test/runTest.ts index fe2331a6..6a345c52 100644 --- a/src/test/runTest.ts +++ b/src/test/runTest.ts @@ -21,10 +21,7 @@ async function main(): Promise { await runTests({ extensionDevelopmentPath, extensionTestsPath, - launchArgs: [ - testWorkspace, - '--disable-extensions' - ] + launchArgs: [testWorkspace, '--disable-extensions'], }); } catch (err) { console.error('Failed to run tests:'); diff --git a/src/test/suite/commands/launchMongoShell.test.ts b/src/test/suite/commands/launchMongoShell.test.ts index 99368f75..9352f27a 100644 --- a/src/test/suite/commands/launchMongoShell.test.ts +++ b/src/test/suite/commands/launchMongoShell.test.ts @@ -38,7 +38,7 @@ suite('Commands Test Suite', () => { createTerminalStub.returns({ sendText: fakeSendTerminalText, - show: () => { } + show: () => {}, }); sandbox.replace(vscode.window, 'createTerminal', createTerminalStub); }); @@ -57,7 +57,8 @@ suite('Commands Test Suite', () => { }); test('openMongoDBShell should display an error message when not connected', async () => { - const errorMessage = 'You need to be connected before launching the MongoDB Shell.'; + const errorMessage = + 'You need to be connected before launching the MongoDB Shell.'; fakeShowErrorMessage.resolves(errorMessage); @@ -69,11 +70,12 @@ suite('Commands Test Suite', () => { }); test('openMongoDBShell should open a terminal with the active connection driver url', async () => { - const expectedDriverUrl = 'mongodb://localhost:27018/?readPreference=primary&ssl=false'; + const expectedDriverUrl = + 'mongodb://localhost:27018/?readPreference=primary&ssl=false'; fakeGetMongoClientConnectionOptions.returns({ url: 'mongodb://localhost:27018/?readPreference=primary&ssl=false', - options: {} + options: {}, }); fakeIsCurrentlyConnected.returns(true); @@ -101,7 +103,8 @@ suite('Commands Test Suite', () => { }); test('powershell openMongoDBShell should open a terminal with the active connection driver url', async () => { - const expectedDriverUrl = 'mongodb://localhost:27018/?readPreference=primary&ssl=false'; + const expectedDriverUrl = + 'mongodb://localhost:27018/?readPreference=primary&ssl=false'; fakeGetMongoClientConnectionOptions.returns({ url: 'mongodb://localhost:27018/?readPreference=primary&ssl=false', @@ -136,11 +139,12 @@ suite('Commands Test Suite', () => { }); test('windows cmd openMongoDBShell should open a terminal with the active connection driver url', async () => { - const expectedDriverUrl = 'mongodb://localhost:27018/?readPreference=primary&ssl=false'; + const expectedDriverUrl = + 'mongodb://localhost:27018/?readPreference=primary&ssl=false'; fakeGetMongoClientConnectionOptions.returns({ url: 'mongodb://localhost:27018/?readPreference=primary&ssl=false', - options: {} + options: {}, }); fakeIsCurrentlyConnected.returns(true); diff --git a/src/test/suite/connectionController.test.ts b/src/test/suite/connectionController.test.ts index 9aab0cda..463a1b54 100644 --- a/src/test/suite/connectionController.test.ts +++ b/src/test/suite/connectionController.test.ts @@ -7,13 +7,13 @@ import { DataService } from 'mongodb-data-service'; import AUTH_STRATEGY_VALUES from '../../views/webview-app/connection-model/constants/auth-strategies'; import ConnectionController, { - DataServiceEventTypes + DataServiceEventTypes, } from '../../connectionController'; import formatError from '../../utils/formatError'; import { StorageController, StorageVariables } from '../../storage'; import { StorageLocation, - DefaultSavingLocations + DefaultSavingLocations, } from '../../storage/storageController'; import READ_PREFERENCES from '../../views/webview-app/connection-model/constants/read-preferences'; import SSH_TUNNEL_TYPES from '../../views/webview-app/connection-model/constants/ssh-tunnel-types'; @@ -25,7 +25,7 @@ import { TEST_DATABASE_URI, TEST_DATABASE_URI_USER, TEST_USER_USERNAME, - TEST_USER_PASSWORD + TEST_USER_PASSWORD, } from './dbTestHelper'; const testDatabaseConnectionName = 'localhost:27018'; @@ -73,16 +73,20 @@ suite('Connection Controller Test Suite', function () { }); test('it connects to mongodb', async () => { - const succesfullyConnected = await testConnectionController.addNewConnectionStringAndConnect( - TEST_DATABASE_URI - ); + const succesfullyConnected = + await testConnectionController.addNewConnectionStringAndConnect( + TEST_DATABASE_URI + ); const connnectionId = testConnectionController.getActiveConnectionId() || ''; const name = testConnectionController._connections[connnectionId].name; const dataService = testConnectionController.getActiveDataService(); assert.strictEqual(succesfullyConnected, true); - assert.strictEqual(testConnectionController.getSavedConnections().length, 1); + assert.strictEqual( + testConnectionController.getSavedConnections().length, + 1 + ); assert.strictEqual(name, 'localhost:27018'); assert.strictEqual(testConnectionController.isCurrentlyConnected(), true); @@ -90,22 +94,30 @@ suite('Connection Controller Test Suite', function () { }); test('"disconnect()" disconnects from the active connection', async () => { - const succesfullyConnected = await testConnectionController.addNewConnectionStringAndConnect( - TEST_DATABASE_URI - ); + const succesfullyConnected = + await testConnectionController.addNewConnectionStringAndConnect( + TEST_DATABASE_URI + ); assert.strictEqual(succesfullyConnected, true); - assert.strictEqual(testConnectionController.getConnectionStatus(), 'CONNECTED'); + assert.strictEqual( + testConnectionController.getConnectionStatus(), + 'CONNECTED' + ); - const successfullyDisconnected = await testConnectionController.disconnect(); + const successfullyDisconnected = + await testConnectionController.disconnect(); // Disconnecting should keep the connection contract, just disconnected. - const connectionsCount = testConnectionController.getSavedConnections() - .length; + const connectionsCount = + testConnectionController.getSavedConnections().length; const connnectionId = testConnectionController.getActiveConnectionId(); const dataService = testConnectionController.getActiveDataService(); - assert.strictEqual(testConnectionController.getConnectionStatus(), 'DISCONNECTED'); + assert.strictEqual( + testConnectionController.getConnectionStatus(), + 'DISCONNECTED' + ); assert.strictEqual(successfullyDisconnected, true); assert.strictEqual(connectionsCount, 1); assert.strictEqual(connnectionId, null); @@ -119,9 +131,13 @@ suite('Connection Controller Test Suite', function () { sinon.replace(vscode.window, 'showErrorMessage', fakeVscodeErrorMessage); - const successfullyRemovedMongoDBConnection = await testConnectionController.onRemoveMongoDBConnection(); + const successfullyRemovedMongoDBConnection = + await testConnectionController.onRemoveMongoDBConnection(); - assert.strictEqual(fakeVscodeErrorMessage.firstCall.args[0], expectedMessage); + assert.strictEqual( + fakeVscodeErrorMessage.firstCall.args[0], + expectedMessage + ); assert.strictEqual(successfullyRemovedMongoDBConnection, false); }); @@ -131,16 +147,21 @@ suite('Connection Controller Test Suite', function () { sinon.replace(vscode.window, 'showErrorMessage', fakeVscodeErrorMessage); - const successfullyDisconnected = await testConnectionController.disconnect(); + const successfullyDisconnected = + await testConnectionController.disconnect(); - assert.strictEqual(fakeVscodeErrorMessage.firstCall.args[0], expectedMessage); + assert.strictEqual( + fakeVscodeErrorMessage.firstCall.args[0], + expectedMessage + ); assert.strictEqual(successfullyDisconnected, false); }); test('when adding a new connection it disconnects from the current connection', async () => { - const succesfullyConnected = await testConnectionController.addNewConnectionStringAndConnect( - TEST_DATABASE_URI - ); + const succesfullyConnected = + await testConnectionController.addNewConnectionStringAndConnect( + TEST_DATABASE_URI + ); assert.strictEqual(succesfullyConnected, true); @@ -151,16 +172,23 @@ suite('Connection Controller Test Suite', function () { } catch (error) { const expectedError = 'Failed to connect'; - assert.strictEqual(formatError(error).message.includes(expectedError), true); + assert.strictEqual( + formatError(error).message.includes(expectedError), + true + ); assert.strictEqual(testConnectionController.getActiveDataService(), null); - assert.strictEqual(testConnectionController.getActiveConnectionId(), null); + assert.strictEqual( + testConnectionController.getActiveConnectionId(), + null + ); } }); test('when adding a new connection it sets the connection controller as connecting while it disconnects from the current connection', async () => { - const succesfullyConnected = await testConnectionController.addNewConnectionStringAndConnect( - TEST_DATABASE_URI - ); + const succesfullyConnected = + await testConnectionController.addNewConnectionStringAndConnect( + TEST_DATABASE_URI + ); assert.strictEqual(succesfullyConnected, true); @@ -171,9 +199,10 @@ suite('Connection Controller Test Suite', function () { return Promise.resolve(true); }); - const succesfullyConnected2 = await testConnectionController.addNewConnectionStringAndConnect( - TEST_DATABASE_URI - ); + const succesfullyConnected2 = + await testConnectionController.addNewConnectionStringAndConnect( + TEST_DATABASE_URI + ); assert.strictEqual(succesfullyConnected2, true); assert.strictEqual(wasSetToConnectingWhenDisconnecting, true); @@ -221,14 +250,15 @@ suite('Connection Controller Test Suite', function () { test('when there are no existing connections in the store and the connection controller loads connections', async () => { await testConnectionController.loadSavedConnections(); - const connectionsCount = testConnectionController.getSavedConnections() - .length; + const connectionsCount = + testConnectionController.getSavedConnections().length; assert.strictEqual(connectionsCount, 0); }); test('the connection model loads both global and workspace stored connection models', async () => { - const expectedDriverUrl = 'mongodb://localhost:27018/?appname=mongodb-vscode+0.0.0-dev.0'; + const expectedDriverUrl = + 'mongodb://localhost:27018/?appname=mongodb-vscode+0.0.0-dev.0'; await vscode.workspace .getConfiguration('mdb.connectionSaving') @@ -258,8 +288,15 @@ suite('Connection Controller Test Suite', function () { const connections = testConnectionController._connections; assert.strictEqual(Object.keys(connections).length, 4); - assert.strictEqual(connections[Object.keys(connections)[0]].name, 'localhost:27018'); - assert.strictEqual(connections[Object.keys(connections)[2]].connectionOptions?.connectionString, expectedDriverUrl); + assert.strictEqual( + connections[Object.keys(connections)[0]].name, + 'localhost:27018' + ); + assert.strictEqual( + connections[Object.keys(connections)[2]].connectionOptions + ?.connectionString, + expectedDriverUrl + ); }); test('when a connection is added it is saved to the global storage', async () => { @@ -280,7 +317,10 @@ suite('Connection Controller Test Suite', function () { const id = Object.keys(globalStoreConnections)[0]; - assert.strictEqual(globalStoreConnections[id].name, testDatabaseConnectionName); + assert.strictEqual( + globalStoreConnections[id].name, + testDatabaseConnectionName + ); const workspaceStoreConnections = mockStorageController.get( StorageVariables.WORKSPACE_SAVED_CONNECTIONS @@ -310,7 +350,10 @@ suite('Connection Controller Test Suite', function () { const id = Object.keys(workspaceStoreConnections)[0]; - assert.strictEqual(workspaceStoreConnections[id].name, testDatabaseConnectionName); + assert.strictEqual( + workspaceStoreConnections[id].name, + testDatabaseConnectionName + ); const globalStoreConnections = mockStorageController.get( StorageVariables.GLOBAL_SAVED_CONNECTIONS, @@ -326,13 +369,12 @@ suite('Connection Controller Test Suite', function () { id: '25', name: 'tester', connectionOptions: { connectionString: TEST_DATABASE_URI }, - storageLocation: StorageLocation.NONE - } + storageLocation: StorageLocation.NONE, + }, }; - const successfulConnection = await testConnectionController.connectWithConnectionId( - '25' - ); + const successfulConnection = + await testConnectionController.connectWithConnectionId('25'); assert.strictEqual(successfulConnection, true); assert.strictEqual(testConnectionController.getActiveConnectionId(), '25'); @@ -360,12 +402,18 @@ suite('Connection Controller Test Suite', function () { await testConnectionController.disconnect(); testConnectionController.clearAllConnections(); - assert.strictEqual(testConnectionController.getSavedConnections().length, 0); + assert.strictEqual( + testConnectionController.getSavedConnections().length, + 0 + ); // Activate (which will load the past connection). await testConnectionController.loadSavedConnections(); - assert.strictEqual(testConnectionController.getSavedConnections().length, 1); + assert.strictEqual( + testConnectionController.getSavedConnections().length, + 1 + ); const id = testConnectionController.getSavedConnections()[0].id; @@ -390,9 +438,10 @@ suite('Connection Controller Test Suite', function () { assert.notStrictEqual(activeConnectionId, null); - const testDriverUrl = testConnectionController.copyConnectionStringByConnectionId( - activeConnectionId || '' - ); + const testDriverUrl = + testConnectionController.copyConnectionStringByConnectionId( + activeConnectionId || '' + ); assert.strictEqual(testDriverUrl, expectedDriverUrl); }); @@ -524,12 +573,18 @@ suite('Connection Controller Test Suite', function () { testConnectionController.clearAllConnections(); - assert.strictEqual(testConnectionController.getSavedConnections().length, 0); + assert.strictEqual( + testConnectionController.getSavedConnections().length, + 0 + ); // Activate (which will load the past connection). await testConnectionController.loadSavedConnections(); - assert.strictEqual(testConnectionController.getSavedConnections().length, 1); + assert.strictEqual( + testConnectionController.getSavedConnections().length, + 1 + ); const id = testConnectionController.getSavedConnections()[0].id; const name = testConnectionController._connections[id || 'x'].name; @@ -578,7 +633,8 @@ suite('Connection Controller Test Suite', function () { assert.strictEqual(connectionIds.length, 2); - const connectionQuickPicks = testConnectionController.getConnectionQuickPicks(); + const connectionQuickPicks = + testConnectionController.getConnectionQuickPicks(); assert.strictEqual(connectionQuickPicks.length, 3); assert.strictEqual(connectionQuickPicks[0].label, 'Add new connection'); @@ -602,7 +658,10 @@ suite('Connection Controller Test Suite', function () { await sleep(1050); assert.strictEqual(testConnectionController.isCurrentlyConnected(), true); - assert.strictEqual(testConnectionController.getActiveConnectionName(), 'localhost:27018'); + assert.strictEqual( + testConnectionController.getActiveConnectionName(), + 'localhost:27018' + ); }); test('updates the connecting version on each new connection attempt', async () => { @@ -612,13 +671,15 @@ suite('Connection Controller Test Suite', function () { TEST_DATABASE_URI ); - const currentConnectingVersion = testConnectionController.getConnectingVersion(); + const currentConnectingVersion = + testConnectionController.getConnectingVersion(); assert.notStrictEqual(currentConnectingVersion, null); - const id = testConnectionController._connections[ - Object.keys(testConnectionController._connections)[0] - ].id; + const id = + testConnectionController._connections[ + Object.keys(testConnectionController._connections)[0] + ].id; assert.strictEqual(currentConnectingVersion, id); @@ -626,7 +687,10 @@ suite('Connection Controller Test Suite', function () { TEST_DATABASE_URI ); - assert.notStrictEqual(testConnectionController.getConnectingVersion(), currentConnectingVersion); + assert.notStrictEqual( + testConnectionController.getConnectingVersion(), + currentConnectingVersion + ); }); test('it only connects to the most recent connection attempt', async () => { @@ -636,7 +700,7 @@ suite('Connection Controller Test Suite', function () { id, name: `test${i}`, connectionOptions: { connectionString: TEST_DATABASE_URI }, - storageLocation: StorageLocation.NONE + storageLocation: StorageLocation.NONE, }; } @@ -650,7 +714,10 @@ suite('Connection Controller Test Suite', function () { assert.strictEqual(testConnectionController.isConnecting(), false); assert.strictEqual(testConnectionController.isCurrentlyConnected(), true); - assert.strictEqual(testConnectionController.getActiveConnectionName(), 'test4'); + assert.strictEqual( + testConnectionController.getActiveConnectionName(), + 'test4' + ); }); }); @@ -682,13 +749,16 @@ suite('Connection Controller Test Suite', function () { id: connectionId, name: 'asdfasdg', connectionOptions: { connectionString: testDatabaseURI2WithTimeout }, - storageLocation: StorageLocation.NONE + storageLocation: StorageLocation.NONE, }; void testConnectionController.connectWithConnectionId(connectionId); assert.strictEqual(testConnectionController.isConnecting(), true); - assert.strictEqual(testConnectionController.getConnectionStatus(), 'CONNECTING'); + assert.strictEqual( + testConnectionController.getConnectionStatus(), + 'CONNECTING' + ); try { await testConnectionController.removeSavedConnection(connectionId); @@ -703,7 +773,7 @@ suite('Connection Controller Test Suite', function () { id: connectionId, name: 'asdfasdg', connectionOptions: { connectionString: TEST_DATABASE_URI }, - storageLocation: StorageLocation.NONE + storageLocation: StorageLocation.NONE, }; sinon.replace( @@ -751,22 +821,23 @@ suite('Connection Controller Test Suite', function () { kerberosCanonicalizeHostname: false, sslMethod: SSL_METHODS.NONE, sshTunnel: SSH_TUNNEL_TYPES.NONE, - sshTunnelPort: 22 - } + sshTunnelPort: 22, + }, }; - const newSavedConnectionInfoWithSecrets = await testConnectionController._migratePreviouslySavedConnection(oldSavedConnectionInfo); - - assert.deepStrictEqual( - newSavedConnectionInfoWithSecrets, - { - id: '1d700f37-ba57-4568-9552-0ea23effea89', - name: 'localhost:27017', - storageLocation: 'GLOBAL', - connectionOptions: { - connectionString: 'mongodb://localhost:27017/?readPreference=primary&ssl=false' - } - } - ); + const newSavedConnectionInfoWithSecrets = + await testConnectionController._migratePreviouslySavedConnection( + oldSavedConnectionInfo + ); + + assert.deepStrictEqual(newSavedConnectionInfoWithSecrets, { + id: '1d700f37-ba57-4568-9552-0ea23effea89', + name: 'localhost:27017', + storageLocation: 'GLOBAL', + connectionOptions: { + connectionString: + 'mongodb://localhost:27017/?readPreference=primary&ssl=false', + }, + }); }); test('_migratePreviouslySavedConnection converts an old previously saved connection model with secrets to a new connection info format', async () => { @@ -785,7 +856,7 @@ suite('Connection Controller Test Suite', function () { hosts: [ { host: 'host-shard-00-00.u88dd.test.test', port: 27017 }, { host: 'host-shard-00-01.u88dd.test.test', port: 27017 }, - { host: 'host-shard-00-02.u88dd.test.test', port: 27017 } + { host: 'host-shard-00-02.u88dd.test.test', port: 27017 }, ], extraOptions: {}, connectionType: 'NODE_DRIVER', @@ -801,23 +872,24 @@ suite('Connection Controller Test Suite', function () { ssl: true, sslMethod: SSL_METHODS.SYSTEMCA, sshTunnel: SSH_TUNNEL_TYPES.NONE, - sshTunnelPort: 22 - } + sshTunnelPort: 22, + }, }; - const newSavedConnectionInfoWithSecrets = await testConnectionController._migratePreviouslySavedConnection(oldSavedConnectionInfo); - - assert.deepStrictEqual( - newSavedConnectionInfoWithSecrets, - { - id: 'fb210b47-f85d-4823-8552-aa6d7825156b', - name: 'host.u88dd.test.test', - storageLocation: 'WORKSPACE', - connectionOptions: { - connectionString: 'mongodb+srv://username:password@compass-data-sets.e06dc.mongodb.net/test?authSource=admin&replicaSet=host-shard-0&readPreference=primary&appname=mongodb-vscode+0.6.14&ssl=true' - } - } - ); + const newSavedConnectionInfoWithSecrets = + await testConnectionController._migratePreviouslySavedConnection( + oldSavedConnectionInfo + ); + + assert.deepStrictEqual(newSavedConnectionInfoWithSecrets, { + id: 'fb210b47-f85d-4823-8552-aa6d7825156b', + name: 'host.u88dd.test.test', + storageLocation: 'WORKSPACE', + connectionOptions: { + connectionString: + 'mongodb+srv://username:password@compass-data-sets.e06dc.mongodb.net/test?authSource=admin&replicaSet=host-shard-0&readPreference=primary&appname=mongodb-vscode+0.6.14&ssl=true', + }, + }); }); test('_migratePreviouslySavedConnection does not store secrets to disc', async () => { @@ -836,7 +908,7 @@ suite('Connection Controller Test Suite', function () { hosts: [ { host: 'host-shard-00-00.u88dd.test.test', port: 27017 }, { host: 'host-shard-00-01.u88dd.test.test', port: 27017 }, - { host: 'host-shard-00-02.u88dd.test.test', port: 27017 } + { host: 'host-shard-00-02.u88dd.test.test', port: 27017 }, ], extraOptions: {}, connectionType: 'NODE_DRIVER', @@ -852,11 +924,11 @@ suite('Connection Controller Test Suite', function () { ssl: true, sslMethod: SSL_METHODS.SYSTEMCA, sshTunnel: SSH_TUNNEL_TYPES.NONE, - sshTunnelPort: 22 - } + sshTunnelPort: 22, + }, }; const mockSaveConnection: any = sinon.fake.resolves({ - id: 'fb210b47-f85d-4823-8552-aa6d7825156b' + id: 'fb210b47-f85d-4823-8552-aa6d7825156b', }); sinon.replace( @@ -865,9 +937,12 @@ suite('Connection Controller Test Suite', function () { mockSaveConnection ); - await testConnectionController._migratePreviouslySavedConnection(oldSavedConnectionInfo); + await testConnectionController._migratePreviouslySavedConnection( + oldSavedConnectionInfo + ); - const connectionString = mockSaveConnection.firstCall.args[0].connectionOptions?.connectionString; + const connectionString = + mockSaveConnection.firstCall.args[0].connectionOptions?.connectionString; assert.strictEqual(connectionString.includes(TEST_USER_USERNAME), true); assert.strictEqual(connectionString.includes(TEST_USER_PASSWORD), false); @@ -893,16 +968,17 @@ suite('Connection Controller Test Suite', function () { kerberosCanonicalizeHostname: false, sslMethod: SSL_METHODS.NONE, sshTunnel: SSH_TUNNEL_TYPES.NONE, - sshTunnelPort: 22 - } + sshTunnelPort: 22, + }, }; const mockMigratePreviouslySavedConnection: any = sinon.fake.resolves({ id: '1d700f37-ba57-4568-9552-0ea23effea89', name: 'localhost:27017', storageLocation: 'GLOBAL', connectionOptions: { - connectionString: 'mongodb://localhost:27017/?readPreference=primary&ssl=false' - } + connectionString: + 'mongodb://localhost:27017/?readPreference=primary&ssl=false', + }, }); sinon.replace( @@ -911,7 +987,9 @@ suite('Connection Controller Test Suite', function () { mockMigratePreviouslySavedConnection ); - await testConnectionController._getConnectionInfoWithSecrets(oldSavedConnectionInfo); + await testConnectionController._getConnectionInfoWithSecrets( + oldSavedConnectionInfo + ); assert.strictEqual(mockMigratePreviouslySavedConnection.called, true); }); @@ -922,10 +1000,13 @@ suite('Connection Controller Test Suite', function () { name: 'localhost:27017', storageLocation: StorageLocation.GLOBAL, connectionOptions: { - connectionString: 'mongodb://localhost:27017/?readPreference=primary&ssl=false' - } + connectionString: + 'mongodb://localhost:27017/?readPreference=primary&ssl=false', + }, }; - await testConnectionController._storageController.saveConnectionToStore(connectionInfo); + await testConnectionController._storageController.saveConnectionToStore( + connectionInfo + ); await testConnectionController.loadSavedConnections(); const connections = testConnectionController.getSavedConnections(); @@ -940,23 +1021,21 @@ suite('Connection Controller Test Suite', function () { mockMigratePreviouslySavedConnection ); - const newSavedConnectionInfoWithSecrets = await testConnectionController._getConnectionInfoWithSecrets(connections[0]); + const newSavedConnectionInfoWithSecrets = + await testConnectionController._getConnectionInfoWithSecrets( + connections[0] + ); - assert.deepStrictEqual( - newSavedConnectionInfoWithSecrets, - connectionInfo - ); + assert.deepStrictEqual(newSavedConnectionInfoWithSecrets, connectionInfo); assert.strictEqual(mockMigratePreviouslySavedConnection.called, false); }); test('addNewConnectionStringAndConnect saves connection without secrets to the global storage', async () => { - const mockConnect: any = sinon.fake.resolves({ successfullyConnected: true }); + const mockConnect: any = sinon.fake.resolves({ + successfullyConnected: true, + }); - sinon.replace( - testConnectionController, - '_connect', - mockConnect - ); + sinon.replace(testConnectionController, '_connect', mockConnect); await vscode.workspace .getConfiguration('mdb.connectionSaving') @@ -965,9 +1044,10 @@ suite('Connection Controller Test Suite', function () { TEST_DATABASE_URI_USER ); - const workspaceStoreConnections = testConnectionController._storageController.get( - StorageVariables.GLOBAL_SAVED_CONNECTIONS - ); + const workspaceStoreConnections = + testConnectionController._storageController.get( + StorageVariables.GLOBAL_SAVED_CONNECTIONS + ); assert.strictEqual( !!workspaceStoreConnections, @@ -978,11 +1058,34 @@ suite('Connection Controller Test Suite', function () { const connections = Object.values(workspaceStoreConnections); assert.strictEqual(connections.length, 1); - assert.strictEqual(connections[0].connectionOptions?.connectionString.includes(TEST_USER_USERNAME), true); - assert.strictEqual(connections[0].connectionOptions?.connectionString.includes(TEST_USER_PASSWORD), false); - assert.strictEqual(connections[0].connectionOptions?.connectionString.includes('appname=mongodb-vscode+0.0.0-dev.0'), true); - assert.strictEqual(testConnectionController._connections[connections[0].id].connectionOptions?.connectionString.includes(TEST_USER_PASSWORD), true); - assert.strictEqual(testConnectionController._connections[connections[0].id].name, 'localhost:27018'); + assert.strictEqual( + connections[0].connectionOptions?.connectionString.includes( + TEST_USER_USERNAME + ), + true + ); + assert.strictEqual( + connections[0].connectionOptions?.connectionString.includes( + TEST_USER_PASSWORD + ), + false + ); + assert.strictEqual( + connections[0].connectionOptions?.connectionString.includes( + 'appname=mongodb-vscode+0.0.0-dev.0' + ), + true + ); + assert.strictEqual( + testConnectionController._connections[ + connections[0].id + ].connectionOptions?.connectionString.includes(TEST_USER_PASSWORD), + true + ); + assert.strictEqual( + testConnectionController._connections[connections[0].id].name, + 'localhost:27018' + ); }); test('parseNewConnection converts a connection model to a connaction info and overrides a default appname', () => { @@ -996,7 +1099,7 @@ suite('Connection Controller Test Suite', function () { hosts: [ { host: 'host-shard-00-00.u88dd.test.test', port: 27017 }, { host: 'host-shard-00-01.u88dd.test.test', port: 27017 }, - { host: 'host-shard-00-02.u88dd.test.test', port: 27017 } + { host: 'host-shard-00-02.u88dd.test.test', port: 27017 }, ], extraOptions: {}, readPreference: READ_PREFERENCES.PRIMARY, @@ -1007,18 +1110,16 @@ suite('Connection Controller Test Suite', function () { sshTunnelPort: 22, mongodbUsername: 'username', mongodbPassword: 'somepassword', - mongodbDatabaseName: 'admin' + mongodbDatabaseName: 'admin', }); - assert.deepStrictEqual( - connectionInfo, - { - id: 'c4871b21-92c4-40e2-a2c2-fdd551cff114', - connectionOptions: { - connectionString: 'mongodb+srv://username:somepassword@host.u88dd.test.test/?authSource=admin&readPreference=primary&appname=mongodb-vscode+0.0.0-dev.0&ssl=true' - } - } - ); + assert.deepStrictEqual(connectionInfo, { + id: 'c4871b21-92c4-40e2-a2c2-fdd551cff114', + connectionOptions: { + connectionString: + 'mongodb+srv://username:somepassword@host.u88dd.test.test/?authSource=admin&readPreference=primary&appname=mongodb-vscode+0.0.0-dev.0&ssl=true', + }, + }); }); test('getMongoClientConnectionOptions returns url and options properties', async () => { @@ -1026,28 +1127,28 @@ suite('Connection Controller Test Suite', function () { TEST_DATABASE_URI ); - const mongoClientConnectionOptions = testConnectionController.getMongoClientConnectionOptions(); + const mongoClientConnectionOptions = + testConnectionController.getMongoClientConnectionOptions(); - assert.deepStrictEqual( - mongoClientConnectionOptions, - { - url: 'mongodb://localhost:27018/?appname=mongodb-vscode+0.0.0-dev.0', - options: { monitorCommands: true } - } - ); + assert.deepStrictEqual(mongoClientConnectionOptions, { + url: 'mongodb://localhost:27018/?appname=mongodb-vscode+0.0.0-dev.0', + options: { monitorCommands: true }, + }); }); test('_getConnectionStringWithProxy returns string with proxy options', () => { - const expectedConnectionStringWithProxy = 'mongodb://localhost:27018/?appname=mongodb-vscode+0.0.0-dev.0&proxyHost=localhost&proxyPassword=gwce7tr8733ujbr&proxyPort=3378&proxyUsername=test'; - const connectionString = testConnectionController._getConnectionStringWithProxy({ - url: 'mongodb://localhost:27018/?appname=mongodb-vscode+0.0.0-dev.0', - options: { - proxyHost: 'localhost', - proxyPassword: 'gwce7tr8733ujbr', - proxyPort: 3378, - proxyUsername: 'test', - } - }); + const expectedConnectionStringWithProxy = + 'mongodb://localhost:27018/?appname=mongodb-vscode+0.0.0-dev.0&proxyHost=localhost&proxyPassword=gwce7tr8733ujbr&proxyPort=3378&proxyUsername=test'; + const connectionString = + testConnectionController._getConnectionStringWithProxy({ + url: 'mongodb://localhost:27018/?appname=mongodb-vscode+0.0.0-dev.0', + options: { + proxyHost: 'localhost', + proxyPassword: 'gwce7tr8733ujbr', + proxyPort: 3378, + proxyUsername: 'test', + }, + }); assert.strictEqual(connectionString, expectedConnectionStringWithProxy); }); }); diff --git a/src/test/suite/dbTestHelper.ts b/src/test/suite/dbTestHelper.ts index f8c82658..79a351de 100644 --- a/src/test/suite/dbTestHelper.ts +++ b/src/test/suite/dbTestHelper.ts @@ -12,7 +12,9 @@ export const TEST_DB_NAME = 'vscodeTestDatabaseAA'; let testDataService; -export const createTestDataService = async (connectionString: string): Promise => { +export const createTestDataService = async ( + connectionString: string +): Promise => { testDataService = await connect({ connectionString }); return testDataService; }; @@ -21,12 +23,16 @@ export const seedTestDB = async ( collectionName: string, documentsArray: EJSON.SerializableTypes[] ): Promise => { - const insertMany = util.promisify(testDataService.insertMany.bind(testDataService)); + const insertMany = util.promisify( + testDataService.insertMany.bind(testDataService) + ); await insertMany(`${TEST_DB_NAME}.${collectionName}`, documentsArray, {}); }; export const cleanupTestDB = async (): Promise => { - const dropDatabase = util.promisify(testDataService.dropDatabase.bind(testDataService)); + const dropDatabase = util.promisify( + testDataService.dropDatabase.bind(testDataService) + ); await dropDatabase(TEST_DB_NAME); }; diff --git a/src/test/suite/editors/activeDBCodeLensProvider.test.ts b/src/test/suite/editors/activeDBCodeLensProvider.test.ts index a2a22a7f..725149cb 100644 --- a/src/test/suite/editors/activeDBCodeLensProvider.test.ts +++ b/src/test/suite/editors/activeDBCodeLensProvider.test.ts @@ -67,12 +67,13 @@ suite('Active DB CodeLens Provider Test Suite', () => { find: (namespace, filter, options, callback): void => { return callback(null, [{ field: 'Text message' }]); }, - instance: () => Promise.resolve({ - dataLake: {}, - build: {}, - genuineMongoDB: {}, - host: {} - }), + instance: () => + Promise.resolve({ + dataLake: {}, + build: {}, + genuineMongoDB: {}, + host: {}, + }), } as DataService; testConnectionController.setActiveDataService(mockActiveDataService); diff --git a/src/test/suite/editors/codeActionProvider.test.ts b/src/test/suite/editors/codeActionProvider.test.ts index f4df42fc..43cbfbe8 100644 --- a/src/test/suite/editors/codeActionProvider.test.ts +++ b/src/test/suite/editors/codeActionProvider.test.ts @@ -10,7 +10,10 @@ import { ExplorerController } from '../../../explorer'; import { LanguageServerController } from '../../../language'; import { mdbTestExtension } from '../stubbableMdbExtension'; import { PlaygroundController } from '../../../editors'; -import { PlaygroundResult, ExportToLanguageMode } from '../../../types/playgroundType'; +import { + PlaygroundResult, + ExportToLanguageMode, +} from '../../../types/playgroundType'; import { TEST_DATABASE_URI } from '../dbTestHelper'; import { TestExtensionContext } from '../stubs'; @@ -26,9 +29,7 @@ suite('Code Action Provider Test Suite', function () { sinon.replace( mdbTestExtension.testExtensionController, '_languageServerController', - new LanguageServerController( - testExtensionContext - ) + new LanguageServerController(testExtensionContext) ); sinon.replace( vscode.window, @@ -43,23 +44,25 @@ suite('Code Action Provider Test Suite', function () { const testActiveDBCodeLensProvider = new ActiveDBCodeLensProvider( mdbTestExtension.testExtensionController._connectionController ); - const testExportToLanguageCodeLensProvider = new ExportToLanguageCodeLensProvider(); + const testExportToLanguageCodeLensProvider = + new ExportToLanguageCodeLensProvider(); const testCodeActionProvider = new CodeActionProvider(); const testExplorerController = new ExplorerController( mdbTestExtension.testExtensionController._connectionController ); - mdbTestExtension.testExtensionController._playgroundController = new PlaygroundController( - mdbTestExtension.testExtensionController._connectionController, - mdbTestExtension.testExtensionController._languageServerController, - mdbTestExtension.testExtensionController._telemetryService, - mdbTestExtension.testExtensionController._statusView, - mdbTestExtension.testExtensionController._playgroundResultViewProvider, - testActiveDBCodeLensProvider, - testExportToLanguageCodeLensProvider, - testCodeActionProvider, - testExplorerController - ); + mdbTestExtension.testExtensionController._playgroundController = + new PlaygroundController( + mdbTestExtension.testExtensionController._connectionController, + mdbTestExtension.testExtensionController._languageServerController, + mdbTestExtension.testExtensionController._telemetryService, + mdbTestExtension.testExtensionController._statusView, + mdbTestExtension.testExtensionController._playgroundResultViewProvider, + testActiveDBCodeLensProvider, + testExportToLanguageCodeLensProvider, + testCodeActionProvider, + testExplorerController + ); const mockOpenPlaygroundResult: any = sinon.fake(); sinon.replace( @@ -93,15 +96,19 @@ suite('Code Action Provider Test Suite', function () { }); test('returns a run selected playground blocks action', async () => { - mdbTestExtension.testExtensionController._playgroundController._selectedText = '123'; + mdbTestExtension.testExtensionController._playgroundController._selectedText = + '123'; const selection = { start: { line: 0, character: 0 }, - end: { line: 0, character: 4 } + end: { line: 0, character: 4 }, } as vscode.Selection; const testCodeActionProvider = new CodeActionProvider(); - testCodeActionProvider.refresh({ selection, mode: ExportToLanguageMode.OTHER }); + testCodeActionProvider.refresh({ + selection, + mode: ExportToLanguageMode.OTHER, + }); const codeActions = testCodeActionProvider.provideCodeActions(); @@ -112,14 +119,29 @@ suite('Code Action Provider Test Suite', function () { const actionCommand = codeActions[0].command; if (actionCommand) { - expect(actionCommand.command).to.be.equal('mdb.runSelectedPlaygroundBlocks'); - expect(actionCommand.title).to.be.equal('Run selected playground blocks'); + expect(actionCommand.command).to.be.equal( + 'mdb.runSelectedPlaygroundBlocks' + ); + expect(actionCommand.title).to.be.equal( + 'Run selected playground blocks' + ); await vscode.commands.executeCommand(actionCommand.command); - const expectedResult = { namespace: null, type: 'number', content: 123, language: 'plaintext' }; - expect(mdbTestExtension.testExtensionController._playgroundController._playgroundResult).to.be.deep.equal(expectedResult); - expect(mdbTestExtension.testExtensionController._playgroundController._isPartialRun).to.be.equal(true); + const expectedResult = { + namespace: null, + type: 'number', + content: 123, + language: 'plaintext', + }; + expect( + mdbTestExtension.testExtensionController._playgroundController + ._playgroundResult + ).to.be.deep.equal(expectedResult); + expect( + mdbTestExtension.testExtensionController._playgroundController + ._isPartialRun + ).to.be.equal(true); } } }); @@ -128,15 +150,21 @@ suite('Code Action Provider Test Suite', function () { const textFromEditor = ' { name: "Alena Khineika" } '; const selection = { start: { line: 0, character: 2 }, - end: { line: 0, character: 27 } + end: { line: 0, character: 27 }, } as vscode.Selection; const mode = ExportToLanguageMode.QUERY; - const activeTextEditor = { document: { getText: () => textFromEditor } } as vscode.TextEditor; - - mdbTestExtension.testExtensionController._playgroundController._selectedText = textFromEditor; - mdbTestExtension.testExtensionController._playgroundController._codeActionProvider.selection = selection; - mdbTestExtension.testExtensionController._playgroundController._codeActionProvider.mode = mode; - mdbTestExtension.testExtensionController._playgroundController._activeTextEditor = activeTextEditor; + const activeTextEditor = { + document: { getText: () => textFromEditor }, + } as vscode.TextEditor; + + mdbTestExtension.testExtensionController._playgroundController._selectedText = + textFromEditor; + mdbTestExtension.testExtensionController._playgroundController._codeActionProvider.selection = + selection; + mdbTestExtension.testExtensionController._playgroundController._codeActionProvider.mode = + mode; + mdbTestExtension.testExtensionController._playgroundController._activeTextEditor = + activeTextEditor; const testCodeActionProvider = new CodeActionProvider(); testCodeActionProvider.refresh({ selection, mode }); @@ -160,15 +188,21 @@ suite('Code Action Provider Test Suite', function () { const textFromEditor = "{ name: '22' }"; const selection = { start: { line: 0, character: 0 }, - end: { line: 0, character: 14 } + end: { line: 0, character: 14 }, } as vscode.Selection; const mode = ExportToLanguageMode.QUERY; - const activeTextEditor = { document: { getText: () => textFromEditor } } as vscode.TextEditor; - - mdbTestExtension.testExtensionController._playgroundController._selectedText = textFromEditor; - mdbTestExtension.testExtensionController._playgroundController._codeActionProvider.selection = selection; - mdbTestExtension.testExtensionController._playgroundController._codeActionProvider.mode = mode; - mdbTestExtension.testExtensionController._playgroundController._activeTextEditor = activeTextEditor; + const activeTextEditor = { + document: { getText: () => textFromEditor }, + } as vscode.TextEditor; + + mdbTestExtension.testExtensionController._playgroundController._selectedText = + textFromEditor; + mdbTestExtension.testExtensionController._playgroundController._codeActionProvider.selection = + selection; + mdbTestExtension.testExtensionController._playgroundController._codeActionProvider.mode = + mode; + mdbTestExtension.testExtensionController._playgroundController._activeTextEditor = + activeTextEditor; const testCodeActionProvider = new CodeActionProvider(); testCodeActionProvider.refresh({ selection, mode }); @@ -187,19 +221,32 @@ suite('Code Action Provider Test Suite', function () { await vscode.commands.executeCommand(actionCommand.command); - const expectedResult = { namespace: 'DATABASE_NAME.COLLECTION_NAME', type: null, content: 'new Document("name", "22")', language: 'java' }; + const expectedResult = { + namespace: 'DATABASE_NAME.COLLECTION_NAME', + type: null, + content: 'new Document("name", "22")', + language: 'java', + }; - const codeLenses = mdbTestExtension.testExtensionController._playgroundController._exportToLanguageCodeLensProvider.provideCodeLenses(); + const codeLenses = + mdbTestExtension.testExtensionController._playgroundController._exportToLanguageCodeLensProvider.provideCodeLenses(); expect(codeLenses.length).to.be.equal(3); // Only java queries supports builders. - await vscode.commands.executeCommand('mdb.changeExportToLanguageAddons', { - ...mdbTestExtension.testExtensionController._playgroundController._exportToLanguageCodeLensProvider._exportToLanguageAddons, - builders: true - }); + await vscode.commands.executeCommand( + 'mdb.changeExportToLanguageAddons', + { + ...mdbTestExtension.testExtensionController._playgroundController + ._exportToLanguageCodeLensProvider._exportToLanguageAddons, + builders: true, + } + ); expectedResult.content = 'eq("name", "22")'; - expect(mdbTestExtension.testExtensionController._playgroundController._playgroundResult).to.be.deep.equal(expectedResult); + expect( + mdbTestExtension.testExtensionController._playgroundController + ._playgroundResult + ).to.be.deep.equal(expectedResult); } } }); @@ -208,15 +255,21 @@ suite('Code Action Provider Test Suite', function () { const textFromEditor = "{ name: '22' }"; const selection = { start: { line: 0, character: 0 }, - end: { line: 0, character: 14 } + end: { line: 0, character: 14 }, } as vscode.Selection; const mode = ExportToLanguageMode.QUERY; - const activeTextEditor = { document: { getText: () => textFromEditor } } as vscode.TextEditor; - - mdbTestExtension.testExtensionController._playgroundController._selectedText = textFromEditor; - mdbTestExtension.testExtensionController._playgroundController._codeActionProvider.selection = selection; - mdbTestExtension.testExtensionController._playgroundController._codeActionProvider.mode = mode; - mdbTestExtension.testExtensionController._playgroundController._activeTextEditor = activeTextEditor; + const activeTextEditor = { + document: { getText: () => textFromEditor }, + } as vscode.TextEditor; + + mdbTestExtension.testExtensionController._playgroundController._selectedText = + textFromEditor; + mdbTestExtension.testExtensionController._playgroundController._codeActionProvider.selection = + selection; + mdbTestExtension.testExtensionController._playgroundController._codeActionProvider.mode = + mode; + mdbTestExtension.testExtensionController._playgroundController._activeTextEditor = + activeTextEditor; const testCodeActionProvider = new CodeActionProvider(); @@ -239,21 +292,33 @@ suite('Code Action Provider Test Suite', function () { const expectedResult = { namespace: 'DATABASE_NAME.COLLECTION_NAME', type: null, - content: 'new BsonDocument(\"name\", \"22\")', - language: 'csharp' + content: 'new BsonDocument("name", "22")', + language: 'csharp', }; - expect(mdbTestExtension.testExtensionController._playgroundController._playgroundResult).to.be.deep.equal(expectedResult); + expect( + mdbTestExtension.testExtensionController._playgroundController + ._playgroundResult + ).to.be.deep.equal(expectedResult); - const codeLenses = mdbTestExtension.testExtensionController._playgroundController._exportToLanguageCodeLensProvider.provideCodeLenses(); + const codeLenses = + mdbTestExtension.testExtensionController._playgroundController._exportToLanguageCodeLensProvider.provideCodeLenses(); expect(codeLenses.length).to.be.equal(1); // Csharp does not support driver syntax. - await vscode.commands.executeCommand('mdb.changeExportToLanguageAddons', { - ...mdbTestExtension.testExtensionController._playgroundController._exportToLanguageCodeLensProvider._exportToLanguageAddons, - importStatements: true - }); - - expectedResult.content = 'using MongoDB.Bson;\nusing MongoDB.Driver;\n\nnew BsonDocument(\"name\", \"22\")'; - expect(mdbTestExtension.testExtensionController._playgroundController._playgroundResult).to.be.deep.equal(expectedResult); + await vscode.commands.executeCommand( + 'mdb.changeExportToLanguageAddons', + { + ...mdbTestExtension.testExtensionController._playgroundController + ._exportToLanguageCodeLensProvider._exportToLanguageAddons, + importStatements: true, + } + ); + + expectedResult.content = + 'using MongoDB.Bson;\nusing MongoDB.Driver;\n\nnew BsonDocument("name", "22")'; + expect( + mdbTestExtension.testExtensionController._playgroundController + ._playgroundResult + ).to.be.deep.equal(expectedResult); } } }); @@ -262,15 +327,21 @@ suite('Code Action Provider Test Suite', function () { const textFromEditor = "use('db'); db.coll.find({ name: '22' })"; const selection = { start: { line: 0, character: 24 }, - end: { line: 0, character: 38 } + end: { line: 0, character: 38 }, } as vscode.Selection; const mode = ExportToLanguageMode.QUERY; - const activeTextEditor = { document: { getText: () => textFromEditor } } as vscode.TextEditor; - - mdbTestExtension.testExtensionController._playgroundController._selectedText = "{ name: '22' }"; - mdbTestExtension.testExtensionController._playgroundController._codeActionProvider.selection = selection; - mdbTestExtension.testExtensionController._playgroundController._codeActionProvider.mode = mode; - mdbTestExtension.testExtensionController._playgroundController._activeTextEditor = activeTextEditor; + const activeTextEditor = { + document: { getText: () => textFromEditor }, + } as vscode.TextEditor; + + mdbTestExtension.testExtensionController._playgroundController._selectedText = + "{ name: '22' }"; + mdbTestExtension.testExtensionController._playgroundController._codeActionProvider.selection = + selection; + mdbTestExtension.testExtensionController._playgroundController._codeActionProvider.mode = + mode; + mdbTestExtension.testExtensionController._playgroundController._activeTextEditor = + activeTextEditor; const testCodeActionProvider = new CodeActionProvider(); testCodeActionProvider.refresh({ selection, mode }); @@ -293,26 +364,38 @@ suite('Code Action Provider Test Suite', function () { namespace: 'DATABASE_NAME.COLLECTION_NAME', type: null, content: "{\n 'name': '22'\n}", - language: 'python' + language: 'python', }; - expect(mdbTestExtension.testExtensionController._playgroundController._playgroundResult).to.be.deep.equal(expectedResult); + expect( + mdbTestExtension.testExtensionController._playgroundController + ._playgroundResult + ).to.be.deep.equal(expectedResult); - const codeLenses = mdbTestExtension.testExtensionController._playgroundController._exportToLanguageCodeLensProvider.provideCodeLenses(); + const codeLenses = + mdbTestExtension.testExtensionController._playgroundController._exportToLanguageCodeLensProvider.provideCodeLenses(); expect(codeLenses.length).to.be.equal(2); - await vscode.commands.executeCommand('mdb.changeExportToLanguageAddons', { - ...mdbTestExtension.testExtensionController._playgroundController._exportToLanguageCodeLensProvider._exportToLanguageAddons, - driverSyntax: true - }); + await vscode.commands.executeCommand( + 'mdb.changeExportToLanguageAddons', + { + ...mdbTestExtension.testExtensionController._playgroundController + ._exportToLanguageCodeLensProvider._exportToLanguageAddons, + driverSyntax: true, + } + ); expectedResult = { namespace: 'db.coll', type: null, - content: "# Requires the PyMongo package.\n# https://api.mongodb.com/python/current\n\nclient = MongoClient('mongodb://localhost:27018/?appname=mongodb-vscode+0.0.0-dev.0')\nfilter={\n 'name': '22'\n}\n\nresult = client['db']['coll'].find(\n filter=filter\n)", - language: 'python' + content: + "# Requires the PyMongo package.\n# https://api.mongodb.com/python/current\n\nclient = MongoClient('mongodb://localhost:27018/?appname=mongodb-vscode+0.0.0-dev.0')\nfilter={\n 'name': '22'\n}\n\nresult = client['db']['coll'].find(\n filter=filter\n)", + language: 'python', }; - expect(mdbTestExtension.testExtensionController._playgroundController._playgroundResult).to.be.deep.equal(expectedResult); + expect( + mdbTestExtension.testExtensionController._playgroundController + ._playgroundResult + ).to.be.deep.equal(expectedResult); } } }); @@ -320,15 +403,21 @@ suite('Code Action Provider Test Suite', function () { const textFromEditor = "use('db'); db.coll.find({ name: '22' })"; const selection = { start: { line: 0, character: 24 }, - end: { line: 0, character: 38 } + end: { line: 0, character: 38 }, } as vscode.Selection; const mode = ExportToLanguageMode.QUERY; - const activeTextEditor = { document: { getText: () => textFromEditor } } as vscode.TextEditor; - - mdbTestExtension.testExtensionController._playgroundController._selectedText = "{ name: '22' }"; - mdbTestExtension.testExtensionController._playgroundController._codeActionProvider.selection = selection; - mdbTestExtension.testExtensionController._playgroundController._codeActionProvider.mode = mode; - mdbTestExtension.testExtensionController._playgroundController._activeTextEditor = activeTextEditor; + const activeTextEditor = { + document: { getText: () => textFromEditor }, + } as vscode.TextEditor; + + mdbTestExtension.testExtensionController._playgroundController._selectedText = + "{ name: '22' }"; + mdbTestExtension.testExtensionController._playgroundController._codeActionProvider.selection = + selection; + mdbTestExtension.testExtensionController._playgroundController._codeActionProvider.mode = + mode; + mdbTestExtension.testExtensionController._playgroundController._activeTextEditor = + activeTextEditor; const testCodeActionProvider = new CodeActionProvider(); testCodeActionProvider.refresh({ selection, mode }); @@ -351,26 +440,38 @@ suite('Code Action Provider Test Suite', function () { namespace: 'DATABASE_NAME.COLLECTION_NAME', type: null, content: "{\n 'name' => '22'\n}", - language: 'ruby' + language: 'ruby', }; - expect(mdbTestExtension.testExtensionController._playgroundController._playgroundResult).to.be.deep.equal(expectedResult); + expect( + mdbTestExtension.testExtensionController._playgroundController + ._playgroundResult + ).to.be.deep.equal(expectedResult); - const codeLenses = mdbTestExtension.testExtensionController._playgroundController._exportToLanguageCodeLensProvider.provideCodeLenses(); + const codeLenses = + mdbTestExtension.testExtensionController._playgroundController._exportToLanguageCodeLensProvider.provideCodeLenses(); expect(codeLenses.length).to.be.equal(2); - await vscode.commands.executeCommand('mdb.changeExportToLanguageAddons', { - ...mdbTestExtension.testExtensionController._playgroundController._exportToLanguageCodeLensProvider._exportToLanguageAddons, - driverSyntax: true - }); + await vscode.commands.executeCommand( + 'mdb.changeExportToLanguageAddons', + { + ...mdbTestExtension.testExtensionController._playgroundController + ._exportToLanguageCodeLensProvider._exportToLanguageAddons, + driverSyntax: true, + } + ); expectedResult = { namespace: 'db.coll', type: null, - content: "# Requires the MongoDB Ruby Driver\n# https://docs.mongodb.com/ruby-driver/master/\n\nclient = Mongo::Client.new('mongodb://localhost:27018/?appname=mongodb-vscode+0.0.0-dev.0', :database => 'db')\n\nresult = client.database['coll'].find({\n 'name' => '22'\n})", - language: 'ruby' + content: + "# Requires the MongoDB Ruby Driver\n# https://docs.mongodb.com/ruby-driver/master/\n\nclient = Mongo::Client.new('mongodb://localhost:27018/?appname=mongodb-vscode+0.0.0-dev.0', :database => 'db')\n\nresult = client.database['coll'].find({\n 'name' => '22'\n})", + language: 'ruby', }; - expect(mdbTestExtension.testExtensionController._playgroundController._playgroundResult).to.be.deep.equal(expectedResult); + expect( + mdbTestExtension.testExtensionController._playgroundController + ._playgroundResult + ).to.be.deep.equal(expectedResult); } } }); diff --git a/src/test/suite/editors/collectionDocumentsCodeLensProvider.test.ts b/src/test/suite/editors/collectionDocumentsCodeLensProvider.test.ts index 68f8e4b3..bc84f3a4 100644 --- a/src/test/suite/editors/collectionDocumentsCodeLensProvider.test.ts +++ b/src/test/suite/editors/collectionDocumentsCodeLensProvider.test.ts @@ -21,7 +21,7 @@ suite('Collection Documents Provider Test Suite', () => { const mockDocument = { ...mockVSCodeTextDocument, uri, - lineCount: 50 + lineCount: 50, }; const codeLens = testCodeLensProvider.provideCodeLenses(mockDocument); @@ -55,7 +55,7 @@ suite('Collection Documents Provider Test Suite', () => { const mockDocument = { ...mockVSCodeTextDocument, - uri + uri, }; const codeLens = testCodeLensProvider.provideCodeLenses(mockDocument); diff --git a/src/test/suite/editors/collectionDocumentsProvider.test.ts b/src/test/suite/editors/collectionDocumentsProvider.test.ts index 56a7a57d..d964efdf 100644 --- a/src/test/suite/editors/collectionDocumentsProvider.test.ts +++ b/src/test/suite/editors/collectionDocumentsProvider.test.ts @@ -6,7 +6,9 @@ import sinon from 'sinon'; import { DocumentSource } from '../../../documentSource'; import CollectionDocumentsOperationsStore from '../../../editors/collectionDocumentsOperationsStore'; -import CollectionDocumentsProvider, { VIEW_COLLECTION_SCHEME } from '../../../editors/collectionDocumentsProvider'; +import CollectionDocumentsProvider, { + VIEW_COLLECTION_SCHEME, +} from '../../../editors/collectionDocumentsProvider'; import ConnectionController from '../../../connectionController'; import EditDocumentCodeLensProvider from '../../../editors/editDocumentCodeLensProvider'; import { StatusView } from '../../../views'; @@ -55,7 +57,7 @@ suite('Collection Documents Provider Test Suite', () => { ); return callback(null, [{ field: 'Declaration of Independence' }]); - } + }, } as DataService; const mockConnectionController = new ConnectionController( @@ -99,18 +101,18 @@ suite('Collection Documents Provider Test Suite', () => { const mockDocuments = [ { _id: 'first_id', - field1: 'first_field' + field1: 'first_field', }, { _id: 'first_id', - field1: 'first_field' - } + field1: 'first_field', + }, ]; const mockActiveDataService = { find: (namespace, filter, options, callback): void => { return callback(null, mockDocuments); - } + }, } as DataService; const mockConnectionController = new ConnectionController( new StatusView(mockExtensionContext), @@ -153,7 +155,7 @@ suite('Collection Documents Provider Test Suite', () => { const mockActiveDataService = { find: (namespace, filter, options, callback): void => { return callback(null, [{ field: 'Apollo' }, { field: 'Gemini ' }]); - } + }, } as DataService; const mockConnectionController = new ConnectionController( new StatusView(mockExtensionContext), @@ -278,9 +280,12 @@ suite('Collection Documents Provider Test Suite', () => { testCodeLensProvider ); - testCollectionViewProvider._operationsStore = new CollectionDocumentsOperationsStore(); + testCollectionViewProvider._operationsStore = + new CollectionDocumentsOperationsStore(); - const documents: any[] = [ { _id: '5ea8745ee4811fafe8b65ecb', koko: 'nothing5' } ]; + const documents: any[] = [ + { _id: '5ea8745ee4811fafe8b65ecb', koko: 'nothing5' }, + ]; const mockGetActiveDataService = sinon.fake.returns({ find: ( namespace: string, @@ -289,7 +294,7 @@ suite('Collection Documents Provider Test Suite', () => { callback: (error: Error | null, result: object) => void ) => { return callback(null, documents); - } + }, }); sinon.replace( testCollectionViewProvider._connectionController, @@ -298,10 +303,18 @@ suite('Collection Documents Provider Test Suite', () => { ); const mockShowMessage = sinon.fake(); - sinon.replace(testCollectionViewProvider._statusView, 'showMessage', mockShowMessage); + sinon.replace( + testCollectionViewProvider._statusView, + 'showMessage', + mockShowMessage + ); const mockHideMessage = sinon.fake(); - sinon.replace(testCollectionViewProvider._statusView, 'hideMessage', mockHideMessage); + sinon.replace( + testCollectionViewProvider._statusView, + 'hideMessage', + mockHideMessage + ); const connectionId = '1c8c2b06-fbfb-40b7-bd8a-bd1f8333a487'; const mockActiveConnectionId = sinon.fake.returns(connectionId); @@ -311,12 +324,13 @@ suite('Collection Documents Provider Test Suite', () => { mockActiveConnectionId ); - const firstCollectionOperationId = testCollectionViewProvider._operationsStore.createNewOperation(); + const firstCollectionOperationId = + testCollectionViewProvider._operationsStore.createNewOperation(); const firstCollectionNamespace = 'berlin.cocktailbars'; const firstCollectionQuery = [ `namespace=${firstCollectionNamespace}`, `connectionId=${connectionId}`, - `operationId=${firstCollectionOperationId}` + `operationId=${firstCollectionOperationId}`, ].join('&'); const firstCollectionUri = vscode.Uri.parse( `${VIEW_COLLECTION_SCHEME}:Results: ${firstCollectionNamespace}.json?${firstCollectionQuery}` @@ -324,9 +338,15 @@ suite('Collection Documents Provider Test Suite', () => { const activeTextEditor = mockTextEditor; activeTextEditor.document.uri = firstCollectionUri; - sandbox.replaceGetter(vscode.window, 'activeTextEditor', () => activeTextEditor); + sandbox.replaceGetter( + vscode.window, + 'activeTextEditor', + () => activeTextEditor + ); - await testCollectionViewProvider.provideTextDocumentContent(firstCollectionUri); + await testCollectionViewProvider.provideTextDocumentContent( + firstCollectionUri + ); let codeLenses = testCodeLensProvider.provideCodeLenses(); @@ -342,30 +362,46 @@ suite('Collection Documents Provider Test Suite', () => { ); assert(codeLenses[0].command?.title === 'Edit Document'); - const firstCollectionFirstCommandArguments = codeLenses[0].command?.arguments; + const firstCollectionFirstCommandArguments = + codeLenses[0].command?.arguments; assert(!!firstCollectionFirstCommandArguments); - assert(firstCollectionFirstCommandArguments[0].source === DocumentSource.DOCUMENT_SOURCE_COLLECTIONVIEW); - assert(firstCollectionFirstCommandArguments[0].namespace === firstCollectionNamespace); - assert(firstCollectionFirstCommandArguments[0].connectionId === connectionId); - assert(firstCollectionFirstCommandArguments[0].documentId === '5ea8745ee4811fafe8b65ecb'); + assert( + firstCollectionFirstCommandArguments[0].source === + DocumentSource.DOCUMENT_SOURCE_COLLECTIONVIEW + ); + assert( + firstCollectionFirstCommandArguments[0].namespace === + firstCollectionNamespace + ); + assert( + firstCollectionFirstCommandArguments[0].connectionId === connectionId + ); + assert( + firstCollectionFirstCommandArguments[0].documentId === + '5ea8745ee4811fafe8b65ecb' + ); let codeLensesInfo = testCodeLensProvider._codeLensesInfo; assert(Object.keys(codeLensesInfo).length === 1); - let firstCollectionCodeLensesInfo = testCodeLensProvider._codeLensesInfo[firstCollectionUri.toString()]; + let firstCollectionCodeLensesInfo = + testCodeLensProvider._codeLensesInfo[firstCollectionUri.toString()]; assert(!!firstCollectionCodeLensesInfo); - assert(firstCollectionCodeLensesInfo[0].documentId === '5ea8745ee4811fafe8b65ecb'); + assert( + firstCollectionCodeLensesInfo[0].documentId === '5ea8745ee4811fafe8b65ecb' + ); // Connect to another connection. - const secondCollectionOperationId = testCollectionViewProvider._operationsStore.createNewOperation(); + const secondCollectionOperationId = + testCollectionViewProvider._operationsStore.createNewOperation(); const secondCollectionNamespace = 'companies.companies'; const secondCollectionQuery = [ `namespace=${secondCollectionNamespace}`, `connectionId=${connectionId}`, - `operationId=${secondCollectionOperationId}` + `operationId=${secondCollectionOperationId}`, ].join('&'); const secondCollectionUri = vscode.Uri.parse( `${VIEW_COLLECTION_SCHEME}:Results: ${secondCollectionNamespace}.json?${secondCollectionQuery}` @@ -378,7 +414,9 @@ suite('Collection Documents Provider Test Suite', () => { { _id: '26', name: 'another name', price: 500 } ); - await testCollectionViewProvider.provideTextDocumentContent(secondCollectionUri); + await testCollectionViewProvider.provideTextDocumentContent( + secondCollectionUri + ); codeLenses = testCodeLensProvider.provideCodeLenses(); assert(!!codeLenses); @@ -393,23 +431,39 @@ suite('Collection Documents Provider Test Suite', () => { ); assert(codeLenses[0].command?.title === 'Edit Document'); - const secondCollectionFirstCommandArguments = codeLenses[0].command?.arguments; + const secondCollectionFirstCommandArguments = + codeLenses[0].command?.arguments; assert(!!secondCollectionFirstCommandArguments); - assert(secondCollectionFirstCommandArguments[0].source === DocumentSource.DOCUMENT_SOURCE_COLLECTIONVIEW); - assert(secondCollectionFirstCommandArguments[0].namespace === firstCollectionNamespace); - assert(secondCollectionFirstCommandArguments[0].connectionId === connectionId); - assert(secondCollectionFirstCommandArguments[0].documentId === '5ea8745ee4811fafe8b65ecb'); + assert( + secondCollectionFirstCommandArguments[0].source === + DocumentSource.DOCUMENT_SOURCE_COLLECTIONVIEW + ); + assert( + secondCollectionFirstCommandArguments[0].namespace === + firstCollectionNamespace + ); + assert( + secondCollectionFirstCommandArguments[0].connectionId === connectionId + ); + assert( + secondCollectionFirstCommandArguments[0].documentId === + '5ea8745ee4811fafe8b65ecb' + ); codeLensesInfo = testCodeLensProvider._codeLensesInfo; assert(Object.keys(codeLensesInfo).length === 2); - firstCollectionCodeLensesInfo = testCodeLensProvider._codeLensesInfo[firstCollectionUri.toString()]; + firstCollectionCodeLensesInfo = + testCodeLensProvider._codeLensesInfo[firstCollectionUri.toString()]; - assert(firstCollectionCodeLensesInfo[0].documentId === '5ea8745ee4811fafe8b65ecb'); + assert( + firstCollectionCodeLensesInfo[0].documentId === '5ea8745ee4811fafe8b65ecb' + ); - const secondCollectionCodeLensesInfo = testCodeLensProvider._codeLensesInfo[secondCollectionUri.toString()]; + const secondCollectionCodeLensesInfo = + testCodeLensProvider._codeLensesInfo[secondCollectionUri.toString()]; assert(!!secondCollectionCodeLensesInfo); assert(secondCollectionCodeLensesInfo[1].documentId === '26'); @@ -433,9 +487,12 @@ suite('Collection Documents Provider Test Suite', () => { testCodeLensProvider ); - testCollectionViewProvider._operationsStore = new CollectionDocumentsOperationsStore(); + testCollectionViewProvider._operationsStore = + new CollectionDocumentsOperationsStore(); - const documents: any[] = [ { _id: '5ea8745ee4811fafe8b65ecb', location: 'alexanderplatz' } ]; + const documents: any[] = [ + { _id: '5ea8745ee4811fafe8b65ecb', location: 'alexanderplatz' }, + ]; const mockGetActiveDataService = sinon.fake.returns({ find: ( namespace: string, @@ -444,7 +501,7 @@ suite('Collection Documents Provider Test Suite', () => { callback: (error: Error | null, result: object) => void ) => { return callback(null, documents); - } + }, }); sinon.replace( testCollectionViewProvider._connectionController, @@ -453,10 +510,18 @@ suite('Collection Documents Provider Test Suite', () => { ); const mockShowMessage = sinon.fake(); - sinon.replace(testCollectionViewProvider._statusView, 'showMessage', mockShowMessage); + sinon.replace( + testCollectionViewProvider._statusView, + 'showMessage', + mockShowMessage + ); const mockHideMessage = sinon.fake(); - sinon.replace(testCollectionViewProvider._statusView, 'hideMessage', mockHideMessage); + sinon.replace( + testCollectionViewProvider._statusView, + 'hideMessage', + mockHideMessage + ); const firstConnectionId = '1c8c2b06-fbfb-40b7-bd8a-bd1f8333a487'; const secondConnectionId = '333c2b06-hhhh-40b7-bd8a-bd1f8333a896'; @@ -466,24 +531,25 @@ suite('Collection Documents Provider Test Suite', () => { id: firstConnectionId, name: 'localhost', connectionOptions: { connectionString: TEST_DATABASE_URI }, - storageLocation: StorageLocation.NONE + storageLocation: StorageLocation.NONE, }, [secondConnectionId]: { id: secondConnectionId, name: 'compass', connectionOptions: { connectionString: TEST_DATABASE_URI }, - storageLocation: StorageLocation.NONE - } + storageLocation: StorageLocation.NONE, + }, }; await mockConnectionController.connectWithConnectionId(firstConnectionId); - const firstCollectionOperationId = testCollectionViewProvider._operationsStore.createNewOperation(); + const firstCollectionOperationId = + testCollectionViewProvider._operationsStore.createNewOperation(); const firstCollectionNamespace = 'berlin.places'; const firstCollectionQuery = [ `namespace=${firstCollectionNamespace}`, `connectionId=${firstConnectionId}`, - `operationId=${firstCollectionOperationId}` + `operationId=${firstCollectionOperationId}`, ].join('&'); const firstCollectionUri = vscode.Uri.parse( `${VIEW_COLLECTION_SCHEME}:Results: ${firstCollectionNamespace}.json?${firstCollectionQuery}` @@ -491,9 +557,15 @@ suite('Collection Documents Provider Test Suite', () => { const activeTextEditor = mockTextEditor; activeTextEditor.document.uri = firstCollectionUri; - sandbox.replaceGetter(vscode.window, 'activeTextEditor', () => activeTextEditor); + sandbox.replaceGetter( + vscode.window, + 'activeTextEditor', + () => activeTextEditor + ); - await testCollectionViewProvider.provideTextDocumentContent(firstCollectionUri); + await testCollectionViewProvider.provideTextDocumentContent( + firstCollectionUri + ); let codeLenses = testCodeLensProvider.provideCodeLenses(); @@ -509,32 +581,48 @@ suite('Collection Documents Provider Test Suite', () => { ); assert(codeLenses[0].command?.title === 'Edit Document'); - const firstCollectionFirstCommandArguments = codeLenses[0].command?.arguments; + const firstCollectionFirstCommandArguments = + codeLenses[0].command?.arguments; assert(!!firstCollectionFirstCommandArguments); - assert(firstCollectionFirstCommandArguments[0].source === DocumentSource.DOCUMENT_SOURCE_COLLECTIONVIEW); - assert(firstCollectionFirstCommandArguments[0].namespace === firstCollectionNamespace); - assert(firstCollectionFirstCommandArguments[0].connectionId === firstConnectionId); - assert(firstCollectionFirstCommandArguments[0].documentId === '5ea8745ee4811fafe8b65ecb'); + assert( + firstCollectionFirstCommandArguments[0].source === + DocumentSource.DOCUMENT_SOURCE_COLLECTIONVIEW + ); + assert( + firstCollectionFirstCommandArguments[0].namespace === + firstCollectionNamespace + ); + assert( + firstCollectionFirstCommandArguments[0].connectionId === firstConnectionId + ); + assert( + firstCollectionFirstCommandArguments[0].documentId === + '5ea8745ee4811fafe8b65ecb' + ); let codeLensesInfo = testCodeLensProvider._codeLensesInfo; assert(Object.keys(codeLensesInfo).length === 1); - let firstCollectionCodeLensesInfo = testCodeLensProvider._codeLensesInfo[firstCollectionUri.toString()]; + let firstCollectionCodeLensesInfo = + testCodeLensProvider._codeLensesInfo[firstCollectionUri.toString()]; assert(!!firstCollectionCodeLensesInfo); - assert(firstCollectionCodeLensesInfo[0].documentId === '5ea8745ee4811fafe8b65ecb'); + assert( + firstCollectionCodeLensesInfo[0].documentId === '5ea8745ee4811fafe8b65ecb' + ); // Connect to another connection. await mockConnectionController.connectWithConnectionId(secondConnectionId); - const secondCollectionOperationId = testCollectionViewProvider._operationsStore.createNewOperation(); + const secondCollectionOperationId = + testCollectionViewProvider._operationsStore.createNewOperation(); const secondCollectionNamespace = 'berlin.places'; const secondCollectionQuery = [ `namespace=${secondCollectionNamespace}`, `connectionId=${secondConnectionId}`, - `operationId=${secondCollectionOperationId}` + `operationId=${secondCollectionOperationId}`, ].join('&'); const secondCollectionUri = vscode.Uri.parse( `${VIEW_COLLECTION_SCHEME}:Results: ${secondCollectionNamespace}.json?${secondCollectionQuery}` @@ -549,7 +637,9 @@ suite('Collection Documents Provider Test Suite', () => { { _id: '5678', location: 'bergmannstrasse', district: 'kreuzberg' } ); - await testCollectionViewProvider.provideTextDocumentContent(secondCollectionUri); + await testCollectionViewProvider.provideTextDocumentContent( + secondCollectionUri + ); codeLenses = testCodeLensProvider.provideCodeLenses(); assert(!!codeLenses); @@ -564,12 +654,22 @@ suite('Collection Documents Provider Test Suite', () => { ); assert(codeLenses[0].command?.title === 'Edit Document'); - const secondCollectionFirstCommandArguments = codeLenses[0].command?.arguments; + const secondCollectionFirstCommandArguments = + codeLenses[0].command?.arguments; assert(!!secondCollectionFirstCommandArguments); - assert(secondCollectionFirstCommandArguments[0].source === DocumentSource.DOCUMENT_SOURCE_COLLECTIONVIEW); - assert(secondCollectionFirstCommandArguments[0].namespace === secondCollectionNamespace); - assert(secondCollectionFirstCommandArguments[0].connectionId === secondConnectionId); + assert( + secondCollectionFirstCommandArguments[0].source === + DocumentSource.DOCUMENT_SOURCE_COLLECTIONVIEW + ); + assert( + secondCollectionFirstCommandArguments[0].namespace === + secondCollectionNamespace + ); + assert( + secondCollectionFirstCommandArguments[0].connectionId === + secondConnectionId + ); assert(secondCollectionFirstCommandArguments[0].documentId === '1234'); const secondCodeLensRange = codeLenses[1].range; @@ -581,7 +681,8 @@ suite('Collection Documents Provider Test Suite', () => { ); assert(codeLenses[0].command?.title === 'Edit Document'); - const secondCollectionSecondCommandArguments = codeLenses[1].command?.arguments; + const secondCollectionSecondCommandArguments = + codeLenses[1].command?.arguments; assert(!!secondCollectionSecondCommandArguments); assert(secondCollectionSecondCommandArguments[0].documentId === '5678'); @@ -590,11 +691,15 @@ suite('Collection Documents Provider Test Suite', () => { assert(Object.keys(codeLensesInfo).length === 2); - firstCollectionCodeLensesInfo = testCodeLensProvider._codeLensesInfo[firstCollectionUri.toString()]; + firstCollectionCodeLensesInfo = + testCodeLensProvider._codeLensesInfo[firstCollectionUri.toString()]; - assert(firstCollectionCodeLensesInfo[0].documentId === '5ea8745ee4811fafe8b65ecb'); + assert( + firstCollectionCodeLensesInfo[0].documentId === '5ea8745ee4811fafe8b65ecb' + ); - const secondCollectionCodeLensesInfo = testCodeLensProvider._codeLensesInfo[secondCollectionUri.toString()]; + const secondCollectionCodeLensesInfo = + testCodeLensProvider._codeLensesInfo[secondCollectionUri.toString()]; assert(!!secondCollectionCodeLensesInfo); assert(secondCollectionCodeLensesInfo[0].documentId === '1234'); diff --git a/src/test/suite/editors/documentStringFixtures.ts b/src/test/suite/editors/documentStringFixtures.ts index de3ff743..cc8a98bc 100644 --- a/src/test/suite/editors/documentStringFixtures.ts +++ b/src/test/suite/editors/documentStringFixtures.ts @@ -58,7 +58,7 @@ export const documentWithAllBsonTypesJsonified = `{ }`; export const documentWithBinaryId = { - _id: new Binary('a+b') + _id: new Binary('a+b'), }; export const documentWithBinaryIdString = JSON.stringify( documentWithBinaryId, diff --git a/src/test/suite/editors/editDocumentCodeLensProvider.test.ts b/src/test/suite/editors/editDocumentCodeLensProvider.test.ts index 9d12b721..76cfca94 100644 --- a/src/test/suite/editors/editDocumentCodeLensProvider.test.ts +++ b/src/test/suite/editors/editDocumentCodeLensProvider.test.ts @@ -50,12 +50,14 @@ suite('Edit Document Code Lens Provider Test Suite', () => { ); const ejsinId = { $oid: '5d973ae744376d2aae72a160' }; const playgroundResult = { - content: [{ - _id: ejsinId, - name: 'test name' - }], + content: [ + { + _id: ejsinId, + name: 'test name', + }, + ], namespace: 'db.coll', - source: DocumentSource.DOCUMENT_SOURCE_PLAYGROUND + source: DocumentSource.DOCUMENT_SOURCE_PLAYGROUND, }; const mockActiveConnectionId = sinon.fake.returns('tasty_sandwhich'); @@ -65,7 +67,8 @@ suite('Edit Document Code Lens Provider Test Suite', () => { mockActiveConnectionId ); - const result = testCodeLensProvider._updateCodeLensesForCursor(playgroundResult); + const result = + testCodeLensProvider._updateCodeLensesForCursor(playgroundResult); assert(!!result); const codeLensesInfo = result[0]; @@ -85,10 +88,10 @@ suite('Edit Document Code Lens Provider Test Suite', () => { const playgroundResult = { content: { _id: ejsinId, - name: 'test name' + name: 'test name', }, namespace: 'db.coll', - source: DocumentSource.DOCUMENT_SOURCE_PLAYGROUND + source: DocumentSource.DOCUMENT_SOURCE_PLAYGROUND, }; const mockActiveConnectionId = sinon.fake.returns('tasty_sandwhich'); @@ -98,7 +101,8 @@ suite('Edit Document Code Lens Provider Test Suite', () => { mockActiveConnectionId ); - const result = testCodeLensProvider._updateCodeLensesForDocument(playgroundResult); + const result = + testCodeLensProvider._updateCodeLensesForDocument(playgroundResult); assert(!!result); const codeLensesInfo = result[0]; @@ -117,14 +121,20 @@ suite('Edit Document Code Lens Provider Test Suite', () => { ); const activeTextEditor = mockTextEditor; - mockTextEditor.document.uri = vscode.Uri.parse('PLAYGROUND_RESULT_SCHEME:/Playground Result'); - sandbox.replaceGetter(vscode.window, 'activeTextEditor', () => activeTextEditor); + mockTextEditor.document.uri = vscode.Uri.parse( + 'PLAYGROUND_RESULT_SCHEME:/Playground Result' + ); + sandbox.replaceGetter( + vscode.window, + 'activeTextEditor', + () => activeTextEditor + ); testCodeLensProvider.updateCodeLensesForPlayground({ namespace: 'db.coll', type: 'Document', content: { _id: '93333a0d-83f6-4e6f-a575-af7ea6187a4a' }, - language: 'json' + language: 'json', }); const codeLens = testCodeLensProvider.provideCodeLenses(); @@ -144,7 +154,9 @@ suite('Edit Document Code Lens Provider Test Suite', () => { ); assert(codeLens[0].command?.title === 'Edit Document'); assert(!!codeLens[0].command?.command); - assert(codeLens[0].command?.command === 'mdb.openMongoDBDocumentFromCodeLens'); + assert( + codeLens[0].command?.command === 'mdb.openMongoDBDocumentFromCodeLens' + ); const commandArguments = codeLens[0].command?.arguments; assert(!!commandArguments); assert(commandArguments[0].source === 'playground'); @@ -156,17 +168,23 @@ suite('Edit Document Code Lens Provider Test Suite', () => { ); const activeTextEditor = mockTextEditor; - activeTextEditor.document.uri = vscode.Uri.parse('PLAYGROUND_RESULT_SCHEME:/Playground Result'); - sandbox.replaceGetter(vscode.window, 'activeTextEditor', () => activeTextEditor); + activeTextEditor.document.uri = vscode.Uri.parse( + 'PLAYGROUND_RESULT_SCHEME:/Playground Result' + ); + sandbox.replaceGetter( + vscode.window, + 'activeTextEditor', + () => activeTextEditor + ); testCodeLensProvider.updateCodeLensesForPlayground({ namespace: 'db.coll', type: 'Cursor', content: [ { _id: '93333a0d-83f6-4e6f-a575-af7ea6187a4a' }, - { _id: '21333a0d-83f6-4e6f-a575-af7ea6187444' } + { _id: '21333a0d-83f6-4e6f-a575-af7ea6187444' }, ], - language: 'json' + language: 'json', }); const codeLens = testCodeLensProvider.provideCodeLenses(); @@ -203,8 +221,14 @@ suite('Edit Document Code Lens Provider Test Suite', () => { ); const activeTextEditor = mockTextEditor; - activeTextEditor.document.uri = vscode.Uri.parse('PLAYGROUND_RESULT_SCHEME:/Playground Result'); - sandbox.replaceGetter(vscode.window, 'activeTextEditor', () => activeTextEditor); + activeTextEditor.document.uri = vscode.Uri.parse( + 'PLAYGROUND_RESULT_SCHEME:/Playground Result' + ); + sandbox.replaceGetter( + vscode.window, + 'activeTextEditor', + () => activeTextEditor + ); testCodeLensProvider.updateCodeLensesForPlayground({ namespace: 'db.coll', @@ -216,8 +240,8 @@ suite('Edit Document Code Lens Provider Test Suite', () => { price: 5, quantity: 20, date: { - $date: '2014-04-04T11:21:39.736Z' - } + $date: '2014-04-04T11:21:39.736Z', + }, }, { _id: 5, @@ -225,11 +249,11 @@ suite('Edit Document Code Lens Provider Test Suite', () => { price: 10, quantity: 10, date: { - $date: '2014-04-04T21:23:13.331Z' - } - } + $date: '2014-04-04T21:23:13.331Z', + }, + }, ], - language: 'json' + language: 'json', }); const codeLens = testCodeLensProvider.provideCodeLenses(); diff --git a/src/test/suite/editors/editorsController.test.ts b/src/test/suite/editors/editorsController.test.ts index 1f5ee2d3..3ba37b89 100644 --- a/src/test/suite/editors/editorsController.test.ts +++ b/src/test/suite/editors/editorsController.test.ts @@ -8,7 +8,7 @@ import { ObjectId } from 'bson'; import { getFileDisplayNameForDocument, - getViewCollectionDocumentsUri + getViewCollectionDocumentsUri, } from '../../../editors/editorsController'; const expect = chai.expect; @@ -25,24 +25,28 @@ suite('Editors Controller Test Suite', () => { test('it strips special characters from the document id', () => { const str = 'abc//\\\nab c"$%%..@1s df""'; const result = getFileDisplayNameForDocument(str, 'a.b'); - const expected = 'a.b:"abc%2f%2f%5c%5c%5cnab c%5c"$%25%25..@1s df%5c"%5c""'; + const expected = + 'a.b:"abc%2f%2f%5c%5c%5cnab c%5c"$%25%25..@1s df%5c"%5c""'; assert.strictEqual(result, expected); }); test('it trims the string to 200 characters', () => { - const str = '123sdfhadfbnjiekbfdakjsdbfkjsabdfkjasbdfkjsvasdjvbskdafdf123sdfhadfbnjiekbfdakjsdbfkjsabdfkjasbdfkjsvasdjvbskdafdffbnjiekbfdakjsdbfkjsabdfkjasbfbnjiekbfdakjsdbfkjsabdfkjasbkjasbfbnjiekbfdakjsdbfkjsabdfkjasb'; + const str = + '123sdfhadfbnjiekbfdakjsdbfkjsabdfkjasbdfkjsvasdjvbskdafdf123sdfhadfbnjiekbfdakjsdbfkjsabdfkjasbdfkjsvasdjvbskdafdffbnjiekbfdakjsdbfkjsabdfkjasbfbnjiekbfdakjsdbfkjsabdfkjasbkjasbfbnjiekbfdakjsdbfkjsabdfkjasb'; const result = getFileDisplayNameForDocument(str, 'db.col'); - const expected = 'db.col:"123sdfhadfbnjiekbfdakjsdbfkjsabdfkjasbdfkjsvasdjvbskdafdf123sdfhadfbnjiekbfdakjsdbfkjsabdfkjasbdfkjsvasdjvbskdafdffbnjiekbfdakjsdbfkjsabdfkjasbfbnjiekbfdakjsdbfkjsabdfkjasbkjasbfbnjiekbfdakjsd'; + const expected = + 'db.col:"123sdfhadfbnjiekbfdakjsdbfkjsabdfkjasbdfkjsvasdjvbskdafdf123sdfhadfbnjiekbfdakjsdbfkjsabdfkjasbdfkjsvasdjvbskdafdffbnjiekbfdakjsdbfkjsabdfkjasbfbnjiekbfdakjsdbfkjsabdfkjasbkjasbfbnjiekbfdakjsd'; assert.strictEqual(result, expected); }); test('it handles ids that are objects', () => { const str = { str: 'abc//\\\nab c$%%..@1s df"', - b: new ObjectId('5d973ae744376d2aae72a160') + b: new ObjectId('5d973ae744376d2aae72a160'), }; const result = getFileDisplayNameForDocument(str, 'db.col'); - const expected = 'db.col:{"str":"abc%2f%2f%5c%5c%5cnab c$%25%25..@1s df%5c"","b":{"$oid":"5d973ae744376d2aae72a160"}}'; + const expected = + 'db.col:{"str":"abc%2f%2f%5c%5c%5cnab c$%25%25..@1s df%5c"","b":{"$oid":"5d973ae744376d2aae72a160"}}'; assert.strictEqual(result, expected); }); @@ -68,7 +72,7 @@ suite('Editors Controller Test Suite', () => { assert.strictEqual(testUri.scheme, 'VIEW_COLLECTION_SCHEME'); assert.strictEqual( testUri.query, - 'namespace=myFavoriteNamespace&connectionId=alienSateliteConnection&operationId=100011011101110011', + 'namespace=myFavoriteNamespace&connectionId=alienSateliteConnection&operationId=100011011101110011' ); }); @@ -82,11 +86,14 @@ suite('Editors Controller Test Suite', () => { testConnectionId ); - assert.strictEqual(testUri.path, 'Results: myFa%25%25%5c%5c%2f%2f%2f%5c%25vorite%25Namespace.json'); + assert.strictEqual( + testUri.path, + 'Results: myFa%25%25%5c%5c%2f%2f%2f%5c%25vorite%25Namespace.json' + ); assert.strictEqual(testUri.scheme, 'VIEW_COLLECTION_SCHEME'); assert.strictEqual( testUri.query, - 'namespace=myFa%%\\\\///\\%vorite%Namespace&connectionId=alienSateliteConnection&operationId=100011011101110011', + 'namespace=myFa%%\\\\///\\%vorite%Namespace&connectionId=alienSateliteConnection&operationId=100011011101110011' ); }); @@ -106,15 +113,21 @@ suite('Editors Controller Test Suite', () => { test('saveMongoDBDocument returns false if this is not a mongodb document', async () => { const activeTextEditor = mockTextEditor; - activeTextEditor.document.uri = vscode.Uri.parse([ - 'file:/', - 'waffle.house:pancakes.json?', - 'namespace=waffle.house&', - 'connectionId=tasty_sandwhich&', - 'documentId=93333a0d-83f6-4e6f-a575-af7ea6187a4a&', - 'source=treeview' - ].join('')); - sandbox.replaceGetter(vscode.window, 'activeTextEditor', () => activeTextEditor); + activeTextEditor.document.uri = vscode.Uri.parse( + [ + 'file:/', + 'waffle.house:pancakes.json?', + 'namespace=waffle.house&', + 'connectionId=tasty_sandwhich&', + 'documentId=93333a0d-83f6-4e6f-a575-af7ea6187a4a&', + 'source=treeview', + ].join('') + ); + sandbox.replaceGetter( + vscode.window, + 'activeTextEditor', + () => activeTextEditor + ); const result = await vscode.commands.executeCommand( 'mdb.saveMongoDBDocument' @@ -125,14 +138,20 @@ suite('Editors Controller Test Suite', () => { test('saveMongoDBDocument returns false if this is not a mongodb document and namespace is missing', async () => { const activeTextEditor = mockTextEditor; - activeTextEditor.document.uri = vscode.Uri.parse([ - 'VIEW_DOCUMENT_SCHEME:/', - 'waffle.house:pancakes.json?', - 'connectionId=tasty_sandwhich&', - 'documentId=93333a0d-83f6-4e6f-a575-af7ea6187a4a&', - 'source=treeview' - ].join('')); - sandbox.replaceGetter(vscode.window, 'activeTextEditor', () => activeTextEditor); + activeTextEditor.document.uri = vscode.Uri.parse( + [ + 'VIEW_DOCUMENT_SCHEME:/', + 'waffle.house:pancakes.json?', + 'connectionId=tasty_sandwhich&', + 'documentId=93333a0d-83f6-4e6f-a575-af7ea6187a4a&', + 'source=treeview', + ].join('') + ); + sandbox.replaceGetter( + vscode.window, + 'activeTextEditor', + () => activeTextEditor + ); const result = await vscode.commands.executeCommand( 'mdb.saveMongoDBDocument' @@ -143,14 +162,20 @@ suite('Editors Controller Test Suite', () => { test('saveMongoDBDocument returns false if this is not a mongodb document and connectionId is missing', async () => { const activeTextEditor = mockTextEditor; - activeTextEditor.document.uri = vscode.Uri.parse([ - 'VIEW_DOCUMENT_SCHEME:/', - 'waffle.house:pancakes.json?', - 'namespace=waffle.house&', - 'documentId=93333a0d-83f6-4e6f-a575-af7ea6187a4a&', - 'source=treeview' - ].join('')); - sandbox.replaceGetter(vscode.window, 'activeTextEditor', () => activeTextEditor); + activeTextEditor.document.uri = vscode.Uri.parse( + [ + 'VIEW_DOCUMENT_SCHEME:/', + 'waffle.house:pancakes.json?', + 'namespace=waffle.house&', + 'documentId=93333a0d-83f6-4e6f-a575-af7ea6187a4a&', + 'source=treeview', + ].join('') + ); + sandbox.replaceGetter( + vscode.window, + 'activeTextEditor', + () => activeTextEditor + ); const result = await vscode.commands.executeCommand( 'mdb.saveMongoDBDocument' @@ -161,14 +186,20 @@ suite('Editors Controller Test Suite', () => { test('saveMongoDBDocument returns false if this is not a mongodb document and documentId is missing', async () => { const activeTextEditor = mockTextEditor; - activeTextEditor.document.uri = vscode.Uri.parse([ - 'VIEW_DOCUMENT_SCHEME:/', - 'waffle.house:pancakes.json?', - 'namespace=waffle.house&', - 'connectionId=tasty_sandwhich&', - 'source=treeview' - ].join('')); - sandbox.replaceGetter(vscode.window, 'activeTextEditor', () => activeTextEditor); + activeTextEditor.document.uri = vscode.Uri.parse( + [ + 'VIEW_DOCUMENT_SCHEME:/', + 'waffle.house:pancakes.json?', + 'namespace=waffle.house&', + 'connectionId=tasty_sandwhich&', + 'source=treeview', + ].join('') + ); + sandbox.replaceGetter( + vscode.window, + 'activeTextEditor', + () => activeTextEditor + ); const result = await vscode.commands.executeCommand( 'mdb.saveMongoDBDocument' @@ -179,16 +210,22 @@ suite('Editors Controller Test Suite', () => { test('saveMongoDBDocument returns false if a user saves an invalid javascript value', async () => { const activeTextEditor = mockTextEditor; - activeTextEditor.document.uri = vscode.Uri.parse([ - 'VIEW_DOCUMENT_SCHEME:/', - 'waffle.house:pancakes.json?', - 'namespace=waffle.house&', - 'connectionId=tasty_sandwhich&', - 'documentId=93333a0d-83f6-4e6f-a575-af7ea6187a4a&', - 'source=treeview' - ].join('')); + activeTextEditor.document.uri = vscode.Uri.parse( + [ + 'VIEW_DOCUMENT_SCHEME:/', + 'waffle.house:pancakes.json?', + 'namespace=waffle.house&', + 'connectionId=tasty_sandwhich&', + 'documentId=93333a0d-83f6-4e6f-a575-af7ea6187a4a&', + 'source=treeview', + ].join('') + ); activeTextEditor.document.getText = () => '{'; - sandbox.replaceGetter(vscode.window, 'activeTextEditor', () => activeTextEditor); + sandbox.replaceGetter( + vscode.window, + 'activeTextEditor', + () => activeTextEditor + ); const result = await vscode.commands.executeCommand( 'mdb.saveMongoDBDocument' diff --git a/src/test/suite/editors/exportToLanguageCodeLensProvider.test.ts b/src/test/suite/editors/exportToLanguageCodeLensProvider.test.ts index 20291245..3936c901 100644 --- a/src/test/suite/editors/exportToLanguageCodeLensProvider.test.ts +++ b/src/test/suite/editors/exportToLanguageCodeLensProvider.test.ts @@ -11,12 +11,13 @@ suite('Export To Language Code Lens Provider Test Suite', function () { importStatements: false, driverSyntax: false, builders: false, - language: 'shell' + language: 'shell', }; let testExportToLanguageCodeLensProvider: ExportToLanguageCodeLensProvider; beforeEach(() => { - testExportToLanguageCodeLensProvider = new ExportToLanguageCodeLensProvider(); + testExportToLanguageCodeLensProvider = + new ExportToLanguageCodeLensProvider(); }); test('has the include import statements code lens when importStatements is false', () => { @@ -25,16 +26,23 @@ suite('Export To Language Code Lens Provider Test Suite', function () { const codeLenses = testExportToLanguageCodeLensProvider.provideCodeLenses(); expect(codeLenses.length).to.be.equal(2); - expect(codeLenses[0].command?.title).to.be.equal('Include Import Statements'); + expect(codeLenses[0].command?.title).to.be.equal( + 'Include Import Statements' + ); }); test('has the exclude import statements code lens when importStatements is true', () => { - testExportToLanguageCodeLensProvider.refresh({ ...defaults, importStatements: true }); + testExportToLanguageCodeLensProvider.refresh({ + ...defaults, + importStatements: true, + }); const codeLenses = testExportToLanguageCodeLensProvider.provideCodeLenses(); expect(codeLenses.length).to.be.equal(2); - expect(codeLenses[0].command?.title).to.be.equal('Exclude Import Statements'); + expect(codeLenses[0].command?.title).to.be.equal( + 'Exclude Import Statements' + ); }); test('has the include import statements code lens when driverSyntax is false', () => { @@ -47,7 +55,10 @@ suite('Export To Language Code Lens Provider Test Suite', function () { }); test('has the exclude import statements code lens when driverSyntax is true', () => { - testExportToLanguageCodeLensProvider.refresh({ ...defaults, driverSyntax: true }); + testExportToLanguageCodeLensProvider.refresh({ + ...defaults, + driverSyntax: true, + }); const codeLenses = testExportToLanguageCodeLensProvider.provideCodeLenses(); @@ -56,7 +67,11 @@ suite('Export To Language Code Lens Provider Test Suite', function () { }); test('has the use builders code lens when builders is false, language is java, and mode is query', () => { - testExportToLanguageCodeLensProvider.refresh({ ...defaults, mode: ExportToLanguageMode.QUERY, language: 'java' }); + testExportToLanguageCodeLensProvider.refresh({ + ...defaults, + mode: ExportToLanguageMode.QUERY, + language: 'java', + }); const codeLenses = testExportToLanguageCodeLensProvider.provideCodeLenses(); @@ -65,16 +80,27 @@ suite('Export To Language Code Lens Provider Test Suite', function () { }); test('does not have the include driver syntax code lens when language is csharp', () => { - testExportToLanguageCodeLensProvider.refresh({ ...defaults, mode: ExportToLanguageMode.QUERY, language: 'csharp' }); + testExportToLanguageCodeLensProvider.refresh({ + ...defaults, + mode: ExportToLanguageMode.QUERY, + language: 'csharp', + }); const codeLenses = testExportToLanguageCodeLensProvider.provideCodeLenses(); expect(codeLenses.length).to.be.equal(1); // Csharp does not support driver syntax. - expect(codeLenses[0].command?.title).to.be.equal('Include Import Statements'); + expect(codeLenses[0].command?.title).to.be.equal( + 'Include Import Statements' + ); }); test('has the use raw query code lens when builders is true, language is java, and mode is query', () => { - testExportToLanguageCodeLensProvider.refresh({ ...defaults, builders: true, mode: ExportToLanguageMode.QUERY, language: 'java' }); + testExportToLanguageCodeLensProvider.refresh({ + ...defaults, + builders: true, + mode: ExportToLanguageMode.QUERY, + language: 'java', + }); const codeLenses = testExportToLanguageCodeLensProvider.provideCodeLenses(); @@ -83,7 +109,12 @@ suite('Export To Language Code Lens Provider Test Suite', function () { }); test('does not have the use raw query code lens when builders is true, language is java, and mode is plain text', () => { - testExportToLanguageCodeLensProvider.refresh({ ...defaults, builders: true, mode: ExportToLanguageMode.OTHER, language: 'java' }); + testExportToLanguageCodeLensProvider.refresh({ + ...defaults, + builders: true, + mode: ExportToLanguageMode.OTHER, + language: 'java', + }); const codeLenses = testExportToLanguageCodeLensProvider.provideCodeLenses(); diff --git a/src/test/suite/editors/mongoDBDocumentService.test.ts b/src/test/suite/editors/mongoDBDocumentService.test.ts index 4c6eba3f..7926b240 100644 --- a/src/test/suite/editors/mongoDBDocumentService.test.ts +++ b/src/test/suite/editors/mongoDBDocumentService.test.ts @@ -73,7 +73,7 @@ suite('MongoDB Document Service Test Suite', () => { document.price = 5000; return callback(null, document); - } + }, }); sinon.replace( testConnectionController, @@ -92,7 +92,7 @@ suite('MongoDB Document Service Test Suite', () => { documentId, connectionId, newDocument, - source + source, }); expect(document).to.be.deep.equal(newDocument); @@ -114,7 +114,7 @@ suite('MongoDB Document Service Test Suite', () => { callback: (error: Error | null, result: object) => void ) => { return callback(null, [{ _id: '123' }]); - } + }, }); sinon.replace( testConnectionController, @@ -140,7 +140,7 @@ suite('MongoDB Document Service Test Suite', () => { documentId, line, connectionId, - source + source, }); expect(result).to.be.deep.equal(JSON.parse(EJSON.stringify(documents[0]))); @@ -176,7 +176,7 @@ suite('MongoDB Document Service Test Suite', () => { namespace, connectionId, newDocument, - source + source, }); } catch (error) { const expectedMessage = @@ -216,7 +216,7 @@ suite('MongoDB Document Service Test Suite', () => { namespace, connectionId, newDocument, - source + source, }); } catch (error) { const expectedMessage = @@ -259,7 +259,7 @@ suite('MongoDB Document Service Test Suite', () => { documentId, line, connectionId, - source + source, }); } catch (error) { const expectedMessage = diff --git a/src/test/suite/editors/playgroundController.test.ts b/src/test/suite/editors/playgroundController.test.ts index 87fe787d..2b5b5c7e 100644 --- a/src/test/suite/editors/playgroundController.test.ts +++ b/src/test/suite/editors/playgroundController.test.ts @@ -56,7 +56,8 @@ suite('Playground Controller Test Suite', function () { const testActiveDBCodeLensProvider = new ActiveDBCodeLensProvider( testConnectionController ); - const testExportToLanguageCodeLensProvider = new ExportToLanguageCodeLensProvider(); + const testExportToLanguageCodeLensProvider = + new ExportToLanguageCodeLensProvider(); const testCodeActionProvider = new CodeActionProvider(); const testExplorerController = new ExplorerController( testConnectionController @@ -95,8 +96,8 @@ suite('Playground Controller Test Suite', function () { const mockActiveDataService = { getMongoClientConnectionOptions: () => ({ url: 'mongodb://username@ldaphost:27017/?authMechanism=MONGODB-X509&readPreference=primary&appname=mongodb-vscode+0.0.0-dev.0&ssl=true&authSource=%24external&tlsAllowInvalidCertificates=true&tlsAllowInvalidHostnames=true&tlsCAFile=./path/to/ca&tlsCertificateKeyFile=./path/to/cert', - options: { monitorCommands: true } - }) + options: { monitorCommands: true }, + }), } as DataService; const mockGetActiveConnectionId = sinon.fake.returns('pineapple'); mockConnectToServiceProvider = sinon.fake.resolves(undefined); @@ -122,28 +123,36 @@ suite('Playground Controller Test Suite', function () { mockConnectToServiceProvider ); - testPlaygroundController._connectionController.setActiveDataService(mockActiveDataService); + testPlaygroundController._connectionController.setActiveDataService( + mockActiveDataService + ); await testPlaygroundController._connectToServiceProvider(); }); test('it should pass the active connection id to the language server for connecting', () => { expect( - (mockConnectToServiceProvider.firstCall.firstArg as { - connectionId: string; - }).connectionId + ( + mockConnectToServiceProvider.firstCall.firstArg as { + connectionId: string; + } + ).connectionId ).to.equal('pineapple'); }); test('it should pass ssl strings to the language server for connecting', () => { expect( - (mockConnectToServiceProvider.firstCall.firstArg as { - connectionString: string - }).connectionString + ( + mockConnectToServiceProvider.firstCall.firstArg as { + connectionString: string; + } + ).connectionString ).includes('./path/to/cert'); expect( - (mockConnectToServiceProvider.firstCall.firstArg as { - connectionString: string - }).connectionString + ( + mockConnectToServiceProvider.firstCall.firstArg as { + connectionString: string; + } + ).connectionString ).includes('./path/to/ca'); }); }); @@ -152,13 +161,10 @@ suite('Playground Controller Test Suite', function () { testPlaygroundController._activeTextEditor = undefined; test('run all playground blocks should throw the playground not found error', async () => { - const expectedMessage = "Please open a '.mongodb' playground file before running it."; + const expectedMessage = + "Please open a '.mongodb' playground file before running it."; const fakeShowErrorMessage: any = sinon.fake(); - sinon.replace( - vscode.window, - 'showErrorMessage', - fakeShowErrorMessage - ); + sinon.replace(vscode.window, 'showErrorMessage', fakeShowErrorMessage); try { await testPlaygroundController.runAllPlaygroundBlocks(); @@ -168,13 +174,10 @@ suite('Playground Controller Test Suite', function () { }); test('run selected playground blocks should throw the playground not found error', async () => { - const expectedMessage = "Please open a '.mongodb' playground file before running it."; + const expectedMessage = + "Please open a '.mongodb' playground file before running it."; const fakeShowErrorMessage: any = sinon.fake(); - sinon.replace( - vscode.window, - 'showErrorMessage', - fakeShowErrorMessage - ); + sinon.replace(vscode.window, 'showErrorMessage', fakeShowErrorMessage); try { await testPlaygroundController.runSelectedPlaygroundBlocks(); @@ -184,13 +187,10 @@ suite('Playground Controller Test Suite', function () { }); test('run all or selected playground blocks should throw the playground not found error', async () => { - const expectedMessage = "Please open a '.mongodb' playground file before running it."; + const expectedMessage = + "Please open a '.mongodb' playground file before running it."; const fakeShowErrorMessage: any = sinon.fake(); - sinon.replace( - vscode.window, - 'showErrorMessage', - fakeShowErrorMessage - ); + sinon.replace(vscode.window, 'showErrorMessage', fakeShowErrorMessage); try { await testPlaygroundController.runAllOrSelectedPlaygroundBlocks(); @@ -205,21 +205,22 @@ suite('Playground Controller Test Suite', function () { document: { languageId: 'mongodb', uri: { - path: 'test' + path: 'test', }, getText: () => "use('dbName');", - lineAt: sinon.fake.returns({ text: "use('dbName');" }) + lineAt: sinon.fake.returns({ text: "use('dbName');" }), }, selections: [ new vscode.Selection( new vscode.Position(0, 0), new vscode.Position(0, 0) - ) - ] + ), + ], }; beforeEach(() => { - testPlaygroundController._activeTextEditor = activeTestEditorMock as vscode.TextEditor; + testPlaygroundController._activeTextEditor = + activeTestEditorMock as vscode.TextEditor; }); suite('user is not connected', () => { @@ -234,13 +235,10 @@ suite('Playground Controller Test Suite', function () { }); test('run all playground blocks should throw the error', async () => { - const expectedMessage = 'Please connect to a database before running a playground.'; + const expectedMessage = + 'Please connect to a database before running a playground.'; const fakeShowErrorMessage: any = sinon.fake(); - sinon.replace( - vscode.window, - 'showErrorMessage', - fakeShowErrorMessage - ); + sinon.replace(vscode.window, 'showErrorMessage', fakeShowErrorMessage); try { await testPlaygroundController.runAllPlaygroundBlocks(); @@ -250,13 +248,10 @@ suite('Playground Controller Test Suite', function () { }); test('run selected playground blocks should throw the error', async () => { - const expectedMessage = 'Please connect to a database before running a playground.'; + const expectedMessage = + 'Please connect to a database before running a playground.'; const fakeShowErrorMessage: any = sinon.fake(); - sinon.replace( - vscode.window, - 'showErrorMessage', - fakeShowErrorMessage - ); + sinon.replace(vscode.window, 'showErrorMessage', fakeShowErrorMessage); try { await testPlaygroundController.runSelectedPlaygroundBlocks(); @@ -266,13 +261,10 @@ suite('Playground Controller Test Suite', function () { }); test('run all or selected playground blocks should throw the error', async () => { - const expectedMessage = 'Please connect to a database before running a playground.'; + const expectedMessage = + 'Please connect to a database before running a playground.'; const fakeShowErrorMessage: any = sinon.fake(); - sinon.replace( - vscode.window, - 'showErrorMessage', - fakeShowErrorMessage - ); + sinon.replace(vscode.window, 'showErrorMessage', fakeShowErrorMessage); try { await testPlaygroundController.runAllOrSelectedPlaygroundBlocks(); @@ -288,8 +280,8 @@ suite('Playground Controller Test Suite', function () { const mockGetActiveDataService = sinon.fake.returns({ getMongoClientConnectionOptions: () => ({ url: TEST_DATABASE_URI, - options: {} - }) + options: {}, + }), }); const mockGetActiveConnectionId = sinon.fake.returns('pineapple'); @@ -335,7 +327,7 @@ suite('Playground Controller Test Suite', function () { const mockEvaluateWithCancelModal = sinon.fake.resolves({ outputLines: [], - result: '123' + result: '123', }); sinon.replace( testPlaygroundController, @@ -365,7 +357,7 @@ suite('Playground Controller Test Suite', function () { const mockEvaluateWithCancelModal = sinon.fake.resolves({ outputLines: [], - result: '123' + result: '123', }); sinon.replace( testPlaygroundController, @@ -405,11 +397,12 @@ suite('Playground Controller Test Suite', function () { sinon.fake.rejects(false) ); - const result = await testPlaygroundController._evaluateWithCancelModal(); + const result = + await testPlaygroundController._evaluateWithCancelModal(); expect(result).to.deep.equal({ outputLines: undefined, - result: undefined + result: undefined, }); }); @@ -458,10 +451,12 @@ suite('Playground Controller Test Suite', function () { const textFromEditor = 'var x = { name: qwerty }'; const selection = { start: { line: 0, character: 8 }, - end: { line: 0, character: 24 } + end: { line: 0, character: 24 }, } as vscode.Selection; const mode = ExportToLanguageMode.OTHER; - const activeTextEditor = { document: { getText: () => textFromEditor } } as vscode.TextEditor; + const activeTextEditor = { + document: { getText: () => textFromEditor }, + } as vscode.TextEditor; const fakeVscodeErrorMessage: any = sinon.fake(); sinon.replace( @@ -477,7 +472,8 @@ suite('Playground Controller Test Suite', function () { await playgroundControllerTest.exportToLanguage('csharp'); - const expectedMessage = 'Unable to export to csharp language: Symbol \'qwerty\' is undefined'; + const expectedMessage = + "Unable to export to csharp language: Symbol 'qwerty' is undefined"; expect(fakeVscodeErrorMessage.firstArg).to.be.equal(expectedMessage); }); }); diff --git a/src/test/suite/editors/playgroundResultProvider.test.ts b/src/test/suite/editors/playgroundResultProvider.test.ts index 85e7ae57..2ddc2615 100644 --- a/src/test/suite/editors/playgroundResultProvider.test.ts +++ b/src/test/suite/editors/playgroundResultProvider.test.ts @@ -5,7 +5,9 @@ import sinon from 'sinon'; import ConnectionController from '../../../connectionController'; import CollectionDocumentsOperationsStore from '../../../editors/collectionDocumentsOperationsStore'; -import CollectionDocumentsProvider, { VIEW_COLLECTION_SCHEME } from '../../../editors/collectionDocumentsProvider'; +import CollectionDocumentsProvider, { + VIEW_COLLECTION_SCHEME, +} from '../../../editors/collectionDocumentsProvider'; import EditDocumentCodeLensProvider from '../../../editors/editDocumentCodeLensProvider'; import PlaygroundResultProvider from '../../../editors/playgroundResultProvider'; import { StatusView } from '../../../views'; @@ -49,7 +51,7 @@ suite('Playground Result Provider Test Suite', () => { namespace: null, type: null, content: undefined, - language: null + language: null, } ); }); @@ -64,9 +66,9 @@ suite('Playground Result Provider Test Suite', () => { type: 'Cursor', content: { _id: '93333a0d-83f6-4e6f-a575-af7ea6187a4a', - name: 'Berlin' + name: 'Berlin', }, - language: 'json' + language: 'json', }; testPlaygroundResultViewProvider.setPlaygroundResult(playgroundResult); @@ -86,10 +88,11 @@ suite('Playground Result Provider Test Suite', () => { namespace: 'db.berlin', type: 'undefined', content: null, - language: 'plaintext' + language: 'plaintext', }; - const result = testPlaygroundResultViewProvider.provideTextDocumentContent(); + const result = + testPlaygroundResultViewProvider.provideTextDocumentContent(); expect(result).to.be.equal('undefined'); }); @@ -104,10 +107,11 @@ suite('Playground Result Provider Test Suite', () => { namespace: 'db.berlin', type: 'object', content: null, - language: 'plaintext' + language: 'plaintext', }; - const result = testPlaygroundResultViewProvider.provideTextDocumentContent(); + const result = + testPlaygroundResultViewProvider.provideTextDocumentContent(); expect(result).to.be.equal('null'); }); @@ -122,10 +126,11 @@ suite('Playground Result Provider Test Suite', () => { namespace: 'db.berlin', type: 'number', content: 4, - language: 'plaintext' + language: 'plaintext', }; - const result = testPlaygroundResultViewProvider.provideTextDocumentContent(); + const result = + testPlaygroundResultViewProvider.provideTextDocumentContent(); expect(result).to.be.equal('4'); }); @@ -140,10 +145,11 @@ suite('Playground Result Provider Test Suite', () => { namespace: 'db.berlin', type: 'object', content: [], - language: 'json' + language: 'json', }; - const result = testPlaygroundResultViewProvider.provideTextDocumentContent(); + const result = + testPlaygroundResultViewProvider.provideTextDocumentContent(); expect(result).to.be.equal('[]'); }); @@ -158,10 +164,11 @@ suite('Playground Result Provider Test Suite', () => { namespace: 'db.berlin', type: 'object', content: {}, - language: 'json' + language: 'json', }; - const result = testPlaygroundResultViewProvider.provideTextDocumentContent(); + const result = + testPlaygroundResultViewProvider.provideTextDocumentContent(); expect(result).to.be.equal('{}'); }); @@ -176,10 +183,11 @@ suite('Playground Result Provider Test Suite', () => { namespace: 'db.berlin', type: 'boolean', content: true, - language: 'plaintext' + language: 'plaintext', }; - const result = testPlaygroundResultViewProvider.provideTextDocumentContent(); + const result = + testPlaygroundResultViewProvider.provideTextDocumentContent(); expect(result).to.be.equal('true'); }); @@ -194,10 +202,11 @@ suite('Playground Result Provider Test Suite', () => { namespace: 'db.berlin', type: 'string', content: 'Berlin', - language: 'plaintext' + language: 'plaintext', }; - const result = testPlaygroundResultViewProvider.provideTextDocumentContent(); + const result = + testPlaygroundResultViewProvider.provideTextDocumentContent(); expect(result).to.be.equal('Berlin'); }); @@ -210,18 +219,18 @@ suite('Playground Result Provider Test Suite', () => { const content = [ { _id: '93333a0d-83f6-4e6f-a575-af7ea6187a4a', - name: 'Berlin' + name: 'Berlin', }, { _id: '55333a0d-83f6-4e6f-a575-af7ea6187a55', - name: 'Rome' - } + name: 'Rome', + }, ]; const playgroundResult = { namespace: 'db.berlin', type: 'Cursor', content, - language: 'json' + language: 'json', }; const mockRefresh: any = sinon.fake(); @@ -233,7 +242,8 @@ suite('Playground Result Provider Test Suite', () => { testPlaygroundResultViewProvider._playgroundResult = playgroundResult; - const result = testPlaygroundResultViewProvider.provideTextDocumentContent(); + const result = + testPlaygroundResultViewProvider.provideTextDocumentContent(); mockRefresh.firstArg; expect(result).to.be.equal(JSON.stringify(content, null, 2)); @@ -247,13 +257,13 @@ suite('Playground Result Provider Test Suite', () => { ); const content = { _id: '20213a0d-83f6-4e6f-a575-af7ea6187lala', - name: 'Minsk' + name: 'Minsk', }; const playgroundResult = { namespace: 'db.berlin', type: 'Document', content, - language: 'json' + language: 'json', }; const mockRefresh: any = sinon.fake(); @@ -265,7 +275,8 @@ suite('Playground Result Provider Test Suite', () => { testPlaygroundResultViewProvider._playgroundResult = playgroundResult; - const result = testPlaygroundResultViewProvider.provideTextDocumentContent(); + const result = + testPlaygroundResultViewProvider.provideTextDocumentContent(); mockRefresh.firstArg; expect(result).to.be.equal(JSON.stringify(content, null, 2)); @@ -282,10 +293,22 @@ suite('Playground Result Provider Test Suite', () => { namespace: playgroundNamespace, type: 'Cursor', content: [ - { _id: 1, item: 'abc', price: 10, quantity: 2, date: new Date('2014-03-01T08:00:00Z') }, - { _id: 2, item: 'jkl', price: 20, quantity: 1, date: new Date('2014-03-01T09:00:00Z') } + { + _id: 1, + item: 'abc', + price: 10, + quantity: 2, + date: new Date('2014-03-01T08:00:00Z'), + }, + { + _id: 2, + item: 'jkl', + price: 20, + quantity: 1, + date: new Date('2014-03-01T09:00:00Z'), + }, ], - language: 'json' + language: 'json', }; const connectionId = '1c8c2b06-fbfb-40b7-bd8a-bd1f8333a487'; @@ -296,16 +319,19 @@ suite('Playground Result Provider Test Suite', () => { mockActiveConnectionId ); - const playgroundResultUri = vscode.Uri.parse('PLAYGROUND_RESULT_SCHEME:/Playground Result'); + const playgroundResultUri = vscode.Uri.parse( + 'PLAYGROUND_RESULT_SCHEME:/Playground Result' + ); const activeTextEditorDocument = { uri: playgroundResultUri }; sandbox.replaceGetter(vscode.window, 'activeTextEditor', () => ({ - document: activeTextEditorDocument + document: activeTextEditorDocument, })); testPlaygroundResultViewProvider.setPlaygroundResult(playgroundResult); testPlaygroundResultViewProvider.provideTextDocumentContent(); - let codeLenses = testPlaygroundResultViewProvider._editDocumentCodeLensProvider.provideCodeLenses(); + let codeLenses = + testPlaygroundResultViewProvider._editDocumentCodeLensProvider.provideCodeLenses(); expect(codeLenses.length).to.be.equal(2); @@ -318,8 +344,9 @@ suite('Playground Result Provider Test Suite', () => { expect(secondCodeLensRange.start.line).to.be.equal(9); - let codeLensesInfo = testPlaygroundResultViewProvider - ._editDocumentCodeLensProvider._codeLensesInfo; + let codeLensesInfo = + testPlaygroundResultViewProvider._editDocumentCodeLensProvider + ._codeLensesInfo; expect(Object.keys(codeLensesInfo).length).to.be.equal(1); @@ -330,7 +357,9 @@ suite('Playground Result Provider Test Suite', () => { expect(firstCodeLensesInfo[0].source).to.be.equal('playground'); expect(firstCodeLensesInfo[0].line).to.be.equal(2); expect(firstCodeLensesInfo[0].namespace).to.be.equal(playgroundNamespace); - expect(firstCodeLensesInfo[0].connectionId).to.be.equal('1c8c2b06-fbfb-40b7-bd8a-bd1f8333a487'); + expect(firstCodeLensesInfo[0].connectionId).to.be.equal( + '1c8c2b06-fbfb-40b7-bd8a-bd1f8333a487' + ); expect(firstCodeLensesInfo[1].documentId).to.be.equal(2); expect(firstCodeLensesInfo[1].source).to.be.equal('playground'); @@ -345,9 +374,12 @@ suite('Playground Result Provider Test Suite', () => { testEditDocumentCodeLensProvider ); - testCollectionViewProvider._operationsStore = new CollectionDocumentsOperationsStore(); + testCollectionViewProvider._operationsStore = + new CollectionDocumentsOperationsStore(); - const documents: any[] = [ { _id: '5ea8745ee4811fafe8b65ecb', koko: 'nothing5' } ]; + const documents: any[] = [ + { _id: '5ea8745ee4811fafe8b65ecb', koko: 'nothing5' }, + ]; const mockGetActiveDataService: any = sinon.fake.returns({ find: ( namespace: string, @@ -356,7 +388,7 @@ suite('Playground Result Provider Test Suite', () => { callback: (error: Error | null, result: object) => void ) => { return callback(null, documents); - } + }, }); sinon.replace( testCollectionViewProvider._connectionController, @@ -365,17 +397,26 @@ suite('Playground Result Provider Test Suite', () => { ); const mockShowMessage: any = sinon.fake(); - sinon.replace(testCollectionViewProvider._statusView, 'showMessage', mockShowMessage); + sinon.replace( + testCollectionViewProvider._statusView, + 'showMessage', + mockShowMessage + ); const mockHideMessage: any = sinon.fake(); - sinon.replace(testCollectionViewProvider._statusView, 'hideMessage', mockHideMessage); + sinon.replace( + testCollectionViewProvider._statusView, + 'hideMessage', + mockHideMessage + ); - const operationId = testCollectionViewProvider._operationsStore.createNewOperation(); + const operationId = + testCollectionViewProvider._operationsStore.createNewOperation(); const collectionNamespace = 'berlin.cocktailbars'; const collectionQuery = [ `namespace=${collectionNamespace}`, `connectionId=${connectionId}`, - `operationId=${operationId}` + `operationId=${operationId}`, ].join('&'); const collectionUri = vscode.Uri.parse( `${VIEW_COLLECTION_SCHEME}:Results: ${collectionNamespace}.json?${collectionQuery}` @@ -384,7 +425,8 @@ suite('Playground Result Provider Test Suite', () => { activeTextEditorDocument.uri = collectionUri; // Switch active editor. await testCollectionViewProvider.provideTextDocumentContent(collectionUri); testPlaygroundResultViewProvider._editDocumentCodeLensProvider.provideCodeLenses(); - codeLenses = testPlaygroundResultViewProvider._editDocumentCodeLensProvider.provideCodeLenses(); + codeLenses = + testPlaygroundResultViewProvider._editDocumentCodeLensProvider.provideCodeLenses(); expect(codeLenses.length).to.be.equal(1); @@ -393,7 +435,9 @@ suite('Playground Result Provider Test Suite', () => { expect(firstCodeLensRange.start.line).to.be.equal(2); expect(codeLenses[0].command?.title).to.be.equal('Edit Document'); - codeLensesInfo = testPlaygroundResultViewProvider._editDocumentCodeLensProvider._codeLensesInfo; + codeLensesInfo = + testPlaygroundResultViewProvider._editDocumentCodeLensProvider + ._codeLensesInfo; expect(Object.keys(codeLensesInfo).length).to.be.equal(2); @@ -404,7 +448,9 @@ suite('Playground Result Provider Test Suite', () => { expect(firstCodeLensesInfo[0].source).to.be.equal('playground'); expect(firstCodeLensesInfo[0].line).to.be.equal(2); expect(firstCodeLensesInfo[0].namespace).to.be.equal(playgroundNamespace); - expect(firstCodeLensesInfo[0].connectionId).to.be.equal('1c8c2b06-fbfb-40b7-bd8a-bd1f8333a487'); + expect(firstCodeLensesInfo[0].connectionId).to.be.equal( + '1c8c2b06-fbfb-40b7-bd8a-bd1f8333a487' + ); expect(firstCodeLensesInfo[1].documentId).to.be.equal(2); expect(firstCodeLensesInfo[1].source).to.be.equal('playground'); @@ -413,10 +459,14 @@ suite('Playground Result Provider Test Suite', () => { const secondCodeLensesInfo = codeLensesInfo[collectionUri.toString()]; expect(secondCodeLensesInfo.length).to.be.equal(1); - expect(secondCodeLensesInfo[0].documentId).to.be.equal('5ea8745ee4811fafe8b65ecb'); + expect(secondCodeLensesInfo[0].documentId).to.be.equal( + '5ea8745ee4811fafe8b65ecb' + ); expect(secondCodeLensesInfo[0].source).to.be.equal('collectionview'); expect(secondCodeLensesInfo[0].line).to.be.equal(2); expect(secondCodeLensesInfo[0].namespace).to.be.equal(collectionNamespace); - expect(secondCodeLensesInfo[0].connectionId).to.be.equal('1c8c2b06-fbfb-40b7-bd8a-bd1f8333a487'); + expect(secondCodeLensesInfo[0].connectionId).to.be.equal( + '1c8c2b06-fbfb-40b7-bd8a-bd1f8333a487' + ); }); }); diff --git a/src/test/suite/explorer/collectionTreeItem.test.ts b/src/test/suite/explorer/collectionTreeItem.test.ts index 3bff52c6..cbdf7573 100644 --- a/src/test/suite/explorer/collectionTreeItem.test.ts +++ b/src/test/suite/explorer/collectionTreeItem.test.ts @@ -15,7 +15,7 @@ suite('CollectionTreeItem Test Suite', () => { const testCollectionTreeItem = new CollectionTreeItem( { name: 'mock_collection_name_1', - type: CollectionTypes.collection + type: CollectionTypes.collection, }, 'mock_db_name', 'imaginary data service', @@ -40,7 +40,7 @@ suite('CollectionTreeItem Test Suite', () => { const testCollectionTreeItem = new CollectionTreeItem( { name: 'mock_collection_name_1', - type: CollectionTypes.collection + type: CollectionTypes.collection, }, 'mock_db_name', new DataServiceStub(), @@ -75,7 +75,7 @@ suite('CollectionTreeItem Test Suite', () => { const testCollectionTreeItem = new CollectionTreeItem( { name: 'mock_collection_name_1', - type: CollectionTypes.collection + type: CollectionTypes.collection, }, 'mock_db_name', { estimatedCount: (ns, options, cb): void => cb(null, 5000) }, @@ -106,7 +106,7 @@ suite('CollectionTreeItem Test Suite', () => { const testCollectionViewTreeItem = new CollectionTreeItem( { name: 'mock_collection_name_1', - type: CollectionTypes.view + type: CollectionTypes.view, }, 'mock_db_name', 'imaginary data service', @@ -128,7 +128,7 @@ suite('CollectionTreeItem Test Suite', () => { const testCollectionCollectionTreeItem = new CollectionTreeItem( { name: 'mock_collection_name_1', - type: CollectionTypes.collection + type: CollectionTypes.collection, }, 'mock_db_name', 'imaginary data service', @@ -152,7 +152,7 @@ suite('CollectionTreeItem Test Suite', () => { const testCollectionViewTreeItem = new CollectionTreeItem( { name: 'mock_collection_name_1', - type: CollectionTypes.timeseries + type: CollectionTypes.timeseries, }, 'mock_db_name', 'imaginary data service', @@ -174,7 +174,7 @@ suite('CollectionTreeItem Test Suite', () => { const testCollectionCollectionTreeItem = new CollectionTreeItem( { name: 'mock_collection_name_1', - type: CollectionTypes.collection + type: CollectionTypes.collection, }, 'mock_db_name', 'imaginary data service', diff --git a/src/test/suite/explorer/connectionTreeItem.test.ts b/src/test/suite/explorer/connectionTreeItem.test.ts index c2bf6b5e..a4f11575 100644 --- a/src/test/suite/explorer/connectionTreeItem.test.ts +++ b/src/test/suite/explorer/connectionTreeItem.test.ts @@ -5,7 +5,7 @@ import { beforeEach, afterEach } from 'mocha'; import sinon from 'sinon'; import ConnectionTreeItem, { - ConnectionItemContextValues + ConnectionItemContextValues, } from '../../../explorer/connectionTreeItem'; import { DataServiceStub } from '../stubs'; import formatError from '../../../utils/formatError'; @@ -73,16 +73,23 @@ suite('ConnectionTreeItem Test Suite', () => { sinon.replace( mdbTestExtension.testExtensionController._connectionController, 'getActiveDataService', - () => ({ - listDatabases: () => new Promise(() => { throw Error('peaches'); }) - }) as any + () => + ({ + listDatabases: () => + new Promise(() => { + throw Error('peaches'); + }), + } as any) ); try { await testConnectionTreeItem.getChildren(); assert(false); } catch (error) { - assert.strictEqual(formatError(error).message, 'Unable to list databases: peaches'); + assert.strictEqual( + formatError(error).message, + 'Unable to list databases: peaches' + ); } }); }); diff --git a/src/test/suite/explorer/databaseTreeItem.test.ts b/src/test/suite/explorer/databaseTreeItem.test.ts index 6c9f0329..961c572d 100644 --- a/src/test/suite/explorer/databaseTreeItem.test.ts +++ b/src/test/suite/explorer/databaseTreeItem.test.ts @@ -11,7 +11,7 @@ import { cleanupTestDB, disconnectFromTestDB, TEST_DB_NAME, - TEST_DATABASE_URI + TEST_DATABASE_URI, } from '../dbTestHelper'; const { contributes } = require('../../../../package.json'); @@ -79,8 +79,9 @@ suite('DatabaseTreeItem Test Suite', () => { assert( collections[1].label === - mockDatabases[mockDatabaseNames[1]].collections[1].name, - `Expected a tree item child with the label collection name ${mockDatabases[mockDatabaseNames[1]].collections[1].name + mockDatabases[mockDatabaseNames[1]].collections[1].name, + `Expected a tree item child with the label collection name ${ + mockDatabases[mockDatabaseNames[1]].collections[1].name } found ${collections[1].label}` ); }); @@ -121,7 +122,8 @@ suite('DatabaseTreeItem Test Suite', () => { ); testDatabaseTreeItem.onDidCollapse(); - const postCollapseCollectionTreeItems = await testDatabaseTreeItem.getChildren(); + const postCollapseCollectionTreeItems = + await testDatabaseTreeItem.getChildren(); assert( postCollapseCollectionTreeItems.length === 0, @@ -167,15 +169,13 @@ suite('DatabaseTreeItem Test Suite', () => { 'ZZZ', 'system.buckets.aaa', 'system.buckets.zzz', - 'system.views' + 'system.views', ]; - const collectionTreeItems: CollectionTreeItem[] = await testDatabaseTreeItem - .getChildren(); + const collectionTreeItems: CollectionTreeItem[] = + await testDatabaseTreeItem.getChildren(); assert.deepStrictEqual( - collectionTreeItems - .map(({ collectionName }) => collectionName) - .join(), + collectionTreeItems.map(({ collectionName }) => collectionName).join(), expectedCollectionsOrder.join(), 'Expected collections to be in alphanumerical order but they were not' ); @@ -198,8 +198,8 @@ suite('DatabaseTreeItem Test Suite', () => { const mockDocWithThirtyFields = { _id: 32, testerObject: { - aField: 1234567 - } + aField: 1234567, + }, }; for (let i = 0; i < 28; i++) { @@ -215,7 +215,8 @@ suite('DatabaseTreeItem Test Suite', () => { false, {} ); - const collectionTreeItems: CollectionTreeItem[] = await testDatabaseTreeItem.getChildren(); + const collectionTreeItems: CollectionTreeItem[] = + await testDatabaseTreeItem.getChildren(); assert( collectionTreeItems[0].isExpanded === false, @@ -247,27 +248,27 @@ suite('DatabaseTreeItem Test Suite', () => { await schemaTreeItem.childrenCache.testerObject.onDidExpand(); testDatabaseTreeItem.onDidCollapse(); - const postCollapseCollectionTreeItems = await testDatabaseTreeItem.getChildren(); + const postCollapseCollectionTreeItems = + await testDatabaseTreeItem.getChildren(); assert( postCollapseCollectionTreeItems.length === 0, `Expected the database tree to return no children when collapsed, found ${collectionTreeItems.length}` ); await testDatabaseTreeItem.onDidExpand(); - const newCollectionTreeItems = await testDatabaseTreeItem - .getChildren(); + const newCollectionTreeItems = await testDatabaseTreeItem.getChildren(); - const postCollapseSchemaTreeItem = newCollectionTreeItems[0].getSchemaChild(); + const postCollapseSchemaTreeItem = + newCollectionTreeItems[0].getSchemaChild(); assert( postCollapseSchemaTreeItem.isExpanded === true, 'Expected collection tree item to be expanded from cache.' ); - const fieldsPostCollapseExpand = await postCollapseSchemaTreeItem - .getChildren(); + const fieldsPostCollapseExpand = + await postCollapseSchemaTreeItem.getChildren(); // It should cache that we activated show more. - const amountOfCachedFields = - fieldsPostCollapseExpand.length; + const amountOfCachedFields = fieldsPostCollapseExpand.length; const expectedCachedFields = 30; assert( amountOfCachedFields === expectedCachedFields, @@ -288,7 +289,7 @@ suite('DatabaseTreeItem Test Suite', () => { ); assert( testerObjectField.collapsibleState === - vscode.TreeItemCollapsibleState.Expanded, + vscode.TreeItemCollapsibleState.Expanded, `Expected the subdocument field to have an expanded state (2), found ${postCollapseSchemaTreeItem.childrenCache.testerObject.collapsibleState}.` ); }); diff --git a/src/test/suite/explorer/documentListTreeItem.test.ts b/src/test/suite/explorer/documentListTreeItem.test.ts index 6c9f5acd..9e292e14 100644 --- a/src/test/suite/explorer/documentListTreeItem.test.ts +++ b/src/test/suite/explorer/documentListTreeItem.test.ts @@ -6,7 +6,7 @@ const { contributes } = require('../../../../package.json'); import DocumentListTreeItem, { CollectionTypes, formatDocCount, - MAX_DOCUMENTS_VISIBLE + MAX_DOCUMENTS_VISIBLE, } from '../../../explorer/documentListTreeItem'; import { DataServiceStub, mockDocuments } from '../stubs'; @@ -61,7 +61,8 @@ suite('DocumentListTreeItem Test Suite', () => { testDocumentListTreeItem.onShowMoreClicked(); - const newMaxDocumentsToShow = testDocumentListTreeItem.getMaxDocumentsToShow(); + const newMaxDocumentsToShow = + testDocumentListTreeItem.getMaxDocumentsToShow(); assert( newMaxDocumentsToShow === 20, `Expected max documents to show to be 20, found ${newMaxDocumentsToShow}.` @@ -129,7 +130,7 @@ suite('DocumentListTreeItem Test Suite', () => { assert( testDocumentListTreeItem.collapsibleState === - vscode.TreeItemCollapsibleState.None + vscode.TreeItemCollapsibleState.None ); }); diff --git a/src/test/suite/explorer/documentTreeItem.test.ts b/src/test/suite/explorer/documentTreeItem.test.ts index c49c756c..e6265fb5 100644 --- a/src/test/suite/explorer/documentTreeItem.test.ts +++ b/src/test/suite/explorer/documentTreeItem.test.ts @@ -5,7 +5,7 @@ import DocumentTreeItem from '../../../explorer/documentTreeItem'; suite('DocumentTreeItem Test Suite', () => { test('it makes the document _id the label of the document tree item', function () { const mockDocument = { - _id: 'mock_document_id' + _id: 'mock_document_id', }; const testCollectionTreeItem = new DocumentTreeItem( @@ -25,8 +25,8 @@ suite('DocumentTreeItem Test Suite', () => { const mockDocument = { _id: { someIdField: 'mock_document_id', - anotherIdField: 'mock_document_id_field_2' - } + anotherIdField: 'mock_document_id_field_2', + }, }; const expectedLabel = JSON.stringify(mockDocument._id); @@ -46,7 +46,7 @@ suite('DocumentTreeItem Test Suite', () => { test('when the document does not have an _id, its label is the supplied index', function () { const mockDocument = { - noIdField: true + noIdField: true, }; const expectedLabel = 'Document 2'; diff --git a/src/test/suite/explorer/explorerController.test.ts b/src/test/suite/explorer/explorerController.test.ts index 36cbaab2..88574e3b 100644 --- a/src/test/suite/explorer/explorerController.test.ts +++ b/src/test/suite/explorer/explorerController.test.ts @@ -5,7 +5,7 @@ import sinon from 'sinon'; import { DefaultSavingLocations, - StorageLocation + StorageLocation, } from '../../../storage/storageController'; import { mdbTestExtension } from '../stubbableMdbExtension'; import { TEST_DATABASE_URI } from '../dbTestHelper'; @@ -28,7 +28,11 @@ suite('Explorer Controller Test Suite', function () { ); // Here we stub the showInformationMessage process because it is too much // for the render process and leads to crashes while testing. - sinon.replace(vscode.window, 'showInformationMessage', sinon.fake.resolves(true)); + sinon.replace( + vscode.window, + 'showInformationMessage', + sinon.fake.resolves(true) + ); }); afterEach(async () => { @@ -58,8 +62,8 @@ suite('Explorer Controller Test Suite', function () { id: 'testConnectionId', connectionOptions: { connectionString: 'mongodb://localhost' }, name: 'testConnectionName', - storageLocation: StorageLocation.NONE - } + storageLocation: StorageLocation.NONE, + }, }; testConnectionController.setConnnecting(true); @@ -82,9 +86,10 @@ suite('Explorer Controller Test Suite', function () { mdbTestExtension.testExtensionController._explorerController; const treeController = testExplorerController.getTreeController(); - const succesfullyConnected = await testConnectionController.addNewConnectionStringAndConnect( - TEST_DATABASE_URI - ); + const succesfullyConnected = + await testConnectionController.addNewConnectionStringAndConnect( + TEST_DATABASE_URI + ); assert( succesfullyConnected === true, @@ -127,9 +132,10 @@ suite('Explorer Controller Test Suite', function () { mdbTestExtension.testExtensionController._explorerController; const treeController = testExplorerController.getTreeController(); - const succesfullyConnected = await testConnectionController.addNewConnectionStringAndConnect( - TEST_DATABASE_URI - ); + const succesfullyConnected = + await testConnectionController.addNewConnectionStringAndConnect( + TEST_DATABASE_URI + ); assert( succesfullyConnected === true, @@ -191,17 +197,19 @@ suite('Explorer Controller Test Suite', function () { const connectionId = testConnectionController.getActiveConnectionId() || ''; testConnectionController._connections.aaa = { - connectionOptions: testConnectionController._connections[connectionId].connectionOptions, + connectionOptions: + testConnectionController._connections[connectionId].connectionOptions, name: 'aaa', id: 'aaa', - storageLocation: StorageLocation.WORKSPACE + storageLocation: StorageLocation.WORKSPACE, }; testConnectionController._connections.zzz = { - connectionOptions: testConnectionController._connections[connectionId].connectionOptions, + connectionOptions: + testConnectionController._connections[connectionId].connectionOptions, name: 'zzz', id: 'zzz', - storageLocation: StorageLocation.WORKSPACE + storageLocation: StorageLocation.WORKSPACE, }; const connectionsItems = await treeController.getChildren(); diff --git a/src/test/suite/explorer/fieldTreeItem.test.ts b/src/test/suite/explorer/fieldTreeItem.test.ts index d30851e8..9236147b 100644 --- a/src/test/suite/explorer/fieldTreeItem.test.ts +++ b/src/test/suite/explorer/fieldTreeItem.test.ts @@ -5,7 +5,7 @@ import { ext } from '../../../extensionConstants'; import FieldTreeItem, { FIELD_TREE_ITEM_CONTEXT_VALUE, fieldIsExpandable, - getIconFileNameForField + getIconFileNameForField, } from '../../../explorer/fieldTreeItem'; import { createTestDataService, @@ -13,7 +13,7 @@ import { cleanupTestDB, disconnectFromTestDB, TEST_DB_NAME, - TEST_DATABASE_URI + TEST_DATABASE_URI, } from '../dbTestHelper'; import SchemaTreeItem from '../../../explorer/schemaTreeItem'; import { TestExtensionContext } from '../stubs'; @@ -45,7 +45,7 @@ suite('FieldTreeItem Test Suite', function () { name: 'test', probability: 1, type: 'String', - types: [] + types: [], }, false, {} @@ -60,7 +60,7 @@ suite('FieldTreeItem Test Suite', function () { name: 'test', probability: 1, type: 'Number', - types: [] + types: [], }, false, {} @@ -79,14 +79,14 @@ suite('FieldTreeItem Test Suite', function () { { name: 'a', probability: 0.5, - bsonType: 'String' + bsonType: 'String', }, { name: 'b', probability: 0.5, - bsonType: 'Number' - } - ] + bsonType: 'Number', + }, + ], }; assert(getIconFileNameForField(notFullProbability) === 'mixed-type'); }); @@ -99,9 +99,9 @@ suite('FieldTreeItem Test Suite', function () { { name: 'a', probability: 1, - bsonType: 'String' - } - ] + bsonType: 'String', + }, + ], }; assert(getIconFileNameForField(notFullProbability) === 'mixed-type'); }); @@ -116,21 +116,24 @@ suite('FieldTreeItem Test Suite', function () { { name: 'a', probability: 0.5, - bsonType: 'String' + bsonType: 'String', }, { name: 'b', probability: 0.5, - bsonType: 'Number' - } - ] + bsonType: 'Number', + }, + ], }, false, {} ); const tooltipMatches = testField.tooltip === 'test - mixed-type'; - assert(tooltipMatches, `Expected tooltip '${testField.tooltip}' to equal 'test - mixed-type'`); + assert( + tooltipMatches, + `Expected tooltip '${testField.tooltip}' to equal 'test - mixed-type'` + ); }); suite('Full database tests', () => { @@ -150,10 +153,7 @@ suite('FieldTreeItem Test Suite', function () { }); test('field name is pulled from the name of a field', async () => { - await seedTestDB( - 'pie', - [{ _id: 1, blueberryPie: 'yes' }] - ); + await seedTestDB('pie', [{ _id: 1, blueberryPie: 'yes' }]); const testSchemaTreeItem = new SchemaTreeItem( 'pie', TEST_DB_NAME, @@ -181,29 +181,26 @@ suite('FieldTreeItem Test Suite', function () { }); test('it shows dropdowns for nested subdocuments', async () => { - await seedTestDB( - 'gryffindor', - [ - { - _id: 1, - alwaysDocument: { - nestedSubDocument: { - magic: true, - harry: 'potter' - } - } + await seedTestDB('gryffindor', [ + { + _id: 1, + alwaysDocument: { + nestedSubDocument: { + magic: true, + harry: 'potter', + }, }, - { - _id: 2, - alwaysDocument: { - nestedSubDocument: { - magic: true, - hermione: 'granger' - } - } - } - ] - ); + }, + { + _id: 2, + alwaysDocument: { + nestedSubDocument: { + magic: true, + hermione: 'granger', + }, + }, + }, + ]); const testSchemaTreeItem = new SchemaTreeItem( 'gryffindor', @@ -253,19 +250,16 @@ suite('FieldTreeItem Test Suite', function () { }); test('it shows dropdowns for arrays', async () => { - await seedTestDB( - 'gryffindor', - [ - { - _id: 1, - testingArray: ['okay', 'nice'] - }, - { - _id: 2, - testingArray: ['dobby'] - } - ] - ); + await seedTestDB('gryffindor', [ + { + _id: 1, + testingArray: ['okay', 'nice'], + }, + { + _id: 2, + testingArray: ['dobby'], + }, + ]); const testSchemaTreeItem = new SchemaTreeItem( 'gryffindor', @@ -304,29 +298,26 @@ suite('FieldTreeItem Test Suite', function () { }); test('it shows dropdowns and fields for document fields in arrays', async () => { - await seedTestDB( - 'beach', - [ - { - _id: 1, - testingArray: [ - { - color: 'orange', - sunset: false - } - ] - }, - { - _id: 2, - testingArray: [ - { - color: 'violet', - sunset: true - } - ] - } - ] - ); + await seedTestDB('beach', [ + { + _id: 1, + testingArray: [ + { + color: 'orange', + sunset: false, + }, + ], + }, + { + _id: 2, + testingArray: [ + { + color: 'violet', + sunset: true, + }, + ], + }, + ]); const testSchemaTreeItem = new SchemaTreeItem( 'beach', diff --git a/src/test/suite/explorer/helpExplorer.test.ts b/src/test/suite/explorer/helpExplorer.test.ts index eedf5b8a..68f85d73 100644 --- a/src/test/suite/explorer/helpExplorer.test.ts +++ b/src/test/suite/explorer/helpExplorer.test.ts @@ -42,7 +42,8 @@ suite('Help Explorer Test Suite', function () { const atlasHelpItem = helpTreeItems[5]; assert.strictEqual(atlasHelpItem.label, 'Create Free Atlas Cluster'); - const telemetryUserIdentity = mdbTestExtension.testExtensionController._telemetryService.getTelemetryUserIdentity(); + const telemetryUserIdentity = + mdbTestExtension.testExtensionController._telemetryService.getTelemetryUserIdentity(); assert.strictEqual( atlasHelpItem.url, `https://mongodb.com/products/vs-code/vs-code-atlas-signup?utm_campaign=vs-code-extension&utm_source=visual-studio&utm_medium=product&ajs_aid=${telemetryUserIdentity[0]}` @@ -74,11 +75,11 @@ suite('Help Explorer Test Suite', function () { assert(stubExecuteCommand.firstCall.args[0] === 'vscode.open'); assert( stubExecuteCommand.firstCall.args[1].path === - vscode.Uri.parse(atlasHelpItem.url).path + vscode.Uri.parse(atlasHelpItem.url).path ); assert( stubExecuteCommand.firstCall.args[1].authority === - vscode.Uri.parse(atlasHelpItem.url).authority + vscode.Uri.parse(atlasHelpItem.url).authority ); }); diff --git a/src/test/suite/explorer/indexListTreeItem.test.ts b/src/test/suite/explorer/indexListTreeItem.test.ts index 2c8745ed..7bba1683 100644 --- a/src/test/suite/explorer/indexListTreeItem.test.ts +++ b/src/test/suite/explorer/indexListTreeItem.test.ts @@ -22,7 +22,7 @@ suite('IndexListTreeItem Test Suite', () => { { indexes: (ns, opts, cb): void => { cb(null, []); - } + }, } as DataService, false, false, @@ -46,20 +46,20 @@ suite('IndexListTreeItem Test Suite', () => { { v: 1, key: { - _id: 1 + _id: 1, }, name: '_id_', - ns: 'tasty_fruits.pineapple' + ns: 'tasty_fruits.pineapple', }, { v: 1, key: { _id: 1, - gnocchi: -1 + gnocchi: -1, }, name: '_id_1_gnocchi_1', - ns: 'tasty_fruits.pineapple' - } + ns: 'tasty_fruits.pineapple', + }, ]; let namespaceRequested = ''; @@ -71,7 +71,7 @@ suite('IndexListTreeItem Test Suite', () => { namespaceRequested = ns; cb(null, fakeFetchIndexes); - } + }, } as DataService, false, false, @@ -111,14 +111,17 @@ suite('IndexListTreeItem Test Suite', () => { { indexes: (ns, opts, cb): void => { cb(null, []); - } + }, } as DataService, false, false, [] ); - const indexesIconPath = testIndexListTreeItem.iconPath as { light: string; dark: string }; + const indexesIconPath = testIndexListTreeItem.iconPath as { + light: string; + dark: string; + }; assert( indexesIconPath.dark.includes('indexes.svg'), 'Expected icon path to point to an svg by the name "indexes" with a dark mode' @@ -137,7 +140,7 @@ suite('IndexListTreeItem Test Suite', () => { { indexes: (ns, opts, cb): void => { cb(new Error(expectedMessage), []); - } + }, } as DataService, false, false, @@ -158,26 +161,25 @@ suite('IndexListTreeItem Test Suite', () => { } }); - test('when rebuilt it maintains the expanded state of the cached indexes', async () => { const fakeFetchIndexes = [ { v: 1, key: { - _id: 1 + _id: 1, }, name: '_id_', - ns: 'tasty_fruits.pineapple' + ns: 'tasty_fruits.pineapple', }, { v: 1, key: { _id: 1, - gnocchi: -1 + gnocchi: -1, }, name: '_id_1_gnocchi_1', - ns: 'tasty_fruits.pineapple' - } + ns: 'tasty_fruits.pineapple', + }, ]; const testIndexListTreeItem = new IndexListTreeItem( @@ -186,7 +188,7 @@ suite('IndexListTreeItem Test Suite', () => { { indexes: (ns, opts, cb): void => { cb(null, fakeFetchIndexes); - } + }, } as DataService, false, false, @@ -211,7 +213,7 @@ suite('IndexListTreeItem Test Suite', () => { { indexes: (ns, opts, cb): void => { cb(null, []); - } + }, } as DataService, testIndexListTreeItem.isExpanded, testIndexListTreeItem.cacheIsUpToDate, @@ -234,7 +236,8 @@ suite('IndexListTreeItem Test Suite', () => { 'Expected the first index in list to be expanded' ); assert( - newIndexTreeItems[0].collapsibleState === vscode.TreeItemCollapsibleState.Expanded, + newIndexTreeItems[0].collapsibleState === + vscode.TreeItemCollapsibleState.Expanded, 'Expected the first index in list have expanded tree state' ); }); diff --git a/src/test/suite/explorer/indexTreeItem.test.ts b/src/test/suite/explorer/indexTreeItem.test.ts index dc60dbc7..23e3fd5f 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 + IndexKeyType, } from '../../../explorer/indexTreeItem'; suite('IndexTreeItem Test Suite', () => { @@ -12,10 +12,10 @@ suite('IndexTreeItem Test Suite', () => { v: 1, key: { _id: 1, - gnocchi: -1 + gnocchi: -1, }, name: '_id_1_gnocchi_1', - ns: 'tasty_fruits.pineapple' + ns: 'tasty_fruits.pineapple', }, 'tasty_fruits.pineapple', false @@ -46,7 +46,8 @@ suite('IndexTreeItem Test Suite', () => { const iconPath: any = testIndexFieldTreeItem.iconPath; assert( - iconPath.dark.includes('index') && iconPath.dark.includes('geospatial.svg'), + iconPath.dark.includes('index') && + iconPath.dark.includes('geospatial.svg'), 'Expected icon path to point to an svg by the name "geospatial" in the index folder' ); }); diff --git a/src/test/suite/explorer/schemaTreeItem.test.ts b/src/test/suite/explorer/schemaTreeItem.test.ts index c398f8c5..c3fdde8c 100644 --- a/src/test/suite/explorer/schemaTreeItem.test.ts +++ b/src/test/suite/explorer/schemaTreeItem.test.ts @@ -12,10 +12,10 @@ import { cleanupTestDB, disconnectFromTestDB, TEST_DB_NAME, - TEST_DATABASE_URI + TEST_DATABASE_URI, } from '../dbTestHelper'; import SchemaTreeItem, { - FIELDS_TO_SHOW + FIELDS_TO_SHOW, } from '../../../explorer/schemaTreeItem'; import { TestExtensionContext } from '../stubs'; @@ -83,7 +83,8 @@ suite('SchemaTreeItem Test Suite', function () { }); test('when there are no documents in the schema it should show a message', async () => { - const expectedMessage = 'No documents were found when attempting to parse schema.'; + const expectedMessage = + 'No documents were found when attempting to parse schema.'; const testSchemaTreeItem = new SchemaTreeItem( 'peanutButter', @@ -91,7 +92,7 @@ suite('SchemaTreeItem Test Suite', function () { { find: (ns, filter, options, callback): void => { callback(null, []); - } + }, }, true, false, @@ -130,7 +131,7 @@ suite('SchemaTreeItem Test Suite', function () { { find: (ns, filter, options, callback): void => { callback(null, [mockDocWithTwentyFields]); - } + }, }, true, false, @@ -146,7 +147,8 @@ suite('SchemaTreeItem Test Suite', function () { assert( schemaFields.length === amountOfFieldsExpected + 1, - `Expected ${amountOfFieldsExpected + 1 + `Expected ${ + amountOfFieldsExpected + 1 } documents to be returned, found ${schemaFields.length}` ); assert( @@ -168,7 +170,7 @@ suite('SchemaTreeItem Test Suite', function () { { find: (ns, filter, options, callback): void => { callback(null, [mockDocWithThirtyFields]); - } + }, }, true, false, @@ -199,7 +201,7 @@ suite('SchemaTreeItem Test Suite', function () { { find: (ns, filter, options, callback): void => { callback(null, 'invalid schema to parse'); - } + }, }, true, false, @@ -244,13 +246,12 @@ suite('SchemaTreeItem Test Suite', function () { }); test('when not expanded it has not yet pulled the schema', async () => { - await seedTestDB( - 'favoritePiesIWantToEatRightNow', - [{ + await seedTestDB('favoritePiesIWantToEatRightNow', [ + { _id: 10, - someField: 'applePie' - }] - ); + someField: 'applePie', + }, + ]); const testSchemaTreeItem = new SchemaTreeItem( 'favoritePiesIWantToEatRightNow', @@ -272,13 +273,12 @@ suite('SchemaTreeItem Test Suite', function () { }); test('when expanded shows the fields of a schema', async () => { - await seedTestDB( - 'favoritePiesIWantToEatRightNow', - [{ + await seedTestDB('favoritePiesIWantToEatRightNow', [ + { _id: 1, - nameOfTastyPie: 'applePie' - }] - ); + nameOfTastyPie: 'applePie', + }, + ]); const testSchemaTreeItem = new SchemaTreeItem( 'favoritePiesIWantToEatRightNow', @@ -310,27 +310,24 @@ suite('SchemaTreeItem Test Suite', function () { }); test('it only shows a dropdown for fields which are always documents - and not for polymorphic', async () => { - await seedTestDB( - 'favoritePiesIWantToEatRightNow', - [ - { - _id: 1, - alwaysDocument: { - fieldName: 'nice' - }, - notAlwaysADocument: { - sureImADocument: 'hmmmm' - } + await seedTestDB('favoritePiesIWantToEatRightNow', [ + { + _id: 1, + alwaysDocument: { + fieldName: 'nice', }, - { - _id: 2, - alwaysDocument: { - fieldName: 'nice' - }, - notAlwaysADocument: 'A spy!' - } - ] - ); + notAlwaysADocument: { + sureImADocument: 'hmmmm', + }, + }, + { + _id: 2, + alwaysDocument: { + fieldName: 'nice', + }, + notAlwaysADocument: 'A spy!', + }, + ]); const testSchemaTreeItem = new SchemaTreeItem( 'favoritePiesIWantToEatRightNow', @@ -349,7 +346,9 @@ suite('SchemaTreeItem Test Suite', function () { assert( schemaFields.length === 3, - `Expected 3 schema tree items to be returned, recieved ${schemaFields.length}: ${inspect(schemaFields)}` + `Expected 3 schema tree items to be returned, recieved ${ + schemaFields.length + }: ${inspect(schemaFields)}` ); assert( fieldIsExpandable(schemaFields[1].field), diff --git a/src/test/suite/extension.test.ts b/src/test/suite/extension.test.ts index db9ebf63..095d6117 100644 --- a/src/test/suite/extension.test.ts +++ b/src/test/suite/extension.test.ts @@ -56,7 +56,7 @@ suite('Extension Test Suite', () => { // Editor commands. 'mdb.codeLens.showMoreDocumentsClicked', - ...Object.values(EXTENSION_COMMANDS) + ...Object.values(EXTENSION_COMMANDS), ]; for (const expectedCommand of expectedCommands) { diff --git a/src/test/suite/index.ts b/src/test/suite/index.ts index 4b2eace7..a84bd0e6 100644 --- a/src/test/suite/index.ts +++ b/src/test/suite/index.ts @@ -11,7 +11,7 @@ import { mdbTestExtension } from './stubbableMdbExtension'; export async function run(): Promise { const reporterOptions = { spec: '-', - 'mocha-junit-reporter': path.join(__dirname, './test-results.xml') + 'mocha-junit-reporter': path.join(__dirname, './test-results.xml'), }; // Create the mocha tester. @@ -19,7 +19,7 @@ export async function run(): Promise { reporter: 'mocha-multi', reporterOptions, ui: 'tdd', - color: true + color: true, }); const testsRoot = path.join(__dirname, '..'); @@ -38,7 +38,7 @@ export async function run(): Promise { '**/**.test.js', { cwd: testsRoot, - ignore: ['**/webview-app/**/*.js'] + ignore: ['**/webview-app/**/*.js'], }, (err, files) => { if (err) { diff --git a/src/test/suite/keytarStub.ts b/src/test/suite/keytarStub.ts index b20f06a6..d92a6602 100644 --- a/src/test/suite/keytarStub.ts +++ b/src/test/suite/keytarStub.ts @@ -5,9 +5,14 @@ import { KeytarInterface } from '../../utils/keytar'; const retrievalDelay = 1; // ms simulated delay on keytar methods. export default class KeytarStub implements KeytarInterface { - private _services: Map> = new Map>(); + private _services: Map> = new Map< + string, + Map + >(); - public async findCredentials(service: string): Promise | undefined> { + public async findCredentials( + service: string + ): Promise | undefined> { await this.delay(); const savedServices = this._services.get(service); if (savedServices) { @@ -17,7 +22,10 @@ export default class KeytarStub implements KeytarInterface { return undefined; } - public async getPassword(service: string, account: string): Promise { + public async getPassword( + service: string, + account: string + ): Promise { await this.delay(); const savedService = this._services.get(service); if (savedService) { @@ -31,7 +39,11 @@ export default class KeytarStub implements KeytarInterface { return null; } - public async setPassword(service: string, account: string, password: string): Promise { + public async setPassword( + service: string, + account: string, + password: string + ): Promise { await this.delay(); let savedService = this._services.get(service); if (!savedService) { @@ -42,7 +54,10 @@ export default class KeytarStub implements KeytarInterface { savedService.set(account, password); } - public async deletePassword(service: string, account: string): Promise { + public async deletePassword( + service: string, + account: string + ): Promise { await this.delay(); const savedService = this._services.get(service); if (savedService) { diff --git a/src/test/suite/language/languageServerController.test.ts b/src/test/suite/language/languageServerController.test.ts index 4875c262..20a8aba6 100644 --- a/src/test/suite/language/languageServerController.test.ts +++ b/src/test/suite/language/languageServerController.test.ts @@ -56,7 +56,8 @@ suite('Language Server Controller Test Suite', () => { const testExplorerController = new ExplorerController( testConnectionController ); - const testExportToLanguageCodeLensProvider = new ExportToLanguageCodeLensProvider(); + const testExportToLanguageCodeLensProvider = + new ExportToLanguageCodeLensProvider(); const testCodeActionProvider = new CodeActionProvider(); const testPlaygroundController = new PlaygroundController( testConnectionController, @@ -81,18 +82,15 @@ suite('Language Server Controller Test Suite', () => { sinon.replace( testConnectionController, 'getActiveDataService', - () => ({ - getMongoClientConnectionOptions: () => ({ - url: TEST_DATABASE_URI, - options: {} - }) - } as any) - ); - sinon.replace( - testConnectionController, - 'isCurrentlyConnected', - () => true + () => + ({ + getMongoClientConnectionOptions: () => ({ + url: TEST_DATABASE_URI, + options: {}, + }), + } as any) ); + sinon.replace(testConnectionController, 'isCurrentlyConnected', () => true); await testPlaygroundController._connectToServiceProvider(); }); @@ -122,7 +120,7 @@ suite('Language Server Controller Test Suite', () => { }); currentName `, - connectionId: 'pineapple' + connectionId: 'pineapple', }); testLanguageServerController.cancelAll(); diff --git a/src/test/suite/language/mongoDBService.test.ts b/src/test/suite/language/mongoDBService.test.ts index 7006b64d..e5bdd258 100644 --- a/src/test/suite/language/mongoDBService.test.ts +++ b/src/test/suite/language/mongoDBService.test.ts @@ -1,12 +1,18 @@ import * as vscode from 'vscode'; import { before } from 'mocha'; -import { CancellationTokenSource, CompletionItemKind, CompletionItem } from 'vscode-languageclient/node'; +import { + CancellationTokenSource, + CompletionItemKind, + CompletionItem, +} from 'vscode-languageclient/node'; import chai from 'chai'; import { createConnection } from 'vscode-languageserver/node'; import fs from 'fs'; import path from 'path'; -import MongoDBService, { languageServerWorkerFileName } from '../../../language/mongoDBService'; +import MongoDBService, { + languageServerWorkerFileName, +} from '../../../language/mongoDBService'; import { mdbTestExtension } from '../stubbableMdbExtension'; import { TestStream } from '../stubs'; import READ_PREFERENCES from '../../../views/webview-app/connection-model/constants/read-preferences'; @@ -19,8 +25,8 @@ suite('MongoDBService Test Suite', () => { connectionId: 'pineapple', connectionString: 'mongodb://localhost:27018', connectionOptions: { - readPreference: READ_PREFERENCES.PRIMARY - } + readPreference: READ_PREFERENCES.PRIMARY, + }, }; test('the language server worker dependency bundle exists', () => { @@ -53,7 +59,7 @@ suite('MongoDBService Test Suite', () => { const result = await testMongoDBService.executeAll( { codeToEvaluate: '1 + 1', - connectionId: 'pineapple' + connectionId: 'pineapple', }, source.token ); @@ -62,13 +68,18 @@ suite('MongoDBService Test Suite', () => { }); test('catches error when _getCollectionsCompletionItems is called and extension path is empty string', async () => { - const result = await testMongoDBService._getCollectionsCompletionItems('testDB'); + const result = await testMongoDBService._getCollectionsCompletionItems( + 'testDB' + ); expect(result).to.be.equal(false); }); test('catches error when _getFieldsCompletionItems is called and extension path is empty string', async () => { - const result = await testMongoDBService._getFieldsCompletionItems('testDB', 'testCol'); + const result = await testMongoDBService._getFieldsCompletionItems( + 'testDB', + 'testCol' + ); expect(result).to.be.equal(false); }); @@ -107,9 +118,9 @@ suite('MongoDBService Test Suite', () => { const testMongoDBService = new MongoDBService(connection); before(async () => { - testMongoDBService._getDatabasesCompletionItems = (): void => { }; - testMongoDBService._getCollectionsCompletionItems = (): Promise => - Promise.resolve(true); + testMongoDBService._getDatabasesCompletionItems = (): void => {}; + testMongoDBService._getCollectionsCompletionItems = + (): Promise => Promise.resolve(true); testMongoDBService._getFieldsCompletionItems = (): Promise => Promise.resolve(true); @@ -121,7 +132,9 @@ suite('MongoDBService Test Suite', () => { 'db.test.', { line: 0, character: 8 } ); - const findCompletion = result.find((item: CompletionItem) => item.label === 'find'); + const findCompletion = result.find( + (item: CompletionItem) => item.label === 'find' + ); expect(findCompletion).to.have.property( 'kind', @@ -134,7 +147,9 @@ suite('MongoDBService Test Suite', () => { 'const name = () => { db.test. }', { line: 0, character: 29 } ); - const findCompletion = result.find((item: CompletionItem) => item.label === 'find'); + const findCompletion = result.find( + (item: CompletionItem) => item.label === 'find' + ); expect(findCompletion).to.have.property( 'kind', @@ -147,7 +162,9 @@ suite('MongoDBService Test Suite', () => { ['use("test");', 'db["test"].'].join('\n'), { line: 1, character: 11 } ); - const findCompletion = result.find((item: CompletionItem) => item.label === 'find'); + const findCompletion = result.find( + (item: CompletionItem) => item.label === 'find' + ); expect(findCompletion).to.have.property( 'kind', @@ -160,7 +177,9 @@ suite('MongoDBService Test Suite', () => { ["use('test');", "db['test']."].join('\n'), { line: 1, character: 11 } ); - const findCompletion = result.find((item: CompletionItem) => item.label === 'find'); + const findCompletion = result.find( + (item: CompletionItem) => item.label === 'find' + ); expect(findCompletion).to.have.property( 'kind', @@ -171,9 +190,11 @@ suite('MongoDBService Test Suite', () => { test('provide shell db methods completion with dot the same line', async () => { const result = await testMongoDBService.provideCompletionItems('db.', { line: 0, - character: 3 + character: 3, }); - const findCompletion = result.find((item: CompletionItem) => item.label === 'getCollectionNames'); + const findCompletion = result.find( + (item: CompletionItem) => item.label === 'getCollectionNames' + ); expect(findCompletion).to.have.property( 'kind', @@ -186,10 +207,12 @@ suite('MongoDBService Test Suite', () => { ['db', '.'].join('\n'), { line: 1, - character: 1 + character: 1, } ); - const findCompletion = result.find((item: CompletionItem) => item.label === 'getCollectionNames'); + const findCompletion = result.find( + (item: CompletionItem) => item.label === 'getCollectionNames' + ); expect(findCompletion).to.have.property( 'kind', @@ -200,9 +223,11 @@ suite('MongoDBService Test Suite', () => { test('provide shell db methods completion with dot after space', async () => { const result = await testMongoDBService.provideCompletionItems('db .', { line: 0, - character: 4 + character: 4, }); - const findCompletion = result.find((item: CompletionItem) => item.label === 'getCollectionNames'); + const findCompletion = result.find( + (item: CompletionItem) => item.label === 'getCollectionNames' + ); expect(findCompletion).to.have.property( 'kind', @@ -215,8 +240,12 @@ suite('MongoDBService Test Suite', () => { 'db.collection.aggregate().', { line: 0, character: 26 } ); - const aggCompletion = result.find((item: CompletionItem) => item.label === 'toArray'); - const findCompletion = result.find((item: CompletionItem) => item.label === 'allowPartialResults'); + const aggCompletion = result.find( + (item: CompletionItem) => item.label === 'toArray' + ); + const findCompletion = result.find( + (item: CompletionItem) => item.label === 'allowPartialResults' + ); expect(aggCompletion).to.have.property('kind', CompletionItemKind.Method); expect(findCompletion).to.be.undefined; @@ -227,7 +256,9 @@ suite('MongoDBService Test Suite', () => { 'db.collection.find().', { line: 0, character: 21 } ); - const findCompletion = result.find((item: CompletionItem) => item.label === 'allowPartialResults'); + const findCompletion = result.find( + (item: CompletionItem) => item.label === 'allowPartialResults' + ); expect(findCompletion).to.have.property( 'kind', @@ -242,7 +273,9 @@ suite('MongoDBService Test Suite', () => { ), { line: 2, character: 36 } ); - const findCompletion = result.find((item: CompletionItem) => item.label === 'allowPartialResults'); + const findCompletion = result.find( + (item: CompletionItem) => item.label === 'allowPartialResults' + ); expect(findCompletion).to.have.property( 'kind', @@ -257,11 +290,13 @@ suite('MongoDBService Test Suite', () => { '', 'const name = () => { db.companies.find({', ' blog_feed_url', - '}).}' + '}).}', ].join('\n'), { line: 4, character: 3 } ); - const findCompletion = result.find((item: CompletionItem) => item.label === 'allowPartialResults'); + const findCompletion = result.find( + (item: CompletionItem) => item.label === 'allowPartialResults' + ); expect(findCompletion).to.have.property( 'kind', @@ -273,15 +308,17 @@ suite('MongoDBService Test Suite', () => { testMongoDBService._updateCurrentSessionFields('test.collection', [ { label: 'JavaScript', - kind: CompletionItemKind.Field - } + kind: CompletionItemKind.Field, + }, ]); const result = await testMongoDBService.provideCompletionItems( 'use("test"); db.collection.find({ j});', { line: 0, character: 35 } ); - const findCompletion = result.find((item: CompletionItem) => item.label === 'JavaScript'); + const findCompletion = result.find( + (item: CompletionItem) => item.label === 'JavaScript' + ); expect(findCompletion).to.have.property('kind', CompletionItemKind.Field); }); @@ -290,15 +327,17 @@ suite('MongoDBService Test Suite', () => { testMongoDBService._updateCurrentSessionFields('test.collection', [ { label: 'JavaScript', - kind: CompletionItemKind.Field - } + kind: CompletionItemKind.Field, + }, ]); const result = await testMongoDBService.provideCompletionItems( 'use("test");db.collection.find({j});', { line: 0, character: 33 } ); - const findCompletion = result.find((item: CompletionItem) => item.label === 'JavaScript'); + const findCompletion = result.find( + (item: CompletionItem) => item.label === 'JavaScript' + ); expect(findCompletion).to.have.property('kind', CompletionItemKind.Field); }); @@ -307,8 +346,8 @@ suite('MongoDBService Test Suite', () => { testMongoDBService._updateCurrentSessionFields('test.collection', [ { label: 'JavaScript', - kind: CompletionItemKind.Field - } + kind: CompletionItemKind.Field, + }, ]); const result = await testMongoDBService.provideCompletionItems( @@ -316,11 +355,13 @@ suite('MongoDBService Test Suite', () => { 'use("test");', 'const name = () => {', ' db.collection.find({ j});', - '}' + '}', ].join('\n'), { line: 2, character: 24 } ); - const findCompletion = result.find((item: CompletionItem) => item.label === 'JavaScript'); + const findCompletion = result.find( + (item: CompletionItem) => item.label === 'JavaScript' + ); expect(findCompletion).to.have.property('kind', CompletionItemKind.Field); }); @@ -329,15 +370,17 @@ suite('MongoDBService Test Suite', () => { testMongoDBService._updateCurrentSessionFields('test.collection', [ { label: 'JavaScript', - kind: CompletionItemKind.Field - } + kind: CompletionItemKind.Field, + }, ]); const result = await testMongoDBService.provideCompletionItems( ['use("test");', '', 'db.collection.find({', ' j', '});'].join('\n'), { line: 3, character: 3 } ); - const findCompletion = result.find((item: CompletionItem) => item.label === 'JavaScript'); + const findCompletion = result.find( + (item: CompletionItem) => item.label === 'JavaScript' + ); expect(findCompletion).to.have.property('kind', CompletionItemKind.Field); }); @@ -346,15 +389,17 @@ suite('MongoDBService Test Suite', () => { testMongoDBService._updateCurrentSessionFields('test.collection', [ { label: 'JavaScript', - kind: CompletionItemKind.Field - } + kind: CompletionItemKind.Field, + }, ]); const result = await testMongoDBService.provideCompletionItems( 'use("test"); db.collection.find({ j });', { line: 0, character: 35 } ); - const findCompletion = result.find((item: CompletionItem) => item.label === 'JavaScript'); + const findCompletion = result.find( + (item: CompletionItem) => item.label === 'JavaScript' + ); expect(findCompletion).to.have.property('kind', CompletionItemKind.Field); }); @@ -363,14 +408,14 @@ suite('MongoDBService Test Suite', () => { testMongoDBService._updateCurrentSessionFields('test.collection', [ { label: 'JavaScript', - kind: CompletionItemKind.Field - } + kind: CompletionItemKind.Field, + }, ]); testMongoDBService._updateCurrentSessionFields('second.collection', [ { label: 'TypeScript', - kind: CompletionItemKind.Field - } + kind: CompletionItemKind.Field, + }, ]); const result = await testMongoDBService.provideCompletionItems( @@ -378,8 +423,12 @@ suite('MongoDBService Test Suite', () => { { line: 0, character: 51 } ); - const jsCompletion = result.find((item: CompletionItem) => item.label === 'JavaScript'); - const tsCompletion = result.find((item: CompletionItem) => item.label === 'TypeScript'); + const jsCompletion = result.find( + (item: CompletionItem) => item.label === 'JavaScript' + ); + const tsCompletion = result.find( + (item: CompletionItem) => item.label === 'TypeScript' + ); expect(jsCompletion).to.be.undefined; expect(tsCompletion).to.have.property('kind', CompletionItemKind.Field); @@ -389,15 +438,17 @@ suite('MongoDBService Test Suite', () => { testMongoDBService._updateCurrentSessionFields('test.collection', [ { label: 'JavaScript', - kind: CompletionItemKind.Field - } + kind: CompletionItemKind.Field, + }, ]); const result = await testMongoDBService.provideCompletionItems( 'use("test"); const name = () => { db.collection.find({ j}); }', { line: 0, character: 56 } ); - const findCompletion = result.find((item: CompletionItem) => item.label === 'JavaScript'); + const findCompletion = result.find( + (item: CompletionItem) => item.label === 'JavaScript' + ); expect(findCompletion).to.have.property('kind', CompletionItemKind.Field); }); @@ -406,15 +457,17 @@ suite('MongoDBService Test Suite', () => { testMongoDBService._updateCurrentSessionFields('test.collection', [ { label: 'JavaScript', - kind: CompletionItemKind.Field - } + kind: CompletionItemKind.Field, + }, ]); const result = await testMongoDBService.provideCompletionItems( 'use("test"); db.collection.aggregate([ { $match: { j} } ])', { line: 0, character: 52 } ); - const findCompletion = result.find((item: CompletionItem) => item.label === 'JavaScript'); + const findCompletion = result.find( + (item: CompletionItem) => item.label === 'JavaScript' + ); expect(findCompletion).to.have.property('kind', CompletionItemKind.Field); }); @@ -423,21 +476,23 @@ suite('MongoDBService Test Suite', () => { testMongoDBService._updateCurrentSessionFields('test.firstCollection', [ { label: 'JavaScript First', - kind: CompletionItemKind.Field - } + kind: CompletionItemKind.Field, + }, ]); testMongoDBService._updateCurrentSessionFields('test.secondCollection', [ { label: 'JavaScript Second', - kind: CompletionItemKind.Field - } + kind: CompletionItemKind.Field, + }, ]); const result = await testMongoDBService.provideCompletionItems( 'use("test"); db.firstCollection.find({ j});', { line: 0, character: 40 } ); - const findCompletion = result.find((item: CompletionItem) => item.label === 'JavaScript First'); + const findCompletion = result.find( + (item: CompletionItem) => item.label === 'JavaScript First' + ); expect(findCompletion).to.have.property('kind', CompletionItemKind.Field); }); @@ -446,15 +501,17 @@ suite('MongoDBService Test Suite', () => { testMongoDBService._updateCurrentSessionFields('test.collection', [ { label: 'JavaScript', - kind: CompletionItemKind.Field - } + kind: CompletionItemKind.Field, + }, ]); const result = await testMongoDBService.provideCompletionItems( 'db.collection.find({ j});', { line: 0, character: 22 } ); - const findCompletion = result.find((item: CompletionItem) => item.label === 'JavaScript'); + const findCompletion = result.find( + (item: CompletionItem) => item.label === 'JavaScript' + ); expect(findCompletion).to.be.undefined; }); @@ -463,15 +520,17 @@ suite('MongoDBService Test Suite', () => { testMongoDBService._updateCurrentSessionFields('test.collection', [ { label: 'JavaScript', - kind: CompletionItemKind.Field - } + kind: CompletionItemKind.Field, + }, ]); const result = await testMongoDBService.provideCompletionItems( 'use("test"); db.collection(j);', { line: 0, character: 28 } ); - const findCompletion = result.find((item: CompletionItem) => item.label === 'JavaScript'); + const findCompletion = result.find( + (item: CompletionItem) => item.label === 'JavaScript' + ); expect(findCompletion).to.be.undefined; }); @@ -480,8 +539,8 @@ suite('MongoDBService Test Suite', () => { testMongoDBService._updateCurrentSessionDatabases([ { label: 'admin', - kind: CompletionItemKind.Value - } + kind: CompletionItemKind.Value, + }, ]); const result = await testMongoDBService.provideCompletionItems( @@ -501,8 +560,8 @@ suite('MongoDBService Test Suite', () => { testMongoDBService._updateCurrentSessionDatabases([ { label: 'admin', - kind: CompletionItemKind.Value - } + kind: CompletionItemKind.Value, + }, ]); const result = await testMongoDBService.provideCompletionItems( @@ -522,8 +581,8 @@ suite('MongoDBService Test Suite', () => { testMongoDBService._updateCurrentSessionDatabases([ { label: 'admin', - kind: CompletionItemKind.Value - } + kind: CompletionItemKind.Value, + }, ]); const result = await testMongoDBService.provideCompletionItems( @@ -543,8 +602,8 @@ suite('MongoDBService Test Suite', () => { testMongoDBService._updateCurrentSessionDatabases([ { label: 'admin', - kind: CompletionItemKind.Value - } + kind: CompletionItemKind.Value, + }, ]); const result = await testMongoDBService.provideCompletionItems( @@ -562,14 +621,16 @@ suite('MongoDBService Test Suite', () => { test('provide collection names completion for valid object names', async () => { testMongoDBService._updateCurrentSessionCollections('test', [ - { name: 'empty' } + { name: 'empty' }, ]); const result = await testMongoDBService.provideCompletionItems( 'use("test"); db.', { line: 0, character: 16 } ); - const findCollectionCompletion = result.find((item: CompletionItem) => item.label === 'empty'); + const findCollectionCompletion = result.find( + (item: CompletionItem) => item.label === 'empty' + ); expect(findCollectionCompletion).to.have.property( 'kind', @@ -580,15 +641,17 @@ suite('MongoDBService Test Suite', () => { test('provide collection names completion for object names with dashes', async () => { testMongoDBService._updateCurrentSessionCollections('berlin', [ { - name: 'coll-name' - } + name: 'coll-name', + }, ]); const result = await testMongoDBService.provideCompletionItems( "use('berlin'); db.", { line: 0, character: 18 } ); - const findCollectionCompletion = result.find((item: CompletionItem) => item.label === 'coll-name'); + const findCollectionCompletion = result.find( + (item: CompletionItem) => item.label === 'coll-name' + ); expect(findCollectionCompletion).to.have.property( 'kind', @@ -602,14 +665,16 @@ suite('MongoDBService Test Suite', () => { test('provide collection names completion in variable declarations', async () => { testMongoDBService._updateCurrentSessionCollections('berlin', [ - { name: 'cocktailbars' } + { name: 'cocktailbars' }, ]); const result = await testMongoDBService.provideCompletionItems( ["use('berlin');", '', 'let a = db.'].join('\n'), { line: 2, character: 11 } ); - const findCollectionCompletion = result.find((item: CompletionItem) => item.label === 'cocktailbars'); + const findCollectionCompletion = result.find( + (item: CompletionItem) => item.label === 'cocktailbars' + ); expect(findCollectionCompletion).to.have.property( 'label', @@ -624,16 +689,20 @@ suite('MongoDBService Test Suite', () => { test('provide collection names and shell db symbol completion for db symbol', async () => { testMongoDBService._updateCurrentSessionCollections('berlin', [ { - name: 'coll-name' - } + name: 'coll-name', + }, ]); const result = await testMongoDBService.provideCompletionItems( "use('berlin'); db.", { line: 0, character: 18 } ); - const findCollectionCompletion = result.find((item: CompletionItem) => item.label === 'coll-name'); - const findShellCompletion = result.find((item: CompletionItem) => item.label === 'getCollectionNames'); + const findCollectionCompletion = result.find( + (item: CompletionItem) => item.label === 'coll-name' + ); + const findShellCompletion = result.find( + (item: CompletionItem) => item.label === 'getCollectionNames' + ); expect(findCollectionCompletion).to.have.property( 'kind', @@ -643,19 +712,15 @@ suite('MongoDBService Test Suite', () => { 'kind', CompletionItemKind.Method ); - expect(findShellCompletion).to.have.property( - 'documentation' - ); - expect(findShellCompletion).to.have.property( - 'detail' - ); + expect(findShellCompletion).to.have.property('documentation'); + expect(findShellCompletion).to.have.property('detail'); }); test('provide only collection names and shell db symbol completion after find cursor', async () => { testMongoDBService._updateCurrentSessionCollections('berlin', [ { - name: 'cocktailbars' - } + name: 'cocktailbars', + }, ]); const result = await testMongoDBService.provideCompletionItems( @@ -664,13 +729,19 @@ suite('MongoDBService Test Suite', () => { '', 'let a = db.cocktailbars.find({}).toArray();', '', - 'db.' + 'db.', ].join('\n'), { line: 4, character: 3 } ); - const findCollectionCompletion = result.find((item: CompletionItem) => item.label === 'cocktailbars'); - const findShellCompletion = result.find((item: CompletionItem) => item.label === 'getCollectionNames'); - const findCursorCompletion = result.find((item: CompletionItem) => item.label === 'toArray'); + const findCollectionCompletion = result.find( + (item: CompletionItem) => item.label === 'cocktailbars' + ); + const findShellCompletion = result.find( + (item: CompletionItem) => item.label === 'getCollectionNames' + ); + const findCursorCompletion = result.find( + (item: CompletionItem) => item.label === 'toArray' + ); expect(findCollectionCompletion).to.have.property( 'kind', @@ -680,20 +751,16 @@ suite('MongoDBService Test Suite', () => { 'kind', CompletionItemKind.Method ); - expect(findShellCompletion).to.have.property( - 'documentation' - ); - expect(findShellCompletion).to.have.property( - 'detail' - ); + expect(findShellCompletion).to.have.property('documentation'); + expect(findShellCompletion).to.have.property('detail'); expect(findCursorCompletion).to.be.undefined; }); test('provide only collection names and shell db symbol completion after aggregate cursor', async () => { testMongoDBService._updateCurrentSessionCollections('berlin', [ { - name: 'cocktailbars' - } + name: 'cocktailbars', + }, ]); const result = await testMongoDBService.provideCompletionItems( @@ -702,7 +769,7 @@ suite('MongoDBService Test Suite', () => { '', 'let a = db.cocktailbars.aggregate({}).toArray();', '', - 'db.' + 'db.', ].join('\n'), { line: 4, character: 3 } ); @@ -724,20 +791,16 @@ suite('MongoDBService Test Suite', () => { 'kind', CompletionItemKind.Method ); - expect(findShellCompletion).to.have.property( - 'documentation' - ); - expect(findShellCompletion).to.have.property( - 'detail' - ); + expect(findShellCompletion).to.have.property('documentation'); + expect(findShellCompletion).to.have.property('detail'); expect(findCursorCompletion).to.be.undefined; }); test('provide only collection names completion in the middle of expression', async () => { testMongoDBService._updateCurrentSessionCollections('berlin', [ { - name: 'cocktails' - } + name: 'cocktails', + }, ]); const result = await testMongoDBService.provideCompletionItems( @@ -765,8 +828,8 @@ suite('MongoDBService Test Suite', () => { test('provide collection names with dashes completion in the middle of expression', async () => { testMongoDBService._updateCurrentSessionCollections('berlin', [ { - name: 'coll-name' - } + name: 'coll-name', + }, ]); const result = await testMongoDBService.provideCompletionItems( @@ -785,8 +848,8 @@ suite('MongoDBService Test Suite', () => { test('provide collection names completion after single line comment', async () => { testMongoDBService._updateCurrentSessionCollections('test', [ { - name: 'collection' - } + name: 'collection', + }, ]); const result = await testMongoDBService.provideCompletionItems( @@ -807,8 +870,8 @@ suite('MongoDBService Test Suite', () => { test('provide collection names completion after single line comment with new line character', async () => { testMongoDBService._updateCurrentSessionCollections('test', [ { - name: 'collection' - } + name: 'collection', + }, ]); const result = await testMongoDBService.provideCompletionItems( @@ -829,8 +892,8 @@ suite('MongoDBService Test Suite', () => { test('provide collection names completion after multi-line comment', async () => { testMongoDBService._updateCurrentSessionCollections('test', [ { - name: 'collection' - } + name: 'collection', + }, ]); const result = await testMongoDBService.provideCompletionItems( @@ -851,8 +914,8 @@ suite('MongoDBService Test Suite', () => { test('provide collection names completion after end of line comment', async () => { testMongoDBService._updateCurrentSessionCollections('test', [ { - name: 'collection' - } + name: 'collection', + }, ]); const result = await testMongoDBService.provideCompletionItems( @@ -873,8 +936,8 @@ suite('MongoDBService Test Suite', () => { test('provide collection names completion at the same line block comment starts', async () => { testMongoDBService._updateCurrentSessionCollections('test', [ { - name: 'collection' - } + name: 'collection', + }, ]); const result = await testMongoDBService.provideCompletionItems( @@ -895,8 +958,8 @@ suite('MongoDBService Test Suite', () => { test('provide collection names completion at the same line block comment ends', async () => { testMongoDBService._updateCurrentSessionCollections('test', [ { - name: 'collection' - } + name: 'collection', + }, ]); const result = await testMongoDBService.provideCompletionItems( @@ -917,8 +980,8 @@ suite('MongoDBService Test Suite', () => { test('provide collection names completion at the same line with end line comment', async () => { testMongoDBService._updateCurrentSessionCollections('test', [ { - name: 'collection' - } + name: 'collection', + }, ]); const result = await testMongoDBService.provideCompletionItems( @@ -939,8 +1002,8 @@ suite('MongoDBService Test Suite', () => { test('provide collection names completion if code without a semicolon', async () => { testMongoDBService._updateCurrentSessionCollections('test', [ { - name: 'collection' - } + name: 'collection', + }, ]); const result = await testMongoDBService.provideCompletionItems( @@ -971,7 +1034,8 @@ suite('MongoDBService Test Suite', () => { const testMongoDBService = new MongoDBService(connection); before(async () => { - testMongoDBService._extensionPath = mdbTestExtension.testExtensionContext.extensionPath; + testMongoDBService._extensionPath = + mdbTestExtension.testExtensionContext.extensionPath; await testMongoDBService.connectToServiceProvider(params); }); @@ -980,13 +1044,18 @@ suite('MongoDBService Test Suite', () => { const result = await testMongoDBService.executeAll( { connectionId: 'pineapple', - codeToEvaluate: '1 + 1' + codeToEvaluate: '1 + 1', }, source.token ); const expectedResult = { outputLines: [], - result: { namespace: null, type: 'number', content: 2, language: 'plaintext' } + result: { + namespace: null, + type: 'number', + content: 2, + language: 'plaintext', + }, }; expect(result).to.deep.equal(expectedResult); @@ -997,7 +1066,7 @@ suite('MongoDBService Test Suite', () => { const result = await testMongoDBService.executeAll( { connectionId: 'not pineapple', - codeToEvaluate: '1 + 1' + codeToEvaluate: '1 + 1', }, source.token ); @@ -1010,13 +1079,18 @@ suite('MongoDBService Test Suite', () => { const result = await testMongoDBService.executeAll( { connectionId: 'pineapple', - codeToEvaluate: 'const x = 1; x + 2' + codeToEvaluate: 'const x = 1; x + 2', }, source.token ); const expectedResult = { outputLines: [], - result: { namespace: null, type: 'number', content: 3, language: 'plaintext' } + result: { + namespace: null, + type: 'number', + content: 3, + language: 'plaintext', + }, }; expect(result).to.deep.equal(expectedResult); @@ -1027,13 +1101,18 @@ suite('MongoDBService Test Suite', () => { const firstEvalResult = await testMongoDBService.executeAll( { connectionId: 'pineapple', - codeToEvaluate: 'const x = 1 + 1; x' + codeToEvaluate: 'const x = 1 + 1; x', }, source.token ); const firstRes = { outputLines: [], - result: { namespace: null, type: 'number', content: 2, language: 'plaintext' } + result: { + namespace: null, + type: 'number', + content: 2, + language: 'plaintext', + }, }; expect(firstEvalResult).to.deep.equal(firstRes); @@ -1041,13 +1120,18 @@ suite('MongoDBService Test Suite', () => { const secondEvalResult = await testMongoDBService.executeAll( { connectionId: 'pineapple', - codeToEvaluate: 'const x = 2 + 1; x' + codeToEvaluate: 'const x = 2 + 1; x', }, source.token ); const secondRes = { outputLines: [], - result: { namespace: null, type: 'number', content: 3, language: 'plaintext' } + result: { + namespace: null, + type: 'number', + content: 3, + language: 'plaintext', + }, }; expect(secondEvalResult).to.deep.equal(secondRes); @@ -1060,7 +1144,7 @@ suite('MongoDBService Test Suite', () => { connectionId: 'pineapple', codeToEvaluate: `const { ObjectId } = require('bson'); const x = { _id: new ObjectId('5fb292760ece2dc9c0362075') }; - x` + x`, }, source.token ); @@ -1071,11 +1155,11 @@ suite('MongoDBService Test Suite', () => { type: 'object', content: { _id: { - $oid: '5fb292760ece2dc9c0362075' - } + $oid: '5fb292760ece2dc9c0362075', + }, }, - language: 'json' - } + language: 'json', + }, }; expect(result).to.deep.equal(expectedResult); @@ -1087,7 +1171,7 @@ suite('MongoDBService Test Suite', () => { { connectionId: 'pineapple', codeToEvaluate: `const obj = { name: "a short string" }; - obj` + obj`, }, source.token ); @@ -1097,10 +1181,10 @@ suite('MongoDBService Test Suite', () => { namespace: null, type: 'object', content: { - name: 'a short string' + name: 'a short string', }, - language: 'json' - } + language: 'json', + }, }; expect(result).to.deep.equal(expectedResult); @@ -1112,7 +1196,7 @@ suite('MongoDBService Test Suite', () => { { connectionId: 'pineapple', codeToEvaluate: `const arr = [{ name: "a short string" }]; - arr` + arr`, }, source.token ); @@ -1121,11 +1205,13 @@ suite('MongoDBService Test Suite', () => { result: { namespace: null, type: 'object', - content: [{ - name: 'a short string' - }], - language: 'json' - } + content: [ + { + name: 'a short string', + }, + ], + language: 'json', + }, }; expect(result).to.deep.equal(expectedResult); @@ -1136,7 +1222,7 @@ suite('MongoDBService Test Suite', () => { const result = await testMongoDBService.executeAll( { connectionId: 'pineapple', - codeToEvaluate: 'undefined' + codeToEvaluate: 'undefined', }, source.token ); @@ -1146,8 +1232,8 @@ suite('MongoDBService Test Suite', () => { namespace: null, type: 'undefined', content: undefined, - language: 'plaintext' - } + language: 'plaintext', + }, }; expect(result).to.deep.equal(expectedResult); @@ -1158,7 +1244,7 @@ suite('MongoDBService Test Suite', () => { const result = await testMongoDBService.executeAll( { connectionId: 'pineapple', - codeToEvaluate: 'null' + codeToEvaluate: 'null', }, source.token ); @@ -1168,8 +1254,8 @@ suite('MongoDBService Test Suite', () => { namespace: null, type: 'object', content: null, - language: 'plaintext' - } + language: 'plaintext', + }, }; expect(result).to.deep.equal(expectedResult); @@ -1181,7 +1267,7 @@ suite('MongoDBService Test Suite', () => { { connectionId: 'pineapple', codeToEvaluate: `const x = 'A single line string'; - x` + x`, }, source.token ); @@ -1191,8 +1277,8 @@ suite('MongoDBService Test Suite', () => { namespace: null, type: 'string', content: 'A single line string', - language: 'plaintext' - } + language: 'plaintext', + }, }; expect(result).to.deep.equal(expectedResult); @@ -1206,7 +1292,7 @@ suite('MongoDBService Test Suite', () => { codeToEvaluate: `const x = \`vscode is awesome\`; - x` + x`, }, source.token ); @@ -1218,8 +1304,8 @@ suite('MongoDBService Test Suite', () => { content: `vscode is awesome`, - language: 'plaintext' - } + language: 'plaintext', + }, }; expect(result).to.deep.equal(expectedResult); @@ -1230,7 +1316,7 @@ suite('MongoDBService Test Suite', () => { const result = await testMongoDBService.executeAll( { connectionId: 'pineapple', - codeToEvaluate: 'print("Hello"); console.log(1,2,3); 42' + codeToEvaluate: 'print("Hello"); console.log(1,2,3); 42', }, source.token ); @@ -1239,9 +1325,14 @@ suite('MongoDBService Test Suite', () => { { namespace: null, type: null, content: 'Hello', language: null }, { namespace: null, type: null, content: 1, language: null }, { namespace: null, type: null, content: 2, language: null }, - { namespace: null, type: null, content: 3, language: null } + { namespace: null, type: null, content: 3, language: null }, ], - result: { namespace: null, type: 'number', content: 42, language: 'plaintext' } + result: { + namespace: null, + type: 'number', + content: 42, + language: 'plaintext', + }, }; expect(result).to.deep.equal(expectedResult); @@ -1272,57 +1363,60 @@ suite('MongoDBService Test Suite', () => { ]);`; const selection = { start: { line: 0, character: 0 }, - end: { line: 9, character: 3 } + end: { line: 9, character: 3 }, } as vscode.Selection; const mode = testMongoDBService.getExportToLanguageMode({ textFromEditor, - selection + selection, }); expect(mode).to.be.equal('OTHER'); }); test('returns query for an object', () => { - const textFromEditor = "db.sales.insertMany([{ '_id': 1, 'item': 'abc', 'price': 10, 'quantity': 2, 'date': new Date('2014-03-01T08:00:00Z') }]);"; + const textFromEditor = + "db.sales.insertMany([{ '_id': 1, 'item': 'abc', 'price': 10, 'quantity': 2, 'date': new Date('2014-03-01T08:00:00Z') }]);"; const selection = { start: { line: 0, character: 21 }, - end: { line: 0, character: 118 } + end: { line: 0, character: 118 }, } as vscode.Selection; const mode = testMongoDBService.getExportToLanguageMode({ textFromEditor, - selection + selection, }); expect(mode).to.be.equal('QUERY'); }); test('returns aggregation for an array as function argument', () => { - const textFromEditor = "db.sales.insertMany([{ '_id': 1, 'item': 'abc', 'price': 10, 'quantity': 2, 'date': new Date('2014-03-01T08:00:00Z') }]);"; + const textFromEditor = + "db.sales.insertMany([{ '_id': 1, 'item': 'abc', 'price': 10, 'quantity': 2, 'date': new Date('2014-03-01T08:00:00Z') }]);"; const selection = { start: { line: 0, character: 20 }, - end: { line: 0, character: 119 } + end: { line: 0, character: 119 }, } as vscode.Selection; const mode = testMongoDBService.getExportToLanguageMode({ textFromEditor, - selection + selection, }); expect(mode).to.be.equal('AGGREGATION'); }); test('returns query for an object as function argument', () => { - const textFromEditor = "db.sales.insertMany({ '_id': 1, 'item': 'abc' });"; + const textFromEditor = + "db.sales.insertMany({ '_id': 1, 'item': 'abc' });"; const selection = { start: { line: 0, character: 20 }, - end: { line: 0, character: 47 } + end: { line: 0, character: 47 }, } as vscode.Selection; const mode = testMongoDBService.getExportToLanguageMode({ textFromEditor, - selection + selection, }); expect(mode).to.be.equal('QUERY'); @@ -1332,12 +1426,12 @@ suite('MongoDBService Test Suite', () => { const textFromEditor = "const arr = [{ '_id': 1, 'item': 'abc' }];"; const selection = { start: { line: 0, character: 12 }, - end: { line: 0, character: 41 } + end: { line: 0, character: 41 }, } as vscode.Selection; const mode = testMongoDBService.getExportToLanguageMode({ textFromEditor, - selection + selection, }); expect(mode).to.be.equal('AGGREGATION'); @@ -1347,12 +1441,12 @@ suite('MongoDBService Test Suite', () => { const textFromEditor = "const obj = { '_id': 1 };"; const selection = { start: { line: 0, character: 12 }, - end: { line: 0, character: 24 } + end: { line: 0, character: 24 }, } as vscode.Selection; const mode = testMongoDBService.getExportToLanguageMode({ textFromEditor, - selection + selection, }); expect(mode).to.be.equal('QUERY'); @@ -1362,27 +1456,28 @@ suite('MongoDBService Test Suite', () => { const textFromEditor = "const arr = [{ '_id': 1, 'item': 'abc' }];"; const selection = { start: { line: 0, character: 0 }, - end: { line: 0, character: 42 } + end: { line: 0, character: 42 }, } as vscode.Selection; const mode = testMongoDBService.getExportToLanguageMode({ textFromEditor, - selection + selection, }); expect(mode).to.be.equal('OTHER'); }); test('returns query for an object used as another object property', () => { - const textFromEditor = "const obj = { prop: { '_id': 1, 'item': 'abc' } };"; + const textFromEditor = + "const obj = { prop: { '_id': 1, 'item': 'abc' } };"; const selection = { start: { line: 0, character: 20 }, - end: { line: 0, character: 47 } + end: { line: 0, character: 47 }, } as vscode.Selection; const mode = testMongoDBService.getExportToLanguageMode({ textFromEditor, - selection + selection, }); expect(mode).to.be.equal('QUERY'); @@ -1392,12 +1487,12 @@ suite('MongoDBService Test Suite', () => { const textFromEditor = 'const arr = [[]];'; const selection = { start: { line: 0, character: 13 }, - end: { line: 0, character: 15 } + end: { line: 0, character: 15 }, } as vscode.Selection; const mode = testMongoDBService.getExportToLanguageMode({ textFromEditor, - selection + selection, }); expect(mode).to.be.equal('AGGREGATION'); diff --git a/src/test/suite/mdbExtensionController.test.ts b/src/test/suite/mdbExtensionController.test.ts index 3ac0f01c..62d6ff6e 100644 --- a/src/test/suite/mdbExtensionController.test.ts +++ b/src/test/suite/mdbExtensionController.test.ts @@ -12,7 +12,7 @@ import { ConnectionTreeItem, DatabaseTreeItem, DocumentTreeItem, - SchemaTreeItem + SchemaTreeItem, } from '../../explorer'; import EXTENSION_COMMANDS from '../../commands'; import FieldTreeItem from '../../explorer/fieldTreeItem'; @@ -21,7 +21,7 @@ import { mdbTestExtension } from './stubbableMdbExtension'; import { mockTextEditor } from './stubs'; import { StorageLocation, - StorageVariables + StorageVariables, } from '../../storage/storageController'; import { VIEW_COLLECTION_SCHEME } from '../../editors/collectionDocumentsProvider'; @@ -58,7 +58,7 @@ suite('MDBExtensionController Test Suite', function () { const textCollectionTree = new CollectionTreeItem( { name: 'testColName', - type: CollectionTypes.collection + type: CollectionTypes.collection, }, 'testDbName', {}, @@ -101,7 +101,7 @@ suite('MDBExtensionController Test Suite', function () { const textCollectionTree = new CollectionTreeItem( { name: 'testColName', - type: CollectionTypes.collection + type: CollectionTypes.collection, }, 'testDbName', {}, @@ -250,7 +250,10 @@ suite('MDBExtensionController Test Suite', function () { ); const mockCopyToClipboard: any = sinon.fake(); - sinon.replaceGetter(vscode.env, 'clipboard', () => ({ writeText: mockCopyToClipboard, readText: sinon.fake() as any })); + sinon.replaceGetter(vscode.env, 'clipboard', () => ({ + writeText: mockCopyToClipboard, + readText: sinon.fake() as any, + })); const mockStubUri: any = sinon.fake.returns('weStubThisUri'); sinon.replace( @@ -284,7 +287,10 @@ suite('MDBExtensionController Test Suite', function () { ); const mockCopyToClipboard: any = sinon.fake(); - sinon.replaceGetter(vscode.env, 'clipboard', () => ({ writeText: mockCopyToClipboard, readText: sinon.fake() as any })); + sinon.replaceGetter(vscode.env, 'clipboard', () => ({ + writeText: mockCopyToClipboard, + readText: sinon.fake() as any, + })); vscode.commands .executeCommand('mdb.copyDatabaseName', mockTreeItem) @@ -305,7 +311,7 @@ suite('MDBExtensionController Test Suite', function () { const mockTreeItem = new CollectionTreeItem( { name: 'waterBuffalo', - type: CollectionTypes.collection + type: CollectionTypes.collection, }, 'airZebra', {}, @@ -315,7 +321,10 @@ suite('MDBExtensionController Test Suite', function () { ); const mockCopyToClipboard: any = sinon.fake(); - sinon.replaceGetter(vscode.env, 'clipboard', () => ({ writeText: mockCopyToClipboard, readText: sinon.fake() as any })); + sinon.replaceGetter(vscode.env, 'clipboard', () => ({ + writeText: mockCopyToClipboard, + readText: sinon.fake() as any, + })); vscode.commands .executeCommand('mdb.copyCollectionName', mockTreeItem) @@ -338,14 +347,17 @@ suite('MDBExtensionController Test Suite', function () { name: 'dolphins are sentient', probability: 1, type: 'String', - types: [] + types: [], }, false, {} ); const mockCopyToClipboard: any = sinon.fake(); - sinon.replaceGetter(vscode.env, 'clipboard', () => ({ writeText: mockCopyToClipboard, readText: sinon.fake() as any })); + sinon.replaceGetter(vscode.env, 'clipboard', () => ({ + writeText: mockCopyToClipboard, + readText: sinon.fake() as any, + })); const commandResult = await vscode.commands.executeCommand( 'mdb.copySchemaFieldName', @@ -400,7 +412,7 @@ suite('MDBExtensionController Test Suite', function () { const mockTreeItem = new CollectionTreeItem( { name: 'iSawACatThatLookedLikeALionToday', - type: CollectionTypes.collection + type: CollectionTypes.collection, }, 'airZebra', {}, @@ -442,7 +454,7 @@ suite('MDBExtensionController Test Suite', function () { const mockTreeItem = new CollectionTreeItem( { name: 'iSawACatThatLookedLikeALionToday', - type: CollectionTypes.collection + type: CollectionTypes.collection, }, 'airZebra', { estimatedCount: (ns, opts, cb): void => cb(null, count) }, @@ -614,7 +626,9 @@ suite('MDBExtensionController Test Suite', function () { ) ); assert(mockOpenTextDocument.firstArg.content.includes('NEW_DATABASE_NAME')); - assert(mockOpenTextDocument.firstArg.content.includes('NEW_COLLECTION_NAME')); + assert( + mockOpenTextDocument.firstArg.content.includes('NEW_COLLECTION_NAME') + ); }); test('mdb.addDatabase command fails when disconnecting', (done) => { @@ -744,7 +758,9 @@ suite('MDBExtensionController Test Suite', function () { ) ); assert(mockOpenTextDocument.firstArg.content.includes('iceCreamDB')); - assert(mockOpenTextDocument.firstArg.content.includes('NEW_COLLECTION_NAME')); + assert( + mockOpenTextDocument.firstArg.content.includes('NEW_COLLECTION_NAME') + ); assert(!mockOpenTextDocument.firstArg.content.includes('time-series')); }); @@ -799,7 +815,7 @@ suite('MDBExtensionController Test Suite', function () { dropCollection: (namespace, callback): void => { calledNamespace = namespace; callback(null, true); - } + }, }, false, false, @@ -924,7 +940,7 @@ suite('MDBExtensionController Test Suite', function () { dropDatabase: (dbName, callback): void => { calledDatabaseName = dbName; callback(null, true); - } + }, }, false, false, @@ -1035,12 +1051,13 @@ suite('MDBExtensionController Test Suite', function () { }); test('mdb.renameConnection fails when the name input is empty', (done) => { - mdbTestExtension.testExtensionController._connectionController._connections.blueBerryPancakesAndTheSmellOfBacon = { - id: 'blueBerryPancakesAndTheSmellOfBacon', - connectionOptions: { connectionString: 'mongodb://localhost' }, - name: 'NAAAME', - storageLocation: StorageLocation.NONE - }; + mdbTestExtension.testExtensionController._connectionController._connections.blueBerryPancakesAndTheSmellOfBacon = + { + id: 'blueBerryPancakesAndTheSmellOfBacon', + connectionOptions: { connectionString: 'mongodb://localhost' }, + name: 'NAAAME', + storageLocation: StorageLocation.NONE, + }; const mockTreeItem = new ConnectionTreeItem( 'blueBerryPancakesAndTheSmellOfBacon', @@ -1073,12 +1090,13 @@ suite('MDBExtensionController Test Suite', function () { }); test('mdb.renameConnection updates the name of a connection', (done) => { - mdbTestExtension.testExtensionController._connectionController._connections.blueBerryPancakesAndTheSmellOfBacon = { - id: 'blueBerryPancakesAndTheSmellOfBacon', - name: 'NAAAME', - connectionOptions: { connectionString: 'mongodb://localhost' }, - storageLocation: StorageLocation.NONE - }; + mdbTestExtension.testExtensionController._connectionController._connections.blueBerryPancakesAndTheSmellOfBacon = + { + id: 'blueBerryPancakesAndTheSmellOfBacon', + name: 'NAAAME', + connectionOptions: { connectionString: 'mongodb://localhost' }, + storageLocation: StorageLocation.NONE, + }; const mockTreeItem = new ConnectionTreeItem( 'blueBerryPancakesAndTheSmellOfBacon', @@ -1113,8 +1131,8 @@ suite('MDBExtensionController Test Suite', function () { _id: 'pancakes', name: '', time: { - $time: '12345' - } + $time: '12345', + }, }; const mockOpenTextDocument: any = sinon.fake.resolves('magna carta'); @@ -1132,16 +1150,22 @@ suite('MDBExtensionController Test Suite', function () { ); const activeTextEditor = mockTextEditor; - activeTextEditor.document.uri = vscode.Uri.parse([ - 'VIEW_DOCUMENT_SCHEME:/', - 'waffle.house:pancakes.json?', - 'namespace=waffle.house&', - 'connectionId=tasty_sandwhich&', - 'documentId=93333a0d-83f6-4e6f-a575-af7ea6187a4a&', - 'source=treeview' - ].join('')); + activeTextEditor.document.uri = vscode.Uri.parse( + [ + 'VIEW_DOCUMENT_SCHEME:/', + 'waffle.house:pancakes.json?', + 'namespace=waffle.house&', + 'connectionId=tasty_sandwhich&', + 'documentId=93333a0d-83f6-4e6f-a575-af7ea6187a4a&', + 'source=treeview', + ].join('') + ); activeTextEditor.document.getText = () => JSON.stringify(mockDocument); - sandbox.replaceGetter(vscode.window, 'activeTextEditor', () => activeTextEditor); + sandbox.replaceGetter( + vscode.window, + 'activeTextEditor', + () => activeTextEditor + ); const mockActiveConnectionId: any = sinon.fake.returns('tasty_sandwhich'); sinon.replace( @@ -1169,7 +1193,7 @@ suite('MDBExtensionController Test Suite', function () { mockDocument.name = 'something sweet'; return callback(null, mockDocument); - } + }, }); sinon.replace( mdbTestExtension.testExtensionController._connectionController, @@ -1216,14 +1240,15 @@ suite('MDBExtensionController Test Suite', function () { _id: 'pancakes', name: '', time: { - $time: '12345' - } + $time: '12345', + }, }; const documentItem = new DocumentTreeItem(mockDocument, 'waffle.house', 0); const mockFetchDocument: any = sinon.fake.resolves(null); sinon.replace( - mdbTestExtension.testExtensionController._editorsController._mongoDBDocumentService, + mdbTestExtension.testExtensionController._editorsController + ._mongoDBDocumentService, 'fetchDocument', mockFetchDocument ); @@ -1242,12 +1267,13 @@ suite('MDBExtensionController Test Suite', function () { line: 1, documentId: '93333a0d-83f6-4e6f-a575-af7ea6187a4a', namespace: 'db.coll', - connectionId: null + connectionId: null, }; const mockFetchDocument: any = sinon.fake.resolves(null); sinon.replace( - mdbTestExtension.testExtensionController._editorsController._mongoDBDocumentService, + mdbTestExtension.testExtensionController._editorsController + ._mongoDBDocumentService, 'fetchDocument', mockFetchDocument ); @@ -1265,8 +1291,8 @@ suite('MDBExtensionController Test Suite', function () { _id: 'pancakes', name: '', time: { - $time: '12345' - } + $time: '12345', + }, }; const mockShowTextDocument: any = sinon.fake(); @@ -1288,17 +1314,18 @@ suite('MDBExtensionController Test Suite', function () { 'namespace=waffle.house', 'connectionId=tasty_sandwhich', 'documentId=93333a0d-83f6-4e6f-a575-af7ea6187a4a', - 'source=treeview' - ].join('&') + 'source=treeview', + ].join('&'), }, getText: () => JSON.stringify(mockDocument), - save: () => {} - } + save: () => {}, + }, })); const mockReplaceDocument: any = sinon.fake.resolves(null); sinon.replace( - mdbTestExtension.testExtensionController._editorsController._mongoDBDocumentService, + mdbTestExtension.testExtensionController._editorsController + ._mongoDBDocumentService, 'replaceDocument', mockReplaceDocument ); @@ -1313,8 +1340,8 @@ suite('MDBExtensionController Test Suite', function () { _id: 'pancakes', name: '', time: { - $time: '12345' - } + $time: '12345', + }, }; const mockShowTextDocument: any = sinon.fake(); @@ -1336,17 +1363,18 @@ suite('MDBExtensionController Test Suite', function () { 'namespace=waffle.house', 'connectionId=tasty_sandwhich', 'documentId=93333a0d-83f6-4e6f-a575-af7ea6187a4a', - 'source=playground' - ].join('&') + 'source=playground', + ].join('&'), }, getText: () => JSON.stringify(mockDocument), - save: () => {} - } + save: () => {}, + }, })); const mockReplaceDocument: any = sinon.fake.resolves(null); sinon.replace( - mdbTestExtension.testExtensionController._editorsController._mongoDBDocumentService, + mdbTestExtension.testExtensionController._editorsController + ._mongoDBDocumentService, 'replaceDocument', mockReplaceDocument ); @@ -1365,7 +1393,7 @@ suite('MDBExtensionController Test Suite', function () { await vscode.commands.executeCommand('mdb.searchForDocuments', { databaseName: 'dbbbbbName', - collectionName: 'colllllllllName' + collectionName: 'colllllllllName', }); assert(mockOpenTextDocument.firstArg.language === 'mongodb'); @@ -1391,7 +1419,7 @@ suite('MDBExtensionController Test Suite', function () { await vscode.commands.executeCommand('mdb.createIndexFromTreeView', { databaseName: 'dbbbbbName', - collectionName: 'colllllllllName' + collectionName: 'colllllllllName', }); assert(mockOpenTextDocument.firstArg.language === 'mongodb'); @@ -1416,7 +1444,7 @@ suite('MDBExtensionController Test Suite', function () { sinon.replace(vscode.window, 'showTextDocument', mockShowTextDocument); const mockGetConfiguration: any = sinon.fake.returns({ - get: () => true + get: () => true, }); sinon.replace(vscode.workspace, 'getConfiguration', mockGetConfiguration); @@ -1459,7 +1487,7 @@ suite('MDBExtensionController Test Suite', function () { sinon.replace(vscode.window, 'showTextDocument', mockShowTextDocument); const mockGetConfiguration: any = sinon.fake.returns({ - get: () => false + get: () => false, }); sinon.replace(vscode.workspace, 'getConfiguration', mockGetConfiguration); diff --git a/src/test/suite/storage/storageController.test.ts b/src/test/suite/storage/storageController.test.ts index 9557af2e..395bcedd 100644 --- a/src/test/suite/storage/storageController.test.ts +++ b/src/test/suite/storage/storageController.test.ts @@ -4,7 +4,7 @@ import { v4 as uuidv4 } from 'uuid'; import StorageController, { StorageVariables, - StorageLocation + StorageLocation, } from '../../../storage/storageController'; import { TestExtensionContext } from '../stubs'; @@ -13,8 +13,8 @@ suite('Storage Controller Test Suite', () => { const testExtensionContext = new TestExtensionContext(); testExtensionContext._globalState = { [StorageVariables.GLOBAL_SAVED_CONNECTIONS]: { - 'collOne': { name: 'this_gonna_get_saved' } - } + collOne: { name: 'this_gonna_get_saved' }, + }, }; const testStorageController = new StorageController(testExtensionContext); const testVal = testStorageController.get( @@ -31,8 +31,8 @@ suite('Storage Controller Test Suite', () => { const testExtensionContext = new TestExtensionContext(); testExtensionContext._workspaceState = { [StorageVariables.WORKSPACE_SAVED_CONNECTIONS]: { - 'collTwo': { name: 'i_cant_believe_its_gonna_save_this' } - } + collTwo: { name: 'i_cant_believe_its_gonna_save_this' }, + }, }; const testStorageController = new StorageController(testExtensionContext); const testVal = testStorageController.get( @@ -53,16 +53,16 @@ suite('Storage Controller Test Suite', () => { id: 'conn1', name: 'saved1', storageLocation: StorageLocation.GLOBAL, - connectionOptions: { connectionString: 'mongodb://localhost' } - } - } + connectionOptions: { connectionString: 'mongodb://localhost' }, + }, + }, }; const testStorageController = new StorageController(testExtensionContext); void testStorageController.saveConnectionToStore({ id: 'conn2', name: 'saved2', storageLocation: StorageLocation.GLOBAL, - connectionOptions: { connectionString: 'mongodb://localhost' } + connectionOptions: { connectionString: 'mongodb://localhost' }, }); const updatedGlobalModels = testStorageController.get( @@ -71,7 +71,8 @@ suite('Storage Controller Test Suite', () => { ); assert( Object.keys(updatedGlobalModels).length === 2, - `Expected 2 connections, found ${Object.keys(updatedGlobalModels).length + `Expected 2 connections, found ${ + Object.keys(updatedGlobalModels).length }.` ); assert( @@ -93,16 +94,16 @@ suite('Storage Controller Test Suite', () => { id: 'conn1', name: 'saved1', storageLocation: StorageLocation.WORKSPACE, - connectionOptions: { connectionString: 'mongodb://localhost' } - } - } + connectionOptions: { connectionString: 'mongodb://localhost' }, + }, + }, }; const testStorageController = new StorageController(testExtensionContext); void testStorageController.saveConnectionToStore({ id: 'conn2', name: 'saved2', storageLocation: StorageLocation.WORKSPACE, - connectionOptions: { connectionString: 'mongodb://localhost:27018' } + connectionOptions: { connectionString: 'mongodb://localhost:27018' }, }); const updatedWorkspaceModels = testStorageController.get( @@ -111,7 +112,8 @@ suite('Storage Controller Test Suite', () => { ); assert( Object.keys(updatedWorkspaceModels).length === 2, - `Expected 2 connections, found ${Object.keys(updatedWorkspaceModels).length + `Expected 2 connections, found ${ + Object.keys(updatedWorkspaceModels).length }.` ); assert( @@ -124,7 +126,7 @@ suite('Storage Controller Test Suite', () => { ); assert( updatedWorkspaceModels.conn2.storageLocation === - StorageLocation.WORKSPACE, + StorageLocation.WORKSPACE, 'Expected storage scope to be set.' ); }); @@ -136,7 +138,9 @@ 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); + const anonymousId = testStorageController.get( + StorageVariables.GLOBAL_ANONYMOUS_ID + ); const userId = testStorageController.get(StorageVariables.GLOBAL_USER_ID); assert.deepStrictEqual(userIdentity, { anonymousId }); assert(!userId); @@ -159,7 +163,9 @@ suite('Storage Controller Test Suite', () => { test('getUserIdentity returns userId from the global storage and returns it to telemetry', () => { const userIdentity = testStorageController.getUserIdentity(); - const anonymousId = testStorageController.get(StorageVariables.GLOBAL_ANONYMOUS_ID); + const anonymousId = testStorageController.get( + StorageVariables.GLOBAL_ANONYMOUS_ID + ); const userId = testStorageController.get(StorageVariables.GLOBAL_USER_ID); assert(userId === id); assert.deepStrictEqual(userIdentity, { userId }); @@ -173,9 +179,9 @@ suite('Storage Controller Test Suite', () => { [StorageVariables.WORKSPACE_SAVED_CONNECTIONS]: { conn1: { id: 'conn1', - name: 'saved1' - } - } + name: 'saved1', + }, + }, }; const testStorageController = new StorageController(testExtensionContext); assert(testStorageController.hasSavedConnections()); @@ -187,9 +193,9 @@ suite('Storage Controller Test Suite', () => { [StorageVariables.GLOBAL_SAVED_CONNECTIONS]: { conn1: { id: 'conn1', - name: 'saved1' - } - } + name: 'saved1', + }, + }, }; const testStorageController = new StorageController(testExtensionContext); assert(testStorageController.hasSavedConnections()); diff --git a/src/test/suite/stubs.ts b/src/test/suite/stubs.ts index 330f5cb9..a861464d 100644 --- a/src/test/suite/stubs.ts +++ b/src/test/suite/stubs.ts @@ -5,7 +5,11 @@ import path = require('path'); import { StorageController } from '../../storage'; -import { ShellExecuteAllResult, ExportToLanguageMode, ExportToLanguageNamespace } from '../../types/playgroundType'; +import { + ShellExecuteAllResult, + ExportToLanguageMode, + ExportToLanguageNamespace, +} from '../../types/playgroundType'; // Bare mock of the extension context for vscode. class TestExtensionContext implements vscode.ExtensionContext { @@ -48,7 +52,7 @@ class TestExtensionContext implements vscode.ExtensionContext { return new Promise(() => { this._workspaceState[key] = value; }); - } + }, }; this.globalState = { keys: (): readonly string[] => { @@ -62,7 +66,7 @@ class TestExtensionContext implements vscode.ExtensionContext { this._globalState[key] = value; }); }, - setKeysForSync: (/* keys: string[] */): void => { } + setKeysForSync: (/* keys: string[] */): void => {}, }; this.extensionPath = path.join(__dirname, '..', '..', '..'); this.storagePath = ''; @@ -74,70 +78,70 @@ const mockDatabases = { databaseName: 'mockDatabase1', collections: [ { - name: 'mock_db_1_collection_1' + name: 'mock_db_1_collection_1', }, { - name: 'mock_db_1_collection_2' - } - ] + name: 'mock_db_1_collection_2', + }, + ], }, mockDatabase2: { databaseName: 'mockDatabase2', collections: [ { - name: 'mock_db_2_collection_1' + name: 'mock_db_2_collection_1', }, { - name: 'mock_db_2_collection_2' - } - ] + name: 'mock_db_2_collection_2', + }, + ], }, mockDatabase3: { databaseName: 'mockDatabase3', collections: [ { - name: 'ZZZ' + name: 'ZZZ', }, { - name: 'AAA' + name: 'AAA', }, { - name: '111_abc' + name: '111_abc', }, { - name: '222_abc' + name: '222_abc', }, { - name: 'zzz' + name: 'zzz', }, { - name: 'aaa' + name: 'aaa', }, { - name: 'system.views' + name: 'system.views', }, { - name: 'system.buckets.zzz' + name: 'system.buckets.zzz', }, { - name: 'system.buckets.aaa' - } - ] - } + name: 'system.buckets.aaa', + }, + ], + }, }; const mockDatabaseNames = Object.keys(mockDatabases); const mockDocuments: any[] = []; const numberOfDocumentsToMock = 25; for (let i = 0; i < numberOfDocumentsToMock; i++) { mockDocuments.push({ - _id: `mock_document_${i}` + _id: `mock_document_${i}`, }); } class DataServiceStub { listDatabases(): Promise { return new Promise((resolve) => { - resolve(mockDatabaseNames.map(dbName => ({ name: dbName }))); + resolve(mockDatabaseNames.map((dbName) => ({ name: dbName }))); }); } @@ -166,7 +170,7 @@ const mockTextLine = { range: mockRange, rangeIncludingLineBreak: mockRange, firstNonWhitespaceCharacterIndex: 0, - isEmptyOrWhitespace: false + isEmptyOrWhitespace: false, }; const mockVSCodeTextDocument = { @@ -192,7 +196,7 @@ const mockVSCodeTextDocument = { undefined, validateRange: (/* range: vscode.Range */): vscode.Range => mockRange, validatePosition: (/* position: vscode.Position */): vscode.Position => - mockPosition + mockPosition, }; const mockSelection = new vscode.Selection( @@ -209,15 +213,15 @@ const mockTextEditor = { tabSize: '', insertSpaces: '', cursorStyle: vscode.TextEditorCursorStyle.Line, - lineNumbers: vscode.TextEditorLineNumbersStyle.Off + lineNumbers: vscode.TextEditorLineNumbersStyle.Off, }, viewColumn: vscode.ViewColumn.Beside, edit: () => Promise.resolve(true), insertSnippet: () => Promise.resolve(true), - setDecorations: () => { }, - revealRange: () => { }, - show: () => { }, - hide: () => { } + setDecorations: () => {}, + revealRange: () => {}, + show: () => {}, + hide: () => {}, }; class MockLanguageServerController { @@ -248,7 +252,12 @@ class MockLanguageServerController { executeAll(/* codeToEvaluate: string */): Promise { return Promise.resolve({ outputLines: [], - result: { namespace: null, type: null, content: 'Result', language: 'plaintext' } + result: { + namespace: null, + type: null, + content: 'Result', + language: 'plaintext', + }, }); } @@ -283,7 +292,7 @@ class TestStream extends Duplex { done(); } - _read() { } + _read() {} } export { @@ -296,5 +305,5 @@ export { DataServiceStub, TestExtensionContext, MockLanguageServerController, - TestStream + TestStream, }; diff --git a/src/test/suite/telemetry/connectionTelemetry.test.ts b/src/test/suite/telemetry/connectionTelemetry.test.ts index e8c4bd00..af3bd5a6 100644 --- a/src/test/suite/telemetry/connectionTelemetry.test.ts +++ b/src/test/suite/telemetry/connectionTelemetry.test.ts @@ -4,10 +4,7 @@ import { expect } from 'chai'; import sinon from 'sinon'; import { ConnectionTypes } from '../../../connectionController'; -import { - getConnectionTelemetryProperties -} from '../../../telemetry/connectionTelemetry'; - +import { getConnectionTelemetryProperties } from '../../../telemetry/connectionTelemetry'; const TEST_DATABASE_URI = 'mongodb://localhost:27018'; @@ -19,14 +16,15 @@ suite('ConnectionTelemetry Controller Test Suite', function () { getConnectionString: () => ({ hosts: ['localhost:27018'], searchParams: { get: () => null }, - username: 'authMechanism' + username: 'authMechanism', }), - instance: () => Promise.resolve({ - dataLake: {}, - build: {}, - genuineMongoDB: {}, - host: {} - }) + instance: () => + Promise.resolve({ + dataLake: {}, + build: {}, + genuineMongoDB: {}, + host: {}, + }), }; test('it returns is_used_connect_screen true when the connection type is form', async () => { @@ -102,7 +100,7 @@ suite('ConnectionTelemetry Controller Test Suite', function () { await dataServ.disconnect(); }); - test('track new connection event fetches the connection instance information', async() => { + test('track new connection event fetches the connection instance information', async () => { const instanceTelemetry = await getConnectionTelemetryProperties( dataServ, ConnectionTypes.CONNECTION_STRING diff --git a/src/test/suite/telemetry/telemetryService.test.ts b/src/test/suite/telemetry/telemetryService.test.ts index 388e1768..ebfb6e28 100644 --- a/src/test/suite/telemetry/telemetryService.test.ts +++ b/src/test/suite/telemetry/telemetryService.test.ts @@ -14,12 +14,10 @@ import { ConnectionTypes } from '../../../connectionController'; import { DocumentSource } from '../../../documentSource'; import { ExportToLanguageMode } from '../../../types/playgroundType'; import { mdbTestExtension } from '../stubbableMdbExtension'; -import { - NewConnectionTelemetryEventProperties -} from '../../../telemetry/connectionTelemetry'; +import { NewConnectionTelemetryEventProperties } from '../../../telemetry/connectionTelemetry'; import { SegmentProperties, - TelemetryEventTypes + TelemetryEventTypes, } from '../../../telemetry/telemetryService'; const expect = chai.expect; @@ -35,12 +33,13 @@ suite('Telemetry Controller Test Suite', () => { const testTelemetryService = mdbTestExtension.testExtensionController._telemetryService; const mockDataService: any = sinon.fake.returns({ - instance: () => Promise.resolve({ - dataLake: {}, - build: {}, - genuineMongoDB: {}, - host: {} - }) + instance: () => + Promise.resolve({ + dataLake: {}, + build: {}, + genuineMongoDB: {}, + host: {}, + }), }); let mockTrackNewConnection: Sinon.SinonSpy; @@ -88,7 +87,7 @@ suite('Telemetry Controller Test Suite', () => { 'getNamespaceForSelection', sinon.fake.resolves({ collectionName: 'coll', - databaseName: 'db' + databaseName: 'db', }) ); sinon.replace( @@ -218,11 +217,13 @@ suite('Telemetry Controller Test Suite', () => { line: 1, documentId: '93333a0d-83f6-4e6f-a575-af7ea6187a4a', namespace: 'db.coll', - connectionId: null + connectionId: null, } ); - expect(mockTrackDocumentOpenedInEditor.firstCall.firstArg).to.be.equal('playground'); + expect(mockTrackDocumentOpenedInEditor.firstCall.firstArg).to.be.equal( + 'playground' + ); }); test('track playground code executed event', async () => { @@ -260,22 +261,17 @@ suite('Telemetry Controller Test Suite', () => { sinon.fake.returns(true) ); const fakeSegmentTrack = sinon.fake.yields(null); - sinon.replace( - testTelemetryService, - '_segmentAnalytics', - { - track: fakeSegmentTrack - } as any - ); + sinon.replace(testTelemetryService, '_segmentAnalytics', { + track: fakeSegmentTrack, + } as any); - testTelemetryService.track( - TelemetryEventTypes.EXTENSION_LINK_CLICKED - ); + testTelemetryService.track(TelemetryEventTypes.EXTENSION_LINK_CLICKED); - const telemetryEvent: SegmentProperties = fakeSegmentTrack.firstCall.args[0]; + const telemetryEvent: SegmentProperties = + fakeSegmentTrack.firstCall.args[0]; expect(telemetryEvent.properties).to.deep.equal({ - extension_version: version + extension_version: version, }); expect(telemetryEvent.event).to.equal('Link Clicked'); }); @@ -287,26 +283,20 @@ suite('Telemetry Controller Test Suite', () => { sinon.fake.returns(true) ); const fakeSegmentTrack = sinon.fake.yields(null); - sinon.replace( - testTelemetryService, - '_segmentAnalytics', - { - track: fakeSegmentTrack - } as any - ); + sinon.replace(testTelemetryService, '_segmentAnalytics', { + track: fakeSegmentTrack, + } as any); - testTelemetryService.track( - TelemetryEventTypes.PLAYGROUND_LOADED, - { - source: DocumentSource.DOCUMENT_SOURCE_PLAYGROUND - } - ); + testTelemetryService.track(TelemetryEventTypes.PLAYGROUND_LOADED, { + source: DocumentSource.DOCUMENT_SOURCE_PLAYGROUND, + }); - const telemetryEvent: SegmentProperties = fakeSegmentTrack.firstCall.args[0]; + const telemetryEvent: SegmentProperties = + fakeSegmentTrack.firstCall.args[0]; expect(telemetryEvent.properties).to.deep.equal({ extension_version: version, - source: DocumentSource.DOCUMENT_SOURCE_PLAYGROUND + source: DocumentSource.DOCUMENT_SOURCE_PLAYGROUND, }); expect(telemetryEvent.event).to.equal('Playground Loaded'); }); @@ -324,21 +314,23 @@ suite('Telemetry Controller Test Suite', () => { const textFromEditor = "{ '_id': 1, 'item': 'abc', 'price': 10 }"; const selection = { start: { line: 0, character: 0 }, - end: { line: 0, character: 40 } + end: { line: 0, character: 40 }, } as vscode.Selection; const mode = ExportToLanguageMode.QUERY; const language = 'python'; - mdbTestExtension.testExtensionController._playgroundController._codeActionProvider.mode = mode; - mdbTestExtension.testExtensionController._playgroundController._exportToLanguageCodeLensProvider._exportToLanguageAddons = { - textFromEditor, - selectedText: textFromEditor, - selection, - importStatements: false, - driverSyntax: false, - builders: false, - language - }; + mdbTestExtension.testExtensionController._playgroundController._codeActionProvider.mode = + mode; + mdbTestExtension.testExtensionController._playgroundController._exportToLanguageCodeLensProvider._exportToLanguageAddons = + { + textFromEditor, + selectedText: textFromEditor, + selection, + importStatements: false, + driverSyntax: false, + builders: false, + language, + }; await mdbTestExtension.testExtensionController._playgroundController._transpile(); @@ -348,7 +340,7 @@ suite('Telemetry Controller Test Suite', () => { language, with_import_statements: false, with_builders: false, - with_driver_syntax: false + with_driver_syntax: false, }); }); @@ -365,21 +357,23 @@ suite('Telemetry Controller Test Suite', () => { const textFromEditor = "[{ '_id': 1, 'item': 'abc', 'price': 10 }]"; const selection = { start: { line: 0, character: 0 }, - end: { line: 0, character: 42 } + end: { line: 0, character: 42 }, } as vscode.Selection; const mode = ExportToLanguageMode.AGGREGATION; const language = 'java'; - mdbTestExtension.testExtensionController._playgroundController._codeActionProvider.mode = mode; - mdbTestExtension.testExtensionController._playgroundController._exportToLanguageCodeLensProvider._exportToLanguageAddons = { - textFromEditor, - selectedText: textFromEditor, - selection, - importStatements: false, - driverSyntax: false, - builders: false, - language - }; + mdbTestExtension.testExtensionController._playgroundController._codeActionProvider.mode = + mode; + mdbTestExtension.testExtensionController._playgroundController._exportToLanguageCodeLensProvider._exportToLanguageAddons = + { + textFromEditor, + selectedText: textFromEditor, + selection, + importStatements: false, + driverSyntax: false, + builders: false, + language, + }; await mdbTestExtension.testExtensionController._playgroundController._transpile(); @@ -390,7 +384,7 @@ suite('Telemetry Controller Test Suite', () => { num_stages: 1, with_import_statements: false, with_builders: false, - with_driver_syntax: false + with_driver_syntax: false, }); }); @@ -411,16 +405,21 @@ suite('Telemetry Controller Test Suite', () => { await dataServ.disconnect(); }); - test('track new connection event fetches the connection instance information', async() => { + test('track new connection event fetches the connection instance information', async () => { sinon.replace(testTelemetryService, 'track', mockTrack); - sinon.replace(testTelemetryService, '_isTelemetryFeatureEnabled', () => true); + sinon.replace( + testTelemetryService, + '_isTelemetryFeatureEnabled', + () => true + ); await mdbTestExtension.testExtensionController._telemetryService.trackNewConnection( dataServ, ConnectionTypes.CONNECTION_STRING ); expect(mockTrack.firstCall.args[0]).to.equal('New Connection'); - const instanceTelemetry: NewConnectionTelemetryEventProperties = mockTrack.firstCall.args[1]; + const instanceTelemetry: NewConnectionTelemetryEventProperties = + mockTrack.firstCall.args[1]; expect(instanceTelemetry.is_localhost).to.equal(true); expect(instanceTelemetry.is_atlas).to.equal(false); expect(instanceTelemetry.is_used_connect_screen).to.equal(false); @@ -434,7 +433,12 @@ suite('Telemetry Controller Test Suite', () => { test('convert AggregationCursor shellApiType to aggregation telemetry type', () => { const res = { outputLines: [], - result: { namespace: null, type: 'AggregationCursor', content: '', language: 'plaintext' }, + result: { + namespace: null, + type: 'AggregationCursor', + content: '', + language: 'plaintext', + }, }; const type = testTelemetryService.getPlaygroundResultType(res); @@ -444,7 +448,12 @@ suite('Telemetry Controller Test Suite', () => { test('convert BulkWriteResult shellApiType to other telemetry type', () => { const res = { outputLines: [], - result: { namespace: null, type: 'BulkWriteResult', content: '', language: 'plaintext' } + result: { + namespace: null, + type: 'BulkWriteResult', + content: '', + language: 'plaintext', + }, }; const type = testTelemetryService.getPlaygroundResultType(res); @@ -454,7 +463,12 @@ suite('Telemetry Controller Test Suite', () => { test('convert Collection shellApiType to other telemetry type', () => { const res = { outputLines: [], - result: { namespace: null, type: 'Collection', content: '', language: 'plaintext' } + result: { + namespace: null, + type: 'Collection', + content: '', + language: 'plaintext', + }, }; const type = testTelemetryService.getPlaygroundResultType(res); @@ -464,7 +478,12 @@ suite('Telemetry Controller Test Suite', () => { test('convert Cursor shellApiType to other telemetry type', () => { const res = { outputLines: [], - result: { namespace: null, type: 'Cursor', content: '', language: 'plaintext' } + result: { + namespace: null, + type: 'Cursor', + content: '', + language: 'plaintext', + }, }; const type = testTelemetryService.getPlaygroundResultType(res); @@ -474,7 +493,12 @@ suite('Telemetry Controller Test Suite', () => { test('convert Database shellApiType to other telemetry type', () => { const res = { outputLines: [], - result: { namespace: null, type: 'Database', content: '', language: 'plaintext' } + result: { + namespace: null, + type: 'Database', + content: '', + language: 'plaintext', + }, }; const type = testTelemetryService.getPlaygroundResultType(res); @@ -484,7 +508,12 @@ suite('Telemetry Controller Test Suite', () => { test('convert DeleteResult shellApiType to other telemetry type', () => { const res = { outputLines: [], - result: { namespace: null, type: 'DeleteResult', content: '', language: 'plaintext' } + result: { + namespace: null, + type: 'DeleteResult', + content: '', + language: 'plaintext', + }, }; const type = testTelemetryService.getPlaygroundResultType(res); @@ -494,7 +523,12 @@ suite('Telemetry Controller Test Suite', () => { test('convert InsertManyResult shellApiType to other telemetry type', () => { const res = { outputLines: [], - result: { namespace: null, type: 'InsertManyResult', content: '', language: 'plaintext' } + result: { + namespace: null, + type: 'InsertManyResult', + content: '', + language: 'plaintext', + }, }; const type = testTelemetryService.getPlaygroundResultType(res); @@ -504,7 +538,12 @@ suite('Telemetry Controller Test Suite', () => { test('convert InsertOneResult shellApiType to other telemetry type', () => { const res = { outputLines: [], - result: { namespace: null, type: 'InsertOneResult', content: '', language: 'plaintext' } + result: { + namespace: null, + type: 'InsertOneResult', + content: '', + language: 'plaintext', + }, }; const type = testTelemetryService.getPlaygroundResultType(res); @@ -514,7 +553,12 @@ suite('Telemetry Controller Test Suite', () => { test('convert ReplicaSet shellApiType to other telemetry type', () => { const res = { outputLines: [], - result: { namespace: null, type: 'ReplicaSet', content: '', language: 'plaintext' } + result: { + namespace: null, + type: 'ReplicaSet', + content: '', + language: 'plaintext', + }, }; const type = testTelemetryService.getPlaygroundResultType(res); @@ -524,7 +568,12 @@ suite('Telemetry Controller Test Suite', () => { test('convert Shard shellApiType to other telemetry type', () => { const res = { outputLines: [], - result: { namespace: null, type: 'Shard', content: '', language: 'plaintext' } + result: { + namespace: null, + type: 'Shard', + content: '', + language: 'plaintext', + }, }; const type = testTelemetryService.getPlaygroundResultType(res); @@ -534,7 +583,12 @@ suite('Telemetry Controller Test Suite', () => { test('convert ShellApi shellApiType to other telemetry type', () => { const res = { outputLines: [], - result: { namespace: null, type: 'ShellApi', content: '', language: 'plaintext' } + result: { + namespace: null, + type: 'ShellApi', + content: '', + language: 'plaintext', + }, }; const type = testTelemetryService.getPlaygroundResultType(res); @@ -544,7 +598,12 @@ suite('Telemetry Controller Test Suite', () => { test('convert UpdateResult shellApiType to other telemetry type', () => { const res = { outputLines: [], - result: { namespace: null, type: 'UpdateResult', content: '', language: 'plaintext' } + result: { + namespace: null, + type: 'UpdateResult', + content: '', + language: 'plaintext', + }, }; const type = testTelemetryService.getPlaygroundResultType(res); @@ -554,7 +613,12 @@ suite('Telemetry Controller Test Suite', () => { test('return other telemetry type if evaluation returns a string', () => { const res = { outputLines: [], - result: { namespace: null, type: null, content: '2', language: 'plaintext' } + result: { + namespace: null, + type: null, + content: '2', + language: 'plaintext', + }, }; const type = testTelemetryService.getPlaygroundResultType(res); diff --git a/src/test/suite/utils/linkHelper.test.ts b/src/test/suite/utils/linkHelper.test.ts index fcc98695..a7aebb10 100644 --- a/src/test/suite/utils/linkHelper.test.ts +++ b/src/test/suite/utils/linkHelper.test.ts @@ -9,7 +9,9 @@ import { openLink } from '../../../utils/linkHelper'; suite('Open Link Test Suite', () => { test('the helper server is instantiated correctly', () => { const stubServer: any = { on: sinon.spy(), listen: sinon.spy() }; - const stubCreateServer: any = sinon.stub(http, 'createServer').returns(stubServer); + const stubCreateServer: any = sinon + .stub(http, 'createServer') + .returns(stubServer); void openLink('https://mongodb.com', 4321); expect(stubServer.on.calledWith('connection')).to.be.true; expect(stubServer.listen.calledWith(4321)).to.be.true; @@ -19,14 +21,23 @@ suite('Open Link Test Suite', () => { test('the browser opens correctly for mongodb.com', () => { const stubServer: any = { on: sinon.stub(), - listen: sinon.stub().callsArg(1) + listen: sinon.stub().callsArg(1), }; - const stubCreateStubInstance: any = sinon.createStubInstance(http.Server, stubServer); - const stubCreateServer: any = sinon.stub(http, 'createServer').returns(stubCreateStubInstance); - const stubExecuteCommand: any = sinon.stub(vscode.commands, 'executeCommand').resolves(); + const stubCreateStubInstance: any = sinon.createStubInstance( + http.Server, + stubServer + ); + const stubCreateServer: any = sinon + .stub(http, 'createServer') + .returns(stubCreateStubInstance); + const stubExecuteCommand: any = sinon + .stub(vscode.commands, 'executeCommand') + .resolves(); void openLink('https://mongodb.com', 4321); expect(stubExecuteCommand.firstCall.args[0]).to.equal('vscode.open'); - expect(stubExecuteCommand.firstCall.args[1].authority).to.equal(vscode.Uri.parse('http://localhost:4321').authority); + expect(stubExecuteCommand.firstCall.args[1].authority).to.equal( + vscode.Uri.parse('http://localhost:4321').authority + ); stubExecuteCommand.restore(); stubCreateServer.restore(); }); @@ -34,24 +45,35 @@ suite('Open Link Test Suite', () => { test('the browser opens correctly for a subdomain of mongodb.com', () => { const stubServer: any = { on: sinon.stub(), - listen: sinon.stub().callsArg(1) + listen: sinon.stub().callsArg(1), }; - const stubCreateStubInstance: any = sinon.createStubInstance(http.Server, stubServer); - const stubCreateServer: any = sinon.stub(http, 'createServer').returns(stubCreateStubInstance); - const stubExecuteCommand: any = sinon.stub(vscode.commands, 'executeCommand').resolves(); + const stubCreateStubInstance: any = sinon.createStubInstance( + http.Server, + stubServer + ); + const stubCreateServer: any = sinon + .stub(http, 'createServer') + .returns(stubCreateStubInstance); + const stubExecuteCommand: any = sinon + .stub(vscode.commands, 'executeCommand') + .resolves(); void openLink('https://monkey.mongodb.com', 4321); expect(stubExecuteCommand.firstCall.args[0]).to.equal('vscode.open'); - expect(stubExecuteCommand.firstCall.args[1].authority).to.equal(vscode.Uri.parse('http://localhost:4321').authority); + expect(stubExecuteCommand.firstCall.args[1].authority).to.equal( + vscode.Uri.parse('http://localhost:4321').authority + ); stubExecuteCommand.restore(); stubCreateServer.restore(); }); test('handles errors', (done) => { class MockedServer extends EventEmitter { - listen() { } + listen() {} } const mockedServer: any = new MockedServer(); - const stubCreateServer: any = sinon.stub(http, 'createServer').returns(mockedServer); + const stubCreateServer: any = sinon + .stub(http, 'createServer') + .returns(mockedServer); openLink('https://mongodb.com', 4321).catch((e) => { expect(e.message).to.equal('some error'); stubCreateServer.restore(); @@ -81,4 +103,3 @@ suite('Open Link Test Suite', () => { }); }); }); - diff --git a/src/test/suite/utils/objectIdHelper.test.ts b/src/test/suite/utils/objectIdHelper.test.ts index 1813f500..ad0179d7 100644 --- a/src/test/suite/utils/objectIdHelper.test.ts +++ b/src/test/suite/utils/objectIdHelper.test.ts @@ -17,10 +17,7 @@ suite('ObjectId Test Suite', () => { .update(CONFIG_NAME, false); const idFactory = createIdFactory(); - const ids = [ - idFactory(), - idFactory() - ]; + const ids = [idFactory(), idFactory()]; expect(ids[0]).to.equal(ids[1]); }); @@ -31,10 +28,7 @@ suite('ObjectId Test Suite', () => { .update(CONFIG_NAME, true); const idFactory = createIdFactory(); - const ids = [ - idFactory(), - idFactory() - ]; + const ids = [idFactory(), idFactory()]; expect(ids[0]).to.not.equal(ids[1]); }); diff --git a/src/test/suite/views/webview-app/components/app.test.tsx b/src/test/suite/views/webview-app/components/app.test.tsx index eb8393f0..b0fde7f4 100644 --- a/src/test/suite/views/webview-app/components/app.test.tsx +++ b/src/test/suite/views/webview-app/components/app.test.tsx @@ -7,22 +7,27 @@ import { createStore } from 'redux'; import { initialState, - rootReducer + rootReducer, } from '../../../../../views/webview-app/store/store'; import App, { - App as NotConnectedApp + App as NotConnectedApp, } from '../../../../../views/webview-app/components/app'; import OverviewPage from '../../../../../views/webview-app/components/overview-page/overview-page'; -import { CONNECTION_STATUS, MESSAGE_TYPES } from '../../../../../views/webview-app/extension-app-message-constants'; +import { + CONNECTION_STATUS, + MESSAGE_TYPES, +} from '../../../../../views/webview-app/extension-app-message-constants'; describe('App Component Test Suite', () => { describe('when rendered', () => { test('it shows the overview page', () => { - const wrapper = shallow( { }} - onFilePickerEvent={(): void => { }} - setConnectionStatus={(): void => { }} - />); + const wrapper = shallow( + {}} + onFilePickerEvent={(): void => {}} + setConnectionStatus={(): void => {}} + /> + ); assert(wrapper.find(OverviewPage).exists()); }); }); @@ -47,18 +52,12 @@ describe('App Component Test Suite', () => { fakeVscodeWindowPostMessage ); - sinon.replace( - window, - 'addEventListener', - fakeAddEventListener - ); + sinon.replace(window, 'addEventListener', fakeAddEventListener); store = createStore(rootReducer, initialState); mount( - + ); @@ -75,8 +74,8 @@ describe('App Component Test Suite', () => { data: { command: MESSAGE_TYPES.CONNECTION_STATUS_MESSAGE, connectionStatus: CONNECTION_STATUS.CONNECTED, - activeConnectionName: 'Nice connection' - } + activeConnectionName: 'Nice connection', + }, }); assert(store.getState().connectionStatus === CONNECTION_STATUS.CONNECTED); assert(store.getState().activeConnectionName === 'Nice connection'); diff --git a/src/test/suite/views/webview-app/components/atlas-cta/atlas-cta.test.tsx b/src/test/suite/views/webview-app/components/atlas-cta/atlas-cta.test.tsx index b80e6bdc..c0e60e8e 100644 --- a/src/test/suite/views/webview-app/components/atlas-cta/atlas-cta.test.tsx +++ b/src/test/suite/views/webview-app/components/atlas-cta/atlas-cta.test.tsx @@ -7,7 +7,7 @@ import { Provider } from 'react-redux'; import { initialState, - rootReducer + rootReducer, } from '../../../../../../views/webview-app/store/store'; import AtlasCTA from '../../../../../../views/webview-app/components/atlas-cta/atlas-cta'; import { VSCODE_EXTENSION_SEGMENT_ANONYMOUS_ID } from '../../../../../../views/webview-app/extension-app-message-constants'; @@ -30,9 +30,7 @@ describe('Resources Panel Component Test Suite', () => { store = createStore(rootReducer, initialState); wrapper = mount( - + ); @@ -46,7 +44,10 @@ describe('Resources Panel Component Test Suite', () => { assert(!fakeVscodeWindowPostMessage.called); wrapper.find('a').at(0).simulate('click'); assert(fakeVscodeWindowPostMessage.called); - assert.strictEqual(fakeVscodeWindowPostMessage.firstCall.args[0].command, 'EXTENSION_LINK_CLICKED'); + assert.strictEqual( + fakeVscodeWindowPostMessage.firstCall.args[0].command, + 'EXTENSION_LINK_CLICKED' + ); }); test('when a trusted link is clicked it sends an event to the extension', () => { @@ -54,10 +55,20 @@ describe('Resources Panel Component Test Suite', () => { window[VSCODE_EXTENSION_SEGMENT_ANONYMOUS_ID] = 'mockAnonymousID'; wrapper.find('a').at(1).simulate('click'); assert(fakeVscodeWindowPostMessage.called); - assert.strictEqual(fakeVscodeWindowPostMessage.firstCall.args[0].command, 'OPEN_TRUSTED_LINK'); - assert.strictEqual(fakeVscodeWindowPostMessage.firstCall.args[0].linkTo, 'https://mongodb.com/products/vs-code/vs-code-atlas-signup?utm_campaign=vs-code-extension&utm_source=visual-studio&utm_medium=product&ajs_aid=mockAnonymousID'); + assert.strictEqual( + fakeVscodeWindowPostMessage.firstCall.args[0].command, + 'OPEN_TRUSTED_LINK' + ); + assert.strictEqual( + fakeVscodeWindowPostMessage.firstCall.args[0].linkTo, + 'https://mongodb.com/products/vs-code/vs-code-atlas-signup?utm_campaign=vs-code-extension&utm_source=visual-studio&utm_medium=product&ajs_aid=mockAnonymousID' + ); // The assert below is a bit redundant but will prevent us from redirecting to a non-https URL by mistake - assert(fakeVscodeWindowPostMessage.firstCall.args[0].linkTo.startsWith('https://') === true); + assert( + fakeVscodeWindowPostMessage.firstCall.args[0].linkTo.startsWith( + 'https://' + ) === true + ); }); }); }); diff --git a/src/test/suite/views/webview-app/components/connect-form-modal/connect-form-modal.test.tsx b/src/test/suite/views/webview-app/components/connect-form-modal/connect-form-modal.test.tsx index 83d91bd0..392b7e4e 100644 --- a/src/test/suite/views/webview-app/components/connect-form-modal/connect-form-modal.test.tsx +++ b/src/test/suite/views/webview-app/components/connect-form-modal/connect-form-modal.test.tsx @@ -9,18 +9,18 @@ import { createStore } from 'redux'; import { AppState, initialState, - rootReducer + rootReducer, } from '../../../../../../views/webview-app/store/store'; import ConnectForm from '../../../../../../views/webview-app/components/connect-form/connection-form'; import ConnectFormModal, { - ConnectFormModal as NoStoreConnectFormModal + ConnectFormModal as NoStoreConnectFormModal, } from '../../../../../../views/webview-app/components/connect-form-modal/connect-form-modal'; describe('Connect Form Modal Component Test Suite', () => { describe('when rendered', () => { - const wrapper = shallow( {}} - />); + const wrapper = shallow( + {}} /> + ); test('it shows the connection form', () => { assert(wrapper.find(ConnectForm).exists()); @@ -47,13 +47,11 @@ describe('Connect Form Modal Component Test Suite', () => { store = createStore(rootReducer, { ...initialState, - showConnectForm: true + showConnectForm: true, } as AppState); wrapper = mount( - + ); diff --git a/src/test/suite/views/webview-app/components/connect-form/connection-form.test.tsx b/src/test/suite/views/webview-app/components/connect-form/connection-form.test.tsx index 522d9358..53c0cf6a 100644 --- a/src/test/suite/views/webview-app/components/connect-form/connection-form.test.tsx +++ b/src/test/suite/views/webview-app/components/connect-form/connection-form.test.tsx @@ -2,9 +2,7 @@ import assert from 'assert'; import * as React from 'react'; import { shallow } from 'enzyme'; -import { - ConnectionForm -} from '../../../../../../views/webview-app/components/connect-form/connection-form'; +import { ConnectionForm } from '../../../../../../views/webview-app/components/connect-form/connection-form'; import FormActions from '../../../../../../views/webview-app/components/form/form-actions'; import { CONNECTION_FORM_TABS } from '../../../../../../views/webview-app/store/constants'; import GeneralTab from '../../../../../../views/webview-app/components/connect-form/general-tab/general-tab'; @@ -14,74 +12,84 @@ import AdvancedTab from '../../../../../../views/webview-app/components/connect- describe('Webview Connection Form Component Test Suite', () => { test('it shows a connection form', () => { - const wrapper = shallow( { }} - />); + const wrapper = shallow( + {}} + /> + ); assert(wrapper.find('form').exists()); assert(wrapper.find(FormActions).exists()); }); test('it shows the general tab when the connectionFormTab prop is GENERAL', () => { - const wrapper = shallow( { }} - />); + const wrapper = shallow( + {}} + /> + ); assert(wrapper.find(GeneralTab).exists()); }); test('it shows the ssl tab when the connectionFormTab prop is SSL', () => { - const wrapper = shallow( { }} - />); + const wrapper = shallow( + {}} + /> + ); assert(wrapper.find(SSLTab).exists()); assert(!wrapper.find(GeneralTab).exists()); }); test('it shows the ssh tab when the connectionFormTab prop is SSH', () => { - const wrapper = shallow( { }} - />); + const wrapper = shallow( + {}} + /> + ); assert(wrapper.find(SSHTunnelTab).exists()); }); test('it shows the advanced tab when the connectionFormTab prop is ADVANCED', () => { - const wrapper = shallow( { }} - />); + const wrapper = shallow( + {}} + /> + ); assert(wrapper.find(AdvancedTab).exists()); }); }); diff --git a/src/test/suite/views/webview-app/components/connect-form/general-tab/authentication/authentication.test.tsx b/src/test/suite/views/webview-app/components/connect-form/general-tab/authentication/authentication.test.tsx index 403267d0..a2f767f4 100644 --- a/src/test/suite/views/webview-app/components/connect-form/general-tab/authentication/authentication.test.tsx +++ b/src/test/suite/views/webview-app/components/connect-form/general-tab/authentication/authentication.test.tsx @@ -10,34 +10,40 @@ import ScramSha256 from '../../../../../../../../views/webview-app/components/co describe('Authentication Component Test Suite', () => { test('it shows a select for the authentication method', () => { - const wrapper = shallow( {}} - />); + const wrapper = shallow( + {}} + /> + ); assert(wrapper.find(RadioBoxGroup).exists()); assert(!wrapper.find(MongodbAuthentication).exists()); assert(!wrapper.find(ScramSha256).exists()); }); test('it renders mongodb auth when the authStrategy is set', () => { - const wrapper = shallow( {}} - />); + const wrapper = shallow( + {}} + /> + ); assert(wrapper.find(MongodbAuthentication).exists()); }); test('it renders SCRAM-SHA-256 when the auth strategy is set', () => { - const wrapper = shallow( {}} - />); + const wrapper = shallow( + {}} + /> + ); assert(wrapper.find(ScramSha256).exists()); }); }); diff --git a/src/test/suite/views/webview-app/components/connect-form/general-tab/host.test.tsx b/src/test/suite/views/webview-app/components/connect-form/general-tab/host.test.tsx index b1c575da..bcd8ae83 100644 --- a/src/test/suite/views/webview-app/components/connect-form/general-tab/host.test.tsx +++ b/src/test/suite/views/webview-app/components/connect-form/general-tab/host.test.tsx @@ -11,45 +11,26 @@ import RadioBoxGroup from '../../../../../../../views/webview-app/components/for describe('Host Component Test Suite', () => { test('it shows a form group', () => { - const wrapper = shallow( {}} - onPortChanged={(): void => {}} - setReplicaSet={(): void => {}} - toggleSRVRecord={(): void => {}} - updateHosts={(): void => {}} - />); + const wrapper = shallow( + {}} + onPortChanged={(): void => {}} + setReplicaSet={(): void => {}} + toggleSRVRecord={(): void => {}} + updateHosts={(): void => {}} + /> + ); assert(wrapper.find(FormGroup).exists()); }); test('it shows the three connection types (standalone, replicaset, srv)', () => { - const wrapper = shallow( {}} - onPortChanged={(): void => {}} - setReplicaSet={(): void => {}} - toggleSRVRecord={(): void => {}} - updateHosts={(): void => {}} - />); - assert(wrapper.find(RadioBoxGroup).exists()); - assert(wrapper.find(RadioBoxGroup).props().options[0].label === 'Standalone'); - assert(wrapper.find(RadioBoxGroup).props().options[1].label === 'Replica Set'); - assert(wrapper.find(RadioBoxGroup).props().options[2].label === 'SRV Record'); - }); - - describe('when there is no replicaSet and only one host', () => { - let wrapper: ShallowWrapper; - - beforeEach(() => { - wrapper = shallow( { setReplicaSet={(): void => {}} toggleSRVRecord={(): void => {}} updateHosts={(): void => {}} - />); + /> + ); + assert(wrapper.find(RadioBoxGroup).exists()); + assert( + wrapper.find(RadioBoxGroup).props().options[0].label === 'Standalone' + ); + assert( + wrapper.find(RadioBoxGroup).props().options[1].label === 'Replica Set' + ); + assert( + wrapper.find(RadioBoxGroup).props().options[2].label === 'SRV Record' + ); + }); + + describe('when there is no replicaSet and only one host', () => { + let wrapper: ShallowWrapper; + + beforeEach(() => { + wrapper = shallow( + {}} + onPortChanged={(): void => {}} + setReplicaSet={(): void => {}} + toggleSRVRecord={(): void => {}} + updateHosts={(): void => {}} + /> + ); }); test('it shows the port input', () => { @@ -85,11 +97,11 @@ describe('Host Component Test Suite', () => { wrapper.setProps({ setReplicaSet: fakeSetReplicaSet, - updateHosts: fakeUpdateHosts + updateHosts: fakeUpdateHosts, }); wrapper.find('button').simulate('click', { - preventDefault: () => { } + preventDefault: () => {}, }); }); @@ -111,18 +123,20 @@ describe('Host Component Test Suite', () => { let wrapper: ShallowWrapper; beforeEach(() => { - wrapper = shallow( {}} - onPortChanged={(): void => {}} - setReplicaSet={(): void => {}} - toggleSRVRecord={(): void => {}} - updateHosts={(): void => {}} - />); + wrapper = shallow( + {}} + onPortChanged={(): void => {}} + setReplicaSet={(): void => {}} + toggleSRVRecord={(): void => {}} + updateHosts={(): void => {}} + /> + ); }); test('it shows hostname input', () => { @@ -144,13 +158,16 @@ describe('Host Component Test Suite', () => { describe('when there is more than one host', () => { beforeEach(() => { wrapper.setProps({ - hosts: [{ - host: 'underwaterhost', - port: 27020 - }, { - host: 'outerspacehost', - port: 27029 - }] + hosts: [ + { + host: 'underwaterhost', + port: 27020, + }, + { + host: 'outerspacehost', + port: 27029, + }, + ], }); }); @@ -160,7 +177,12 @@ describe('Host Component Test Suite', () => { it('shows host name input for each host', () => { assert(wrapper.find('#host-name-0').exists()); - assert(wrapper.find('#host-name-0').props().value === 'underwaterhost', `Expected '${wrapper.find('#host-name-0').text()}' to equal 'underwaterhost'`); + assert( + wrapper.find('#host-name-0').props().value === 'underwaterhost', + `Expected '${wrapper + .find('#host-name-0') + .text()}' to equal 'underwaterhost'` + ); assert(wrapper.find('#host-name-1').exists()); assert(wrapper.find('#host-name-1').props().value === 'outerspacehost'); }); @@ -179,18 +201,23 @@ describe('Host Component Test Suite', () => { fakeUpdateHosts = sinon.fake.returns(undefined); wrapper.setProps({ - updateHosts: fakeUpdateHosts + updateHosts: fakeUpdateHosts, }); - wrapper.find('button').at(1).simulate('click', { - preventDefault: () => { } - }); + wrapper + .find('button') + .at(1) + .simulate('click', { + preventDefault: () => {}, + }); }); test('it calls to update hosts to with one less host', () => { assert(fakeUpdateHosts.called); assert(fakeUpdateHosts.firstCall.args[0].length === 1); - assert(fakeUpdateHosts.firstCall.args[0][0].host === 'outerspacehost'); + assert( + fakeUpdateHosts.firstCall.args[0][0].host === 'outerspacehost' + ); assert(fakeUpdateHosts.firstCall.args[0][0].port === 27029); }); }); @@ -201,18 +228,20 @@ describe('Host Component Test Suite', () => { let wrapper: ShallowWrapper; beforeEach(() => { - wrapper = shallow( {}} - onPortChanged={(): void => {}} - setReplicaSet={(): void => {}} - toggleSRVRecord={(): void => {}} - updateHosts={(): void => {}} - />); + wrapper = shallow( + {}} + onPortChanged={(): void => {}} + setReplicaSet={(): void => {}} + toggleSRVRecord={(): void => {}} + updateHosts={(): void => {}} + /> + ); }); test('it shows hostname input', () => { diff --git a/src/test/suite/views/webview-app/components/connect-helper/connect-helper.test.tsx b/src/test/suite/views/webview-app/components/connect-helper/connect-helper.test.tsx index 1e898129..b44ade55 100644 --- a/src/test/suite/views/webview-app/components/connect-helper/connect-helper.test.tsx +++ b/src/test/suite/views/webview-app/components/connect-helper/connect-helper.test.tsx @@ -9,7 +9,7 @@ import ConnectHelper from '../../../../../../views/webview-app/components/connec import { AppState, initialState, - rootReducer + rootReducer, } from '../../../../../../views/webview-app/store/store'; describe('Connect Helper Component Test Suite', () => { @@ -28,13 +28,11 @@ describe('Connect Helper Component Test Suite', () => { ); store = createStore(rootReducer, { - ...initialState + ...initialState, } as AppState); wrapper = mount( - + ); @@ -47,7 +45,10 @@ describe('Connect Helper Component Test Suite', () => { test('when onOpenConnectionStringInput is clicked it posts a message to vscode to open the input', () => { wrapper.find('button').at(0).simulate('click'); assert(fakeVscodeWindowPostMessage.called); - assert(fakeVscodeWindowPostMessage.firstCall.args[0].command === 'OPEN_CONNECTION_STRING_INPUT'); + assert( + fakeVscodeWindowPostMessage.firstCall.args[0].command === + 'OPEN_CONNECTION_STRING_INPUT' + ); }); test('when onOpenConnectionFrom is clicked it shows the connect form modal', () => { diff --git a/src/test/suite/views/webview-app/components/connection-status/connection-status.test.tsx b/src/test/suite/views/webview-app/components/connection-status/connection-status.test.tsx index 4e2463c7..d512dbb8 100644 --- a/src/test/suite/views/webview-app/components/connection-status/connection-status.test.tsx +++ b/src/test/suite/views/webview-app/components/connection-status/connection-status.test.tsx @@ -8,48 +8,54 @@ import { faPencilAlt } from '@fortawesome/free-solid-svg-icons'; import { Provider } from 'react-redux'; import ConnectionStatus, { - ConnectionStatus as PlainConnectionStatus + ConnectionStatus as PlainConnectionStatus, } from '../../../../../../views/webview-app/components/connection-status/connection-status'; import { CONNECTION_STATUS } from '../../../../../../views/webview-app/extension-app-message-constants'; import { AppState, initialState, - rootReducer + rootReducer, } from '../../../../../../views/webview-app/store/store'; describe('Connection Status Component Test Suite', () => { describe('connected connection status', () => { test('it shows that it is connected to the connection name', () => { - const wrapper = shallow( {}} - requestConnectionStatus={(): void => {}} - onClickRenameConnection={(): void => {}} - />); + const wrapper = shallow( + {}} + requestConnectionStatus={(): void => {}} + onClickRenameConnection={(): void => {}} + /> + ); assert(wrapper.text().includes('Connected to:')); assert(wrapper.text().includes('Active connection name')); }); test('it shows a create playground button', () => { - const wrapper = shallow( {}} - requestConnectionStatus={(): void => {}} - onClickRenameConnection={(): void => {}} - />); + const wrapper = shallow( + {}} + requestConnectionStatus={(): void => {}} + onClickRenameConnection={(): void => {}} + /> + ); assert(wrapper.find('button').exists()); }); test('it shows an edit connection name button', () => { - const wrapper = shallow( {}} - requestConnectionStatus={(): void => {}} - onClickRenameConnection={(): void => {}} - />); + const wrapper = shallow( + {}} + requestConnectionStatus={(): void => {}} + onClickRenameConnection={(): void => {}} + /> + ); assert(wrapper.find(FontAwesomeIcon).prop('icon') === faPencilAlt); }); @@ -69,13 +75,11 @@ describe('Connection Status Component Test Suite', () => { store = createStore(rootReducer, { ...initialState, - connectionStatus: CONNECTION_STATUS.CONNECTED + connectionStatus: CONNECTION_STATUS.CONNECTED, } as AppState); wrapper = mount( - + ); @@ -88,70 +92,83 @@ describe('Connection Status Component Test Suite', () => { test('when the edit connection name button is clicked it posts a message to the extension to rename the connection', () => { wrapper.find('button').at(0).simulate('click'); assert(fakeVscodeWindowPostMessage.called); - assert(fakeVscodeWindowPostMessage.secondCall.args[0].command === 'RENAME_ACTIVE_CONNECTION'); + assert( + fakeVscodeWindowPostMessage.secondCall.args[0].command === + 'RENAME_ACTIVE_CONNECTION' + ); }); }); }); describe('disconnected', () => { test('it shows a disconnect message', () => { - const wrapper = shallow( {}} - requestConnectionStatus={(): void => {}} - onClickRenameConnection={(): void => {}} - />); + const wrapper = shallow( + {}} + requestConnectionStatus={(): void => {}} + onClickRenameConnection={(): void => {}} + /> + ); assert(wrapper.text().includes('Not connected')); }); test('it does not show a create playground button', () => { - const wrapper = shallow( {}} - requestConnectionStatus={(): void => {}} - onClickRenameConnection={(): void => {}} - />); + const wrapper = shallow( + {}} + requestConnectionStatus={(): void => {}} + onClickRenameConnection={(): void => {}} + /> + ); assert(wrapper.find('button').exists() === false); }); }); describe('connecting', () => { test('it shows a connecting message', () => { - const wrapper = shallow( {}} - requestConnectionStatus={(): void => {}} - onClickRenameConnection={(): void => {}} - />); + const wrapper = shallow( + {}} + requestConnectionStatus={(): void => {}} + onClickRenameConnection={(): void => {}} + /> + ); assert(wrapper.text().includes('Connecting...')); }); }); describe('disconnecting', () => { test('it shows a connecting message', () => { - const wrapper = shallow( {}} - requestConnectionStatus={(): void => {}} - onClickRenameConnection={(): void => {}} - />); + const wrapper = shallow( + {}} + requestConnectionStatus={(): void => {}} + onClickRenameConnection={(): void => {}} + /> + ); assert(wrapper.text().includes('Disconnecting...')); }); }); describe('loading', () => { test('it shows a loading message', () => { - const wrapper = shallow( {}} - requestConnectionStatus={(): void => {}} - onClickRenameConnection={(): void => {}} - />); + const wrapper = shallow( + {}} + requestConnectionStatus={(): void => {}} + onClickRenameConnection={(): void => {}} + /> + ); assert(wrapper.text().includes('Loading...')); }); }); diff --git a/src/test/suite/views/webview-app/components/form/form-actions.test.tsx b/src/test/suite/views/webview-app/components/form/form-actions.test.tsx index bb23ec93..fe50041d 100644 --- a/src/test/suite/views/webview-app/components/form/form-actions.test.tsx +++ b/src/test/suite/views/webview-app/components/form/form-actions.test.tsx @@ -9,7 +9,7 @@ import FormActions from '../../../../../../views/webview-app/components/form/for import { AppState, initialState, - rootReducer + rootReducer, } from '../../../../../../views/webview-app/store/store'; describe('Connect Form Actions Component Test Suite', () => { @@ -29,13 +29,11 @@ describe('Connect Form Actions Component Test Suite', () => { store = createStore(rootReducer, { ...initialState, - showConnectForm: true + showConnectForm: true, } as AppState); wrapper = mount( - + ); @@ -49,7 +47,9 @@ describe('Connect Form Actions Component Test Suite', () => { assert(!fakeVscodeWindowPostMessage.called); wrapper.find('#connectButton').simulate('click'); assert(fakeVscodeWindowPostMessage.called); - assert(fakeVscodeWindowPostMessage.firstCall.args[0].command === 'CONNECT'); + assert( + fakeVscodeWindowPostMessage.firstCall.args[0].command === 'CONNECT' + ); assert.deepStrictEqual( fakeVscodeWindowPostMessage.firstCall.args[0].connectionModel, store.getState().currentConnection diff --git a/src/test/suite/views/webview-app/components/form/radio-box-group/radio-box-group.test.tsx b/src/test/suite/views/webview-app/components/form/radio-box-group/radio-box-group.test.tsx index 9e8ae8e4..cba5f716 100644 --- a/src/test/suite/views/webview-app/components/form/radio-box-group/radio-box-group.test.tsx +++ b/src/test/suite/views/webview-app/components/form/radio-box-group/radio-box-group.test.tsx @@ -13,19 +13,24 @@ describe('Radio Box Group Component Test Suite', () => { changeHandlerCalledValue = evt.target.value; }; - const wrapper = mount(); + const wrapper = mount( + + ); test('it shows an input for each option', () => { assert(wrapper.find('input').length === 2); diff --git a/src/test/suite/views/webview-app/components/overview-page/overview-page.test.tsx b/src/test/suite/views/webview-app/components/overview-page/overview-page.test.tsx index 7250571c..5003615c 100644 --- a/src/test/suite/views/webview-app/components/overview-page/overview-page.test.tsx +++ b/src/test/suite/views/webview-app/components/overview-page/overview-page.test.tsx @@ -11,10 +11,9 @@ import ResourcesPanel from '../../../../../../views/webview-app/components/resou describe('Overview Page Component Test Suite', () => { describe('when rendered', () => { - const wrapper = shallow(); + const wrapper = shallow( + + ); test('it shows an overview header', () => { assert(wrapper.find(OverviewHeader).exists()); @@ -38,10 +37,9 @@ describe('Overview Page Component Test Suite', () => { }); describe('when rendered with showConnectForm', () => { - const wrapper = shallow(); + const wrapper = shallow( + + ); test('it shows the connect form', () => { assert(wrapper.find(ConnectionFormModal).exists()); @@ -49,10 +47,9 @@ describe('Overview Page Component Test Suite', () => { }); describe('when rendered with showResourcesPanel', () => { - const wrapper = shallow(); + const wrapper = shallow( + + ); test('it shows the resources panel', () => { assert(wrapper.find(ResourcesPanel).exists()); diff --git a/src/test/suite/views/webview-app/components/resources-panel/resources-panel.test.tsx b/src/test/suite/views/webview-app/components/resources-panel/resources-panel.test.tsx index 0eeb5fdf..0ad6754d 100644 --- a/src/test/suite/views/webview-app/components/resources-panel/resources-panel.test.tsx +++ b/src/test/suite/views/webview-app/components/resources-panel/resources-panel.test.tsx @@ -8,7 +8,7 @@ import { Provider } from 'react-redux'; import { AppState, initialState, - rootReducer + rootReducer, } from '../../../../../../views/webview-app/store/store'; import ResourcesPanel from '../../../../../../views/webview-app/components/resources-panel/resources-panel'; @@ -29,13 +29,11 @@ describe('Resources Panel Component Test Suite', () => { store = createStore(rootReducer, { ...initialState, - showResourcesPanel: true + showResourcesPanel: true, } as AppState); wrapper = mount( - + ); @@ -55,7 +53,10 @@ describe('Resources Panel Component Test Suite', () => { assert(!fakeVscodeWindowPostMessage.called); wrapper.find('a').at(0).simulate('click'); assert(fakeVscodeWindowPostMessage.called); - assert(fakeVscodeWindowPostMessage.firstCall.args[0].command === 'EXTENSION_LINK_CLICKED'); + assert( + fakeVscodeWindowPostMessage.firstCall.args[0].command === + 'EXTENSION_LINK_CLICKED' + ); }); }); }); diff --git a/src/test/suite/views/webview-app/jest-setup.js b/src/test/suite/views/webview-app/jest-setup.js index d95c3125..d52a3838 100644 --- a/src/test/suite/views/webview-app/jest-setup.js +++ b/src/test/suite/views/webview-app/jest-setup.js @@ -9,7 +9,7 @@ Enzyme.configure({ adapter: new Adapter() }); jest.mock('@iconify-icons/codicon/book', () => {}); global.vscodeFake = { - postMessage: (message) => { } + postMessage: (message) => {}, }; global.acquireVsCodeApi = () => { diff --git a/src/test/suite/views/webview-app/store/store.test.ts b/src/test/suite/views/webview-app/store/store.test.ts index fec4af7e..96a8a55f 100644 --- a/src/test/suite/views/webview-app/store/store.test.ts +++ b/src/test/suite/views/webview-app/store/store.test.ts @@ -1,24 +1,22 @@ import assert from 'assert'; -import { - rootReducer -} from '../../../../../views/webview-app/store/store'; +import { rootReducer } from '../../../../../views/webview-app/store/store'; describe('Webview Store Test Suite', () => { test('ensure the state updates on an action call', () => { const resultingState = rootReducer(undefined, { type: 'CONNECTION_EVENT_OCCURED', connectionAttemptId: null, - successfullyConnected: true + successfullyConnected: true, } as any); assert(resultingState.isConnected); }); - test('ensure we don\'t update connection status when the connectionAttemptId doesnt match the current one', () => { + test("ensure we don't update connection status when the connectionAttemptId doesnt match the current one", () => { const resultingState = rootReducer(undefined, { type: 'CONNECTION_EVENT_OCCURED', connectionAttemptId: 'aaa', - successfullyConnected: true + successfullyConnected: true, } as any); assert(!resultingState.isConnected); }); diff --git a/src/test/suite/views/webviewController.test.ts b/src/test/suite/views/webviewController.test.ts index 9bd661fc..0cc15e55 100644 --- a/src/test/suite/views/webviewController.test.ts +++ b/src/test/suite/views/webviewController.test.ts @@ -13,7 +13,7 @@ import TelemetryService from '../../../telemetry/telemetryService'; import { TestExtensionContext } from '../stubs'; import { TEST_DATABASE_URI } from '../dbTestHelper'; import WebviewController, { - getWebviewContent + getWebviewContent, } from '../../../views/webviewController'; const fs = require('fs'); @@ -29,10 +29,10 @@ suite('Webview Test Suite', () => { const fakeWebview = { html: '', onDidReceiveMessage: stubOnDidRecieveMessage, - asWebviewUri: sinon.fake.returns('') + asWebviewUri: sinon.fake.returns(''), }; const fakeVSCodeCreateWebviewPanel = sinon.fake.returns({ - webview: fakeWebview + webview: fakeWebview, }); sinon.replace( @@ -47,7 +47,9 @@ suite('Webview Test Suite', () => { mdbTestExtension.testExtensionController._telemetryService ); - void testWebviewController.openWebview(mdbTestExtension.testExtensionContext); + void testWebviewController.openWebview( + mdbTestExtension.testExtensionContext + ); assert(fakeVSCodeCreateWebviewPanel.called); assert(fakeWebview.html !== ''); @@ -72,14 +74,14 @@ suite('Webview Test Suite', () => { const fakeWebview: any = { asWebviewUri: (jsUri) => { return jsUri; - } + }, }; const extensionPath = mdbTestExtension.testExtensionContext.extensionPath; const htmlString = getWebviewContent({ extensionPath, telemetryUserId: '', - webview: fakeWebview + webview: fakeWebview, }); assert(htmlString.includes('dist/webviewApp.js')); @@ -96,17 +98,21 @@ suite('Webview Test Suite', () => { const fakeWebview: any = { asWebviewUri: (jsUri) => { return jsUri; - } + }, }; const extensionPath = mdbTestExtension.testExtensionContext.extensionPath; const htmlString = getWebviewContent({ extensionPath, telemetryUserId: 'MOCK_ANONYMOU_ID', - webview: fakeWebview + webview: fakeWebview, }); - assert(htmlString.includes('>window[\'VSCODE_EXTENSION_SEGMENT_ANONYMOUS_ID\'] = \'MOCK_ANONYMOU_ID\';')); + assert( + htmlString.includes( + ">window['VSCODE_EXTENSION_SEGMENT_ANONYMOUS_ID'] = 'MOCK_ANONYMOU_ID';" + ) + ); }); test('web view listens for a connect message and adds the connection', (done) => { @@ -139,11 +145,11 @@ suite('Webview Test Suite', () => { messageReceived = callback; messageReceivedSet = true; }, - asWebviewUri: sinon.fake.returns('') + asWebviewUri: sinon.fake.returns(''), }; const fakeVSCodeCreateWebviewPanel = sinon.fake.returns({ - webview: fakeWebview + webview: fakeWebview, }); sinon.replace( @@ -158,7 +164,9 @@ suite('Webview Test Suite', () => { testTelemetryService ); - void testWebviewController.openWebview(mdbTestExtension.testExtensionContext); + void testWebviewController.openWebview( + mdbTestExtension.testExtensionContext + ); assert( messageReceivedSet, @@ -171,8 +179,8 @@ suite('Webview Test Suite', () => { connectionModel: { port: 27018, hostname: 'localhost', - hosts: [{ host: 'localhost', port: 27018 }] - } + hosts: [{ host: 'localhost', port: 27018 }], + }, }); }); @@ -207,10 +215,10 @@ suite('Webview Test Suite', () => { messageReceived = callback; messageReceivedSet = true; }, - asWebviewUri: sinon.fake.returns('') + asWebviewUri: sinon.fake.returns(''), }; const fakeVSCodeCreateWebviewPanel = sinon.fake.returns({ - webview: fakeWebview + webview: fakeWebview, }); sinon.replace( @@ -225,7 +233,9 @@ suite('Webview Test Suite', () => { testTelemetryService ); - void testWebviewController.openWebview(mdbTestExtension.testExtensionContext); + void testWebviewController.openWebview( + mdbTestExtension.testExtensionContext + ); assert( messageReceivedSet, @@ -238,8 +248,8 @@ suite('Webview Test Suite', () => { connectionModel: { port: 27018, hostname: 'localhost', - hosts: [{ host: 'localhost', port: 27018 }] - } + hosts: [{ host: 'localhost', port: 27018 }], + }, }); }); @@ -268,10 +278,10 @@ suite('Webview Test Suite', () => { onDidReceiveMessage: (callback): void => { messageReceived = callback; }, - asWebviewUri: sinon.fake.returns('') + asWebviewUri: sinon.fake.returns(''), }; const fakeVSCodeCreateWebviewPanel = sinon.fake.returns({ - webview: fakeWebview + webview: fakeWebview, }); sinon.replace( @@ -286,15 +296,17 @@ suite('Webview Test Suite', () => { testTelemetryService ); - void testWebviewController.openWebview(mdbTestExtension.testExtensionContext); + void testWebviewController.openWebview( + mdbTestExtension.testExtensionContext + ); // Mock a connection call. messageReceived({ command: MESSAGE_TYPES.CONNECT, connectionModel: { port: 2700002, // Bad port number. - hostname: 'localhost' - } + hostname: 'localhost', + }, }); }); @@ -329,10 +341,10 @@ suite('Webview Test Suite', () => { onDidReceiveMessage: (callback): void => { messageReceived = callback; }, - asWebviewUri: sinon.fake.returns('') + asWebviewUri: sinon.fake.returns(''), }; const fakeVSCodeCreateWebviewPanel = sinon.fake.returns({ - webview: fakeWebview + webview: fakeWebview, }); sinon.replace( vscode.window, @@ -344,7 +356,9 @@ suite('Webview Test Suite', () => { testStorageController, testTelemetryService ); - void testWebviewController.openWebview(mdbTestExtension.testExtensionContext); + void testWebviewController.openWebview( + mdbTestExtension.testExtensionContext + ); // Mock a connection call. messageReceived({ @@ -354,8 +368,8 @@ suite('Webview Test Suite', () => { hostname: 'shouldfail', connectTimeoutMS: 500, socketTimeoutMS: 500, - serverSelectionTimeoutMS: 500 - } + serverSelectionTimeoutMS: 500, + }, }); void testConnectionController.addNewConnectionStringAndConnect( @@ -376,7 +390,7 @@ suite('Webview Test Suite', () => { testTelemetryService ); const fakeVSCodeOpenDialog = sinon.fake.resolves({ - path: '/somefilepath/test.text' + path: '/somefilepath/test.text', }); let messageReceived; @@ -392,11 +406,11 @@ suite('Webview Test Suite', () => { onDidReceiveMessage: (callback): void => { messageReceived = callback; }, - asWebviewUri: sinon.fake.returns('') + asWebviewUri: sinon.fake.returns(''), }; const fakeVSCodeCreateWebviewPanel = sinon.fake.returns({ - webview: fakeWebview + webview: fakeWebview, }); sinon.replace( vscode.window, @@ -412,12 +426,14 @@ suite('Webview Test Suite', () => { testTelemetryService ); - void testWebviewController.openWebview(mdbTestExtension.testExtensionContext); + void testWebviewController.openWebview( + mdbTestExtension.testExtensionContext + ); // Mock a connection call. messageReceived({ command: MESSAGE_TYPES.OPEN_FILE_PICKER, - action: 'file_action' + action: 'file_action', }); }); @@ -439,10 +455,7 @@ suite('Webview Test Suite', () => { postMessage: async (message): Promise => { try { assert.strictEqual(message.action, 'file_action'); - assert.strictEqual( - message.files[0], - '/somefilepath/test.text' - ); + assert.strictEqual(message.files[0], '/somefilepath/test.text'); done(); } catch (e) { @@ -454,10 +467,10 @@ suite('Webview Test Suite', () => { onDidReceiveMessage: (callback): void => { messageReceived = callback; }, - asWebviewUri: sinon.fake.returns('') + asWebviewUri: sinon.fake.returns(''), }; const fakeVSCodeCreateWebviewPanel = sinon.fake.returns({ - webview: fakeWebview + webview: fakeWebview, }); sinon.replace( @@ -468,8 +481,8 @@ suite('Webview Test Suite', () => { const fakeVSCodeOpenDialog = sinon.fake.resolves([ { - fsPath: '/somefilepath/test.text' - } + fsPath: '/somefilepath/test.text', + }, ]); sinon.replace(vscode.window, 'showOpenDialog', fakeVSCodeOpenDialog); @@ -480,11 +493,13 @@ suite('Webview Test Suite', () => { testTelemetryService ); - void testWebviewController.openWebview(mdbTestExtension.testExtensionContext); + void testWebviewController.openWebview( + mdbTestExtension.testExtensionContext + ); messageReceived({ command: MESSAGE_TYPES.OPEN_FILE_PICKER, - action: 'file_action' + action: 'file_action', }); }); @@ -506,14 +521,14 @@ suite('Webview Test Suite', () => { onDidReceiveMessage: (callback): void => { messageReceived = callback; }, - asWebviewUri: sinon.fake.returns('') + asWebviewUri: sinon.fake.returns(''), }; const fakeVSCodeExecuteCommand = sinon.fake.resolves(false); sinon.replace(vscode.commands, 'executeCommand', fakeVSCodeExecuteCommand); const fakeVSCodeCreateWebviewPanel = sinon.fake.returns({ - webview: fakeWebview + webview: fakeWebview, }); sinon.replace( @@ -528,10 +543,12 @@ suite('Webview Test Suite', () => { testTelemetryService ); - void testWebviewController.openWebview(mdbTestExtension.testExtensionContext); + void testWebviewController.openWebview( + mdbTestExtension.testExtensionContext + ); messageReceived({ - command: MESSAGE_TYPES.OPEN_CONNECTION_STRING_INPUT + command: MESSAGE_TYPES.OPEN_CONNECTION_STRING_INPUT, }); setTimeout(() => { @@ -569,10 +586,10 @@ suite('Webview Test Suite', () => { onDidReceiveMessage: (callback): void => { messageReceived = callback; }, - asWebviewUri: sinon.fake.returns('') + asWebviewUri: sinon.fake.returns(''), }; const fakeVSCodeCreateWebviewPanel = sinon.fake.returns({ - webview: fakeWebview + webview: fakeWebview, }); sinon.replace( @@ -587,11 +604,13 @@ suite('Webview Test Suite', () => { testTelemetryService ); - void testWebviewController.openWebview(mdbTestExtension.testExtensionContext); + void testWebviewController.openWebview( + mdbTestExtension.testExtensionContext + ); // Mock a connection status request call. messageReceived({ - command: MESSAGE_TYPES.GET_CONNECTION_STATUS + command: MESSAGE_TYPES.GET_CONNECTION_STATUS, }); }); @@ -621,10 +640,10 @@ suite('Webview Test Suite', () => { onDidReceiveMessage: (callback): void => { messageReceived = callback; }, - asWebviewUri: sinon.fake.returns('') + asWebviewUri: sinon.fake.returns(''), }; const fakeVSCodeCreateWebviewPanel = sinon.fake.returns({ - webview: fakeWebview + webview: fakeWebview, }); sinon.replace( @@ -639,14 +658,16 @@ suite('Webview Test Suite', () => { testTelemetryService ); - void testWebviewController.openWebview(mdbTestExtension.testExtensionContext); + void testWebviewController.openWebview( + mdbTestExtension.testExtensionContext + ); void testConnectionController .addNewConnectionStringAndConnect(TEST_DATABASE_URI) .then(() => { // Mock a connection status request call. messageReceived({ - command: MESSAGE_TYPES.GET_CONNECTION_STATUS + command: MESSAGE_TYPES.GET_CONNECTION_STATUS, }); }); }); @@ -670,10 +691,10 @@ suite('Webview Test Suite', () => { onDidReceiveMessage: (callback): void => { messageReceived = callback; }, - asWebviewUri: sinon.fake.returns('') + asWebviewUri: sinon.fake.returns(''), }; const fakeVSCodeCreateWebviewPanel = sinon.fake.returns({ - webview: fakeWebview + webview: fakeWebview, }); sinon.replace( @@ -696,7 +717,9 @@ suite('Webview Test Suite', () => { testTelemetryService ); - void testWebviewController.openWebview(mdbTestExtension.testExtensionContext); + void testWebviewController.openWebview( + mdbTestExtension.testExtensionContext + ); await testConnectionController.addNewConnectionStringAndConnect( TEST_DATABASE_URI @@ -704,7 +727,7 @@ suite('Webview Test Suite', () => { // Mock a connection status request call. messageReceived({ - command: MESSAGE_TYPES.RENAME_ACTIVE_CONNECTION + command: MESSAGE_TYPES.RENAME_ACTIVE_CONNECTION, }); assert(mockRenameConnectionOnConnectionController.called); @@ -743,11 +766,11 @@ suite('Webview Test Suite', () => { onDidReceiveMessage: (callback): void => { messageReceived = callback; }, - asWebviewUri: sinon.fake.returns('') + asWebviewUri: sinon.fake.returns(''), }; const fakeVSCodeCreateWebviewPanel = sinon.fake.returns({ - webview: fakeWebview + webview: fakeWebview, }); sinon.replace( vscode.window, @@ -770,7 +793,7 @@ suite('Webview Test Suite', () => { messageReceived({ command: MESSAGE_TYPES.OPEN_TRUSTED_LINK, - linkTo: 'https://mongodb.com/test' + linkTo: 'https://mongodb.com/test', }); assert(stubOpenLink.called); diff --git a/src/types/playgroundType.ts b/src/types/playgroundType.ts index 5bb24159..3ae91db7 100644 --- a/src/types/playgroundType.ts +++ b/src/types/playgroundType.ts @@ -11,10 +11,12 @@ export type PlaygroundDebug = OutputItem[] | undefined; export type PlaygroundResult = OutputItem | undefined; -export type ShellExecuteAllResult = { - outputLines: PlaygroundDebug; - result: PlaygroundResult -} | undefined; +export type ShellExecuteAllResult = + | { + outputLines: PlaygroundDebug; + result: PlaygroundResult; + } + | undefined; export type PlaygroundExecuteParameters = { codeToEvaluate: string; @@ -42,13 +44,13 @@ export enum ExportToLanguages { JAVA = 'java', CSHARP = 'csharp', JAVASCRIPT = 'javascript', - RUBY = 'ruby' + RUBY = 'ruby', } export enum ExportToLanguageMode { QUERY = 'QUERY', AGGREGATION = 'AGGREGATION', - OTHER = 'OTHER' + OTHER = 'OTHER', } export interface ExportToLanguageNamespace { diff --git a/src/utils/formatError.ts b/src/utils/formatError.ts index 35a9a9f7..3d86fb0d 100644 --- a/src/utils/formatError.ts +++ b/src/utils/formatError.ts @@ -1,9 +1,16 @@ -export default (error: any, message?: string): { +export default ( + error: any, + message?: string +): { name?: string; message: string; stack?: string; } => { - if (typeof error?.name === 'string' && typeof error?.message === 'string' && typeof error?.stack === 'string') { + if ( + typeof error?.name === 'string' && + typeof error?.message === 'string' && + typeof error?.stack === 'string' + ) { return error; } else if (typeof error === 'string') { return { message: error }; diff --git a/src/utils/linkHelper.ts b/src/utils/linkHelper.ts index 9199b806..f24d4000 100644 --- a/src/utils/linkHelper.ts +++ b/src/utils/linkHelper.ts @@ -1,9 +1,7 @@ import * as vscode from 'vscode'; import { createServer, Server } from 'http'; -const TRUSTED_DOMAINS: Array = [ - /^.*mongodb\.com$/i -]; +const TRUSTED_DOMAINS: Array = [/^.*mongodb\.com$/i]; /** * Opens a link through an in-browser redirect from localhost @@ -17,35 +15,39 @@ const TRUSTED_DOMAINS: Array = [ * * @returns {Server} the helper Server instance */ -export const openLink = (url: string, serverPort = 3211): Promise => new Promise((resolve, reject) => { - const { scheme, authority } = vscode.Uri.parse(url); - if (scheme !== 'https' || !TRUSTED_DOMAINS.find(regex => regex.test(authority))) { - return reject(new Error('untrusted url')); - } +export const openLink = (url: string, serverPort = 3211): Promise => + new Promise((resolve, reject) => { + const { scheme, authority } = vscode.Uri.parse(url); + if ( + scheme !== 'https' || + !TRUSTED_DOMAINS.find((regex) => regex.test(authority)) + ) { + return reject(new Error('untrusted url')); + } - const server = createServer((request, response) => { - response.writeHead(302, { location: url }); - response.end(); - }); + const server = createServer((request, response) => { + response.writeHead(302, { location: url }); + response.end(); + }); - // This works well for the time being but it should be changed - // once we introduce a login with Atlas functionality. When that - // will happen, then the server needs to stay alive until we get - // the callback from Atlas. - server.on('connection', () => { - setTimeout(() => { - server.close(); - }, 2000); - }); + // This works well for the time being but it should be changed + // once we introduce a login with Atlas functionality. When that + // will happen, then the server needs to stay alive until we get + // the callback from Atlas. + server.on('connection', () => { + setTimeout(() => { + server.close(); + }, 2000); + }); - server.on('error', (err) => { - reject(err); - }); + server.on('error', (err) => { + reject(err); + }); - server.listen(serverPort, () => { - void vscode.commands.executeCommand( - 'vscode.open', - vscode.Uri.parse(`http://localhost:${serverPort}`) - ); + server.listen(serverPort, () => { + void vscode.commands.executeCommand( + 'vscode.open', + vscode.Uri.parse(`http://localhost:${serverPort}`) + ); + }); }); -}); diff --git a/src/views/statusView.ts b/src/views/statusView.ts index 4bb29adb..b367f214 100644 --- a/src/views/statusView.ts +++ b/src/views/statusView.ts @@ -4,11 +4,12 @@ export default class StatusView { _statusBarItem: vscode.StatusBarItem; constructor(context: vscode.ExtensionContext) { - this._statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, 0); - - context.subscriptions.push( - this._statusBarItem + this._statusBarItem = vscode.window.createStatusBarItem( + vscode.StatusBarAlignment.Left, + 0 ); + + context.subscriptions.push(this._statusBarItem); } public showMessage(message: string): void { diff --git a/src/views/webview-app/components/app.less b/src/views/webview-app/components/app.less index dcea428c..ed1a4a6e 100644 --- a/src/views/webview-app/components/app.less +++ b/src/views/webview-app/components/app.less @@ -1,4 +1,4 @@ -@import "~../styles/_variables"; +@import '~../styles/_variables'; :root { // NOTE: This green is updated in the code dynamically diff --git a/src/views/webview-app/components/app.tsx b/src/views/webview-app/components/app.tsx index 3f6524c4..dce6ae56 100644 --- a/src/views/webview-app/components/app.tsx +++ b/src/views/webview-app/components/app.tsx @@ -7,12 +7,12 @@ import { ConnectionEventOccuredAction, FilePickerActions, FilePickerActionTypes, - SetConnectionStatusAction + SetConnectionStatusAction, } from '../store/actions'; import { CONNECTION_STATUS, MESSAGE_FROM_EXTENSION_TO_WEBVIEW, - MESSAGE_TYPES + MESSAGE_TYPES, } from '../extension-app-message-constants'; const styles = require('../connect.module.less'); @@ -90,14 +90,14 @@ const mapDispatchToProps: DispatchProps = { type: ActionTypes.CONNECTION_EVENT_OCCURED, connectionAttemptId, successfullyConnected, - connectionMessage + connectionMessage, }), onFilePickerEvent: ( action: FilePickerActionTypes, files: string[] | undefined ): FilePickerActions => ({ type: action, - files + files, }), setConnectionStatus: ( connectionStatus: CONNECTION_STATUS, @@ -105,8 +105,8 @@ const mapDispatchToProps: DispatchProps = { ): SetConnectionStatusAction => ({ type: ActionTypes.SET_CONNECTION_STATUS, activeConnectionName, - connectionStatus - }) + connectionStatus, + }), }; export default connect(null, mapDispatchToProps)(App); diff --git a/src/views/webview-app/components/atlas-cta/atlas-cta.less b/src/views/webview-app/components/atlas-cta/atlas-cta.less index 28914e4a..e8cb4948 100644 --- a/src/views/webview-app/components/atlas-cta/atlas-cta.less +++ b/src/views/webview-app/components/atlas-cta/atlas-cta.less @@ -1,4 +1,4 @@ -@import "~../../styles/_variables"; +@import '~../../styles/_variables'; .atlas-cta { display: flex; diff --git a/src/views/webview-app/components/atlas-cta/atlas-cta.tsx b/src/views/webview-app/components/atlas-cta/atlas-cta.tsx index f8f37900..55d31c85 100644 --- a/src/views/webview-app/components/atlas-cta/atlas-cta.tsx +++ b/src/views/webview-app/components/atlas-cta/atlas-cta.tsx @@ -4,7 +4,7 @@ import { connect } from 'react-redux'; import { ActionTypes, LinkClickedAction, - TrustedLinkClickedAction + TrustedLinkClickedAction, } from '../../store/actions'; import { VSCODE_EXTENSION_SEGMENT_ANONYMOUS_ID } from '../../extension-app-message-constants'; import AtlasLogo from './atlas-logo'; @@ -22,10 +22,7 @@ class AtlasCTA extends React.Component { const atlasLink = `https://mongodb.com/products/vs-code/vs-code-atlas-signup?utm_campaign=vs-code-extension&utm_source=visual-studio&utm_medium=product&ajs_aid=${telemetryUserId}`; this.props.openTrustedLink(atlasLink); - this.onLinkClicked( - 'overviewPage', - 'freeClusterCTA' - ); + this.onLinkClicked('overviewPage', 'freeClusterCTA'); }; onLinkClicked = (screen: string, linkId: string): void => { @@ -35,9 +32,7 @@ class AtlasCTA extends React.Component { render(): React.ReactNode { return (
-
- {} -
+
{}
New to MongoDB and don't have a cluster? @@ -56,7 +51,8 @@ class AtlasCTA extends React.Component { )} > MongoDB Atlas - . + + .
({ type: ActionTypes.EXTENSION_LINK_CLICKED, screen, - linkId + linkId, }), openTrustedLink: (linkTo: string): TrustedLinkClickedAction => ({ type: ActionTypes.TRUSTED_LINK_CLICKED, - linkTo - }) + linkTo, + }), }; export default connect(() => ({}), mapDispatchToProps)(AtlasCTA); diff --git a/src/views/webview-app/components/atlas-cta/atlas-logo.tsx b/src/views/webview-app/components/atlas-cta/atlas-logo.tsx index c50f7e1e..d22a45da 100644 --- a/src/views/webview-app/components/atlas-cta/atlas-logo.tsx +++ b/src/views/webview-app/components/atlas-cta/atlas-logo.tsx @@ -3,11 +3,37 @@ import * as React from 'react'; export default class AtlasLogo extends React.PureComponent { render(): React.ReactNode { return ( - - - - - + + + + + ); } diff --git a/src/views/webview-app/components/connect-form-modal/connect-form-modal.tsx b/src/views/webview-app/components/connect-form-modal/connect-form-modal.tsx index cabe0e11..094527ae 100644 --- a/src/views/webview-app/components/connect-form-modal/connect-form-modal.tsx +++ b/src/views/webview-app/components/connect-form-modal/connect-form-modal.tsx @@ -4,7 +4,7 @@ import { connect } from 'react-redux'; import ConnectionForm from '../connect-form/connection-form'; import { ActionTypes, - ToggleShowConnectionFormAction + ToggleShowConnectionFormAction, } from '../../store/actions'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faTimes } from '@fortawesome/free-solid-svg-icons'; @@ -28,9 +28,7 @@ export class ConnectFormModal extends React.PureComponent { className={styles['connect-form-modal-close']} onClick={(): void => this.props.toggleShowConnectForm()} > - +
@@ -41,9 +39,8 @@ export class ConnectFormModal extends React.PureComponent { const mapDispatchToProps: DispatchProps = { toggleShowConnectForm: (): ToggleShowConnectionFormAction => ({ - type: ActionTypes.TOGGLE_SHOW_CONNECTION_FORM - }) + type: ActionTypes.TOGGLE_SHOW_CONNECTION_FORM, + }), }; export default connect(null, mapDispatchToProps)(ConnectFormModal); - diff --git a/src/views/webview-app/components/connect-form/advanced-tab/read-preference-select.tsx b/src/views/webview-app/components/connect-form/advanced-tab/read-preference-select.tsx index 12a9a965..d2337e07 100644 --- a/src/views/webview-app/components/connect-form/advanced-tab/read-preference-select.tsx +++ b/src/views/webview-app/components/connect-form/advanced-tab/read-preference-select.tsx @@ -2,7 +2,10 @@ import * as React from 'react'; import { connect } from 'react-redux'; import { AppState } from '../../../store/store'; -import { ActionTypes, ReadPreferenceChangedAction } from '../../../store/actions'; +import { + ActionTypes, + ReadPreferenceChangedAction, +} from '../../../store/actions'; import RadioBoxGroup from '../../form/radio-box-group/radio-box-group'; import READ_PREFERENCES from '../../../connection-model/constants/read-preferences'; @@ -14,24 +17,24 @@ type ReadPreferenceOption = { const ReadPreferencesOptions: ReadPreferenceOption[] = [ { label: 'Primary', - value: READ_PREFERENCES.PRIMARY + value: READ_PREFERENCES.PRIMARY, }, { label: 'Primary Preferred', - value: READ_PREFERENCES.PRIMARY_PREFERRED + value: READ_PREFERENCES.PRIMARY_PREFERRED, }, { label: 'Secondary', - value: READ_PREFERENCES.SECONDARY + value: READ_PREFERENCES.SECONDARY, }, { label: 'Secondary Preferred', - value: READ_PREFERENCES.SECONDARY_PREFERRED + value: READ_PREFERENCES.SECONDARY_PREFERRED, }, { label: 'Nearest', - value: READ_PREFERENCES.NEAREST - } + value: READ_PREFERENCES.NEAREST, + }, ]; type StateProps = { @@ -42,7 +45,9 @@ type DispatchProps = { onReadPreferenceChanged: (newReadPreference: READ_PREFERENCES) => void; }; -class ReadPreferenceSelect extends React.PureComponent { +class ReadPreferenceSelect extends React.PureComponent< + StateProps & DispatchProps +> { /** * Handles a read preference change. * @@ -69,7 +74,7 @@ class ReadPreferenceSelect extends React.PureComponent { return { - readPreference: state.currentConnection.readPreference + readPreference: state.currentConnection.readPreference, }; }; @@ -78,8 +83,11 @@ const mapDispatchToProps: DispatchProps = { newReadPreference: READ_PREFERENCES ): ReadPreferenceChangedAction => ({ type: ActionTypes.READ_PREFERENCE_CHANGED, - readPreference: newReadPreference - }) + readPreference: newReadPreference, + }), }; -export default connect(mapStateToProps, mapDispatchToProps)(ReadPreferenceSelect); +export default connect( + mapStateToProps, + mapDispatchToProps +)(ReadPreferenceSelect); diff --git a/src/views/webview-app/components/connect-form/connection-form-tabs.tsx b/src/views/webview-app/components/connect-form/connection-form-tabs.tsx index b15de8b2..31487715 100644 --- a/src/views/webview-app/components/connect-form/connection-form-tabs.tsx +++ b/src/views/webview-app/components/connect-form/connection-form-tabs.tsx @@ -2,10 +2,7 @@ import classnames from 'classnames'; import * as React from 'react'; import { connect } from 'react-redux'; -import { - ActionTypes, - SetConnectionFormTabAction -} from '../../store/actions'; +import { ActionTypes, SetConnectionFormTabAction } from '../../store/actions'; import { AppState } from '../../store/store'; import { CONNECTION_FORM_TABS } from '../../store/constants'; @@ -22,58 +19,76 @@ type DispatchProps = { type props = StateProps & DispatchProps; export class ConnectionFormTabs extends React.Component { - onClickNewConnectFormTab = (e: React.MouseEvent, newTab: CONNECTION_FORM_TABS): void => { + onClickNewConnectFormTab = ( + e: React.MouseEvent, + newTab: CONNECTION_FORM_TABS + ): void => { e.preventDefault(); this.props.setConnectionFormTab(newTab); }; render(): React.ReactNode { - const { - connectionFormTab - } = this.props; + const { connectionFormTab } = this.props; return ( -
+
+ > + General + + > + SSL/TLS + + > + SSH Tunnel + + > + Advanced +
); } @@ -81,15 +96,17 @@ export class ConnectionFormTabs extends React.Component { const mapStateToProps = (state: AppState): StateProps => { return { - connectionFormTab: state.connectionFormTab + connectionFormTab: state.connectionFormTab, }; }; const mapDispatchToProps: DispatchProps = { - setConnectionFormTab: (connectionFormTab: CONNECTION_FORM_TABS): SetConnectionFormTabAction => ({ + setConnectionFormTab: ( + connectionFormTab: CONNECTION_FORM_TABS + ): SetConnectionFormTabAction => ({ type: ActionTypes.SET_CONNECTION_FORM_TAB, - connectionFormTab - }) + connectionFormTab, + }), }; export default connect(mapStateToProps, mapDispatchToProps)(ConnectionFormTabs); diff --git a/src/views/webview-app/components/connect-form/connection-form.less b/src/views/webview-app/components/connect-form/connection-form.less index 3e47f2a2..6b38e715 100644 --- a/src/views/webview-app/components/connect-form/connection-form.less +++ b/src/views/webview-app/components/connect-form/connection-form.less @@ -1,4 +1,4 @@ -@import "~../../styles/_variables"; +@import '~../../styles/_variables'; .connection-form { margin-top: 0em; diff --git a/src/views/webview-app/components/connect-form/connection-form.tsx b/src/views/webview-app/components/connect-form/connection-form.tsx index 3598cd1c..651f27ad 100644 --- a/src/views/webview-app/components/connect-form/connection-form.tsx +++ b/src/views/webview-app/components/connect-form/connection-form.tsx @@ -1,10 +1,7 @@ import * as React from 'react'; import { connect } from 'react-redux'; -import { - ActionTypes, - ConnectionFormChangedAction -} from '../../store/actions'; +import { ActionTypes, ConnectionFormChangedAction } from '../../store/actions'; import SSLMethodTab from './ssl-tab/ssl-tab'; import SSHTunnelTab from './ssh-tab/ssh-tunnel-tab'; import FormActions from '../form/form-actions'; @@ -42,7 +39,7 @@ export class ConnectionForm extends React.Component { isConnecting, isValid, onConnectionFormChanged, - syntaxErrorMessage + syntaxErrorMessage, } = this.props; return ( @@ -57,7 +54,9 @@ export class ConnectionForm extends React.Component { {connectionFormTab === CONNECTION_FORM_TABS.GENERAL && } {connectionFormTab === CONNECTION_FORM_TABS.SSL && } {connectionFormTab === CONNECTION_FORM_TABS.SSH && } - {connectionFormTab === CONNECTION_FORM_TABS.ADVANCED && } + {connectionFormTab === CONNECTION_FORM_TABS.ADVANCED && ( + + )}
{ isConnected: state.isConnected, isConnecting: state.isConnecting, isValid: state.isValid, - syntaxErrorMessage: state.syntaxErrorMessage + syntaxErrorMessage: state.syntaxErrorMessage, }; }; const mapDispatchToProps: DispatchProps = { // Resets URL validation if form was changed. onConnectionFormChanged: (): ConnectionFormChangedAction => ({ - type: ActionTypes.CONNECTION_FORM_CHANGED - }) + type: ActionTypes.CONNECTION_FORM_CHANGED, + }), }; export default connect(mapStateToProps, mapDispatchToProps)(ConnectionForm); diff --git a/src/views/webview-app/components/connect-form/general-tab/authentication/authentication.tsx b/src/views/webview-app/components/connect-form/general-tab/authentication/authentication.tsx index 98dce6a6..5b350a41 100644 --- a/src/views/webview-app/components/connect-form/general-tab/authentication/authentication.tsx +++ b/src/views/webview-app/components/connect-form/general-tab/authentication/authentication.tsx @@ -1,9 +1,12 @@ import * as React from 'react'; import { connect } from 'react-redux'; -import { ActionTypes, AuthStrategyChangedAction } from '../../../../store/actions'; +import { + ActionTypes, + AuthStrategyChangedAction, +} from '../../../../store/actions'; import AUTH_STRATEGIES, { - AuthStrategies + AuthStrategies, } from '../../../../connection-model/constants/auth-strategies'; import FormGroup from '../../../form/form-group'; import Kerberos from './kerberos'; @@ -33,7 +36,9 @@ type DispatchProps = { onAuthStrategyChanged: (authStrategy: AUTH_STRATEGIES) => void; }; -export class Authentication extends React.Component { +export class Authentication extends React.Component< + StateProps & DispatchProps +> { /** * Changes an authentication strategy. * @@ -56,7 +61,7 @@ export class Authentication extends React.Component kerberosCanonicalizeHostname, kerberosPassword, kerberosPrincipal, - kerberosServiceName + kerberosServiceName, } = this.props; return ( @@ -81,11 +86,8 @@ export class Authentication extends React.Component ); } if (authStrategy === AUTH_STRATEGIES.MONGODB) { - const { - mongodbDatabaseName, - mongodbPassword, - mongodbUsername - } = this.props; + const { mongodbDatabaseName, mongodbPassword, mongodbUsername } = + this.props; return ( ); } if (authStrategy === AUTH_STRATEGIES['SCRAM-SHA-256']) { - const { - mongodbDatabaseName, - mongodbPassword, - mongodbUsername - } = this.props; + const { mongodbDatabaseName, mongodbPassword, mongodbUsername } = + this.props; return ( name="authStrategy" options={AuthStrategies.map((authStrat) => ({ label: authStrat.title, - value: authStrat.id + value: authStrat.id, }))} onChange={this.onAuthStrategyChanged} value={authStrategy} @@ -143,7 +142,8 @@ const mapStateToProps = (state: AppState): StateProps => { return { authStrategy: state.currentConnection.authStrategy, isValid: state.isValid, - kerberosCanonicalizeHostname: state.currentConnection.kerberosCanonicalizeHostname, + kerberosCanonicalizeHostname: + state.currentConnection.kerberosCanonicalizeHostname, kerberosPassword: state.currentConnection.kerberosPassword, kerberosPrincipal: state.currentConnection.kerberosPrincipal, kerberosServiceName: state.currentConnection.kerberosServiceName, @@ -152,15 +152,15 @@ const mapStateToProps = (state: AppState): StateProps => { mongodbDatabaseName: state.currentConnection.mongodbDatabaseName, mongodbPassword: state.currentConnection.mongodbPassword, mongodbUsername: state.currentConnection.mongodbUsername, - x509Username: state.currentConnection.x509Username + x509Username: state.currentConnection.x509Username, }; }; const mapDispatchToProps: DispatchProps = { onAuthStrategyChanged: (newAuthStrategy): AuthStrategyChangedAction => ({ type: ActionTypes.AUTH_STRATEGY_CHANGED, - authStrategy: newAuthStrategy - }) + authStrategy: newAuthStrategy, + }), }; export default connect(mapStateToProps, mapDispatchToProps)(Authentication); diff --git a/src/views/webview-app/components/connect-form/general-tab/authentication/kerberos.tsx b/src/views/webview-app/components/connect-form/general-tab/authentication/kerberos.tsx index 80a623eb..667aacfc 100644 --- a/src/views/webview-app/components/connect-form/general-tab/authentication/kerberos.tsx +++ b/src/views/webview-app/components/connect-form/general-tab/authentication/kerberos.tsx @@ -5,7 +5,7 @@ import Toggle from '@leafygreen-ui/toggle'; import { ActionTypes, KerberosParameters, - KerberosParametersChanged + KerberosParametersChanged, } from '../../../../store/actions'; import FormInput from '../../../form/form-input'; @@ -36,14 +36,14 @@ class Kerberos extends React.Component { const { kerberosCanonicalizeHostname, kerberosPassword, - kerberosServiceName + kerberosServiceName, } = this.props; this.props.kerberosParametersChanged({ kerberosCanonicalizeHostname, kerberosPassword, kerberosPrincipal: evt.target.value.trim(), - kerberosServiceName + kerberosServiceName, }); }; @@ -56,14 +56,14 @@ class Kerberos extends React.Component { const { kerberosCanonicalizeHostname, kerberosPrincipal, - kerberosServiceName + kerberosServiceName, } = this.props; this.props.kerberosParametersChanged({ kerberosCanonicalizeHostname, kerberosPassword: evt.target.value, kerberosPrincipal, - kerberosServiceName + kerberosServiceName, }); }; @@ -76,14 +76,14 @@ class Kerberos extends React.Component { const { kerberosCanonicalizeHostname, kerberosPassword, - kerberosPrincipal + kerberosPrincipal, } = this.props; this.props.kerberosParametersChanged({ kerberosCanonicalizeHostname, kerberosPassword, kerberosPrincipal, - kerberosServiceName: evt.target.value + kerberosServiceName: evt.target.value, }); }; @@ -92,14 +92,14 @@ class Kerberos extends React.Component { kerberosCanonicalizeHostname, kerberosPassword, kerberosPrincipal, - kerberosServiceName + kerberosServiceName, } = this.props; this.props.kerberosParametersChanged({ kerberosCanonicalizeHostname: !kerberosCanonicalizeHostname, kerberosPassword, kerberosPrincipal, - kerberosServiceName + kerberosServiceName, }); }; @@ -114,7 +114,7 @@ class Kerberos extends React.Component { kerberosCanonicalizeHostname, kerberosPassword, kerberosPrincipal, - kerberosServiceName + kerberosServiceName, } = this.props; return ( @@ -168,8 +168,8 @@ const mapDispatchToProps: DispatchProps = { newKerberosParams ): KerberosParametersChanged => ({ type: ActionTypes.KERBEROS_PARAMETERS_CHANGED, - ...newKerberosParams - }) + ...newKerberosParams, + }), }; export default connect(null, mapDispatchToProps)(Kerberos); diff --git a/src/views/webview-app/components/connect-form/general-tab/authentication/ldap.tsx b/src/views/webview-app/components/connect-form/general-tab/authentication/ldap.tsx index 0c62045e..6de7112e 100644 --- a/src/views/webview-app/components/connect-form/general-tab/authentication/ldap.tsx +++ b/src/views/webview-app/components/connect-form/general-tab/authentication/ldap.tsx @@ -4,7 +4,7 @@ import { connect } from 'react-redux'; import { ActionTypes, LDAPPasswordChangedAction, - LDAPUsernameChangedAction + LDAPUsernameChangedAction, } from '../../../../store/actions'; import FormInput from '../../../form/form-input'; @@ -76,12 +76,12 @@ class LDAP extends React.Component { const mapDispatchToProps: DispatchProps = { onLDAPPasswordChanged: (newPassword): LDAPPasswordChangedAction => ({ type: ActionTypes.LDAP_PASSWORD_CHANGED, - ldapPassword: newPassword + ldapPassword: newPassword, }), onLDAPUsernameChanged: (newPassword): LDAPUsernameChangedAction => ({ type: ActionTypes.LDAP_USERNAME_CHANGED, - ldapUsername: newPassword - }) + ldapUsername: newPassword, + }), }; export default connect(null, mapDispatchToProps)(LDAP); diff --git a/src/views/webview-app/components/connect-form/general-tab/authentication/mongodb-authentication.tsx b/src/views/webview-app/components/connect-form/general-tab/authentication/mongodb-authentication.tsx index ad8a522c..ec35efc5 100644 --- a/src/views/webview-app/components/connect-form/general-tab/authentication/mongodb-authentication.tsx +++ b/src/views/webview-app/components/connect-form/general-tab/authentication/mongodb-authentication.tsx @@ -5,7 +5,7 @@ import { ActionTypes, AuthSourceChangedAction, PasswordChangedAction, - UsernameChangedAction + UsernameChangedAction, } from '../../../../store/actions'; import FormInput from '../../../form/form-input'; @@ -51,12 +51,8 @@ class MongoDBAuthentication extends React.Component { }; render(): React.ReactNode { - const { - isValid, - mongodbDatabaseName, - mongodbPassword, - mongodbUsername - } = this.props; + const { isValid, mongodbDatabaseName, mongodbPassword, mongodbUsername } = + this.props; return (
@@ -92,16 +88,16 @@ class MongoDBAuthentication extends React.Component { const mapDispatchToProps: DispatchProps = { onAuthSourceChanged: (newAuthSource: string): AuthSourceChangedAction => ({ type: ActionTypes.AUTH_SOURCE_CHANGED, - mongodbDatabaseName: newAuthSource + mongodbDatabaseName: newAuthSource, }), onPasswordChanged: (newPassword: string): PasswordChangedAction => ({ type: ActionTypes.PASSWORD_CHANGED, - mongodbPassword: newPassword + mongodbPassword: newPassword, }), onUsernameChanged: (newPassword: string): UsernameChangedAction => ({ type: ActionTypes.USERNAME_CHANGED, - mongodbUsername: newPassword - }) + mongodbUsername: newPassword, + }), }; export default connect(null, mapDispatchToProps)(MongoDBAuthentication); diff --git a/src/views/webview-app/components/connect-form/general-tab/authentication/scram-sha-256.tsx b/src/views/webview-app/components/connect-form/general-tab/authentication/scram-sha-256.tsx index 6cda9da8..2adf72c4 100644 --- a/src/views/webview-app/components/connect-form/general-tab/authentication/scram-sha-256.tsx +++ b/src/views/webview-app/components/connect-form/general-tab/authentication/scram-sha-256.tsx @@ -5,7 +5,7 @@ import { ActionTypes, AuthSourceChangedAction, PasswordChangedAction, - UsernameChangedAction + UsernameChangedAction, } from '../../../../store/actions'; import FormInput from '../../../form/form-input'; @@ -51,12 +51,8 @@ class ScramSha256 extends React.Component { }; render(): React.ReactNode { - const { - isValid, - mongodbDatabaseName, - mongodbPassword, - mongodbUsername - } = this.props; + const { isValid, mongodbDatabaseName, mongodbPassword, mongodbUsername } = + this.props; return (
@@ -92,16 +88,16 @@ class ScramSha256 extends React.Component { const mapDispatchToProps: DispatchProps = { onAuthSourceChanged: (newAuthSource: string): AuthSourceChangedAction => ({ type: ActionTypes.AUTH_SOURCE_CHANGED, - mongodbDatabaseName: newAuthSource + mongodbDatabaseName: newAuthSource, }), onPasswordChanged: (newPassword: string): PasswordChangedAction => ({ type: ActionTypes.PASSWORD_CHANGED, - mongodbPassword: newPassword + mongodbPassword: newPassword, }), onUsernameChanged: (newPassword: string): UsernameChangedAction => ({ type: ActionTypes.USERNAME_CHANGED, - mongodbUsername: newPassword - }) + mongodbUsername: newPassword, + }), }; export default connect(null, mapDispatchToProps)(ScramSha256); diff --git a/src/views/webview-app/components/connect-form/general-tab/authentication/x509.tsx b/src/views/webview-app/components/connect-form/general-tab/authentication/x509.tsx index 126dc192..ee58d096 100644 --- a/src/views/webview-app/components/connect-form/general-tab/authentication/x509.tsx +++ b/src/views/webview-app/components/connect-form/general-tab/authentication/x509.tsx @@ -1,7 +1,10 @@ import * as React from 'react'; import { connect } from 'react-redux'; -import { ActionTypes, X509UsernameChangedAction } from '../../../../store/actions'; +import { + ActionTypes, + X509UsernameChangedAction, +} from '../../../../store/actions'; import FormInput from '../../../form/form-input'; type DispatchProps = { @@ -49,8 +52,8 @@ class X509 extends React.Component { const mapDispatchToProps: DispatchProps = { onX509UsernameChanged: (newUsername: string): X509UsernameChangedAction => ({ type: ActionTypes.X509_USERNAME_CHANGED, - x509Username: newUsername - }) + x509Username: newUsername, + }), }; export default connect(null, mapDispatchToProps)(X509); diff --git a/src/views/webview-app/components/connect-form/general-tab/host/host.less b/src/views/webview-app/components/connect-form/general-tab/host/host.less index 4dc411e7..a28f88ad 100644 --- a/src/views/webview-app/components/connect-form/general-tab/host/host.less +++ b/src/views/webview-app/components/connect-form/general-tab/host/host.less @@ -1,4 +1,3 @@ - .host-input-area { margin: 0; margin-top: 15px; diff --git a/src/views/webview-app/components/connect-form/general-tab/host/host.tsx b/src/views/webview-app/components/connect-form/general-tab/host/host.tsx index cdb8d0ab..58a4a1db 100644 --- a/src/views/webview-app/components/connect-form/general-tab/host/host.tsx +++ b/src/views/webview-app/components/connect-form/general-tab/host/host.tsx @@ -8,13 +8,16 @@ import { HostsChangedAction, IsSrvRecordToggledAction, PortChangedAction, - ReplicaSetChangedAction + ReplicaSetChangedAction, } from '../../../../store/actions'; import FormInput from '../../../form/form-input'; import { AppState } from '../../../../store/store'; import FormGroup from '../../../form/form-group'; import RadioBoxGroup from '../../../form/radio-box-group/radio-box-group'; -import { DEFAULT_HOST, Host } from '../../../../connection-model/legacy-connection-model'; +import { + DEFAULT_HOST, + Host, +} from '../../../../connection-model/legacy-connection-model'; import ReplicaSetInput from './replica-set-input'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faPlus, faMinus } from '@fortawesome/free-solid-svg-icons'; @@ -24,27 +27,27 @@ const styles = require('./host.less'); enum CONNECTION_TYPE { STANDALONE = 'STANDALONE', REPLICA_SET = 'REPLICA_SET', - SRV_RECORD = 'SRV_RECORD' + SRV_RECORD = 'SRV_RECORD', } const CONNECTION_TYPE_OPTIONS: { [connectionType in CONNECTION_TYPE]: { label: string; value: CONNECTION_TYPE; - } + }; } = { [CONNECTION_TYPE.STANDALONE]: { label: 'Standalone', - value: CONNECTION_TYPE.STANDALONE + value: CONNECTION_TYPE.STANDALONE, }, [CONNECTION_TYPE.REPLICA_SET]: { label: 'Replica Set', - value: CONNECTION_TYPE.REPLICA_SET + value: CONNECTION_TYPE.REPLICA_SET, }, [CONNECTION_TYPE.SRV_RECORD]: { label: 'SRV Record', - value: CONNECTION_TYPE.SRV_RECORD - } + value: CONNECTION_TYPE.SRV_RECORD, + }, }; type StateProps = { @@ -64,7 +67,9 @@ type DispatchProps = { }; export class HostInput extends React.PureComponent { - onConnectionTypeChange = (event: React.ChangeEvent): void => { + onConnectionTypeChange = ( + event: React.ChangeEvent + ): void => { switch (event.target.value as CONNECTION_TYPE) { case CONNECTION_TYPE.STANDALONE: this.props.setReplicaSet(); @@ -101,7 +106,7 @@ export class HostInput extends React.PureComponent { onHostChanged = (updatedHost: Host, hostIndex: number): void => { const { hosts } = this.props; - const newHosts = [ ...hosts ]; + const newHosts = [...hosts]; newHosts[hostIndex] = updatedHost; @@ -122,8 +127,8 @@ export class HostInput extends React.PureComponent { this.props.updateHosts([ ...hosts, { - ...DEFAULT_HOST - } + ...DEFAULT_HOST, + }, ]); if (!replicaSet) { @@ -133,19 +138,25 @@ export class HostInput extends React.PureComponent { onHostnameChanged = (event: React.ChangeEvent): void => { this.props.onHostnameChanged(event.target.value); - this.onHostChanged({ - host: event.target.value, - port: this.props.hosts[0].port - }, 0); + this.onHostChanged( + { + host: event.target.value, + port: this.props.hosts[0].port, + }, + 0 + ); }; onPortChanged = (event: React.ChangeEvent): void => { const port = +event.target.value; this.props.onPortChanged(port); - this.onHostChanged({ - host: this.props.hosts[0].host, - port - }, 0); + this.onHostChanged( + { + host: this.props.hosts[0].host, + port, + }, + 0 + ); }; onRemoveHost = ( @@ -156,17 +167,14 @@ export class HostInput extends React.PureComponent { const { hosts } = this.props; - const newHosts = [ ...hosts ]; + const newHosts = [...hosts]; newHosts.splice(hostIndex, 1); this.props.updateHosts(newHosts); }; getCurrentConnectionType = (): CONNECTION_TYPE => { - const { - isSrvRecord, - replicaSet - } = this.props; + const { isSrvRecord, replicaSet } = this.props; if (isSrvRecord) { return CONNECTION_TYPE.SRV_RECORD; @@ -190,15 +198,10 @@ export class HostInput extends React.PureComponent { } renderStandaloneHost(): React.ReactNode { - const { - hostname, - port - } = this.props; + const { hostname, port } = this.props; return ( -
+
{ className={`${styles['host-add-host-button']} ${styles['first-host']}`} onClick={this.onAddNewHost} > - +
); } renderReplicaSetOptions(): React.ReactNode { - const { - hosts - } = this.props; + const { hosts } = this.props; return ( {hosts.map((host, index) => ( -
+
): void => this.onHostChanged({ - host: event.target.value, - port: host.port - }, index)} + changeHandler={( + event: React.ChangeEvent + ): void => + this.onHostChanged( + { + host: event.target.value, + port: host.port, + }, + index + ) + } value={host.host} /> { label={index === 0 ? 'Port' : undefined} name={`host-port-${index}`} placeholder="27017" - changeHandler={(event: React.ChangeEvent): void => this.onHostChanged({ - host: host.host, - port: +event.target.value - }, index)} + changeHandler={( + event: React.ChangeEvent + ): void => + this.onHostChanged( + { + host: host.host, + port: +event.target.value, + }, + index + ) + } value={host.port} type="number" /> - {hosts.length > 1 && ()} + {hosts.length > 1 && ( + + )}
))} @@ -338,30 +346,30 @@ const mapStateToProps = (state: AppState): StateProps => { hosts: state.currentConnection.hosts, isSrvRecord: state.currentConnection.isSrvRecord, port: state.currentConnection.port, - replicaSet: state.currentConnection.replicaSet + replicaSet: state.currentConnection.replicaSet, }; }; const mapDispatchToProps: DispatchProps = { onHostnameChanged: (newHostname: string): HostnameChangedAction => ({ type: ActionTypes.HOSTNAME_CHANGED, - hostname: newHostname + hostname: newHostname, }), onPortChanged: (port: number): PortChangedAction => ({ type: ActionTypes.PORT_CHANGED, - port + port, }), setReplicaSet: (replicaSet?: string): ReplicaSetChangedAction => ({ type: ActionTypes.REPLICA_SET_CHANGED, - replicaSet + replicaSet, }), toggleSRVRecord: (): IsSrvRecordToggledAction => ({ - type: ActionTypes.IS_SRV_RECORD_TOGGLED + type: ActionTypes.IS_SRV_RECORD_TOGGLED, }), updateHosts: (hosts: Host[]): HostsChangedAction => ({ type: ActionTypes.HOSTS_CHANGED, - hosts - }) + hosts, + }), }; export default connect(mapStateToProps, mapDispatchToProps)(HostInput); diff --git a/src/views/webview-app/components/connect-form/general-tab/host/replica-set-input.tsx b/src/views/webview-app/components/connect-form/general-tab/host/replica-set-input.tsx index e1fbe3ab..fe096a7d 100644 --- a/src/views/webview-app/components/connect-form/general-tab/host/replica-set-input.tsx +++ b/src/views/webview-app/components/connect-form/general-tab/host/replica-set-input.tsx @@ -1,7 +1,10 @@ import * as React from 'react'; import { connect } from 'react-redux'; -import { ActionTypes, ReplicaSetChangedAction } from '../../../../store/actions'; +import { + ActionTypes, + ReplicaSetChangedAction, +} from '../../../../store/actions'; import { AppState } from '../../../../store/store'; import FormInput from '../../../form/form-input'; @@ -34,7 +37,7 @@ class ReplicaSetInput extends React.PureComponent { const mapStateToProps = (state: AppState): StateProps => { return { - replicaSet: state.currentConnection.replicaSet + replicaSet: state.currentConnection.replicaSet, }; }; @@ -43,8 +46,8 @@ const mapDispatchToProps: DispatchProps = { newReplicaSetName: string ): ReplicaSetChangedAction => ({ type: ActionTypes.REPLICA_SET_CHANGED, - replicaSet: newReplicaSetName - }) + replicaSet: newReplicaSetName, + }), }; export default connect(mapStateToProps, mapDispatchToProps)(ReplicaSetInput); diff --git a/src/views/webview-app/components/connect-form/general-tab/srv-input.tsx b/src/views/webview-app/components/connect-form/general-tab/srv-input.tsx index fe2fbb0e..1159f03f 100644 --- a/src/views/webview-app/components/connect-form/general-tab/srv-input.tsx +++ b/src/views/webview-app/components/connect-form/general-tab/srv-input.tsx @@ -51,14 +51,14 @@ class SRVInput extends React.PureComponent { const mapStateToProps = (state: AppState): StateProps => { return { - isSrvRecord: state.currentConnection.isSrvRecord + isSrvRecord: state.currentConnection.isSrvRecord, }; }; const mapDispatchToProps: DispatchProps = { onSRVRecordToggled: (): IsSrvRecordToggledAction => ({ - type: ActionTypes.IS_SRV_RECORD_TOGGLED - }) + type: ActionTypes.IS_SRV_RECORD_TOGGLED, + }), }; export default connect(mapStateToProps, mapDispatchToProps)(SRVInput); diff --git a/src/views/webview-app/components/connect-form/ssh-tab/ssh-tunnel-identity-file-validation.tsx b/src/views/webview-app/components/connect-form/ssh-tab/ssh-tunnel-identity-file-validation.tsx index b03b7090..42d3c55a 100644 --- a/src/views/webview-app/components/connect-form/ssh-tab/ssh-tunnel-identity-file-validation.tsx +++ b/src/views/webview-app/components/connect-form/ssh-tab/ssh-tunnel-identity-file-validation.tsx @@ -7,7 +7,7 @@ import { SSHTunnelHostnameChangedAction, SSHTunnelPassphraseChangedAction, SSHTunnelPortChangedAction, - SSHTunnelUsernameChangedAction + SSHTunnelUsernameChangedAction, } from '../../../store/actions'; import { AppState } from '../../../store/store'; import FormInput from '../../form/form-input'; @@ -86,7 +86,7 @@ class SSHTunnelIdentityFileValidation extends React.Component { sshTunnelIdentityFile, sshTunnelPassphrase, sshTunnelPort, - sshTunnelUsername + sshTunnelUsername, } = this.props; return ( @@ -140,38 +140,38 @@ const mapStateToProps = (state: AppState): StateProps => { sshTunnelIdentityFile: state.currentConnection.sshTunnelIdentityFile, sshTunnelPassphrase: state.currentConnection.sshTunnelPassphrase, sshTunnelPort: state.currentConnection.sshTunnelPort, - sshTunnelUsername: state.currentConnection.sshTunnelUsername + sshTunnelUsername: state.currentConnection.sshTunnelUsername, }; }; const mapDispatchToProps: DispatchProps = { onChangeSSHTunnelIdentityFile: (): OnChangeSSHTunnelIdentityFileAction => ({ - type: ActionTypes.ON_CHANGE_SSH_TUNNEL_IDENTITY_FILE + type: ActionTypes.ON_CHANGE_SSH_TUNNEL_IDENTITY_FILE, }), onSSHTunnelHostnameChanged: ( sshTunnelHostname: string ): SSHTunnelHostnameChangedAction => ({ type: ActionTypes.SSH_TUNNEL_HOSTNAME_CHANGED, - sshTunnelHostname + sshTunnelHostname, }), onSSHTunnelPassphraseChanged: ( sshTunnelPassphrase: string ): SSHTunnelPassphraseChangedAction => ({ type: ActionTypes.SSH_TUNNEL_PASSPHRASE_CHANGED, - sshTunnelPassphrase + sshTunnelPassphrase, }), onSSHTunnelPortChanged: ( sshTunnelPort: number ): SSHTunnelPortChangedAction => ({ type: ActionTypes.SSH_TUNNEL_PORT_CHANGED, - sshTunnelPort + sshTunnelPort, }), onSSHTunnelUsernameChanged: ( sshTunnelUsername: string ): SSHTunnelUsernameChangedAction => ({ type: ActionTypes.SSH_TUNNEL_USERNAME_CHANGED, - sshTunnelUsername - }) + sshTunnelUsername, + }), }; export default connect( diff --git a/src/views/webview-app/components/connect-form/ssh-tab/ssh-tunnel-password-validation.tsx b/src/views/webview-app/components/connect-form/ssh-tab/ssh-tunnel-password-validation.tsx index 0c1dd7f3..be1cce74 100644 --- a/src/views/webview-app/components/connect-form/ssh-tab/ssh-tunnel-password-validation.tsx +++ b/src/views/webview-app/components/connect-form/ssh-tab/ssh-tunnel-password-validation.tsx @@ -6,7 +6,7 @@ import { SSHTunnelHostnameChangedAction, SSHTunnelPasswordChangedAction, SSHTunnelPortChangedAction, - SSHTunnelUsernameChangedAction + SSHTunnelUsernameChangedAction, } from '../../../store/actions'; import { AppState } from '../../../store/store'; import FormInput from '../../form/form-input'; @@ -72,7 +72,7 @@ class SSHTunnelPasswordValidation extends React.Component { sshTunnelHostname, sshTunnelPassword, sshTunnelPort, - sshTunnelUsername + sshTunnelUsername, } = this.props; return ( @@ -119,7 +119,7 @@ const mapStateToProps = (state: AppState): StateProps => { sshTunnelHostname: state.currentConnection.sshTunnelHostname, sshTunnelPassword: state.currentConnection.sshTunnelPassword, sshTunnelPort: state.currentConnection.sshTunnelPort, - sshTunnelUsername: state.currentConnection.sshTunnelUsername + sshTunnelUsername: state.currentConnection.sshTunnelUsername, }; }; @@ -128,26 +128,26 @@ const mapDispatchToProps: DispatchProps = { sshTunnelHostname: string ): SSHTunnelHostnameChangedAction => ({ type: ActionTypes.SSH_TUNNEL_HOSTNAME_CHANGED, - sshTunnelHostname + sshTunnelHostname, }), onSSHTunnelPasswordChanged: ( sshTunnelPassword: string ): SSHTunnelPasswordChangedAction => ({ type: ActionTypes.SSH_TUNNEL_PASSWORD_CHANGED, - sshTunnelPassword + sshTunnelPassword, }), onSSHTunnelPortChanged: ( sshTunnelPort: number ): SSHTunnelPortChangedAction => ({ type: ActionTypes.SSH_TUNNEL_PORT_CHANGED, - sshTunnelPort + sshTunnelPort, }), onSSHTunnelUsernameChanged: ( sshTunnelUsername: string ): SSHTunnelUsernameChangedAction => ({ type: ActionTypes.SSH_TUNNEL_USERNAME_CHANGED, - sshTunnelUsername - }) + sshTunnelUsername, + }), }; export default connect( diff --git a/src/views/webview-app/components/connect-form/ssh-tab/ssh-tunnel-tab.tsx b/src/views/webview-app/components/connect-form/ssh-tab/ssh-tunnel-tab.tsx index 5bc3332c..85040a63 100644 --- a/src/views/webview-app/components/connect-form/ssh-tab/ssh-tunnel-tab.tsx +++ b/src/views/webview-app/components/connect-form/ssh-tab/ssh-tunnel-tab.tsx @@ -3,7 +3,7 @@ import { connect } from 'react-redux'; import { ActionTypes, SSHTunnelChangedAction } from '../../../store/actions'; import SSH_TUNNEL_TYPES, { - SSHTunnelOptions + SSHTunnelOptions, } from '../../../connection-model/constants/ssh-tunnel-types'; import FormGroup from '../../form/form-group'; import RadioBoxGroup from '../../form/radio-box-group/radio-box-group'; @@ -56,7 +56,7 @@ class SSHTunnelTab extends React.Component { name="sshTunnel" options={SSHTunnelOptions.map((sshTunnelOption) => ({ label: sshTunnelOption.title, - value: sshTunnelOption.id + value: sshTunnelOption.id, }))} onChange={this.onSSHTunnelChanged} value={sshTunnel} @@ -68,14 +68,14 @@ class SSHTunnelTab extends React.Component { } const mapStateToProps = (state: AppState): StateProps => ({ - sshTunnel: state.currentConnection.sshTunnel + sshTunnel: state.currentConnection.sshTunnel, }); const mapDispatchToProps: DispatchProps = { onSSHTunnelChanged: (newSSHTunnel): SSHTunnelChangedAction => ({ type: ActionTypes.SSH_TUNNEL_CHANGED, - sshTunnel: newSSHTunnel - }) + sshTunnel: newSSHTunnel, + }), }; export default connect(mapStateToProps, mapDispatchToProps)(SSHTunnelTab); diff --git a/src/views/webview-app/components/connect-form/ssl-tab/ssl-server-client-validation.tsx b/src/views/webview-app/components/connect-form/ssl-tab/ssl-server-client-validation.tsx index ee7d5322..3d7d4da4 100644 --- a/src/views/webview-app/components/connect-form/ssl-tab/ssl-server-client-validation.tsx +++ b/src/views/webview-app/components/connect-form/ssl-tab/ssl-server-client-validation.tsx @@ -7,7 +7,7 @@ import { ActionTypes, OnChangeSSLCAAction, OnChangeSSLCertAction, - SSLPassChangedAction + SSLPassChangedAction, } from '../../../store/actions'; import { AppState } from '../../../store/store'; @@ -56,10 +56,7 @@ class SSLServerClientValidation extends React.Component { const { isValid, sslCA, sslCert, sslPass } = this.props; return ( -
+
{ isValid: state.isValid, sslCA: state.currentConnection.sslCA, sslCert: state.currentConnection.sslCert, - sslPass: state.currentConnection.sslPass + sslPass: state.currentConnection.sslPass, }; }; const mapDispatchToProps: DispatchProps = { onChangeSSLCA: (): OnChangeSSLCAAction => ({ - type: ActionTypes.ON_CHANGE_SSL_CA + type: ActionTypes.ON_CHANGE_SSL_CA, }), onChangeSSLCertificate: (): OnChangeSSLCertAction => ({ - type: ActionTypes.ON_CHANGE_SSL_CERT + type: ActionTypes.ON_CHANGE_SSL_CERT, }), sslPrivateKeyPasswordChanged: (newSSLPass: string): SSLPassChangedAction => ({ type: ActionTypes.SSL_PASS_CHANGED, - sslPass: newSSLPass - }) + sslPass: newSSLPass, + }), }; export default connect( diff --git a/src/views/webview-app/components/connect-form/ssl-tab/ssl-server-validation.tsx b/src/views/webview-app/components/connect-form/ssl-tab/ssl-server-validation.tsx index 2cd34bd3..c8ae589c 100644 --- a/src/views/webview-app/components/connect-form/ssl-tab/ssl-server-validation.tsx +++ b/src/views/webview-app/components/connect-form/ssl-tab/ssl-server-validation.tsx @@ -52,14 +52,14 @@ class SSLServerValidation extends React.Component { const mapStateToProps = (state: AppState): StateProps => { return { isValid: state.isValid, - sslCA: state.currentConnection.sslCA + sslCA: state.currentConnection.sslCA, }; }; const mapDispatchToProps: DispatchProps = { onChangeSSLCA: (): OnChangeSSLCAAction => ({ - type: ActionTypes.ON_CHANGE_SSL_CA - }) + type: ActionTypes.ON_CHANGE_SSL_CA, + }), }; export default connect( diff --git a/src/views/webview-app/components/connect-form/ssl-tab/ssl-tab.tsx b/src/views/webview-app/components/connect-form/ssl-tab/ssl-tab.tsx index 769a390f..15057eff 100644 --- a/src/views/webview-app/components/connect-form/ssl-tab/ssl-tab.tsx +++ b/src/views/webview-app/components/connect-form/ssl-tab/ssl-tab.tsx @@ -1,13 +1,10 @@ import * as React from 'react'; import { connect } from 'react-redux'; -import { - ActionTypes, - SSLMethodChangedAction -} from '../../../store/actions'; +import { ActionTypes, SSLMethodChangedAction } from '../../../store/actions'; import { AppState } from '../../../store/store'; import SSL_METHODS, { - SSLMethodOptions + SSLMethodOptions, } from '../../../connection-model/constants/ssl-methods'; import FormGroup from '../../form/form-group'; import RadioBoxGroup from '../../form/radio-box-group/radio-box-group'; @@ -58,7 +55,7 @@ class SSLTab extends React.Component { name="sslMethod" options={SSLMethodOptions.map((sslMethodOption) => ({ label: sslMethodOption.title, - value: sslMethodOption.id + value: sslMethodOption.id, }))} onChange={this.onSSLMethodChanged} value={sslMethod} @@ -71,15 +68,15 @@ class SSLTab extends React.Component { const mapStateToProps = (state: AppState): StateProps => { return { - sslMethod: state.currentConnection.sslMethod + sslMethod: state.currentConnection.sslMethod, }; }; const mapDispatchToProps: DispatchProps = { onSSLMethodChanged: (newSSLMethod): SSLMethodChangedAction => ({ type: ActionTypes.SSL_METHOD_CHANGED, - sslMethod: newSSLMethod - }) + sslMethod: newSSLMethod, + }), }; export default connect(mapStateToProps, mapDispatchToProps)(SSLTab); diff --git a/src/views/webview-app/components/connect-helper/connect-helper.less b/src/views/webview-app/components/connect-helper/connect-helper.less index 8ea31106..5bc937fc 100644 --- a/src/views/webview-app/components/connect-helper/connect-helper.less +++ b/src/views/webview-app/components/connect-helper/connect-helper.less @@ -1,4 +1,4 @@ -@import "~../../styles/_variables"; +@import '~../../styles/_variables'; .connect-helper { margin-top: 20px; @@ -54,7 +54,7 @@ transition: 250ms all; &:hover { - background-color: #FFFFFF; + background-color: #ffffff; color: #292929; } } @@ -68,13 +68,13 @@ background-color: rgba(255, 255, 255, 0.05); } -body[data-vscode-theme-kind="vscode-light"] { +body[data-vscode-theme-kind='vscode-light'] { .connect-connection-form-area { border-color: rgba(228, 244, 228, 0.9); } } -body[data-vscode-theme-kind="vscode-high-contrast"] { +body[data-vscode-theme-kind='vscode-high-contrast'] { .connect-connection-form-area { border-color: rgba(228, 244, 228, 0.9); } diff --git a/src/views/webview-app/components/connect-helper/connect-helper.tsx b/src/views/webview-app/components/connect-helper/connect-helper.tsx index 2c293863..131ef1ca 100644 --- a/src/views/webview-app/components/connect-helper/connect-helper.tsx +++ b/src/views/webview-app/components/connect-helper/connect-helper.tsx @@ -4,7 +4,7 @@ import { connect } from 'react-redux'; import { ActionTypes, OpenConnectionStringInputAction, - ToggleShowConnectionFormAction + ToggleShowConnectionFormAction, } from '../../store/actions'; const styles = require('./connect-helper.less'); @@ -26,18 +26,18 @@ function getOSCommandShortcutName(): string { export class ConnectHelper extends React.Component { render(): React.ReactNode { - const { - onOpenConnectionForm, - onOpenConnectionStringInput - } = this.props; + const { onOpenConnectionForm, onOpenConnectionStringInput } = this.props; return (
-
-
- Connect with -
+
+
Connect with
Connection String
@@ -51,13 +51,13 @@ export class ConnectHelper extends React.Component { Connect
-
-
- Advanced -
+
+
Advanced
Connection Settings
@@ -74,7 +74,8 @@ export class ConnectHelper extends React.Component {
- {getOSCommandShortcutName()} + Shift + P for all MongoDB Command Palette options + {getOSCommandShortcutName()} + Shift + P for all + MongoDB Command Palette options
); @@ -83,11 +84,11 @@ export class ConnectHelper extends React.Component { const mapDispatchToProps: DispatchProps = { onOpenConnectionStringInput: (): OpenConnectionStringInputAction => ({ - type: ActionTypes.OPEN_CONNECTION_STRING_INPUT + type: ActionTypes.OPEN_CONNECTION_STRING_INPUT, }), onOpenConnectionForm: (): ToggleShowConnectionFormAction => ({ - type: ActionTypes.TOGGLE_SHOW_CONNECTION_FORM - }) + type: ActionTypes.TOGGLE_SHOW_CONNECTION_FORM, + }), }; export default connect(() => ({}), mapDispatchToProps)(ConnectHelper); diff --git a/src/views/webview-app/components/connection-status/connection-status.less b/src/views/webview-app/components/connection-status/connection-status.less index 0039ed72..b0f36af1 100644 --- a/src/views/webview-app/components/connection-status/connection-status.less +++ b/src/views/webview-app/components/connection-status/connection-status.less @@ -1,4 +1,4 @@ -@import "~../../styles/_variables"; +@import '~../../styles/_variables'; .connection-status { padding: 11.5px; @@ -29,7 +29,7 @@ } .connection-status-dot-disconnected:before { - background-color: #BB2222; + background-color: #bb2222; } .connection-status-playground-area { diff --git a/src/views/webview-app/components/connection-status/connection-status.tsx b/src/views/webview-app/components/connection-status/connection-status.tsx index 7007fa14..746e6813 100644 --- a/src/views/webview-app/components/connection-status/connection-status.tsx +++ b/src/views/webview-app/components/connection-status/connection-status.tsx @@ -7,7 +7,7 @@ import { ActionTypes, CreateNewPlaygroundAction, RenameConnectionAction, - RequestConnectionStatusAction + RequestConnectionStatusAction, } from '../../store/actions'; import InfoSprinkle from '../info-sprinkle/info-sprinkle'; import { CONNECTION_STATUS } from '../../extension-app-message-constants'; @@ -29,7 +29,9 @@ type DispatchProps = { requestConnectionStatus: () => void; }; -export class ConnectionStatus extends React.Component { +export class ConnectionStatus extends React.Component< + StateProps & DispatchProps +> { componentDidMount(): void { this.startConnectionStatusPolling(); } @@ -65,32 +67,32 @@ export class ConnectionStatus extends React.Component
- Connected to: {activeConnectionName} + + Connected to: {activeConnectionName}
+
All set. Ready to start?
- All set. Ready to start? -
-
- Create a playground. + Create a playground. +
); } @@ -142,17 +147,20 @@ export class ConnectionStatus extends React.Component - {connectionStatus === CONNECTION_STATUS.CONNECTED && this.renderConnectedStatus()} - {connectionStatus === CONNECTION_STATUS.CONNECTING && this.renderConnectingStatus()} - {connectionStatus === CONNECTION_STATUS.DISCONNECTED && this.renderDisconnectedStatus()} - {connectionStatus === CONNECTION_STATUS.DISCONNECTING && this.renderDisconnectingStatus()} - {connectionStatus === CONNECTION_STATUS.LOADING && this.renderLoadingStatus()} + {connectionStatus === CONNECTION_STATUS.CONNECTED && + this.renderConnectedStatus()} + {connectionStatus === CONNECTION_STATUS.CONNECTING && + this.renderConnectingStatus()} + {connectionStatus === CONNECTION_STATUS.DISCONNECTED && + this.renderDisconnectedStatus()} + {connectionStatus === CONNECTION_STATUS.DISCONNECTING && + this.renderDisconnectingStatus()} + {connectionStatus === CONNECTION_STATUS.LOADING && + this.renderLoadingStatus()}
); } @@ -161,21 +169,20 @@ export class ConnectionStatus extends React.Component { return { activeConnectionName: state.activeConnectionName, - connectionStatus: state.connectionStatus + connectionStatus: state.connectionStatus, }; }; const mapDispatchToProps: DispatchProps = { onClickCreatePlayground: (): CreateNewPlaygroundAction => ({ - type: ActionTypes.CREATE_NEW_PLAYGROUND + type: ActionTypes.CREATE_NEW_PLAYGROUND, }), onClickRenameConnection: (): RenameConnectionAction => ({ - type: ActionTypes.RENAME_CONNECTION + type: ActionTypes.RENAME_CONNECTION, }), requestConnectionStatus: (): RequestConnectionStatusAction => ({ - type: ActionTypes.REQUEST_CONNECTION_STATUS - }) + type: ActionTypes.REQUEST_CONNECTION_STATUS, + }), }; export default connect(mapStateToProps, mapDispatchToProps)(ConnectionStatus); - diff --git a/src/views/webview-app/components/form/divider/divider.less b/src/views/webview-app/components/form/divider/divider.less index 7b0b6fab..b7b77847 100644 --- a/src/views/webview-app/components/form/divider/divider.less +++ b/src/views/webview-app/components/form/divider/divider.less @@ -1,4 +1,3 @@ - .form-divider { background-color: rgba(75, 75, 75, 0.5); height: 1px; diff --git a/src/views/webview-app/components/form/divider/divider.tsx b/src/views/webview-app/components/form/divider/divider.tsx index a515a328..89cb5269 100644 --- a/src/views/webview-app/components/form/divider/divider.tsx +++ b/src/views/webview-app/components/form/divider/divider.tsx @@ -4,9 +4,7 @@ import styles from './divider.less'; export class Divider extends React.Component { render(): React.ReactNode { - return ( -
- ); + return
; } } diff --git a/src/views/webview-app/components/form/file-input-button.tsx b/src/views/webview-app/components/form/file-input-button.tsx index abe29c6d..541499f1 100644 --- a/src/views/webview-app/components/form/file-input-button.tsx +++ b/src/views/webview-app/components/form/file-input-button.tsx @@ -77,7 +77,7 @@ class FileInputButton extends React.Component {
{label && ( diff --git a/src/views/webview-app/components/form/form.less b/src/views/webview-app/components/form/form.less index 444c9cdf..38422bc7 100644 --- a/src/views/webview-app/components/form/form.less +++ b/src/views/webview-app/components/form/form.less @@ -1,4 +1,4 @@ -@import "~../../styles/_variables"; +@import '~../../styles/_variables'; @help-icon-button__color: rgba(255, 255, 255, 0.5); @@ -51,7 +51,8 @@ .form-item-file-button { width: 100%; background: var(--vscode-input-background, transparent); - border: 1px solid var(--vscode-searchEditor-textInputBorder, rgba(161, 161, 161, 0.5)); + border: 1px solid + var(--vscode-searchEditor-textInputBorder, rgba(161, 161, 161, 0.5)); border-radius: 3px; color: var(--vscode-editor-foreground); padding: 8px 4px 9px; @@ -114,7 +115,7 @@ } .btn { - background-color: var(--mongodb-green);; + background-color: var(--mongodb-green); padding: 9px 28px 10px; margin: 6px 0 0 0; display: inline-block; diff --git a/src/views/webview-app/components/form/radio-box-group/radio-box-group.less b/src/views/webview-app/components/form/radio-box-group/radio-box-group.less index 535d9767..0977bbbe 100644 --- a/src/views/webview-app/components/form/radio-box-group/radio-box-group.less +++ b/src/views/webview-app/components/form/radio-box-group/radio-box-group.less @@ -1,4 +1,4 @@ -@import "~../../../styles/_variables"; +@import '~../../../styles/_variables'; .radio-box-item { display: inline-block; @@ -14,14 +14,14 @@ } &:focus-within { - box-shadow: 0 0 5px #51CBEE; + box-shadow: 0 0 5px #51cbee; } } .radio-box-item-selected { background: @green-selected; border-color: transparent; - color: #1E1E1E; + color: #1e1e1e; } .radio-box-item-input { diff --git a/src/views/webview-app/components/form/radio-box-group/radio-box-group.tsx b/src/views/webview-app/components/form/radio-box-group/radio-box-group.tsx index eba4ba29..80362eeb 100644 --- a/src/views/webview-app/components/form/radio-box-group/radio-box-group.tsx +++ b/src/views/webview-app/components/form/radio-box-group/radio-box-group.tsx @@ -30,10 +30,7 @@ class RadioBoxGroup extends React.Component { }; renderOptions(): React.ReactNode { - const { - options, - value - } = this.props; + const { options, value } = this.props; return options.map((option, i) => { const checked = value === option.value; @@ -41,7 +38,7 @@ class RadioBoxGroup extends React.Component { return ( ); }); diff --git a/src/views/webview-app/components/info-sprinkle/info-sprinkle.less b/src/views/webview-app/components/info-sprinkle/info-sprinkle.less index 0c27ccdc..1485d10f 100644 --- a/src/views/webview-app/components/info-sprinkle/info-sprinkle.less +++ b/src/views/webview-app/components/info-sprinkle/info-sprinkle.less @@ -1,4 +1,4 @@ -@import "~../../styles/_variables"; +@import '~../../styles/_variables'; .info-sprinkle-icon { display: inline-block; diff --git a/src/views/webview-app/components/mongodb-logo/mongodb-logo.less b/src/views/webview-app/components/mongodb-logo/mongodb-logo.less index 65b444ff..05000dbe 100644 --- a/src/views/webview-app/components/mongodb-logo/mongodb-logo.less +++ b/src/views/webview-app/components/mongodb-logo/mongodb-logo.less @@ -6,4 +6,3 @@ fill: var(--mongodb-green); } } - diff --git a/src/views/webview-app/components/mongodb-logo/mongodb-logo.tsx b/src/views/webview-app/components/mongodb-logo/mongodb-logo.tsx index a48cd513..d9ab5bbf 100644 --- a/src/views/webview-app/components/mongodb-logo/mongodb-logo.tsx +++ b/src/views/webview-app/components/mongodb-logo/mongodb-logo.tsx @@ -1,18 +1,12 @@ import * as React from 'react'; -import { - MongoDBLogo as LeafyGreenMongoDBLogo -} from '@leafygreen-ui/logo'; +import { MongoDBLogo as LeafyGreenMongoDBLogo } from '@leafygreen-ui/logo'; const styles = require('./mongodb-logo.less'); class MongoDBLogo extends React.PureComponent { render(): React.ReactNode { - return ( - - ); + return ; } } diff --git a/src/views/webview-app/components/overview-page/overview-header/overview-header.less b/src/views/webview-app/components/overview-page/overview-header/overview-header.less index 9e7ccf44..d18cb2f2 100644 --- a/src/views/webview-app/components/overview-page/overview-header/overview-header.less +++ b/src/views/webview-app/components/overview-page/overview-header/overview-header.less @@ -7,7 +7,7 @@ } .overview-header-bar { - background-color: #3D4F58; + background-color: #3d4f58; margin: 0 auto; margin-top: 24px; height: 1px; diff --git a/src/views/webview-app/components/overview-page/overview-header/overview-header.tsx b/src/views/webview-app/components/overview-page/overview-header/overview-header.tsx index e1e43ae3..69d8fd2c 100644 --- a/src/views/webview-app/components/overview-page/overview-header/overview-header.tsx +++ b/src/views/webview-app/components/overview-page/overview-header/overview-header.tsx @@ -6,7 +6,7 @@ import bookIcon from '@iconify-icons/codicon/book'; import MongoDBLogo from '../../mongodb-logo/mongodb-logo'; import { ActionTypes, - ToggleShowResourcesPanelAction + ToggleShowResourcesPanelAction, } from '../../../store/actions'; const styles = require('./overview-header.less'); @@ -22,13 +22,8 @@ class OverviewHeader extends React.Component { className={styles['resources-button']} onClick={(): void => this.props.toggleShowResourcesPanel()} > - -
- Resources -
+ +
Resources
); } @@ -36,16 +31,15 @@ class OverviewHeader extends React.Component { render(): React.ReactNode { return (
-
+
- Navigate your databases and collections, use playgrounds for exploring and transforming your data + Navigate your databases and collections, use playgrounds for + exploring and transforming your data
{this.renderResourcesButton()}
-
+
); } @@ -53,8 +47,8 @@ class OverviewHeader extends React.Component { const mapDispatchToProps: DispatchProps = { toggleShowResourcesPanel: (): ToggleShowResourcesPanelAction => ({ - type: ActionTypes.TOGGLE_SHOW_RESOURCES_PANEL - }) + type: ActionTypes.TOGGLE_SHOW_RESOURCES_PANEL, + }), }; export default connect(null, mapDispatchToProps)(OverviewHeader); diff --git a/src/views/webview-app/components/overview-page/overview-page.tsx b/src/views/webview-app/components/overview-page/overview-page.tsx index 249ed12d..c62a45d2 100644 --- a/src/views/webview-app/components/overview-page/overview-page.tsx +++ b/src/views/webview-app/components/overview-page/overview-page.tsx @@ -18,10 +18,7 @@ type StateProps = { export class OverviewPage extends React.Component { render(): React.ReactNode { - const { - showConnectForm, - showResourcesPanel - } = this.props; + const { showConnectForm, showResourcesPanel } = this.props; return (
@@ -41,7 +38,7 @@ export class OverviewPage extends React.Component { const mapStateToProps = (state: AppState): StateProps => { return { showConnectForm: state.showConnectForm, - showResourcesPanel: state.showResourcesPanel + showResourcesPanel: state.showResourcesPanel, }; }; diff --git a/src/views/webview-app/components/resources-panel/resources-panel.less b/src/views/webview-app/components/resources-panel/resources-panel.less index 42e9e9bf..d486e58b 100644 --- a/src/views/webview-app/components/resources-panel/resources-panel.less +++ b/src/views/webview-app/components/resources-panel/resources-panel.less @@ -1,4 +1,4 @@ -@import "~../../styles/_variables"; +@import '~../../styles/_variables'; .resources-panel { position: fixed; diff --git a/src/views/webview-app/components/resources-panel/resources-panel.tsx b/src/views/webview-app/components/resources-panel/resources-panel.tsx index 816c37f8..038b9f74 100644 --- a/src/views/webview-app/components/resources-panel/resources-panel.tsx +++ b/src/views/webview-app/components/resources-panel/resources-panel.tsx @@ -8,64 +8,78 @@ import bookIcon from '@iconify-icons/codicon/book'; import { ActionTypes, LinkClickedAction, - ToggleShowResourcesPanelAction + ToggleShowResourcesPanelAction, } from '../../store/actions'; const styles = require('./resources-panel.less'); -const ResourceLinks = [{ - title: 'Product overview', - description: 'Get an overview on MongoDB', - linkId: 'productOverview', - url: 'https://docs.mongodb.com/' -}, { - title: 'Extension documentation', - description: 'Check the documentation about the extension', - linkId: 'extensionDocumentation', - url: 'https://docs.mongodb.com/mongodb-vscode/' -}, { - title: 'Connect to your database', - description: 'Connect in just a few steps', - linkId: 'connectInfo', - url: 'https://docs.mongodb.com/mongodb-vscode/connect' -}, { - title: 'Interact with your data', - description: 'Play with your data, create queries and aggregations', - linkId: 'interactWithYourData', - url: 'https://docs.mongodb.com/mongodb-vscode/playgrounds' -}]; +const ResourceLinks = [ + { + title: 'Product overview', + description: 'Get an overview on MongoDB', + linkId: 'productOverview', + url: 'https://docs.mongodb.com/', + }, + { + title: 'Extension documentation', + description: 'Check the documentation about the extension', + linkId: 'extensionDocumentation', + url: 'https://docs.mongodb.com/mongodb-vscode/', + }, + { + title: 'Connect to your database', + description: 'Connect in just a few steps', + linkId: 'connectInfo', + url: 'https://docs.mongodb.com/mongodb-vscode/connect', + }, + { + title: 'Interact with your data', + description: 'Play with your data, create queries and aggregations', + linkId: 'interactWithYourData', + url: 'https://docs.mongodb.com/mongodb-vscode/playgrounds', + }, +]; -const FooterFeatures = [{ - title: 'Navigate databases', - linkId: 'navigateDatabaseInfo', - url: 'https://docs.mongodb.com/mongodb-vscode/databases-collections' -}, { - title: 'Perform CRUD operations', - linkId: 'crudInfo', - url: 'https://docs.mongodb.com/mongodb-vscode/crud-ops' -}, { - title: 'Run aggregation pipelines', - linkId: 'aggPipelineInfo', - url: 'https://docs.mongodb.com/mongodb-vscode/run-agg-pipelines' -}, { - title: 'Playgrounds', - linkId: 'playgroundsInfo', - url: 'https://docs.mongodb.com/mongodb-vscode/playgrounds' -}]; +const FooterFeatures = [ + { + title: 'Navigate databases', + linkId: 'navigateDatabaseInfo', + url: 'https://docs.mongodb.com/mongodb-vscode/databases-collections', + }, + { + title: 'Perform CRUD operations', + linkId: 'crudInfo', + url: 'https://docs.mongodb.com/mongodb-vscode/crud-ops', + }, + { + title: 'Run aggregation pipelines', + linkId: 'aggPipelineInfo', + url: 'https://docs.mongodb.com/mongodb-vscode/run-agg-pipelines', + }, + { + title: 'Playgrounds', + linkId: 'playgroundsInfo', + url: 'https://docs.mongodb.com/mongodb-vscode/playgrounds', + }, +]; -const FooterLinks = [{ - title: 'Github', - linkId: 'github', - url: 'https://github.com/mongodb-js/vscode' -}, { - title: 'Suggest a feature', - linkId: 'feedback', - url: 'https://feedback.mongodb.com/forums/929236-mongodb-for-vs-code/' -}, { - title: 'Report a bug', - linkId: 'reportABug', - url: 'https://github.com/mongodb-js/vscode/issues' -}]; +const FooterLinks = [ + { + title: 'Github', + linkId: 'github', + url: 'https://github.com/mongodb-js/vscode', + }, + { + title: 'Suggest a feature', + linkId: 'feedback', + url: 'https://feedback.mongodb.com/forums/929236-mongodb-for-vs-code/', + }, + { + title: 'Report a bug', + linkId: 'reportABug', + url: 'https://github.com/mongodb-js/vscode/issues', + }, +]; const TELEMETRY_SCREEN_ID = 'overviewResourcesPanel'; @@ -86,15 +100,14 @@ class ResourcesPanel extends React.Component { className={styles['resources-panel-close']} onClick={(): void => this.props.toggleShowResourcesPanel()} > - +
 MongoDB resources + /> +  MongoDB resources
); @@ -103,24 +116,19 @@ class ResourcesPanel extends React.Component { renderLinks(): React.ReactNode { return (
- {ResourceLinks.map(resourceLink => ( + {ResourceLinks.map((resourceLink) => ( this.onLinkClicked( - TELEMETRY_SCREEN_ID, - resourceLink.linkId - )} + onClick={(): void => + this.onLinkClicked(TELEMETRY_SCREEN_ID, resourceLink.linkId) + } key={`link-${resourceLink.linkId}`} >
- - {resourceLink.title} - -
-
- {resourceLink.description} + {resourceLink.title}
+
{resourceLink.description}
{
Key features
- {FooterFeatures.map(footerFeature => ( + {FooterFeatures.map((footerFeature) => (
this.onLinkClicked( - TELEMETRY_SCREEN_ID, - footerFeature.linkId - )} + onClick={(): void => + this.onLinkClicked(TELEMETRY_SCREEN_ID, footerFeature.linkId) + } > {footerFeature.title} @@ -156,14 +163,13 @@ class ResourcesPanel extends React.Component {
Contribute
- {FooterLinks.map(footerLink => ( + {FooterLinks.map((footerLink) => ( this.onLinkClicked( - TELEMETRY_SCREEN_ID, - footerLink.linkId - )} + onClick={(): void => + this.onLinkClicked(TELEMETRY_SCREEN_ID, footerLink.linkId) + } key={`footer-link-${footerLink.linkId}`} > {footerLink.title} @@ -195,11 +201,11 @@ const mapDispatchToProps: DispatchProps = { onLinkClicked: (screen, linkId): LinkClickedAction => ({ type: ActionTypes.EXTENSION_LINK_CLICKED, screen, - linkId + linkId, }), toggleShowResourcesPanel: (): ToggleShowResourcesPanelAction => ({ - type: ActionTypes.TOGGLE_SHOW_RESOURCES_PANEL - }) + type: ActionTypes.TOGGLE_SHOW_RESOURCES_PANEL, + }), }; export default connect(null, mapDispatchToProps)(ResourcesPanel); diff --git a/src/views/webview-app/connect.module.less b/src/views/webview-app/connect.module.less index efa79461..902c87cd 100644 --- a/src/views/webview-app/connect.module.less +++ b/src/views/webview-app/connect.module.less @@ -1,4 +1,4 @@ -@import "~./styles/_variables"; +@import '~./styles/_variables'; .page { display: flex; @@ -18,8 +18,10 @@ div { border: none; - background-color: var(--vscode-searchEditor-textInputBorder, - rgba(161, 161, 161, 0.5)); + background-color: var( + --vscode-searchEditor-textInputBorder, + rgba(161, 161, 161, 0.5) + ); } } diff --git a/src/views/webview-app/connection-model/constants/auth-mechanism-to-auth-strategy.ts b/src/views/webview-app/connection-model/constants/auth-mechanism-to-auth-strategy.ts index 6583ca56..6821f1ed 100644 --- a/src/views/webview-app/connection-model/constants/auth-mechanism-to-auth-strategy.ts +++ b/src/views/webview-app/connection-model/constants/auth-mechanism-to-auth-strategy.ts @@ -8,5 +8,5 @@ export default { GSSAPI: 'KERBEROS', SSPI: 'KERBEROS', PLAIN: 'LDAP', - LDAP: 'LDAP' + LDAP: 'LDAP', }; diff --git a/src/views/webview-app/connection-model/constants/auth-strategies.ts b/src/views/webview-app/connection-model/constants/auth-strategies.ts index 82f77a96..7f7802c0 100644 --- a/src/views/webview-app/connection-model/constants/auth-strategies.ts +++ b/src/views/webview-app/connection-model/constants/auth-strategies.ts @@ -24,7 +24,7 @@ export enum AUTH_STRATEGY_VALUES { * @see http://bit.ly/mongodb-node-driver-ldap */ LDAP = 'LDAP', - 'SCRAM-SHA-256' = 'SCRAM-SHA-256' + 'SCRAM-SHA-256' = 'SCRAM-SHA-256', } type AuthStrategy = { @@ -35,15 +35,15 @@ type AuthStrategy = { export const AuthStrategies: AuthStrategy[] = [ { id: AUTH_STRATEGY_VALUES.NONE, - title: 'None' + title: 'None', }, { id: AUTH_STRATEGY_VALUES.MONGODB, - title: 'Username / Password' + title: 'Username / Password', }, { id: AUTH_STRATEGY_VALUES['SCRAM-SHA-256'], - title: 'SCRAM-SHA-256' + title: 'SCRAM-SHA-256', }, // Currently disabled. // { @@ -52,12 +52,12 @@ export const AuthStrategies: AuthStrategy[] = [ // }, { id: AUTH_STRATEGY_VALUES.LDAP, - title: 'LDAP' + title: 'LDAP', }, { id: AUTH_STRATEGY_VALUES.X509, - title: 'X.509' - } + title: 'X.509', + }, ]; export default AUTH_STRATEGY_VALUES; diff --git a/src/views/webview-app/connection-model/constants/auth-strategy-to-auth-mechanism.ts b/src/views/webview-app/connection-model/constants/auth-strategy-to-auth-mechanism.ts index ea790fad..7e6072a5 100644 --- a/src/views/webview-app/connection-model/constants/auth-strategy-to-auth-mechanism.ts +++ b/src/views/webview-app/connection-model/constants/auth-strategy-to-auth-mechanism.ts @@ -5,5 +5,5 @@ export default { KERBEROS: 'GSSAPI', X509: 'MONGODB-X509', LDAP: 'PLAIN', - 'SCRAM-SHA-256': 'SCRAM-SHA-256' + 'SCRAM-SHA-256': 'SCRAM-SHA-256', }; diff --git a/src/views/webview-app/connection-model/constants/auth-strategy-to-field-names.ts b/src/views/webview-app/connection-model/constants/auth-strategy-to-field-names.ts index 565a426a..05acfb45 100644 --- a/src/views/webview-app/connection-model/constants/auth-strategy-to-field-names.ts +++ b/src/views/webview-app/connection-model/constants/auth-strategy-to-field-names.ts @@ -4,24 +4,24 @@ export default { MONGODB: [ 'mongodbUsername', // required 'mongodbPassword', // required - 'mongodbDatabaseName' // optional + 'mongodbDatabaseName', // optional ], 'SCRAM-SHA-256': [ 'mongodbUsername', // required 'mongodbPassword', // required - 'mongodbDatabaseName' // optional + 'mongodbDatabaseName', // optional ], KERBEROS: [ 'kerberosPrincipal', // required 'kerberosPassword', // optional 'kerberosServiceName', // optional - 'kerberosCanonicalizeHostname' + 'kerberosCanonicalizeHostname', ], X509: [ - 'x509Username' // required + 'x509Username', // required ], LDAP: [ 'ldapUsername', // required - 'ldapPassword' // required - ] + 'ldapPassword', // required + ], }; diff --git a/src/views/webview-app/connection-model/constants/connection-types.ts b/src/views/webview-app/connection-model/constants/connection-types.ts index 6af3a0c8..76714aa5 100644 --- a/src/views/webview-app/connection-model/constants/connection-types.ts +++ b/src/views/webview-app/connection-model/constants/connection-types.ts @@ -2,7 +2,7 @@ enum CONNECTION_TYPES { NODE_DRIVER = 'NODE_DRIVER', STITCH_ON_PREM = 'STITCH_ON_PREM', - STITCH_ATLAS = 'STITCH_ATLAS' + STITCH_ATLAS = 'STITCH_ATLAS', } export default CONNECTION_TYPES; diff --git a/src/views/webview-app/connection-model/constants/read-preferences.ts b/src/views/webview-app/connection-model/constants/read-preferences.ts index 1cee7244..d846e033 100644 --- a/src/views/webview-app/connection-model/constants/read-preferences.ts +++ b/src/views/webview-app/connection-model/constants/read-preferences.ts @@ -3,7 +3,7 @@ enum READ_PREFERENCES { PRIMARY_PREFERRED = 'primaryPreferred', SECONDARY = 'secondary', SECONDARY_PREFERRED = 'secondaryPreferred', - NEAREST = 'nearest' + NEAREST = 'nearest', } export default READ_PREFERENCES; diff --git a/src/views/webview-app/connection-model/constants/ssh-tunnel-types.ts b/src/views/webview-app/connection-model/constants/ssh-tunnel-types.ts index 258231f7..25e08593 100644 --- a/src/views/webview-app/connection-model/constants/ssh-tunnel-types.ts +++ b/src/views/webview-app/connection-model/constants/ssh-tunnel-types.ts @@ -11,7 +11,7 @@ export enum SSH_TUNNEL_TYPES { /** * The tunnel is created using an identity file. */ - IDENTITY_FILE = 'IDENTITY_FILE' + IDENTITY_FILE = 'IDENTITY_FILE', } type SSHTunnelOption = { @@ -22,16 +22,16 @@ type SSHTunnelOption = { export const SSHTunnelOptions: SSHTunnelOption[] = [ { id: SSH_TUNNEL_TYPES.NONE, - title: 'None' + title: 'None', }, { id: SSH_TUNNEL_TYPES.USER_PASSWORD, - title: 'Use Password' + title: 'Use Password', }, { id: SSH_TUNNEL_TYPES.IDENTITY_FILE, - title: 'Use Identity File' - } + title: 'Use Identity File', + }, ]; export default SSH_TUNNEL_TYPES; diff --git a/src/views/webview-app/connection-model/constants/ssl-methods.ts b/src/views/webview-app/connection-model/constants/ssl-methods.ts index 6552ad4c..4f837935 100644 --- a/src/views/webview-app/connection-model/constants/ssl-methods.ts +++ b/src/views/webview-app/connection-model/constants/ssl-methods.ts @@ -23,7 +23,7 @@ export enum SSL_METHODS { /** * The driver must present a valid certificate and validate the server certificate. */ - ALL = 'ALL' + ALL = 'ALL', } type SSLMethod = { @@ -34,24 +34,24 @@ type SSLMethod = { export const SSLMethodOptions: SSLMethod[] = [ { id: SSL_METHODS.NONE, - title: 'None' + title: 'None', }, { id: SSL_METHODS.SYSTEMCA, - title: 'System CA / Atlas Deployment' + title: 'System CA / Atlas Deployment', }, { id: SSL_METHODS.SERVER, - title: 'Server Validation' + title: 'Server Validation', }, { id: SSL_METHODS.ALL, - title: 'Server and Client Validation' + title: 'Server and Client Validation', }, { id: SSL_METHODS.UNVALIDATED, - title: 'Unvalidated (insecure)' - } + title: 'Unvalidated (insecure)', + }, ]; export default SSL_METHODS; diff --git a/src/views/webview-app/connection-model/legacy-connection-model.ts b/src/views/webview-app/connection-model/legacy-connection-model.ts index 5263814d..61167c3e 100644 --- a/src/views/webview-app/connection-model/legacy-connection-model.ts +++ b/src/views/webview-app/connection-model/legacy-connection-model.ts @@ -168,9 +168,12 @@ const validateKerberos = (attrs: LegacyConnectionModel): void => { }; const validateX509 = (attrs: LegacyConnectionModel): void => { - if (attrs.authStrategy === AUTH_STRATEGIES.X509 && attrs.sslMethod !== SSL_METHODS.ALL) { + if ( + attrs.authStrategy === AUTH_STRATEGIES.X509 && + attrs.sslMethod !== SSL_METHODS.ALL + ) { throw new TypeError( - 'SSL method is required to be set to \'Server and Client\' when using x509 authentication' + "SSL method is required to be set to 'Server and Client' when using x509 authentication" ); } }; @@ -190,7 +193,9 @@ const validateLdap = (attrs: LegacyConnectionModel): void => { } }; -const validateStandardSshTunnelOptions = (attrs: LegacyConnectionModel): void => { +const validateStandardSshTunnelOptions = ( + attrs: LegacyConnectionModel +): void => { if (attrs.sshTunnel !== SSH_TUNNEL_TYPES.NONE && attrs.isSrvRecord) { throw new TypeError( 'SSH Tunnel connections are not currently supported with srv records, please specify an individual server to connect to.' @@ -240,7 +245,9 @@ const validateSshTunnel = (attrs: LegacyConnectionModel): void => { } }; -export const validateConnectionModel = (attrs: LegacyConnectionModel): Error | undefined => { +export const validateConnectionModel = ( + attrs: LegacyConnectionModel +): Error | undefined => { try { validateSsl(attrs); validateMongodb(attrs); diff --git a/src/views/webview-app/extension-app-message-constants.ts b/src/views/webview-app/extension-app-message-constants.ts index 6e5e7ac8..c052f3c2 100644 --- a/src/views/webview-app/extension-app-message-constants.ts +++ b/src/views/webview-app/extension-app-message-constants.ts @@ -6,10 +6,11 @@ export enum CONNECTION_STATUS { CONNECTED = 'CONNECTED', CONNECTING = 'CONNECTING', DISCONNECTING = 'DISCONNECTING', - DISCONNECTED = 'DISCONNECTED' + DISCONNECTED = 'DISCONNECTED', } -export const VSCODE_EXTENSION_SEGMENT_ANONYMOUS_ID = 'VSCODE_EXTENSION_SEGMENT_ANONYMOUS_ID'; +export const VSCODE_EXTENSION_SEGMENT_ANONYMOUS_ID = + 'VSCODE_EXTENSION_SEGMENT_ANONYMOUS_ID'; export enum MESSAGE_TYPES { CONNECT = 'CONNECT', @@ -22,7 +23,7 @@ export enum MESSAGE_TYPES { OPEN_CONNECTION_STRING_INPUT = 'OPEN_CONNECTION_STRING_INPUT', OPEN_FILE_PICKER = 'OPEN_FILE_PICKER', OPEN_TRUSTED_LINK = 'OPEN_TRUSTED_LINK', - RENAME_ACTIVE_CONNECTION = 'RENAME_ACTIVE_CONNECTION' + RENAME_ACTIVE_CONNECTION = 'RENAME_ACTIVE_CONNECTION', } interface BasicWebviewMessage { diff --git a/src/views/webview-app/store/constants.ts b/src/views/webview-app/store/constants.ts index fbcd9c0c..ded06b18 100644 --- a/src/views/webview-app/store/constants.ts +++ b/src/views/webview-app/store/constants.ts @@ -2,5 +2,5 @@ export enum CONNECTION_FORM_TABS { GENERAL = 'GENERAL', SSL = 'SSL', SSH = 'SSH', - ADVANCED = 'ADVANCED' + ADVANCED = 'ADVANCED', } diff --git a/src/views/webview-app/store/store.ts b/src/views/webview-app/store/store.ts index 0dc577f7..d1eabf38 100644 --- a/src/views/webview-app/store/store.ts +++ b/src/views/webview-app/store/store.ts @@ -3,13 +3,13 @@ import { v4 as uuidv4 } from 'uuid'; import LegacyConnectionModel, { DEFAULT_HOST, - validateConnectionModel + validateConnectionModel, } from '../connection-model/legacy-connection-model'; import SSL_METHODS from '../connection-model/constants/ssl-methods'; import { CONNECTION_STATUS, MESSAGE_FROM_WEBVIEW_TO_EXTENSION, - MESSAGE_TYPES + MESSAGE_TYPES, } from '../extension-app-message-constants'; import { CONNECTION_FORM_TABS } from './constants'; @@ -51,7 +51,7 @@ export const initialState: AppState = { showConnectForm: false, showResourcesPanel: false, syntaxErrorMessage: '', - savedMessage: '' + savedMessage: '', }; const showFilePicker = ( @@ -61,17 +61,19 @@ const showFilePicker = ( vscode.postMessage({ command: MESSAGE_TYPES.OPEN_FILE_PICKER, action, - multi + multi, }); }; -const sendConnectToExtension = (connectionModel: LegacyConnectionModel): string => { +const sendConnectToExtension = ( + connectionModel: LegacyConnectionModel +): string => { const connectionAttemptId = uuidv4(); vscode.postMessage({ command: MESSAGE_TYPES.CONNECT, connectionModel, - connectionAttemptId + connectionAttemptId, }); return connectionAttemptId; @@ -88,8 +90,8 @@ export const rootReducer = ( ...state, currentConnection: { ...state.currentConnection, - mongodbDatabaseName: action.mongodbDatabaseName - } + mongodbDatabaseName: action.mongodbDatabaseName, + }, }; case ActionTypes.AUTH_STRATEGY_CHANGED: @@ -108,8 +110,8 @@ export const rootReducer = ( kerberosServiceName: undefined, x509Username: undefined, ldapUsername: undefined, - ldapPassword: undefined - } + ldapPassword: undefined, + }, }; case ActionTypes.CONNECT: @@ -119,9 +121,9 @@ export const rootReducer = ( isValid: false, errorMessage: ( validateConnectionModel(state.currentConnection) || { - message: 'The required fields can not be empty.' + message: 'The required fields can not be empty.', } - ).message + ).message, }; } @@ -131,12 +133,12 @@ export const rootReducer = ( isValid: true, isConnecting: true, isConnected: false, - connectionAttemptId: sendConnectToExtension(state.currentConnection) + connectionAttemptId: sendConnectToExtension(state.currentConnection), }; case ActionTypes.CREATE_NEW_PLAYGROUND: vscode.postMessage({ - command: MESSAGE_TYPES.CREATE_NEW_PLAYGROUND + command: MESSAGE_TYPES.CREATE_NEW_PLAYGROUND, }); return { ...state }; @@ -145,7 +147,7 @@ export const rootReducer = ( vscode.postMessage({ command: MESSAGE_TYPES.EXTENSION_LINK_CLICKED, screen: action.screen, - linkId: action.linkId + linkId: action.linkId, }); return { ...state }; @@ -157,7 +159,7 @@ export const rootReducer = ( errorMessage: '', isValid: true, isConnected: false, - syntaxErrorMessage: '' + syntaxErrorMessage: '', }; case ActionTypes.CONNECTION_EVENT_OCCURED: @@ -169,8 +171,10 @@ export const rootReducer = ( isConnecting: false, isConnected: action.successfullyConnected, isValid: action.successfullyConnected ? state.isValid : false, - errorMessage: action.successfullyConnected ? '' : action.connectionMessage, - connectionMessage: action.connectionMessage + errorMessage: action.successfullyConnected + ? '' + : action.connectionMessage, + connectionMessage: action.connectionMessage, }; } return { ...state }; @@ -183,8 +187,8 @@ export const rootReducer = ( hostname: action.hostname.trim(), sslMethod: /mongodb\.net/i.exec(action.hostname) ? SSL_METHODS.SYSTEMCA - : state.currentConnection.sslMethod - } + : state.currentConnection.sslMethod, + }, }; case ActionTypes.HOSTS_CHANGED: @@ -192,10 +196,8 @@ export const rootReducer = ( ...state, currentConnection: { ...state.currentConnection, - hosts: [ - ...(action.hosts ? action.hosts : [DEFAULT_HOST]) - ] - } + hosts: [...(action.hosts ? action.hosts : [DEFAULT_HOST])], + }, }; case ActionTypes.IS_SRV_RECORD_TOGGLED: @@ -203,8 +205,8 @@ export const rootReducer = ( ...state, currentConnection: { ...state.currentConnection, - isSrvRecord: !state.currentConnection.isSrvRecord - } + isSrvRecord: !state.currentConnection.isSrvRecord, + }, }; case ActionTypes.KERBEROS_PARAMETERS_CHANGED: @@ -215,8 +217,8 @@ export const rootReducer = ( kerberosCanonicalizeHostname: action.kerberosCanonicalizeHostname, kerberosPassword: action.kerberosPassword, kerberosPrincipal: action.kerberosPrincipal, - kerberosServiceName: action.kerberosServiceName - } + kerberosServiceName: action.kerberosServiceName, + }, }; case ActionTypes.LDAP_PASSWORD_CHANGED: @@ -224,8 +226,8 @@ export const rootReducer = ( ...state, currentConnection: { ...state.currentConnection, - ldapPassword: action.ldapPassword - } + ldapPassword: action.ldapPassword, + }, }; case ActionTypes.LDAP_USERNAME_CHANGED: @@ -233,8 +235,8 @@ export const rootReducer = ( ...state, currentConnection: { ...state.currentConnection, - ldapUsername: action.ldapUsername - } + ldapUsername: action.ldapUsername, + }, }; case ActionTypes.ON_CHANGE_SSH_TUNNEL_IDENTITY_FILE: @@ -244,8 +246,8 @@ export const rootReducer = ( ...state, currentConnection: { ...state.currentConnection, - sshTunnelIdentityFile: undefined - } + sshTunnelIdentityFile: undefined, + }, }; case ActionTypes.ON_CHANGE_SSL_CA: @@ -255,8 +257,8 @@ export const rootReducer = ( ...state, currentConnection: { ...state.currentConnection, - sslCA: undefined - } + sslCA: undefined, + }, }; case ActionTypes.ON_CHANGE_SSL_CERT: @@ -266,18 +268,18 @@ export const rootReducer = ( ...state, currentConnection: { ...state.currentConnection, - sslCert: undefined - } + sslCert: undefined, + }, }; case ActionTypes.OPEN_CONNECTION_STRING_INPUT: vscode.postMessage({ - command: MESSAGE_TYPES.OPEN_CONNECTION_STRING_INPUT + command: MESSAGE_TYPES.OPEN_CONNECTION_STRING_INPUT, }); return { ...state, - isConnected: false + isConnected: false, }; case ActionTypes.PASSWORD_CHANGED: @@ -285,8 +287,8 @@ export const rootReducer = ( ...state, currentConnection: { ...state.currentConnection, - mongodbPassword: action.mongodbPassword - } + mongodbPassword: action.mongodbPassword, + }, }; case ActionTypes.PORT_CHANGED: @@ -294,8 +296,8 @@ export const rootReducer = ( ...state, currentConnection: { ...state.currentConnection, - port: action.port - } + port: action.port, + }, }; case ActionTypes.READ_PREFERENCE_CHANGED: @@ -303,13 +305,13 @@ export const rootReducer = ( ...state, currentConnection: { ...state.currentConnection, - readPreference: action.readPreference - } + readPreference: action.readPreference, + }, }; case ActionTypes.RENAME_CONNECTION: vscode.postMessage({ - command: MESSAGE_TYPES.RENAME_ACTIVE_CONNECTION + command: MESSAGE_TYPES.RENAME_ACTIVE_CONNECTION, }); return { ...state }; @@ -319,13 +321,13 @@ export const rootReducer = ( ...state, currentConnection: { ...state.currentConnection, - replicaSet: action.replicaSet - } + replicaSet: action.replicaSet, + }, }; case ActionTypes.REQUEST_CONNECTION_STATUS: vscode.postMessage({ - command: MESSAGE_TYPES.GET_CONNECTION_STATUS + command: MESSAGE_TYPES.GET_CONNECTION_STATUS, }); return { ...state }; @@ -333,14 +335,14 @@ export const rootReducer = ( case ActionTypes.SET_CONNECTION_FORM_TAB: return { ...state, - connectionFormTab: action.connectionFormTab + connectionFormTab: action.connectionFormTab, }; case ActionTypes.SET_CONNECTION_STATUS: return { ...state, activeConnectionName: action.activeConnectionName, - connectionStatus: action.connectionStatus + connectionStatus: action.connectionStatus, }; case ActionTypes.SSH_TUNNEL_CHANGED: @@ -356,8 +358,8 @@ export const rootReducer = ( sshTunnelPassword: undefined, sshTunnelIdentityFile: undefined, sshTunnelPassphrase: undefined, - replicaSet: undefined - } + replicaSet: undefined, + }, }; case ActionTypes.SSH_TUNNEL_HOSTNAME_CHANGED: @@ -365,8 +367,8 @@ export const rootReducer = ( ...state, currentConnection: { ...state.currentConnection, - sshTunnelHostname: action.sshTunnelHostname - } + sshTunnelHostname: action.sshTunnelHostname, + }, }; case ActionTypes.SSH_TUNNEL_IDENTITY_FILE_CHANGED: @@ -374,8 +376,8 @@ export const rootReducer = ( ...state, currentConnection: { ...state.currentConnection, - sshTunnelIdentityFile: action.files - } + sshTunnelIdentityFile: action.files, + }, }; case ActionTypes.SSH_TUNNEL_PASSPHRASE_CHANGED: @@ -383,8 +385,8 @@ export const rootReducer = ( ...state, currentConnection: { ...state.currentConnection, - sshTunnelPassphrase: action.sshTunnelPassphrase - } + sshTunnelPassphrase: action.sshTunnelPassphrase, + }, }; case ActionTypes.SSH_TUNNEL_PASSWORD_CHANGED: @@ -392,8 +394,8 @@ export const rootReducer = ( ...state, currentConnection: { ...state.currentConnection, - sshTunnelPassword: action.sshTunnelPassword - } + sshTunnelPassword: action.sshTunnelPassword, + }, }; case ActionTypes.SSH_TUNNEL_PORT_CHANGED: @@ -401,8 +403,8 @@ export const rootReducer = ( ...state, currentConnection: { ...state.currentConnection, - sshTunnelPort: action.sshTunnelPort - } + sshTunnelPort: action.sshTunnelPort, + }, }; case ActionTypes.SSH_TUNNEL_USERNAME_CHANGED: @@ -410,8 +412,8 @@ export const rootReducer = ( ...state, currentConnection: { ...state.currentConnection, - sshTunnelUsername: action.sshTunnelUsername - } + sshTunnelUsername: action.sshTunnelUsername, + }, }; case ActionTypes.SSL_CA_CHANGED: @@ -419,8 +421,8 @@ export const rootReducer = ( ...state, currentConnection: { ...state.currentConnection, - sslCA: action.files - } + sslCA: action.files, + }, }; case ActionTypes.SSL_CERT_CHANGED: @@ -429,8 +431,8 @@ export const rootReducer = ( currentConnection: { ...state.currentConnection, sslCert: action.files, - sslKey: action.files - } + sslKey: action.files, + }, }; case ActionTypes.SSL_METHOD_CHANGED: @@ -443,8 +445,8 @@ export const rootReducer = ( sslCA: undefined, sslCert: undefined, sslKey: undefined, - sslPass: undefined - } + sslPass: undefined, + }, }; case ActionTypes.SSL_PASS_CHANGED: @@ -452,26 +454,26 @@ export const rootReducer = ( ...state, currentConnection: { ...state.currentConnection, - sslPass: action.sslPass - } + sslPass: action.sslPass, + }, }; case ActionTypes.TOGGLE_SHOW_CONNECTION_FORM: return { ...state, - showConnectForm: !state.showConnectForm + showConnectForm: !state.showConnectForm, }; case ActionTypes.TOGGLE_SHOW_RESOURCES_PANEL: return { ...state, - showResourcesPanel: !state.showResourcesPanel + showResourcesPanel: !state.showResourcesPanel, }; case ActionTypes.TRUSTED_LINK_CLICKED: vscode.postMessage({ command: MESSAGE_TYPES.OPEN_TRUSTED_LINK, - linkTo: action.linkTo + linkTo: action.linkTo, }); return { ...state }; @@ -481,8 +483,8 @@ export const rootReducer = ( ...state, currentConnection: { ...state.currentConnection, - mongodbUsername: action.mongodbUsername - } + mongodbUsername: action.mongodbUsername, + }, }; case ActionTypes.X509_USERNAME_CHANGED: @@ -490,8 +492,8 @@ export const rootReducer = ( ...state, currentConnection: { ...state.currentConnection, - x509Username: action.x509Username - } + x509Username: action.x509Username, + }, }; default: diff --git a/src/views/webview-app/styles/_variables.less b/src/views/webview-app/styles/_variables.less index e21cd26c..27bda0d4 100644 --- a/src/views/webview-app/styles/_variables.less +++ b/src/views/webview-app/styles/_variables.less @@ -2,9 +2,9 @@ @font-white__color: #ffffff; @alertRed: #cf4a22; @warningText: #ffdd49; -@green: #00ED64; -@green-dark: #00684A; -@green-hover: #3F864B; -@green-selected: #C3E7CA; +@green: #00ed64; +@green-dark: #00684a; +@green-hover: #3f864b; +@green-selected: #c3e7ca; @gray: #5d6c74; @icon-button-hover__color: #fbb129; diff --git a/src/views/webviewController.ts b/src/views/webviewController.ts index fe91638b..639a7157 100644 --- a/src/views/webviewController.ts +++ b/src/views/webviewController.ts @@ -1,9 +1,7 @@ import * as vscode from 'vscode'; import path from 'path'; -import ConnectionController, { - ConnectionTypes -} from '../connectionController'; +import ConnectionController, { ConnectionTypes } from '../connectionController'; import LegacyConnectionModel from './webview-app/connection-model/legacy-connection-model'; import { createLogger } from '../logging'; import EXTENSION_COMMANDS from '../commands'; @@ -11,7 +9,7 @@ import { MESSAGE_FROM_WEBVIEW_TO_EXTENSION, MESSAGE_TYPES, VSCODE_EXTENSION_SEGMENT_ANONYMOUS_ID, - OpenFilePickerMessage + OpenFilePickerMessage, } from './webview-app/extension-app-message-constants'; import { openLink } from '../utils/linkHelper'; import { StorageController } from '../storage'; @@ -25,8 +23,8 @@ const openFileOptions = { canSelectMany: false, // Can be overridden. openLabel: 'Open', filters: { - 'All files': ['*'] - } + 'All files': ['*'], + }, }; export const getReactAppUri = ( @@ -43,11 +41,11 @@ export const getReactAppUri = ( export const getWebviewContent = ({ extensionPath, telemetryUserId, - webview + webview, }: { - extensionPath: string, - telemetryUserId?: string, - webview: vscode.Webview + extensionPath: string; + telemetryUserId?: string; + webview: vscode.Webview; }): string => { const jsAppFileUrl = getReactAppUri(extensionPath, webview); @@ -87,14 +85,13 @@ export default class WebviewController { connectionAttemptId: string ): Promise => { try { - const connectionInfo = this._connectionController.parseNewConnection(rawConnectionModel); - const { - successfullyConnected, - connectionErrorMessage - } = await this._connectionController.saveNewConnectionAndConnect( - connectionInfo, - ConnectionTypes.CONNECTION_FORM - ); + const connectionInfo = + this._connectionController.parseNewConnection(rawConnectionModel); + const { successfullyConnected, connectionErrorMessage } = + await this._connectionController.saveNewConnectionAndConnect( + connectionInfo, + ConnectionTypes.CONNECTION_FORM + ); try { // The webview may have been closed in which case this will throw. @@ -104,19 +101,21 @@ export default class WebviewController { connectionSuccess: successfullyConnected, connectionMessage: successfullyConnected ? `Successfully connected to ${this._connectionController.getActiveConnectionName()}.` - : connectionErrorMessage + : connectionErrorMessage, }); } catch (err) { log.error('Unable to send connection result to webview:', err); } } catch (error) { - void vscode.window.showErrorMessage(`Unable to load connection: ${error}`); + void vscode.window.showErrorMessage( + `Unable to load connection: ${error}` + ); void panel.webview.postMessage({ command: MESSAGE_TYPES.CONNECT_RESULT, connectionAttemptId, connectionSuccess: false, - connectionMessage: `Unable to load connection: ${error}` + connectionMessage: `Unable to load connection: ${error}`, }); } }; @@ -127,14 +126,15 @@ export default class WebviewController { ): Promise => { const files = await vscode.window.showOpenDialog({ ...openFileOptions, - canSelectMany: message.multi + canSelectMany: message.multi, }); void panel.webview.postMessage({ command: MESSAGE_TYPES.FILE_PICKER_RESULTS, action: message.action, - files: (files && files.length > 0) - ? files.map((file) => file.fsPath) - : undefined + files: + files && files.length > 0 + ? files.map((file) => file.fsPath) + : undefined, }); }; @@ -159,14 +159,17 @@ export default class WebviewController { void panel.webview.postMessage({ command: MESSAGE_TYPES.CONNECTION_STATUS_MESSAGE, connectionStatus: this._connectionController.getConnectionStatus(), - activeConnectionName: this._connectionController.getActiveConnectionName() + activeConnectionName: + this._connectionController.getActiveConnectionName(), }); return; case MESSAGE_TYPES.OPEN_FILE_PICKER: await this.handleWebviewOpenFilePickerRequest(message, panel); return; case MESSAGE_TYPES.OPEN_CONNECTION_STRING_INPUT: - void vscode.commands.executeCommand(EXTENSION_COMMANDS.MDB_CONNECT_WITH_URI); + void vscode.commands.executeCommand( + EXTENSION_COMMANDS.MDB_CONNECT_WITH_URI + ); return; case MESSAGE_TYPES.OPEN_TRUSTED_LINK: try { @@ -180,10 +183,7 @@ export default class WebviewController { } return; case MESSAGE_TYPES.EXTENSION_LINK_CLICKED: - this._telemetryService.trackLinkClicked( - message.screen, - message.linkId - ); + this._telemetryService.trackLinkClicked(message.screen, message.linkId); return; case MESSAGE_TYPES.RENAME_ACTIVE_CONNECTION: if (this._connectionController.isCurrentlyConnected()) { @@ -213,9 +213,7 @@ export default class WebviewController { } }; - openWebview( - context: vscode.ExtensionContext - ): Promise { + openWebview(context: vscode.ExtensionContext): Promise { log.info('open webview called.'); const extensionPath = context.extensionPath; @@ -230,8 +228,8 @@ export default class WebviewController { retainContextWhenHidden: true, localResourceRoots: [ vscode.Uri.file(path.join(extensionPath, 'dist')), - vscode.Uri.file(path.join(extensionPath, 'resources')) - ] + vscode.Uri.file(path.join(extensionPath, 'resources')), + ], } ); @@ -250,8 +248,9 @@ export default class WebviewController { panel.webview.html = getWebviewContent({ extensionPath, - telemetryUserId: telemetryUserIdentity.anonymousId || telemetryUserIdentity.userId, - webview: panel.webview + telemetryUserId: + telemetryUserIdentity.anonymousId || telemetryUserIdentity.userId, + webview: panel.webview, }); // Handle messages from the webview. diff --git a/tsconfig.json b/tsconfig.json index 17c58d22..0fa980b5 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -4,13 +4,8 @@ "noImplicitAny": false, "target": "es6", "outDir": "out", - "lib": [ - "es6", - "dom" - ], - "types": [ - "node" - ], + "lib": ["es6", "dom"], + "types": ["node"], "jsx": "react", "sourceMap": true, "rootDir": "src", @@ -21,11 +16,5 @@ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ // "noUnusedParameters": true, /* Report errors on unused parameters. */ }, - "exclude": [ - "node_modules", - "dist", - "out", - ".vscode-test", - "scripts" - ] + "exclude": ["node_modules", "dist", "out", ".vscode-test", "scripts"] } diff --git a/webpack.config.js b/webpack.config.js index 33ce936e..06224206 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -7,7 +7,7 @@ const outputPath = path.join(__dirname, 'dist'); const ContextMapPlugin = require('context-map-webpack-plugin'); const baseConfig = { - devtool: 'source-map' + devtool: 'source-map', // performance: { // hints: false // } @@ -20,14 +20,14 @@ const extensionConfig = { path: outputPath, filename: '[name].js', libraryTarget: 'commonjs2', - devtoolModuleFilenameTemplate: '../[resource-path]' + devtoolModuleFilenameTemplate: '../[resource-path]', }, target: 'node', entry: { - extension: './src/extension.ts' + extension: './src/extension.ts', }, resolve: { - extensions: ['.js', '.ts', '.json'] + extensions: ['.js', '.ts', '.json'], }, externals: { // The vscode-module is created on-the-fly and must be excluded. @@ -35,7 +35,7 @@ const extensionConfig = { // Currently connection-model has a keytar dependency, vscode provides its // own keytar dependency. Here we are telling it to use vscode's keytar. keytar: 'keytar', - electron: 'electron' + electron: 'electron', }, module: { rules: [ @@ -48,20 +48,17 @@ const extensionConfig = { test: /\.(ts|tsx)$/, loader: 'ts-loader', exclude: /node_modules/, - options: {} + options: {}, }, { test: /\.node$/, - loader: 'node-loader' - } - ] + loader: 'node-loader', + }, + ], }, plugins: [ - new ContextMapPlugin( - 'node_modules/context-eval', - ['./lib/context-node'] - ) - ] + new ContextMapPlugin('node_modules/context-eval', ['./lib/context-node']), + ], }; const languageServerConfig = { @@ -71,23 +68,23 @@ const languageServerConfig = { path: outputPath, filename: '[name].js', libraryTarget: 'commonjs2', - devtoolModuleFilenameTemplate: '../[resource-path]' + devtoolModuleFilenameTemplate: '../[resource-path]', }, target: 'node', entry: { - languageServer: './src/language/server.ts' + languageServer: './src/language/server.ts', }, optimization: { // Don't minimize in order to preserve // the signature names from @mongosh/shell-api. - minimize: false + minimize: false, }, resolve: { - extensions: ['.js', '.ts', '.json'] + extensions: ['.js', '.ts', '.json'], }, externals: { // The vscode-module is created on-the-fly and must be excluded. - vscode: 'commonjs vscode' + vscode: 'commonjs vscode', }, module: { rules: [ @@ -100,14 +97,14 @@ const languageServerConfig = { test: /\.(ts|tsx)$/, loader: 'ts-loader', exclude: /node_modules/, - options: {} + options: {}, }, { test: /\.node$/, - loader: 'node-loader' - } - ] - } + loader: 'node-loader', + }, + ], + }, }; const languageServerWorkerConfig = { @@ -117,23 +114,23 @@ const languageServerWorkerConfig = { path: outputPath, filename: '[name].js', libraryTarget: 'commonjs2', - devtoolModuleFilenameTemplate: '../[resource-path]' + devtoolModuleFilenameTemplate: '../[resource-path]', }, target: 'node', entry: { - languageServerWorker: './src/language/worker.ts' + languageServerWorker: './src/language/worker.ts', }, optimization: { // Don't minimize in order to preserve // the signature names from @mongosh/shell-api. - minimize: false + minimize: false, }, resolve: { - extensions: ['.js', '.ts', '.json'] + extensions: ['.js', '.ts', '.json'], }, externals: { // The vscode-module is created on-the-fly and must be excluded. - vscode: 'commonjs vscode' + vscode: 'commonjs vscode', }, module: { rules: [ @@ -146,14 +143,14 @@ const languageServerWorkerConfig = { test: /\.(ts|tsx)$/, loader: 'ts-loader', exclude: /node_modules/, - options: {} + options: {}, }, { test: /\.node$/, - loader: 'node-loader' - } - ] - } + loader: 'node-loader', + }, + ], + }, }; const webviewConfig = { @@ -162,14 +159,14 @@ const webviewConfig = { strictModuleExceptionHandling: true, path: outputPath, filename: '[name].js', - devtoolModuleFilenameTemplate: '../[resource-path]' + devtoolModuleFilenameTemplate: '../[resource-path]', }, target: 'web', entry: { - webviewApp: './src/views/webview-app/index.tsx' + webviewApp: './src/views/webview-app/index.tsx', }, resolve: { - extensions: ['.js', '.ts', '.tsx', '.json'] + extensions: ['.js', '.ts', '.tsx', '.json'], }, module: { rules: [ @@ -177,7 +174,7 @@ const webviewConfig = { test: /\.(ts|tsx)$/, loader: 'ts-loader', exclude: /node_modules/, - options: {} + options: {}, }, { test: /\.less$/, @@ -188,8 +185,8 @@ const webviewConfig = { loader: 'css-loader', options: { modules: true, - importLoaders: 1 - } + importLoaders: 1, + }, }, { loader: 'postcss-loader', @@ -197,24 +194,24 @@ const webviewConfig = { // eslint-disable-next-line @typescript-eslint/explicit-function-return-type plugins: function () { return [autoprefixer()]; - } - } + }, + }, }, { loader: 'less-loader', options: { - noIeCompat: true - } - } - ] - } - ] - } + noIeCompat: true, + }, + }, + ], + }, + ], + }, }; module.exports = [ extensionConfig, languageServerConfig, languageServerWorkerConfig, - webviewConfig + webviewConfig, ];