@lvce-editor/output-view 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Lvce Editor
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,16 @@
1
+ # Output View
2
+
3
+ WebWorker for the output view functionality in Lvce Editor.
4
+
5
+ ## Contributing
6
+
7
+ ```sh
8
+ git clone git@github.com:lvce-editor/output-view.git &&
9
+ cd output-view &&
10
+ npm ci &&
11
+ npm test
12
+ ```
13
+
14
+ ## Gitpod
15
+
16
+ [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/lvce-editor/output-view)
@@ -0,0 +1,1284 @@
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
+ return;
100
+ }
101
+ };
102
+ const getTransferrables = value => {
103
+ const transferrables = [];
104
+ walkValue(value, transferrables, isTransferrable);
105
+ return transferrables;
106
+ };
107
+ const attachEvents = that => {
108
+ const handleMessage = (...args) => {
109
+ const data = that.getData(...args);
110
+ that.dispatchEvent(new MessageEvent('message', {
111
+ data
112
+ }));
113
+ };
114
+ that.onMessage(handleMessage);
115
+ const handleClose = event => {
116
+ that.dispatchEvent(new Event('close'));
117
+ };
118
+ that.onClose(handleClose);
119
+ };
120
+ class Ipc extends EventTarget {
121
+ constructor(rawIpc) {
122
+ super();
123
+ this._rawIpc = rawIpc;
124
+ attachEvents(this);
125
+ }
126
+ }
127
+ const E_INCOMPATIBLE_NATIVE_MODULE = 'E_INCOMPATIBLE_NATIVE_MODULE';
128
+ const E_MODULES_NOT_SUPPORTED_IN_ELECTRON = 'E_MODULES_NOT_SUPPORTED_IN_ELECTRON';
129
+ const ERR_MODULE_NOT_FOUND = 'ERR_MODULE_NOT_FOUND';
130
+ const NewLine$1 = '\n';
131
+ const joinLines$1 = lines => {
132
+ return lines.join(NewLine$1);
133
+ };
134
+ const RE_AT = /^\s+at/;
135
+ const RE_AT_PROMISE_INDEX = /^\s*at async Promise.all \(index \d+\)$/;
136
+ const isNormalStackLine = line => {
137
+ return RE_AT.test(line) && !RE_AT_PROMISE_INDEX.test(line);
138
+ };
139
+ const getDetails = lines => {
140
+ const index = lines.findIndex(isNormalStackLine);
141
+ if (index === -1) {
142
+ return {
143
+ actualMessage: joinLines$1(lines),
144
+ rest: []
145
+ };
146
+ }
147
+ let lastIndex = index - 1;
148
+ while (++lastIndex < lines.length) {
149
+ if (!isNormalStackLine(lines[lastIndex])) {
150
+ break;
151
+ }
152
+ }
153
+ return {
154
+ actualMessage: lines[index - 1],
155
+ rest: lines.slice(index, lastIndex)
156
+ };
157
+ };
158
+ const splitLines$1 = lines => {
159
+ return lines.split(NewLine$1);
160
+ };
161
+ const RE_MESSAGE_CODE_BLOCK_START = /^Error: The module '.*'$/;
162
+ const RE_MESSAGE_CODE_BLOCK_END = /^\s* at/;
163
+ const isMessageCodeBlockStartIndex = line => {
164
+ return RE_MESSAGE_CODE_BLOCK_START.test(line);
165
+ };
166
+ const isMessageCodeBlockEndIndex = line => {
167
+ return RE_MESSAGE_CODE_BLOCK_END.test(line);
168
+ };
169
+ const getMessageCodeBlock = stderr => {
170
+ const lines = splitLines$1(stderr);
171
+ const startIndex = lines.findIndex(isMessageCodeBlockStartIndex);
172
+ const endIndex = startIndex + lines.slice(startIndex).findIndex(isMessageCodeBlockEndIndex, startIndex);
173
+ const relevantLines = lines.slice(startIndex, endIndex);
174
+ const relevantMessage = relevantLines.join(' ').slice('Error: '.length);
175
+ return relevantMessage;
176
+ };
177
+ const isModuleNotFoundMessage = line => {
178
+ return line.includes('[ERR_MODULE_NOT_FOUND]');
179
+ };
180
+ const getModuleNotFoundError = stderr => {
181
+ const lines = splitLines$1(stderr);
182
+ const messageIndex = lines.findIndex(isModuleNotFoundMessage);
183
+ const message = lines[messageIndex];
184
+ return {
185
+ message,
186
+ code: ERR_MODULE_NOT_FOUND
187
+ };
188
+ };
189
+ const isModuleNotFoundError = stderr => {
190
+ if (!stderr) {
191
+ return false;
192
+ }
193
+ return stderr.includes('ERR_MODULE_NOT_FOUND');
194
+ };
195
+ const isModulesSyntaxError = stderr => {
196
+ if (!stderr) {
197
+ return false;
198
+ }
199
+ return stderr.includes('SyntaxError: Cannot use import statement outside a module');
200
+ };
201
+ const RE_NATIVE_MODULE_ERROR = /^innerError Error: Cannot find module '.*.node'/;
202
+ const RE_NATIVE_MODULE_ERROR_2 = /was compiled against a different Node.js version/;
203
+ const isUnhelpfulNativeModuleError = stderr => {
204
+ return RE_NATIVE_MODULE_ERROR.test(stderr) && RE_NATIVE_MODULE_ERROR_2.test(stderr);
205
+ };
206
+ const getNativeModuleErrorMessage = stderr => {
207
+ const message = getMessageCodeBlock(stderr);
208
+ return {
209
+ message: `Incompatible native node module: ${message}`,
210
+ code: E_INCOMPATIBLE_NATIVE_MODULE
211
+ };
212
+ };
213
+ const getModuleSyntaxError = () => {
214
+ return {
215
+ message: `ES Modules are not supported in electron`,
216
+ code: E_MODULES_NOT_SUPPORTED_IN_ELECTRON
217
+ };
218
+ };
219
+ const getHelpfulChildProcessError = (stdout, stderr) => {
220
+ if (isUnhelpfulNativeModuleError(stderr)) {
221
+ return getNativeModuleErrorMessage(stderr);
222
+ }
223
+ if (isModulesSyntaxError(stderr)) {
224
+ return getModuleSyntaxError();
225
+ }
226
+ if (isModuleNotFoundError(stderr)) {
227
+ return getModuleNotFoundError(stderr);
228
+ }
229
+ const lines = splitLines$1(stderr);
230
+ const {
231
+ actualMessage,
232
+ rest
233
+ } = getDetails(lines);
234
+ return {
235
+ message: actualMessage,
236
+ code: '',
237
+ stack: rest
238
+ };
239
+ };
240
+ class IpcError extends VError {
241
+ // @ts-ignore
242
+ constructor(betterMessage, stdout = '', stderr = '') {
243
+ if (stdout || stderr) {
244
+ // @ts-ignore
245
+ const {
246
+ message,
247
+ code,
248
+ stack
249
+ } = getHelpfulChildProcessError(stdout, stderr);
250
+ const cause = new Error(message);
251
+ // @ts-ignore
252
+ cause.code = code;
253
+ cause.stack = stack;
254
+ super(cause, betterMessage);
255
+ } else {
256
+ super(betterMessage);
257
+ }
258
+ // @ts-ignore
259
+ this.name = 'IpcError';
260
+ // @ts-ignore
261
+ this.stdout = stdout;
262
+ // @ts-ignore
263
+ this.stderr = stderr;
264
+ }
265
+ }
266
+ const readyMessage = 'ready';
267
+ const getData$2 = event => {
268
+ return event.data;
269
+ };
270
+ const listen$7 = () => {
271
+ // @ts-ignore
272
+ if (typeof WorkerGlobalScope === 'undefined') {
273
+ throw new TypeError('module is not in web worker scope');
274
+ }
275
+ return globalThis;
276
+ };
277
+ const signal$8 = global => {
278
+ global.postMessage(readyMessage);
279
+ };
280
+ class IpcChildWithModuleWorker extends Ipc {
281
+ getData(event) {
282
+ return getData$2(event);
283
+ }
284
+ send(message) {
285
+ // @ts-ignore
286
+ this._rawIpc.postMessage(message);
287
+ }
288
+ sendAndTransfer(message) {
289
+ const transfer = getTransferrables(message);
290
+ // @ts-ignore
291
+ this._rawIpc.postMessage(message, transfer);
292
+ }
293
+ dispose() {
294
+ // ignore
295
+ }
296
+ onClose(callback) {
297
+ // ignore
298
+ }
299
+ onMessage(callback) {
300
+ this._rawIpc.addEventListener('message', callback);
301
+ }
302
+ }
303
+ const wrap$f = global => {
304
+ return new IpcChildWithModuleWorker(global);
305
+ };
306
+ const waitForFirstMessage = async port => {
307
+ const {
308
+ resolve,
309
+ promise
310
+ } = Promise.withResolvers();
311
+ port.addEventListener('message', resolve, {
312
+ once: true
313
+ });
314
+ const event = await promise;
315
+ // @ts-ignore
316
+ return event.data;
317
+ };
318
+ const listen$6 = async () => {
319
+ const parentIpcRaw = listen$7();
320
+ signal$8(parentIpcRaw);
321
+ const parentIpc = wrap$f(parentIpcRaw);
322
+ const firstMessage = await waitForFirstMessage(parentIpc);
323
+ if (firstMessage.method !== 'initialize') {
324
+ throw new IpcError('unexpected first message');
325
+ }
326
+ const type = firstMessage.params[0];
327
+ if (type === 'message-port') {
328
+ parentIpc.send({
329
+ jsonrpc: '2.0',
330
+ id: firstMessage.id,
331
+ result: null
332
+ });
333
+ parentIpc.dispose();
334
+ const port = firstMessage.params[1];
335
+ return port;
336
+ }
337
+ return globalThis;
338
+ };
339
+ class IpcChildWithModuleWorkerAndMessagePort extends Ipc {
340
+ getData(event) {
341
+ return getData$2(event);
342
+ }
343
+ send(message) {
344
+ this._rawIpc.postMessage(message);
345
+ }
346
+ sendAndTransfer(message) {
347
+ const transfer = getTransferrables(message);
348
+ this._rawIpc.postMessage(message, transfer);
349
+ }
350
+ dispose() {
351
+ if (this._rawIpc.close) {
352
+ this._rawIpc.close();
353
+ }
354
+ }
355
+ onClose(callback) {
356
+ // ignore
357
+ }
358
+ onMessage(callback) {
359
+ this._rawIpc.addEventListener('message', callback);
360
+ this._rawIpc.start();
361
+ }
362
+ }
363
+ const wrap$e = port => {
364
+ return new IpcChildWithModuleWorkerAndMessagePort(port);
365
+ };
366
+ const IpcChildWithModuleWorkerAndMessagePort$1 = {
367
+ __proto__: null,
368
+ listen: listen$6,
369
+ wrap: wrap$e
370
+ };
371
+
372
+ const Two = '2.0';
373
+ const create$4 = (method, params) => {
374
+ return {
375
+ jsonrpc: Two,
376
+ method,
377
+ params
378
+ };
379
+ };
380
+ const callbacks = Object.create(null);
381
+ const set$2 = (id, fn) => {
382
+ callbacks[id] = fn;
383
+ };
384
+ const get$2 = id => {
385
+ return callbacks[id];
386
+ };
387
+ const remove = id => {
388
+ delete callbacks[id];
389
+ };
390
+ let id = 0;
391
+ const create$3$1 = () => {
392
+ return ++id;
393
+ };
394
+ const registerPromise = () => {
395
+ const id = create$3$1();
396
+ const {
397
+ resolve,
398
+ promise
399
+ } = Promise.withResolvers();
400
+ set$2(id, resolve);
401
+ return {
402
+ id,
403
+ promise
404
+ };
405
+ };
406
+ const create$2$1 = (method, params) => {
407
+ const {
408
+ id,
409
+ promise
410
+ } = registerPromise();
411
+ const message = {
412
+ jsonrpc: Two,
413
+ method,
414
+ params,
415
+ id
416
+ };
417
+ return {
418
+ message,
419
+ promise
420
+ };
421
+ };
422
+ class JsonRpcError extends Error {
423
+ constructor(message) {
424
+ super(message);
425
+ this.name = 'JsonRpcError';
426
+ }
427
+ }
428
+ const NewLine = '\n';
429
+ const DomException = 'DOMException';
430
+ const ReferenceError$1 = 'ReferenceError';
431
+ const SyntaxError$1 = 'SyntaxError';
432
+ const TypeError$1 = 'TypeError';
433
+ const getErrorConstructor = (message, type) => {
434
+ if (type) {
435
+ switch (type) {
436
+ case DomException:
437
+ return DOMException;
438
+ case TypeError$1:
439
+ return TypeError;
440
+ case SyntaxError$1:
441
+ return SyntaxError;
442
+ case ReferenceError$1:
443
+ return ReferenceError;
444
+ default:
445
+ return Error;
446
+ }
447
+ }
448
+ if (message.startsWith('TypeError: ')) {
449
+ return TypeError;
450
+ }
451
+ if (message.startsWith('SyntaxError: ')) {
452
+ return SyntaxError;
453
+ }
454
+ if (message.startsWith('ReferenceError: ')) {
455
+ return ReferenceError;
456
+ }
457
+ return Error;
458
+ };
459
+ const constructError = (message, type, name) => {
460
+ const ErrorConstructor = getErrorConstructor(message, type);
461
+ if (ErrorConstructor === DOMException && name) {
462
+ return new ErrorConstructor(message, name);
463
+ }
464
+ if (ErrorConstructor === Error) {
465
+ const error = new Error(message);
466
+ if (name && name !== 'VError') {
467
+ error.name = name;
468
+ }
469
+ return error;
470
+ }
471
+ return new ErrorConstructor(message);
472
+ };
473
+ const joinLines = lines => {
474
+ return lines.join(NewLine);
475
+ };
476
+ const splitLines = lines => {
477
+ return lines.split(NewLine);
478
+ };
479
+ const getCurrentStack = () => {
480
+ const stackLinesToSkip = 3;
481
+ const currentStack = joinLines(splitLines(new Error().stack || '').slice(stackLinesToSkip));
482
+ return currentStack;
483
+ };
484
+ const getNewLineIndex = (string, startIndex = undefined) => {
485
+ return string.indexOf(NewLine, startIndex);
486
+ };
487
+ const getParentStack = error => {
488
+ let parentStack = error.stack || error.data || error.message || '';
489
+ if (parentStack.startsWith(' at')) {
490
+ parentStack = error.message + NewLine + parentStack;
491
+ }
492
+ return parentStack;
493
+ };
494
+ const MethodNotFound = -32601;
495
+ const Custom = -32001;
496
+ const restoreJsonRpcError = error => {
497
+ const currentStack = getCurrentStack();
498
+ if (error && error instanceof Error) {
499
+ if (typeof error.stack === 'string') {
500
+ error.stack = error.stack + NewLine + currentStack;
501
+ }
502
+ return error;
503
+ }
504
+ if (error && error.code && error.code === MethodNotFound) {
505
+ const restoredError = new JsonRpcError(error.message);
506
+ const parentStack = getParentStack(error);
507
+ restoredError.stack = parentStack + NewLine + currentStack;
508
+ return restoredError;
509
+ }
510
+ if (error && error.message) {
511
+ const restoredError = constructError(error.message, error.type, error.name);
512
+ if (error.data) {
513
+ if (error.data.stack && error.data.type && error.message) {
514
+ restoredError.stack = error.data.type + ': ' + error.message + NewLine + error.data.stack + NewLine + currentStack;
515
+ } else if (error.data.stack) {
516
+ restoredError.stack = error.data.stack;
517
+ }
518
+ if (error.data.codeFrame) {
519
+ // @ts-ignore
520
+ restoredError.codeFrame = error.data.codeFrame;
521
+ }
522
+ if (error.data.code) {
523
+ // @ts-ignore
524
+ restoredError.code = error.data.code;
525
+ }
526
+ if (error.data.type) {
527
+ // @ts-ignore
528
+ restoredError.name = error.data.type;
529
+ }
530
+ } else {
531
+ if (error.stack) {
532
+ const lowerStack = restoredError.stack || '';
533
+ // @ts-ignore
534
+ const indexNewLine = getNewLineIndex(lowerStack);
535
+ const parentStack = getParentStack(error);
536
+ // @ts-ignore
537
+ restoredError.stack = parentStack + lowerStack.slice(indexNewLine);
538
+ }
539
+ if (error.codeFrame) {
540
+ // @ts-ignore
541
+ restoredError.codeFrame = error.codeFrame;
542
+ }
543
+ }
544
+ return restoredError;
545
+ }
546
+ if (typeof error === 'string') {
547
+ return new Error(`JsonRpc Error: ${error}`);
548
+ }
549
+ return new Error(`JsonRpc Error: ${error}`);
550
+ };
551
+ const unwrapJsonRpcResult = responseMessage => {
552
+ if ('error' in responseMessage) {
553
+ const restoredError = restoreJsonRpcError(responseMessage.error);
554
+ throw restoredError;
555
+ }
556
+ if ('result' in responseMessage) {
557
+ return responseMessage.result;
558
+ }
559
+ throw new JsonRpcError('unexpected response message');
560
+ };
561
+ const warn = (...args) => {
562
+ console.warn(...args);
563
+ };
564
+ const resolve = (id, response) => {
565
+ const fn = get$2(id);
566
+ if (!fn) {
567
+ console.log(response);
568
+ warn(`callback ${id} may already be disposed`);
569
+ return;
570
+ }
571
+ fn(response);
572
+ remove(id);
573
+ };
574
+ const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
575
+ const getErrorType = prettyError => {
576
+ if (prettyError && prettyError.type) {
577
+ return prettyError.type;
578
+ }
579
+ if (prettyError && prettyError.constructor && prettyError.constructor.name) {
580
+ return prettyError.constructor.name;
581
+ }
582
+ return undefined;
583
+ };
584
+ const isAlreadyStack = line => {
585
+ return line.trim().startsWith('at ');
586
+ };
587
+ const getStack = prettyError => {
588
+ const stackString = prettyError.stack || '';
589
+ const newLineIndex = stackString.indexOf('\n');
590
+ if (newLineIndex !== -1 && !isAlreadyStack(stackString.slice(0, newLineIndex))) {
591
+ return stackString.slice(newLineIndex + 1);
592
+ }
593
+ return stackString;
594
+ };
595
+ const getErrorProperty = (error, prettyError) => {
596
+ if (error && error.code === E_COMMAND_NOT_FOUND) {
597
+ return {
598
+ code: MethodNotFound,
599
+ message: error.message,
600
+ data: error.stack
601
+ };
602
+ }
603
+ return {
604
+ code: Custom,
605
+ message: prettyError.message,
606
+ data: {
607
+ stack: getStack(prettyError),
608
+ codeFrame: prettyError.codeFrame,
609
+ type: getErrorType(prettyError),
610
+ code: prettyError.code,
611
+ name: prettyError.name
612
+ }
613
+ };
614
+ };
615
+ const create$1$1 = (id, error) => {
616
+ return {
617
+ jsonrpc: Two,
618
+ id,
619
+ error
620
+ };
621
+ };
622
+ const getErrorResponse = (id, error, preparePrettyError, logError) => {
623
+ const prettyError = preparePrettyError(error);
624
+ logError(error, prettyError);
625
+ const errorProperty = getErrorProperty(error, prettyError);
626
+ return create$1$1(id, errorProperty);
627
+ };
628
+ const create$5 = (message, result) => {
629
+ return {
630
+ jsonrpc: Two,
631
+ id: message.id,
632
+ result: result ?? null
633
+ };
634
+ };
635
+ const getSuccessResponse = (message, result) => {
636
+ const resultProperty = result ?? null;
637
+ return create$5(message, resultProperty);
638
+ };
639
+ const getErrorResponseSimple = (id, error) => {
640
+ return {
641
+ jsonrpc: Two,
642
+ id,
643
+ error: {
644
+ code: Custom,
645
+ // @ts-ignore
646
+ message: error.message,
647
+ data: error
648
+ }
649
+ };
650
+ };
651
+ const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
652
+ try {
653
+ const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
654
+ return getSuccessResponse(message, result);
655
+ } catch (error) {
656
+ if (ipc.canUseSimpleErrorResponse) {
657
+ return getErrorResponseSimple(message.id, error);
658
+ }
659
+ return getErrorResponse(message.id, error, preparePrettyError, logError);
660
+ }
661
+ };
662
+ const defaultPreparePrettyError = error => {
663
+ return error;
664
+ };
665
+ const defaultLogError = () => {
666
+ // ignore
667
+ };
668
+ const defaultRequiresSocket = () => {
669
+ return false;
670
+ };
671
+ const defaultResolve = resolve;
672
+
673
+ // TODO maybe remove this in v6 or v7, only accept options object to simplify the code
674
+ const normalizeParams = args => {
675
+ if (args.length === 1) {
676
+ const options = args[0];
677
+ return {
678
+ ipc: options.ipc,
679
+ message: options.message,
680
+ execute: options.execute,
681
+ resolve: options.resolve || defaultResolve,
682
+ preparePrettyError: options.preparePrettyError || defaultPreparePrettyError,
683
+ logError: options.logError || defaultLogError,
684
+ requiresSocket: options.requiresSocket || defaultRequiresSocket
685
+ };
686
+ }
687
+ return {
688
+ ipc: args[0],
689
+ message: args[1],
690
+ execute: args[2],
691
+ resolve: args[3],
692
+ preparePrettyError: args[4],
693
+ logError: args[5],
694
+ requiresSocket: args[6]
695
+ };
696
+ };
697
+ const handleJsonRpcMessage = async (...args) => {
698
+ const options = normalizeParams(args);
699
+ const {
700
+ message,
701
+ ipc,
702
+ execute,
703
+ resolve,
704
+ preparePrettyError,
705
+ logError,
706
+ requiresSocket
707
+ } = options;
708
+ if ('id' in message) {
709
+ if ('method' in message) {
710
+ const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
711
+ try {
712
+ ipc.send(response);
713
+ } catch (error) {
714
+ const errorResponse = getErrorResponse(message.id, error, preparePrettyError, logError);
715
+ ipc.send(errorResponse);
716
+ }
717
+ return;
718
+ }
719
+ resolve(message.id, message);
720
+ return;
721
+ }
722
+ if ('method' in message) {
723
+ await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
724
+ return;
725
+ }
726
+ throw new JsonRpcError('unexpected message');
727
+ };
728
+ const invokeHelper = async (ipc, method, params, useSendAndTransfer) => {
729
+ const {
730
+ message,
731
+ promise
732
+ } = create$2$1(method, params);
733
+ if (useSendAndTransfer && ipc.sendAndTransfer) {
734
+ ipc.sendAndTransfer(message);
735
+ } else {
736
+ ipc.send(message);
737
+ }
738
+ const responseMessage = await promise;
739
+ return unwrapJsonRpcResult(responseMessage);
740
+ };
741
+ const send = (transport, method, ...params) => {
742
+ const message = create$4(method, params);
743
+ transport.send(message);
744
+ };
745
+ const invoke = (ipc, method, ...params) => {
746
+ return invokeHelper(ipc, method, params, false);
747
+ };
748
+ const invokeAndTransfer = (ipc, method, ...params) => {
749
+ return invokeHelper(ipc, method, params, true);
750
+ };
751
+
752
+ class CommandNotFoundError extends Error {
753
+ constructor(command) {
754
+ super(`Command not found ${command}`);
755
+ this.name = 'CommandNotFoundError';
756
+ }
757
+ }
758
+ const commands = Object.create(null);
759
+ const register = commandMap => {
760
+ Object.assign(commands, commandMap);
761
+ };
762
+ const getCommand = key => {
763
+ return commands[key];
764
+ };
765
+ const execute = (command, ...args) => {
766
+ const fn = getCommand(command);
767
+ if (!fn) {
768
+ throw new CommandNotFoundError(command);
769
+ }
770
+ return fn(...args);
771
+ };
772
+
773
+ const createRpc = ipc => {
774
+ const rpc = {
775
+ // @ts-ignore
776
+ ipc,
777
+ /**
778
+ * @deprecated
779
+ */
780
+ send(method, ...params) {
781
+ send(ipc, method, ...params);
782
+ },
783
+ invoke(method, ...params) {
784
+ return invoke(ipc, method, ...params);
785
+ },
786
+ invokeAndTransfer(method, ...params) {
787
+ return invokeAndTransfer(ipc, method, ...params);
788
+ },
789
+ async dispose() {
790
+ await ipc?.dispose();
791
+ }
792
+ };
793
+ return rpc;
794
+ };
795
+ const requiresSocket = () => {
796
+ return false;
797
+ };
798
+ const preparePrettyError = error => {
799
+ return error;
800
+ };
801
+ const logError = () => {
802
+ // handled by renderer worker
803
+ };
804
+ const handleMessage = event => {
805
+ const actualRequiresSocket = event?.target?.requiresSocket || requiresSocket;
806
+ const actualExecute = event?.target?.execute || execute;
807
+ return handleJsonRpcMessage(event.target, event.data, actualExecute, resolve, preparePrettyError, logError, actualRequiresSocket);
808
+ };
809
+ const handleIpc = ipc => {
810
+ if ('addEventListener' in ipc) {
811
+ ipc.addEventListener('message', handleMessage);
812
+ } else if ('on' in ipc) {
813
+ // deprecated
814
+ ipc.on('message', handleMessage);
815
+ }
816
+ };
817
+ const listen$1 = async (module, options) => {
818
+ const rawIpc = await module.listen(options);
819
+ if (module.signal) {
820
+ module.signal(rawIpc);
821
+ }
822
+ const ipc = module.wrap(rawIpc);
823
+ return ipc;
824
+ };
825
+ const create$3 = async ({
826
+ commandMap
827
+ }) => {
828
+ // TODO create a commandMap per rpc instance
829
+ register(commandMap);
830
+ const ipc = await listen$1(IpcChildWithModuleWorkerAndMessagePort$1);
831
+ handleIpc(ipc);
832
+ const rpc = createRpc(ipc);
833
+ return rpc;
834
+ };
835
+ const WebWorkerRpcClient = {
836
+ __proto__: null,
837
+ create: create$3
838
+ };
839
+
840
+ const toCommandId$1 = key => {
841
+ const dotIndex = key.indexOf('.');
842
+ return key.slice(dotIndex + 1);
843
+ };
844
+ const create$2 = () => {
845
+ const states = Object.create(null);
846
+ const commandMapRef = {};
847
+ return {
848
+ get(uid) {
849
+ return states[uid];
850
+ },
851
+ set(uid, oldState, newState) {
852
+ states[uid] = {
853
+ oldState,
854
+ newState
855
+ };
856
+ },
857
+ dispose(uid) {
858
+ delete states[uid];
859
+ },
860
+ getKeys() {
861
+ return Object.keys(states).map(key => {
862
+ return Number.parseInt(key);
863
+ });
864
+ },
865
+ clear() {
866
+ for (const key of Object.keys(states)) {
867
+ delete states[key];
868
+ }
869
+ },
870
+ wrapCommand(fn) {
871
+ const wrapped = async (uid, ...args) => {
872
+ const {
873
+ newState
874
+ } = states[uid];
875
+ const newerState = await fn(newState, ...args);
876
+ if (newState === newerState) {
877
+ return;
878
+ }
879
+ const latest = states[uid];
880
+ states[uid] = {
881
+ oldState: latest.oldState,
882
+ newState: newerState
883
+ };
884
+ };
885
+ return wrapped;
886
+ },
887
+ wrapGetter(fn) {
888
+ const wrapped = (uid, ...args) => {
889
+ const {
890
+ newState
891
+ } = states[uid];
892
+ return fn(newState, ...args);
893
+ };
894
+ return wrapped;
895
+ },
896
+ diff(uid, modules, numbers) {
897
+ const {
898
+ oldState,
899
+ newState
900
+ } = states[uid];
901
+ const diffResult = [];
902
+ for (let i = 0; i < modules.length; i++) {
903
+ const fn = modules[i];
904
+ if (!fn(oldState, newState)) {
905
+ diffResult.push(numbers[i]);
906
+ }
907
+ }
908
+ return diffResult;
909
+ },
910
+ getCommandIds() {
911
+ const keys = Object.keys(commandMapRef);
912
+ const ids = keys.map(toCommandId$1);
913
+ return ids;
914
+ },
915
+ registerCommands(commandMap) {
916
+ Object.assign(commandMapRef, commandMap);
917
+ }
918
+ };
919
+ };
920
+ const terminate = () => {
921
+ globalThis.close();
922
+ };
923
+
924
+ const User = 1;
925
+ const Script = 2;
926
+
927
+ const {
928
+ get: get$1,
929
+ set: set$1,
930
+ wrapCommand
931
+ } = create$2();
932
+
933
+ const create$1 = (id, uri, x, y, width, height, workspaceUri) => {
934
+ const state = {
935
+ uid: id,
936
+ focusedIndex: -2,
937
+ message: '',
938
+ itemHeight: 22,
939
+ x,
940
+ y,
941
+ width,
942
+ height,
943
+ filterValue: '',
944
+ inputSource: User,
945
+ minLineY: 0,
946
+ maxLineY: 0,
947
+ listItems: [],
948
+ collapsedUris: [],
949
+ smallWidthBreakPoint: 650,
950
+ workspaceUri
951
+ };
952
+ set$1(id, state, state);
953
+ };
954
+
955
+ const isEqual$1 = (oldState, newState) => {
956
+ return newState.inputSource === User || oldState.filterValue === newState.filterValue;
957
+ };
958
+
959
+ const isEqual = (oldState, newState) => {
960
+ return oldState.filterValue === newState.filterValue && oldState.message === newState.message;
961
+ };
962
+
963
+ const RenderItems = 1;
964
+ const RenderFilterValue = 2;
965
+
966
+ const modules = [isEqual, isEqual$1];
967
+ const numbers = [RenderItems, RenderFilterValue];
968
+
969
+ const diff = (oldState, newState) => {
970
+ const diffResult = [];
971
+ for (let i = 0; i < modules.length; i++) {
972
+ const fn = modules[i];
973
+ if (!fn(oldState, newState)) {
974
+ diffResult.push(numbers[i]);
975
+ }
976
+ }
977
+ return diffResult;
978
+ };
979
+
980
+ const diff2 = uid => {
981
+ const {
982
+ oldState,
983
+ newState
984
+ } = get$1(uid);
985
+ const diffResult = diff(oldState, newState);
986
+ return diffResult;
987
+ };
988
+
989
+ const focusIndex = (state, index) => {
990
+ return {
991
+ ...state,
992
+ focusedIndex: index
993
+ };
994
+ };
995
+
996
+ const commandMapRef = {};
997
+
998
+ const toCommandId = key => {
999
+ const dotIndex = key.indexOf('.');
1000
+ return key.slice(dotIndex + 1);
1001
+ };
1002
+ const getCommandIds = () => {
1003
+ const keys = Object.keys(commandMapRef);
1004
+ const ids = keys.map(toCommandId);
1005
+ return ids;
1006
+ };
1007
+
1008
+ const ToolBar = 'toolbar';
1009
+ const AriaRoles = {
1010
+ __proto__: null,
1011
+ ToolBar};
1012
+ const Space = 9;
1013
+ const PageUp = 10;
1014
+ const PageDown = 11;
1015
+ const End = 255;
1016
+ const Home = 12;
1017
+ const LeftArrow = 13;
1018
+ const UpArrow = 14;
1019
+ const RightArrow = 15;
1020
+ const DownArrow = 16;
1021
+ const KeyCode = {
1022
+ __proto__: null,
1023
+ DownArrow,
1024
+ End,
1025
+ Home,
1026
+ LeftArrow,
1027
+ PageDown,
1028
+ PageUp,
1029
+ RightArrow,
1030
+ Space,
1031
+ UpArrow
1032
+ };
1033
+ const Div = 4;
1034
+ const VirtualDomElements = {
1035
+ __proto__: null,
1036
+ Div};
1037
+
1038
+ const FocusProblems = 19;
1039
+
1040
+ const getKeyBindings = () => {
1041
+ return [{
1042
+ key: KeyCode.DownArrow,
1043
+ command: 'Problems.focusNext',
1044
+ when: FocusProblems
1045
+ }, {
1046
+ key: KeyCode.UpArrow,
1047
+ command: 'Problems.focusPrevious',
1048
+ when: FocusProblems
1049
+ }, {
1050
+ key: KeyCode.Home,
1051
+ command: 'Problems.focusFirst',
1052
+ when: FocusProblems
1053
+ }, {
1054
+ key: KeyCode.PageUp,
1055
+ command: 'Problems.focusFirst',
1056
+ when: FocusProblems
1057
+ }, {
1058
+ key: KeyCode.PageDown,
1059
+ command: 'Problems.focusLast',
1060
+ when: FocusProblems
1061
+ }, {
1062
+ key: KeyCode.End,
1063
+ command: 'Problems.focusLast',
1064
+ when: FocusProblems
1065
+ }, {
1066
+ key: KeyCode.Space,
1067
+ command: 'Problems.selectCurrent',
1068
+ when: FocusProblems
1069
+ }, {
1070
+ key: KeyCode.Home,
1071
+ command: 'Problems.focusFirst',
1072
+ when: FocusProblems
1073
+ }, {
1074
+ key: KeyCode.End,
1075
+ command: 'Problems.focusLast',
1076
+ when: FocusProblems
1077
+ }, {
1078
+ key: KeyCode.LeftArrow,
1079
+ command: 'Problems.handleArrowLeft',
1080
+ when: FocusProblems
1081
+ }, {
1082
+ key: KeyCode.RightArrow,
1083
+ command: 'Problems.handleArrowRight',
1084
+ when: FocusProblems
1085
+ }];
1086
+ };
1087
+
1088
+ const initialize = async () => {};
1089
+
1090
+ const isString = value => {
1091
+ return typeof value === 'string';
1092
+ };
1093
+ const getSavedCollapsedUris = savedState => {
1094
+ if (savedState && savedState.collapsedUris && Array.isArray(savedState.collapsedUris) && savedState.collapsedUris.every(isString)) {
1095
+ return savedState.collapsedUris;
1096
+ }
1097
+ return [];
1098
+ };
1099
+ const loadContent = async (state, savedState) => {
1100
+ const collapsedUris = getSavedCollapsedUris(savedState);
1101
+ return {
1102
+ ...state,
1103
+ inputSource: Script,
1104
+ listItems: [],
1105
+ collapsedUris
1106
+ };
1107
+ };
1108
+
1109
+ const Filter = 'filter';
1110
+
1111
+ const renderFilterValue = (oldState, newState) => {
1112
+ return ['Viewlet.setValueByName', Filter, newState.filterValue];
1113
+ };
1114
+
1115
+ const renderItems = (oldState, newState) => {
1116
+ // TODO
1117
+ const dom = [];
1118
+ return ['Viewlet.setDom2', dom];
1119
+ };
1120
+
1121
+ const getRenderer = diffType => {
1122
+ switch (diffType) {
1123
+ case RenderItems:
1124
+ return renderItems;
1125
+ case RenderFilterValue:
1126
+ return renderFilterValue;
1127
+ default:
1128
+ throw new Error('unknown renderer');
1129
+ }
1130
+ };
1131
+
1132
+ const applyRender = (oldState, newState, diffResult) => {
1133
+ const commands = [];
1134
+ for (const item of diffResult) {
1135
+ const fn = getRenderer(item);
1136
+ commands.push(fn(oldState, newState));
1137
+ }
1138
+ return commands;
1139
+ };
1140
+
1141
+ const render2 = (uid, diffResult) => {
1142
+ const {
1143
+ oldState,
1144
+ newState
1145
+ } = get$1(uid);
1146
+ set$1(uid, newState, newState);
1147
+ const commands = applyRender(oldState, newState, diffResult);
1148
+ return commands;
1149
+ };
1150
+
1151
+ const Actions = 'Actions';
1152
+
1153
+ const getActionsVirtualDom = actions => {
1154
+ return [{
1155
+ type: VirtualDomElements.Div,
1156
+ className: Actions,
1157
+ role: AriaRoles.ToolBar,
1158
+ childCount: actions.length
1159
+ }];
1160
+ };
1161
+
1162
+ const renderActions = uid => {
1163
+ const actions = [];
1164
+ const dom = getActionsVirtualDom(actions);
1165
+ return dom;
1166
+ };
1167
+
1168
+ const HandleBlur = 'handleBlur';
1169
+ const HandleClearFilterClick = 'handleClearFilterClick';
1170
+ const HandleContextMenu = 'handleContextMenu';
1171
+ const HandleFilterInput = 'handleFilterInput';
1172
+ const HandlePointerDown = 'handlePointerDown';
1173
+
1174
+ const renderEventListeners = () => {
1175
+ return [{
1176
+ name: HandleBlur,
1177
+ params: ['handleBlur']
1178
+ }, {
1179
+ name: HandleContextMenu,
1180
+ params: ['handleContextMenu', 'event.clientX', 'event.clientY'],
1181
+ preventDefault: true
1182
+ }, {
1183
+ name: HandleFilterInput,
1184
+ // @ts-ignore
1185
+ params: ['handleFilterInput', 'event.target.value', User]
1186
+ }, {
1187
+ name: HandleClearFilterClick,
1188
+ params: ['clearFilter']
1189
+ }, {
1190
+ name: HandlePointerDown,
1191
+ params: ['handleClickAt', 'event.clientX', 'event.clientY']
1192
+ }];
1193
+ };
1194
+
1195
+ const resize = (state, dimensions) => {
1196
+ return {
1197
+ ...state,
1198
+ ...dimensions
1199
+ };
1200
+ };
1201
+
1202
+ const saveState = state => {
1203
+ const {
1204
+ filterValue,
1205
+ collapsedUris
1206
+ } = state;
1207
+ return {
1208
+ filterValue,
1209
+ collapsedUris
1210
+ };
1211
+ };
1212
+
1213
+ const commandMap = {
1214
+ 'Problems.create': create$1,
1215
+ 'Problems.diff2': diff2,
1216
+ 'Problems.focusIndex': wrapCommand(focusIndex),
1217
+ 'Problems.getCommandIds': getCommandIds,
1218
+ 'Problems.getKeyBindings': getKeyBindings,
1219
+ 'Problems.initialize': initialize,
1220
+ 'Problems.loadContent': wrapCommand(loadContent),
1221
+ 'Problems.render2': render2,
1222
+ 'Problems.renderActions': renderActions,
1223
+ 'Problems.renderEventListeners': renderEventListeners,
1224
+ 'Problems.resize': resize,
1225
+ 'Problems.saveState': saveState,
1226
+ 'Problems.terminate': terminate
1227
+ };
1228
+
1229
+ const rpcs = Object.create(null);
1230
+ const set$g = (id, rpc) => {
1231
+ rpcs[id] = rpc;
1232
+ };
1233
+ const get = id => {
1234
+ return rpcs[id];
1235
+ };
1236
+
1237
+ /* eslint-disable @typescript-eslint/explicit-function-return-type */
1238
+
1239
+ const create = rpcId => {
1240
+ return {
1241
+ // @ts-ignore
1242
+ invoke(method, ...params) {
1243
+ const rpc = get(rpcId);
1244
+ // @ts-ignore
1245
+ return rpc.invoke(method, ...params);
1246
+ },
1247
+ // @ts-ignore
1248
+ invokeAndTransfer(method, ...params) {
1249
+ const rpc = get(rpcId);
1250
+ // @ts-ignore
1251
+ return rpc.invokeAndTransfer(method, ...params);
1252
+ },
1253
+ set(rpc) {
1254
+ set$g(rpcId, rpc);
1255
+ },
1256
+ async dispose() {
1257
+ const rpc = get(rpcId);
1258
+ await rpc.dispose();
1259
+ }
1260
+ };
1261
+ };
1262
+ const RendererWorker$1 = 1;
1263
+ const {
1264
+ set: set$3} = create(RendererWorker$1);
1265
+ const RendererWorker = {
1266
+ __proto__: null,
1267
+ set: set$3};
1268
+
1269
+ const {
1270
+ set} = RendererWorker;
1271
+
1272
+ const listen = async () => {
1273
+ Object.assign(commandMapRef, commandMap);
1274
+ const rpc = await WebWorkerRpcClient.create({
1275
+ commandMap: commandMapRef
1276
+ });
1277
+ set(rpc);
1278
+ };
1279
+
1280
+ const main = async () => {
1281
+ await listen();
1282
+ };
1283
+
1284
+ main();
package/package.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "name": "@lvce-editor/output-view",
3
+ "version": "1.0.0",
4
+ "description": "Output View Worker",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/lvce-editor/output-view.git"
8
+ },
9
+ "license": "MIT",
10
+ "author": "Lvce Editor",
11
+ "type": "module",
12
+ "main": "dist/outputViewWorkerMain.js"
13
+ }