@@ -49,7 +49,10 @@ import { Script, createContext, runInContext } from 'vm';
4949import { installPasteSupport } from './repl-paste-support' ;
5050import util from 'util' ;
5151
52- import type { MongoDBAutocompleter } from '@mongodb-js/mongodb-ts-autocomplete' ;
52+ import type {
53+ AutocompletionContext ,
54+ MongoDBAutocompleter ,
55+ } from '@mongodb-js/mongodb-ts-autocomplete' ;
5356
5457declare const __non_webpack_require__ : any ;
5558
@@ -140,6 +143,23 @@ function transformAutocompleteResults(
140143 return [ results . map ( ( result ) => result . result ) , line ] ;
141144}
142145
146+ function hasActiveConnection (
147+ autocompletionContext : AutocompletionContext
148+ ) : boolean {
149+ try {
150+ // mongodb-ts-autocomplete uses this to find the active connection. If it
151+ // errors, then it means that (at least right now) it is not possible for us
152+ // to determine the active connection.
153+ autocompletionContext . currentDatabaseAndConnection ( ) ;
154+ return true ;
155+ } catch ( err : any ) {
156+ if ( err . name === 'MongoshInvalidInputError' ) {
157+ return false ;
158+ }
159+ throw err ;
160+ }
161+ }
162+
143163/**
144164 * An instance of a `mongosh` REPL, without any of the actual I/O.
145165 * Specifically, code called by this class should not do any
@@ -440,6 +460,7 @@ class MongoshNodeRepl implements EvaluationListener {
440460
441461 const origReplCompleter = promisify ( repl . completer . bind ( repl ) ) ; // repl.completer is callback-style
442462
463+ let autocompletionContext : AutocompletionContext ;
443464 let newMongoshCompleter : MongoDBAutocompleter | undefined ;
444465 let oldMongoshCompleter : (
445466 line : string
@@ -475,15 +496,14 @@ class MongoshNodeRepl implements EvaluationListener {
475496 '@mongodb-js/mongodb-ts-autocomplete'
476497 ) ;
477498
478- const autocompletionContext =
479- instanceState . getAutocompletionContext ( ) ;
499+ autocompletionContext = instanceState . getAutocompletionContext ( ) ;
480500 newMongoshCompleter = new MongoDBAutocompleter ( {
481501 context : autocompletionContext ,
482502 } ) ;
483503 }
484504
485505 // mongodb-ts-autocomplete requires a connection and a schema
486- if ( this . shellCliOptions . nodb ) {
506+ if ( ! hasActiveConnection ( autocompletionContext ) ) {
487507 return [ [ ] , text ] ;
488508 }
489509
0 commit comments