@lvce-editor/search-process 4.2.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/bin/searchProcess.js +1 -1
  2. package/dist/index.js +468 -0
  3. package/package.json +12 -54
  4. package/src/parts/Assert/Assert.js +0 -1
  5. package/src/parts/Character/Character.js +0 -2
  6. package/src/parts/CollectTextSearchStdout/CollectTextSearchStdout.js +0 -103
  7. package/src/parts/CommandMap/CommandMap.js +0 -11
  8. package/src/parts/EncodingType/EncodingType.js +0 -2
  9. package/src/parts/Env/Env.js +0 -3
  10. package/src/parts/ErrorCodes/ErrorCodes.js +0 -2
  11. package/src/parts/Exec/Exec.js +0 -20
  12. package/src/parts/GetFirstEvent/GetFirstEvent.js +0 -23
  13. package/src/parts/GetNewLineIndex/GetNewLineIndex.js +0 -11
  14. package/src/parts/HandleElectronMessagePort/HandleElectronMessagePort.js +0 -11
  15. package/src/parts/HandleWebSocket/HandleWebSocket.js +0 -13
  16. package/src/parts/IpcChild/IpcChild.js +0 -8
  17. package/src/parts/IpcChildModule/IpcChildModule.js +0 -25
  18. package/src/parts/IpcChildType/IpcChildType.js +0 -19
  19. package/src/parts/IsEnoentError/IsEnoentError.js +0 -13
  20. package/src/parts/IsEnoentErrorWindows/IsEnoentErrorWindows.js +0 -3
  21. package/src/parts/LimitString/LimitString.js +0 -17
  22. package/src/parts/Listen/Listen.js +0 -10
  23. package/src/parts/Logger/Logger.js +0 -38
  24. package/src/parts/Main/Main.js +0 -5
  25. package/src/parts/ParseRipGrepLines/ParseRipGrepLines.js +0 -11
  26. package/src/parts/ProcessExitEventType/ProcessExitEventType.js +0 -2
  27. package/src/parts/Promises/Promises.js +0 -19
  28. package/src/parts/RipGrep/RipGrep.js +0 -40
  29. package/src/parts/RipGrepParsedLineType/RipGrepParsedLineType.js +0 -3
  30. package/src/parts/RipGrepPath/RipGrepPath.js +0 -1
  31. package/src/parts/SearchFile/SearchFile.js +0 -35
  32. package/src/parts/TextSearch/TextSearch.js +0 -31
  33. package/src/parts/TextSearchError/TextSearchError.js +0 -15
  34. package/src/parts/TextSearchResultType/TextSearchResultType.js +0 -2
  35. package/src/parts/ToTextSearchResult/ToTextSearchResult.js +0 -25
  36. package/src/parts/VError/VError.js +0 -1
  37. package/src/parts/WaitForProcessToExit/WaitForProcessToExit.js +0 -9
  38. package/src/searchProcessMain.js +0 -3
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import '../src/searchProcessMain.js'
3
+ import '../dist/index.js'
package/dist/index.js ADDED
@@ -0,0 +1,468 @@
1
+ import { object, string, array, number } from '@lvce-editor/assert';
2
+ import { NodeWebSocketRpcClient, ElectronMessagePortRpcClient, ElectronUtilityProcessRpcClient, NodeWorkerRpcClient, NodeForkedProcessRpcClient } from '@lvce-editor/rpc';
3
+ import { Console } from 'node:console';
4
+ import { createWriteStream } from 'node:fs';
5
+ import { tmpdir } from 'node:os';
6
+ import * as NodeChildProcess from 'node:child_process';
7
+ import { execa } from 'execa';
8
+ import { rgPath } from '@lvce-editor/ripgrep';
9
+ import { VError } from '@lvce-editor/verror';
10
+ import { Writable } from 'node:stream';
11
+ import { pipeline } from 'node:stream/promises';
12
+
13
+ const NodeWorker = 1;
14
+ const NodeForkedProcess = 2;
15
+ const ElectronUtilityProcess = 3;
16
+ const ElectronMessagePort = 4;
17
+ const WebSocket = 6;
18
+ const Auto = () => {
19
+ const {
20
+ argv
21
+ } = process;
22
+ if (argv.includes('--ipc-type=node-worker')) {
23
+ return NodeWorker;
24
+ }
25
+ if (argv.includes('--ipc-type=node-forked-process')) {
26
+ return NodeForkedProcess;
27
+ }
28
+ if (argv.includes('--ipc-type=electron-utility-process')) {
29
+ return ElectronUtilityProcess;
30
+ }
31
+ throw new Error(`[shared-process] unknown ipc type`);
32
+ };
33
+
34
+ const getModule = method => {
35
+ switch (method) {
36
+ case NodeForkedProcess:
37
+ return NodeForkedProcessRpcClient;
38
+ case NodeWorker:
39
+ return NodeWorkerRpcClient;
40
+ case ElectronUtilityProcess:
41
+ return ElectronUtilityProcessRpcClient;
42
+ case ElectronMessagePort:
43
+ return ElectronMessagePortRpcClient;
44
+ case WebSocket:
45
+ return NodeWebSocketRpcClient;
46
+ default:
47
+ throw new Error('unexpected ipc type');
48
+ }
49
+ };
50
+
51
+ const listen$1 = async ({
52
+ method,
53
+ ...params
54
+ }) => {
55
+ const module = getModule(method);
56
+ // @ts-ignore
57
+ const rpc = await module.create(params);
58
+ return rpc;
59
+ };
60
+
61
+ const handleElectronMessagePort = async (messagePort, ...params) => {
62
+ object(messagePort);
63
+ await listen$1({
64
+ method: ElectronMessagePort,
65
+ messagePort
66
+ });
67
+ };
68
+
69
+ const handleWebSocket = async (handle, request) => {
70
+ object(handle);
71
+ object(request);
72
+ await listen$1({
73
+ method: WebSocket,
74
+ request,
75
+ handle
76
+ });
77
+ };
78
+
79
+ const EmptyString = '';
80
+ const NewLine = '\n';
81
+
82
+ const ENOENT = 'ENOENT';
83
+ const E_RIP_GREP_NOT_FOUND = 'E_RIP_GREP_NOT_FOUND';
84
+
85
+ const isEnoentErrorWindows = error => {
86
+ return error && error.message && error.message.includes('The system cannot find the path specified.');
87
+ };
88
+
89
+ const isEnoentErrorLinux = error => {
90
+ return error.code === ENOENT;
91
+ };
92
+ const isEnoentError = error => {
93
+ if (!error) {
94
+ return false;
95
+ }
96
+ return isEnoentErrorLinux(error) || isEnoentErrorWindows(error);
97
+ };
98
+
99
+ const getNewLineIndex = (string, startIndex = undefined) => {
100
+ return string.indexOf(NewLine, startIndex);
101
+ };
102
+
103
+ const limitString = (string, limit) => {
104
+ let lines = 0;
105
+ let i = 0;
106
+ while (i !== -1 && lines < limit) {
107
+ i = getNewLineIndex(string, i + 1);
108
+ if (i === -1) {
109
+ break;
110
+ }
111
+ lines++;
112
+ }
113
+ if (i === -1) {
114
+ return string;
115
+ }
116
+ return string.slice(0, i);
117
+ };
118
+
119
+ // TODO mock this module when used in unit tests
120
+
121
+ const state = {
122
+ console: undefined
123
+ };
124
+ const createConsole = () => {
125
+ const logFile = `${tmpdir()}/log-shared-process.txt`;
126
+ const writeStream = createWriteStream(logFile);
127
+ const logger = new Console(writeStream);
128
+ return logger;
129
+ };
130
+ const getOrCreateLogger = () => {
131
+ if (!state.console) {
132
+ state.console = createConsole();
133
+ }
134
+ return state.console;
135
+ };
136
+ const info = (...args) => {
137
+ const logger = getOrCreateLogger();
138
+ logger.info(...args);
139
+ console.info(...args);
140
+ };
141
+ const error = (...args) => {
142
+ const logger = getOrCreateLogger();
143
+ logger.error(...args);
144
+ console.error(...args);
145
+ };
146
+
147
+ const getRipGrepPath = () => {
148
+ return process.env.RIP_GREP_PATH;
149
+ };
150
+
151
+ const exec$1 = async (command, args, options) => {
152
+ string(command);
153
+ array(args);
154
+ object(options);
155
+ const {
156
+ stdout,
157
+ stderr
158
+ } = await execa(command, args, options);
159
+ return {
160
+ stdout,
161
+ stderr
162
+ };
163
+ };
164
+
165
+ const ripGrepPath = getRipGrepPath() || rgPath;
166
+ const spawn = (args, options) => {
167
+ try {
168
+ const childProcess = NodeChildProcess.spawn(rgPath, args, options);
169
+ return {
170
+ childProcess,
171
+ on(event, listener) {
172
+ this.childProcess.on(event, listener);
173
+ },
174
+ off(event, listener) {
175
+ this.childProcess.off(event, listener);
176
+ },
177
+ once(event, listener) {
178
+ this.childProcess.once(event, listener);
179
+ },
180
+ stdout: childProcess.stdout,
181
+ stderr: childProcess.stderr,
182
+ kill() {
183
+ this.childProcess.kill();
184
+ }
185
+ };
186
+ } catch (error) {
187
+ throw new VError(error, `Failed to spawn ripgrep`);
188
+ }
189
+ };
190
+ const exec = async (args, options) => {
191
+ array(args);
192
+ object(options);
193
+ const {
194
+ stdout,
195
+ stderr
196
+ } = await exec$1(ripGrepPath, args, options);
197
+ return {
198
+ stdout,
199
+ stderr
200
+ };
201
+ };
202
+
203
+ // TODO don't necessarily need ripgrep to list all the files,
204
+ // maybe also a faster c program can do it
205
+ // another option would be to cache the results in renderer-worker and
206
+ // do a delta comparison, so the first time it would send 100kB
207
+ // but the second time only a few hundred bytes of changes
208
+
209
+ const searchFile = async ({
210
+ searchPath = '',
211
+ limit = 100,
212
+ ripGrepArgs = []
213
+ }) => {
214
+ try {
215
+ string(searchPath);
216
+ array(ripGrepArgs);
217
+ number(limit);
218
+ const {
219
+ stdout,
220
+ stderr
221
+ } = await exec(ripGrepArgs, {
222
+ cwd: searchPath
223
+ });
224
+ return limitString(stdout, limit);
225
+ } catch (error$1) {
226
+ if (isEnoentError(error$1)) {
227
+ info(`[shared-process] ripgrep could not be found at "${ripGrepPath}"`);
228
+ return EmptyString;
229
+ }
230
+ // @ts-ignore
231
+ if (error$1 && error$1.stderr === EmptyString) {
232
+ return EmptyString;
233
+ }
234
+ error(error$1);
235
+ return EmptyString;
236
+ }
237
+ };
238
+
239
+ const Utf8 = 'utf8';
240
+ const Base64 = 'base64';
241
+
242
+ const Begin = 'begin';
243
+ const Match$1 = 'match';
244
+ const Summary = 'summary';
245
+
246
+ const File = 1;
247
+ const Match = 2;
248
+
249
+ const parseRipGrepLines = parsedLineData => {
250
+ if (parsedLineData.lines.text) {
251
+ return parsedLineData.lines.text;
252
+ }
253
+ if (parsedLineData.lines.bytes) {
254
+ return Buffer.from(parsedLineData.lines.bytes, Base64).toString();
255
+ }
256
+ throw new Error(`unable to parse line data`);
257
+ };
258
+
259
+ const toTextSearchResult = (parsedLine, remaining, charsBefore, charsAfter) => {
260
+ const results = [];
261
+ const parsedLineData = parsedLine.data;
262
+ const lines = parseRipGrepLines(parsedLineData);
263
+ const lineNumber = parsedLineData.line_number;
264
+ const {
265
+ submatches
266
+ } = parsedLineData;
267
+ const linesLength = lines.length;
268
+ for (const submatch of submatches) {
269
+ const previewStart = Math.max(submatch.start - charsBefore, 0);
270
+ const actualStart = previewStart;
271
+ const previewEnd = Math.min(submatch.end + charsAfter, linesLength);
272
+ const previewText = lines.slice(actualStart, previewEnd);
273
+ results.push({
274
+ type: Match,
275
+ start: submatch.start - actualStart,
276
+ end: submatch.end - actualStart,
277
+ lineNumber,
278
+ text: previewText
279
+ });
280
+ }
281
+ return results;
282
+ };
283
+
284
+ // TODO update vscode-ripgrep when https://github.com/mhinz/vim-grepper/issues/244, https://github.com/BurntSushi/ripgrep/issues/1892 is fixed
285
+
286
+ // need to use '.' as last argument for ripgrep
287
+ // issue 1 https://github.com/nvim-telescope/telescope.nvim/pull/908/files
288
+ // issue 2 https://github.com/BurntSushi/ripgrep/issues/1892
289
+ // remove workaround when ripgrep is fixed
290
+
291
+ // TODO stats flag might not be necessary
292
+ // TODO update client
293
+ // TODO not always run nice, maybe configure nice via flag/options
294
+
295
+ const collectStdout = async (childProcess, maxSearchResults, charsBefore, charsAfter) => {
296
+ const allSearchResults = Object.create(null);
297
+ let buffer = '';
298
+ let stats = {};
299
+ let limitHit = false;
300
+ let numberOfResults = 0;
301
+ childProcess.stdout.setEncoding(Utf8);
302
+ const handleLine = line => {
303
+ const parsedLine = JSON.parse(line);
304
+ const {
305
+ type,
306
+ data
307
+ } = parsedLine;
308
+ switch (type) {
309
+ case Begin:
310
+ allSearchResults[data.path.text] = [{
311
+ type: File,
312
+ start: 0,
313
+ end: 0,
314
+ lineNumber: 0,
315
+ text: data.path.text
316
+ }];
317
+ break;
318
+ case Match$1:
319
+ const remaining = maxSearchResults - numberOfResults;
320
+ const matches = toTextSearchResult(parsedLine, remaining, charsBefore, charsAfter);
321
+ numberOfResults += matches.length;
322
+ allSearchResults[data.path.text].push(...matches);
323
+ break;
324
+ case Summary:
325
+ stats = data;
326
+ break;
327
+ }
328
+ };
329
+ const handleData = chunk => {
330
+ let newLineIndex = getNewLineIndex(chunk);
331
+ const dataString = buffer + chunk;
332
+ if (newLineIndex === -1) {
333
+ buffer = dataString;
334
+ return;
335
+ }
336
+ newLineIndex += buffer.length;
337
+ let previousIndex = 0;
338
+ while (newLineIndex >= 0) {
339
+ const line = dataString.slice(previousIndex, newLineIndex);
340
+ handleLine(line);
341
+ previousIndex = newLineIndex + 1;
342
+ newLineIndex = getNewLineIndex(dataString, previousIndex);
343
+ }
344
+ buffer = dataString.slice(previousIndex);
345
+ if (numberOfResults > maxSearchResults) {
346
+ limitHit = true;
347
+ childProcess.kill();
348
+ }
349
+ };
350
+ await pipeline(childProcess.stdout, new Writable({
351
+ decodeStrings: false,
352
+ construct(callback) {
353
+ callback();
354
+ },
355
+ write(chunk, encoding, callback) {
356
+ try {
357
+ handleData(chunk);
358
+ callback();
359
+ } catch (error) {
360
+ callback(error);
361
+ }
362
+ }
363
+ }));
364
+ const results = Object.values(allSearchResults).flat(1);
365
+ return {
366
+ results,
367
+ stats,
368
+ limitHit
369
+ };
370
+ };
371
+
372
+ const Error$1 = 1;
373
+ const Exit = 2;
374
+
375
+ class TextSearchError extends Error {
376
+ constructor(cause) {
377
+ if (isEnoentError(cause)) {
378
+ super(`ripgrep path not found: ${cause}`);
379
+ this.code = E_RIP_GREP_NOT_FOUND;
380
+ } else {
381
+ super(`ripgrep process error: ${cause}`);
382
+ this.code = cause.code;
383
+ }
384
+ this.name = 'TextSearchError';
385
+ }
386
+ }
387
+
388
+ const getFirstEvent = (eventEmitter, eventMap) => {
389
+ const {
390
+ resolve,
391
+ promise
392
+ } = Promise.withResolvers();
393
+ const listenerMap = Object.create(null);
394
+ const cleanup = value => {
395
+ for (const event of Object.keys(eventMap)) {
396
+ eventEmitter.off(event, listenerMap[event]);
397
+ }
398
+ resolve(value);
399
+ };
400
+ for (const [event, type] of Object.entries(eventMap)) {
401
+ const listener = event => {
402
+ cleanup({
403
+ type,
404
+ event
405
+ });
406
+ };
407
+ eventEmitter.on(event, listener);
408
+ listenerMap[event] = listener;
409
+ }
410
+ return promise;
411
+ };
412
+
413
+ const waitForProcessToExit = childProcess => {
414
+ return getFirstEvent(childProcess, {
415
+ error: Error$1,
416
+ close: Exit
417
+ });
418
+ };
419
+
420
+ // TODO update vscode-ripgrep when https://github.com/mhinz/vim-grepper/issues/244, https://github.com/BurntSushi/ripgrep/issues/1892 is fixed
421
+
422
+ // need to use '.' as last argument for ripgrep
423
+ // issue 1 https://github.com/nvim-telescope/telescope.nvim/pull/908/files
424
+ // issue 2 https://github.com/BurntSushi/ripgrep/issues/1892
425
+ // remove workaround when ripgrep is fixed
426
+
427
+ // TODO stats flag might not be necessary
428
+ // TODO update client
429
+ // TODO not always run nice, maybe configure nice via flag/options
430
+
431
+ const search = async ({
432
+ searchDir = '',
433
+ maxSearchResults = 20_000,
434
+ ripGrepArgs = []
435
+ } = {}) => {
436
+ const charsBefore = 26;
437
+ const charsAfter = 50;
438
+ const childProcess = spawn(ripGrepArgs, {
439
+ cwd: searchDir
440
+ });
441
+ const pipeLinePromise = collectStdout(childProcess, maxSearchResults, charsBefore, charsAfter);
442
+ const closePromise = waitForProcessToExit(childProcess);
443
+ const [pipeLineResult, exitResult] = await Promise.all([pipeLinePromise, closePromise]);
444
+ if (exitResult.type === Error$1) {
445
+ throw new TextSearchError(exitResult.event);
446
+ }
447
+ return pipeLineResult;
448
+ };
449
+
450
+ const commandMap = {
451
+ 'HandleElectronMessagePort.handleElectronMessagePort': handleElectronMessagePort,
452
+ 'SearchFile.searchFile': searchFile,
453
+ 'HandleWebSocket.handleWebSocket': handleWebSocket,
454
+ 'TextSearch.search': search
455
+ };
456
+
457
+ const listen = async () => {
458
+ await listen$1({
459
+ method: Auto(),
460
+ commandMap: commandMap
461
+ });
462
+ };
463
+
464
+ const main = async () => {
465
+ await listen();
466
+ };
467
+
468
+ main();
package/package.json CHANGED
@@ -1,21 +1,21 @@
1
1
  {
2
2
  "name": "@lvce-editor/search-process",
3
- "version": "4.2.0",
3
+ "version": "5.1.0",
4
4
  "description": "Search Process",
5
- "main": "src/searchProcessMain.js",
6
- "bin": "./bin/searchProcess.js",
7
- "type": "module",
8
5
  "keywords": [
9
- "Lvce Editor"
6
+ "Lvce Editor",
7
+ "Search"
10
8
  ],
11
- "author": "Lvce Editor",
12
- "license": "MIT",
13
9
  "repository": {
14
10
  "type": "git",
15
- "url": "https://github.com/lvce-editor/search-process.git"
11
+ "url": "git+https://github.com/lvce-editor/search-process.git"
16
12
  },
17
- "engines": {
18
- "node": ">=18"
13
+ "license": "MIT",
14
+ "author": "Lvce Editor",
15
+ "type": "module",
16
+ "main": "dist/index.js",
17
+ "bin": {
18
+ "search-process": "bin/searchProcess.js"
19
19
  },
20
20
  "dependencies": {
21
21
  "@lvce-editor/assert": "^1.3.0",
@@ -26,49 +26,7 @@
26
26
  "optionalDependencies": {
27
27
  "@lvce-editor/ripgrep": "^1.6.0"
28
28
  },
29
- "xo": {
30
- "rules": {
31
- "unicorn/filename-case": "off",
32
- "indent": "off",
33
- "semi": "off",
34
- "no-unused-vars": "off",
35
- "unicorn/numeric-separators-style": "off",
36
- "no-extra-semi": "off",
37
- "arrow-body-style": "off",
38
- "padded-blocks": "off",
39
- "capitalized-comments": "off",
40
- "padding-line-between-statements": "off",
41
- "arrow-parens": "off",
42
- "no-warning-comments": "off",
43
- "array-bracket-spacing": "off",
44
- "comma-spacing": "off",
45
- "unicorn/no-array-callback-reference": "off",
46
- "comma-dangle": "off",
47
- "operator-linebreak": "off",
48
- "no-case-declarations": "off",
49
- "no-undef": "off",
50
- "object-curly-spacing": "off",
51
- "object-shorthand": "off",
52
- "complexity": "off",
53
- "no-labels": "off",
54
- "no-multi-assign": "off",
55
- "max-params": "off",
56
- "no-bitwise": "off",
57
- "unicorn/prefer-math-trunc": "off",
58
- "no-await-in-loop": "off",
59
- "unicorn/prefer-add-event-listener": "off",
60
- "no-unused-expressions": "off",
61
- "node/prefer-global/process": "off",
62
- "unicorn/prevent-abbreviations": "off",
63
- "unicorn/no-process-exit": "off",
64
- "quotes": "off",
65
- "n/prefer-global/process": [
66
- "error",
67
- "always"
68
- ]
69
- },
70
- "ignores": [
71
- "distmin"
72
- ]
29
+ "engines": {
30
+ "node": ">=22"
73
31
  }
74
32
  }
@@ -1 +0,0 @@
1
- export * from '@lvce-editor/assert'
@@ -1,2 +0,0 @@
1
- export const EmptyString = ''
2
- export const NewLine = '\n'
@@ -1,103 +0,0 @@
1
- import { Writable } from 'node:stream'
2
- import { pipeline } from 'node:stream/promises'
3
- import * as EncodingType from '../EncodingType/EncodingType.js'
4
- import * as GetNewLineIndex from '../GetNewLineIndex/GetNewLineIndex.js'
5
- import * as RipGrepParsedLineType from '../RipGrepParsedLineType/RipGrepParsedLineType.js'
6
- import * as TextSearchResultType from '../TextSearchResultType/TextSearchResultType.js'
7
- import * as ToTextSearchResult from '../ToTextSearchResult/ToTextSearchResult.js'
8
- // TODO update vscode-ripgrep when https://github.com/mhinz/vim-grepper/issues/244, https://github.com/BurntSushi/ripgrep/issues/1892 is fixed
9
-
10
- // need to use '.' as last argument for ripgrep
11
- // issue 1 https://github.com/nvim-telescope/telescope.nvim/pull/908/files
12
- // issue 2 https://github.com/BurntSushi/ripgrep/issues/1892
13
- // remove workaround when ripgrep is fixed
14
-
15
- // TODO stats flag might not be necessary
16
- // TODO update client
17
- // TODO not always run nice, maybe configure nice via flag/options
18
-
19
- export const collectStdout = async (childProcess, maxSearchResults, charsBefore, charsAfter) => {
20
- const allSearchResults = Object.create(null)
21
- let buffer = ''
22
- let stats = {}
23
- let limitHit = false
24
- let numberOfResults = 0
25
-
26
- childProcess.stdout.setEncoding(EncodingType.Utf8)
27
-
28
- const handleLine = (line) => {
29
- const parsedLine = JSON.parse(line)
30
- const { type, data } = parsedLine
31
- switch (type) {
32
- case RipGrepParsedLineType.Begin:
33
- allSearchResults[data.path.text] = [
34
- {
35
- type: TextSearchResultType.File,
36
- start: 0,
37
- end: 0,
38
- lineNumber: 0,
39
- text: data.path.text,
40
- },
41
- ]
42
- break
43
- case RipGrepParsedLineType.Match:
44
- const remaining = maxSearchResults - numberOfResults
45
- const matches = ToTextSearchResult.toTextSearchResult(parsedLine, remaining, charsBefore, charsAfter)
46
- numberOfResults += matches.length
47
- allSearchResults[data.path.text].push(...matches)
48
- break
49
- case RipGrepParsedLineType.Summary:
50
- stats = data
51
- break
52
- default:
53
- break
54
- }
55
- }
56
-
57
- const handleData = (chunk) => {
58
- let newLineIndex = GetNewLineIndex.getNewLineIndex(chunk)
59
- const dataString = buffer + chunk
60
- if (newLineIndex === -1) {
61
- buffer = dataString
62
- return
63
- }
64
- newLineIndex += buffer.length
65
- let previousIndex = 0
66
- while (newLineIndex >= 0) {
67
- const line = dataString.slice(previousIndex, newLineIndex)
68
- handleLine(line)
69
- previousIndex = newLineIndex + 1
70
- newLineIndex = GetNewLineIndex.getNewLineIndex(dataString, previousIndex)
71
- }
72
- buffer = dataString.slice(previousIndex)
73
-
74
- if (numberOfResults > maxSearchResults) {
75
- limitHit = true
76
- childProcess.kill()
77
- }
78
- }
79
-
80
- await pipeline(
81
- childProcess.stdout,
82
- new Writable({
83
- decodeStrings: false,
84
- construct(callback) {
85
- callback()
86
- },
87
- write(chunk, encoding, callback) {
88
- try {
89
- handleData(chunk)
90
- callback()
91
- } catch (error) {
92
- callback(error)
93
- }
94
- },
95
- }),
96
- )
97
- const results = Object.values(allSearchResults).flat(1)
98
- return {
99
- results,
100
- stats,
101
- limitHit,
102
- }
103
- }
@@ -1,11 +0,0 @@
1
- import * as HandleElectronMessagePort from '../HandleElectronMessagePort/HandleElectronMessagePort.js'
2
- import * as HandleWebSocket from '../HandleWebSocket/HandleWebSocket.js'
3
- import * as SearchFile from '../SearchFile/SearchFile.js'
4
- import * as TextSearch from '../TextSearch/TextSearch.js'
5
-
6
- export const commandMap = {
7
- 'HandleElectronMessagePort.handleElectronMessagePort': HandleElectronMessagePort.handleElectronMessagePort,
8
- 'SearchFile.searchFile': SearchFile.searchFile,
9
- 'HandleWebSocket.handleWebSocket': HandleWebSocket.handleWebSocket,
10
- 'TextSearch.search': TextSearch.search,
11
- }
@@ -1,2 +0,0 @@
1
- export const Utf8 = 'utf8'
2
- export const Base64 = 'base64'
@@ -1,3 +0,0 @@
1
- export const getRipGrepPath = () => {
2
- return process.env.RIP_GREP_PATH
3
- }
@@ -1,2 +0,0 @@
1
- export const ENOENT = 'ENOENT'
2
- export const E_RIP_GREP_NOT_FOUND = 'E_RIP_GREP_NOT_FOUND'
@@ -1,20 +0,0 @@
1
- import { execa } from 'execa'
2
- import * as Assert from '../Assert/Assert.js'
3
-
4
- /**
5
- *
6
- * @param {string} command
7
- * @param {string[]} args
8
- * @param {import('execa').Options} options
9
- * @returns
10
- */
11
- export const exec = async (command, args, options) => {
12
- Assert.string(command)
13
- Assert.array(args)
14
- Assert.object(options)
15
- const { stdout, stderr } = await execa(command, args, options)
16
- return {
17
- stdout,
18
- stderr,
19
- }
20
- }
@@ -1,23 +0,0 @@
1
- import * as Promises from '../Promises/Promises.js'
2
-
3
- export const getFirstEvent = (eventEmitter, eventMap) => {
4
- const { resolve, promise } = Promises.withResolvers()
5
- const listenerMap = Object.create(null)
6
- const cleanup = (value) => {
7
- for (const event of Object.keys(eventMap)) {
8
- eventEmitter.off(event, listenerMap[event])
9
- }
10
- resolve(value)
11
- }
12
- for (const [event, type] of Object.entries(eventMap)) {
13
- const listener = (event) => {
14
- cleanup({
15
- type,
16
- event,
17
- })
18
- }
19
- eventEmitter.on(event, listener)
20
- listenerMap[event] = listener
21
- }
22
- return promise
23
- }
@@ -1,11 +0,0 @@
1
- import * as Character from '../Character/Character.js'
2
-
3
- /**
4
- *
5
- * @param {string} string
6
- * @param {number|undefined} startIndex
7
- * @returns
8
- */
9
- export const getNewLineIndex = (string, startIndex = undefined) => {
10
- return string.indexOf(Character.NewLine, startIndex)
11
- }
@@ -1,11 +0,0 @@
1
- import * as Assert from '../Assert/Assert.js'
2
- import * as IpcChild from '../IpcChild/IpcChild.js'
3
- import * as IpcChildType from '../IpcChildType/IpcChildType.js'
4
-
5
- export const handleElectronMessagePort = async (messagePort, ...params) => {
6
- Assert.object(messagePort)
7
- await IpcChild.listen({
8
- method: IpcChildType.ElectronMessagePort,
9
- messagePort,
10
- })
11
- }
@@ -1,13 +0,0 @@
1
- import * as Assert from '../Assert/Assert.js'
2
- import * as IpcChild from '../IpcChild/IpcChild.js'
3
- import * as IpcChildType from '../IpcChildType/IpcChildType.js'
4
-
5
- export const handleWebSocket = async (handle, request) => {
6
- Assert.object(handle)
7
- Assert.object(request)
8
- await IpcChild.listen({
9
- method: IpcChildType.WebSocket,
10
- request,
11
- handle,
12
- })
13
- }
@@ -1,8 +0,0 @@
1
- import * as IpcChildModule from '../IpcChildModule/IpcChildModule.js'
2
-
3
- export const listen = async ({ method, ...params }) => {
4
- const module = IpcChildModule.getModule(method)
5
- // @ts-ignore
6
- const rpc = await module.create(params)
7
- return rpc
8
- }
@@ -1,25 +0,0 @@
1
- import {
2
- ElectronMessagePortRpcClient,
3
- ElectronUtilityProcessRpcClient,
4
- NodeForkedProcessRpcClient,
5
- NodeWebSocketRpcClient,
6
- NodeWorkerRpcClient,
7
- } from '@lvce-editor/rpc'
8
- import * as IpcChildType from '../IpcChildType/IpcChildType.js'
9
-
10
- export const getModule = (method) => {
11
- switch (method) {
12
- case IpcChildType.NodeForkedProcess:
13
- return NodeForkedProcessRpcClient
14
- case IpcChildType.NodeWorker:
15
- return NodeWorkerRpcClient
16
- case IpcChildType.ElectronUtilityProcess:
17
- return ElectronUtilityProcessRpcClient
18
- case IpcChildType.ElectronMessagePort:
19
- return ElectronMessagePortRpcClient
20
- case IpcChildType.WebSocket:
21
- return NodeWebSocketRpcClient
22
- default:
23
- throw new Error('unexpected ipc type')
24
- }
25
- }
@@ -1,19 +0,0 @@
1
- export const NodeWorker = 1
2
- export const NodeForkedProcess = 2
3
- export const ElectronUtilityProcess = 3
4
- export const ElectronMessagePort = 4
5
- export const WebSocket = 6
6
-
7
- export const Auto = () => {
8
- const { argv } = process
9
- if (argv.includes('--ipc-type=node-worker')) {
10
- return NodeWorker
11
- }
12
- if (argv.includes('--ipc-type=node-forked-process')) {
13
- return NodeForkedProcess
14
- }
15
- if (argv.includes('--ipc-type=electron-utility-process')) {
16
- return ElectronUtilityProcess
17
- }
18
- throw new Error(`[shared-process] unknown ipc type`)
19
- }
@@ -1,13 +0,0 @@
1
- import * as ErrorCodes from '../ErrorCodes/ErrorCodes.js'
2
- import * as IsEnoentErrorWindows from '../IsEnoentErrorWindows/IsEnoentErrorWindows.js'
3
-
4
- const isEnoentErrorLinux = (error) => {
5
- return error.code === ErrorCodes.ENOENT
6
- }
7
-
8
- export const isEnoentError = (error) => {
9
- if (!error) {
10
- return false
11
- }
12
- return isEnoentErrorLinux(error) || IsEnoentErrorWindows.isEnoentErrorWindows(error)
13
- }
@@ -1,3 +0,0 @@
1
- export const isEnoentErrorWindows = (error) => {
2
- return error && error.message && error.message.includes('The system cannot find the path specified.')
3
- }
@@ -1,17 +0,0 @@
1
- import * as GetNewLineIndex from '../GetNewLineIndex/GetNewLineIndex.js'
2
-
3
- export const limitString = (string, limit) => {
4
- let lines = 0
5
- let i = 0
6
- while (i !== -1 && lines < limit) {
7
- i = GetNewLineIndex.getNewLineIndex(string, i + 1)
8
- if (i === -1) {
9
- break
10
- }
11
- lines++
12
- }
13
- if (i === -1) {
14
- return string
15
- }
16
- return string.slice(0, i)
17
- }
@@ -1,10 +0,0 @@
1
- import * as CommandMap from '../CommandMap/CommandMap.js'
2
- import * as IpcChild from '../IpcChild/IpcChild.js'
3
- import * as IpcChildType from '../IpcChildType/IpcChildType.js'
4
-
5
- export const listen = async () => {
6
- await IpcChild.listen({
7
- method: IpcChildType.Auto(),
8
- commandMap: CommandMap.commandMap,
9
- })
10
- }
@@ -1,38 +0,0 @@
1
- import { Console } from 'node:console'
2
- import { createWriteStream } from 'node:fs'
3
- import { tmpdir } from 'node:os'
4
-
5
- // TODO mock this module when used in unit tests
6
-
7
- const state = {
8
- /**
9
- * @type {Console|undefined}
10
- */
11
- console: undefined,
12
- }
13
-
14
- const createConsole = () => {
15
- const logFile = `${tmpdir()}/log-shared-process.txt`
16
- const writeStream = createWriteStream(logFile)
17
- const logger = new Console(writeStream)
18
- return logger
19
- }
20
-
21
- const getOrCreateLogger = () => {
22
- if (!state.console) {
23
- state.console = createConsole()
24
- }
25
- return state.console
26
- }
27
-
28
- export const info = (...args) => {
29
- const logger = getOrCreateLogger()
30
- logger.info(...args)
31
- console.info(...args)
32
- }
33
-
34
- export const error = (...args) => {
35
- const logger = getOrCreateLogger()
36
- logger.error(...args)
37
- console.error(...args)
38
- }
@@ -1,5 +0,0 @@
1
- import * as Listen from '../Listen/Listen.js'
2
-
3
- export const main = async () => {
4
- await Listen.listen()
5
- }
@@ -1,11 +0,0 @@
1
- import * as EncodingType from '../EncodingType/EncodingType.js'
2
-
3
- export const parseRipGrepLines = (parsedLineData) => {
4
- if (parsedLineData.lines.text) {
5
- return parsedLineData.lines.text
6
- }
7
- if (parsedLineData.lines.bytes) {
8
- return Buffer.from(parsedLineData.lines.bytes, EncodingType.Base64).toString()
9
- }
10
- throw new Error(`unable to parse line data`)
11
- }
@@ -1,2 +0,0 @@
1
- export const Error = 1
2
- export const Exit = 2
@@ -1,19 +0,0 @@
1
- export const withResolvers = () => {
2
- /**
3
- * @type {any}
4
- */
5
- let _resolve
6
- /**
7
- * @type {any}
8
- */
9
- let _reject
10
- const promise = new Promise((resolve, reject) => {
11
- _resolve = resolve
12
- _reject = reject
13
- })
14
- return {
15
- resolve: _resolve,
16
- reject: _reject,
17
- promise,
18
- }
19
- }
@@ -1,40 +0,0 @@
1
- import * as NodeChildProcess from 'node:child_process'
2
- import * as Assert from '../Assert/Assert.js'
3
- import * as Env from '../Env/Env.js'
4
- import * as Exec from '../Exec/Exec.js'
5
- import * as RgPath from '../RipGrepPath/RipGrepPath.js'
6
- import { VError } from '../VError/VError.js'
7
-
8
- export const ripGrepPath = Env.getRipGrepPath() || RgPath.rgPath
9
-
10
- export const spawn = (args, options) => {
11
- try {
12
- const childProcess = NodeChildProcess.spawn(RgPath.rgPath, args, options)
13
- return {
14
- childProcess,
15
- on(event, listener) {
16
- this.childProcess.on(event, listener)
17
- },
18
- off(event, listener) {
19
- this.childProcess.off(event, listener)
20
- },
21
- once(event, listener) {
22
- this.childProcess.once(event, listener)
23
- },
24
- stdout: childProcess.stdout,
25
- stderr: childProcess.stderr,
26
- kill() {
27
- this.childProcess.kill()
28
- },
29
- }
30
- } catch (error) {
31
- throw new VError(error, `Failed to spawn ripgrep`)
32
- }
33
- }
34
-
35
- export const exec = async (args, options) => {
36
- Assert.array(args)
37
- Assert.object(options)
38
- const { stdout, stderr } = await Exec.exec(ripGrepPath, args, options)
39
- return { stdout, stderr }
40
- }
@@ -1,3 +0,0 @@
1
- export const Begin = 'begin'
2
- export const Match = 'match'
3
- export const Summary = 'summary'
@@ -1 +0,0 @@
1
- export { rgPath } from '@lvce-editor/ripgrep'
@@ -1,35 +0,0 @@
1
- import * as Assert from '../Assert/Assert.js'
2
- import * as Character from '../Character/Character.js'
3
- import * as IsEnoentError from '../IsEnoentError/IsEnoentError.js'
4
- import * as LimitString from '../LimitString/LimitString.js'
5
- import * as Logger from '../Logger/Logger.js'
6
- import * as RipGrep from '../RipGrep/RipGrep.js'
7
-
8
- // TODO don't necessarily need ripgrep to list all the files,
9
- // maybe also a faster c program can do it
10
- // another option would be to cache the results in renderer-worker and
11
- // do a delta comparison, so the first time it would send 100kB
12
- // but the second time only a few hundred bytes of changes
13
-
14
- export const searchFile = async ({ searchPath = '', limit = 100, ripGrepArgs = [] }) => {
15
- try {
16
- Assert.string(searchPath)
17
- Assert.array(ripGrepArgs)
18
- Assert.number(limit)
19
- const { stdout, stderr } = await RipGrep.exec(ripGrepArgs, {
20
- cwd: searchPath,
21
- })
22
- return LimitString.limitString(stdout, limit)
23
- } catch (error) {
24
- if (IsEnoentError.isEnoentError(error)) {
25
- Logger.info(`[shared-process] ripgrep could not be found at "${RipGrep.ripGrepPath}"`)
26
- return Character.EmptyString
27
- }
28
- // @ts-ignore
29
- if (error && error.stderr === Character.EmptyString) {
30
- return Character.EmptyString
31
- }
32
- Logger.error(error)
33
- return Character.EmptyString
34
- }
35
- }
@@ -1,31 +0,0 @@
1
- import * as CollectTextSearchStdout from '../CollectTextSearchStdout/CollectTextSearchStdout.js'
2
- import * as ProcessExitEventType from '../ProcessExitEventType/ProcessExitEventType.js'
3
- import * as RipGrep from '../RipGrep/RipGrep.js'
4
- import { TextSearchError } from '../TextSearchError/TextSearchError.js'
5
- import * as WaitForProcessToExit from '../WaitForProcessToExit/WaitForProcessToExit.js'
6
-
7
- // TODO update vscode-ripgrep when https://github.com/mhinz/vim-grepper/issues/244, https://github.com/BurntSushi/ripgrep/issues/1892 is fixed
8
-
9
- // need to use '.' as last argument for ripgrep
10
- // issue 1 https://github.com/nvim-telescope/telescope.nvim/pull/908/files
11
- // issue 2 https://github.com/BurntSushi/ripgrep/issues/1892
12
- // remove workaround when ripgrep is fixed
13
-
14
- // TODO stats flag might not be necessary
15
- // TODO update client
16
- // TODO not always run nice, maybe configure nice via flag/options
17
-
18
- export const search = async ({ searchDir = '', maxSearchResults = 20_000, ripGrepArgs = [] } = {}) => {
19
- const charsBefore = 26
20
- const charsAfter = 50
21
- const childProcess = RipGrep.spawn(ripGrepArgs, {
22
- cwd: searchDir,
23
- })
24
- const pipeLinePromise = CollectTextSearchStdout.collectStdout(childProcess, maxSearchResults, charsBefore, charsAfter)
25
- const closePromise = WaitForProcessToExit.waitForProcessToExit(childProcess)
26
- const [pipeLineResult, exitResult] = await Promise.all([pipeLinePromise, closePromise])
27
- if (exitResult.type === ProcessExitEventType.Error) {
28
- throw new TextSearchError(exitResult.event)
29
- }
30
- return pipeLineResult
31
- }
@@ -1,15 +0,0 @@
1
- import * as ErrorCodes from '../ErrorCodes/ErrorCodes.js'
2
- import * as IsEnoentError from '../IsEnoentError/IsEnoentError.js'
3
-
4
- export class TextSearchError extends Error {
5
- constructor(cause) {
6
- if (IsEnoentError.isEnoentError(cause)) {
7
- super(`ripgrep path not found: ${cause}`)
8
- this.code = ErrorCodes.E_RIP_GREP_NOT_FOUND
9
- } else {
10
- super(`ripgrep process error: ${cause}`)
11
- this.code = cause.code
12
- }
13
- this.name = 'TextSearchError'
14
- }
15
- }
@@ -1,2 +0,0 @@
1
- export const File = 1
2
- export const Match = 2
@@ -1,25 +0,0 @@
1
- import * as ParseRipGrepLines from '../ParseRipGrepLines/ParseRipGrepLines.js'
2
- import * as TextSearchResultType from '../TextSearchResultType/TextSearchResultType.js'
3
-
4
- export const toTextSearchResult = (parsedLine, remaining, charsBefore, charsAfter) => {
5
- const results = []
6
- const parsedLineData = parsedLine.data
7
- const lines = ParseRipGrepLines.parseRipGrepLines(parsedLineData)
8
- const lineNumber = parsedLineData.line_number
9
- const { submatches } = parsedLineData
10
- const linesLength = lines.length
11
- for (const submatch of submatches) {
12
- const previewStart = Math.max(submatch.start - charsBefore, 0)
13
- const actualStart = previewStart
14
- const previewEnd = Math.min(submatch.end + charsAfter, linesLength)
15
- const previewText = lines.slice(actualStart, previewEnd)
16
- results.push({
17
- type: TextSearchResultType.Match,
18
- start: submatch.start - actualStart,
19
- end: submatch.end - actualStart,
20
- lineNumber,
21
- text: previewText,
22
- })
23
- }
24
- return results
25
- }
@@ -1 +0,0 @@
1
- export * from '@lvce-editor/verror'
@@ -1,9 +0,0 @@
1
- import * as GetFirstEvent from '../GetFirstEvent/GetFirstEvent.js'
2
- import * as ProcessExitEventType from '../ProcessExitEventType/ProcessExitEventType.js'
3
-
4
- export const waitForProcessToExit = (childProcess) => {
5
- return GetFirstEvent.getFirstEvent(childProcess, {
6
- error: ProcessExitEventType.Error,
7
- close: ProcessExitEventType.Exit,
8
- })
9
- }
@@ -1,3 +0,0 @@
1
- import * as Main from './parts/Main/Main.js'
2
-
3
- Main.main()