@lvce-editor/text-search-worker 3.18.0 → 3.20.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.
@@ -1,4 +1,4 @@
1
- const normalizeLine$1 = line => {
1
+ const normalizeLine = line => {
2
2
  if (line.startsWith('Error: ')) {
3
3
  return line.slice('Error: '.length);
4
4
  }
@@ -7,41 +7,41 @@ const normalizeLine$1 = line => {
7
7
  }
8
8
  return line;
9
9
  };
10
- const getCombinedMessage$1 = (error, message) => {
11
- const stringifiedError = normalizeLine$1(`${error}`);
10
+ const getCombinedMessage = (error, message) => {
11
+ const stringifiedError = normalizeLine(`${error}`);
12
12
  if (message) {
13
13
  return `${message}: ${stringifiedError}`;
14
14
  }
15
15
  return stringifiedError;
16
16
  };
17
- const NewLine$3 = '\n';
18
- const getNewLineIndex$2 = (string, startIndex = undefined) => {
19
- return string.indexOf(NewLine$3, startIndex);
17
+ const NewLine$2 = '\n';
18
+ const getNewLineIndex$1 = (string, startIndex = undefined) => {
19
+ return string.indexOf(NewLine$2, startIndex);
20
20
  };
21
- const mergeStacks$1 = (parent, child) => {
21
+ const mergeStacks = (parent, child) => {
22
22
  if (!child) {
23
23
  return parent;
24
24
  }
25
- const parentNewLineIndex = getNewLineIndex$2(parent);
26
- const childNewLineIndex = getNewLineIndex$2(child);
25
+ const parentNewLineIndex = getNewLineIndex$1(parent);
26
+ const childNewLineIndex = getNewLineIndex$1(child);
27
27
  if (childNewLineIndex === -1) {
28
28
  return parent;
29
29
  }
30
30
  const parentFirstLine = parent.slice(0, parentNewLineIndex);
31
31
  const childRest = child.slice(childNewLineIndex);
32
- const childFirstLine = normalizeLine$1(child.slice(0, childNewLineIndex));
32
+ const childFirstLine = normalizeLine(child.slice(0, childNewLineIndex));
33
33
  if (parentFirstLine.includes(childFirstLine)) {
34
34
  return parentFirstLine + childRest;
35
35
  }
36
36
  return child;
37
37
  };
38
- let VError$1 = class VError extends Error {
38
+ class VError extends Error {
39
39
  constructor(error, message) {
40
- const combinedMessage = getCombinedMessage$1(error, message);
40
+ const combinedMessage = getCombinedMessage(error, message);
41
41
  super(combinedMessage);
42
42
  this.name = 'VError';
43
43
  if (error instanceof Error) {
44
- this.stack = mergeStacks$1(this.stack, error.stack);
44
+ this.stack = mergeStacks(this.stack, error.stack);
45
45
  }
46
46
  if (error.codeFrame) {
47
47
  // @ts-ignore
@@ -52,7 +52,7 @@ let VError$1 = class VError extends Error {
52
52
  this.code = error.code;
53
53
  }
54
54
  }
55
- };
55
+ }
56
56
 
57
57
  class AssertionError extends Error {
58
58
  constructor(message) {
@@ -107,900 +107,843 @@ const string = value => {
107
107
  }
108
108
  };
109
109
 
110
- const Two = '2.0';
111
- const create$4 = (method, params) => {
112
- return {
113
- jsonrpc: Two,
114
- method,
115
- params
116
- };
110
+ const walkValue = (value, transferrables, isTransferrable) => {
111
+ if (!value) {
112
+ return;
113
+ }
114
+ if (isTransferrable(value)) {
115
+ transferrables.push(value);
116
+ return;
117
+ }
118
+ if (Array.isArray(value)) {
119
+ for (const item of value) {
120
+ walkValue(item, transferrables, isTransferrable);
121
+ }
122
+ return;
123
+ }
124
+ if (typeof value === 'object') {
125
+ for (const property of Object.values(value)) {
126
+ walkValue(property, transferrables, isTransferrable);
127
+ }
128
+ return;
129
+ }
117
130
  };
118
- const state$4 = {
119
- callbacks: Object.create(null)
131
+ const isMessagePort = value => {
132
+ return value && value instanceof MessagePort;
120
133
  };
121
- const set$1 = (id, fn) => {
122
- state$4.callbacks[id] = fn;
134
+ const isMessagePortMain = value => {
135
+ return value && value.constructor && value.constructor.name === 'MessagePortMain';
123
136
  };
124
- const get$1 = id => {
125
- return state$4.callbacks[id];
137
+ const isOffscreenCanvas = value => {
138
+ return typeof OffscreenCanvas !== 'undefined' && value instanceof OffscreenCanvas;
126
139
  };
127
- const remove$1 = id => {
128
- delete state$4.callbacks[id];
140
+ const isInstanceOf = (value, constructorName) => {
141
+ return value?.constructor?.name === constructorName;
129
142
  };
130
- let id = 0;
131
- const create$3$1 = () => {
132
- return ++id;
143
+ const isSocket = value => {
144
+ return isInstanceOf(value, 'Socket');
133
145
  };
134
- const warn = (...args) => {
135
- console.warn(...args);
146
+ const transferrables = [isMessagePort, isMessagePortMain, isOffscreenCanvas, isSocket];
147
+ const isTransferrable = value => {
148
+ for (const fn of transferrables) {
149
+ if (fn(value)) {
150
+ return true;
151
+ }
152
+ }
153
+ return false;
136
154
  };
137
- const registerPromise = () => {
138
- const id = create$3$1();
139
- const {
140
- resolve,
141
- promise
142
- } = Promise.withResolvers();
143
- set$1(id, resolve);
144
- return {
145
- id,
146
- promise
155
+ const getTransferrables = value => {
156
+ const transferrables = [];
157
+ walkValue(value, transferrables, isTransferrable);
158
+ return transferrables;
159
+ };
160
+ const attachEvents = that => {
161
+ const handleMessage = (...args) => {
162
+ const data = that.getData(...args);
163
+ that.dispatchEvent(new MessageEvent('message', {
164
+ data
165
+ }));
166
+ };
167
+ that.onMessage(handleMessage);
168
+ const handleClose = event => {
169
+ that.dispatchEvent(new Event('close'));
147
170
  };
171
+ that.onClose(handleClose);
148
172
  };
149
- const resolve = (id, response) => {
150
- const fn = get$1(id);
151
- if (!fn) {
152
- console.log(response);
153
- warn(`callback ${id} may already be disposed`);
154
- return;
173
+ class Ipc extends EventTarget {
174
+ constructor(rawIpc) {
175
+ super();
176
+ this._rawIpc = rawIpc;
177
+ attachEvents(this);
155
178
  }
156
- fn(response);
157
- remove$1(id);
179
+ }
180
+ const E_INCOMPATIBLE_NATIVE_MODULE = 'E_INCOMPATIBLE_NATIVE_MODULE';
181
+ const E_MODULES_NOT_SUPPORTED_IN_ELECTRON = 'E_MODULES_NOT_SUPPORTED_IN_ELECTRON';
182
+ const ERR_MODULE_NOT_FOUND = 'ERR_MODULE_NOT_FOUND';
183
+ const NewLine$1 = '\n';
184
+ const joinLines$1 = lines => {
185
+ return lines.join(NewLine$1);
158
186
  };
159
- const create$2$2 = (method, params) => {
160
- const {
161
- id,
162
- promise
163
- } = registerPromise();
164
- const message = {
165
- jsonrpc: Two,
166
- method,
167
- params,
168
- id
169
- };
187
+ const splitLines$1 = lines => {
188
+ return lines.split(NewLine$1);
189
+ };
190
+ const isModuleNotFoundMessage = line => {
191
+ return line.includes('[ERR_MODULE_NOT_FOUND]');
192
+ };
193
+ const getModuleNotFoundError = stderr => {
194
+ const lines = splitLines$1(stderr);
195
+ const messageIndex = lines.findIndex(isModuleNotFoundMessage);
196
+ const message = lines[messageIndex];
170
197
  return {
171
198
  message,
172
- promise
199
+ code: ERR_MODULE_NOT_FOUND
173
200
  };
174
201
  };
175
- class JsonRpcError extends Error {
176
- constructor(message) {
177
- super(message);
178
- this.name = 'JsonRpcError';
179
- }
180
- }
181
- const NewLine$2 = '\n';
182
- const DomException = 'DOMException';
183
- const ReferenceError$1 = 'ReferenceError';
184
- const SyntaxError$1 = 'SyntaxError';
185
- const TypeError$1 = 'TypeError';
186
- const getErrorConstructor = (message, type) => {
187
- if (type) {
188
- switch (type) {
189
- case DomException:
190
- return DOMException;
191
- case TypeError$1:
192
- return TypeError;
193
- case SyntaxError$1:
194
- return SyntaxError;
195
- case ReferenceError$1:
196
- return ReferenceError;
197
- default:
198
- return Error;
199
- }
200
- }
201
- if (message.startsWith('TypeError: ')) {
202
- return TypeError;
203
- }
204
- if (message.startsWith('SyntaxError: ')) {
205
- return SyntaxError;
206
- }
207
- if (message.startsWith('ReferenceError: ')) {
208
- return ReferenceError;
209
- }
210
- return Error;
202
+ const RE_NATIVE_MODULE_ERROR = /^innerError Error: Cannot find module '.*.node'/;
203
+ const RE_NATIVE_MODULE_ERROR_2 = /was compiled against a different Node.js version/;
204
+ const RE_MESSAGE_CODE_BLOCK_START = /^Error: The module '.*'$/;
205
+ const RE_MESSAGE_CODE_BLOCK_END = /^\s* at/;
206
+ const RE_AT = /^\s+at/;
207
+ const RE_AT_PROMISE_INDEX = /^\s*at async Promise.all \(index \d+\)$/;
208
+ const isUnhelpfulNativeModuleError = stderr => {
209
+ return RE_NATIVE_MODULE_ERROR.test(stderr) && RE_NATIVE_MODULE_ERROR_2.test(stderr);
211
210
  };
212
- const constructError = (message, type, name) => {
213
- const ErrorConstructor = getErrorConstructor(message, type);
214
- if (ErrorConstructor === DOMException && name) {
215
- return new ErrorConstructor(message, name);
216
- }
217
- if (ErrorConstructor === Error) {
218
- const error = new Error(message);
219
- if (name && name !== 'VError') {
220
- error.name = name;
221
- }
222
- return error;
223
- }
224
- return new ErrorConstructor(message);
211
+ const isMessageCodeBlockStartIndex = line => {
212
+ return RE_MESSAGE_CODE_BLOCK_START.test(line);
225
213
  };
226
- const getNewLineIndex$1 = (string, startIndex = undefined) => {
227
- return string.indexOf(NewLine$2, startIndex);
214
+ const isMessageCodeBlockEndIndex = line => {
215
+ return RE_MESSAGE_CODE_BLOCK_END.test(line);
228
216
  };
229
- const getParentStack = error => {
230
- let parentStack = error.stack || error.data || error.message || '';
231
- if (parentStack.startsWith(' at')) {
232
- parentStack = error.message + NewLine$2 + parentStack;
217
+ const getMessageCodeBlock = stderr => {
218
+ const lines = splitLines$1(stderr);
219
+ const startIndex = lines.findIndex(isMessageCodeBlockStartIndex);
220
+ const endIndex = startIndex + lines.slice(startIndex).findIndex(isMessageCodeBlockEndIndex, startIndex);
221
+ const relevantLines = lines.slice(startIndex, endIndex);
222
+ const relevantMessage = relevantLines.join(' ').slice('Error: '.length);
223
+ return relevantMessage;
224
+ };
225
+ const getNativeModuleErrorMessage = stderr => {
226
+ const message = getMessageCodeBlock(stderr);
227
+ return {
228
+ message: `Incompatible native node module: ${message}`,
229
+ code: E_INCOMPATIBLE_NATIVE_MODULE
230
+ };
231
+ };
232
+ const isModulesSyntaxError = stderr => {
233
+ if (!stderr) {
234
+ return false;
233
235
  }
234
- return parentStack;
236
+ return stderr.includes('SyntaxError: Cannot use import statement outside a module');
235
237
  };
236
- const joinLines$1 = lines => {
237
- return lines.join(NewLine$2);
238
+ const getModuleSyntaxError = () => {
239
+ return {
240
+ message: `ES Modules are not supported in electron`,
241
+ code: E_MODULES_NOT_SUPPORTED_IN_ELECTRON
242
+ };
238
243
  };
239
- const MethodNotFound = -32601;
240
- const Custom = -32001;
241
- const splitLines$2 = lines => {
242
- return lines.split(NewLine$2);
244
+ const isModuleNotFoundError = stderr => {
245
+ if (!stderr) {
246
+ return false;
247
+ }
248
+ return stderr.includes('ERR_MODULE_NOT_FOUND');
243
249
  };
244
- const restoreJsonRpcError = error => {
245
- if (error && error instanceof Error) {
246
- return error;
250
+ const isNormalStackLine = line => {
251
+ return RE_AT.test(line) && !RE_AT_PROMISE_INDEX.test(line);
252
+ };
253
+ const getDetails = lines => {
254
+ const index = lines.findIndex(isNormalStackLine);
255
+ if (index === -1) {
256
+ return {
257
+ actualMessage: joinLines$1(lines),
258
+ rest: []
259
+ };
247
260
  }
248
- const currentStack = joinLines$1(splitLines$2(new Error().stack || '').slice(1));
249
- if (error && error.code && error.code === MethodNotFound) {
250
- const restoredError = new JsonRpcError(error.message);
251
- const parentStack = getParentStack(error);
252
- restoredError.stack = parentStack + NewLine$2 + currentStack;
253
- return restoredError;
261
+ let lastIndex = index - 1;
262
+ while (++lastIndex < lines.length) {
263
+ if (!isNormalStackLine(lines[lastIndex])) {
264
+ break;
265
+ }
254
266
  }
255
- if (error && error.message) {
256
- const restoredError = constructError(error.message, error.type, error.name);
257
- if (error.data) {
258
- if (error.data.stack && error.data.type && error.message) {
259
- restoredError.stack = error.data.type + ': ' + error.message + NewLine$2 + error.data.stack + NewLine$2 + currentStack;
260
- } else if (error.data.stack) {
261
- restoredError.stack = error.data.stack;
262
- }
263
- if (error.data.codeFrame) {
264
- // @ts-ignore
265
- restoredError.codeFrame = error.data.codeFrame;
266
- }
267
- if (error.data.code) {
268
- // @ts-ignore
269
- restoredError.code = error.data.code;
270
- }
271
- if (error.data.type) {
272
- // @ts-ignore
273
- restoredError.name = error.data.type;
274
- }
267
+ return {
268
+ actualMessage: lines[index - 1],
269
+ rest: lines.slice(index, lastIndex)
270
+ };
271
+ };
272
+ const getHelpfulChildProcessError = (stdout, stderr) => {
273
+ if (isUnhelpfulNativeModuleError(stderr)) {
274
+ return getNativeModuleErrorMessage(stderr);
275
+ }
276
+ if (isModulesSyntaxError(stderr)) {
277
+ return getModuleSyntaxError();
278
+ }
279
+ if (isModuleNotFoundError(stderr)) {
280
+ return getModuleNotFoundError(stderr);
281
+ }
282
+ const lines = splitLines$1(stderr);
283
+ const {
284
+ actualMessage,
285
+ rest
286
+ } = getDetails(lines);
287
+ return {
288
+ message: `${actualMessage}`,
289
+ code: '',
290
+ stack: rest
291
+ };
292
+ };
293
+ class IpcError extends VError {
294
+ // @ts-ignore
295
+ constructor(betterMessage, stdout = '', stderr = '') {
296
+ if (stdout || stderr) {
297
+ // @ts-ignore
298
+ const {
299
+ message,
300
+ code,
301
+ stack
302
+ } = getHelpfulChildProcessError(stdout, stderr);
303
+ const cause = new Error(message);
304
+ // @ts-ignore
305
+ cause.code = code;
306
+ cause.stack = stack;
307
+ super(cause, betterMessage);
275
308
  } else {
276
- if (error.stack) {
277
- const lowerStack = restoredError.stack || '';
278
- // @ts-ignore
279
- const indexNewLine = getNewLineIndex$1(lowerStack);
280
- const parentStack = getParentStack(error);
281
- // @ts-ignore
282
- restoredError.stack = parentStack + lowerStack.slice(indexNewLine);
283
- }
284
- if (error.codeFrame) {
285
- // @ts-ignore
286
- restoredError.codeFrame = error.codeFrame;
287
- }
309
+ super(betterMessage);
288
310
  }
289
- return restoredError;
311
+ // @ts-ignore
312
+ this.name = 'IpcError';
313
+ // @ts-ignore
314
+ this.stdout = stdout;
315
+ // @ts-ignore
316
+ this.stderr = stderr;
290
317
  }
291
- if (typeof error === 'string') {
292
- return new Error(`JsonRpc Error: ${error}`);
318
+ }
319
+ const readyMessage = 'ready';
320
+ const getData$2 = event => {
321
+ return event.data;
322
+ };
323
+ const listen$7 = () => {
324
+ // @ts-ignore
325
+ if (typeof WorkerGlobalScope === 'undefined') {
326
+ throw new TypeError('module is not in web worker scope');
293
327
  }
294
- return new Error(`JsonRpc Error: ${error}`);
328
+ return globalThis;
295
329
  };
296
- const unwrapJsonRpcResult = responseMessage => {
297
- if ('error' in responseMessage) {
298
- const restoredError = restoreJsonRpcError(responseMessage.error);
299
- throw restoredError;
330
+ const signal$7 = global => {
331
+ global.postMessage(readyMessage);
332
+ };
333
+ class IpcChildWithModuleWorker extends Ipc {
334
+ getData(event) {
335
+ return getData$2(event);
300
336
  }
301
- if ('result' in responseMessage) {
302
- return responseMessage.result;
337
+ send(message) {
338
+ // @ts-ignore
339
+ this._rawIpc.postMessage(message);
303
340
  }
304
- throw new JsonRpcError('unexpected response message');
305
- };
306
- const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
307
- const getErrorType = prettyError => {
308
- if (prettyError && prettyError.type) {
309
- return prettyError.type;
341
+ sendAndTransfer(message) {
342
+ const transfer = getTransferrables(message);
343
+ // @ts-ignore
344
+ this._rawIpc.postMessage(message, transfer);
310
345
  }
311
- if (prettyError && prettyError.constructor && prettyError.constructor.name) {
312
- return prettyError.constructor.name;
346
+ dispose() {
347
+ // ignore
313
348
  }
314
- return undefined;
315
- };
316
- const getErrorProperty = (error, prettyError) => {
317
- if (error && error.code === E_COMMAND_NOT_FOUND) {
318
- return {
319
- code: MethodNotFound,
320
- message: error.message,
321
- data: error.stack
322
- };
349
+ onClose(callback) {
350
+ // ignore
323
351
  }
324
- return {
325
- code: Custom,
326
- message: prettyError.message,
327
- data: {
328
- stack: prettyError.stack,
329
- codeFrame: prettyError.codeFrame,
330
- type: getErrorType(prettyError),
331
- code: prettyError.code,
332
- name: prettyError.name
333
- }
334
- };
352
+ onMessage(callback) {
353
+ this._rawIpc.addEventListener('message', callback);
354
+ }
355
+ }
356
+ const wrap$e = global => {
357
+ return new IpcChildWithModuleWorker(global);
335
358
  };
336
- const create$1$2 = (message, error) => {
359
+ const withResolvers = () => {
360
+ let _resolve;
361
+ const promise = new Promise(resolve => {
362
+ _resolve = resolve;
363
+ });
337
364
  return {
338
- jsonrpc: Two,
339
- id: message.id,
340
- error
365
+ resolve: _resolve,
366
+ promise
341
367
  };
342
368
  };
343
- const getErrorResponse = (message, error, preparePrettyError, logError) => {
344
- const prettyError = preparePrettyError(error);
345
- logError(error, prettyError);
346
- const errorProperty = getErrorProperty(error, prettyError);
347
- return create$1$2(message, errorProperty);
348
- };
349
- const create$6 = (message, result) => {
350
- return {
351
- jsonrpc: Two,
352
- id: message.id,
353
- result: result ?? null
354
- };
369
+ const waitForFirstMessage = async port => {
370
+ const {
371
+ resolve,
372
+ promise
373
+ } = withResolvers();
374
+ port.addEventListener('message', resolve, {
375
+ once: true
376
+ });
377
+ const event = await promise;
378
+ // @ts-ignore
379
+ return event.data;
355
380
  };
356
- const getSuccessResponse = (message, result) => {
357
- const resultProperty = result ?? null;
358
- return create$6(message, resultProperty);
381
+ const listen$6 = async () => {
382
+ const parentIpcRaw = listen$7();
383
+ signal$7(parentIpcRaw);
384
+ const parentIpc = wrap$e(parentIpcRaw);
385
+ const firstMessage = await waitForFirstMessage(parentIpc);
386
+ if (firstMessage.method !== 'initialize') {
387
+ throw new IpcError('unexpected first message');
388
+ }
389
+ const type = firstMessage.params[0];
390
+ if (type === 'message-port') {
391
+ parentIpc.send({
392
+ jsonrpc: '2.0',
393
+ id: firstMessage.id,
394
+ result: null
395
+ });
396
+ parentIpc.dispose();
397
+ const port = firstMessage.params[1];
398
+ return port;
399
+ }
400
+ return globalThis;
359
401
  };
360
- const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
361
- try {
362
- const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
363
- return getSuccessResponse(message, result);
364
- } catch (error) {
365
- return getErrorResponse(message, error, preparePrettyError, logError);
402
+ class IpcChildWithModuleWorkerAndMessagePort extends Ipc {
403
+ constructor(port) {
404
+ super(port);
405
+ }
406
+ getData(event) {
407
+ return getData$2(event);
408
+ }
409
+ send(message) {
410
+ this._rawIpc.postMessage(message);
411
+ }
412
+ sendAndTransfer(message) {
413
+ const transfer = getTransferrables(message);
414
+ this._rawIpc.postMessage(message, transfer);
415
+ }
416
+ dispose() {
417
+ if (this._rawIpc.close) {
418
+ this._rawIpc.close();
419
+ }
366
420
  }
421
+ onClose(callback) {
422
+ // ignore
423
+ }
424
+ onMessage(callback) {
425
+ this._rawIpc.addEventListener('message', callback);
426
+ this._rawIpc.start();
427
+ }
428
+ }
429
+ const wrap$d = port => {
430
+ return new IpcChildWithModuleWorkerAndMessagePort(port);
367
431
  };
368
- const defaultPreparePrettyError = error => {
369
- return error;
432
+ const IpcChildWithModuleWorkerAndMessagePort$1 = {
433
+ __proto__: null,
434
+ listen: listen$6,
435
+ wrap: wrap$d
370
436
  };
371
- const defaultLogError = () => {
372
- // ignore
437
+ const Open = 1;
438
+ const Close = 2;
439
+ const addListener = (emitter, type, callback) => {
440
+ if ('addEventListener' in emitter) {
441
+ emitter.addEventListener(type, callback);
442
+ } else {
443
+ emitter.on(type, callback);
444
+ }
373
445
  };
374
- const defaultRequiresSocket = () => {
375
- return false;
446
+ const removeListener = (emitter, type, callback) => {
447
+ if ('removeEventListener' in emitter) {
448
+ emitter.removeEventListener(type, callback);
449
+ } else {
450
+ emitter.off(type, callback);
451
+ }
376
452
  };
377
- const defaultResolve = resolve;
378
-
379
- // TODO maybe remove this in v6 or v7, only accept options object to simplify the code
380
- const normalizeParams = args => {
381
- if (args.length === 1) {
382
- const options = args[0];
383
- return {
384
- ipc: options.ipc,
385
- message: options.message,
386
- execute: options.execute,
387
- resolve: options.resolve || defaultResolve,
388
- preparePrettyError: options.preparePrettyError || defaultPreparePrettyError,
389
- logError: options.logError || defaultLogError,
390
- requiresSocket: options.requiresSocket || defaultRequiresSocket
391
- };
392
- }
393
- return {
394
- ipc: args[0],
395
- message: args[1],
396
- execute: args[2],
397
- resolve: args[3],
398
- preparePrettyError: args[4],
399
- logError: args[5],
400
- requiresSocket: args[6]
401
- };
402
- };
403
- const handleJsonRpcMessage = async (...args) => {
404
- const options = normalizeParams(args);
453
+ const getFirstEvent = (eventEmitter, eventMap) => {
405
454
  const {
406
- message,
407
- ipc,
408
- execute,
409
455
  resolve,
410
- preparePrettyError,
411
- logError,
412
- requiresSocket
413
- } = options;
414
- if ('id' in message) {
415
- if ('method' in message) {
416
- const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
417
- try {
418
- ipc.send(response);
419
- } catch (error) {
420
- const errorResponse = getErrorResponse(message, error, preparePrettyError, logError);
421
- ipc.send(errorResponse);
422
- }
423
- return;
456
+ promise
457
+ } = withResolvers();
458
+ const listenerMap = Object.create(null);
459
+ const cleanup = value => {
460
+ for (const event of Object.keys(eventMap)) {
461
+ removeListener(eventEmitter, event, listenerMap[event]);
424
462
  }
425
- resolve(message.id, message);
426
- return;
427
- }
428
- if ('method' in message) {
429
- await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
430
- return;
463
+ resolve(value);
464
+ };
465
+ for (const [event, type] of Object.entries(eventMap)) {
466
+ const listener = event => {
467
+ cleanup({
468
+ type,
469
+ event
470
+ });
471
+ };
472
+ addListener(eventEmitter, event, listener);
473
+ listenerMap[event] = listener;
431
474
  }
432
- throw new JsonRpcError('unexpected message');
475
+ return promise;
433
476
  };
434
- const invokeHelper = async (ipc, method, params, useSendAndTransfer) => {
435
- const {
436
- message,
437
- promise
438
- } = create$2$2(method, params);
439
- if (useSendAndTransfer && ipc.sendAndTransfer) {
440
- ipc.sendAndTransfer(message);
441
- } else {
442
- ipc.send(message);
477
+ const Message$1 = 3;
478
+ const create$4$1 = async ({
479
+ messagePort,
480
+ isMessagePortOpen
481
+ }) => {
482
+ if (!isMessagePort(messagePort)) {
483
+ throw new IpcError('port must be of type MessagePort');
443
484
  }
444
- const responseMessage = await promise;
445
- return unwrapJsonRpcResult(responseMessage);
446
- };
447
- const send = (transport, method, ...params) => {
448
- const message = create$4(method, params);
449
- transport.send(message);
450
- };
451
- const invoke$3 = (ipc, method, ...params) => {
452
- return invokeHelper(ipc, method, params, false);
453
- };
454
- const invokeAndTransfer$1 = (ipc, method, ...params) => {
455
- return invokeHelper(ipc, method, params, true);
456
- };
457
-
458
- const commands = Object.create(null);
459
- const register = commandMap => {
460
- Object.assign(commands, commandMap);
461
- };
462
- const getCommand = key => {
463
- return commands[key];
464
- };
465
- const execute = (command, ...args) => {
466
- const fn = getCommand(command);
467
- if (!fn) {
468
- throw new Error(`command not found ${command}`);
485
+ if (isMessagePortOpen) {
486
+ return messagePort;
469
487
  }
470
- return fn(...args);
471
- };
472
-
473
- const getData$1 = event => {
474
- return event.data;
488
+ const eventPromise = getFirstEvent(messagePort, {
489
+ message: Message$1
490
+ });
491
+ messagePort.start();
492
+ const event = await eventPromise;
493
+ // @ts-ignore
494
+ if (event.data !== readyMessage) {
495
+ throw new IpcError('unexpected first message');
496
+ }
497
+ return messagePort;
475
498
  };
476
- const attachEvents = that => {
477
- const handleMessage = (...args) => {
478
- const data = that.getData(...args);
479
- that.dispatchEvent(new MessageEvent('message', {
480
- data
481
- }));
482
- };
483
- that.onMessage(handleMessage);
484
- const handleClose = event => {
485
- that.dispatchEvent(new Event('close'));
486
- };
487
- that.onClose(handleClose);
499
+ const signal = messagePort => {
500
+ messagePort.start();
488
501
  };
489
- class Ipc extends EventTarget {
490
- constructor(rawIpc) {
491
- super();
492
- this._rawIpc = rawIpc;
493
- attachEvents(this);
502
+ class IpcParentWithMessagePort extends Ipc {
503
+ constructor(port) {
504
+ super(port);
494
505
  }
495
- }
496
- const readyMessage = 'ready';
497
- const walkValue = (value, transferrables, isTransferrable) => {
498
- if (!value) {
499
- return;
506
+ getData = getData$2;
507
+ send(message) {
508
+ this._rawIpc.postMessage(message);
500
509
  }
501
- if (isTransferrable(value)) {
502
- transferrables.push(value);
503
- return;
510
+ sendAndTransfer(message) {
511
+ throw new Error('not implemented');
504
512
  }
505
- if (Array.isArray(value)) {
506
- for (const item of value) {
507
- walkValue(item, transferrables, isTransferrable);
508
- }
509
- return;
513
+ dispose() {
514
+ this._rawIpc.close();
510
515
  }
511
- if (typeof value === 'object') {
512
- for (const property of Object.values(value)) {
513
- walkValue(property, transferrables, isTransferrable);
514
- }
515
- return;
516
+ onMessage(callback) {
517
+ this._rawIpc.addEventListener('message', callback);
516
518
  }
519
+ onClose(callback) {}
520
+ }
521
+ const wrap$4 = messagePort => {
522
+ return new IpcParentWithMessagePort(messagePort);
517
523
  };
518
- const isMessagePort = value => {
519
- return value && value instanceof MessagePort;
520
- };
521
- const isMessagePortMain = value => {
522
- return value && value.constructor && value.constructor.name === 'MessagePortMain';
523
- };
524
- const isOffscreenCanvas = value => {
525
- return typeof OffscreenCanvas !== 'undefined' && value instanceof OffscreenCanvas;
526
- };
527
- const isInstanceOf = (value, constructorName) => {
528
- return value?.constructor?.name === constructorName;
524
+ const IpcParentWithMessagePort$1 = {
525
+ __proto__: null,
526
+ create: create$4$1,
527
+ signal,
528
+ wrap: wrap$4
529
529
  };
530
- const isSocket = value => {
531
- return isInstanceOf(value, 'Socket');
530
+ const stringifyCompact = value => {
531
+ return JSON.stringify(value);
532
532
  };
533
- const transferrables = [isMessagePort, isMessagePortMain, isOffscreenCanvas, isSocket];
534
- const isTransferrable = value => {
535
- for (const fn of transferrables) {
536
- if (fn(value)) {
537
- return true;
538
- }
533
+ const parse = content => {
534
+ if (content === 'undefined') {
535
+ return null;
536
+ }
537
+ try {
538
+ return JSON.parse(content);
539
+ } catch (error) {
540
+ throw new VError(error, 'failed to parse json');
539
541
  }
540
- return false;
541
542
  };
542
- const getTransferrables = value => {
543
- const transferrables = [];
544
- walkValue(value, transferrables, isTransferrable);
545
- return transferrables;
543
+ const waitForWebSocketToBeOpen = webSocket => {
544
+ return getFirstEvent(webSocket, {
545
+ open: Open,
546
+ close: Close
547
+ });
546
548
  };
547
- const listen$2 = () => {
549
+ const create$7 = async ({
550
+ webSocket
551
+ }) => {
552
+ const firstWebSocketEvent = await waitForWebSocketToBeOpen(webSocket);
548
553
  // @ts-ignore
549
- if (typeof WorkerGlobalScope === 'undefined') {
550
- throw new TypeError('module is not in web worker scope');
554
+ if (firstWebSocketEvent.type === Close) {
555
+ throw new IpcError('Websocket connection was immediately closed');
551
556
  }
552
- return globalThis;
553
- };
554
- const signal$2 = global => {
555
- global.postMessage(readyMessage);
557
+ return webSocket;
556
558
  };
557
- class IpcChildWithModuleWorker extends Ipc {
559
+ class IpcParentWithWebSocket extends Ipc {
558
560
  getData(event) {
559
- return getData$1(event);
561
+ return parse(event.data);
560
562
  }
561
563
  send(message) {
562
- // @ts-ignore
563
- this._rawIpc.postMessage(message);
564
+ this._rawIpc.send(stringifyCompact(message));
564
565
  }
565
566
  sendAndTransfer(message) {
566
- const transfer = getTransferrables(message);
567
- // @ts-ignore
568
- this._rawIpc.postMessage(message, transfer);
567
+ throw new Error('sendAndTransfer not supported');
569
568
  }
570
569
  dispose() {
571
- // ignore
570
+ this._rawIpc.close();
572
571
  }
573
572
  onClose(callback) {
574
- // ignore
573
+ this._rawIpc.addEventListener('close', callback);
575
574
  }
576
575
  onMessage(callback) {
577
576
  this._rawIpc.addEventListener('message', callback);
578
577
  }
579
578
  }
580
- const wrap$5 = global => {
581
- return new IpcChildWithModuleWorker(global);
579
+ const wrap = webSocket => {
580
+ return new IpcParentWithWebSocket(webSocket);
582
581
  };
583
- const E_INCOMPATIBLE_NATIVE_MODULE = 'E_INCOMPATIBLE_NATIVE_MODULE';
584
- const E_MODULES_NOT_SUPPORTED_IN_ELECTRON = 'E_MODULES_NOT_SUPPORTED_IN_ELECTRON';
585
- const ERR_MODULE_NOT_FOUND = 'ERR_MODULE_NOT_FOUND';
586
- const NewLine$1 = '\n';
587
- const joinLines = lines => {
588
- return lines.join(NewLine$1);
582
+ const IpcParentWithWebSocket$1 = {
583
+ __proto__: null,
584
+ create: create$7,
585
+ wrap
589
586
  };
590
- const splitLines$1 = lines => {
591
- return lines.split(NewLine$1);
587
+
588
+ const Two = '2.0';
589
+ const create$4 = (method, params) => {
590
+ return {
591
+ jsonrpc: Two,
592
+ method,
593
+ params
594
+ };
592
595
  };
593
- const isModuleNotFoundMessage = line => {
594
- return line.includes('[ERR_MODULE_NOT_FOUND]');
595
- };
596
- const getModuleNotFoundError = stderr => {
597
- const lines = splitLines$1(stderr);
598
- const messageIndex = lines.findIndex(isModuleNotFoundMessage);
599
- const message = lines[messageIndex];
600
- return {
601
- message,
602
- code: ERR_MODULE_NOT_FOUND
603
- };
596
+ const callbacks = Object.create(null);
597
+ const set$1 = (id, fn) => {
598
+ callbacks[id] = fn;
604
599
  };
605
- const RE_NATIVE_MODULE_ERROR = /^innerError Error: Cannot find module '.*.node'/;
606
- const RE_NATIVE_MODULE_ERROR_2 = /was compiled against a different Node.js version/;
607
- const RE_MESSAGE_CODE_BLOCK_START = /^Error: The module '.*'$/;
608
- const RE_MESSAGE_CODE_BLOCK_END = /^\s* at/;
609
- const RE_AT = /^\s+at/;
610
- const RE_AT_PROMISE_INDEX = /^\s*at async Promise.all \(index \d+\)$/;
611
- const isUnhelpfulNativeModuleError = stderr => {
612
- return RE_NATIVE_MODULE_ERROR.test(stderr) && RE_NATIVE_MODULE_ERROR_2.test(stderr);
600
+ const get$1 = id => {
601
+ return callbacks[id];
613
602
  };
614
- const isMessageCodeBlockStartIndex = line => {
615
- return RE_MESSAGE_CODE_BLOCK_START.test(line);
603
+ const remove$1 = id => {
604
+ delete callbacks[id];
616
605
  };
617
- const isMessageCodeBlockEndIndex = line => {
618
- return RE_MESSAGE_CODE_BLOCK_END.test(line);
606
+ let id = 0;
607
+ const create$3 = () => {
608
+ return ++id;
619
609
  };
620
- const getMessageCodeBlock = stderr => {
621
- const lines = splitLines$1(stderr);
622
- const startIndex = lines.findIndex(isMessageCodeBlockStartIndex);
623
- const endIndex = startIndex + lines.slice(startIndex).findIndex(isMessageCodeBlockEndIndex, startIndex);
624
- const relevantLines = lines.slice(startIndex, endIndex);
625
- const relevantMessage = relevantLines.join(' ').slice('Error: '.length);
626
- return relevantMessage;
610
+ const warn = (...args) => {
611
+ console.warn(...args);
627
612
  };
628
- const getNativeModuleErrorMessage = stderr => {
629
- const message = getMessageCodeBlock(stderr);
613
+ const registerPromise = () => {
614
+ const id = create$3();
615
+ const {
616
+ resolve,
617
+ promise
618
+ } = Promise.withResolvers();
619
+ set$1(id, resolve);
630
620
  return {
631
- message: `Incompatible native node module: ${message}`,
632
- code: E_INCOMPATIBLE_NATIVE_MODULE
621
+ id,
622
+ promise
633
623
  };
634
624
  };
635
- const isModulesSyntaxError = stderr => {
636
- if (!stderr) {
637
- return false;
625
+ const resolve = (id, response) => {
626
+ const fn = get$1(id);
627
+ if (!fn) {
628
+ console.log(response);
629
+ warn(`callback ${id} may already be disposed`);
630
+ return;
638
631
  }
639
- return stderr.includes('SyntaxError: Cannot use import statement outside a module');
632
+ fn(response);
633
+ remove$1(id);
640
634
  };
641
- const getModuleSyntaxError = () => {
635
+ const create$2$1 = (method, params) => {
636
+ const {
637
+ id,
638
+ promise
639
+ } = registerPromise();
640
+ const message = {
641
+ jsonrpc: Two,
642
+ method,
643
+ params,
644
+ id
645
+ };
642
646
  return {
643
- message: `ES Modules are not supported in electron`,
644
- code: E_MODULES_NOT_SUPPORTED_IN_ELECTRON
647
+ message,
648
+ promise
645
649
  };
646
650
  };
647
- const isModuleNotFoundError = stderr => {
648
- if (!stderr) {
649
- return false;
650
- }
651
- return stderr.includes('ERR_MODULE_NOT_FOUND');
652
- };
653
- const isNormalStackLine = line => {
654
- return RE_AT.test(line) && !RE_AT_PROMISE_INDEX.test(line);
655
- };
656
- const getDetails = lines => {
657
- const index = lines.findIndex(isNormalStackLine);
658
- if (index === -1) {
659
- return {
660
- actualMessage: joinLines(lines),
661
- rest: []
662
- };
651
+ class JsonRpcError extends Error {
652
+ constructor(message) {
653
+ super(message);
654
+ this.name = 'JsonRpcError';
663
655
  }
664
- let lastIndex = index - 1;
665
- while (++lastIndex < lines.length) {
666
- if (!isNormalStackLine(lines[lastIndex])) {
667
- break;
656
+ }
657
+ const NewLine = '\n';
658
+ const DomException = 'DOMException';
659
+ const ReferenceError$1 = 'ReferenceError';
660
+ const SyntaxError$1 = 'SyntaxError';
661
+ const TypeError$1 = 'TypeError';
662
+ const getErrorConstructor = (message, type) => {
663
+ if (type) {
664
+ switch (type) {
665
+ case DomException:
666
+ return DOMException;
667
+ case TypeError$1:
668
+ return TypeError;
669
+ case SyntaxError$1:
670
+ return SyntaxError;
671
+ case ReferenceError$1:
672
+ return ReferenceError;
673
+ default:
674
+ return Error;
668
675
  }
669
676
  }
670
- return {
671
- actualMessage: lines[index - 1],
672
- rest: lines.slice(index, lastIndex)
673
- };
674
- };
675
- const getHelpfulChildProcessError = (stdout, stderr) => {
676
- if (isUnhelpfulNativeModuleError(stderr)) {
677
- return getNativeModuleErrorMessage(stderr);
677
+ if (message.startsWith('TypeError: ')) {
678
+ return TypeError;
678
679
  }
679
- if (isModulesSyntaxError(stderr)) {
680
- return getModuleSyntaxError();
680
+ if (message.startsWith('SyntaxError: ')) {
681
+ return SyntaxError;
681
682
  }
682
- if (isModuleNotFoundError(stderr)) {
683
- return getModuleNotFoundError(stderr);
683
+ if (message.startsWith('ReferenceError: ')) {
684
+ return ReferenceError;
684
685
  }
685
- const lines = splitLines$1(stderr);
686
- const {
687
- actualMessage,
688
- rest
689
- } = getDetails(lines);
690
- return {
691
- message: `${actualMessage}`,
692
- code: '',
693
- stack: rest
694
- };
686
+ return Error;
695
687
  };
696
- const normalizeLine = line => {
697
- if (line.startsWith('Error: ')) {
698
- return line.slice('Error: '.length);
699
- }
700
- if (line.startsWith('VError: ')) {
701
- return line.slice('VError: '.length);
688
+ const constructError = (message, type, name) => {
689
+ const ErrorConstructor = getErrorConstructor(message, type);
690
+ if (ErrorConstructor === DOMException && name) {
691
+ return new ErrorConstructor(message, name);
702
692
  }
703
- return line;
704
- };
705
- const getCombinedMessage = (error, message) => {
706
- const stringifiedError = normalizeLine(`${error}`);
707
- if (message) {
708
- return `${message}: ${stringifiedError}`;
693
+ if (ErrorConstructor === Error) {
694
+ const error = new Error(message);
695
+ if (name && name !== 'VError') {
696
+ error.name = name;
697
+ }
698
+ return error;
709
699
  }
710
- return stringifiedError;
700
+ return new ErrorConstructor(message);
711
701
  };
712
- const NewLine = '\n';
713
702
  const getNewLineIndex = (string, startIndex = undefined) => {
714
703
  return string.indexOf(NewLine, startIndex);
715
704
  };
716
- const mergeStacks = (parent, child) => {
717
- if (!child) {
718
- return parent;
719
- }
720
- const parentNewLineIndex = getNewLineIndex(parent);
721
- const childNewLineIndex = getNewLineIndex(child);
722
- if (childNewLineIndex === -1) {
723
- return parent;
724
- }
725
- const parentFirstLine = parent.slice(0, parentNewLineIndex);
726
- const childRest = child.slice(childNewLineIndex);
727
- const childFirstLine = normalizeLine(child.slice(0, childNewLineIndex));
728
- if (parentFirstLine.includes(childFirstLine)) {
729
- return parentFirstLine + childRest;
705
+ const getParentStack = error => {
706
+ let parentStack = error.stack || error.data || error.message || '';
707
+ if (parentStack.startsWith(' at')) {
708
+ parentStack = error.message + NewLine + parentStack;
730
709
  }
731
- return child;
710
+ return parentStack;
732
711
  };
733
- class VError extends Error {
734
- constructor(error, message) {
735
- const combinedMessage = getCombinedMessage(error, message);
736
- super(combinedMessage);
737
- this.name = 'VError';
738
- if (error instanceof Error) {
739
- this.stack = mergeStacks(this.stack, error.stack);
740
- }
741
- if (error.codeFrame) {
742
- // @ts-ignore
743
- this.codeFrame = error.codeFrame;
744
- }
745
- if (error.code) {
746
- // @ts-ignore
747
- this.code = error.code;
748
- }
712
+ const joinLines = lines => {
713
+ return lines.join(NewLine);
714
+ };
715
+ const MethodNotFound = -32601;
716
+ const Custom = -32001;
717
+ const splitLines = lines => {
718
+ return lines.split(NewLine);
719
+ };
720
+ const restoreJsonRpcError = error => {
721
+ if (error && error instanceof Error) {
722
+ return error;
749
723
  }
750
- }
751
- class IpcError extends VError {
752
- // @ts-ignore
753
- constructor(betterMessage, stdout = '', stderr = '') {
754
- if (stdout || stderr) {
755
- // @ts-ignore
756
- const {
757
- message,
758
- code,
759
- stack
760
- } = getHelpfulChildProcessError(stdout, stderr);
761
- const cause = new Error(message);
762
- // @ts-ignore
763
- cause.code = code;
764
- cause.stack = stack;
765
- super(cause, betterMessage);
724
+ const currentStack = joinLines(splitLines(new Error().stack || '').slice(1));
725
+ if (error && error.code && error.code === MethodNotFound) {
726
+ const restoredError = new JsonRpcError(error.message);
727
+ const parentStack = getParentStack(error);
728
+ restoredError.stack = parentStack + NewLine + currentStack;
729
+ return restoredError;
730
+ }
731
+ if (error && error.message) {
732
+ const restoredError = constructError(error.message, error.type, error.name);
733
+ if (error.data) {
734
+ if (error.data.stack && error.data.type && error.message) {
735
+ restoredError.stack = error.data.type + ': ' + error.message + NewLine + error.data.stack + NewLine + currentStack;
736
+ } else if (error.data.stack) {
737
+ restoredError.stack = error.data.stack;
738
+ }
739
+ if (error.data.codeFrame) {
740
+ // @ts-ignore
741
+ restoredError.codeFrame = error.data.codeFrame;
742
+ }
743
+ if (error.data.code) {
744
+ // @ts-ignore
745
+ restoredError.code = error.data.code;
746
+ }
747
+ if (error.data.type) {
748
+ // @ts-ignore
749
+ restoredError.name = error.data.type;
750
+ }
766
751
  } else {
767
- super(betterMessage);
752
+ if (error.stack) {
753
+ const lowerStack = restoredError.stack || '';
754
+ // @ts-ignore
755
+ const indexNewLine = getNewLineIndex(lowerStack);
756
+ const parentStack = getParentStack(error);
757
+ // @ts-ignore
758
+ restoredError.stack = parentStack + lowerStack.slice(indexNewLine);
759
+ }
760
+ if (error.codeFrame) {
761
+ // @ts-ignore
762
+ restoredError.codeFrame = error.codeFrame;
763
+ }
768
764
  }
769
- // @ts-ignore
770
- this.name = 'IpcError';
771
- // @ts-ignore
772
- this.stdout = stdout;
773
- // @ts-ignore
774
- this.stderr = stderr;
765
+ return restoredError;
775
766
  }
776
- }
777
- const withResolvers = () => {
778
- let _resolve;
779
- const promise = new Promise(resolve => {
780
- _resolve = resolve;
781
- });
782
- return {
783
- resolve: _resolve,
784
- promise
785
- };
786
- };
787
- const waitForFirstMessage = async port => {
788
- const {
789
- resolve,
790
- promise
791
- } = withResolvers();
792
- port.addEventListener('message', resolve, {
793
- once: true
794
- });
795
- const event = await promise;
796
- // @ts-ignore
797
- return event.data;
767
+ if (typeof error === 'string') {
768
+ return new Error(`JsonRpc Error: ${error}`);
769
+ }
770
+ return new Error(`JsonRpc Error: ${error}`);
798
771
  };
799
- const listen$1$1 = async () => {
800
- const parentIpcRaw = listen$2();
801
- signal$2(parentIpcRaw);
802
- const parentIpc = wrap$5(parentIpcRaw);
803
- const firstMessage = await waitForFirstMessage(parentIpc);
804
- if (firstMessage.method !== 'initialize') {
805
- throw new IpcError('unexpected first message');
772
+ const unwrapJsonRpcResult = responseMessage => {
773
+ if ('error' in responseMessage) {
774
+ const restoredError = restoreJsonRpcError(responseMessage.error);
775
+ throw restoredError;
806
776
  }
807
- const type = firstMessage.params[0];
808
- if (type === 'message-port') {
809
- parentIpc.send({
810
- jsonrpc: '2.0',
811
- id: firstMessage.id,
812
- result: null
813
- });
814
- parentIpc.dispose();
815
- const port = firstMessage.params[1];
816
- return port;
777
+ if ('result' in responseMessage) {
778
+ return responseMessage.result;
817
779
  }
818
- return globalThis;
780
+ throw new JsonRpcError('unexpected response message');
819
781
  };
820
- class IpcChildWithModuleWorkerAndMessagePort extends Ipc {
821
- constructor(port) {
822
- super(port);
823
- }
824
- getData(event) {
825
- return getData$1(event);
782
+ const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
783
+ const getErrorType = prettyError => {
784
+ if (prettyError && prettyError.type) {
785
+ return prettyError.type;
826
786
  }
827
- send(message) {
828
- this._rawIpc.postMessage(message);
787
+ if (prettyError && prettyError.constructor && prettyError.constructor.name) {
788
+ return prettyError.constructor.name;
829
789
  }
830
- sendAndTransfer(message) {
831
- const transfer = getTransferrables(message);
832
- this._rawIpc.postMessage(message, transfer);
790
+ return undefined;
791
+ };
792
+ const getErrorProperty = (error, prettyError) => {
793
+ if (error && error.code === E_COMMAND_NOT_FOUND) {
794
+ return {
795
+ code: MethodNotFound,
796
+ message: error.message,
797
+ data: error.stack
798
+ };
833
799
  }
834
- dispose() {
835
- if (this._rawIpc.close) {
836
- this._rawIpc.close();
800
+ return {
801
+ code: Custom,
802
+ message: prettyError.message,
803
+ data: {
804
+ stack: prettyError.stack,
805
+ codeFrame: prettyError.codeFrame,
806
+ type: getErrorType(prettyError),
807
+ code: prettyError.code,
808
+ name: prettyError.name
837
809
  }
838
- }
839
- onClose(callback) {
840
- // ignore
841
- }
842
- onMessage(callback) {
843
- this._rawIpc.addEventListener('message', callback);
844
- this._rawIpc.start();
845
- }
846
- }
847
- const wrap$4 = port => {
848
- return new IpcChildWithModuleWorkerAndMessagePort(port);
849
- };
850
- const IpcChildWithModuleWorkerAndMessagePort$1 = {
851
- __proto__: null,
852
- listen: listen$1$1,
853
- wrap: wrap$4
810
+ };
854
811
  };
855
- const Message$1 = 3;
856
- const addListener = (emitter, type, callback) => {
857
- if ('addEventListener' in emitter) {
858
- emitter.addEventListener(type, callback);
859
- } else {
860
- emitter.on(type, callback);
861
- }
812
+ const create$1$2 = (message, error) => {
813
+ return {
814
+ jsonrpc: Two,
815
+ id: message.id,
816
+ error
817
+ };
862
818
  };
863
- const removeListener = (emitter, type, callback) => {
864
- if ('removeEventListener' in emitter) {
865
- emitter.removeEventListener(type, callback);
866
- } else {
867
- emitter.off(type, callback);
868
- }
819
+ const getErrorResponse = (message, error, preparePrettyError, logError) => {
820
+ const prettyError = preparePrettyError(error);
821
+ logError(error, prettyError);
822
+ const errorProperty = getErrorProperty(error, prettyError);
823
+ return create$1$2(message, errorProperty);
869
824
  };
870
- const getFirstEvent = (eventEmitter, eventMap) => {
871
- const {
872
- resolve,
873
- promise
874
- } = withResolvers();
875
- const listenerMap = Object.create(null);
876
- const cleanup = value => {
877
- for (const event of Object.keys(eventMap)) {
878
- removeListener(eventEmitter, event, listenerMap[event]);
879
- }
880
- resolve(value);
825
+ const create$6 = (message, result) => {
826
+ return {
827
+ jsonrpc: Two,
828
+ id: message.id,
829
+ result: result ?? null
881
830
  };
882
- for (const [event, type] of Object.entries(eventMap)) {
883
- const listener = event => {
884
- cleanup({
885
- type,
886
- event
887
- });
888
- };
889
- addListener(eventEmitter, event, listener);
890
- listenerMap[event] = listener;
891
- }
892
- return promise;
893
831
  };
894
- const create$2$1 = async ({
895
- messagePort,
896
- isMessagePortOpen
897
- }) => {
898
- if (!isMessagePort(messagePort)) {
899
- throw new IpcError('port must be of type MessagePort');
900
- }
901
- if (isMessagePortOpen) {
902
- return messagePort;
903
- }
904
- const eventPromise = getFirstEvent(messagePort, {
905
- message: Message$1
906
- });
907
- messagePort.start();
908
- const event = await eventPromise;
909
- // @ts-ignore
910
- if (event.data !== readyMessage) {
911
- throw new IpcError('unexpected first message');
832
+ const getSuccessResponse = (message, result) => {
833
+ const resultProperty = result ?? null;
834
+ return create$6(message, resultProperty);
835
+ };
836
+ const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
837
+ try {
838
+ const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
839
+ return getSuccessResponse(message, result);
840
+ } catch (error) {
841
+ return getErrorResponse(message, error, preparePrettyError, logError);
912
842
  }
913
- return messagePort;
914
843
  };
915
- const signal = messagePort => {
916
- messagePort.start();
844
+ const defaultPreparePrettyError = error => {
845
+ return error;
917
846
  };
918
- class IpcParentWithMessagePort extends Ipc {
919
- constructor(port) {
920
- super(port);
921
- }
922
- getData = getData$1;
923
- send(message) {
924
- this._rawIpc.postMessage(message);
847
+ const defaultLogError = () => {
848
+ // ignore
849
+ };
850
+ const defaultRequiresSocket = () => {
851
+ return false;
852
+ };
853
+ const defaultResolve = resolve;
854
+
855
+ // TODO maybe remove this in v6 or v7, only accept options object to simplify the code
856
+ const normalizeParams = args => {
857
+ if (args.length === 1) {
858
+ const options = args[0];
859
+ return {
860
+ ipc: options.ipc,
861
+ message: options.message,
862
+ execute: options.execute,
863
+ resolve: options.resolve || defaultResolve,
864
+ preparePrettyError: options.preparePrettyError || defaultPreparePrettyError,
865
+ logError: options.logError || defaultLogError,
866
+ requiresSocket: options.requiresSocket || defaultRequiresSocket
867
+ };
925
868
  }
926
- sendAndTransfer(message) {
927
- throw new Error('not implemented');
869
+ return {
870
+ ipc: args[0],
871
+ message: args[1],
872
+ execute: args[2],
873
+ resolve: args[3],
874
+ preparePrettyError: args[4],
875
+ logError: args[5],
876
+ requiresSocket: args[6]
877
+ };
878
+ };
879
+ const handleJsonRpcMessage = async (...args) => {
880
+ const options = normalizeParams(args);
881
+ const {
882
+ message,
883
+ ipc,
884
+ execute,
885
+ resolve,
886
+ preparePrettyError,
887
+ logError,
888
+ requiresSocket
889
+ } = options;
890
+ if ('id' in message) {
891
+ if ('method' in message) {
892
+ const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
893
+ try {
894
+ ipc.send(response);
895
+ } catch (error) {
896
+ const errorResponse = getErrorResponse(message, error, preparePrettyError, logError);
897
+ ipc.send(errorResponse);
898
+ }
899
+ return;
900
+ }
901
+ resolve(message.id, message);
902
+ return;
928
903
  }
929
- dispose() {
930
- this._rawIpc.close();
904
+ if ('method' in message) {
905
+ await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
906
+ return;
931
907
  }
932
- onMessage(callback) {
933
- this._rawIpc.addEventListener('message', callback);
908
+ throw new JsonRpcError('unexpected message');
909
+ };
910
+ const invokeHelper = async (ipc, method, params, useSendAndTransfer) => {
911
+ const {
912
+ message,
913
+ promise
914
+ } = create$2$1(method, params);
915
+ if (useSendAndTransfer && ipc.sendAndTransfer) {
916
+ ipc.sendAndTransfer(message);
917
+ } else {
918
+ ipc.send(message);
934
919
  }
935
- onClose(callback) {}
936
- }
937
- const wrap$2 = messagePort => {
938
- return new IpcParentWithMessagePort(messagePort);
920
+ const responseMessage = await promise;
921
+ return unwrapJsonRpcResult(responseMessage);
939
922
  };
940
- const IpcParentWithMessagePort$1 = {
941
- __proto__: null,
942
- create: create$2$1,
943
- signal,
944
- wrap: wrap$2
923
+ const send = (transport, method, ...params) => {
924
+ const message = create$4(method, params);
925
+ transport.send(message);
945
926
  };
946
- const Open = 1;
947
- const Close = 2;
948
- const stringifyCompact = value => {
949
- return JSON.stringify(value);
927
+ const invoke$3 = (ipc, method, ...params) => {
928
+ return invokeHelper(ipc, method, params, false);
950
929
  };
951
- const parse = content => {
952
- if (content === 'undefined') {
953
- return null;
954
- }
955
- try {
956
- return JSON.parse(content);
957
- } catch (error) {
958
- throw new VError(error, 'failed to parse json');
959
- }
930
+ const invokeAndTransfer$1 = (ipc, method, ...params) => {
931
+ return invokeHelper(ipc, method, params, true);
960
932
  };
961
- const waitForWebSocketToBeOpen = webSocket => {
962
- return getFirstEvent(webSocket, {
963
- open: Open,
964
- close: Close
965
- });
933
+
934
+ const commands = Object.create(null);
935
+ const register = commandMap => {
936
+ Object.assign(commands, commandMap);
966
937
  };
967
- const create$3 = async ({
968
- webSocket
969
- }) => {
970
- const firstWebSocketEvent = await waitForWebSocketToBeOpen(webSocket);
971
- // @ts-ignore
972
- if (firstWebSocketEvent.type === Close) {
973
- throw new IpcError('Websocket connection was immediately closed');
974
- }
975
- return webSocket;
938
+ const getCommand = key => {
939
+ return commands[key];
976
940
  };
977
- class IpcParentWithWebSocket extends Ipc {
978
- getData(event) {
979
- return parse(event.data);
980
- }
981
- send(message) {
982
- this._rawIpc.send(stringifyCompact(message));
983
- }
984
- sendAndTransfer(message) {
985
- throw new Error('sendAndTransfer not supported');
986
- }
987
- dispose() {
988
- this._rawIpc.close();
989
- }
990
- onClose(callback) {
991
- this._rawIpc.addEventListener('close', callback);
992
- }
993
- onMessage(callback) {
994
- this._rawIpc.addEventListener('message', callback);
941
+ const execute = (command, ...args) => {
942
+ const fn = getCommand(command);
943
+ if (!fn) {
944
+ throw new Error(`command not found ${command}`);
995
945
  }
996
- }
997
- const wrap$1 = webSocket => {
998
- return new IpcParentWithWebSocket(webSocket);
999
- };
1000
- const IpcParentWithWebSocket$1 = {
1001
- __proto__: null,
1002
- create: create$3,
1003
- wrap: wrap$1
946
+ return fn(...args);
1004
947
  };
1005
948
 
1006
949
  const createRpc = ipc => {
@@ -1030,7 +973,8 @@ const logError = () => {
1030
973
  // handled by renderer worker
1031
974
  };
1032
975
  const handleMessage = event => {
1033
- return handleJsonRpcMessage(event.target, event.data, execute, resolve, preparePrettyError, logError, requiresSocket);
976
+ const actualRequiresSocket = event?.target?.requiresSocket || requiresSocket;
977
+ return handleJsonRpcMessage(event.target, event.data, execute, resolve, preparePrettyError, logError, actualRequiresSocket);
1034
978
  };
1035
979
  const handleIpc = ipc => {
1036
980
  if ('addEventListener' in ipc) {
@@ -1134,21 +1078,21 @@ const clearSearchResults$1 = state => {
1134
1078
  };
1135
1079
  };
1136
1080
 
1137
- const state$3 = {
1081
+ const state$2 = {
1138
1082
  rpc: undefined
1139
1083
  };
1140
1084
  const invoke$2 = (method, ...params) => {
1141
- const rpc = state$3.rpc;
1085
+ const rpc = state$2.rpc;
1142
1086
  // @ts-ignore
1143
1087
  return rpc.invoke(method, ...params);
1144
1088
  };
1145
1089
  const invokeAndTransfer = (method, ...params) => {
1146
- const rpc = state$3.rpc;
1090
+ const rpc = state$2.rpc;
1147
1091
  // @ts-ignore
1148
1092
  return rpc.invokeAndTransfer(method, ...params);
1149
1093
  };
1150
1094
  const setRpc = rpc => {
1151
- state$3.rpc = rpc;
1095
+ state$2.rpc = rpc;
1152
1096
  };
1153
1097
 
1154
1098
  const copy = async state => {
@@ -1273,13 +1217,6 @@ const lastIndex = array => {
1273
1217
  const remove = (array, index, deleteCount) => {
1274
1218
  return array.toSpliced(index, deleteCount);
1275
1219
  };
1276
- const fromAsync = async asyncIterable => {
1277
- const children = [];
1278
- for await (const value of asyncIterable) {
1279
- children.push(value);
1280
- }
1281
- return children;
1282
- };
1283
1220
 
1284
1221
  const emptyObject = {};
1285
1222
  const RE_PLACEHOLDER = /\{(PH\d+)\}/g;
@@ -1293,143 +1230,133 @@ const i18nString = (key, placeholders = emptyObject) => {
1293
1230
  return key.replaceAll(RE_PLACEHOLDER, replacer);
1294
1231
  };
1295
1232
 
1296
- /**
1297
- * @enum {string}
1298
- */
1299
- const UiStrings = {
1300
- ClearSearchResults: 'Clear Search Results',
1301
- CollapseAll: 'Collapse All',
1302
- ConfirmReplaceAll: 'Replace All?',
1303
- ConfirmReplaceManyOccurrencesInManyFiles: "Replace {PH1} occurrences across {PH2} files with '{PH3}'",
1304
- ConfirmReplaceManyOccurrencesInManyFilesNoValue: 'Replace {PH1} occurrences across {PH2} files',
1305
- ConfirmReplaceManyOccurrencesInOneFile: "Replace {PH1} occurrences across 1 file with '{PH2}'",
1306
- ConfirmReplaceManyOccurrencesInOneFileNoValue: 'Replace {PH1} occurrences across 1 file',
1307
- ConfirmReplaceOneOccurrenceInOneFile: "Replace 1 occurrence across 1 file with '{PH1}'",
1308
- ConfirmReplaceOneOccurrenceInOneFileNoValue: 'Replace 1 occurrence across 1 file',
1309
- CopyPath: 'Copy Path',
1310
- Dismiss: 'Dismiss',
1311
- ManyResultsInManyFiles: '{PH1} results in {PH2} files',
1312
- ManyResultsInOneFile: '{PH1} results in 1 file',
1313
- MatchCase: 'Match Case',
1314
- MatchWholeWord: 'Match Whole Word',
1315
- NoResults: 'No results found',
1316
- Oneresult: '1 result in 1 file',
1317
- OpenNewSearchEditor: 'Open New Search Editor',
1318
- PreserveCase: 'Preserve Case',
1319
- Refresh: 'Refresh',
1320
- Replace: 'Replace',
1321
- ReplaceAll: 'Replace All',
1322
- ReplacedManyOccurrencesInManyFiles: "Replaced {PH1} occurrences across {PH2} files with '{PH3}'",
1323
- ReplacedManyOccurrencesInOneFile: "Replaced {PH1} occurrences across 1 file with '{PH2}'",
1324
- ReplacedOneOccurrenceInOneFile: "Replaced 1 occurrence across 1 file with '{PH1}'",
1325
- ToggleReplace: 'Toggle Replace',
1326
- UseRegularExpression: 'Use Regular Expression',
1327
- ViewAsTree: 'View as Tree',
1328
- FilesToInclude: 'Files to Include',
1329
- FilesToExclude: 'Files to Exclude',
1330
- ToggleSearchDetails: 'Toggle Search Details',
1331
- SearchOnlyOpenEditors: 'Search Only Open Editors',
1332
- UseExcludeSettings: 'Use Exclude Settings'
1333
- };
1233
+ const ClearSearchResults = 'Clear Search Results';
1234
+ const CollapseAll$1 = 'Collapse All';
1235
+ const ConfirmReplaceManyOccurrencesInManyFiles = "Replace {PH1} occurrences across {PH2} files with '{PH3}'";
1236
+ const ConfirmReplaceManyOccurrencesInManyFilesNoValue = 'Replace {PH1} occurrences across {PH2} files';
1237
+ const ConfirmReplaceManyOccurrencesInOneFile = "Replace {PH1} occurrences across 1 file with '{PH2}'";
1238
+ const ConfirmReplaceManyOccurrencesInOneFileNoValue = 'Replace {PH1} occurrences across 1 file';
1239
+ const ConfirmReplaceOneOccurrenceInOneFile = "Replace 1 occurrence across 1 file with '{PH1}'";
1240
+ const ConfirmReplaceOneOccurrenceInOneFileNoValue = 'Replace 1 occurrence across 1 file';
1241
+ const ManyResultsInManyFiles = '{PH1} results in {PH2} files';
1242
+ const ManyResultsInOneFile = '{PH1} results in 1 file';
1243
+ const MatchCase$2 = 'Match Case';
1244
+ const MatchWholeWord$2 = 'Match Whole Word';
1245
+ const NoResults = 'No results found';
1246
+ const Oneresult = '1 result in 1 file';
1247
+ const OpenNewSearchEditor = 'Open New Search Editor';
1248
+ const PreserveCase$2 = 'Preserve Case';
1249
+ const Refresh$1 = 'Refresh';
1250
+ const Replace = 'Replace';
1251
+ const ReplaceAll$1 = 'Replace All';
1252
+ const ToggleReplace$1 = 'Toggle Replace';
1253
+ const UseRegularExpression$2 = 'Use Regular Expression';
1254
+ const ViewAsTree = 'View as Tree';
1255
+ const FilesToInclude$1 = 'Files to Include';
1256
+ const FilesToExclude$1 = 'Files to Exclude';
1257
+ const ToggleSearchDetails$1 = 'Toggle Search Details';
1258
+ const SearchOnlyOpenEditors$1 = 'Search Only Open Editors';
1259
+ const UseExcludeSettings$1 = 'Use Exclude Settings';
1260
+
1334
1261
  const noResults = () => {
1335
- return i18nString(UiStrings.NoResults);
1262
+ return i18nString(NoResults);
1336
1263
  };
1337
1264
  const oneResult = () => {
1338
- return i18nString(UiStrings.Oneresult);
1265
+ return i18nString(Oneresult);
1339
1266
  };
1340
1267
  const toggleReplace$1 = () => {
1341
- return i18nString(UiStrings.ToggleReplace);
1268
+ return i18nString(ToggleReplace$1);
1342
1269
  };
1343
1270
  const matchCase = () => {
1344
- return i18nString(UiStrings.MatchCase);
1271
+ return i18nString(MatchCase$2);
1345
1272
  };
1346
1273
  const preserveCase = () => {
1347
- return i18nString(UiStrings.PreserveCase);
1274
+ return i18nString(PreserveCase$2);
1348
1275
  };
1349
1276
  const matchWholeWord = () => {
1350
- return i18nString(UiStrings.MatchWholeWord);
1277
+ return i18nString(MatchWholeWord$2);
1351
1278
  };
1352
1279
  const toggleSearchDetails = () => {
1353
- return i18nString(UiStrings.ToggleSearchDetails);
1280
+ return i18nString(ToggleSearchDetails$1);
1354
1281
  };
1355
1282
  const useRegularExpression = () => {
1356
- return i18nString(UiStrings.UseRegularExpression);
1283
+ return i18nString(UseRegularExpression$2);
1357
1284
  };
1358
1285
  const manyResultsInOneFile = resultCount => {
1359
- return i18nString(UiStrings.ManyResultsInOneFile, {
1286
+ return i18nString(ManyResultsInOneFile, {
1360
1287
  PH1: resultCount
1361
1288
  });
1362
1289
  };
1363
1290
  const manyResultsInManyFiles = (resultCount, fileResultCount) => {
1364
- return i18nString(UiStrings.ManyResultsInManyFiles, {
1291
+ return i18nString(ManyResultsInManyFiles, {
1365
1292
  PH1: resultCount,
1366
1293
  PH2: fileResultCount
1367
1294
  });
1368
1295
  };
1369
1296
  const confirmReplaceOneOccurrenceInOneFile = replacement => {
1370
- return i18nString(UiStrings.ConfirmReplaceOneOccurrenceInOneFile, {
1297
+ return i18nString(ConfirmReplaceOneOccurrenceInOneFile, {
1371
1298
  PH1: replacement
1372
1299
  });
1373
1300
  };
1374
1301
  const confirmReplaceOneOccurrenceInOneFileNoValue = () => {
1375
- return i18nString(UiStrings.ConfirmReplaceOneOccurrenceInOneFileNoValue);
1302
+ return i18nString(ConfirmReplaceOneOccurrenceInOneFileNoValue);
1376
1303
  };
1377
1304
  const confirmReplaceManyOccurrencesInOneFile = (matchCount, replacement) => {
1378
- return i18nString(UiStrings.ConfirmReplaceManyOccurrencesInOneFile, {
1305
+ return i18nString(ConfirmReplaceManyOccurrencesInOneFile, {
1379
1306
  PH1: matchCount,
1380
1307
  PH2: replacement
1381
1308
  });
1382
1309
  };
1383
1310
  const confirmReplaceManyOccurrencesInOneFileNoValue = matchCount => {
1384
- return i18nString(UiStrings.ConfirmReplaceManyOccurrencesInOneFileNoValue, {
1311
+ return i18nString(ConfirmReplaceManyOccurrencesInOneFileNoValue, {
1385
1312
  PH1: matchCount
1386
1313
  });
1387
1314
  };
1388
1315
  const confirmReplaceManyOccurrencesInManyFiles = (matchCount, fileCount, replacement) => {
1389
- return i18nString(UiStrings.ConfirmReplaceManyOccurrencesInManyFiles, {
1316
+ return i18nString(ConfirmReplaceManyOccurrencesInManyFiles, {
1390
1317
  PH1: matchCount,
1391
1318
  PH2: fileCount,
1392
1319
  PH3: replacement
1393
1320
  });
1394
1321
  };
1395
1322
  const confirmReplaceManyOccurrencesInManyFilesNoValue = (matchCount, fileCount) => {
1396
- return i18nString(UiStrings.ConfirmReplaceManyOccurrencesInManyFilesNoValue, {
1323
+ return i18nString(ConfirmReplaceManyOccurrencesInManyFilesNoValue, {
1397
1324
  PH1: matchCount,
1398
1325
  PH2: fileCount
1399
1326
  });
1400
1327
  };
1401
1328
  const replaceAll$1 = () => {
1402
- return i18nString(UiStrings.ReplaceAll);
1329
+ return i18nString(ReplaceAll$1);
1403
1330
  };
1404
1331
  const replace = () => {
1405
- return i18nString(UiStrings.Replace);
1332
+ return i18nString(Replace);
1406
1333
  };
1407
1334
  const refresh$1 = () => {
1408
- return i18nString(UiStrings.Refresh);
1335
+ return i18nString(Refresh$1);
1409
1336
  };
1410
1337
  const clearSearchResults = () => {
1411
- return i18nString(UiStrings.ClearSearchResults);
1338
+ return i18nString(ClearSearchResults);
1412
1339
  };
1413
1340
  const openNewSearchEditor = () => {
1414
- return i18nString(UiStrings.OpenNewSearchEditor);
1341
+ return i18nString(OpenNewSearchEditor);
1415
1342
  };
1416
1343
  const viewAsTree = () => {
1417
- return i18nString(UiStrings.ViewAsTree);
1344
+ return i18nString(ViewAsTree);
1418
1345
  };
1419
1346
  const collapseAll = () => {
1420
- return i18nString(UiStrings.CollapseAll);
1347
+ return i18nString(CollapseAll$1);
1421
1348
  };
1422
1349
  const filesToInclude = () => {
1423
- return i18nString(UiStrings.FilesToInclude);
1350
+ return i18nString(FilesToInclude$1);
1424
1351
  };
1425
1352
  const filesToExclude = () => {
1426
- return i18nString(UiStrings.FilesToExclude);
1353
+ return i18nString(FilesToExclude$1);
1427
1354
  };
1428
1355
  const searchOnlyOpenEditors = () => {
1429
- return i18nString(UiStrings.SearchOnlyOpenEditors);
1356
+ return i18nString(SearchOnlyOpenEditors$1);
1430
1357
  };
1431
1358
  const useExcludeSettings = () => {
1432
- return i18nString(UiStrings.UseExcludeSettings);
1359
+ return i18nString(UseExcludeSettings$1);
1433
1360
  };
1434
1361
 
1435
1362
  const getStatusMessage = (resultCount, fileResultCount) => {
@@ -1445,13 +1372,13 @@ const getStatusMessage = (resultCount, fileResultCount) => {
1445
1372
  return manyResultsInManyFiles(resultCount, fileResultCount);
1446
1373
  };
1447
1374
 
1448
- const File$1 = 1;
1375
+ const File = 1;
1449
1376
  const Match = 2;
1450
1377
 
1451
1378
  const getSetSize = (items, index) => {
1452
1379
  let setSize = 0;
1453
1380
  for (let i = index + 1; i < items.length; i++) {
1454
- if (items[i].type === File$1) {
1381
+ if (items[i].type === File) {
1455
1382
  break;
1456
1383
  }
1457
1384
  setSize++;
@@ -1470,7 +1397,7 @@ const getRemoveIndicesFile = (items, item, index, matchCount, fileCount) => {
1470
1397
  };
1471
1398
  const getRemoveIndicesMatch = (items, index, matchCount, fileCount) => {
1472
1399
  for (let i = index; i >= 0; i--) {
1473
- if (items[i].type === File$1) {
1400
+ if (items[i].type === File) {
1474
1401
  const setSize = getSetSize(items, i);
1475
1402
  if (setSize === 1) {
1476
1403
  return {
@@ -1495,7 +1422,7 @@ const getRemoveIndicesMatch = (items, index, matchCount, fileCount) => {
1495
1422
  const getRemoveIndices = (items, index, matchCount, fileCount) => {
1496
1423
  const item = items[index];
1497
1424
  switch (item.type) {
1498
- case File$1:
1425
+ case File:
1499
1426
  return getRemoveIndicesFile(items, item, index, matchCount, fileCount);
1500
1427
  case Match:
1501
1428
  return getRemoveIndicesMatch(items, index, matchCount, fileCount);
@@ -1971,13 +1898,13 @@ const getDisplayResult = (result, fileIcons, fileIconIndex, itemHeight, i, setSi
1971
1898
  const top = i * itemHeight;
1972
1899
  const focused = i === focusedIndex;
1973
1900
  switch (type) {
1974
- case File$1:
1901
+ case File:
1975
1902
  const path = text;
1976
1903
  const absolutePath = getAbsolutePath(path);
1977
1904
  const baseName = pathBaseName(path);
1978
1905
  return {
1979
1906
  title: absolutePath,
1980
- type: File$1,
1907
+ type: File,
1981
1908
  text: baseName,
1982
1909
  icon: fileIcons[fileIconIndex],
1983
1910
  posInSet,
@@ -2025,7 +1952,7 @@ const getDisplayResults = (results, itemHeight, resultCount, searchTerm, minLine
2025
1952
  const result = results[i];
2026
1953
  const displayResult = getDisplayResult(result, fileIcons, fileIconIndex, itemHeight, i, setSize, searchTermLength, replacement, focusedIndex);
2027
1954
  displayResults.push(displayResult);
2028
- if (result.type === File$1) {
1955
+ if (result.type === File) {
2029
1956
  fileResult = displayResult;
2030
1957
  fileIconIndex++;
2031
1958
  } else {
@@ -2381,13 +2308,13 @@ const getSearchResultVirtualDom = rowInfo => {
2381
2308
  treeItem.className += ' ' + TreeItemActive;
2382
2309
  }
2383
2310
  switch (type) {
2384
- case File$1:
2311
+ case File:
2385
2312
  treeItem.ariaExpanded = 'true';
2386
2313
  break;
2387
2314
  }
2388
2315
  const dom = [];
2389
2316
  dom.push(treeItem);
2390
- if (type === File$1) {
2317
+ if (type === File) {
2391
2318
  treeItem.childCount += 2;
2392
2319
  dom.push(chevronDownVirtualDom, getFileIconVirtualDom(icon));
2393
2320
  }
@@ -2434,17 +2361,22 @@ const handleError = error => {
2434
2361
  console.error(`[text-search-worker] ${error}`);
2435
2362
  };
2436
2363
 
2437
- const getFileIcons = async files => {
2364
+ const isFile = match => {
2365
+ return match.type === File;
2366
+ };
2367
+ const getFiles = matches => {
2368
+ return matches.filter(isFile);
2369
+ };
2370
+
2371
+ const getFileIcon = file => {
2372
+ return invoke$2('IconTheme.getFileIcon', {
2373
+ name: file.text
2374
+ });
2375
+ };
2376
+ const getFileIcons = async matches => {
2438
2377
  // TODO cache file icons
2439
- const promises = [];
2440
- for (const file of files) {
2441
- if (file.type === Match) {
2442
- continue;
2443
- }
2444
- promises.push(invoke$2('IconTheme.getFileIcon', {
2445
- name: file.text
2446
- }));
2447
- }
2378
+ const files = getFiles(matches);
2379
+ const promises = files.map(getFileIcon);
2448
2380
  const icons = await Promise.all(promises);
2449
2381
  return icons;
2450
2382
  };
@@ -2461,7 +2393,7 @@ const getTextSearchResultCounts = results => {
2461
2393
  let fileCount = 0;
2462
2394
  for (const result of results) {
2463
2395
  switch (result.type) {
2464
- case File$1:
2396
+ case File:
2465
2397
  fileCount++;
2466
2398
  break;
2467
2399
  case Match:
@@ -2531,473 +2463,12 @@ const textSearch$5 = async (scheme, root, query) => {
2531
2463
  return result;
2532
2464
  };
2533
2465
 
2534
- const getJson = async url => {
2535
- try {
2536
- const response = await fetch(url);
2537
- if (!response.ok) {
2538
- throw new Error(response.statusText);
2539
- }
2540
- const json = await response.json();
2541
- return json;
2542
- } catch (error) {
2543
- throw new VError$1(error, `Failed to get json`);
2544
- }
2545
- };
2546
-
2547
- const getText = async url => {
2548
- try {
2549
- const response = await fetch(url);
2550
- if (!response.ok) {
2551
- throw new Error(response.statusText);
2552
- }
2553
- const text = await response.text();
2554
- return text;
2555
- } catch (error) {
2556
- throw new VError$1(error, `Failed to get text`);
2557
- }
2558
- };
2559
-
2560
- const splitLines = lines => {
2561
- return lines.split('\n');
2562
- };
2563
-
2564
- const textSearchInText = (file, content, query) => {
2565
- const results = [];
2566
- const lines = splitLines(content);
2567
- for (let i = 0; i < lines.length; i++) {
2568
- const line = lines[i];
2569
- const index = line.indexOf(query);
2570
- if (index !== -1) {
2571
- results.push({
2572
- type: Match,
2573
- text: line,
2574
- start: index,
2575
- end: index + query.length,
2576
- lineNumber: i
2577
- });
2578
- }
2579
- }
2580
- if (results.length > 0) {
2581
- results.unshift({
2582
- type: File$1,
2583
- text: file,
2584
- start: 0,
2585
- end: 0,
2586
- lineNumber: 0
2587
- });
2588
- }
2589
- return results;
2590
- };
2591
-
2592
2466
  const textSearch$4 = async (scheme, root, query, options, assetDir) => {
2593
- string(scheme);
2594
- string(root);
2595
- string(query);
2596
- const fetchUri = `${assetDir}/config/fileMap.json`;
2597
- const fileList = await getJson(fetchUri);
2598
- const allResults = [];
2599
- const relativeRoot = root.slice('fetch://'.length);
2600
- for (const uri of fileList) {
2601
- const fetchUri = `${assetDir}${uri}`;
2602
- const content = await getText(fetchUri);
2603
- const relativeUri = uri.slice(relativeRoot.length + 1);
2604
- const results = textSearchInText(relativeUri, content, query);
2605
- allResults.push(...results);
2606
- }
2607
- return allResults;
2608
- };
2609
-
2610
- class FileNotFoundError extends Error {
2611
- constructor(message) {
2612
- super(message);
2613
- this.name = 'FileNotFoundError';
2614
- }
2615
- }
2616
-
2617
- const Directory = 'directory';
2618
- const File = 'file';
2619
-
2620
- const getChildHandles$1 = async handle => {
2621
- object(handle);
2622
- // @ts-ignore
2623
- const childHandles = handle.values();
2624
- const handles = await fromAsync(childHandles);
2625
- return handles;
2626
- };
2627
-
2628
- const getChildHandles = async handle => {
2629
- try {
2630
- return await getChildHandles$1(handle);
2631
- } catch (error) {
2632
- throw new VError$1(error, 'failed to get child handles');
2633
- }
2634
- };
2635
-
2636
- const dirname = (pathSeparator, path) => {
2637
- const index = path.lastIndexOf(pathSeparator);
2638
- if (index === -1) {
2639
- return path;
2640
- }
2641
- return path.slice(0, index);
2642
- };
2643
-
2644
- const instanceOfAny = (object, constructors) => constructors.some(c => object instanceof c);
2645
- let idbProxyableTypes;
2646
- let cursorAdvanceMethods;
2647
- // This is a function to prevent it throwing up in node environments.
2648
- function getIdbProxyableTypes() {
2649
- return idbProxyableTypes || (idbProxyableTypes = [IDBDatabase, IDBObjectStore, IDBIndex, IDBCursor, IDBTransaction]);
2650
- }
2651
- // This is a function to prevent it throwing up in node environments.
2652
- function getCursorAdvanceMethods() {
2653
- return cursorAdvanceMethods || (cursorAdvanceMethods = [IDBCursor.prototype.advance, IDBCursor.prototype.continue, IDBCursor.prototype.continuePrimaryKey]);
2654
- }
2655
- const transactionDoneMap = new WeakMap();
2656
- const transformCache = new WeakMap();
2657
- const reverseTransformCache = new WeakMap();
2658
- function promisifyRequest(request) {
2659
- const promise = new Promise((resolve, reject) => {
2660
- const unlisten = () => {
2661
- request.removeEventListener('success', success);
2662
- request.removeEventListener('error', error);
2663
- };
2664
- const success = () => {
2665
- resolve(wrap(request.result));
2666
- unlisten();
2667
- };
2668
- const error = () => {
2669
- reject(request.error);
2670
- unlisten();
2671
- };
2672
- request.addEventListener('success', success);
2673
- request.addEventListener('error', error);
2674
- });
2675
- // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This
2676
- // is because we create many promises from a single IDBRequest.
2677
- reverseTransformCache.set(promise, request);
2678
- return promise;
2679
- }
2680
- function cacheDonePromiseForTransaction(tx) {
2681
- // Early bail if we've already created a done promise for this transaction.
2682
- if (transactionDoneMap.has(tx)) return;
2683
- const done = new Promise((resolve, reject) => {
2684
- const unlisten = () => {
2685
- tx.removeEventListener('complete', complete);
2686
- tx.removeEventListener('error', error);
2687
- tx.removeEventListener('abort', error);
2688
- };
2689
- const complete = () => {
2690
- resolve();
2691
- unlisten();
2692
- };
2693
- const error = () => {
2694
- reject(tx.error || new DOMException('AbortError', 'AbortError'));
2695
- unlisten();
2696
- };
2697
- tx.addEventListener('complete', complete);
2698
- tx.addEventListener('error', error);
2699
- tx.addEventListener('abort', error);
2700
- });
2701
- // Cache it for later retrieval.
2702
- transactionDoneMap.set(tx, done);
2703
- }
2704
- let idbProxyTraps = {
2705
- get(target, prop, receiver) {
2706
- if (target instanceof IDBTransaction) {
2707
- // Special handling for transaction.done.
2708
- if (prop === 'done') return transactionDoneMap.get(target);
2709
- // Make tx.store return the only store in the transaction, or undefined if there are many.
2710
- if (prop === 'store') {
2711
- return receiver.objectStoreNames[1] ? undefined : receiver.objectStore(receiver.objectStoreNames[0]);
2712
- }
2713
- }
2714
- // Else transform whatever we get back.
2715
- return wrap(target[prop]);
2716
- },
2717
- set(target, prop, value) {
2718
- target[prop] = value;
2719
- return true;
2720
- },
2721
- has(target, prop) {
2722
- if (target instanceof IDBTransaction && (prop === 'done' || prop === 'store')) {
2723
- return true;
2724
- }
2725
- return prop in target;
2726
- }
2727
- };
2728
- function replaceTraps(callback) {
2729
- idbProxyTraps = callback(idbProxyTraps);
2730
- }
2731
- function wrapFunction(func) {
2732
- // Due to expected object equality (which is enforced by the caching in `wrap`), we
2733
- // only create one new func per func.
2734
- // Cursor methods are special, as the behaviour is a little more different to standard IDB. In
2735
- // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the
2736
- // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense
2737
- // with real promises, so each advance methods returns a new promise for the cursor object, or
2738
- // undefined if the end of the cursor has been reached.
2739
- if (getCursorAdvanceMethods().includes(func)) {
2740
- return function (...args) {
2741
- // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
2742
- // the original object.
2743
- func.apply(unwrap(this), args);
2744
- return wrap(this.request);
2745
- };
2746
- }
2747
- return function (...args) {
2748
- // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
2749
- // the original object.
2750
- return wrap(func.apply(unwrap(this), args));
2751
- };
2752
- }
2753
- function transformCachableValue(value) {
2754
- if (typeof value === 'function') return wrapFunction(value);
2755
- // This doesn't return, it just creates a 'done' promise for the transaction,
2756
- // which is later returned for transaction.done (see idbObjectHandler).
2757
- if (value instanceof IDBTransaction) cacheDonePromiseForTransaction(value);
2758
- if (instanceOfAny(value, getIdbProxyableTypes())) return new Proxy(value, idbProxyTraps);
2759
- // Return the same value back if we're not going to transform it.
2760
- return value;
2761
- }
2762
- function wrap(value) {
2763
- // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because
2764
- // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.
2765
- if (value instanceof IDBRequest) return promisifyRequest(value);
2766
- // If we've already transformed this value before, reuse the transformed value.
2767
- // This is faster, but it also provides object equality.
2768
- if (transformCache.has(value)) return transformCache.get(value);
2769
- const newValue = transformCachableValue(value);
2770
- // Not all types are transformed.
2771
- // These may be primitive types, so they can't be WeakMap keys.
2772
- if (newValue !== value) {
2773
- transformCache.set(value, newValue);
2774
- reverseTransformCache.set(newValue, value);
2775
- }
2776
- return newValue;
2777
- }
2778
- const unwrap = value => reverseTransformCache.get(value);
2779
-
2780
- /**
2781
- * Open a database.
2782
- *
2783
- * @param name Name of the database.
2784
- * @param version Schema version.
2785
- * @param callbacks Additional callbacks.
2786
- */
2787
- function openDB(name, version, {
2788
- blocked,
2789
- upgrade,
2790
- blocking,
2791
- terminated
2792
- } = {}) {
2793
- const request = indexedDB.open(name, version);
2794
- const openPromise = wrap(request);
2795
- if (upgrade) {
2796
- request.addEventListener('upgradeneeded', event => {
2797
- upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);
2798
- });
2799
- }
2800
- if (blocked) {
2801
- request.addEventListener('blocked', event => blocked(
2802
- // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
2803
- event.oldVersion, event.newVersion, event));
2804
- }
2805
- openPromise.then(db => {
2806
- if (terminated) db.addEventListener('close', () => terminated());
2807
- if (blocking) {
2808
- db.addEventListener('versionchange', event => blocking(event.oldVersion, event.newVersion, event));
2809
- }
2810
- }).catch(() => {});
2811
- return openPromise;
2812
- }
2813
- const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];
2814
- const writeMethods = ['put', 'add', 'delete', 'clear'];
2815
- const cachedMethods = new Map();
2816
- function getMethod(target, prop) {
2817
- if (!(target instanceof IDBDatabase && !(prop in target) && typeof prop === 'string')) {
2818
- return;
2819
- }
2820
- if (cachedMethods.get(prop)) return cachedMethods.get(prop);
2821
- const targetFuncName = prop.replace(/FromIndex$/, '');
2822
- const useIndex = prop !== targetFuncName;
2823
- const isWrite = writeMethods.includes(targetFuncName);
2824
- if (
2825
- // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.
2826
- !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) || !(isWrite || readMethods.includes(targetFuncName))) {
2827
- return;
2828
- }
2829
- const method = async function (storeName, ...args) {
2830
- // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(
2831
- const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');
2832
- let target = tx.store;
2833
- if (useIndex) target = target.index(args.shift());
2834
- // Must reject if op rejects.
2835
- // If it's a write operation, must reject if tx.done rejects.
2836
- // Must reject with op rejection first.
2837
- // Must resolve with op value.
2838
- // Must handle both promises (no unhandled rejections)
2839
- return (await Promise.all([target[targetFuncName](...args), isWrite && tx.done]))[0];
2840
- };
2841
- cachedMethods.set(prop, method);
2842
- return method;
2843
- }
2844
- replaceTraps(oldTraps => ({
2845
- ...oldTraps,
2846
- get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),
2847
- has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop)
2848
- }));
2849
- const advanceMethodProps = ['continue', 'continuePrimaryKey', 'advance'];
2850
- const methodMap = {};
2851
- const advanceResults = new WeakMap();
2852
- const ittrProxiedCursorToOriginalProxy = new WeakMap();
2853
- const cursorIteratorTraps = {
2854
- get(target, prop) {
2855
- if (!advanceMethodProps.includes(prop)) return target[prop];
2856
- let cachedFunc = methodMap[prop];
2857
- if (!cachedFunc) {
2858
- cachedFunc = methodMap[prop] = function (...args) {
2859
- advanceResults.set(this, ittrProxiedCursorToOriginalProxy.get(this)[prop](...args));
2860
- };
2861
- }
2862
- return cachedFunc;
2863
- }
2864
- };
2865
- async function* iterate(...args) {
2866
- // tslint:disable-next-line:no-this-assignment
2867
- let cursor = this;
2868
- if (!(cursor instanceof IDBCursor)) {
2869
- cursor = await cursor.openCursor(...args);
2870
- }
2871
- if (!cursor) return;
2872
- cursor = cursor;
2873
- const proxiedCursor = new Proxy(cursor, cursorIteratorTraps);
2874
- ittrProxiedCursorToOriginalProxy.set(proxiedCursor, cursor);
2875
- // Map this double-proxy back to the original, so other cursor methods work.
2876
- reverseTransformCache.set(proxiedCursor, unwrap(cursor));
2877
- while (cursor) {
2878
- yield proxiedCursor;
2879
- // If one of the advancing methods was not called, call continue().
2880
- cursor = await (advanceResults.get(proxiedCursor) || cursor.continue());
2881
- advanceResults.delete(proxiedCursor);
2882
- }
2883
- }
2884
- function isIteratorProp(target, prop) {
2885
- return prop === Symbol.asyncIterator && instanceOfAny(target, [IDBIndex, IDBObjectStore, IDBCursor]) || prop === 'iterate' && instanceOfAny(target, [IDBIndex, IDBObjectStore]);
2886
- }
2887
- replaceTraps(oldTraps => ({
2888
- ...oldTraps,
2889
- get(target, prop, receiver) {
2890
- if (isIteratorProp(target, prop)) return iterate;
2891
- return oldTraps.get(target, prop, receiver);
2892
- },
2893
- has(target, prop) {
2894
- return isIteratorProp(target, prop) || oldTraps.has(target, prop);
2895
- }
2896
- }));
2897
-
2898
- const state$2 = {
2899
- databases: Object.create(null),
2900
- eventId: 0,
2901
- dbVersion: 1,
2902
- cachedDb: undefined
2903
- };
2904
-
2905
- // TODO high memory usage in idb because of transactionDoneMap
2906
-
2907
- const getHandleDb = async () => {
2908
- // @ts-ignore
2909
- const db = await openDB('handle', state$2.dbVersion, {
2910
- async upgrade(db) {
2911
- if (!db.objectStoreNames.contains('file-handles-store')) {
2912
- await db.createObjectStore('file-handles-store', {});
2913
- }
2914
- }
2915
- });
2916
- return db;
2917
- };
2918
- const getHandle$1 = async uri => {
2919
- const handleDb = await getHandleDb();
2920
- const handle = await handleDb.get('file-handles-store', uri);
2921
- return handle;
2922
- };
2923
-
2924
- const getHandle = async uri => {
2925
- try {
2926
- // TODO retrieve handle from state or from indexeddb
2927
- // TODO if not found, throw error
2928
- const handle = await getHandle$1(uri);
2929
- return handle;
2930
- } catch (error) {
2931
- throw new VError$1(error, 'Failed to get handle');
2932
- }
2933
- };
2934
-
2935
- const getDirectoryHandle = async uri => {
2936
- const handle = await getHandle(uri);
2937
- if (handle) {
2938
- return handle;
2939
- }
2940
- const dirname$1 = dirname('/', uri);
2941
- if (uri === dirname$1) {
2942
- return undefined;
2943
- }
2944
- return getDirectoryHandle(dirname$1);
2945
- };
2946
-
2947
- const NotReadableError = 'NotReadableError';
2948
-
2949
- const isNotReadableError = error => {
2950
- return error && error.name === NotReadableError;
2951
- };
2952
-
2953
- const getFile = handle => {
2954
- return handle.getFile();
2955
- };
2956
-
2957
- const textSearchInFile = async (all, handle, absolutePath, query) => {
2958
- try {
2959
- const file = await getFile(handle);
2960
- const content = await file.text();
2961
- const results = textSearchInText(absolutePath, content, query);
2962
- push(all, results);
2963
- } catch (error) {
2964
- if (isNotReadableError(error)) {
2965
- // ignore
2966
- return;
2967
- }
2968
- throw error;
2969
- }
2467
+ return invoke$2('ExtensionHostTextSearch.textSearchFetch', scheme, root, query, options, assetDir);
2970
2468
  };
2971
2469
 
2972
- const textSearchRecursively = async (all, parent, handle, query) => {
2973
- const childHandles = await getChildHandles(handle);
2974
- const promises = [];
2975
- for (const childHandle of childHandles) {
2976
- const absolutePath = parent + '/' + childHandle.name;
2977
- switch (childHandle.kind) {
2978
- case Directory:
2979
- promises.push(textSearchRecursively(all, absolutePath, childHandle, query));
2980
- break;
2981
- case File:
2982
- // @ts-ignore
2983
- promises.push(textSearchInFile(all, childHandle, absolutePath, query));
2984
- break;
2985
- }
2986
- }
2987
- await Promise.all(promises);
2988
- };
2989
2470
  const textSearch$3 = async (scheme, root, query) => {
2990
- string(scheme);
2991
- string(root);
2992
- string(query);
2993
- const relativeRoot = root.slice('html://'.length);
2994
- const handle = await getDirectoryHandle(relativeRoot);
2995
- if (!handle) {
2996
- throw new FileNotFoundError(`Folder not found: ${relativeRoot}`);
2997
- }
2998
- const all = [];
2999
- await textSearchRecursively(all, '', handle, query);
3000
- return all;
2471
+ return invoke$2('ExtensionHostTextSearch.textSearchHtml', scheme, root, query);
3001
2472
  };
3002
2473
 
3003
2474
  const getRipGrepArgs = ({
@@ -3492,7 +2963,7 @@ const getFilteredResults = (results, collapsedPaths) => {
3492
2963
  const filteredResults = [];
3493
2964
  let isExcluded = false;
3494
2965
  for (const result of results) {
3495
- if (result.type === File$1) {
2966
+ if (result.type === File) {
3496
2967
  if (collapsedPaths.includes(result.text)) {
3497
2968
  isExcluded = true;
3498
2969
  } else {
@@ -3535,7 +3006,7 @@ const openUri = async (path, focus = true, props = {}) => {
3535
3006
  const getFileIndex = (items, index) => {
3536
3007
  for (let i = index; i >= 0; i--) {
3537
3008
  const item = items[i];
3538
- if (item.type === File$1) {
3009
+ if (item.type === File) {
3539
3010
  return i;
3540
3011
  }
3541
3012
  }
@@ -3578,7 +3049,7 @@ const selectIndex = async (state, index) => {
3578
3049
  } = state;
3579
3050
  const searchResult = items[index];
3580
3051
  switch (searchResult.type) {
3581
- case File$1:
3052
+ case File:
3582
3053
  return selectIndexFile(state, searchResult, index);
3583
3054
  case Match:
3584
3055
  return selectIndexPreview(state, searchResult, index);
@@ -3890,7 +3361,7 @@ const getBulkReplacementEdits = (workspacePath, matches) => {
3890
3361
  text
3891
3362
  } = match;
3892
3363
  switch (type) {
3893
- case File$1:
3364
+ case File:
3894
3365
  ranges.push(currentRanges.length);
3895
3366
  push(ranges, currentRanges);
3896
3367
  const absolutePath = `${workspacePath}/${text.slice(2)}`;