@lvce-editor/status-bar-worker 3.35.0 → 3.35.1

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,2087 +1,2102 @@
1
- const toCommandId = key => {
2
- const dotIndex = key.indexOf('.');
3
- return key.slice(dotIndex + 1);
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;
4
9
  };
5
- const create$a = () => {
6
- const commandQueues = new Map();
7
- const generations = Object.create(null);
8
- const states = Object.create(null);
9
- const commandMapRef = Object.create(null);
10
- const commandsById = Object.create(null);
11
- const getGeneration = uid => generations[uid] || 0;
12
- const isCurrentGeneration = (uid, generation) => {
13
- return states[uid] !== undefined && getGeneration(uid) === generation;
14
- };
15
- const updateState = (uid, generation, fallbackState, updater) => {
16
- if (!isCurrentGeneration(uid, generation)) {
17
- return Promise.resolve(fallbackState);
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;
37
+ };
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);
18
45
  }
19
- const current = states[uid];
20
- const updatedState = updater(current.newState);
21
- if (updatedState !== current.newState) {
22
- states[uid] = {
23
- newState: updatedState,
24
- oldState: current.oldState,
25
- scheduledState: updatedState
26
- };
46
+ if (error.codeFrame) {
47
+ // @ts-ignore
48
+ this.codeFrame = error.codeFrame;
27
49
  }
28
- return Promise.resolve(updatedState);
50
+ if (error.code) {
51
+ // @ts-ignore
52
+ this.code = error.code;
53
+ }
54
+ }
55
+ }
56
+
57
+ const isMessagePort = value => {
58
+ return value && value instanceof MessagePort;
59
+ };
60
+ const isMessagePortMain = value => {
61
+ return value && value.constructor && value.constructor.name === 'MessagePortMain';
62
+ };
63
+ const isOffscreenCanvas = value => {
64
+ return typeof OffscreenCanvas !== 'undefined' && value instanceof OffscreenCanvas;
65
+ };
66
+ const isInstanceOf = (value, constructorName) => {
67
+ return value?.constructor?.name === constructorName;
68
+ };
69
+ const isSocket = value => {
70
+ return isInstanceOf(value, 'Socket');
71
+ };
72
+ const transferrables = [isMessagePort, isMessagePortMain, isOffscreenCanvas, isSocket];
73
+ const isTransferrable = value => {
74
+ for (const fn of transferrables) {
75
+ if (fn(value)) {
76
+ return true;
77
+ }
78
+ }
79
+ return false;
80
+ };
81
+ const walkValue = (value, transferrables, isTransferrable) => {
82
+ if (!value) {
83
+ return;
84
+ }
85
+ if (isTransferrable(value)) {
86
+ transferrables.push(value);
87
+ return;
88
+ }
89
+ if (Array.isArray(value)) {
90
+ for (const item of value) {
91
+ walkValue(item, transferrables, isTransferrable);
92
+ }
93
+ return;
94
+ }
95
+ if (typeof value === 'object') {
96
+ for (const property of Object.values(value)) {
97
+ walkValue(property, transferrables, isTransferrable);
98
+ }
99
+ }
100
+ };
101
+ const getTransferrables = value => {
102
+ const transferrables = [];
103
+ walkValue(value, transferrables, isTransferrable);
104
+ return transferrables;
105
+ };
106
+ const attachEvents = that => {
107
+ const handleMessage = (...args) => {
108
+ const data = that.getData(...args);
109
+ that.dispatchEvent(new MessageEvent('message', {
110
+ data
111
+ }));
29
112
  };
30
- const createAsyncCommandContext = (uid, generation) => {
31
- let latestState = states[uid].newState;
32
- return {
33
- getState: () => {
34
- if (isCurrentGeneration(uid, generation)) {
35
- latestState = states[uid].newState;
36
- }
37
- return latestState;
38
- },
39
- updateState: async updater => {
40
- latestState = await updateState(uid, generation, latestState, updater);
41
- return latestState;
42
- }
43
- };
113
+ that.onMessage(handleMessage);
114
+ const handleClose = event => {
115
+ that.dispatchEvent(new Event('close'));
44
116
  };
45
- const enqueueCommand = async (uid, command) => {
46
- const previous = commandQueues.get(uid) || Promise.resolve();
47
- const run = async () => {
48
- try {
49
- await previous;
50
- } catch {
51
- // The previous caller receives its error; later commands must still run.
52
- }
53
- await command();
117
+ that.onClose(handleClose);
118
+ };
119
+ class Ipc extends EventTarget {
120
+ constructor(rawIpc) {
121
+ super();
122
+ this._rawIpc = rawIpc;
123
+ attachEvents(this);
124
+ }
125
+ }
126
+ const E_INCOMPATIBLE_NATIVE_MODULE = 'E_INCOMPATIBLE_NATIVE_MODULE';
127
+ const E_MODULES_NOT_SUPPORTED_IN_ELECTRON = 'E_MODULES_NOT_SUPPORTED_IN_ELECTRON';
128
+ const ERR_MODULE_NOT_FOUND = 'ERR_MODULE_NOT_FOUND';
129
+ const NewLine$1 = '\n';
130
+ const joinLines$1 = lines => {
131
+ return lines.join(NewLine$1);
132
+ };
133
+ const RE_AT = /^\s+at/;
134
+ const RE_AT_PROMISE_INDEX = /^\s*at async Promise.all \(index \d+\)$/;
135
+ const isNormalStackLine = line => {
136
+ return RE_AT.test(line) && !RE_AT_PROMISE_INDEX.test(line);
137
+ };
138
+ const getDetails = lines => {
139
+ const index = lines.findIndex(isNormalStackLine);
140
+ if (index === -1) {
141
+ return {
142
+ actualMessage: joinLines$1(lines),
143
+ rest: []
54
144
  };
55
- const current = run();
56
- commandQueues.set(uid, current);
57
- try {
58
- await current;
59
- } finally {
60
- if (commandQueues.get(uid) === current) {
61
- commandQueues.delete(uid);
62
- }
145
+ }
146
+ let lastIndex = index - 1;
147
+ while (++lastIndex < lines.length) {
148
+ if (!isNormalStackLine(lines[lastIndex])) {
149
+ break;
63
150
  }
151
+ }
152
+ return {
153
+ actualMessage: lines[index - 1],
154
+ rest: lines.slice(index, lastIndex)
64
155
  };
156
+ };
157
+ const splitLines$1 = lines => {
158
+ return lines.split(NewLine$1);
159
+ };
160
+ const RE_MESSAGE_CODE_BLOCK_START = /^Error: The module '.*'$/;
161
+ const RE_MESSAGE_CODE_BLOCK_END = /^\s* at/;
162
+ const isMessageCodeBlockStartIndex = line => {
163
+ return RE_MESSAGE_CODE_BLOCK_START.test(line);
164
+ };
165
+ const isMessageCodeBlockEndIndex = line => {
166
+ return RE_MESSAGE_CODE_BLOCK_END.test(line);
167
+ };
168
+ const getMessageCodeBlock = stderr => {
169
+ const lines = splitLines$1(stderr);
170
+ const startIndex = lines.findIndex(isMessageCodeBlockStartIndex);
171
+ const endIndex = startIndex + lines.slice(startIndex).findIndex(isMessageCodeBlockEndIndex, startIndex);
172
+ const relevantLines = lines.slice(startIndex, endIndex);
173
+ const relevantMessage = relevantLines.join(' ').slice('Error: '.length);
174
+ return relevantMessage;
175
+ };
176
+ const isModuleNotFoundMessage = line => {
177
+ return line.includes('[ERR_MODULE_NOT_FOUND]');
178
+ };
179
+ const getModuleNotFoundError = stderr => {
180
+ const lines = splitLines$1(stderr);
181
+ const messageIndex = lines.findIndex(isModuleNotFoundMessage);
182
+ const message = lines[messageIndex];
65
183
  return {
66
- clear() {
67
- commandQueues.clear();
68
- for (const key of Object.keys(states)) {
69
- delete states[key];
70
- }
71
- },
72
- createDirectEventCommandMap(requestRender) {
73
- return {
74
- async 'Viewlet.executeViewletCommand'(uid, command, ...args) {
75
- const fn = commandsById[command];
76
- if (!fn) {
77
- throw new Error(`Viewlet command not found: ${command}`);
78
- }
79
- await fn(uid, ...args);
80
- await requestRender(uid);
81
- }
82
- };
83
- },
84
- diff(uid, modules, numbers) {
85
- const {
86
- oldState,
87
- scheduledState
88
- } = states[uid];
89
- const diffResult = [];
90
- for (let i = 0; i < modules.length; i++) {
91
- const fn = modules[i];
92
- if (!fn(oldState, scheduledState)) {
93
- diffResult.push(numbers[i]);
94
- }
95
- }
96
- return diffResult;
97
- },
98
- dispose(uid) {
99
- commandQueues.delete(uid);
100
- delete states[uid];
101
- },
102
- get(uid) {
103
- return states[uid];
104
- },
105
- getCommandIds() {
106
- const keys = Object.keys(commandMapRef);
107
- const ids = keys.map(toCommandId);
108
- return ids;
109
- },
110
- getKeys() {
111
- return Object.keys(states).map(Number);
112
- },
113
- registerCommands(commandMap) {
114
- Object.assign(commandMapRef, commandMap);
115
- for (const [key, fn] of Object.entries(commandMap)) {
116
- commandsById[toCommandId(key)] = fn;
117
- }
118
- },
119
- set(uid, oldState, newState, scheduledState) {
120
- const current = states[uid];
121
- if (!current || oldState === newState && newState !== current.newState) {
122
- generations[uid] = getGeneration(uid) + 1;
123
- }
124
- states[uid] = {
125
- newState,
126
- oldState,
127
- scheduledState: scheduledState ?? newState
128
- };
129
- },
130
- wrapAsyncCommand(fn) {
131
- const wrapped = async (uid, ...args) => {
132
- const generation = getGeneration(uid);
133
- const context = createAsyncCommandContext(uid, generation);
134
- await fn(context, ...args);
135
- };
136
- return wrapped;
137
- },
138
- wrapCommand(fn) {
139
- const wrapped = async (uid, ...args) => {
140
- const generation = getGeneration(uid);
141
- const {
142
- newState,
143
- oldState
144
- } = states[uid];
145
- const newerState = await fn(newState, ...args);
146
- if (oldState === newerState || newState === newerState) {
147
- return;
148
- }
149
- if (!isCurrentGeneration(uid, generation)) {
150
- return;
151
- }
152
- const latestOld = states[uid];
153
- const latestNew = {
154
- ...latestOld.newState,
155
- ...newerState
156
- };
157
- states[uid] = {
158
- newState: latestNew,
159
- oldState: latestOld.oldState,
160
- scheduledState: latestNew
161
- };
162
- };
163
- return wrapped;
164
- },
165
- wrapGetter(fn) {
166
- const wrapped = (uid, ...args) => {
167
- const {
168
- newState
169
- } = states[uid];
170
- return fn(newState, ...args);
171
- };
172
- return wrapped;
173
- },
174
- wrapLoadContent(fn) {
175
- const wrapped = async (uid, ...args) => {
176
- const generation = getGeneration(uid);
177
- const {
178
- newState,
179
- oldState
180
- } = states[uid];
181
- const result = await fn(newState, ...args);
182
- const {
183
- error,
184
- state
185
- } = result;
186
- if (oldState === state || newState === state) {
187
- return {
188
- error
189
- };
190
- }
191
- if (!isCurrentGeneration(uid, generation)) {
192
- return {
193
- error
194
- };
195
- }
196
- const latestOld = states[uid];
197
- const latestNew = {
198
- ...latestOld.newState,
199
- ...state
200
- };
201
- states[uid] = {
202
- newState: latestNew,
203
- oldState: latestOld.oldState,
204
- scheduledState: latestNew
205
- };
206
- return {
207
- error
208
- };
209
- };
210
- return wrapped;
211
- },
212
- wrapSerialAsyncCommand(fn) {
213
- const wrapped = async (uid, ...args) => {
214
- await enqueueCommand(uid, async () => {
215
- if (!states[uid]) {
216
- return;
217
- }
218
- const generation = getGeneration(uid);
219
- const context = createAsyncCommandContext(uid, generation);
220
- await fn(context, ...args);
221
- });
222
- };
223
- return wrapped;
224
- },
225
- wrapSerialCommand(fn) {
226
- const wrapped = async (uid, ...args) => {
227
- await enqueueCommand(uid, async () => {
228
- if (!states[uid]) {
229
- return;
230
- }
231
- const generation = getGeneration(uid);
232
- const {
233
- newState,
234
- oldState
235
- } = states[uid];
236
- const newerState = await fn(newState, ...args);
237
- if (oldState === newerState || newState === newerState) {
238
- return;
239
- }
240
- if (!isCurrentGeneration(uid, generation)) {
241
- return;
242
- }
243
- const latestOld = states[uid];
244
- const latestNew = {
245
- ...latestOld.newState,
246
- ...newerState
247
- };
248
- states[uid] = {
249
- newState: latestNew,
250
- oldState: latestOld.oldState,
251
- scheduledState: latestNew
252
- };
253
- });
254
- };
255
- return wrapped;
256
- }
184
+ code: ERR_MODULE_NOT_FOUND,
185
+ message
257
186
  };
258
187
  };
259
- const terminate = () => {
260
- globalThis.close();
188
+ const isModuleNotFoundError = stderr => {
189
+ if (!stderr) {
190
+ return false;
191
+ }
192
+ return stderr.includes('ERR_MODULE_NOT_FOUND');
261
193
  };
262
-
263
- const {
264
- get: get$5,
265
- getCommandIds,
266
- getKeys: getKeys$1,
267
- registerCommands,
268
- set: set$9,
269
- wrapCommand,
270
- wrapGetter,
271
- wrapSerialAsyncCommand} = create$a();
272
-
273
- const create$9 = (uid, uri, x, y, width, height, platform, assetDir, applicationId) => {
274
- const state = {
275
- ...(applicationId !== undefined && {
276
- applicationId
277
- }),
278
- assetDir,
279
- errorCount: 0,
280
- initial: true,
281
- platform,
282
- statusBarItemsLeft: [],
283
- statusBarItemsRight: [],
284
- uid,
285
- visibleStatusBarItemsLeft: [],
286
- visibleStatusBarItemsRight: [],
287
- warningCount: 0,
288
- width
289
- };
290
- set$9(uid, state, state);
194
+ const isModulesSyntaxError = stderr => {
195
+ if (!stderr) {
196
+ return false;
197
+ }
198
+ return stderr.includes('SyntaxError: Cannot use import statement outside a module');
291
199
  };
292
-
293
- const areItemsEqual = (left, right) => {
294
- return left.length === right.length && left.every((item, index) => item === right[index]);
200
+ const RE_NATIVE_MODULE_ERROR = /^innerError Error: Cannot find module '.*.node'/;
201
+ const RE_NATIVE_MODULE_ERROR_2 = /was compiled against a different Node.js version/;
202
+ const isUnhelpfulNativeModuleError = stderr => {
203
+ return RE_NATIVE_MODULE_ERROR.test(stderr) && RE_NATIVE_MODULE_ERROR_2.test(stderr);
295
204
  };
296
- const isEqual = (oldState, newState) => {
297
- return oldState.statusBarItemsLeft === newState.statusBarItemsLeft && oldState.statusBarItemsRight === newState.statusBarItemsRight && oldState.width === newState.width && areItemsEqual(oldState.visibleStatusBarItemsLeft, newState.visibleStatusBarItemsLeft) && areItemsEqual(oldState.visibleStatusBarItemsRight, newState.visibleStatusBarItemsRight);
205
+ const getNativeModuleErrorMessage = stderr => {
206
+ const message = getMessageCodeBlock(stderr);
207
+ return {
208
+ code: E_INCOMPATIBLE_NATIVE_MODULE,
209
+ message: `Incompatible native node module: ${message}`
210
+ };
298
211
  };
299
-
300
- const RenderItems = 4;
301
- const RenderIncremental = 11;
302
-
303
- const modules = [isEqual];
304
- const numbers = [RenderIncremental];
305
-
306
- const diff = (oldState, newState) => {
307
- const diffResult = [];
308
- for (let i = 0; i < modules.length; i++) {
309
- const fn = modules[i];
310
- if (!fn(oldState, newState)) {
311
- diffResult.push(numbers[i]);
312
- }
313
- }
314
- return diffResult;
212
+ const getModuleSyntaxError = () => {
213
+ return {
214
+ code: E_MODULES_NOT_SUPPORTED_IN_ELECTRON,
215
+ message: `ES Modules are not supported in electron`
216
+ };
315
217
  };
316
-
317
- const diff2 = uid => {
218
+ const getHelpfulChildProcessError = (stdout, stderr) => {
219
+ if (isUnhelpfulNativeModuleError(stderr)) {
220
+ return getNativeModuleErrorMessage(stderr);
221
+ }
222
+ if (isModulesSyntaxError(stderr)) {
223
+ return getModuleSyntaxError();
224
+ }
225
+ if (isModuleNotFoundError(stderr)) {
226
+ return getModuleNotFoundError(stderr);
227
+ }
228
+ const lines = splitLines$1(stderr);
318
229
  const {
319
- newState,
320
- oldState
321
- } = get$5(uid);
322
- const result = diff(oldState, newState);
323
- return result;
324
- };
325
-
326
- const getComponentState = uid => {
327
- return get$5(uid).newState;
328
- };
329
-
330
- const Status = 'status';
331
-
332
- const MaskIcon = 'MaskIcon';
333
-
334
- const Button$1 = 1;
335
- const Div = 4;
336
- const Span = 8;
337
- const Text = 12;
338
- const Progress = 92;
339
- const Reference = 100;
340
-
341
- const Button = 'event.button';
342
- const ClientX = 'event.clientX';
343
- const ClientY = 'event.clientY';
344
- const TargetName = 'event.target.name';
345
-
346
- const ExtensionManagementWorker = 9006;
347
- const RendererProcess = 1670;
348
- const RendererWorker = 1;
349
- const TextMeasurementWorker = 7011;
350
-
351
- const SetDom2 = 'Viewlet.setDom2';
352
- const SetFocusContext = 'Viewlet.setFocusContext';
353
- const SetPatches = 'Viewlet.setPatches';
354
-
355
- const mergeClassNames = (...classNames) => {
356
- return classNames.filter(Boolean).join(' ');
357
- };
358
-
359
- const text = data => {
230
+ actualMessage,
231
+ rest
232
+ } = getDetails(lines);
360
233
  return {
361
- childCount: 0,
362
- text: data,
363
- type: Text
234
+ code: '',
235
+ message: actualMessage,
236
+ stack: rest
364
237
  };
365
238
  };
366
-
367
- const SetText = 1;
368
- const Replace = 2;
369
- const SetAttribute = 3;
370
- const RemoveAttribute = 4;
371
- const Add = 6;
372
- const NavigateChild = 7;
373
- const NavigateParent = 8;
374
- const RemoveChild = 9;
375
- const NavigateSibling = 10;
376
- const SetReferenceNodeUid = 11;
377
- const MultiNavigation = 18;
378
-
379
- const isKey = key => {
380
- return key !== 'type' && key !== 'childCount';
381
- };
382
-
383
- const getKeys = node => {
384
- const keys = Object.keys(node).filter(isKey);
385
- return keys;
386
- };
387
-
388
- const arrayToTree = nodes => {
389
- const result = [];
390
- let i = 0;
391
- while (i < nodes.length) {
392
- const node = nodes[i];
393
- const {
394
- children,
395
- nodesConsumed
396
- } = getChildrenWithCount(nodes, i + 1, node.childCount || 0);
397
- result.push({
398
- node,
399
- children
400
- });
401
- i += 1 + nodesConsumed;
239
+ class IpcError extends VError {
240
+ // @ts-ignore
241
+ constructor(betterMessage, stdout = '', stderr = '') {
242
+ if (stdout || stderr) {
243
+ // @ts-ignore
244
+ const {
245
+ code,
246
+ message,
247
+ stack
248
+ } = getHelpfulChildProcessError(stdout, stderr);
249
+ const cause = new Error(message);
250
+ // @ts-ignore
251
+ cause.code = code;
252
+ if (stack) {
253
+ Object.defineProperty(cause, 'stack', {
254
+ configurable: true,
255
+ enumerable: false,
256
+ value: stack,
257
+ writable: true
258
+ });
259
+ }
260
+ super(cause, betterMessage);
261
+ } else {
262
+ super(betterMessage);
263
+ }
264
+ // @ts-ignore
265
+ this.name = 'IpcError';
266
+ // @ts-ignore
267
+ this.stdout = stdout;
268
+ // @ts-ignore
269
+ this.stderr = stderr;
402
270
  }
403
- return result;
271
+ }
272
+ const readyMessage = 'ready';
273
+ const getData$2 = event => {
274
+ return event.data;
404
275
  };
405
- const getChildrenWithCount = (nodes, startIndex, childCount) => {
406
- if (childCount === 0) {
407
- return {
408
- children: [],
409
- nodesConsumed: 0
410
- };
411
- }
412
- const children = [];
413
- let i = startIndex;
414
- let remaining = childCount;
415
- let totalConsumed = 0;
416
- while (remaining > 0 && i < nodes.length) {
417
- const node = nodes[i];
418
- const nodeChildCount = node.childCount || 0;
419
- const {
420
- children: nodeChildren,
421
- nodesConsumed
422
- } = getChildrenWithCount(nodes, i + 1, nodeChildCount);
423
- children.push({
424
- node,
425
- children: nodeChildren
426
- });
427
- const nodeSize = 1 + nodesConsumed;
428
- i += nodeSize;
429
- totalConsumed += nodeSize;
430
- remaining--;
276
+ const listen$7 = () => {
277
+ // @ts-ignore
278
+ if (typeof WorkerGlobalScope === 'undefined') {
279
+ throw new TypeError('module is not in web worker scope');
431
280
  }
432
- return {
433
- children,
434
- nodesConsumed: totalConsumed
435
- };
281
+ return globalThis;
436
282
  };
437
-
438
- const isNavigationPatch = patch => {
439
- switch (patch.type) {
440
- case NavigateChild:
441
- case NavigateParent:
442
- case NavigateSibling:
443
- return true;
444
- default:
445
- return false;
446
- }
283
+ const signal$8 = global => {
284
+ global.postMessage(readyMessage);
447
285
  };
448
- const getNavigationIndex = patch => {
449
- switch (patch.type) {
450
- case NavigateChild:
451
- case NavigateSibling:
452
- return patch.index;
453
- default:
454
- return 0;
286
+ class IpcChildWithModuleWorker extends Ipc {
287
+ getData(event) {
288
+ return getData$2(event);
455
289
  }
456
- };
457
- const appendNavigationPatch = (patches, type, index) => {
458
- const previousPatch = patches.at(-1);
459
- if (!previousPatch) {
460
- patches.push(type === NavigateParent ? {
461
- type
462
- } : {
463
- index,
464
- type
465
- });
466
- return;
290
+ send(message) {
291
+ // @ts-ignore
292
+ this._rawIpc.postMessage(message);
467
293
  }
468
- if (previousPatch.type === MultiNavigation) {
469
- previousPatch.navigations.push(type, index);
470
- return;
294
+ sendAndTransfer(message) {
295
+ const transfer = getTransferrables(message);
296
+ // @ts-ignore
297
+ this._rawIpc.postMessage(message, transfer);
471
298
  }
472
- if (isNavigationPatch(previousPatch)) {
473
- patches[patches.length - 1] = {
474
- navigations: [previousPatch.type, getNavigationIndex(previousPatch), type, index],
475
- type: MultiNavigation
476
- };
477
- return;
299
+ dispose() {
300
+ // ignore
478
301
  }
479
- patches.push(type === NavigateParent ? {
480
- type
481
- } : {
482
- index,
483
- type
302
+ onClose(callback) {
303
+ // ignore
304
+ }
305
+ onMessage(callback) {
306
+ this._rawIpc.addEventListener('message', callback);
307
+ }
308
+ }
309
+ const wrap$f = global => {
310
+ return new IpcChildWithModuleWorker(global);
311
+ };
312
+ const waitForFirstMessage = async port => {
313
+ const {
314
+ promise,
315
+ resolve
316
+ } = Promise.withResolvers();
317
+ port.addEventListener('message', resolve, {
318
+ once: true
484
319
  });
320
+ const event = await promise;
321
+ // @ts-ignore
322
+ return event.data;
485
323
  };
486
-
487
- const compareNodes = (oldNode, newNode) => {
488
- // Check if node type changed - return null to signal incompatible nodes
489
- // (caller should handle this with a Replace operation)
490
- if (oldNode.type !== newNode.type) {
491
- return null;
324
+ const listen$6 = async () => {
325
+ const parentIpcRaw = listen$7();
326
+ signal$8(parentIpcRaw);
327
+ const parentIpc = wrap$f(parentIpcRaw);
328
+ const firstMessage = await waitForFirstMessage(parentIpc);
329
+ if (firstMessage.method !== 'initialize') {
330
+ throw new IpcError('unexpected first message');
492
331
  }
493
- const patches = [];
494
- // Handle reference nodes - special handling for uid changes
495
- if (oldNode.type === Reference && oldNode.uid !== newNode.uid) {
496
- patches.push({
497
- type: SetReferenceNodeUid,
498
- uid: newNode.uid
332
+ const type = firstMessage.params[0];
333
+ if (type === 'message-port') {
334
+ parentIpc.send({
335
+ id: firstMessage.id,
336
+ jsonrpc: '2.0',
337
+ result: null
499
338
  });
339
+ parentIpc.dispose();
340
+ const port = firstMessage.params[1];
341
+ return port;
500
342
  }
501
- // Handle text nodes
502
- if (oldNode.type === Text && newNode.type === Text) {
503
- if (oldNode.text !== newNode.text) {
504
- patches.push({
505
- type: SetText,
506
- value: newNode.text
507
- });
508
- }
509
- return patches;
343
+ return globalThis;
344
+ };
345
+ class IpcChildWithModuleWorkerAndMessagePort extends Ipc {
346
+ getData(event) {
347
+ return getData$2(event);
510
348
  }
511
- // Compare attributes
512
- const oldKeys = getKeys(oldNode).filter(key => oldNode.type !== Reference || key !== 'uid');
513
- const newKeys = getKeys(newNode).filter(key => newNode.type !== Reference || key !== 'uid');
514
- // Check for attribute changes
515
- for (const key of newKeys) {
516
- if (oldNode[key] !== newNode[key]) {
517
- patches.push({
518
- type: SetAttribute,
519
- key,
520
- value: newNode[key]
521
- });
522
- }
349
+ send(message) {
350
+ this._rawIpc.postMessage(message);
523
351
  }
524
- // Check for removed attributes
525
- for (const key of oldKeys) {
526
- if (!Object.hasOwn(newNode, key)) {
527
- patches.push({
528
- type: RemoveAttribute,
529
- key
530
- });
531
- }
352
+ sendAndTransfer(message) {
353
+ const transfer = getTransferrables(message);
354
+ this._rawIpc.postMessage(message, transfer);
532
355
  }
533
- return patches;
534
- };
535
-
536
- const treeToArray = node => {
537
- const result = [];
538
- const stack = [node];
539
- while (stack.length > 0) {
540
- const current = stack.pop();
541
- result.push(current.node);
542
- for (let i = current.children.length - 1; i >= 0; i--) {
543
- stack.push(current.children[i]);
356
+ dispose() {
357
+ if (this._rawIpc.close) {
358
+ this._rawIpc.close();
544
359
  }
545
360
  }
546
- return result;
547
- };
548
-
549
- const navigateToChild = (patches, currentChildIndex, index) => {
550
- if (currentChildIndex === -1) {
551
- appendNavigationPatch(patches, NavigateChild, index);
552
- return index;
553
- }
554
- if (currentChildIndex !== index) {
555
- appendNavigationPatch(patches, NavigateSibling, index);
361
+ onClose(callback) {
362
+ // ignore
556
363
  }
557
- return index;
558
- };
559
- const navigateToParent = (patches, currentChildIndex) => {
560
- if (currentChildIndex >= 0) {
561
- appendNavigationPatch(patches, NavigateParent, 0);
364
+ onMessage(callback) {
365
+ this._rawIpc.addEventListener('message', callback);
366
+ this._rawIpc.start();
562
367
  }
563
- return -1;
368
+ }
369
+ const wrap$e = port => {
370
+ return new IpcChildWithModuleWorkerAndMessagePort(port);
564
371
  };
565
- const addTree = (newNode, patches) => {
566
- patches.push({
567
- type: Add,
568
- nodes: treeToArray(newNode)
569
- });
372
+ const IpcChildWithModuleWorkerAndMessagePort$1 = {
373
+ __proto__: null,
374
+ listen: listen$6,
375
+ wrap: wrap$e
570
376
  };
571
- const replaceTree = (newNode, patches) => {
572
- patches.push({
573
- type: Replace,
574
- nodes: treeToArray(newNode)
575
- });
377
+ const addListener = (emitter, type, callback) => {
378
+ if ('addEventListener' in emitter) {
379
+ emitter.addEventListener(type, callback);
380
+ } else {
381
+ emitter.on(type, callback);
382
+ }
576
383
  };
577
- const appendPatch = (patches, patch) => {
578
- switch (patch.type) {
579
- case MultiNavigation:
580
- for (let i = 0; i < patch.navigations.length; i += 2) {
581
- appendNavigationPatch(patches, patch.navigations[i], patch.navigations[i + 1]);
582
- }
583
- return;
584
- case NavigateChild:
585
- case NavigateSibling:
586
- appendNavigationPatch(patches, patch.type, patch.index);
587
- return;
588
- case NavigateParent:
589
- appendNavigationPatch(patches, patch.type, 0);
590
- return;
591
- default:
592
- patches.push(patch);
384
+ const removeListener = (emitter, type, callback) => {
385
+ if ('removeEventListener' in emitter) {
386
+ emitter.removeEventListener(type, callback);
387
+ } else {
388
+ emitter.off(type, callback);
593
389
  }
594
390
  };
595
- const appendPatches = (patches, newPatches) => {
596
- for (const patch of newPatches) {
597
- appendPatch(patches, patch);
391
+ const getFirstEvent = (eventEmitter, eventMap) => {
392
+ const {
393
+ promise,
394
+ resolve
395
+ } = Promise.withResolvers();
396
+ const listenerMap = Object.create(null);
397
+ const cleanup = value => {
398
+ for (const event of Object.keys(eventMap)) {
399
+ removeListener(eventEmitter, event, listenerMap[event]);
400
+ }
401
+ resolve(value);
402
+ };
403
+ for (const [event, type] of Object.entries(eventMap)) {
404
+ const listener = event => {
405
+ cleanup({
406
+ event,
407
+ type
408
+ });
409
+ };
410
+ addListener(eventEmitter, event, listener);
411
+ listenerMap[event] = listener;
598
412
  }
413
+ return promise;
599
414
  };
600
- const diffExistingChild = (oldNode, newNode, patches, currentChildIndex, index) => {
601
- const nodePatches = compareNodes(oldNode.node, newNode.node);
602
- if (nodePatches === null) {
603
- const nextChildIndex = navigateToChild(patches, currentChildIndex, index);
604
- replaceTree(newNode, patches);
605
- return nextChildIndex;
415
+ const Message$1 = 3;
416
+ const create$5$1 = async ({
417
+ isMessagePortOpen,
418
+ messagePort
419
+ }) => {
420
+ if (!isMessagePort(messagePort)) {
421
+ throw new IpcError('port must be of type MessagePort');
606
422
  }
607
- const hasChildrenToCompare = oldNode.children.length > 0 || newNode.children.length > 0;
608
- const childPatches = [];
609
- if (hasChildrenToCompare) {
610
- diffChildren(oldNode.children, newNode.children, childPatches);
423
+ if (isMessagePortOpen) {
424
+ return messagePort;
611
425
  }
612
- if (nodePatches.length === 0 && childPatches.length === 0) {
613
- return currentChildIndex;
426
+ const eventPromise = getFirstEvent(messagePort, {
427
+ message: Message$1
428
+ });
429
+ messagePort.start();
430
+ const {
431
+ event,
432
+ type
433
+ } = await eventPromise;
434
+ if (type !== Message$1) {
435
+ throw new IpcError('Failed to wait for ipc message');
614
436
  }
615
- const nextChildIndex = navigateToChild(patches, currentChildIndex, index);
616
- patches.push(...nodePatches);
617
- appendPatches(patches, childPatches);
618
- return nextChildIndex;
619
- };
620
- const diffRootNode = (oldNode, newNode, patches) => {
621
- const nodePatches = compareNodes(oldNode.node, newNode.node);
622
- if (nodePatches === null) {
623
- replaceTree(newNode, patches);
624
- return;
437
+ if (event.data !== readyMessage) {
438
+ throw new IpcError('unexpected first message');
625
439
  }
626
- if (nodePatches.length > 0) {
627
- patches.push(...nodePatches);
440
+ return messagePort;
441
+ };
442
+ const signal$1 = messagePort => {
443
+ messagePort.start();
444
+ };
445
+ class IpcParentWithMessagePort extends Ipc {
446
+ getData = getData$2;
447
+ send(message) {
448
+ this._rawIpc.postMessage(message);
628
449
  }
629
- if (oldNode.children.length > 0 || newNode.children.length > 0) {
630
- diffChildren(oldNode.children, newNode.children, patches);
450
+ sendAndTransfer(message) {
451
+ const transfer = getTransferrables(message);
452
+ this._rawIpc.postMessage(message, transfer);
631
453
  }
632
- };
633
- const diffChildren = (oldChildren, newChildren, patches) => {
634
- const maxLength = Math.max(oldChildren.length, newChildren.length);
635
- let currentChildIndex = -1;
636
- const indicesToRemove = [];
637
- for (let i = 0; i < maxLength; i++) {
638
- const oldNode = oldChildren[i];
639
- const newNode = newChildren[i];
640
- if (!oldNode && !newNode) {
641
- continue;
642
- }
643
- if (!oldNode) {
644
- currentChildIndex = navigateToParent(patches, currentChildIndex);
645
- addTree(newNode, patches);
646
- continue;
647
- }
648
- if (!newNode) {
649
- indicesToRemove.push(i);
650
- continue;
651
- }
652
- currentChildIndex = diffExistingChild(oldNode, newNode, patches, currentChildIndex, i);
454
+ dispose() {
455
+ this._rawIpc.close();
653
456
  }
654
- navigateToParent(patches, currentChildIndex);
655
- for (let j = indicesToRemove.length - 1; j >= 0; j--) {
656
- patches.push({
657
- type: RemoveChild,
658
- index: indicesToRemove[j]
659
- });
457
+ onMessage(callback) {
458
+ this._rawIpc.addEventListener('message', callback);
660
459
  }
460
+ onClose(callback) {}
461
+ }
462
+ const wrap$5 = messagePort => {
463
+ return new IpcParentWithMessagePort(messagePort);
661
464
  };
662
- const diffTrees = (oldTree, newTree, patches, path) => {
663
- if (path.length === 0 && oldTree.length === 1 && newTree.length === 1) {
664
- diffRootNode(oldTree[0], newTree[0], patches);
665
- return;
666
- }
667
- diffChildren(oldTree, newTree, patches);
465
+ const IpcParentWithMessagePort$1 = {
466
+ __proto__: null,
467
+ create: create$5$1,
468
+ signal: signal$1,
469
+ wrap: wrap$5
668
470
  };
669
471
 
670
- const removeTrailingNavigationPatches = patches => {
671
- while (patches.length > 0) {
672
- const patch = patches.at(-1);
673
- if (patch.type !== NavigateChild && patch.type !== NavigateParent && patch.type !== NavigateSibling && patch.type !== MultiNavigation) {
674
- break;
675
- }
676
- patches.pop();
677
- }
678
- return patches;
679
- };
680
-
681
- const diffTree = (oldNodes, newNodes) => {
682
- // Step 1: Convert flat arrays to tree structures
683
- const oldTree = arrayToTree(oldNodes);
684
- const newTree = arrayToTree(newNodes);
685
- // Step 3: Compare the trees
686
- const patches = [];
687
- diffTrees(oldTree, newTree, patches, []);
688
- // Remove trailing navigation patches since they serve no purpose
689
- return removeTrailingNavigationPatches(patches);
472
+ class CommandNotFoundError extends Error {
473
+ constructor(command) {
474
+ super(`Command not found ${command}`);
475
+ this.name = 'CommandNotFoundError';
476
+ }
477
+ }
478
+ const commands = Object.create(null);
479
+ const register = commandMap => {
480
+ Object.assign(commands, commandMap);
481
+ };
482
+ const getCommand = key => {
483
+ return commands[key];
484
+ };
485
+ const execute = (command, ...args) => {
486
+ const fn = getCommand(command);
487
+ if (!fn) {
488
+ throw new CommandNotFoundError(command);
489
+ }
490
+ return fn(...args);
690
491
  };
691
492
 
692
- const HandleContextMenu = 2;
693
- const HandleClick = 11;
694
-
695
- const ProblemsErrorIcon = 'ProblemsErrorIcon';
696
- const ProblemsWarningIcon = 'ProblemsWarningIcon';
697
- const StatusBarItem = 'StatusBarItem';
698
- const StatusBarItemsLeft = 'StatusBarItemsLeft';
699
- const StatusBarItemsRight = 'StatusBarItemsRight';
700
-
701
- const getTextVirtualDom = (element, name) => {
702
- return [{
703
- childCount: 1,
704
- className: 'StatusBarItemLabel',
705
- name,
706
- type: Span
707
- }, text(element.value)];
493
+ const Two$1 = '2.0';
494
+ const callbacks = Object.create(null);
495
+ const get$5 = id => {
496
+ return callbacks[id];
708
497
  };
709
- const getIconVirtualDom = (element, name) => {
710
- return [{
711
- childCount: 0,
712
- className: mergeClassNames(MaskIcon, 'StatusBarIcon', element.value, element.spinning ? 'Spinning' : ''),
713
- name,
714
- type: Div
715
- }];
498
+ const remove$1 = id => {
499
+ delete callbacks[id];
716
500
  };
717
- const getProgressVirtualDom = (element, name) => {
718
- const node = {
719
- ariaLabel: element.ariaLabel,
720
- className: 'StatusBarItemProgress',
721
- max: element.max,
722
- name,
723
- type: Progress
724
- };
725
- if (element.value !== undefined) {
726
- return [{
727
- ...node,
728
- value: element.value
729
- }];
501
+ class JsonRpcError extends Error {
502
+ constructor(message) {
503
+ super(message);
504
+ this.name = 'JsonRpcError';
730
505
  }
731
- return [node];
732
- };
733
- const getStatusBarItemElementVirtualDom = (element, name) => {
734
- if (element.type === 'text') {
735
- return getTextVirtualDom(element, name);
506
+ }
507
+ const NewLine = '\n';
508
+ const DomException = 'DOMException';
509
+ const ReferenceError$1 = 'ReferenceError';
510
+ const SyntaxError$1 = 'SyntaxError';
511
+ const TypeError$1 = 'TypeError';
512
+ const getErrorConstructor = (message, type) => {
513
+ if (type) {
514
+ switch (type) {
515
+ case DomException:
516
+ return DOMException;
517
+ case ReferenceError$1:
518
+ return ReferenceError;
519
+ case SyntaxError$1:
520
+ return SyntaxError;
521
+ case TypeError$1:
522
+ return TypeError;
523
+ default:
524
+ return Error;
525
+ }
736
526
  }
737
- if (element.type === 'icon') {
738
- return getIconVirtualDom(element, name);
527
+ if (message.startsWith('TypeError: ')) {
528
+ return TypeError;
739
529
  }
740
- if (element.type === 'progress') {
741
- return getProgressVirtualDom(element, name);
530
+ if (message.startsWith('SyntaxError: ')) {
531
+ return SyntaxError;
742
532
  }
743
- return [];
744
- };
745
-
746
- const getStatusBarItemVirtualDom = statusBarItem => {
747
- const {
748
- ariaLabel,
749
- elements,
750
- name,
751
- tooltip
752
- } = statusBarItem;
753
- const elementNodes = elements.flatMap(element => getStatusBarItemElementVirtualDom(element, name));
754
- const buttonNode = {
755
- ariaLabel,
756
- childCount: elements.length,
757
- className: StatusBarItem,
758
- name,
759
- tabIndex: -1,
760
- title: tooltip,
761
- type: Button$1
762
- };
763
- return [buttonNode, ...elementNodes];
764
- };
765
-
766
- const getStatusBarItemsVirtualDom = (items, className) => {
767
- if (items.length === 0) {
768
- return [];
533
+ if (message.startsWith('ReferenceError: ')) {
534
+ return ReferenceError;
769
535
  }
770
- return [{
771
- childCount: items.length,
772
- className,
773
- type: Div
774
- }, ...items.flatMap(getStatusBarItemVirtualDom)];
536
+ return Error;
775
537
  };
776
-
777
- const emptyStatusBarItemsLeftDom = [{
778
- childCount: 0,
779
- className: StatusBarItemsLeft,
780
- type: Div
781
- }];
782
- const getStatusBarItemsLeftDom = statusBarItemsLeft => {
783
- if (statusBarItemsLeft.length === 0) {
784
- return emptyStatusBarItemsLeftDom;
538
+ const constructError = (message, type, name) => {
539
+ const ErrorConstructor = getErrorConstructor(message, type);
540
+ if (ErrorConstructor === DOMException && name) {
541
+ return new ErrorConstructor(message, name);
785
542
  }
786
- return getStatusBarItemsVirtualDom(statusBarItemsLeft, StatusBarItemsLeft);
543
+ if (ErrorConstructor === Error) {
544
+ const error = new Error(message);
545
+ if (name && name !== 'VError') {
546
+ Object.defineProperty(error, 'name', {
547
+ configurable: true,
548
+ value: name
549
+ });
550
+ }
551
+ return error;
552
+ }
553
+ return new ErrorConstructor(message);
787
554
  };
788
-
789
- const getStatusBarItemsRightDom = statusBarItemsRight => {
790
- return getStatusBarItemsVirtualDom(statusBarItemsRight, StatusBarItemsRight);
555
+ const joinLines = lines => {
556
+ return lines.join(NewLine);
791
557
  };
792
-
793
- const Focusable = 0;
794
-
795
- const getChildCount = rightCount => {
796
- return rightCount > 0 ? 2 : 1;
558
+ const splitLines = lines => {
559
+ return lines.split(NewLine);
797
560
  };
798
- const getStatusBarVirtualDom = (statusBarItemsLeft, statusBarItemsRight) => {
799
- const dom = [{
800
- ariaLive: 'off',
801
- ariaRoleDescription: 'Status Bar',
802
- childCount: getChildCount(statusBarItemsRight.length),
803
- className: 'StatusBar',
804
- onClick: HandleClick,
805
- onContextMenu: HandleContextMenu,
806
- role: Status,
807
- tabIndex: Focusable,
808
- type: Div
809
- }, ...getStatusBarItemsLeftDom(statusBarItemsLeft), ...getStatusBarItemsRightDom(statusBarItemsRight)];
810
- return dom;
561
+ const getCurrentStack = () => {
562
+ const stackLinesToSkip = 3;
563
+ const currentStack = joinLines(splitLines(new Error().stack || '').slice(stackLinesToSkip));
564
+ return currentStack;
811
565
  };
812
-
813
- const renderItems = (oldState, newState) => {
814
- const {
815
- uid,
816
- visibleStatusBarItemsLeft,
817
- visibleStatusBarItemsRight
818
- } = newState;
819
- const dom = getStatusBarVirtualDom(visibleStatusBarItemsLeft, visibleStatusBarItemsRight);
820
- return [SetDom2, uid, dom];
566
+ const getNewLineIndex = (string, startIndex) => {
567
+ {
568
+ return string.indexOf(NewLine);
569
+ }
821
570
  };
822
-
823
- const getComponentDom = uid => {
824
- const state = getComponentState(uid);
825
- return renderItems(state, state)[2];
571
+ const getParentStack = error => {
572
+ let parentStack = error.stack || error.data || error.message || '';
573
+ if (parentStack.startsWith(' at')) {
574
+ parentStack = error.message + NewLine + parentStack;
575
+ }
576
+ return parentStack;
826
577
  };
827
-
828
- const getMatchingItemInternal = (items, name) => {
829
- for (const item of items) {
830
- if (item.name === name) {
831
- return item;
578
+ const MethodNotFound = -32601;
579
+ const Custom = -32001;
580
+ const setStack = (error, stack) => {
581
+ const descriptor = Object.getOwnPropertyDescriptor(error, 'stack');
582
+ if (descriptor) {
583
+ if (!descriptor.configurable && !descriptor.writable) {
584
+ return;
585
+ }
586
+ if (!descriptor.configurable && descriptor.writable) {
587
+ error.stack = stack;
588
+ return;
832
589
  }
833
590
  }
834
- return undefined;
591
+ Object.defineProperty(error, 'stack', {
592
+ configurable: true,
593
+ value: stack,
594
+ writable: true
595
+ });
835
596
  };
836
- const getMatchingItem = (itemsLeft, itemsRight, name) => {
837
- return getMatchingItemInternal(itemsLeft, name) ?? getMatchingItemInternal(itemsRight, name);
597
+ const restoreExistingError = (error, currentStack) => {
598
+ if (typeof error.stack === 'string') {
599
+ setStack(error, `${error.stack}${NewLine}${currentStack}`);
600
+ }
601
+ return error;
838
602
  };
839
-
840
- const EditorEncoding$1 = 'EditorEncoding';
841
- const EditorEndOfLine$1 = 'EditorEndOfLine';
842
- const EditorIndentation = 'EditorIndentation';
843
- const EditorLanguage$1 = 'EditorLanguage';
844
- const EditorPosition$1 = 'EditorPosition';
845
- const Notifications$1 = 'Notifications';
846
- const Problems$1 = 'Problems';
847
- const isEditorStatus = name => {
848
- return [EditorEncoding$1, EditorEndOfLine$1, EditorIndentation, EditorLanguage$1, EditorPosition$1].includes(name);
849
- };
850
- const isRight = name => {
851
- return name === Notifications$1 || isEditorStatus(name);
852
- };
853
-
854
- const state$2 = {
855
- rpc: undefined
856
- };
857
- const set$8 = rpc => {
858
- state$2.rpc = rpc;
859
- };
860
- const invoke$6 = (method, ...args) => {
861
- const {
862
- rpc
863
- } = state$2;
864
- return rpc.invoke(method, ...args);
603
+ const restoreMethodNotFoundError = (error, currentStack) => {
604
+ const restoredError = new JsonRpcError(error.message);
605
+ Object.assign(restoredError, {
606
+ code: error.code
607
+ });
608
+ const parentStack = getParentStack(error);
609
+ setStack(restoredError, `${parentStack}${NewLine}${currentStack}`);
610
+ return restoredError;
865
611
  };
866
-
867
- const handleClickEditorStatus = async (name, status) => {
868
- if (!status) {
612
+ const restoreStackFromData = (restoredError, error, currentStack) => {
613
+ if (error.data.stack && error.data.type && error.message) {
614
+ setStack(restoredError, `${error.data.type}: ${error.message}${NewLine}${error.data.stack}${NewLine}${currentStack}`);
869
615
  return;
870
616
  }
871
- switch (name) {
872
- case EditorEndOfLine$1:
873
- await invoke$6('QuickPick.openStatusBarPicker', 'end-of-line');
874
- return;
875
- case EditorIndentation:
876
- await invoke$6('QuickPick.openStatusBarPicker', 'indentation');
877
- return;
878
- case EditorLanguage$1:
879
- await invoke$6('QuickPick.openStatusBarPicker', 'language-mode');
880
- return;
881
- case EditorPosition$1:
882
- await invoke$6('QuickPick.openStatusBarPicker', 'go-to-line', status.line, status.column);
883
- return;
617
+ if (error.data.stack) {
618
+ setStack(restoredError, error.data.stack);
884
619
  }
885
620
  };
886
-
887
- const normalizeLine = line => {
888
- if (line.startsWith('Error: ')) {
889
- return line.slice('Error: '.length);
621
+ const applyDataProperties = (restoredError, error) => {
622
+ restoreStackFromData(restoredError, error, getCurrentStack());
623
+ if (error.data.codeFrame) {
624
+ // @ts-ignore
625
+ restoredError.codeFrame = error.data.codeFrame;
890
626
  }
891
- if (line.startsWith('VError: ')) {
892
- return line.slice('VError: '.length);
627
+ if (typeof error.data.code === 'string' || typeof error.data.code === 'number') {
628
+ // @ts-ignore
629
+ Object.defineProperty(restoredError, 'code', {
630
+ configurable: true,
631
+ value: error.data.code,
632
+ writable: true
633
+ });
634
+ }
635
+ if (error.data.type) {
636
+ // @ts-ignore
637
+ restoredError.name = error.data.type;
893
638
  }
894
- return line;
895
639
  };
896
- const getCombinedMessage = (error, message) => {
897
- const stringifiedError = normalizeLine(`${error}`);
898
- if (message) {
899
- return `${message}: ${stringifiedError}`;
640
+ const applyDirectProperties = (restoredError, error) => {
641
+ if (error.stack) {
642
+ const lowerStack = restoredError.stack || '';
643
+ const indexNewLine = getNewLineIndex(lowerStack);
644
+ const parentStack = getParentStack(error);
645
+ // @ts-ignore
646
+ setStack(restoredError, `${parentStack}${lowerStack.slice(indexNewLine)}`);
647
+ }
648
+ if (error.codeFrame) {
649
+ // @ts-ignore
650
+ restoredError.codeFrame = error.codeFrame;
900
651
  }
901
- return stringifiedError;
902
652
  };
903
- const NewLine$2 = '\n';
904
- const getNewLineIndex$1 = (string, startIndex = undefined) => {
905
- return string.indexOf(NewLine$2, startIndex);
653
+ const restoreMessageError = (error, _currentStack) => {
654
+ const restoredError = constructError(error.message, error.type || error.data?.type, error.name);
655
+ if (typeof error.code === 'string' || typeof error.code === 'number') {
656
+ Object.defineProperty(restoredError, 'code', {
657
+ configurable: true,
658
+ value: error.code,
659
+ writable: true
660
+ });
661
+ }
662
+ if (error.data) {
663
+ applyDataProperties(restoredError, error);
664
+ } else {
665
+ applyDirectProperties(restoredError, error);
666
+ }
667
+ return restoredError;
906
668
  };
907
- const mergeStacks = (parent, child) => {
908
- if (!child) {
909
- return parent;
669
+ const getFallbackMessage = error => {
670
+ if (error && typeof error.message === 'string' && error.message) {
671
+ return error.message;
910
672
  }
911
- const parentNewLineIndex = getNewLineIndex$1(parent);
912
- const childNewLineIndex = getNewLineIndex$1(child);
913
- if (childNewLineIndex === -1) {
914
- return parent;
673
+ if (error && error.data) {
674
+ return getFallbackMessage(error.data);
915
675
  }
916
- const parentFirstLine = parent.slice(0, parentNewLineIndex);
917
- const childRest = child.slice(childNewLineIndex);
918
- const childFirstLine = normalizeLine(child.slice(0, childNewLineIndex));
919
- if (parentFirstLine.includes(childFirstLine)) {
920
- return parentFirstLine + childRest;
676
+ const stringified = String(error);
677
+ if (stringified !== '[object Object]') {
678
+ return stringified;
921
679
  }
922
- return child;
923
- };
924
- class VError extends Error {
925
- constructor(error, message) {
926
- const combinedMessage = getCombinedMessage(error, message);
927
- super(combinedMessage);
928
- this.name = 'VError';
929
- if (error instanceof Error) {
930
- this.stack = mergeStacks(this.stack, error.stack);
931
- }
932
- if (error.codeFrame) {
933
- // @ts-ignore
934
- this.codeFrame = error.codeFrame;
935
- }
936
- if (error.code) {
937
- // @ts-ignore
938
- this.code = error.code;
939
- }
680
+ try {
681
+ return JSON.stringify(error);
682
+ } catch {
683
+ return stringified;
940
684
  }
941
- }
942
-
943
- const isMessagePort = value => {
944
- return value && value instanceof MessagePort;
945
- };
946
- const isMessagePortMain = value => {
947
- return value && value.constructor && value.constructor.name === 'MessagePortMain';
948
- };
949
- const isOffscreenCanvas = value => {
950
- return typeof OffscreenCanvas !== 'undefined' && value instanceof OffscreenCanvas;
951
- };
952
- const isInstanceOf = (value, constructorName) => {
953
- return value?.constructor?.name === constructorName;
954
685
  };
955
- const isSocket = value => {
956
- return isInstanceOf(value, 'Socket');
957
- };
958
- const transferrables = [isMessagePort, isMessagePortMain, isOffscreenCanvas, isSocket];
959
- const isTransferrable = value => {
960
- for (const fn of transferrables) {
961
- if (fn(value)) {
962
- return true;
963
- }
686
+ const restoreJsonRpcError = error => {
687
+ const currentStack = getCurrentStack();
688
+ if (error && error instanceof Error) {
689
+ return restoreExistingError(error, currentStack);
964
690
  }
965
- return false;
966
- };
967
- const walkValue = (value, transferrables, isTransferrable) => {
968
- if (!value) {
969
- return;
691
+ if (error && error.code && error.code === MethodNotFound) {
692
+ return restoreMethodNotFoundError(error, currentStack);
970
693
  }
971
- if (isTransferrable(value)) {
972
- transferrables.push(value);
973
- return;
694
+ if (error && error.error) {
695
+ return restoreJsonRpcError(error.error);
974
696
  }
975
- if (Array.isArray(value)) {
976
- for (const item of value) {
977
- walkValue(item, transferrables, isTransferrable);
978
- }
979
- return;
697
+ if (error && error.message) {
698
+ return restoreMessageError(error);
980
699
  }
981
- if (typeof value === 'object') {
982
- for (const property of Object.values(value)) {
983
- walkValue(property, transferrables, isTransferrable);
984
- }
700
+ return new Error(`JsonRpc Error: ${getFallbackMessage(error)}`);
701
+ };
702
+ const unwrapJsonRpcResult = responseMessage => {
703
+ if ('error' in responseMessage) {
704
+ const restoredError = restoreJsonRpcError(responseMessage.error);
705
+ throw restoredError;
706
+ }
707
+ if ('result' in responseMessage) {
708
+ return responseMessage.result;
985
709
  }
710
+ throw new JsonRpcError('unexpected response message');
986
711
  };
987
- const getTransferrables = value => {
988
- const transferrables = [];
989
- walkValue(value, transferrables, isTransferrable);
990
- return transferrables;
712
+ const warn = (...args) => {
713
+ console.warn(...args);
991
714
  };
992
- const attachEvents = that => {
993
- const handleMessage = (...args) => {
994
- const data = that.getData(...args);
995
- that.dispatchEvent(new MessageEvent('message', {
996
- data
997
- }));
998
- };
999
- that.onMessage(handleMessage);
1000
- const handleClose = event => {
1001
- that.dispatchEvent(new Event('close'));
1002
- };
1003
- that.onClose(handleClose);
715
+ const resolve = (id, response) => {
716
+ const fn = get$5(id);
717
+ if (!fn) {
718
+ console.log(response);
719
+ warn(`callback ${id} may already be disposed`);
720
+ return;
721
+ }
722
+ fn(response);
723
+ remove$1(id);
1004
724
  };
1005
- class Ipc extends EventTarget {
1006
- constructor(rawIpc) {
1007
- super();
1008
- this._rawIpc = rawIpc;
1009
- attachEvents(this);
725
+ const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
726
+ const getErrorType = prettyError => {
727
+ if (prettyError && prettyError.type) {
728
+ return prettyError.type;
1010
729
  }
1011
- }
1012
- const E_INCOMPATIBLE_NATIVE_MODULE = 'E_INCOMPATIBLE_NATIVE_MODULE';
1013
- const E_MODULES_NOT_SUPPORTED_IN_ELECTRON = 'E_MODULES_NOT_SUPPORTED_IN_ELECTRON';
1014
- const ERR_MODULE_NOT_FOUND = 'ERR_MODULE_NOT_FOUND';
1015
- const NewLine$1 = '\n';
1016
- const joinLines$1 = lines => {
1017
- return lines.join(NewLine$1);
730
+ if (prettyError && prettyError.constructor && prettyError.constructor.name) {
731
+ return prettyError.constructor.name;
732
+ }
733
+ return undefined;
1018
734
  };
1019
- const RE_AT = /^\s+at/;
1020
- const RE_AT_PROMISE_INDEX = /^\s*at async Promise.all \(index \d+\)$/;
1021
- const isNormalStackLine = line => {
1022
- return RE_AT.test(line) && !RE_AT_PROMISE_INDEX.test(line);
735
+ const isAlreadyStack = line => {
736
+ return line.trim().startsWith('at ');
1023
737
  };
1024
- const getDetails = lines => {
1025
- const index = lines.findIndex(isNormalStackLine);
1026
- if (index === -1) {
1027
- return {
1028
- actualMessage: joinLines$1(lines),
1029
- rest: []
1030
- };
738
+ const getStack = prettyError => {
739
+ const stackString = prettyError.stack || '';
740
+ const newLineIndex = stackString.indexOf('\n');
741
+ if (newLineIndex !== -1 && !isAlreadyStack(stackString.slice(0, newLineIndex))) {
742
+ return stackString.slice(newLineIndex + 1);
1031
743
  }
1032
- let lastIndex = index - 1;
1033
- while (++lastIndex < lines.length) {
1034
- if (!isNormalStackLine(lines[lastIndex])) {
1035
- break;
1036
- }
744
+ return stackString;
745
+ };
746
+ const getErrorProperty = (error, prettyError) => {
747
+ if (error && error.code === E_COMMAND_NOT_FOUND) {
748
+ return {
749
+ code: MethodNotFound,
750
+ data: error.stack,
751
+ message: error.message
752
+ };
1037
753
  }
1038
754
  return {
1039
- actualMessage: lines[index - 1],
1040
- rest: lines.slice(index, lastIndex)
755
+ code: Custom,
756
+ data: {
757
+ code: prettyError.code ?? error?.code,
758
+ codeFrame: prettyError.codeFrame,
759
+ name: prettyError.name ?? error?.name,
760
+ stack: getStack(prettyError),
761
+ type: getErrorType(prettyError)
762
+ },
763
+ message: prettyError.message
1041
764
  };
1042
765
  };
1043
- const splitLines$1 = lines => {
1044
- return lines.split(NewLine$1);
1045
- };
1046
- const RE_MESSAGE_CODE_BLOCK_START = /^Error: The module '.*'$/;
1047
- const RE_MESSAGE_CODE_BLOCK_END = /^\s* at/;
1048
- const isMessageCodeBlockStartIndex = line => {
1049
- return RE_MESSAGE_CODE_BLOCK_START.test(line);
766
+ const create$1$1 = (id, error) => {
767
+ return {
768
+ error,
769
+ id,
770
+ jsonrpc: Two$1
771
+ };
1050
772
  };
1051
- const isMessageCodeBlockEndIndex = line => {
1052
- return RE_MESSAGE_CODE_BLOCK_END.test(line);
773
+ const getErrorResponse = (id, error, preparePrettyError, logError) => {
774
+ const prettyError = preparePrettyError(error);
775
+ logError(error, prettyError);
776
+ const errorProperty = getErrorProperty(error, prettyError);
777
+ return create$1$1(id, errorProperty);
1053
778
  };
1054
- const getMessageCodeBlock = stderr => {
1055
- const lines = splitLines$1(stderr);
1056
- const startIndex = lines.findIndex(isMessageCodeBlockStartIndex);
1057
- const endIndex = startIndex + lines.slice(startIndex).findIndex(isMessageCodeBlockEndIndex, startIndex);
1058
- const relevantLines = lines.slice(startIndex, endIndex);
1059
- const relevantMessage = relevantLines.join(' ').slice('Error: '.length);
1060
- return relevantMessage;
779
+ const create$a = (message, result) => {
780
+ return {
781
+ id: message.id,
782
+ jsonrpc: Two$1,
783
+ result: result ?? null
784
+ };
1061
785
  };
1062
- const isModuleNotFoundMessage = line => {
1063
- return line.includes('[ERR_MODULE_NOT_FOUND]');
786
+ const getSuccessResponse = (message, result) => {
787
+ const resultProperty = result ?? null;
788
+ return create$a(message, resultProperty);
1064
789
  };
1065
- const getModuleNotFoundError = stderr => {
1066
- const lines = splitLines$1(stderr);
1067
- const messageIndex = lines.findIndex(isModuleNotFoundMessage);
1068
- const message = lines[messageIndex];
790
+ const getErrorResponseSimple = (id, error) => {
1069
791
  return {
1070
- code: ERR_MODULE_NOT_FOUND,
1071
- message
792
+ error: {
793
+ code: Custom,
794
+ data: error instanceof Error ? {
795
+ ...error,
796
+ code: 'code' in error ? error.code : undefined,
797
+ stack: error.stack,
798
+ type: error.name
799
+ } : error,
800
+ // @ts-ignore
801
+ message: error.message
802
+ },
803
+ id,
804
+ jsonrpc: Two$1
1072
805
  };
1073
806
  };
1074
- const isModuleNotFoundError = stderr => {
1075
- if (!stderr) {
1076
- return false;
1077
- }
1078
- return stderr.includes('ERR_MODULE_NOT_FOUND');
1079
- };
1080
- const isModulesSyntaxError = stderr => {
1081
- if (!stderr) {
1082
- return false;
807
+ const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
808
+ try {
809
+ const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
810
+ return getSuccessResponse(message, result);
811
+ } catch (error) {
812
+ if (ipc.canUseSimpleErrorResponse) {
813
+ return getErrorResponseSimple(message.id, error);
814
+ }
815
+ return getErrorResponse(message.id, error, preparePrettyError, logError);
1083
816
  }
1084
- return stderr.includes('SyntaxError: Cannot use import statement outside a module');
1085
817
  };
1086
- const RE_NATIVE_MODULE_ERROR = /^innerError Error: Cannot find module '.*.node'/;
1087
- const RE_NATIVE_MODULE_ERROR_2 = /was compiled against a different Node.js version/;
1088
- const isUnhelpfulNativeModuleError = stderr => {
1089
- return RE_NATIVE_MODULE_ERROR.test(stderr) && RE_NATIVE_MODULE_ERROR_2.test(stderr);
818
+ const defaultPreparePrettyError = error => {
819
+ return error;
1090
820
  };
1091
- const getNativeModuleErrorMessage = stderr => {
1092
- const message = getMessageCodeBlock(stderr);
1093
- return {
1094
- code: E_INCOMPATIBLE_NATIVE_MODULE,
1095
- message: `Incompatible native node module: ${message}`
1096
- };
821
+ const defaultLogError = () => {
822
+ // ignore
1097
823
  };
1098
- const getModuleSyntaxError = () => {
1099
- return {
1100
- code: E_MODULES_NOT_SUPPORTED_IN_ELECTRON,
1101
- message: `ES Modules are not supported in electron`
1102
- };
824
+ const defaultRequiresSocket = () => {
825
+ return false;
1103
826
  };
1104
- const getHelpfulChildProcessError = (stdout, stderr) => {
1105
- if (isUnhelpfulNativeModuleError(stderr)) {
1106
- return getNativeModuleErrorMessage(stderr);
1107
- }
1108
- if (isModulesSyntaxError(stderr)) {
1109
- return getModuleSyntaxError();
1110
- }
1111
- if (isModuleNotFoundError(stderr)) {
1112
- return getModuleNotFoundError(stderr);
827
+ const defaultResolve = resolve;
828
+
829
+ // TODO maybe remove this in v6 or v7, only accept options object to simplify the code
830
+ const normalizeParams = args => {
831
+ if (args.length === 1) {
832
+ const options = args[0];
833
+ return {
834
+ execute: options.execute,
835
+ ipc: options.ipc,
836
+ logError: options.logError || defaultLogError,
837
+ message: options.message,
838
+ preparePrettyError: options.preparePrettyError || defaultPreparePrettyError,
839
+ requiresSocket: options.requiresSocket || defaultRequiresSocket,
840
+ resolve: options.resolve || defaultResolve
841
+ };
1113
842
  }
1114
- const lines = splitLines$1(stderr);
1115
- const {
1116
- actualMessage,
1117
- rest
1118
- } = getDetails(lines);
1119
843
  return {
1120
- code: '',
1121
- message: actualMessage,
1122
- stack: rest
844
+ execute: args[2],
845
+ ipc: args[0],
846
+ logError: args[5],
847
+ message: args[1],
848
+ preparePrettyError: args[4],
849
+ requiresSocket: args[6],
850
+ resolve: args[3]
1123
851
  };
1124
852
  };
1125
- class IpcError extends VError {
1126
- // @ts-ignore
1127
- constructor(betterMessage, stdout = '', stderr = '') {
1128
- if (stdout || stderr) {
1129
- // @ts-ignore
1130
- const {
1131
- code,
1132
- message,
1133
- stack
1134
- } = getHelpfulChildProcessError(stdout, stderr);
1135
- const cause = new Error(message);
1136
- // @ts-ignore
1137
- cause.code = code;
1138
- if (stack) {
1139
- Object.defineProperty(cause, 'stack', {
1140
- configurable: true,
1141
- enumerable: false,
1142
- value: stack,
1143
- writable: true
1144
- });
853
+ const handleJsonRpcMessage = async (...args) => {
854
+ const options = normalizeParams(args);
855
+ const {
856
+ execute,
857
+ ipc,
858
+ logError,
859
+ message,
860
+ preparePrettyError,
861
+ requiresSocket,
862
+ resolve
863
+ } = options;
864
+ if ('id' in message) {
865
+ if ('method' in message) {
866
+ const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
867
+ try {
868
+ ipc.send(response);
869
+ } catch (error) {
870
+ const errorResponse = getErrorResponse(message.id, error, preparePrettyError, logError);
871
+ ipc.send(errorResponse);
1145
872
  }
1146
- super(cause, betterMessage);
1147
- } else {
1148
- super(betterMessage);
873
+ return;
1149
874
  }
1150
- // @ts-ignore
1151
- this.name = 'IpcError';
1152
- // @ts-ignore
1153
- this.stdout = stdout;
1154
- // @ts-ignore
1155
- this.stderr = stderr;
875
+ resolve(message.id, message);
876
+ return;
1156
877
  }
1157
- }
1158
- const readyMessage = 'ready';
1159
- const getData$2 = event => {
1160
- return event.data;
1161
- };
1162
- const listen$7 = () => {
1163
- // @ts-ignore
1164
- if (typeof WorkerGlobalScope === 'undefined') {
1165
- throw new TypeError('module is not in web worker scope');
878
+ if ('method' in message) {
879
+ await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
880
+ return;
1166
881
  }
1167
- return globalThis;
882
+ throw new JsonRpcError('unexpected message');
1168
883
  };
1169
- const signal$8 = global => {
1170
- global.postMessage(readyMessage);
884
+
885
+ const Two = '2.0';
886
+
887
+ const create$9 = (method, params) => {
888
+ return {
889
+ jsonrpc: Two,
890
+ method,
891
+ params
892
+ };
1171
893
  };
1172
- class IpcChildWithModuleWorker extends Ipc {
1173
- getData(event) {
1174
- return getData$2(event);
1175
- }
1176
- send(message) {
1177
- // @ts-ignore
1178
- this._rawIpc.postMessage(message);
1179
- }
1180
- sendAndTransfer(message) {
1181
- const transfer = getTransferrables(message);
1182
- // @ts-ignore
1183
- this._rawIpc.postMessage(message, transfer);
1184
- }
1185
- dispose() {
1186
- // ignore
1187
- }
1188
- onClose(callback) {
1189
- // ignore
1190
- }
1191
- onMessage(callback) {
1192
- this._rawIpc.addEventListener('message', callback);
1193
- }
1194
- }
1195
- const wrap$f = global => {
1196
- return new IpcChildWithModuleWorker(global);
894
+
895
+ const create$8 = (id, method, params) => {
896
+ const message = {
897
+ id,
898
+ jsonrpc: Two,
899
+ method,
900
+ params
901
+ };
902
+ return message;
1197
903
  };
1198
- const waitForFirstMessage = async port => {
904
+
905
+ let id = 0;
906
+ const create$7 = () => {
907
+ return ++id;
908
+ };
909
+
910
+ const registerPromise = map => {
911
+ const id = create$7();
1199
912
  const {
1200
913
  promise,
1201
914
  resolve
1202
915
  } = Promise.withResolvers();
1203
- port.addEventListener('message', resolve, {
1204
- once: true
1205
- });
1206
- const event = await promise;
1207
- // @ts-ignore
1208
- return event.data;
916
+ map[id] = resolve;
917
+ return {
918
+ id,
919
+ promise
920
+ };
1209
921
  };
1210
- const listen$6 = async () => {
1211
- const parentIpcRaw = listen$7();
1212
- signal$8(parentIpcRaw);
1213
- const parentIpc = wrap$f(parentIpcRaw);
1214
- const firstMessage = await waitForFirstMessage(parentIpc);
1215
- if (firstMessage.method !== 'initialize') {
1216
- throw new IpcError('unexpected first message');
1217
- }
1218
- const type = firstMessage.params[0];
1219
- if (type === 'message-port') {
1220
- parentIpc.send({
1221
- id: firstMessage.id,
1222
- jsonrpc: '2.0',
1223
- result: null
1224
- });
1225
- parentIpc.dispose();
1226
- const port = firstMessage.params[1];
1227
- return port;
922
+
923
+ const invokeHelper = async (callbacks, ipc, method, params, useSendAndTransfer) => {
924
+ const {
925
+ id,
926
+ promise
927
+ } = registerPromise(callbacks);
928
+ const message = create$8(id, method, params);
929
+ if (useSendAndTransfer && ipc.sendAndTransfer) {
930
+ ipc.sendAndTransfer(message);
931
+ } else {
932
+ ipc.send(message);
1228
933
  }
1229
- return globalThis;
934
+ const responseMessage = await promise;
935
+ return unwrapJsonRpcResult(responseMessage);
1230
936
  };
1231
- class IpcChildWithModuleWorkerAndMessagePort extends Ipc {
1232
- getData(event) {
1233
- return getData$2(event);
1234
- }
1235
- send(message) {
1236
- this._rawIpc.postMessage(message);
1237
- }
1238
- sendAndTransfer(message) {
1239
- const transfer = getTransferrables(message);
1240
- this._rawIpc.postMessage(message, transfer);
1241
- }
1242
- dispose() {
1243
- if (this._rawIpc.close) {
1244
- this._rawIpc.close();
937
+ const createRpc = ipc => {
938
+ const callbacks = Object.create(null);
939
+ ipc._resolve = (id, response) => {
940
+ const fn = callbacks[id];
941
+ if (!fn) {
942
+ console.warn(`callback ${id} may already be disposed`);
943
+ return;
1245
944
  }
1246
- }
1247
- onClose(callback) {
1248
- // ignore
1249
- }
1250
- onMessage(callback) {
1251
- this._rawIpc.addEventListener('message', callback);
1252
- this._rawIpc.start();
1253
- }
1254
- }
1255
- const wrap$e = port => {
1256
- return new IpcChildWithModuleWorkerAndMessagePort(port);
945
+ fn(response);
946
+ delete callbacks[id];
947
+ };
948
+ const rpc = {
949
+ async dispose() {
950
+ await ipc?.dispose();
951
+ },
952
+ invoke(method, ...params) {
953
+ return invokeHelper(callbacks, ipc, method, params, false);
954
+ },
955
+ invokeAndTransfer(method, ...params) {
956
+ return invokeHelper(callbacks, ipc, method, params, true);
957
+ },
958
+ // @ts-ignore
959
+ ipc,
960
+ /**
961
+ * @deprecated
962
+ */
963
+ send(method, ...params) {
964
+ const message = create$9(method, params);
965
+ ipc.send(message);
966
+ }
967
+ };
968
+ return rpc;
1257
969
  };
1258
- const IpcChildWithModuleWorkerAndMessagePort$1 = {
1259
- __proto__: null,
1260
- listen: listen$6,
1261
- wrap: wrap$e
970
+
971
+ const requiresSocket = () => {
972
+ return false;
1262
973
  };
1263
- const addListener = (emitter, type, callback) => {
1264
- if ('addEventListener' in emitter) {
1265
- emitter.addEventListener(type, callback);
1266
- } else {
1267
- emitter.on(type, callback);
974
+ const preparePrettyError = error => {
975
+ return error;
976
+ };
977
+ const logError = () => {
978
+ // handled by renderer worker
979
+ };
980
+ const handleMessage = event => {
981
+ if (event.data === 'ready') {
982
+ return Promise.resolve();
1268
983
  }
984
+ const actualRequiresSocket = event?.target?.requiresSocket || requiresSocket;
985
+ const actualExecute = event?.target?.execute || execute;
986
+ return handleJsonRpcMessage(event.target, event.data, actualExecute, event.target._resolve, preparePrettyError, logError, actualRequiresSocket);
1269
987
  };
1270
- const removeListener = (emitter, type, callback) => {
1271
- if ('removeEventListener' in emitter) {
1272
- emitter.removeEventListener(type, callback);
1273
- } else {
1274
- emitter.off(type, callback);
988
+
989
+ const handleIpc = ipc => {
990
+ if ('addEventListener' in ipc) {
991
+ ipc.addEventListener('message', handleMessage);
992
+ } else if ('on' in ipc) {
993
+ // deprecated
994
+ ipc.on('message', handleMessage);
1275
995
  }
1276
996
  };
1277
- const getFirstEvent = (eventEmitter, eventMap) => {
1278
- const {
1279
- promise,
1280
- resolve
1281
- } = Promise.withResolvers();
1282
- const listenerMap = Object.create(null);
1283
- const cleanup = value => {
1284
- for (const event of Object.keys(eventMap)) {
1285
- removeListener(eventEmitter, event, listenerMap[event]);
997
+
998
+ const listen$1 = async (module, options) => {
999
+ const rawIpc = await module.listen(options);
1000
+ if (module.signal) {
1001
+ module.signal(rawIpc);
1002
+ }
1003
+ const ipc = module.wrap(rawIpc);
1004
+ return ipc;
1005
+ };
1006
+
1007
+ const createSharedLazyRpc = factory => {
1008
+ let rpcPromise;
1009
+ const getOrCreate = () => {
1010
+ if (!rpcPromise) {
1011
+ rpcPromise = factory();
1012
+ }
1013
+ return rpcPromise;
1014
+ };
1015
+ return {
1016
+ async dispose() {
1017
+ const rpc = await getOrCreate();
1018
+ await rpc.dispose();
1019
+ },
1020
+ async invoke(method, ...params) {
1021
+ const rpc = await getOrCreate();
1022
+ return rpc.invoke(method, ...params);
1023
+ },
1024
+ async invokeAndTransfer(method, ...params) {
1025
+ const rpc = await getOrCreate();
1026
+ return rpc.invokeAndTransfer(method, ...params);
1027
+ },
1028
+ async send(method, ...params) {
1029
+ const rpc = await getOrCreate();
1030
+ rpc.send(method, ...params);
1286
1031
  }
1287
- resolve(value);
1288
1032
  };
1289
- for (const [event, type] of Object.entries(eventMap)) {
1290
- const listener = event => {
1291
- cleanup({
1292
- event,
1293
- type
1294
- });
1295
- };
1296
- addListener(eventEmitter, event, listener);
1297
- listenerMap[event] = listener;
1298
- }
1299
- return promise;
1300
1033
  };
1301
- const Message$1 = 3;
1302
- const create$5$1 = async ({
1303
- isMessagePortOpen,
1034
+
1035
+ const create$6 = async ({
1036
+ commandMap,
1037
+ isMessagePortOpen = true,
1304
1038
  messagePort
1305
1039
  }) => {
1306
- if (!isMessagePort(messagePort)) {
1307
- throw new IpcError('port must be of type MessagePort');
1308
- }
1309
- if (isMessagePortOpen) {
1310
- return messagePort;
1311
- }
1312
- const eventPromise = getFirstEvent(messagePort, {
1313
- message: Message$1
1040
+ // TODO create a commandMap per rpc instance
1041
+ register(commandMap);
1042
+ const rawIpc = await IpcParentWithMessagePort$1.create({
1043
+ isMessagePortOpen,
1044
+ messagePort
1314
1045
  });
1046
+ const ipc = IpcParentWithMessagePort$1.wrap(rawIpc);
1047
+ handleIpc(ipc);
1048
+ const rpc = createRpc(ipc);
1315
1049
  messagePort.start();
1316
- const {
1317
- event,
1318
- type
1319
- } = await eventPromise;
1320
- if (type !== Message$1) {
1321
- throw new IpcError('Failed to wait for ipc message');
1322
- }
1323
- if (event.data !== readyMessage) {
1324
- throw new IpcError('unexpected first message');
1325
- }
1326
- return messagePort;
1327
- };
1328
- const signal$1 = messagePort => {
1329
- messagePort.start();
1050
+ return rpc;
1330
1051
  };
1331
- class IpcParentWithMessagePort extends Ipc {
1332
- getData = getData$2;
1333
- send(message) {
1334
- this._rawIpc.postMessage(message);
1335
- }
1336
- sendAndTransfer(message) {
1337
- const transfer = getTransferrables(message);
1338
- this._rawIpc.postMessage(message, transfer);
1339
- }
1340
- dispose() {
1341
- this._rawIpc.close();
1342
- }
1343
- onMessage(callback) {
1344
- this._rawIpc.addEventListener('message', callback);
1345
- }
1346
- onClose(callback) {}
1347
- }
1348
- const wrap$5 = messagePort => {
1349
- return new IpcParentWithMessagePort(messagePort);
1350
- };
1351
- const IpcParentWithMessagePort$1 = {
1352
- __proto__: null,
1353
- create: create$5$1,
1354
- signal: signal$1,
1355
- wrap: wrap$5
1052
+
1053
+ const create$5 = async ({
1054
+ commandMap,
1055
+ isMessagePortOpen,
1056
+ send
1057
+ }) => {
1058
+ const {
1059
+ port1,
1060
+ port2
1061
+ } = new MessageChannel();
1062
+ await send(port1);
1063
+ return create$6({
1064
+ commandMap,
1065
+ isMessagePortOpen,
1066
+ messagePort: port2
1067
+ });
1356
1068
  };
1357
1069
 
1358
- class CommandNotFoundError extends Error {
1359
- constructor(command) {
1360
- super(`Command not found ${command}`);
1361
- this.name = 'CommandNotFoundError';
1362
- }
1363
- }
1364
- const commands = Object.create(null);
1365
- const register = commandMap => {
1366
- Object.assign(commands, commandMap);
1070
+ const create$4 = async ({
1071
+ commandMap,
1072
+ isMessagePortOpen,
1073
+ send
1074
+ }) => {
1075
+ return createSharedLazyRpc(() => {
1076
+ return create$5({
1077
+ commandMap,
1078
+ isMessagePortOpen,
1079
+ send
1080
+ });
1081
+ });
1367
1082
  };
1368
- const getCommand = key => {
1369
- return commands[key];
1083
+
1084
+ const create$3 = async ({
1085
+ commandMap
1086
+ }) => {
1087
+ // TODO create a commandMap per rpc instance
1088
+ register(commandMap);
1089
+ const ipc = await listen$1(IpcChildWithModuleWorkerAndMessagePort$1);
1090
+ handleIpc(ipc);
1091
+ const rpc = createRpc(ipc);
1092
+ return rpc;
1370
1093
  };
1371
- const execute = (command, ...args) => {
1372
- const fn = getCommand(command);
1373
- if (!fn) {
1374
- throw new CommandNotFoundError(command);
1375
- }
1376
- return fn(...args);
1094
+
1095
+ const createMockRpc = ({
1096
+ commandMap
1097
+ }) => {
1098
+ const invocations = [];
1099
+ const invoke = (method, ...params) => {
1100
+ invocations.push([method, ...params]);
1101
+ const command = commandMap[method];
1102
+ if (!command) {
1103
+ throw new Error(`command ${method} not found`);
1104
+ }
1105
+ return command(...params);
1106
+ };
1107
+ const mockRpc = {
1108
+ invocations,
1109
+ invoke,
1110
+ invokeAndTransfer: invoke
1111
+ };
1112
+ return mockRpc;
1377
1113
  };
1378
1114
 
1379
- const Two$1 = '2.0';
1380
- const callbacks = Object.create(null);
1381
- const get$4 = id => {
1382
- return callbacks[id];
1115
+ const rpcs = Object.create(null);
1116
+ const set$a = (id, rpc) => {
1117
+ rpcs[id] = rpc;
1383
1118
  };
1384
- const remove$1 = id => {
1385
- delete callbacks[id];
1119
+ const get$4 = id => {
1120
+ return rpcs[id];
1386
1121
  };
1387
- class JsonRpcError extends Error {
1388
- constructor(message) {
1389
- super(message);
1390
- this.name = 'JsonRpcError';
1391
- }
1392
- }
1393
- const NewLine = '\n';
1394
- const DomException = 'DOMException';
1395
- const ReferenceError$1 = 'ReferenceError';
1396
- const SyntaxError$1 = 'SyntaxError';
1397
- const TypeError$1 = 'TypeError';
1398
- const getErrorConstructor = (message, type) => {
1399
- if (type) {
1400
- switch (type) {
1401
- case DomException:
1402
- return DOMException;
1403
- case ReferenceError$1:
1404
- return ReferenceError;
1405
- case SyntaxError$1:
1406
- return SyntaxError;
1407
- case TypeError$1:
1408
- return TypeError;
1409
- default:
1410
- return Error;
1411
- }
1412
- }
1413
- if (message.startsWith('TypeError: ')) {
1414
- return TypeError;
1415
- }
1416
- if (message.startsWith('SyntaxError: ')) {
1417
- return SyntaxError;
1418
- }
1419
- if (message.startsWith('ReferenceError: ')) {
1420
- return ReferenceError;
1421
- }
1422
- return Error;
1122
+ const remove = id => {
1123
+ delete rpcs[id];
1423
1124
  };
1424
- const constructError = (message, type, name) => {
1425
- const ErrorConstructor = getErrorConstructor(message, type);
1426
- if (ErrorConstructor === DOMException && name) {
1427
- return new ErrorConstructor(message, name);
1428
- }
1429
- if (ErrorConstructor === Error) {
1430
- const error = new Error(message);
1431
- if (name && name !== 'VError') {
1432
- Object.defineProperty(error, 'name', {
1433
- configurable: true,
1434
- value: name
1125
+
1126
+ /* eslint-disable @typescript-eslint/explicit-function-return-type */
1127
+ const create$2 = rpcId => {
1128
+ return {
1129
+ async dispose() {
1130
+ const rpc = get$4(rpcId);
1131
+ await rpc.dispose();
1132
+ },
1133
+ // @ts-ignore
1134
+ invoke(method, ...params) {
1135
+ const rpc = get$4(rpcId);
1136
+ // @ts-ignore
1137
+ return rpc.invoke(method, ...params);
1138
+ },
1139
+ // @ts-ignore
1140
+ invokeAndTransfer(method, ...params) {
1141
+ const rpc = get$4(rpcId);
1142
+ // @ts-ignore
1143
+ return rpc.invokeAndTransfer(method, ...params);
1144
+ },
1145
+ registerMockRpc(commandMap) {
1146
+ const mockRpc = createMockRpc({
1147
+ commandMap
1435
1148
  });
1149
+ set$a(rpcId, mockRpc);
1150
+ // @ts-ignore
1151
+ mockRpc[Symbol.dispose] = () => {
1152
+ remove(rpcId);
1153
+ };
1154
+ // @ts-ignore
1155
+ return mockRpc;
1156
+ },
1157
+ set(rpc) {
1158
+ set$a(rpcId, rpc);
1436
1159
  }
1437
- return error;
1438
- }
1439
- return new ErrorConstructor(message);
1160
+ };
1440
1161
  };
1441
- const joinLines = lines => {
1442
- return lines.join(NewLine);
1162
+
1163
+ const {
1164
+ invoke: invoke$7,
1165
+ set: set$9
1166
+ } = create$2(19_001);
1167
+ const getCacheStorageJsonItem = async (request, cacheName, bucketName, bucketOptions) => {
1168
+ return invoke$7('Cache.getCacheStorageJsonItem', request, cacheName, bucketName, bucketOptions);
1443
1169
  };
1444
- const splitLines = lines => {
1445
- return lines.split(NewLine);
1170
+ const setCacheStorageJsonItem = async (request, value, cacheName, bucketName, bucketOptions) => {
1171
+ return invoke$7('Cache.setCacheStorageJsonItem', request, value, cacheName, bucketName, bucketOptions);
1446
1172
  };
1447
- const getCurrentStack = () => {
1448
- const stackLinesToSkip = 3;
1449
- const currentStack = joinLines(splitLines(new Error().stack || '').slice(stackLinesToSkip));
1450
- return currentStack;
1173
+
1174
+ const Status = 'status';
1175
+
1176
+ const MaskIcon = 'MaskIcon';
1177
+
1178
+ const Button$1 = 1;
1179
+ const Div = 4;
1180
+ const Span = 8;
1181
+ const Text = 12;
1182
+ const Progress = 92;
1183
+ const Reference = 100;
1184
+
1185
+ const Button = 'event.button';
1186
+ const ClientX = 'event.clientX';
1187
+ const ClientY = 'event.clientY';
1188
+ const TargetName = 'event.target.name';
1189
+
1190
+ const ExtensionManagementWorker = 9006;
1191
+ const RendererProcess = 1670;
1192
+ const RendererWorker = 1;
1193
+ const TextMeasurementWorker = 7011;
1194
+
1195
+ const SetDom2 = 'Viewlet.setDom2';
1196
+ const SetFocusContext = 'Viewlet.setFocusContext';
1197
+ const SetPatches = 'Viewlet.setPatches';
1198
+
1199
+ const {
1200
+ invoke: invoke$6,
1201
+ set: set$8
1202
+ } = create$2(ExtensionManagementWorker);
1203
+
1204
+ const {
1205
+ invoke: invoke$5,
1206
+ set: set$7
1207
+ } = create$2(RendererProcess);
1208
+
1209
+ const {
1210
+ invoke: invoke$4,
1211
+ set: set$6
1212
+ } = create$2(TextMeasurementWorker);
1213
+ const measureTextWidths$1 = async (texts, fontWeight, fontSize, fontFamily, letterSpacing, isMonoSpaceFont, charWidth) => {
1214
+ return invoke$4('TextMeasurement.measureTextWidths', texts, fontWeight, fontSize, fontFamily, letterSpacing, isMonoSpaceFont, charWidth);
1451
1215
  };
1452
- const getNewLineIndex = (string, startIndex) => {
1453
- {
1454
- return string.indexOf(NewLine);
1455
- }
1216
+
1217
+ const {
1218
+ invoke: invoke$3,
1219
+ invokeAndTransfer,
1220
+ set: set$5
1221
+ } = create$2(RendererWorker);
1222
+ const sendMessagePortToTextMeasurementWorker = async port => {
1223
+ const command = 'TextMeasurement.handleMessagePort';
1224
+ await invokeAndTransfer('SendMessagePortToExtensionHostWorker.sendMessagePortToTextMeasurementWorker', port, command, 0);
1456
1225
  };
1457
- const getParentStack = error => {
1458
- let parentStack = error.stack || error.data || error.message || '';
1459
- if (parentStack.startsWith(' at')) {
1460
- parentStack = error.message + NewLine + parentStack;
1461
- }
1462
- return parentStack;
1226
+ const sendMessagePortToCacheWorker = async port => {
1227
+ const command = 'CacheWorker.handleMessagePort';
1228
+ await invokeAndTransfer('SendMessagePortToExtensionHostWorker.sendMessagePortToCacheWorker', port, command, 0);
1463
1229
  };
1464
- const MethodNotFound = -32601;
1465
- const Custom = -32001;
1466
- const setStack = (error, stack) => {
1467
- const descriptor = Object.getOwnPropertyDescriptor(error, 'stack');
1468
- if (descriptor) {
1469
- if (!descriptor.configurable && !descriptor.writable) {
1470
- return;
1471
- }
1472
- if (!descriptor.configurable && descriptor.writable) {
1473
- error.stack = stack;
1474
- return;
1475
- }
1476
- }
1477
- Object.defineProperty(error, 'stack', {
1478
- configurable: true,
1479
- value: stack,
1480
- writable: true
1481
- });
1482
- };
1483
- const restoreExistingError = (error, currentStack) => {
1484
- if (typeof error.stack === 'string') {
1485
- setStack(error, `${error.stack}${NewLine}${currentStack}`);
1486
- }
1487
- return error;
1488
- };
1489
- const restoreMethodNotFoundError = (error, currentStack) => {
1490
- const restoredError = new JsonRpcError(error.message);
1491
- Object.assign(restoredError, {
1492
- code: error.code
1493
- });
1494
- const parentStack = getParentStack(error);
1495
- setStack(restoredError, `${parentStack}${NewLine}${currentStack}`);
1496
- return restoredError;
1497
- };
1498
- const restoreStackFromData = (restoredError, error, currentStack) => {
1499
- if (error.data.stack && error.data.type && error.message) {
1500
- setStack(restoredError, `${error.data.type}: ${error.message}${NewLine}${error.data.stack}${NewLine}${currentStack}`);
1501
- return;
1502
- }
1503
- if (error.data.stack) {
1504
- setStack(restoredError, error.data.stack);
1505
- }
1506
- };
1507
- const applyDataProperties = (restoredError, error) => {
1508
- restoreStackFromData(restoredError, error, getCurrentStack());
1509
- if (error.data.codeFrame) {
1510
- // @ts-ignore
1511
- restoredError.codeFrame = error.data.codeFrame;
1512
- }
1513
- if (typeof error.data.code === 'string' || typeof error.data.code === 'number') {
1514
- // @ts-ignore
1515
- Object.defineProperty(restoredError, 'code', {
1516
- configurable: true,
1517
- value: error.data.code,
1518
- writable: true
1519
- });
1520
- }
1521
- if (error.data.type) {
1522
- // @ts-ignore
1523
- restoredError.name = error.data.type;
1524
- }
1525
- };
1526
- const applyDirectProperties = (restoredError, error) => {
1527
- if (error.stack) {
1528
- const lowerStack = restoredError.stack || '';
1529
- const indexNewLine = getNewLineIndex(lowerStack);
1530
- const parentStack = getParentStack(error);
1531
- // @ts-ignore
1532
- setStack(restoredError, `${parentStack}${lowerStack.slice(indexNewLine)}`);
1533
- }
1534
- if (error.codeFrame) {
1535
- // @ts-ignore
1536
- restoredError.codeFrame = error.codeFrame;
1537
- }
1538
- };
1539
- const restoreMessageError = (error, _currentStack) => {
1540
- const restoredError = constructError(error.message, error.type || error.data?.type, error.name);
1541
- if (typeof error.code === 'string' || typeof error.code === 'number') {
1542
- Object.defineProperty(restoredError, 'code', {
1543
- configurable: true,
1544
- value: error.code,
1545
- writable: true
1546
- });
1547
- }
1548
- if (error.data) {
1549
- applyDataProperties(restoredError, error);
1550
- } else {
1551
- applyDirectProperties(restoredError, error);
1552
- }
1553
- return restoredError;
1554
- };
1555
- const getFallbackMessage = error => {
1556
- if (error && typeof error.message === 'string' && error.message) {
1557
- return error.message;
1558
- }
1559
- if (error && error.data) {
1560
- return getFallbackMessage(error.data);
1561
- }
1562
- const stringified = String(error);
1563
- if (stringified !== '[object Object]') {
1564
- return stringified;
1565
- }
1566
- try {
1567
- return JSON.stringify(error);
1568
- } catch {
1569
- return stringified;
1570
- }
1571
- };
1572
- const restoreJsonRpcError = error => {
1573
- const currentStack = getCurrentStack();
1574
- if (error && error instanceof Error) {
1575
- return restoreExistingError(error, currentStack);
1576
- }
1577
- if (error && error.code && error.code === MethodNotFound) {
1578
- return restoreMethodNotFoundError(error, currentStack);
1579
- }
1580
- if (error && error.error) {
1581
- return restoreJsonRpcError(error.error);
1582
- }
1583
- if (error && error.message) {
1584
- return restoreMessageError(error);
1585
- }
1586
- return new Error(`JsonRpc Error: ${getFallbackMessage(error)}`);
1230
+ const getPreference = async key => {
1231
+ return await invoke$3('Preferences.get', key);
1587
1232
  };
1588
- const unwrapJsonRpcResult = responseMessage => {
1589
- if ('error' in responseMessage) {
1590
- const restoredError = restoreJsonRpcError(responseMessage.error);
1591
- throw restoredError;
1592
- }
1593
- if ('result' in responseMessage) {
1594
- return responseMessage.result;
1595
- }
1596
- throw new JsonRpcError('unexpected response message');
1233
+
1234
+ const toCommandId = key => {
1235
+ const dotIndex = key.indexOf('.');
1236
+ return key.slice(dotIndex + 1);
1597
1237
  };
1598
- const warn = (...args) => {
1599
- console.warn(...args);
1238
+ const create$1 = () => {
1239
+ const commandQueues = new Map();
1240
+ const generations = Object.create(null);
1241
+ const states = Object.create(null);
1242
+ const commandMapRef = Object.create(null);
1243
+ const commandsById = Object.create(null);
1244
+ const getGeneration = uid => generations[uid] || 0;
1245
+ const isCurrentGeneration = (uid, generation) => {
1246
+ return states[uid] !== undefined && getGeneration(uid) === generation;
1247
+ };
1248
+ const updateState = (uid, generation, fallbackState, updater) => {
1249
+ if (!isCurrentGeneration(uid, generation)) {
1250
+ return Promise.resolve(fallbackState);
1251
+ }
1252
+ const current = states[uid];
1253
+ const updatedState = updater(current.newState);
1254
+ if (updatedState !== current.newState) {
1255
+ states[uid] = {
1256
+ newState: updatedState,
1257
+ oldState: current.oldState,
1258
+ scheduledState: updatedState
1259
+ };
1260
+ }
1261
+ return Promise.resolve(updatedState);
1262
+ };
1263
+ const createAsyncCommandContext = (uid, generation) => {
1264
+ let latestState = states[uid].newState;
1265
+ return {
1266
+ getState: () => {
1267
+ if (isCurrentGeneration(uid, generation)) {
1268
+ latestState = states[uid].newState;
1269
+ }
1270
+ return latestState;
1271
+ },
1272
+ updateState: async updater => {
1273
+ latestState = await updateState(uid, generation, latestState, updater);
1274
+ return latestState;
1275
+ }
1276
+ };
1277
+ };
1278
+ const enqueueCommand = async (uid, command) => {
1279
+ const previous = commandQueues.get(uid) || Promise.resolve();
1280
+ const run = async () => {
1281
+ try {
1282
+ await previous;
1283
+ } catch {
1284
+ // The previous caller receives its error; later commands must still run.
1285
+ }
1286
+ await command();
1287
+ };
1288
+ const current = run();
1289
+ commandQueues.set(uid, current);
1290
+ try {
1291
+ await current;
1292
+ } finally {
1293
+ if (commandQueues.get(uid) === current) {
1294
+ commandQueues.delete(uid);
1295
+ }
1296
+ }
1297
+ };
1298
+ return {
1299
+ clear() {
1300
+ commandQueues.clear();
1301
+ for (const key of Object.keys(states)) {
1302
+ delete states[key];
1303
+ }
1304
+ },
1305
+ createDirectEventCommandMap(requestRender) {
1306
+ return {
1307
+ async 'Viewlet.executeViewletCommand'(uid, command, ...args) {
1308
+ const fn = commandsById[command];
1309
+ if (!fn) {
1310
+ throw new Error(`Viewlet command not found: ${command}`);
1311
+ }
1312
+ await fn(uid, ...args);
1313
+ await requestRender(uid);
1314
+ }
1315
+ };
1316
+ },
1317
+ diff(uid, modules, numbers) {
1318
+ const {
1319
+ oldState,
1320
+ scheduledState
1321
+ } = states[uid];
1322
+ const diffResult = [];
1323
+ for (let i = 0; i < modules.length; i++) {
1324
+ const fn = modules[i];
1325
+ if (!fn(oldState, scheduledState)) {
1326
+ diffResult.push(numbers[i]);
1327
+ }
1328
+ }
1329
+ return diffResult;
1330
+ },
1331
+ dispose(uid) {
1332
+ commandQueues.delete(uid);
1333
+ delete states[uid];
1334
+ },
1335
+ get(uid) {
1336
+ return states[uid];
1337
+ },
1338
+ getCommandIds() {
1339
+ const keys = Object.keys(commandMapRef);
1340
+ const ids = keys.map(toCommandId);
1341
+ return ids;
1342
+ },
1343
+ getKeys() {
1344
+ return Object.keys(states).map(Number);
1345
+ },
1346
+ registerCommands(commandMap) {
1347
+ Object.assign(commandMapRef, commandMap);
1348
+ for (const [key, fn] of Object.entries(commandMap)) {
1349
+ commandsById[toCommandId(key)] = fn;
1350
+ }
1351
+ },
1352
+ set(uid, oldState, newState, scheduledState) {
1353
+ const current = states[uid];
1354
+ if (!current || oldState === newState && newState !== current.newState) {
1355
+ generations[uid] = getGeneration(uid) + 1;
1356
+ }
1357
+ states[uid] = {
1358
+ newState,
1359
+ oldState,
1360
+ scheduledState: scheduledState ?? newState
1361
+ };
1362
+ },
1363
+ wrapAsyncCommand(fn) {
1364
+ const wrapped = async (uid, ...args) => {
1365
+ const generation = getGeneration(uid);
1366
+ const context = createAsyncCommandContext(uid, generation);
1367
+ await fn(context, ...args);
1368
+ };
1369
+ return wrapped;
1370
+ },
1371
+ wrapCommand(fn) {
1372
+ const wrapped = async (uid, ...args) => {
1373
+ const generation = getGeneration(uid);
1374
+ const {
1375
+ newState,
1376
+ oldState
1377
+ } = states[uid];
1378
+ const newerState = await fn(newState, ...args);
1379
+ if (oldState === newerState || newState === newerState) {
1380
+ return;
1381
+ }
1382
+ if (!isCurrentGeneration(uid, generation)) {
1383
+ return;
1384
+ }
1385
+ const latestOld = states[uid];
1386
+ const latestNew = {
1387
+ ...latestOld.newState,
1388
+ ...newerState
1389
+ };
1390
+ states[uid] = {
1391
+ newState: latestNew,
1392
+ oldState: latestOld.oldState,
1393
+ scheduledState: latestNew
1394
+ };
1395
+ };
1396
+ return wrapped;
1397
+ },
1398
+ wrapGetter(fn) {
1399
+ const wrapped = (uid, ...args) => {
1400
+ const {
1401
+ newState
1402
+ } = states[uid];
1403
+ return fn(newState, ...args);
1404
+ };
1405
+ return wrapped;
1406
+ },
1407
+ wrapLoadContent(fn) {
1408
+ const wrapped = async (uid, ...args) => {
1409
+ const generation = getGeneration(uid);
1410
+ const {
1411
+ newState,
1412
+ oldState
1413
+ } = states[uid];
1414
+ const result = await fn(newState, ...args);
1415
+ const {
1416
+ error,
1417
+ state
1418
+ } = result;
1419
+ if (oldState === state || newState === state) {
1420
+ return {
1421
+ error
1422
+ };
1423
+ }
1424
+ if (!isCurrentGeneration(uid, generation)) {
1425
+ return {
1426
+ error
1427
+ };
1428
+ }
1429
+ const latestOld = states[uid];
1430
+ const latestNew = {
1431
+ ...latestOld.newState,
1432
+ ...state
1433
+ };
1434
+ states[uid] = {
1435
+ newState: latestNew,
1436
+ oldState: latestOld.oldState,
1437
+ scheduledState: latestNew
1438
+ };
1439
+ return {
1440
+ error
1441
+ };
1442
+ };
1443
+ return wrapped;
1444
+ },
1445
+ wrapSerialAsyncCommand(fn) {
1446
+ const wrapped = async (uid, ...args) => {
1447
+ await enqueueCommand(uid, async () => {
1448
+ if (!states[uid]) {
1449
+ return;
1450
+ }
1451
+ const generation = getGeneration(uid);
1452
+ const context = createAsyncCommandContext(uid, generation);
1453
+ await fn(context, ...args);
1454
+ });
1455
+ };
1456
+ return wrapped;
1457
+ },
1458
+ wrapSerialCommand(fn) {
1459
+ const wrapped = async (uid, ...args) => {
1460
+ await enqueueCommand(uid, async () => {
1461
+ if (!states[uid]) {
1462
+ return;
1463
+ }
1464
+ const generation = getGeneration(uid);
1465
+ const {
1466
+ newState,
1467
+ oldState
1468
+ } = states[uid];
1469
+ const newerState = await fn(newState, ...args);
1470
+ if (oldState === newerState || newState === newerState) {
1471
+ return;
1472
+ }
1473
+ if (!isCurrentGeneration(uid, generation)) {
1474
+ return;
1475
+ }
1476
+ const latestOld = states[uid];
1477
+ const latestNew = {
1478
+ ...latestOld.newState,
1479
+ ...newerState
1480
+ };
1481
+ states[uid] = {
1482
+ newState: latestNew,
1483
+ oldState: latestOld.oldState,
1484
+ scheduledState: latestNew
1485
+ };
1486
+ });
1487
+ };
1488
+ return wrapped;
1489
+ }
1490
+ };
1600
1491
  };
1601
- const resolve = (id, response) => {
1602
- const fn = get$4(id);
1603
- if (!fn) {
1604
- console.log(response);
1605
- warn(`callback ${id} may already be disposed`);
1606
- return;
1607
- }
1608
- fn(response);
1609
- remove$1(id);
1492
+ const terminate = () => {
1493
+ globalThis.close();
1610
1494
  };
1611
- const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
1612
- const getErrorType = prettyError => {
1613
- if (prettyError && prettyError.type) {
1614
- return prettyError.type;
1615
- }
1616
- if (prettyError && prettyError.constructor && prettyError.constructor.name) {
1617
- return prettyError.constructor.name;
1618
- }
1619
- return undefined;
1495
+
1496
+ const {
1497
+ get: get$3,
1498
+ getCommandIds,
1499
+ getKeys: getKeys$1,
1500
+ registerCommands,
1501
+ set: set$4,
1502
+ wrapCommand,
1503
+ wrapGetter,
1504
+ wrapSerialAsyncCommand} = create$1();
1505
+
1506
+ const create = (uid, uri, x, y, width, height, platform, assetDir, applicationId) => {
1507
+ const state = {
1508
+ ...(applicationId !== undefined && {
1509
+ applicationId
1510
+ }),
1511
+ assetDir,
1512
+ errorCount: 0,
1513
+ initial: true,
1514
+ platform,
1515
+ statusBarItemsLeft: [],
1516
+ statusBarItemsRight: [],
1517
+ uid,
1518
+ visibleStatusBarItemsLeft: [],
1519
+ visibleStatusBarItemsRight: [],
1520
+ warningCount: 0,
1521
+ width
1522
+ };
1523
+ set$4(uid, state, state);
1620
1524
  };
1621
- const isAlreadyStack = line => {
1622
- return line.trim().startsWith('at ');
1525
+
1526
+ const areItemsEqual = (left, right) => {
1527
+ return left.length === right.length && left.every((item, index) => item === right[index]);
1623
1528
  };
1624
- const getStack = prettyError => {
1625
- const stackString = prettyError.stack || '';
1626
- const newLineIndex = stackString.indexOf('\n');
1627
- if (newLineIndex !== -1 && !isAlreadyStack(stackString.slice(0, newLineIndex))) {
1628
- return stackString.slice(newLineIndex + 1);
1629
- }
1630
- return stackString;
1529
+ const isEqual = (oldState, newState) => {
1530
+ return oldState.statusBarItemsLeft === newState.statusBarItemsLeft && oldState.statusBarItemsRight === newState.statusBarItemsRight && oldState.width === newState.width && areItemsEqual(oldState.visibleStatusBarItemsLeft, newState.visibleStatusBarItemsLeft) && areItemsEqual(oldState.visibleStatusBarItemsRight, newState.visibleStatusBarItemsRight);
1631
1531
  };
1632
- const getErrorProperty = (error, prettyError) => {
1633
- if (error && error.code === E_COMMAND_NOT_FOUND) {
1634
- return {
1635
- code: MethodNotFound,
1636
- data: error.stack,
1637
- message: error.message
1638
- };
1532
+
1533
+ const RenderItems = 4;
1534
+ const RenderIncremental = 11;
1535
+
1536
+ const modules = [isEqual];
1537
+ const numbers = [RenderIncremental];
1538
+
1539
+ const diff = (oldState, newState) => {
1540
+ const diffResult = [];
1541
+ for (let i = 0; i < modules.length; i++) {
1542
+ const fn = modules[i];
1543
+ if (!fn(oldState, newState)) {
1544
+ diffResult.push(numbers[i]);
1545
+ }
1639
1546
  }
1640
- return {
1641
- code: Custom,
1642
- data: {
1643
- code: prettyError.code ?? error?.code,
1644
- codeFrame: prettyError.codeFrame,
1645
- name: prettyError.name ?? error?.name,
1646
- stack: getStack(prettyError),
1647
- type: getErrorType(prettyError)
1648
- },
1649
- message: prettyError.message
1650
- };
1651
- };
1652
- const create$1$1 = (id, error) => {
1653
- return {
1654
- error,
1655
- id,
1656
- jsonrpc: Two$1
1657
- };
1547
+ return diffResult;
1658
1548
  };
1659
- const getErrorResponse = (id, error, preparePrettyError, logError) => {
1660
- const prettyError = preparePrettyError(error);
1661
- logError(error, prettyError);
1662
- const errorProperty = getErrorProperty(error, prettyError);
1663
- return create$1$1(id, errorProperty);
1549
+
1550
+ const diff2 = uid => {
1551
+ const {
1552
+ newState,
1553
+ oldState
1554
+ } = get$3(uid);
1555
+ const result = diff(oldState, newState);
1556
+ return result;
1664
1557
  };
1665
- const create$8 = (message, result) => {
1666
- return {
1667
- id: message.id,
1668
- jsonrpc: Two$1,
1669
- result: result ?? null
1670
- };
1558
+
1559
+ const getComponentState = uid => {
1560
+ return get$3(uid).newState;
1671
1561
  };
1672
- const getSuccessResponse = (message, result) => {
1673
- const resultProperty = result ?? null;
1674
- return create$8(message, resultProperty);
1562
+
1563
+ const mergeClassNames = (...classNames) => {
1564
+ return classNames.filter(Boolean).join(' ');
1675
1565
  };
1676
- const getErrorResponseSimple = (id, error) => {
1566
+
1567
+ const text = data => {
1677
1568
  return {
1678
- error: {
1679
- code: Custom,
1680
- data: error instanceof Error ? {
1681
- ...error,
1682
- code: 'code' in error ? error.code : undefined,
1683
- stack: error.stack,
1684
- type: error.name
1685
- } : error,
1686
- // @ts-ignore
1687
- message: error.message
1688
- },
1689
- id,
1690
- jsonrpc: Two$1
1569
+ childCount: 0,
1570
+ text: data,
1571
+ type: Text
1691
1572
  };
1692
1573
  };
1693
- const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
1694
- try {
1695
- const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
1696
- return getSuccessResponse(message, result);
1697
- } catch (error) {
1698
- if (ipc.canUseSimpleErrorResponse) {
1699
- return getErrorResponseSimple(message.id, error);
1700
- }
1701
- return getErrorResponse(message.id, error, preparePrettyError, logError);
1702
- }
1703
- };
1704
- const defaultPreparePrettyError = error => {
1705
- return error;
1706
- };
1707
- const defaultLogError = () => {
1708
- // ignore
1574
+
1575
+ const SetText = 1;
1576
+ const Replace = 2;
1577
+ const SetAttribute = 3;
1578
+ const RemoveAttribute = 4;
1579
+ const Add = 6;
1580
+ const NavigateChild = 7;
1581
+ const NavigateParent = 8;
1582
+ const RemoveChild = 9;
1583
+ const NavigateSibling = 10;
1584
+ const SetReferenceNodeUid = 11;
1585
+ const MultiNavigation = 18;
1586
+
1587
+ const isKey = key => {
1588
+ return key !== 'type' && key !== 'childCount';
1709
1589
  };
1710
- const defaultRequiresSocket = () => {
1711
- return false;
1590
+
1591
+ const getKeys = node => {
1592
+ const keys = Object.keys(node).filter(isKey);
1593
+ return keys;
1712
1594
  };
1713
- const defaultResolve = resolve;
1714
1595
 
1715
- // TODO maybe remove this in v6 or v7, only accept options object to simplify the code
1716
- const normalizeParams = args => {
1717
- if (args.length === 1) {
1718
- const options = args[0];
1596
+ const arrayToTree = nodes => {
1597
+ const result = [];
1598
+ let i = 0;
1599
+ while (i < nodes.length) {
1600
+ const node = nodes[i];
1601
+ const {
1602
+ children,
1603
+ nodesConsumed
1604
+ } = getChildrenWithCount(nodes, i + 1, node.childCount || 0);
1605
+ result.push({
1606
+ node,
1607
+ children
1608
+ });
1609
+ i += 1 + nodesConsumed;
1610
+ }
1611
+ return result;
1612
+ };
1613
+ const getChildrenWithCount = (nodes, startIndex, childCount) => {
1614
+ if (childCount === 0) {
1719
1615
  return {
1720
- execute: options.execute,
1721
- ipc: options.ipc,
1722
- logError: options.logError || defaultLogError,
1723
- message: options.message,
1724
- preparePrettyError: options.preparePrettyError || defaultPreparePrettyError,
1725
- requiresSocket: options.requiresSocket || defaultRequiresSocket,
1726
- resolve: options.resolve || defaultResolve
1616
+ children: [],
1617
+ nodesConsumed: 0
1727
1618
  };
1728
1619
  }
1620
+ const children = [];
1621
+ let i = startIndex;
1622
+ let remaining = childCount;
1623
+ let totalConsumed = 0;
1624
+ while (remaining > 0 && i < nodes.length) {
1625
+ const node = nodes[i];
1626
+ const nodeChildCount = node.childCount || 0;
1627
+ const {
1628
+ children: nodeChildren,
1629
+ nodesConsumed
1630
+ } = getChildrenWithCount(nodes, i + 1, nodeChildCount);
1631
+ children.push({
1632
+ node,
1633
+ children: nodeChildren
1634
+ });
1635
+ const nodeSize = 1 + nodesConsumed;
1636
+ i += nodeSize;
1637
+ totalConsumed += nodeSize;
1638
+ remaining--;
1639
+ }
1729
1640
  return {
1730
- execute: args[2],
1731
- ipc: args[0],
1732
- logError: args[5],
1733
- message: args[1],
1734
- preparePrettyError: args[4],
1735
- requiresSocket: args[6],
1736
- resolve: args[3]
1641
+ children,
1642
+ nodesConsumed: totalConsumed
1737
1643
  };
1738
1644
  };
1739
- const handleJsonRpcMessage = async (...args) => {
1740
- const options = normalizeParams(args);
1741
- const {
1742
- execute,
1743
- ipc,
1744
- logError,
1745
- message,
1746
- preparePrettyError,
1747
- requiresSocket,
1748
- resolve
1749
- } = options;
1750
- if ('id' in message) {
1751
- if ('method' in message) {
1752
- const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
1753
- try {
1754
- ipc.send(response);
1755
- } catch (error) {
1756
- const errorResponse = getErrorResponse(message.id, error, preparePrettyError, logError);
1757
- ipc.send(errorResponse);
1758
- }
1759
- return;
1760
- }
1761
- resolve(message.id, message);
1645
+
1646
+ const isNavigationPatch = patch => {
1647
+ switch (patch.type) {
1648
+ case NavigateChild:
1649
+ case NavigateParent:
1650
+ case NavigateSibling:
1651
+ return true;
1652
+ default:
1653
+ return false;
1654
+ }
1655
+ };
1656
+ const getNavigationIndex = patch => {
1657
+ switch (patch.type) {
1658
+ case NavigateChild:
1659
+ case NavigateSibling:
1660
+ return patch.index;
1661
+ default:
1662
+ return 0;
1663
+ }
1664
+ };
1665
+ const appendNavigationPatch = (patches, type, index) => {
1666
+ const previousPatch = patches.at(-1);
1667
+ if (!previousPatch) {
1668
+ patches.push(type === NavigateParent ? {
1669
+ type
1670
+ } : {
1671
+ index,
1672
+ type
1673
+ });
1762
1674
  return;
1763
1675
  }
1764
- if ('method' in message) {
1765
- await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
1676
+ if (previousPatch.type === MultiNavigation) {
1677
+ previousPatch.navigations.push(type, index);
1766
1678
  return;
1767
1679
  }
1768
- throw new JsonRpcError('unexpected message');
1680
+ if (isNavigationPatch(previousPatch)) {
1681
+ patches[patches.length - 1] = {
1682
+ navigations: [previousPatch.type, getNavigationIndex(previousPatch), type, index],
1683
+ type: MultiNavigation
1684
+ };
1685
+ return;
1686
+ }
1687
+ patches.push(type === NavigateParent ? {
1688
+ type
1689
+ } : {
1690
+ index,
1691
+ type
1692
+ });
1769
1693
  };
1770
1694
 
1771
- const Two = '2.0';
1695
+ const compareNodes = (oldNode, newNode) => {
1696
+ // Check if node type changed - return null to signal incompatible nodes
1697
+ // (caller should handle this with a Replace operation)
1698
+ if (oldNode.type !== newNode.type) {
1699
+ return null;
1700
+ }
1701
+ const patches = [];
1702
+ // Handle reference nodes - special handling for uid changes
1703
+ if (oldNode.type === Reference && oldNode.uid !== newNode.uid) {
1704
+ patches.push({
1705
+ type: SetReferenceNodeUid,
1706
+ uid: newNode.uid
1707
+ });
1708
+ }
1709
+ // Handle text nodes
1710
+ if (oldNode.type === Text && newNode.type === Text) {
1711
+ if (oldNode.text !== newNode.text) {
1712
+ patches.push({
1713
+ type: SetText,
1714
+ value: newNode.text
1715
+ });
1716
+ }
1717
+ return patches;
1718
+ }
1719
+ // Compare attributes
1720
+ const oldKeys = getKeys(oldNode).filter(key => oldNode.type !== Reference || key !== 'uid');
1721
+ const newKeys = getKeys(newNode).filter(key => newNode.type !== Reference || key !== 'uid');
1722
+ // Check for attribute changes
1723
+ for (const key of newKeys) {
1724
+ if (oldNode[key] !== newNode[key]) {
1725
+ patches.push({
1726
+ type: SetAttribute,
1727
+ key,
1728
+ value: newNode[key]
1729
+ });
1730
+ }
1731
+ }
1732
+ // Check for removed attributes
1733
+ for (const key of oldKeys) {
1734
+ if (!Object.hasOwn(newNode, key)) {
1735
+ patches.push({
1736
+ type: RemoveAttribute,
1737
+ key
1738
+ });
1739
+ }
1740
+ }
1741
+ return patches;
1742
+ };
1772
1743
 
1773
- const create$7 = (method, params) => {
1774
- return {
1775
- jsonrpc: Two,
1776
- method,
1777
- params
1778
- };
1744
+ const treeToArray = node => {
1745
+ const result = [];
1746
+ const stack = [node];
1747
+ while (stack.length > 0) {
1748
+ const current = stack.pop();
1749
+ result.push(current.node);
1750
+ for (let i = current.children.length - 1; i >= 0; i--) {
1751
+ stack.push(current.children[i]);
1752
+ }
1753
+ }
1754
+ return result;
1779
1755
  };
1780
1756
 
1781
- const create$6 = (id, method, params) => {
1782
- const message = {
1783
- id,
1784
- jsonrpc: Two,
1785
- method,
1786
- params
1787
- };
1788
- return message;
1757
+ const navigateToChild = (patches, currentChildIndex, index) => {
1758
+ if (currentChildIndex === -1) {
1759
+ appendNavigationPatch(patches, NavigateChild, index);
1760
+ return index;
1761
+ }
1762
+ if (currentChildIndex !== index) {
1763
+ appendNavigationPatch(patches, NavigateSibling, index);
1764
+ }
1765
+ return index;
1766
+ };
1767
+ const navigateToParent = (patches, currentChildIndex) => {
1768
+ if (currentChildIndex >= 0) {
1769
+ appendNavigationPatch(patches, NavigateParent, 0);
1770
+ }
1771
+ return -1;
1772
+ };
1773
+ const addTree = (newNode, patches) => {
1774
+ patches.push({
1775
+ type: Add,
1776
+ nodes: treeToArray(newNode)
1777
+ });
1778
+ };
1779
+ const replaceTree = (newNode, patches) => {
1780
+ patches.push({
1781
+ type: Replace,
1782
+ nodes: treeToArray(newNode)
1783
+ });
1784
+ };
1785
+ const appendPatch = (patches, patch) => {
1786
+ switch (patch.type) {
1787
+ case MultiNavigation:
1788
+ for (let i = 0; i < patch.navigations.length; i += 2) {
1789
+ appendNavigationPatch(patches, patch.navigations[i], patch.navigations[i + 1]);
1790
+ }
1791
+ return;
1792
+ case NavigateChild:
1793
+ case NavigateSibling:
1794
+ appendNavigationPatch(patches, patch.type, patch.index);
1795
+ return;
1796
+ case NavigateParent:
1797
+ appendNavigationPatch(patches, patch.type, 0);
1798
+ return;
1799
+ default:
1800
+ patches.push(patch);
1801
+ }
1789
1802
  };
1790
-
1791
- let id = 0;
1792
- const create$5 = () => {
1793
- return ++id;
1803
+ const appendPatches = (patches, newPatches) => {
1804
+ for (const patch of newPatches) {
1805
+ appendPatch(patches, patch);
1806
+ }
1794
1807
  };
1795
-
1796
- const registerPromise = map => {
1797
- const id = create$5();
1798
- const {
1799
- promise,
1800
- resolve
1801
- } = Promise.withResolvers();
1802
- map[id] = resolve;
1803
- return {
1804
- id,
1805
- promise
1806
- };
1808
+ const diffExistingChild = (oldNode, newNode, patches, currentChildIndex, index) => {
1809
+ const nodePatches = compareNodes(oldNode.node, newNode.node);
1810
+ if (nodePatches === null) {
1811
+ const nextChildIndex = navigateToChild(patches, currentChildIndex, index);
1812
+ replaceTree(newNode, patches);
1813
+ return nextChildIndex;
1814
+ }
1815
+ const hasChildrenToCompare = oldNode.children.length > 0 || newNode.children.length > 0;
1816
+ const childPatches = [];
1817
+ if (hasChildrenToCompare) {
1818
+ diffChildren(oldNode.children, newNode.children, childPatches);
1819
+ }
1820
+ if (nodePatches.length === 0 && childPatches.length === 0) {
1821
+ return currentChildIndex;
1822
+ }
1823
+ const nextChildIndex = navigateToChild(patches, currentChildIndex, index);
1824
+ patches.push(...nodePatches);
1825
+ appendPatches(patches, childPatches);
1826
+ return nextChildIndex;
1807
1827
  };
1808
-
1809
- const invokeHelper = async (callbacks, ipc, method, params, useSendAndTransfer) => {
1810
- const {
1811
- id,
1812
- promise
1813
- } = registerPromise(callbacks);
1814
- const message = create$6(id, method, params);
1815
- if (useSendAndTransfer && ipc.sendAndTransfer) {
1816
- ipc.sendAndTransfer(message);
1817
- } else {
1818
- ipc.send(message);
1828
+ const diffRootNode = (oldNode, newNode, patches) => {
1829
+ const nodePatches = compareNodes(oldNode.node, newNode.node);
1830
+ if (nodePatches === null) {
1831
+ replaceTree(newNode, patches);
1832
+ return;
1833
+ }
1834
+ if (nodePatches.length > 0) {
1835
+ patches.push(...nodePatches);
1836
+ }
1837
+ if (oldNode.children.length > 0 || newNode.children.length > 0) {
1838
+ diffChildren(oldNode.children, newNode.children, patches);
1819
1839
  }
1820
- const responseMessage = await promise;
1821
- return unwrapJsonRpcResult(responseMessage);
1822
1840
  };
1823
- const createRpc = ipc => {
1824
- const callbacks = Object.create(null);
1825
- ipc._resolve = (id, response) => {
1826
- const fn = callbacks[id];
1827
- if (!fn) {
1828
- console.warn(`callback ${id} may already be disposed`);
1829
- return;
1841
+ const diffChildren = (oldChildren, newChildren, patches) => {
1842
+ const maxLength = Math.max(oldChildren.length, newChildren.length);
1843
+ let currentChildIndex = -1;
1844
+ const indicesToRemove = [];
1845
+ for (let i = 0; i < maxLength; i++) {
1846
+ const oldNode = oldChildren[i];
1847
+ const newNode = newChildren[i];
1848
+ if (!oldNode && !newNode) {
1849
+ continue;
1830
1850
  }
1831
- fn(response);
1832
- delete callbacks[id];
1833
- };
1834
- const rpc = {
1835
- async dispose() {
1836
- await ipc?.dispose();
1837
- },
1838
- invoke(method, ...params) {
1839
- return invokeHelper(callbacks, ipc, method, params, false);
1840
- },
1841
- invokeAndTransfer(method, ...params) {
1842
- return invokeHelper(callbacks, ipc, method, params, true);
1843
- },
1844
- // @ts-ignore
1845
- ipc,
1846
- /**
1847
- * @deprecated
1848
- */
1849
- send(method, ...params) {
1850
- const message = create$7(method, params);
1851
- ipc.send(message);
1851
+ if (!oldNode) {
1852
+ currentChildIndex = navigateToParent(patches, currentChildIndex);
1853
+ addTree(newNode, patches);
1854
+ continue;
1852
1855
  }
1853
- };
1854
- return rpc;
1855
- };
1856
-
1857
- const requiresSocket = () => {
1858
- return false;
1859
- };
1860
- const preparePrettyError = error => {
1861
- return error;
1862
- };
1863
- const logError = () => {
1864
- // handled by renderer worker
1856
+ if (!newNode) {
1857
+ indicesToRemove.push(i);
1858
+ continue;
1859
+ }
1860
+ currentChildIndex = diffExistingChild(oldNode, newNode, patches, currentChildIndex, i);
1861
+ }
1862
+ navigateToParent(patches, currentChildIndex);
1863
+ for (let j = indicesToRemove.length - 1; j >= 0; j--) {
1864
+ patches.push({
1865
+ type: RemoveChild,
1866
+ index: indicesToRemove[j]
1867
+ });
1868
+ }
1865
1869
  };
1866
- const handleMessage = event => {
1867
- if (event.data === 'ready') {
1868
- return Promise.resolve();
1870
+ const diffTrees = (oldTree, newTree, patches, path) => {
1871
+ if (path.length === 0 && oldTree.length === 1 && newTree.length === 1) {
1872
+ diffRootNode(oldTree[0], newTree[0], patches);
1873
+ return;
1869
1874
  }
1870
- const actualRequiresSocket = event?.target?.requiresSocket || requiresSocket;
1871
- const actualExecute = event?.target?.execute || execute;
1872
- return handleJsonRpcMessage(event.target, event.data, actualExecute, event.target._resolve, preparePrettyError, logError, actualRequiresSocket);
1875
+ diffChildren(oldTree, newTree, patches);
1873
1876
  };
1874
1877
 
1875
- const handleIpc = ipc => {
1876
- if ('addEventListener' in ipc) {
1877
- ipc.addEventListener('message', handleMessage);
1878
- } else if ('on' in ipc) {
1879
- // deprecated
1880
- ipc.on('message', handleMessage);
1878
+ const removeTrailingNavigationPatches = patches => {
1879
+ while (patches.length > 0) {
1880
+ const patch = patches.at(-1);
1881
+ if (patch.type !== NavigateChild && patch.type !== NavigateParent && patch.type !== NavigateSibling && patch.type !== MultiNavigation) {
1882
+ break;
1883
+ }
1884
+ patches.pop();
1881
1885
  }
1886
+ return patches;
1882
1887
  };
1883
1888
 
1884
- const listen$1 = async (module, options) => {
1885
- const rawIpc = await module.listen(options);
1886
- if (module.signal) {
1887
- module.signal(rawIpc);
1888
- }
1889
- const ipc = module.wrap(rawIpc);
1890
- return ipc;
1889
+ const diffTree = (oldNodes, newNodes) => {
1890
+ // Step 1: Convert flat arrays to tree structures
1891
+ const oldTree = arrayToTree(oldNodes);
1892
+ const newTree = arrayToTree(newNodes);
1893
+ // Step 3: Compare the trees
1894
+ const patches = [];
1895
+ diffTrees(oldTree, newTree, patches, []);
1896
+ // Remove trailing navigation patches since they serve no purpose
1897
+ return removeTrailingNavigationPatches(patches);
1891
1898
  };
1892
1899
 
1893
- const createSharedLazyRpc = factory => {
1894
- let rpcPromise;
1895
- const getOrCreate = () => {
1896
- if (!rpcPromise) {
1897
- rpcPromise = factory();
1898
- }
1899
- return rpcPromise;
1900
- };
1901
- return {
1902
- async dispose() {
1903
- const rpc = await getOrCreate();
1904
- await rpc.dispose();
1905
- },
1906
- async invoke(method, ...params) {
1907
- const rpc = await getOrCreate();
1908
- return rpc.invoke(method, ...params);
1909
- },
1910
- async invokeAndTransfer(method, ...params) {
1911
- const rpc = await getOrCreate();
1912
- return rpc.invokeAndTransfer(method, ...params);
1913
- },
1914
- async send(method, ...params) {
1915
- const rpc = await getOrCreate();
1916
- rpc.send(method, ...params);
1917
- }
1900
+ const HandleContextMenu = 2;
1901
+ const HandleClick = 11;
1902
+
1903
+ const ProblemsErrorIcon = 'ProblemsErrorIcon';
1904
+ const ProblemsWarningIcon = 'ProblemsWarningIcon';
1905
+ const StatusBarItem = 'StatusBarItem';
1906
+ const StatusBarItemsLeft = 'StatusBarItemsLeft';
1907
+ const StatusBarItemsRight = 'StatusBarItemsRight';
1908
+
1909
+ const getTextVirtualDom = (element, name) => {
1910
+ return [{
1911
+ childCount: 1,
1912
+ className: 'StatusBarItemLabel',
1913
+ name,
1914
+ type: Span
1915
+ }, text(element.value)];
1916
+ };
1917
+ const getIconVirtualDom = (element, name) => {
1918
+ return [{
1919
+ childCount: 0,
1920
+ className: mergeClassNames(MaskIcon, 'StatusBarIcon', element.value, element.spinning ? 'Spinning' : ''),
1921
+ name,
1922
+ type: Div
1923
+ }];
1924
+ };
1925
+ const getProgressVirtualDom = (element, name) => {
1926
+ const node = {
1927
+ ariaLabel: element.ariaLabel,
1928
+ className: 'StatusBarItemProgress',
1929
+ max: element.max,
1930
+ name,
1931
+ type: Progress
1918
1932
  };
1933
+ if (element.value !== undefined) {
1934
+ return [{
1935
+ ...node,
1936
+ value: element.value
1937
+ }];
1938
+ }
1939
+ return [node];
1919
1940
  };
1920
-
1921
- const create$4 = async ({
1922
- commandMap,
1923
- isMessagePortOpen = true,
1924
- messagePort
1925
- }) => {
1926
- // TODO create a commandMap per rpc instance
1927
- register(commandMap);
1928
- const rawIpc = await IpcParentWithMessagePort$1.create({
1929
- isMessagePortOpen,
1930
- messagePort
1931
- });
1932
- const ipc = IpcParentWithMessagePort$1.wrap(rawIpc);
1933
- handleIpc(ipc);
1934
- const rpc = createRpc(ipc);
1935
- messagePort.start();
1936
- return rpc;
1941
+ const getStatusBarItemElementVirtualDom = (element, name) => {
1942
+ if (element.type === 'text') {
1943
+ return getTextVirtualDom(element, name);
1944
+ }
1945
+ if (element.type === 'icon') {
1946
+ return getIconVirtualDom(element, name);
1947
+ }
1948
+ if (element.type === 'progress') {
1949
+ return getProgressVirtualDom(element, name);
1950
+ }
1951
+ return [];
1937
1952
  };
1938
1953
 
1939
- const create$3 = async ({
1940
- commandMap,
1941
- isMessagePortOpen,
1942
- send
1943
- }) => {
1954
+ const getStatusBarItemVirtualDom = statusBarItem => {
1944
1955
  const {
1945
- port1,
1946
- port2
1947
- } = new MessageChannel();
1948
- await send(port1);
1949
- return create$4({
1950
- commandMap,
1951
- isMessagePortOpen,
1952
- messagePort: port2
1953
- });
1956
+ ariaLabel,
1957
+ elements,
1958
+ name,
1959
+ tooltip
1960
+ } = statusBarItem;
1961
+ const elementNodes = elements.flatMap(element => getStatusBarItemElementVirtualDom(element, name));
1962
+ const buttonNode = {
1963
+ ariaLabel,
1964
+ childCount: elements.length,
1965
+ className: StatusBarItem,
1966
+ name,
1967
+ tabIndex: -1,
1968
+ title: tooltip,
1969
+ type: Button$1
1970
+ };
1971
+ return [buttonNode, ...elementNodes];
1954
1972
  };
1955
1973
 
1956
- const create$2 = async ({
1957
- commandMap,
1958
- isMessagePortOpen,
1959
- send
1960
- }) => {
1961
- return createSharedLazyRpc(() => {
1962
- return create$3({
1963
- commandMap,
1964
- isMessagePortOpen,
1965
- send
1966
- });
1967
- });
1974
+ const getStatusBarItemsVirtualDom = (items, className) => {
1975
+ if (items.length === 0) {
1976
+ return [];
1977
+ }
1978
+ return [{
1979
+ childCount: items.length,
1980
+ className,
1981
+ type: Div
1982
+ }, ...items.flatMap(getStatusBarItemVirtualDom)];
1968
1983
  };
1969
1984
 
1970
- const create$1 = async ({
1971
- commandMap
1972
- }) => {
1973
- // TODO create a commandMap per rpc instance
1974
- register(commandMap);
1975
- const ipc = await listen$1(IpcChildWithModuleWorkerAndMessagePort$1);
1976
- handleIpc(ipc);
1977
- const rpc = createRpc(ipc);
1978
- return rpc;
1985
+ const emptyStatusBarItemsLeftDom = [{
1986
+ childCount: 0,
1987
+ className: StatusBarItemsLeft,
1988
+ type: Div
1989
+ }];
1990
+ const getStatusBarItemsLeftDom = statusBarItemsLeft => {
1991
+ if (statusBarItemsLeft.length === 0) {
1992
+ return emptyStatusBarItemsLeftDom;
1993
+ }
1994
+ return getStatusBarItemsVirtualDom(statusBarItemsLeft, StatusBarItemsLeft);
1979
1995
  };
1980
1996
 
1981
- const createMockRpc = ({
1982
- commandMap
1983
- }) => {
1984
- const invocations = [];
1985
- const invoke = (method, ...params) => {
1986
- invocations.push([method, ...params]);
1987
- const command = commandMap[method];
1988
- if (!command) {
1989
- throw new Error(`command ${method} not found`);
1990
- }
1991
- return command(...params);
1992
- };
1993
- const mockRpc = {
1994
- invocations,
1995
- invoke,
1996
- invokeAndTransfer: invoke
1997
- };
1998
- return mockRpc;
1997
+ const getStatusBarItemsRightDom = statusBarItemsRight => {
1998
+ return getStatusBarItemsVirtualDom(statusBarItemsRight, StatusBarItemsRight);
1999
1999
  };
2000
2000
 
2001
- const rpcs = Object.create(null);
2002
- const set$7 = (id, rpc) => {
2003
- rpcs[id] = rpc;
2004
- };
2005
- const get$3 = id => {
2006
- return rpcs[id];
2001
+ const Focusable = 0;
2002
+
2003
+ const getChildCount = rightCount => {
2004
+ return rightCount > 0 ? 2 : 1;
2007
2005
  };
2008
- const remove = id => {
2009
- delete rpcs[id];
2006
+ const getStatusBarVirtualDom = (statusBarItemsLeft, statusBarItemsRight) => {
2007
+ const dom = [{
2008
+ ariaLive: 'off',
2009
+ ariaRoleDescription: 'Status Bar',
2010
+ childCount: getChildCount(statusBarItemsRight.length),
2011
+ className: 'StatusBar',
2012
+ onClick: HandleClick,
2013
+ onContextMenu: HandleContextMenu,
2014
+ role: Status,
2015
+ tabIndex: Focusable,
2016
+ type: Div
2017
+ }, ...getStatusBarItemsLeftDom(statusBarItemsLeft), ...getStatusBarItemsRightDom(statusBarItemsRight)];
2018
+ return dom;
2010
2019
  };
2011
2020
 
2012
- /* eslint-disable @typescript-eslint/explicit-function-return-type */
2013
- const create = rpcId => {
2014
- return {
2015
- async dispose() {
2016
- const rpc = get$3(rpcId);
2017
- await rpc.dispose();
2018
- },
2019
- // @ts-ignore
2020
- invoke(method, ...params) {
2021
- const rpc = get$3(rpcId);
2022
- // @ts-ignore
2023
- return rpc.invoke(method, ...params);
2024
- },
2025
- // @ts-ignore
2026
- invokeAndTransfer(method, ...params) {
2027
- const rpc = get$3(rpcId);
2028
- // @ts-ignore
2029
- return rpc.invokeAndTransfer(method, ...params);
2030
- },
2031
- registerMockRpc(commandMap) {
2032
- const mockRpc = createMockRpc({
2033
- commandMap
2034
- });
2035
- set$7(rpcId, mockRpc);
2036
- // @ts-ignore
2037
- mockRpc[Symbol.dispose] = () => {
2038
- remove(rpcId);
2039
- };
2040
- // @ts-ignore
2041
- return mockRpc;
2042
- },
2043
- set(rpc) {
2044
- set$7(rpcId, rpc);
2045
- }
2046
- };
2021
+ const renderItems = (oldState, newState) => {
2022
+ const {
2023
+ uid,
2024
+ visibleStatusBarItemsLeft,
2025
+ visibleStatusBarItemsRight
2026
+ } = newState;
2027
+ const dom = getStatusBarVirtualDom(visibleStatusBarItemsLeft, visibleStatusBarItemsRight);
2028
+ return [SetDom2, uid, dom];
2047
2029
  };
2048
2030
 
2049
- const {
2050
- invoke: invoke$5,
2051
- set: set$6
2052
- } = create(ExtensionManagementWorker);
2031
+ const getComponentDom = uid => {
2032
+ const state = getComponentState(uid);
2033
+ return renderItems(state, state)[2];
2034
+ };
2053
2035
 
2054
- const {
2055
- invoke: invoke$4,
2056
- set: set$5
2057
- } = create(RendererProcess);
2036
+ const getMatchingItemInternal = (items, name) => {
2037
+ for (const item of items) {
2038
+ if (item.name === name) {
2039
+ return item;
2040
+ }
2041
+ }
2042
+ return undefined;
2043
+ };
2044
+ const getMatchingItem = (itemsLeft, itemsRight, name) => {
2045
+ return getMatchingItemInternal(itemsLeft, name) ?? getMatchingItemInternal(itemsRight, name);
2046
+ };
2058
2047
 
2059
- const {
2060
- invoke: invoke$3,
2061
- set: set$4
2062
- } = create(TextMeasurementWorker);
2063
- const measureTextWidths$1 = async (texts, fontWeight, fontSize, fontFamily, letterSpacing, isMonoSpaceFont, charWidth) => {
2064
- return invoke$3('TextMeasurement.measureTextWidths', texts, fontWeight, fontSize, fontFamily, letterSpacing, isMonoSpaceFont, charWidth);
2048
+ const EditorEncoding$1 = 'EditorEncoding';
2049
+ const EditorEndOfLine$1 = 'EditorEndOfLine';
2050
+ const EditorIndentation = 'EditorIndentation';
2051
+ const EditorLanguage$1 = 'EditorLanguage';
2052
+ const EditorPosition$1 = 'EditorPosition';
2053
+ const Notifications$1 = 'Notifications';
2054
+ const Problems$1 = 'Problems';
2055
+ const isEditorStatus = name => {
2056
+ return [EditorEncoding$1, EditorEndOfLine$1, EditorIndentation, EditorLanguage$1, EditorPosition$1].includes(name);
2057
+ };
2058
+ const isRight = name => {
2059
+ return name === Notifications$1 || isEditorStatus(name);
2065
2060
  };
2066
2061
 
2067
- const {
2068
- invoke: invoke$2,
2069
- invokeAndTransfer,
2070
- set: set$3
2071
- } = create(RendererWorker);
2072
- const sendMessagePortToTextMeasurementWorker = async port => {
2073
- const command = 'TextMeasurement.handleMessagePort';
2074
- await invokeAndTransfer('SendMessagePortToExtensionHostWorker.sendMessagePortToTextMeasurementWorker', port, command, 0);
2062
+ const state$2 = {
2063
+ rpc: undefined
2075
2064
  };
2076
- const getPreference = async key => {
2077
- return await invoke$2('Preferences.get', key);
2065
+ const set$3 = rpc => {
2066
+ state$2.rpc = rpc;
2067
+ };
2068
+ const invoke$2 = (method, ...args) => {
2069
+ const {
2070
+ rpc
2071
+ } = state$2;
2072
+ return rpc.invoke(method, ...args);
2073
+ };
2074
+
2075
+ const handleClickEditorStatus = async (name, status) => {
2076
+ if (!status) {
2077
+ return;
2078
+ }
2079
+ switch (name) {
2080
+ case EditorEndOfLine$1:
2081
+ await invoke$2('QuickPick.openStatusBarPicker', 'end-of-line');
2082
+ return;
2083
+ case EditorIndentation:
2084
+ await invoke$2('QuickPick.openStatusBarPicker', 'indentation');
2085
+ return;
2086
+ case EditorLanguage$1:
2087
+ await invoke$2('QuickPick.openStatusBarPicker', 'language-mode');
2088
+ return;
2089
+ case EditorPosition$1:
2090
+ await invoke$2('QuickPick.openStatusBarPicker', 'go-to-line', status.line, status.column);
2091
+ return;
2092
+ }
2078
2093
  };
2079
2094
 
2080
2095
  const invokeExtensionCommand = (applicationId, command, ...args) => {
2081
2096
  if (applicationId !== undefined) {
2082
- return invoke$5('Extensions.invokeForApplication', applicationId, command, ...args);
2097
+ return invoke$6('Extensions.invokeForApplication', applicationId, command, ...args);
2083
2098
  }
2084
- return invoke$5(command, ...args);
2099
+ return invoke$6(command, ...args);
2085
2100
  };
2086
2101
 
2087
2102
  const handleClickExtensionStatusBarItem = async (name, applicationId) => {
@@ -2093,12 +2108,12 @@ const handleClickExtensionStatusBarItem = async (name, applicationId) => {
2093
2108
  };
2094
2109
 
2095
2110
  const handleClickNotification = async () => {
2096
- await invoke$2('Viewlet.openWidget', 'NotificationCenter');
2111
+ await invoke$3('Viewlet.openWidget', 'NotificationCenter');
2097
2112
  };
2098
2113
 
2099
2114
  const handleClickProblems = async () => {
2100
2115
  // @ts-ignore
2101
- await invoke$2('Layout.showPanel', 'Problems');
2116
+ await invoke$3('Layout.showPanel', 'Problems');
2102
2117
  };
2103
2118
 
2104
2119
  const handleClick = async (state, name) => {
@@ -2434,6 +2449,32 @@ const applyRender = (oldState, newState, diffResult) => {
2434
2449
  return commands;
2435
2450
  };
2436
2451
 
2452
+ const cacheName = 'lvce-status-bar-measurements-v1';
2453
+ const fontSize$1 = 12;
2454
+ const fontFamily$1 = 'system-ui, Ubuntu, Droid Sans, sans-serif';
2455
+ const getCacheKey = text => {
2456
+ const parameters = [text, 400, fontSize$1, fontFamily$1, 0, false, 0];
2457
+ return `/status-bar-measurements/v1/${encodeURIComponent(JSON.stringify(parameters))}`;
2458
+ };
2459
+ const isValidWidth = value => {
2460
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0;
2461
+ };
2462
+ const getWidth = async text => {
2463
+ try {
2464
+ const item = await getCacheStorageJsonItem(getCacheKey(text), cacheName);
2465
+ return item && isValidWidth(item.value) ? item.value : undefined;
2466
+ } catch {
2467
+ return undefined;
2468
+ }
2469
+ };
2470
+ const setWidth = async (text, width) => {
2471
+ try {
2472
+ await setCacheStorageJsonItem(getCacheKey(text), width, cacheName);
2473
+ } catch {
2474
+ // Cache writes are best-effort; measurements remain usable without persistence.
2475
+ }
2476
+ };
2477
+
2437
2478
  const fontSize = 12;
2438
2479
  const fontFamily = 'system-ui, Ubuntu, Droid Sans, sans-serif';
2439
2480
  const itemPaddingAndMargin = 16;
@@ -2446,11 +2487,31 @@ const measureTextWidths = async values => {
2446
2487
  if (values.length === 0) {
2447
2488
  return [];
2448
2489
  }
2490
+ const cachedWidths = await Promise.all(values.map(value => getWidth(value)));
2491
+ const missingValues = values.filter((_, index) => cachedWidths[index] === undefined);
2492
+ if (missingValues.length === 0) {
2493
+ return cachedWidths;
2494
+ }
2495
+ let measuredWidths;
2496
+ let measurementSucceeded = true;
2449
2497
  try {
2450
- return await measureTextWidths$1(values, 400, fontSize, fontFamily, 0, false, 0);
2498
+ measuredWidths = await measureTextWidths$1(missingValues, 400, fontSize, fontFamily, 0, false, 0);
2451
2499
  } catch {
2452
- return values.map(() => fallbackTextWidth);
2500
+ measurementSucceeded = false;
2501
+ measuredWidths = missingValues.map(() => fallbackTextWidth);
2453
2502
  }
2503
+ let measuredIndex = 0;
2504
+ const widths = cachedWidths.map(width => {
2505
+ if (width !== undefined) {
2506
+ return width;
2507
+ }
2508
+ const measuredWidth = measuredWidths[measuredIndex++];
2509
+ if (measurementSucceeded) {
2510
+ void setWidth(missingValues[measuredIndex - 1], measuredWidth);
2511
+ }
2512
+ return measuredWidth;
2513
+ });
2514
+ return widths;
2454
2515
  };
2455
2516
  const getElementWidth = (element, textWidths, textIndex) => {
2456
2517
  switch (element.type) {
@@ -2528,10 +2589,10 @@ const isConnected = () => {
2528
2589
  return connected;
2529
2590
  };
2530
2591
  const invoke = (method, ...params) => {
2531
- return invoke$4(method, ...params);
2592
+ return invoke$5(method, ...params);
2532
2593
  };
2533
2594
  const set$1 = rpc => {
2534
- set$5(rpc);
2595
+ set$7(rpc);
2535
2596
  state.connected = true;
2536
2597
  };
2537
2598
 
@@ -2542,20 +2603,20 @@ const renderDirect = async (uid, commands) => {
2542
2603
  return [...rendererWorkerCommands, ['Viewlet.commitPending', uid, transactionId]];
2543
2604
  };
2544
2605
  const render2 = async (uid, _diffResult) => {
2545
- let current = get$5(uid);
2606
+ let current = get$3(uid);
2546
2607
  let {
2547
2608
  newState
2548
2609
  } = current;
2549
2610
  while (true) {
2550
2611
  const measuredState = await getVisibleStatusBarItems(newState);
2551
- const latest = get$5(uid);
2612
+ const latest = get$3(uid);
2552
2613
  const {
2553
2614
  newState: latestState
2554
2615
  } = latest;
2555
2616
  if (latestState === newState) {
2556
2617
  current = latest;
2557
2618
  newState = measuredState;
2558
- set$9(uid, current.oldState, newState);
2619
+ set$4(uid, current.oldState, newState);
2559
2620
  break;
2560
2621
  }
2561
2622
  newState = latestState;
@@ -2570,7 +2631,7 @@ const render2 = async (uid, _diffResult) => {
2570
2631
  const commands = applyRender(oldState, newState, diffResult);
2571
2632
  // Advance synchronously: subsequent out-of-band updates must diff against
2572
2633
  // the DOM commands just generated, including updates that revert a value.
2573
- set$9(uid, newState, newState);
2634
+ set$4(uid, newState, newState);
2574
2635
  if (!isConnected()) {
2575
2636
  return commands;
2576
2637
  }
@@ -2583,7 +2644,7 @@ const renderOutOfBand = async uid => {
2583
2644
  }
2584
2645
  const {
2585
2646
  newState
2586
- } = get$5(uid);
2647
+ } = get$3(uid);
2587
2648
  if (newState.initial) {
2588
2649
  return;
2589
2650
  }
@@ -2608,7 +2669,7 @@ const handleEditorStatusChangedAll = async update => {
2608
2669
  const {
2609
2670
  newState,
2610
2671
  oldState
2611
- } = get$5(uid);
2672
+ } = get$3(uid);
2612
2673
  const newerState = isVisible() ? handleEditorStatusChanged(newState, editorStatus, previous) : {
2613
2674
  ...newState,
2614
2675
  editorStatus
@@ -2616,7 +2677,7 @@ const handleEditorStatusChangedAll = async update => {
2616
2677
  if (newState === newerState || oldState === newerState) {
2617
2678
  continue;
2618
2679
  }
2619
- set$9(uid, oldState, newerState);
2680
+ set$4(uid, oldState, newerState);
2620
2681
  changedUids.push(uid);
2621
2682
  }
2622
2683
  await Promise.all(changedUids.map(renderOutOfBand));
@@ -2652,12 +2713,12 @@ const handleEditorStatusVisibilityChangedAll = async visible => {
2652
2713
  const {
2653
2714
  newState,
2654
2715
  oldState
2655
- } = get$5(uid);
2716
+ } = get$3(uid);
2656
2717
  const newerState = handleEditorStatusVisibilityChanged(newState, visible);
2657
2718
  if (newState === newerState || oldState === newerState) {
2658
2719
  continue;
2659
2720
  }
2660
- set$9(uid, oldState, newerState);
2721
+ set$4(uid, oldState, newerState);
2661
2722
  changedUids.push(uid);
2662
2723
  }
2663
2724
  await Promise.all(changedUids.map(renderOutOfBand));
@@ -2823,7 +2884,7 @@ const toUiStatusBarItems = statusBarItems => {
2823
2884
 
2824
2885
  const getNotificationCount = async () => {
2825
2886
  try {
2826
- return await invoke$5('Extensions.getNotificationCount');
2887
+ return await invoke$6('Extensions.getNotificationCount');
2827
2888
  } catch {
2828
2889
  return 0;
2829
2890
  }
@@ -2897,15 +2958,15 @@ const handleExtensionManagementChange = async () => {
2897
2958
  const {
2898
2959
  newState,
2899
2960
  oldState
2900
- } = get$5(uid);
2961
+ } = get$3(uid);
2901
2962
  const newerState = await handleItemsChanged(newState);
2902
2963
  if (newState === newerState || oldState === newerState) {
2903
2964
  continue;
2904
2965
  }
2905
2966
  // Loading and other updates can finish while the provider query is pending.
2906
2967
  // Only replace the extension items; retain the current lifecycle and render baseline.
2907
- const current = get$5(uid);
2908
- set$9(uid, current.oldState, {
2968
+ const current = get$3(uid);
2969
+ set$4(uid, current.oldState, {
2909
2970
  ...current.newState,
2910
2971
  statusBarItemsLeft: newerState.statusBarItemsLeft
2911
2972
  });
@@ -2945,12 +3006,12 @@ const handleNotificationCountChangedAll = async count => {
2945
3006
  const {
2946
3007
  newState,
2947
3008
  oldState
2948
- } = get$5(uid);
3009
+ } = get$3(uid);
2949
3010
  const newerState = handleNotificationCountChanged(newState, count);
2950
3011
  if (newState === newerState || oldState === newerState) {
2951
3012
  continue;
2952
3013
  }
2953
- set$9(uid, oldState, newerState);
3014
+ set$4(uid, oldState, newerState);
2954
3015
  await renderOutOfBand(uid);
2955
3016
  }
2956
3017
  };
@@ -2961,11 +3022,11 @@ const commandMap$1 = {
2961
3022
  };
2962
3023
 
2963
3024
  const handleExtensionManagementMessagePort = async port => {
2964
- const rpc = await create$4({
3025
+ const rpc = await create$6({
2965
3026
  commandMap: commandMap$1,
2966
3027
  messagePort: port
2967
3028
  });
2968
- set$6(rpc);
3029
+ set$8(rpc);
2969
3030
  };
2970
3031
 
2971
3032
  const supportsEditorStatusDeltas = () => true;
@@ -2977,9 +3038,9 @@ const handleMessagePort = async (port, viewletCommandMap, setAsRendererProcess =
2977
3038
  throw new TypeError(`Viewlet command not found: ${command}`);
2978
3039
  }
2979
3040
  await fn(uid, ...args);
2980
- await invoke$2('Viewlet.requestRender', uid);
3041
+ await invoke$3('Viewlet.requestRender', uid);
2981
3042
  };
2982
- const rpc = await create$4({
3043
+ const rpc = await create$6({
2983
3044
  commandMap: {
2984
3045
  'StatusBar.handleEditorStatusChanged': handleEditorStatusChangedAll,
2985
3046
  'StatusBar.handleEditorStatusVisibilityChanged': handleEditorStatusVisibilityChangedAll,
@@ -3063,7 +3124,7 @@ const handleWorkspaceChange = async state => {
3063
3124
  assetDir,
3064
3125
  platform
3065
3126
  } = state;
3066
- await invoke$5('Extensions.activateByEvent', 'onStatusBarItem', assetDir, platform);
3127
+ await invoke$6('Extensions.activateByEvent', 'onStatusBarItem', assetDir, platform);
3067
3128
  return state;
3068
3129
  };
3069
3130
 
@@ -3255,7 +3316,7 @@ const handleWorkspaceChangeAndRefresh = async (uid, workspacePath) => {
3255
3316
  await refreshExtensionItems(uid);
3256
3317
  };
3257
3318
  const commandMap = {
3258
- 'StatusBar.create': create$9,
3319
+ 'StatusBar.create': create,
3259
3320
  'StatusBar.diff2': diff2,
3260
3321
  'StatusBar.getCommandIds': getCommandIds,
3261
3322
  'StatusBar.getComponentDom': getComponentDom,
@@ -3288,7 +3349,7 @@ const commandMap = {
3288
3349
  };
3289
3350
 
3290
3351
  const initializeMenuWorker = async () => {
3291
- const rpc = await create$2({
3352
+ const rpc = await create$4({
3292
3353
  commandMap: {},
3293
3354
  async send(port) {
3294
3355
  await invokeAndTransfer('SendMessagePortToExtensionHostWorker.sendMessagePortToMenuWorker', port);
@@ -3298,20 +3359,20 @@ const initializeMenuWorker = async () => {
3298
3359
  };
3299
3360
 
3300
3361
  const initializeQuickPickWorker = async () => {
3301
- const rpc = await create$2({
3362
+ const rpc = await create$4({
3302
3363
  commandMap: {},
3303
3364
  async send(port) {
3304
3365
  await invokeAndTransfer('SendMessagePortToExtensionHostWorker.sendMessagePortToQuickPickWorker', port, 'QuickPick.handleStatusBarMessagePort', 0);
3305
3366
  }
3306
3367
  });
3307
- set$8(rpc);
3368
+ set$3(rpc);
3308
3369
  };
3309
3370
 
3310
3371
  const initializeRenderWorker = async () => {
3311
- const rpc = await create$1({
3372
+ const rpc = await create$3({
3312
3373
  commandMap: commandMap
3313
3374
  });
3314
- set$3(rpc);
3375
+ set$5(rpc);
3315
3376
  };
3316
3377
 
3317
3378
  const send = port => {
@@ -3319,16 +3380,30 @@ const send = port => {
3319
3380
  return sendMessagePortToTextMeasurementWorker(port);
3320
3381
  };
3321
3382
  const initializeTextMeasurementWorkerRpc = async () => {
3322
- const rpc = await create$2({
3383
+ const rpc = await create$4({
3323
3384
  commandMap: {},
3324
3385
  send
3325
3386
  });
3326
- set$4(rpc);
3387
+ set$6(rpc);
3327
3388
  };
3328
3389
 
3390
+ const registerCacheWorker = async () => {
3391
+ const lazyRpc = await create$4({
3392
+ commandMap: {},
3393
+ async send(port) {
3394
+ try {
3395
+ await sendMessagePortToCacheWorker(port);
3396
+ } catch (error) {
3397
+ await registerCacheWorker();
3398
+ throw error;
3399
+ }
3400
+ }
3401
+ });
3402
+ set$9(lazyRpc);
3403
+ };
3329
3404
  const listen = async () => {
3330
3405
  registerCommands(commandMap);
3331
- await Promise.all([initializeRenderWorker(), initializeQuickPickWorker(), initializeMenuWorker(), initializeTextMeasurementWorkerRpc()]);
3406
+ await Promise.all([initializeRenderWorker(), initializeQuickPickWorker(), initializeMenuWorker(), initializeTextMeasurementWorkerRpc(), registerCacheWorker()]);
3332
3407
  };
3333
3408
 
3334
3409
  const main = async () => {