@lvce-editor/extension-host-worker 8.64.0 → 8.66.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.
@@ -75,1637 +75,1608 @@ class VError extends Error {
75
75
  }
76
76
  }
77
77
 
78
- class AssertionError extends Error {
78
+ class CommandNotFoundError extends Error {
79
+ constructor(command) {
80
+ super(`Command not found ${command}`);
81
+ this.name = 'CommandNotFoundError';
82
+ }
83
+ }
84
+ const commands = Object.create(null);
85
+ const register$1 = commandMap => {
86
+ Object.assign(commands, commandMap);
87
+ };
88
+ const getCommand = key => {
89
+ return commands[key];
90
+ };
91
+ const execute$3 = (command, ...args) => {
92
+ const fn = getCommand(command);
93
+ if (!fn) {
94
+ throw new CommandNotFoundError(command);
95
+ }
96
+ return fn(...args);
97
+ };
98
+
99
+ const Two$1 = '2.0';
100
+ const callbacks = Object.create(null);
101
+ const get$c = id => {
102
+ return callbacks[id];
103
+ };
104
+ const remove$5 = id => {
105
+ delete callbacks[id];
106
+ };
107
+ class JsonRpcError extends Error {
79
108
  constructor(message) {
80
109
  super(message);
81
- this.name = 'AssertionError';
110
+ this.name = 'JsonRpcError';
82
111
  }
83
112
  }
84
- const Object$1$1 = 1;
85
- const Number$1 = 2;
86
- const Array$1$1 = 3;
87
- const String$2 = 4;
88
- const Boolean$2 = 5;
89
- const Function = 6;
90
- const Null = 7;
91
- const Unknown = 8;
92
- const getType$2 = value => {
93
- switch (typeof value) {
94
- case 'number':
95
- return Number$1;
96
- case 'function':
97
- return Function;
98
- case 'string':
99
- return String$2;
100
- case 'object':
101
- if (value === null) {
102
- return Null;
103
- }
104
- if (Array.isArray(value)) {
105
- return Array$1$1;
106
- }
107
- return Object$1$1;
108
- case 'boolean':
109
- return Boolean$2;
110
- default:
111
- return Unknown;
113
+ const NewLine$2 = '\n';
114
+ const DomException = 'DOMException';
115
+ const ReferenceError$1 = 'ReferenceError';
116
+ const SyntaxError$1 = 'SyntaxError';
117
+ const TypeError$1 = 'TypeError';
118
+ const getErrorConstructor = (message, type) => {
119
+ if (type) {
120
+ switch (type) {
121
+ case DomException:
122
+ return DOMException;
123
+ case ReferenceError$1:
124
+ return ReferenceError;
125
+ case SyntaxError$1:
126
+ return SyntaxError;
127
+ case TypeError$1:
128
+ return TypeError;
129
+ default:
130
+ return Error;
131
+ }
112
132
  }
113
- };
114
- const object = value => {
115
- const type = getType$2(value);
116
- if (type !== Object$1$1) {
117
- throw new AssertionError('expected value to be of type object');
133
+ if (message.startsWith('TypeError: ')) {
134
+ return TypeError;
118
135
  }
119
- };
120
- const number = value => {
121
- const type = getType$2(value);
122
- if (type !== Number$1) {
123
- throw new AssertionError('expected value to be of type number');
136
+ if (message.startsWith('SyntaxError: ')) {
137
+ return SyntaxError;
124
138
  }
125
- };
126
- const array = value => {
127
- const type = getType$2(value);
128
- if (type !== Array$1$1) {
129
- throw new AssertionError('expected value to be of type array');
139
+ if (message.startsWith('ReferenceError: ')) {
140
+ return ReferenceError;
130
141
  }
142
+ return Error;
131
143
  };
132
- const string = value => {
133
- const type = getType$2(value);
134
- if (type !== String$2) {
135
- throw new AssertionError('expected value to be of type string');
144
+ const constructError = (message, type, name) => {
145
+ const ErrorConstructor = getErrorConstructor(message, type);
146
+ if (ErrorConstructor === DOMException && name) {
147
+ return new ErrorConstructor(message, name);
136
148
  }
137
- };
138
- const fn = value => {
139
- const type = getType$2(value);
140
- if (type !== Function) {
141
- throw new AssertionError('expected value to be of type function');
149
+ if (ErrorConstructor === Error) {
150
+ const error = new Error(message);
151
+ if (name && name !== 'VError') {
152
+ Object.defineProperty(error, 'name', {
153
+ configurable: true,
154
+ value: name
155
+ });
156
+ }
157
+ return error;
142
158
  }
159
+ return new ErrorConstructor(message);
143
160
  };
144
-
145
- const isMessagePort = value => {
146
- return value && value instanceof MessagePort;
161
+ const joinLines$1 = lines => {
162
+ return lines.join(NewLine$2);
147
163
  };
148
- const isMessagePortMain = value => {
149
- return value && value.constructor && value.constructor.name === 'MessagePortMain';
164
+ const splitLines$2 = lines => {
165
+ return lines.split(NewLine$2);
150
166
  };
151
- const isOffscreenCanvas = value => {
152
- return typeof OffscreenCanvas !== 'undefined' && value instanceof OffscreenCanvas;
167
+ const getCurrentStack = () => {
168
+ const stackLinesToSkip = 3;
169
+ const currentStack = joinLines$1(splitLines$2(new Error().stack || '').slice(stackLinesToSkip));
170
+ return currentStack;
153
171
  };
154
- const isInstanceOf = (value, constructorName) => {
155
- return value?.constructor?.name === constructorName;
172
+ const getNewLineIndex = (string, startIndex) => {
173
+ {
174
+ return string.indexOf(NewLine$2);
175
+ }
156
176
  };
157
- const isSocket = value => {
158
- return isInstanceOf(value, 'Socket');
177
+ const getParentStack = error => {
178
+ let parentStack = error.stack || error.data || error.message || '';
179
+ if (parentStack.startsWith(' at')) {
180
+ parentStack = error.message + NewLine$2 + parentStack;
181
+ }
182
+ return parentStack;
159
183
  };
160
- const transferrables = [isMessagePort, isMessagePortMain, isOffscreenCanvas, isSocket];
161
- const isTransferrable = value => {
162
- for (const fn of transferrables) {
163
- if (fn(value)) {
164
- return true;
184
+ const MethodNotFound = -32601;
185
+ const Custom = -32001;
186
+ const setStack = (error, stack) => {
187
+ const descriptor = Object.getOwnPropertyDescriptor(error, 'stack');
188
+ if (descriptor) {
189
+ if (!descriptor.configurable && !descriptor.writable) {
190
+ return;
191
+ }
192
+ if (!descriptor.configurable && descriptor.writable) {
193
+ error.stack = stack;
194
+ return;
165
195
  }
166
196
  }
167
- return false;
197
+ Object.defineProperty(error, 'stack', {
198
+ configurable: true,
199
+ value: stack,
200
+ writable: true
201
+ });
168
202
  };
169
- const walkValue = (value, transferrables, isTransferrable) => {
170
- if (!value) {
171
- return;
172
- }
173
- if (isTransferrable(value)) {
174
- transferrables.push(value);
175
- return;
203
+ const restoreExistingError = (error, currentStack) => {
204
+ if (typeof error.stack === 'string') {
205
+ setStack(error, `${error.stack}${NewLine$2}${currentStack}`);
176
206
  }
177
- if (Array.isArray(value)) {
178
- for (const item of value) {
179
- walkValue(item, transferrables, isTransferrable);
180
- }
207
+ return error;
208
+ };
209
+ const restoreMethodNotFoundError = (error, currentStack) => {
210
+ const restoredError = new JsonRpcError(error.message);
211
+ const parentStack = getParentStack(error);
212
+ setStack(restoredError, `${parentStack}${NewLine$2}${currentStack}`);
213
+ return restoredError;
214
+ };
215
+ const restoreStackFromData = (restoredError, error, currentStack) => {
216
+ if (error.data.stack && error.data.type && error.message) {
217
+ setStack(restoredError, `${error.data.type}: ${error.message}${NewLine$2}${error.data.stack}${NewLine$2}${currentStack}`);
181
218
  return;
182
219
  }
183
- if (typeof value === 'object') {
184
- for (const property of Object.values(value)) {
185
- walkValue(property, transferrables, isTransferrable);
186
- }
187
- return;
220
+ if (error.data.stack) {
221
+ setStack(restoredError, error.data.stack);
188
222
  }
189
223
  };
190
- const getTransferrables = value => {
191
- const transferrables = [];
192
- walkValue(value, transferrables, isTransferrable);
193
- return transferrables;
224
+ const applyDataProperties = (restoredError, error) => {
225
+ restoreStackFromData(restoredError, error, getCurrentStack());
226
+ if (error.data.codeFrame) {
227
+ // @ts-ignore
228
+ restoredError.codeFrame = error.data.codeFrame;
229
+ }
230
+ if (error.data.code) {
231
+ // @ts-ignore
232
+ restoredError.code = error.data.code;
233
+ }
234
+ if (error.data.type) {
235
+ // @ts-ignore
236
+ restoredError.name = error.data.type;
237
+ }
194
238
  };
195
- const attachEvents = that => {
196
- const handleMessage = (...args) => {
197
- const data = that.getData(...args);
198
- that.dispatchEvent(new MessageEvent('message', {
199
- data
200
- }));
201
- };
202
- that.onMessage(handleMessage);
203
- const handleClose = event => {
204
- that.dispatchEvent(new Event('close'));
205
- };
206
- that.onClose(handleClose);
239
+ const applyDirectProperties = (restoredError, error) => {
240
+ if (error.stack) {
241
+ const lowerStack = restoredError.stack || '';
242
+ const indexNewLine = getNewLineIndex(lowerStack);
243
+ const parentStack = getParentStack(error);
244
+ // @ts-ignore
245
+ setStack(restoredError, `${parentStack}${lowerStack.slice(indexNewLine)}`);
246
+ }
247
+ if (error.codeFrame) {
248
+ // @ts-ignore
249
+ restoredError.codeFrame = error.codeFrame;
250
+ }
207
251
  };
208
- class Ipc extends EventTarget {
209
- constructor(rawIpc) {
210
- super();
211
- this._rawIpc = rawIpc;
212
- attachEvents(this);
252
+ const restoreMessageError = (error, _currentStack) => {
253
+ const restoredError = constructError(error.message, error.type, error.name);
254
+ if (error.data) {
255
+ applyDataProperties(restoredError, error);
256
+ } else {
257
+ applyDirectProperties(restoredError, error);
213
258
  }
214
- }
215
- const E_INCOMPATIBLE_NATIVE_MODULE = 'E_INCOMPATIBLE_NATIVE_MODULE';
216
- const E_MODULES_NOT_SUPPORTED_IN_ELECTRON = 'E_MODULES_NOT_SUPPORTED_IN_ELECTRON';
217
- const ERR_MODULE_NOT_FOUND = 'ERR_MODULE_NOT_FOUND';
218
- const NewLine$2 = '\n';
219
- const joinLines$1 = lines => {
220
- return lines.join(NewLine$2);
259
+ return restoredError;
221
260
  };
222
- const RE_AT = /^\s+at/;
223
- const RE_AT_PROMISE_INDEX = /^\s*at async Promise.all \(index \d+\)$/;
224
- const isNormalStackLine = line => {
225
- return RE_AT.test(line) && !RE_AT_PROMISE_INDEX.test(line);
261
+ const restoreJsonRpcError = error => {
262
+ const currentStack = getCurrentStack();
263
+ if (error && error instanceof Error) {
264
+ return restoreExistingError(error, currentStack);
265
+ }
266
+ if (error && error.code && error.code === MethodNotFound) {
267
+ return restoreMethodNotFoundError(error, currentStack);
268
+ }
269
+ if (error && error.message) {
270
+ return restoreMessageError(error);
271
+ }
272
+ if (typeof error === 'string') {
273
+ return new Error(`JsonRpc Error: ${error}`);
274
+ }
275
+ return new Error(`JsonRpc Error: ${error}`);
226
276
  };
227
- const getDetails = lines => {
228
- const index = lines.findIndex(isNormalStackLine);
229
- if (index === -1) {
230
- return {
231
- actualMessage: joinLines$1(lines),
232
- rest: []
233
- };
277
+ const unwrapJsonRpcResult = responseMessage => {
278
+ if ('error' in responseMessage) {
279
+ const restoredError = restoreJsonRpcError(responseMessage.error);
280
+ throw restoredError;
234
281
  }
235
- let lastIndex = index - 1;
236
- while (++lastIndex < lines.length) {
237
- if (!isNormalStackLine(lines[lastIndex])) {
238
- break;
239
- }
282
+ if ('result' in responseMessage) {
283
+ return responseMessage.result;
240
284
  }
241
- return {
242
- actualMessage: lines[index - 1],
243
- rest: lines.slice(index, lastIndex)
244
- };
285
+ throw new JsonRpcError('unexpected response message');
245
286
  };
246
- const splitLines$2 = lines => {
247
- return lines.split(NewLine$2);
287
+ const warn$1 = (...args) => {
288
+ console.warn(...args);
248
289
  };
249
- const RE_MESSAGE_CODE_BLOCK_START = /^Error: The module '.*'$/;
250
- const RE_MESSAGE_CODE_BLOCK_END = /^\s* at/;
251
- const isMessageCodeBlockStartIndex = line => {
252
- return RE_MESSAGE_CODE_BLOCK_START.test(line);
290
+ const resolve = (id, response) => {
291
+ const fn = get$c(id);
292
+ if (!fn) {
293
+ console.log(response);
294
+ warn$1(`callback ${id} may already be disposed`);
295
+ return;
296
+ }
297
+ fn(response);
298
+ remove$5(id);
253
299
  };
254
- const isMessageCodeBlockEndIndex = line => {
255
- return RE_MESSAGE_CODE_BLOCK_END.test(line);
300
+ const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
301
+ const getErrorType = prettyError => {
302
+ if (prettyError && prettyError.type) {
303
+ return prettyError.type;
304
+ }
305
+ if (prettyError && prettyError.constructor && prettyError.constructor.name) {
306
+ return prettyError.constructor.name;
307
+ }
308
+ return undefined;
256
309
  };
257
- const getMessageCodeBlock = stderr => {
258
- const lines = splitLines$2(stderr);
259
- const startIndex = lines.findIndex(isMessageCodeBlockStartIndex);
260
- const endIndex = startIndex + lines.slice(startIndex).findIndex(isMessageCodeBlockEndIndex, startIndex);
261
- const relevantLines = lines.slice(startIndex, endIndex);
262
- const relevantMessage = relevantLines.join(' ').slice('Error: '.length);
263
- return relevantMessage;
310
+ const isAlreadyStack = line => {
311
+ return line.trim().startsWith('at ');
264
312
  };
265
- const isModuleNotFoundMessage = line => {
266
- return line.includes('[ERR_MODULE_NOT_FOUND]');
313
+ const getStack = prettyError => {
314
+ const stackString = prettyError.stack || '';
315
+ const newLineIndex = stackString.indexOf('\n');
316
+ if (newLineIndex !== -1 && !isAlreadyStack(stackString.slice(0, newLineIndex))) {
317
+ return stackString.slice(newLineIndex + 1);
318
+ }
319
+ return stackString;
267
320
  };
268
- const getModuleNotFoundError = stderr => {
269
- const lines = splitLines$2(stderr);
270
- const messageIndex = lines.findIndex(isModuleNotFoundMessage);
271
- const message = lines[messageIndex];
321
+ const getErrorProperty = (error, prettyError) => {
322
+ if (error && error.code === E_COMMAND_NOT_FOUND) {
323
+ return {
324
+ code: MethodNotFound,
325
+ data: error.stack,
326
+ message: error.message
327
+ };
328
+ }
272
329
  return {
273
- code: ERR_MODULE_NOT_FOUND,
274
- message
330
+ code: Custom,
331
+ data: {
332
+ code: prettyError.code,
333
+ codeFrame: prettyError.codeFrame,
334
+ name: prettyError.name,
335
+ stack: getStack(prettyError),
336
+ type: getErrorType(prettyError)
337
+ },
338
+ message: prettyError.message
275
339
  };
276
340
  };
277
- const isModuleNotFoundError = stderr => {
278
- if (!stderr) {
279
- return false;
280
- }
281
- return stderr.includes('ERR_MODULE_NOT_FOUND');
282
- };
283
- const isModulesSyntaxError = stderr => {
284
- if (!stderr) {
285
- return false;
286
- }
287
- return stderr.includes('SyntaxError: Cannot use import statement outside a module');
341
+ const create$1$1 = (id, error) => {
342
+ return {
343
+ error,
344
+ id,
345
+ jsonrpc: Two$1
346
+ };
288
347
  };
289
- const RE_NATIVE_MODULE_ERROR = /^innerError Error: Cannot find module '.*.node'/;
290
- const RE_NATIVE_MODULE_ERROR_2 = /was compiled against a different Node.js version/;
291
- const isUnhelpfulNativeModuleError = stderr => {
292
- return RE_NATIVE_MODULE_ERROR.test(stderr) && RE_NATIVE_MODULE_ERROR_2.test(stderr);
348
+ const getErrorResponse = (id, error, preparePrettyError, logError) => {
349
+ const prettyError = preparePrettyError(error);
350
+ logError(error, prettyError);
351
+ const errorProperty = getErrorProperty(error, prettyError);
352
+ return create$1$1(id, errorProperty);
293
353
  };
294
- const getNativeModuleErrorMessage = stderr => {
295
- const message = getMessageCodeBlock(stderr);
354
+ const create$k = (message, result) => {
296
355
  return {
297
- code: E_INCOMPATIBLE_NATIVE_MODULE,
298
- message: `Incompatible native node module: ${message}`
356
+ id: message.id,
357
+ jsonrpc: Two$1,
358
+ result: result ?? null
299
359
  };
300
360
  };
301
- const getModuleSyntaxError = () => {
361
+ const getSuccessResponse = (message, result) => {
362
+ const resultProperty = result ?? null;
363
+ return create$k(message, resultProperty);
364
+ };
365
+ const getErrorResponseSimple = (id, error) => {
302
366
  return {
303
- code: E_MODULES_NOT_SUPPORTED_IN_ELECTRON,
304
- message: `ES Modules are not supported in electron`
367
+ error: {
368
+ code: Custom,
369
+ data: error,
370
+ // @ts-ignore
371
+ message: error.message
372
+ },
373
+ id,
374
+ jsonrpc: Two$1
305
375
  };
306
376
  };
307
- const getHelpfulChildProcessError = (stdout, stderr) => {
308
- if (isUnhelpfulNativeModuleError(stderr)) {
309
- return getNativeModuleErrorMessage(stderr);
310
- }
311
- if (isModulesSyntaxError(stderr)) {
312
- return getModuleSyntaxError();
377
+ const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
378
+ try {
379
+ const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
380
+ return getSuccessResponse(message, result);
381
+ } catch (error) {
382
+ if (ipc.canUseSimpleErrorResponse) {
383
+ return getErrorResponseSimple(message.id, error);
384
+ }
385
+ return getErrorResponse(message.id, error, preparePrettyError, logError);
313
386
  }
314
- if (isModuleNotFoundError(stderr)) {
315
- return getModuleNotFoundError(stderr);
387
+ };
388
+ const defaultPreparePrettyError = error => {
389
+ return error;
390
+ };
391
+ const defaultLogError = () => {
392
+ // ignore
393
+ };
394
+ const defaultRequiresSocket = () => {
395
+ return false;
396
+ };
397
+ const defaultResolve = resolve;
398
+
399
+ // TODO maybe remove this in v6 or v7, only accept options object to simplify the code
400
+ const normalizeParams = args => {
401
+ if (args.length === 1) {
402
+ const options = args[0];
403
+ return {
404
+ execute: options.execute,
405
+ ipc: options.ipc,
406
+ logError: options.logError || defaultLogError,
407
+ message: options.message,
408
+ preparePrettyError: options.preparePrettyError || defaultPreparePrettyError,
409
+ requiresSocket: options.requiresSocket || defaultRequiresSocket,
410
+ resolve: options.resolve || defaultResolve
411
+ };
316
412
  }
317
- const lines = splitLines$2(stderr);
318
- const {
319
- actualMessage,
320
- rest
321
- } = getDetails(lines);
322
413
  return {
323
- code: '',
324
- message: actualMessage,
325
- stack: rest
414
+ execute: args[2],
415
+ ipc: args[0],
416
+ logError: args[5],
417
+ message: args[1],
418
+ preparePrettyError: args[4],
419
+ requiresSocket: args[6],
420
+ resolve: args[3]
326
421
  };
327
422
  };
328
- class IpcError extends VError {
329
- // @ts-ignore
330
- constructor(betterMessage, stdout = '', stderr = '') {
331
- if (stdout || stderr) {
332
- // @ts-ignore
333
- const {
334
- code,
335
- message,
336
- stack
337
- } = getHelpfulChildProcessError(stdout, stderr);
338
- const cause = new Error(message);
339
- // @ts-ignore
340
- cause.code = code;
341
- cause.stack = stack;
342
- super(cause, betterMessage);
343
- } else {
344
- super(betterMessage);
423
+ const handleJsonRpcMessage = async (...args) => {
424
+ const options = normalizeParams(args);
425
+ const {
426
+ execute,
427
+ ipc,
428
+ logError,
429
+ message,
430
+ preparePrettyError,
431
+ requiresSocket,
432
+ resolve
433
+ } = options;
434
+ if ('id' in message) {
435
+ if ('method' in message) {
436
+ const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
437
+ try {
438
+ ipc.send(response);
439
+ } catch (error) {
440
+ const errorResponse = getErrorResponse(message.id, error, preparePrettyError, logError);
441
+ ipc.send(errorResponse);
442
+ }
443
+ return;
345
444
  }
346
- // @ts-ignore
347
- this.name = 'IpcError';
348
- // @ts-ignore
349
- this.stdout = stdout;
350
- // @ts-ignore
351
- this.stderr = stderr;
445
+ resolve(message.id, message);
446
+ return;
352
447
  }
353
- }
354
- const readyMessage = 'ready';
355
- const getData$2 = event => {
356
- return event.data;
448
+ if ('method' in message) {
449
+ await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
450
+ return;
451
+ }
452
+ throw new JsonRpcError('unexpected message');
357
453
  };
358
- const listen$8 = ({
359
- port
454
+
455
+ const createMockRpc = ({
456
+ commandMap
360
457
  }) => {
361
- return port;
458
+ const invocations = [];
459
+ const invoke = (method, ...params) => {
460
+ invocations.push([method, ...params]);
461
+ const command = commandMap[method];
462
+ if (!command) {
463
+ throw new Error(`command ${method} not found`);
464
+ }
465
+ return command(...params);
466
+ };
467
+ const mockRpc = {
468
+ invocations,
469
+ invoke,
470
+ invokeAndTransfer: invoke
471
+ };
472
+ return mockRpc;
362
473
  };
363
- const signal$9 = port => {
364
- port.postMessage(readyMessage);
474
+
475
+ const rpcs$2 = Object.create(null);
476
+ const set$e = (id, rpc) => {
477
+ rpcs$2[id] = rpc;
365
478
  };
366
- class IpcChildWithMessagePort extends Ipc {
367
- getData(event) {
368
- return getData$2(event);
369
- }
370
- send(message) {
371
- this._rawIpc.postMessage(message);
372
- }
373
- sendAndTransfer(message) {
374
- const transfer = getTransferrables(message);
375
- this._rawIpc.postMessage(message, transfer);
376
- }
377
- dispose() {
378
- // ignore
379
- }
380
- onClose(callback) {
381
- // ignore
382
- }
383
- onMessage(callback) {
384
- this._rawIpc.addEventListener('message', callback);
385
- this._rawIpc.start();
386
- }
387
- }
388
- const wrap$g = port => {
389
- return new IpcChildWithMessagePort(port);
479
+ const get$b = id => {
480
+ return rpcs$2[id];
390
481
  };
391
- const IpcChildWithMessagePort$1 = {
482
+ const remove$4 = id => {
483
+ delete rpcs$2[id];
484
+ };
485
+
486
+ /* eslint-disable @typescript-eslint/explicit-function-return-type */
487
+ const create$j = rpcId => {
488
+ return {
489
+ async dispose() {
490
+ const rpc = get$b(rpcId);
491
+ await rpc.dispose();
492
+ },
493
+ // @ts-ignore
494
+ invoke(method, ...params) {
495
+ const rpc = get$b(rpcId);
496
+ // @ts-ignore
497
+ return rpc.invoke(method, ...params);
498
+ },
499
+ // @ts-ignore
500
+ invokeAndTransfer(method, ...params) {
501
+ const rpc = get$b(rpcId);
502
+ // @ts-ignore
503
+ return rpc.invokeAndTransfer(method, ...params);
504
+ },
505
+ registerMockRpc(commandMap) {
506
+ const mockRpc = createMockRpc({
507
+ commandMap
508
+ });
509
+ set$e(rpcId, mockRpc);
510
+ // @ts-ignore
511
+ mockRpc[Symbol.dispose] = () => {
512
+ remove$4(rpcId);
513
+ };
514
+ // @ts-ignore
515
+ return mockRpc;
516
+ },
517
+ set(rpc) {
518
+ set$e(rpcId, rpc);
519
+ }
520
+ };
521
+ };
522
+
523
+ const Text = 12;
524
+ const Reference = 100;
525
+
526
+ const DebugWorker$1 = 55;
527
+ const DialogWorker = 7014;
528
+ const ExtensionManagementWorker = 9006;
529
+ const RendererWorker$1 = 1;
530
+
531
+ const {
532
+ invoke: invoke$8} = create$j(DebugWorker$1);
533
+
534
+ const DebugWorker = {
392
535
  __proto__: null,
393
- listen: listen$8,
394
- signal: signal$9,
395
- wrap: wrap$g
536
+ invoke: invoke$8
396
537
  };
397
- const listen$7 = () => {
398
- // @ts-ignore
399
- if (typeof WorkerGlobalScope === 'undefined') {
400
- throw new TypeError('module is not in web worker scope');
401
- }
402
- return globalThis;
538
+
539
+ const {
540
+ invoke: invoke$7,
541
+ set: set$d
542
+ } = create$j(DialogWorker);
543
+
544
+ const {
545
+ invoke: invoke$6,
546
+ invokeAndTransfer: invokeAndTransfer$3,
547
+ set: set$c
548
+ } = create$j(ExtensionManagementWorker);
549
+
550
+ const {
551
+ set: set$b
552
+ } = create$j(7013);
553
+
554
+ const {
555
+ invoke: invoke$5,
556
+ set: set$a
557
+ } = create$j(10_000);
558
+
559
+ const {
560
+ invoke: invoke$4,
561
+ invokeAndTransfer: invokeAndTransfer$2} = create$j(RendererWorker$1);
562
+ const sendMessagePortToDialogWorker = async port => {
563
+ const command = 'HandleMessagePort.handleMessagePort';
564
+ await invokeAndTransfer$2('SendMessagePortToExtensionHostWorker.sendMessagePortToDialogWorker', port, command);
403
565
  };
404
- const signal$8 = global => {
405
- global.postMessage(readyMessage);
566
+ const sendMessagePortToFileSearchWorker = async (port, rpcId = 0) => {
567
+ const command = 'QuickPick.handleMessagePort';
568
+ await invokeAndTransfer$2('SendMessagePortToExtensionHostWorker.sendMessagePortToFileSearchWorker', port, command, rpcId);
406
569
  };
407
- class IpcChildWithModuleWorker extends Ipc {
408
- getData(event) {
409
- return getData$2(event);
570
+ const sendMessagePortToQuickPickWorker = async (port, rpcId = 0) => {
571
+ const command = 'QuickPick.handleMessagePort';
572
+ await invokeAndTransfer$2('SendMessagePortToExtensionHostWorker.sendMessagePortToQuickPickWorker', port, command, rpcId);
573
+ };
574
+ const sendMessagePortToIframeWorker = async (port, rpcId) => {
575
+ const command = 'Iframes.handleMessagePort';
576
+ await invokeAndTransfer$2('SendMessagePortToExtensionHostWorker.sendMessagePortToIframeWorker', port, command, rpcId);
577
+ };
578
+ const sendMessagePortToExtensionManagementWorker = async (port, rpcId) => {
579
+ const command = 'Extensions.handleMessagePort';
580
+ await invokeAndTransfer$2('SendMessagePortToExtensionHostWorker.sendMessagePortToExtensionManagementWorker', port, command, rpcId);
581
+ };
582
+
583
+ const state$c = {
584
+ commands: Object.create(null)
585
+ };
586
+ const getCommandDisplay = command => {
587
+ if (command && command.id && typeof command.id === 'string') {
588
+ return ` ${command.id}`;
410
589
  }
411
- send(message) {
412
- // @ts-ignore
413
- this._rawIpc.postMessage(message);
590
+ return '';
591
+ };
592
+ const registerCommand = command => {
593
+ try {
594
+ if (!command) {
595
+ if (command === null) {
596
+ throw new Error(`command is null`);
597
+ }
598
+ throw new Error('command is not defined');
599
+ }
600
+ if (!command.id) {
601
+ throw new Error('command is missing id');
602
+ }
603
+ if (!command.execute) {
604
+ throw new Error('command is missing execute function');
605
+ }
606
+ if (command.id in state$c.commands) {
607
+ throw new Error(`command cannot be registered multiple times`);
608
+ }
609
+ state$c.commands[command.id] = command;
610
+ } catch (error) {
611
+ const commandDisplayId = getCommandDisplay(command);
612
+ throw new VError(error, `Failed to register command${commandDisplayId}`);
414
613
  }
415
- sendAndTransfer(message) {
416
- const transfer = getTransferrables(message);
614
+ };
615
+ const executeCommand$2 = async (id, ...args) => {
616
+ try {
617
+ const command = state$c.commands[id];
618
+ if (!command) {
619
+ throw new Error(`command ${id} not found`);
620
+ }
621
+ const results = await command.execute(...args);
622
+ return results;
623
+ } catch (error) {
417
624
  // @ts-ignore
418
- this._rawIpc.postMessage(message, transfer);
419
- }
420
- dispose() {
421
- // ignore
422
- }
423
- onClose(callback) {
424
- // ignore
425
- }
426
- onMessage(callback) {
427
- this._rawIpc.addEventListener('message', callback);
625
+ if (error && error.isExpected) {
626
+ throw error;
627
+ }
628
+ throw new VError(error, 'Failed to execute command');
428
629
  }
429
- }
430
- const wrap$f = global => {
431
- return new IpcChildWithModuleWorker(global);
432
630
  };
433
- const waitForFirstMessage = async port => {
434
- const {
435
- promise,
436
- resolve
437
- } = Promise.withResolvers();
438
- port.addEventListener('message', resolve, {
439
- once: true
440
- });
441
- const event = await promise;
442
- // @ts-ignore
443
- return event.data;
631
+ const hasCommand = id => {
632
+ return id in state$c.commands;
444
633
  };
445
- const listen$6 = async () => {
446
- const parentIpcRaw = listen$7();
447
- signal$8(parentIpcRaw);
448
- const parentIpc = wrap$f(parentIpcRaw);
449
- const firstMessage = await waitForFirstMessage(parentIpc);
450
- if (firstMessage.method !== 'initialize') {
451
- throw new IpcError('unexpected first message');
634
+ const getRegisteredCommandIds$1 = () => {
635
+ return Object.values(state$c.commands).map(command => command.id);
636
+ };
637
+
638
+ const isCommandNotFoundError = error => {
639
+ return error instanceof Error && error.name === 'CommandNotFoundError';
640
+ };
641
+ const executeCommand$1 = async (id, ...args) => {
642
+ try {
643
+ return await invoke$6('Extensions.executeCommand', id, ...args);
644
+ } catch (error) {
645
+ if (!isCommandNotFoundError(error)) {
646
+ throw error;
647
+ }
648
+ if (hasCommand(id)) {
649
+ return executeCommand$2(id, ...args);
650
+ }
651
+ return invoke$4(id, ...args);
452
652
  }
453
- const type = firstMessage.params[0];
454
- if (type === 'message-port') {
455
- parentIpc.send({
456
- id: firstMessage.id,
457
- jsonrpc: '2.0',
458
- result: null
459
- });
460
- parentIpc.dispose();
461
- const port = firstMessage.params[1];
462
- return port;
653
+ };
654
+
655
+ class DepecratedError extends Error {
656
+ constructor(message) {
657
+ super(message);
658
+ this.name = 'DeprecatedError';
463
659
  }
464
- return globalThis;
660
+ }
661
+
662
+ const getJson$1 = async url => {
663
+ throw new DepecratedError(`vscode.getJson is deprecated, use createNodeRpc instead`);
465
664
  };
466
- class IpcChildWithModuleWorkerAndMessagePort extends Ipc {
467
- getData(event) {
468
- return getData$2(event);
469
- }
470
- send(message) {
471
- this._rawIpc.postMessage(message);
472
- }
473
- sendAndTransfer(message) {
474
- const transfer = getTransferrables(message);
475
- this._rawIpc.postMessage(message, transfer);
476
- }
477
- dispose() {
478
- if (this._rawIpc.close) {
479
- this._rawIpc.close();
480
- }
481
- }
482
- onClose(callback) {
483
- // ignore
484
- }
485
- onMessage(callback) {
486
- this._rawIpc.addEventListener('message', callback);
487
- this._rawIpc.start();
665
+
666
+ class AssertionError extends Error {
667
+ constructor(message) {
668
+ super(message);
669
+ this.name = 'AssertionError';
488
670
  }
489
671
  }
490
- const wrap$e = port => {
491
- return new IpcChildWithModuleWorkerAndMessagePort(port);
492
- };
493
- const IpcChildWithModuleWorkerAndMessagePort$1 = {
494
- __proto__: null,
495
- listen: listen$6,
496
- wrap: wrap$e
497
- };
498
- const Error$3 = 1;
499
- const Open = 2;
500
- const Close = 3;
501
- const addListener = (emitter, type, callback) => {
502
- if ('addEventListener' in emitter) {
503
- emitter.addEventListener(type, callback);
504
- } else {
505
- emitter.on(type, callback);
672
+ const Object$1$1 = 1;
673
+ const Number$1 = 2;
674
+ const Array$1$1 = 3;
675
+ const String$2 = 4;
676
+ const Boolean$2 = 5;
677
+ const Function = 6;
678
+ const Null = 7;
679
+ const Unknown = 8;
680
+ const getType$2 = value => {
681
+ switch (typeof value) {
682
+ case 'number':
683
+ return Number$1;
684
+ case 'function':
685
+ return Function;
686
+ case 'string':
687
+ return String$2;
688
+ case 'object':
689
+ if (value === null) {
690
+ return Null;
691
+ }
692
+ if (Array.isArray(value)) {
693
+ return Array$1$1;
694
+ }
695
+ return Object$1$1;
696
+ case 'boolean':
697
+ return Boolean$2;
698
+ default:
699
+ return Unknown;
506
700
  }
507
701
  };
508
- const removeListener = (emitter, type, callback) => {
509
- if ('removeEventListener' in emitter) {
510
- emitter.removeEventListener(type, callback);
511
- } else {
512
- emitter.off(type, callback);
702
+ const object = value => {
703
+ const type = getType$2(value);
704
+ if (type !== Object$1$1) {
705
+ throw new AssertionError('expected value to be of type object');
513
706
  }
514
707
  };
515
- const getFirstEvent = (eventEmitter, eventMap) => {
516
- const {
517
- promise,
518
- resolve
519
- } = Promise.withResolvers();
520
- const listenerMap = Object.create(null);
521
- const cleanup = value => {
522
- for (const event of Object.keys(eventMap)) {
523
- removeListener(eventEmitter, event, listenerMap[event]);
524
- }
525
- resolve(value);
526
- };
527
- for (const [event, type] of Object.entries(eventMap)) {
528
- const listener = event => {
529
- cleanup({
530
- event,
531
- type
532
- });
533
- };
534
- addListener(eventEmitter, event, listener);
535
- listenerMap[event] = listener;
708
+ const number = value => {
709
+ const type = getType$2(value);
710
+ if (type !== Number$1) {
711
+ throw new AssertionError('expected value to be of type number');
536
712
  }
537
- return promise;
538
713
  };
539
- const Message$1 = 3;
540
- const create$5$1 = async ({
541
- isMessagePortOpen,
542
- messagePort
543
- }) => {
544
- if (!isMessagePort(messagePort)) {
545
- throw new IpcError('port must be of type MessagePort');
546
- }
547
- if (isMessagePortOpen) {
548
- return messagePort;
549
- }
550
- const eventPromise = getFirstEvent(messagePort, {
551
- message: Message$1
552
- });
553
- messagePort.start();
554
- const {
555
- event,
556
- type
557
- } = await eventPromise;
558
- if (type !== Message$1) {
559
- throw new IpcError('Failed to wait for ipc message');
560
- }
561
- if (event.data !== readyMessage) {
562
- throw new IpcError('unexpected first message');
714
+ const array = value => {
715
+ const type = getType$2(value);
716
+ if (type !== Array$1$1) {
717
+ throw new AssertionError('expected value to be of type array');
563
718
  }
564
- return messagePort;
565
- };
566
- const signal$1 = messagePort => {
567
- messagePort.start();
568
719
  };
569
- class IpcParentWithMessagePort extends Ipc {
570
- getData = getData$2;
571
- send(message) {
572
- this._rawIpc.postMessage(message);
573
- }
574
- sendAndTransfer(message) {
575
- const transfer = getTransferrables(message);
576
- this._rawIpc.postMessage(message, transfer);
577
- }
578
- dispose() {
579
- this._rawIpc.close();
580
- }
581
- onMessage(callback) {
582
- this._rawIpc.addEventListener('message', callback);
720
+ const string = value => {
721
+ const type = getType$2(value);
722
+ if (type !== String$2) {
723
+ throw new AssertionError('expected value to be of type string');
583
724
  }
584
- onClose(callback) {}
585
- }
586
- const wrap$5 = messagePort => {
587
- return new IpcParentWithMessagePort(messagePort);
588
- };
589
- const IpcParentWithMessagePort$1 = {
590
- __proto__: null,
591
- create: create$5$1,
592
- signal: signal$1,
593
- wrap: wrap$5
594
- };
595
- const stringifyCompact = value => {
596
- return JSON.stringify(value);
597
725
  };
598
- const parse$1 = content => {
599
- if (content === 'undefined') {
600
- return null;
601
- }
602
- try {
603
- return JSON.parse(content);
604
- } catch (error) {
605
- throw new VError(error, 'failed to parse json');
726
+ const fn = value => {
727
+ const type = getType$2(value);
728
+ if (type !== Function) {
729
+ throw new AssertionError('expected value to be of type function');
606
730
  }
607
731
  };
608
- const waitForWebSocketToBeOpen = webSocket => {
609
- return getFirstEvent(webSocket, {
610
- close: Close,
611
- error: Error$3,
612
- open: Open
613
- });
732
+
733
+ const state$b = {
734
+ /** @type{any[]} */
735
+ onDidChangeTextDocumentListeners: [],
736
+ /** @type{any[]} */
737
+ onDidSaveTextDocumentListeners: [],
738
+ /** @type{any[]} */
739
+ onWillChangeEditorListeners: [],
740
+ textDocuments: Object.create(null)
614
741
  };
615
- const create$k = async ({
616
- webSocket
617
- }) => {
618
- const firstWebSocketEvent = await waitForWebSocketToBeOpen(webSocket);
619
- if (firstWebSocketEvent.type === Error$3) {
620
- throw new IpcError(`WebSocket connection error`);
621
- }
622
- if (firstWebSocketEvent.type === Close) {
623
- throw new IpcError('Websocket connection was immediately closed');
624
- }
625
- return webSocket;
742
+ const setDocument = (textDocumentId, textDocument) => {
743
+ state$b.textDocuments[textDocumentId] = textDocument;
626
744
  };
627
- let IpcParentWithWebSocket$1 = class IpcParentWithWebSocket extends Ipc {
628
- getData(event) {
629
- return parse$1(event.data);
630
- }
631
- send(message) {
632
- this._rawIpc.send(stringifyCompact(message));
633
- }
634
- sendAndTransfer(message) {
635
- throw new Error('sendAndTransfer not supported');
636
- }
637
- dispose() {
638
- this._rawIpc.close();
639
- }
640
- onClose(callback) {
641
- this._rawIpc.addEventListener('close', callback);
642
- }
643
- onMessage(callback) {
644
- this._rawIpc.addEventListener('message', callback);
645
- }
745
+ const getDidOpenListeners = () => {
746
+ return state$b.onDidSaveTextDocumentListeners;
646
747
  };
647
- const wrap$1 = webSocket => {
648
- return new IpcParentWithWebSocket$1(webSocket);
748
+ const getWillChangeListeners = () => {
749
+ return state$b.onWillChangeEditorListeners;
649
750
  };
650
- const IpcParentWithWebSocket$1$1 = {
651
- __proto__: null,
652
- create: create$k,
653
- wrap: wrap$1
751
+ const getDidChangeListeners = () => {
752
+ return state$b.onDidChangeTextDocumentListeners;
753
+ };
754
+ const getDocument = textDocumentId => {
755
+ return state$b.textDocuments[textDocumentId];
654
756
  };
655
757
 
656
- class CommandNotFoundError extends Error {
657
- constructor(command) {
658
- super(`Command not found ${command}`);
659
- this.name = 'CommandNotFoundError';
758
+ const getOffset$1 = (textDocument, position) => {
759
+ let offset = 0;
760
+ let rowIndex = 0;
761
+ while (rowIndex++ < position.rowIndex) {
762
+ const newLineIndex = textDocument.text.indexOf('\n', offset);
763
+ offset = newLineIndex + 1;
660
764
  }
661
- }
662
- const commands = Object.create(null);
663
- const register$1 = commandMap => {
664
- Object.assign(commands, commandMap);
665
- };
666
- const getCommand = key => {
667
- return commands[key];
668
- };
669
- const execute$3 = (command, ...args) => {
670
- const fn = getCommand(command);
671
- if (!fn) {
672
- throw new CommandNotFoundError(command);
673
- }
674
- return fn(...args);
765
+ offset += position.columnIndex;
766
+ return offset;
675
767
  };
676
768
 
677
- const Two$1 = '2.0';
678
- const callbacks = Object.create(null);
679
- const get$c = id => {
680
- return callbacks[id];
681
- };
682
- const remove$5 = id => {
683
- delete callbacks[id];
684
- };
685
- class JsonRpcError extends Error {
686
- constructor(message) {
687
- super(message);
688
- this.name = 'JsonRpcError';
689
- }
690
- }
691
- const NewLine$1 = '\n';
692
- const DomException = 'DOMException';
693
- const ReferenceError$1 = 'ReferenceError';
694
- const SyntaxError$1 = 'SyntaxError';
695
- const TypeError$1 = 'TypeError';
696
- const getErrorConstructor = (message, type) => {
697
- if (type) {
698
- switch (type) {
699
- case DomException:
700
- return DOMException;
701
- case ReferenceError$1:
702
- return ReferenceError;
703
- case SyntaxError$1:
704
- return SyntaxError;
705
- case TypeError$1:
706
- return TypeError;
707
- default:
708
- return Error;
709
- }
710
- }
711
- if (message.startsWith('TypeError: ')) {
712
- return TypeError;
713
- }
714
- if (message.startsWith('SyntaxError: ')) {
715
- return SyntaxError;
716
- }
717
- if (message.startsWith('ReferenceError: ')) {
718
- return ReferenceError;
719
- }
720
- return Error;
721
- };
722
- const constructError = (message, type, name) => {
723
- const ErrorConstructor = getErrorConstructor(message, type);
724
- if (ErrorConstructor === DOMException && name) {
725
- return new ErrorConstructor(message, name);
726
- }
727
- if (ErrorConstructor === Error) {
728
- const error = new Error(message);
729
- if (name && name !== 'VError') {
730
- error.name = name;
769
+ // const toOffsetBasedEdit = (textDocument, documentEdit) => {
770
+ // switch (documentEdit.type) {
771
+ // case /* singleLineEdit */ 1: {
772
+ // const offset = getOffset(textDocument, documentEdit)
773
+ // return {
774
+ // offset,
775
+ // inserted: documentEdit.inserted,
776
+ // deleted: documentEdit.deleted,
777
+ // // type: /* singleLineEdit */ 1
778
+ // }
779
+ // }
780
+ // case /* splice */ 2:
781
+ // const offset = getOffset(textDocument, {
782
+ // rowIndex: documentEdit.rowIndex,
783
+ // columnIndex: textDocument.lines[documentEdit.rowIndex - 1].length,
784
+ // })
785
+ // const inserted = '\n' + documentEdit.newLines.join('\n')
786
+ // return {
787
+ // offset,
788
+ // inserted,
789
+ // deleted: 0 /* TODO */,
790
+ // }
791
+ // }
792
+ // }
793
+
794
+ // TODO incremental edits, don't send full text
795
+ // export const applyEdit = (id, text, edits) => {
796
+ // const textDocument = get(id)
797
+ // textDocument.lines = text.split('\n')
798
+ // const offsetBasedEdits = edits.map((edit) =>
799
+ // toOffsetBasedEdit(textDocument, edit)
800
+ // )
801
+ // for (const listener of state.onDidChangeTextDocumentListeners) {
802
+ // // TODO avoid extra object allocation
803
+ // listener(textDocument, offsetBasedEdits)
804
+ // }
805
+ // }
806
+
807
+ // TODO data oriented vs object oriented
808
+ // data -> simpler, exposes internals, sometimes weird/long (vscode.TextDocument.getText(textDocument))
809
+ // object oriented -> hides internals, banana problem (textDocument.getText())
810
+
811
+ // TODO send to shared process, which sends it to renderer worker
812
+ // renderer worker sends back the edit
813
+ // export const applyEdit2 = (textDocument, edit) => {
814
+ // if (VALIDATION_ENABLED) {
815
+ // assert(typeof textDocument === 'object')
816
+ // assert(textDocument !== null)
817
+ // assert(typeof textDocument.id === 'number')
818
+ // assert(textDocument.id > 0)
819
+ // assert(typeof textDocument.getText === 'function')
820
+ // assert(typeof edit === 'object')
821
+ // assert(typeof edit.offset === 'number')
822
+ // assert(typeof edit.inserted === 'string')
823
+ // assert(typeof edit.deleted === 'number')
824
+ // }
825
+
826
+ // let rowIndex = 0
827
+ // let offset = 0
828
+ // const lines = textDocument.getText().split('\n')
829
+ // while (offset < edit.offset) {
830
+ // offset += lines[rowIndex++].length + 1
831
+ // }
832
+ // rowIndex--
833
+ // offset -= lines[rowIndex].length + 1
834
+ // const edit2 = {
835
+ // rowIndex,
836
+ // inserted: edit.inserted,
837
+ // deleted: edit.deleted,
838
+ // columnIndex: edit.offset - offset + edit.deleted,
839
+ // type: 1,
840
+ // }
841
+
842
+ // // // TODO should be invoke and return boolean whether edit was applied or not
843
+ // SharedProcess.send({
844
+ // event: 'TextDocument.applyEdit',
845
+ // args: [/* id */ textDocument.id, /* edits */ edit2],
846
+ // })
847
+ // }
848
+
849
+ // export const create = (textDocumentId, languageId, content) => {
850
+ // const textDocument = {
851
+ // languageId,
852
+ // lines: content.split('\n'),
853
+ // }
854
+ // state.textDocuments[textDocumentId] = textDocument
855
+ // }
856
+
857
+ // const createTextDocument = (uri, languageId, text) => {
858
+ // if (VALIDATION_ENABLED) {
859
+ // assert(typeof uri === 'string')
860
+ // assert(typeof languageId === 'string')
861
+ // assert(typeof text === 'string')
862
+ // }
863
+ // const state = {
864
+ // /** @internal */
865
+ // lines: text.split('\n'),
866
+ // uri,
867
+ // languageId,
868
+ // getText() {
869
+ // return state.lines.join('\n')
870
+ // },
871
+ // }
872
+ // return state
873
+ // }
874
+
875
+ // export const sync = (documentId, languageId, text) => {
876
+ // const textDocument = get(documentId)
877
+ // if (!textDocument) {
878
+ // console.warn(`textDocument is undefined ${languageId}`)
879
+ // return
880
+ // }
881
+ // textDocument.languageId = languageId
882
+ // textDocument.lines = text.split('\n')
883
+ // // console.log('sync', JSON.stringify(text))
884
+ // }
885
+
886
+ const runListenerSafe = async (listener, ...args) => {
887
+ try {
888
+ await listener(...args);
889
+ } catch (error) {
890
+ // @ts-ignore
891
+ if (error && error.message) {
892
+ // @ts-ignore
893
+ error.message = 'Failed to run open listener: ' + error.message;
731
894
  }
732
- return error;
733
- }
734
- return new ErrorConstructor(message);
735
- };
736
- const joinLines = lines => {
737
- return lines.join(NewLine$1);
738
- };
739
- const splitLines$1 = lines => {
740
- return lines.split(NewLine$1);
741
- };
742
- const getCurrentStack = () => {
743
- const stackLinesToSkip = 3;
744
- const currentStack = joinLines(splitLines$1(new Error().stack || '').slice(stackLinesToSkip));
745
- return currentStack;
746
- };
747
- const getNewLineIndex = (string, startIndex = undefined) => {
748
- return string.indexOf(NewLine$1, startIndex);
749
- };
750
- const getParentStack = error => {
751
- let parentStack = error.stack || error.data || error.message || '';
752
- if (parentStack.startsWith(' at')) {
753
- parentStack = error.message + NewLine$1 + parentStack;
895
+ console.error(error);
754
896
  }
755
- return parentStack;
756
897
  };
757
- const MethodNotFound = -32601;
758
- const Custom = -32001;
759
- const restoreJsonRpcError = error => {
760
- const currentStack = getCurrentStack();
761
- if (error && error instanceof Error) {
762
- if (typeof error.stack === 'string') {
763
- error.stack = error.stack + NewLine$1 + currentStack;
764
- }
765
- return error;
766
- }
767
- if (error && error.code && error.code === MethodNotFound) {
768
- const restoredError = new JsonRpcError(error.message);
769
- const parentStack = getParentStack(error);
770
- restoredError.stack = parentStack + NewLine$1 + currentStack;
771
- return restoredError;
772
- }
773
- if (error && error.message) {
774
- const restoredError = constructError(error.message, error.type, error.name);
775
- if (error.data) {
776
- if (error.data.stack && error.data.type && error.message) {
777
- restoredError.stack = error.data.type + ': ' + error.message + NewLine$1 + error.data.stack + NewLine$1 + currentStack;
778
- } else if (error.data.stack) {
779
- restoredError.stack = error.data.stack;
780
- }
781
- if (error.data.codeFrame) {
782
- // @ts-ignore
783
- restoredError.codeFrame = error.data.codeFrame;
784
- }
785
- if (error.data.code) {
786
- // @ts-ignore
787
- restoredError.code = error.data.code;
788
- }
789
- if (error.data.type) {
790
- // @ts-ignore
791
- restoredError.name = error.data.type;
792
- }
793
- } else {
794
- if (error.stack) {
795
- const lowerStack = restoredError.stack || '';
796
- // @ts-ignore
797
- const indexNewLine = getNewLineIndex(lowerStack);
798
- const parentStack = getParentStack(error);
799
- // @ts-ignore
800
- restoredError.stack = parentStack + lowerStack.slice(indexNewLine);
801
- }
802
- if (error.codeFrame) {
803
- // @ts-ignore
804
- restoredError.codeFrame = error.codeFrame;
805
- }
806
- }
807
- return restoredError;
808
- }
809
- if (typeof error === 'string') {
810
- return new Error(`JsonRpc Error: ${error}`);
898
+ const runListenersSafe = (listeners, ...args) => {
899
+ for (const listener of listeners) {
900
+ runListenerSafe(listener, ...args);
811
901
  }
812
- return new Error(`JsonRpc Error: ${error}`);
813
902
  };
814
- const unwrapJsonRpcResult = responseMessage => {
815
- if ('error' in responseMessage) {
816
- const restoredError = restoreJsonRpcError(responseMessage.error);
817
- throw restoredError;
818
- }
819
- if ('result' in responseMessage) {
820
- return responseMessage.result;
821
- }
822
- throw new JsonRpcError('unexpected response message');
903
+ const syncFull = (uri, textDocumentId, languageId, text) => {
904
+ const textDocument = {
905
+ documentId: textDocumentId,
906
+ languageId,
907
+ text,
908
+ uri
909
+ };
910
+ setDocument(textDocumentId, textDocument);
911
+ runListenersSafe(getDidOpenListeners(), textDocument);
823
912
  };
824
- const warn$1 = (...args) => {
825
- console.warn(...args);
913
+ const getSyntheticChanges = (textDocument, changes) => {
914
+ // console.log({ textDocument, changes })
915
+ object(textDocument);
916
+ array(changes);
917
+ const change = changes[0];
918
+ const startOffset = getOffset$1(textDocument, change.start);
919
+ const endOffset = getOffset$1(textDocument, change.end);
920
+ const inserted = change.inserted.join('\n');
921
+ const syntheticChanges = [{
922
+ endOffset,
923
+ inserted,
924
+ startOffset
925
+ }];
926
+ return syntheticChanges;
826
927
  };
827
- const resolve = (id, response) => {
828
- const fn = get$c(id);
829
- if (!fn) {
830
- console.log(response);
831
- warn$1(`callback ${id} may already be disposed`);
928
+ const syncIncremental = (textDocumentId, changes) => {
929
+ number(textDocumentId);
930
+ array(changes);
931
+ const textDocument = getDocument(textDocumentId);
932
+ if (!textDocument) {
933
+ console.warn(`sync not possible, no matching textDocument with id ${textDocumentId}`);
832
934
  return;
833
935
  }
834
- fn(response);
835
- remove$5(id);
836
- };
837
- const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
838
- const getErrorType = prettyError => {
839
- if (prettyError && prettyError.type) {
840
- return prettyError.type;
841
- }
842
- if (prettyError && prettyError.constructor && prettyError.constructor.name) {
843
- return prettyError.constructor.name;
844
- }
845
- return undefined;
846
- };
847
- const isAlreadyStack = line => {
848
- return line.trim().startsWith('at ');
936
+ const syntheticChanges = getSyntheticChanges(textDocument, changes);
937
+ runListenersSafe(getWillChangeListeners(), textDocument, syntheticChanges);
938
+ const syntheticChange = syntheticChanges[0];
939
+ const oldText = textDocument.text;
940
+ const before = oldText.slice(0, syntheticChange.startOffset);
941
+ const after = oldText.slice(syntheticChange.endOffset);
942
+ textDocument.text = before + syntheticChange.inserted + after;
943
+ runListenersSafe(getDidChangeListeners(), textDocument, syntheticChanges);
849
944
  };
850
- const getStack = prettyError => {
851
- const stackString = prettyError.stack || '';
852
- const newLineIndex = stackString.indexOf('\n');
853
- if (newLineIndex !== -1 && !isAlreadyStack(stackString.slice(0, newLineIndex))) {
854
- return stackString.slice(newLineIndex + 1);
855
- }
856
- return stackString;
945
+ const get$a = textDocumentId => {
946
+ const textDocument = getDocument(textDocumentId);
947
+ return textDocument;
857
948
  };
858
- const getErrorProperty = (error, prettyError) => {
859
- if (error && error.code === E_COMMAND_NOT_FOUND) {
860
- return {
861
- code: MethodNotFound,
862
- data: error.stack,
863
- message: error.message
864
- };
865
- }
866
- return {
867
- code: Custom,
868
- data: {
869
- code: prettyError.code,
870
- codeFrame: prettyError.codeFrame,
871
- name: prettyError.name,
872
- stack: getStack(prettyError),
873
- type: getErrorType(prettyError)
874
- },
875
- message: prettyError.message
876
- };
949
+ const getText$2 = textDocument => {
950
+ return textDocument.text;
877
951
  };
878
- const create$1$1 = (id, error) => {
879
- return {
880
- error,
881
- id,
882
- jsonrpc: Two$1
952
+ const setLanguageId = (textDocumentId, languageId) => {
953
+ const newTextDocument = {
954
+ ...getDocument(textDocumentId),
955
+ languageId
883
956
  };
957
+ setDocument(textDocumentId, newTextDocument);
958
+ runListenersSafe(getDidOpenListeners(), newTextDocument);
884
959
  };
885
- const getErrorResponse = (id, error, preparePrettyError, logError) => {
886
- const prettyError = preparePrettyError(error);
887
- logError(error, prettyError);
888
- const errorProperty = getErrorProperty(error, prettyError);
889
- return create$1$1(id, errorProperty);
890
- };
891
- const create$j = (message, result) => {
892
- return {
893
- id: message.id,
894
- jsonrpc: Two$1,
895
- result: result ?? null
896
- };
960
+
961
+ const hasLegacyProvider = (getProvider, textDocumentId) => {
962
+ const textDocument = get$a(textDocumentId);
963
+ return Boolean(textDocument && getProvider(textDocument.languageId));
897
964
  };
898
- const getSuccessResponse = (message, result) => {
899
- const resultProperty = result ?? null;
900
- return create$j(message, resultProperty);
965
+ const executeLegacy = (executeProvider, textDocumentId, args) => {
966
+ return executeProvider(textDocumentId, ...args);
901
967
  };
902
- const getErrorResponseSimple = (id, error) => {
903
- return {
904
- error: {
905
- code: Custom,
906
- data: error,
907
- // @ts-ignore
908
- message: error.message
909
- },
910
- id,
911
- jsonrpc: Two$1
912
- };
968
+ const isUnavailableError$2 = error => {
969
+ return error instanceof Error && error.name === 'CommandNotFoundError' || error instanceof TypeError && error.message === "Cannot read properties of undefined (reading 'invoke')";
913
970
  };
914
- const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
971
+ const invoke$3 = async (method, ...args) => {
915
972
  try {
916
- const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
917
- return getSuccessResponse(message, result);
973
+ return await invoke$6(method, ...args);
918
974
  } catch (error) {
919
- if (ipc.canUseSimpleErrorResponse) {
920
- return getErrorResponseSimple(message.id, error);
975
+ if (isUnavailableError$2(error)) {
976
+ return {
977
+ found: false
978
+ };
921
979
  }
922
- return getErrorResponse(message.id, error, preparePrettyError, logError);
980
+ throw error;
923
981
  }
924
982
  };
925
- const defaultPreparePrettyError = error => {
926
- return error;
927
- };
928
- const defaultLogError = () => {
929
- // ignore
930
- };
931
- const defaultRequiresSocket = () => {
932
- return false;
933
- };
934
- const defaultResolve = resolve;
935
-
936
- // TODO maybe remove this in v6 or v7, only accept options object to simplify the code
937
- const normalizeParams = args => {
938
- if (args.length === 1) {
939
- const options = args[0];
983
+ const execute$2 = async (kind, methodName, textDocumentId, ...args) => {
984
+ const textDocument = get$a(textDocumentId);
985
+ if (!textDocument) {
940
986
  return {
941
- execute: options.execute,
942
- ipc: options.ipc,
943
- logError: options.logError || defaultLogError,
944
- message: options.message,
945
- preparePrettyError: options.preparePrettyError || defaultPreparePrettyError,
946
- requiresSocket: options.requiresSocket || defaultRequiresSocket,
947
- resolve: options.resolve || defaultResolve
987
+ found: false
948
988
  };
949
989
  }
950
- return {
951
- execute: args[2],
952
- ipc: args[0],
953
- logError: args[5],
954
- message: args[1],
955
- preparePrettyError: args[4],
956
- requiresSocket: args[6],
957
- resolve: args[3]
958
- };
990
+ return invoke$3('Extensions.executeLanguageProvider', kind, methodName, textDocument, ...args);
959
991
  };
960
- const handleJsonRpcMessage = async (...args) => {
961
- const options = normalizeParams(args);
962
- const {
963
- execute,
964
- ipc,
965
- logError,
966
- message,
967
- preparePrettyError,
968
- requiresSocket,
969
- resolve
970
- } = options;
971
- if ('id' in message) {
972
- if ('method' in message) {
973
- const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
974
- try {
975
- ipc.send(response);
976
- } catch (error) {
977
- const errorResponse = getErrorResponse(message.id, error, preparePrettyError, logError);
978
- ipc.send(errorResponse);
979
- }
980
- return;
981
- }
982
- resolve(message.id, message);
983
- return;
984
- }
985
- if ('method' in message) {
986
- await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
987
- return;
992
+ const executeWithTextDocument = (kind, methodName, textDocument, ...args) => {
993
+ return invoke$3('Extensions.executeLanguageProvider', kind, methodName, textDocument, ...args);
994
+ };
995
+ const executeOrganizeImports$1 = async textDocumentId => {
996
+ const textDocument = get$a(textDocumentId);
997
+ if (!textDocument) {
998
+ return {
999
+ found: false
1000
+ };
988
1001
  }
989
- throw new JsonRpcError('unexpected message');
1002
+ return invoke$3('Extensions.executeOrganizeImportsProvider', textDocument);
990
1003
  };
991
1004
 
992
- const Two = '2.0';
1005
+ class NonError extends Error {
1006
+ name = 'NonError';
1007
+ constructor(message) {
1008
+ super(message);
1009
+ }
1010
+ }
993
1011
 
994
- const create$i = (method, params) => {
995
- return {
996
- jsonrpc: Two,
997
- method,
998
- params
999
- };
1012
+ // ensureError based on https://github.com/sindresorhus/ensure-error/blob/main/index.ts (License MIT)
1013
+ const ensureError = input => {
1014
+ if (!(input instanceof Error)) {
1015
+ return new NonError(input);
1016
+ }
1017
+ return input;
1000
1018
  };
1001
1019
 
1002
- const create$h = (id, method, params) => {
1003
- const message = {
1004
- id,
1005
- jsonrpc: Two,
1006
- method,
1007
- params
1008
- };
1009
- return message;
1010
- };
1020
+ const E_NO_PROVIDER_FOUND = 'E_NO_PROVIDER_FOUND';
1021
+ const BABEL_PARSER_SYNTAX_ERROR = 'BABEL_PARSER_SYNTAX_ERROR';
1011
1022
 
1012
- let id$1 = 0;
1013
- const create$g = () => {
1014
- return ++id$1;
1015
- };
1023
+ class NoProviderFoundError extends Error {
1024
+ constructor(message) {
1025
+ super(message);
1026
+ // @ts-ignore
1027
+ this.code = E_NO_PROVIDER_FOUND;
1028
+ }
1029
+ }
1016
1030
 
1017
- const registerPromise = map => {
1018
- const id = create$g();
1019
- const {
1020
- promise,
1021
- resolve
1022
- } = Promise.withResolvers();
1023
- map[id] = resolve;
1024
- return {
1025
- id,
1026
- promise
1027
- };
1031
+ const getType$1 = value => {
1032
+ switch (typeof value) {
1033
+ case 'boolean':
1034
+ return 'boolean';
1035
+ case 'function':
1036
+ return 'function';
1037
+ case 'number':
1038
+ return 'number';
1039
+ case 'object':
1040
+ if (value === null) {
1041
+ return 'null';
1042
+ }
1043
+ if (Array.isArray(value)) {
1044
+ return 'array';
1045
+ }
1046
+ return 'object';
1047
+ case 'string':
1048
+ return 'string';
1049
+ case 'undefined':
1050
+ return 'undefined';
1051
+ default:
1052
+ return 'unknown';
1053
+ }
1028
1054
  };
1029
1055
 
1030
- const invokeHelper = async (callbacks, ipc, method, params, useSendAndTransfer) => {
1031
- const {
1032
- id,
1033
- promise
1034
- } = registerPromise(callbacks);
1035
- const message = create$h(id, method, params);
1036
- if (useSendAndTransfer && ipc.sendAndTransfer) {
1037
- ipc.sendAndTransfer(message);
1038
- } else {
1039
- ipc.send(message);
1056
+ const validateResultObject = (result, resultShape) => {
1057
+ if (!resultShape.properties) {
1058
+ return undefined;
1040
1059
  }
1041
- const responseMessage = await promise;
1042
- return unwrapJsonRpcResult(responseMessage);
1043
- };
1044
- const createRpc$1 = ipc => {
1045
- const callbacks = Object.create(null);
1046
- ipc._resolve = (id, response) => {
1047
- const fn = callbacks[id];
1048
- if (!fn) {
1049
- console.warn(`callback ${id} may already be disposed`);
1050
- return;
1051
- }
1052
- fn(response);
1053
- delete callbacks[id];
1054
- };
1055
- const rpc = {
1056
- async dispose() {
1057
- await ipc?.dispose();
1058
- },
1059
- invoke(method, ...params) {
1060
- return invokeHelper(callbacks, ipc, method, params, false);
1061
- },
1062
- invokeAndTransfer(method, ...params) {
1063
- return invokeHelper(callbacks, ipc, method, params, true);
1064
- },
1060
+ for (const [key, value] of Object.entries(resultShape.properties)) {
1065
1061
  // @ts-ignore
1066
- ipc,
1067
- /**
1068
- * @deprecated
1069
- */
1070
- send(method, ...params) {
1071
- const message = create$i(method, params);
1072
- ipc.send(message);
1062
+ const expectedType = value.type;
1063
+ const actualType = getType$1(result[key]);
1064
+ if (expectedType !== actualType) {
1065
+ return `item.${key} must be of type ${expectedType}`;
1073
1066
  }
1074
- };
1075
- return rpc;
1067
+ }
1068
+ return undefined;
1076
1069
  };
1077
-
1078
- const requiresSocket = () => {
1079
- return false;
1070
+ const validateResultArray = (result, resultShape) => {
1071
+ for (const item of result) {
1072
+ const actualType = getType$1(item);
1073
+ const expectedType = resultShape.items.type;
1074
+ if (actualType !== expectedType) {
1075
+ return `expected result to be of type ${expectedType} but was of type ${actualType}`;
1076
+ }
1077
+ }
1078
+ return undefined;
1080
1079
  };
1081
- const preparePrettyError = error => {
1082
- return error;
1080
+ const getPreviewObject = item => {
1081
+ return 'object';
1083
1082
  };
1084
- const logError = () => {
1085
- // handled by renderer worker
1083
+ const getPreviewArray = item => {
1084
+ if (item.length === 0) {
1085
+ return '[]';
1086
+ }
1087
+ return 'array';
1086
1088
  };
1087
- const handleMessage = event => {
1088
- const actualRequiresSocket = event?.target?.requiresSocket || requiresSocket;
1089
- const actualExecute = event?.target?.execute || execute$3;
1090
- return handleJsonRpcMessage(event.target, event.data, actualExecute, event.target._resolve, preparePrettyError, logError, actualRequiresSocket);
1089
+ const getPreviewString = item => {
1090
+ return `"${item}"`;
1091
1091
  };
1092
-
1093
- const handleIpc = ipc => {
1094
- if ('addEventListener' in ipc) {
1095
- ipc.addEventListener('message', handleMessage);
1096
- } else if ('on' in ipc) {
1097
- // deprecated
1098
- ipc.on('message', handleMessage);
1092
+ const getPreview = item => {
1093
+ const type = getType$1(item);
1094
+ switch (type) {
1095
+ case 'array':
1096
+ return getPreviewArray(item);
1097
+ case 'object':
1098
+ return getPreviewObject();
1099
+ case 'string':
1100
+ return getPreviewString(item);
1101
+ default:
1102
+ return `${item}`;
1099
1103
  }
1100
1104
  };
1101
-
1102
- const listen$1 = async (module, options) => {
1103
- const rawIpc = await module.listen(options);
1104
- if (module.signal) {
1105
- module.signal(rawIpc);
1105
+ const validate = (item, schema) => {
1106
+ if (typeof schema === 'function') {
1107
+ return schema(item);
1106
1108
  }
1107
- const ipc = module.wrap(rawIpc);
1108
- return ipc;
1109
+ const actualType = getType$1(item);
1110
+ const expectedType = schema.type;
1111
+ if (actualType !== expectedType) {
1112
+ if (schema.allowUndefined && (item === undefined || item === null)) {
1113
+ return item;
1114
+ }
1115
+ const preview = getPreview(item);
1116
+ return `item must be of type ${expectedType} but is ${preview}`;
1117
+ }
1118
+ switch (actualType) {
1119
+ case 'array':
1120
+ return validateResultArray(item, schema);
1121
+ case 'object':
1122
+ return validateResultObject(item, schema);
1123
+ }
1124
+ // TODO use json schema to validate result
1125
+ return undefined;
1109
1126
  };
1110
1127
 
1111
- const create$f = async ({
1112
- commandMap,
1113
- isMessagePortOpen = true,
1114
- messagePort
1115
- }) => {
1116
- // TODO create a commandMap per rpc instance
1117
- register$1(commandMap);
1118
- const rawIpc = await IpcParentWithMessagePort$1.create({
1119
- isMessagePortOpen,
1120
- messagePort
1128
+ const RE_UPPERCASE_LETTER = /[A-Z]/g;
1129
+ const RE_PROPERTY = /item\..*must be of type/;
1130
+ const spaceOut = camelCaseWord => {
1131
+ return camelCaseWord.replaceAll(RE_UPPERCASE_LETTER, (character, index) => {
1132
+ if (index === 0) {
1133
+ return character.toLowerCase();
1134
+ }
1135
+ return ' ' + character.toLowerCase();
1121
1136
  });
1122
- const ipc = IpcParentWithMessagePort$1.wrap(rawIpc);
1123
- handleIpc(ipc);
1124
- const rpc = createRpc$1(ipc);
1125
- messagePort.start();
1126
- return rpc;
1127
1137
  };
1128
-
1129
- const create$e = async ({
1130
- commandMap,
1131
- isMessagePortOpen,
1132
- send
1133
- }) => {
1134
- const {
1135
- port1,
1136
- port2
1137
- } = new MessageChannel();
1138
- await send(port1);
1139
- return create$f({
1140
- commandMap,
1141
- isMessagePortOpen,
1142
- messagePort: port2
1143
- });
1138
+ const toCamelCase = string => {
1139
+ return string[0].toLowerCase() + string.slice(1);
1144
1140
  };
1145
-
1146
- const createSharedLazyRpc = factory => {
1147
- let rpcPromise;
1148
- const getOrCreate = () => {
1149
- if (!rpcPromise) {
1150
- rpcPromise = factory();
1141
+ const improveValidationErrorPostMessage = (validationError, camelCaseName) => {
1142
+ if (validationError.startsWith('item must be of type')) {
1143
+ return validationError.replace('item', camelCaseName);
1144
+ }
1145
+ if (validationError.startsWith('expected result to be')) {
1146
+ return validationError.replace('result', `${camelCaseName} item`);
1147
+ }
1148
+ if (RE_PROPERTY.test(validationError)) {
1149
+ return validationError.replace('item', camelCaseName);
1150
+ }
1151
+ return validationError;
1152
+ };
1153
+ const improveValidationError = (name, validationError) => {
1154
+ const camelCaseName = toCamelCase(name);
1155
+ const spacedOutName = spaceOut(name);
1156
+ const pre = `invalid ${spacedOutName} result`;
1157
+ const post = improveValidationErrorPostMessage(validationError, camelCaseName);
1158
+ return pre + ': ' + post;
1159
+ };
1160
+ const registerMethod = ({
1161
+ context,
1162
+ methodName,
1163
+ name,
1164
+ providers,
1165
+ resultShape,
1166
+ returnUndefinedWhenNoProviderFound
1167
+ }) => {
1168
+ context[`execute${name}Provider`] = async function (textDocumentId, ...params) {
1169
+ try {
1170
+ const textDocument = get$a(textDocumentId);
1171
+ if (!textDocument) {
1172
+ throw new Error(`textDocument with id ${textDocumentId} not found`);
1173
+ }
1174
+ const provider = providers[textDocument.languageId];
1175
+ if (!provider) {
1176
+ if (returnUndefinedWhenNoProviderFound) {
1177
+ return undefined;
1178
+ }
1179
+ const spacedOutName = spaceOut(name);
1180
+ throw new NoProviderFoundError(`No ${spacedOutName} provider found for ${textDocument.languageId}`);
1181
+ }
1182
+ const result = await provider[methodName](textDocument, ...params);
1183
+ const error = validate(result, resultShape);
1184
+ if (error) {
1185
+ const improvedError = improveValidationError(name, error);
1186
+ throw new VError(improvedError);
1187
+ }
1188
+ return result;
1189
+ } catch (error) {
1190
+ const actualError = ensureError(error);
1191
+ const spacedOutName = spaceOut(name);
1192
+ if (actualError && actualError.message) {
1193
+ if (actualError.message === 'provider[methodName] is not a function') {
1194
+ const camelCaseName = toCamelCase(name);
1195
+ throw new VError(`Failed to execute ${spacedOutName} provider: VError: ${camelCaseName}Provider.${methodName} is not a function`);
1196
+ }
1197
+ throw new VError(actualError, `Failed to execute ${spacedOutName} provider`);
1198
+ }
1199
+ throw actualError;
1151
1200
  }
1152
- return rpcPromise;
1153
1201
  };
1154
- return {
1155
- async dispose() {
1156
- const rpc = await getOrCreate();
1157
- await rpc.dispose();
1202
+ };
1203
+ const create$i = ({
1204
+ additionalMethodNames = [],
1205
+ executeKey = '',
1206
+ name,
1207
+ resultShape,
1208
+ returnUndefinedWhenNoProviderFound = false
1209
+ }) => {
1210
+ const multipleResults = resultShape.type === 'array';
1211
+ const methodName = executeKey || (multipleResults ? `provide${name}s` : `provide${name}`);
1212
+ const providers = Object.create(null);
1213
+ const context = {
1214
+ [`register${name}Provider`](provider) {
1215
+ providers[provider.languageId] = provider;
1158
1216
  },
1159
- async invoke(method, ...params) {
1160
- const rpc = await getOrCreate();
1161
- return rpc.invoke(method, ...params);
1217
+ getProvider(languageId) {
1218
+ return providers[languageId];
1162
1219
  },
1163
- async invokeAndTransfer(method, ...params) {
1164
- const rpc = await getOrCreate();
1165
- return rpc.invokeAndTransfer(method, ...params);
1220
+ getProviders() {
1221
+ return Object.values(providers);
1166
1222
  },
1167
- async send(method, ...params) {
1168
- const rpc = await getOrCreate();
1169
- rpc.send(method, ...params);
1223
+ reset() {
1224
+ for (const key in providers) {
1225
+ delete providers[key];
1226
+ }
1170
1227
  }
1171
1228
  };
1172
- };
1173
-
1174
- const create$d = async ({
1175
- commandMap,
1176
- isMessagePortOpen,
1177
- send
1178
- }) => {
1179
- return createSharedLazyRpc(() => {
1180
- return create$e({
1181
- commandMap,
1182
- isMessagePortOpen,
1183
- send
1184
- });
1185
- });
1186
- };
1187
-
1188
- const create$c = async ({
1189
- commandMap,
1190
- webSocket
1191
- }) => {
1192
- // TODO create a commandMap per rpc instance
1193
- register$1(commandMap);
1194
- const rawIpc = await IpcParentWithWebSocket$1$1.create({
1195
- webSocket
1196
- });
1197
- const ipc = IpcParentWithWebSocket$1$1.wrap(rawIpc);
1198
- handleIpc(ipc);
1199
- const rpc = createRpc$1(ipc);
1200
- return rpc;
1201
- };
1202
-
1203
- const create$b = async ({
1204
- commandMap,
1205
- messagePort
1206
- }) => {
1207
- // TODO create a commandMap per rpc instance
1208
- register$1(commandMap);
1209
- const ipc = await listen$1(IpcChildWithMessagePort$1, {
1210
- port: messagePort
1229
+ registerMethod({
1230
+ context,
1231
+ methodName,
1232
+ name,
1233
+ providers,
1234
+ resultShape,
1235
+ returnUndefinedWhenNoProviderFound
1211
1236
  });
1212
- handleIpc(ipc);
1213
- const rpc = createRpc$1(ipc);
1214
- return rpc;
1237
+ for (const method of additionalMethodNames) {
1238
+ // @ts-ignore
1239
+ registerMethod({
1240
+ context,
1241
+ providers,
1242
+ ...method
1243
+ });
1244
+ }
1245
+ const finalContext = {
1246
+ ...context
1247
+ };
1248
+ return finalContext;
1215
1249
  };
1216
1250
 
1217
- const create$a = async ({
1218
- commandMap,
1219
- isMessagePortOpen,
1220
- messagePort
1221
- }) => {
1222
- // TODO create a commandMap per rpc instance
1223
- register$1(commandMap);
1224
- const rawIpc = await IpcParentWithMessagePort$1.create({
1225
- isMessagePortOpen,
1226
- messagePort
1227
- });
1228
- const ipc = IpcParentWithMessagePort$1.wrap(rawIpc);
1229
- handleIpc(ipc);
1230
- const rpc = createRpc$1(ipc);
1231
- return rpc;
1232
- };
1251
+ const Array$1 = 'array';
1252
+ const Boolean$1 = 'boolean';
1253
+ const Number = 'number';
1254
+ const Object$1 = 'object';
1255
+ const String$1 = 'string';
1233
1256
 
1234
- const create$9 = async ({
1235
- commandMap,
1236
- messagePort
1237
- }) => {
1238
- return create$f({
1239
- commandMap,
1240
- messagePort
1241
- });
1257
+ const {
1258
+ executeBraceCompletionProvider: executeLegacyBraceCompletionProvider,
1259
+ getProvider: getProvider$d,
1260
+ registerBraceCompletionProvider} = create$i({
1261
+ name: 'BraceCompletion',
1262
+ resultShape: {
1263
+ type: Boolean$1
1264
+ }
1265
+ });
1266
+ const executeBraceCompletionProvider = async (textDocumentId, ...args) => {
1267
+ if (hasLegacyProvider(getProvider$d, textDocumentId)) {
1268
+ return executeLegacy(executeLegacyBraceCompletionProvider, textDocumentId, args);
1269
+ }
1270
+ const isolated = await execute$2('brace completion', 'provideBraceCompletion', textDocumentId, ...args);
1271
+ return isolated.found ? isolated.result : executeLegacy(executeLegacyBraceCompletionProvider, textDocumentId, args);
1242
1272
  };
1243
1273
 
1244
- const create$8 = async ({
1245
- commandMap
1246
- }) => {
1247
- // TODO create a commandMap per rpc instance
1248
- register$1(commandMap);
1249
- const ipc = await listen$1(IpcChildWithModuleWorkerAndMessagePort$1);
1250
- handleIpc(ipc);
1251
- const rpc = createRpc$1(ipc);
1252
- return rpc;
1274
+ const {
1275
+ executeClosingTagProvider: executeLegacyClosingTagProvider,
1276
+ getProvider: getProvider$c,
1277
+ registerClosingTagProvider
1278
+ } = create$i({
1279
+ name: 'ClosingTag',
1280
+ resultShape: {
1281
+ allowUndefined: true,
1282
+ type: Object$1
1283
+ },
1284
+ returnUndefinedWhenNoProviderFound: true
1285
+ });
1286
+ const executeClosingTagProvider = async (textDocumentId, ...args) => {
1287
+ if (hasLegacyProvider(getProvider$c, textDocumentId)) {
1288
+ return executeLegacy(executeLegacyClosingTagProvider, textDocumentId, args);
1289
+ }
1290
+ const isolated = await execute$2('closing tag', 'provideClosingTag', textDocumentId, ...args);
1291
+ return isolated.found ? isolated.result : executeLegacy(executeLegacyClosingTagProvider, textDocumentId, args);
1253
1292
  };
1254
1293
 
1255
- const createMockRpc = ({
1256
- commandMap
1257
- }) => {
1258
- const invocations = [];
1259
- const invoke = (method, ...params) => {
1260
- invocations.push([method, ...params]);
1261
- const command = commandMap[method];
1262
- if (!command) {
1263
- throw new Error(`command ${method} not found`);
1294
+ const {
1295
+ executeCodeActionProvider: executeRegisteredCodeActionProvider,
1296
+ getProvider: getProvider$b,
1297
+ registerCodeActionProvider} = create$i({
1298
+ name: 'CodeAction',
1299
+ resultShape: {
1300
+ items: {
1301
+ type: Object$1
1302
+ },
1303
+ type: Array$1
1304
+ }
1305
+ });
1306
+ const executeCodeActionProvider = async (uid, ...args) => {
1307
+ if (!hasLegacyProvider(getProvider$b, uid)) {
1308
+ const isolated = await execute$2('code action', 'provideCodeActions', uid, ...args);
1309
+ if (isolated.found) {
1310
+ return isolated.result;
1264
1311
  }
1265
- return command(...params);
1266
- };
1267
- const mockRpc = {
1268
- invocations,
1269
- invoke,
1270
- invokeAndTransfer: invoke
1271
- };
1272
- return mockRpc;
1312
+ }
1313
+ const executeProvider = executeRegisteredCodeActionProvider;
1314
+ return executeProvider(uid, ...args);
1273
1315
  };
1274
-
1275
- const rpcs$2 = Object.create(null);
1276
- const set$e = (id, rpc) => {
1277
- rpcs$2[id] = rpc;
1316
+ const toSourceAction = (languageId, action) => {
1317
+ return {
1318
+ ...(action.edits && {
1319
+ edits: action.edits
1320
+ }),
1321
+ kind: action.kind,
1322
+ languageId,
1323
+ name: action.name
1324
+ };
1278
1325
  };
1279
- const get$b = id => {
1280
- return rpcs$2[id];
1326
+ const getSourceActions = async (uid, ...args) => {
1327
+ const textDocument = get$a(uid);
1328
+ if (!textDocument) {
1329
+ return [];
1330
+ }
1331
+ const actions = await executeCodeActionProvider(uid, ...args);
1332
+ return actions.map(action => toSourceAction(textDocument.languageId, action));
1281
1333
  };
1282
- const remove$4 = id => {
1283
- delete rpcs$2[id];
1334
+ const isOrganizeImports = action => {
1335
+ return action.kind === 'source.organizeImports';
1284
1336
  };
1285
1337
 
1286
- /* eslint-disable @typescript-eslint/explicit-function-return-type */
1287
- const create$7 = rpcId => {
1288
- return {
1289
- async dispose() {
1290
- const rpc = get$b(rpcId);
1291
- await rpc.dispose();
1292
- },
1293
- // @ts-ignore
1294
- invoke(method, ...params) {
1295
- const rpc = get$b(rpcId);
1296
- // @ts-ignore
1297
- return rpc.invoke(method, ...params);
1298
- },
1299
- // @ts-ignore
1300
- invokeAndTransfer(method, ...params) {
1301
- const rpc = get$b(rpcId);
1302
- // @ts-ignore
1303
- return rpc.invokeAndTransfer(method, ...params);
1304
- },
1305
- registerMockRpc(commandMap) {
1306
- const mockRpc = createMockRpc({
1307
- commandMap
1308
- });
1309
- set$e(rpcId, mockRpc);
1310
- // @ts-ignore
1311
- mockRpc[Symbol.dispose] = () => {
1312
- remove$4(rpcId);
1313
- };
1314
- // @ts-ignore
1315
- return mockRpc;
1316
- },
1317
- set(rpc) {
1318
- set$e(rpcId, rpc);
1338
+ // TODO handle case when multiple organize imports providers are registered
1339
+ const executeOrganizeImports = async uid => {
1340
+ if (!hasLegacyProvider(getProvider$b, uid)) {
1341
+ const isolated = await executeOrganizeImports$1(uid);
1342
+ if (isolated.found) {
1343
+ return isolated.result;
1319
1344
  }
1320
- };
1345
+ }
1346
+ const actions = await executeRegisteredCodeActionProvider(uid);
1347
+ // @ts-ignore
1348
+ if (!actions || actions.length === 0) {
1349
+ return [];
1350
+ }
1351
+ // @ts-ignore
1352
+ const organizeImportsAction = actions.find(isOrganizeImports);
1353
+ if (!organizeImportsAction) {
1354
+ return [];
1355
+ }
1356
+ const textDocument = get$a(uid);
1357
+ const edits = await organizeImportsAction.execute(textDocument);
1358
+ return edits;
1321
1359
  };
1322
1360
 
1323
- const Text = 12;
1324
- const Reference = 100;
1325
-
1326
- const DebugWorker$1 = 55;
1327
- const DialogWorker = 7014;
1328
- const ExtensionManagementWorker = 9006;
1329
- const RendererWorker$1 = 1;
1330
-
1331
1361
  const {
1332
- invoke: invoke$8} = create$7(DebugWorker$1);
1333
-
1334
- const DebugWorker = {
1335
- __proto__: null,
1336
- invoke: invoke$8
1362
+ executeCommentProvider: executeLegacyCommentProvider,
1363
+ getProvider: getProvider$a,
1364
+ registerCommentProvider
1365
+ } = create$i({
1366
+ name: 'Comment',
1367
+ resultShape() {
1368
+ return '';
1369
+ }
1370
+ });
1371
+ const executeCommentProvider = async (textDocumentId, ...args) => {
1372
+ if (hasLegacyProvider(getProvider$a, textDocumentId)) {
1373
+ return executeLegacy(executeLegacyCommentProvider, textDocumentId, args);
1374
+ }
1375
+ const isolated = await execute$2('comment', 'provideComment', textDocumentId, ...args);
1376
+ return isolated.found ? isolated.result : executeLegacy(executeLegacyCommentProvider, textDocumentId, args);
1337
1377
  };
1338
1378
 
1339
1379
  const {
1340
- invoke: invoke$7,
1341
- set: set$d
1342
- } = create$7(DialogWorker);
1343
-
1344
- const {
1345
- invoke: invoke$6,
1346
- invokeAndTransfer: invokeAndTransfer$3,
1347
- set: set$c
1348
- } = create$7(ExtensionManagementWorker);
1380
+ executeCompletionProvider,
1381
+ executeresolveCompletionItemProvider,
1382
+ getProviders: getProviders$3,
1383
+ registerCompletionProvider} = create$i({
1384
+ additionalMethodNames: [
1385
+ // @ts-ignore
1386
+ {
1387
+ methodName: 'resolveCompletionItem',
1388
+ name: 'resolveCompletionItem',
1389
+ resultShape: {
1390
+ allowUndefined: true,
1391
+ type: Object$1
1392
+ }
1393
+ }],
1394
+ name: 'Completion',
1395
+ resultShape: {
1396
+ items: {
1397
+ type: Object$1
1398
+ },
1399
+ type: Array$1
1400
+ }
1401
+ });
1402
+ const getRegisteredCompletionProviderIds$1 = () => {
1403
+ return getProviders$3().map(provider => provider.id);
1404
+ };
1349
1405
 
1350
- const {
1351
- set: set$b
1352
- } = create$7(7013);
1406
+ const state$a = {
1407
+ configuration: Object.create(null)
1408
+ };
1409
+ const getConfiguration = key => {
1410
+ return state$a.configuration[key] ?? '';
1411
+ };
1412
+ const setConfigurations = preferences => {
1413
+ state$a.configuration = preferences;
1414
+ };
1353
1415
 
1354
1416
  const {
1355
- invoke: invoke$5,
1356
- set: set$a
1357
- } = create$7(10_000);
1417
+ invoke: invoke$2
1418
+ } = DebugWorker;
1358
1419
 
1359
- const {
1360
- invoke: invoke$4,
1361
- invokeAndTransfer: invokeAndTransfer$2} = create$7(RendererWorker$1);
1362
- const sendMessagePortToDialogWorker = async port => {
1363
- const command = 'HandleMessagePort.handleMessagePort';
1364
- await invokeAndTransfer$2('SendMessagePortToExtensionHostWorker.sendMessagePortToDialogWorker', port, command);
1420
+ const state$9 = {
1421
+ debugProviderMap: Object.create(null)
1365
1422
  };
1366
- const sendMessagePortToFileSearchWorker = async (port, rpcId = 0) => {
1367
- const command = 'QuickPick.handleMessagePort';
1368
- await invokeAndTransfer$2('SendMessagePortToExtensionHostWorker.sendMessagePortToFileSearchWorker', port, command, rpcId);
1423
+ const getDebugProvider = id => {
1424
+ const provider = state$9.debugProviderMap[id];
1425
+ if (!provider) {
1426
+ // @ts-ignore
1427
+ throw new VError(`no debug provider "${id}" found`);
1428
+ }
1429
+ return provider;
1369
1430
  };
1370
- const sendMessagePortToQuickPickWorker = async (port, rpcId = 0) => {
1371
- const command = 'QuickPick.handleMessagePort';
1372
- await invokeAndTransfer$2('SendMessagePortToExtensionHostWorker.sendMessagePortToQuickPickWorker', port, command, rpcId);
1431
+ const registerDebugProvider = debugProvider => {
1432
+ if (!debugProvider.id) {
1433
+ throw new Error('Failed to register debug system provider: missing id');
1434
+ }
1435
+ state$9.debugProviderMap[debugProvider.id] = debugProvider;
1373
1436
  };
1374
- const sendMessagePortToIframeWorker = async (port, rpcId) => {
1375
- const command = 'Iframes.handleMessagePort';
1376
- await invokeAndTransfer$2('SendMessagePortToExtensionHostWorker.sendMessagePortToIframeWorker', port, command, rpcId);
1437
+ const handlePaused = async params => {
1438
+ // @ts-ignore
1439
+ await invoke$2('Debug.paused', params);
1377
1440
  };
1378
- const sendMessagePortToExtensionManagementWorker = async (port, rpcId) => {
1379
- const command = 'Extensions.handleMessagePort';
1380
- await invokeAndTransfer$2('SendMessagePortToExtensionHostWorker.sendMessagePortToExtensionManagementWorker', port, command, rpcId);
1441
+ const handleResumed = async () => {
1442
+ // @ts-ignore
1443
+ await invoke$2('Debug.resumed');
1381
1444
  };
1382
-
1383
- const state$c = {
1384
- commands: Object.create(null)
1445
+ const handleScriptParsed = async parsedScript => {
1446
+ // @ts-ignore
1447
+ await invoke$2('Debug.scriptParsed', parsedScript);
1385
1448
  };
1386
- const getCommandDisplay = command => {
1387
- if (command && command.id && typeof command.id === 'string') {
1388
- return ` ${command.id}`;
1389
- }
1390
- return '';
1449
+ const handleChange = async params => {
1450
+ object(params);
1451
+ // @ts-ignore
1452
+ await invoke$2('Debug.handleChange', params);
1391
1453
  };
1392
- const registerCommand = command => {
1454
+ const start = async (protocol, path) => {
1393
1455
  try {
1394
- if (!command) {
1395
- if (command === null) {
1396
- throw new Error(`command is null`);
1397
- }
1398
- throw new Error('command is not defined');
1399
- }
1400
- if (!command.id) {
1401
- throw new Error('command is missing id');
1402
- }
1403
- if (!command.execute) {
1404
- throw new Error('command is missing execute function');
1405
- }
1406
- if (command.id in state$c.commands) {
1407
- throw new Error(`command cannot be registered multiple times`);
1408
- }
1409
- state$c.commands[command.id] = command;
1456
+ const provider = getDebugProvider(protocol);
1457
+ const emitter = {
1458
+ handleChange,
1459
+ handlePaused,
1460
+ handleResumed,
1461
+ handleScriptParsed
1462
+ };
1463
+ await provider.start(emitter, path);
1410
1464
  } catch (error) {
1411
- const commandDisplayId = getCommandDisplay(command);
1412
- throw new VError(error, `Failed to register command${commandDisplayId}`);
1465
+ throw new VError(error, 'Failed to execute debug provider');
1413
1466
  }
1414
1467
  };
1415
- const executeCommand$2 = async (id, ...args) => {
1468
+ const listProcesses = async (protocol, path) => {
1416
1469
  try {
1417
- const command = state$c.commands[id];
1418
- if (!command) {
1419
- throw new Error(`command ${id} not found`);
1420
- }
1421
- const results = await command.execute(...args);
1422
- return results;
1470
+ const provider = getDebugProvider(protocol);
1471
+ const processes = await provider.listProcesses(path);
1472
+ array(processes);
1473
+ return processes;
1423
1474
  } catch (error) {
1424
- // @ts-ignore
1425
- if (error && error.isExpected) {
1426
- throw error;
1427
- }
1428
- throw new VError(error, 'Failed to execute command');
1475
+ throw new VError(error, 'Failed to execute debug provider');
1429
1476
  }
1430
1477
  };
1431
- const hasCommand = id => {
1432
- return id in state$c.commands;
1433
- };
1434
- const getRegisteredCommandIds$1 = () => {
1435
- return Object.values(state$c.commands).map(command => command.id);
1478
+ const resume = async protocol => {
1479
+ try {
1480
+ const provider = getDebugProvider(protocol);
1481
+ return await provider.resume();
1482
+ } catch (error) {
1483
+ throw new VError(error, 'Failed to execute debug provider');
1484
+ }
1436
1485
  };
1437
-
1438
- const isCommandNotFoundError = error => {
1439
- return error instanceof Error && error.name === 'CommandNotFoundError';
1486
+ const pause = async protocol => {
1487
+ try {
1488
+ const provider = getDebugProvider(protocol);
1489
+ return await provider.pause();
1490
+ } catch (error) {
1491
+ throw new VError(error, 'Failed to execute debug provider');
1492
+ }
1440
1493
  };
1441
- const executeCommand$1 = async (id, ...args) => {
1494
+ const getScriptSource = async (protocol, scriptId) => {
1442
1495
  try {
1443
- return await invoke$6('Extensions.executeCommand', id, ...args);
1496
+ const provider = getDebugProvider(protocol);
1497
+ return await provider.getScriptSource(scriptId);
1444
1498
  } catch (error) {
1445
- if (!isCommandNotFoundError(error)) {
1446
- throw error;
1447
- }
1448
- if (hasCommand(id)) {
1449
- return executeCommand$2(id, ...args);
1450
- }
1451
- return invoke$4(id, ...args);
1499
+ throw new VError(error, 'Failed to execute debug provider');
1452
1500
  }
1453
1501
  };
1454
1502
 
1455
- class DepecratedError extends Error {
1456
- constructor(message) {
1457
- super(message);
1458
- this.name = 'DeprecatedError';
1459
- }
1460
- }
1503
+ // TODO create direct connection from debug worker to extension, not needing extension host worker apis
1461
1504
 
1462
- const getJson$1 = async url => {
1463
- throw new DepecratedError(`vscode.getJson is deprecated, use createNodeRpc instead`);
1505
+ const getStatus = async protocol => {
1506
+ try {
1507
+ const provider = getDebugProvider(protocol);
1508
+ return await provider.getStatus();
1509
+ } catch (error) {
1510
+ throw new VError(error, 'Failed to execute debug provider');
1511
+ }
1464
1512
  };
1465
-
1466
- const state$b = {
1467
- /** @type{any[]} */
1468
- onDidChangeTextDocumentListeners: [],
1469
- /** @type{any[]} */
1470
- onDidSaveTextDocumentListeners: [],
1471
- /** @type{any[]} */
1472
- onWillChangeEditorListeners: [],
1473
- textDocuments: Object.create(null)
1513
+ const getCallStack = async protocol => {
1514
+ try {
1515
+ const provider = getDebugProvider(protocol);
1516
+ return await provider.getCallStack();
1517
+ } catch (error) {
1518
+ throw new VError(error, 'Failed to execute debug provider');
1519
+ }
1474
1520
  };
1475
- const setDocument = (textDocumentId, textDocument) => {
1476
- state$b.textDocuments[textDocumentId] = textDocument;
1521
+ const getScopeChain = async protocol => {
1522
+ try {
1523
+ const provider = getDebugProvider(protocol);
1524
+ return await provider.getScopeChain();
1525
+ } catch (error) {
1526
+ throw new VError(error, 'Failed to execute debug provider');
1527
+ }
1477
1528
  };
1478
- const getDidOpenListeners = () => {
1479
- return state$b.onDidSaveTextDocumentListeners;
1529
+ const getScripts = async protocol => {
1530
+ try {
1531
+ const provider = getDebugProvider(protocol);
1532
+ return await provider.getScripts();
1533
+ } catch (error) {
1534
+ throw new VError(error, 'Failed to execute debug provider');
1535
+ }
1480
1536
  };
1481
- const getWillChangeListeners = () => {
1482
- return state$b.onWillChangeEditorListeners;
1537
+
1538
+ // eslint-disable-next-line sonarjs/no-identical-functions
1539
+ const getPausedStatus = async protocol => {
1540
+ try {
1541
+ const provider = getDebugProvider(protocol);
1542
+ return await provider.getStatus();
1543
+ } catch (error) {
1544
+ throw new VError(error, 'Failed to execute debug provider');
1545
+ }
1483
1546
  };
1484
- const getDidChangeListeners = () => {
1485
- return state$b.onDidChangeTextDocumentListeners;
1547
+ const stepInto = async protocol => {
1548
+ try {
1549
+ const provider = getDebugProvider(protocol);
1550
+ return await provider.stepInto();
1551
+ } catch (error) {
1552
+ throw new VError(error, 'Failed to execute debug provider');
1553
+ }
1486
1554
  };
1487
- const getDocument = textDocumentId => {
1488
- return state$b.textDocuments[textDocumentId];
1555
+ const stepOut = async protocol => {
1556
+ try {
1557
+ const provider = getDebugProvider(protocol);
1558
+ return await provider.stepOut();
1559
+ } catch (error) {
1560
+ throw new VError(error, 'Failed to execute debug provider');
1561
+ }
1489
1562
  };
1490
-
1491
- const getOffset$1 = (textDocument, position) => {
1492
- let offset = 0;
1493
- let rowIndex = 0;
1494
- while (rowIndex++ < position.rowIndex) {
1495
- const newLineIndex = textDocument.text.indexOf('\n', offset);
1496
- offset = newLineIndex + 1;
1563
+ const stepOver = async protocol => {
1564
+ try {
1565
+ const provider = getDebugProvider(protocol);
1566
+ return await provider.stepOver();
1567
+ } catch (error) {
1568
+ throw new VError(error, 'Failed to execute debug provider');
1497
1569
  }
1498
- offset += position.columnIndex;
1499
- return offset;
1500
1570
  };
1501
-
1502
- // const toOffsetBasedEdit = (textDocument, documentEdit) => {
1503
- // switch (documentEdit.type) {
1504
- // case /* singleLineEdit */ 1: {
1505
- // const offset = getOffset(textDocument, documentEdit)
1506
- // return {
1507
- // offset,
1508
- // inserted: documentEdit.inserted,
1509
- // deleted: documentEdit.deleted,
1510
- // // type: /* singleLineEdit */ 1
1511
- // }
1512
- // }
1513
- // case /* splice */ 2:
1514
- // const offset = getOffset(textDocument, {
1515
- // rowIndex: documentEdit.rowIndex,
1516
- // columnIndex: textDocument.lines[documentEdit.rowIndex - 1].length,
1517
- // })
1518
- // const inserted = '\n' + documentEdit.newLines.join('\n')
1519
- // return {
1520
- // offset,
1521
- // inserted,
1522
- // deleted: 0 /* TODO */,
1523
- // }
1524
- // }
1525
- // }
1526
-
1527
- // TODO incremental edits, don't send full text
1528
- // export const applyEdit = (id, text, edits) => {
1529
- // const textDocument = get(id)
1530
- // textDocument.lines = text.split('\n')
1531
- // const offsetBasedEdits = edits.map((edit) =>
1532
- // toOffsetBasedEdit(textDocument, edit)
1533
- // )
1534
- // for (const listener of state.onDidChangeTextDocumentListeners) {
1535
- // // TODO avoid extra object allocation
1536
- // listener(textDocument, offsetBasedEdits)
1537
- // }
1538
- // }
1539
-
1540
- // TODO data oriented vs object oriented
1541
- // data -> simpler, exposes internals, sometimes weird/long (vscode.TextDocument.getText(textDocument))
1542
- // object oriented -> hides internals, banana problem (textDocument.getText())
1543
-
1544
- // TODO send to shared process, which sends it to renderer worker
1545
- // renderer worker sends back the edit
1546
- // export const applyEdit2 = (textDocument, edit) => {
1547
- // if (VALIDATION_ENABLED) {
1548
- // assert(typeof textDocument === 'object')
1549
- // assert(textDocument !== null)
1550
- // assert(typeof textDocument.id === 'number')
1551
- // assert(textDocument.id > 0)
1552
- // assert(typeof textDocument.getText === 'function')
1553
- // assert(typeof edit === 'object')
1554
- // assert(typeof edit.offset === 'number')
1555
- // assert(typeof edit.inserted === 'string')
1556
- // assert(typeof edit.deleted === 'number')
1557
- // }
1558
-
1559
- // let rowIndex = 0
1560
- // let offset = 0
1561
- // const lines = textDocument.getText().split('\n')
1562
- // while (offset < edit.offset) {
1563
- // offset += lines[rowIndex++].length + 1
1564
- // }
1565
- // rowIndex--
1566
- // offset -= lines[rowIndex].length + 1
1567
- // const edit2 = {
1568
- // rowIndex,
1569
- // inserted: edit.inserted,
1570
- // deleted: edit.deleted,
1571
- // columnIndex: edit.offset - offset + edit.deleted,
1572
- // type: 1,
1573
- // }
1574
-
1575
- // // // TODO should be invoke and return boolean whether edit was applied or not
1576
- // SharedProcess.send({
1577
- // event: 'TextDocument.applyEdit',
1578
- // args: [/* id */ textDocument.id, /* edits */ edit2],
1579
- // })
1580
- // }
1581
-
1582
- // export const create = (textDocumentId, languageId, content) => {
1583
- // const textDocument = {
1584
- // languageId,
1585
- // lines: content.split('\n'),
1586
- // }
1587
- // state.textDocuments[textDocumentId] = textDocument
1588
- // }
1589
-
1590
- // const createTextDocument = (uri, languageId, text) => {
1591
- // if (VALIDATION_ENABLED) {
1592
- // assert(typeof uri === 'string')
1593
- // assert(typeof languageId === 'string')
1594
- // assert(typeof text === 'string')
1595
- // }
1596
- // const state = {
1597
- // /** @internal */
1598
- // lines: text.split('\n'),
1599
- // uri,
1600
- // languageId,
1601
- // getText() {
1602
- // return state.lines.join('\n')
1603
- // },
1604
- // }
1605
- // return state
1606
- // }
1607
-
1608
- // export const sync = (documentId, languageId, text) => {
1609
- // const textDocument = get(documentId)
1610
- // if (!textDocument) {
1611
- // console.warn(`textDocument is undefined ${languageId}`)
1612
- // return
1613
- // }
1614
- // textDocument.languageId = languageId
1615
- // textDocument.lines = text.split('\n')
1616
- // // console.log('sync', JSON.stringify(text))
1617
- // }
1618
-
1619
- const runListenerSafe = async (listener, ...args) => {
1571
+ const setPauseOnException = async (protocol, value) => {
1620
1572
  try {
1621
- await listener(...args);
1573
+ const provider = getDebugProvider(protocol);
1574
+ return await provider.setPauseOnExceptions(value);
1622
1575
  } catch (error) {
1623
- // @ts-ignore
1624
- if (error && error.message) {
1625
- // @ts-ignore
1626
- error.message = 'Failed to run open listener: ' + error.message;
1627
- }
1628
- console.error(error);
1576
+ throw new VError(error, 'Failed to execute debug provider');
1629
1577
  }
1630
1578
  };
1631
- const runListenersSafe = (listeners, ...args) => {
1632
- for (const listener of listeners) {
1633
- runListenerSafe(listener, ...args);
1579
+ const getProperties = async (protocol, objectId) => {
1580
+ try {
1581
+ const provider = getDebugProvider(protocol);
1582
+ return await provider.getProperties(objectId);
1583
+ } catch (error) {
1584
+ throw new VError(error, 'Failed to execute debug provider');
1634
1585
  }
1635
1586
  };
1636
- const syncFull = (uri, textDocumentId, languageId, text) => {
1637
- const textDocument = {
1638
- documentId: textDocumentId,
1639
- languageId,
1640
- text,
1641
- uri
1642
- };
1643
- setDocument(textDocumentId, textDocument);
1644
- runListenersSafe(getDidOpenListeners(), textDocument);
1587
+ const evaluate = async (protocol, expression, callFrameId) => {
1588
+ try {
1589
+ const provider = getDebugProvider(protocol);
1590
+ return await provider.evaluate(expression, callFrameId);
1591
+ } catch (error) {
1592
+ throw new VError(error, 'Failed to execute debug provider');
1593
+ }
1645
1594
  };
1646
- const getSyntheticChanges = (textDocument, changes) => {
1647
- // console.log({ textDocument, changes })
1648
- object(textDocument);
1649
- array(changes);
1650
- const change = changes[0];
1651
- const startOffset = getOffset$1(textDocument, change.start);
1652
- const endOffset = getOffset$1(textDocument, change.end);
1653
- const inserted = change.inserted.join('\n');
1654
- const syntheticChanges = [{
1655
- endOffset,
1656
- inserted,
1657
- startOffset
1658
- }];
1659
- return syntheticChanges;
1595
+ const setPauseOnExceptions = async (protocol, value) => {
1596
+ try {
1597
+ const provider = getDebugProvider(protocol);
1598
+ return await provider.setPauseOnExceptions(value);
1599
+ } catch (error) {
1600
+ throw new VError(error, 'Failed to execute setPauseOnExceptions');
1601
+ }
1660
1602
  };
1661
- const syncIncremental = (textDocumentId, changes) => {
1662
- number(textDocumentId);
1663
- array(changes);
1664
- const textDocument = getDocument(textDocumentId);
1665
- if (!textDocument) {
1666
- console.warn(`sync not possible, no matching textDocument with id ${textDocumentId}`);
1667
- return;
1603
+
1604
+ const {
1605
+ executeDefinitionProvider: executeLegacyDefinitionProvider,
1606
+ getProvider: getProvider$9,
1607
+ registerDefinitionProvider} = create$i({
1608
+ name: 'Definition',
1609
+ resultShape: {
1610
+ allowUndefined: true,
1611
+ properties: {
1612
+ endOffset: {
1613
+ type: Number
1614
+ },
1615
+ startOffset: {
1616
+ type: Number
1617
+ },
1618
+ uri: {
1619
+ type: String$1
1620
+ }
1621
+ },
1622
+ type: Object$1
1623
+ }
1624
+ });
1625
+ const executeDefinitionProvider = async (textDocumentId, ...args) => {
1626
+ if (hasLegacyProvider(getProvider$9, textDocumentId)) {
1627
+ return executeLegacy(executeLegacyDefinitionProvider, textDocumentId, args);
1668
1628
  }
1669
- const syntheticChanges = getSyntheticChanges(textDocument, changes);
1670
- runListenersSafe(getWillChangeListeners(), textDocument, syntheticChanges);
1671
- const syntheticChange = syntheticChanges[0];
1672
- const oldText = textDocument.text;
1673
- const before = oldText.slice(0, syntheticChange.startOffset);
1674
- const after = oldText.slice(syntheticChange.endOffset);
1675
- textDocument.text = before + syntheticChange.inserted + after;
1676
- runListenersSafe(getDidChangeListeners(), textDocument, syntheticChanges);
1629
+ const isolated = await execute$2('definition', 'provideDefinition', textDocumentId, ...args);
1630
+ return isolated.found ? isolated.result : executeLegacy(executeLegacyDefinitionProvider, textDocumentId, args);
1677
1631
  };
1678
- const get$a = textDocumentId => {
1679
- const textDocument = getDocument(textDocumentId);
1680
- return textDocument;
1632
+
1633
+ const {
1634
+ executeDiagnosticProvider,
1635
+ getProviders: getProviders$2,
1636
+ registerDiagnosticProvider} = create$i({
1637
+ name: 'Diagnostic',
1638
+ resultShape: {
1639
+ items: {
1640
+ type: Object$1
1641
+ },
1642
+ type: Array$1
1643
+ }
1644
+ });
1645
+ const getRegisteredDiagnosticProviderIds$1 = () => {
1646
+ return getProviders$2().map(provider => provider.id);
1681
1647
  };
1682
- const getText$2 = textDocument => {
1683
- return textDocument.text;
1648
+
1649
+ const RendererWorker = 1;
1650
+
1651
+ const invoke$1 = (method, ...params) => {
1652
+ const rpc = get$b(RendererWorker);
1653
+ return rpc.invoke(method, ...params);
1684
1654
  };
1685
- const setLanguageId = (textDocumentId, languageId) => {
1686
- const newTextDocument = {
1687
- ...getDocument(textDocumentId),
1688
- languageId
1689
- };
1690
- setDocument(textDocumentId, newTextDocument);
1691
- runListenersSafe(getDidOpenListeners(), newTextDocument);
1655
+ const invokeAndTransfer$1 = (method, ...params) => {
1656
+ const rpc = get$b(RendererWorker);
1657
+ return rpc.invokeAndTransfer(method, ...params);
1692
1658
  };
1693
1659
 
1694
- const hasLegacyProvider = (getProvider, textDocumentId) => {
1695
- const textDocument = get$a(textDocumentId);
1696
- return Boolean(textDocument && getProvider(textDocument.languageId));
1660
+ const showInformationMessage = message => {
1661
+ string(message);
1662
+ const result = invoke$1('ExtensionHostDialog.showInformationMessage', message);
1663
+ return result;
1697
1664
  };
1698
- const executeLegacy = (executeProvider, textDocumentId, args) => {
1699
- return executeProvider(textDocumentId, ...args);
1665
+
1666
+ const env = {};
1667
+
1668
+ const exec = async (command, args, options) => {
1669
+ throw new DepecratedError(`vscode.exec is deprecated, use createNodeRpc instead`);
1700
1670
  };
1701
- const isUnavailableError$2 = error => {
1671
+
1672
+ const isUnavailableError$1 = error => {
1702
1673
  return error instanceof Error && error.name === 'CommandNotFoundError' || error instanceof TypeError && error.message === "Cannot read properties of undefined (reading 'invoke')";
1703
1674
  };
1704
- const invoke$3 = async (method, ...args) => {
1675
+ const executeMethod = async (method, providerId, ...args) => {
1705
1676
  try {
1706
- return await invoke$6(method, ...args);
1677
+ return await invoke$6(method, providerId, ...args);
1707
1678
  } catch (error) {
1708
- if (isUnavailableError$2(error)) {
1679
+ if (isUnavailableError$1(error)) {
1709
1680
  return {
1710
1681
  found: false
1711
1682
  };
@@ -1713,322 +1684,274 @@ const invoke$3 = async (method, ...args) => {
1713
1684
  throw error;
1714
1685
  }
1715
1686
  };
1716
- const execute$2 = async (kind, methodName, textDocumentId, ...args) => {
1717
- const textDocument = get$a(textDocumentId);
1718
- if (!textDocument) {
1719
- return {
1720
- found: false
1721
- };
1722
- }
1723
- return invoke$3('Extensions.executeLanguageProvider', kind, methodName, textDocument, ...args);
1687
+ const execute$1 = (providerId, uri) => {
1688
+ return executeMethod('Extensions.executeFileSystemProviderReadFile', providerId, uri);
1724
1689
  };
1725
- const executeWithTextDocument = (kind, methodName, textDocument, ...args) => {
1726
- return invoke$3('Extensions.executeLanguageProvider', kind, methodName, textDocument, ...args);
1690
+ const getPathSeparator$1 = providerId => {
1691
+ return executeMethod('Extensions.executeFileSystemProviderGetPathSeparator', providerId);
1727
1692
  };
1728
- const executeOrganizeImports$1 = async textDocumentId => {
1729
- const textDocument = get$a(textDocumentId);
1730
- if (!textDocument) {
1731
- return {
1732
- found: false
1733
- };
1734
- }
1735
- return invoke$3('Extensions.executeOrganizeImportsProvider', textDocument);
1693
+ const isReadonly$1 = providerId => {
1694
+ return executeMethod('Extensions.executeFileSystemProviderIsReadonly', providerId);
1736
1695
  };
1737
-
1738
- class NonError extends Error {
1739
- name = 'NonError';
1740
- constructor(message) {
1741
- super(message);
1742
- }
1743
- }
1744
-
1745
- // ensureError based on https://github.com/sindresorhus/ensure-error/blob/main/index.ts (License MIT)
1746
- const ensureError = input => {
1747
- if (!(input instanceof Error)) {
1748
- return new NonError(input);
1749
- }
1750
- return input;
1696
+ const readDirWithFileTypes$3 = (providerId, uri) => {
1697
+ return executeMethod('Extensions.executeFileSystemProviderReadDirWithFileTypes', providerId, uri);
1751
1698
  };
1752
1699
 
1753
- const E_NO_PROVIDER_FOUND = 'E_NO_PROVIDER_FOUND';
1754
- const BABEL_PARSER_SYNTAX_ERROR = 'BABEL_PARSER_SYNTAX_ERROR';
1755
-
1756
- class NoProviderFoundError extends Error {
1757
- constructor(message) {
1758
- super(message);
1700
+ const fileSystemProviderMap = Object.create(null);
1701
+ const get$9 = protocol => {
1702
+ const provider = fileSystemProviderMap[protocol];
1703
+ if (!provider) {
1759
1704
  // @ts-ignore
1760
- this.code = E_NO_PROVIDER_FOUND;
1705
+ throw new VError(`no file system provider for protocol "${protocol}" found`);
1761
1706
  }
1762
- }
1763
-
1764
- const getType$1 = value => {
1765
- switch (typeof value) {
1766
- case 'boolean':
1767
- return 'boolean';
1768
- case 'function':
1769
- return 'function';
1770
- case 'number':
1771
- return 'number';
1772
- case 'object':
1773
- if (value === null) {
1774
- return 'null';
1775
- }
1776
- if (Array.isArray(value)) {
1777
- return 'array';
1778
- }
1779
- return 'object';
1780
- case 'string':
1781
- return 'string';
1782
- case 'undefined':
1783
- return 'undefined';
1784
- default:
1785
- return 'unknown';
1707
+ return provider;
1708
+ };
1709
+ const getOptional = protocol => {
1710
+ return fileSystemProviderMap[protocol];
1711
+ };
1712
+ const set$9 = (id, provider) => {
1713
+ if (!id) {
1714
+ throw new Error('Failed to register file system provider: missing id');
1786
1715
  }
1716
+ fileSystemProviderMap[id] = provider;
1787
1717
  };
1788
1718
 
1789
- const validateResultObject = (result, resultShape) => {
1790
- if (!resultShape.properties) {
1791
- return undefined;
1792
- }
1793
- for (const [key, value] of Object.entries(resultShape.properties)) {
1794
- // @ts-ignore
1795
- const expectedType = value.type;
1796
- const actualType = getType$1(result[key]);
1797
- if (expectedType !== actualType) {
1798
- return `item.${key} must be of type ${expectedType}`;
1799
- }
1719
+ const registerFileSystemProvider = fileSystemProvider => {
1720
+ if (!fileSystemProvider.id) {
1721
+ throw new Error('Failed to register file system provider: missing id');
1800
1722
  }
1801
- return undefined;
1723
+ set$9(fileSystemProvider.id, fileSystemProvider);
1802
1724
  };
1803
- const validateResultArray = (result, resultShape) => {
1804
- for (const item of result) {
1805
- const actualType = getType$1(item);
1806
- const expectedType = resultShape.items.type;
1807
- if (actualType !== expectedType) {
1808
- return `expected result to be of type ${expectedType} but was of type ${actualType}`;
1725
+ const readDirWithFileTypes$2 = async (protocol, path) => {
1726
+ try {
1727
+ const provider = getOptional(protocol);
1728
+ if (provider) {
1729
+ return await provider.readDirWithFileTypes(path);
1730
+ }
1731
+ const isolated = await readDirWithFileTypes$3(protocol, path);
1732
+ if (isolated.found) {
1733
+ return isolated.result;
1809
1734
  }
1735
+ return await get$9(protocol).readDirWithFileTypes(path);
1736
+ } catch (error) {
1737
+ throw new VError(error, 'Failed to execute file system provider');
1810
1738
  }
1811
- return undefined;
1812
1739
  };
1813
- const getPreviewObject = item => {
1814
- return 'object';
1815
- };
1816
- const getPreviewArray = item => {
1817
- if (item.length === 0) {
1818
- return '[]';
1740
+ const readFile$2 = async (protocol, path) => {
1741
+ try {
1742
+ const provider = getOptional(protocol);
1743
+ if (provider) {
1744
+ return await provider.readFile(path);
1745
+ }
1746
+ const isolated = await execute$1(protocol, path);
1747
+ if (isolated.found) {
1748
+ return isolated.result;
1749
+ }
1750
+ return await get$9(protocol).readFile(path);
1751
+ } catch (error) {
1752
+ throw new VError(error, 'Failed to execute file system provider');
1819
1753
  }
1820
- return 'array';
1821
1754
  };
1822
- const getPreviewString = item => {
1823
- return `"${item}"`;
1824
- };
1825
- const getPreview = item => {
1826
- const type = getType$1(item);
1827
- switch (type) {
1828
- case 'array':
1829
- return getPreviewArray(item);
1830
- case 'object':
1831
- return getPreviewObject();
1832
- case 'string':
1833
- return getPreviewString(item);
1834
- default:
1835
- return `${item}`;
1755
+ const mkdir$2 = async (protocol, path) => {
1756
+ try {
1757
+ const provider = get$9(protocol);
1758
+ return await provider.mkdir(path);
1759
+ } catch (error) {
1760
+ throw new VError(error, 'Failed to execute file system provider');
1836
1761
  }
1837
1762
  };
1838
- const validate = (item, schema) => {
1839
- if (typeof schema === 'function') {
1840
- return schema(item);
1841
- }
1842
- const actualType = getType$1(item);
1843
- const expectedType = schema.type;
1844
- if (actualType !== expectedType) {
1845
- if (schema.allowUndefined && (item === undefined || item === null)) {
1846
- return item;
1847
- }
1848
- const preview = getPreview(item);
1849
- return `item must be of type ${expectedType} but is ${preview}`;
1850
- }
1851
- switch (actualType) {
1852
- case 'array':
1853
- return validateResultArray(item, schema);
1854
- case 'object':
1855
- return validateResultObject(item, schema);
1856
- }
1857
- // TODO use json schema to validate result
1858
- return undefined;
1763
+ const readFileExternal = async path => {
1764
+ // TODO when file is local,
1765
+ // don't ask renderer worker
1766
+ // instead read file directly from shared process
1767
+ // this avoid parsing the potentially large message
1768
+ // and improve performance by not blocking the renderer worker
1769
+ // when reading / writing large files
1770
+ const content = await invoke$1('FileSystem.readFile', path);
1771
+ return content;
1859
1772
  };
1860
-
1861
- const RE_UPPERCASE_LETTER = /[A-Z]/g;
1862
- const RE_PROPERTY = /item\..*must be of type/;
1863
- const spaceOut = camelCaseWord => {
1864
- return camelCaseWord.replaceAll(RE_UPPERCASE_LETTER, (character, index) => {
1865
- if (index === 0) {
1866
- return character.toLowerCase();
1867
- }
1868
- return ' ' + character.toLowerCase();
1869
- });
1773
+ const removeExternal = async path => {
1774
+ const content = await invoke$1('FileSystem.remove', path);
1775
+ return content;
1870
1776
  };
1871
- const toCamelCase = string => {
1872
- return string[0].toLowerCase() + string.slice(1);
1777
+ const existsExternal = async uri => {
1778
+ return await invoke$1('FileSystem.exists', uri);
1873
1779
  };
1874
- const improveValidationErrorPostMessage = (validationError, camelCaseName) => {
1875
- if (validationError.startsWith('item must be of type')) {
1876
- return validationError.replace('item', camelCaseName);
1877
- }
1878
- if (validationError.startsWith('expected result to be')) {
1879
- return validationError.replace('result', `${camelCaseName} item`);
1780
+ const mkdirExternal = async uri => {
1781
+ return await invoke$1('FileSystem.mkdir', uri);
1782
+ };
1783
+ const writeFileExternal = async (uri, content) => {
1784
+ return await invoke$1('FileSystem.writeFile', uri, content);
1785
+ };
1786
+ const statExternal = async uri => {
1787
+ return await invoke$1('FileSystem.stat', uri);
1788
+ };
1789
+ const readDirWithFileTypesExternal = async path => {
1790
+ // TODO when file is local,
1791
+ // don't ask renderer worker
1792
+ // instead read file directly from shared process
1793
+ // this avoid parsing the potentially large message
1794
+ // and improve performance by not blocking the renderer worker
1795
+ // when reading / writing large files
1796
+ const content = await invoke$1('FileSystem.readDirWithFileTypes', path);
1797
+ return content;
1798
+ };
1799
+ const remove$3 = async (protocol, path) => {
1800
+ try {
1801
+ const provider = get$9(protocol);
1802
+ return await provider.remove(path);
1803
+ } catch (error) {
1804
+ throw new VError(error, 'Failed to execute file system provider');
1880
1805
  }
1881
- if (RE_PROPERTY.test(validationError)) {
1882
- return validationError.replace('item', camelCaseName);
1806
+ };
1807
+ const rename$1 = async (protocol, oldUri, newUri) => {
1808
+ try {
1809
+ const provider = get$9(protocol);
1810
+ return await provider.rename(oldUri, newUri);
1811
+ } catch (error) {
1812
+ throw new VError(error, 'Failed to execute file system provider');
1883
1813
  }
1884
- return validationError;
1885
1814
  };
1886
- const improveValidationError = (name, validationError) => {
1887
- const camelCaseName = toCamelCase(name);
1888
- const spacedOutName = spaceOut(name);
1889
- const pre = `invalid ${spacedOutName} result`;
1890
- const post = improveValidationErrorPostMessage(validationError, camelCaseName);
1891
- return pre + ': ' + post;
1815
+ const writeFile$3 = async (protocol, uri, content) => {
1816
+ try {
1817
+ const provider = get$9(protocol);
1818
+ return await provider.writeFile(uri, content);
1819
+ } catch (error) {
1820
+ throw new VError(error, 'Failed to execute file system provider');
1821
+ }
1892
1822
  };
1893
- const registerMethod = ({
1894
- context,
1895
- methodName,
1896
- name,
1897
- providers,
1898
- resultShape,
1899
- returnUndefinedWhenNoProviderFound
1900
- }) => {
1901
- context[`execute${name}Provider`] = async function (textDocumentId, ...params) {
1902
- try {
1903
- const textDocument = get$a(textDocumentId);
1904
- if (!textDocument) {
1905
- throw new Error(`textDocument with id ${textDocumentId} not found`);
1906
- }
1907
- const provider = providers[textDocument.languageId];
1908
- if (!provider) {
1909
- if (returnUndefinedWhenNoProviderFound) {
1910
- return undefined;
1911
- }
1912
- const spacedOutName = spaceOut(name);
1913
- throw new NoProviderFoundError(`No ${spacedOutName} provider found for ${textDocument.languageId}`);
1914
- }
1915
- const result = await provider[methodName](textDocument, ...params);
1916
- const error = validate(result, resultShape);
1917
- if (error) {
1918
- const improvedError = improveValidationError(name, error);
1919
- throw new VError(improvedError);
1920
- }
1921
- return result;
1922
- } catch (error) {
1923
- const actualError = ensureError(error);
1924
- const spacedOutName = spaceOut(name);
1925
- if (actualError && actualError.message) {
1926
- if (actualError.message === 'provider[methodName] is not a function') {
1927
- const camelCaseName = toCamelCase(name);
1928
- throw new VError(`Failed to execute ${spacedOutName} provider: VError: ${camelCaseName}Provider.${methodName} is not a function`);
1929
- }
1930
- throw new VError(actualError, `Failed to execute ${spacedOutName} provider`);
1931
- }
1932
- throw actualError;
1823
+ const getPathSeparator = async protocol => {
1824
+ try {
1825
+ const provider = getOptional(protocol);
1826
+ if (provider) {
1827
+ return provider.pathSeparator;
1933
1828
  }
1934
- };
1829
+ const isolated = await getPathSeparator$1(protocol);
1830
+ if (isolated.found) {
1831
+ return isolated.result;
1832
+ }
1833
+ return get$9(protocol).pathSeparator;
1834
+ } catch (error) {
1835
+ throw new VError(error, 'Failed to execute file system provider');
1836
+ }
1935
1837
  };
1936
- const create$6 = ({
1937
- additionalMethodNames = [],
1938
- executeKey = '',
1939
- name,
1940
- resultShape,
1941
- returnUndefinedWhenNoProviderFound = false
1942
- }) => {
1943
- const multipleResults = resultShape.type === 'array';
1944
- const methodName = executeKey || (multipleResults ? `provide${name}s` : `provide${name}`);
1945
- const providers = Object.create(null);
1946
- const context = {
1947
- [`register${name}Provider`](provider) {
1948
- providers[provider.languageId] = provider;
1949
- },
1950
- getProvider(languageId) {
1951
- return providers[languageId];
1952
- },
1953
- getProviders() {
1954
- return Object.values(providers);
1955
- },
1956
- reset() {
1957
- for (const key in providers) {
1958
- delete providers[key];
1838
+ const isReadonly = async protocol => {
1839
+ try {
1840
+ const provider = getOptional(protocol);
1841
+ if (provider) {
1842
+ if (!provider.isReadonly) {
1843
+ return false;
1959
1844
  }
1845
+ return await provider.isReadonly();
1960
1846
  }
1961
- };
1962
- registerMethod({
1963
- context,
1964
- methodName,
1965
- name,
1966
- providers,
1967
- resultShape,
1968
- returnUndefinedWhenNoProviderFound
1969
- });
1970
- for (const method of additionalMethodNames) {
1971
- // @ts-ignore
1972
- registerMethod({
1973
- context,
1974
- providers,
1975
- ...method
1976
- });
1847
+ const isolated = await isReadonly$1(protocol);
1848
+ if (isolated.found) {
1849
+ return isolated.result;
1850
+ }
1851
+ return await get$9(protocol).isReadonly();
1852
+ } catch (error) {
1853
+ throw new VError(error, 'Failed to execute file system provider');
1977
1854
  }
1978
- const finalContext = {
1979
- ...context
1980
- };
1981
- return finalContext;
1982
1855
  };
1983
1856
 
1984
- const Array$1 = 'array';
1985
- const Boolean$1 = 'boolean';
1986
- const Number = 'number';
1987
- const Object$1 = 'object';
1988
- const String$1 = 'string';
1989
-
1990
1857
  const {
1991
- executeBraceCompletionProvider: executeLegacyBraceCompletionProvider,
1992
- getProvider: getProvider$d,
1993
- registerBraceCompletionProvider} = create$6({
1994
- name: 'BraceCompletion',
1858
+ executeFormattingProvider: executeRegisteredFormattingProvider,
1859
+ getProvider: getProvider$8,
1860
+ getProviders: getProviders$1,
1861
+ registerFormattingProvider} = create$i({
1862
+ executeKey: 'format',
1863
+ name: 'Formatting',
1995
1864
  resultShape: {
1996
- type: Boolean$1
1865
+ allowUndefined: true,
1866
+ items: {
1867
+ properties: {
1868
+ endOffset: {
1869
+ type: Number
1870
+ },
1871
+ inserted: {
1872
+ type: String$1
1873
+ },
1874
+ startOffset: {
1875
+ type: Number
1876
+ }
1877
+ },
1878
+ type: Object$1
1879
+ },
1880
+ type: Array$1
1997
1881
  }
1998
1882
  });
1999
- const executeBraceCompletionProvider = async (textDocumentId, ...args) => {
2000
- if (hasLegacyProvider(getProvider$d, textDocumentId)) {
2001
- return executeLegacy(executeLegacyBraceCompletionProvider, textDocumentId, args);
1883
+ const executeRegisteredFormattingProviderWithParams = executeRegisteredFormattingProvider;
1884
+ const executeFormattingProvider = async (textDocumentId, ...params) => {
1885
+ const textDocument = get$a(textDocumentId);
1886
+ if (!textDocument) {
1887
+ throw new VError(`Failed to execute formatting provider: textDocument with id ${textDocumentId} not found`);
1888
+ }
1889
+ const provider = getProvider$8(textDocument.languageId);
1890
+ if (!provider) {
1891
+ throw new VError(`No formatting provider found for ${textDocument.languageId}`, 'Failed to execute formatting provider');
1892
+ }
1893
+ return executeRegisteredFormattingProviderWithParams(textDocumentId, ...params);
1894
+ };
1895
+ const getRegisteredFormattingProviderIds$1 = () => {
1896
+ return getProviders$1().map(provider => provider.id);
1897
+ };
1898
+
1899
+ const getOffset = (textDocument, position) => {
1900
+ let offset = 0;
1901
+ let rowIndex = 0;
1902
+ while (rowIndex++ < position.rowIndex) {
1903
+ const newLineIndex = textDocument.text.indexOf('\n', offset);
1904
+ offset = newLineIndex + 1;
1905
+ }
1906
+ offset += position.columnIndex;
1907
+ return offset;
1908
+ };
1909
+
1910
+ const getPosition = (textDocument, offset) => {
1911
+ let index = 0;
1912
+ let rowIndex = 0;
1913
+ const {
1914
+ text
1915
+ } = textDocument;
1916
+ while (index < offset) {
1917
+ const newLineIndex = text.indexOf('\n', index);
1918
+ if (newLineIndex === -1) {
1919
+ break;
1920
+ }
1921
+ const newIndex = newLineIndex + 1;
1922
+ if (newIndex > offset) {
1923
+ break;
1924
+ }
1925
+ index = newIndex;
1926
+ rowIndex++;
2002
1927
  }
2003
- const isolated = await execute$2('brace completion', 'provideBraceCompletion', textDocumentId, ...args);
2004
- return isolated.found ? isolated.result : executeLegacy(executeLegacyBraceCompletionProvider, textDocumentId, args);
1928
+ const columnIndex = offset - index;
1929
+ return {
1930
+ columnIndex,
1931
+ rowIndex
1932
+ };
2005
1933
  };
2006
1934
 
2007
1935
  const {
2008
- executeClosingTagProvider: executeLegacyClosingTagProvider,
2009
- getProvider: getProvider$c,
2010
- registerClosingTagProvider
2011
- } = create$6({
2012
- name: 'ClosingTag',
1936
+ executeHoverProvider,
1937
+ getProviders,
1938
+ registerHoverProvider} = create$i({
1939
+ name: 'Hover',
2013
1940
  resultShape: {
2014
1941
  allowUndefined: true,
1942
+ properties: {},
2015
1943
  type: Object$1
2016
- },
2017
- returnUndefinedWhenNoProviderFound: true
2018
- });
2019
- const executeClosingTagProvider = async (textDocumentId, ...args) => {
2020
- if (hasLegacyProvider(getProvider$c, textDocumentId)) {
2021
- return executeLegacy(executeLegacyClosingTagProvider, textDocumentId, args);
2022
1944
  }
2023
- const isolated = await execute$2('closing tag', 'provideClosingTag', textDocumentId, ...args);
2024
- return isolated.found ? isolated.result : executeLegacy(executeLegacyClosingTagProvider, textDocumentId, args);
1945
+ });
1946
+ const getRegisteredHoverProviderIds$1 = () => {
1947
+ return getProviders().map(provider => provider.id);
2025
1948
  };
2026
1949
 
2027
1950
  const {
2028
- executeCodeActionProvider: executeRegisteredCodeActionProvider,
2029
- getProvider: getProvider$b,
2030
- registerCodeActionProvider} = create$6({
2031
- name: 'CodeAction',
1951
+ executeImplementationProvider: executeLegacyImplementationProvider,
1952
+ getProvider: getProvider$7,
1953
+ registerImplementationProvider} = create$i({
1954
+ name: 'Implementation',
2032
1955
  resultShape: {
2033
1956
  items: {
2034
1957
  type: Object$1
@@ -2036,673 +1959,791 @@ const {
2036
1959
  type: Array$1
2037
1960
  }
2038
1961
  });
2039
- const executeCodeActionProvider = async (uid, ...args) => {
2040
- if (!hasLegacyProvider(getProvider$b, uid)) {
2041
- const isolated = await execute$2('code action', 'provideCodeActions', uid, ...args);
2042
- if (isolated.found) {
2043
- return isolated.result;
1962
+ const executeImplementationProvider = async (textDocumentId, ...args) => {
1963
+ if (hasLegacyProvider(getProvider$7, textDocumentId)) {
1964
+ return executeLegacy(executeLegacyImplementationProvider, textDocumentId, args);
1965
+ }
1966
+ const isolated = await execute$2('implementation', 'provideImplementations', textDocumentId, ...args);
1967
+ return isolated.found ? isolated.result : executeLegacy(executeLegacyImplementationProvider, textDocumentId, args);
1968
+ };
1969
+
1970
+ const WebSocket$1 = 5;
1971
+ const ElectronMessagePort = 6;
1972
+ const ModuleWorkerAndWorkaroundForChromeDevtoolsBug$1 = 7;
1973
+
1974
+ const isMessagePort = value => {
1975
+ return value && value instanceof MessagePort;
1976
+ };
1977
+ const isMessagePortMain = value => {
1978
+ return value && value.constructor && value.constructor.name === 'MessagePortMain';
1979
+ };
1980
+ const isOffscreenCanvas = value => {
1981
+ return typeof OffscreenCanvas !== 'undefined' && value instanceof OffscreenCanvas;
1982
+ };
1983
+ const isInstanceOf = (value, constructorName) => {
1984
+ return value?.constructor?.name === constructorName;
1985
+ };
1986
+ const isSocket = value => {
1987
+ return isInstanceOf(value, 'Socket');
1988
+ };
1989
+ const transferrables = [isMessagePort, isMessagePortMain, isOffscreenCanvas, isSocket];
1990
+ const isTransferrable = value => {
1991
+ for (const fn of transferrables) {
1992
+ if (fn(value)) {
1993
+ return true;
2044
1994
  }
2045
1995
  }
2046
- const executeProvider = executeRegisteredCodeActionProvider;
2047
- return executeProvider(uid, ...args);
1996
+ return false;
2048
1997
  };
2049
- const toSourceAction = (languageId, action) => {
2050
- return {
2051
- ...(action.edits && {
2052
- edits: action.edits
2053
- }),
2054
- kind: action.kind,
2055
- languageId,
2056
- name: action.name
1998
+ const walkValue = (value, transferrables, isTransferrable) => {
1999
+ if (!value) {
2000
+ return;
2001
+ }
2002
+ if (isTransferrable(value)) {
2003
+ transferrables.push(value);
2004
+ return;
2005
+ }
2006
+ if (Array.isArray(value)) {
2007
+ for (const item of value) {
2008
+ walkValue(item, transferrables, isTransferrable);
2009
+ }
2010
+ return;
2011
+ }
2012
+ if (typeof value === 'object') {
2013
+ for (const property of Object.values(value)) {
2014
+ walkValue(property, transferrables, isTransferrable);
2015
+ }
2016
+ return;
2017
+ }
2018
+ };
2019
+ const getTransferrables = value => {
2020
+ const transferrables = [];
2021
+ walkValue(value, transferrables, isTransferrable);
2022
+ return transferrables;
2023
+ };
2024
+ const attachEvents = that => {
2025
+ const handleMessage = (...args) => {
2026
+ const data = that.getData(...args);
2027
+ that.dispatchEvent(new MessageEvent('message', {
2028
+ data
2029
+ }));
2030
+ };
2031
+ that.onMessage(handleMessage);
2032
+ const handleClose = event => {
2033
+ that.dispatchEvent(new Event('close'));
2057
2034
  };
2035
+ that.onClose(handleClose);
2058
2036
  };
2059
- const getSourceActions = async (uid, ...args) => {
2060
- const textDocument = get$a(uid);
2061
- if (!textDocument) {
2062
- return [];
2037
+ class Ipc extends EventTarget {
2038
+ constructor(rawIpc) {
2039
+ super();
2040
+ this._rawIpc = rawIpc;
2041
+ attachEvents(this);
2063
2042
  }
2064
- const actions = await executeCodeActionProvider(uid, ...args);
2065
- return actions.map(action => toSourceAction(textDocument.languageId, action));
2043
+ }
2044
+ const E_INCOMPATIBLE_NATIVE_MODULE = 'E_INCOMPATIBLE_NATIVE_MODULE';
2045
+ const E_MODULES_NOT_SUPPORTED_IN_ELECTRON = 'E_MODULES_NOT_SUPPORTED_IN_ELECTRON';
2046
+ const ERR_MODULE_NOT_FOUND = 'ERR_MODULE_NOT_FOUND';
2047
+ const NewLine$1 = '\n';
2048
+ const joinLines = lines => {
2049
+ return lines.join(NewLine$1);
2066
2050
  };
2067
- const isOrganizeImports = action => {
2068
- return action.kind === 'source.organizeImports';
2051
+ const RE_AT = /^\s+at/;
2052
+ const RE_AT_PROMISE_INDEX = /^\s*at async Promise.all \(index \d+\)$/;
2053
+ const isNormalStackLine = line => {
2054
+ return RE_AT.test(line) && !RE_AT_PROMISE_INDEX.test(line);
2069
2055
  };
2070
-
2071
- // TODO handle case when multiple organize imports providers are registered
2072
- const executeOrganizeImports = async uid => {
2073
- if (!hasLegacyProvider(getProvider$b, uid)) {
2074
- const isolated = await executeOrganizeImports$1(uid);
2075
- if (isolated.found) {
2076
- return isolated.result;
2056
+ const getDetails = lines => {
2057
+ const index = lines.findIndex(isNormalStackLine);
2058
+ if (index === -1) {
2059
+ return {
2060
+ actualMessage: joinLines(lines),
2061
+ rest: []
2062
+ };
2063
+ }
2064
+ let lastIndex = index - 1;
2065
+ while (++lastIndex < lines.length) {
2066
+ if (!isNormalStackLine(lines[lastIndex])) {
2067
+ break;
2077
2068
  }
2078
2069
  }
2079
- const actions = await executeRegisteredCodeActionProvider(uid);
2080
- // @ts-ignore
2081
- if (!actions || actions.length === 0) {
2082
- return [];
2070
+ return {
2071
+ actualMessage: lines[index - 1],
2072
+ rest: lines.slice(index, lastIndex)
2073
+ };
2074
+ };
2075
+ const splitLines$1 = lines => {
2076
+ return lines.split(NewLine$1);
2077
+ };
2078
+ const RE_MESSAGE_CODE_BLOCK_START = /^Error: The module '.*'$/;
2079
+ const RE_MESSAGE_CODE_BLOCK_END = /^\s* at/;
2080
+ const isMessageCodeBlockStartIndex = line => {
2081
+ return RE_MESSAGE_CODE_BLOCK_START.test(line);
2082
+ };
2083
+ const isMessageCodeBlockEndIndex = line => {
2084
+ return RE_MESSAGE_CODE_BLOCK_END.test(line);
2085
+ };
2086
+ const getMessageCodeBlock = stderr => {
2087
+ const lines = splitLines$1(stderr);
2088
+ const startIndex = lines.findIndex(isMessageCodeBlockStartIndex);
2089
+ const endIndex = startIndex + lines.slice(startIndex).findIndex(isMessageCodeBlockEndIndex, startIndex);
2090
+ const relevantLines = lines.slice(startIndex, endIndex);
2091
+ const relevantMessage = relevantLines.join(' ').slice('Error: '.length);
2092
+ return relevantMessage;
2093
+ };
2094
+ const isModuleNotFoundMessage = line => {
2095
+ return line.includes('[ERR_MODULE_NOT_FOUND]');
2096
+ };
2097
+ const getModuleNotFoundError = stderr => {
2098
+ const lines = splitLines$1(stderr);
2099
+ const messageIndex = lines.findIndex(isModuleNotFoundMessage);
2100
+ const message = lines[messageIndex];
2101
+ return {
2102
+ code: ERR_MODULE_NOT_FOUND,
2103
+ message
2104
+ };
2105
+ };
2106
+ const isModuleNotFoundError = stderr => {
2107
+ if (!stderr) {
2108
+ return false;
2083
2109
  }
2084
- // @ts-ignore
2085
- const organizeImportsAction = actions.find(isOrganizeImports);
2086
- if (!organizeImportsAction) {
2087
- return [];
2110
+ return stderr.includes('ERR_MODULE_NOT_FOUND');
2111
+ };
2112
+ const isModulesSyntaxError = stderr => {
2113
+ if (!stderr) {
2114
+ return false;
2088
2115
  }
2089
- const textDocument = get$a(uid);
2090
- const edits = await organizeImportsAction.execute(textDocument);
2091
- return edits;
2116
+ return stderr.includes('SyntaxError: Cannot use import statement outside a module');
2092
2117
  };
2093
-
2094
- const {
2095
- executeCommentProvider: executeLegacyCommentProvider,
2096
- getProvider: getProvider$a,
2097
- registerCommentProvider
2098
- } = create$6({
2099
- name: 'Comment',
2100
- resultShape() {
2101
- return '';
2118
+ const RE_NATIVE_MODULE_ERROR = /^innerError Error: Cannot find module '.*.node'/;
2119
+ const RE_NATIVE_MODULE_ERROR_2 = /was compiled against a different Node.js version/;
2120
+ const isUnhelpfulNativeModuleError = stderr => {
2121
+ return RE_NATIVE_MODULE_ERROR.test(stderr) && RE_NATIVE_MODULE_ERROR_2.test(stderr);
2122
+ };
2123
+ const getNativeModuleErrorMessage = stderr => {
2124
+ const message = getMessageCodeBlock(stderr);
2125
+ return {
2126
+ code: E_INCOMPATIBLE_NATIVE_MODULE,
2127
+ message: `Incompatible native node module: ${message}`
2128
+ };
2129
+ };
2130
+ const getModuleSyntaxError = () => {
2131
+ return {
2132
+ code: E_MODULES_NOT_SUPPORTED_IN_ELECTRON,
2133
+ message: `ES Modules are not supported in electron`
2134
+ };
2135
+ };
2136
+ const getHelpfulChildProcessError = (stdout, stderr) => {
2137
+ if (isUnhelpfulNativeModuleError(stderr)) {
2138
+ return getNativeModuleErrorMessage(stderr);
2102
2139
  }
2103
- });
2104
- const executeCommentProvider = async (textDocumentId, ...args) => {
2105
- if (hasLegacyProvider(getProvider$a, textDocumentId)) {
2106
- return executeLegacy(executeLegacyCommentProvider, textDocumentId, args);
2140
+ if (isModulesSyntaxError(stderr)) {
2141
+ return getModuleSyntaxError();
2142
+ }
2143
+ if (isModuleNotFoundError(stderr)) {
2144
+ return getModuleNotFoundError(stderr);
2107
2145
  }
2108
- const isolated = await execute$2('comment', 'provideComment', textDocumentId, ...args);
2109
- return isolated.found ? isolated.result : executeLegacy(executeLegacyCommentProvider, textDocumentId, args);
2146
+ const lines = splitLines$1(stderr);
2147
+ const {
2148
+ actualMessage,
2149
+ rest
2150
+ } = getDetails(lines);
2151
+ return {
2152
+ code: '',
2153
+ message: actualMessage,
2154
+ stack: rest
2155
+ };
2110
2156
  };
2111
-
2112
- const {
2113
- executeCompletionProvider,
2114
- executeresolveCompletionItemProvider,
2115
- getProviders: getProviders$3,
2116
- registerCompletionProvider} = create$6({
2117
- additionalMethodNames: [
2157
+ class IpcError extends VError {
2118
2158
  // @ts-ignore
2119
- {
2120
- methodName: 'resolveCompletionItem',
2121
- name: 'resolveCompletionItem',
2122
- resultShape: {
2123
- allowUndefined: true,
2124
- type: Object$1
2159
+ constructor(betterMessage, stdout = '', stderr = '') {
2160
+ if (stdout || stderr) {
2161
+ // @ts-ignore
2162
+ const {
2163
+ code,
2164
+ message,
2165
+ stack
2166
+ } = getHelpfulChildProcessError(stdout, stderr);
2167
+ const cause = new Error(message);
2168
+ // @ts-ignore
2169
+ cause.code = code;
2170
+ cause.stack = stack;
2171
+ super(cause, betterMessage);
2172
+ } else {
2173
+ super(betterMessage);
2125
2174
  }
2126
- }],
2127
- name: 'Completion',
2128
- resultShape: {
2129
- items: {
2130
- type: Object$1
2131
- },
2132
- type: Array$1
2175
+ // @ts-ignore
2176
+ this.name = 'IpcError';
2177
+ // @ts-ignore
2178
+ this.stdout = stdout;
2179
+ // @ts-ignore
2180
+ this.stderr = stderr;
2133
2181
  }
2134
- });
2135
- const getRegisteredCompletionProviderIds$1 = () => {
2136
- return getProviders$3().map(provider => provider.id);
2137
- };
2138
-
2139
- const state$a = {
2140
- configuration: Object.create(null)
2141
- };
2142
- const getConfiguration = key => {
2143
- return state$a.configuration[key] ?? '';
2182
+ }
2183
+ const readyMessage = 'ready';
2184
+ const getData$2 = event => {
2185
+ return event.data;
2144
2186
  };
2145
- const setConfigurations = preferences => {
2146
- state$a.configuration = preferences;
2187
+ const listen$8 = ({
2188
+ port
2189
+ }) => {
2190
+ return port;
2147
2191
  };
2148
-
2149
- const {
2150
- invoke: invoke$2
2151
- } = DebugWorker;
2152
-
2153
- const state$9 = {
2154
- debugProviderMap: Object.create(null)
2192
+ const signal$9 = port => {
2193
+ port.postMessage(readyMessage);
2155
2194
  };
2156
- const getDebugProvider = id => {
2157
- const provider = state$9.debugProviderMap[id];
2158
- if (!provider) {
2159
- // @ts-ignore
2160
- throw new VError(`no debug provider "${id}" found`);
2195
+ class IpcChildWithMessagePort extends Ipc {
2196
+ getData(event) {
2197
+ return getData$2(event);
2161
2198
  }
2162
- return provider;
2163
- };
2164
- const registerDebugProvider = debugProvider => {
2165
- if (!debugProvider.id) {
2166
- throw new Error('Failed to register debug system provider: missing id');
2199
+ send(message) {
2200
+ this._rawIpc.postMessage(message);
2167
2201
  }
2168
- state$9.debugProviderMap[debugProvider.id] = debugProvider;
2169
- };
2170
- const handlePaused = async params => {
2171
- // @ts-ignore
2172
- await invoke$2('Debug.paused', params);
2202
+ sendAndTransfer(message) {
2203
+ const transfer = getTransferrables(message);
2204
+ this._rawIpc.postMessage(message, transfer);
2205
+ }
2206
+ dispose() {
2207
+ // ignore
2208
+ }
2209
+ onClose(callback) {
2210
+ // ignore
2211
+ }
2212
+ onMessage(callback) {
2213
+ this._rawIpc.addEventListener('message', callback);
2214
+ this._rawIpc.start();
2215
+ }
2216
+ }
2217
+ const wrap$g = port => {
2218
+ return new IpcChildWithMessagePort(port);
2173
2219
  };
2174
- const handleResumed = async () => {
2175
- // @ts-ignore
2176
- await invoke$2('Debug.resumed');
2220
+ const IpcChildWithMessagePort$1 = {
2221
+ __proto__: null,
2222
+ listen: listen$8,
2223
+ signal: signal$9,
2224
+ wrap: wrap$g
2177
2225
  };
2178
- const handleScriptParsed = async parsedScript => {
2226
+ const listen$7 = () => {
2179
2227
  // @ts-ignore
2180
- await invoke$2('Debug.scriptParsed', parsedScript);
2228
+ if (typeof WorkerGlobalScope === 'undefined') {
2229
+ throw new TypeError('module is not in web worker scope');
2230
+ }
2231
+ return globalThis;
2181
2232
  };
2182
- const handleChange = async params => {
2183
- object(params);
2184
- // @ts-ignore
2185
- await invoke$2('Debug.handleChange', params);
2233
+ const signal$8 = global => {
2234
+ global.postMessage(readyMessage);
2186
2235
  };
2187
- const start = async (protocol, path) => {
2188
- try {
2189
- const provider = getDebugProvider(protocol);
2190
- const emitter = {
2191
- handleChange,
2192
- handlePaused,
2193
- handleResumed,
2194
- handleScriptParsed
2195
- };
2196
- await provider.start(emitter, path);
2197
- } catch (error) {
2198
- throw new VError(error, 'Failed to execute debug provider');
2236
+ class IpcChildWithModuleWorker extends Ipc {
2237
+ getData(event) {
2238
+ return getData$2(event);
2199
2239
  }
2200
- };
2201
- const listProcesses = async (protocol, path) => {
2202
- try {
2203
- const provider = getDebugProvider(protocol);
2204
- const processes = await provider.listProcesses(path);
2205
- array(processes);
2206
- return processes;
2207
- } catch (error) {
2208
- throw new VError(error, 'Failed to execute debug provider');
2240
+ send(message) {
2241
+ // @ts-ignore
2242
+ this._rawIpc.postMessage(message);
2209
2243
  }
2210
- };
2211
- const resume = async protocol => {
2212
- try {
2213
- const provider = getDebugProvider(protocol);
2214
- return await provider.resume();
2215
- } catch (error) {
2216
- throw new VError(error, 'Failed to execute debug provider');
2244
+ sendAndTransfer(message) {
2245
+ const transfer = getTransferrables(message);
2246
+ // @ts-ignore
2247
+ this._rawIpc.postMessage(message, transfer);
2217
2248
  }
2218
- };
2219
- const pause = async protocol => {
2220
- try {
2221
- const provider = getDebugProvider(protocol);
2222
- return await provider.pause();
2223
- } catch (error) {
2224
- throw new VError(error, 'Failed to execute debug provider');
2249
+ dispose() {
2250
+ // ignore
2225
2251
  }
2226
- };
2227
- const getScriptSource = async (protocol, scriptId) => {
2228
- try {
2229
- const provider = getDebugProvider(protocol);
2230
- return await provider.getScriptSource(scriptId);
2231
- } catch (error) {
2232
- throw new VError(error, 'Failed to execute debug provider');
2252
+ onClose(callback) {
2253
+ // ignore
2233
2254
  }
2234
- };
2235
-
2236
- // TODO create direct connection from debug worker to extension, not needing extension host worker apis
2237
-
2238
- const getStatus = async protocol => {
2239
- try {
2240
- const provider = getDebugProvider(protocol);
2241
- return await provider.getStatus();
2242
- } catch (error) {
2243
- throw new VError(error, 'Failed to execute debug provider');
2255
+ onMessage(callback) {
2256
+ this._rawIpc.addEventListener('message', callback);
2244
2257
  }
2258
+ }
2259
+ const wrap$f = global => {
2260
+ return new IpcChildWithModuleWorker(global);
2245
2261
  };
2246
- const getCallStack = async protocol => {
2247
- try {
2248
- const provider = getDebugProvider(protocol);
2249
- return await provider.getCallStack();
2250
- } catch (error) {
2251
- throw new VError(error, 'Failed to execute debug provider');
2252
- }
2262
+ const waitForFirstMessage = async port => {
2263
+ const {
2264
+ promise,
2265
+ resolve
2266
+ } = Promise.withResolvers();
2267
+ port.addEventListener('message', resolve, {
2268
+ once: true
2269
+ });
2270
+ const event = await promise;
2271
+ // @ts-ignore
2272
+ return event.data;
2253
2273
  };
2254
- const getScopeChain = async protocol => {
2255
- try {
2256
- const provider = getDebugProvider(protocol);
2257
- return await provider.getScopeChain();
2258
- } catch (error) {
2259
- throw new VError(error, 'Failed to execute debug provider');
2274
+ const listen$6 = async () => {
2275
+ const parentIpcRaw = listen$7();
2276
+ signal$8(parentIpcRaw);
2277
+ const parentIpc = wrap$f(parentIpcRaw);
2278
+ const firstMessage = await waitForFirstMessage(parentIpc);
2279
+ if (firstMessage.method !== 'initialize') {
2280
+ throw new IpcError('unexpected first message');
2260
2281
  }
2261
- };
2262
- const getScripts = async protocol => {
2263
- try {
2264
- const provider = getDebugProvider(protocol);
2265
- return await provider.getScripts();
2266
- } catch (error) {
2267
- throw new VError(error, 'Failed to execute debug provider');
2282
+ const type = firstMessage.params[0];
2283
+ if (type === 'message-port') {
2284
+ parentIpc.send({
2285
+ id: firstMessage.id,
2286
+ jsonrpc: '2.0',
2287
+ result: null
2288
+ });
2289
+ parentIpc.dispose();
2290
+ const port = firstMessage.params[1];
2291
+ return port;
2268
2292
  }
2293
+ return globalThis;
2269
2294
  };
2270
-
2271
- // eslint-disable-next-line sonarjs/no-identical-functions
2272
- const getPausedStatus = async protocol => {
2273
- try {
2274
- const provider = getDebugProvider(protocol);
2275
- return await provider.getStatus();
2276
- } catch (error) {
2277
- throw new VError(error, 'Failed to execute debug provider');
2295
+ class IpcChildWithModuleWorkerAndMessagePort extends Ipc {
2296
+ getData(event) {
2297
+ return getData$2(event);
2278
2298
  }
2279
- };
2280
- const stepInto = async protocol => {
2281
- try {
2282
- const provider = getDebugProvider(protocol);
2283
- return await provider.stepInto();
2284
- } catch (error) {
2285
- throw new VError(error, 'Failed to execute debug provider');
2299
+ send(message) {
2300
+ this._rawIpc.postMessage(message);
2286
2301
  }
2287
- };
2288
- const stepOut = async protocol => {
2289
- try {
2290
- const provider = getDebugProvider(protocol);
2291
- return await provider.stepOut();
2292
- } catch (error) {
2293
- throw new VError(error, 'Failed to execute debug provider');
2302
+ sendAndTransfer(message) {
2303
+ const transfer = getTransferrables(message);
2304
+ this._rawIpc.postMessage(message, transfer);
2294
2305
  }
2295
- };
2296
- const stepOver = async protocol => {
2297
- try {
2298
- const provider = getDebugProvider(protocol);
2299
- return await provider.stepOver();
2300
- } catch (error) {
2301
- throw new VError(error, 'Failed to execute debug provider');
2306
+ dispose() {
2307
+ if (this._rawIpc.close) {
2308
+ this._rawIpc.close();
2309
+ }
2302
2310
  }
2303
- };
2304
- const setPauseOnException = async (protocol, value) => {
2305
- try {
2306
- const provider = getDebugProvider(protocol);
2307
- return await provider.setPauseOnExceptions(value);
2308
- } catch (error) {
2309
- throw new VError(error, 'Failed to execute debug provider');
2311
+ onClose(callback) {
2312
+ // ignore
2313
+ }
2314
+ onMessage(callback) {
2315
+ this._rawIpc.addEventListener('message', callback);
2316
+ this._rawIpc.start();
2310
2317
  }
2318
+ }
2319
+ const wrap$e = port => {
2320
+ return new IpcChildWithModuleWorkerAndMessagePort(port);
2311
2321
  };
2312
- const getProperties = async (protocol, objectId) => {
2313
- try {
2314
- const provider = getDebugProvider(protocol);
2315
- return await provider.getProperties(objectId);
2316
- } catch (error) {
2317
- throw new VError(error, 'Failed to execute debug provider');
2322
+ const IpcChildWithModuleWorkerAndMessagePort$1 = {
2323
+ __proto__: null,
2324
+ listen: listen$6,
2325
+ wrap: wrap$e
2326
+ };
2327
+ const Error$3 = 1;
2328
+ const Open = 2;
2329
+ const Close = 3;
2330
+ const addListener = (emitter, type, callback) => {
2331
+ if ('addEventListener' in emitter) {
2332
+ emitter.addEventListener(type, callback);
2333
+ } else {
2334
+ emitter.on(type, callback);
2318
2335
  }
2319
2336
  };
2320
- const evaluate = async (protocol, expression, callFrameId) => {
2321
- try {
2322
- const provider = getDebugProvider(protocol);
2323
- return await provider.evaluate(expression, callFrameId);
2324
- } catch (error) {
2325
- throw new VError(error, 'Failed to execute debug provider');
2337
+ const removeListener = (emitter, type, callback) => {
2338
+ if ('removeEventListener' in emitter) {
2339
+ emitter.removeEventListener(type, callback);
2340
+ } else {
2341
+ emitter.off(type, callback);
2326
2342
  }
2327
2343
  };
2328
- const setPauseOnExceptions = async (protocol, value) => {
2329
- try {
2330
- const provider = getDebugProvider(protocol);
2331
- return await provider.setPauseOnExceptions(value);
2332
- } catch (error) {
2333
- throw new VError(error, 'Failed to execute setPauseOnExceptions');
2344
+ const getFirstEvent = (eventEmitter, eventMap) => {
2345
+ const {
2346
+ promise,
2347
+ resolve
2348
+ } = Promise.withResolvers();
2349
+ const listenerMap = Object.create(null);
2350
+ const cleanup = value => {
2351
+ for (const event of Object.keys(eventMap)) {
2352
+ removeListener(eventEmitter, event, listenerMap[event]);
2353
+ }
2354
+ resolve(value);
2355
+ };
2356
+ for (const [event, type] of Object.entries(eventMap)) {
2357
+ const listener = event => {
2358
+ cleanup({
2359
+ event,
2360
+ type
2361
+ });
2362
+ };
2363
+ addListener(eventEmitter, event, listener);
2364
+ listenerMap[event] = listener;
2334
2365
  }
2366
+ return promise;
2335
2367
  };
2336
-
2337
- const {
2338
- executeDefinitionProvider: executeLegacyDefinitionProvider,
2339
- getProvider: getProvider$9,
2340
- registerDefinitionProvider} = create$6({
2341
- name: 'Definition',
2342
- resultShape: {
2343
- allowUndefined: true,
2344
- properties: {
2345
- endOffset: {
2346
- type: Number
2347
- },
2348
- startOffset: {
2349
- type: Number
2350
- },
2351
- uri: {
2352
- type: String$1
2353
- }
2354
- },
2355
- type: Object$1
2368
+ const Message$1 = 3;
2369
+ const create$5$1 = async ({
2370
+ isMessagePortOpen,
2371
+ messagePort
2372
+ }) => {
2373
+ if (!isMessagePort(messagePort)) {
2374
+ throw new IpcError('port must be of type MessagePort');
2356
2375
  }
2357
- });
2358
- const executeDefinitionProvider = async (textDocumentId, ...args) => {
2359
- if (hasLegacyProvider(getProvider$9, textDocumentId)) {
2360
- return executeLegacy(executeLegacyDefinitionProvider, textDocumentId, args);
2376
+ if (isMessagePortOpen) {
2377
+ return messagePort;
2361
2378
  }
2362
- const isolated = await execute$2('definition', 'provideDefinition', textDocumentId, ...args);
2363
- return isolated.found ? isolated.result : executeLegacy(executeLegacyDefinitionProvider, textDocumentId, args);
2364
- };
2365
-
2366
- const {
2367
- executeDiagnosticProvider,
2368
- getProviders: getProviders$2,
2369
- registerDiagnosticProvider} = create$6({
2370
- name: 'Diagnostic',
2371
- resultShape: {
2372
- items: {
2373
- type: Object$1
2374
- },
2375
- type: Array$1
2379
+ const eventPromise = getFirstEvent(messagePort, {
2380
+ message: Message$1
2381
+ });
2382
+ messagePort.start();
2383
+ const {
2384
+ event,
2385
+ type
2386
+ } = await eventPromise;
2387
+ if (type !== Message$1) {
2388
+ throw new IpcError('Failed to wait for ipc message');
2376
2389
  }
2377
- });
2378
- const getRegisteredDiagnosticProviderIds$1 = () => {
2379
- return getProviders$2().map(provider => provider.id);
2380
- };
2381
-
2382
- const RendererWorker = 1;
2383
-
2384
- const invoke$1 = (method, ...params) => {
2385
- const rpc = get$b(RendererWorker);
2386
- return rpc.invoke(method, ...params);
2387
- };
2388
- const invokeAndTransfer$1 = (method, ...params) => {
2389
- const rpc = get$b(RendererWorker);
2390
- return rpc.invokeAndTransfer(method, ...params);
2391
- };
2392
-
2393
- const showInformationMessage = message => {
2394
- string(message);
2395
- const result = invoke$1('ExtensionHostDialog.showInformationMessage', message);
2396
- return result;
2397
- };
2398
-
2399
- const env = {};
2400
-
2401
- const exec = async (command, args, options) => {
2402
- throw new DepecratedError(`vscode.exec is deprecated, use createNodeRpc instead`);
2403
- };
2404
-
2405
- const isUnavailableError$1 = error => {
2406
- return error instanceof Error && error.name === 'CommandNotFoundError' || error instanceof TypeError && error.message === "Cannot read properties of undefined (reading 'invoke')";
2407
- };
2408
- const executeMethod = async (method, providerId, ...args) => {
2409
- try {
2410
- return await invoke$6(method, providerId, ...args);
2411
- } catch (error) {
2412
- if (isUnavailableError$1(error)) {
2413
- return {
2414
- found: false
2415
- };
2416
- }
2417
- throw error;
2390
+ if (event.data !== readyMessage) {
2391
+ throw new IpcError('unexpected first message');
2418
2392
  }
2393
+ return messagePort;
2419
2394
  };
2420
- const execute$1 = (providerId, uri) => {
2421
- return executeMethod('Extensions.executeFileSystemProviderReadFile', providerId, uri);
2422
- };
2423
- const getPathSeparator$1 = providerId => {
2424
- return executeMethod('Extensions.executeFileSystemProviderGetPathSeparator', providerId);
2425
- };
2426
- const isReadonly$1 = providerId => {
2427
- return executeMethod('Extensions.executeFileSystemProviderIsReadonly', providerId);
2428
- };
2429
- const readDirWithFileTypes$3 = (providerId, uri) => {
2430
- return executeMethod('Extensions.executeFileSystemProviderReadDirWithFileTypes', providerId, uri);
2395
+ const signal$1 = messagePort => {
2396
+ messagePort.start();
2431
2397
  };
2432
-
2433
- const fileSystemProviderMap = Object.create(null);
2434
- const get$9 = protocol => {
2435
- const provider = fileSystemProviderMap[protocol];
2436
- if (!provider) {
2437
- // @ts-ignore
2438
- throw new VError(`no file system provider for protocol "${protocol}" found`);
2398
+ class IpcParentWithMessagePort extends Ipc {
2399
+ getData = getData$2;
2400
+ send(message) {
2401
+ this._rawIpc.postMessage(message);
2439
2402
  }
2440
- return provider;
2441
- };
2442
- const getOptional = protocol => {
2443
- return fileSystemProviderMap[protocol];
2444
- };
2445
- const set$9 = (id, provider) => {
2446
- if (!id) {
2447
- throw new Error('Failed to register file system provider: missing id');
2403
+ sendAndTransfer(message) {
2404
+ const transfer = getTransferrables(message);
2405
+ this._rawIpc.postMessage(message, transfer);
2406
+ }
2407
+ dispose() {
2408
+ this._rawIpc.close();
2409
+ }
2410
+ onMessage(callback) {
2411
+ this._rawIpc.addEventListener('message', callback);
2448
2412
  }
2449
- fileSystemProviderMap[id] = provider;
2413
+ onClose(callback) {}
2414
+ }
2415
+ const wrap$5 = messagePort => {
2416
+ return new IpcParentWithMessagePort(messagePort);
2450
2417
  };
2451
-
2452
- const registerFileSystemProvider = fileSystemProvider => {
2453
- if (!fileSystemProvider.id) {
2454
- throw new Error('Failed to register file system provider: missing id');
2455
- }
2456
- set$9(fileSystemProvider.id, fileSystemProvider);
2418
+ const IpcParentWithMessagePort$1 = {
2419
+ __proto__: null,
2420
+ create: create$5$1,
2421
+ signal: signal$1,
2422
+ wrap: wrap$5
2457
2423
  };
2458
- const readDirWithFileTypes$2 = async (protocol, path) => {
2459
- try {
2460
- const provider = getOptional(protocol);
2461
- if (provider) {
2462
- return await provider.readDirWithFileTypes(path);
2463
- }
2464
- const isolated = await readDirWithFileTypes$3(protocol, path);
2465
- if (isolated.found) {
2466
- return isolated.result;
2467
- }
2468
- return await get$9(protocol).readDirWithFileTypes(path);
2469
- } catch (error) {
2470
- throw new VError(error, 'Failed to execute file system provider');
2471
- }
2424
+ const stringifyCompact = value => {
2425
+ return JSON.stringify(value);
2472
2426
  };
2473
- const readFile$2 = async (protocol, path) => {
2474
- try {
2475
- const provider = getOptional(protocol);
2476
- if (provider) {
2477
- return await provider.readFile(path);
2478
- }
2479
- const isolated = await execute$1(protocol, path);
2480
- if (isolated.found) {
2481
- return isolated.result;
2482
- }
2483
- return await get$9(protocol).readFile(path);
2484
- } catch (error) {
2485
- throw new VError(error, 'Failed to execute file system provider');
2427
+ const parse$1 = content => {
2428
+ if (content === 'undefined') {
2429
+ return null;
2486
2430
  }
2487
- };
2488
- const mkdir$2 = async (protocol, path) => {
2489
2431
  try {
2490
- const provider = get$9(protocol);
2491
- return await provider.mkdir(path);
2432
+ return JSON.parse(content);
2492
2433
  } catch (error) {
2493
- throw new VError(error, 'Failed to execute file system provider');
2434
+ throw new VError(error, 'failed to parse json');
2494
2435
  }
2495
2436
  };
2496
- const readFileExternal = async path => {
2497
- // TODO when file is local,
2498
- // don't ask renderer worker
2499
- // instead read file directly from shared process
2500
- // this avoid parsing the potentially large message
2501
- // and improve performance by not blocking the renderer worker
2502
- // when reading / writing large files
2503
- const content = await invoke$1('FileSystem.readFile', path);
2504
- return content;
2437
+ const waitForWebSocketToBeOpen = webSocket => {
2438
+ return getFirstEvent(webSocket, {
2439
+ close: Close,
2440
+ error: Error$3,
2441
+ open: Open
2442
+ });
2505
2443
  };
2506
- const removeExternal = async path => {
2507
- const content = await invoke$1('FileSystem.remove', path);
2508
- return content;
2444
+ const create$h = async ({
2445
+ webSocket
2446
+ }) => {
2447
+ const firstWebSocketEvent = await waitForWebSocketToBeOpen(webSocket);
2448
+ if (firstWebSocketEvent.type === Error$3) {
2449
+ throw new IpcError(`WebSocket connection error`);
2450
+ }
2451
+ if (firstWebSocketEvent.type === Close) {
2452
+ throw new IpcError('Websocket connection was immediately closed');
2453
+ }
2454
+ return webSocket;
2509
2455
  };
2510
- const existsExternal = async uri => {
2511
- return await invoke$1('FileSystem.exists', uri);
2456
+ let IpcParentWithWebSocket$1 = class IpcParentWithWebSocket extends Ipc {
2457
+ getData(event) {
2458
+ return parse$1(event.data);
2459
+ }
2460
+ send(message) {
2461
+ this._rawIpc.send(stringifyCompact(message));
2462
+ }
2463
+ sendAndTransfer(message) {
2464
+ throw new Error('sendAndTransfer not supported');
2465
+ }
2466
+ dispose() {
2467
+ this._rawIpc.close();
2468
+ }
2469
+ onClose(callback) {
2470
+ this._rawIpc.addEventListener('close', callback);
2471
+ }
2472
+ onMessage(callback) {
2473
+ this._rawIpc.addEventListener('message', callback);
2474
+ }
2512
2475
  };
2513
- const mkdirExternal = async uri => {
2514
- return await invoke$1('FileSystem.mkdir', uri);
2476
+ const wrap$1 = webSocket => {
2477
+ return new IpcParentWithWebSocket$1(webSocket);
2515
2478
  };
2516
- const writeFileExternal = async (uri, content) => {
2517
- return await invoke$1('FileSystem.writeFile', uri, content);
2479
+ const IpcParentWithWebSocket$1$1 = {
2480
+ __proto__: null,
2481
+ create: create$h,
2482
+ wrap: wrap$1
2518
2483
  };
2519
- const statExternal = async uri => {
2520
- return await invoke$1('FileSystem.stat', uri);
2484
+
2485
+ const Two = '2.0';
2486
+
2487
+ const create$g = (method, params) => {
2488
+ return {
2489
+ jsonrpc: Two,
2490
+ method,
2491
+ params
2492
+ };
2521
2493
  };
2522
- const readDirWithFileTypesExternal = async path => {
2523
- // TODO when file is local,
2524
- // don't ask renderer worker
2525
- // instead read file directly from shared process
2526
- // this avoid parsing the potentially large message
2527
- // and improve performance by not blocking the renderer worker
2528
- // when reading / writing large files
2529
- const content = await invoke$1('FileSystem.readDirWithFileTypes', path);
2530
- return content;
2494
+
2495
+ const create$f = (id, method, params) => {
2496
+ const message = {
2497
+ id,
2498
+ jsonrpc: Two,
2499
+ method,
2500
+ params
2501
+ };
2502
+ return message;
2531
2503
  };
2532
- const remove$3 = async (protocol, path) => {
2533
- try {
2534
- const provider = get$9(protocol);
2535
- return await provider.remove(path);
2536
- } catch (error) {
2537
- throw new VError(error, 'Failed to execute file system provider');
2538
- }
2504
+
2505
+ let id$1 = 0;
2506
+ const create$e = () => {
2507
+ return ++id$1;
2539
2508
  };
2540
- const rename$1 = async (protocol, oldUri, newUri) => {
2541
- try {
2542
- const provider = get$9(protocol);
2543
- return await provider.rename(oldUri, newUri);
2544
- } catch (error) {
2545
- throw new VError(error, 'Failed to execute file system provider');
2546
- }
2509
+
2510
+ const registerPromise = map => {
2511
+ const id = create$e();
2512
+ const {
2513
+ promise,
2514
+ resolve
2515
+ } = Promise.withResolvers();
2516
+ map[id] = resolve;
2517
+ return {
2518
+ id,
2519
+ promise
2520
+ };
2547
2521
  };
2548
- const writeFile$3 = async (protocol, uri, content) => {
2549
- try {
2550
- const provider = get$9(protocol);
2551
- return await provider.writeFile(uri, content);
2552
- } catch (error) {
2553
- throw new VError(error, 'Failed to execute file system provider');
2522
+
2523
+ const invokeHelper = async (callbacks, ipc, method, params, useSendAndTransfer) => {
2524
+ const {
2525
+ id,
2526
+ promise
2527
+ } = registerPromise(callbacks);
2528
+ const message = create$f(id, method, params);
2529
+ if (useSendAndTransfer && ipc.sendAndTransfer) {
2530
+ ipc.sendAndTransfer(message);
2531
+ } else {
2532
+ ipc.send(message);
2554
2533
  }
2534
+ const responseMessage = await promise;
2535
+ return unwrapJsonRpcResult(responseMessage);
2555
2536
  };
2556
- const getPathSeparator = async protocol => {
2557
- try {
2558
- const provider = getOptional(protocol);
2559
- if (provider) {
2560
- return provider.pathSeparator;
2537
+ const createRpc$1 = ipc => {
2538
+ const callbacks = Object.create(null);
2539
+ ipc._resolve = (id, response) => {
2540
+ const fn = callbacks[id];
2541
+ if (!fn) {
2542
+ console.warn(`callback ${id} may already be disposed`);
2543
+ return;
2561
2544
  }
2562
- const isolated = await getPathSeparator$1(protocol);
2563
- if (isolated.found) {
2564
- return isolated.result;
2545
+ fn(response);
2546
+ delete callbacks[id];
2547
+ };
2548
+ const rpc = {
2549
+ async dispose() {
2550
+ await ipc?.dispose();
2551
+ },
2552
+ invoke(method, ...params) {
2553
+ return invokeHelper(callbacks, ipc, method, params, false);
2554
+ },
2555
+ invokeAndTransfer(method, ...params) {
2556
+ return invokeHelper(callbacks, ipc, method, params, true);
2557
+ },
2558
+ // @ts-ignore
2559
+ ipc,
2560
+ /**
2561
+ * @deprecated
2562
+ */
2563
+ send(method, ...params) {
2564
+ const message = create$g(method, params);
2565
+ ipc.send(message);
2565
2566
  }
2566
- return get$9(protocol).pathSeparator;
2567
- } catch (error) {
2568
- throw new VError(error, 'Failed to execute file system provider');
2569
- }
2567
+ };
2568
+ return rpc;
2570
2569
  };
2571
- const isReadonly = async protocol => {
2572
- try {
2573
- const provider = getOptional(protocol);
2574
- if (provider) {
2575
- if (!provider.isReadonly) {
2576
- return false;
2577
- }
2578
- return await provider.isReadonly();
2579
- }
2580
- const isolated = await isReadonly$1(protocol);
2581
- if (isolated.found) {
2582
- return isolated.result;
2583
- }
2584
- return await get$9(protocol).isReadonly();
2585
- } catch (error) {
2586
- throw new VError(error, 'Failed to execute file system provider');
2587
- }
2570
+
2571
+ const requiresSocket = () => {
2572
+ return false;
2573
+ };
2574
+ const preparePrettyError = error => {
2575
+ return error;
2576
+ };
2577
+ const logError = () => {
2578
+ // handled by renderer worker
2579
+ };
2580
+ const handleMessage = event => {
2581
+ const actualRequiresSocket = event?.target?.requiresSocket || requiresSocket;
2582
+ const actualExecute = event?.target?.execute || execute$3;
2583
+ return handleJsonRpcMessage(event.target, event.data, actualExecute, event.target._resolve, preparePrettyError, logError, actualRequiresSocket);
2588
2584
  };
2589
2585
 
2590
- const {
2591
- executeFormattingProvider: executeRegisteredFormattingProvider,
2592
- getProvider: getProvider$8,
2593
- getProviders: getProviders$1,
2594
- registerFormattingProvider} = create$6({
2595
- executeKey: 'format',
2596
- name: 'Formatting',
2597
- resultShape: {
2598
- allowUndefined: true,
2599
- items: {
2600
- properties: {
2601
- endOffset: {
2602
- type: Number
2603
- },
2604
- inserted: {
2605
- type: String$1
2606
- },
2607
- startOffset: {
2608
- type: Number
2609
- }
2610
- },
2611
- type: Object$1
2612
- },
2613
- type: Array$1
2614
- }
2615
- });
2616
- const executeRegisteredFormattingProviderWithParams = executeRegisteredFormattingProvider;
2617
- const executeFormattingProvider = async (textDocumentId, ...params) => {
2618
- const textDocument = get$a(textDocumentId);
2619
- if (!textDocument) {
2620
- throw new VError(`Failed to execute formatting provider: textDocument with id ${textDocumentId} not found`);
2621
- }
2622
- const provider = getProvider$8(textDocument.languageId);
2623
- if (!provider) {
2624
- throw new VError(`No formatting provider found for ${textDocument.languageId}`, 'Failed to execute formatting provider');
2586
+ const handleIpc = ipc => {
2587
+ if ('addEventListener' in ipc) {
2588
+ ipc.addEventListener('message', handleMessage);
2589
+ } else if ('on' in ipc) {
2590
+ // deprecated
2591
+ ipc.on('message', handleMessage);
2625
2592
  }
2626
- return executeRegisteredFormattingProviderWithParams(textDocumentId, ...params);
2627
- };
2628
- const getRegisteredFormattingProviderIds$1 = () => {
2629
- return getProviders$1().map(provider => provider.id);
2630
2593
  };
2631
2594
 
2632
- const getOffset = (textDocument, position) => {
2633
- let offset = 0;
2634
- let rowIndex = 0;
2635
- while (rowIndex++ < position.rowIndex) {
2636
- const newLineIndex = textDocument.text.indexOf('\n', offset);
2637
- offset = newLineIndex + 1;
2595
+ const listen$1 = async (module, options) => {
2596
+ const rawIpc = await module.listen(options);
2597
+ if (module.signal) {
2598
+ module.signal(rawIpc);
2638
2599
  }
2639
- offset += position.columnIndex;
2640
- return offset;
2600
+ const ipc = module.wrap(rawIpc);
2601
+ return ipc;
2641
2602
  };
2642
2603
 
2643
- const getPosition = (textDocument, offset) => {
2644
- let index = 0;
2645
- let rowIndex = 0;
2604
+ const create$d = async ({
2605
+ commandMap,
2606
+ isMessagePortOpen = true,
2607
+ messagePort
2608
+ }) => {
2609
+ // TODO create a commandMap per rpc instance
2610
+ register$1(commandMap);
2611
+ const rawIpc = await IpcParentWithMessagePort$1.create({
2612
+ isMessagePortOpen,
2613
+ messagePort
2614
+ });
2615
+ const ipc = IpcParentWithMessagePort$1.wrap(rawIpc);
2616
+ handleIpc(ipc);
2617
+ const rpc = createRpc$1(ipc);
2618
+ messagePort.start();
2619
+ return rpc;
2620
+ };
2621
+
2622
+ const create$c = async ({
2623
+ commandMap,
2624
+ isMessagePortOpen,
2625
+ send
2626
+ }) => {
2646
2627
  const {
2647
- text
2648
- } = textDocument;
2649
- while (index < offset) {
2650
- const newLineIndex = text.indexOf('\n', index);
2651
- if (newLineIndex === -1) {
2652
- break;
2653
- }
2654
- const newIndex = newLineIndex + 1;
2655
- if (newIndex > offset) {
2656
- break;
2628
+ port1,
2629
+ port2
2630
+ } = new MessageChannel();
2631
+ await send(port1);
2632
+ return create$d({
2633
+ commandMap,
2634
+ isMessagePortOpen,
2635
+ messagePort: port2
2636
+ });
2637
+ };
2638
+
2639
+ const createSharedLazyRpc = factory => {
2640
+ let rpcPromise;
2641
+ const getOrCreate = () => {
2642
+ if (!rpcPromise) {
2643
+ rpcPromise = factory();
2657
2644
  }
2658
- index = newIndex;
2659
- rowIndex++;
2660
- }
2661
- const columnIndex = offset - index;
2645
+ return rpcPromise;
2646
+ };
2662
2647
  return {
2663
- columnIndex,
2664
- rowIndex
2648
+ async dispose() {
2649
+ const rpc = await getOrCreate();
2650
+ await rpc.dispose();
2651
+ },
2652
+ async invoke(method, ...params) {
2653
+ const rpc = await getOrCreate();
2654
+ return rpc.invoke(method, ...params);
2655
+ },
2656
+ async invokeAndTransfer(method, ...params) {
2657
+ const rpc = await getOrCreate();
2658
+ return rpc.invokeAndTransfer(method, ...params);
2659
+ },
2660
+ async send(method, ...params) {
2661
+ const rpc = await getOrCreate();
2662
+ rpc.send(method, ...params);
2663
+ }
2665
2664
  };
2666
2665
  };
2667
2666
 
2668
- const {
2669
- executeHoverProvider,
2670
- getProviders,
2671
- registerHoverProvider} = create$6({
2672
- name: 'Hover',
2673
- resultShape: {
2674
- allowUndefined: true,
2675
- properties: {},
2676
- type: Object$1
2677
- }
2678
- });
2679
- const getRegisteredHoverProviderIds$1 = () => {
2680
- return getProviders().map(provider => provider.id);
2667
+ const create$b = async ({
2668
+ commandMap,
2669
+ isMessagePortOpen,
2670
+ send
2671
+ }) => {
2672
+ return createSharedLazyRpc(() => {
2673
+ return create$c({
2674
+ commandMap,
2675
+ isMessagePortOpen,
2676
+ send
2677
+ });
2678
+ });
2681
2679
  };
2682
2680
 
2683
- const {
2684
- executeImplementationProvider: executeLegacyImplementationProvider,
2685
- getProvider: getProvider$7,
2686
- registerImplementationProvider} = create$6({
2687
- name: 'Implementation',
2688
- resultShape: {
2689
- items: {
2690
- type: Object$1
2691
- },
2692
- type: Array$1
2693
- }
2694
- });
2695
- const executeImplementationProvider = async (textDocumentId, ...args) => {
2696
- if (hasLegacyProvider(getProvider$7, textDocumentId)) {
2697
- return executeLegacy(executeLegacyImplementationProvider, textDocumentId, args);
2698
- }
2699
- const isolated = await execute$2('implementation', 'provideImplementations', textDocumentId, ...args);
2700
- return isolated.found ? isolated.result : executeLegacy(executeLegacyImplementationProvider, textDocumentId, args);
2681
+ const create$a = async ({
2682
+ commandMap,
2683
+ webSocket
2684
+ }) => {
2685
+ // TODO create a commandMap per rpc instance
2686
+ register$1(commandMap);
2687
+ const rawIpc = await IpcParentWithWebSocket$1$1.create({
2688
+ webSocket
2689
+ });
2690
+ const ipc = IpcParentWithWebSocket$1$1.wrap(rawIpc);
2691
+ handleIpc(ipc);
2692
+ const rpc = createRpc$1(ipc);
2693
+ return rpc;
2701
2694
  };
2702
2695
 
2703
- const WebSocket$1 = 5;
2704
- const ElectronMessagePort = 6;
2705
- const ModuleWorkerAndWorkaroundForChromeDevtoolsBug$1 = 7;
2696
+ const create$9 = async ({
2697
+ commandMap,
2698
+ messagePort
2699
+ }) => {
2700
+ // TODO create a commandMap per rpc instance
2701
+ register$1(commandMap);
2702
+ const ipc = await listen$1(IpcChildWithMessagePort$1, {
2703
+ port: messagePort
2704
+ });
2705
+ handleIpc(ipc);
2706
+ const rpc = createRpc$1(ipc);
2707
+ return rpc;
2708
+ };
2709
+
2710
+ const create$8 = async ({
2711
+ commandMap,
2712
+ isMessagePortOpen,
2713
+ messagePort
2714
+ }) => {
2715
+ // TODO create a commandMap per rpc instance
2716
+ register$1(commandMap);
2717
+ const rawIpc = await IpcParentWithMessagePort$1.create({
2718
+ isMessagePortOpen,
2719
+ messagePort
2720
+ });
2721
+ const ipc = IpcParentWithMessagePort$1.wrap(rawIpc);
2722
+ handleIpc(ipc);
2723
+ const rpc = createRpc$1(ipc);
2724
+ return rpc;
2725
+ };
2726
+
2727
+ const create$7 = async ({
2728
+ commandMap,
2729
+ messagePort
2730
+ }) => {
2731
+ return create$d({
2732
+ commandMap,
2733
+ messagePort
2734
+ });
2735
+ };
2736
+
2737
+ const create$6 = async ({
2738
+ commandMap
2739
+ }) => {
2740
+ // TODO create a commandMap per rpc instance
2741
+ register$1(commandMap);
2742
+ const ipc = await listen$1(IpcChildWithModuleWorkerAndMessagePort$1);
2743
+ handleIpc(ipc);
2744
+ const rpc = createRpc$1(ipc);
2745
+ return rpc;
2746
+ };
2706
2747
 
2707
2748
  const getPortTuple = () => {
2708
2749
  const {
@@ -2741,7 +2782,7 @@ const create$5 = async ({
2741
2782
  port1,
2742
2783
  port2
2743
2784
  } = getPortTuple();
2744
- const rpcPromise = create$a({
2785
+ const rpcPromise = create$8({
2745
2786
  commandMap,
2746
2787
  isMessagePortOpen: true,
2747
2788
  messagePort: port2
@@ -2780,7 +2821,7 @@ const create$4 = async ({
2780
2821
  const port = await getPort();
2781
2822
  // TODO rpc module should start port
2782
2823
  port.start();
2783
- const rpc = await create$a({
2824
+ const rpc = await create$8({
2784
2825
  commandMap: {},
2785
2826
  isMessagePortOpen: true,
2786
2827
  messagePort: port
@@ -2808,7 +2849,7 @@ const create$3 = async ({
2808
2849
  string(type);
2809
2850
  const wsUrl = getWebSocketUrl(type, location.host);
2810
2851
  const webSocket = new WebSocket(wsUrl);
2811
- const rpc = await create$c({
2852
+ const rpc = await create$a({
2812
2853
  commandMap: {},
2813
2854
  webSocket
2814
2855
  });
@@ -2926,7 +2967,7 @@ const send = async port => {
2926
2967
  await invokeAndTransfer$1('SendMessagePortToExtensionHostWorker.sendMessagePortToFileSystemWorker', port, initialCommand);
2927
2968
  };
2928
2969
  const launchFileSystemProcess = async () => {
2929
- const rpc = await create$e({
2970
+ const rpc = await create$c({
2930
2971
  commandMap: {},
2931
2972
  send
2932
2973
  });
@@ -3044,7 +3085,7 @@ const {
3044
3085
  executefileReferenceProvider: executeLegacyFileReferenceProvider,
3045
3086
  executeReferenceProvider: executeLegacyReferenceProvider,
3046
3087
  getProvider: getProvider$6,
3047
- registerReferenceProvider} = create$6({
3088
+ registerReferenceProvider} = create$i({
3048
3089
  additionalMethodNames: [
3049
3090
  // @ts-ignore
3050
3091
  {
@@ -3135,7 +3176,7 @@ const {
3135
3176
  executeprepareRenameProvider: executeLegacyPrepareRenameProvider,
3136
3177
  executeRenameProvider: executeLegacyRenameProvider,
3137
3178
  getProvider: getProvider$5,
3138
- registerRenameProvider} = create$6({
3179
+ registerRenameProvider} = create$i({
3139
3180
  additionalMethodNames: [
3140
3181
  // @ts-ignore
3141
3182
  {
@@ -3307,7 +3348,7 @@ const createRpc = ({
3307
3348
  const {
3308
3349
  executeSelectionProvider: executeLegacySelectionProvider,
3309
3350
  getProvider: getProvider$4,
3310
- registerSelectionProvider} = create$6({
3351
+ registerSelectionProvider} = create$i({
3311
3352
  name: 'Selection',
3312
3353
  resultShape: {
3313
3354
  allowUndefined: true,
@@ -3838,7 +3879,7 @@ const registerStatuBarItemProvider = provider => {
3838
3879
  const {
3839
3880
  executeTabCompletionProvider: executeLegacyTabCompletionProvider,
3840
3881
  getProvider: getProvider$2,
3841
- registerTabCompletionProvider} = create$6({
3882
+ registerTabCompletionProvider} = create$i({
3842
3883
  name: 'TabCompletion',
3843
3884
  resultShape: {
3844
3885
  allowUndefined: true,
@@ -3885,7 +3926,7 @@ const executeTextSearchProvider = async (scheme, query) => {
3885
3926
  const {
3886
3927
  executeTypeDefinitionProvider: executeLegacyTypeDefinitionProvider,
3887
3928
  getProvider: getProvider$1,
3888
- registerTypeDefinitionProvider} = create$6({
3929
+ registerTypeDefinitionProvider} = create$i({
3889
3930
  name: 'TypeDefinition',
3890
3931
  resultShape: {
3891
3932
  allowUndefined: true,
@@ -4337,7 +4378,7 @@ const createWebView = async (providerId, port, uri, uid, origin, webView) => {
4337
4378
  // TODO cancel promise when webview is disposed before sending message
4338
4379
  // TODO handle case when webview doesn't send ready message
4339
4380
 
4340
- const rpc = await create$a({
4381
+ const rpc = await create$8({
4341
4382
  commandMap: provider.commands || {},
4342
4383
  isMessagePortOpen: false,
4343
4384
  messagePort: port
@@ -4629,7 +4670,7 @@ const setup = ({
4629
4670
  };
4630
4671
 
4631
4672
  const launchExtensionManagementWorker = async () => {
4632
- const rpc = await create$d({
4673
+ const rpc = await create$b({
4633
4674
  commandMap: {},
4634
4675
  async send(port) {
4635
4676
  await sendMessagePortToExtensionManagementWorker(port, 0);
@@ -4639,7 +4680,7 @@ const launchExtensionManagementWorker = async () => {
4639
4680
  };
4640
4681
 
4641
4682
  const launchFileSearchWorker = async () => {
4642
- const rpc = await create$d({
4683
+ const rpc = await create$b({
4643
4684
  commandMap: {},
4644
4685
  async send(port) {
4645
4686
  await sendMessagePortToFileSearchWorker(port, 0);
@@ -6057,7 +6098,7 @@ const hydrate$1 = async () => {
6057
6098
  };
6058
6099
 
6059
6100
  const launchIframeWorker = async () => {
6060
- const rpc = await create$e({
6101
+ const rpc = await create$c({
6061
6102
  commandMap: {},
6062
6103
  async send(port) {
6063
6104
  await sendMessagePortToIframeWorker(port, 0);
@@ -6696,14 +6737,14 @@ const handleBeforeUnload = () => {
6696
6737
  };
6697
6738
 
6698
6739
  const handleExtensionManagementMessagePort = async port => {
6699
- await create$b({
6740
+ await create$9({
6700
6741
  commandMap: commandMap,
6701
6742
  messagePort: port
6702
6743
  });
6703
6744
  };
6704
6745
 
6705
6746
  const handleMessagePort2 = async (port, rpcId) => {
6706
- const rpc = await create$9({
6747
+ const rpc = await create$7({
6707
6748
  commandMap: {},
6708
6749
  messagePort: port
6709
6750
  });
@@ -6713,7 +6754,7 @@ const handleMessagePort2 = async (port, rpcId) => {
6713
6754
  };
6714
6755
 
6715
6756
  const handleMessagePort = async (port, rpcId) => {
6716
- const rpc = await create$b({
6757
+ const rpc = await create$9({
6717
6758
  commandMap: {},
6718
6759
  messagePort: port
6719
6760
  });
@@ -7494,7 +7535,7 @@ const commandMap = {
7494
7535
  };
7495
7536
 
7496
7537
  const launchQuickPickWorker = async () => {
7497
- const rpc = await create$d({
7538
+ const rpc = await create$b({
7498
7539
  commandMap: commandMap,
7499
7540
  async send(port) {
7500
7541
  await sendMessagePortToQuickPickWorker(port, 0);
@@ -7504,7 +7545,7 @@ const launchQuickPickWorker = async () => {
7504
7545
  };
7505
7546
 
7506
7547
  const launchRendererWorker = async () => {
7507
- const rpc = await create$8({
7548
+ const rpc = await create$6({
7508
7549
  commandMap: commandMap
7509
7550
  });
7510
7551
  set$e(RendererWorker, rpc);
@@ -7512,7 +7553,7 @@ const launchRendererWorker = async () => {
7512
7553
 
7513
7554
  const listen = async () => {
7514
7555
  await Promise.all([launchExtensionManagementWorker(), launchFileSearchWorker(), launchRendererWorker(), launchQuickPickWorker()]);
7515
- const dialogRpc = await create$d({
7556
+ const dialogRpc = await create$b({
7516
7557
  commandMap: {},
7517
7558
  send: sendMessagePortToDialogWorker
7518
7559
  });