-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathmongosh-repl.ts
1233 lines (1140 loc) · 41.2 KB
/
mongosh-repl.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import completer from '@mongosh/autocomplete';
import { MongoshInternalError, MongoshWarning } from '@mongosh/errors';
import { changeHistory } from '@mongosh/history';
import type {
AutoEncryptionOptions,
ServiceProvider,
} from '@mongosh/service-provider-core';
import type {
EvaluationListener,
OnLoadResult,
ShellCliOptions,
} from '@mongosh/shell-api';
import {
ShellInstanceState,
getShellApiType,
toShellResult,
} from '@mongosh/shell-api';
import type { ShellResult } from '@mongosh/shell-evaluator';
import { ShellEvaluator } from '@mongosh/shell-evaluator';
import type { ConfigProvider, MongoshBus } from '@mongosh/types';
import {
CliUserConfig,
CliUserConfigValidator,
TimingCategories,
} from '@mongosh/types';
import askcharacter from 'askcharacter';
import askpassword from 'askpassword';
import { Console } from 'console';
import { once } from 'events';
import type { ReplOptions, REPLServer } from 'repl';
import type { Readable, Writable } from 'stream';
import type { ReadStream, WriteStream } from 'tty';
import { callbackify, promisify } from 'util';
import * as asyncRepl from './async-repl';
import type { StyleDefinition } from './clr';
import clr from './clr';
import { MONGOSH_WIKI, TELEMETRY_GREETING_MESSAGE } from './constants';
import formatOutput, { formatError } from './format-output';
import { makeMultilineJSIntoSingleLine } from '@mongosh/js-multiline-to-singleline';
import { LineByLineInput } from './line-by-line-input';
import type { FormatOptions } from './format-output';
import { markTime } from './startup-timing';
import type { Context } from 'vm';
import { Script, createContext, runInContext } from 'vm';
declare const __non_webpack_require__: any;
/**
* All CLI flags that are useful for {@link MongoshNodeRepl}.
*/
export type MongoshCliOptions = ShellCliOptions & {
quiet?: boolean;
/**
* Whether to instantiate a Node.js REPL instance, including support
* for async error tracking, or not.
*/
jsContext?: JSContext;
exposeAsyncRewriter?: boolean;
};
/**
* An interface that contains everything necessary for {@link MongoshNodeRepl}
* instances to actually perform I/O operations.
*/
export type MongoshIOProvider = Omit<
ConfigProvider<CliUserConfig>,
'validateConfig' | 'resetConfig'
> & {
getHistoryFilePath(): string;
exit(code?: number): Promise<never>;
readFileUTF8(
filename: string
): Promise<{ contents: string; absolutePath: string }>;
getCryptLibraryOptions(): Promise<AutoEncryptionOptions['extraOptions']>;
bugReportErrorMessageInfo?(): string | undefined;
};
export type JSContext = 'repl' | 'plain-vm';
/**
* Options required for MongoshNodeRepl instance to communicate with
* other parts of the application.
*/
export type MongoshNodeReplOptions = {
/** Input stream from which to read input (e.g. process.stdin). */
input: Readable;
/** Output stream to which to write output (e.g. process.stdout). */
output: Writable;
/** A bus instance on which to emit events about REPL execution. */
bus: MongoshBus;
/** Interface for communicating with the outside world, e.g. file I/O. */
ioProvider: MongoshIOProvider;
/** All relevant CLI options (i.e. parsed command line flags). */
shellCliOptions?: Partial<MongoshCliOptions>;
/** All relevant Node.js REPL options. */
nodeReplOptions?: Partial<ReplOptions>;
};
/**
* Opaque token used to make sure that start() can only be called after
* having called initialize().
*/
export type InitializationToken = { __initialized: 'yes' };
/**
* Grouped properties of MongoshNodeRepl that are only available
* after initialization.
*/
type MongoshRuntimeState = {
shellEvaluator: ShellEvaluator<any>;
instanceState: ShellInstanceState;
repl: REPLServer | null;
context: Context;
console: Console;
};
/* Utility, inverse of Readonly<T> */
type Mutable<T> = {
-readonly [P in keyof T]: T[P];
};
/**
* An instance of a `mongosh` REPL, without any of the actual I/O.
* Specifically, code called by this class should not do any
* filesystem I/O, network I/O or write to/read from stdio streams.
*/
class MongoshNodeRepl implements EvaluationListener {
_runtimeState: MongoshRuntimeState | null;
input: Readable;
lineByLineInput: LineByLineInput;
output: Writable;
bus: MongoshBus;
nodeReplOptions: Partial<ReplOptions>;
shellCliOptions: Partial<MongoshCliOptions>;
ioProvider: MongoshIOProvider;
onClearCommand?: EvaluationListener['onClearCommand'];
insideAutoCompleteOrGetPrompt: boolean;
inspectCompact: number | boolean = 0;
inspectDepth = 0;
started = false;
showStackTraces = false;
loadNestingLevel = 0;
redactHistory: 'keep' | 'remove' | 'remove-redact' = 'remove';
rawValueToShellResult: WeakMap<any, ShellResult> = new WeakMap();
constructor(options: MongoshNodeReplOptions) {
this.input = options.input;
this.lineByLineInput = new LineByLineInput(this.input as ReadStream);
this.output = options.output;
this.bus = options.bus;
this.nodeReplOptions = options.nodeReplOptions || {};
this.shellCliOptions = options.shellCliOptions || {};
this.ioProvider = options.ioProvider;
this.insideAutoCompleteOrGetPrompt = false;
this._runtimeState = null;
}
/**
* Controls whether the shell considers itself to be in interactive mode,
* i.e. whether .start() will be called or not.
*
* @param value The new isInteractive value.
*/
setIsInteractive(value: boolean): void {
this.runtimeState().instanceState.isInteractive = value;
}
get isInteractive(): boolean {
return this.runtimeState().instanceState.isInteractive;
}
/**
* Create a Node.js REPL instance that can run mongosh commands,
* print greeting messages, and set up autocompletion and
* history handling. This does not yet start evaluating any code
* or print any user prompt.
*/
async initialize(
serviceProvider: ServiceProvider,
moreRecentMongoshVersion?: string | null
): Promise<InitializationToken> {
const usePlainVMContext = this.shellCliOptions.jsContext === 'plain-vm';
const instanceState = new ShellInstanceState(
serviceProvider,
this.bus,
this.shellCliOptions
);
const shellEvaluator = new ShellEvaluator(
instanceState,
(value: any) => value,
markTime,
!!this.shellCliOptions.exposeAsyncRewriter
);
instanceState.setEvaluationListener(this);
// Fetch connection metadata if not in quiet mode or in REPL mode:
// not-quiet mode -> We'll need it for the greeting message (and need it now)
// REPL mode -> We'll want it for fast autocomplete (and need it soon-ish, but not now)
instanceState.setPreFetchCollectionAndDatabaseNames(!usePlainVMContext);
// `if` commented out because we currently still want the connection info for
// logging/telemetry but we may want to revisit that in the future:
// if (!this.shellCliOptions.quiet || !usePlainVMContext)
{
const connectionInfoPromise = instanceState.fetchConnectionInfo();
connectionInfoPromise.catch(() => {
// Ignore potential unhandled rejection warning
});
if (!this.shellCliOptions.quiet) {
const connectionInfo = await connectionInfoPromise;
markTime(TimingCategories.REPLInstantiation, 'fetched connection info');
const { buildInfo, extraInfo } = connectionInfo ?? {};
let mongodVersion = extraInfo?.is_stream
? 'Atlas Stream Processing'
: buildInfo?.version;
const apiVersion = serviceProvider.getRawClient()?.serverApi?.version;
if (apiVersion) {
mongodVersion =
(mongodVersion ? mongodVersion + ' ' : '') +
`(API Version ${apiVersion})`;
}
await this.greet(mongodVersion, moreRecentMongoshVersion);
}
}
await this.printBasicConnectivityWarning(instanceState);
markTime(TimingCategories.REPLInstantiation, 'greeted');
this.inspectCompact =
(await this.getConfig('inspectCompact')) ?? this.inspectCompact;
this.inspectDepth =
(await this.getConfig('inspectDepth')) ?? this.inspectDepth;
this.showStackTraces =
(await this.getConfig('showStackTraces')) ?? this.showStackTraces;
this.redactHistory =
(await this.getConfig('redactHistory')) ?? this.redactHistory;
markTime(TimingCategories.UserConfigLoading, 'fetched config vars');
let repl: REPLServer | null = null;
let context: Context;
if (!usePlainVMContext) {
repl = asyncRepl.start({
// 'repl' is not supported in startup snapshots yet.
// eslint-disable-next-line @typescript-eslint/no-var-requires
start: require('pretty-repl').start,
input: this.lineByLineInput as unknown as Readable,
output: this.output,
prompt: '',
writer: this.writer.bind(this),
breakEvalOnSigint: true,
preview: false,
asyncEval: this.eval.bind(this),
historySize: await this.getConfig('historyLength'),
wrapCallbackError: (err: Error) =>
Object.assign(new MongoshInternalError(err.message), {
stack: err.stack,
}),
onAsyncSigint: this.onAsyncSigint.bind(this),
...this.nodeReplOptions,
});
context = repl.context;
} else {
// https://nodejs.org/api/repl.html#replbuiltinmodules not represented in TS types
// repl is not supported in startup snapshots yet
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { builtinModules: nodeReplBuiltinModules } = require('repl');
context = createContext();
// Allow tests to easily verify that they are in the right environment,
// and fetch a list of built-in global property names
const jsBuiltinGlobalNames = runInContext(
'globalThis[Symbol.for("@@mongosh.usingPlainVMContext")] = true;' +
'Object.getOwnPropertyNames(globalThis)',
context
);
// copy over things like setTimeout, Crypto, URL, etc.
for (const nodeJsGlobal of Object.getOwnPropertyNames(globalThis)) {
if (!jsBuiltinGlobalNames.includes(nodeJsGlobal))
Object.defineProperty(context, nodeJsGlobal, {
...Object.getOwnPropertyDescriptor(globalThis, nodeJsGlobal),
});
}
// make built-in modules like `fs` available as global variables
for (const builtin of nodeReplBuiltinModules as string[]) {
let value;
Object.defineProperty(context, builtin, {
enumerable: false,
configurable: true,
get() {
return (value ??=
typeof __non_webpack_require__ === 'function'
? __non_webpack_require__(builtin)
: require(builtin));
},
set(v) {
value = v;
},
});
}
context.global = context;
context.require = require('node:module').createRequire(
process.cwd() + '/index.js'
);
}
const console = new Console({
stdout: this.output,
stderr: this.output,
colorMode: this.getFormatOptions().colors,
});
delete context.parcelRequire; // MONGOSH-965
delete context.__webpack_require__;
delete context.__non_webpack_require__;
this.onClearCommand = console.clear.bind(console);
context.console = console;
// Copy our context's Date object into the inner one because we have a custom
// util.inspect override for Date objects.
context.Date = Date;
{
// Node.js 18+ defines `crypto` in the REPL to be the global WebCrypto object,
// not the Node.js `crypto` module. We would need to decide if/when to break this
// separately from the Node.js upgrade cycle, so we always use the Node.js builtin
// module for now.
const globalCryptoDescriptor =
Object.getOwnPropertyDescriptor(context, 'crypto') ?? {};
if (
globalCryptoDescriptor.value?.subtle ||
globalCryptoDescriptor.get?.call(null)?.subtle
) {
delete context.crypto;
context.crypto = await import('node:crypto');
}
}
this._runtimeState = {
shellEvaluator,
instanceState,
repl,
context,
console,
};
markTime(
TimingCategories.REPLInstantiation,
'basic repl/vm initialization complete'
);
await this.finishInitializingNodeRepl();
instanceState.setCtx(context);
if (!this.shellCliOptions.nodb && !this.shellCliOptions.quiet) {
// cf. legacy shell:
// https://github.com/mongodb/mongo/blob/a6df396047a77b90bf1ce9463eecffbee16fb864/src/mongo/shell/mongo_main.cpp#L1003-L1026
const { shellApi } = instanceState;
// Assuming `instanceState.fetchConnectionInfo()` was already called above
const connectionInfo = instanceState.cachedConnectionInfo();
// Skipping startup warnings (see https://jira.mongodb.org/browse/MONGOSH-1776)
const bannerCommands = connectionInfo?.extraInfo?.is_local_atlas
? ['automationNotices', 'nonGenuineMongoDBCheck']
: ['startupWarnings', 'automationNotices', 'nonGenuineMongoDBCheck'];
const banners = await Promise.all(
bannerCommands.map(
async (command) => await shellApi._untrackedShow(command)
)
);
for (const banner of banners) {
if (banner.value) {
await shellApi.print(banner);
}
}
}
markTime(TimingCategories.REPLInstantiation, 'finished initialization');
return { __initialized: 'yes' };
}
private async finishInitializingNodeRepl(): Promise<void> {
const { repl, instanceState } = this.runtimeState();
if (!repl) return;
const origReplCompleter = promisify(repl.completer.bind(repl)); // repl.completer is callback-style
const mongoshCompleter = completer.bind(
null,
instanceState.getAutocompleteParameters()
);
(repl as Mutable<typeof repl>).completer = callbackify(
async (text: string): Promise<[string[], string]> => {
this.insideAutoCompleteOrGetPrompt = true;
try {
// Merge the results from the repl completer and the mongosh completer.
const [
[replResults, replOrig],
[mongoshResults, , mongoshResultsExclusive],
] = await Promise.all([
(async () => (await origReplCompleter(text)) || [[]])(),
(async () => await mongoshCompleter(text))(),
]);
this.bus.emit('mongosh:autocompletion-complete'); // For testing.
// Sometimes the mongosh completion knows that what it is doing is right,
// and that autocompletion based on inspecting the actual objects that
// are being accessed will not be helpful, e.g. in `use a<tab>`, we know
// that we want *only* database names and not e.g. `assert`.
if (mongoshResultsExclusive) {
return [mongoshResults, text];
}
// The REPL completer may not complete the entire string; for example,
// when completing ".ed" to ".editor", it reports as having completed
// only the last piece ("ed"), or when completing "{ $g", it completes
// only "$g" and not the entire result.
// The mongosh completer always completes on the entire string.
// In order to align them, we always extend the REPL results to include
// the full string prefix.
const replResultPrefix = replOrig
? text.substr(0, text.lastIndexOf(replOrig))
: '';
const longReplResults = replResults.map(
(result: string) => replResultPrefix + result
);
// Remove duplicates, because shell API methods might otherwise show
// up in both completions.
const deduped = [...new Set([...longReplResults, ...mongoshResults])];
return [deduped, text];
} finally {
this.insideAutoCompleteOrGetPrompt = false;
}
}
);
// This is used below for multiline history manipulation.
let originalHistory: string[] | null = null;
const originalDisplayPrompt = repl.displayPrompt.bind(repl);
repl.displayPrompt = (...args: any[]) => {
if (!this.started) {
return;
}
originalDisplayPrompt(...args);
this.lineByLineInput.nextLine();
};
if (repl.commands.editor) {
const originalEditorAction = repl.commands.editor.action.bind(repl);
repl.commands.editor.action = (
...args: Parameters<typeof originalEditorAction>
): any => {
originalHistory = [...(repl as any).history];
this.lineByLineInput.disableBlockOnNewline();
return originalEditorAction(...args);
};
}
repl.defineCommand('clear', {
help: '',
action: () => {
repl.displayPrompt();
},
});
// Work around a weird Node.js REPL bug where .line is expected to be
// defined but not necessarily present during the .setupHistory() call.
// https://github.com/nodejs/node/issues/36773
(repl as Mutable<typeof repl>).line = '';
markTime(TimingCategories.REPLInstantiation, 'created repl object');
const historyFile = this.ioProvider.getHistoryFilePath();
try {
await promisify(repl.setupHistory).call(repl, historyFile);
// repl.history is an array of previous commands. We need to hijack the
// value we just typed, and shift it off the history array if the info is
// sensitive.
repl.on('line', () => {
if (this.redactHistory !== 'keep') {
const history: string[] = (repl as any).history;
changeHistory(
history,
this.redactHistory === 'remove-redact'
? 'redact-sensitive-data'
: 'keep-sensitive-data'
);
}
});
// We also want to group multiline history entries and .editor input into
// a single entry per evaluation, so that arrow-up functionality
// is more useful.
(repl as any).on(
asyncRepl.evalFinish,
(ev: asyncRepl.EvalFinishEvent) => {
if (this.insideAutoCompleteOrGetPrompt) {
return; // These are not the evaluations we are looking for.
}
const history: string[] = (repl as any).history;
if (ev.success === false && ev.recoverable) {
if (originalHistory === null) {
// If this is the first recoverable error we encounter, store the
// current history in order to be later able to restore it.
// We skip the first entry because it is part of the multiline
// input.
originalHistory = history.slice(1);
}
} else if (originalHistory !== null) {
// We are seeing the first completion after a recoverable error that
// did not result in a recoverable error, i.e. the multiline input
// is complete.
// Add the current input, with newlines replaced by spaces, to the
// front of the history array. We restore the original history, i.e.
// any intermediate lines added to the history while we were gathering
// the multiline input are replaced at this point.
const newHistoryEntry = makeMultilineJSIntoSingleLine(ev.input);
if (newHistoryEntry.length > 0) {
const newLines = [newHistoryEntry];
/*
changeHistory(
newLines,
this.redactHistory === 'remove-redact'
? 'redact-sensitive-data'
: 'keep-sensitive-data'
);
*/
originalHistory.unshift(...newLines);
}
history.splice(0, history.length, ...originalHistory);
originalHistory = null;
}
}
);
} catch (err: any) {
// repl.setupHistory() only reports failure when something went wrong
// *after* the file was already opened for the first time. If the initial
// open fails, it will print a warning to the REPL and report success to us.
const warn = new MongoshWarning(
'Error processing history file: ' + err?.message
);
this.output.write(this.writer(warn) + '\n');
}
markTime(TimingCategories.UserConfigLoading, 'set up history file');
// Similar calls are added for plain-vm evaluation below
(repl as any).on(asyncRepl.evalStart, () => {
this.bus.emit('mongosh:evaluate-started');
});
(repl as any).on(asyncRepl.evalFinish, () => {
this.bus.emit('mongosh:evaluate-finished');
});
repl.on('exit', () => {
this.onExit().catch(() => {
/* ... */
});
});
}
/**
* Print a REPL prompt and start processing data from the input stream.
*
* @param _initializationToken A value obtained by calling {@link MongoshNodeRepl.initialize}.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async startRepl(_initializationToken: InitializationToken): Promise<void> {
this.started = true;
const { repl } = this.runtimeState();
if (!repl) {
throw new MongoshInternalError(
'Cannot start REPL when not in REPL evaluation mode'
);
}
// Set up the prompt before consuming input so that we do not end up
// running the prompt function in parallel with actual input code.
repl.setPrompt(await this.getShellPrompt());
// Only start reading from the input *after* we set up everything, including
// instanceState.setCtx() and configuring the REPL prompt.
this.lineByLineInput.start();
this.input.resume();
repl.displayPrompt();
}
/**
* The greeting for the shell, showing server and shell version.
*/
async greet(
mongodVersion: string,
moreRecentMongoshVersion?: string | null
): Promise<void> {
if (this.shellCliOptions.quiet) {
return;
}
const { version } = require('../package.json');
let text = '';
if (!this.shellCliOptions.nodb) {
text += `Using MongoDB:\t\t${mongodVersion}\n`;
}
text += `${this.clr(
'Using Mongosh',
'mongosh:section-header'
)}:\t\t${version}\n`;
if (moreRecentMongoshVersion) {
text += `mongosh ${this.clr(
moreRecentMongoshVersion,
'bold'
)} is available for download: ${this.clr(
'https://www.mongodb.com/try/download/shell',
'mongosh:uri'
)}\n`;
}
text += `${MONGOSH_WIKI}\n`;
if (!(await this.getConfig('disableGreetingMessage'))) {
text += `${TELEMETRY_GREETING_MESSAGE}\n`;
await this.setConfig('disableGreetingMessage', true);
}
this.output.write(text);
}
/**
* Print a warning if the server is not able to respond to commands.
* This can happen in load balanced mode, for example.
*/
async printBasicConnectivityWarning(
instanceState: ShellInstanceState
): Promise<void> {
if (this.shellCliOptions.nodb || this.shellCliOptions.quiet) {
return;
}
let err: Error;
try {
await instanceState.currentDb.adminCommand({ ping: 1 });
return;
} catch (error: any) {
err = error;
}
const text = this.clr(
'The server failed to respond to a ping and may be unavailable:',
'mongosh:warning'
);
this.output.write(text + '\n' + this.formatError(err) + '\n');
}
/**
* Evaluate a piece of input code. This is called by the AsyncRepl eval function
* and calls the {@link ShellEvaluator} eval function, passing along all of its
* arguments.
*
* It mostly handles interaction with input processing (stop accepting input until
* evaluation is complete) and full mongosh-specific Ctrl+C interruption support.
*
* @param originalEval The original Node.js REPL evaluation function
* @param input The input string to be evaluated
* @param context The REPL context object (the globalThis object seen by its scope)
* @param filename The filename used for this evaluation, for stack traces
* @returns The result of evaluating `input`
*/
async eval(
originalEval: asyncRepl.OriginalEvalFunction,
input: string,
context: any,
filename: string
): Promise<any> {
markTime(TimingCategories.Eval, 'start repl eval');
if (!this.insideAutoCompleteOrGetPrompt) {
this.lineByLineInput.enableBlockOnNewLine();
}
const { repl, shellEvaluator } = this.runtimeState();
let interrupted = false;
try {
const rawValue = await shellEvaluator.customEval(
originalEval,
input,
context,
filename
);
if (
(typeof rawValue === 'object' && rawValue !== null) ||
typeof rawValue === 'function'
) {
this.rawValueToShellResult.set(rawValue, await toShellResult(rawValue));
}
// The Node.js auto completion needs to access the raw values in order
// to be able to autocomplete their properties properly. One catch is
// that we peform some filtering of mongosh methods depending on
// topology, server version, etc., so for those, we only autocomplete
// own, enumerable, non-underscore-prefixed properties and instead leave
// the rest to the @mongosh/autocomplete package.
if (
!this.insideAutoCompleteOrGetPrompt ||
getShellApiType(rawValue) === null
) {
return rawValue;
}
return Object.fromEntries(
Object.entries(rawValue).filter(([key]) => !key.startsWith('_'))
);
} catch (err: any) {
if (this.runtimeState().instanceState.interrupted.isSet()) {
interrupted = true;
this.bus.emit('mongosh:eval-interrupted');
// The shell is interrupted by CTRL-C - so we ignore any errors
// that happened during evaluation.
return undefined;
}
if (!isErrorLike(err)) {
throw new Error(
this.formatOutput({
value: err,
})
);
}
throw err;
} finally {
markTime(TimingCategories.Eval, 'done repl eval');
if (!this.insideAutoCompleteOrGetPrompt && !interrupted && repl) {
// In case of an interrupt, onAsyncSigint will print the prompt when completed
repl.setPrompt(await this.getShellPrompt());
}
if (this.loadNestingLevel <= 1) {
this.bus.emit('mongosh:eval-complete'); // For testing purposes.
}
markTime(TimingCategories.Eval, 're-set prompt');
}
}
/**
* Called when load() is called in the REPL.
* This is part of the EvaluationListener interface.
*/
async onLoad(filename: string): Promise<OnLoadResult> {
const { contents, absolutePath } = await this.ioProvider.readFileUTF8(
filename
);
return {
resolvedFilename: absolutePath,
evaluate: async () => {
this.loadNestingLevel += 1;
try {
await this.loadExternalCode(contents, absolutePath);
} finally {
this.loadNestingLevel -= 1;
}
},
};
}
/**
* Load and evaluate a specified file by its filename, using the shell load() method.
*
* @param filename The filename to be loaded.
*/
async loadExternalFile(filename: string): Promise<void> {
await this.runtimeState().instanceState.shellApi.load(filename);
}
/**
* Load and evaluate a specified piece of code.
*
* @param input The code to be evaluated.
* @param filename The filename, for stack trace purposes.
* @returns The result of evaluating `input`.
*/
async loadExternalCode(
input: string,
filename: string
): Promise<ShellResult> {
const { repl, context } = this.runtimeState();
if (repl) {
return await promisify(repl.eval.bind(repl))(input, context, filename);
}
let asyncSigintHandler!: () => void;
const asyncSigintPromise = new Promise((resolve, reject) => {
asyncSigintHandler = () => {
void this.onAsyncSigint();
setImmediate(() =>
reject(
new Error('Asynchronous execution was interrupted by `SIGINT`')
)
);
};
});
this.bus.emit('mongosh:evaluate-started');
try {
process.addListener('SIGINT', asyncSigintHandler);
return await Promise.race([
asyncSigintPromise,
this.eval(
(input, context, filename) =>
new Script(input, { filename }).runInContext(context, {
breakOnSigint: true,
}),
input,
context,
filename
),
]);
} finally {
process.removeListener('SIGINT', asyncSigintHandler);
this.bus.emit('mongosh:evaluate-finished');
}
}
/**
* This function is called by the async REPL helpers when an interrupt occurs.
* It is called while .eval() is still running, and typically finishes
* asynchronously after it, once the driver connections have been restarted.
*
* @returns true
*/
async onAsyncSigint(): Promise<boolean> {
const { instanceState } = this.runtimeState();
if (instanceState.interrupted.isSet()) {
return true;
}
this.output.write('Stopping execution...');
const mongodVersion: string | undefined =
instanceState.cachedConnectionInfo()?.buildInfo?.version;
if (mongodVersion?.match(/^(4\.0\.|3\.)\d+/)) {
this.output.write(
this.clr(
`\nWARNING: Operations running on the server cannot be killed automatically for MongoDB ${mongodVersion}.` +
'\n Please make sure to kill them manually. Killing operations is supported starting with MongoDB 4.1.',
'mongosh:warning'
)
);
}
const fullyInterrupted = await instanceState.onInterruptExecution();
// this is an async interrupt - the evaluation is still running in the background
// we wait until it finally completes (which should happen immediately)
await Promise.race([
once(this.bus, 'mongosh:eval-interrupted'),
new Promise(setImmediate),
]);
const fullyResumed = await instanceState.onResumeExecution();
if (!fullyInterrupted || !fullyResumed) {
this.output.write(
this.formatError({
name: 'MongoshInternalError',
message:
'Could not re-establish all connections, we suggest to restart the shell.',
})
);
}
this.bus.emit('mongosh:interrupt-complete'); // For testing purposes.
const { repl } = this.runtimeState();
if (repl) {
repl.setPrompt(await this.getShellPrompt());
}
return true;
}
/**
* Format the result to a string so it can be written to the output stream.
*/
writer(result: any): string {
// This checks for error instances.
// The writer gets called immediately by the internal `repl.eval`
// in case of errors.
if (isErrorLike(result)) {
const output = {
...result,
message: result.message || result.errmsg,
name: result.name || 'MongoshInternalError',
stack: result.stack,
cause: result.cause,
};
this.bus.emit('mongosh:error', output, 'repl');
return this.formatError(output);
}
return this.formatShellResult(
this.rawValueToShellResult.get(result) ?? {
type: null,
printable: result,
}
);
}
/**
* Format a ShellResult instance so that it can be written to the output stream.
*
* @param result A ShellResult (or similar) object.
* @returns The pretty-printed version of the input.
*/
formatShellResult(
result: { type: null | string; printable: any },
extraFormatOptions: Partial<FormatOptions> = {}
): string {
return this.formatOutput(
{ type: result.type, value: result.printable },
extraFormatOptions
);
}
/**
* Called when print(), console.log() etc. are called from the shell.
*
* @param values A list of values to be printed.
*/
onPrint(values: ShellResult[], type: 'print' | 'printjson'): void {
const extraOptions: Partial<FormatOptions> | undefined =
// MONGOSH-955: when `printjson()` is called in mongosh, we will try to
// replicate the format of the old shell: start every object on the new
// line, and set all the collapse options threshold to infinity
type === 'printjson'
? {
compact: false,
depth: Infinity,
maxArrayLength: Infinity,
maxStringLength: Infinity,
}
: undefined;
const joined = values
.map((value) => this.formatShellResult(value, extraOptions))
.join(' ');
this.output.write(joined + '\n');
}
/**
* Called when the shell requests a prompt, e.g. through passwordPrompt().
*
* @param question The prompt to be displayed.
* @param type Which kind of answer to ask for.
* @returns 'yes'/'no' for 'yesno' prompts, otherwise the user input.
*/
async onPrompt(
question: string,
type: 'password' | 'yesno'
): Promise<string> {
// Make sure we are in async evaluation mode, see comments in the
// function for details
await enterAsynchronousExecutionForPrompt();
if (type === 'password') {
const passwordPromise = askpassword({
input: this.input,
output: this.output,
replacementCharacter: '*',
});
this.output.write(question + '\n');
return (await passwordPromise).toString();
} else if (type === 'yesno') {
let result = '';
// eslint-disable-next-line no-constant-condition
while (true) {
const charPromise = askcharacter({
input: this.input,
output: this.output,
});
this.output.write(question + ': ');
result = await charPromise;
if (result.length > 0 && !/^[yYnN\r\n]$/.exec(result)) {
this.output.write('\nPlease enter Y or N: ');
} else {
break;
}
}
this.output.write('\n');
return { Y: 'yes', N: 'no' }[result.toUpperCase() as 'Y' | 'N'] ?? '';
}
throw new Error(`Unrecognized prompt type ${type}`);
}
/**
* Format a shell evaluation result so that it can be written to the output stream.
*
* @param value A value, together with optional type information.
* @returns The pretty-printed version of the input.
*/
formatOutput(
value: { value: any; type?: string | null },
extraFormatOptions: Partial<FormatOptions> = {}
): string {
return formatOutput(value, {
...this.getFormatOptions(),
...extraFormatOptions,
});
}
/**
* Format an Error object can be written to the output stream.
*
* @param value An Error object.