@lvce-editor/extension-host-worker 2.1.0 → 2.2.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.
@@ -303,7 +303,7 @@ const syncIncremental = (textDocumentId, changes) => {
303
303
  textDocument.text = before + syntheticChange.inserted + after;
304
304
  runListenersSafe(getDidChangeListeners(), textDocument, syntheticChanges);
305
305
  };
306
- const get$6 = textDocumentId => {
306
+ const get$5 = textDocumentId => {
307
307
  const textDocument = getDocument(textDocumentId);
308
308
  return textDocument;
309
309
  };
@@ -330,62 +330,6 @@ class NoProviderFoundError extends Error {
330
330
  }
331
331
  }
332
332
 
333
- const normalizeLine = line => {
334
- if (line.startsWith('Error: ')) {
335
- return line.slice('Error: '.length);
336
- }
337
- if (line.startsWith('VError: ')) {
338
- return line.slice('VError: '.length);
339
- }
340
- return line;
341
- };
342
- const getCombinedMessage = (error, message) => {
343
- const stringifiedError = normalizeLine(`${error}`);
344
- if (message) {
345
- return `${message}: ${stringifiedError}`;
346
- }
347
- return stringifiedError;
348
- };
349
- const NewLine$2 = '\n';
350
- const getNewLineIndex$1 = (string, startIndex = undefined) => {
351
- return string.indexOf(NewLine$2, startIndex);
352
- };
353
- const mergeStacks = (parent, child) => {
354
- if (!child) {
355
- return parent;
356
- }
357
- const parentNewLineIndex = getNewLineIndex$1(parent);
358
- const childNewLineIndex = getNewLineIndex$1(child);
359
- if (childNewLineIndex === -1) {
360
- return parent;
361
- }
362
- const parentFirstLine = parent.slice(0, parentNewLineIndex);
363
- const childRest = child.slice(childNewLineIndex);
364
- const childFirstLine = normalizeLine(child.slice(0, childNewLineIndex));
365
- if (parentFirstLine.includes(childFirstLine)) {
366
- return parentFirstLine + childRest;
367
- }
368
- return child;
369
- };
370
- class VError extends Error {
371
- constructor(error, message) {
372
- const combinedMessage = getCombinedMessage(error, message);
373
- super(combinedMessage);
374
- this.name = 'VError';
375
- if (error instanceof Error) {
376
- this.stack = mergeStacks(this.stack, error.stack);
377
- }
378
- if (error.codeFrame) {
379
- // @ts-ignore
380
- this.codeFrame = error.codeFrame;
381
- }
382
- if (error.code) {
383
- // @ts-ignore
384
- this.code = error.code;
385
- }
386
- }
387
- }
388
-
389
333
  const getType = value => {
390
334
  switch (typeof value) {
391
335
  case 'number':
@@ -479,6 +423,62 @@ const validate = (item, schema) => {
479
423
  return undefined;
480
424
  };
481
425
 
426
+ const normalizeLine = line => {
427
+ if (line.startsWith('Error: ')) {
428
+ return line.slice('Error: '.length);
429
+ }
430
+ if (line.startsWith('VError: ')) {
431
+ return line.slice('VError: '.length);
432
+ }
433
+ return line;
434
+ };
435
+ const getCombinedMessage = (error, message) => {
436
+ const stringifiedError = normalizeLine(`${error}`);
437
+ if (message) {
438
+ return `${message}: ${stringifiedError}`;
439
+ }
440
+ return stringifiedError;
441
+ };
442
+ const NewLine$2 = '\n';
443
+ const getNewLineIndex$1 = (string, startIndex = undefined) => {
444
+ return string.indexOf(NewLine$2, startIndex);
445
+ };
446
+ const mergeStacks = (parent, child) => {
447
+ if (!child) {
448
+ return parent;
449
+ }
450
+ const parentNewLineIndex = getNewLineIndex$1(parent);
451
+ const childNewLineIndex = getNewLineIndex$1(child);
452
+ if (childNewLineIndex === -1) {
453
+ return parent;
454
+ }
455
+ const parentFirstLine = parent.slice(0, parentNewLineIndex);
456
+ const childRest = child.slice(childNewLineIndex);
457
+ const childFirstLine = normalizeLine(child.slice(0, childNewLineIndex));
458
+ if (parentFirstLine.includes(childFirstLine)) {
459
+ return parentFirstLine + childRest;
460
+ }
461
+ return child;
462
+ };
463
+ class VError extends Error {
464
+ constructor(error, message) {
465
+ const combinedMessage = getCombinedMessage(error, message);
466
+ super(combinedMessage);
467
+ this.name = 'VError';
468
+ if (error instanceof Error) {
469
+ this.stack = mergeStacks(this.stack, error.stack);
470
+ }
471
+ if (error.codeFrame) {
472
+ // @ts-ignore
473
+ this.codeFrame = error.codeFrame;
474
+ }
475
+ if (error.code) {
476
+ // @ts-ignore
477
+ this.code = error.code;
478
+ }
479
+ }
480
+ }
481
+
482
482
  const RE_UPPERCASE_LETTER = /[A-Z]/g;
483
483
  const RE_PROPERTY = /item\..*must be of type/;
484
484
  const spaceOut = camelCaseWord => {
@@ -535,7 +535,7 @@ const registerMethod = ({
535
535
  }) => {
536
536
  context[`execute${name}Provider`] = async function (textDocumentId, ...params) {
537
537
  try {
538
- const textDocument = get$6(textDocumentId);
538
+ const textDocument = get$5(textDocumentId);
539
539
  if (!textDocument) {
540
540
  throw new Error(`textDocument with id ${textDocumentId} not found`);
541
541
  }
@@ -564,14 +564,14 @@ const registerMethod = ({
564
564
  // @ts-ignore
565
565
  throw new VError(`Failed to execute ${spacedOutName} provider: VError: ${camelCaseName}Provider.${methodName} is not a function`);
566
566
  }
567
- const message = actualError.name === 'Error' ? `${actualError.message}` : `${actualError.name}: ${actualError.message}`;
567
+ const message = actualError.name === 'Error' ? actualError.message : `${actualError.name}: ${actualError.message}`;
568
568
  actualError.message = `Failed to execute ${spacedOutName} provider: ${message}`;
569
569
  }
570
570
  throw actualError;
571
571
  }
572
572
  };
573
573
  };
574
- const create$9 = ({
574
+ const create$a = ({
575
575
  name,
576
576
  resultShape,
577
577
  executeKey = '',
@@ -617,13 +617,13 @@ const Array$1 = 'array';
617
617
  const Boolean = 'boolean';
618
618
  const Number = 'number';
619
619
  const Object$1 = 'object';
620
- const String = 'string';
620
+ const String$1 = 'string';
621
621
 
622
622
  const {
623
623
  registerBraceCompletionProvider,
624
624
  executeBraceCompletionProvider,
625
625
  reset: reset$9
626
- } = create$9({
626
+ } = create$a({
627
627
  name: 'BraceCompletion',
628
628
  resultShape: {
629
629
  type: Boolean
@@ -633,7 +633,7 @@ const {
633
633
  const {
634
634
  registerClosingTagProvider,
635
635
  executeClosingTagProvider
636
- } = create$9({
636
+ } = create$a({
637
637
  name: 'ClosingTag',
638
638
  returnUndefinedWhenNoProviderFound: true,
639
639
  resultShape: {
@@ -645,7 +645,7 @@ const {
645
645
  const {
646
646
  registerCodeActionProvider,
647
647
  executeCodeActionProvider
648
- } = create$9({
648
+ } = create$a({
649
649
  name: 'CodeAction',
650
650
  resultShape: {
651
651
  type: Array$1,
@@ -670,7 +670,7 @@ const executeOrganizeImports = async uid => {
670
670
  if (!organizeImportsAction) {
671
671
  return [];
672
672
  }
673
- const textDocument = get$6(uid);
673
+ const textDocument = get$5(uid);
674
674
  const edits = await organizeImportsAction.execute(textDocument);
675
675
  return edits;
676
676
  };
@@ -728,7 +728,7 @@ const {
728
728
  registerCompletionProvider,
729
729
  executeCompletionProvider,
730
730
  executeresolveCompletionItemProvider
731
- } = create$9({
731
+ } = create$a({
732
732
  name: 'Completion',
733
733
  resultShape: {
734
734
  type: Array$1,
@@ -758,1224 +758,1213 @@ const setConfigurations = preferences => {
758
758
  state$8.configuration = preferences;
759
759
  };
760
760
 
761
- const Two = '2.0';
762
- const create$4$1 = (method, params) => {
763
- return {
764
- jsonrpc: Two,
765
- method,
766
- params
767
- };
768
- };
769
- const callbacks = Object.create(null);
770
- const set$5 = (id, fn) => {
771
- callbacks[id] = fn;
761
+ const state$7 = {
762
+ rpc: undefined
772
763
  };
773
- const get$5 = id => {
774
- return callbacks[id];
764
+ const invoke$1 = (method, ...params) => {
765
+ const rpc = state$7.rpc;
766
+ return rpc.invoke(method, ...params);
775
767
  };
776
- const remove = id => {
777
- delete callbacks[id];
768
+ const send$1 = (method, ...params) => {
769
+ const rpc = state$7.rpc;
770
+ return rpc.send(method, ...params);
778
771
  };
779
- let id = 0;
780
- const create$3$1 = () => {
781
- return ++id;
772
+ const invokeAndTransfer$1 = (method, ...params) => {
773
+ const rpc = state$7.rpc;
774
+ return rpc.invokeAndTransfer(method, ...params);
782
775
  };
783
- const warn = (...args) => {
784
- console.warn(...args);
776
+ const setRpc = rpc => {
777
+ state$7.rpc = rpc;
785
778
  };
786
- const registerPromise = () => {
787
- const id = create$3$1();
788
- const {
789
- resolve,
790
- promise
791
- } = Promise.withResolvers();
792
- set$5(id, resolve);
793
- return {
794
- id,
795
- promise
796
- };
779
+
780
+ const state$6 = {
781
+ debugProviderMap: Object.create(null)
797
782
  };
798
- const resolve = (id, response) => {
799
- const fn = get$5(id);
800
- if (!fn) {
801
- console.log(response);
802
- warn(`callback ${id} may already be disposed`);
803
- return;
783
+ const getDebugProvider = id => {
784
+ const provider = state$6.debugProviderMap[id];
785
+ if (!provider) {
786
+ // @ts-ignore
787
+ throw new VError(`no debug provider "${id}" found`);
804
788
  }
805
- fn(response);
806
- remove(id);
789
+ return provider;
807
790
  };
808
- const create$2$1 = (method, params) => {
809
- const {
810
- id,
811
- promise
812
- } = registerPromise();
813
- const message = {
814
- jsonrpc: Two,
815
- method,
816
- params,
817
- id
818
- };
819
- return {
820
- message,
821
- promise
822
- };
791
+ const registerDebugProvider = debugProvider => {
792
+ if (!debugProvider.id) {
793
+ throw new Error('Failed to register debug system provider: missing id');
794
+ }
795
+ state$6.debugProviderMap[debugProvider.id] = debugProvider;
823
796
  };
824
- class JsonRpcError extends Error {
825
- constructor(message) {
826
- super(message);
827
- this.name = 'JsonRpcError';
797
+ const start = async (protocol, path) => {
798
+ try {
799
+ const handlePaused = params => {
800
+ console.log('send paused', params);
801
+ send$1('Debug.paused', params);
802
+ };
803
+ const handleResumed = () => {
804
+ send$1('Debug.resumed');
805
+ };
806
+ const handleScriptParsed = parsedScript => {
807
+ send$1('Debug.scriptParsed', parsedScript);
808
+ };
809
+ const provider = getDebugProvider(protocol);
810
+ await provider.start({
811
+ handlePaused,
812
+ handleResumed,
813
+ handleScriptParsed
814
+ }, path);
815
+ } catch (error) {
816
+ throw new VError(error, 'Failed to execute debug provider');
828
817
  }
829
- }
830
- const NewLine$1 = '\n';
831
- const DomException = 'DOMException';
832
- const ReferenceError$1 = 'ReferenceError';
833
- const SyntaxError$1 = 'SyntaxError';
834
- const TypeError$1 = 'TypeError';
835
- const getErrorConstructor = (message, type) => {
836
- if (type) {
837
- switch (type) {
838
- case DomException:
839
- return DOMException;
840
- case TypeError$1:
841
- return TypeError;
842
- case SyntaxError$1:
843
- return SyntaxError;
844
- case ReferenceError$1:
845
- return ReferenceError;
846
- default:
847
- return Error;
848
- }
818
+ };
819
+ const listProcesses = async (protocol, path) => {
820
+ try {
821
+ const provider = getDebugProvider(protocol);
822
+ const processes = await provider.listProcesses(path);
823
+ array(processes);
824
+ return processes;
825
+ } catch (error) {
826
+ throw new VError(error, 'Failed to execute debug provider');
849
827
  }
850
- if (message.startsWith('TypeError: ')) {
851
- return TypeError;
828
+ };
829
+ const resume = async protocol => {
830
+ try {
831
+ const provider = getDebugProvider(protocol);
832
+ return await provider.resume();
833
+ } catch (error) {
834
+ throw new VError(error, 'Failed to execute debug provider');
852
835
  }
853
- if (message.startsWith('SyntaxError: ')) {
854
- return SyntaxError;
836
+ };
837
+ const pause = async protocol => {
838
+ try {
839
+ const provider = getDebugProvider(protocol);
840
+ return await provider.pause();
841
+ } catch (error) {
842
+ throw new VError(error, 'Failed to execute debug provider');
855
843
  }
856
- if (message.startsWith('ReferenceError: ')) {
857
- return ReferenceError;
844
+ };
845
+ const stepInto = async protocol => {
846
+ try {
847
+ const provider = getDebugProvider(protocol);
848
+ return await provider.stepInto();
849
+ } catch (error) {
850
+ throw new VError(error, 'Failed to execute debug provider');
858
851
  }
859
- return Error;
860
852
  };
861
- const constructError = (message, type, name) => {
862
- const ErrorConstructor = getErrorConstructor(message, type);
863
- if (ErrorConstructor === DOMException && name) {
864
- return new ErrorConstructor(message, name);
865
- }
866
- if (ErrorConstructor === Error) {
867
- const error = new Error(message);
868
- if (name && name !== 'VError') {
869
- error.name = name;
870
- }
871
- return error;
853
+ const stepOut = async protocol => {
854
+ try {
855
+ const provider = getDebugProvider(protocol);
856
+ return await provider.stepOut();
857
+ } catch (error) {
858
+ throw new VError(error, 'Failed to execute debug provider');
872
859
  }
873
- return new ErrorConstructor(message);
874
- };
875
- const getNewLineIndex = (string, startIndex = undefined) => {
876
- return string.indexOf(NewLine$1, startIndex);
877
860
  };
878
- const getParentStack = error => {
879
- let parentStack = error.stack || error.data || error.message || '';
880
- if (parentStack.startsWith(' at')) {
881
- parentStack = error.message + NewLine$1 + parentStack;
861
+ const stepOver = async protocol => {
862
+ try {
863
+ const provider = getDebugProvider(protocol);
864
+ return await provider.stepOver();
865
+ } catch (error) {
866
+ throw new VError(error, 'Failed to execute debug provider');
882
867
  }
883
- return parentStack;
884
868
  };
885
- const joinLines$1 = lines => {
886
- return lines.join(NewLine$1);
869
+ const setPauseOnException = async (protocol, value) => {
870
+ try {
871
+ const provider = getDebugProvider(protocol);
872
+ return await provider.setPauseOnExceptions(value);
873
+ } catch (error) {
874
+ throw new VError(error, 'Failed to execute debug provider');
875
+ }
887
876
  };
888
- const MethodNotFound = -32601;
889
- const Custom = -32001;
890
- const splitLines$2 = lines => {
891
- return lines.split(NewLine$1);
877
+ const getProperties = async (protocol, objectId) => {
878
+ try {
879
+ const provider = getDebugProvider(protocol);
880
+ return await provider.getProperties(objectId);
881
+ } catch (error) {
882
+ throw new VError(error, 'Failed to execute debug provider');
883
+ }
892
884
  };
893
- const restoreJsonRpcError = error => {
894
- if (error && error instanceof Error) {
895
- return error;
885
+ const evaluate = async (protocol, expression, callFrameId) => {
886
+ try {
887
+ const provider = getDebugProvider(protocol);
888
+ return await provider.evaluate(expression, callFrameId);
889
+ } catch (error) {
890
+ throw new VError(error, 'Failed to execute debug provider');
896
891
  }
897
- const currentStack = joinLines$1(splitLines$2(new Error().stack || '').slice(1));
898
- if (error && error.code && error.code === MethodNotFound) {
899
- const restoredError = new JsonRpcError(error.message);
900
- const parentStack = getParentStack(error);
901
- restoredError.stack = parentStack + NewLine$1 + currentStack;
902
- return restoredError;
892
+ };
893
+ const setPauseOnExceptions = async (protocol, value) => {
894
+ try {
895
+ const provider = getDebugProvider(protocol);
896
+ return await provider.setPauseOnExceptions(value);
897
+ } catch (error) {
898
+ throw new VError(error, 'Failed to execute setPauseOnExceptions');
903
899
  }
904
- if (error && error.message) {
905
- const restoredError = constructError(error.message, error.type, error.name);
906
- if (error.data) {
907
- if (error.data.stack && error.data.type && error.message) {
908
- restoredError.stack = error.data.type + ': ' + error.message + NewLine$1 + error.data.stack + NewLine$1 + currentStack;
909
- } else if (error.data.stack) {
910
- restoredError.stack = error.data.stack;
911
- }
912
- if (error.data.codeFrame) {
913
- // @ts-ignore
914
- restoredError.codeFrame = error.data.codeFrame;
915
- }
916
- if (error.data.code) {
917
- // @ts-ignore
918
- restoredError.code = error.data.code;
919
- }
920
- if (error.data.type) {
921
- // @ts-ignore
922
- restoredError.name = error.data.type;
923
- }
924
- } else {
925
- if (error.stack) {
926
- const lowerStack = restoredError.stack || '';
927
- // @ts-ignore
928
- const indexNewLine = getNewLineIndex(lowerStack);
929
- const parentStack = getParentStack(error);
930
- // @ts-ignore
931
- restoredError.stack = parentStack + lowerStack.slice(indexNewLine);
932
- }
933
- if (error.codeFrame) {
934
- // @ts-ignore
935
- restoredError.codeFrame = error.codeFrame;
900
+ };
901
+
902
+ const {
903
+ registerDefinitionProvider,
904
+ executeDefinitionProvider,
905
+ reset: reset$8
906
+ } = create$a({
907
+ name: 'Definition',
908
+ resultShape: {
909
+ allowUndefined: true,
910
+ type: Object$1,
911
+ properties: {
912
+ uri: {
913
+ type: String$1
914
+ },
915
+ startOffset: {
916
+ type: Number
917
+ },
918
+ endOffset: {
919
+ type: Number
936
920
  }
937
921
  }
938
- return restoredError;
939
922
  }
940
- if (typeof error === 'string') {
941
- return new Error(`JsonRpc Error: ${error}`);
923
+ });
924
+
925
+ const {
926
+ registerDiagnosticProvider,
927
+ executeDiagnosticProvider
928
+ } = create$a({
929
+ name: 'Diagnostic',
930
+ resultShape: {
931
+ type: Array$1,
932
+ items: {
933
+ type: Object$1
934
+ }
942
935
  }
943
- return new Error(`JsonRpc Error: ${error}`);
936
+ });
937
+
938
+ const showInformationMessage = message => {
939
+ string(message);
940
+ const result = invoke$1('ExtensionHostDialog.showInformationMessage', message);
941
+ return result;
944
942
  };
945
- const unwrapJsonRpcResult = responseMessage => {
946
- if ('error' in responseMessage) {
947
- const restoredError = restoreJsonRpcError(responseMessage.error);
948
- throw restoredError;
949
- }
950
- if ('result' in responseMessage) {
951
- return responseMessage.result;
943
+
944
+ const env = {};
945
+
946
+ const exec = async (command, args, options) => {
947
+ throw new DepecratedError(`vscode.exec is deprecated, use createNodeRpc instead`);
948
+ };
949
+
950
+ const fileSystemProviderMap = Object.create(null);
951
+ const get$4 = protocol => {
952
+ const provider = fileSystemProviderMap[protocol];
953
+ if (!provider) {
954
+ // @ts-ignore
955
+ throw new VError(`no file system provider for protocol "${protocol}" found`);
952
956
  }
953
- throw new JsonRpcError('unexpected response message');
957
+ return provider;
954
958
  };
955
- const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
956
- const getErrorType = prettyError => {
957
- if (prettyError && prettyError.type) {
958
- return prettyError.type;
959
+ const set$4 = (id, provider) => {
960
+ if (!id) {
961
+ throw new Error('Failed to register file system provider: missing id');
959
962
  }
960
- if (prettyError && prettyError.constructor && prettyError.constructor.name) {
961
- return prettyError.constructor.name;
963
+ fileSystemProviderMap[id] = provider;
964
+ };
965
+
966
+ const registerFileSystemProvider = fileSystemProvider => {
967
+ if (!fileSystemProvider.id) {
968
+ throw new Error('Failed to register file system provider: missing id');
962
969
  }
963
- return undefined;
970
+ set$4(fileSystemProvider.id, fileSystemProvider);
964
971
  };
965
- const getErrorProperty = (error, prettyError) => {
966
- if (error && error.code === E_COMMAND_NOT_FOUND) {
967
- return {
968
- code: MethodNotFound,
969
- message: error.message,
970
- data: error.stack
971
- };
972
+ const readDirWithFileTypes = async (protocol, path) => {
973
+ try {
974
+ const provider = get$4(protocol);
975
+ return await provider.readDirWithFileTypes(path);
976
+ } catch (error) {
977
+ throw new VError(error, 'Failed to execute file system provider');
972
978
  }
973
- return {
974
- code: Custom,
975
- message: prettyError.message,
976
- data: {
977
- stack: prettyError.stack,
978
- codeFrame: prettyError.codeFrame,
979
- type: getErrorType(prettyError),
980
- code: prettyError.code,
981
- name: prettyError.name
982
- }
983
- };
984
979
  };
985
- const create$1$1 = (message, error) => {
986
- return {
987
- jsonrpc: Two,
988
- id: message.id,
989
- error
990
- };
980
+ const readFile = async (protocol, path) => {
981
+ try {
982
+ const provider = get$4(protocol);
983
+ return await provider.readFile(path);
984
+ } catch (error) {
985
+ throw new VError(error, 'Failed to execute file system provider');
986
+ }
991
987
  };
992
- const getErrorResponse = (message, error, preparePrettyError, logError) => {
993
- const prettyError = preparePrettyError(error);
994
- logError(error, prettyError);
995
- const errorProperty = getErrorProperty(error, prettyError);
996
- return create$1$1(message, errorProperty);
988
+ const readFileExternal = async path => {
989
+ // TODO when file is local,
990
+ // don't ask renderer worker
991
+ // instead read file directly from shared process
992
+ // this avoid parsing the potentially large message
993
+ // and improve performance by not blocking the renderer worker
994
+ // when reading / writing large files
995
+ const content = await invoke$1('FileSystem.readFile', path);
996
+ return content;
997
997
  };
998
- const create$8 = (message, result) => {
999
- return {
1000
- jsonrpc: Two,
1001
- id: message.id,
1002
- result: result ?? null
1003
- };
998
+ const readDirWithFileTypesExternal = async path => {
999
+ // TODO when file is local,
1000
+ // don't ask renderer worker
1001
+ // instead read file directly from shared process
1002
+ // this avoid parsing the potentially large message
1003
+ // and improve performance by not blocking the renderer worker
1004
+ // when reading / writing large files
1005
+ const content = await invoke$1('FileSystem.readDirWithFileTypes', path);
1006
+ return content;
1004
1007
  };
1005
- const getSuccessResponse = (message, result) => {
1006
- const resultProperty = result ?? null;
1007
- return create$8(message, resultProperty);
1008
+ const writeFile = async (protocol, uri, content) => {
1009
+ try {
1010
+ const provider = get$4(protocol);
1011
+ return await provider.writeFile(uri, content);
1012
+ } catch (error) {
1013
+ throw new VError(error, 'Failed to execute file system provider');
1014
+ }
1008
1015
  };
1009
- const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
1016
+ const getPathSeparator = protocol => {
1010
1017
  try {
1011
- const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
1012
- return getSuccessResponse(message, result);
1018
+ const provider = get$4(protocol);
1019
+ return provider.pathSeparator;
1013
1020
  } catch (error) {
1014
- return getErrorResponse(message, error, preparePrettyError, logError);
1021
+ throw new VError(error, 'Failed to execute file system provider');
1015
1022
  }
1016
1023
  };
1017
- const defaultPreparePrettyError = error => {
1018
- return error;
1019
- };
1020
- const defaultLogError = () => {
1021
- // ignore
1022
- };
1023
- const defaultRequiresSocket = () => {
1024
- return false;
1024
+
1025
+ const {
1026
+ registerFormattingProvider,
1027
+ executeFormattingProvider,
1028
+ reset: reset$7
1029
+ } = create$a({
1030
+ name: 'Formatting',
1031
+ executeKey: 'format',
1032
+ resultShape: {
1033
+ allowUndefined: true,
1034
+ type: Array$1,
1035
+ items: {
1036
+ type: Object$1,
1037
+ properties: {
1038
+ startOffset: {
1039
+ type: Number
1040
+ },
1041
+ endOffset: {
1042
+ type: Number
1043
+ },
1044
+ inserted: {
1045
+ type: String$1
1046
+ }
1047
+ }
1048
+ }
1049
+ }
1050
+ });
1051
+
1052
+ const getOffset = (textDocument, position) => {
1053
+ let offset = 0;
1054
+ let rowIndex = 0;
1055
+ while (rowIndex++ < position.rowIndex) {
1056
+ const newLineIndex = textDocument.text.indexOf('\n', offset);
1057
+ offset = newLineIndex + 1;
1058
+ }
1059
+ offset += position.columnIndex;
1060
+ return offset;
1025
1061
  };
1026
- const defaultResolve = resolve;
1027
1062
 
1028
- // TODO maybe remove this in v6 or v7, only accept options object to simplify the code
1029
- const normalizeParams = args => {
1030
- if (args.length === 1) {
1031
- const options = args[0];
1032
- return {
1033
- ipc: options.ipc,
1034
- message: options.message,
1035
- execute: options.execute,
1036
- resolve: options.resolve || defaultResolve,
1037
- preparePrettyError: options.preparePrettyError || defaultPreparePrettyError,
1038
- logError: options.logError || defaultLogError,
1039
- requiresSocket: options.requiresSocket || defaultRequiresSocket
1040
- };
1063
+ const getPosition = (textDocument, offset) => {
1064
+ let index = 0;
1065
+ let rowIndex = 0;
1066
+ let newLineIndex = 0;
1067
+ const text = textDocument.text;
1068
+ while (index < offset) {
1069
+ newLineIndex = text.indexOf('\n', index);
1070
+ if (newLineIndex === -1) {
1071
+ break;
1072
+ }
1073
+ const newIndex = newLineIndex + 1;
1074
+ if (newIndex > offset) {
1075
+ break;
1076
+ }
1077
+ index = newIndex;
1078
+ rowIndex++;
1041
1079
  }
1080
+ const columnIndex = offset - index;
1042
1081
  return {
1043
- ipc: args[0],
1044
- message: args[1],
1045
- execute: args[2],
1046
- resolve: args[3],
1047
- preparePrettyError: args[4],
1048
- logError: args[5],
1049
- requiresSocket: args[6]
1082
+ rowIndex,
1083
+ columnIndex
1050
1084
  };
1051
1085
  };
1052
- const handleJsonRpcMessage = async (...args) => {
1053
- const options = normalizeParams(args);
1054
- const {
1055
- message,
1056
- ipc,
1057
- execute,
1058
- resolve,
1059
- preparePrettyError,
1060
- logError,
1061
- requiresSocket
1062
- } = options;
1063
- if ('id' in message) {
1064
- if ('method' in message) {
1065
- const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
1066
- try {
1067
- ipc.send(response);
1068
- } catch (error) {
1069
- const errorResponse = getErrorResponse(message, error, preparePrettyError, logError);
1070
- ipc.send(errorResponse);
1071
- }
1072
- return;
1086
+
1087
+ const {
1088
+ registerHoverProvider,
1089
+ executeHoverProvider,
1090
+ reset: reset$6
1091
+ } = create$a({
1092
+ name: 'Hover',
1093
+ resultShape: {
1094
+ allowUndefined: true,
1095
+ type: Object$1,
1096
+ properties: {}
1097
+ }
1098
+ });
1099
+
1100
+ const {
1101
+ registerImplementationProvider,
1102
+ executeImplementationProvider,
1103
+ reset: reset$5
1104
+ } = create$a({
1105
+ name: 'Implementation',
1106
+ resultShape: {
1107
+ type: Array$1,
1108
+ items: {
1109
+ type: Object$1
1073
1110
  }
1074
- resolve(message.id, message);
1075
- return;
1076
1111
  }
1077
- if ('method' in message) {
1078
- await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
1079
- return;
1112
+ });
1113
+
1114
+ const WebSocket$1 = 5;
1115
+ const ElectronMessagePort = 6;
1116
+ const ModuleWorkerAndWorkaroundForChromeDevtoolsBug$1 = 7;
1117
+
1118
+ const getModule$3 = method => {
1119
+ switch (method) {
1120
+ case WebSocket$1:
1121
+ return Promise.resolve().then(function () { return IpcParentWithWebSocket; });
1122
+ case ElectronMessagePort:
1123
+ return Promise.resolve().then(function () { return IpcParentWithNode; });
1124
+ case ModuleWorkerAndWorkaroundForChromeDevtoolsBug$1:
1125
+ return Promise.resolve().then(function () { return IpcParentWithModuleWorkerAndWorkaroundForChromeDevtoolsBug; });
1126
+ default:
1127
+ throw new Error('unexpected ipc type');
1080
1128
  }
1081
- throw new JsonRpcError('unexpected message');
1082
1129
  };
1083
- const invokeHelper = async (ipc, method, params, useSendAndTransfer) => {
1084
- const {
1085
- message,
1086
- promise
1087
- } = create$2$1(method, params);
1088
- if (useSendAndTransfer && ipc.sendAndTransfer) {
1089
- ipc.sendAndTransfer(message);
1090
- } else {
1091
- ipc.send(message);
1130
+
1131
+ const create$9 = async ({
1132
+ method,
1133
+ ...options
1134
+ }) => {
1135
+ try {
1136
+ const module = await getModule$3(method);
1137
+ // @ts-ignore
1138
+ const rawIpc = await module.create(options);
1139
+ // @ts-ignore
1140
+ const ipc = module.wrap(rawIpc);
1141
+ return ipc;
1142
+ } catch (error) {
1143
+ throw new VError(error, `Failed to create ipc`);
1092
1144
  }
1093
- const responseMessage = await promise;
1094
- return unwrapJsonRpcResult(responseMessage);
1095
- };
1096
- const send$1 = (transport, method, ...params) => {
1097
- const message = create$4$1(method, params);
1098
- transport.send(message);
1099
- };
1100
- const invoke$1 = (ipc, method, ...params) => {
1101
- return invokeHelper(ipc, method, params, false);
1102
- };
1103
- const invokeAndTransfer$1 = (ipc, method, ...params) => {
1104
- return invokeHelper(ipc, method, params, true);
1105
1145
  };
1106
1146
 
1107
- const commands = Object.create(null);
1108
- const register$1 = commandMap => {
1109
- Object.assign(commands, commandMap);
1110
- };
1111
- const getCommand = key => {
1112
- return commands[key];
1113
- };
1114
- const execute = (command, ...args) => {
1115
- const fn = getCommand(command);
1116
- if (!fn) {
1117
- throw new Error(`command not found ${command}`);
1147
+ const JsonRpc = 1;
1148
+
1149
+ const getModule$2 = method => {
1150
+ switch (method) {
1151
+ case JsonRpc:
1152
+ return Promise.resolve().then(function () { return RpcParentWithJsonRpc; });
1153
+ default:
1154
+ throw new Error('unexpected rpc type');
1118
1155
  }
1119
- return fn(...args);
1120
1156
  };
1121
1157
 
1122
- const requiresSocket$1 = () => {
1123
- return false;
1124
- };
1125
- const preparePrettyError$1 = error => {
1126
- return error;
1158
+ const create$8 = async ({
1159
+ method,
1160
+ ...options
1161
+ }) => {
1162
+ const module = await getModule$2(method);
1163
+ // @ts-ignore
1164
+ const rpc = module.create(options);
1165
+ return rpc;
1127
1166
  };
1128
- const logError$1 = error => {
1129
- // handled by renderer worker
1167
+
1168
+ const defaultExecute$1 = () => {
1169
+ throw new Error('not implemented');
1130
1170
  };
1131
- const handleMessage = event => {
1132
- return handleJsonRpcMessage(event.target, event.data, execute, resolve, preparePrettyError$1, logError$1, requiresSocket$1);
1171
+ const createNodeRpc = async ({
1172
+ path,
1173
+ execute = defaultExecute$1,
1174
+ name = ''
1175
+ }) => {
1176
+ try {
1177
+ string(path);
1178
+ fn(execute);
1179
+ const ipc = await create$9({
1180
+ method: ElectronMessagePort,
1181
+ type: 'extension-host-helper-process',
1182
+ name
1183
+ });
1184
+ const rpc = await create$8({
1185
+ ipc,
1186
+ method: JsonRpc,
1187
+ execute
1188
+ });
1189
+ await rpc.invoke('LoadFile.loadFile', path);
1190
+ return rpc;
1191
+ } catch (error) {
1192
+ throw new VError(error, `Failed to create node rpc`);
1193
+ }
1133
1194
  };
1134
1195
 
1135
- const handleIpc = ipc => {
1136
- ipc.addEventListener('message', handleMessage);
1196
+ const confirm = message => {
1197
+ string(message);
1198
+ const result = invoke$1('ConfirmPrompt.prompt', message);
1199
+ return result;
1137
1200
  };
1138
1201
 
1139
- const state$7 = {
1140
- /**
1141
- * @type {any}
1142
- */
1143
- ipc: undefined
1144
- };
1145
- const get$4 = () => {
1146
- return state$7.ipc;
1147
- };
1148
- const set$4 = ipc => {
1149
- state$7.ipc = ipc;
1150
- };
1202
+ const ExtensionHostQuickPickShow = 'ExtensionHostQuickPick.show';
1151
1203
 
1152
- const send = (method, ...params) => {
1153
- const ipc = get$4();
1154
- send$1(ipc, method, ...params);
1155
- };
1156
- const invoke = (method, ...params) => {
1157
- const ipc = get$4();
1158
- return invoke$1(ipc, method, ...params);
1159
- };
1160
- const invokeAndTransfer = (method, ...params) => {
1161
- const ipc = get$4();
1162
- return invokeAndTransfer$1(ipc, method, ...params);
1163
- };
1164
- const listen$1 = ipc => {
1165
- handleIpc(ipc);
1166
- set$4(ipc);
1204
+ const showQuickPick = async ({
1205
+ getPicks,
1206
+ toPick
1207
+ }) => {
1208
+ const rawPicks = await getPicks();
1209
+ const picks = rawPicks.map(toPick);
1210
+ return invoke$1(ExtensionHostQuickPickShow, picks);
1167
1211
  };
1168
1212
 
1169
- const state$6 = {
1170
- debugProviderMap: Object.create(null)
1213
+ const {
1214
+ registerReferenceProvider,
1215
+ executeReferenceProvider,
1216
+ executefileReferenceProvider,
1217
+ reset: reset$4
1218
+ } = create$a({
1219
+ name: 'Reference',
1220
+ resultShape: {
1221
+ type: Array$1,
1222
+ items: {
1223
+ type: Object$1
1224
+ }
1225
+ },
1226
+ additionalMethodNames: [
1227
+ // @ts-ignore
1228
+ {
1229
+ name: 'fileReference',
1230
+ methodName: 'provideFileReferences',
1231
+ resultShape: {
1232
+ type: Array$1,
1233
+ items: {
1234
+ type: Object$1
1235
+ }
1236
+ }
1237
+ }]
1238
+ });
1239
+
1240
+ const {
1241
+ registerRenameProvider,
1242
+ executeRenameProvider,
1243
+ executeprepareRenameProvider,
1244
+ reset: reset$3
1245
+ } = create$a({
1246
+ name: 'Rename',
1247
+ resultShape: {
1248
+ type: Object$1,
1249
+ allowUndefined: true
1250
+ },
1251
+ additionalMethodNames: [
1252
+ // @ts-ignore
1253
+ {
1254
+ name: 'prepareRename',
1255
+ methodName: 'prepareRename',
1256
+ resultShape: {
1257
+ type: Object$1,
1258
+ allowUndefined: true
1259
+ }
1260
+ }]
1261
+ });
1262
+
1263
+ const getExtensionHostSubWorkerUrl = () => {
1264
+ return new URL('../../../../extension-host-sub-worker/src/extensionHostSubWorkerMain.js', import.meta.url).toString();
1171
1265
  };
1172
- const getDebugProvider = id => {
1173
- const provider = state$6.debugProviderMap[id];
1174
- if (!provider) {
1175
- // @ts-ignore
1176
- throw new VError(`no debug provider "${id}" found`);
1177
- }
1178
- return provider;
1266
+ const extensionHostSubWorkerUrl = getExtensionHostSubWorkerUrl();
1267
+
1268
+ const set$3 = async (url, contentSecurityPolicy) => {
1269
+ const pathName = new URL(url).pathname;
1270
+ await invoke$1('ExtensionHostWorkerContentSecurityPolicy.set', pathName, contentSecurityPolicy);
1179
1271
  };
1180
- const registerDebugProvider = debugProvider => {
1181
- if (!debugProvider.id) {
1182
- throw new Error('Failed to register debug system provider: missing id');
1183
- }
1184
- state$6.debugProviderMap[debugProvider.id] = debugProvider;
1272
+
1273
+ const rpcs$1 = Object.create(null);
1274
+ const add$1 = (id, rpc) => {
1275
+ rpcs$1[id] = rpc;
1185
1276
  };
1186
- const start = async (protocol, path) => {
1187
- try {
1188
- const handlePaused = params => {
1189
- console.log('send paused', params);
1190
- send('Debug.paused', params);
1191
- };
1192
- const handleResumed = () => {
1193
- send('Debug.resumed');
1194
- };
1195
- const handleScriptParsed = parsedScript => {
1196
- send('Debug.scriptParsed', parsedScript);
1197
- };
1198
- const provider = getDebugProvider(protocol);
1199
- await provider.start({
1200
- handlePaused,
1201
- handleResumed,
1202
- handleScriptParsed
1203
- }, path);
1204
- } catch (error) {
1205
- throw new VError(error, 'Failed to execute debug provider');
1206
- }
1277
+ const get$3 = id => {
1278
+ return rpcs$1[id];
1207
1279
  };
1208
- const listProcesses = async (protocol, path) => {
1209
- try {
1210
- const provider = getDebugProvider(protocol);
1211
- const processes = await provider.listProcesses(path);
1212
- array(processes);
1213
- return processes;
1214
- } catch (error) {
1215
- throw new VError(error, 'Failed to execute debug provider');
1216
- }
1280
+
1281
+ const registry = Object.create(null);
1282
+ const rpcs = Object.create(null);
1283
+ const register$1 = (id, execute) => {
1284
+ registry[id] = execute;
1217
1285
  };
1218
- const resume = async protocol => {
1219
- try {
1220
- const provider = getDebugProvider(protocol);
1221
- return await provider.resume();
1222
- } catch (error) {
1223
- throw new VError(error, 'Failed to execute debug provider');
1224
- }
1286
+ const acquire = id => {
1287
+ const fn = registry[id];
1288
+ delete registry[id];
1289
+ return fn;
1225
1290
  };
1226
- const pause = async protocol => {
1227
- try {
1228
- const provider = getDebugProvider(protocol);
1229
- return await provider.pause();
1230
- } catch (error) {
1231
- throw new VError(error, 'Failed to execute debug provider');
1232
- }
1291
+ const get$2 = id => {
1292
+ return rpcs[id];
1233
1293
  };
1234
- const stepInto = async protocol => {
1235
- try {
1236
- const provider = getDebugProvider(protocol);
1237
- return await provider.stepInto();
1238
- } catch (error) {
1239
- throw new VError(error, 'Failed to execute debug provider');
1240
- }
1294
+ const set$2 = (id, rpc) => {
1295
+ rpcs[id] = rpc;
1241
1296
  };
1242
- const stepOut = async protocol => {
1243
- try {
1244
- const provider = getDebugProvider(protocol);
1245
- return await provider.stepOut();
1246
- } catch (error) {
1247
- throw new VError(error, 'Failed to execute debug provider');
1297
+
1298
+ const createRpcWithId$1 = async id => {
1299
+ const fn = acquire(id);
1300
+ const info = get$3(id);
1301
+ if (!info) {
1302
+ throw new Error(`rpc with id ${id} not found`);
1248
1303
  }
1304
+ const ipc = await create$9({
1305
+ method: ModuleWorkerAndWorkaroundForChromeDevtoolsBug$1,
1306
+ url: extensionHostSubWorkerUrl,
1307
+ name: info.name
1308
+ });
1309
+ const newRpc = await create$8({
1310
+ ipc,
1311
+ method: JsonRpc,
1312
+ execute: fn
1313
+ });
1314
+ await newRpc.invoke('LoadFile.loadFile', info.url);
1315
+ set$2(id, newRpc);
1316
+ return newRpc;
1249
1317
  };
1250
- const stepOver = async protocol => {
1251
- try {
1252
- const provider = getDebugProvider(protocol);
1253
- return await provider.stepOver();
1254
- } catch (error) {
1255
- throw new VError(error, 'Failed to execute debug provider');
1318
+
1319
+ const getOrCreateRpc = async id => {
1320
+ const rpc = get$2(id);
1321
+ if (!rpc) {
1322
+ set$2(id, createRpcWithId$1(id));
1256
1323
  }
1324
+ return get$2(id);
1257
1325
  };
1258
- const setPauseOnException = async (protocol, value) => {
1259
- try {
1260
- const provider = getDebugProvider(protocol);
1261
- return await provider.setPauseOnExceptions(value);
1262
- } catch (error) {
1263
- throw new VError(error, 'Failed to execute debug provider');
1264
- }
1326
+ const createRpcWithId = ({
1327
+ id,
1328
+ execute
1329
+ }) => {
1330
+ string(id);
1331
+ register$1(id, execute);
1332
+ const lazyRpc = {
1333
+ async invoke(method, ...params) {
1334
+ const rpc = await getOrCreateRpc(id);
1335
+ return rpc.invoke(method, ...params);
1336
+ }
1337
+ };
1338
+ return lazyRpc;
1265
1339
  };
1266
- const getProperties = async (protocol, objectId) => {
1267
- try {
1268
- const provider = getDebugProvider(protocol);
1269
- return await provider.getProperties(objectId);
1270
- } catch (error) {
1271
- throw new VError(error, 'Failed to execute debug provider');
1272
- }
1340
+
1341
+ const defaultExecute = () => {
1342
+ throw new Error('not implemented');
1273
1343
  };
1274
- const evaluate = async (protocol, expression, callFrameId) => {
1275
- try {
1276
- const provider = getDebugProvider(protocol);
1277
- return await provider.evaluate(expression, callFrameId);
1278
- } catch (error) {
1279
- throw new VError(error, 'Failed to execute debug provider');
1344
+
1345
+ /**
1346
+ *
1347
+ * @deprecated
1348
+ */
1349
+ const createLegacyRpc = async ({
1350
+ url,
1351
+ name,
1352
+ execute = defaultExecute,
1353
+ contentSecurityPolicy
1354
+ }) => {
1355
+ string(url);
1356
+ string(name);
1357
+ fn(execute);
1358
+ if (contentSecurityPolicy) {
1359
+ await set$3(url, contentSecurityPolicy);
1280
1360
  }
1361
+ const ipc = await create$9({
1362
+ method: ModuleWorkerAndWorkaroundForChromeDevtoolsBug$1,
1363
+ url: extensionHostSubWorkerUrl,
1364
+ name
1365
+ });
1366
+ const rpc = await create$8({
1367
+ ipc,
1368
+ method: JsonRpc,
1369
+ execute
1370
+ });
1371
+ await rpc.invoke('LoadFile.loadFile', url);
1372
+ return rpc;
1281
1373
  };
1282
- const setPauseOnExceptions = async (protocol, value) => {
1374
+ const createRpc$1 = ({
1375
+ id,
1376
+ url,
1377
+ name,
1378
+ execute = defaultExecute,
1379
+ contentSecurityPolicy
1380
+ }) => {
1283
1381
  try {
1284
- const provider = getDebugProvider(protocol);
1285
- return await provider.setPauseOnExceptions(value);
1382
+ if (id) {
1383
+ string(id);
1384
+ return createRpcWithId({
1385
+ id,
1386
+ execute
1387
+ });
1388
+ }
1389
+ return createLegacyRpc({
1390
+ url,
1391
+ name,
1392
+ execute,
1393
+ contentSecurityPolicy
1394
+ });
1286
1395
  } catch (error) {
1287
- throw new VError(error, 'Failed to execute setPauseOnExceptions');
1396
+ throw new VError(error, `Failed to create webworker rpc`);
1288
1397
  }
1289
1398
  };
1290
1399
 
1291
1400
  const {
1292
- registerDefinitionProvider,
1293
- executeDefinitionProvider,
1294
- reset: reset$8
1295
- } = create$9({
1296
- name: 'Definition',
1401
+ registerSelectionProvider,
1402
+ executeSelectionProvider,
1403
+ reset: reset$2
1404
+ } = create$a({
1405
+ name: 'Selection',
1297
1406
  resultShape: {
1298
1407
  allowUndefined: true,
1299
- type: Object$1,
1300
- properties: {
1301
- uri: {
1302
- type: String
1303
- },
1304
- startOffset: {
1305
- type: Number
1306
- },
1307
- endOffset: {
1308
- type: Number
1309
- }
1310
- }
1311
- }
1312
- });
1313
-
1314
- const {
1315
- registerDiagnosticProvider,
1316
- executeDiagnosticProvider
1317
- } = create$9({
1318
- name: 'Diagnostic',
1319
- resultShape: {
1320
1408
  type: Array$1,
1321
1409
  items: {
1322
- type: Object$1
1410
+ type: 'number'
1323
1411
  }
1324
1412
  }
1325
1413
  });
1326
1414
 
1327
- const showInformationMessage = message => {
1328
- string(message);
1329
- const result = invoke('ExtensionHostDialog.showInformationMessage', message);
1330
- return result;
1415
+ const state$5 = {
1416
+ providers: Object.create(null)
1331
1417
  };
1332
-
1333
- const env = {};
1334
-
1335
- const exec = async (command, args, options) => {
1336
- throw new DepecratedError(`vscode.exec is deprecated, use createNodeRpc instead`);
1418
+ const registerSourceControlProvider = provider => {
1419
+ state$5.providers[provider.id] = provider;
1337
1420
  };
1338
-
1339
- const fileSystemProviderMap = Object.create(null);
1340
- const get$3 = protocol => {
1341
- const provider = fileSystemProviderMap[protocol];
1421
+ const getFilesFromProvider = provider => {
1422
+ return provider.getChangedFiles();
1423
+ };
1424
+ const getChangedFiles = async providerId => {
1425
+ const provider = state$5.providers[providerId];
1342
1426
  if (!provider) {
1343
- // @ts-ignore
1344
- throw new VError(`no file system provider for protocol "${protocol}" found`);
1427
+ throw new Error('no source control provider found');
1345
1428
  }
1346
- return provider;
1429
+ const changedFiles = await getFilesFromProvider(provider);
1430
+ const flattenedChangedFiles = changedFiles;
1431
+ return flattenedChangedFiles;
1347
1432
  };
1348
- const set$3 = (id, provider) => {
1349
- if (!id) {
1350
- throw new Error('Failed to register file system provider: missing id');
1433
+ const getFileBefore = async (providerId, uri) => {
1434
+ string(providerId);
1435
+ string(uri);
1436
+ const provider = state$5.providers[providerId];
1437
+ if (!provider) {
1438
+ throw new Error('no source control provider found');
1351
1439
  }
1352
- fileSystemProviderMap[id] = provider;
1440
+ return provider.getFileBefore(uri);
1353
1441
  };
1354
-
1355
- const registerFileSystemProvider = fileSystemProvider => {
1356
- if (!fileSystemProvider.id) {
1357
- throw new Error('Failed to register file system provider: missing id');
1442
+ const getGroupsFromProvider = async (provider, cwd) => {
1443
+ if (provider.getGroups) {
1444
+ return provider.getGroups(cwd);
1445
+ }
1446
+ if (provider.getChangedFiles) {
1447
+ const files = await provider.getChangedFiles();
1448
+ const groups = [{
1449
+ id: 'changes',
1450
+ label: 'Changes',
1451
+ items: files
1452
+ }];
1453
+ return groups;
1358
1454
  }
1359
- set$3(fileSystemProvider.id, fileSystemProvider);
1455
+ throw new Error('source control provider is missing required function getGroups');
1360
1456
  };
1361
- const readDirWithFileTypes = async (protocol, path) => {
1362
- try {
1363
- const provider = get$3(protocol);
1364
- return await provider.readDirWithFileTypes(path);
1365
- } catch (error) {
1366
- throw new VError(error, 'Failed to execute file system provider');
1457
+ const getGroups = async (providerId, cwd) => {
1458
+ const provider = state$5.providers[providerId];
1459
+ if (!provider) {
1460
+ throw new Error('no source control provider found');
1367
1461
  }
1462
+ const groups = await getGroupsFromProvider(provider, cwd);
1463
+ return groups;
1368
1464
  };
1369
- const readFile = async (protocol, path) => {
1370
- try {
1371
- const provider = get$3(protocol);
1372
- return await provider.readFile(path);
1373
- } catch (error) {
1374
- throw new VError(error, 'Failed to execute file system provider');
1465
+ const acceptInput = async (providerId, value) => {
1466
+ const provider = state$5.providers[providerId];
1467
+ if (!provider) {
1468
+ throw new Error('no source control provider found');
1375
1469
  }
1470
+ await provider.acceptInput(value);
1376
1471
  };
1377
- const readFileExternal = async path => {
1378
- // TODO when file is local,
1379
- // don't ask renderer worker
1380
- // instead read file directly from shared process
1381
- // this avoid parsing the potentially large message
1382
- // and improve performance by not blocking the renderer worker
1383
- // when reading / writing large files
1384
- const content = await invoke('FileSystem.readFile', path);
1385
- return content;
1472
+ const add = async path => {
1473
+ const provider = Object.values(state$5.providers)[0];
1474
+ if (!provider) {
1475
+ return;
1476
+ }
1477
+ // @ts-ignore
1478
+ await provider.add(path);
1386
1479
  };
1387
- const readDirWithFileTypesExternal = async path => {
1388
- // TODO when file is local,
1389
- // don't ask renderer worker
1390
- // instead read file directly from shared process
1391
- // this avoid parsing the potentially large message
1392
- // and improve performance by not blocking the renderer worker
1393
- // when reading / writing large files
1394
- const content = await invoke('FileSystem.readDirWithFileTypes', path);
1395
- return content;
1480
+ const discard = async path => {
1481
+ const provider = Object.values(state$5.providers)[0];
1482
+ if (!provider) {
1483
+ return;
1484
+ }
1485
+ // @ts-ignore
1486
+ await provider.discard(path);
1396
1487
  };
1397
- const writeFile = async (protocol, uri, content) => {
1488
+ const getEnabledProviderIds = async (scheme, root) => {
1489
+ string(scheme);
1490
+ string(root);
1491
+ const providers = Object.values(state$5.providers);
1492
+ const enabledIds = [];
1493
+ for (const provider of providers) {
1494
+ // @ts-ignore
1495
+ if (typeof provider.isActive !== 'function') {
1496
+ continue;
1497
+ }
1498
+ // @ts-ignore
1499
+ const isActive = await provider.isActive(scheme, root);
1500
+ if (isActive) {
1501
+ // @ts-ignore
1502
+ enabledIds.push(provider.id);
1503
+ }
1504
+ }
1505
+ return enabledIds;
1506
+ };
1507
+
1508
+ const {
1509
+ registerTabCompletionProvider,
1510
+ executeTabCompletionProvider,
1511
+ reset: reset$1
1512
+ } = create$a({
1513
+ name: 'TabCompletion',
1514
+ resultShape: {
1515
+ type: Object$1,
1516
+ allowUndefined: true
1517
+ }
1518
+ });
1519
+
1520
+ const state$4 = {
1521
+ textSearchProviders: Object.create(null)
1522
+ };
1523
+ const registerTextSearchProvider = textSearchProvider => {
1398
1524
  try {
1399
- const provider = get$3(protocol);
1400
- return await provider.writeFile(uri, content);
1525
+ if (!textSearchProvider) {
1526
+ throw new Error('textSearchProvider is not defined');
1527
+ }
1528
+ if (!textSearchProvider.scheme) {
1529
+ throw new Error('textSearchProvider is missing scheme');
1530
+ }
1531
+ state$4.textSearchProviders[textSearchProvider.scheme] = textSearchProvider;
1401
1532
  } catch (error) {
1402
- throw new VError(error, 'Failed to execute file system provider');
1533
+ throw new VError(error, 'Failed to register text search provider');
1403
1534
  }
1404
1535
  };
1405
- const getPathSeparator = protocol => {
1536
+ const executeTextSearchProvider = async (scheme, query) => {
1406
1537
  try {
1407
- const provider = get$3(protocol);
1408
- return provider.pathSeparator;
1538
+ const textSearchProvider = state$4.textSearchProviders[scheme];
1539
+ if (!textSearchProvider) {
1540
+ throw new Error(`No text search provider for ${scheme} found`);
1541
+ }
1542
+ const results = await textSearchProvider.provideTextSearchResults(query);
1543
+ return results;
1409
1544
  } catch (error) {
1410
- throw new VError(error, 'Failed to execute file system provider');
1545
+ throw new VError(error, 'Failed to execute text search provider');
1411
1546
  }
1412
1547
  };
1413
1548
 
1414
1549
  const {
1415
- registerFormattingProvider,
1416
- executeFormattingProvider,
1417
- reset: reset$7
1418
- } = create$9({
1419
- name: 'Formatting',
1420
- executeKey: 'format',
1550
+ registerTypeDefinitionProvider,
1551
+ executeTypeDefinitionProvider,
1552
+ reset
1553
+ } = create$a({
1554
+ name: 'TypeDefinition',
1421
1555
  resultShape: {
1422
1556
  allowUndefined: true,
1423
- type: Array$1,
1424
- items: {
1425
- type: Object$1,
1426
- properties: {
1427
- startOffset: {
1428
- type: Number
1429
- },
1430
- endOffset: {
1431
- type: Number
1432
- },
1433
- inserted: {
1434
- type: String
1435
- }
1557
+ type: Object$1,
1558
+ properties: {
1559
+ uri: {
1560
+ type: String$1
1561
+ },
1562
+ startOffset: {
1563
+ type: Number
1564
+ },
1565
+ endOffset: {
1566
+ type: Number
1436
1567
  }
1437
1568
  }
1438
1569
  }
1439
1570
  });
1440
1571
 
1441
- const getOffset = (textDocument, position) => {
1442
- let offset = 0;
1443
- let rowIndex = 0;
1444
- while (rowIndex++ < position.rowIndex) {
1445
- const newLineIndex = textDocument.text.indexOf('\n', offset);
1446
- offset = newLineIndex + 1;
1572
+ const RE_PROTOCOL = /^([a-z\-]+):\/\//;
1573
+ const getProtocol = uri => {
1574
+ const protocolMatch = uri.match(RE_PROTOCOL);
1575
+ if (protocolMatch) {
1576
+ return protocolMatch[1];
1447
1577
  }
1448
- offset += position.columnIndex;
1449
- return offset;
1578
+ return '';
1450
1579
  };
1451
1580
 
1452
- const getPosition = (textDocument, offset) => {
1453
- let index = 0;
1454
- let rowIndex = 0;
1455
- let newLineIndex = 0;
1456
- const text = textDocument.text;
1457
- while (index < offset) {
1458
- newLineIndex = text.indexOf('\n', index);
1459
- if (newLineIndex === -1) {
1460
- break;
1461
- }
1462
- const newIndex = newLineIndex + 1;
1463
- if (newIndex > offset) {
1464
- break;
1465
- }
1466
- index = newIndex;
1467
- rowIndex++;
1468
- }
1469
- const columnIndex = offset - index;
1581
+ const getPortTuple = () => {
1582
+ const {
1583
+ port1,
1584
+ port2
1585
+ } = new MessageChannel();
1470
1586
  return {
1471
- rowIndex,
1472
- columnIndex
1587
+ port1,
1588
+ port2
1473
1589
  };
1474
1590
  };
1475
1591
 
1476
- const {
1477
- registerHoverProvider,
1478
- executeHoverProvider,
1479
- reset: reset$6
1480
- } = create$9({
1481
- name: 'Hover',
1482
- resultShape: {
1483
- allowUndefined: true,
1484
- type: Object$1,
1485
- properties: {}
1592
+ const Two = '2.0';
1593
+ const create$4$1 = (method, params) => {
1594
+ return {
1595
+ jsonrpc: Two,
1596
+ method,
1597
+ params
1598
+ };
1599
+ };
1600
+ const callbacks = Object.create(null);
1601
+ const set$1 = (id, fn) => {
1602
+ callbacks[id] = fn;
1603
+ };
1604
+ const get$1 = id => {
1605
+ return callbacks[id];
1606
+ };
1607
+ const remove = id => {
1608
+ delete callbacks[id];
1609
+ };
1610
+ let id = 0;
1611
+ const create$3$1 = () => {
1612
+ return ++id;
1613
+ };
1614
+ const registerPromise = () => {
1615
+ const id = create$3$1();
1616
+ const {
1617
+ resolve,
1618
+ promise
1619
+ } = Promise.withResolvers();
1620
+ set$1(id, resolve);
1621
+ return {
1622
+ id,
1623
+ promise
1624
+ };
1625
+ };
1626
+ const create$2$1 = (method, params) => {
1627
+ const {
1628
+ id,
1629
+ promise
1630
+ } = registerPromise();
1631
+ const message = {
1632
+ jsonrpc: Two,
1633
+ method,
1634
+ params,
1635
+ id
1636
+ };
1637
+ return {
1638
+ message,
1639
+ promise
1640
+ };
1641
+ };
1642
+ class JsonRpcError extends Error {
1643
+ constructor(message) {
1644
+ super(message);
1645
+ this.name = 'JsonRpcError';
1486
1646
  }
1487
- });
1488
-
1489
- const {
1490
- registerImplementationProvider,
1491
- executeImplementationProvider,
1492
- reset: reset$5
1493
- } = create$9({
1494
- name: 'Implementation',
1495
- resultShape: {
1496
- type: Array$1,
1497
- items: {
1498
- type: Object$1
1647
+ }
1648
+ const NewLine$1 = '\n';
1649
+ const DomException = 'DOMException';
1650
+ const ReferenceError$1 = 'ReferenceError';
1651
+ const SyntaxError$1 = 'SyntaxError';
1652
+ const TypeError$1 = 'TypeError';
1653
+ const getErrorConstructor = (message, type) => {
1654
+ if (type) {
1655
+ switch (type) {
1656
+ case DomException:
1657
+ return DOMException;
1658
+ case TypeError$1:
1659
+ return TypeError;
1660
+ case SyntaxError$1:
1661
+ return SyntaxError;
1662
+ case ReferenceError$1:
1663
+ return ReferenceError;
1664
+ default:
1665
+ return Error;
1499
1666
  }
1500
1667
  }
1501
- });
1502
-
1503
- const WebSocket$1 = 5;
1504
- const ElectronMessagePort = 6;
1505
- const ModuleWorkerAndWorkaroundForChromeDevtoolsBug$1 = 7;
1506
-
1507
- const getModule$3 = method => {
1508
- switch (method) {
1509
- case WebSocket$1:
1510
- return Promise.resolve().then(function () { return IpcParentWithWebSocket; });
1511
- case ElectronMessagePort:
1512
- return Promise.resolve().then(function () { return IpcParentWithNode; });
1513
- case ModuleWorkerAndWorkaroundForChromeDevtoolsBug$1:
1514
- return Promise.resolve().then(function () { return IpcParentWithModuleWorkerAndWorkaroundForChromeDevtoolsBug; });
1515
- default:
1516
- throw new Error('unexpected ipc type');
1668
+ if (message.startsWith('TypeError: ')) {
1669
+ return TypeError;
1517
1670
  }
1518
- };
1519
-
1520
- const create$7 = async ({
1521
- method,
1522
- ...options
1523
- }) => {
1524
- try {
1525
- const module = await getModule$3(method);
1526
- // @ts-ignore
1527
- const rawIpc = await module.create(options);
1528
- // @ts-ignore
1529
- const ipc = module.wrap(rawIpc);
1530
- return ipc;
1531
- } catch (error) {
1532
- throw new VError(error, `Failed to create ipc`);
1671
+ if (message.startsWith('SyntaxError: ')) {
1672
+ return SyntaxError;
1533
1673
  }
1534
- };
1535
-
1536
- const JsonRpc = 1;
1537
-
1538
- const getModule$2 = method => {
1539
- switch (method) {
1540
- case JsonRpc:
1541
- return Promise.resolve().then(function () { return RpcParentWithJsonRpc; });
1542
- default:
1543
- throw new Error('unexpected rpc type');
1674
+ if (message.startsWith('ReferenceError: ')) {
1675
+ return ReferenceError;
1544
1676
  }
1677
+ return Error;
1545
1678
  };
1546
-
1547
- const create$6 = async ({
1548
- method,
1549
- ...options
1550
- }) => {
1551
- const module = await getModule$2(method);
1552
- // @ts-ignore
1553
- const rpc = module.create(options);
1554
- return rpc;
1679
+ const constructError = (message, type, name) => {
1680
+ const ErrorConstructor = getErrorConstructor(message, type);
1681
+ if (ErrorConstructor === DOMException && name) {
1682
+ return new ErrorConstructor(message, name);
1683
+ }
1684
+ if (ErrorConstructor === Error) {
1685
+ const error = new Error(message);
1686
+ if (name && name !== 'VError') {
1687
+ error.name = name;
1688
+ }
1689
+ return error;
1690
+ }
1691
+ return new ErrorConstructor(message);
1555
1692
  };
1556
-
1557
- const defaultExecute$1 = () => {
1558
- throw new Error('not implemented');
1693
+ const getNewLineIndex = (string, startIndex = undefined) => {
1694
+ return string.indexOf(NewLine$1, startIndex);
1559
1695
  };
1560
- const createNodeRpc = async ({
1561
- path,
1562
- execute = defaultExecute$1,
1563
- name = ''
1564
- }) => {
1565
- try {
1566
- string(path);
1567
- fn(execute);
1568
- const ipc = await create$7({
1569
- method: ElectronMessagePort,
1570
- type: 'extension-host-helper-process',
1571
- name
1572
- });
1573
- const rpc = await create$6({
1574
- ipc,
1575
- method: JsonRpc,
1576
- execute
1577
- });
1578
- await rpc.invoke('LoadFile.loadFile', path);
1579
- return rpc;
1580
- } catch (error) {
1581
- throw new VError(error, `Failed to create node rpc`);
1696
+ const getParentStack = error => {
1697
+ let parentStack = error.stack || error.data || error.message || '';
1698
+ if (parentStack.startsWith(' at')) {
1699
+ parentStack = error.message + NewLine$1 + parentStack;
1582
1700
  }
1701
+ return parentStack;
1583
1702
  };
1584
-
1585
- const confirm = message => {
1586
- string(message);
1587
- const result = invoke('ConfirmPrompt.prompt', message);
1588
- return result;
1703
+ const joinLines$1 = lines => {
1704
+ return lines.join(NewLine$1);
1589
1705
  };
1590
-
1591
- const ExtensionHostQuickPickShow = 'ExtensionHostQuickPick.show';
1592
-
1593
- const showQuickPick = async ({
1594
- getPicks,
1595
- toPick
1596
- }) => {
1597
- const rawPicks = await getPicks();
1598
- const picks = rawPicks.map(toPick);
1599
- return invoke(ExtensionHostQuickPickShow, picks);
1706
+ const MethodNotFound = -32601;
1707
+ const Custom = -32001;
1708
+ const splitLines$2 = lines => {
1709
+ return lines.split(NewLine$1);
1600
1710
  };
1601
-
1602
- const {
1603
- registerReferenceProvider,
1604
- executeReferenceProvider,
1605
- executefileReferenceProvider,
1606
- reset: reset$4
1607
- } = create$9({
1608
- name: 'Reference',
1609
- resultShape: {
1610
- type: Array$1,
1611
- items: {
1612
- type: Object$1
1613
- }
1614
- },
1615
- additionalMethodNames: [
1616
- // @ts-ignore
1617
- {
1618
- name: 'fileReference',
1619
- methodName: 'provideFileReferences',
1620
- resultShape: {
1621
- type: Array$1,
1622
- items: {
1623
- type: Object$1
1711
+ const restoreJsonRpcError = error => {
1712
+ if (error && error instanceof Error) {
1713
+ return error;
1714
+ }
1715
+ const currentStack = joinLines$1(splitLines$2(new Error().stack || '').slice(1));
1716
+ if (error && error.code && error.code === MethodNotFound) {
1717
+ const restoredError = new JsonRpcError(error.message);
1718
+ const parentStack = getParentStack(error);
1719
+ restoredError.stack = parentStack + NewLine$1 + currentStack;
1720
+ return restoredError;
1721
+ }
1722
+ if (error && error.message) {
1723
+ const restoredError = constructError(error.message, error.type, error.name);
1724
+ if (error.data) {
1725
+ if (error.data.stack && error.data.type && error.message) {
1726
+ restoredError.stack = error.data.type + ': ' + error.message + NewLine$1 + error.data.stack + NewLine$1 + currentStack;
1727
+ } else if (error.data.stack) {
1728
+ restoredError.stack = error.data.stack;
1729
+ }
1730
+ if (error.data.codeFrame) {
1731
+ // @ts-ignore
1732
+ restoredError.codeFrame = error.data.codeFrame;
1733
+ }
1734
+ if (error.data.code) {
1735
+ // @ts-ignore
1736
+ restoredError.code = error.data.code;
1737
+ }
1738
+ if (error.data.type) {
1739
+ // @ts-ignore
1740
+ restoredError.name = error.data.type;
1741
+ }
1742
+ } else {
1743
+ if (error.stack) {
1744
+ const lowerStack = restoredError.stack || '';
1745
+ // @ts-ignore
1746
+ const indexNewLine = getNewLineIndex(lowerStack);
1747
+ const parentStack = getParentStack(error);
1748
+ // @ts-ignore
1749
+ restoredError.stack = parentStack + lowerStack.slice(indexNewLine);
1750
+ }
1751
+ if (error.codeFrame) {
1752
+ // @ts-ignore
1753
+ restoredError.codeFrame = error.codeFrame;
1624
1754
  }
1625
1755
  }
1626
- }]
1627
- });
1628
-
1629
- const {
1630
- registerRenameProvider,
1631
- executeRenameProvider,
1632
- executeprepareRenameProvider,
1633
- reset: reset$3
1634
- } = create$9({
1635
- name: 'Rename',
1636
- resultShape: {
1637
- type: Object$1,
1638
- allowUndefined: true
1639
- },
1640
- additionalMethodNames: [
1641
- // @ts-ignore
1642
- {
1643
- name: 'prepareRename',
1644
- methodName: 'prepareRename',
1645
- resultShape: {
1646
- type: Object$1,
1647
- allowUndefined: true
1648
- }
1649
- }]
1650
- });
1651
-
1652
- const getExtensionHostSubWorkerUrl = () => {
1653
- return new URL('../../../../extension-host-sub-worker/src/extensionHostSubWorkerMain.js', import.meta.url).toString();
1654
- };
1655
- const extensionHostSubWorkerUrl = getExtensionHostSubWorkerUrl();
1656
-
1657
- const set$2 = async (url, contentSecurityPolicy) => {
1658
- const pathName = new URL(url).pathname;
1659
- await invoke('ExtensionHostWorkerContentSecurityPolicy.set', pathName, contentSecurityPolicy);
1660
- };
1661
-
1662
- const rpcs$1 = Object.create(null);
1663
- const add$1 = (id, rpc) => {
1664
- rpcs$1[id] = rpc;
1665
- };
1666
- const get$2 = id => {
1667
- return rpcs$1[id];
1668
- };
1669
-
1670
- const registry = Object.create(null);
1671
- const rpcs = Object.create(null);
1672
- const register = (id, execute) => {
1673
- registry[id] = execute;
1674
- };
1675
- const acquire = id => {
1676
- const fn = registry[id];
1677
- delete registry[id];
1678
- return fn;
1679
- };
1680
- const get$1 = id => {
1681
- return rpcs[id];
1682
- };
1683
- const set$1 = (id, rpc) => {
1684
- rpcs[id] = rpc;
1685
- };
1686
-
1687
- const createRpcWithId$1 = async id => {
1688
- const fn = acquire(id);
1689
- const info = get$2(id);
1690
- if (!info) {
1691
- throw new Error(`rpc with id ${id} not found`);
1756
+ return restoredError;
1692
1757
  }
1693
- const ipc = await create$7({
1694
- method: ModuleWorkerAndWorkaroundForChromeDevtoolsBug$1,
1695
- url: extensionHostSubWorkerUrl,
1696
- name: info.name
1697
- });
1698
- const newRpc = await create$6({
1699
- ipc,
1700
- method: JsonRpc,
1701
- execute: fn
1702
- });
1703
- await newRpc.invoke('LoadFile.loadFile', info.url);
1704
- set$1(id, newRpc);
1705
- return newRpc;
1706
- };
1707
-
1708
- const getOrCreateRpc = async id => {
1709
- const rpc = get$1(id);
1710
- if (!rpc) {
1711
- set$1(id, createRpcWithId$1(id));
1758
+ if (typeof error === 'string') {
1759
+ return new Error(`JsonRpc Error: ${error}`);
1712
1760
  }
1713
- return get$1(id);
1761
+ return new Error(`JsonRpc Error: ${error}`);
1714
1762
  };
1715
- const createRpcWithId = ({
1716
- id,
1717
- execute
1718
- }) => {
1719
- string(id);
1720
- register(id, execute);
1721
- const lazyRpc = {
1722
- async invoke(method, ...params) {
1723
- const rpc = await getOrCreateRpc(id);
1724
- return rpc.invoke(method, ...params);
1725
- }
1726
- };
1727
- return lazyRpc;
1763
+ const unwrapJsonRpcResult = responseMessage => {
1764
+ if ('error' in responseMessage) {
1765
+ const restoredError = restoreJsonRpcError(responseMessage.error);
1766
+ throw restoredError;
1767
+ }
1768
+ if ('result' in responseMessage) {
1769
+ return responseMessage.result;
1770
+ }
1771
+ throw new JsonRpcError('unexpected response message');
1728
1772
  };
1729
-
1730
- const defaultExecute = () => {
1731
- throw new Error('not implemented');
1773
+ const warn = (...args) => {
1774
+ console.warn(...args);
1732
1775
  };
1733
-
1734
- /**
1735
- *
1736
- * @deprecated
1737
- */
1738
- const createLegacyRpc = async ({
1739
- url,
1740
- name,
1741
- execute = defaultExecute,
1742
- contentSecurityPolicy
1743
- }) => {
1744
- string(url);
1745
- string(name);
1746
- fn(execute);
1747
- if (contentSecurityPolicy) {
1748
- await set$2(url, contentSecurityPolicy);
1776
+ const resolve = (id, response) => {
1777
+ const fn = get$1(id);
1778
+ if (!fn) {
1779
+ console.log(response);
1780
+ warn(`callback ${id} may already be disposed`);
1781
+ return;
1749
1782
  }
1750
- const ipc = await create$7({
1751
- method: ModuleWorkerAndWorkaroundForChromeDevtoolsBug$1,
1752
- url: extensionHostSubWorkerUrl,
1753
- name
1754
- });
1755
- const rpc = await create$6({
1756
- ipc,
1757
- method: JsonRpc,
1758
- execute
1759
- });
1760
- await rpc.invoke('LoadFile.loadFile', url);
1761
- return rpc;
1783
+ fn(response);
1784
+ remove(id);
1762
1785
  };
1763
- const createRpc = ({
1764
- id,
1765
- url,
1766
- name,
1767
- execute = defaultExecute,
1768
- contentSecurityPolicy
1769
- }) => {
1770
- try {
1771
- if (id) {
1772
- string(id);
1773
- return createRpcWithId({
1774
- id,
1775
- execute
1776
- });
1777
- }
1778
- return createLegacyRpc({
1779
- url,
1780
- name,
1781
- execute,
1782
- contentSecurityPolicy
1783
- });
1784
- } catch (error) {
1785
- throw new VError(error, `Failed to create webworker rpc`);
1786
+ const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
1787
+ const getErrorType = prettyError => {
1788
+ if (prettyError && prettyError.type) {
1789
+ return prettyError.type;
1786
1790
  }
1791
+ if (prettyError && prettyError.constructor && prettyError.constructor.name) {
1792
+ return prettyError.constructor.name;
1793
+ }
1794
+ return undefined;
1787
1795
  };
1788
-
1789
- const {
1790
- registerSelectionProvider,
1791
- executeSelectionProvider,
1792
- reset: reset$2
1793
- } = create$9({
1794
- name: 'Selection',
1795
- resultShape: {
1796
- allowUndefined: true,
1797
- type: Array$1,
1798
- items: {
1799
- type: 'number'
1800
- }
1796
+ const getErrorProperty = (error, prettyError) => {
1797
+ if (error && error.code === E_COMMAND_NOT_FOUND) {
1798
+ return {
1799
+ code: MethodNotFound,
1800
+ message: error.message,
1801
+ data: error.stack
1802
+ };
1801
1803
  }
1802
- });
1803
-
1804
- const state$5 = {
1805
- providers: Object.create(null)
1804
+ return {
1805
+ code: Custom,
1806
+ message: prettyError.message,
1807
+ data: {
1808
+ stack: prettyError.stack,
1809
+ codeFrame: prettyError.codeFrame,
1810
+ type: getErrorType(prettyError),
1811
+ code: prettyError.code,
1812
+ name: prettyError.name
1813
+ }
1814
+ };
1815
+ };
1816
+ const create$1$1 = (message, error) => {
1817
+ return {
1818
+ jsonrpc: Two,
1819
+ id: message.id,
1820
+ error
1821
+ };
1806
1822
  };
1807
- const registerSourceControlProvider = provider => {
1808
- state$5.providers[provider.id] = provider;
1823
+ const getErrorResponse = (message, error, preparePrettyError, logError) => {
1824
+ const prettyError = preparePrettyError(error);
1825
+ logError(error, prettyError);
1826
+ const errorProperty = getErrorProperty(error, prettyError);
1827
+ return create$1$1(message, errorProperty);
1809
1828
  };
1810
- const getFilesFromProvider = provider => {
1811
- return provider.getChangedFiles();
1829
+ const create$7 = (message, result) => {
1830
+ return {
1831
+ jsonrpc: Two,
1832
+ id: message.id,
1833
+ result: result ?? null
1834
+ };
1812
1835
  };
1813
- const getChangedFiles = async providerId => {
1814
- const provider = state$5.providers[providerId];
1815
- if (!provider) {
1816
- throw new Error('no source control provider found');
1817
- }
1818
- const changedFiles = await getFilesFromProvider(provider);
1819
- const flattenedChangedFiles = changedFiles;
1820
- return flattenedChangedFiles;
1836
+ const getSuccessResponse = (message, result) => {
1837
+ const resultProperty = result ?? null;
1838
+ return create$7(message, resultProperty);
1821
1839
  };
1822
- const getFileBefore = async (providerId, uri) => {
1823
- string(providerId);
1824
- string(uri);
1825
- const provider = state$5.providers[providerId];
1826
- if (!provider) {
1827
- throw new Error('no source control provider found');
1840
+ const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
1841
+ try {
1842
+ const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
1843
+ return getSuccessResponse(message, result);
1844
+ } catch (error) {
1845
+ return getErrorResponse(message, error, preparePrettyError, logError);
1828
1846
  }
1829
- return provider.getFileBefore(uri);
1830
1847
  };
1831
- const getGroupsFromProvider = async (provider, cwd) => {
1832
- if (provider.getGroups) {
1833
- return provider.getGroups(cwd);
1834
- }
1835
- if (provider.getChangedFiles) {
1836
- const files = await provider.getChangedFiles();
1837
- const groups = [{
1838
- id: 'changes',
1839
- label: 'Changes',
1840
- items: files
1841
- }];
1842
- return groups;
1843
- }
1844
- throw new Error('source control provider is missing required function getGroups');
1848
+ const defaultPreparePrettyError = error => {
1849
+ return error;
1845
1850
  };
1846
- const getGroups = async (providerId, cwd) => {
1847
- const provider = state$5.providers[providerId];
1848
- if (!provider) {
1849
- throw new Error('no source control provider found');
1850
- }
1851
- const groups = await getGroupsFromProvider(provider, cwd);
1852
- return groups;
1851
+ const defaultLogError = () => {
1852
+ // ignore
1853
1853
  };
1854
- const acceptInput = async (providerId, value) => {
1855
- const provider = state$5.providers[providerId];
1856
- if (!provider) {
1857
- throw new Error('no source control provider found');
1854
+ const defaultRequiresSocket = () => {
1855
+ return false;
1856
+ };
1857
+ const defaultResolve = resolve;
1858
+
1859
+ // TODO maybe remove this in v6 or v7, only accept options object to simplify the code
1860
+ const normalizeParams = args => {
1861
+ if (args.length === 1) {
1862
+ const options = args[0];
1863
+ return {
1864
+ ipc: options.ipc,
1865
+ message: options.message,
1866
+ execute: options.execute,
1867
+ resolve: options.resolve || defaultResolve,
1868
+ preparePrettyError: options.preparePrettyError || defaultPreparePrettyError,
1869
+ logError: options.logError || defaultLogError,
1870
+ requiresSocket: options.requiresSocket || defaultRequiresSocket
1871
+ };
1858
1872
  }
1859
- await provider.acceptInput(value);
1873
+ return {
1874
+ ipc: args[0],
1875
+ message: args[1],
1876
+ execute: args[2],
1877
+ resolve: args[3],
1878
+ preparePrettyError: args[4],
1879
+ logError: args[5],
1880
+ requiresSocket: args[6]
1881
+ };
1860
1882
  };
1861
- const add = async path => {
1862
- const provider = Object.values(state$5.providers)[0];
1863
- if (!provider) {
1883
+ const handleJsonRpcMessage = async (...args) => {
1884
+ const options = normalizeParams(args);
1885
+ const {
1886
+ message,
1887
+ ipc,
1888
+ execute,
1889
+ resolve,
1890
+ preparePrettyError,
1891
+ logError,
1892
+ requiresSocket
1893
+ } = options;
1894
+ if ('id' in message) {
1895
+ if ('method' in message) {
1896
+ const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
1897
+ try {
1898
+ ipc.send(response);
1899
+ } catch (error) {
1900
+ const errorResponse = getErrorResponse(message, error, preparePrettyError, logError);
1901
+ ipc.send(errorResponse);
1902
+ }
1903
+ return;
1904
+ }
1905
+ resolve(message.id, message);
1864
1906
  return;
1865
1907
  }
1866
- // @ts-ignore
1867
- await provider.add(path);
1868
- };
1869
- const discard = async path => {
1870
- const provider = Object.values(state$5.providers)[0];
1871
- if (!provider) {
1908
+ if ('method' in message) {
1909
+ await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
1872
1910
  return;
1873
1911
  }
1874
- // @ts-ignore
1875
- await provider.discard(path);
1912
+ throw new JsonRpcError('unexpected message');
1876
1913
  };
1877
- const getEnabledProviderIds = async (scheme, root) => {
1878
- string(scheme);
1879
- string(root);
1880
- const providers = Object.values(state$5.providers);
1881
- const enabledIds = [];
1882
- for (const provider of providers) {
1883
- // @ts-ignore
1884
- if (typeof provider.isActive !== 'function') {
1885
- continue;
1886
- }
1887
- // @ts-ignore
1888
- const isActive = await provider.isActive(scheme, root);
1889
- if (isActive) {
1890
- // @ts-ignore
1891
- enabledIds.push(provider.id);
1892
- }
1914
+ const invokeHelper = async (ipc, method, params, useSendAndTransfer) => {
1915
+ const {
1916
+ message,
1917
+ promise
1918
+ } = create$2$1(method, params);
1919
+ if (useSendAndTransfer && ipc.sendAndTransfer) {
1920
+ ipc.sendAndTransfer(message);
1921
+ } else {
1922
+ ipc.send(message);
1893
1923
  }
1894
- return enabledIds;
1924
+ const responseMessage = await promise;
1925
+ return unwrapJsonRpcResult(responseMessage);
1895
1926
  };
1896
-
1897
- const {
1898
- registerTabCompletionProvider,
1899
- executeTabCompletionProvider,
1900
- reset: reset$1
1901
- } = create$9({
1902
- name: 'TabCompletion',
1903
- resultShape: {
1904
- type: Object$1,
1905
- allowUndefined: true
1906
- }
1907
- });
1908
-
1909
- const state$4 = {
1910
- textSearchProviders: Object.create(null)
1927
+ const send = (transport, method, ...params) => {
1928
+ const message = create$4$1(method, params);
1929
+ transport.send(message);
1911
1930
  };
1912
- const registerTextSearchProvider = textSearchProvider => {
1913
- try {
1914
- if (!textSearchProvider) {
1915
- throw new Error('textSearchProvider is not defined');
1916
- }
1917
- if (!textSearchProvider.scheme) {
1918
- throw new Error('textSearchProvider is missing scheme');
1919
- }
1920
- state$4.textSearchProviders[textSearchProvider.scheme] = textSearchProvider;
1921
- } catch (error) {
1922
- throw new VError(error, 'Failed to register text search provider');
1923
- }
1931
+ const invoke = (ipc, method, ...params) => {
1932
+ return invokeHelper(ipc, method, params, false);
1924
1933
  };
1925
- const executeTextSearchProvider = async (scheme, query) => {
1926
- try {
1927
- const textSearchProvider = state$4.textSearchProviders[scheme];
1928
- if (!textSearchProvider) {
1929
- throw new Error(`No text search provider for ${scheme} found`);
1930
- }
1931
- const results = await textSearchProvider.provideTextSearchResults(query);
1932
- return results;
1933
- } catch (error) {
1934
- throw new VError(error, 'Failed to execute text search provider');
1935
- }
1934
+ const invokeAndTransfer = (ipc, method, ...params) => {
1935
+ return invokeHelper(ipc, method, params, true);
1936
1936
  };
1937
1937
 
1938
- const {
1939
- registerTypeDefinitionProvider,
1940
- executeTypeDefinitionProvider,
1941
- reset
1942
- } = create$9({
1943
- name: 'TypeDefinition',
1944
- resultShape: {
1945
- allowUndefined: true,
1946
- type: Object$1,
1947
- properties: {
1948
- uri: {
1949
- type: String
1950
- },
1951
- startOffset: {
1952
- type: Number
1953
- },
1954
- endOffset: {
1955
- type: Number
1956
- }
1957
- }
1938
+ const commands = Object.create(null);
1939
+ const register = commandMap => {
1940
+ Object.assign(commands, commandMap);
1941
+ };
1942
+ const getCommand = key => {
1943
+ return commands[key];
1944
+ };
1945
+ const execute = (command, ...args) => {
1946
+ const fn = getCommand(command);
1947
+ if (!fn) {
1948
+ throw new Error(`command not found ${command}`);
1958
1949
  }
1959
- });
1950
+ return fn(...args);
1951
+ };
1960
1952
 
1961
- const RE_PROTOCOL = /^([a-z\-]+):\/\//;
1962
- const getProtocol = uri => {
1963
- const protocolMatch = uri.match(RE_PROTOCOL);
1964
- if (protocolMatch) {
1965
- return protocolMatch[1];
1966
- }
1967
- return '';
1953
+ const requiresSocket$2 = () => {
1954
+ return false;
1955
+ };
1956
+ const preparePrettyError$2 = error => {
1957
+ return error;
1958
+ };
1959
+ const logError$2 = error => {
1960
+ // handled by renderer worker
1961
+ };
1962
+ const handleMessage$1 = event => {
1963
+ return handleJsonRpcMessage(event.target, event.data, execute, resolve, preparePrettyError$2, logError$2, requiresSocket$2);
1968
1964
  };
1969
1965
 
1970
- const getPortTuple = () => {
1971
- const {
1972
- port1,
1973
- port2
1974
- } = new MessageChannel();
1975
- return {
1976
- port1,
1977
- port2
1978
- };
1966
+ const handleIpc$1 = ipc => {
1967
+ ipc.addEventListener('message', handleMessage$1);
1979
1968
  };
1980
1969
 
1981
1970
  const createWebViewIpc = async webView => {
@@ -1991,7 +1980,7 @@ const createWebViewIpc = async webView => {
1991
1980
  port2.onmessage = resolve;
1992
1981
  });
1993
1982
  const portType = 'test';
1994
- await invokeAndTransfer('WebView.setPort', uid, port1, origin, portType);
1983
+ await invokeAndTransfer$1('WebView.setPort', uid, port1, origin, portType);
1995
1984
  const event = await promise;
1996
1985
  // @ts-ignore
1997
1986
  if (event.data !== 'ready') {
@@ -2016,7 +2005,7 @@ const createWebViewIpc = async webView => {
2016
2005
  };
2017
2006
  // TODO maybe don't send a message port only to get object url?
2018
2007
  // TODO dispose ipc to avoid memory leak
2019
- handleIpc(ipc);
2008
+ handleIpc$1(ipc);
2020
2009
  return ipc;
2021
2010
  };
2022
2011
 
@@ -2050,8 +2039,8 @@ const getRemoteUrlForWebView = async (uri, options = {}) => {
2050
2039
  if (!webView) {
2051
2040
  throw new Error(`webview ${options.webViewId} not found`);
2052
2041
  }
2053
- const [ipc, blob] = await Promise.all([createWebViewIpc(webView), invoke('FileSystem.getBlob', uri)]);
2054
- const objectUrl = await invoke$1(ipc, 'createObjectUrl', blob);
2042
+ const [ipc, blob] = await Promise.all([createWebViewIpc(webView), invoke$1('FileSystem.getBlob', uri)]);
2043
+ const objectUrl = await invoke(ipc, 'createObjectUrl', blob);
2055
2044
  return objectUrl;
2056
2045
  };
2057
2046
 
@@ -2081,18 +2070,26 @@ const getPlatform = () => {
2081
2070
  const platform = getPlatform(); // TODO tree-shake this out in production
2082
2071
 
2083
2072
  const getRemoteUrl = async (uri, options = {}) => {
2073
+ // TODO uri should always have protocol
2074
+ // then ask file system provider for remote url, for example disk file system provider or html file system provider
2084
2075
  const protocol = getProtocol(uri);
2085
2076
  if (platform === Remote && !protocol) {
2077
+ if (uri.startsWith('/')) {
2078
+ return `/remote${uri}`;
2079
+ }
2086
2080
  return `/remote/${uri}`;
2087
2081
  }
2088
2082
  if (platform === Electron && !protocol) {
2083
+ if (uri.startsWith('/')) {
2084
+ return `/remote${uri}`;
2085
+ }
2089
2086
  return `/remote/${uri}`;
2090
2087
  }
2091
2088
  if (options.webViewId) {
2092
2089
  return getRemoteUrlForWebView(uri, options);
2093
2090
  }
2094
2091
  if (uri.startsWith('html://')) {
2095
- const url = await invoke('Blob.getSrc', uri);
2092
+ const url = await invoke$1('Blob.getSrc', uri);
2096
2093
  return url;
2097
2094
  }
2098
2095
  throw new Error(`unsupported platform for remote url`);
@@ -2202,7 +2199,7 @@ const createWorker = async ({
2202
2199
  string(method);
2203
2200
  string(url);
2204
2201
  string(name);
2205
- const ipc = create$7({
2202
+ const ipc = create$9({
2206
2203
  method: ModuleWorkerAndWorkaroundForChromeDevtoolsBug$1,
2207
2204
  url,
2208
2205
  name
@@ -2290,7 +2287,7 @@ const api = {
2290
2287
  registerHoverProvider: registerHoverProvider,
2291
2288
  executeHoverProvider: executeHoverProvider,
2292
2289
  // Rpc
2293
- createRpc: createRpc,
2290
+ createRpc: createRpc$1,
2294
2291
  createNodeRpc: createNodeRpc,
2295
2292
  // Implementation
2296
2293
  registerImplementationProvider: registerImplementationProvider,
@@ -2333,967 +2330,1094 @@ const api = {
2333
2330
  getWorkspaceFolder: getWorkspaceFolder
2334
2331
  };
2335
2332
 
2336
- const BraceCompletionExecuteBraceCompletionProvider = 'ExtensionHostBraceCompletion.executeBraceCompletionProvider';
2337
- const ClosingTagExecuteClosingTagProvider = 'ExtensionHostClosingTag.executeClosingTagProvider';
2338
- const CommandExecute = 'ExtensionHostCommand.executeCommand';
2339
- const CompletionExecute = 'ExtensionHostCompletion.execute';
2340
- const CompletionResolveExecute = 'ExtensionHostCompletion.executeResolve';
2341
- const DefinitionExecuteDefinitionProvider = 'ExtensionHostDefinition.executeDefinitionProvider';
2342
- const DiagnosticExecuteDiagnosticProvider = 'ExtensionHost.executeDiagnosticProvider';
2343
- const ExtensionActivate = 'ExtensionHostExtension.activate';
2344
- const FileSystemGetPathSeparator = 'ExtensionHostFileSystem.getPathSeparator';
2345
- const FileSystemReadDirWithFileTypes = 'ExtensionHostFileSystem.readDirWithFileTypes';
2346
- const FileSystemReadFile = 'ExtensionHostFileSystem.readFile';
2347
- const FileSystemWriteFile = 'ExtensionHostFileSystem.writeFile';
2348
- const FormattingExecuteFormmattingProvider = 'ExtensionHostFormatting.executeFormattingProvider';
2349
- const HoverExecute = 'ExtensionHostHover.execute';
2350
- const ImplementationExecuteImplementationProvider = 'ExtensionHostImplementation.executeImplementationProvider';
2351
- const MockExec = 'ExtensionHostMockExec.mockExec';
2352
- const MockRpc = 'ExtensionHostMockRpc.mockRpc';
2353
- const OrganizeImportsExecute = 'ExtensionHostOrganizeImports.execute';
2354
- const ReferenceExecuteFileReferenceProvider = 'ExtensionHostReference.executeFileReferenceProvider';
2355
- const ReferenceExecuteReferenceProvider = 'ExtensionHostReference.executeReferenceProvider';
2356
- const SourceControlAcceptInput = 'ExtensionHostSourceControl.acceptInput';
2357
- const SourceControlAdd = 'ExtensionHostSourceControl.add';
2358
- const SourceControlDiscard = 'ExtensionHostSourceControl.discard';
2359
- const SourceControlGetChangedFiles = 'ExtensionHost.sourceControlGetChangedFiles';
2360
- const SourceControlGetEnabledProviderIds = 'ExtensionHostSourceControl.getEnabledProviderIds';
2361
- const SourceControlGetFileBefore = 'ExtensionHostSourceControl.GetFileBefore';
2362
- const SourceControlGetGroups = 'ExtensionHostSourceControl.getGroups';
2363
- const StatusBarGetStatusBarItems = 'ExtensionHost.getStatusBarItems';
2364
- const StatusBarRegisterChangeListener = 'ExtensionHostStatusBar.registerChangeListener';
2365
- const TabCompletionExecuteTabCompletionProvider = 'ExtensionHost.executeTabCompletionProvider';
2366
- const TextDocumentSetLanguageId = 'ExtensionHostTextDocument.setLanguageId';
2367
- const TextDocumentSyncFull = 'ExtensionHostTextDocument.syncFull';
2368
- const TextDocumentSyncIncremental = 'ExtensionHostTextDocument.syncIncremental';
2369
- const TextSearchExecuteTextSearchProvider = 'ExtensionHostTextSearch.executeTextSearchProvider';
2370
- const TypeDefinitionExecuteTypeDefinitionProvider = 'ExtensionHostTypeDefinition.executeTypeDefinitionProvider';
2371
- const WorkspaceSetPath = 'Workspace.setWorkspacePath';
2372
- const SelectionExecuteSelectionProvider = 'ExtensionHostSelection.executeSelectionProvider';
2373
- const ConfigurationSetConfiguration = 'ExtensionHostConfiguration.setConfiguration';
2333
+ const handleError = async error => {
2334
+ console.error(error);
2335
+ };
2374
2336
 
2375
- const create$5 = () => {
2337
+ /**
2338
+ * @param {ErrorEvent} event
2339
+ */
2340
+ const handleUnhandledError = async event => {
2341
+ try {
2342
+ event.preventDefault();
2343
+ await handleError(event.error);
2344
+ } catch {
2345
+ console.error(event.error);
2346
+ }
2347
+ };
2348
+
2349
+ const processName = `extension host worker`;
2350
+
2351
+ const getOutput = error => {
2352
+ const errorMessage = error && error.message ? error.message : String(error);
2353
+ const prefix = `[${processName}] Unhandled Rejection: ${errorMessage}`;
2354
+ if (error && error.stack) {
2355
+ return `${prefix}\n${error.stack}`;
2356
+ }
2357
+ return prefix;
2358
+ };
2359
+ const handleUnhandledRejection = event => {
2360
+ if (event instanceof PromiseRejectionEvent) {
2361
+ event.preventDefault();
2362
+ const output = getOutput(event.reason);
2363
+ console.error(output);
2364
+ return;
2365
+ }
2366
+ const output = getOutput(event);
2367
+ console.error(output);
2368
+ };
2369
+
2370
+ const state$2 = {
2371
+ /**
2372
+ * @type {any[]}
2373
+ */
2374
+ errors: []
2375
+ };
2376
+ const addError = error => {
2377
+ // @ts-ignore
2378
+ state$2.errors.push(error);
2379
+ };
2380
+ const hasRecentErrors = () => {
2381
+ return state$2.errors.length > 0;
2382
+ };
2383
+ const getRecentError = () => {
2384
+ };
2385
+
2386
+ const handleContentSecurityPolicyViolation = event => {
2387
+ const {
2388
+ violatedDirective,
2389
+ sourceFile,
2390
+ lineNumber,
2391
+ columnNumber
2392
+ } = event;
2393
+ addError({
2394
+ violatedDirective,
2395
+ sourceFile,
2396
+ lineNumber,
2397
+ columnNumber
2398
+ });
2399
+ };
2400
+
2401
+ const setStackTraceLimit = (errorConstructor, value) => {
2402
+ if (errorConstructor.stackTraceLimit && errorConstructor.stackTraceLimit < value) {
2403
+ errorConstructor.stackTraceLimit = value;
2404
+ }
2405
+ };
2406
+
2407
+ const setup = ({
2408
+ global,
2409
+ errorConstructor
2410
+ }) => {
2411
+ setStackTraceLimit(errorConstructor, 20);
2412
+ global.onerror ||= handleUnhandledError;
2413
+ global.onunhandledrejection ||= handleUnhandledRejection;
2414
+ if ('SecurityPolicyViolationEvent' in self) {
2415
+ global.addEventListener('securitypolicyviolation', handleContentSecurityPolicyViolation);
2416
+ }
2417
+ // @ts-ignore
2418
+ global.vscode = api;
2419
+ };
2420
+
2421
+ const walkValue = (value, transferrables, isTransferrable) => {
2422
+ if (!value) {
2423
+ return;
2424
+ }
2425
+ if (isTransferrable(value)) {
2426
+ transferrables.push(value);
2427
+ return;
2428
+ }
2429
+ if (Array.isArray(value)) {
2430
+ for (const item of value) {
2431
+ walkValue(item, transferrables, isTransferrable);
2432
+ }
2433
+ return;
2434
+ }
2435
+ if (typeof value === 'object') {
2436
+ for (const property of Object.values(value)) {
2437
+ walkValue(property, transferrables, isTransferrable);
2438
+ }
2439
+ return;
2440
+ }
2441
+ };
2442
+ const isMessagePort = value => {
2443
+ return value && value instanceof MessagePort;
2444
+ };
2445
+ const isMessagePortMain = value => {
2446
+ return value && value.constructor && value.constructor.name === 'MessagePortMain';
2447
+ };
2448
+ const isOffscreenCanvas = value => {
2449
+ return typeof OffscreenCanvas !== 'undefined' && value instanceof OffscreenCanvas;
2450
+ };
2451
+ const isInstanceOf = (value, constructorName) => {
2452
+ return value?.constructor?.name === constructorName;
2453
+ };
2454
+ const isSocket = value => {
2455
+ return isInstanceOf(value, 'Socket');
2456
+ };
2457
+ const transferrables = [isMessagePort, isMessagePortMain, isOffscreenCanvas, isSocket];
2458
+ const isTransferrable = value => {
2459
+ for (const fn of transferrables) {
2460
+ if (fn(value)) {
2461
+ return true;
2462
+ }
2463
+ }
2464
+ return false;
2465
+ };
2466
+ const getTransferrables = value => {
2467
+ const transferrables = [];
2468
+ walkValue(value, transferrables, isTransferrable);
2469
+ return transferrables;
2470
+ };
2471
+ const attachEvents = that => {
2472
+ const handleMessage = (...args) => {
2473
+ const data = that.getData(...args);
2474
+ that.dispatchEvent(new MessageEvent('message', {
2475
+ data
2476
+ }));
2477
+ };
2478
+ that.onMessage(handleMessage);
2479
+ const handleClose = event => {
2480
+ that.dispatchEvent(new Event('close'));
2481
+ };
2482
+ that.onClose(handleClose);
2483
+ };
2484
+ class Ipc extends EventTarget {
2485
+ constructor(rawIpc) {
2486
+ super();
2487
+ this._rawIpc = rawIpc;
2488
+ attachEvents(this);
2489
+ }
2490
+ }
2491
+ const E_INCOMPATIBLE_NATIVE_MODULE = 'E_INCOMPATIBLE_NATIVE_MODULE';
2492
+ const E_MODULES_NOT_SUPPORTED_IN_ELECTRON = 'E_MODULES_NOT_SUPPORTED_IN_ELECTRON';
2493
+ const ERR_MODULE_NOT_FOUND = 'ERR_MODULE_NOT_FOUND';
2494
+ const NewLine = '\n';
2495
+ const joinLines = lines => {
2496
+ return lines.join(NewLine);
2497
+ };
2498
+ const splitLines$1 = lines => {
2499
+ return lines.split(NewLine);
2500
+ };
2501
+ const isModuleNotFoundMessage = line => {
2502
+ return line.includes('[ERR_MODULE_NOT_FOUND]');
2503
+ };
2504
+ const getModuleNotFoundError = stderr => {
2505
+ const lines = splitLines$1(stderr);
2506
+ const messageIndex = lines.findIndex(isModuleNotFoundMessage);
2507
+ const message = lines[messageIndex];
2508
+ return {
2509
+ message,
2510
+ code: ERR_MODULE_NOT_FOUND
2511
+ };
2512
+ };
2513
+ const RE_NATIVE_MODULE_ERROR = /^innerError Error: Cannot find module '.*.node'/;
2514
+ const RE_NATIVE_MODULE_ERROR_2 = /was compiled against a different Node.js version/;
2515
+ const RE_MESSAGE_CODE_BLOCK_START = /^Error: The module '.*'$/;
2516
+ const RE_MESSAGE_CODE_BLOCK_END = /^\s* at/;
2517
+ const RE_AT = /^\s+at/;
2518
+ const RE_AT_PROMISE_INDEX = /^\s*at async Promise.all \(index \d+\)$/;
2519
+ const isUnhelpfulNativeModuleError = stderr => {
2520
+ return RE_NATIVE_MODULE_ERROR.test(stderr) && RE_NATIVE_MODULE_ERROR_2.test(stderr);
2521
+ };
2522
+ const isMessageCodeBlockStartIndex = line => {
2523
+ return RE_MESSAGE_CODE_BLOCK_START.test(line);
2524
+ };
2525
+ const isMessageCodeBlockEndIndex = line => {
2526
+ return RE_MESSAGE_CODE_BLOCK_END.test(line);
2527
+ };
2528
+ const getMessageCodeBlock = stderr => {
2529
+ const lines = splitLines$1(stderr);
2530
+ const startIndex = lines.findIndex(isMessageCodeBlockStartIndex);
2531
+ const endIndex = startIndex + lines.slice(startIndex).findIndex(isMessageCodeBlockEndIndex, startIndex);
2532
+ const relevantLines = lines.slice(startIndex, endIndex);
2533
+ const relevantMessage = relevantLines.join(' ').slice('Error: '.length);
2534
+ return relevantMessage;
2535
+ };
2536
+ const getNativeModuleErrorMessage = stderr => {
2537
+ const message = getMessageCodeBlock(stderr);
2538
+ return {
2539
+ message: `Incompatible native node module: ${message}`,
2540
+ code: E_INCOMPATIBLE_NATIVE_MODULE
2541
+ };
2542
+ };
2543
+ const isModulesSyntaxError = stderr => {
2544
+ if (!stderr) {
2545
+ return false;
2546
+ }
2547
+ return stderr.includes('SyntaxError: Cannot use import statement outside a module');
2548
+ };
2549
+ const getModuleSyntaxError = () => {
2550
+ return {
2551
+ message: `ES Modules are not supported in electron`,
2552
+ code: E_MODULES_NOT_SUPPORTED_IN_ELECTRON
2553
+ };
2554
+ };
2555
+ const isModuleNotFoundError = stderr => {
2556
+ if (!stderr) {
2557
+ return false;
2558
+ }
2559
+ return stderr.includes('ERR_MODULE_NOT_FOUND');
2560
+ };
2561
+ const isNormalStackLine = line => {
2562
+ return RE_AT.test(line) && !RE_AT_PROMISE_INDEX.test(line);
2563
+ };
2564
+ const getDetails = lines => {
2565
+ const index = lines.findIndex(isNormalStackLine);
2566
+ if (index === -1) {
2567
+ return {
2568
+ actualMessage: joinLines(lines),
2569
+ rest: []
2570
+ };
2571
+ }
2572
+ let lastIndex = index - 1;
2573
+ while (++lastIndex < lines.length) {
2574
+ if (!isNormalStackLine(lines[lastIndex])) {
2575
+ break;
2576
+ }
2577
+ }
2376
2578
  return {
2377
- finished: false
2579
+ actualMessage: lines[index - 1],
2580
+ rest: lines.slice(index, lastIndex)
2378
2581
  };
2379
2582
  };
2380
- const cancel = token => {
2381
- token.finished = true;
2583
+ const getHelpfulChildProcessError = (stdout, stderr) => {
2584
+ if (isUnhelpfulNativeModuleError(stderr)) {
2585
+ return getNativeModuleErrorMessage(stderr);
2586
+ }
2587
+ if (isModulesSyntaxError(stderr)) {
2588
+ return getModuleSyntaxError();
2589
+ }
2590
+ if (isModuleNotFoundError(stderr)) {
2591
+ return getModuleNotFoundError(stderr);
2592
+ }
2593
+ const lines = splitLines$1(stderr);
2594
+ const {
2595
+ actualMessage,
2596
+ rest
2597
+ } = getDetails(lines);
2598
+ return {
2599
+ message: `${actualMessage}`,
2600
+ code: '',
2601
+ stack: rest
2602
+ };
2382
2603
  };
2383
- const isCanceled = token => {
2384
- return token.finished;
2604
+ let IpcError$1 = class IpcError extends VError {
2605
+ // @ts-ignore
2606
+ constructor(betterMessage, stdout = '', stderr = '') {
2607
+ if (stdout || stderr) {
2608
+ // @ts-ignore
2609
+ const {
2610
+ message,
2611
+ code,
2612
+ stack
2613
+ } = getHelpfulChildProcessError(stdout, stderr);
2614
+ const cause = new Error(message);
2615
+ // @ts-ignore
2616
+ cause.code = code;
2617
+ cause.stack = stack;
2618
+ super(cause, betterMessage);
2619
+ } else {
2620
+ super(betterMessage);
2621
+ }
2622
+ // @ts-ignore
2623
+ this.name = 'IpcError';
2624
+ // @ts-ignore
2625
+ this.stdout = stdout;
2626
+ // @ts-ignore
2627
+ this.stderr = stderr;
2628
+ }
2385
2629
  };
2386
-
2387
- const baseName = path => {
2388
- const slashIndex = path.lastIndexOf('/');
2389
- return path.slice(slashIndex + 1);
2630
+ const readyMessage = 'ready';
2631
+ const getData$2 = event => {
2632
+ return event.data;
2390
2633
  };
2391
- const getExtensionId = extension => {
2392
- if (extension && extension.id) {
2393
- return extension.id;
2634
+ const listen$8 = ({
2635
+ port
2636
+ }) => {
2637
+ return port;
2638
+ };
2639
+ const signal$8 = port => {
2640
+ port.postMessage(readyMessage);
2641
+ };
2642
+ class IpcChildWithMessagePort extends Ipc {
2643
+ constructor(port) {
2644
+ super(port);
2394
2645
  }
2395
- if (extension && extension.path) {
2396
- return baseName(extension.path);
2646
+ getData(event) {
2647
+ return getData$2(event);
2397
2648
  }
2398
- return '<unknown>';
2399
- };
2400
-
2401
- const getUrlPrefix = extensionPath => {
2402
- if (extensionPath.startsWith('http://') || extensionPath.startsWith('https://')) {
2403
- return extensionPath;
2649
+ send(message) {
2650
+ this._rawIpc.postMessage(message);
2404
2651
  }
2405
- if (platform === Web) {
2406
- return extensionPath;
2652
+ sendAndTransfer(message) {
2653
+ const transfer = getTransferrables(message);
2654
+ this._rawIpc.postMessage(message, transfer);
2407
2655
  }
2408
- if (extensionPath.startsWith('/')) {
2409
- return `/remote${extensionPath}`;
2656
+ dispose() {
2657
+ // ignore
2410
2658
  }
2411
- return `/remote/${extensionPath}`;
2659
+ onClose(callback) {
2660
+ // ignore
2661
+ }
2662
+ onMessage(callback) {
2663
+ this._rawIpc.addEventListener('message', callback);
2664
+ this._rawIpc.start();
2665
+ }
2666
+ }
2667
+ const wrap$f = port => {
2668
+ return new IpcChildWithMessagePort(port);
2412
2669
  };
2413
-
2414
- const handleRpcInfos = extension => {
2415
- try {
2416
- if (!extension) {
2417
- return;
2418
- }
2419
- const rpcs = extension.rpc;
2420
- const urlPrefix = getUrlPrefix(extension.path);
2421
- if (!rpcs) {
2422
- return;
2423
- }
2424
- if (!Array.isArray(rpcs)) {
2425
- return;
2426
- }
2427
- for (const rpc of rpcs) {
2428
- rpc.url = `${urlPrefix}/${rpc.url}`;
2429
- add$1(rpc.id, rpc);
2430
- }
2431
- } catch (error) {
2432
- console.warn(`Failed to handle extension rpcs: ${error}`);
2670
+ const IpcChildWithMessagePort$1 = {
2671
+ __proto__: null,
2672
+ listen: listen$8,
2673
+ signal: signal$8,
2674
+ wrap: wrap$f
2675
+ };
2676
+ const listen$7 = () => {
2677
+ // @ts-ignore
2678
+ if (typeof WorkerGlobalScope === 'undefined') {
2679
+ throw new TypeError('module is not in web worker scope');
2433
2680
  }
2681
+ return globalThis;
2434
2682
  };
2435
-
2436
- class ContentSecurityPolicyError extends Error {
2437
- constructor(violatedDirective, sourceFile, lineNumber, columnNumber) {
2438
- super(`Content Security Policy Violation: ${violatedDirective}`);
2439
- this.name = 'ContentSecurityPolicyError';
2440
- if (sourceFile) {
2441
- this.stack = `Content Security Policy Violation
2442
- at ${sourceFile}:${lineNumber}:${columnNumber}`;
2443
- } else {
2444
- this.stack = `Content Security Policy Violation
2445
- at <unknown>`;
2446
- }
2683
+ const signal$7 = global => {
2684
+ global.postMessage(readyMessage);
2685
+ };
2686
+ class IpcChildWithModuleWorker extends Ipc {
2687
+ getData(event) {
2688
+ return getData$2(event);
2689
+ }
2690
+ send(message) {
2691
+ // @ts-ignore
2692
+ this._rawIpc.postMessage(message);
2693
+ }
2694
+ sendAndTransfer(message) {
2695
+ const transfer = getTransferrables(message);
2696
+ // @ts-ignore
2697
+ this._rawIpc.postMessage(message, transfer);
2698
+ }
2699
+ dispose() {
2700
+ // ignore
2701
+ }
2702
+ onClose(callback) {
2703
+ // ignore
2704
+ }
2705
+ onMessage(callback) {
2706
+ this._rawIpc.addEventListener('message', callback);
2447
2707
  }
2448
2708
  }
2449
-
2450
- const state$2 = {
2451
- /**
2452
- * @type {any[]}
2453
- */
2454
- errors: []
2709
+ const wrap$e = global => {
2710
+ return new IpcChildWithModuleWorker(global);
2455
2711
  };
2456
- const addError = error => {
2712
+ const IpcChildWithModuleWorker$1 = {
2713
+ __proto__: null,
2714
+ listen: listen$7,
2715
+ signal: signal$7,
2716
+ wrap: wrap$e
2717
+ };
2718
+ const withResolvers$1 = () => {
2719
+ let _resolve;
2720
+ const promise = new Promise(resolve => {
2721
+ _resolve = resolve;
2722
+ });
2723
+ return {
2724
+ resolve: _resolve,
2725
+ promise
2726
+ };
2727
+ };
2728
+ const waitForFirstMessage = async port => {
2729
+ const {
2730
+ resolve,
2731
+ promise
2732
+ } = withResolvers$1();
2733
+ port.addEventListener('message', resolve, {
2734
+ once: true
2735
+ });
2736
+ const event = await promise;
2457
2737
  // @ts-ignore
2458
- state$2.errors.push(error);
2738
+ return event.data;
2459
2739
  };
2460
- const hasRecentErrors = () => {
2461
- return state$2.errors.length > 0;
2740
+ const listen$6 = async () => {
2741
+ const parentIpcRaw = listen$7();
2742
+ signal$7(parentIpcRaw);
2743
+ const parentIpc = wrap$e(parentIpcRaw);
2744
+ const firstMessage = await waitForFirstMessage(parentIpc);
2745
+ if (firstMessage.method !== 'initialize') {
2746
+ throw new IpcError$1('unexpected first message');
2747
+ }
2748
+ const type = firstMessage.params[0];
2749
+ if (type === 'message-port') {
2750
+ parentIpc.send({
2751
+ jsonrpc: '2.0',
2752
+ id: firstMessage.id,
2753
+ result: null
2754
+ });
2755
+ parentIpc.dispose();
2756
+ const port = firstMessage.params[1];
2757
+ return port;
2758
+ }
2759
+ return globalThis;
2760
+ };
2761
+ class IpcChildWithModuleWorkerAndMessagePort extends Ipc {
2762
+ constructor(port) {
2763
+ super(port);
2764
+ }
2765
+ getData(event) {
2766
+ return getData$2(event);
2767
+ }
2768
+ send(message) {
2769
+ this._rawIpc.postMessage(message);
2770
+ }
2771
+ sendAndTransfer(message) {
2772
+ const transfer = getTransferrables(message);
2773
+ this._rawIpc.postMessage(message, transfer);
2774
+ }
2775
+ dispose() {
2776
+ if (this._rawIpc.close) {
2777
+ this._rawIpc.close();
2778
+ }
2779
+ }
2780
+ onClose(callback) {
2781
+ // ignore
2782
+ }
2783
+ onMessage(callback) {
2784
+ this._rawIpc.addEventListener('message', callback);
2785
+ this._rawIpc.start();
2786
+ }
2787
+ }
2788
+ const wrap$d = port => {
2789
+ return new IpcChildWithModuleWorkerAndMessagePort(port);
2462
2790
  };
2463
- const getRecentError = () => {
2464
- return state$2.errors.at(-1);
2791
+ const IpcChildWithModuleWorkerAndMessagePort$1 = {
2792
+ __proto__: null,
2793
+ listen: listen$6,
2794
+ wrap: wrap$d
2465
2795
  };
2466
2796
 
2467
- const isImportErrorChrome = error => {
2468
- return error && error instanceof Error && error.message.startsWith('Failed to fetch dynamically imported module');
2797
+ const createRpc = ipc => {
2798
+ const rpc = {
2799
+ /**
2800
+ * @deprecated
2801
+ */
2802
+ send(method, ...params) {
2803
+ send(ipc, method, ...params);
2804
+ },
2805
+ invoke(method, ...params) {
2806
+ return invoke(ipc, method, ...params);
2807
+ },
2808
+ invokeAndTransfer(method, ...params) {
2809
+ return invokeAndTransfer(ipc, method, ...params);
2810
+ }
2811
+ };
2812
+ return rpc;
2469
2813
  };
2470
-
2471
- const isImportErrorFirefox = error => {
2472
- return error && error instanceof TypeError && error.message === 'error loading dynamically imported module';
2814
+ const requiresSocket$1 = () => {
2815
+ return false;
2473
2816
  };
2474
-
2475
- const isSyntaxError = error => {
2476
- return error instanceof SyntaxError;
2817
+ const preparePrettyError$1 = error => {
2818
+ return error;
2477
2819
  };
2478
-
2479
- const isImportError = error => {
2480
- return isImportErrorChrome(error) || isImportErrorFirefox(error) || isSyntaxError(error);
2820
+ const logError$1 = () => {
2821
+ // handled by renderer worker
2481
2822
  };
2482
-
2483
- const sleep = duration => {
2484
- const promiseCallback = (resolve, reject) => {
2485
- setTimeout(resolve, duration);
2486
- };
2487
- return new Promise(promiseCallback);
2823
+ const handleMessage = event => {
2824
+ const actualRequiresSocket = event?.target?.requiresSocket || requiresSocket$1;
2825
+ return handleJsonRpcMessage(event.target, event.data, execute, resolve, preparePrettyError$1, logError$1, actualRequiresSocket);
2488
2826
  };
2489
-
2490
- const NotFound = 404;
2491
-
2492
- const RE_LINE_COLUMN = /(.*)(?:\(\d+\:\d+\))/;
2493
- const getBabelErrorMessage = message => {
2494
- const match = message.match(RE_LINE_COLUMN);
2495
- if (match) {
2496
- return match[1].trim();
2827
+ const handleIpc = ipc => {
2828
+ if ('addEventListener' in ipc) {
2829
+ ipc.addEventListener('message', handleMessage);
2830
+ } else if ('on' in ipc) {
2831
+ // deprecated
2832
+ ipc.on('message', handleMessage);
2497
2833
  }
2498
- return message;
2499
2834
  };
2500
- class BabelParseError extends SyntaxError {
2501
- constructor(url, error) {
2502
- const message = getBabelErrorMessage(error.message);
2503
- super(message);
2504
- this.name = 'BabelParseError';
2505
- // @ts-ignore
2506
- const line = error.loc.line;
2507
- // @ts-ignore
2508
- const column = error.loc.column + 1;
2509
- this.stack = `${message}
2510
- at ${url}:${line}:${column}`;
2511
- }
2512
- }
2513
-
2514
- const getAssetDir = () => {
2515
- // @ts-ignore
2516
- if (typeof ASSET_DIR !== 'undefined') {
2517
- // @ts-ignore
2518
- return ASSET_DIR;
2519
- }
2520
- if (platform === Electron) {
2521
- return '../../../../..';
2835
+ const listen$1 = async (module, options) => {
2836
+ const rawIpc = await module.listen(options);
2837
+ if (module.signal) {
2838
+ module.signal(rawIpc);
2522
2839
  }
2523
- return '';
2524
- };
2525
- const assetDir = getAssetDir();
2526
-
2527
- const loadBabelParser = () => {
2528
- const url = `${assetDir}/js/babel-parser.js`;
2529
- return import(url);
2840
+ const ipc = module.wrap(rawIpc);
2841
+ return ipc;
2530
2842
  };
2531
-
2532
- const parse = async (code, options) => {
2533
- const BabelParse = await loadBabelParser();
2534
- return BabelParse.parse(code, options);
2843
+ const create$6 = async ({
2844
+ commandMap
2845
+ }) => {
2846
+ // TODO create a commandMap per rpc instance
2847
+ register(commandMap);
2848
+ const ipc = await listen$1(IpcChildWithModuleWorkerAndMessagePort$1);
2849
+ handleIpc(ipc);
2850
+ const rpc = createRpc(ipc);
2851
+ return rpc;
2535
2852
  };
2536
-
2537
- const Module = 'module';
2538
-
2539
- const getLineAndColumn = (text, start, end) => {
2540
- let index = -1;
2541
- let line = 0;
2542
- const column = 0;
2543
- while ((index = text.indexOf('\n', index + 1)) !== -1) {
2544
- line++;
2545
- if (index >= start) {
2546
- break;
2547
- }
2548
- }
2549
- return {
2550
- line,
2551
- column
2552
- };
2853
+ const WebWorkerRpcClient = {
2854
+ __proto__: null,
2855
+ create: create$6
2553
2856
  };
2554
2857
 
2555
- class DependencyNotFoundError extends Error {
2556
- constructor(code, start, end, dependencyRelativePath, dependencyUrl, sourceUrl) {
2557
- super(`Module not found "${dependencyRelativePath}"`);
2558
- const {
2559
- line,
2560
- column
2561
- } = getLineAndColumn(code, start);
2562
- this.stack = `${this.message}
2563
- at Module (${sourceUrl}:${line}:${column})`;
2564
- }
2565
- }
2566
-
2567
- const ArrowFunctionExpression = 'ArrowFunctionExpression';
2568
- const AwaitExpression = 'AwaitExpression';
2569
- const BlockStatement = 'BlockStatement';
2570
- const CallExpression = 'CallExpression';
2571
- const ExportAllDeclaration = 'ExportAllDeclaration';
2572
- const ExportNamedDeclaration = 'ExportNamedDeclaration';
2573
- const ExpressionStatement = 'ExpressionStatement';
2574
- const File$1 = 'File';
2575
- const Import = 'Import';
2576
- const ImportDeclaration = 'ImportDeclaration';
2577
- const Program = 'Program';
2578
- const StringLiteral = 'StringLiteral';
2579
- const VariableDeclaration = 'VariableDeclaration';
2580
- const VariableDeclarator = 'VariableDeclarator';
2581
-
2582
- const walk = (node, visitor) => {
2583
- if (!node) {
2584
- return;
2585
- }
2586
- if (Array.isArray(node)) {
2587
- for (const item of node) {
2588
- walk(item, visitor);
2589
- }
2590
- return;
2591
- }
2592
- visitor(node);
2593
- switch (node.type) {
2594
- case File$1:
2595
- walk(node.program, visitor);
2596
- break;
2597
- case Program:
2598
- walk(node.body, visitor);
2599
- break;
2600
- case ExportNamedDeclaration:
2601
- walk(node.declaration, visitor);
2602
- break;
2603
- case VariableDeclaration:
2604
- walk(node.declarations, visitor);
2605
- break;
2606
- case VariableDeclarator:
2607
- walk(node.init, visitor);
2608
- break;
2609
- case ArrowFunctionExpression:
2610
- walk(node.body, visitor);
2611
- break;
2612
- case BlockStatement:
2613
- walk(node.body, visitor);
2614
- break;
2615
- case ExpressionStatement:
2616
- walk(node.expression, visitor);
2617
- break;
2618
- case AwaitExpression:
2619
- walk(node.argument, visitor);
2620
- break;
2621
- case CallExpression:
2622
- walk(node.callee, visitor);
2623
- break;
2624
- }
2625
- };
2626
- const getBabelAstDependencies = (code, ast) => {
2627
- const {
2628
- program
2629
- } = ast;
2630
- const {
2631
- body
2632
- } = program;
2633
- const dependencies = [];
2634
- for (const node of body) {
2635
- if (node.type === ImportDeclaration || node.type === ExportAllDeclaration) {
2636
- const relativePath = node.source.extra.rawValue;
2637
- const start = node.source.start;
2638
- const end = node.source.end;
2639
- // @ts-ignore
2640
- dependencies.push({
2641
- relativePath,
2642
- code,
2643
- start,
2644
- end
2645
- });
2646
- } else if (node.type === VariableDeclaration && node.declarations && node.declarations[0] && node.declarations[0].type === VariableDeclarator && node.declarations[0].init && node.declarations[0].init.type === AwaitExpression && node.declarations[0].init.argument && node.declarations[0].init.argument.type === CallExpression && node.declarations[0].init.argument.callee && node.declarations[0].init.argument.callee.type === Import && node.declarations[0].init.argument.arguments && node.declarations[0].init.argument.arguments[0] && node.declarations[0].init.argument.arguments[0].type === StringLiteral) {
2647
- const relativePath = node.declarations[0].init.argument.arguments[0].extra.rawValue;
2648
- const start = node.declarations[0].init.argument.arguments[0].start;
2649
- const end = node.declarations[0].init.argument.arguments[0].end;
2650
- // @ts-ignore
2651
- dependencies.push({
2652
- relativePath,
2653
- code,
2654
- start,
2655
- end
2656
- });
2657
- }
2658
- }
2659
- const visitor = node => {
2660
- if (node && node.type === CallExpression && node.callee && node.callee.type === Import && node.arguments && node.arguments[0] && node.arguments[0].type === StringLiteral) {
2661
- const relativePath = node.arguments[0].extra.rawValue;
2662
- const start = node.arguments[0].start;
2663
- const end = node.arguments[0].end;
2664
- // @ts-ignore
2665
- dependencies.push({
2666
- relativePath,
2667
- code,
2668
- start,
2669
- end
2670
- });
2671
- }
2858
+ const BraceCompletionExecuteBraceCompletionProvider = 'ExtensionHostBraceCompletion.executeBraceCompletionProvider';
2859
+ const ClosingTagExecuteClosingTagProvider = 'ExtensionHostClosingTag.executeClosingTagProvider';
2860
+ const CommandExecute = 'ExtensionHostCommand.executeCommand';
2861
+ const CompletionExecute = 'ExtensionHostCompletion.execute';
2862
+ const CompletionResolveExecute = 'ExtensionHostCompletion.executeResolve';
2863
+ const DefinitionExecuteDefinitionProvider = 'ExtensionHostDefinition.executeDefinitionProvider';
2864
+ const DiagnosticExecuteDiagnosticProvider = 'ExtensionHost.executeDiagnosticProvider';
2865
+ const ExtensionActivate = 'ExtensionHostExtension.activate';
2866
+ const FileSystemGetPathSeparator = 'ExtensionHostFileSystem.getPathSeparator';
2867
+ const FileSystemReadDirWithFileTypes = 'ExtensionHostFileSystem.readDirWithFileTypes';
2868
+ const FileSystemReadFile = 'ExtensionHostFileSystem.readFile';
2869
+ const FileSystemWriteFile = 'ExtensionHostFileSystem.writeFile';
2870
+ const FormattingExecuteFormmattingProvider = 'ExtensionHostFormatting.executeFormattingProvider';
2871
+ const HoverExecute = 'ExtensionHostHover.execute';
2872
+ const ImplementationExecuteImplementationProvider = 'ExtensionHostImplementation.executeImplementationProvider';
2873
+ const MockExec = 'ExtensionHostMockExec.mockExec';
2874
+ const MockRpc = 'ExtensionHostMockRpc.mockRpc';
2875
+ const OrganizeImportsExecute = 'ExtensionHostOrganizeImports.execute';
2876
+ const ReferenceExecuteFileReferenceProvider = 'ExtensionHostReference.executeFileReferenceProvider';
2877
+ const ReferenceExecuteReferenceProvider = 'ExtensionHostReference.executeReferenceProvider';
2878
+ const SourceControlAcceptInput = 'ExtensionHostSourceControl.acceptInput';
2879
+ const SourceControlAdd = 'ExtensionHostSourceControl.add';
2880
+ const SourceControlDiscard = 'ExtensionHostSourceControl.discard';
2881
+ const SourceControlGetChangedFiles = 'ExtensionHost.sourceControlGetChangedFiles';
2882
+ const SourceControlGetEnabledProviderIds = 'ExtensionHostSourceControl.getEnabledProviderIds';
2883
+ const SourceControlGetFileBefore = 'ExtensionHostSourceControl.GetFileBefore';
2884
+ const SourceControlGetGroups = 'ExtensionHostSourceControl.getGroups';
2885
+ const StatusBarGetStatusBarItems = 'ExtensionHost.getStatusBarItems';
2886
+ const StatusBarRegisterChangeListener = 'ExtensionHostStatusBar.registerChangeListener';
2887
+ const TabCompletionExecuteTabCompletionProvider = 'ExtensionHost.executeTabCompletionProvider';
2888
+ const TextDocumentSetLanguageId = 'ExtensionHostTextDocument.setLanguageId';
2889
+ const TextDocumentSyncFull = 'ExtensionHostTextDocument.syncFull';
2890
+ const TextDocumentSyncIncremental = 'ExtensionHostTextDocument.syncIncremental';
2891
+ const TextSearchExecuteTextSearchProvider = 'ExtensionHostTextSearch.executeTextSearchProvider';
2892
+ const TypeDefinitionExecuteTypeDefinitionProvider = 'ExtensionHostTypeDefinition.executeTypeDefinitionProvider';
2893
+ const WorkspaceSetPath = 'Workspace.setWorkspacePath';
2894
+ const SelectionExecuteSelectionProvider = 'ExtensionHostSelection.executeSelectionProvider';
2895
+ const ConfigurationSetConfiguration = 'ExtensionHostConfiguration.setConfiguration';
2896
+
2897
+ const create$5 = () => {
2898
+ return {
2899
+ finished: false
2672
2900
  };
2673
- walk(ast, visitor);
2674
- return dependencies;
2675
2901
  };
2676
-
2677
- const isBabelError = error => {
2678
- // @ts-ignore
2679
- return isSyntaxError(error) && error.code === BABEL_PARSER_SYNTAX_ERROR;
2902
+ const cancel = token => {
2903
+ token.finished = true;
2680
2904
  };
2681
-
2682
- const getOrigin = () => {
2683
- return location.origin;
2905
+ const isCanceled = token => {
2906
+ return token.finished;
2684
2907
  };
2685
2908
 
2686
- const getAbsoluteUrl = (relativePath, sourceUrl) => {
2687
- if (sourceUrl.startsWith('/')) {
2688
- const origin = getOrigin();
2689
- const absoluteSourceUrl = new URL(sourceUrl, origin).toString();
2690
- return new URL(relativePath, absoluteSourceUrl).toString();
2691
- }
2692
- return new URL(relativePath, sourceUrl).toString();
2909
+ const baseName = path => {
2910
+ const slashIndex = path.lastIndexOf('/');
2911
+ return path.slice(slashIndex + 1);
2693
2912
  };
2694
-
2695
- const isExternal = url => {
2696
- if (url.startsWith('/')) {
2697
- return false;
2698
- }
2699
- if (url.startsWith(location.protocol)) {
2700
- return false;
2913
+ const getExtensionId = extension => {
2914
+ if (extension && extension.id) {
2915
+ return extension.id;
2701
2916
  }
2702
- return true;
2703
- };
2704
- const getErrorInDependencies = async (url, dependencies, seenUrls) => {
2705
- for (const dependency of dependencies) {
2706
- const dependencyUrl = getAbsoluteUrl(dependency.relativePath, url);
2707
- if (isExternal(dependencyUrl) || seenUrls.includes(dependencyUrl)) {
2708
- continue;
2709
- }
2710
- seenUrls.push(dependencyUrl);
2711
- // let dependencyResponse
2712
- // try {
2713
- const dependencyResponse = await fetch(dependencyUrl);
2714
- // } catch (error) {}
2715
- if (dependencyResponse.ok) {
2716
- await tryToGetActualErrorMessage(null, dependencyUrl, dependencyResponse, seenUrls);
2717
- } else {
2718
- switch (dependencyResponse.status) {
2719
- case NotFound:
2720
- throw new DependencyNotFoundError(dependency.code, dependency.start, dependency.end, dependency.relativePath, dependencyUrl, url);
2721
- // return `Failed to import ${url}: ${error}`
2722
- }
2723
- }
2917
+ if (extension && extension.path) {
2918
+ return baseName(extension.path);
2724
2919
  }
2920
+ return '<unknown>';
2725
2921
  };
2726
2922
 
2727
- /**
2728
- *
2729
- * @param {string} url
2730
- * @param {Response} response
2731
- * @returns
2732
- */
2733
- const tryToGetActualErrorMessage = async (error, url, response, seenUrls = []) => {
2734
- let text;
2735
- try {
2736
- text = await response.text();
2737
- } catch (error) {
2738
- return `Failed to import ${url}: Unknown Network Error`;
2739
- }
2740
- let ast;
2741
- try {
2742
- ast = await parse(text, {
2743
- sourceType: Module
2744
- });
2745
- } catch (error) {
2746
- if (isBabelError(error)) {
2747
- throw new BabelParseError(url, error);
2748
- }
2749
- throw error;
2923
+ const getUrlPrefix = extensionPath => {
2924
+ if (extensionPath.startsWith('http://') || extensionPath.startsWith('https://')) {
2925
+ return extensionPath;
2750
2926
  }
2751
- const dependencies = getBabelAstDependencies(text, ast);
2752
- await getErrorInDependencies(url, dependencies, seenUrls);
2753
- if (hasRecentErrors()) {
2754
- const recentError = getRecentError();
2755
- // @ts-ignore
2756
- throw new ContentSecurityPolicyError(recentError.violatedDirective, recentError.sourceFile, recentError.lineNumber, recentError.columnNumber);
2927
+ if (platform === Web) {
2928
+ return extensionPath;
2757
2929
  }
2758
- const contentType = response.headers.get('Content-Type');
2759
- if (url.endsWith('.ts') && contentType === null) {
2760
- return `Failed to import ${url}: Missing Content-Type header for javascript`;
2930
+ if (extensionPath.startsWith('/')) {
2931
+ return `/remote${extensionPath}`;
2761
2932
  }
2762
- return `Failed to import ${url}: Unknown Network Error`;
2933
+ return `/remote/${extensionPath}`;
2763
2934
  };
2764
2935
 
2765
- const tryToGetActualImportErrorMessage = async (url, error) => {
2766
- let response;
2936
+ const handleRpcInfos = extension => {
2767
2937
  try {
2768
- response = await fetch(url);
2938
+ if (!extension) {
2939
+ return;
2940
+ }
2941
+ const rpcs = extension.rpc;
2942
+ const urlPrefix = getUrlPrefix(extension.path);
2943
+ if (!rpcs) {
2944
+ return;
2945
+ }
2946
+ if (!Array.isArray(rpcs)) {
2947
+ return;
2948
+ }
2949
+ for (const rpc of rpcs) {
2950
+ rpc.url = `${urlPrefix}/${rpc.url}`;
2951
+ add$1(rpc.id, rpc);
2952
+ }
2769
2953
  } catch (error) {
2770
- return `Failed to import ${url}: ${error}`;
2771
- }
2772
- if (response.ok) {
2773
- return await tryToGetActualErrorMessage(error, url, response);
2774
- }
2775
- switch (response.status) {
2776
- case NotFound:
2777
- throw new Error(`Failed to import ${url}: Not found (404)`);
2778
- default:
2779
- return `Failed to import ${url}: ${error}`;
2954
+ console.warn(`Failed to handle extension rpcs: ${error}`);
2780
2955
  }
2781
2956
  };
2782
2957
 
2783
- const importScript = async url => {
2784
- try {
2785
- return await import(url);
2786
- } catch (error) {
2787
- if (isImportError(error)) {
2788
- const actualErrorMessage = await tryToGetActualImportErrorMessage(url, error);
2789
- throw new Error(actualErrorMessage);
2790
- }
2791
- // content security policy errors arrive a little bit later
2792
- await sleep(0);
2793
- if (hasRecentErrors()) {
2794
- const recentError = getRecentError();
2795
- // @ts-ignore
2796
- throw new ContentSecurityPolicyError(recentError.violatedDirective, recentError.sourceFile, recentError.lineNumber, recentError.columnNumber);
2958
+ class ContentSecurityPolicyError extends Error {
2959
+ constructor(violatedDirective, sourceFile, lineNumber, columnNumber) {
2960
+ super(`Content Security Policy Violation: ${violatedDirective}`);
2961
+ this.name = 'ContentSecurityPolicyError';
2962
+ if (sourceFile) {
2963
+ this.stack = `Content Security Policy Violation
2964
+ at ${sourceFile}:${lineNumber}:${columnNumber}`;
2965
+ } else {
2966
+ this.stack = `Content Security Policy Violation
2967
+ at <unknown>`;
2797
2968
  }
2798
- throw error;
2799
2969
  }
2970
+ }
2971
+
2972
+ const isImportErrorChrome = error => {
2973
+ return error && error instanceof Error && error.message.startsWith('Failed to fetch dynamically imported module');
2800
2974
  };
2801
2975
 
2802
- const activationTimeout = 10_000;
2803
- const rejectAfterTimeout = async (timeout, token) => {
2804
- await sleep(timeout);
2805
- if (isCanceled(token)) {
2806
- return;
2807
- }
2808
- throw new Error(`Activation timeout of ${timeout}ms exceeded`);
2976
+ const isImportErrorFirefox = error => {
2977
+ return error && error instanceof TypeError && error.message === 'error loading dynamically imported module';
2809
2978
  };
2810
- const activate = async (extension, absolutePath) => {
2811
- try {
2812
- string(extension.path);
2813
- string(extension.browser);
2814
- string(absolutePath);
2815
- const module = await importScript(absolutePath);
2816
- handleRpcInfos(extension);
2817
- const token = create$5();
2818
- try {
2819
- await Promise.race([module.activate(extension), rejectAfterTimeout(activationTimeout, token)]);
2820
- } catch (error) {
2821
- if (isImportError(error)) {
2822
- const actualErrorMessage = await tryToGetActualImportErrorMessage(absolutePath, error);
2823
- throw new Error(actualErrorMessage);
2824
- }
2825
- throw error;
2826
- } finally {
2827
- cancel(token);
2828
- }
2829
- } catch (error) {
2830
- const id = getExtensionId(extension);
2831
- throw new VError(error, `Failed to activate extension ${id}`);
2832
- }
2833
- // console.info('activated', path)
2979
+
2980
+ const isSyntaxError = error => {
2981
+ return error instanceof SyntaxError;
2834
2982
  };
2835
2983
 
2836
- class ExecError extends Error {
2837
- constructor(command, args, stdout, stderr, exitCode) {
2838
- super(`Failed to execute ${command}: process exited with code ${exitCode}`);
2839
- this.name = 'ExecError';
2840
- // @ts-ignore
2841
- this.stdout = stdout;
2842
- // @ts-ignore
2843
- this.stderr = stderr;
2844
- // @ts-ignore
2845
- this.exitCode = exitCode;
2846
- }
2847
- }
2984
+ const isImportError = error => {
2985
+ return isImportErrorChrome(error) || isImportErrorFirefox(error) || isSyntaxError(error);
2986
+ };
2848
2987
 
2849
- const mockExec = () => {
2850
- try {
2851
- // @ts-ignore
2852
- api.exec = async (command, args, options) => {
2853
- const result = await invoke('Test.executeMockExecFunction', command, args, options);
2854
- const {
2855
- stdout,
2856
- stderr,
2857
- exitCode
2858
- } = result;
2859
- if (exitCode !== 0) {
2860
- throw new ExecError(command, args, stdout, stderr, exitCode);
2861
- }
2862
- return {
2863
- stdout,
2864
- stderr,
2865
- exitCode
2866
- };
2867
- };
2868
- } catch (error) {
2869
- throw new VError(error, 'Failed to mock exec function');
2988
+ const sleep = duration => {
2989
+ const promiseCallback = (resolve, reject) => {
2990
+ setTimeout(resolve, duration);
2991
+ };
2992
+ return new Promise(promiseCallback);
2993
+ };
2994
+
2995
+ const NotFound = 404;
2996
+
2997
+ const RE_LINE_COLUMN = /(.*)(?:\(\d+\:\d+\))/;
2998
+ const getBabelErrorMessage = message => {
2999
+ const match = message.match(RE_LINE_COLUMN);
3000
+ if (match) {
3001
+ return match[1].trim();
2870
3002
  }
3003
+ return message;
2871
3004
  };
3005
+ class BabelParseError extends SyntaxError {
3006
+ constructor(url, error) {
3007
+ const message = getBabelErrorMessage(error.message);
3008
+ super(message);
3009
+ this.name = 'BabelParseError';
3010
+ // @ts-ignore
3011
+ const line = error.loc.line;
3012
+ // @ts-ignore
3013
+ const column = error.loc.column + 1;
3014
+ this.stack = `${message}
3015
+ at ${url}:${line}:${column}`;
3016
+ }
3017
+ }
2872
3018
 
2873
- const mockRpc = () => {
3019
+ const getAssetDir = () => {
2874
3020
  // @ts-ignore
2875
- api.createNodeRpc = async options => {
2876
- try {
2877
- return {
2878
- async invoke(method, ...params) {
2879
- const result = await invoke('Test.executeMockRpcFunction', options.name, method, ...params);
2880
- return result;
2881
- }
2882
- };
2883
- } catch (error) {
2884
- throw new VError(error, 'Failed to mock exec function');
2885
- }
2886
- };
2887
- };
2888
-
2889
- const getStatusBarItems = async () => {
2890
- const providers = Object.values(state$5.providers);
2891
- const statusBarItems = [];
2892
- for (const provider of providers) {
3021
+ if (typeof ASSET_DIR !== 'undefined') {
2893
3022
  // @ts-ignore
2894
- if (provider && provider.statusBarCommands) {
2895
- // @ts-ignore
2896
- statusBarItems.push(...provider.statusBarCommands);
2897
- }
3023
+ return ASSET_DIR;
2898
3024
  }
2899
- return statusBarItems;
3025
+ if (platform === Electron) {
3026
+ return '../../../../..';
3027
+ }
3028
+ return '';
2900
3029
  };
2901
- const registerChangeListener = () => {
2902
- // TODO
3030
+ const assetDir = getAssetDir();
3031
+
3032
+ const loadBabelParser = () => {
3033
+ const url = `${assetDir}/js/babel-parser.js`;
3034
+ return import(url);
2903
3035
  };
2904
3036
 
2905
- const handleBeforeUnload = () => {
2906
- // TODO save all webviews in localstorage
2907
- // cannot use indexeddb during unload
2908
- console.log('before unload');
3037
+ const parse = async (code, options) => {
3038
+ const BabelParse = await loadBabelParser();
3039
+ return BabelParse.parse(code, options);
2909
3040
  };
2910
3041
 
2911
- const MessagePort$1 = 1;
2912
- const ModuleWorker = 2;
2913
- const ModuleWorkerWithMessagePort = 4;
2914
- const Auto = () => {
2915
- if (globalThis.acceptPort) {
2916
- return MessagePort$1;
3042
+ const Module = 'module';
3043
+
3044
+ const getLineAndColumn = (text, start, end) => {
3045
+ let index = -1;
3046
+ let line = 0;
3047
+ const column = 0;
3048
+ while ((index = text.indexOf('\n', index + 1)) !== -1) {
3049
+ line++;
3050
+ if (index >= start) {
3051
+ break;
3052
+ }
2917
3053
  }
2918
- return ModuleWorkerWithMessagePort;
3054
+ return {
3055
+ line,
3056
+ column
3057
+ };
2919
3058
  };
2920
3059
 
2921
- const walkValue = (value, transferrables, isTransferrable) => {
2922
- if (!value) {
2923
- return;
3060
+ class DependencyNotFoundError extends Error {
3061
+ constructor(code, start, end, dependencyRelativePath, dependencyUrl, sourceUrl) {
3062
+ super(`Module not found "${dependencyRelativePath}"`);
3063
+ const {
3064
+ line,
3065
+ column
3066
+ } = getLineAndColumn(code, start);
3067
+ this.stack = `${this.message}
3068
+ at Module (${sourceUrl}:${line}:${column})`;
2924
3069
  }
2925
- if (isTransferrable(value)) {
2926
- transferrables.push(value);
3070
+ }
3071
+
3072
+ const ArrowFunctionExpression = 'ArrowFunctionExpression';
3073
+ const AwaitExpression = 'AwaitExpression';
3074
+ const BlockStatement = 'BlockStatement';
3075
+ const CallExpression = 'CallExpression';
3076
+ const ExportAllDeclaration = 'ExportAllDeclaration';
3077
+ const ExportNamedDeclaration = 'ExportNamedDeclaration';
3078
+ const ExpressionStatement = 'ExpressionStatement';
3079
+ const File$1 = 'File';
3080
+ const Import = 'Import';
3081
+ const ImportDeclaration = 'ImportDeclaration';
3082
+ const Program = 'Program';
3083
+ const StringLiteral = 'StringLiteral';
3084
+ const VariableDeclaration = 'VariableDeclaration';
3085
+ const VariableDeclarator = 'VariableDeclarator';
3086
+
3087
+ const walk = (node, visitor) => {
3088
+ if (!node) {
2927
3089
  return;
2928
3090
  }
2929
- if (Array.isArray(value)) {
2930
- for (const item of value) {
2931
- walkValue(item, transferrables, isTransferrable);
3091
+ if (Array.isArray(node)) {
3092
+ for (const item of node) {
3093
+ walk(item, visitor);
2932
3094
  }
2933
3095
  return;
2934
3096
  }
2935
- if (typeof value === 'object') {
2936
- for (const property of Object.values(value)) {
2937
- walkValue(property, transferrables, isTransferrable);
2938
- }
2939
- return;
3097
+ visitor(node);
3098
+ switch (node.type) {
3099
+ case File$1:
3100
+ walk(node.program, visitor);
3101
+ break;
3102
+ case Program:
3103
+ walk(node.body, visitor);
3104
+ break;
3105
+ case ExportNamedDeclaration:
3106
+ walk(node.declaration, visitor);
3107
+ break;
3108
+ case VariableDeclaration:
3109
+ walk(node.declarations, visitor);
3110
+ break;
3111
+ case VariableDeclarator:
3112
+ walk(node.init, visitor);
3113
+ break;
3114
+ case ArrowFunctionExpression:
3115
+ walk(node.body, visitor);
3116
+ break;
3117
+ case BlockStatement:
3118
+ walk(node.body, visitor);
3119
+ break;
3120
+ case ExpressionStatement:
3121
+ walk(node.expression, visitor);
3122
+ break;
3123
+ case AwaitExpression:
3124
+ walk(node.argument, visitor);
3125
+ break;
3126
+ case CallExpression:
3127
+ walk(node.callee, visitor);
3128
+ break;
2940
3129
  }
2941
3130
  };
2942
- const isMessagePort = value => {
2943
- return value && value instanceof MessagePort;
2944
- };
2945
- const isMessagePortMain = value => {
2946
- return value && value.constructor && value.constructor.name === 'MessagePortMain';
2947
- };
2948
- const isOffscreenCanvas = value => {
2949
- return typeof OffscreenCanvas !== 'undefined' && value instanceof OffscreenCanvas;
2950
- };
2951
- const isInstanceOf = (value, constructorName) => {
2952
- return value?.constructor?.name === constructorName;
2953
- };
2954
- const isSocket = value => {
2955
- return isInstanceOf(value, 'Socket');
2956
- };
2957
- const transferrables = [isMessagePort, isMessagePortMain, isOffscreenCanvas, isSocket];
2958
- const isTransferrable = value => {
2959
- for (const fn of transferrables) {
2960
- if (fn(value)) {
2961
- return true;
3131
+ const getBabelAstDependencies = (code, ast) => {
3132
+ const {
3133
+ program
3134
+ } = ast;
3135
+ const {
3136
+ body
3137
+ } = program;
3138
+ const dependencies = [];
3139
+ for (const node of body) {
3140
+ if (node.type === ImportDeclaration || node.type === ExportAllDeclaration) {
3141
+ const relativePath = node.source.extra.rawValue;
3142
+ const start = node.source.start;
3143
+ const end = node.source.end;
3144
+ // @ts-ignore
3145
+ dependencies.push({
3146
+ relativePath,
3147
+ code,
3148
+ start,
3149
+ end
3150
+ });
3151
+ } else if (node.type === VariableDeclaration && node.declarations && node.declarations[0] && node.declarations[0].type === VariableDeclarator && node.declarations[0].init && node.declarations[0].init.type === AwaitExpression && node.declarations[0].init.argument && node.declarations[0].init.argument.type === CallExpression && node.declarations[0].init.argument.callee && node.declarations[0].init.argument.callee.type === Import && node.declarations[0].init.argument.arguments && node.declarations[0].init.argument.arguments[0] && node.declarations[0].init.argument.arguments[0].type === StringLiteral) {
3152
+ const relativePath = node.declarations[0].init.argument.arguments[0].extra.rawValue;
3153
+ const start = node.declarations[0].init.argument.arguments[0].start;
3154
+ const end = node.declarations[0].init.argument.arguments[0].end;
3155
+ // @ts-ignore
3156
+ dependencies.push({
3157
+ relativePath,
3158
+ code,
3159
+ start,
3160
+ end
3161
+ });
2962
3162
  }
2963
3163
  }
2964
- return false;
2965
- };
2966
- const getTransferrables = value => {
2967
- const transferrables = [];
2968
- walkValue(value, transferrables, isTransferrable);
2969
- return transferrables;
2970
- };
2971
- const attachEvents = that => {
2972
- const handleMessage = (...args) => {
2973
- const data = that.getData(...args);
2974
- that.dispatchEvent(new MessageEvent('message', {
2975
- data
2976
- }));
2977
- };
2978
- that.onMessage(handleMessage);
2979
- const handleClose = event => {
2980
- that.dispatchEvent(new Event('close'));
2981
- };
2982
- that.onClose(handleClose);
2983
- };
2984
- class Ipc extends EventTarget {
2985
- constructor(rawIpc) {
2986
- super();
2987
- this._rawIpc = rawIpc;
2988
- attachEvents(this);
2989
- }
2990
- }
2991
- const E_INCOMPATIBLE_NATIVE_MODULE = 'E_INCOMPATIBLE_NATIVE_MODULE';
2992
- const E_MODULES_NOT_SUPPORTED_IN_ELECTRON = 'E_MODULES_NOT_SUPPORTED_IN_ELECTRON';
2993
- const ERR_MODULE_NOT_FOUND = 'ERR_MODULE_NOT_FOUND';
2994
- const NewLine = '\n';
2995
- const joinLines = lines => {
2996
- return lines.join(NewLine);
2997
- };
2998
- const splitLines$1 = lines => {
2999
- return lines.split(NewLine);
3000
- };
3001
- const isModuleNotFoundMessage = line => {
3002
- return line.includes('[ERR_MODULE_NOT_FOUND]');
3003
- };
3004
- const getModuleNotFoundError = stderr => {
3005
- const lines = splitLines$1(stderr);
3006
- const messageIndex = lines.findIndex(isModuleNotFoundMessage);
3007
- const message = lines[messageIndex];
3008
- return {
3009
- message,
3010
- code: ERR_MODULE_NOT_FOUND
3164
+ const visitor = node => {
3165
+ if (node && node.type === CallExpression && node.callee && node.callee.type === Import && node.arguments && node.arguments[0] && node.arguments[0].type === StringLiteral) {
3166
+ const relativePath = node.arguments[0].extra.rawValue;
3167
+ const start = node.arguments[0].start;
3168
+ const end = node.arguments[0].end;
3169
+ // @ts-ignore
3170
+ dependencies.push({
3171
+ relativePath,
3172
+ code,
3173
+ start,
3174
+ end
3175
+ });
3176
+ }
3011
3177
  };
3178
+ walk(ast, visitor);
3179
+ return dependencies;
3012
3180
  };
3013
- const RE_NATIVE_MODULE_ERROR = /^innerError Error: Cannot find module '.*.node'/;
3014
- const RE_NATIVE_MODULE_ERROR_2 = /was compiled against a different Node.js version/;
3015
- const RE_MESSAGE_CODE_BLOCK_START = /^Error: The module '.*'$/;
3016
- const RE_MESSAGE_CODE_BLOCK_END = /^\s* at/;
3017
- const RE_AT = /^\s+at/;
3018
- const RE_AT_PROMISE_INDEX = /^\s*at async Promise.all \(index \d+\)$/;
3019
- const isUnhelpfulNativeModuleError = stderr => {
3020
- return RE_NATIVE_MODULE_ERROR.test(stderr) && RE_NATIVE_MODULE_ERROR_2.test(stderr);
3021
- };
3022
- const isMessageCodeBlockStartIndex = line => {
3023
- return RE_MESSAGE_CODE_BLOCK_START.test(line);
3024
- };
3025
- const isMessageCodeBlockEndIndex = line => {
3026
- return RE_MESSAGE_CODE_BLOCK_END.test(line);
3181
+
3182
+ const isBabelError = error => {
3183
+ // @ts-ignore
3184
+ return isSyntaxError(error) && error.code === BABEL_PARSER_SYNTAX_ERROR;
3027
3185
  };
3028
- const getMessageCodeBlock = stderr => {
3029
- const lines = splitLines$1(stderr);
3030
- const startIndex = lines.findIndex(isMessageCodeBlockStartIndex);
3031
- const endIndex = startIndex + lines.slice(startIndex).findIndex(isMessageCodeBlockEndIndex, startIndex);
3032
- const relevantLines = lines.slice(startIndex, endIndex);
3033
- const relevantMessage = relevantLines.join(' ').slice('Error: '.length);
3034
- return relevantMessage;
3186
+
3187
+ const getOrigin = () => {
3188
+ return location.origin;
3035
3189
  };
3036
- const getNativeModuleErrorMessage = stderr => {
3037
- const message = getMessageCodeBlock(stderr);
3038
- return {
3039
- message: `Incompatible native node module: ${message}`,
3040
- code: E_INCOMPATIBLE_NATIVE_MODULE
3041
- };
3190
+
3191
+ const getAbsoluteUrl = (relativePath, sourceUrl) => {
3192
+ if (sourceUrl.startsWith('/')) {
3193
+ const origin = getOrigin();
3194
+ const absoluteSourceUrl = new URL(sourceUrl, origin).toString();
3195
+ return new URL(relativePath, absoluteSourceUrl).toString();
3196
+ }
3197
+ return new URL(relativePath, sourceUrl).toString();
3042
3198
  };
3043
- const isModulesSyntaxError = stderr => {
3044
- if (!stderr) {
3199
+
3200
+ const isExternal = url => {
3201
+ if (url.startsWith('/')) {
3045
3202
  return false;
3046
3203
  }
3047
- return stderr.includes('SyntaxError: Cannot use import statement outside a module');
3048
- };
3049
- const getModuleSyntaxError = () => {
3050
- return {
3051
- message: `ES Modules are not supported in electron`,
3052
- code: E_MODULES_NOT_SUPPORTED_IN_ELECTRON
3053
- };
3054
- };
3055
- const isModuleNotFoundError = stderr => {
3056
- if (!stderr) {
3204
+ if (url.startsWith(location.protocol)) {
3057
3205
  return false;
3058
3206
  }
3059
- return stderr.includes('ERR_MODULE_NOT_FOUND');
3060
- };
3061
- const isNormalStackLine = line => {
3062
- return RE_AT.test(line) && !RE_AT_PROMISE_INDEX.test(line);
3207
+ return true;
3063
3208
  };
3064
- const getDetails = lines => {
3065
- const index = lines.findIndex(isNormalStackLine);
3066
- if (index === -1) {
3067
- return {
3068
- actualMessage: joinLines(lines),
3069
- rest: []
3070
- };
3071
- }
3072
- let lastIndex = index - 1;
3073
- while (++lastIndex < lines.length) {
3074
- if (!isNormalStackLine(lines[lastIndex])) {
3075
- break;
3209
+ const getErrorInDependencies = async (url, dependencies, seenUrls) => {
3210
+ for (const dependency of dependencies) {
3211
+ const dependencyUrl = getAbsoluteUrl(dependency.relativePath, url);
3212
+ if (isExternal(dependencyUrl) || seenUrls.includes(dependencyUrl)) {
3213
+ continue;
3076
3214
  }
3077
- }
3078
- return {
3079
- actualMessage: lines[index - 1],
3080
- rest: lines.slice(index, lastIndex)
3081
- };
3082
- };
3083
- const getHelpfulChildProcessError = (stdout, stderr) => {
3084
- if (isUnhelpfulNativeModuleError(stderr)) {
3085
- return getNativeModuleErrorMessage(stderr);
3086
- }
3087
- if (isModulesSyntaxError(stderr)) {
3088
- return getModuleSyntaxError();
3089
- }
3090
- if (isModuleNotFoundError(stderr)) {
3091
- return getModuleNotFoundError(stderr);
3092
- }
3093
- const lines = splitLines$1(stderr);
3094
- const {
3095
- actualMessage,
3096
- rest
3097
- } = getDetails(lines);
3098
- return {
3099
- message: `${actualMessage}`,
3100
- code: '',
3101
- stack: rest
3102
- };
3103
- };
3104
- let IpcError$1 = class IpcError extends VError {
3105
- // @ts-ignore
3106
- constructor(betterMessage, stdout = '', stderr = '') {
3107
- if (stdout || stderr) {
3108
- // @ts-ignore
3109
- const {
3110
- message,
3111
- code,
3112
- stack
3113
- } = getHelpfulChildProcessError(stdout, stderr);
3114
- const cause = new Error(message);
3115
- // @ts-ignore
3116
- cause.code = code;
3117
- cause.stack = stack;
3118
- super(cause, betterMessage);
3215
+ seenUrls.push(dependencyUrl);
3216
+ // let dependencyResponse
3217
+ // try {
3218
+ const dependencyResponse = await fetch(dependencyUrl);
3219
+ // } catch (error) {}
3220
+ if (dependencyResponse.ok) {
3221
+ await tryToGetActualErrorMessage(null, dependencyUrl, dependencyResponse, seenUrls);
3119
3222
  } else {
3120
- super(betterMessage);
3223
+ switch (dependencyResponse.status) {
3224
+ case NotFound:
3225
+ throw new DependencyNotFoundError(dependency.code, dependency.start, dependency.end, dependency.relativePath, dependencyUrl, url);
3226
+ // return `Failed to import ${url}: ${error}`
3227
+ }
3121
3228
  }
3122
- // @ts-ignore
3123
- this.name = 'IpcError';
3124
- // @ts-ignore
3125
- this.stdout = stdout;
3126
- // @ts-ignore
3127
- this.stderr = stderr;
3128
3229
  }
3129
3230
  };
3130
- const readyMessage = 'ready';
3131
- const getData$2 = event => {
3132
- return event.data;
3133
- };
3134
- const listen$8 = ({
3135
- port
3136
- }) => {
3137
- return port;
3138
- };
3139
- const signal$8 = port => {
3140
- port.postMessage(readyMessage);
3141
- };
3142
- class IpcChildWithMessagePort extends Ipc {
3143
- constructor(port) {
3144
- super(port);
3231
+
3232
+ /**
3233
+ *
3234
+ * @param {string} url
3235
+ * @param {Response} response
3236
+ * @returns
3237
+ */
3238
+ const tryToGetActualErrorMessage = async (error, url, response, seenUrls = []) => {
3239
+ let text;
3240
+ try {
3241
+ text = await response.text();
3242
+ } catch (error) {
3243
+ return `Failed to import ${url}: Unknown Network Error`;
3145
3244
  }
3146
- getData(event) {
3147
- return getData$2(event);
3245
+ let ast;
3246
+ try {
3247
+ ast = await parse(text, {
3248
+ sourceType: Module
3249
+ });
3250
+ } catch (error) {
3251
+ if (isBabelError(error)) {
3252
+ throw new BabelParseError(url, error);
3253
+ }
3254
+ throw error;
3148
3255
  }
3149
- send(message) {
3150
- this._rawIpc.postMessage(message);
3256
+ const dependencies = getBabelAstDependencies(text, ast);
3257
+ await getErrorInDependencies(url, dependencies, seenUrls);
3258
+ if (hasRecentErrors()) {
3259
+ const recentError = getRecentError();
3260
+ // @ts-ignore
3261
+ throw new ContentSecurityPolicyError(recentError.violatedDirective, recentError.sourceFile, recentError.lineNumber, recentError.columnNumber);
3151
3262
  }
3152
- sendAndTransfer(message) {
3153
- const transfer = getTransferrables(message);
3154
- this._rawIpc.postMessage(message, transfer);
3263
+ const contentType = response.headers.get('Content-Type');
3264
+ if (url.endsWith('.ts') && contentType === null) {
3265
+ return `Failed to import ${url}: Missing Content-Type header for javascript`;
3155
3266
  }
3156
- dispose() {
3157
- // ignore
3267
+ return `Failed to import ${url}: Unknown Network Error`;
3268
+ };
3269
+
3270
+ const tryToGetActualImportErrorMessage = async (url, error) => {
3271
+ let response;
3272
+ try {
3273
+ response = await fetch(url);
3274
+ } catch (error) {
3275
+ return `Failed to import ${url}: ${error}`;
3158
3276
  }
3159
- onClose(callback) {
3160
- // ignore
3277
+ if (response.ok) {
3278
+ return await tryToGetActualErrorMessage(error, url, response);
3161
3279
  }
3162
- onMessage(callback) {
3163
- this._rawIpc.addEventListener('message', callback);
3164
- this._rawIpc.start();
3280
+ switch (response.status) {
3281
+ case NotFound:
3282
+ throw new Error(`Failed to import ${url}: Not found (404)`);
3283
+ default:
3284
+ return `Failed to import ${url}: ${error}`;
3165
3285
  }
3166
- }
3167
- const wrap$f = port => {
3168
- return new IpcChildWithMessagePort(port);
3169
- };
3170
- const IpcChildWithMessagePort$1 = {
3171
- __proto__: null,
3172
- listen: listen$8,
3173
- signal: signal$8,
3174
- wrap: wrap$f
3175
3286
  };
3176
- const listen$7 = () => {
3177
- // @ts-ignore
3178
- if (typeof WorkerGlobalScope === 'undefined') {
3179
- throw new TypeError('module is not in web worker scope');
3287
+
3288
+ const importScript = async url => {
3289
+ try {
3290
+ return await import(url);
3291
+ } catch (error) {
3292
+ if (isImportError(error)) {
3293
+ const actualErrorMessage = await tryToGetActualImportErrorMessage(url, error);
3294
+ throw new Error(actualErrorMessage);
3295
+ }
3296
+ // content security policy errors arrive a little bit later
3297
+ await sleep(0);
3298
+ if (hasRecentErrors()) {
3299
+ const recentError = getRecentError();
3300
+ // @ts-ignore
3301
+ throw new ContentSecurityPolicyError(recentError.violatedDirective, recentError.sourceFile, recentError.lineNumber, recentError.columnNumber);
3302
+ }
3303
+ throw error;
3180
3304
  }
3181
- return globalThis;
3182
3305
  };
3183
- const signal$7 = global => {
3184
- global.postMessage(readyMessage);
3306
+
3307
+ const activationTimeout = 10_000;
3308
+ const rejectAfterTimeout = async (timeout, token) => {
3309
+ await sleep(timeout);
3310
+ if (isCanceled(token)) {
3311
+ return;
3312
+ }
3313
+ throw new Error(`Activation timeout of ${timeout}ms exceeded`);
3185
3314
  };
3186
- class IpcChildWithModuleWorker extends Ipc {
3187
- getData(event) {
3188
- return getData$2(event);
3315
+ const activate = async (extension, absolutePath) => {
3316
+ try {
3317
+ string(extension.path);
3318
+ string(extension.browser);
3319
+ string(absolutePath);
3320
+ const module = await importScript(absolutePath);
3321
+ handleRpcInfos(extension);
3322
+ const token = create$5();
3323
+ try {
3324
+ await Promise.race([module.activate(extension), rejectAfterTimeout(activationTimeout, token)]);
3325
+ } catch (error) {
3326
+ if (isImportError(error)) {
3327
+ const actualErrorMessage = await tryToGetActualImportErrorMessage(absolutePath, error);
3328
+ throw new Error(actualErrorMessage);
3329
+ }
3330
+ throw error;
3331
+ } finally {
3332
+ cancel(token);
3333
+ }
3334
+ } catch (error) {
3335
+ const id = getExtensionId(extension);
3336
+ throw new VError(error, `Failed to activate extension ${id}`);
3189
3337
  }
3190
- send(message) {
3338
+ // console.info('activated', path)
3339
+ };
3340
+
3341
+ class ExecError extends Error {
3342
+ constructor(command, args, stdout, stderr, exitCode) {
3343
+ super(`Failed to execute ${command}: process exited with code ${exitCode}`);
3344
+ this.name = 'ExecError';
3191
3345
  // @ts-ignore
3192
- this._rawIpc.postMessage(message);
3193
- }
3194
- sendAndTransfer(message) {
3195
- const transfer = getTransferrables(message);
3346
+ this.stdout = stdout;
3196
3347
  // @ts-ignore
3197
- this._rawIpc.postMessage(message, transfer);
3198
- }
3199
- dispose() {
3200
- // ignore
3201
- }
3202
- onClose(callback) {
3203
- // ignore
3204
- }
3205
- onMessage(callback) {
3206
- this._rawIpc.addEventListener('message', callback);
3348
+ this.stderr = stderr;
3349
+ // @ts-ignore
3350
+ this.exitCode = exitCode;
3207
3351
  }
3208
3352
  }
3209
- const wrap$e = global => {
3210
- return new IpcChildWithModuleWorker(global);
3211
- };
3212
- const IpcChildWithModuleWorker$1 = {
3213
- __proto__: null,
3214
- listen: listen$7,
3215
- signal: signal$7,
3216
- wrap: wrap$e
3217
- };
3218
- const withResolvers$1 = () => {
3219
- let _resolve;
3220
- const promise = new Promise(resolve => {
3221
- _resolve = resolve;
3222
- });
3223
- return {
3224
- resolve: _resolve,
3225
- promise
3226
- };
3353
+
3354
+ const mockExec = () => {
3355
+ try {
3356
+ // @ts-ignore
3357
+ api.exec = async (command, args, options) => {
3358
+ const result = await invoke$1('Test.executeMockExecFunction', command, args, options);
3359
+ const {
3360
+ stdout,
3361
+ stderr,
3362
+ exitCode
3363
+ } = result;
3364
+ if (exitCode !== 0) {
3365
+ throw new ExecError(command, args, stdout, stderr, exitCode);
3366
+ }
3367
+ return {
3368
+ stdout,
3369
+ stderr,
3370
+ exitCode
3371
+ };
3372
+ };
3373
+ } catch (error) {
3374
+ throw new VError(error, 'Failed to mock exec function');
3375
+ }
3227
3376
  };
3228
- const waitForFirstMessage = async port => {
3229
- const {
3230
- resolve,
3231
- promise
3232
- } = withResolvers$1();
3233
- port.addEventListener('message', resolve, {
3234
- once: true
3235
- });
3236
- const event = await promise;
3377
+
3378
+ const mockRpc = () => {
3237
3379
  // @ts-ignore
3238
- return event.data;
3239
- };
3240
- const listen$6 = async () => {
3241
- const parentIpcRaw = listen$7();
3242
- signal$7(parentIpcRaw);
3243
- const parentIpc = wrap$e(parentIpcRaw);
3244
- const firstMessage = await waitForFirstMessage(parentIpc);
3245
- if (firstMessage.method !== 'initialize') {
3246
- throw new IpcError$1('unexpected first message');
3247
- }
3248
- const type = firstMessage.params[0];
3249
- if (type === 'message-port') {
3250
- parentIpc.send({
3251
- jsonrpc: '2.0',
3252
- id: firstMessage.id,
3253
- result: null
3254
- });
3255
- parentIpc.dispose();
3256
- const port = firstMessage.params[1];
3257
- return port;
3258
- }
3259
- return globalThis;
3380
+ api.createNodeRpc = async options => {
3381
+ try {
3382
+ return {
3383
+ async invoke(method, ...params) {
3384
+ const result = await invoke$1('Test.executeMockRpcFunction', options.name, method, ...params);
3385
+ return result;
3386
+ }
3387
+ };
3388
+ } catch (error) {
3389
+ throw new VError(error, 'Failed to mock exec function');
3390
+ }
3391
+ };
3260
3392
  };
3261
- class IpcChildWithModuleWorkerAndMessagePort extends Ipc {
3262
- constructor(port) {
3263
- super(port);
3264
- }
3265
- getData(event) {
3266
- return getData$2(event);
3267
- }
3268
- send(message) {
3269
- this._rawIpc.postMessage(message);
3270
- }
3271
- sendAndTransfer(message) {
3272
- const transfer = getTransferrables(message);
3273
- this._rawIpc.postMessage(message, transfer);
3274
- }
3275
- dispose() {
3276
- if (this._rawIpc.close) {
3277
- this._rawIpc.close();
3393
+
3394
+ const getStatusBarItems = async () => {
3395
+ const providers = Object.values(state$5.providers);
3396
+ const statusBarItems = [];
3397
+ for (const provider of providers) {
3398
+ // @ts-ignore
3399
+ if (provider && provider.statusBarCommands) {
3400
+ // @ts-ignore
3401
+ statusBarItems.push(...provider.statusBarCommands);
3278
3402
  }
3279
3403
  }
3280
- onClose(callback) {
3281
- // ignore
3282
- }
3283
- onMessage(callback) {
3284
- this._rawIpc.addEventListener('message', callback);
3285
- this._rawIpc.start();
3286
- }
3287
- }
3288
- const wrap$d = port => {
3289
- return new IpcChildWithModuleWorkerAndMessagePort(port);
3404
+ return statusBarItems;
3290
3405
  };
3291
- const IpcChildWithModuleWorkerAndMessagePort$1 = {
3292
- __proto__: null,
3293
- listen: listen$6,
3294
- wrap: wrap$d
3406
+ const registerChangeListener = () => {
3407
+ // TODO
3408
+ };
3409
+
3410
+ const handleBeforeUnload = () => {
3411
+ // TODO save all webviews in localstorage
3412
+ // cannot use indexeddb during unload
3413
+ console.log('before unload');
3295
3414
  };
3296
3415
 
3416
+ const MessagePort$1 = 1;
3417
+ const ModuleWorker = 2;
3418
+ const ModuleWorkerWithMessagePort = 4;
3419
+
3420
+ // @ts-ignore
3297
3421
  const getModule$1 = method => {
3298
3422
  switch (method) {
3299
3423
  case ModuleWorker:
@@ -3310,7 +3434,7 @@ const getModule$1 = method => {
3310
3434
  const handleMessagePort = port => {
3311
3435
  const module = getModule$1(MessagePort$1);
3312
3436
  const ipc = module.wrap(port);
3313
- handleIpc(ipc);
3437
+ handleIpc$1(ipc);
3314
3438
  ipc.send('ready');
3315
3439
  };
3316
3440
 
@@ -4084,82 +4208,19 @@ const commandMap = {
4084
4208
  [WorkspaceSetPath]: setWorkspacePath
4085
4209
  };
4086
4210
 
4087
- const handleError = async error => {
4088
- console.error(error);
4089
- };
4090
-
4091
- /**
4092
- * @param {PromiseRejectionEvent} event
4093
- */
4094
- const handleUnhandledRejection = async event => {
4095
- try {
4096
- event.preventDefault();
4097
- await handleError(event.reason);
4098
- } catch {
4099
- console.error(event.reason);
4100
- }
4101
- };
4102
-
4103
- /**
4104
- * @param {ErrorEvent} event
4105
- */
4106
- const handleUnhandledError = async event => {
4107
- try {
4108
- event.preventDefault();
4109
- await handleError(event.error);
4110
- } catch {
4111
- console.error(event.error);
4112
- }
4113
- };
4114
-
4115
- const handleContentSecurityPolicyViolation = event => {
4116
- const {
4117
- violatedDirective,
4118
- sourceFile,
4119
- lineNumber,
4120
- columnNumber
4121
- } = event;
4122
- addError({
4123
- violatedDirective,
4124
- sourceFile,
4125
- lineNumber,
4126
- columnNumber
4211
+ const listen = async () => {
4212
+ const rpc = await WebWorkerRpcClient.create({
4213
+ commandMap: commandMap
4127
4214
  });
4128
- };
4129
-
4130
- const listen = async ({
4131
- method
4132
- }) => {
4133
- const module = await getModule$1(method);
4134
- const rawIpc = await module.listen();
4135
- // @ts-ignore
4136
- if (module.signal) {
4137
- // @ts-ignore
4138
- module.signal(rawIpc);
4139
- }
4140
- const ipc = module.wrap(rawIpc);
4141
- return ipc;
4142
- };
4143
-
4144
- const setStackTraceLimit = value => {
4145
- if (Error.stackTraceLimit && Error.stackTraceLimit < value) {
4146
- Error.stackTraceLimit = value;
4147
- }
4215
+ setRpc(rpc);
4148
4216
  };
4149
4217
 
4150
4218
  const main = async () => {
4151
- setStackTraceLimit(20);
4152
- onerror ||= handleUnhandledError;
4153
- onunhandledrejection ||= handleUnhandledRejection;
4154
- if ('SecurityPolicyViolationEvent' in self) {
4155
- self.addEventListener('securitypolicyviolation', handleContentSecurityPolicyViolation);
4156
- }
4157
- globalThis.vscode = api;
4158
- register$1(commandMap);
4159
- const ipc = await listen({
4160
- method: Auto()
4219
+ setup({
4220
+ errorConstructor: Error,
4221
+ global: globalThis
4161
4222
  });
4162
- listen$1(ipc);
4223
+ await listen();
4163
4224
  };
4164
4225
 
4165
4226
  main();
@@ -4353,7 +4414,7 @@ const create$2 = async ({
4353
4414
  port1,
4354
4415
  port2
4355
4416
  } = getPortTuple();
4356
- await invokeAndTransfer('IpcParent.create', {
4417
+ await invokeAndTransfer$1('IpcParent.create', {
4357
4418
  method: ModuleWorkerAndWorkaroundForChromeDevtoolsBug,
4358
4419
  url,
4359
4420
  name,
@@ -4430,7 +4491,7 @@ const create$1 = ({
4430
4491
  return {
4431
4492
  ipc,
4432
4493
  invoke(method, ...params) {
4433
- return invoke$1(this.ipc, method, ...params);
4494
+ return invoke(this.ipc, method, ...params);
4434
4495
  }
4435
4496
  };
4436
4497
  };
@@ -4441,7 +4502,7 @@ const RpcParentWithJsonRpc = {
4441
4502
  };
4442
4503
 
4443
4504
  const sendMessagePortToElectron = async (port, initialCommand) => {
4444
- await invokeAndTransfer('SendMessagePortToElectron.sendMessagePortToElectron', port, initialCommand);
4505
+ await invokeAndTransfer$1('SendMessagePortToElectron.sendMessagePortToElectron', port, initialCommand);
4445
4506
  };
4446
4507
 
4447
4508
  const getPort = async type => {