@lvce-editor/ports-view 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2551 @@
1
+ const normalizeLine = line => {
2
+ if (line.startsWith('Error: ')) {
3
+ return line.slice('Error: '.length);
4
+ }
5
+ if (line.startsWith('VError: ')) {
6
+ return line.slice('VError: '.length);
7
+ }
8
+ return line;
9
+ };
10
+ const getCombinedMessage = (error, message) => {
11
+ const stringifiedError = normalizeLine(`${error}`);
12
+ if (message) {
13
+ return `${message}: ${stringifiedError}`;
14
+ }
15
+ return stringifiedError;
16
+ };
17
+ const NewLine$2 = '\n';
18
+ const getNewLineIndex$1 = (string, startIndex = undefined) => {
19
+ return string.indexOf(NewLine$2, startIndex);
20
+ };
21
+ const mergeStacks = (parent, child) => {
22
+ if (!child) {
23
+ return parent;
24
+ }
25
+ const parentNewLineIndex = getNewLineIndex$1(parent);
26
+ const childNewLineIndex = getNewLineIndex$1(child);
27
+ if (childNewLineIndex === -1) {
28
+ return parent;
29
+ }
30
+ const parentFirstLine = parent.slice(0, parentNewLineIndex);
31
+ const childRest = child.slice(childNewLineIndex);
32
+ const childFirstLine = normalizeLine(child.slice(0, childNewLineIndex));
33
+ if (parentFirstLine.includes(childFirstLine)) {
34
+ return parentFirstLine + childRest;
35
+ }
36
+ return child;
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);
45
+ }
46
+ if (error.codeFrame) {
47
+ // @ts-ignore
48
+ this.codeFrame = error.codeFrame;
49
+ }
50
+ if (error.code) {
51
+ // @ts-ignore
52
+ this.code = error.code;
53
+ }
54
+ }
55
+ }
56
+
57
+ 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
+ }));
112
+ };
113
+ that.onMessage(handleMessage);
114
+ const handleClose = event => {
115
+ that.dispatchEvent(new Event('close'));
116
+ };
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: []
144
+ };
145
+ }
146
+ let lastIndex = index - 1;
147
+ while (++lastIndex < lines.length) {
148
+ if (!isNormalStackLine(lines[lastIndex])) {
149
+ break;
150
+ }
151
+ }
152
+ return {
153
+ actualMessage: lines[index - 1],
154
+ rest: lines.slice(index, lastIndex)
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];
183
+ return {
184
+ code: ERR_MODULE_NOT_FOUND,
185
+ message
186
+ };
187
+ };
188
+ const isModuleNotFoundError = stderr => {
189
+ if (!stderr) {
190
+ return false;
191
+ }
192
+ return stderr.includes('ERR_MODULE_NOT_FOUND');
193
+ };
194
+ const isModulesSyntaxError = stderr => {
195
+ if (!stderr) {
196
+ return false;
197
+ }
198
+ return stderr.includes('SyntaxError: Cannot use import statement outside a module');
199
+ };
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);
204
+ };
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
+ };
211
+ };
212
+ const getModuleSyntaxError = () => {
213
+ return {
214
+ code: E_MODULES_NOT_SUPPORTED_IN_ELECTRON,
215
+ message: `ES Modules are not supported in electron`
216
+ };
217
+ };
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);
229
+ const {
230
+ actualMessage,
231
+ rest
232
+ } = getDetails(lines);
233
+ return {
234
+ code: '',
235
+ message: actualMessage,
236
+ stack: rest
237
+ };
238
+ };
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;
270
+ }
271
+ }
272
+ const readyMessage = 'ready';
273
+ const getData$2 = event => {
274
+ return event.data;
275
+ };
276
+ const listen$7 = () => {
277
+ // @ts-ignore
278
+ if (typeof WorkerGlobalScope === 'undefined') {
279
+ throw new TypeError('module is not in web worker scope');
280
+ }
281
+ return globalThis;
282
+ };
283
+ const signal$8 = global => {
284
+ global.postMessage(readyMessage);
285
+ };
286
+ class IpcChildWithModuleWorker extends Ipc {
287
+ getData(event) {
288
+ return getData$2(event);
289
+ }
290
+ send(message) {
291
+ // @ts-ignore
292
+ this._rawIpc.postMessage(message);
293
+ }
294
+ sendAndTransfer(message) {
295
+ const transfer = getTransferrables(message);
296
+ // @ts-ignore
297
+ this._rawIpc.postMessage(message, transfer);
298
+ }
299
+ dispose() {
300
+ // ignore
301
+ }
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
319
+ });
320
+ const event = await promise;
321
+ // @ts-ignore
322
+ return event.data;
323
+ };
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');
331
+ }
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
338
+ });
339
+ parentIpc.dispose();
340
+ const port = firstMessage.params[1];
341
+ return port;
342
+ }
343
+ return globalThis;
344
+ };
345
+ class IpcChildWithModuleWorkerAndMessagePort extends Ipc {
346
+ getData(event) {
347
+ return getData$2(event);
348
+ }
349
+ send(message) {
350
+ this._rawIpc.postMessage(message);
351
+ }
352
+ sendAndTransfer(message) {
353
+ const transfer = getTransferrables(message);
354
+ this._rawIpc.postMessage(message, transfer);
355
+ }
356
+ dispose() {
357
+ if (this._rawIpc.close) {
358
+ this._rawIpc.close();
359
+ }
360
+ }
361
+ onClose(callback) {
362
+ // ignore
363
+ }
364
+ onMessage(callback) {
365
+ this._rawIpc.addEventListener('message', callback);
366
+ this._rawIpc.start();
367
+ }
368
+ }
369
+ const wrap$e = port => {
370
+ return new IpcChildWithModuleWorkerAndMessagePort(port);
371
+ };
372
+ const IpcChildWithModuleWorkerAndMessagePort$1 = {
373
+ __proto__: null,
374
+ listen: listen$6,
375
+ wrap: wrap$e
376
+ };
377
+
378
+ class CommandNotFoundError extends Error {
379
+ constructor(command) {
380
+ super(`Command not found ${command}`);
381
+ this.name = 'CommandNotFoundError';
382
+ }
383
+ }
384
+ const commands = Object.create(null);
385
+ const register = commandMap => {
386
+ Object.assign(commands, commandMap);
387
+ };
388
+ const getCommand = key => {
389
+ return commands[key];
390
+ };
391
+ const execute = (command, ...args) => {
392
+ const fn = getCommand(command);
393
+ if (!fn) {
394
+ throw new CommandNotFoundError(command);
395
+ }
396
+ return fn(...args);
397
+ };
398
+
399
+ const Two$1 = '2.0';
400
+ const callbacks = Object.create(null);
401
+ const get$2 = id => {
402
+ return callbacks[id];
403
+ };
404
+ const remove$1 = id => {
405
+ delete callbacks[id];
406
+ };
407
+ class JsonRpcError extends Error {
408
+ constructor(message) {
409
+ super(message);
410
+ this.name = 'JsonRpcError';
411
+ }
412
+ }
413
+ const NewLine = '\n';
414
+ const DomException = 'DOMException';
415
+ const ReferenceError$1 = 'ReferenceError';
416
+ const SyntaxError$1 = 'SyntaxError';
417
+ const TypeError$1 = 'TypeError';
418
+ const getErrorConstructor = (message, type) => {
419
+ if (type) {
420
+ switch (type) {
421
+ case DomException:
422
+ return DOMException;
423
+ case ReferenceError$1:
424
+ return ReferenceError;
425
+ case SyntaxError$1:
426
+ return SyntaxError;
427
+ case TypeError$1:
428
+ return TypeError;
429
+ default:
430
+ return Error;
431
+ }
432
+ }
433
+ if (message.startsWith('TypeError: ')) {
434
+ return TypeError;
435
+ }
436
+ if (message.startsWith('SyntaxError: ')) {
437
+ return SyntaxError;
438
+ }
439
+ if (message.startsWith('ReferenceError: ')) {
440
+ return ReferenceError;
441
+ }
442
+ return Error;
443
+ };
444
+ const constructError = (message, type, name) => {
445
+ const ErrorConstructor = getErrorConstructor(message, type);
446
+ if (ErrorConstructor === DOMException && name) {
447
+ return new ErrorConstructor(message, name);
448
+ }
449
+ if (ErrorConstructor === Error) {
450
+ const error = new Error(message);
451
+ if (name && name !== 'VError') {
452
+ Object.defineProperty(error, 'name', {
453
+ configurable: true,
454
+ value: name
455
+ });
456
+ }
457
+ return error;
458
+ }
459
+ return new ErrorConstructor(message);
460
+ };
461
+ const joinLines = lines => {
462
+ return lines.join(NewLine);
463
+ };
464
+ const splitLines = lines => {
465
+ return lines.split(NewLine);
466
+ };
467
+ const getCurrentStack = () => {
468
+ const stackLinesToSkip = 3;
469
+ const currentStack = joinLines(splitLines(new Error().stack || '').slice(stackLinesToSkip));
470
+ return currentStack;
471
+ };
472
+ const getNewLineIndex = (string, startIndex) => {
473
+ {
474
+ return string.indexOf(NewLine);
475
+ }
476
+ };
477
+ const getParentStack = error => {
478
+ let parentStack = error.stack || error.data || error.message || '';
479
+ if (parentStack.startsWith(' at')) {
480
+ parentStack = error.message + NewLine + parentStack;
481
+ }
482
+ return parentStack;
483
+ };
484
+ const MethodNotFound = -32601;
485
+ const Custom = -32001;
486
+ const setStack = (error, stack) => {
487
+ const descriptor = Object.getOwnPropertyDescriptor(error, 'stack');
488
+ if (descriptor) {
489
+ if (!descriptor.configurable && !descriptor.writable) {
490
+ return;
491
+ }
492
+ if (!descriptor.configurable && descriptor.writable) {
493
+ error.stack = stack;
494
+ return;
495
+ }
496
+ }
497
+ Object.defineProperty(error, 'stack', {
498
+ configurable: true,
499
+ value: stack,
500
+ writable: true
501
+ });
502
+ };
503
+ const restoreExistingError = (error, currentStack) => {
504
+ if (typeof error.stack === 'string') {
505
+ setStack(error, `${error.stack}${NewLine}${currentStack}`);
506
+ }
507
+ return error;
508
+ };
509
+ const restoreMethodNotFoundError = (error, currentStack) => {
510
+ const restoredError = new JsonRpcError(error.message);
511
+ Object.assign(restoredError, {
512
+ code: error.code
513
+ });
514
+ const parentStack = getParentStack(error);
515
+ setStack(restoredError, `${parentStack}${NewLine}${currentStack}`);
516
+ return restoredError;
517
+ };
518
+ const restoreStackFromData = (restoredError, error, currentStack) => {
519
+ if (error.data.stack && error.data.type && error.message) {
520
+ setStack(restoredError, `${error.data.type}: ${error.message}${NewLine}${error.data.stack}${NewLine}${currentStack}`);
521
+ return;
522
+ }
523
+ if (error.data.stack) {
524
+ setStack(restoredError, error.data.stack);
525
+ }
526
+ };
527
+ const applyDataProperties = (restoredError, error) => {
528
+ restoreStackFromData(restoredError, error, getCurrentStack());
529
+ if (error.data.codeFrame) {
530
+ // @ts-ignore
531
+ restoredError.codeFrame = error.data.codeFrame;
532
+ }
533
+ if (typeof error.data.code === 'string' || typeof error.data.code === 'number') {
534
+ // @ts-ignore
535
+ Object.defineProperty(restoredError, 'code', {
536
+ configurable: true,
537
+ value: error.data.code,
538
+ writable: true
539
+ });
540
+ }
541
+ if (error.data.type) {
542
+ // @ts-ignore
543
+ restoredError.name = error.data.type;
544
+ }
545
+ };
546
+ const applyDirectProperties = (restoredError, error) => {
547
+ if (error.stack) {
548
+ const lowerStack = restoredError.stack || '';
549
+ const indexNewLine = getNewLineIndex(lowerStack);
550
+ const parentStack = getParentStack(error);
551
+ // @ts-ignore
552
+ setStack(restoredError, `${parentStack}${lowerStack.slice(indexNewLine)}`);
553
+ }
554
+ if (error.codeFrame) {
555
+ // @ts-ignore
556
+ restoredError.codeFrame = error.codeFrame;
557
+ }
558
+ };
559
+ const restoreMessageError = (error, _currentStack) => {
560
+ const restoredError = constructError(error.message, error.type, error.name);
561
+ if (typeof error.code === 'string' || typeof error.code === 'number') {
562
+ Object.defineProperty(restoredError, 'code', {
563
+ configurable: true,
564
+ value: error.code,
565
+ writable: true
566
+ });
567
+ }
568
+ if (error.data) {
569
+ applyDataProperties(restoredError, error);
570
+ } else {
571
+ applyDirectProperties(restoredError, error);
572
+ }
573
+ return restoredError;
574
+ };
575
+ const restoreJsonRpcError = error => {
576
+ const currentStack = getCurrentStack();
577
+ if (error && error instanceof Error) {
578
+ return restoreExistingError(error, currentStack);
579
+ }
580
+ if (error && error.code && error.code === MethodNotFound) {
581
+ return restoreMethodNotFoundError(error, currentStack);
582
+ }
583
+ if (error && error.message) {
584
+ return restoreMessageError(error);
585
+ }
586
+ if (typeof error === 'string') {
587
+ return new Error(`JsonRpc Error: ${error}`);
588
+ }
589
+ return new Error(`JsonRpc Error: ${error}`);
590
+ };
591
+ const unwrapJsonRpcResult = responseMessage => {
592
+ if ('error' in responseMessage) {
593
+ const restoredError = restoreJsonRpcError(responseMessage.error);
594
+ throw restoredError;
595
+ }
596
+ if ('result' in responseMessage) {
597
+ return responseMessage.result;
598
+ }
599
+ throw new JsonRpcError('unexpected response message');
600
+ };
601
+ const warn = (...args) => {
602
+ console.warn(...args);
603
+ };
604
+ const resolve = (id, response) => {
605
+ const fn = get$2(id);
606
+ if (!fn) {
607
+ console.log(response);
608
+ warn(`callback ${id} may already be disposed`);
609
+ return;
610
+ }
611
+ fn(response);
612
+ remove$1(id);
613
+ };
614
+ const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
615
+ const getErrorType = prettyError => {
616
+ if (prettyError && prettyError.type) {
617
+ return prettyError.type;
618
+ }
619
+ if (prettyError && prettyError.constructor && prettyError.constructor.name) {
620
+ return prettyError.constructor.name;
621
+ }
622
+ return undefined;
623
+ };
624
+ const isAlreadyStack = line => {
625
+ return line.trim().startsWith('at ');
626
+ };
627
+ const getStack = prettyError => {
628
+ const stackString = prettyError.stack || '';
629
+ const newLineIndex = stackString.indexOf('\n');
630
+ if (newLineIndex !== -1 && !isAlreadyStack(stackString.slice(0, newLineIndex))) {
631
+ return stackString.slice(newLineIndex + 1);
632
+ }
633
+ return stackString;
634
+ };
635
+ const getErrorProperty = (error, prettyError) => {
636
+ if (error && error.code === E_COMMAND_NOT_FOUND) {
637
+ return {
638
+ code: MethodNotFound,
639
+ data: error.stack,
640
+ message: error.message
641
+ };
642
+ }
643
+ return {
644
+ code: Custom,
645
+ data: {
646
+ code: prettyError.code ?? error?.code,
647
+ codeFrame: prettyError.codeFrame,
648
+ name: prettyError.name,
649
+ stack: getStack(prettyError),
650
+ type: getErrorType(prettyError)
651
+ },
652
+ message: prettyError.message
653
+ };
654
+ };
655
+ const create$1$1 = (id, error) => {
656
+ return {
657
+ error,
658
+ id,
659
+ jsonrpc: Two$1
660
+ };
661
+ };
662
+ const getErrorResponse = (id, error, preparePrettyError, logError) => {
663
+ const prettyError = preparePrettyError(error);
664
+ logError(error, prettyError);
665
+ const errorProperty = getErrorProperty(error, prettyError);
666
+ return create$1$1(id, errorProperty);
667
+ };
668
+ const create$7 = (message, result) => {
669
+ return {
670
+ id: message.id,
671
+ jsonrpc: Two$1,
672
+ result: result ?? null
673
+ };
674
+ };
675
+ const getSuccessResponse = (message, result) => {
676
+ const resultProperty = result ?? null;
677
+ return create$7(message, resultProperty);
678
+ };
679
+ const getErrorResponseSimple = (id, error) => {
680
+ return {
681
+ error: {
682
+ code: Custom,
683
+ data: error instanceof Error ? {
684
+ ...error,
685
+ code: 'code' in error ? error.code : undefined,
686
+ stack: error.stack,
687
+ type: error.name
688
+ } : error,
689
+ // @ts-ignore
690
+ message: error.message
691
+ },
692
+ id,
693
+ jsonrpc: Two$1
694
+ };
695
+ };
696
+ const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
697
+ try {
698
+ const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
699
+ return getSuccessResponse(message, result);
700
+ } catch (error) {
701
+ if (ipc.canUseSimpleErrorResponse) {
702
+ return getErrorResponseSimple(message.id, error);
703
+ }
704
+ return getErrorResponse(message.id, error, preparePrettyError, logError);
705
+ }
706
+ };
707
+ const defaultPreparePrettyError = error => {
708
+ return error;
709
+ };
710
+ const defaultLogError = () => {
711
+ // ignore
712
+ };
713
+ const defaultRequiresSocket = () => {
714
+ return false;
715
+ };
716
+ const defaultResolve = resolve;
717
+
718
+ // TODO maybe remove this in v6 or v7, only accept options object to simplify the code
719
+ const normalizeParams = args => {
720
+ if (args.length === 1) {
721
+ const options = args[0];
722
+ return {
723
+ execute: options.execute,
724
+ ipc: options.ipc,
725
+ logError: options.logError || defaultLogError,
726
+ message: options.message,
727
+ preparePrettyError: options.preparePrettyError || defaultPreparePrettyError,
728
+ requiresSocket: options.requiresSocket || defaultRequiresSocket,
729
+ resolve: options.resolve || defaultResolve
730
+ };
731
+ }
732
+ return {
733
+ execute: args[2],
734
+ ipc: args[0],
735
+ logError: args[5],
736
+ message: args[1],
737
+ preparePrettyError: args[4],
738
+ requiresSocket: args[6],
739
+ resolve: args[3]
740
+ };
741
+ };
742
+ const handleJsonRpcMessage = async (...args) => {
743
+ const options = normalizeParams(args);
744
+ const {
745
+ execute,
746
+ ipc,
747
+ logError,
748
+ message,
749
+ preparePrettyError,
750
+ requiresSocket,
751
+ resolve
752
+ } = options;
753
+ if ('id' in message) {
754
+ if ('method' in message) {
755
+ const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
756
+ try {
757
+ ipc.send(response);
758
+ } catch (error) {
759
+ const errorResponse = getErrorResponse(message.id, error, preparePrettyError, logError);
760
+ ipc.send(errorResponse);
761
+ }
762
+ return;
763
+ }
764
+ resolve(message.id, message);
765
+ return;
766
+ }
767
+ if ('method' in message) {
768
+ await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
769
+ return;
770
+ }
771
+ throw new JsonRpcError('unexpected message');
772
+ };
773
+
774
+ const Two = '2.0';
775
+
776
+ const create$6 = (method, params) => {
777
+ return {
778
+ jsonrpc: Two,
779
+ method,
780
+ params
781
+ };
782
+ };
783
+
784
+ const create$5 = (id, method, params) => {
785
+ const message = {
786
+ id,
787
+ jsonrpc: Two,
788
+ method,
789
+ params
790
+ };
791
+ return message;
792
+ };
793
+
794
+ let id = 0;
795
+ const create$4 = () => {
796
+ return ++id;
797
+ };
798
+
799
+ const registerPromise = map => {
800
+ const id = create$4();
801
+ const {
802
+ promise,
803
+ resolve
804
+ } = Promise.withResolvers();
805
+ map[id] = resolve;
806
+ return {
807
+ id,
808
+ promise
809
+ };
810
+ };
811
+
812
+ const invokeHelper = async (callbacks, ipc, method, params, useSendAndTransfer) => {
813
+ const {
814
+ id,
815
+ promise
816
+ } = registerPromise(callbacks);
817
+ const message = create$5(id, method, params);
818
+ if (useSendAndTransfer && ipc.sendAndTransfer) {
819
+ ipc.sendAndTransfer(message);
820
+ } else {
821
+ ipc.send(message);
822
+ }
823
+ const responseMessage = await promise;
824
+ return unwrapJsonRpcResult(responseMessage);
825
+ };
826
+ const createRpc = ipc => {
827
+ const callbacks = Object.create(null);
828
+ ipc._resolve = (id, response) => {
829
+ const fn = callbacks[id];
830
+ if (!fn) {
831
+ console.warn(`callback ${id} may already be disposed`);
832
+ return;
833
+ }
834
+ fn(response);
835
+ delete callbacks[id];
836
+ };
837
+ const rpc = {
838
+ async dispose() {
839
+ await ipc?.dispose();
840
+ },
841
+ invoke(method, ...params) {
842
+ return invokeHelper(callbacks, ipc, method, params, false);
843
+ },
844
+ invokeAndTransfer(method, ...params) {
845
+ return invokeHelper(callbacks, ipc, method, params, true);
846
+ },
847
+ // @ts-ignore
848
+ ipc,
849
+ /**
850
+ * @deprecated
851
+ */
852
+ send(method, ...params) {
853
+ const message = create$6(method, params);
854
+ ipc.send(message);
855
+ }
856
+ };
857
+ return rpc;
858
+ };
859
+
860
+ const requiresSocket = () => {
861
+ return false;
862
+ };
863
+ const preparePrettyError = error => {
864
+ return error;
865
+ };
866
+ const logError = () => {
867
+ // handled by renderer worker
868
+ };
869
+ const handleMessage = event => {
870
+ const actualRequiresSocket = event?.target?.requiresSocket || requiresSocket;
871
+ const actualExecute = event?.target?.execute || execute;
872
+ return handleJsonRpcMessage(event.target, event.data, actualExecute, event.target._resolve, preparePrettyError, logError, actualRequiresSocket);
873
+ };
874
+
875
+ const handleIpc = ipc => {
876
+ if ('addEventListener' in ipc) {
877
+ ipc.addEventListener('message', handleMessage);
878
+ } else if ('on' in ipc) {
879
+ // deprecated
880
+ ipc.on('message', handleMessage);
881
+ }
882
+ };
883
+
884
+ const listen$1 = async (module, options) => {
885
+ const rawIpc = await module.listen(options);
886
+ if (module.signal) {
887
+ module.signal(rawIpc);
888
+ }
889
+ const ipc = module.wrap(rawIpc);
890
+ return ipc;
891
+ };
892
+
893
+ const create$3 = async ({
894
+ commandMap
895
+ }) => {
896
+ // TODO create a commandMap per rpc instance
897
+ register(commandMap);
898
+ const ipc = await listen$1(IpcChildWithModuleWorkerAndMessagePort$1);
899
+ handleIpc(ipc);
900
+ const rpc = createRpc(ipc);
901
+ return rpc;
902
+ };
903
+
904
+ const createMockRpc = ({
905
+ commandMap
906
+ }) => {
907
+ const invocations = [];
908
+ const invoke = (method, ...params) => {
909
+ invocations.push([method, ...params]);
910
+ const command = commandMap[method];
911
+ if (!command) {
912
+ throw new Error(`command ${method} not found`);
913
+ }
914
+ return command(...params);
915
+ };
916
+ const mockRpc = {
917
+ invocations,
918
+ invoke,
919
+ invokeAndTransfer: invoke
920
+ };
921
+ return mockRpc;
922
+ };
923
+
924
+ const rpcs = Object.create(null);
925
+ const set$2 = (id, rpc) => {
926
+ rpcs[id] = rpc;
927
+ };
928
+ const get$1 = id => {
929
+ return rpcs[id];
930
+ };
931
+ const remove = id => {
932
+ delete rpcs[id];
933
+ };
934
+
935
+ /* eslint-disable @typescript-eslint/explicit-function-return-type */
936
+ const create$2 = rpcId => {
937
+ return {
938
+ async dispose() {
939
+ const rpc = get$1(rpcId);
940
+ await rpc.dispose();
941
+ },
942
+ // @ts-ignore
943
+ invoke(method, ...params) {
944
+ const rpc = get$1(rpcId);
945
+ // @ts-ignore
946
+ return rpc.invoke(method, ...params);
947
+ },
948
+ // @ts-ignore
949
+ invokeAndTransfer(method, ...params) {
950
+ const rpc = get$1(rpcId);
951
+ // @ts-ignore
952
+ return rpc.invokeAndTransfer(method, ...params);
953
+ },
954
+ registerMockRpc(commandMap) {
955
+ const mockRpc = createMockRpc({
956
+ commandMap
957
+ });
958
+ set$2(rpcId, mockRpc);
959
+ // @ts-ignore
960
+ mockRpc[Symbol.dispose] = () => {
961
+ remove(rpcId);
962
+ };
963
+ // @ts-ignore
964
+ return mockRpc;
965
+ },
966
+ set(rpc) {
967
+ set$2(rpcId, rpc);
968
+ }
969
+ };
970
+ };
971
+
972
+ const Button = 1;
973
+ const Div = 4;
974
+ const Input = 6;
975
+ const Span = 8;
976
+ const Text = 12;
977
+ const A = 53;
978
+ const Reference = 100;
979
+
980
+ const ClientY = 'event.clientY';
981
+ const DeltaMode = 'event.deltaMode';
982
+ const DeltaY = 'event.deltaY';
983
+ const Key = 'event.key';
984
+ const TargetName = 'event.target.name';
985
+ const TargetValue = 'event.target.value';
986
+
987
+ const Backspace = 1;
988
+ const Enter = 3;
989
+ const Space = 9;
990
+ const End = 255;
991
+ const Home = 12;
992
+ const UpArrow = 14;
993
+ const DownArrow = 16;
994
+ const Delete = 18;
995
+ const KeyA = 29;
996
+
997
+ const Shift = 1 << 10 >>> 0;
998
+
999
+ const RendererWorker = 1;
1000
+
1001
+ const SetCss = 'Viewlet.setCss';
1002
+ const SetDom2 = 'Viewlet.setDom2';
1003
+ const SetFocusContext = 'Viewlet.setFocusContext';
1004
+ const SetPatches = 'Viewlet.setPatches';
1005
+
1006
+ const {
1007
+ invoke,
1008
+ set: set$1
1009
+ } = create$2(RendererWorker);
1010
+ const openUri = async (uri, focus, options) => {
1011
+ await invoke('Main.openUri', {
1012
+ ...options,
1013
+ focus,
1014
+ uri
1015
+ });
1016
+ };
1017
+
1018
+ const toCommandId = key => {
1019
+ const dotIndex = key.indexOf('.');
1020
+ return key.slice(dotIndex + 1);
1021
+ };
1022
+ const create$1 = () => {
1023
+ const commandQueues = new Map();
1024
+ const generations = Object.create(null);
1025
+ const states = Object.create(null);
1026
+ const commandMapRef = Object.create(null);
1027
+ const commandsById = Object.create(null);
1028
+ const getGeneration = uid => generations[uid] || 0;
1029
+ const isCurrentGeneration = (uid, generation) => {
1030
+ return states[uid] !== undefined && getGeneration(uid) === generation;
1031
+ };
1032
+ const updateState = (uid, generation, fallbackState, updater) => {
1033
+ if (!isCurrentGeneration(uid, generation)) {
1034
+ return Promise.resolve(fallbackState);
1035
+ }
1036
+ const current = states[uid];
1037
+ const updatedState = updater(current.newState);
1038
+ if (updatedState !== current.newState) {
1039
+ states[uid] = {
1040
+ newState: updatedState,
1041
+ oldState: current.oldState,
1042
+ scheduledState: updatedState
1043
+ };
1044
+ }
1045
+ return Promise.resolve(updatedState);
1046
+ };
1047
+ const createAsyncCommandContext = (uid, generation) => {
1048
+ let latestState = states[uid].newState;
1049
+ return {
1050
+ getState: () => {
1051
+ if (isCurrentGeneration(uid, generation)) {
1052
+ latestState = states[uid].newState;
1053
+ }
1054
+ return latestState;
1055
+ },
1056
+ updateState: async updater => {
1057
+ latestState = await updateState(uid, generation, latestState, updater);
1058
+ return latestState;
1059
+ }
1060
+ };
1061
+ };
1062
+ const enqueueCommand = async (uid, command) => {
1063
+ const previous = commandQueues.get(uid) || Promise.resolve();
1064
+ const run = async () => {
1065
+ try {
1066
+ await previous;
1067
+ } catch {
1068
+ // The previous caller receives its error; later commands must still run.
1069
+ }
1070
+ await command();
1071
+ };
1072
+ const current = run();
1073
+ commandQueues.set(uid, current);
1074
+ try {
1075
+ await current;
1076
+ } finally {
1077
+ if (commandQueues.get(uid) === current) {
1078
+ commandQueues.delete(uid);
1079
+ }
1080
+ }
1081
+ };
1082
+ return {
1083
+ clear() {
1084
+ commandQueues.clear();
1085
+ for (const key of Object.keys(states)) {
1086
+ delete states[key];
1087
+ }
1088
+ },
1089
+ createDirectEventCommandMap(requestRender) {
1090
+ return {
1091
+ async 'Viewlet.executeViewletCommand'(uid, command, ...args) {
1092
+ const fn = commandsById[command];
1093
+ if (!fn) {
1094
+ throw new Error(`Viewlet command not found: ${command}`);
1095
+ }
1096
+ await fn(uid, ...args);
1097
+ await requestRender(uid);
1098
+ }
1099
+ };
1100
+ },
1101
+ diff(uid, modules, numbers) {
1102
+ const {
1103
+ oldState,
1104
+ scheduledState
1105
+ } = states[uid];
1106
+ const diffResult = [];
1107
+ for (let i = 0; i < modules.length; i++) {
1108
+ const fn = modules[i];
1109
+ if (!fn(oldState, scheduledState)) {
1110
+ diffResult.push(numbers[i]);
1111
+ }
1112
+ }
1113
+ return diffResult;
1114
+ },
1115
+ dispose(uid) {
1116
+ commandQueues.delete(uid);
1117
+ delete states[uid];
1118
+ },
1119
+ get(uid) {
1120
+ return states[uid];
1121
+ },
1122
+ getCommandIds() {
1123
+ const keys = Object.keys(commandMapRef);
1124
+ const ids = keys.map(toCommandId);
1125
+ return ids;
1126
+ },
1127
+ getKeys() {
1128
+ return Object.keys(states).map(Number);
1129
+ },
1130
+ registerCommands(commandMap) {
1131
+ Object.assign(commandMapRef, commandMap);
1132
+ for (const [key, fn] of Object.entries(commandMap)) {
1133
+ commandsById[toCommandId(key)] = fn;
1134
+ }
1135
+ },
1136
+ set(uid, oldState, newState, scheduledState) {
1137
+ const current = states[uid];
1138
+ if (!current || oldState === newState && newState !== current.newState) {
1139
+ generations[uid] = getGeneration(uid) + 1;
1140
+ }
1141
+ states[uid] = {
1142
+ newState,
1143
+ oldState,
1144
+ scheduledState: scheduledState ?? newState
1145
+ };
1146
+ },
1147
+ wrapAsyncCommand(fn) {
1148
+ const wrapped = async (uid, ...args) => {
1149
+ const generation = getGeneration(uid);
1150
+ const context = createAsyncCommandContext(uid, generation);
1151
+ await fn(context, ...args);
1152
+ };
1153
+ return wrapped;
1154
+ },
1155
+ wrapCommand(fn) {
1156
+ const wrapped = async (uid, ...args) => {
1157
+ const generation = getGeneration(uid);
1158
+ const {
1159
+ newState,
1160
+ oldState
1161
+ } = states[uid];
1162
+ const newerState = await fn(newState, ...args);
1163
+ if (oldState === newerState || newState === newerState) {
1164
+ return;
1165
+ }
1166
+ if (!isCurrentGeneration(uid, generation)) {
1167
+ return;
1168
+ }
1169
+ const latestOld = states[uid];
1170
+ const latestNew = {
1171
+ ...latestOld.newState,
1172
+ ...newerState
1173
+ };
1174
+ states[uid] = {
1175
+ newState: latestNew,
1176
+ oldState: latestOld.oldState,
1177
+ scheduledState: latestNew
1178
+ };
1179
+ };
1180
+ return wrapped;
1181
+ },
1182
+ wrapGetter(fn) {
1183
+ const wrapped = (uid, ...args) => {
1184
+ const {
1185
+ newState
1186
+ } = states[uid];
1187
+ return fn(newState, ...args);
1188
+ };
1189
+ return wrapped;
1190
+ },
1191
+ wrapLoadContent(fn) {
1192
+ const wrapped = async (uid, ...args) => {
1193
+ const generation = getGeneration(uid);
1194
+ const {
1195
+ newState,
1196
+ oldState
1197
+ } = states[uid];
1198
+ const result = await fn(newState, ...args);
1199
+ const {
1200
+ error,
1201
+ state
1202
+ } = result;
1203
+ if (oldState === state || newState === state) {
1204
+ return {
1205
+ error
1206
+ };
1207
+ }
1208
+ if (!isCurrentGeneration(uid, generation)) {
1209
+ return {
1210
+ error
1211
+ };
1212
+ }
1213
+ const latestOld = states[uid];
1214
+ const latestNew = {
1215
+ ...latestOld.newState,
1216
+ ...state
1217
+ };
1218
+ states[uid] = {
1219
+ newState: latestNew,
1220
+ oldState: latestOld.oldState,
1221
+ scheduledState: latestNew
1222
+ };
1223
+ return {
1224
+ error
1225
+ };
1226
+ };
1227
+ return wrapped;
1228
+ },
1229
+ wrapSerialAsyncCommand(fn) {
1230
+ const wrapped = async (uid, ...args) => {
1231
+ await enqueueCommand(uid, async () => {
1232
+ if (!states[uid]) {
1233
+ return;
1234
+ }
1235
+ const generation = getGeneration(uid);
1236
+ const context = createAsyncCommandContext(uid, generation);
1237
+ await fn(context, ...args);
1238
+ });
1239
+ };
1240
+ return wrapped;
1241
+ },
1242
+ wrapSerialCommand(fn) {
1243
+ const wrapped = async (uid, ...args) => {
1244
+ await enqueueCommand(uid, async () => {
1245
+ if (!states[uid]) {
1246
+ return;
1247
+ }
1248
+ const generation = getGeneration(uid);
1249
+ const {
1250
+ newState,
1251
+ oldState
1252
+ } = states[uid];
1253
+ const newerState = await fn(newState, ...args);
1254
+ if (oldState === newerState || newState === newerState) {
1255
+ return;
1256
+ }
1257
+ if (!isCurrentGeneration(uid, generation)) {
1258
+ return;
1259
+ }
1260
+ const latestOld = states[uid];
1261
+ const latestNew = {
1262
+ ...latestOld.newState,
1263
+ ...newerState
1264
+ };
1265
+ states[uid] = {
1266
+ newState: latestNew,
1267
+ oldState: latestOld.oldState,
1268
+ scheduledState: latestNew
1269
+ };
1270
+ });
1271
+ };
1272
+ return wrapped;
1273
+ }
1274
+ };
1275
+ };
1276
+ const terminate = () => {
1277
+ globalThis.close();
1278
+ };
1279
+
1280
+ const assertString = (value, name) => {
1281
+ if (typeof value !== 'string') {
1282
+ throw new TypeError(`${name} must be a string`);
1283
+ }
1284
+ };
1285
+ const normalizePort = input => {
1286
+ if (!input || typeof input !== 'object') {
1287
+ throw new TypeError('port must be an object');
1288
+ }
1289
+ const {
1290
+ port
1291
+ } = input;
1292
+ if (!Number.isSafeInteger(port) || port < 1 || port > 65_535) {
1293
+ throw new RangeError('port must be an integer between 1 and 65535');
1294
+ }
1295
+ const forwardedAddress = input.forwardedAddress ?? `localhost:${port}`;
1296
+ const runningProcess = input.runningProcess ?? '';
1297
+ const origin = input.origin ?? 'User Forwarded';
1298
+ assertString(forwardedAddress, 'forwardedAddress');
1299
+ assertString(runningProcess, 'runningProcess');
1300
+ assertString(origin, 'origin');
1301
+ if (input.active !== undefined && typeof input.active !== 'boolean') {
1302
+ throw new TypeError('active must be a boolean');
1303
+ }
1304
+ return {
1305
+ active: input.active ?? true,
1306
+ forwardedAddress,
1307
+ origin,
1308
+ port,
1309
+ runningProcess
1310
+ };
1311
+ };
1312
+ const normalizePorts = ports => {
1313
+ if (!Array.isArray(ports)) {
1314
+ throw new TypeError('ports must be an array');
1315
+ }
1316
+ const byPort = new Map();
1317
+ for (const port of ports) {
1318
+ const normalized = normalizePort(port);
1319
+ byPort.set(normalized.port, normalized);
1320
+ }
1321
+ return byPort.values().toArray().toSorted((a, b) => a.port - b.port);
1322
+ };
1323
+
1324
+ const clamp = (value, minimum, maximum) => {
1325
+ return Math.min(Math.max(value, minimum), maximum);
1326
+ };
1327
+
1328
+ const recalculateVirtualList = state => {
1329
+ const {
1330
+ deltaY: oldDeltaY,
1331
+ footerHeight,
1332
+ headerHeight,
1333
+ height,
1334
+ itemHeight,
1335
+ minimumScrollBarSize,
1336
+ ports
1337
+ } = state;
1338
+ const listHeight = Math.max(0, height - headerHeight - footerHeight);
1339
+ const contentHeight = ports.length * itemHeight;
1340
+ const finalDeltaY = Math.max(0, contentHeight - listHeight);
1341
+ const deltaY = clamp(oldDeltaY, 0, finalDeltaY);
1342
+ const minLineY = itemHeight === 0 ? 0 : Math.floor(deltaY / itemHeight);
1343
+ const visibleCount = itemHeight === 0 ? 0 : Math.ceil(listHeight / itemHeight) + 1;
1344
+ const maxLineY = Math.min(ports.length, minLineY + visibleCount);
1345
+ const scrollBarHeight = contentHeight <= listHeight || listHeight === 0 ? 0 : Math.max(minimumScrollBarSize, listHeight * listHeight / contentHeight);
1346
+ const scrollBarY = finalDeltaY === 0 ? 0 : deltaY / finalDeltaY * (listHeight - scrollBarHeight);
1347
+ return {
1348
+ ...state,
1349
+ deltaY,
1350
+ finalDeltaY,
1351
+ listHeight,
1352
+ maxLineY,
1353
+ minLineY,
1354
+ scrollBarHeight,
1355
+ scrollBarY
1356
+ };
1357
+ };
1358
+
1359
+ const setPorts = (state, ports) => {
1360
+ const {
1361
+ focusedIndex: oldFocusedIndex
1362
+ } = state;
1363
+ const normalized = normalizePorts(ports);
1364
+ const focusedIndex = Math.min(oldFocusedIndex, normalized.length - 1);
1365
+ return recalculateVirtualList({
1366
+ ...state,
1367
+ focusedIndex,
1368
+ loaded: true,
1369
+ ports: normalized
1370
+ });
1371
+ };
1372
+
1373
+ const addPort = (state, port) => {
1374
+ const {
1375
+ ports
1376
+ } = state;
1377
+ return setPorts(state, [...ports, port]);
1378
+ };
1379
+
1380
+ const PortRegex = /^\d+$/;
1381
+ const startAddPort = state => {
1382
+ return {
1383
+ ...state,
1384
+ addPortError: '',
1385
+ addPortValue: '',
1386
+ editing: true
1387
+ };
1388
+ };
1389
+ const cancelAddPort = state => {
1390
+ return {
1391
+ ...state,
1392
+ addPortError: '',
1393
+ addPortValue: '',
1394
+ editing: false
1395
+ };
1396
+ };
1397
+ const handleAddPortInput = (state, value) => {
1398
+ return {
1399
+ ...state,
1400
+ addPortError: '',
1401
+ addPortValue: value
1402
+ };
1403
+ };
1404
+ const submitAddPort = state => {
1405
+ const {
1406
+ addPortValue
1407
+ } = state;
1408
+ const value = addPortValue.trim();
1409
+ const port = Number(value);
1410
+ if (!PortRegex.test(value) || !Number.isSafeInteger(port) || port < 1 || port > 65_535) {
1411
+ return {
1412
+ ...state,
1413
+ addPortError: 'Enter a port number between 1 and 65535'
1414
+ };
1415
+ }
1416
+ return {
1417
+ ...addPort(state, {
1418
+ port
1419
+ }),
1420
+ addPortError: '',
1421
+ addPortValue: '',
1422
+ editing: false
1423
+ };
1424
+ };
1425
+ const handleAddPortKeyDown = (state, key) => {
1426
+ if (key === 'Enter') {
1427
+ return submitAddPort(state);
1428
+ }
1429
+ if (key === 'Escape') {
1430
+ return cancelAddPort(state);
1431
+ }
1432
+ return state;
1433
+ };
1434
+
1435
+ const {
1436
+ diff,
1437
+ dispose,
1438
+ get,
1439
+ getCommandIds,
1440
+ registerCommands,
1441
+ set,
1442
+ wrapCommand
1443
+ } = create$1();
1444
+
1445
+ const create = (uid, uri, x, y, width, height, platform, assetDir, parentUid) => {
1446
+ const state = {
1447
+ addPortError: '',
1448
+ addPortValue: '',
1449
+ deltaY: 0,
1450
+ editing: false,
1451
+ finalDeltaY: 0,
1452
+ focused: false,
1453
+ focusedIndex: -1,
1454
+ footerHeight: 36,
1455
+ headerHeight: 28,
1456
+ height,
1457
+ itemHeight: 24,
1458
+ listHeight: 0,
1459
+ loaded: false,
1460
+ maxLineY: 0,
1461
+ minimumScrollBarSize: 20,
1462
+ minLineY: 0,
1463
+ parentUid,
1464
+ platform,
1465
+ ports: [],
1466
+ scrollBarHeight: 0,
1467
+ scrollBarY: 0,
1468
+ uid,
1469
+ width,
1470
+ x,
1471
+ y
1472
+ };
1473
+ const calculated = recalculateVirtualList(state);
1474
+ set(uid, calculated, calculated);
1475
+ };
1476
+
1477
+ const isFocusContextEqual = (oldState, newState) => {
1478
+ return oldState.focused === newState.focused && oldState.editing === newState.editing;
1479
+ };
1480
+ const isDomEqual = (oldState, newState) => {
1481
+ return oldState.addPortError === newState.addPortError && oldState.addPortValue === newState.addPortValue && oldState.editing === newState.editing && oldState.focusedIndex === newState.focusedIndex && oldState.loaded === newState.loaded && oldState.maxLineY === newState.maxLineY && oldState.minLineY === newState.minLineY && oldState.ports === newState.ports;
1482
+ };
1483
+ const isCssEqual = (oldState, newState) => {
1484
+ return oldState.loaded && oldState.deltaY % oldState.itemHeight === newState.deltaY % newState.itemHeight && oldState.footerHeight === newState.footerHeight && oldState.headerHeight === newState.headerHeight && oldState.height === newState.height && oldState.itemHeight === newState.itemHeight && oldState.width === newState.width;
1485
+ };
1486
+
1487
+ const RenderCss = 1;
1488
+ const RenderDom = 2;
1489
+ const RenderIncremental = 3;
1490
+ const RenderFocusContext = 4;
1491
+
1492
+ const diff2 = uid => {
1493
+ const {
1494
+ oldState
1495
+ } = get(uid);
1496
+ const domDiffType = oldState.loaded ? RenderIncremental : RenderDom;
1497
+ return diff(uid, [isDomEqual, isCssEqual, isFocusContextEqual], [domDiffType, RenderCss, RenderFocusContext]);
1498
+ };
1499
+
1500
+ const setDeltaY = (state, deltaY) => {
1501
+ return recalculateVirtualList({
1502
+ ...state,
1503
+ deltaY
1504
+ });
1505
+ };
1506
+
1507
+ const focusIndex = (state, index) => {
1508
+ const {
1509
+ itemHeight,
1510
+ listHeight,
1511
+ ports
1512
+ } = state;
1513
+ if (ports.length === 0) {
1514
+ return {
1515
+ ...state,
1516
+ focusedIndex: -1
1517
+ };
1518
+ }
1519
+ const focusedIndex = clamp(index, 0, ports.length - 1);
1520
+ let {
1521
+ deltaY
1522
+ } = state;
1523
+ const itemTop = focusedIndex * itemHeight;
1524
+ const itemBottom = itemTop + itemHeight;
1525
+ if (itemTop < deltaY) {
1526
+ deltaY = itemTop;
1527
+ } else if (itemBottom > deltaY + listHeight) {
1528
+ deltaY = itemBottom - listHeight;
1529
+ }
1530
+ return setDeltaY({
1531
+ ...state,
1532
+ focusedIndex
1533
+ }, deltaY);
1534
+ };
1535
+ const focusNext = state => {
1536
+ const {
1537
+ focusedIndex
1538
+ } = state;
1539
+ return focusIndex(state, focusedIndex + 1);
1540
+ };
1541
+ const focusPrevious = state => {
1542
+ const {
1543
+ focusedIndex,
1544
+ ports
1545
+ } = state;
1546
+ const index = (focusedIndex === -1 ? ports.length : focusedIndex) - 1;
1547
+ return focusIndex(state, index);
1548
+ };
1549
+
1550
+ const focusFirst = state => {
1551
+ return focusIndex(state, 0);
1552
+ };
1553
+
1554
+ const focusLast = state => {
1555
+ const {
1556
+ ports
1557
+ } = state;
1558
+ return focusIndex(state, ports.length - 1);
1559
+ };
1560
+
1561
+ const mergeClassNames = (...classNames) => {
1562
+ return classNames.filter(Boolean).join(' ');
1563
+ };
1564
+
1565
+ const text = data => {
1566
+ return {
1567
+ childCount: 0,
1568
+ text: data,
1569
+ type: Text
1570
+ };
1571
+ };
1572
+
1573
+ const SetText = 1;
1574
+ const Replace = 2;
1575
+ const SetAttribute = 3;
1576
+ const RemoveAttribute = 4;
1577
+ const Add = 6;
1578
+ const NavigateChild = 7;
1579
+ const NavigateParent = 8;
1580
+ const RemoveChild = 9;
1581
+ const NavigateSibling = 10;
1582
+ const SetReferenceNodeUid = 11;
1583
+ const MultiNavigation = 18;
1584
+
1585
+ const isKey = key => {
1586
+ return key !== 'type' && key !== 'childCount';
1587
+ };
1588
+
1589
+ const getKeys = node => {
1590
+ const keys = Object.keys(node).filter(isKey);
1591
+ return keys;
1592
+ };
1593
+
1594
+ const arrayToTree = nodes => {
1595
+ const result = [];
1596
+ let i = 0;
1597
+ while (i < nodes.length) {
1598
+ const node = nodes[i];
1599
+ const {
1600
+ children,
1601
+ nodesConsumed
1602
+ } = getChildrenWithCount(nodes, i + 1, node.childCount || 0);
1603
+ result.push({
1604
+ node,
1605
+ children
1606
+ });
1607
+ i += 1 + nodesConsumed;
1608
+ }
1609
+ return result;
1610
+ };
1611
+ const getChildrenWithCount = (nodes, startIndex, childCount) => {
1612
+ if (childCount === 0) {
1613
+ return {
1614
+ children: [],
1615
+ nodesConsumed: 0
1616
+ };
1617
+ }
1618
+ const children = [];
1619
+ let i = startIndex;
1620
+ let remaining = childCount;
1621
+ let totalConsumed = 0;
1622
+ while (remaining > 0 && i < nodes.length) {
1623
+ const node = nodes[i];
1624
+ const nodeChildCount = node.childCount || 0;
1625
+ const {
1626
+ children: nodeChildren,
1627
+ nodesConsumed
1628
+ } = getChildrenWithCount(nodes, i + 1, nodeChildCount);
1629
+ children.push({
1630
+ node,
1631
+ children: nodeChildren
1632
+ });
1633
+ const nodeSize = 1 + nodesConsumed;
1634
+ i += nodeSize;
1635
+ totalConsumed += nodeSize;
1636
+ remaining--;
1637
+ }
1638
+ return {
1639
+ children,
1640
+ nodesConsumed: totalConsumed
1641
+ };
1642
+ };
1643
+
1644
+ const isNavigationPatch = patch => {
1645
+ switch (patch.type) {
1646
+ case NavigateChild:
1647
+ case NavigateParent:
1648
+ case NavigateSibling:
1649
+ return true;
1650
+ default:
1651
+ return false;
1652
+ }
1653
+ };
1654
+ const getNavigationIndex = patch => {
1655
+ switch (patch.type) {
1656
+ case NavigateChild:
1657
+ case NavigateSibling:
1658
+ return patch.index;
1659
+ default:
1660
+ return 0;
1661
+ }
1662
+ };
1663
+ const appendNavigationPatch = (patches, type, index) => {
1664
+ const previousPatch = patches.at(-1);
1665
+ if (!previousPatch) {
1666
+ patches.push(type === NavigateParent ? {
1667
+ type
1668
+ } : {
1669
+ index,
1670
+ type
1671
+ });
1672
+ return;
1673
+ }
1674
+ if (previousPatch.type === MultiNavigation) {
1675
+ previousPatch.navigations.push(type, index);
1676
+ return;
1677
+ }
1678
+ if (isNavigationPatch(previousPatch)) {
1679
+ patches[patches.length - 1] = {
1680
+ navigations: [previousPatch.type, getNavigationIndex(previousPatch), type, index],
1681
+ type: MultiNavigation
1682
+ };
1683
+ return;
1684
+ }
1685
+ patches.push(type === NavigateParent ? {
1686
+ type
1687
+ } : {
1688
+ index,
1689
+ type
1690
+ });
1691
+ };
1692
+
1693
+ const compareNodes = (oldNode, newNode) => {
1694
+ // Check if node type changed - return null to signal incompatible nodes
1695
+ // (caller should handle this with a Replace operation)
1696
+ if (oldNode.type !== newNode.type) {
1697
+ return null;
1698
+ }
1699
+ const patches = [];
1700
+ // Handle reference nodes - special handling for uid changes
1701
+ if (oldNode.type === Reference && oldNode.uid !== newNode.uid) {
1702
+ patches.push({
1703
+ type: SetReferenceNodeUid,
1704
+ uid: newNode.uid
1705
+ });
1706
+ }
1707
+ // Handle text nodes
1708
+ if (oldNode.type === Text && newNode.type === Text) {
1709
+ if (oldNode.text !== newNode.text) {
1710
+ patches.push({
1711
+ type: SetText,
1712
+ value: newNode.text
1713
+ });
1714
+ }
1715
+ return patches;
1716
+ }
1717
+ // Compare attributes
1718
+ const oldKeys = getKeys(oldNode).filter(key => oldNode.type !== Reference || key !== 'uid');
1719
+ const newKeys = getKeys(newNode).filter(key => newNode.type !== Reference || key !== 'uid');
1720
+ // Check for attribute changes
1721
+ for (const key of newKeys) {
1722
+ if (oldNode[key] !== newNode[key]) {
1723
+ patches.push({
1724
+ type: SetAttribute,
1725
+ key,
1726
+ value: newNode[key]
1727
+ });
1728
+ }
1729
+ }
1730
+ // Check for removed attributes
1731
+ for (const key of oldKeys) {
1732
+ if (!Object.hasOwn(newNode, key)) {
1733
+ patches.push({
1734
+ type: RemoveAttribute,
1735
+ key
1736
+ });
1737
+ }
1738
+ }
1739
+ return patches;
1740
+ };
1741
+
1742
+ const treeToArray = node => {
1743
+ const result = [];
1744
+ const stack = [node];
1745
+ while (stack.length > 0) {
1746
+ const current = stack.pop();
1747
+ result.push(current.node);
1748
+ for (let i = current.children.length - 1; i >= 0; i--) {
1749
+ stack.push(current.children[i]);
1750
+ }
1751
+ }
1752
+ return result;
1753
+ };
1754
+
1755
+ const navigateToChild = (patches, currentChildIndex, index) => {
1756
+ if (currentChildIndex === -1) {
1757
+ appendNavigationPatch(patches, NavigateChild, index);
1758
+ return index;
1759
+ }
1760
+ if (currentChildIndex !== index) {
1761
+ appendNavigationPatch(patches, NavigateSibling, index);
1762
+ }
1763
+ return index;
1764
+ };
1765
+ const navigateToParent = (patches, currentChildIndex) => {
1766
+ if (currentChildIndex >= 0) {
1767
+ appendNavigationPatch(patches, NavigateParent, 0);
1768
+ }
1769
+ return -1;
1770
+ };
1771
+ const addTree = (newNode, patches) => {
1772
+ patches.push({
1773
+ type: Add,
1774
+ nodes: treeToArray(newNode)
1775
+ });
1776
+ };
1777
+ const replaceTree = (newNode, patches) => {
1778
+ patches.push({
1779
+ type: Replace,
1780
+ nodes: treeToArray(newNode)
1781
+ });
1782
+ };
1783
+ const appendPatch = (patches, patch) => {
1784
+ switch (patch.type) {
1785
+ case MultiNavigation:
1786
+ for (let i = 0; i < patch.navigations.length; i += 2) {
1787
+ appendNavigationPatch(patches, patch.navigations[i], patch.navigations[i + 1]);
1788
+ }
1789
+ return;
1790
+ case NavigateChild:
1791
+ case NavigateSibling:
1792
+ appendNavigationPatch(patches, patch.type, patch.index);
1793
+ return;
1794
+ case NavigateParent:
1795
+ appendNavigationPatch(patches, patch.type, 0);
1796
+ return;
1797
+ default:
1798
+ patches.push(patch);
1799
+ }
1800
+ };
1801
+ const appendPatches = (patches, newPatches) => {
1802
+ for (const patch of newPatches) {
1803
+ appendPatch(patches, patch);
1804
+ }
1805
+ };
1806
+ const diffExistingChild = (oldNode, newNode, patches, currentChildIndex, index) => {
1807
+ const nodePatches = compareNodes(oldNode.node, newNode.node);
1808
+ if (nodePatches === null) {
1809
+ const nextChildIndex = navigateToChild(patches, currentChildIndex, index);
1810
+ replaceTree(newNode, patches);
1811
+ return nextChildIndex;
1812
+ }
1813
+ const hasChildrenToCompare = oldNode.children.length > 0 || newNode.children.length > 0;
1814
+ const childPatches = [];
1815
+ if (hasChildrenToCompare) {
1816
+ diffChildren(oldNode.children, newNode.children, childPatches);
1817
+ }
1818
+ if (nodePatches.length === 0 && childPatches.length === 0) {
1819
+ return currentChildIndex;
1820
+ }
1821
+ const nextChildIndex = navigateToChild(patches, currentChildIndex, index);
1822
+ patches.push(...nodePatches);
1823
+ appendPatches(patches, childPatches);
1824
+ return nextChildIndex;
1825
+ };
1826
+ const diffRootNode = (oldNode, newNode, patches) => {
1827
+ const nodePatches = compareNodes(oldNode.node, newNode.node);
1828
+ if (nodePatches === null) {
1829
+ replaceTree(newNode, patches);
1830
+ return;
1831
+ }
1832
+ if (nodePatches.length > 0) {
1833
+ patches.push(...nodePatches);
1834
+ }
1835
+ if (oldNode.children.length > 0 || newNode.children.length > 0) {
1836
+ diffChildren(oldNode.children, newNode.children, patches);
1837
+ }
1838
+ };
1839
+ const diffChildren = (oldChildren, newChildren, patches) => {
1840
+ const maxLength = Math.max(oldChildren.length, newChildren.length);
1841
+ let currentChildIndex = -1;
1842
+ const indicesToRemove = [];
1843
+ for (let i = 0; i < maxLength; i++) {
1844
+ const oldNode = oldChildren[i];
1845
+ const newNode = newChildren[i];
1846
+ if (!oldNode && !newNode) {
1847
+ continue;
1848
+ }
1849
+ if (!oldNode) {
1850
+ currentChildIndex = navigateToParent(patches, currentChildIndex);
1851
+ addTree(newNode, patches);
1852
+ continue;
1853
+ }
1854
+ if (!newNode) {
1855
+ indicesToRemove.push(i);
1856
+ continue;
1857
+ }
1858
+ currentChildIndex = diffExistingChild(oldNode, newNode, patches, currentChildIndex, i);
1859
+ }
1860
+ navigateToParent(patches, currentChildIndex);
1861
+ for (let j = indicesToRemove.length - 1; j >= 0; j--) {
1862
+ patches.push({
1863
+ type: RemoveChild,
1864
+ index: indicesToRemove[j]
1865
+ });
1866
+ }
1867
+ };
1868
+ const diffTrees = (oldTree, newTree, patches, path) => {
1869
+ if (path.length === 0 && oldTree.length === 1 && newTree.length === 1) {
1870
+ diffRootNode(oldTree[0], newTree[0], patches);
1871
+ return;
1872
+ }
1873
+ diffChildren(oldTree, newTree, patches);
1874
+ };
1875
+
1876
+ const removeTrailingNavigationPatches = patches => {
1877
+ while (patches.length > 0) {
1878
+ const patch = patches.at(-1);
1879
+ if (patch.type !== NavigateChild && patch.type !== NavigateParent && patch.type !== NavigateSibling && patch.type !== MultiNavigation) {
1880
+ break;
1881
+ }
1882
+ patches.pop();
1883
+ }
1884
+ return patches;
1885
+ };
1886
+
1887
+ const diffTree = (oldNodes, newNodes) => {
1888
+ // Step 1: Convert flat arrays to tree structures
1889
+ const oldTree = arrayToTree(oldNodes);
1890
+ const newTree = arrayToTree(newNodes);
1891
+ // Step 3: Compare the trees
1892
+ const patches = [];
1893
+ diffTrees(oldTree, newTree, patches, []);
1894
+ // Remove trailing navigation patches since they serve no purpose
1895
+ return removeTrailingNavigationPatches(patches);
1896
+ };
1897
+
1898
+ const Empty = 0;
1899
+ const FocusPorts = 9000;
1900
+
1901
+ const getKeyBindings = () => {
1902
+ return [{
1903
+ command: 'Ports.focusNext',
1904
+ key: DownArrow,
1905
+ when: FocusPorts
1906
+ }, {
1907
+ command: 'Ports.focusPrevious',
1908
+ key: UpArrow,
1909
+ when: FocusPorts
1910
+ }, {
1911
+ command: 'Ports.focusFirst',
1912
+ key: Home,
1913
+ when: FocusPorts
1914
+ }, {
1915
+ command: 'Ports.focusLast',
1916
+ key: End,
1917
+ when: FocusPorts
1918
+ }, {
1919
+ command: 'Ports.startAddPort',
1920
+ key: KeyA,
1921
+ when: FocusPorts
1922
+ }, {
1923
+ command: 'Ports.startAddPort',
1924
+ key: KeyA | Shift,
1925
+ when: FocusPorts
1926
+ }, {
1927
+ command: 'Ports.openFocusedAddress',
1928
+ key: Enter,
1929
+ when: FocusPorts
1930
+ }, {
1931
+ command: 'Ports.toggleFocusedPort',
1932
+ key: Space,
1933
+ when: FocusPorts
1934
+ }, {
1935
+ command: 'Ports.removeFocusedPort',
1936
+ key: Delete,
1937
+ when: FocusPorts
1938
+ }, {
1939
+ command: 'Ports.removeFocusedPort',
1940
+ key: Backspace,
1941
+ when: FocusPorts
1942
+ }];
1943
+ };
1944
+
1945
+ const handleBlur = state => {
1946
+ return {
1947
+ ...state,
1948
+ focused: false,
1949
+ focusedIndex: -1
1950
+ };
1951
+ };
1952
+
1953
+ const handleClickAt = (state, clientY, name) => {
1954
+ const {
1955
+ deltaY,
1956
+ headerHeight,
1957
+ itemHeight,
1958
+ minLineY,
1959
+ ports,
1960
+ y
1961
+ } = state;
1962
+ if (name.startsWith('port-address-') || name.startsWith('port-status-')) {
1963
+ const port = Number(name.slice(name.lastIndexOf('-') + 1));
1964
+ const index = ports.findIndex(item => item.port === port);
1965
+ return index === -1 ? state : focusIndex(state, index);
1966
+ }
1967
+ const relativeY = clientY - y - headerHeight;
1968
+ const index = minLineY + Math.floor((relativeY + deltaY % itemHeight) / itemHeight);
1969
+ if (relativeY < 0 || index < 0 || index >= ports.length) {
1970
+ return state;
1971
+ }
1972
+ return focusIndex(state, index);
1973
+ };
1974
+
1975
+ const SchemeRegex = /^[a-z][a-z\d+.-]*:\/\//i;
1976
+ const getAddressUrl = address => {
1977
+ return SchemeRegex.test(address) ? address : `http://${address}`;
1978
+ };
1979
+
1980
+ const openAddress = async (state, portNumber) => {
1981
+ const {
1982
+ ports
1983
+ } = state;
1984
+ const port = ports.find(item => item.port === portNumber);
1985
+ if (!port || !port.forwardedAddress) {
1986
+ return state;
1987
+ }
1988
+ await openUri(getAddressUrl(port.forwardedAddress));
1989
+ return state;
1990
+ };
1991
+
1992
+ const togglePortActive = (state, portNumber) => {
1993
+ const {
1994
+ ports
1995
+ } = state;
1996
+ return {
1997
+ ...state,
1998
+ ports: ports.map(item => {
1999
+ if (item.port !== portNumber) {
2000
+ return item;
2001
+ }
2002
+ return {
2003
+ ...item,
2004
+ active: !item.active
2005
+ };
2006
+ })
2007
+ };
2008
+ };
2009
+
2010
+ const parsePort = name => {
2011
+ return Number(name.slice(name.lastIndexOf('-') + 1));
2012
+ };
2013
+ const handleClick = async (state, clientY, name) => {
2014
+ const {
2015
+ ports
2016
+ } = state;
2017
+ if (name.startsWith('port-address-')) {
2018
+ const portNumber = parsePort(name);
2019
+ const index = ports.findIndex(item => item.port === portNumber);
2020
+ const focused = index === -1 ? state : focusIndex(state, index);
2021
+ return openAddress(focused, portNumber);
2022
+ }
2023
+ if (name.startsWith('port-status-')) {
2024
+ const portNumber = parsePort(name);
2025
+ const index = ports.findIndex(item => item.port === portNumber);
2026
+ const focused = index === -1 ? state : focusIndex(state, index);
2027
+ return togglePortActive(focused, portNumber);
2028
+ }
2029
+ return handleClickAt(state, clientY, name);
2030
+ };
2031
+
2032
+ const handleFocus = state => {
2033
+ return {
2034
+ ...state,
2035
+ focused: true
2036
+ };
2037
+ };
2038
+
2039
+ const PageScrollMultiplier = 16;
2040
+ const handleWheel = (state, deltaMode, deltaY) => {
2041
+ const {
2042
+ deltaY: oldDeltaY
2043
+ } = state;
2044
+ const multiplier = deltaMode === 0 ? 1 : PageScrollMultiplier;
2045
+ return setDeltaY(state, oldDeltaY + deltaY * multiplier);
2046
+ };
2047
+
2048
+ const requests = new Map();
2049
+ const loadContent = async (state, workspaceUri = '') => {
2050
+ const {
2051
+ uid
2052
+ } = state;
2053
+ const request = {};
2054
+ requests.set(uid, request);
2055
+ try {
2056
+ const ports = workspaceUri ? await invoke('Application.executeForView', uid, 'PortProvider.getPorts', workspaceUri) : [];
2057
+ if (requests.get(uid) !== request) {
2058
+ return get(uid).newState;
2059
+ }
2060
+ return setPorts(state, ports);
2061
+ } finally {
2062
+ if (requests.get(uid) === request) {
2063
+ requests.delete(uid);
2064
+ }
2065
+ }
2066
+ };
2067
+
2068
+ const openFocusedAddress = async state => {
2069
+ const {
2070
+ editing,
2071
+ focusedIndex,
2072
+ ports
2073
+ } = state;
2074
+ const selected = ports[focusedIndex];
2075
+ if (editing || !selected) {
2076
+ return state;
2077
+ }
2078
+ return openAddress(state, selected.port);
2079
+ };
2080
+
2081
+ const removePort = (state, portNumber) => {
2082
+ const {
2083
+ focusedIndex: oldFocusedIndex,
2084
+ ports: oldPorts
2085
+ } = state;
2086
+ const ports = oldPorts.filter(item => item.port !== portNumber);
2087
+ const focusedIndex = Math.min(oldFocusedIndex, ports.length - 1);
2088
+ return recalculateVirtualList({
2089
+ ...state,
2090
+ focusedIndex,
2091
+ ports
2092
+ });
2093
+ };
2094
+
2095
+ const removeFocusedPort = state => {
2096
+ const {
2097
+ editing,
2098
+ focusedIndex,
2099
+ ports
2100
+ } = state;
2101
+ const selected = ports[focusedIndex];
2102
+ if (editing || !selected) {
2103
+ return state;
2104
+ }
2105
+ return removePort(state, selected.port);
2106
+ };
2107
+
2108
+ const getCss = state => {
2109
+ const {
2110
+ deltaY,
2111
+ footerHeight,
2112
+ headerHeight,
2113
+ itemHeight
2114
+ } = state;
2115
+ const relativeY = -(deltaY % itemHeight);
2116
+ return `.Ports {
2117
+ grid-template-rows: minmax(0, 1fr) ${footerHeight}px;
2118
+ }
2119
+
2120
+ .PortsTable {
2121
+ grid-template-rows: ${headerHeight}px minmax(0, 1fr);
2122
+ }
2123
+
2124
+ .PortsTableBody > .PortsTableRow:first-child {
2125
+ margin-top: ${relativeY}px;
2126
+ }
2127
+
2128
+ .PortsTableRow {
2129
+ height: ${itemHeight}px;
2130
+ }
2131
+ `;
2132
+ };
2133
+
2134
+ const renderCss = (oldState, newState) => {
2135
+ return [SetCss, newState.uid, getCss(newState)];
2136
+ };
2137
+
2138
+ const Alert = 'alert';
2139
+ const Cell = 'cell';
2140
+ const ColumnHeader = 'columnheader';
2141
+ const Link = 'link';
2142
+ const Row = 'row';
2143
+ const RowGroup = 'rowgroup';
2144
+ const Status = 'status';
2145
+ const Table = 'table';
2146
+
2147
+ const AddPortButton = 'AddPortButton';
2148
+ const AddPortEditor = 'AddPortEditor';
2149
+ const AddPortError = 'AddPortError';
2150
+ const AddPortInput = 'AddPortInput';
2151
+ const Focused = 'Focused';
2152
+ const Ports = 'Ports';
2153
+ const PortsEmpty = 'PortsEmpty';
2154
+ const PortsFooter = 'PortsFooter';
2155
+ const PortsStatusButton = 'PortsStatusButton';
2156
+ const PortsStatusIcon = 'PortsStatusIcon';
2157
+ const PortsStatusIconActive = 'PortsStatusIconActive';
2158
+ const PortsStatusIconInactive = 'PortsStatusIconInactive';
2159
+ const PortsTable = 'PortsTable';
2160
+ const PortsTableBody = 'PortsTableBody';
2161
+ const PortsTableCell = 'PortsTableCell';
2162
+ const PortsTableHeader = 'PortsTableHeader';
2163
+ const PortsTableRow = 'PortsTableRow';
2164
+ const PortsTableRowOdd = 'PortsTableRowOdd';
2165
+ const Viewlet = 'Viewlet';
2166
+
2167
+ const HandleAddPortInput = 1;
2168
+ const HandleAddPortKeyDown = 2;
2169
+ const HandleBlur = 3;
2170
+ const HandleCancelAddPort = 4;
2171
+ const HandleClick = 5;
2172
+ const HandleFocus = 6;
2173
+ const HandleStartAddPort = 7;
2174
+ const HandleSubmitAddPort = 8;
2175
+ const HandleWheel = 9;
2176
+
2177
+ const errorMessage = {
2178
+ childCount: 1,
2179
+ className: AddPortError,
2180
+ role: Alert,
2181
+ type: Div
2182
+ };
2183
+ const getErrorDom = addPortError => {
2184
+ if (!addPortError) {
2185
+ return [];
2186
+ }
2187
+ return [errorMessage, text(addPortError)];
2188
+ };
2189
+
2190
+ const cancelButton = {
2191
+ childCount: 1,
2192
+ className: 'CancelAddPortButton',
2193
+ onClick: HandleCancelAddPort,
2194
+ type: Button
2195
+ };
2196
+ const getEditor = state => {
2197
+ const {
2198
+ addPortError,
2199
+ addPortValue
2200
+ } = state;
2201
+ return [{
2202
+ childCount: addPortError ? 4 : 3,
2203
+ className: AddPortEditor,
2204
+ type: Div
2205
+ }, {
2206
+ ariaLabel: 'Port number',
2207
+ childCount: 0,
2208
+ className: AddPortInput,
2209
+ inputMode: 'numeric',
2210
+ onInput: HandleAddPortInput,
2211
+ onKeyDown: HandleAddPortKeyDown,
2212
+ placeholder: 'Port number',
2213
+ type: Input,
2214
+ value: addPortValue
2215
+ }, {
2216
+ childCount: 1,
2217
+ className: AddPortButton,
2218
+ disabled: addPortValue.length === 0,
2219
+ onClick: HandleSubmitAddPort,
2220
+ type: Button
2221
+ }, text('Add'), cancelButton, text('Cancel'), ...getErrorDom(addPortError)];
2222
+ };
2223
+
2224
+ const addButton = {
2225
+ childCount: 1,
2226
+ className: AddPortButton,
2227
+ onClick: HandleStartAddPort,
2228
+ type: Button
2229
+ };
2230
+ const addButtonDom = [addButton, text('Add Port')];
2231
+ const footer = {
2232
+ childCount: 1,
2233
+ className: PortsFooter,
2234
+ type: Div
2235
+ };
2236
+ const footerContent = {
2237
+ childCount: 1,
2238
+ type: Div
2239
+ };
2240
+ const getPortsFooterVirtualDom = state => {
2241
+ const {
2242
+ editing
2243
+ } = state;
2244
+ const content = editing ? getEditor(state) : addButtonDom;
2245
+ return [footer, footerContent, ...content];
2246
+ };
2247
+
2248
+ const getPortsStatusVirtualDom = (active, port) => {
2249
+ const state = active ? 'active' : 'inactive';
2250
+ const stateClass = active ? PortsStatusIconActive : PortsStatusIconInactive;
2251
+ return [{
2252
+ ariaLabel: `Port ${port} is ${state}`,
2253
+ childCount: 1,
2254
+ className: PortsStatusButton,
2255
+ name: `port-status-${port}`,
2256
+ title: `Port ${port} is ${state}`,
2257
+ type: Button
2258
+ }, {
2259
+ childCount: 1,
2260
+ className: mergeClassNames(PortsStatusIcon, stateClass),
2261
+ name: `port-status-${port}`,
2262
+ type: Span
2263
+ }, text(active ? '●' : '○')];
2264
+ };
2265
+
2266
+ const getRowClassName = port => {
2267
+ let className = PortsTableRow;
2268
+ if (port.index % 2 === 1) {
2269
+ className = mergeClassNames(className, PortsTableRowOdd);
2270
+ }
2271
+ if (port.selected) {
2272
+ className = mergeClassNames(className, Focused);
2273
+ }
2274
+ return className;
2275
+ };
2276
+
2277
+ const getTextCell = (value, className) => {
2278
+ return [{
2279
+ childCount: 1,
2280
+ className: mergeClassNames(PortsTableCell, className),
2281
+ role: Cell,
2282
+ title: value,
2283
+ type: Div
2284
+ }, text(value)];
2285
+ };
2286
+
2287
+ const Focusable = 0;
2288
+ const Unfocusable = -1;
2289
+
2290
+ const statusCell = {
2291
+ childCount: 1,
2292
+ className: mergeClassNames(PortsTableCell, 'PortsStatusColumn'),
2293
+ role: Cell,
2294
+ type: Div
2295
+ };
2296
+ const getPortRowVirtualDom = port => {
2297
+ const portText = String(port.port);
2298
+ return [{
2299
+ ariaRowIndex: port.index + 2,
2300
+ childCount: 5,
2301
+ className: getRowClassName(port),
2302
+ role: Row,
2303
+ type: Div
2304
+ }, statusCell, ...getPortsStatusVirtualDom(port.active, port.port), ...getTextCell(portText, 'PortsPortColumn'), {
2305
+ childCount: 1,
2306
+ className: mergeClassNames(PortsTableCell, 'PortsAddressColumn'),
2307
+ role: Cell,
2308
+ title: port.forwardedAddress,
2309
+ type: Div
2310
+ }, {
2311
+ childCount: 1,
2312
+ className: 'PortsAddressLink',
2313
+ name: `port-address-${port.port}`,
2314
+ role: Link,
2315
+ tabIndex: Unfocusable,
2316
+ type: A
2317
+ }, text(port.forwardedAddress), ...getTextCell(port.runningProcess, 'PortsProcessColumn'), ...getTextCell(port.origin, 'PortsOriginColumn')];
2318
+ };
2319
+
2320
+ const getVisiblePorts = state => {
2321
+ const {
2322
+ focusedIndex,
2323
+ maxLineY,
2324
+ minLineY,
2325
+ ports
2326
+ } = state;
2327
+ const visible = [];
2328
+ for (let index = minLineY; index < maxLineY; index++) {
2329
+ visible.push({
2330
+ ...ports[index],
2331
+ index,
2332
+ selected: index === focusedIndex
2333
+ });
2334
+ }
2335
+ return visible;
2336
+ };
2337
+
2338
+ const emptyBody = {
2339
+ childCount: 1,
2340
+ className: PortsTableBody,
2341
+ role: RowGroup,
2342
+ type: Div
2343
+ };
2344
+ const emptyMessage = {
2345
+ childCount: 1,
2346
+ className: PortsEmpty,
2347
+ role: Status,
2348
+ type: Div
2349
+ };
2350
+ const getPortsTableBodyVirtualDom = state => {
2351
+ const {
2352
+ loaded,
2353
+ ports
2354
+ } = state;
2355
+ if (loaded && ports.length === 0) {
2356
+ return [emptyBody, emptyMessage, text('No forwarded ports')];
2357
+ }
2358
+ const visible = getVisiblePorts(state);
2359
+ return [{
2360
+ ariaRowCount: ports.length + 1,
2361
+ childCount: visible.length,
2362
+ className: PortsTableBody,
2363
+ role: RowGroup,
2364
+ type: Div
2365
+ }, ...visible.flatMap(getPortRowVirtualDom)];
2366
+ };
2367
+
2368
+ const headerRow = {
2369
+ childCount: 5,
2370
+ className: PortsTableHeader,
2371
+ role: Row,
2372
+ type: Div
2373
+ };
2374
+ const getHeaderCell = (label, className) => {
2375
+ return [{
2376
+ childCount: 1,
2377
+ className: mergeClassNames(PortsTableCell, className),
2378
+ role: ColumnHeader,
2379
+ type: Div
2380
+ }, text(label)];
2381
+ };
2382
+ const getPortsTableHeaderVirtualDom = () => {
2383
+ return [headerRow, ...getHeaderCell('', 'PortsStatusColumn'), ...getHeaderCell('Port', 'PortsPortColumn'), ...getHeaderCell('Forwarded Address', 'PortsAddressColumn'), ...getHeaderCell('Running Process', 'PortsProcessColumn'), ...getHeaderCell('Origin', 'PortsOriginColumn')];
2384
+ };
2385
+
2386
+ const table = {
2387
+ childCount: 2,
2388
+ className: PortsTable,
2389
+ type: Div
2390
+ };
2391
+ const getPortsVirtualDom = state => {
2392
+ const {
2393
+ ports
2394
+ } = state;
2395
+ return [{
2396
+ ariaLabel: 'Ports',
2397
+ ariaRowCount: ports.length + 1,
2398
+ childCount: 2,
2399
+ className: mergeClassNames(Viewlet, Ports),
2400
+ onBlur: HandleBlur,
2401
+ onClick: HandleClick,
2402
+ onFocus: HandleFocus,
2403
+ onWheel: HandleWheel,
2404
+ role: Table,
2405
+ tabIndex: Focusable,
2406
+ type: Div
2407
+ }, table, ...getPortsTableHeaderVirtualDom(), ...getPortsTableBodyVirtualDom(state), ...getPortsFooterVirtualDom(state)];
2408
+ };
2409
+
2410
+ const renderDom = (oldState, newState) => {
2411
+ return [SetDom2, newState.uid, getPortsVirtualDom(newState)];
2412
+ };
2413
+
2414
+ const renderFocusContext = (oldState, newState) => {
2415
+ if (!newState.focused) {
2416
+ return ['Viewlet.unsetAdditionalFocus', newState.uid, FocusPorts];
2417
+ }
2418
+ return [SetFocusContext, newState.uid, newState.editing ? Empty : FocusPorts];
2419
+ };
2420
+
2421
+ const renderIncremental = (oldState, newState) => {
2422
+ const oldDom = getPortsVirtualDom(oldState);
2423
+ const newDom = getPortsVirtualDom(newState);
2424
+ return [SetPatches, newState.uid, diffTree(oldDom, newDom)];
2425
+ };
2426
+
2427
+ const getRenderer = diffType => {
2428
+ switch (diffType) {
2429
+ case RenderCss:
2430
+ return renderCss;
2431
+ case RenderDom:
2432
+ return renderDom;
2433
+ case RenderFocusContext:
2434
+ return renderFocusContext;
2435
+ case RenderIncremental:
2436
+ return renderIncremental;
2437
+ default:
2438
+ throw new Error(`Unknown diff type ${diffType}`);
2439
+ }
2440
+ };
2441
+ const render2 = (uid, diffResult) => {
2442
+ const {
2443
+ newState,
2444
+ oldState
2445
+ } = get(uid);
2446
+ set(uid, newState, newState);
2447
+ return diffResult.map(diffType => getRenderer(diffType)(oldState, newState));
2448
+ };
2449
+
2450
+ const renderEventListeners = () => {
2451
+ return [{
2452
+ name: HandleAddPortInput,
2453
+ params: ['handleAddPortInput', TargetValue]
2454
+ }, {
2455
+ name: HandleAddPortKeyDown,
2456
+ params: ['handleAddPortKeyDown', Key]
2457
+ }, {
2458
+ name: HandleBlur,
2459
+ params: ['handleBlur']
2460
+ }, {
2461
+ name: HandleCancelAddPort,
2462
+ params: ['cancelAddPort']
2463
+ }, {
2464
+ name: HandleClick,
2465
+ params: ['handleClick', ClientY, TargetName]
2466
+ }, {
2467
+ name: HandleFocus,
2468
+ params: ['handleFocus']
2469
+ }, {
2470
+ name: HandleStartAddPort,
2471
+ params: ['startAddPort']
2472
+ }, {
2473
+ name: HandleSubmitAddPort,
2474
+ params: ['submitAddPort']
2475
+ }, {
2476
+ name: HandleWheel,
2477
+ params: ['handleWheel', DeltaMode, DeltaY],
2478
+ passive: true
2479
+ }];
2480
+ };
2481
+
2482
+ const resize = (state, dimensions) => {
2483
+ return recalculateVirtualList({
2484
+ ...state,
2485
+ ...dimensions
2486
+ });
2487
+ };
2488
+
2489
+ const toggleFocusedPort = state => {
2490
+ const {
2491
+ editing,
2492
+ focusedIndex,
2493
+ ports
2494
+ } = state;
2495
+ const selected = ports[focusedIndex];
2496
+ if (editing || !selected) {
2497
+ return state;
2498
+ }
2499
+ return togglePortActive(state, selected.port);
2500
+ };
2501
+
2502
+ const commandMap = {
2503
+ 'Ports.addPort': wrapCommand(addPort),
2504
+ 'Ports.cancelAddPort': wrapCommand(cancelAddPort),
2505
+ 'Ports.create': create,
2506
+ 'Ports.diff2': diff2,
2507
+ 'Ports.dispose': dispose,
2508
+ 'Ports.focusFirst': wrapCommand(focusFirst),
2509
+ 'Ports.focusIndex': wrapCommand(focusIndex),
2510
+ 'Ports.focusLast': wrapCommand(focusLast),
2511
+ 'Ports.focusNext': wrapCommand(focusNext),
2512
+ 'Ports.focusPrevious': wrapCommand(focusPrevious),
2513
+ 'Ports.getCommandIds': getCommandIds,
2514
+ 'Ports.getKeyBindings': getKeyBindings,
2515
+ 'Ports.handleAddPortInput': wrapCommand(handleAddPortInput),
2516
+ 'Ports.handleAddPortKeyDown': wrapCommand(handleAddPortKeyDown),
2517
+ 'Ports.handleBlur': wrapCommand(handleBlur),
2518
+ 'Ports.handleClick': wrapCommand(handleClick),
2519
+ 'Ports.handleFocus': wrapCommand(handleFocus),
2520
+ 'Ports.handleWheel': wrapCommand(handleWheel),
2521
+ 'Ports.handleWorkspaceChange': wrapCommand(loadContent),
2522
+ 'Ports.loadContent': wrapCommand(loadContent),
2523
+ 'Ports.openAddress': wrapCommand(openAddress),
2524
+ 'Ports.openFocusedAddress': wrapCommand(openFocusedAddress),
2525
+ 'Ports.removeFocusedPort': wrapCommand(removeFocusedPort),
2526
+ 'Ports.removePort': wrapCommand(removePort),
2527
+ 'Ports.render2': render2,
2528
+ 'Ports.renderEventListeners': renderEventListeners,
2529
+ 'Ports.resize': wrapCommand(resize),
2530
+ 'Ports.setDeltaY': wrapCommand(setDeltaY),
2531
+ 'Ports.setPorts': wrapCommand(setPorts),
2532
+ 'Ports.startAddPort': wrapCommand(startAddPort),
2533
+ 'Ports.submitAddPort': wrapCommand(submitAddPort),
2534
+ 'Ports.terminate': terminate,
2535
+ 'Ports.toggleFocusedPort': wrapCommand(toggleFocusedPort),
2536
+ 'Ports.togglePortActive': wrapCommand(togglePortActive)
2537
+ };
2538
+
2539
+ const listen = async () => {
2540
+ registerCommands(commandMap);
2541
+ const rpc = await create$3({
2542
+ commandMap: commandMap
2543
+ });
2544
+ set$1(rpc);
2545
+ };
2546
+
2547
+ const main = async () => {
2548
+ await listen();
2549
+ };
2550
+
2551
+ main();