@lvce-editor/activity-bar-worker 6.2.0 → 7.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1705 +1,1715 @@
1
- const normalizeLine = line => {
2
- if (line.startsWith('Error: ')) {
3
- return line.slice('Error: '.length);
4
- }
5
- if (line.startsWith('VError: ')) {
6
- return line.slice('VError: '.length);
7
- }
8
- return line;
9
- };
10
- const getCombinedMessage = (error, message) => {
11
- const stringifiedError = normalizeLine(`${error}`);
12
- if (message) {
13
- return `${message}: ${stringifiedError}`;
14
- }
15
- return stringifiedError;
16
- };
17
- const NewLine$2 = '\n';
18
- const getNewLineIndex$1 = (string, startIndex = undefined) => {
19
- return string.indexOf(NewLine$2, startIndex);
20
- };
21
- const mergeStacks = (parent, child) => {
22
- if (!child) {
23
- return parent;
24
- }
25
- const parentNewLineIndex = getNewLineIndex$1(parent);
26
- const childNewLineIndex = getNewLineIndex$1(child);
27
- if (childNewLineIndex === -1) {
28
- return parent;
29
- }
30
- const parentFirstLine = parent.slice(0, parentNewLineIndex);
31
- const childRest = child.slice(childNewLineIndex);
32
- const childFirstLine = normalizeLine(child.slice(0, childNewLineIndex));
33
- if (parentFirstLine.includes(childFirstLine)) {
34
- return parentFirstLine + childRest;
35
- }
36
- return child;
1
+ const toCommandId = key => {
2
+ const dotIndex = key.indexOf('.');
3
+ return key.slice(dotIndex + 1);
37
4
  };
38
- class VError extends Error {
39
- constructor(error, message) {
40
- const combinedMessage = getCombinedMessage(error, message);
41
- super(combinedMessage);
42
- this.name = 'VError';
43
- if (error instanceof Error) {
44
- this.stack = mergeStacks(this.stack, error.stack);
45
- }
46
- if (error.codeFrame) {
47
- // @ts-ignore
48
- this.codeFrame = error.codeFrame;
49
- }
50
- if (error.code) {
51
- // @ts-ignore
52
- this.code = error.code;
53
- }
54
- }
55
- }
56
-
57
- class AssertionError extends Error {
58
- constructor(message) {
59
- super(message);
60
- this.name = 'AssertionError';
61
- }
62
- }
63
- const Object$1 = 1;
64
- const Number$1 = 2;
65
- const Array$1 = 3;
66
- const String = 4;
67
- const Boolean$1 = 5;
68
- const Function = 6;
69
- const Null = 7;
70
- const Unknown = 8;
71
- const getType = value => {
72
- switch (typeof value) {
73
- case 'number':
74
- return Number$1;
75
- case 'function':
76
- return Function;
77
- case 'string':
78
- return String;
79
- case 'object':
80
- if (value === null) {
81
- return Null;
5
+ const create$a = () => {
6
+ const states = Object.create(null);
7
+ const commandMapRef = {};
8
+ return {
9
+ clear() {
10
+ for (const key of Object.keys(states)) {
11
+ delete states[key];
82
12
  }
83
- if (Array.isArray(value)) {
84
- return Array$1;
13
+ },
14
+ diff(uid, modules, numbers) {
15
+ const {
16
+ newState,
17
+ oldState
18
+ } = states[uid];
19
+ const diffResult = [];
20
+ for (let i = 0; i < modules.length; i++) {
21
+ const fn = modules[i];
22
+ if (!fn(oldState, newState)) {
23
+ diffResult.push(numbers[i]);
24
+ }
85
25
  }
86
- return Object$1;
87
- case 'boolean':
88
- return Boolean$1;
89
- default:
90
- return Unknown;
91
- }
26
+ return diffResult;
27
+ },
28
+ dispose(uid) {
29
+ delete states[uid];
30
+ },
31
+ get(uid) {
32
+ return states[uid];
33
+ },
34
+ getCommandIds() {
35
+ const keys = Object.keys(commandMapRef);
36
+ const ids = keys.map(toCommandId);
37
+ return ids;
38
+ },
39
+ getKeys() {
40
+ return Object.keys(states).map(key => {
41
+ return Number.parseFloat(key);
42
+ });
43
+ },
44
+ registerCommands(commandMap) {
45
+ Object.assign(commandMapRef, commandMap);
46
+ },
47
+ set(uid, oldState, newState) {
48
+ states[uid] = {
49
+ newState,
50
+ oldState
51
+ };
52
+ },
53
+ wrapCommand(fn) {
54
+ const wrapped = async (uid, ...args) => {
55
+ const {
56
+ newState,
57
+ oldState
58
+ } = states[uid];
59
+ const newerState = await fn(newState, ...args);
60
+ if (oldState === newerState || newState === newerState) {
61
+ return;
62
+ }
63
+ const latestOld = states[uid];
64
+ const latestNew = {
65
+ ...latestOld.newState,
66
+ ...newerState
67
+ };
68
+ states[uid] = {
69
+ newState: latestNew,
70
+ oldState: latestOld.oldState
71
+ };
72
+ };
73
+ return wrapped;
74
+ },
75
+ wrapGetter(fn) {
76
+ const wrapped = (uid, ...args) => {
77
+ const {
78
+ newState
79
+ } = states[uid];
80
+ return fn(newState, ...args);
81
+ };
82
+ return wrapped;
83
+ },
84
+ wrapLoadContent(fn) {
85
+ const wrapped = async (uid, ...args) => {
86
+ const {
87
+ newState,
88
+ oldState
89
+ } = states[uid];
90
+ const result = await fn(newState, ...args);
91
+ const {
92
+ error,
93
+ state
94
+ } = result;
95
+ if (oldState === state || newState === state) {
96
+ return {
97
+ error
98
+ };
99
+ }
100
+ const latestOld = states[uid];
101
+ const latestNew = {
102
+ ...latestOld.newState,
103
+ ...state
104
+ };
105
+ states[uid] = {
106
+ newState: latestNew,
107
+ oldState: latestOld.oldState
108
+ };
109
+ return {
110
+ error
111
+ };
112
+ };
113
+ return wrapped;
114
+ }
115
+ };
92
116
  };
93
- const number = value => {
94
- const type = getType(value);
95
- if (type !== Number$1) {
96
- throw new AssertionError('expected value to be of type number');
97
- }
117
+ const terminate = () => {
118
+ globalThis.close();
98
119
  };
99
120
 
100
- const isMessagePort = value => {
101
- return value && value instanceof MessagePort;
102
- };
103
- const isMessagePortMain = value => {
104
- return value && value.constructor && value.constructor.name === 'MessagePortMain';
105
- };
106
- const isOffscreenCanvas = value => {
107
- return typeof OffscreenCanvas !== 'undefined' && value instanceof OffscreenCanvas;
108
- };
109
- const isInstanceOf = (value, constructorName) => {
110
- return value?.constructor?.name === constructorName;
111
- };
112
- const isSocket = value => {
113
- return isInstanceOf(value, 'Socket');
121
+ const {
122
+ diff,
123
+ get: get$2,
124
+ getCommandIds,
125
+ registerCommands,
126
+ set: set$4,
127
+ wrapCommand,
128
+ wrapGetter
129
+ } = create$a();
130
+
131
+ // TODO parentUid might ot be needed
132
+ const create$9 = (id, uri, x, y, width, height, args, parentUid, platform = 0) => {
133
+ const state = {
134
+ accountEnabled: true,
135
+ activityBarItems: [],
136
+ currentViewletId: '',
137
+ filteredItems: [],
138
+ focus: 0,
139
+ focused: false,
140
+ focusedIndex: -1,
141
+ height,
142
+ initial: true,
143
+ itemHeight: 48,
144
+ numberOfVisibleItems: 0,
145
+ platform,
146
+ scrollBarHeight: 0,
147
+ selectedIndex: -1,
148
+ sideBarLocation: 0,
149
+ sideBarVisible: false,
150
+ uid: id,
151
+ updateProgress: 0,
152
+ updateState: '',
153
+ userLoginState: 'logged out',
154
+ width,
155
+ x,
156
+ y
157
+ };
158
+ set$4(id, state, state);
159
+ return state;
114
160
  };
115
- const transferrables = [isMessagePort, isMessagePortMain, isOffscreenCanvas, isSocket];
116
- const isTransferrable = value => {
117
- for (const fn of transferrables) {
118
- if (fn(value)) {
119
- return true;
120
- }
121
- }
122
- return false;
161
+
162
+ const isEqual$2 = (oldState, newState) => {
163
+ return oldState.itemHeight === newState.itemHeight;
123
164
  };
124
- const walkValue = (value, transferrables, isTransferrable) => {
125
- if (!value) {
126
- return;
127
- }
128
- if (isTransferrable(value)) {
129
- transferrables.push(value);
130
- return;
131
- }
132
- if (Array.isArray(value)) {
133
- for (const item of value) {
134
- walkValue(item, transferrables, isTransferrable);
135
- }
136
- return;
137
- }
138
- if (typeof value === 'object') {
139
- for (const property of Object.values(value)) {
140
- walkValue(property, transferrables, isTransferrable);
141
- }
142
- return;
143
- }
165
+
166
+ const isEqual$1 = (oldState, newState) => {
167
+ return oldState.focused === newState.focused && oldState.focus === newState.focus;
144
168
  };
145
- const getTransferrables = value => {
146
- const transferrables = [];
147
- walkValue(value, transferrables, isTransferrable);
148
- return transferrables;
169
+
170
+ const isEqual = (oldState, newState) => {
171
+ return oldState.activityBarItems === newState.activityBarItems && oldState.filteredItems === newState.filteredItems && oldState.focusedIndex === newState.focusedIndex && oldState.sideBarLocation === newState.sideBarLocation && oldState.sideBarVisible === newState.sideBarVisible && oldState.updateProgress === newState.updateProgress && oldState.updateState === newState.updateState;
149
172
  };
150
- const attachEvents = that => {
151
- const handleMessage = (...args) => {
152
- const data = that.getData(...args);
153
- that.dispatchEvent(new MessageEvent('message', {
154
- data
155
- }));
173
+
174
+ const RenderItems = 4;
175
+ const RenderFocus = 6;
176
+ const RenderFocusContext = 7;
177
+ const RenderCss = 11;
178
+ const RenderIncremental = 12;
179
+
180
+ const modules = [isEqual, isEqual$1, isEqual$1, isEqual$2];
181
+ const numbers = [RenderIncremental, RenderFocus, RenderFocusContext, RenderCss];
182
+
183
+ const diff2 = uid => {
184
+ return diff(uid, modules, numbers);
185
+ };
186
+
187
+ const List = 1;
188
+
189
+ const focus = state => {
190
+ const {
191
+ focus
192
+ } = state;
193
+ if (focus) {
194
+ return state;
195
+ }
196
+ return {
197
+ ...state,
198
+ focus: List
156
199
  };
157
- that.onMessage(handleMessage);
158
- const handleClose = event => {
159
- that.dispatchEvent(new Event('close'));
200
+ };
201
+
202
+ const focusIndex = (state, index) => {
203
+ return {
204
+ ...state,
205
+ focused: true,
206
+ focusedIndex: index
160
207
  };
161
- that.onClose(handleClose);
162
208
  };
163
- class Ipc extends EventTarget {
164
- constructor(rawIpc) {
165
- super();
166
- this._rawIpc = rawIpc;
167
- attachEvents(this);
209
+
210
+ const focusFirst = state => {
211
+ return focusIndex(state, -1);
212
+ };
213
+
214
+ const focusLast = state => {
215
+ return focusIndex(state, -1);
216
+ };
217
+
218
+ const focusNext = state => {
219
+ return focusIndex(state, -1);
220
+ };
221
+
222
+ const focusNone = state => {
223
+ const {
224
+ focusedIndex
225
+ } = state;
226
+ if (focusedIndex === -1) {
227
+ return state;
168
228
  }
169
- }
170
- const E_INCOMPATIBLE_NATIVE_MODULE = 'E_INCOMPATIBLE_NATIVE_MODULE';
171
- const E_MODULES_NOT_SUPPORTED_IN_ELECTRON = 'E_MODULES_NOT_SUPPORTED_IN_ELECTRON';
172
- const ERR_MODULE_NOT_FOUND = 'ERR_MODULE_NOT_FOUND';
173
- const NewLine$1 = '\n';
174
- const joinLines$1 = lines => {
175
- return lines.join(NewLine$1);
229
+ return focusIndex(state, -1);
176
230
  };
177
- const RE_AT = /^\s+at/;
178
- const RE_AT_PROMISE_INDEX = /^\s*at async Promise.all \(index \d+\)$/;
179
- const isNormalStackLine = line => {
180
- return RE_AT.test(line) && !RE_AT_PROMISE_INDEX.test(line);
231
+
232
+ const Button$2 = 'button';
233
+ const None$1 = 'none';
234
+ const Tab$1 = 'tab';
235
+ const ToolBar = 'toolbar';
236
+
237
+ const Div = 4;
238
+ const Text = 12;
239
+ const Reference = 100;
240
+
241
+ const Button$1 = 'event.button';
242
+ const ClientX = 'event.clientX';
243
+ const ClientY = 'event.clientY';
244
+
245
+ const Enter = 3;
246
+ const Space = 9;
247
+ const PageUp = 10;
248
+ const PageDown = 11;
249
+ const End = 255;
250
+ const Home = 12;
251
+ const UpArrow = 14;
252
+ const DownArrow = 16;
253
+
254
+ const ActivityBar$3 = 1;
255
+ const Settings$1 = 12;
256
+ const ActivityBarAdditionalViews = 17;
257
+
258
+ const Separator = 1;
259
+ const None = 0;
260
+ const Checked = 2;
261
+ const Unchecked = 3;
262
+
263
+ const LeftClick = 0;
264
+
265
+ const Web = 1;
266
+
267
+ const ExtensionManagementWorker = 9006;
268
+ const RendererWorker = 1;
269
+
270
+ const Left = 1;
271
+ const Right = 2;
272
+
273
+ const SetCss = 'Viewlet.setCss';
274
+ const SetDom2 = 'Viewlet.setDom2';
275
+ const SetFocusContext = 'Viewlet.setFocusContext';
276
+ const SetPatches = 'Viewlet.setPatches';
277
+
278
+ const FocusActivityBar = 5;
279
+ const FocusExplorer = 13;
280
+
281
+ const getKeyBindings = () => {
282
+ return [{
283
+ command: 'ActivityBar.focusNext',
284
+ key: DownArrow,
285
+ when: FocusActivityBar
286
+ }, {
287
+ command: 'ActivityBar.focusPrevious',
288
+ key: UpArrow,
289
+ when: FocusActivityBar
290
+ }, {
291
+ command: 'ActivityBar.focusFirst',
292
+ key: Home,
293
+ when: FocusActivityBar
294
+ }, {
295
+ command: 'ActivityBar.focusFirst',
296
+ key: PageUp,
297
+ when: FocusActivityBar
298
+ }, {
299
+ command: 'ActivityBar.focusLast',
300
+ key: PageDown,
301
+ when: FocusActivityBar
302
+ }, {
303
+ command: 'ActivityBar.focusLast',
304
+ key: End,
305
+ when: FocusActivityBar
306
+ }, {
307
+ command: 'ActivityBar.selectCurrent',
308
+ key: Space,
309
+ when: FocusActivityBar
310
+ }, {
311
+ command: 'ActivityBar.selectCurrent',
312
+ key: Enter,
313
+ when: FocusActivityBar
314
+ }];
181
315
  };
182
- const getDetails = lines => {
183
- const index = lines.findIndex(isNormalStackLine);
184
- if (index === -1) {
185
- return {
186
- actualMessage: joinLines$1(lines),
187
- rest: []
188
- };
316
+
317
+ const getMenuEntriesAccountLoggedIn = state => {
318
+ const {
319
+ userLoginState
320
+ } = state;
321
+ const signOutLabel = userLoginState === 'logging out' ? 'Signing Out...' : 'Sign Out';
322
+ return [{
323
+ command: 'ActivityBar.handleClickSignOut',
324
+ flags: None,
325
+ id: 'signOut',
326
+ label: signOutLabel
327
+ }];
328
+ };
329
+ const getMenuEntriesAccountLoggedOut = state => {
330
+ const {
331
+ userLoginState
332
+ } = state;
333
+ const signInLabel = userLoginState === 'logging in' ? 'Signing In...' : 'Sign In';
334
+ return [{
335
+ command: 'ActivityBar.handleClickSignIn',
336
+ flags: None,
337
+ id: 'signIn',
338
+ label: signInLabel
339
+ }];
340
+ };
341
+ const getMenuEntriesAccount = state => {
342
+ // TODO maybe query it now from layout?
343
+ const {
344
+ userLoginState
345
+ } = state;
346
+ if (userLoginState === 'logged in' || userLoginState === 'logging out') {
347
+ return getMenuEntriesAccountLoggedIn(state);
189
348
  }
190
- let lastIndex = index - 1;
191
- while (++lastIndex < lines.length) {
192
- if (!isNormalStackLine(lines[lastIndex])) {
193
- break;
194
- }
349
+ return getMenuEntriesAccountLoggedOut(state);
350
+ };
351
+
352
+ const Tab = 1;
353
+ const Button = 1 << 1;
354
+ const Progress = 1 << 2;
355
+ const Enabled = 1 << 3;
356
+ const Selected = 1 << 4;
357
+ const Focused = 1 << 5;
358
+ const MarginTop = 1 << 6;
359
+
360
+ const emptyObject = {};
361
+ const RE_PLACEHOLDER = /\{(PH\d+)\}/g;
362
+ const i18nString = (key, placeholders = emptyObject) => {
363
+ if (placeholders === emptyObject) {
364
+ return key;
195
365
  }
196
- return {
197
- actualMessage: lines[index - 1],
198
- rest: lines.slice(index, lastIndex)
366
+ const replacer = (match, rest) => {
367
+ return placeholders[rest];
199
368
  };
369
+ return key.replaceAll(RE_PLACEHOLDER, replacer);
200
370
  };
201
- const splitLines$1 = lines => {
202
- return lines.split(NewLine$1);
371
+
372
+ const Account$1 = 'Account';
373
+ const Explorer$1 = 'Explorer';
374
+ const Search$2 = 'Search';
375
+ const SourceControl$2 = 'Source Control';
376
+ const RunAndDebug$1 = 'Run and Debug';
377
+ const Extensions$2 = 'Extensions';
378
+ const Settings = 'Settings';
379
+ const AdditionalViews = 'Additional Views';
380
+ const ActivityBar$2 = 'Activity Bar';
381
+ const MoveSideBarLeft = 'Move Side Bar Left';
382
+ const MoveSideBarRight = 'Move Side Bar Right';
383
+ const HideActivityBar = 'Hide Activity Bar';
384
+ const CheckForUpdates = 'Check For Updates';
385
+ const ColorTheme = 'Color Theme';
386
+ const CommandPalette = 'Command Palette';
387
+ const KeyboardShortcuts = 'Keyboard Shortcuts';
388
+
389
+ const account = () => {
390
+ return i18nString(Account$1);
203
391
  };
204
- const RE_MESSAGE_CODE_BLOCK_START = /^Error: The module '.*'$/;
205
- const RE_MESSAGE_CODE_BLOCK_END = /^\s* at/;
206
- const isMessageCodeBlockStartIndex = line => {
207
- return RE_MESSAGE_CODE_BLOCK_START.test(line);
392
+ const explorer = () => {
393
+ return i18nString(Explorer$1);
208
394
  };
209
- const isMessageCodeBlockEndIndex = line => {
210
- return RE_MESSAGE_CODE_BLOCK_END.test(line);
395
+ const search = () => {
396
+ return i18nString(Search$2);
211
397
  };
212
- const getMessageCodeBlock = stderr => {
213
- const lines = splitLines$1(stderr);
214
- const startIndex = lines.findIndex(isMessageCodeBlockStartIndex);
215
- const endIndex = startIndex + lines.slice(startIndex).findIndex(isMessageCodeBlockEndIndex, startIndex);
216
- const relevantLines = lines.slice(startIndex, endIndex);
217
- const relevantMessage = relevantLines.join(' ').slice('Error: '.length);
218
- return relevantMessage;
398
+ const sourceControl = () => {
399
+ return i18nString(SourceControl$2);
219
400
  };
220
- const isModuleNotFoundMessage = line => {
221
- return line.includes('[ERR_MODULE_NOT_FOUND]');
401
+ const runAndDebug = () => {
402
+ return i18nString(RunAndDebug$1);
403
+ };
404
+ const extensions = () => {
405
+ return i18nString(Extensions$2);
222
406
  };
223
- const getModuleNotFoundError = stderr => {
224
- const lines = splitLines$1(stderr);
225
- const messageIndex = lines.findIndex(isModuleNotFoundMessage);
226
- const message = lines[messageIndex];
227
- return {
228
- code: ERR_MODULE_NOT_FOUND,
229
- message
230
- };
407
+ const settings = () => {
408
+ return i18nString(Settings);
231
409
  };
232
- const isModuleNotFoundError = stderr => {
233
- if (!stderr) {
234
- return false;
235
- }
236
- return stderr.includes('ERR_MODULE_NOT_FOUND');
410
+ const additionalViews = () => {
411
+ return i18nString(AdditionalViews);
237
412
  };
238
- const isModulesSyntaxError = stderr => {
239
- if (!stderr) {
240
- return false;
241
- }
242
- return stderr.includes('SyntaxError: Cannot use import statement outside a module');
413
+ const activityBar = () => {
414
+ return i18nString(ActivityBar$2);
243
415
  };
244
- const RE_NATIVE_MODULE_ERROR = /^innerError Error: Cannot find module '.*.node'/;
245
- const RE_NATIVE_MODULE_ERROR_2 = /was compiled against a different Node.js version/;
246
- const isUnhelpfulNativeModuleError = stderr => {
247
- return RE_NATIVE_MODULE_ERROR.test(stderr) && RE_NATIVE_MODULE_ERROR_2.test(stderr);
416
+ const moveSideBarRight = () => {
417
+ return i18nString(MoveSideBarRight);
248
418
  };
249
- const getNativeModuleErrorMessage = stderr => {
250
- const message = getMessageCodeBlock(stderr);
251
- return {
252
- code: E_INCOMPATIBLE_NATIVE_MODULE,
253
- message: `Incompatible native node module: ${message}`
254
- };
419
+ const moveSideBarLeft = () => {
420
+ return i18nString(MoveSideBarLeft);
255
421
  };
256
- const getModuleSyntaxError = () => {
257
- return {
258
- code: E_MODULES_NOT_SUPPORTED_IN_ELECTRON,
259
- message: `ES Modules are not supported in electron`
260
- };
422
+ const hideActivityBar = () => {
423
+ return i18nString(HideActivityBar);
261
424
  };
262
- const getHelpfulChildProcessError = (stdout, stderr) => {
263
- if (isUnhelpfulNativeModuleError(stderr)) {
264
- return getNativeModuleErrorMessage(stderr);
265
- }
266
- if (isModulesSyntaxError(stderr)) {
267
- return getModuleSyntaxError();
268
- }
269
- if (isModuleNotFoundError(stderr)) {
270
- return getModuleNotFoundError(stderr);
271
- }
272
- const lines = splitLines$1(stderr);
273
- const {
274
- actualMessage,
275
- rest
276
- } = getDetails(lines);
277
- return {
278
- code: '',
279
- message: actualMessage,
280
- stack: rest
281
- };
425
+ const checkForUpdates = () => {
426
+ return i18nString(CheckForUpdates);
282
427
  };
283
- class IpcError extends VError {
284
- // @ts-ignore
285
- constructor(betterMessage, stdout = '', stderr = '') {
286
- if (stdout || stderr) {
287
- // @ts-ignore
288
- const {
289
- code,
290
- message,
291
- stack
292
- } = getHelpfulChildProcessError(stdout, stderr);
293
- const cause = new Error(message);
294
- // @ts-ignore
295
- cause.code = code;
296
- cause.stack = stack;
297
- super(cause, betterMessage);
298
- } else {
299
- super(betterMessage);
300
- }
301
- // @ts-ignore
302
- this.name = 'IpcError';
303
- // @ts-ignore
304
- this.stdout = stdout;
305
- // @ts-ignore
306
- this.stderr = stderr;
307
- }
308
- }
309
- const readyMessage = 'ready';
310
- const getData$2 = event => {
311
- return event.data;
428
+ const commandPalette = () => {
429
+ return i18nString(CommandPalette);
312
430
  };
313
- const listen$7 = () => {
314
- // @ts-ignore
315
- if (typeof WorkerGlobalScope === 'undefined') {
316
- throw new TypeError('module is not in web worker scope');
317
- }
318
- return globalThis;
431
+ const keyboardShortcuts = () => {
432
+ return i18nString(KeyboardShortcuts);
319
433
  };
320
- const signal$8 = global => {
321
- global.postMessage(readyMessage);
434
+ const colorTheme = () => {
435
+ return i18nString(ColorTheme);
322
436
  };
323
- class IpcChildWithModuleWorker extends Ipc {
324
- getData(event) {
325
- return getData$2(event);
326
- }
327
- send(message) {
328
- // @ts-ignore
329
- this._rawIpc.postMessage(message);
330
- }
331
- sendAndTransfer(message) {
332
- const transfer = getTransferrables(message);
333
- // @ts-ignore
334
- this._rawIpc.postMessage(message, transfer);
335
- }
336
- dispose() {
337
- // ignore
338
- }
339
- onClose(callback) {
340
- // ignore
341
- }
342
- onMessage(callback) {
343
- this._rawIpc.addEventListener('message', callback);
437
+
438
+ const menuEntryMoveSideBar = sideBarLocation => {
439
+ switch (sideBarLocation) {
440
+ case Left:
441
+ return {
442
+ command: 'Layout.moveSideBarRight',
443
+ flags: None,
444
+ id: 'moveSideBarRight',
445
+ label: moveSideBarRight()
446
+ };
447
+ case Right:
448
+ return {
449
+ command: 'Layout.moveSideBarLeft',
450
+ flags: None,
451
+ id: 'moveSideBarLeft',
452
+ label: moveSideBarLeft()
453
+ };
454
+ default:
455
+ throw new Error('unexpected side bar location');
344
456
  }
345
- }
346
- const wrap$f = global => {
347
- return new IpcChildWithModuleWorker(global);
348
457
  };
349
- const waitForFirstMessage = async port => {
350
- const {
351
- promise,
352
- resolve
353
- } = Promise.withResolvers();
354
- port.addEventListener('message', resolve, {
355
- once: true
356
- });
357
- const event = await promise;
358
- // @ts-ignore
359
- return event.data;
458
+
459
+ const menuEntrySeparator = {
460
+ command: '',
461
+ flags: Separator,
462
+ id: 'separator',
463
+ label: ''
360
464
  };
361
- const listen$6 = async () => {
362
- const parentIpcRaw = listen$7();
363
- signal$8(parentIpcRaw);
364
- const parentIpc = wrap$f(parentIpcRaw);
365
- const firstMessage = await waitForFirstMessage(parentIpc);
366
- if (firstMessage.method !== 'initialize') {
367
- throw new IpcError('unexpected first message');
368
- }
369
- const type = firstMessage.params[0];
370
- if (type === 'message-port') {
371
- parentIpc.send({
372
- id: firstMessage.id,
373
- jsonrpc: '2.0',
374
- result: null
375
- });
376
- parentIpc.dispose();
377
- const port = firstMessage.params[1];
378
- return port;
379
- }
380
- return globalThis;
465
+
466
+ const toContextMenuItem$1 = activityBarItem => {
467
+ const isEnabled = activityBarItem.flags & Enabled;
468
+ return {
469
+ args: [activityBarItem.id],
470
+ command: 'ActivityBar.toggleActivityBarItem',
471
+ flags: isEnabled ? Checked : Unchecked,
472
+ id: `toggle-${activityBarItem.id}`,
473
+ label: activityBarItem.id
474
+ };
381
475
  };
382
- class IpcChildWithModuleWorkerAndMessagePort extends Ipc {
383
- getData(event) {
384
- return getData$2(event);
385
- }
386
- send(message) {
387
- this._rawIpc.postMessage(message);
388
- }
389
- sendAndTransfer(message) {
390
- const transfer = getTransferrables(message);
391
- this._rawIpc.postMessage(message, transfer);
392
- }
393
- dispose() {
394
- if (this._rawIpc.close) {
395
- this._rawIpc.close();
396
- }
397
- }
398
- onClose(callback) {
399
- // ignore
400
- }
401
- onMessage(callback) {
402
- this._rawIpc.addEventListener('message', callback);
403
- this._rawIpc.start();
476
+
477
+ const getMenuEntriesActivityBar = state => {
478
+ const {
479
+ activityBarItems,
480
+ sideBarLocation
481
+ } = state;
482
+ const topItems = activityBarItems.filter(item => !(item.flags & Button));
483
+ const bottomItems = activityBarItems.filter(item => item.flags & Button);
484
+ const entries = [...topItems.map(toContextMenuItem$1)];
485
+ if (bottomItems.length > 0) {
486
+ entries.push(menuEntrySeparator, ...bottomItems.map(toContextMenuItem$1));
404
487
  }
405
- }
406
- const wrap$e = port => {
407
- return new IpcChildWithModuleWorkerAndMessagePort(port);
488
+ return [...entries, menuEntrySeparator, menuEntryMoveSideBar(sideBarLocation), {
489
+ command: 'Layout.hideActivityBar',
490
+ flags: None,
491
+ id: 'hideActivityBar',
492
+ label: hideActivityBar()
493
+ }];
408
494
  };
409
- const IpcChildWithModuleWorkerAndMessagePort$1 = {
410
- __proto__: null,
411
- listen: listen$6,
412
- wrap: wrap$e
495
+
496
+ const getNumberOfVisibleItems = state => {
497
+ const {
498
+ height,
499
+ itemHeight
500
+ } = state;
501
+ const numberOfVisibleItemsTop = Math.floor(height / itemHeight);
502
+ return numberOfVisibleItemsTop;
413
503
  };
414
- const addListener = (emitter, type, callback) => {
415
- if ('addEventListener' in emitter) {
416
- emitter.addEventListener(type, callback);
417
- } else {
418
- emitter.on(type, callback);
504
+ const getHiddenItems = state => {
505
+ const numberOfVisibleItems = getNumberOfVisibleItems(state);
506
+ const items = state.activityBarItems.filter(item => item.flags & Enabled);
507
+ if (numberOfVisibleItems >= items.length) {
508
+ return [];
419
509
  }
510
+ return items.slice(numberOfVisibleItems - 2, -1);
420
511
  };
421
- const removeListener = (emitter, type, callback) => {
422
- if ('removeEventListener' in emitter) {
423
- emitter.removeEventListener(type, callback);
424
- } else {
425
- emitter.off(type, callback);
426
- }
512
+
513
+ const toContextMenuItem = activityBarItem => {
514
+ return {
515
+ command: '-1',
516
+ // TODO
517
+ flags: None,
518
+ id: '8000',
519
+ // TODO
520
+ label: activityBarItem.id
521
+ };
427
522
  };
428
- const getFirstEvent = (eventEmitter, eventMap) => {
523
+ const getMenuEntriesAdditionalViews = state => {
524
+ const hiddenActivityBarItems = getHiddenItems(state);
525
+ return hiddenActivityBarItems.map(toContextMenuItem);
526
+ };
527
+
528
+ const keyBindingsUri = 'app://keybindings';
529
+ const getMenuEntriesSettings = state => {
429
530
  const {
430
- promise,
431
- resolve
432
- } = Promise.withResolvers();
433
- const listenerMap = Object.create(null);
434
- const cleanup = value => {
435
- for (const event of Object.keys(eventMap)) {
436
- removeListener(eventEmitter, event, listenerMap[event]);
437
- }
438
- resolve(value);
439
- };
440
- for (const [event, type] of Object.entries(eventMap)) {
441
- const listener = event => {
442
- cleanup({
443
- event,
444
- type
445
- });
446
- };
447
- addListener(eventEmitter, event, listener);
448
- listenerMap[event] = listener;
531
+ platform
532
+ } = state;
533
+ const items = [{
534
+ command: 'QuickPick.showEverything',
535
+ flags: None,
536
+ id: 'commandPalette',
537
+ label: commandPalette()
538
+ }, menuEntrySeparator, {
539
+ command: 'Preferences.openSettingsJson',
540
+ flags: None,
541
+ id: 'settings',
542
+ label: settings()
543
+ }, {
544
+ args: [keyBindingsUri],
545
+ command: 'Main.openUri',
546
+ flags: None,
547
+ id: 'keyboardShortcuts',
548
+ label: keyboardShortcuts()
549
+ }, {
550
+ command: 'QuickPick.showColorTheme',
551
+ flags: None,
552
+ id: 'colorTheme',
553
+ label: colorTheme()
554
+ }];
555
+ if (platform !== Web) {
556
+ items.push(menuEntrySeparator, {
557
+ command: 'AutoUpdater.checkForUpdates',
558
+ flags: None,
559
+ id: 'checkForUpdates',
560
+ label: checkForUpdates()
561
+ });
449
562
  }
450
- return promise;
563
+ return items;
451
564
  };
452
- const Message$1 = 3;
453
- const create$5$1 = async ({
454
- isMessagePortOpen,
455
- messagePort
456
- }) => {
457
- if (!isMessagePort(messagePort)) {
458
- throw new IpcError('port must be of type MessagePort');
459
- }
460
- if (isMessagePortOpen) {
461
- return messagePort;
565
+
566
+ const normalizeLine = line => {
567
+ if (line.startsWith('Error: ')) {
568
+ return line.slice('Error: '.length);
462
569
  }
463
- const eventPromise = getFirstEvent(messagePort, {
464
- message: Message$1
465
- });
466
- messagePort.start();
467
- const {
468
- event,
469
- type
470
- } = await eventPromise;
471
- if (type !== Message$1) {
472
- throw new IpcError('Failed to wait for ipc message');
570
+ if (line.startsWith('VError: ')) {
571
+ return line.slice('VError: '.length);
473
572
  }
474
- if (event.data !== readyMessage) {
475
- throw new IpcError('unexpected first message');
573
+ return line;
574
+ };
575
+ const getCombinedMessage = (error, message) => {
576
+ const stringifiedError = normalizeLine(`${error}`);
577
+ if (message) {
578
+ return `${message}: ${stringifiedError}`;
476
579
  }
477
- return messagePort;
580
+ return stringifiedError;
478
581
  };
479
- const signal$1 = messagePort => {
480
- messagePort.start();
582
+ const NewLine$2 = '\n';
583
+ const getNewLineIndex$1 = (string, startIndex = undefined) => {
584
+ return string.indexOf(NewLine$2, startIndex);
481
585
  };
482
- class IpcParentWithMessagePort extends Ipc {
483
- getData = getData$2;
484
- send(message) {
485
- this._rawIpc.postMessage(message);
486
- }
487
- sendAndTransfer(message) {
488
- const transfer = getTransferrables(message);
489
- this._rawIpc.postMessage(message, transfer);
586
+ const mergeStacks = (parent, child) => {
587
+ if (!child) {
588
+ return parent;
490
589
  }
491
- dispose() {
492
- this._rawIpc.close();
590
+ const parentNewLineIndex = getNewLineIndex$1(parent);
591
+ const childNewLineIndex = getNewLineIndex$1(child);
592
+ if (childNewLineIndex === -1) {
593
+ return parent;
493
594
  }
494
- onMessage(callback) {
495
- this._rawIpc.addEventListener('message', callback);
595
+ const parentFirstLine = parent.slice(0, parentNewLineIndex);
596
+ const childRest = child.slice(childNewLineIndex);
597
+ const childFirstLine = normalizeLine(child.slice(0, childNewLineIndex));
598
+ if (parentFirstLine.includes(childFirstLine)) {
599
+ return parentFirstLine + childRest;
496
600
  }
497
- onClose(callback) {}
498
- }
499
- const wrap$5 = messagePort => {
500
- return new IpcParentWithMessagePort(messagePort);
501
- };
502
- const IpcParentWithMessagePort$1 = {
503
- __proto__: null,
504
- create: create$5$1,
505
- signal: signal$1,
506
- wrap: wrap$5
601
+ return child;
507
602
  };
508
-
509
- class CommandNotFoundError extends Error {
510
- constructor(command) {
511
- super(`Command not found ${command}`);
512
- this.name = 'CommandNotFoundError';
603
+ class VError extends Error {
604
+ constructor(error, message) {
605
+ const combinedMessage = getCombinedMessage(error, message);
606
+ super(combinedMessage);
607
+ this.name = 'VError';
608
+ if (error instanceof Error) {
609
+ this.stack = mergeStacks(this.stack, error.stack);
610
+ }
611
+ if (error.codeFrame) {
612
+ // @ts-ignore
613
+ this.codeFrame = error.codeFrame;
614
+ }
615
+ if (error.code) {
616
+ // @ts-ignore
617
+ this.code = error.code;
618
+ }
513
619
  }
514
620
  }
515
- const commands = Object.create(null);
516
- const register = commandMap => {
517
- Object.assign(commands, commandMap);
518
- };
519
- const getCommand = key => {
520
- return commands[key];
521
- };
522
- const execute = (command, ...args) => {
523
- const fn = getCommand(command);
524
- if (!fn) {
525
- throw new CommandNotFoundError(command);
526
- }
527
- return fn(...args);
528
- };
529
621
 
530
- const Two$1 = '2.0';
531
- const callbacks = Object.create(null);
532
- const get$2 = id => {
533
- return callbacks[id];
534
- };
535
- const remove$1 = id => {
536
- delete callbacks[id];
537
- };
538
- class JsonRpcError extends Error {
622
+ class AssertionError extends Error {
539
623
  constructor(message) {
540
624
  super(message);
541
- this.name = 'JsonRpcError';
625
+ this.name = 'AssertionError';
542
626
  }
543
627
  }
544
- const NewLine = '\n';
545
- const DomException = 'DOMException';
546
- const ReferenceError$1 = 'ReferenceError';
547
- const SyntaxError$1 = 'SyntaxError';
548
- const TypeError$1 = 'TypeError';
549
- const getErrorConstructor = (message, type) => {
550
- if (type) {
551
- switch (type) {
552
- case DomException:
553
- return DOMException;
554
- case ReferenceError$1:
555
- return ReferenceError;
556
- case SyntaxError$1:
557
- return SyntaxError;
558
- case TypeError$1:
559
- return TypeError;
560
- default:
561
- return Error;
562
- }
563
- }
564
- if (message.startsWith('TypeError: ')) {
565
- return TypeError;
566
- }
567
- if (message.startsWith('SyntaxError: ')) {
568
- return SyntaxError;
569
- }
570
- if (message.startsWith('ReferenceError: ')) {
571
- return ReferenceError;
628
+ const Object$1 = 1;
629
+ const Number$1 = 2;
630
+ const Array$1 = 3;
631
+ const String = 4;
632
+ const Boolean$1 = 5;
633
+ const Function = 6;
634
+ const Null = 7;
635
+ const Unknown = 8;
636
+ const getType = value => {
637
+ switch (typeof value) {
638
+ case 'number':
639
+ return Number$1;
640
+ case 'function':
641
+ return Function;
642
+ case 'string':
643
+ return String;
644
+ case 'object':
645
+ if (value === null) {
646
+ return Null;
647
+ }
648
+ if (Array.isArray(value)) {
649
+ return Array$1;
650
+ }
651
+ return Object$1;
652
+ case 'boolean':
653
+ return Boolean$1;
654
+ default:
655
+ return Unknown;
572
656
  }
573
- return Error;
574
657
  };
575
- const constructError = (message, type, name) => {
576
- const ErrorConstructor = getErrorConstructor(message, type);
577
- if (ErrorConstructor === DOMException && name) {
578
- return new ErrorConstructor(message, name);
579
- }
580
- if (ErrorConstructor === Error) {
581
- const error = new Error(message);
582
- if (name && name !== 'VError') {
583
- error.name = name;
584
- }
585
- return error;
658
+ const number = value => {
659
+ const type = getType(value);
660
+ if (type !== Number$1) {
661
+ throw new AssertionError('expected value to be of type number');
586
662
  }
587
- return new ErrorConstructor(message);
588
663
  };
589
- const joinLines = lines => {
590
- return lines.join(NewLine);
664
+
665
+ const isMessagePort = value => {
666
+ return value && value instanceof MessagePort;
591
667
  };
592
- const splitLines = lines => {
593
- return lines.split(NewLine);
668
+ const isMessagePortMain = value => {
669
+ return value && value.constructor && value.constructor.name === 'MessagePortMain';
594
670
  };
595
- const getCurrentStack = () => {
596
- const stackLinesToSkip = 3;
597
- const currentStack = joinLines(splitLines(new Error().stack || '').slice(stackLinesToSkip));
598
- return currentStack;
671
+ const isOffscreenCanvas = value => {
672
+ return typeof OffscreenCanvas !== 'undefined' && value instanceof OffscreenCanvas;
599
673
  };
600
- const getNewLineIndex = (string, startIndex = undefined) => {
601
- return string.indexOf(NewLine, startIndex);
674
+ const isInstanceOf = (value, constructorName) => {
675
+ return value?.constructor?.name === constructorName;
602
676
  };
603
- const getParentStack = error => {
604
- let parentStack = error.stack || error.data || error.message || '';
605
- if (parentStack.startsWith(' at')) {
606
- parentStack = error.message + NewLine + parentStack;
607
- }
608
- return parentStack;
677
+ const isSocket = value => {
678
+ return isInstanceOf(value, 'Socket');
609
679
  };
610
- const MethodNotFound = -32601;
611
- const Custom = -32001;
612
- const restoreJsonRpcError = error => {
613
- const currentStack = getCurrentStack();
614
- if (error && error instanceof Error) {
615
- if (typeof error.stack === 'string') {
616
- error.stack = error.stack + NewLine + currentStack;
680
+ const transferrables = [isMessagePort, isMessagePortMain, isOffscreenCanvas, isSocket];
681
+ const isTransferrable = value => {
682
+ for (const fn of transferrables) {
683
+ if (fn(value)) {
684
+ return true;
617
685
  }
618
- return error;
619
686
  }
620
- if (error && error.code && error.code === MethodNotFound) {
621
- const restoredError = new JsonRpcError(error.message);
622
- const parentStack = getParentStack(error);
623
- restoredError.stack = parentStack + NewLine + currentStack;
624
- return restoredError;
687
+ return false;
688
+ };
689
+ const walkValue = (value, transferrables, isTransferrable) => {
690
+ if (!value) {
691
+ return;
625
692
  }
626
- if (error && error.message) {
627
- const restoredError = constructError(error.message, error.type, error.name);
628
- if (error.data) {
629
- if (error.data.stack && error.data.type && error.message) {
630
- restoredError.stack = error.data.type + ': ' + error.message + NewLine + error.data.stack + NewLine + currentStack;
631
- } else if (error.data.stack) {
632
- restoredError.stack = error.data.stack;
633
- }
634
- if (error.data.codeFrame) {
635
- // @ts-ignore
636
- restoredError.codeFrame = error.data.codeFrame;
637
- }
638
- if (error.data.code) {
639
- // @ts-ignore
640
- restoredError.code = error.data.code;
641
- }
642
- if (error.data.type) {
643
- // @ts-ignore
644
- restoredError.name = error.data.type;
645
- }
646
- } else {
647
- if (error.stack) {
648
- const lowerStack = restoredError.stack || '';
649
- // @ts-ignore
650
- const indexNewLine = getNewLineIndex(lowerStack);
651
- const parentStack = getParentStack(error);
652
- // @ts-ignore
653
- restoredError.stack = parentStack + lowerStack.slice(indexNewLine);
654
- }
655
- if (error.codeFrame) {
656
- // @ts-ignore
657
- restoredError.codeFrame = error.codeFrame;
658
- }
693
+ if (isTransferrable(value)) {
694
+ transferrables.push(value);
695
+ return;
696
+ }
697
+ if (Array.isArray(value)) {
698
+ for (const item of value) {
699
+ walkValue(item, transferrables, isTransferrable);
659
700
  }
660
- return restoredError;
701
+ return;
661
702
  }
662
- if (typeof error === 'string') {
663
- return new Error(`JsonRpc Error: ${error}`);
703
+ if (typeof value === 'object') {
704
+ for (const property of Object.values(value)) {
705
+ walkValue(property, transferrables, isTransferrable);
706
+ }
707
+ return;
664
708
  }
665
- return new Error(`JsonRpc Error: ${error}`);
666
709
  };
667
- const unwrapJsonRpcResult = responseMessage => {
668
- if ('error' in responseMessage) {
669
- const restoredError = restoreJsonRpcError(responseMessage.error);
670
- throw restoredError;
671
- }
672
- if ('result' in responseMessage) {
673
- return responseMessage.result;
674
- }
675
- throw new JsonRpcError('unexpected response message');
710
+ const getTransferrables = value => {
711
+ const transferrables = [];
712
+ walkValue(value, transferrables, isTransferrable);
713
+ return transferrables;
676
714
  };
677
- const warn = (...args) => {
678
- console.warn(...args);
715
+ const attachEvents = that => {
716
+ const handleMessage = (...args) => {
717
+ const data = that.getData(...args);
718
+ that.dispatchEvent(new MessageEvent('message', {
719
+ data
720
+ }));
721
+ };
722
+ that.onMessage(handleMessage);
723
+ const handleClose = event => {
724
+ that.dispatchEvent(new Event('close'));
725
+ };
726
+ that.onClose(handleClose);
679
727
  };
680
- const resolve = (id, response) => {
681
- const fn = get$2(id);
682
- if (!fn) {
683
- console.log(response);
684
- warn(`callback ${id} may already be disposed`);
685
- return;
728
+ class Ipc extends EventTarget {
729
+ constructor(rawIpc) {
730
+ super();
731
+ this._rawIpc = rawIpc;
732
+ attachEvents(this);
686
733
  }
687
- fn(response);
688
- remove$1(id);
734
+ }
735
+ const E_INCOMPATIBLE_NATIVE_MODULE = 'E_INCOMPATIBLE_NATIVE_MODULE';
736
+ const E_MODULES_NOT_SUPPORTED_IN_ELECTRON = 'E_MODULES_NOT_SUPPORTED_IN_ELECTRON';
737
+ const ERR_MODULE_NOT_FOUND = 'ERR_MODULE_NOT_FOUND';
738
+ const NewLine$1 = '\n';
739
+ const joinLines$1 = lines => {
740
+ return lines.join(NewLine$1);
689
741
  };
690
- const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
691
- const getErrorType = prettyError => {
692
- if (prettyError && prettyError.type) {
693
- return prettyError.type;
742
+ const RE_AT = /^\s+at/;
743
+ const RE_AT_PROMISE_INDEX = /^\s*at async Promise.all \(index \d+\)$/;
744
+ const isNormalStackLine = line => {
745
+ return RE_AT.test(line) && !RE_AT_PROMISE_INDEX.test(line);
746
+ };
747
+ const getDetails = lines => {
748
+ const index = lines.findIndex(isNormalStackLine);
749
+ if (index === -1) {
750
+ return {
751
+ actualMessage: joinLines$1(lines),
752
+ rest: []
753
+ };
694
754
  }
695
- if (prettyError && prettyError.constructor && prettyError.constructor.name) {
696
- return prettyError.constructor.name;
755
+ let lastIndex = index - 1;
756
+ while (++lastIndex < lines.length) {
757
+ if (!isNormalStackLine(lines[lastIndex])) {
758
+ break;
759
+ }
697
760
  }
698
- return undefined;
761
+ return {
762
+ actualMessage: lines[index - 1],
763
+ rest: lines.slice(index, lastIndex)
764
+ };
699
765
  };
700
- const isAlreadyStack = line => {
701
- return line.trim().startsWith('at ');
766
+ const splitLines$1 = lines => {
767
+ return lines.split(NewLine$1);
702
768
  };
703
- const getStack = prettyError => {
704
- const stackString = prettyError.stack || '';
705
- const newLineIndex = stackString.indexOf('\n');
706
- if (newLineIndex !== -1 && !isAlreadyStack(stackString.slice(0, newLineIndex))) {
707
- return stackString.slice(newLineIndex + 1);
708
- }
709
- return stackString;
769
+ const RE_MESSAGE_CODE_BLOCK_START = /^Error: The module '.*'$/;
770
+ const RE_MESSAGE_CODE_BLOCK_END = /^\s* at/;
771
+ const isMessageCodeBlockStartIndex = line => {
772
+ return RE_MESSAGE_CODE_BLOCK_START.test(line);
710
773
  };
711
- const getErrorProperty = (error, prettyError) => {
712
- if (error && error.code === E_COMMAND_NOT_FOUND) {
713
- return {
714
- code: MethodNotFound,
715
- data: error.stack,
716
- message: error.message
717
- };
718
- }
774
+ const isMessageCodeBlockEndIndex = line => {
775
+ return RE_MESSAGE_CODE_BLOCK_END.test(line);
776
+ };
777
+ const getMessageCodeBlock = stderr => {
778
+ const lines = splitLines$1(stderr);
779
+ const startIndex = lines.findIndex(isMessageCodeBlockStartIndex);
780
+ const endIndex = startIndex + lines.slice(startIndex).findIndex(isMessageCodeBlockEndIndex, startIndex);
781
+ const relevantLines = lines.slice(startIndex, endIndex);
782
+ const relevantMessage = relevantLines.join(' ').slice('Error: '.length);
783
+ return relevantMessage;
784
+ };
785
+ const isModuleNotFoundMessage = line => {
786
+ return line.includes('[ERR_MODULE_NOT_FOUND]');
787
+ };
788
+ const getModuleNotFoundError = stderr => {
789
+ const lines = splitLines$1(stderr);
790
+ const messageIndex = lines.findIndex(isModuleNotFoundMessage);
791
+ const message = lines[messageIndex];
719
792
  return {
720
- code: Custom,
721
- data: {
722
- code: prettyError.code,
723
- codeFrame: prettyError.codeFrame,
724
- name: prettyError.name,
725
- stack: getStack(prettyError),
726
- type: getErrorType(prettyError)
727
- },
728
- message: prettyError.message
793
+ code: ERR_MODULE_NOT_FOUND,
794
+ message
729
795
  };
730
796
  };
731
- const create$1$1 = (id, error) => {
732
- return {
733
- error,
734
- id,
735
- jsonrpc: Two$1
736
- };
797
+ const isModuleNotFoundError = stderr => {
798
+ if (!stderr) {
799
+ return false;
800
+ }
801
+ return stderr.includes('ERR_MODULE_NOT_FOUND');
802
+ };
803
+ const isModulesSyntaxError = stderr => {
804
+ if (!stderr) {
805
+ return false;
806
+ }
807
+ return stderr.includes('SyntaxError: Cannot use import statement outside a module');
737
808
  };
738
- const getErrorResponse = (id, error, preparePrettyError, logError) => {
739
- const prettyError = preparePrettyError(error);
740
- logError(error, prettyError);
741
- const errorProperty = getErrorProperty(error, prettyError);
742
- return create$1$1(id, errorProperty);
809
+ const RE_NATIVE_MODULE_ERROR = /^innerError Error: Cannot find module '.*.node'/;
810
+ const RE_NATIVE_MODULE_ERROR_2 = /was compiled against a different Node.js version/;
811
+ const isUnhelpfulNativeModuleError = stderr => {
812
+ return RE_NATIVE_MODULE_ERROR.test(stderr) && RE_NATIVE_MODULE_ERROR_2.test(stderr);
743
813
  };
744
- const create$a = (message, result) => {
814
+ const getNativeModuleErrorMessage = stderr => {
815
+ const message = getMessageCodeBlock(stderr);
745
816
  return {
746
- id: message.id,
747
- jsonrpc: Two$1,
748
- result: result ?? null
817
+ code: E_INCOMPATIBLE_NATIVE_MODULE,
818
+ message: `Incompatible native node module: ${message}`
749
819
  };
750
820
  };
751
- const getSuccessResponse = (message, result) => {
752
- const resultProperty = result ?? null;
753
- return create$a(message, resultProperty);
821
+ const getModuleSyntaxError = () => {
822
+ return {
823
+ code: E_MODULES_NOT_SUPPORTED_IN_ELECTRON,
824
+ message: `ES Modules are not supported in electron`
825
+ };
754
826
  };
755
- const getErrorResponseSimple = (id, error) => {
827
+ const getHelpfulChildProcessError = (stdout, stderr) => {
828
+ if (isUnhelpfulNativeModuleError(stderr)) {
829
+ return getNativeModuleErrorMessage(stderr);
830
+ }
831
+ if (isModulesSyntaxError(stderr)) {
832
+ return getModuleSyntaxError();
833
+ }
834
+ if (isModuleNotFoundError(stderr)) {
835
+ return getModuleNotFoundError(stderr);
836
+ }
837
+ const lines = splitLines$1(stderr);
838
+ const {
839
+ actualMessage,
840
+ rest
841
+ } = getDetails(lines);
756
842
  return {
757
- error: {
758
- code: Custom,
759
- data: error,
760
- // @ts-ignore
761
- message: error.message
762
- },
763
- id,
764
- jsonrpc: Two$1
843
+ code: '',
844
+ message: actualMessage,
845
+ stack: rest
765
846
  };
766
847
  };
767
- const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
768
- try {
769
- const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
770
- return getSuccessResponse(message, result);
771
- } catch (error) {
772
- if (ipc.canUseSimpleErrorResponse) {
773
- return getErrorResponseSimple(message.id, error);
848
+ class IpcError extends VError {
849
+ // @ts-ignore
850
+ constructor(betterMessage, stdout = '', stderr = '') {
851
+ if (stdout || stderr) {
852
+ // @ts-ignore
853
+ const {
854
+ code,
855
+ message,
856
+ stack
857
+ } = getHelpfulChildProcessError(stdout, stderr);
858
+ const cause = new Error(message);
859
+ // @ts-ignore
860
+ cause.code = code;
861
+ cause.stack = stack;
862
+ super(cause, betterMessage);
863
+ } else {
864
+ super(betterMessage);
774
865
  }
775
- return getErrorResponse(message.id, error, preparePrettyError, logError);
866
+ // @ts-ignore
867
+ this.name = 'IpcError';
868
+ // @ts-ignore
869
+ this.stdout = stdout;
870
+ // @ts-ignore
871
+ this.stderr = stderr;
776
872
  }
873
+ }
874
+ const readyMessage = 'ready';
875
+ const getData$2 = event => {
876
+ return event.data;
777
877
  };
778
- const defaultPreparePrettyError = error => {
779
- return error;
780
- };
781
- const defaultLogError = () => {
782
- // ignore
878
+ const listen$7 = () => {
879
+ // @ts-ignore
880
+ if (typeof WorkerGlobalScope === 'undefined') {
881
+ throw new TypeError('module is not in web worker scope');
882
+ }
883
+ return globalThis;
783
884
  };
784
- const defaultRequiresSocket = () => {
785
- return false;
885
+ const signal$8 = global => {
886
+ global.postMessage(readyMessage);
786
887
  };
787
- const defaultResolve = resolve;
788
-
789
- // TODO maybe remove this in v6 or v7, only accept options object to simplify the code
790
- const normalizeParams = args => {
791
- if (args.length === 1) {
792
- const options = args[0];
793
- return {
794
- execute: options.execute,
795
- ipc: options.ipc,
796
- logError: options.logError || defaultLogError,
797
- message: options.message,
798
- preparePrettyError: options.preparePrettyError || defaultPreparePrettyError,
799
- requiresSocket: options.requiresSocket || defaultRequiresSocket,
800
- resolve: options.resolve || defaultResolve
801
- };
888
+ class IpcChildWithModuleWorker extends Ipc {
889
+ getData(event) {
890
+ return getData$2(event);
802
891
  }
803
- return {
804
- execute: args[2],
805
- ipc: args[0],
806
- logError: args[5],
807
- message: args[1],
808
- preparePrettyError: args[4],
809
- requiresSocket: args[6],
810
- resolve: args[3]
811
- };
892
+ send(message) {
893
+ // @ts-ignore
894
+ this._rawIpc.postMessage(message);
895
+ }
896
+ sendAndTransfer(message) {
897
+ const transfer = getTransferrables(message);
898
+ // @ts-ignore
899
+ this._rawIpc.postMessage(message, transfer);
900
+ }
901
+ dispose() {
902
+ // ignore
903
+ }
904
+ onClose(callback) {
905
+ // ignore
906
+ }
907
+ onMessage(callback) {
908
+ this._rawIpc.addEventListener('message', callback);
909
+ }
910
+ }
911
+ const wrap$f = global => {
912
+ return new IpcChildWithModuleWorker(global);
812
913
  };
813
- const handleJsonRpcMessage = async (...args) => {
814
- const options = normalizeParams(args);
914
+ const waitForFirstMessage = async port => {
815
915
  const {
816
- execute,
817
- ipc,
818
- logError,
819
- message,
820
- preparePrettyError,
821
- requiresSocket,
916
+ promise,
822
917
  resolve
823
- } = options;
824
- if ('id' in message) {
825
- if ('method' in message) {
826
- const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
827
- try {
828
- ipc.send(response);
829
- } catch (error) {
830
- const errorResponse = getErrorResponse(message.id, error, preparePrettyError, logError);
831
- ipc.send(errorResponse);
832
- }
833
- return;
834
- }
835
- resolve(message.id, message);
836
- return;
918
+ } = Promise.withResolvers();
919
+ port.addEventListener('message', resolve, {
920
+ once: true
921
+ });
922
+ const event = await promise;
923
+ // @ts-ignore
924
+ return event.data;
925
+ };
926
+ const listen$6 = async () => {
927
+ const parentIpcRaw = listen$7();
928
+ signal$8(parentIpcRaw);
929
+ const parentIpc = wrap$f(parentIpcRaw);
930
+ const firstMessage = await waitForFirstMessage(parentIpc);
931
+ if (firstMessage.method !== 'initialize') {
932
+ throw new IpcError('unexpected first message');
837
933
  }
838
- if ('method' in message) {
839
- await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
840
- return;
934
+ const type = firstMessage.params[0];
935
+ if (type === 'message-port') {
936
+ parentIpc.send({
937
+ id: firstMessage.id,
938
+ jsonrpc: '2.0',
939
+ result: null
940
+ });
941
+ parentIpc.dispose();
942
+ const port = firstMessage.params[1];
943
+ return port;
841
944
  }
842
- throw new JsonRpcError('unexpected message');
843
- };
844
-
845
- const Two = '2.0';
846
-
847
- const create$9 = (method, params) => {
848
- return {
849
- jsonrpc: Two,
850
- method,
851
- params
852
- };
945
+ return globalThis;
853
946
  };
854
-
855
- const create$8 = (id, method, params) => {
856
- const message = {
857
- id,
858
- jsonrpc: Two,
859
- method,
860
- params
861
- };
862
- return message;
947
+ class IpcChildWithModuleWorkerAndMessagePort extends Ipc {
948
+ getData(event) {
949
+ return getData$2(event);
950
+ }
951
+ send(message) {
952
+ this._rawIpc.postMessage(message);
953
+ }
954
+ sendAndTransfer(message) {
955
+ const transfer = getTransferrables(message);
956
+ this._rawIpc.postMessage(message, transfer);
957
+ }
958
+ dispose() {
959
+ if (this._rawIpc.close) {
960
+ this._rawIpc.close();
961
+ }
962
+ }
963
+ onClose(callback) {
964
+ // ignore
965
+ }
966
+ onMessage(callback) {
967
+ this._rawIpc.addEventListener('message', callback);
968
+ this._rawIpc.start();
969
+ }
970
+ }
971
+ const wrap$e = port => {
972
+ return new IpcChildWithModuleWorkerAndMessagePort(port);
863
973
  };
864
-
865
- let id = 0;
866
- const create$7 = () => {
867
- return ++id;
974
+ const IpcChildWithModuleWorkerAndMessagePort$1 = {
975
+ __proto__: null,
976
+ listen: listen$6,
977
+ wrap: wrap$e
868
978
  };
869
-
870
- const registerPromise = map => {
871
- const id = create$7();
979
+ const addListener = (emitter, type, callback) => {
980
+ if ('addEventListener' in emitter) {
981
+ emitter.addEventListener(type, callback);
982
+ } else {
983
+ emitter.on(type, callback);
984
+ }
985
+ };
986
+ const removeListener = (emitter, type, callback) => {
987
+ if ('removeEventListener' in emitter) {
988
+ emitter.removeEventListener(type, callback);
989
+ } else {
990
+ emitter.off(type, callback);
991
+ }
992
+ };
993
+ const getFirstEvent = (eventEmitter, eventMap) => {
872
994
  const {
873
995
  promise,
874
996
  resolve
875
997
  } = Promise.withResolvers();
876
- map[id] = resolve;
877
- return {
878
- id,
879
- promise
998
+ const listenerMap = Object.create(null);
999
+ const cleanup = value => {
1000
+ for (const event of Object.keys(eventMap)) {
1001
+ removeListener(eventEmitter, event, listenerMap[event]);
1002
+ }
1003
+ resolve(value);
880
1004
  };
1005
+ for (const [event, type] of Object.entries(eventMap)) {
1006
+ const listener = event => {
1007
+ cleanup({
1008
+ event,
1009
+ type
1010
+ });
1011
+ };
1012
+ addListener(eventEmitter, event, listener);
1013
+ listenerMap[event] = listener;
1014
+ }
1015
+ return promise;
881
1016
  };
882
-
883
- const invokeHelper = async (callbacks, ipc, method, params, useSendAndTransfer) => {
1017
+ const Message$1 = 3;
1018
+ const create$5$1 = async ({
1019
+ isMessagePortOpen,
1020
+ messagePort
1021
+ }) => {
1022
+ if (!isMessagePort(messagePort)) {
1023
+ throw new IpcError('port must be of type MessagePort');
1024
+ }
1025
+ if (isMessagePortOpen) {
1026
+ return messagePort;
1027
+ }
1028
+ const eventPromise = getFirstEvent(messagePort, {
1029
+ message: Message$1
1030
+ });
1031
+ messagePort.start();
884
1032
  const {
885
- id,
886
- promise
887
- } = registerPromise(callbacks);
888
- const message = create$8(id, method, params);
889
- if (useSendAndTransfer && ipc.sendAndTransfer) {
890
- ipc.sendAndTransfer(message);
891
- } else {
892
- ipc.send(message);
1033
+ event,
1034
+ type
1035
+ } = await eventPromise;
1036
+ if (type !== Message$1) {
1037
+ throw new IpcError('Failed to wait for ipc message');
893
1038
  }
894
- const responseMessage = await promise;
895
- return unwrapJsonRpcResult(responseMessage);
896
- };
897
- const createRpc = ipc => {
898
- const callbacks = Object.create(null);
899
- ipc._resolve = (id, response) => {
900
- const fn = callbacks[id];
901
- if (!fn) {
902
- console.warn(`callback ${id} may already be disposed`);
903
- return;
904
- }
905
- fn(response);
906
- delete callbacks[id];
907
- };
908
- const rpc = {
909
- async dispose() {
910
- await ipc?.dispose();
911
- },
912
- invoke(method, ...params) {
913
- return invokeHelper(callbacks, ipc, method, params, false);
914
- },
915
- invokeAndTransfer(method, ...params) {
916
- return invokeHelper(callbacks, ipc, method, params, true);
917
- },
918
- // @ts-ignore
919
- ipc,
920
- /**
921
- * @deprecated
922
- */
923
- send(method, ...params) {
924
- const message = create$9(method, params);
925
- ipc.send(message);
926
- }
927
- };
928
- return rpc;
929
- };
930
-
931
- const requiresSocket = () => {
932
- return false;
1039
+ if (event.data !== readyMessage) {
1040
+ throw new IpcError('unexpected first message');
1041
+ }
1042
+ return messagePort;
933
1043
  };
934
- const preparePrettyError = error => {
935
- return error;
1044
+ const signal$1 = messagePort => {
1045
+ messagePort.start();
936
1046
  };
937
- const logError = () => {
938
- // handled by renderer worker
1047
+ class IpcParentWithMessagePort extends Ipc {
1048
+ getData = getData$2;
1049
+ send(message) {
1050
+ this._rawIpc.postMessage(message);
1051
+ }
1052
+ sendAndTransfer(message) {
1053
+ const transfer = getTransferrables(message);
1054
+ this._rawIpc.postMessage(message, transfer);
1055
+ }
1056
+ dispose() {
1057
+ this._rawIpc.close();
1058
+ }
1059
+ onMessage(callback) {
1060
+ this._rawIpc.addEventListener('message', callback);
1061
+ }
1062
+ onClose(callback) {}
1063
+ }
1064
+ const wrap$5 = messagePort => {
1065
+ return new IpcParentWithMessagePort(messagePort);
939
1066
  };
940
- const handleMessage = event => {
941
- const actualRequiresSocket = event?.target?.requiresSocket || requiresSocket;
942
- const actualExecute = event?.target?.execute || execute;
943
- return handleJsonRpcMessage(event.target, event.data, actualExecute, event.target._resolve, preparePrettyError, logError, actualRequiresSocket);
1067
+ const IpcParentWithMessagePort$1 = {
1068
+ __proto__: null,
1069
+ create: create$5$1,
1070
+ signal: signal$1,
1071
+ wrap: wrap$5
944
1072
  };
945
1073
 
946
- const handleIpc = ipc => {
947
- if ('addEventListener' in ipc) {
948
- ipc.addEventListener('message', handleMessage);
949
- } else if ('on' in ipc) {
950
- // deprecated
951
- ipc.on('message', handleMessage);
1074
+ class CommandNotFoundError extends Error {
1075
+ constructor(command) {
1076
+ super(`Command not found ${command}`);
1077
+ this.name = 'CommandNotFoundError';
952
1078
  }
1079
+ }
1080
+ const commands = Object.create(null);
1081
+ const register = commandMap => {
1082
+ Object.assign(commands, commandMap);
953
1083
  };
954
-
955
- const listen$1 = async (module, options) => {
956
- const rawIpc = await module.listen(options);
957
- if (module.signal) {
958
- module.signal(rawIpc);
1084
+ const getCommand = key => {
1085
+ return commands[key];
1086
+ };
1087
+ const execute = (command, ...args) => {
1088
+ const fn = getCommand(command);
1089
+ if (!fn) {
1090
+ throw new CommandNotFoundError(command);
959
1091
  }
960
- const ipc = module.wrap(rawIpc);
961
- return ipc;
1092
+ return fn(...args);
962
1093
  };
963
1094
 
964
- const create$6 = async ({
965
- commandMap,
966
- isMessagePortOpen = true,
967
- messagePort
968
- }) => {
969
- // TODO create a commandMap per rpc instance
970
- register(commandMap);
971
- const rawIpc = await IpcParentWithMessagePort$1.create({
972
- isMessagePortOpen,
973
- messagePort
974
- });
975
- const ipc = IpcParentWithMessagePort$1.wrap(rawIpc);
976
- handleIpc(ipc);
977
- const rpc = createRpc(ipc);
978
- messagePort.start();
979
- return rpc;
1095
+ const Two$1 = '2.0';
1096
+ const callbacks = Object.create(null);
1097
+ const get$1 = id => {
1098
+ return callbacks[id];
980
1099
  };
981
-
982
- const create$5 = async ({
983
- commandMap,
984
- isMessagePortOpen,
985
- send
986
- }) => {
987
- const {
988
- port1,
989
- port2
990
- } = new MessageChannel();
991
- await send(port1);
992
- return create$6({
993
- commandMap,
994
- isMessagePortOpen,
995
- messagePort: port2
996
- });
1100
+ const remove$1 = id => {
1101
+ delete callbacks[id];
997
1102
  };
998
-
999
- const createSharedLazyRpc = factory => {
1000
- let rpcPromise;
1001
- const getOrCreate = () => {
1002
- if (!rpcPromise) {
1003
- rpcPromise = factory();
1004
- }
1005
- return rpcPromise;
1006
- };
1007
- return {
1008
- async dispose() {
1009
- const rpc = await getOrCreate();
1010
- await rpc.dispose();
1011
- },
1012
- async invoke(method, ...params) {
1013
- const rpc = await getOrCreate();
1014
- return rpc.invoke(method, ...params);
1015
- },
1016
- async invokeAndTransfer(method, ...params) {
1017
- const rpc = await getOrCreate();
1018
- return rpc.invokeAndTransfer(method, ...params);
1019
- },
1020
- async send(method, ...params) {
1021
- const rpc = await getOrCreate();
1022
- rpc.send(method, ...params);
1103
+ class JsonRpcError extends Error {
1104
+ constructor(message) {
1105
+ super(message);
1106
+ this.name = 'JsonRpcError';
1107
+ }
1108
+ }
1109
+ const NewLine = '\n';
1110
+ const DomException = 'DOMException';
1111
+ const ReferenceError$1 = 'ReferenceError';
1112
+ const SyntaxError$1 = 'SyntaxError';
1113
+ const TypeError$1 = 'TypeError';
1114
+ const getErrorConstructor = (message, type) => {
1115
+ if (type) {
1116
+ switch (type) {
1117
+ case DomException:
1118
+ return DOMException;
1119
+ case ReferenceError$1:
1120
+ return ReferenceError;
1121
+ case SyntaxError$1:
1122
+ return SyntaxError;
1123
+ case TypeError$1:
1124
+ return TypeError;
1125
+ default:
1126
+ return Error;
1023
1127
  }
1024
- };
1128
+ }
1129
+ if (message.startsWith('TypeError: ')) {
1130
+ return TypeError;
1131
+ }
1132
+ if (message.startsWith('SyntaxError: ')) {
1133
+ return SyntaxError;
1134
+ }
1135
+ if (message.startsWith('ReferenceError: ')) {
1136
+ return ReferenceError;
1137
+ }
1138
+ return Error;
1025
1139
  };
1026
-
1027
- const create$4 = async ({
1028
- commandMap,
1029
- isMessagePortOpen,
1030
- send
1031
- }) => {
1032
- return createSharedLazyRpc(() => {
1033
- return create$5({
1034
- commandMap,
1035
- isMessagePortOpen,
1036
- send
1037
- });
1038
- });
1140
+ const constructError = (message, type, name) => {
1141
+ const ErrorConstructor = getErrorConstructor(message, type);
1142
+ if (ErrorConstructor === DOMException && name) {
1143
+ return new ErrorConstructor(message, name);
1144
+ }
1145
+ if (ErrorConstructor === Error) {
1146
+ const error = new Error(message);
1147
+ if (name && name !== 'VError') {
1148
+ error.name = name;
1149
+ }
1150
+ return error;
1151
+ }
1152
+ return new ErrorConstructor(message);
1039
1153
  };
1040
-
1041
- const create$3 = async ({
1042
- commandMap
1043
- }) => {
1044
- // TODO create a commandMap per rpc instance
1045
- register(commandMap);
1046
- const ipc = await listen$1(IpcChildWithModuleWorkerAndMessagePort$1);
1047
- handleIpc(ipc);
1048
- const rpc = createRpc(ipc);
1049
- return rpc;
1154
+ const joinLines = lines => {
1155
+ return lines.join(NewLine);
1050
1156
  };
1051
-
1052
- const createMockRpc = ({
1053
- commandMap
1054
- }) => {
1055
- const invocations = [];
1056
- const invoke = (method, ...params) => {
1057
- invocations.push([method, ...params]);
1058
- const command = commandMap[method];
1059
- if (!command) {
1060
- throw new Error(`command ${method} not found`);
1061
- }
1062
- return command(...params);
1063
- };
1064
- const mockRpc = {
1065
- invocations,
1066
- invoke,
1067
- invokeAndTransfer: invoke
1068
- };
1069
- return mockRpc;
1157
+ const splitLines = lines => {
1158
+ return lines.split(NewLine);
1070
1159
  };
1071
-
1072
- const rpcs = Object.create(null);
1073
- const set$3 = (id, rpc) => {
1074
- rpcs[id] = rpc;
1160
+ const getCurrentStack = () => {
1161
+ const stackLinesToSkip = 3;
1162
+ const currentStack = joinLines(splitLines(new Error().stack || '').slice(stackLinesToSkip));
1163
+ return currentStack;
1075
1164
  };
1076
- const get$1 = id => {
1077
- return rpcs[id];
1165
+ const getNewLineIndex = (string, startIndex = undefined) => {
1166
+ return string.indexOf(NewLine, startIndex);
1078
1167
  };
1079
- const remove = id => {
1080
- delete rpcs[id];
1168
+ const getParentStack = error => {
1169
+ let parentStack = error.stack || error.data || error.message || '';
1170
+ if (parentStack.startsWith(' at')) {
1171
+ parentStack = error.message + NewLine + parentStack;
1172
+ }
1173
+ return parentStack;
1081
1174
  };
1082
-
1083
- /* eslint-disable @typescript-eslint/explicit-function-return-type */
1084
- const create$2 = rpcId => {
1085
- return {
1086
- async dispose() {
1087
- const rpc = get$1(rpcId);
1088
- await rpc.dispose();
1089
- },
1090
- // @ts-ignore
1091
- invoke(method, ...params) {
1092
- const rpc = get$1(rpcId);
1093
- // @ts-ignore
1094
- return rpc.invoke(method, ...params);
1095
- },
1096
- // @ts-ignore
1097
- invokeAndTransfer(method, ...params) {
1098
- const rpc = get$1(rpcId);
1099
- // @ts-ignore
1100
- return rpc.invokeAndTransfer(method, ...params);
1101
- },
1102
- registerMockRpc(commandMap) {
1103
- const mockRpc = createMockRpc({
1104
- commandMap
1105
- });
1106
- set$3(rpcId, mockRpc);
1107
- // @ts-ignore
1108
- mockRpc[Symbol.dispose] = () => {
1109
- remove(rpcId);
1110
- };
1111
- // @ts-ignore
1112
- return mockRpc;
1113
- },
1114
- set(rpc) {
1115
- set$3(rpcId, rpc);
1175
+ const MethodNotFound = -32601;
1176
+ const Custom = -32001;
1177
+ const restoreJsonRpcError = error => {
1178
+ const currentStack = getCurrentStack();
1179
+ if (error && error instanceof Error) {
1180
+ if (typeof error.stack === 'string') {
1181
+ error.stack = error.stack + NewLine + currentStack;
1116
1182
  }
1117
- };
1183
+ return error;
1184
+ }
1185
+ if (error && error.code && error.code === MethodNotFound) {
1186
+ const restoredError = new JsonRpcError(error.message);
1187
+ const parentStack = getParentStack(error);
1188
+ restoredError.stack = parentStack + NewLine + currentStack;
1189
+ return restoredError;
1190
+ }
1191
+ if (error && error.message) {
1192
+ const restoredError = constructError(error.message, error.type, error.name);
1193
+ if (error.data) {
1194
+ if (error.data.stack && error.data.type && error.message) {
1195
+ restoredError.stack = error.data.type + ': ' + error.message + NewLine + error.data.stack + NewLine + currentStack;
1196
+ } else if (error.data.stack) {
1197
+ restoredError.stack = error.data.stack;
1198
+ }
1199
+ if (error.data.codeFrame) {
1200
+ // @ts-ignore
1201
+ restoredError.codeFrame = error.data.codeFrame;
1202
+ }
1203
+ if (error.data.code) {
1204
+ // @ts-ignore
1205
+ restoredError.code = error.data.code;
1206
+ }
1207
+ if (error.data.type) {
1208
+ // @ts-ignore
1209
+ restoredError.name = error.data.type;
1210
+ }
1211
+ } else {
1212
+ if (error.stack) {
1213
+ const lowerStack = restoredError.stack || '';
1214
+ // @ts-ignore
1215
+ const indexNewLine = getNewLineIndex(lowerStack);
1216
+ const parentStack = getParentStack(error);
1217
+ // @ts-ignore
1218
+ restoredError.stack = parentStack + lowerStack.slice(indexNewLine);
1219
+ }
1220
+ if (error.codeFrame) {
1221
+ // @ts-ignore
1222
+ restoredError.codeFrame = error.codeFrame;
1223
+ }
1224
+ }
1225
+ return restoredError;
1226
+ }
1227
+ if (typeof error === 'string') {
1228
+ return new Error(`JsonRpc Error: ${error}`);
1229
+ }
1230
+ return new Error(`JsonRpc Error: ${error}`);
1118
1231
  };
1119
-
1120
- const {
1121
- set: set$2
1122
- } = create$2(6010);
1123
-
1124
- const Button$2 = 'button';
1125
- const None$1 = 'none';
1126
- const Tab$1 = 'tab';
1127
- const ToolBar = 'toolbar';
1128
-
1129
- const Div = 4;
1130
- const Text = 12;
1131
- const Reference = 100;
1132
-
1133
- const Button$1 = 'event.button';
1134
- const ClientX = 'event.clientX';
1135
- const ClientY = 'event.clientY';
1136
-
1137
- const Enter = 3;
1138
- const Space = 9;
1139
- const PageUp = 10;
1140
- const PageDown = 11;
1141
- const End = 255;
1142
- const Home = 12;
1143
- const UpArrow = 14;
1144
- const DownArrow = 16;
1145
-
1146
- const ActivityBar$3 = 1;
1147
- const Settings$1 = 12;
1148
- const ActivityBarAdditionalViews = 17;
1149
-
1150
- const Separator = 1;
1151
- const None = 0;
1152
- const Checked = 2;
1153
- const Unchecked = 3;
1154
-
1155
- const LeftClick = 0;
1156
-
1157
- const Web = 1;
1158
-
1159
- const RendererWorker = 1;
1160
-
1161
- const Left = 1;
1162
- const Right = 2;
1163
-
1164
- const SetCss = 'Viewlet.setCss';
1165
- const SetDom2 = 'Viewlet.setDom2';
1166
- const SetFocusContext = 'Viewlet.setFocusContext';
1167
- const SetPatches = 'Viewlet.setPatches';
1168
-
1169
- const FocusActivityBar = 5;
1170
- const FocusExplorer = 13;
1171
-
1172
- const {
1173
- invoke,
1174
- invokeAndTransfer,
1175
- set: set$1
1176
- } = create$2(RendererWorker);
1177
- const showContextMenu2 = async (uid, menuId, x, y, args) => {
1178
- number(uid);
1179
- number(menuId);
1180
- number(x);
1181
- number(y);
1182
- await invoke('ContextMenu.show2', uid, menuId, x, y, args);
1232
+ const unwrapJsonRpcResult = responseMessage => {
1233
+ if ('error' in responseMessage) {
1234
+ const restoredError = restoreJsonRpcError(responseMessage.error);
1235
+ throw restoredError;
1236
+ }
1237
+ if ('result' in responseMessage) {
1238
+ return responseMessage.result;
1239
+ }
1240
+ throw new JsonRpcError('unexpected response message');
1241
+ };
1242
+ const warn = (...args) => {
1243
+ console.warn(...args);
1183
1244
  };
1184
- const sendMessagePortToAuthWorker = async (port, rpcId) => {
1185
- const command = 'HandleMessagePort.handleMessagePort';
1186
- await invokeAndTransfer('SendMessagePortToExtensionHostWorker.sendMessagePortToAuthWorker', port, command, rpcId);
1245
+ const resolve = (id, response) => {
1246
+ const fn = get$1(id);
1247
+ if (!fn) {
1248
+ console.log(response);
1249
+ warn(`callback ${id} may already be disposed`);
1250
+ return;
1251
+ }
1252
+ fn(response);
1253
+ remove$1(id);
1187
1254
  };
1188
-
1189
- const toCommandId = key => {
1190
- const dotIndex = key.indexOf('.');
1191
- return key.slice(dotIndex + 1);
1255
+ const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
1256
+ const getErrorType = prettyError => {
1257
+ if (prettyError && prettyError.type) {
1258
+ return prettyError.type;
1259
+ }
1260
+ if (prettyError && prettyError.constructor && prettyError.constructor.name) {
1261
+ return prettyError.constructor.name;
1262
+ }
1263
+ return undefined;
1192
1264
  };
1193
- const create$1 = () => {
1194
- const states = Object.create(null);
1195
- const commandMapRef = {};
1265
+ const isAlreadyStack = line => {
1266
+ return line.trim().startsWith('at ');
1267
+ };
1268
+ const getStack = prettyError => {
1269
+ const stackString = prettyError.stack || '';
1270
+ const newLineIndex = stackString.indexOf('\n');
1271
+ if (newLineIndex !== -1 && !isAlreadyStack(stackString.slice(0, newLineIndex))) {
1272
+ return stackString.slice(newLineIndex + 1);
1273
+ }
1274
+ return stackString;
1275
+ };
1276
+ const getErrorProperty = (error, prettyError) => {
1277
+ if (error && error.code === E_COMMAND_NOT_FOUND) {
1278
+ return {
1279
+ code: MethodNotFound,
1280
+ data: error.stack,
1281
+ message: error.message
1282
+ };
1283
+ }
1196
1284
  return {
1197
- clear() {
1198
- for (const key of Object.keys(states)) {
1199
- delete states[key];
1200
- }
1201
- },
1202
- diff(uid, modules, numbers) {
1203
- const {
1204
- newState,
1205
- oldState
1206
- } = states[uid];
1207
- const diffResult = [];
1208
- for (let i = 0; i < modules.length; i++) {
1209
- const fn = modules[i];
1210
- if (!fn(oldState, newState)) {
1211
- diffResult.push(numbers[i]);
1212
- }
1213
- }
1214
- return diffResult;
1215
- },
1216
- dispose(uid) {
1217
- delete states[uid];
1218
- },
1219
- get(uid) {
1220
- return states[uid];
1221
- },
1222
- getCommandIds() {
1223
- const keys = Object.keys(commandMapRef);
1224
- const ids = keys.map(toCommandId);
1225
- return ids;
1226
- },
1227
- getKeys() {
1228
- return Object.keys(states).map(key => {
1229
- return Number.parseFloat(key);
1230
- });
1231
- },
1232
- registerCommands(commandMap) {
1233
- Object.assign(commandMapRef, commandMap);
1234
- },
1235
- set(uid, oldState, newState) {
1236
- states[uid] = {
1237
- newState,
1238
- oldState
1239
- };
1240
- },
1241
- wrapCommand(fn) {
1242
- const wrapped = async (uid, ...args) => {
1243
- const {
1244
- newState,
1245
- oldState
1246
- } = states[uid];
1247
- const newerState = await fn(newState, ...args);
1248
- if (oldState === newerState || newState === newerState) {
1249
- return;
1250
- }
1251
- const latestOld = states[uid];
1252
- const latestNew = {
1253
- ...latestOld.newState,
1254
- ...newerState
1255
- };
1256
- states[uid] = {
1257
- newState: latestNew,
1258
- oldState: latestOld.oldState
1259
- };
1260
- };
1261
- return wrapped;
1262
- },
1263
- wrapGetter(fn) {
1264
- const wrapped = (uid, ...args) => {
1265
- const {
1266
- newState
1267
- } = states[uid];
1268
- return fn(newState, ...args);
1269
- };
1270
- return wrapped;
1285
+ code: Custom,
1286
+ data: {
1287
+ code: prettyError.code,
1288
+ codeFrame: prettyError.codeFrame,
1289
+ name: prettyError.name,
1290
+ stack: getStack(prettyError),
1291
+ type: getErrorType(prettyError)
1271
1292
  },
1272
- wrapLoadContent(fn) {
1273
- const wrapped = async (uid, ...args) => {
1274
- const {
1275
- newState,
1276
- oldState
1277
- } = states[uid];
1278
- const result = await fn(newState, ...args);
1279
- const {
1280
- error,
1281
- state
1282
- } = result;
1283
- if (oldState === state || newState === state) {
1284
- return {
1285
- error
1286
- };
1287
- }
1288
- const latestOld = states[uid];
1289
- const latestNew = {
1290
- ...latestOld.newState,
1291
- ...state
1292
- };
1293
- states[uid] = {
1294
- newState: latestNew,
1295
- oldState: latestOld.oldState
1296
- };
1297
- return {
1298
- error
1299
- };
1300
- };
1301
- return wrapped;
1302
- }
1293
+ message: prettyError.message
1303
1294
  };
1304
1295
  };
1305
- const terminate = () => {
1306
- globalThis.close();
1307
- };
1308
-
1309
- const {
1310
- diff,
1311
- get,
1312
- getCommandIds,
1313
- registerCommands,
1314
- set,
1315
- wrapCommand,
1316
- wrapGetter
1317
- } = create$1();
1318
-
1319
- // TODO parentUid might ot be needed
1320
- const create = (id, uri, x, y, width, height, args, parentUid, platform = 0) => {
1321
- const state = {
1322
- accountEnabled: true,
1323
- activityBarItems: [],
1324
- currentViewletId: '',
1325
- filteredItems: [],
1326
- focus: 0,
1327
- focused: false,
1328
- focusedIndex: -1,
1329
- height,
1330
- initial: true,
1331
- itemHeight: 48,
1332
- numberOfVisibleItems: 0,
1333
- platform,
1334
- scrollBarHeight: 0,
1335
- selectedIndex: -1,
1336
- sideBarLocation: 0,
1337
- sideBarVisible: false,
1338
- uid: id,
1339
- updateProgress: 0,
1340
- updateState: '',
1341
- userLoginState: 'logged out',
1342
- width,
1343
- x,
1344
- y
1296
+ const create$1$1 = (id, error) => {
1297
+ return {
1298
+ error,
1299
+ id,
1300
+ jsonrpc: Two$1
1345
1301
  };
1346
- set(id, state, state);
1347
- return state;
1348
- };
1349
-
1350
- const isEqual$2 = (oldState, newState) => {
1351
- return oldState.itemHeight === newState.itemHeight;
1352
1302
  };
1353
-
1354
- const isEqual$1 = (oldState, newState) => {
1355
- return oldState.focused === newState.focused && oldState.focus === newState.focus;
1303
+ const getErrorResponse = (id, error, preparePrettyError, logError) => {
1304
+ const prettyError = preparePrettyError(error);
1305
+ logError(error, prettyError);
1306
+ const errorProperty = getErrorProperty(error, prettyError);
1307
+ return create$1$1(id, errorProperty);
1356
1308
  };
1357
-
1358
- const isEqual = (oldState, newState) => {
1359
- return oldState.activityBarItems === newState.activityBarItems && oldState.filteredItems === newState.filteredItems && oldState.focusedIndex === newState.focusedIndex && oldState.sideBarLocation === newState.sideBarLocation && oldState.sideBarVisible === newState.sideBarVisible && oldState.updateProgress === newState.updateProgress && oldState.updateState === newState.updateState;
1309
+ const create$8 = (message, result) => {
1310
+ return {
1311
+ id: message.id,
1312
+ jsonrpc: Two$1,
1313
+ result: result ?? null
1314
+ };
1360
1315
  };
1361
-
1362
- const RenderItems = 4;
1363
- const RenderFocus = 6;
1364
- const RenderFocusContext = 7;
1365
- const RenderCss = 11;
1366
- const RenderIncremental = 12;
1367
-
1368
- const modules = [isEqual, isEqual$1, isEqual$1, isEqual$2];
1369
- const numbers = [RenderIncremental, RenderFocus, RenderFocusContext, RenderCss];
1370
-
1371
- const diff2 = uid => {
1372
- return diff(uid, modules, numbers);
1316
+ const getSuccessResponse = (message, result) => {
1317
+ const resultProperty = result ?? null;
1318
+ return create$8(message, resultProperty);
1373
1319
  };
1374
-
1375
- const List = 1;
1376
-
1377
- const focus = state => {
1378
- const {
1379
- focus
1380
- } = state;
1381
- if (focus) {
1382
- return state;
1383
- }
1320
+ const getErrorResponseSimple = (id, error) => {
1384
1321
  return {
1385
- ...state,
1386
- focus: List
1322
+ error: {
1323
+ code: Custom,
1324
+ data: error,
1325
+ // @ts-ignore
1326
+ message: error.message
1327
+ },
1328
+ id,
1329
+ jsonrpc: Two$1
1387
1330
  };
1388
1331
  };
1389
-
1390
- const focusIndex = (state, index) => {
1391
- return {
1392
- ...state,
1393
- focused: true,
1394
- focusedIndex: index
1395
- };
1332
+ const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
1333
+ try {
1334
+ const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
1335
+ return getSuccessResponse(message, result);
1336
+ } catch (error) {
1337
+ if (ipc.canUseSimpleErrorResponse) {
1338
+ return getErrorResponseSimple(message.id, error);
1339
+ }
1340
+ return getErrorResponse(message.id, error, preparePrettyError, logError);
1341
+ }
1396
1342
  };
1397
-
1398
- const focusFirst = state => {
1399
- return focusIndex(state, -1);
1343
+ const defaultPreparePrettyError = error => {
1344
+ return error;
1400
1345
  };
1401
-
1402
- const focusLast = state => {
1403
- return focusIndex(state, -1);
1346
+ const defaultLogError = () => {
1347
+ // ignore
1404
1348
  };
1405
-
1406
- const focusNext = state => {
1407
- return focusIndex(state, -1);
1349
+ const defaultRequiresSocket = () => {
1350
+ return false;
1408
1351
  };
1352
+ const defaultResolve = resolve;
1409
1353
 
1410
- const focusNone = state => {
1411
- const {
1412
- focusedIndex
1413
- } = state;
1414
- if (focusedIndex === -1) {
1415
- return state;
1354
+ // TODO maybe remove this in v6 or v7, only accept options object to simplify the code
1355
+ const normalizeParams = args => {
1356
+ if (args.length === 1) {
1357
+ const options = args[0];
1358
+ return {
1359
+ execute: options.execute,
1360
+ ipc: options.ipc,
1361
+ logError: options.logError || defaultLogError,
1362
+ message: options.message,
1363
+ preparePrettyError: options.preparePrettyError || defaultPreparePrettyError,
1364
+ requiresSocket: options.requiresSocket || defaultRequiresSocket,
1365
+ resolve: options.resolve || defaultResolve
1366
+ };
1416
1367
  }
1417
- return focusIndex(state, -1);
1418
- };
1419
-
1420
- const getKeyBindings = () => {
1421
- return [{
1422
- command: 'ActivityBar.focusNext',
1423
- key: DownArrow,
1424
- when: FocusActivityBar
1425
- }, {
1426
- command: 'ActivityBar.focusPrevious',
1427
- key: UpArrow,
1428
- when: FocusActivityBar
1429
- }, {
1430
- command: 'ActivityBar.focusFirst',
1431
- key: Home,
1432
- when: FocusActivityBar
1433
- }, {
1434
- command: 'ActivityBar.focusFirst',
1435
- key: PageUp,
1436
- when: FocusActivityBar
1437
- }, {
1438
- command: 'ActivityBar.focusLast',
1439
- key: PageDown,
1440
- when: FocusActivityBar
1441
- }, {
1442
- command: 'ActivityBar.focusLast',
1443
- key: End,
1444
- when: FocusActivityBar
1445
- }, {
1446
- command: 'ActivityBar.selectCurrent',
1447
- key: Space,
1448
- when: FocusActivityBar
1449
- }, {
1450
- command: 'ActivityBar.selectCurrent',
1451
- key: Enter,
1452
- when: FocusActivityBar
1453
- }];
1454
- };
1455
-
1456
- const getMenuEntriesAccountLoggedIn = state => {
1457
- const {
1458
- userLoginState
1459
- } = state;
1460
- const signOutLabel = userLoginState === 'logging out' ? 'Signing Out...' : 'Sign Out';
1461
- return [{
1462
- command: 'ActivityBar.handleClickSignOut',
1463
- flags: None,
1464
- id: 'signOut',
1465
- label: signOutLabel
1466
- }];
1467
- };
1468
- const getMenuEntriesAccountLoggedOut = state => {
1469
- const {
1470
- userLoginState
1471
- } = state;
1472
- const signInLabel = userLoginState === 'logging in' ? 'Signing In...' : 'Sign In';
1473
- return [{
1474
- command: 'ActivityBar.handleClickSignIn',
1475
- flags: None,
1476
- id: 'signIn',
1477
- label: signInLabel
1478
- }];
1368
+ return {
1369
+ execute: args[2],
1370
+ ipc: args[0],
1371
+ logError: args[5],
1372
+ message: args[1],
1373
+ preparePrettyError: args[4],
1374
+ requiresSocket: args[6],
1375
+ resolve: args[3]
1376
+ };
1479
1377
  };
1480
- const getMenuEntriesAccount = state => {
1481
- // TODO maybe query it now from layout?
1378
+ const handleJsonRpcMessage = async (...args) => {
1379
+ const options = normalizeParams(args);
1482
1380
  const {
1483
- userLoginState
1484
- } = state;
1485
- if (userLoginState === 'logged in' || userLoginState === 'logging out') {
1486
- return getMenuEntriesAccountLoggedIn(state);
1381
+ execute,
1382
+ ipc,
1383
+ logError,
1384
+ message,
1385
+ preparePrettyError,
1386
+ requiresSocket,
1387
+ resolve
1388
+ } = options;
1389
+ if ('id' in message) {
1390
+ if ('method' in message) {
1391
+ const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
1392
+ try {
1393
+ ipc.send(response);
1394
+ } catch (error) {
1395
+ const errorResponse = getErrorResponse(message.id, error, preparePrettyError, logError);
1396
+ ipc.send(errorResponse);
1397
+ }
1398
+ return;
1399
+ }
1400
+ resolve(message.id, message);
1401
+ return;
1487
1402
  }
1488
- return getMenuEntriesAccountLoggedOut(state);
1403
+ if ('method' in message) {
1404
+ await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
1405
+ return;
1406
+ }
1407
+ throw new JsonRpcError('unexpected message');
1489
1408
  };
1490
1409
 
1491
- const Tab = 1;
1492
- const Button = 1 << 1;
1493
- const Progress = 1 << 2;
1494
- const Enabled = 1 << 3;
1495
- const Selected = 1 << 4;
1496
- const Focused = 1 << 5;
1497
- const MarginTop = 1 << 6;
1410
+ const Two = '2.0';
1498
1411
 
1499
- const emptyObject = {};
1500
- const RE_PLACEHOLDER = /\{(PH\d+)\}/g;
1501
- const i18nString = (key, placeholders = emptyObject) => {
1502
- if (placeholders === emptyObject) {
1503
- return key;
1504
- }
1505
- const replacer = (match, rest) => {
1506
- return placeholders[rest];
1412
+ const create$7 = (method, params) => {
1413
+ return {
1414
+ jsonrpc: Two,
1415
+ method,
1416
+ params
1507
1417
  };
1508
- return key.replaceAll(RE_PLACEHOLDER, replacer);
1509
1418
  };
1510
1419
 
1511
- const Account$1 = 'Account';
1512
- const Explorer$1 = 'Explorer';
1513
- const Search$2 = 'Search';
1514
- const SourceControl$2 = 'Source Control';
1515
- const RunAndDebug$1 = 'Run and Debug';
1516
- const Extensions$2 = 'Extensions';
1517
- const Settings = 'Settings';
1518
- const AdditionalViews = 'Additional Views';
1519
- const ActivityBar$2 = 'Activity Bar';
1520
- const MoveSideBarLeft = 'Move Side Bar Left';
1521
- const MoveSideBarRight = 'Move Side Bar Right';
1522
- const HideActivityBar = 'Hide Activity Bar';
1523
- const CheckForUpdates = 'Check For Updates';
1524
- const ColorTheme = 'Color Theme';
1525
- const CommandPalette = 'Command Palette';
1526
- const KeyboardShortcuts = 'Keyboard Shortcuts';
1527
-
1528
- const account = () => {
1529
- return i18nString(Account$1);
1530
- };
1531
- const explorer = () => {
1532
- return i18nString(Explorer$1);
1533
- };
1534
- const search = () => {
1535
- return i18nString(Search$2);
1536
- };
1537
- const sourceControl = () => {
1538
- return i18nString(SourceControl$2);
1539
- };
1540
- const runAndDebug = () => {
1541
- return i18nString(RunAndDebug$1);
1542
- };
1543
- const extensions = () => {
1544
- return i18nString(Extensions$2);
1545
- };
1546
- const settings = () => {
1547
- return i18nString(Settings);
1420
+ const create$6 = (id, method, params) => {
1421
+ const message = {
1422
+ id,
1423
+ jsonrpc: Two,
1424
+ method,
1425
+ params
1426
+ };
1427
+ return message;
1548
1428
  };
1549
- const additionalViews = () => {
1550
- return i18nString(AdditionalViews);
1429
+
1430
+ let id = 0;
1431
+ const create$5 = () => {
1432
+ return ++id;
1551
1433
  };
1552
- const activityBar = () => {
1553
- return i18nString(ActivityBar$2);
1434
+
1435
+ const registerPromise = map => {
1436
+ const id = create$5();
1437
+ const {
1438
+ promise,
1439
+ resolve
1440
+ } = Promise.withResolvers();
1441
+ map[id] = resolve;
1442
+ return {
1443
+ id,
1444
+ promise
1445
+ };
1554
1446
  };
1555
- const moveSideBarRight = () => {
1556
- return i18nString(MoveSideBarRight);
1447
+
1448
+ const invokeHelper = async (callbacks, ipc, method, params, useSendAndTransfer) => {
1449
+ const {
1450
+ id,
1451
+ promise
1452
+ } = registerPromise(callbacks);
1453
+ const message = create$6(id, method, params);
1454
+ if (useSendAndTransfer && ipc.sendAndTransfer) {
1455
+ ipc.sendAndTransfer(message);
1456
+ } else {
1457
+ ipc.send(message);
1458
+ }
1459
+ const responseMessage = await promise;
1460
+ return unwrapJsonRpcResult(responseMessage);
1557
1461
  };
1558
- const moveSideBarLeft = () => {
1559
- return i18nString(MoveSideBarLeft);
1462
+ const createRpc = ipc => {
1463
+ const callbacks = Object.create(null);
1464
+ ipc._resolve = (id, response) => {
1465
+ const fn = callbacks[id];
1466
+ if (!fn) {
1467
+ console.warn(`callback ${id} may already be disposed`);
1468
+ return;
1469
+ }
1470
+ fn(response);
1471
+ delete callbacks[id];
1472
+ };
1473
+ const rpc = {
1474
+ async dispose() {
1475
+ await ipc?.dispose();
1476
+ },
1477
+ invoke(method, ...params) {
1478
+ return invokeHelper(callbacks, ipc, method, params, false);
1479
+ },
1480
+ invokeAndTransfer(method, ...params) {
1481
+ return invokeHelper(callbacks, ipc, method, params, true);
1482
+ },
1483
+ // @ts-ignore
1484
+ ipc,
1485
+ /**
1486
+ * @deprecated
1487
+ */
1488
+ send(method, ...params) {
1489
+ const message = create$7(method, params);
1490
+ ipc.send(message);
1491
+ }
1492
+ };
1493
+ return rpc;
1560
1494
  };
1561
- const hideActivityBar = () => {
1562
- return i18nString(HideActivityBar);
1495
+
1496
+ const requiresSocket = () => {
1497
+ return false;
1563
1498
  };
1564
- const checkForUpdates = () => {
1565
- return i18nString(CheckForUpdates);
1499
+ const preparePrettyError = error => {
1500
+ return error;
1566
1501
  };
1567
- const commandPalette = () => {
1568
- return i18nString(CommandPalette);
1502
+ const logError = () => {
1503
+ // handled by renderer worker
1569
1504
  };
1570
- const keyboardShortcuts = () => {
1571
- return i18nString(KeyboardShortcuts);
1505
+ const handleMessage = event => {
1506
+ const actualRequiresSocket = event?.target?.requiresSocket || requiresSocket;
1507
+ const actualExecute = event?.target?.execute || execute;
1508
+ return handleJsonRpcMessage(event.target, event.data, actualExecute, event.target._resolve, preparePrettyError, logError, actualRequiresSocket);
1572
1509
  };
1573
- const colorTheme = () => {
1574
- return i18nString(ColorTheme);
1510
+
1511
+ const handleIpc = ipc => {
1512
+ if ('addEventListener' in ipc) {
1513
+ ipc.addEventListener('message', handleMessage);
1514
+ } else if ('on' in ipc) {
1515
+ // deprecated
1516
+ ipc.on('message', handleMessage);
1517
+ }
1575
1518
  };
1576
1519
 
1577
- const menuEntryMoveSideBar = sideBarLocation => {
1578
- switch (sideBarLocation) {
1579
- case Left:
1580
- return {
1581
- command: 'Layout.moveSideBarRight',
1582
- flags: None,
1583
- id: 'moveSideBarRight',
1584
- label: moveSideBarRight()
1585
- };
1586
- case Right:
1587
- return {
1588
- command: 'Layout.moveSideBarLeft',
1589
- flags: None,
1590
- id: 'moveSideBarLeft',
1591
- label: moveSideBarLeft()
1592
- };
1593
- default:
1594
- throw new Error('unexpected side bar location');
1520
+ const listen$1 = async (module, options) => {
1521
+ const rawIpc = await module.listen(options);
1522
+ if (module.signal) {
1523
+ module.signal(rawIpc);
1595
1524
  }
1525
+ const ipc = module.wrap(rawIpc);
1526
+ return ipc;
1596
1527
  };
1597
1528
 
1598
- const menuEntrySeparator = {
1599
- command: '',
1600
- flags: Separator,
1601
- id: 'separator',
1602
- label: ''
1529
+ const create$4 = async ({
1530
+ commandMap,
1531
+ isMessagePortOpen = true,
1532
+ messagePort
1533
+ }) => {
1534
+ // TODO create a commandMap per rpc instance
1535
+ register(commandMap);
1536
+ const rawIpc = await IpcParentWithMessagePort$1.create({
1537
+ isMessagePortOpen,
1538
+ messagePort
1539
+ });
1540
+ const ipc = IpcParentWithMessagePort$1.wrap(rawIpc);
1541
+ handleIpc(ipc);
1542
+ const rpc = createRpc(ipc);
1543
+ messagePort.start();
1544
+ return rpc;
1603
1545
  };
1604
1546
 
1605
- const toContextMenuItem$1 = activityBarItem => {
1606
- const isEnabled = activityBarItem.flags & Enabled;
1547
+ const create$3 = async ({
1548
+ commandMap,
1549
+ isMessagePortOpen,
1550
+ send
1551
+ }) => {
1552
+ const {
1553
+ port1,
1554
+ port2
1555
+ } = new MessageChannel();
1556
+ await send(port1);
1557
+ return create$4({
1558
+ commandMap,
1559
+ isMessagePortOpen,
1560
+ messagePort: port2
1561
+ });
1562
+ };
1563
+
1564
+ const createSharedLazyRpc = factory => {
1565
+ let rpcPromise;
1566
+ const getOrCreate = () => {
1567
+ if (!rpcPromise) {
1568
+ rpcPromise = factory();
1569
+ }
1570
+ return rpcPromise;
1571
+ };
1607
1572
  return {
1608
- args: [activityBarItem.id],
1609
- command: 'ActivityBar.toggleActivityBarItem',
1610
- flags: isEnabled ? Checked : Unchecked,
1611
- id: `toggle-${activityBarItem.id}`,
1612
- label: activityBarItem.id
1573
+ async dispose() {
1574
+ const rpc = await getOrCreate();
1575
+ await rpc.dispose();
1576
+ },
1577
+ async invoke(method, ...params) {
1578
+ const rpc = await getOrCreate();
1579
+ return rpc.invoke(method, ...params);
1580
+ },
1581
+ async invokeAndTransfer(method, ...params) {
1582
+ const rpc = await getOrCreate();
1583
+ return rpc.invokeAndTransfer(method, ...params);
1584
+ },
1585
+ async send(method, ...params) {
1586
+ const rpc = await getOrCreate();
1587
+ rpc.send(method, ...params);
1588
+ }
1613
1589
  };
1614
1590
  };
1615
1591
 
1616
- const getMenuEntriesActivityBar = state => {
1617
- const {
1618
- activityBarItems,
1619
- sideBarLocation
1620
- } = state;
1621
- const topItems = activityBarItems.filter(item => !(item.flags & Button));
1622
- const bottomItems = activityBarItems.filter(item => item.flags & Button);
1623
- const entries = [...topItems.map(toContextMenuItem$1)];
1624
- if (bottomItems.length > 0) {
1625
- entries.push(menuEntrySeparator, ...bottomItems.map(toContextMenuItem$1));
1626
- }
1627
- return [...entries, menuEntrySeparator, menuEntryMoveSideBar(sideBarLocation), {
1628
- command: 'Layout.hideActivityBar',
1629
- flags: None,
1630
- id: 'hideActivityBar',
1631
- label: hideActivityBar()
1632
- }];
1592
+ const create$2 = async ({
1593
+ commandMap,
1594
+ isMessagePortOpen,
1595
+ send
1596
+ }) => {
1597
+ return createSharedLazyRpc(() => {
1598
+ return create$3({
1599
+ commandMap,
1600
+ isMessagePortOpen,
1601
+ send
1602
+ });
1603
+ });
1633
1604
  };
1634
1605
 
1635
- const getNumberOfVisibleItems = state => {
1636
- const {
1637
- height,
1638
- itemHeight
1639
- } = state;
1640
- const numberOfVisibleItemsTop = Math.floor(height / itemHeight);
1641
- return numberOfVisibleItemsTop;
1606
+ const create$1 = async ({
1607
+ commandMap
1608
+ }) => {
1609
+ // TODO create a commandMap per rpc instance
1610
+ register(commandMap);
1611
+ const ipc = await listen$1(IpcChildWithModuleWorkerAndMessagePort$1);
1612
+ handleIpc(ipc);
1613
+ const rpc = createRpc(ipc);
1614
+ return rpc;
1642
1615
  };
1643
- const getHiddenItems = state => {
1644
- const numberOfVisibleItems = getNumberOfVisibleItems(state);
1645
- const items = state.activityBarItems;
1646
- if (numberOfVisibleItems >= items.length) {
1647
- return [];
1648
- }
1649
- return state.activityBarItems.slice(numberOfVisibleItems - 2, -1);
1616
+
1617
+ const createMockRpc = ({
1618
+ commandMap
1619
+ }) => {
1620
+ const invocations = [];
1621
+ const invoke = (method, ...params) => {
1622
+ invocations.push([method, ...params]);
1623
+ const command = commandMap[method];
1624
+ if (!command) {
1625
+ throw new Error(`command ${method} not found`);
1626
+ }
1627
+ return command(...params);
1628
+ };
1629
+ const mockRpc = {
1630
+ invocations,
1631
+ invoke,
1632
+ invokeAndTransfer: invoke
1633
+ };
1634
+ return mockRpc;
1635
+ };
1636
+
1637
+ const rpcs = Object.create(null);
1638
+ const set$3 = (id, rpc) => {
1639
+ rpcs[id] = rpc;
1640
+ };
1641
+ const get = id => {
1642
+ return rpcs[id];
1643
+ };
1644
+ const remove = id => {
1645
+ delete rpcs[id];
1646
+ };
1647
+
1648
+ /* eslint-disable @typescript-eslint/explicit-function-return-type */
1649
+ const create = rpcId => {
1650
+ return {
1651
+ async dispose() {
1652
+ const rpc = get(rpcId);
1653
+ await rpc.dispose();
1654
+ },
1655
+ // @ts-ignore
1656
+ invoke(method, ...params) {
1657
+ const rpc = get(rpcId);
1658
+ // @ts-ignore
1659
+ return rpc.invoke(method, ...params);
1660
+ },
1661
+ // @ts-ignore
1662
+ invokeAndTransfer(method, ...params) {
1663
+ const rpc = get(rpcId);
1664
+ // @ts-ignore
1665
+ return rpc.invokeAndTransfer(method, ...params);
1666
+ },
1667
+ registerMockRpc(commandMap) {
1668
+ const mockRpc = createMockRpc({
1669
+ commandMap
1670
+ });
1671
+ set$3(rpcId, mockRpc);
1672
+ // @ts-ignore
1673
+ mockRpc[Symbol.dispose] = () => {
1674
+ remove(rpcId);
1675
+ };
1676
+ // @ts-ignore
1677
+ return mockRpc;
1678
+ },
1679
+ set(rpc) {
1680
+ set$3(rpcId, rpc);
1681
+ }
1682
+ };
1650
1683
  };
1651
1684
 
1652
- const toContextMenuItem = activityBarItem => {
1653
- return {
1654
- command: '-1',
1655
- // TODO
1656
- flags: None,
1657
- id: '8000',
1658
- // TODO
1659
- label: activityBarItem.id
1660
- };
1685
+ const {
1686
+ set: set$2
1687
+ } = create(6010);
1688
+
1689
+ const {
1690
+ invoke: invoke$1,
1691
+ set: set$1
1692
+ } = create(ExtensionManagementWorker);
1693
+
1694
+ const {
1695
+ invoke,
1696
+ invokeAndTransfer,
1697
+ set
1698
+ } = create(RendererWorker);
1699
+ const showContextMenu2 = async (uid, menuId, x, y, args) => {
1700
+ number(uid);
1701
+ number(menuId);
1702
+ number(x);
1703
+ number(y);
1704
+ await invoke('ContextMenu.show2', uid, menuId, x, y, args);
1661
1705
  };
1662
- const getMenuEntriesAdditionalViews = state => {
1663
- const hiddenActivityBarItems = getHiddenItems(state);
1664
- return hiddenActivityBarItems.map(toContextMenuItem);
1706
+ const sendMessagePortToAuthWorker = async (port, rpcId) => {
1707
+ const command = 'HandleMessagePort.handleMessagePort';
1708
+ await invokeAndTransfer('SendMessagePortToExtensionHostWorker.sendMessagePortToAuthWorker', port, command, rpcId);
1665
1709
  };
1666
-
1667
- const keyBindingsUri = 'app://keybindings';
1668
- const getMenuEntriesSettings = state => {
1669
- const {
1670
- platform
1671
- } = state;
1672
- const items = [{
1673
- command: 'QuickPick.showEverything',
1674
- flags: None,
1675
- id: 'commandPalette',
1676
- label: commandPalette()
1677
- }, menuEntrySeparator, {
1678
- command: 'Preferences.openSettingsJson',
1679
- flags: None,
1680
- id: 'settings',
1681
- label: settings()
1682
- }, {
1683
- args: [keyBindingsUri],
1684
- command: 'Main.openUri',
1685
- flags: None,
1686
- id: 'keyboardShortcuts',
1687
- label: keyboardShortcuts()
1688
- }, {
1689
- command: 'QuickPick.showColorTheme',
1690
- flags: None,
1691
- id: 'colorTheme',
1692
- label: colorTheme()
1693
- }];
1694
- if (platform !== Web) {
1695
- items.push(menuEntrySeparator, {
1696
- command: 'AutoUpdater.checkForUpdates',
1697
- flags: None,
1698
- id: 'checkForUpdates',
1699
- label: checkForUpdates()
1700
- });
1701
- }
1702
- return items;
1710
+ const sendMessagePortToExtensionManagementWorker = async (port, rpcId) => {
1711
+ const command = 'Extensions.handleMessagePort';
1712
+ await invokeAndTransfer('SendMessagePortToExtensionHostWorker.sendMessagePortToExtensionManagementWorker', port, command, rpcId);
1703
1713
  };
1704
1714
 
1705
1715
  const show2 = async (uid, menuId, x, y, args) => {
@@ -1849,12 +1859,13 @@ const SourceControl$1 = 'SourceControl';
1849
1859
  const Ellipsis = 'Ellipsis';
1850
1860
 
1851
1861
  const getFilteredActivityBarItems = (items, height, itemHeight) => {
1862
+ const enabledItems = items.filter(item => item.flags & Enabled);
1852
1863
  const numberOfVisibleItems = getNumberOfVisibleItems({
1853
1864
  height,
1854
1865
  itemHeight
1855
1866
  });
1856
- if (numberOfVisibleItems >= items.length) {
1857
- return items;
1867
+ if (numberOfVisibleItems >= enabledItems.length) {
1868
+ return enabledItems;
1858
1869
  }
1859
1870
  const showMoreItem = {
1860
1871
  flags: Button,
@@ -1863,7 +1874,7 @@ const getFilteredActivityBarItems = (items, height, itemHeight) => {
1863
1874
  keyShortcuts: '',
1864
1875
  title: additionalViews()
1865
1876
  };
1866
- return [...items.slice(0, numberOfVisibleItems - 2), showMoreItem, items.at(-1)];
1877
+ return [...enabledItems.slice(0, numberOfVisibleItems - 2), showMoreItem, enabledItems.at(-1)];
1867
1878
  };
1868
1879
 
1869
1880
  const setFlag = (item, flag, enabled) => {
@@ -2001,42 +2012,14 @@ const handleContextMenu = async (state, button, eventX, eventY) => {
2001
2012
  return state;
2002
2013
  };
2003
2014
 
2004
- const handleFocus = state => {
2005
- return {
2006
- ...state,
2007
- focused: true
2008
- };
2009
- };
2010
-
2011
- const handleResize = (state, dimensions) => {
2012
- const {
2013
- activityBarItems,
2014
- itemHeight
2015
- } = state;
2016
- const {
2017
- height,
2018
- width,
2019
- x,
2020
- y
2021
- } = dimensions;
2022
- const filteredItems = getFilteredActivityBarItems(activityBarItems, height, itemHeight);
2023
- return {
2024
- ...state,
2025
- filteredItems,
2026
- height,
2027
- width,
2028
- x,
2029
- y
2030
- };
2031
- };
2015
+ const commandMap$1 = {};
2032
2016
 
2033
- const getAccountEnabled = async defaultValue => {
2034
- try {
2035
- const value = await invoke('Preferences.get', 'activityBar.accountEnabled');
2036
- return typeof value === 'boolean' ? value : defaultValue;
2037
- } catch {
2038
- return defaultValue;
2039
- }
2017
+ const handleExtensionManagementMessagePort = async port => {
2018
+ const rpc = await create$4({
2019
+ commandMap: commandMap$1,
2020
+ messagePort: port
2021
+ });
2022
+ set$1(rpc);
2040
2023
  };
2041
2024
 
2042
2025
  const Explorer = 'Explorer';
@@ -2045,7 +2028,16 @@ const RunAndDebug = 'Run And Debug';
2045
2028
  const Search = 'Search';
2046
2029
  const SourceControl = 'Source Control';
2047
2030
 
2048
- const getActivityBarItems = state => {
2031
+ const toActivityBarItem = view => {
2032
+ return {
2033
+ flags: Tab | Enabled,
2034
+ icon: view.icon || Extensions$1,
2035
+ id: view.id,
2036
+ keyShortcuts: '',
2037
+ title: view.title || view.id
2038
+ };
2039
+ };
2040
+ const getActivityBarItems = (state, contributedViews = []) => {
2049
2041
  const {
2050
2042
  accountEnabled
2051
2043
  } = state;
@@ -2082,7 +2074,7 @@ const getActivityBarItems = state => {
2082
2074
  id: Extensions,
2083
2075
  keyShortcuts: 'Control+Shift+X',
2084
2076
  title: extensions()
2085
- }
2077
+ }, ...contributedViews.map(toActivityBarItem)
2086
2078
  // Bottom
2087
2079
  ];
2088
2080
  if (accountEnabled) {
@@ -2104,6 +2096,70 @@ const getActivityBarItems = state => {
2104
2096
  return items;
2105
2097
  };
2106
2098
 
2099
+ const getContributedViews = async platform => {
2100
+ try {
2101
+ return await invoke$1('Extensions.getViews', '', platform);
2102
+ } catch {
2103
+ return [];
2104
+ }
2105
+ };
2106
+
2107
+ const handleExtensionsChanged = async state => {
2108
+ const {
2109
+ height,
2110
+ itemHeight,
2111
+ selectedIndex
2112
+ } = state;
2113
+ const contributedViews = await getContributedViews(state.platform);
2114
+ const items = getActivityBarItems(state, contributedViews);
2115
+ const itemsWithSelected = markSelected(items, selectedIndex);
2116
+ const filteredItems = getFilteredActivityBarItems(itemsWithSelected, height, itemHeight);
2117
+ const newItems = await updateItemsWithBadgeCount(filteredItems);
2118
+ return {
2119
+ ...state,
2120
+ activityBarItems: itemsWithSelected,
2121
+ filteredItems: newItems
2122
+ };
2123
+ };
2124
+
2125
+ const handleFocus = state => {
2126
+ return {
2127
+ ...state,
2128
+ focused: true
2129
+ };
2130
+ };
2131
+
2132
+ const handleResize = (state, dimensions) => {
2133
+ const {
2134
+ activityBarItems,
2135
+ itemHeight
2136
+ } = state;
2137
+ const {
2138
+ height,
2139
+ width,
2140
+ x,
2141
+ y
2142
+ } = dimensions;
2143
+ const filteredItems = getFilteredActivityBarItems(activityBarItems, height, itemHeight);
2144
+ return {
2145
+ ...state,
2146
+ filteredItems,
2147
+ height,
2148
+ width,
2149
+ x,
2150
+ y
2151
+ };
2152
+ };
2153
+
2154
+ const getAccountEnabled = async defaultValue => {
2155
+ try {
2156
+ const value = await invoke('Preferences.get', 'activityBar.accountEnabled');
2157
+ return typeof value === 'boolean' ? value : defaultValue;
2158
+ } catch {
2159
+ return defaultValue;
2160
+ }
2161
+ };
2162
+
2107
2163
  const getSideBarPosition = async () => {
2108
2164
  try {
2109
2165
  return await invoke('Layout.getSideBarPosition');
@@ -2118,12 +2174,12 @@ const handleSettingsChanged = async state => {
2118
2174
  itemHeight,
2119
2175
  selectedIndex
2120
2176
  } = state;
2121
- const [accountEnabled, sidebarLocation] = await Promise.all([getAccountEnabled(state.accountEnabled), getSideBarPosition()]);
2177
+ const [accountEnabled, contributedViews, sidebarLocation] = await Promise.all([getAccountEnabled(state.accountEnabled), getContributedViews(state.platform), getSideBarPosition()]);
2122
2178
  const newState = {
2123
2179
  ...state,
2124
2180
  accountEnabled
2125
2181
  };
2126
- const items = getActivityBarItems(newState);
2182
+ const items = getActivityBarItems(newState, contributedViews);
2127
2183
  const itemsWithSelected = markSelected(items, selectedIndex);
2128
2184
  const filteredItems = getFilteredActivityBarItems(itemsWithSelected, height, itemHeight);
2129
2185
  const newItems = await updateItemsWithBadgeCount(filteredItems);
@@ -2262,15 +2318,16 @@ const loadContent = async state => {
2262
2318
  const {
2263
2319
  accountEnabled,
2264
2320
  height,
2265
- itemHeight
2321
+ itemHeight,
2322
+ platform
2266
2323
  } = state;
2267
- const [accountEnabledNew, activeView, sideBarVisible, sidebarLocation, userInfo] = await Promise.all([getAccountEnabled(accountEnabled), getActiveView(), getSideBarVisible(), getSideBarPosition(), getUserInfo()]);
2324
+ const [accountEnabledNew, activeView, contributedViews, sideBarVisible, sidebarLocation, userInfo] = await Promise.all([getAccountEnabled(accountEnabled), getActiveView(), getContributedViews(platform), getSideBarVisible(), getSideBarPosition(), getUserInfo()]);
2268
2325
  const newState = {
2269
2326
  ...state,
2270
2327
  accountEnabled: accountEnabledNew,
2271
2328
  userLoginState: toUserLoginState(getUserState(userInfo))
2272
2329
  };
2273
- const items = getActivityBarItems(newState);
2330
+ const items = getActivityBarItems(newState, contributedViews);
2274
2331
  const index = items.findIndex(item => item.id === activeView);
2275
2332
  const selectedIndex = sideBarVisible ? index : -1;
2276
2333
  const itemsWithSelected = markSelected(items, selectedIndex);
@@ -2453,11 +2510,78 @@ const treeToArray = node => {
2453
2510
  return result;
2454
2511
  };
2455
2512
 
2513
+ const navigateToChild = (patches, currentChildIndex, index) => {
2514
+ if (currentChildIndex === -1) {
2515
+ patches.push({
2516
+ type: NavigateChild,
2517
+ index
2518
+ });
2519
+ return index;
2520
+ }
2521
+ if (currentChildIndex !== index) {
2522
+ patches.push({
2523
+ type: NavigateSibling,
2524
+ index
2525
+ });
2526
+ }
2527
+ return index;
2528
+ };
2529
+ const navigateToParent = (patches, currentChildIndex) => {
2530
+ if (currentChildIndex >= 0) {
2531
+ patches.push({
2532
+ type: NavigateParent
2533
+ });
2534
+ }
2535
+ return -1;
2536
+ };
2537
+ const addTree = (newNode, patches) => {
2538
+ patches.push({
2539
+ type: Add,
2540
+ nodes: treeToArray(newNode)
2541
+ });
2542
+ };
2543
+ const replaceTree = (newNode, patches) => {
2544
+ patches.push({
2545
+ type: Replace,
2546
+ nodes: treeToArray(newNode)
2547
+ });
2548
+ };
2549
+ const diffExistingChild = (oldNode, newNode, patches, currentChildIndex, index) => {
2550
+ const nodePatches = compareNodes(oldNode.node, newNode.node);
2551
+ if (nodePatches === null) {
2552
+ const nextChildIndex = navigateToChild(patches, currentChildIndex, index);
2553
+ replaceTree(newNode, patches);
2554
+ return nextChildIndex;
2555
+ }
2556
+ const hasChildrenToCompare = oldNode.children.length > 0 || newNode.children.length > 0;
2557
+ if (nodePatches.length === 0 && !hasChildrenToCompare) {
2558
+ return currentChildIndex;
2559
+ }
2560
+ const nextChildIndex = navigateToChild(patches, currentChildIndex, index);
2561
+ if (nodePatches.length > 0) {
2562
+ patches.push(...nodePatches);
2563
+ }
2564
+ if (hasChildrenToCompare) {
2565
+ diffChildren(oldNode.children, newNode.children, patches);
2566
+ }
2567
+ return nextChildIndex;
2568
+ };
2569
+ const diffRootNode = (oldNode, newNode, patches) => {
2570
+ const nodePatches = compareNodes(oldNode.node, newNode.node);
2571
+ if (nodePatches === null) {
2572
+ replaceTree(newNode, patches);
2573
+ return;
2574
+ }
2575
+ if (nodePatches.length > 0) {
2576
+ patches.push(...nodePatches);
2577
+ }
2578
+ if (oldNode.children.length > 0 || newNode.children.length > 0) {
2579
+ diffChildren(oldNode.children, newNode.children, patches);
2580
+ }
2581
+ };
2456
2582
  const diffChildren = (oldChildren, newChildren, patches) => {
2457
2583
  const maxLength = Math.max(oldChildren.length, newChildren.length);
2458
- // Track where we are: -1 means at parent, >= 0 means at child index
2459
2584
  let currentChildIndex = -1;
2460
- // Collect indices of children to remove (we'll add these patches at the end in reverse order)
2461
2585
  const indicesToRemove = [];
2462
2586
  for (let i = 0; i < maxLength; i++) {
2463
2587
  const oldNode = oldChildren[i];
@@ -2466,88 +2590,17 @@ const diffChildren = (oldChildren, newChildren, patches) => {
2466
2590
  continue;
2467
2591
  }
2468
2592
  if (!oldNode) {
2469
- // Add new node - we should be at the parent
2470
- if (currentChildIndex >= 0) {
2471
- // Navigate back to parent
2472
- patches.push({
2473
- type: NavigateParent
2474
- });
2475
- currentChildIndex = -1;
2476
- }
2477
- // Flatten the entire subtree so renderInternal can handle it
2478
- const flatNodes = treeToArray(newNode);
2479
- patches.push({
2480
- type: Add,
2481
- nodes: flatNodes
2482
- });
2483
- } else if (newNode) {
2484
- // Compare nodes to see if we need any patches
2485
- const nodePatches = compareNodes(oldNode.node, newNode.node);
2486
- // If nodePatches is null, the node types are incompatible - need to replace
2487
- if (nodePatches === null) {
2488
- // Navigate to this child
2489
- if (currentChildIndex === -1) {
2490
- patches.push({
2491
- type: NavigateChild,
2492
- index: i
2493
- });
2494
- currentChildIndex = i;
2495
- } else if (currentChildIndex !== i) {
2496
- patches.push({
2497
- type: NavigateSibling,
2498
- index: i
2499
- });
2500
- currentChildIndex = i;
2501
- }
2502
- // Replace the entire subtree
2503
- const flatNodes = treeToArray(newNode);
2504
- patches.push({
2505
- type: Replace,
2506
- nodes: flatNodes
2507
- });
2508
- // After replace, we're at the new element (same position)
2509
- continue;
2510
- }
2511
- // Check if we need to recurse into children
2512
- const hasChildrenToCompare = oldNode.children.length > 0 || newNode.children.length > 0;
2513
- // Only navigate to this element if we need to do something
2514
- if (nodePatches.length > 0 || hasChildrenToCompare) {
2515
- // Navigate to this child if not already there
2516
- if (currentChildIndex === -1) {
2517
- patches.push({
2518
- type: NavigateChild,
2519
- index: i
2520
- });
2521
- currentChildIndex = i;
2522
- } else if (currentChildIndex !== i) {
2523
- patches.push({
2524
- type: NavigateSibling,
2525
- index: i
2526
- });
2527
- currentChildIndex = i;
2528
- }
2529
- // Apply node patches (these apply to the current element, not children)
2530
- if (nodePatches.length > 0) {
2531
- patches.push(...nodePatches);
2532
- }
2533
- // Compare children recursively
2534
- if (hasChildrenToCompare) {
2535
- diffChildren(oldNode.children, newNode.children, patches);
2536
- }
2537
- }
2538
- } else {
2539
- // Remove old node - collect the index for later removal
2593
+ currentChildIndex = navigateToParent(patches, currentChildIndex);
2594
+ addTree(newNode, patches);
2595
+ continue;
2596
+ }
2597
+ if (!newNode) {
2540
2598
  indicesToRemove.push(i);
2599
+ continue;
2541
2600
  }
2601
+ currentChildIndex = diffExistingChild(oldNode, newNode, patches, currentChildIndex, i);
2542
2602
  }
2543
- // Navigate back to parent if we ended at a child
2544
- if (currentChildIndex >= 0) {
2545
- patches.push({
2546
- type: NavigateParent
2547
- });
2548
- }
2549
- // Add remove patches in reverse order (highest index first)
2550
- // This ensures indices remain valid as we remove
2603
+ navigateToParent(patches, currentChildIndex);
2551
2604
  for (let j = indicesToRemove.length - 1; j >= 0; j--) {
2552
2605
  patches.push({
2553
2606
  type: RemoveChild,
@@ -2556,33 +2609,11 @@ const diffChildren = (oldChildren, newChildren, patches) => {
2556
2609
  }
2557
2610
  };
2558
2611
  const diffTrees = (oldTree, newTree, patches, path) => {
2559
- // At the root level (path.length === 0), we're already AT the element
2560
- // So we compare the root node directly, then compare its children
2561
2612
  if (path.length === 0 && oldTree.length === 1 && newTree.length === 1) {
2562
- const oldNode = oldTree[0];
2563
- const newNode = newTree[0];
2564
- // Compare root nodes
2565
- const nodePatches = compareNodes(oldNode.node, newNode.node);
2566
- // If nodePatches is null, the root node types are incompatible - need to replace
2567
- if (nodePatches === null) {
2568
- const flatNodes = treeToArray(newNode);
2569
- patches.push({
2570
- type: Replace,
2571
- nodes: flatNodes
2572
- });
2573
- return;
2574
- }
2575
- if (nodePatches.length > 0) {
2576
- patches.push(...nodePatches);
2577
- }
2578
- // Compare children
2579
- if (oldNode.children.length > 0 || newNode.children.length > 0) {
2580
- diffChildren(oldNode.children, newNode.children, patches);
2581
- }
2582
- } else {
2583
- // Non-root level or multiple root elements - use the regular comparison
2584
- diffChildren(oldTree, newTree, patches);
2613
+ diffRootNode(oldTree[0], newTree[0], patches);
2614
+ return;
2585
2615
  }
2616
+ diffChildren(oldTree, newTree, patches);
2586
2617
  };
2587
2618
 
2588
2619
  const removeTrailingNavigationPatches = patches => {
@@ -2882,8 +2913,8 @@ const render2 = (uid, diffResult) => {
2882
2913
  const {
2883
2914
  newState,
2884
2915
  oldState
2885
- } = get(uid);
2886
- set(uid, newState, newState);
2916
+ } = get$2(uid);
2917
+ set$4(uid, newState, newState);
2887
2918
  const commands = applyRender(oldState, newState, diffResult);
2888
2919
  return commands;
2889
2920
  };
@@ -2963,7 +2994,7 @@ const toggleActivityBarItem = async (state, itemId) => {
2963
2994
  };
2964
2995
 
2965
2996
  const commandMap = {
2966
- 'ActivityBar.create': create,
2997
+ 'ActivityBar.create': create$9,
2967
2998
  'ActivityBar.diff2': diff2,
2968
2999
  'ActivityBar.focus': wrapCommand(focus),
2969
3000
  'ActivityBar.focusFirst': wrapCommand(focusFirst),
@@ -2985,6 +3016,8 @@ const commandMap = {
2985
3016
  'ActivityBar.handleClickSignIn': wrapCommand(handleClickSignIn),
2986
3017
  'ActivityBar.handleClickSignOut': wrapCommand(handleClickSignOut),
2987
3018
  'ActivityBar.handleContextMenu': wrapCommand(handleContextMenu),
3019
+ 'ActivityBar.handleExtensionManagementMessagePort': handleExtensionManagementMessagePort,
3020
+ 'ActivityBar.handleExtensionsChanged': wrapCommand(handleExtensionsChanged),
2988
3021
  'ActivityBar.handleFocus': wrapCommand(handleFocus),
2989
3022
  'ActivityBar.handleSettingsChanged': wrapCommand(handleSettingsChanged),
2990
3023
  'ActivityBar.handleSideBarStateChange': wrapCommand(handleSideBarStateChange),
@@ -3000,25 +3033,39 @@ const commandMap = {
3000
3033
  'ActivityBar.toggleActivityBarItem': wrapCommand(toggleActivityBarItem)
3001
3034
  };
3002
3035
 
3003
- const send = async port => {
3036
+ const send$1 = async port => {
3004
3037
  // @ts-ignore
3005
3038
  await sendMessagePortToAuthWorker(port);
3006
3039
  };
3007
3040
  const initializeAuthWorker = async () => {
3008
- const rpc = await create$4({
3041
+ const rpc = await create$2({
3009
3042
  commandMap: {},
3010
- send
3043
+ send: send$1
3011
3044
  });
3012
3045
  set$2(rpc);
3013
3046
  };
3014
3047
 
3015
- const listen = async () => {
3016
- registerCommands(commandMap);
3017
- const rpc = await create$3({
3018
- commandMap: commandMap
3048
+ const send = async port => {
3049
+ await sendMessagePortToExtensionManagementWorker(port, 0);
3050
+ };
3051
+ const initializeExtensionManagementWorker = async () => {
3052
+ const rpc = await create$2({
3053
+ commandMap: {},
3054
+ send
3019
3055
  });
3020
3056
  set$1(rpc);
3021
- await initializeAuthWorker();
3057
+ };
3058
+
3059
+ const initializeRendererWorker = async () => {
3060
+ const rpc = await create$1({
3061
+ commandMap: commandMap
3062
+ });
3063
+ set(rpc);
3064
+ };
3065
+
3066
+ const listen = async () => {
3067
+ registerCommands(commandMap);
3068
+ await Promise.all([initializeRendererWorker(), initializeAuthWorker(), initializeExtensionManagementWorker()]);
3022
3069
  };
3023
3070
 
3024
3071
  const main = async () => {