@lvce-editor/file-watcher-process 2.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +998 -4
  2. package/package.json +1 -4
package/dist/index.js CHANGED
@@ -1,10 +1,996 @@
1
- import { ElectronMessagePortRpcClient, ElectronUtilityProcessRpcClient, NodeWorkerRpcClient, NodeForkedProcessRpcClient } from '@lvce-editor/rpc';
2
- import { get, set } from '@lvce-editor/rpc-registry';
3
- import { VError } from '@lvce-editor/verror';
4
1
  import * as fs from 'node:fs/promises';
5
2
  import { watch } from 'chokidar';
6
3
  import { pathToFileURL, fileURLToPath } from 'node:url';
7
4
 
5
+ const normalizeLine = line => {
6
+ if (line.startsWith('Error: ')) {
7
+ return line.slice('Error: '.length);
8
+ }
9
+ if (line.startsWith('VError: ')) {
10
+ return line.slice('VError: '.length);
11
+ }
12
+ return line;
13
+ };
14
+ const getCombinedMessage = (error, message) => {
15
+ const stringifiedError = normalizeLine(`${error}`);
16
+ if (message) {
17
+ return `${message}: ${stringifiedError}`;
18
+ }
19
+ return stringifiedError;
20
+ };
21
+ const NewLine$2 = '\n';
22
+ const getNewLineIndex$1 = (string, startIndex = undefined) => {
23
+ return string.indexOf(NewLine$2, startIndex);
24
+ };
25
+ const mergeStacks = (parent, child) => {
26
+ if (!child) {
27
+ return parent;
28
+ }
29
+ const parentNewLineIndex = getNewLineIndex$1(parent);
30
+ const childNewLineIndex = getNewLineIndex$1(child);
31
+ if (childNewLineIndex === -1) {
32
+ return parent;
33
+ }
34
+ const parentFirstLine = parent.slice(0, parentNewLineIndex);
35
+ const childRest = child.slice(childNewLineIndex);
36
+ const childFirstLine = normalizeLine(child.slice(0, childNewLineIndex));
37
+ if (parentFirstLine.includes(childFirstLine)) {
38
+ return parentFirstLine + childRest;
39
+ }
40
+ return child;
41
+ };
42
+ class VError extends Error {
43
+ constructor(error, message) {
44
+ const combinedMessage = getCombinedMessage(error, message);
45
+ super(combinedMessage);
46
+ this.name = 'VError';
47
+ if (error instanceof Error) {
48
+ this.stack = mergeStacks(this.stack, error.stack);
49
+ }
50
+ if (error.codeFrame) {
51
+ // @ts-ignore
52
+ this.codeFrame = error.codeFrame;
53
+ }
54
+ if (error.code) {
55
+ // @ts-ignore
56
+ this.code = error.code;
57
+ }
58
+ }
59
+ }
60
+
61
+ const isMessagePort = value => {
62
+ return value && value instanceof MessagePort;
63
+ };
64
+ const isMessagePortMain = value => {
65
+ return value && value.constructor && value.constructor.name === 'MessagePortMain';
66
+ };
67
+ const isOffscreenCanvas = value => {
68
+ return typeof OffscreenCanvas !== 'undefined' && value instanceof OffscreenCanvas;
69
+ };
70
+ const isInstanceOf = (value, constructorName) => {
71
+ return value?.constructor?.name === constructorName;
72
+ };
73
+ const isSocket = value => {
74
+ return isInstanceOf(value, 'Socket');
75
+ };
76
+ const transferrables = [isMessagePort, isMessagePortMain, isOffscreenCanvas, isSocket];
77
+ const isTransferrable = value => {
78
+ for (const fn of transferrables) {
79
+ if (fn(value)) {
80
+ return true;
81
+ }
82
+ }
83
+ return false;
84
+ };
85
+ const walkValue = (value, transferrables, isTransferrable) => {
86
+ if (!value) {
87
+ return;
88
+ }
89
+ if (isTransferrable(value)) {
90
+ transferrables.push(value);
91
+ return;
92
+ }
93
+ if (Array.isArray(value)) {
94
+ for (const item of value) {
95
+ walkValue(item, transferrables, isTransferrable);
96
+ }
97
+ return;
98
+ }
99
+ if (typeof value === 'object') {
100
+ for (const property of Object.values(value)) {
101
+ walkValue(property, transferrables, isTransferrable);
102
+ }
103
+ return;
104
+ }
105
+ };
106
+ const getTransferrables = value => {
107
+ const transferrables = [];
108
+ walkValue(value, transferrables, isTransferrable);
109
+ return transferrables;
110
+ };
111
+ const removeValues = (value, toRemove) => {
112
+ if (!value) {
113
+ return value;
114
+ }
115
+ if (Array.isArray(value)) {
116
+ const newItems = [];
117
+ for (const item of value) {
118
+ if (!toRemove.includes(item)) {
119
+ newItems.push(removeValues(item, toRemove));
120
+ }
121
+ }
122
+ return newItems;
123
+ }
124
+ if (typeof value === 'object') {
125
+ const newObject = Object.create(null);
126
+ for (const [key, property] of Object.entries(value)) {
127
+ if (!toRemove.includes(property)) {
128
+ newObject[key] = removeValues(property, toRemove);
129
+ }
130
+ }
131
+ return newObject;
132
+ }
133
+ return value;
134
+ };
135
+
136
+ // workaround for electron not supporting transferrable objects
137
+ // as parameters. If the transferrable object is a parameter, in electron
138
+ // only an empty objected is received in the main process
139
+ const fixElectronParameters = value => {
140
+ const transfer = getTransferrables(value);
141
+ const newValue = removeValues(value, transfer);
142
+ return {
143
+ newValue,
144
+ transfer
145
+ };
146
+ };
147
+ const getActualDataElectron = event => {
148
+ const {
149
+ data,
150
+ ports
151
+ } = event;
152
+ if (ports.length === 0) {
153
+ return data;
154
+ }
155
+ return {
156
+ ...data,
157
+ params: [...ports, ...data.params]
158
+ };
159
+ };
160
+ const attachEvents = that => {
161
+ const handleMessage = (...args) => {
162
+ const data = that.getData(...args);
163
+ that.dispatchEvent(new MessageEvent('message', {
164
+ data
165
+ }));
166
+ };
167
+ that.onMessage(handleMessage);
168
+ const handleClose = event => {
169
+ that.dispatchEvent(new Event('close'));
170
+ };
171
+ that.onClose(handleClose);
172
+ };
173
+ class Ipc extends EventTarget {
174
+ constructor(rawIpc) {
175
+ super();
176
+ this._rawIpc = rawIpc;
177
+ attachEvents(this);
178
+ }
179
+ }
180
+ const E_INCOMPATIBLE_NATIVE_MODULE = 'E_INCOMPATIBLE_NATIVE_MODULE';
181
+ const E_MODULES_NOT_SUPPORTED_IN_ELECTRON = 'E_MODULES_NOT_SUPPORTED_IN_ELECTRON';
182
+ const ERR_MODULE_NOT_FOUND = 'ERR_MODULE_NOT_FOUND';
183
+ const NewLine$1 = '\n';
184
+ const joinLines$1 = lines => {
185
+ return lines.join(NewLine$1);
186
+ };
187
+ const RE_AT = /^\s+at/;
188
+ const RE_AT_PROMISE_INDEX = /^\s*at async Promise.all \(index \d+\)$/;
189
+ const isNormalStackLine = line => {
190
+ return RE_AT.test(line) && !RE_AT_PROMISE_INDEX.test(line);
191
+ };
192
+ const getDetails = lines => {
193
+ const index = lines.findIndex(isNormalStackLine);
194
+ if (index === -1) {
195
+ return {
196
+ actualMessage: joinLines$1(lines),
197
+ rest: []
198
+ };
199
+ }
200
+ let lastIndex = index - 1;
201
+ while (++lastIndex < lines.length) {
202
+ if (!isNormalStackLine(lines[lastIndex])) {
203
+ break;
204
+ }
205
+ }
206
+ return {
207
+ actualMessage: lines[index - 1],
208
+ rest: lines.slice(index, lastIndex)
209
+ };
210
+ };
211
+ const splitLines$1 = lines => {
212
+ return lines.split(NewLine$1);
213
+ };
214
+ const RE_MESSAGE_CODE_BLOCK_START = /^Error: The module '.*'$/;
215
+ const RE_MESSAGE_CODE_BLOCK_END = /^\s* at/;
216
+ const isMessageCodeBlockStartIndex = line => {
217
+ return RE_MESSAGE_CODE_BLOCK_START.test(line);
218
+ };
219
+ const isMessageCodeBlockEndIndex = line => {
220
+ return RE_MESSAGE_CODE_BLOCK_END.test(line);
221
+ };
222
+ const getMessageCodeBlock = stderr => {
223
+ const lines = splitLines$1(stderr);
224
+ const startIndex = lines.findIndex(isMessageCodeBlockStartIndex);
225
+ const endIndex = startIndex + lines.slice(startIndex).findIndex(isMessageCodeBlockEndIndex, startIndex);
226
+ const relevantLines = lines.slice(startIndex, endIndex);
227
+ const relevantMessage = relevantLines.join(' ').slice('Error: '.length);
228
+ return relevantMessage;
229
+ };
230
+ const isModuleNotFoundMessage = line => {
231
+ return line.includes('[ERR_MODULE_NOT_FOUND]');
232
+ };
233
+ const getModuleNotFoundError = stderr => {
234
+ const lines = splitLines$1(stderr);
235
+ const messageIndex = lines.findIndex(isModuleNotFoundMessage);
236
+ const message = lines[messageIndex];
237
+ return {
238
+ message,
239
+ code: ERR_MODULE_NOT_FOUND
240
+ };
241
+ };
242
+ const isModuleNotFoundError = stderr => {
243
+ if (!stderr) {
244
+ return false;
245
+ }
246
+ return stderr.includes('ERR_MODULE_NOT_FOUND');
247
+ };
248
+ const isModulesSyntaxError = stderr => {
249
+ if (!stderr) {
250
+ return false;
251
+ }
252
+ return stderr.includes('SyntaxError: Cannot use import statement outside a module');
253
+ };
254
+ const RE_NATIVE_MODULE_ERROR = /^innerError Error: Cannot find module '.*.node'/;
255
+ const RE_NATIVE_MODULE_ERROR_2 = /was compiled against a different Node.js version/;
256
+ const isUnhelpfulNativeModuleError = stderr => {
257
+ return RE_NATIVE_MODULE_ERROR.test(stderr) && RE_NATIVE_MODULE_ERROR_2.test(stderr);
258
+ };
259
+ const getNativeModuleErrorMessage = stderr => {
260
+ const message = getMessageCodeBlock(stderr);
261
+ return {
262
+ message: `Incompatible native node module: ${message}`,
263
+ code: E_INCOMPATIBLE_NATIVE_MODULE
264
+ };
265
+ };
266
+ const getModuleSyntaxError = () => {
267
+ return {
268
+ message: `ES Modules are not supported in electron`,
269
+ code: E_MODULES_NOT_SUPPORTED_IN_ELECTRON
270
+ };
271
+ };
272
+ const getHelpfulChildProcessError = (stdout, stderr) => {
273
+ if (isUnhelpfulNativeModuleError(stderr)) {
274
+ return getNativeModuleErrorMessage(stderr);
275
+ }
276
+ if (isModulesSyntaxError(stderr)) {
277
+ return getModuleSyntaxError();
278
+ }
279
+ if (isModuleNotFoundError(stderr)) {
280
+ return getModuleNotFoundError(stderr);
281
+ }
282
+ const lines = splitLines$1(stderr);
283
+ const {
284
+ actualMessage,
285
+ rest
286
+ } = getDetails(lines);
287
+ return {
288
+ message: actualMessage,
289
+ code: '',
290
+ stack: rest
291
+ };
292
+ };
293
+ class IpcError extends VError {
294
+ // @ts-ignore
295
+ constructor(betterMessage, stdout = '', stderr = '') {
296
+ if (stdout || stderr) {
297
+ // @ts-ignore
298
+ const {
299
+ message,
300
+ code,
301
+ stack
302
+ } = getHelpfulChildProcessError(stdout, stderr);
303
+ const cause = new Error(message);
304
+ // @ts-ignore
305
+ cause.code = code;
306
+ cause.stack = stack;
307
+ super(cause, betterMessage);
308
+ } else {
309
+ super(betterMessage);
310
+ }
311
+ // @ts-ignore
312
+ this.name = 'IpcError';
313
+ // @ts-ignore
314
+ this.stdout = stdout;
315
+ // @ts-ignore
316
+ this.stderr = stderr;
317
+ }
318
+ }
319
+ const listen$b = ({
320
+ messagePort
321
+ }) => {
322
+ if (!isMessagePortMain(messagePort)) {
323
+ throw new IpcError('port must be of type MessagePortMain');
324
+ }
325
+ return messagePort;
326
+ };
327
+ const signal$c = messagePort => {
328
+ messagePort.start();
329
+ };
330
+ class IpcChildWithElectronMessagePort extends Ipc {
331
+ getData = getActualDataElectron;
332
+ send(message) {
333
+ this._rawIpc.postMessage(message);
334
+ }
335
+ sendAndTransfer(message) {
336
+ const {
337
+ newValue,
338
+ transfer
339
+ } = fixElectronParameters(message);
340
+ this._rawIpc.postMessage(newValue, transfer);
341
+ }
342
+ dispose() {
343
+ this._rawIpc.close();
344
+ }
345
+ onMessage(callback) {
346
+ this._rawIpc.on('message', callback);
347
+ }
348
+ onClose(callback) {
349
+ this._rawIpc.on('close', callback);
350
+ }
351
+ }
352
+ const wrap$j = messagePort => {
353
+ return new IpcChildWithElectronMessagePort(messagePort);
354
+ };
355
+ const IpcChildWithElectronMessagePort$1 = {
356
+ __proto__: null,
357
+ listen: listen$b,
358
+ signal: signal$c,
359
+ wrap: wrap$j
360
+ };
361
+
362
+ // @ts-ignore
363
+ const getUtilityProcessPortData = event => {
364
+ const {
365
+ data,
366
+ ports
367
+ } = event;
368
+ if (ports.length === 0) {
369
+ return data;
370
+ }
371
+ return {
372
+ ...data,
373
+ params: [...ports, ...data.params]
374
+ };
375
+ };
376
+ const readyMessage = 'ready';
377
+ const listen$a = () => {
378
+ // @ts-ignore
379
+ const {
380
+ parentPort
381
+ } = process;
382
+ if (!parentPort) {
383
+ throw new Error('parent port must be defined');
384
+ }
385
+ return parentPort;
386
+ };
387
+ const signal$b = parentPort => {
388
+ parentPort.postMessage(readyMessage);
389
+ };
390
+ class IpcChildWithElectronUtilityProcess extends Ipc {
391
+ getData(event) {
392
+ return getUtilityProcessPortData(event);
393
+ }
394
+ send(message) {
395
+ this._rawIpc.postMessage(message);
396
+ }
397
+ sendAndTransfer(message) {
398
+ const {
399
+ newValue,
400
+ transfer
401
+ } = fixElectronParameters(message);
402
+ this._rawIpc.postMessage(newValue, transfer);
403
+ }
404
+ dispose() {
405
+ this._rawIpc.close();
406
+ }
407
+ onClose(callback) {
408
+ this._rawIpc.on('close', callback);
409
+ }
410
+ onMessage(callback) {
411
+ this._rawIpc.on('message', callback);
412
+ }
413
+ }
414
+ const wrap$i = parentPort => {
415
+ return new IpcChildWithElectronUtilityProcess(parentPort);
416
+ };
417
+ const IpcChildWithElectronUtilityProcess$1 = {
418
+ __proto__: null,
419
+ listen: listen$a,
420
+ signal: signal$b,
421
+ wrap: wrap$i
422
+ };
423
+ const getActualData = (message, handle) => {
424
+ if (handle) {
425
+ return {
426
+ ...message,
427
+ params: [handle, ...message.params]
428
+ };
429
+ }
430
+ return message;
431
+ };
432
+ const getTransferrablesNode = value => {
433
+ const transferrables = getTransferrables(value);
434
+ if (transferrables.length === 0) {
435
+ throw new Error(`no transferrables found`);
436
+ }
437
+ return transferrables[0];
438
+ };
439
+ const listen$5 = async () => {
440
+ if (!process.send) {
441
+ throw new Error('process.send must be defined');
442
+ }
443
+ return process;
444
+ };
445
+ const signal$7 = process => {
446
+ process.send(readyMessage);
447
+ };
448
+ class IpcChildWithNodeForkedProcess extends Ipc {
449
+ getData(message, handle) {
450
+ return getActualData(message, handle);
451
+ }
452
+ onClose(callback) {
453
+ this._rawIpc.on('close', callback);
454
+ }
455
+ send(message) {
456
+ this._rawIpc.send(message);
457
+ }
458
+ onMessage(callback) {
459
+ this._rawIpc.on('message', callback);
460
+ }
461
+ sendAndTransfer(message) {
462
+ const transfer = getTransferrablesNode(message);
463
+ this._rawIpc.send(message, transfer);
464
+ }
465
+ dispose() {
466
+ // ignore
467
+ }
468
+ }
469
+ const wrap$d = process => {
470
+ return new IpcChildWithNodeForkedProcess(process);
471
+ };
472
+ const IpcChildWithNodeForkedProcess$1 = {
473
+ __proto__: null,
474
+ listen: listen$5,
475
+ signal: signal$7,
476
+ wrap: wrap$d
477
+ };
478
+ const listen$3 = async () => {
479
+ const {
480
+ parentPort
481
+ } = await import('node:worker_threads');
482
+ if (!parentPort) {
483
+ throw new IpcError('parentPort is required');
484
+ }
485
+ return parentPort;
486
+ };
487
+ const signal$5 = parentPort => {
488
+ parentPort.postMessage(readyMessage);
489
+ };
490
+ class IpcChildWithNodeWorker extends Ipc {
491
+ getData(data) {
492
+ return data;
493
+ }
494
+ onClose(callback) {
495
+ this._rawIpc.on('close', callback);
496
+ }
497
+ send(message) {
498
+ this._rawIpc.postMessage(message);
499
+ }
500
+ onMessage(callback) {
501
+ this._rawIpc.on('message', callback);
502
+ }
503
+ sendAndTransfer(message) {
504
+ const transfer = getTransferrablesNode(message);
505
+ this._rawIpc.postMessage(message, transfer);
506
+ }
507
+ dispose() {
508
+ this._rawIpc.close();
509
+ }
510
+ }
511
+ const wrap$b = parentPort => {
512
+ return new IpcChildWithNodeWorker(parentPort);
513
+ };
514
+ const IpcChildWithNodeWorker$1 = {
515
+ __proto__: null,
516
+ listen: listen$3,
517
+ signal: signal$5,
518
+ wrap: wrap$b
519
+ };
520
+
521
+ const Two = '2.0';
522
+ const create$4$1 = (method, params) => {
523
+ return {
524
+ jsonrpc: Two,
525
+ method,
526
+ params
527
+ };
528
+ };
529
+ const callbacks = Object.create(null);
530
+ const set = (id, fn) => {
531
+ callbacks[id] = fn;
532
+ };
533
+ const get$1 = id => {
534
+ return callbacks[id];
535
+ };
536
+ const remove = id => {
537
+ delete callbacks[id];
538
+ };
539
+ let id = 0;
540
+ const create$3 = () => {
541
+ return ++id;
542
+ };
543
+ const registerPromise = () => {
544
+ const id = create$3();
545
+ const {
546
+ resolve,
547
+ promise
548
+ } = Promise.withResolvers();
549
+ set(id, resolve);
550
+ return {
551
+ id,
552
+ promise
553
+ };
554
+ };
555
+ const create$2 = (method, params) => {
556
+ const {
557
+ id,
558
+ promise
559
+ } = registerPromise();
560
+ const message = {
561
+ jsonrpc: Two,
562
+ method,
563
+ params,
564
+ id
565
+ };
566
+ return {
567
+ message,
568
+ promise
569
+ };
570
+ };
571
+ class JsonRpcError extends Error {
572
+ constructor(message) {
573
+ super(message);
574
+ this.name = 'JsonRpcError';
575
+ }
576
+ }
577
+ const NewLine = '\n';
578
+ const DomException = 'DOMException';
579
+ const ReferenceError$1 = 'ReferenceError';
580
+ const SyntaxError$1 = 'SyntaxError';
581
+ const TypeError$1 = 'TypeError';
582
+ const getErrorConstructor = (message, type) => {
583
+ if (type) {
584
+ switch (type) {
585
+ case DomException:
586
+ return DOMException;
587
+ case TypeError$1:
588
+ return TypeError;
589
+ case SyntaxError$1:
590
+ return SyntaxError;
591
+ case ReferenceError$1:
592
+ return ReferenceError;
593
+ default:
594
+ return Error;
595
+ }
596
+ }
597
+ if (message.startsWith('TypeError: ')) {
598
+ return TypeError;
599
+ }
600
+ if (message.startsWith('SyntaxError: ')) {
601
+ return SyntaxError;
602
+ }
603
+ if (message.startsWith('ReferenceError: ')) {
604
+ return ReferenceError;
605
+ }
606
+ return Error;
607
+ };
608
+ const constructError = (message, type, name) => {
609
+ const ErrorConstructor = getErrorConstructor(message, type);
610
+ if (ErrorConstructor === DOMException && name) {
611
+ return new ErrorConstructor(message, name);
612
+ }
613
+ if (ErrorConstructor === Error) {
614
+ const error = new Error(message);
615
+ if (name && name !== 'VError') {
616
+ error.name = name;
617
+ }
618
+ return error;
619
+ }
620
+ return new ErrorConstructor(message);
621
+ };
622
+ const getNewLineIndex = (string, startIndex = undefined) => {
623
+ return string.indexOf(NewLine, startIndex);
624
+ };
625
+ const getParentStack = error => {
626
+ let parentStack = error.stack || error.data || error.message || '';
627
+ if (parentStack.startsWith(' at')) {
628
+ parentStack = error.message + NewLine + parentStack;
629
+ }
630
+ return parentStack;
631
+ };
632
+ const joinLines = lines => {
633
+ return lines.join(NewLine);
634
+ };
635
+ const MethodNotFound = -32601;
636
+ const Custom = -32001;
637
+ const splitLines = lines => {
638
+ return lines.split(NewLine);
639
+ };
640
+ const restoreJsonRpcError = error => {
641
+ if (error && error instanceof Error) {
642
+ return error;
643
+ }
644
+ const currentStack = joinLines(splitLines(new Error().stack || '').slice(1));
645
+ if (error && error.code && error.code === MethodNotFound) {
646
+ const restoredError = new JsonRpcError(error.message);
647
+ const parentStack = getParentStack(error);
648
+ restoredError.stack = parentStack + NewLine + currentStack;
649
+ return restoredError;
650
+ }
651
+ if (error && error.message) {
652
+ const restoredError = constructError(error.message, error.type, error.name);
653
+ if (error.data) {
654
+ if (error.data.stack && error.data.type && error.message) {
655
+ restoredError.stack = error.data.type + ': ' + error.message + NewLine + error.data.stack + NewLine + currentStack;
656
+ } else if (error.data.stack) {
657
+ restoredError.stack = error.data.stack;
658
+ }
659
+ if (error.data.codeFrame) {
660
+ // @ts-ignore
661
+ restoredError.codeFrame = error.data.codeFrame;
662
+ }
663
+ if (error.data.code) {
664
+ // @ts-ignore
665
+ restoredError.code = error.data.code;
666
+ }
667
+ if (error.data.type) {
668
+ // @ts-ignore
669
+ restoredError.name = error.data.type;
670
+ }
671
+ } else {
672
+ if (error.stack) {
673
+ const lowerStack = restoredError.stack || '';
674
+ // @ts-ignore
675
+ const indexNewLine = getNewLineIndex(lowerStack);
676
+ const parentStack = getParentStack(error);
677
+ // @ts-ignore
678
+ restoredError.stack = parentStack + lowerStack.slice(indexNewLine);
679
+ }
680
+ if (error.codeFrame) {
681
+ // @ts-ignore
682
+ restoredError.codeFrame = error.codeFrame;
683
+ }
684
+ }
685
+ return restoredError;
686
+ }
687
+ if (typeof error === 'string') {
688
+ return new Error(`JsonRpc Error: ${error}`);
689
+ }
690
+ return new Error(`JsonRpc Error: ${error}`);
691
+ };
692
+ const unwrapJsonRpcResult = responseMessage => {
693
+ if ('error' in responseMessage) {
694
+ const restoredError = restoreJsonRpcError(responseMessage.error);
695
+ throw restoredError;
696
+ }
697
+ if ('result' in responseMessage) {
698
+ return responseMessage.result;
699
+ }
700
+ throw new JsonRpcError('unexpected response message');
701
+ };
702
+ const warn = (...args) => {
703
+ console.warn(...args);
704
+ };
705
+ const resolve = (id, response) => {
706
+ const fn = get$1(id);
707
+ if (!fn) {
708
+ console.log(response);
709
+ warn(`callback ${id} may already be disposed`);
710
+ return;
711
+ }
712
+ fn(response);
713
+ remove(id);
714
+ };
715
+ const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
716
+ const getErrorType = prettyError => {
717
+ if (prettyError && prettyError.type) {
718
+ return prettyError.type;
719
+ }
720
+ if (prettyError && prettyError.constructor && prettyError.constructor.name) {
721
+ return prettyError.constructor.name;
722
+ }
723
+ return undefined;
724
+ };
725
+ const getErrorProperty = (error, prettyError) => {
726
+ if (error && error.code === E_COMMAND_NOT_FOUND) {
727
+ return {
728
+ code: MethodNotFound,
729
+ message: error.message,
730
+ data: error.stack
731
+ };
732
+ }
733
+ return {
734
+ code: Custom,
735
+ message: prettyError.message,
736
+ data: {
737
+ stack: prettyError.stack,
738
+ codeFrame: prettyError.codeFrame,
739
+ type: getErrorType(prettyError),
740
+ code: prettyError.code,
741
+ name: prettyError.name
742
+ }
743
+ };
744
+ };
745
+ const create$1 = (message, error) => {
746
+ return {
747
+ jsonrpc: Two,
748
+ id: message.id,
749
+ error
750
+ };
751
+ };
752
+ const getErrorResponse = (message, error, preparePrettyError, logError) => {
753
+ const prettyError = preparePrettyError(error);
754
+ logError(error, prettyError);
755
+ const errorProperty = getErrorProperty(error, prettyError);
756
+ return create$1(message, errorProperty);
757
+ };
758
+ const create = (message, result) => {
759
+ return {
760
+ jsonrpc: Two,
761
+ id: message.id,
762
+ result: result ?? null
763
+ };
764
+ };
765
+ const getSuccessResponse = (message, result) => {
766
+ const resultProperty = result ?? null;
767
+ return create(message, resultProperty);
768
+ };
769
+ const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
770
+ try {
771
+ const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
772
+ return getSuccessResponse(message, result);
773
+ } catch (error) {
774
+ return getErrorResponse(message, error, preparePrettyError, logError);
775
+ }
776
+ };
777
+ const defaultPreparePrettyError = error => {
778
+ return error;
779
+ };
780
+ const defaultLogError = () => {
781
+ // ignore
782
+ };
783
+ const defaultRequiresSocket = () => {
784
+ return false;
785
+ };
786
+ const defaultResolve = resolve;
787
+
788
+ // TODO maybe remove this in v6 or v7, only accept options object to simplify the code
789
+ const normalizeParams = args => {
790
+ if (args.length === 1) {
791
+ const options = args[0];
792
+ return {
793
+ ipc: options.ipc,
794
+ message: options.message,
795
+ execute: options.execute,
796
+ resolve: options.resolve || defaultResolve,
797
+ preparePrettyError: options.preparePrettyError || defaultPreparePrettyError,
798
+ logError: options.logError || defaultLogError,
799
+ requiresSocket: options.requiresSocket || defaultRequiresSocket
800
+ };
801
+ }
802
+ return {
803
+ ipc: args[0],
804
+ message: args[1],
805
+ execute: args[2],
806
+ resolve: args[3],
807
+ preparePrettyError: args[4],
808
+ logError: args[5],
809
+ requiresSocket: args[6]
810
+ };
811
+ };
812
+ const handleJsonRpcMessage = async (...args) => {
813
+ const options = normalizeParams(args);
814
+ const {
815
+ message,
816
+ ipc,
817
+ execute,
818
+ resolve,
819
+ preparePrettyError,
820
+ logError,
821
+ requiresSocket
822
+ } = options;
823
+ if ('id' in message) {
824
+ if ('method' in message) {
825
+ const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
826
+ try {
827
+ ipc.send(response);
828
+ } catch (error) {
829
+ const errorResponse = getErrorResponse(message, error, preparePrettyError, logError);
830
+ ipc.send(errorResponse);
831
+ }
832
+ return;
833
+ }
834
+ resolve(message.id, message);
835
+ return;
836
+ }
837
+ if ('method' in message) {
838
+ await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
839
+ return;
840
+ }
841
+ throw new JsonRpcError('unexpected message');
842
+ };
843
+ const invokeHelper = async (ipc, method, params, useSendAndTransfer) => {
844
+ const {
845
+ message,
846
+ promise
847
+ } = create$2(method, params);
848
+ if (useSendAndTransfer && ipc.sendAndTransfer) {
849
+ ipc.sendAndTransfer(message);
850
+ } else {
851
+ ipc.send(message);
852
+ }
853
+ const responseMessage = await promise;
854
+ return unwrapJsonRpcResult(responseMessage);
855
+ };
856
+ const send = (transport, method, ...params) => {
857
+ const message = create$4$1(method, params);
858
+ transport.send(message);
859
+ };
860
+ const invoke$1 = (ipc, method, ...params) => {
861
+ return invokeHelper(ipc, method, params, false);
862
+ };
863
+ const invokeAndTransfer = (ipc, method, ...params) => {
864
+ return invokeHelper(ipc, method, params, true);
865
+ };
866
+
867
+ const commands = Object.create(null);
868
+ const register = commandMap => {
869
+ Object.assign(commands, commandMap);
870
+ };
871
+ const getCommand = key => {
872
+ return commands[key];
873
+ };
874
+ const execute = (command, ...args) => {
875
+ const fn = getCommand(command);
876
+ if (!fn) {
877
+ throw new Error(`command not found ${command}`);
878
+ }
879
+ return fn(...args);
880
+ };
881
+
882
+ const createRpc = ipc => {
883
+ const rpc = {
884
+ // @ts-ignore
885
+ ipc,
886
+ /**
887
+ * @deprecated
888
+ */
889
+ send(method, ...params) {
890
+ send(ipc, method, ...params);
891
+ },
892
+ invoke(method, ...params) {
893
+ return invoke$1(ipc, method, ...params);
894
+ },
895
+ invokeAndTransfer(method, ...params) {
896
+ return invokeAndTransfer(ipc, method, ...params);
897
+ },
898
+ async dispose() {
899
+ await ipc?.dispose();
900
+ }
901
+ };
902
+ return rpc;
903
+ };
904
+ const requiresSocket = () => {
905
+ return false;
906
+ };
907
+ const preparePrettyError = error => {
908
+ return error;
909
+ };
910
+ const logError = () => {
911
+ // handled by renderer worker
912
+ };
913
+ const handleMessage = event => {
914
+ const actualRequiresSocket = event?.target?.requiresSocket || requiresSocket;
915
+ const actualExecute = event?.target?.execute || execute;
916
+ return handleJsonRpcMessage(event.target, event.data, actualExecute, resolve, preparePrettyError, logError, actualRequiresSocket);
917
+ };
918
+ const handleIpc = ipc => {
919
+ if ('addEventListener' in ipc) {
920
+ ipc.addEventListener('message', handleMessage);
921
+ } else if ('on' in ipc) {
922
+ // deprecated
923
+ ipc.on('message', handleMessage);
924
+ }
925
+ };
926
+ const listen$2 = async (module, options) => {
927
+ const rawIpc = await module.listen(options);
928
+ if (module.signal) {
929
+ module.signal(rawIpc);
930
+ }
931
+ const ipc = module.wrap(rawIpc);
932
+ return ipc;
933
+ };
934
+ const create$c = async ({
935
+ commandMap,
936
+ messagePort
937
+ }) => {
938
+ // TODO create a commandMap per rpc instance
939
+ register(commandMap);
940
+ const ipc = await listen$2(IpcChildWithElectronMessagePort$1, {
941
+ messagePort
942
+ });
943
+ handleIpc(ipc);
944
+ const rpc = createRpc(ipc);
945
+ return rpc;
946
+ };
947
+ const ElectronMessagePortRpcClient = {
948
+ __proto__: null,
949
+ create: create$c
950
+ };
951
+ const create$b = async ({
952
+ commandMap
953
+ }) => {
954
+ // TODO create a commandMap per rpc instance
955
+ register(commandMap);
956
+ const ipc = await listen$2(IpcChildWithElectronUtilityProcess$1);
957
+ handleIpc(ipc);
958
+ const rpc = createRpc(ipc);
959
+ return rpc;
960
+ };
961
+ const ElectronUtilityProcessRpcClient = {
962
+ __proto__: null,
963
+ create: create$b
964
+ };
965
+ const create$7 = async ({
966
+ commandMap
967
+ }) => {
968
+ // TODO create a commandMap per rpc instance
969
+ register(commandMap);
970
+ const ipc = await listen$2(IpcChildWithNodeForkedProcess$1);
971
+ handleIpc(ipc);
972
+ const rpc = createRpc(ipc);
973
+ return rpc;
974
+ };
975
+ const NodeForkedProcessRpcClient = {
976
+ __proto__: null,
977
+ create: create$7
978
+ };
979
+ const create$4 = async ({
980
+ commandMap
981
+ }) => {
982
+ // TODO create a commandMap per rpc instance
983
+ register(commandMap);
984
+ const ipc = await listen$2(IpcChildWithNodeWorker$1);
985
+ handleIpc(ipc);
986
+ const rpc = createRpc(ipc);
987
+ return rpc;
988
+ };
989
+ const NodeWorkerRpcClient = {
990
+ __proto__: null,
991
+ create: create$4
992
+ };
993
+
8
994
  const NodeWorker = 1;
