-
-
Notifications
You must be signed in to change notification settings - Fork 35.4k
Expand file tree
/
Copy pathhistory.js
More file actions
423 lines (354 loc) · 12.5 KB
/
history.js
File metadata and controls
423 lines (354 loc) · 12.5 KB
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
'use strict';
const {
ArrayPrototypeIndexOf,
ArrayPrototypeJoin,
ArrayPrototypePop,
ArrayPrototypeShift,
ArrayPrototypeSplice,
ArrayPrototypeUnshift,
Boolean,
RegExpPrototypeSymbolSplit,
StringPrototypeStartsWith,
StringPrototypeTrim,
Symbol,
} = primordials;
const { validateNumber, validateArray } = require('internal/validators');
const path = require('path');
const fs = require('fs');
const os = require('os');
let debug = require('internal/util/debuglog').debuglog('repl', (fn) => {
debug = fn;
});
const permission = require('internal/process/permission');
const { clearTimeout, setTimeout } = require('timers');
const {
reverseString,
} = require('internal/readline/utils');
// The debounce is to guard against code pasted into the REPL.
const kDebounceHistoryMS = 15;
const kHistorySize = 30;
// Class fields
const kTimer = Symbol('_kTimer');
const kWriting = Symbol('_kWriting');
const kPending = Symbol('_kPending');
const kRemoveHistoryDuplicates = Symbol('_kRemoveHistoryDuplicates');
const kHistoryHandle = Symbol('_kHistoryHandle');
const kHistoryPath = Symbol('_kHistoryPath');
const kContext = Symbol('_kContext');
const kIsFlushing = Symbol('_kIsFlushing');
const kHistory = Symbol('_kHistory');
const kSize = Symbol('_kSize');
const kIndex = Symbol('_kIndex');
// Class methods
const kNormalizeLineEndings = Symbol('_kNormalizeLineEndings');
const kWriteToOutput = Symbol('_kWriteToOutput');
const kOnLine = Symbol('_kOnLine');
const kOnExit = Symbol('_kOnExit');
const kInitializeHistory = Symbol('_kInitializeHistory');
const kHandleHistoryInitError = Symbol('_kHandleHistoryInitError');
const kHasWritePermission = Symbol('_kHasWritePermission');
const kValidateOptions = Symbol('_kValidateOptions');
const kResolveHistoryPath = Symbol('_kResolveHistoryPath');
const kReplHistoryMessage = Symbol('_kReplHistoryMessage');
const kFlushHistory = Symbol('_kFlushHistory');
const kGetHistoryPath = Symbol('_kGetHistoryPath');
class ReplHistory {
constructor(context, options) {
this[kValidateOptions](options);
this[kHistoryPath] = ReplHistory[kGetHistoryPath](options);
this[kContext] = context;
this[kTimer] = null;
this[kWriting] = false;
this[kPending] = false;
this[kRemoveHistoryDuplicates] = options.removeHistoryDuplicates || false;
this[kHistoryHandle] = null;
this[kIsFlushing] = false;
this[kSize] = options.size ?? context.historySize ?? kHistorySize;
this[kHistory] = options.history ?? [];
this[kIndex] = -1;
}
initialize(onReadyCallback) {
// Empty string disables persistent history
if (this[kHistoryPath] === '') {
// Save a reference to the context's original _historyPrev
this.historyPrev = this[kContext]._historyPrev;
this[kContext]._historyPrev = this[kReplHistoryMessage].bind(this);
return onReadyCallback(null, this[kContext]);
}
const resolvedPath = this[kResolveHistoryPath]();
if (!resolvedPath) {
ReplHistory[kWriteToOutput](
this[kContext],
'\nError: Could not get the home directory.\n' +
'REPL session history will not be persisted.\n',
);
// Save a reference to the context's original _historyPrev
this.historyPrev = this[kContext]._historyPrev;
this[kContext]._historyPrev = this[kReplHistoryMessage].bind(this);
return onReadyCallback(null, this[kContext]);
}
if (!this[kHasWritePermission]()) {
ReplHistory[kWriteToOutput](
this[kContext],
'\nAccess to FileSystemWrite is restricted.\n' +
'REPL session history will not be persisted.\n',
);
return onReadyCallback(null, this[kContext]);
}
this[kContext].pause();
this[kInitializeHistory](onReadyCallback).catch((err) => {
this[kHandleHistoryInitError](err, onReadyCallback);
});
}
addHistory(isMultiline, lastCommandErrored) {
const line = this[kContext].line;
if (line.length === 0) return '';
// If the history is disabled then return the line
if (this[kSize] === 0) return line;
// If the trimmed line is empty then return the line
if (StringPrototypeTrim(line).length === 0) return line;
// This is necessary because each line would be saved in the history while creating
// a new multiline, and we don't want that.
if (isMultiline && this[kIndex] === -1) {
ArrayPrototypeShift(this[kHistory]);
} else if (lastCommandErrored) {
// If the last command errored and we are trying to edit the history to fix it
// remove the broken one from the history
ArrayPrototypeShift(this[kHistory]);
}
const normalizedLine = ReplHistory[kNormalizeLineEndings](line, '\n', '\r');
if (this[kHistory].length === 0 || this[kHistory][0] !== normalizedLine) {
if (this[kRemoveHistoryDuplicates]) {
// Remove older history line if identical to new one
const dupIndex = ArrayPrototypeIndexOf(this[kHistory], line);
if (dupIndex !== -1) ArrayPrototypeSplice(this[kHistory], dupIndex, 1);
}
// Add the new line to the history
ArrayPrototypeUnshift(this[kHistory], normalizedLine);
// Only store so many
if (this[kHistory].length > this[kSize])
ArrayPrototypePop(this[kHistory]);
}
this[kIndex] = -1;
const finalLine = isMultiline ? reverseString(this[kHistory][0]) : this[kHistory][0];
// The listener could change the history object, possibly
// to remove the last added entry if it is sensitive and should
// not be persisted in the history, like a password
// Emit history event to notify listeners of update
this[kContext].emit('history', this[kHistory]);
return finalLine;
}
canNavigateToNext() {
return this[kIndex] > -1 && this[kHistory].length > 0;
}
navigateToNext(substringSearch) {
if (!this.canNavigateToNext()) {
return null;
}
const search = substringSearch || '';
let index = this[kIndex] - 1;
while (
index >= 0 &&
(!StringPrototypeStartsWith(this[kHistory][index], search) ||
this[kContext].line === this[kHistory][index])
) {
index--;
}
this[kIndex] = index;
if (index === -1) {
return search;
}
return ReplHistory[kNormalizeLineEndings](this[kHistory][index], '\r', '\n');
}
canNavigateToPrevious() {
return this[kHistory].length !== this[kIndex] && this[kHistory].length > 0;
}
navigateToPrevious(substringSearch = '') {
if (!this.canNavigateToPrevious()) {
return null;
}
const search = substringSearch || '';
let index = this[kIndex] + 1;
while (
index < this[kHistory].length &&
(!StringPrototypeStartsWith(this[kHistory][index], search) ||
this[kContext].line === this[kHistory][index])
) {
index++;
}
this[kIndex] = index;
if (index === this[kHistory].length) {
return search;
}
return ReplHistory[kNormalizeLineEndings](this[kHistory][index], '\r', '\n');
}
get size() { return this[kSize]; }
get isFlushing() { return this[kIsFlushing]; }
get history() { return this[kHistory]; }
set history(value) { this[kHistory] = value; }
get index() { return this[kIndex]; }
set index(value) { this[kIndex] = value; }
// Start private methods
static [kGetHistoryPath](options) {
let historyPath = options.filePath;
if (typeof historyPath === 'string') {
historyPath = StringPrototypeTrim(historyPath);
}
return historyPath;
}
static [kNormalizeLineEndings](line, from, to) {
// Multiline history entries are saved reversed
// History is structured with the newest entries at the top
// and the oldest at the bottom. Multiline histories, however, only occupy
// one line in the history file. When loading multiline history with
// an old node binary, the history will be saved in the old format.
// This is why we need to reverse the multilines.
// Reversing the multilines is necessary when adding / editing and displaying them
return reverseString(line, from, to);
}
static [kWriteToOutput](context, message) {
if (typeof context._writeToOutput === 'function') {
context._writeToOutput(message);
if (typeof context._refreshLine === 'function') {
context._refreshLine();
}
}
}
[kResolveHistoryPath]() {
if (!this[kHistoryPath]) {
try {
this[kHistoryPath] = path.join(os.homedir(), '.node_repl_history');
return this[kHistoryPath];
} catch (err) {
debug(err.stack);
return null;
}
}
return this[kHistoryPath];
}
[kHasWritePermission]() {
return !(permission.isEnabled() &&
permission.has('fs.write', this[kHistoryPath]) === false);
}
[kValidateOptions](options) {
if (typeof options.history !== 'undefined') {
validateArray(options.history, 'history');
}
if (typeof options.size !== 'undefined') {
validateNumber(options.size, 'size', 0);
}
}
async [kInitializeHistory](onReadyCallback) {
try {
// Open and close file first to ensure it exists
// History files are conventionally not readable by others
// 0o0600 = read/write for owner only
const hnd = await fs.promises.open(this[kHistoryPath], 'a+', 0o0600);
await hnd.close();
let data;
try {
data = await fs.promises.readFile(this[kHistoryPath], 'utf8');
} catch (err) {
return this[kHandleHistoryInitError](err, onReadyCallback);
}
if (data) {
this[kHistory] = RegExpPrototypeSymbolSplit(/\r?\n+/, data, this[kSize]);
} else {
this[kHistory] = [];
}
validateArray(this[kHistory], 'history');
const handle = await fs.promises.open(this[kHistoryPath], 'r+');
this[kHistoryHandle] = handle;
await handle.truncate(0);
this[kContext].on('line', this[kOnLine].bind(this));
this[kContext].once('exit', this[kOnExit].bind(this));
this[kContext].once('flushHistory', () => {
if (!this[kContext].closed) {
this[kContext].resume();
onReadyCallback(null, this[kContext]);
}
});
await this[kFlushHistory]();
} catch (err) {
return this[kHandleHistoryInitError](err, onReadyCallback);
}
}
[kHandleHistoryInitError](err, onReadyCallback) {
// Cannot open history file.
// Don't crash, just don't persist history.
ReplHistory[kWriteToOutput](
this[kContext],
'\nError: Could not open history file.\n' +
'REPL session history will not be persisted.\n',
);
debug(err.stack);
// Save a reference to the context's original _historyPrev
this.historyPrev = this[kContext]._historyPrev;
this[kContext]._historyPrev = this[kReplHistoryMessage].bind(this);
this[kContext].resume();
return onReadyCallback(null, this[kContext]);
}
[kOnLine]() {
this[kIsFlushing] = true;
if (this[kTimer]) {
clearTimeout(this[kTimer]);
}
this[kTimer] = setTimeout(() => this[kFlushHistory](), kDebounceHistoryMS);
}
async [kFlushHistory]() {
this[kTimer] = null;
if (this[kWriting]) {
this[kPending] = true;
return;
}
this[kWriting] = true;
const historyData = ArrayPrototypeJoin(this[kHistory], '\n');
try {
await this[kHistoryHandle].write(historyData, 0, 'utf8');
this[kWriting] = false;
if (this[kPending]) {
this[kPending] = false;
this[kOnLine]();
} else {
this[kIsFlushing] = Boolean(this[kTimer]);
if (!this[kIsFlushing]) {
this[kContext].emit('flushHistory');
}
}
} catch (err) {
this[kWriting] = false;
debug('Error writing history file:', err);
}
}
async [kOnExit]() {
if (this[kIsFlushing]) {
this[kContext].once('flushHistory', this[kOnExit].bind(this));
return;
}
this[kContext].off('line', this[kOnLine].bind(this));
if (this[kHistoryHandle] !== null) {
try {
await this[kHistoryHandle].close();
} catch (err) {
debug('Error closing history file:', err);
}
}
}
[kReplHistoryMessage]() {
if (this[kHistory].length === 0) {
ReplHistory[kWriteToOutput](
this[kContext],
'\nPersistent history support disabled. ' +
'Set the NODE_REPL_HISTORY environment\nvariable to ' +
'a valid, user-writable path to enable.\n',
);
}
// First restore the original method on the context
this[kContext]._historyPrev = this.historyPrev;
// Then call it with the correct context
return this[kContext]._historyPrev();
}
}
module.exports = {
ReplHistory,
};