11import type { Topologies , TypeSignature } from '@mongosh/shell-api' ;
22import { signatures as shellSignatures } from '@mongosh/shell-api' ;
3+ import type { AutocompletionContext } from '@mongodb-js/mongodb-ts-autocomplete' ;
34import semver from 'semver' ;
45import {
56 CONVERSION_OPERATORS ,
@@ -13,6 +14,7 @@ import {
1314 ON_PREM ,
1415 DATABASE ,
1516} from '@mongodb-js/mongodb-constants' ;
17+ import { directCommandCompleter } from './direct-command-completer' ;
1618
1719type TypeSignatureAttributes = { [ key : string ] : TypeSignature } ;
1820
@@ -78,7 +80,7 @@ const GROUP = '$group';
7880 *
7981 * @returns {array } Matching Completions, Current User Input.
8082 */
81- async function completer (
83+ export async function completer (
8284 params : AutocompleteParameters ,
8385 line : string
8486) : Promise < [ string [ ] , string , 'exclusive' ] | [ string [ ] , string ] > {
@@ -398,4 +400,51 @@ function filterShellAPI(
398400 return hits ;
399401}
400402
401- export default completer ;
403+ type AutocompleteShellInstanceState = {
404+ getAutocompleteParameters : ( ) => AutocompleteParameters ;
405+ getAutocompletionContext : ( ) => AutocompletionContext ;
406+ } ;
407+
408+ function transformAutocompleteResults (
409+ line : string ,
410+ results : { result : string } [ ]
411+ ) : [ string [ ] , string ] {
412+ return [ results . map ( ( result ) => result . result ) , line ] ;
413+ }
414+
415+ export type CompletionResults =
416+ | [ string [ ] , string , 'exclusive' ]
417+ | [ string [ ] , string ] ;
418+
419+ export async function initNewAutocompleter (
420+ instanceState : Pick <
421+ AutocompleteShellInstanceState ,
422+ 'getAutocompletionContext'
423+ >
424+ ) : Promise < ( text : string ) => Promise < CompletionResults > > {
425+ // only import the autocompleter code the first time we need it to
426+ // hide the time it takes from the initial startup time
427+ const { MongoDBAutocompleter } = await import (
428+ '@mongodb-js/mongodb-ts-autocomplete'
429+ ) ;
430+
431+ const autocompletionContext = instanceState . getAutocompletionContext ( ) ;
432+ const mongoDBCompleter = new MongoDBAutocompleter ( {
433+ context : autocompletionContext ,
434+ } ) ;
435+
436+ return async ( text : string ) : Promise < CompletionResults > => {
437+ const directResults = await directCommandCompleter (
438+ autocompletionContext ,
439+ text
440+ ) ;
441+
442+ if ( directResults . length ) {
443+ return [ directResults , text , 'exclusive' ] ;
444+ }
445+
446+ const results = await mongoDBCompleter . autocomplete ( text ) ;
447+ const transformed = transformAutocompleteResults ( text , results ) ;
448+ return transformed ;
449+ } ;
450+ }
0 commit comments