9
995
  const NodeForkedProcess = 2;
10
996
  const ElectronUtilityProcess = 3;
@@ -60,6 +1046,14 @@ const handleElectronMessagePort = async messagePort => {
60
1046
 
61
1047
  const SharedProcess = 1;
62
1048
 
1049
+ const rpcs = Object.create(null);
1050
+ const set$3 = (id, rpc) => {
1051
+ rpcs[id] = rpc;
1052
+ };
1053
+ const get = id => {
1054
+ return rpcs[id];
1055
+ };
1056
+
63
1057
  const invoke = async (method, ...params) => {
64
1058
  const rpc = get(SharedProcess);
65
1059
  await rpc.invoke(method, ...params);
@@ -166,7 +1160,7 @@ const listen = async () => {
166
1160
  method: Auto(),
167
1161
  commandMap: commandMap
168
1162
  });
169
- set(SharedProcess, rpc);
1163
+ set$3(SharedProcess, rpc);
170
1164
  };
171
1165
 
172
1166
  const main = async () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lvce-editor/file-watcher-process",
3
- "version": "2.0.0",
3
+ "version": "3.1.0",
4
4
  "description": "File Watcher Process",
5
5
  "keywords": [
6
6
  "Lvce Editor",
@@ -18,9 +18,6 @@
18
18
  "file-watcher-process": "bin/fileWatcherProcess.js"
19
19
  },
20
20
  "dependencies": {
21
- "@lvce-editor/rpc": "^2.1.0",
22
- "@lvce-editor/rpc-registry": "^1.1.0",
23
- "@lvce-editor/verror": "^1.6.0",
24
21
  "chokidar": "^4.0.3"
25
22
  },
26
23
  "engines": {