@lvce-editor/embeds-process 2.3.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 (34) hide show
  1. package/bin/embedsProcess.js +3 -0
  2. package/dist/embedsProcessMain.js +1619 -0
  3. package/package.json +16 -54
  4. package/src/embedsProcessMain.js +0 -3
  5. package/src/parts/ApplyIncomingIpcResponse/ApplyIncomingIpcResponse.js +0 -11
  6. package/src/parts/Assert/Assert.js +0 -1
  7. package/src/parts/Callback/Callback.js +0 -1
  8. package/src/parts/Command/Command.js +0 -9
  9. package/src/parts/CommandMap/CommandMap.js +0 -27
  10. package/src/parts/CommandState/CommandState.js +0 -21
  11. package/src/parts/ElectronWebContents/ElectronWebContents.js +0 -82
  12. package/src/parts/ElectronWebContentsView/ElectronWebContentsView.js +0 -68
  13. package/src/parts/ElectronWebContentsViewIpcState/ElectronWebContentsViewIpcState.js +0 -17
  14. package/src/parts/ElectronWebContentsViewState/ElectronWebContentsViewState.js +0 -13
  15. package/src/parts/HandleElectronMessagePort/HandleElectronMessagePort.js +0 -8
  16. package/src/parts/HandleIncomingIpc/HandleIncomingIpc.js +0 -15
  17. package/src/parts/HandleIncomingIpcMessagePort/HandleIncomingIpcMessagePort.js +0 -8
  18. package/src/parts/HandleIpc/HandleIpc.js +0 -5
  19. package/src/parts/HandleIpcClosed/HandleIpcClosed.js +0 -23
  20. package/src/parts/HandleIpcEmbedsWorker/HandleIpcEmbedsWorker.js +0 -20
  21. package/src/parts/HandleIpcMainProcess/HandleIpcMainProcess.js +0 -20
  22. package/src/parts/HandleIpcModule/HandleIpcModule.js +0 -19
  23. package/src/parts/HandleIpcSharedProcess/HandleIpcSharedProcess.js +0 -21
  24. package/src/parts/HandleMessage/HandleMessage.js +0 -19
  25. package/src/parts/IpcChild/IpcChild.js +0 -15
  26. package/src/parts/IpcChildModule/IpcChildModule.js +0 -25
  27. package/src/parts/IpcChildType/IpcChildType.js +0 -20
  28. package/src/parts/IpcId/IpcId.js +0 -9
  29. package/src/parts/JsonRpc/JsonRpc.js +0 -1
  30. package/src/parts/Listen/Listen.js +0 -10
  31. package/src/parts/Main/Main.js +0 -8
  32. package/src/parts/ParentIpc/ParentIpc.js +0 -20
  33. package/src/parts/SharedProcessIpc/SharedProcessIpc.js +0 -20
  34. package/src/parts/VError/VError.js +0 -1
@@ -0,0 +1,1619 @@
1
+ import { Buffer } from 'node:buffer';
2
+
3
+ const ipcMap = Object.create(null);
4
+ const add = (id, ipc) => {
5
+ ipcMap[id] = ipc;
6
+ };
7
+ const get$2 = id => {
8
+ return ipcMap[id];
9
+ };
10
+ const remove$1 = id => {
11
+ delete ipcMap[id];
12
+ };
13
+ const getAll = () => {
14
+ return Object.entries(ipcMap);
15
+ };
16
+
17
+ const rpcs = Object.create(null);
18
+ const set$5 = (id, rpc) => {
19
+ rpcs[id] = rpc;
20
+ };
21
+ const get$1 = id => {
22
+ return rpcs[id];
23
+ };
24
+ const MainProcess$1 = -5;
25
+ const SharedProcess$1 = 1;
26
+ const invoke$3 = (method, ...params) => {
27
+ const rpc = get$1(MainProcess$1);
28
+ // @ts-ignore
29
+ return rpc.invoke(method, ...params);
30
+ };
31
+ const set$3 = rpc => {
32
+ set$5(MainProcess$1, rpc);
33
+ };
34
+ const MainProcess$2 = {
35
+ __proto__: null,
36
+ invoke: invoke$3,
37
+ set: set$3
38
+ };
39
+ const set$4 = rpc => {
40
+ set$5(SharedProcess$1, rpc);
41
+ };
42
+ const SharedProcess$2 = {
43
+ __proto__: null,
44
+ set: set$4
45
+ };
46
+
47
+ const {
48
+ invoke: invoke$1,
49
+ set: set$2
50
+ } = MainProcess$2;
51
+
52
+ const normalizeLine = line => {
53
+ if (line.startsWith('Error: ')) {
54
+ return line.slice('Error: '.length);
55
+ }
56
+ if (line.startsWith('VError: ')) {
57
+ return line.slice('VError: '.length);
58
+ }
59
+ return line;
60
+ };
61
+ const getCombinedMessage = (error, message) => {
62
+ const stringifiedError = normalizeLine(`${error}`);
63
+ if (message) {
64
+ return `${message}: ${stringifiedError}`;
65
+ }
66
+ return stringifiedError;
67
+ };
68
+ const NewLine$2 = '\n';
69
+ const getNewLineIndex$1 = (string, startIndex = undefined) => {
70
+ return string.indexOf(NewLine$2, startIndex);
71
+ };
72
+ const mergeStacks = (parent, child) => {
73
+ if (!child) {
74
+ return parent;
75
+ }
76
+ const parentNewLineIndex = getNewLineIndex$1(parent);
77
+ const childNewLineIndex = getNewLineIndex$1(child);
78
+ if (childNewLineIndex === -1) {
79
+ return parent;
80
+ }
81
+ const parentFirstLine = parent.slice(0, parentNewLineIndex);
82
+ const childRest = child.slice(childNewLineIndex);
83
+ const childFirstLine = normalizeLine(child.slice(0, childNewLineIndex));
84
+ if (parentFirstLine.includes(childFirstLine)) {
85
+ return parentFirstLine + childRest;
86
+ }
87
+ return child;
88
+ };
89
+ class VError extends Error {
90
+ constructor(error, message) {
91
+ const combinedMessage = getCombinedMessage(error, message);
92
+ super(combinedMessage);
93
+ this.name = 'VError';
94
+ if (error instanceof Error) {
95
+ this.stack = mergeStacks(this.stack, error.stack);
96
+ }
97
+ if (error.codeFrame) {
98
+ // @ts-ignore
99
+ this.codeFrame = error.codeFrame;
100
+ }
101
+ if (error.code) {
102
+ // @ts-ignore
103
+ this.code = error.code;
104
+ }
105
+ }
106
+ }
107
+
108
+ const dispose = async id => {
109
+ try {
110
+ await invoke$1('ElectronWebContents.dispose', id);
111
+ } catch (error) {
112
+ throw new VError(error, `Failed to dispose webcontents`);
113
+ }
114
+ };
115
+ const callFunction = (webContentsId, method, ...params) => {
116
+ return invoke$1(`ElectronWebContents.callFunction`, webContentsId, method, ...params);
117
+ };
118
+ const focus = webContentsId => {
119
+ return callFunction(webContentsId, 'focus');
120
+ };
121
+ const openDevtools = webContentsId => {
122
+ return callFunction(webContentsId, 'openDevTools');
123
+ };
124
+ const reload = webContentsId => {
125
+ return callFunction(webContentsId, 'reload');
126
+ };
127
+ const forward = webContentsId => {
128
+ return callFunction(webContentsId, 'goForward');
129
+ };
130
+ const backward = webContentsId => {
131
+ return callFunction(webContentsId, 'goBack');
132
+ };
133
+ const inspectElement = (webContentsId, x, y) => {
134
+ return callFunction(webContentsId, `inspectElement`, x, y);
135
+ };
136
+
137
+ class AssertionError extends Error {
138
+ constructor(message) {
139
+ super(message);
140
+ this.name = 'AssertionError';
141
+ }
142
+ }
143
+ const getType = value => {
144
+ switch (typeof value) {
145
+ case 'number':
146
+ return 'number';
147
+ case 'function':
148
+ return 'function';
149
+ case 'string':
150
+ return 'string';
151
+ case 'object':
152
+ if (value === null) {
153
+ return 'null';
154
+ }
155
+ if (Array.isArray(value)) {
156
+ return 'array';
157
+ }
158
+ return 'object';
159
+ case 'boolean':
160
+ return 'boolean';
161
+ default:
162
+ return 'unknown';
163
+ }
164
+ };
165
+ const object = value => {
166
+ const type = getType(value);
167
+ if (type !== 'object') {
168
+ throw new AssertionError('expected value to be of type object');
169
+ }
170
+ };
171
+ const number = value => {
172
+ const type = getType(value);
173
+ if (type !== 'number') {
174
+ throw new AssertionError('expected value to be of type number');
175
+ }
176
+ };
177
+
178
+ const createWebContentsView = async (ipcId, restoreId, fallthroughKeyBindings) => {
179
+ number(restoreId);
180
+ // TODO race condition: ipc can be disposed while webcontents are being created
181
+ const webContentsId = await invoke$1('ElectronWebContentsView.createWebContentsView', restoreId);
182
+ add(webContentsId, ipcId);
183
+ // TODO get window id from renderer worker
184
+ await invoke$1('ElectronWebContentsView.attachEventListeners', webContentsId);
185
+ await invoke$1('ElectronWebContentsViewFunctions.setBackgroundColor', webContentsId, 'white');
186
+ return webContentsId;
187
+ };
188
+ const disposeWebContentsView = async id => {
189
+ await invoke$1('ElectronWebContentsView.disposeWebContentsView', id);
190
+ await dispose(id);
191
+ };
192
+ const resizeWebContentsView = async (id, ...args) => {
193
+ return invoke$1('ElectronWebContentsViewFunctions.resizeBrowserView', id, ...args);
194
+ };
195
+ const setIframeSrc = async (id, ...args) => {
196
+ return invoke$1('ElectronWebContentsViewFunctions.setIframeSrc', id, ...args);
197
+ };
198
+ const setIframeSrcFallback = async (id, ...args) => {
199
+ return invoke$1('ElectronWebContentsViewFunctions.setIframeSrcFallback', id, ...args);
200
+ };
201
+ const setFallthroughKeyBindings = async (id, ...args) => {
202
+ return invoke$1('ElectronWebContentsViewFunctions.setFallthroughKeyBindings', id, ...args);
203
+ };
204
+ const getStats = async (id, ...args) => {
205
+ return invoke$1('ElectronWebContentsViewFunctions.getStats', id, ...args);
206
+ };
207
+ const show = async (id, ...args) => {
208
+ return invoke$1('ElectronWebContentsViewFunctions.show', id, ...args);
209
+ };
210
+ const forwardIpcEvent = key => (id, ...args) => {
211
+ const ipc = get$2(id);
212
+ if (!ipc) {
213
+ return;
214
+ }
215
+ ipc.send(key, id, ...args);
216
+ };
217
+ const handleDidNavigate = forwardIpcEvent('ElectronWebContentsView.handleDidNavigate');
218
+ const handleTitleUpdated = forwardIpcEvent('ElectronWebContentsView.handleTitleUpdated');
219
+ const handleWillNavigate = forwardIpcEvent('ElectronWebContentsView.handleWillNavigate');
220
+ const handleContextMenu = forwardIpcEvent('ElectronWebContentsView.handleContextMenu');
221
+ const handleKeyBinding = forwardIpcEvent('ElectronWebContentsView.handleKeyBinding');
222
+ const handleBrowserViewDestroyed = (id, ...args) => {
223
+ // TODO send to embeds worker?
224
+ };
225
+
226
+ const applyIncomingIpcResponse = async (target, response, ipcId) => {
227
+ switch (response.type) {
228
+ case 'handle':
229
+ break;
230
+ default:
231
+ throw new Error('unexpected response');
232
+ }
233
+ };
234
+
235
+ const handleIncomingIpcMessagePort = async (module, handle, message) => {
236
+ const target = await module.targetMessagePort(handle, message);
237
+ const response = module.upgradeMessagePort(handle, message);
238
+ return {
239
+ target,
240
+ response
241
+ };
242
+ };
243
+
244
+ const commandMapRef = {};
245
+
246
+ const getIdsToDispose = ipc => {
247
+ const entries = getAll();
248
+ const toDispose = [];
249
+ for (const [id, value] of entries) {
250
+ if (value === ipc) {
251
+ toDispose.push(Number.parseInt(id));
252
+ }
253
+ }
254
+ return toDispose;
255
+ };
256
+ const handleIpcClosed = async event => {
257
+ const idsToDispose = getIdsToDispose(event.target);
258
+ for (const id of idsToDispose) {
259
+ remove$1(id);
260
+ await disposeWebContentsView(id);
261
+ }
262
+ // SharedProcessIpc.send('HandleMessagePortForEmbedsProcess.handleEmbedsProcessIpcClosed')
263
+ };
264
+
265
+ const isMessagePort = value => {
266
+ return value && value instanceof MessagePort;
267
+ };
268
+ const isMessagePortMain = value => {
269
+ return value && value.constructor && value.constructor.name === 'MessagePortMain';
270
+ };
271
+ const isOffscreenCanvas = value => {
272
+ return typeof OffscreenCanvas !== 'undefined' && value instanceof OffscreenCanvas;
273
+ };
274
+ const isInstanceOf = (value, constructorName) => {
275
+ return value?.constructor?.name === constructorName;
276
+ };
277
+ const isSocket = value => {
278
+ return isInstanceOf(value, 'Socket');
279
+ };
280
+ const transferrables = [isMessagePort, isMessagePortMain, isOffscreenCanvas, isSocket];
281
+ const isTransferrable = value => {
282
+ for (const fn of transferrables) {
283
+ if (fn(value)) {
284
+ return true;
285
+ }
286
+ }
287
+ return false;
288
+ };
289
+ const walkValue = (value, transferrables, isTransferrable) => {
290
+ if (!value) {
291
+ return;
292
+ }
293
+ if (isTransferrable(value)) {
294
+ transferrables.push(value);
295
+ return;
296
+ }
297
+ if (Array.isArray(value)) {
298
+ for (const item of value) {
299
+ walkValue(item, transferrables, isTransferrable);
300
+ }
301
+ return;
302
+ }
303
+ if (typeof value === 'object') {
304
+ for (const property of Object.values(value)) {
305
+ walkValue(property, transferrables, isTransferrable);
306
+ }
307
+ return;
308
+ }
309
+ };
310
+ const getTransferrables = value => {
311
+ const transferrables = [];
312
+ walkValue(value, transferrables, isTransferrable);
313
+ return transferrables;
314
+ };
315
+ const removeValues = (value, toRemove) => {
316
+ if (!value) {
317
+ return value;
318
+ }
319
+ if (Array.isArray(value)) {
320
+ const newItems = [];
321
+ for (const item of value) {
322
+ if (!toRemove.includes(item)) {
323
+ newItems.push(removeValues(item, toRemove));
324
+ }
325
+ }
326
+ return newItems;
327
+ }
328
+ if (typeof value === 'object') {
329
+ const newObject = Object.create(null);
330
+ for (const [key, property] of Object.entries(value)) {
331
+ if (!toRemove.includes(property)) {
332
+ newObject[key] = removeValues(property, toRemove);
333
+ }
334
+ }
335
+ return newObject;
336
+ }
337
+ return value;
338
+ };
339
+
340
+ // workaround for electron not supporting transferrable objects
341
+ // as parameters. If the transferrable object is a parameter, in electron
342
+ // only an empty objected is received in the main process
343
+ const fixElectronParameters = value => {
344
+ const transfer = getTransferrables(value);
345
+ const newValue = removeValues(value, transfer);
346
+ return {
347
+ newValue,
348
+ transfer
349
+ };
350
+ };
351
+ const getActualDataElectron = event => {
352
+ const {
353
+ data,
354
+ ports
355
+ } = event;
356
+ if (ports.length === 0) {
357
+ return data;
358
+ }
359
+ return {
360
+ ...data,
361
+ params: [...ports, ...data.params]
362
+ };
363
+ };
364
+ const attachEvents = that => {
365
+ const handleMessage = (...args) => {
366
+ const data = that.getData(...args);
367
+ that.dispatchEvent(new MessageEvent('message', {
368
+ data
369
+ }));
370
+ };
371
+ that.onMessage(handleMessage);
372
+ const handleClose = event => {
373
+ that.dispatchEvent(new Event('close'));
374
+ };
375
+ that.onClose(handleClose);
376
+ };
377
+ class Ipc extends EventTarget {
378
+ constructor(rawIpc) {
379
+ super();
380
+ this._rawIpc = rawIpc;
381
+ attachEvents(this);
382
+ }
383
+ }
384
+ const E_INCOMPATIBLE_NATIVE_MODULE = 'E_INCOMPATIBLE_NATIVE_MODULE';
385
+ const E_MODULES_NOT_SUPPORTED_IN_ELECTRON = 'E_MODULES_NOT_SUPPORTED_IN_ELECTRON';
386
+ const ERR_MODULE_NOT_FOUND = 'ERR_MODULE_NOT_FOUND';
387
+ const NewLine$1 = '\n';
388
+ const joinLines$1 = lines => {
389
+ return lines.join(NewLine$1);
390
+ };
391
+ const RE_AT = /^\s+at/;
392
+ const RE_AT_PROMISE_INDEX = /^\s*at async Promise.all \(index \d+\)$/;
393
+ const isNormalStackLine = line => {
394
+ return RE_AT.test(line) && !RE_AT_PROMISE_INDEX.test(line);
395
+ };
396
+ const getDetails = lines => {
397
+ const index = lines.findIndex(isNormalStackLine);
398
+ if (index === -1) {
399
+ return {
400
+ actualMessage: joinLines$1(lines),
401
+ rest: []
402
+ };
403
+ }
404
+ let lastIndex = index - 1;
405
+ while (++lastIndex < lines.length) {
406
+ if (!isNormalStackLine(lines[lastIndex])) {
407
+ break;
408
+ }
409
+ }
410
+ return {
411
+ actualMessage: lines[index - 1],
412
+ rest: lines.slice(index, lastIndex)
413
+ };
414
+ };
415
+ const splitLines$1 = lines => {
416
+ return lines.split(NewLine$1);
417
+ };
418
+ const RE_MESSAGE_CODE_BLOCK_START = /^Error: The module '.*'$/;
419
+ const RE_MESSAGE_CODE_BLOCK_END = /^\s* at/;
420
+ const isMessageCodeBlockStartIndex = line => {
421
+ return RE_MESSAGE_CODE_BLOCK_START.test(line);
422
+ };
423
+ const isMessageCodeBlockEndIndex = line => {
424
+ return RE_MESSAGE_CODE_BLOCK_END.test(line);
425
+ };
426
+ const getMessageCodeBlock = stderr => {
427
+ const lines = splitLines$1(stderr);
428
+ const startIndex = lines.findIndex(isMessageCodeBlockStartIndex);
429
+ const endIndex = startIndex + lines.slice(startIndex).findIndex(isMessageCodeBlockEndIndex, startIndex);
430
+ const relevantLines = lines.slice(startIndex, endIndex);
431
+ const relevantMessage = relevantLines.join(' ').slice('Error: '.length);
432
+ return relevantMessage;
433
+ };
434
+ const isModuleNotFoundMessage = line => {
435
+ return line.includes('[ERR_MODULE_NOT_FOUND]');
436
+ };
437
+ const getModuleNotFoundError = stderr => {
438
+ const lines = splitLines$1(stderr);
439
+ const messageIndex = lines.findIndex(isModuleNotFoundMessage);
440
+ const message = lines[messageIndex];
441
+ return {
442
+ message,
443
+ code: ERR_MODULE_NOT_FOUND
444
+ };
445
+ };
446
+ const isModuleNotFoundError = stderr => {
447
+ if (!stderr) {
448
+ return false;
449
+ }
450
+ return stderr.includes('ERR_MODULE_NOT_FOUND');
451
+ };
452
+ const isModulesSyntaxError = stderr => {
453
+ if (!stderr) {
454
+ return false;
455
+ }
456
+ return stderr.includes('SyntaxError: Cannot use import statement outside a module');
457
+ };
458
+ const RE_NATIVE_MODULE_ERROR = /^innerError Error: Cannot find module '.*.node'/;
459
+ const RE_NATIVE_MODULE_ERROR_2 = /was compiled against a different Node.js version/;
460
+ const isUnhelpfulNativeModuleError = stderr => {
461
+ return RE_NATIVE_MODULE_ERROR.test(stderr) && RE_NATIVE_MODULE_ERROR_2.test(stderr);
462
+ };
463
+ const getNativeModuleErrorMessage = stderr => {
464
+ const message = getMessageCodeBlock(stderr);
465
+ return {
466
+ message: `Incompatible native node module: ${message}`,
467
+ code: E_INCOMPATIBLE_NATIVE_MODULE
468
+ };
469
+ };
470
+ const getModuleSyntaxError = () => {
471
+ return {
472
+ message: `ES Modules are not supported in electron`,
473
+ code: E_MODULES_NOT_SUPPORTED_IN_ELECTRON
474
+ };
475
+ };
476
+ const getHelpfulChildProcessError = (stdout, stderr) => {
477
+ if (isUnhelpfulNativeModuleError(stderr)) {
478
+ return getNativeModuleErrorMessage(stderr);
479
+ }
480
+ if (isModulesSyntaxError(stderr)) {
481
+ return getModuleSyntaxError();
482
+ }
483
+ if (isModuleNotFoundError(stderr)) {
484
+ return getModuleNotFoundError(stderr);
485
+ }
486
+ const lines = splitLines$1(stderr);
487
+ const {
488
+ actualMessage,
489
+ rest
490
+ } = getDetails(lines);
491
+ return {
492
+ message: actualMessage,
493
+ code: '',
494
+ stack: rest
495
+ };
496
+ };
497
+ class IpcError extends VError {
498
+ // @ts-ignore
499
+ constructor(betterMessage, stdout = '', stderr = '') {
500
+ if (stdout || stderr) {
501
+ // @ts-ignore
502
+ const {
503
+ message,
504
+ code,
505
+ stack
506
+ } = getHelpfulChildProcessError(stdout, stderr);
507
+ const cause = new Error(message);
508
+ // @ts-ignore
509
+ cause.code = code;
510
+ cause.stack = stack;
511
+ super(cause, betterMessage);
512
+ } else {
513
+ super(betterMessage);
514
+ }
515
+ // @ts-ignore
516
+ this.name = 'IpcError';
517
+ // @ts-ignore
518
+ this.stdout = stdout;
519
+ // @ts-ignore
520
+ this.stderr = stderr;
521
+ }
522
+ }
523
+ const listen$b = ({
524
+ messagePort
525
+ }) => {
526
+ if (!isMessagePortMain(messagePort)) {
527
+ throw new IpcError('port must be of type MessagePortMain');
528
+ }
529
+ return messagePort;
530
+ };
531
+ const signal$c = messagePort => {
532
+ messagePort.start();
533
+ };
534
+ class IpcChildWithElectronMessagePort extends Ipc {
535
+ getData = getActualDataElectron;
536
+ send(message) {
537
+ this._rawIpc.postMessage(message);
538
+ }
539
+ sendAndTransfer(message) {
540
+ const {
541
+ newValue,
542
+ transfer
543
+ } = fixElectronParameters(message);
544
+ this._rawIpc.postMessage(newValue, transfer);
545
+ }
546
+ dispose() {
547
+ this._rawIpc.close();
548
+ }
549
+ onMessage(callback) {
550
+ this._rawIpc.on('message', callback);
551
+ }
552
+ onClose(callback) {
553
+ this._rawIpc.on('close', callback);
554
+ }
555
+ }
556
+ const wrap$j = messagePort => {
557
+ return new IpcChildWithElectronMessagePort(messagePort);
558
+ };
559
+ const IpcChildWithElectronMessagePort$1 = {
560
+ __proto__: null,
561
+ listen: listen$b,
562
+ signal: signal$c,
563
+ wrap: wrap$j
564
+ };
565
+
566
+ // @ts-ignore
567
+ const getUtilityProcessPortData = event => {
568
+ const {
569
+ data,
570
+ ports
571
+ } = event;
572
+ if (ports.length === 0) {
573
+ return data;
574
+ }
575
+ return {
576
+ ...data,
577
+ params: [...ports, ...data.params]
578
+ };
579
+ };
580
+ const readyMessage = 'ready';
581
+ const listen$a = () => {
582
+ // @ts-ignore
583
+ const {
584
+ parentPort
585
+ } = process;
586
+ if (!parentPort) {
587
+ throw new Error('parent port must be defined');
588
+ }
589
+ return parentPort;
590
+ };
591
+ const signal$b = parentPort => {
592
+ parentPort.postMessage(readyMessage);
593
+ };
594
+ class IpcChildWithElectronUtilityProcess extends Ipc {
595
+ getData(event) {
596
+ return getUtilityProcessPortData(event);
597
+ }
598
+ send(message) {
599
+ this._rawIpc.postMessage(message);
600
+ }
601
+ sendAndTransfer(message) {
602
+ const {
603
+ newValue,
604
+ transfer
605
+ } = fixElectronParameters(message);
606
+ this._rawIpc.postMessage(newValue, transfer);
607
+ }
608
+ dispose() {
609
+ this._rawIpc.close();
610
+ }
611
+ onClose(callback) {
612
+ this._rawIpc.on('close', callback);
613
+ }
614
+ onMessage(callback) {
615
+ this._rawIpc.on('message', callback);
616
+ }
617
+ }
618
+ const wrap$i = parentPort => {
619
+ return new IpcChildWithElectronUtilityProcess(parentPort);
620
+ };
621
+ const IpcChildWithElectronUtilityProcess$1 = {
622
+ __proto__: null,
623
+ listen: listen$a,
624
+ signal: signal$b,
625
+ wrap: wrap$i
626
+ };
627
+ const getActualData = (message, handle) => {
628
+ if (handle) {
629
+ return {
630
+ ...message,
631
+ params: [handle, ...message.params]
632
+ };
633
+ }
634
+ return message;
635
+ };
636
+ const getTransferrablesNode = value => {
637
+ const transferrables = getTransferrables(value);
638
+ if (transferrables.length === 0) {
639
+ throw new Error(`no transferrables found`);
640
+ }
641
+ return transferrables[0];
642
+ };
643
+ const listen$5 = async () => {
644
+ if (!process.send) {
645
+ throw new Error('process.send must be defined');
646
+ }
647
+ return process;
648
+ };
649
+ const signal$7 = process => {
650
+ process.send(readyMessage);
651
+ };
652
+ class IpcChildWithNodeForkedProcess extends Ipc {
653
+ getData(message, handle) {
654
+ return getActualData(message, handle);
655
+ }
656
+ onClose(callback) {
657
+ this._rawIpc.on('close', callback);
658
+ }
659
+ send(message) {
660
+ this._rawIpc.send(message);
661
+ }
662
+ onMessage(callback) {
663
+ this._rawIpc.on('message', callback);
664
+ }
665
+ sendAndTransfer(message) {
666
+ const transfer = getTransferrablesNode(message);
667
+ this._rawIpc.send(message, transfer);
668
+ }
669
+ dispose() {
670
+ // ignore
671
+ }
672
+ }
673
+ const wrap$d = process => {
674
+ return new IpcChildWithNodeForkedProcess(process);
675
+ };
676
+ const IpcChildWithNodeForkedProcess$1 = {
677
+ __proto__: null,
678
+ listen: listen$5,
679
+ signal: signal$7,
680
+ wrap: wrap$d
681
+ };
682
+ const listen$3 = async () => {
683
+ const {
684
+ parentPort
685
+ } = await import('node:worker_threads');
686
+ if (!parentPort) {
687
+ throw new IpcError('parentPort is required');
688
+ }
689
+ return parentPort;
690
+ };
691
+ const signal$5 = parentPort => {
692
+ parentPort.postMessage(readyMessage);
693
+ };
694
+ class IpcChildWithNodeWorker extends Ipc {
695
+ getData(data) {
696
+ return data;
697
+ }
698
+ onClose(callback) {
699
+ this._rawIpc.on('close', callback);
700
+ }
701
+ send(message) {
702
+ this._rawIpc.postMessage(message);
703
+ }
704
+ onMessage(callback) {
705
+ this._rawIpc.on('message', callback);
706
+ }
707
+ sendAndTransfer(message) {
708
+ const transfer = getTransferrablesNode(message);
709
+ this._rawIpc.postMessage(message, transfer);
710
+ }
711
+ dispose() {
712
+ this._rawIpc.close();
713
+ }
714
+ }
715
+ const wrap$b = parentPort => {
716
+ return new IpcChildWithNodeWorker(parentPort);
717
+ };
718
+ const IpcChildWithNodeWorker$1 = {
719
+ __proto__: null,
720
+ listen: listen$3,
721
+ signal: signal$5,
722
+ wrap: wrap$b
723
+ };
724
+ const Open = 2;
725
+ const Close = 3;
726
+ const addListener = (emitter, type, callback) => {
727
+ if ('addEventListener' in emitter) {
728
+ emitter.addEventListener(type, callback);
729
+ } else {
730
+ emitter.on(type, callback);
731
+ }
732
+ };
733
+ const removeListener = (emitter, type, callback) => {
734
+ if ('removeEventListener' in emitter) {
735
+ emitter.removeEventListener(type, callback);
736
+ } else {
737
+ emitter.off(type, callback);
738
+ }
739
+ };
740
+ const getFirstEvent = (eventEmitter, eventMap) => {
741
+ const {
742
+ resolve,
743
+ promise
744
+ } = Promise.withResolvers();
745
+ const listenerMap = Object.create(null);
746
+ const cleanup = value => {
747
+ for (const event of Object.keys(eventMap)) {
748
+ removeListener(eventEmitter, event, listenerMap[event]);
749
+ }
750
+ resolve(value);
751
+ };
752
+ for (const [event, type] of Object.entries(eventMap)) {
753
+ const listener = event => {
754
+ cleanup({
755
+ type,
756
+ event
757
+ });
758
+ };
759
+ addListener(eventEmitter, event, listener);
760
+ listenerMap[event] = listener;
761
+ }
762
+ return promise;
763
+ };
764
+
765
+ // @ts-ignore
766
+ const getFirstWebSocketEvent = async webSocket => {
767
+ // @ts-ignore
768
+ const {
769
+ WebSocket
770
+ } = await import('ws');
771
+ switch (webSocket.readyState) {
772
+ case WebSocket.OPEN:
773
+ return {
774
+ type: Open,
775
+ event: undefined
776
+ };
777
+ case WebSocket.CLOSED:
778
+ return {
779
+ type: Close,
780
+ event: undefined
781
+ };
782
+ }
783
+ // @ts-ignore
784
+ const {
785
+ type,
786
+ event
787
+ } = await getFirstEvent(webSocket, {
788
+ open: Open,
789
+ close: Close
790
+ });
791
+ return {
792
+ type,
793
+ event
794
+ };
795
+ };
796
+
797
+ // @ts-ignore
798
+ const isWebSocketOpen = async webSocket => {
799
+ // @ts-ignore
800
+ const {
801
+ WebSocket
802
+ } = await import('ws');
803
+ return webSocket.readyState === WebSocket.OPEN;
804
+ };
805
+
806
+ // @ts-ignore
807
+ const serialize = message => {
808
+ return JSON.stringify(message);
809
+ };
810
+
811
+ // @ts-ignore
812
+ const deserialize = message => {
813
+ return JSON.parse(message.toString());
814
+ };
815
+
816
+ // @ts-ignore
817
+ const handleUpgrade$1 = async (...args) => {
818
+ const module = await Promise.resolve().then(function () { return index; });
819
+ // @ts-ignore
820
+ return module.handleUpgrade(...args);
821
+ };
822
+
823
+ // @ts-ignore
824
+ const listen$1$1 = async ({
825
+ request,
826
+ handle
827
+ }) => {
828
+ if (!request) {
829
+ throw new IpcError('request must be defined');
830
+ }
831
+ if (!handle) {
832
+ throw new IpcError('handle must be defined');
833
+ }
834
+ const webSocket = await handleUpgrade$1(request, handle);
835
+ webSocket.pause();
836
+ if (!(await isWebSocketOpen(webSocket))) {
837
+ await getFirstWebSocketEvent(webSocket);
838
+ }
839
+ return webSocket;
840
+ };
841
+ const signal$4 = webSocket => {
842
+ webSocket.resume();
843
+ };
844
+
845
+ // @ts-ignore
846
+ const wrap$9 = webSocket => {
847
+ return {
848
+ webSocket,
849
+ /**
850
+ * @type {any}
851
+ */
852
+ wrappedListener: undefined,
853
+ // @ts-ignore
854
+ on(event, listener) {
855
+ switch (event) {
856
+ case 'message':
857
+ // @ts-ignore
858
+ const wrappedListener = message => {
859
+ const data = deserialize(message);
860
+ const event = {
861
+ data,
862
+ target: this
863
+ };
864
+ listener(event);
865
+ };
866
+ webSocket.on('message', wrappedListener);
867
+ break;
868
+ case 'close':
869
+ webSocket.on('close', listener);
870
+ break;
871
+ default:
872
+ throw new Error('unknown event listener type');
873
+ }
874
+ },
875
+ // @ts-ignore
876
+ off(event, listener) {
877
+ this.webSocket.off(event, listener);
878
+ },
879
+ // @ts-ignore
880
+ send(message) {
881
+ const stringifiedMessage = serialize(message);
882
+ this.webSocket.send(stringifiedMessage);
883
+ },
884
+ dispose() {
885
+ this.webSocket.close();
886
+ },
887
+ start() {
888
+ throw new Error('start method is deprecated');
889
+ }
890
+ };
891
+ };
892
+ const IpcChildWithWebSocket = {
893
+ __proto__: null,
894
+ listen: listen$1$1,
895
+ signal: signal$4,
896
+ wrap: wrap$9
897
+ };
898
+
899
+ const Two = '2.0';
900
+ const create$4$1 = (method, params) => {
901
+ return {
902
+ jsonrpc: Two,
903
+ method,
904
+ params
905
+ };
906
+ };
907
+ const callbacks = Object.create(null);
908
+ const set$1 = (id, fn) => {
909
+ callbacks[id] = fn;
910
+ };
911
+ const get = id => {
912
+ return callbacks[id];
913
+ };
914
+ const remove = id => {
915
+ delete callbacks[id];
916
+ };
917
+ let id = 0;
918
+ const create$3 = () => {
919
+ return ++id;
920
+ };
921
+ const registerPromise = () => {
922
+ const id = create$3();
923
+ const {
924
+ resolve,
925
+ promise
926
+ } = Promise.withResolvers();
927
+ set$1(id, resolve);
928
+ return {
929
+ id,
930
+ promise
931
+ };
932
+ };
933
+ const create$2 = (method, params) => {
934
+ const {
935
+ id,
936
+ promise
937
+ } = registerPromise();
938
+ const message = {
939
+ jsonrpc: Two,
940
+ method,
941
+ params,
942
+ id
943
+ };
944
+ return {
945
+ message,
946
+ promise
947
+ };
948
+ };
949
+ class JsonRpcError extends Error {
950
+ constructor(message) {
951
+ super(message);
952
+ this.name = 'JsonRpcError';
953
+ }
954
+ }
955
+ const NewLine = '\n';
956
+ const DomException = 'DOMException';
957
+ const ReferenceError$1 = 'ReferenceError';
958
+ const SyntaxError$1 = 'SyntaxError';
959
+ const TypeError$1 = 'TypeError';
960
+ const getErrorConstructor = (message, type) => {
961
+ if (type) {
962
+ switch (type) {
963
+ case DomException:
964
+ return DOMException;
965
+ case TypeError$1:
966
+ return TypeError;
967
+ case SyntaxError$1:
968
+ return SyntaxError;
969
+ case ReferenceError$1:
970
+ return ReferenceError;
971
+ default:
972
+ return Error;
973
+ }
974
+ }
975
+ if (message.startsWith('TypeError: ')) {
976
+ return TypeError;
977
+ }
978
+ if (message.startsWith('SyntaxError: ')) {
979
+ return SyntaxError;
980
+ }
981
+ if (message.startsWith('ReferenceError: ')) {
982
+ return ReferenceError;
983
+ }
984
+ return Error;
985
+ };
986
+ const constructError = (message, type, name) => {
987
+ const ErrorConstructor = getErrorConstructor(message, type);
988
+ if (ErrorConstructor === DOMException && name) {
989
+ return new ErrorConstructor(message, name);
990
+ }
991
+ if (ErrorConstructor === Error) {
992
+ const error = new Error(message);
993
+ if (name && name !== 'VError') {
994
+ error.name = name;
995
+ }
996
+ return error;
997
+ }
998
+ return new ErrorConstructor(message);
999
+ };
1000
+ const getNewLineIndex = (string, startIndex = undefined) => {
1001
+ return string.indexOf(NewLine, startIndex);
1002
+ };
1003
+ const getParentStack = error => {
1004
+ let parentStack = error.stack || error.data || error.message || '';
1005
+ if (parentStack.startsWith(' at')) {
1006
+ parentStack = error.message + NewLine + parentStack;
1007
+ }
1008
+ return parentStack;
1009
+ };
1010
+ const joinLines = lines => {
1011
+ return lines.join(NewLine);
1012
+ };
1013
+ const MethodNotFound = -32601;
1014
+ const Custom = -32001;
1015
+ const splitLines = lines => {
1016
+ return lines.split(NewLine);
1017
+ };
1018
+ const restoreJsonRpcError = error => {
1019
+ if (error && error instanceof Error) {
1020
+ return error;
1021
+ }
1022
+ const currentStack = joinLines(splitLines(new Error().stack || '').slice(1));
1023
+ if (error && error.code && error.code === MethodNotFound) {
1024
+ const restoredError = new JsonRpcError(error.message);
1025
+ const parentStack = getParentStack(error);
1026
+ restoredError.stack = parentStack + NewLine + currentStack;
1027
+ return restoredError;
1028
+ }
1029
+ if (error && error.message) {
1030
+ const restoredError = constructError(error.message, error.type, error.name);
1031
+ if (error.data) {
1032
+ if (error.data.stack && error.data.type && error.message) {
1033
+ restoredError.stack = error.data.type + ': ' + error.message + NewLine + error.data.stack + NewLine + currentStack;
1034
+ } else if (error.data.stack) {
1035
+ restoredError.stack = error.data.stack;
1036
+ }
1037
+ if (error.data.codeFrame) {
1038
+ // @ts-ignore
1039
+ restoredError.codeFrame = error.data.codeFrame;
1040
+ }
1041
+ if (error.data.code) {
1042
+ // @ts-ignore
1043
+ restoredError.code = error.data.code;
1044
+ }
1045
+ if (error.data.type) {
1046
+ // @ts-ignore
1047
+ restoredError.name = error.data.type;
1048
+ }
1049
+ } else {
1050
+ if (error.stack) {
1051
+ const lowerStack = restoredError.stack || '';
1052
+ // @ts-ignore
1053
+ const indexNewLine = getNewLineIndex(lowerStack);
1054
+ const parentStack = getParentStack(error);
1055
+ // @ts-ignore
1056
+ restoredError.stack = parentStack + lowerStack.slice(indexNewLine);
1057
+ }
1058
+ if (error.codeFrame) {
1059
+ // @ts-ignore
1060
+ restoredError.codeFrame = error.codeFrame;
1061
+ }
1062
+ }
1063
+ return restoredError;
1064
+ }
1065
+ if (typeof error === 'string') {
1066
+ return new Error(`JsonRpc Error: ${error}`);
1067
+ }
1068
+ return new Error(`JsonRpc Error: ${error}`);
1069
+ };
1070
+ const unwrapJsonRpcResult = responseMessage => {
1071
+ if ('error' in responseMessage) {
1072
+ const restoredError = restoreJsonRpcError(responseMessage.error);
1073
+ throw restoredError;
1074
+ }
1075
+ if ('result' in responseMessage) {
1076
+ return responseMessage.result;
1077
+ }
1078
+ throw new JsonRpcError('unexpected response message');
1079
+ };
1080
+ const warn = (...args) => {
1081
+ console.warn(...args);
1082
+ };
1083
+ const resolve = (id, response) => {
1084
+ const fn = get(id);
1085
+ if (!fn) {
1086
+ console.log(response);
1087
+ warn(`callback ${id} may already be disposed`);
1088
+ return;
1089
+ }
1090
+ fn(response);
1091
+ remove(id);
1092
+ };
1093
+ const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
1094
+ const getErrorType = prettyError => {
1095
+ if (prettyError && prettyError.type) {
1096
+ return prettyError.type;
1097
+ }
1098
+ if (prettyError && prettyError.constructor && prettyError.constructor.name) {
1099
+ return prettyError.constructor.name;
1100
+ }
1101
+ return undefined;
1102
+ };
1103
+ const getErrorProperty = (error, prettyError) => {
1104
+ if (error && error.code === E_COMMAND_NOT_FOUND) {
1105
+ return {
1106
+ code: MethodNotFound,
1107
+ message: error.message,
1108
+ data: error.stack
1109
+ };
1110
+ }
1111
+ return {
1112
+ code: Custom,
1113
+ message: prettyError.message,
1114
+ data: {
1115
+ stack: prettyError.stack,
1116
+ codeFrame: prettyError.codeFrame,
1117
+ type: getErrorType(prettyError),
1118
+ code: prettyError.code,
1119
+ name: prettyError.name
1120
+ }
1121
+ };
1122
+ };
1123
+ const create$1 = (message, error) => {
1124
+ return {
1125
+ jsonrpc: Two,
1126
+ id: message.id,
1127
+ error
1128
+ };
1129
+ };
1130
+ const getErrorResponse = (message, error, preparePrettyError, logError) => {
1131
+ const prettyError = preparePrettyError(error);
1132
+ logError(error, prettyError);
1133
+ const errorProperty = getErrorProperty(error, prettyError);
1134
+ return create$1(message, errorProperty);
1135
+ };
1136
+ const create = (message, result) => {
1137
+ return {
1138
+ jsonrpc: Two,
1139
+ id: message.id,
1140
+ result: result ?? null
1141
+ };
1142
+ };
1143
+ const getSuccessResponse = (message, result) => {
1144
+ const resultProperty = result ?? null;
1145
+ return create(message, resultProperty);
1146
+ };
1147
+ const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
1148
+ try {
1149
+ const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
1150
+ return getSuccessResponse(message, result);
1151
+ } catch (error) {
1152
+ return getErrorResponse(message, error, preparePrettyError, logError);
1153
+ }
1154
+ };
1155
+ const defaultPreparePrettyError = error => {
1156
+ return error;
1157
+ };
1158
+ const defaultLogError = () => {
1159
+ // ignore
1160
+ };
1161
+ const defaultRequiresSocket = () => {
1162
+ return false;
1163
+ };
1164
+ const defaultResolve = resolve;
1165
+
1166
+ // TODO maybe remove this in v6 or v7, only accept options object to simplify the code
1167
+ const normalizeParams = args => {
1168
+ if (args.length === 1) {
1169
+ const options = args[0];
1170
+ return {
1171
+ ipc: options.ipc,
1172
+ message: options.message,
1173
+ execute: options.execute,
1174
+ resolve: options.resolve || defaultResolve,
1175
+ preparePrettyError: options.preparePrettyError || defaultPreparePrettyError,
1176
+ logError: options.logError || defaultLogError,
1177
+ requiresSocket: options.requiresSocket || defaultRequiresSocket
1178
+ };
1179
+ }
1180
+ return {
1181
+ ipc: args[0],
1182
+ message: args[1],
1183
+ execute: args[2],
1184
+ resolve: args[3],
1185
+ preparePrettyError: args[4],
1186
+ logError: args[5],
1187
+ requiresSocket: args[6]
1188
+ };
1189
+ };
1190
+ const handleJsonRpcMessage = async (...args) => {
1191
+ const options = normalizeParams(args);
1192
+ const {
1193
+ message,
1194
+ ipc,
1195
+ execute,
1196
+ resolve,
1197
+ preparePrettyError,
1198
+ logError,
1199
+ requiresSocket
1200
+ } = options;
1201
+ if ('id' in message) {
1202
+ if ('method' in message) {
1203
+ const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
1204
+ try {
1205
+ ipc.send(response);
1206
+ } catch (error) {
1207
+ const errorResponse = getErrorResponse(message, error, preparePrettyError, logError);
1208
+ ipc.send(errorResponse);
1209
+ }
1210
+ return;
1211
+ }
1212
+ resolve(message.id, message);
1213
+ return;
1214
+ }
1215
+ if ('method' in message) {
1216
+ await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
1217
+ return;
1218
+ }
1219
+ throw new JsonRpcError('unexpected message');
1220
+ };
1221
+ const invokeHelper = async (ipc, method, params, useSendAndTransfer) => {
1222
+ const {
1223
+ message,
1224
+ promise
1225
+ } = create$2(method, params);
1226
+ if (useSendAndTransfer && ipc.sendAndTransfer) {
1227
+ ipc.sendAndTransfer(message);
1228
+ } else {
1229
+ ipc.send(message);
1230
+ }
1231
+ const responseMessage = await promise;
1232
+ return unwrapJsonRpcResult(responseMessage);
1233
+ };
1234
+ const send = (transport, method, ...params) => {
1235
+ const message = create$4$1(method, params);
1236
+ transport.send(message);
1237
+ };
1238
+ const invoke = (ipc, method, ...params) => {
1239
+ return invokeHelper(ipc, method, params, false);
1240
+ };
1241
+ const invokeAndTransfer = (ipc, method, ...params) => {
1242
+ return invokeHelper(ipc, method, params, true);
1243
+ };
1244
+
1245
+ const commands = Object.create(null);
1246
+ const register = commandMap => {
1247
+ Object.assign(commands, commandMap);
1248
+ };
1249
+ const getCommand = key => {
1250
+ return commands[key];
1251
+ };
1252
+ const execute = (command, ...args) => {
1253
+ const fn = getCommand(command);
1254
+ if (!fn) {
1255
+ throw new Error(`command not found ${command}`);
1256
+ }
1257
+ return fn(...args);
1258
+ };
1259
+
1260
+ const createRpc = ipc => {
1261
+ const rpc = {
1262
+ // @ts-ignore
1263
+ ipc,
1264
+ /**
1265
+ * @deprecated
1266
+ */
1267
+ send(method, ...params) {
1268
+ send(ipc, method, ...params);
1269
+ },
1270
+ invoke(method, ...params) {
1271
+ return invoke(ipc, method, ...params);
1272
+ },
1273
+ invokeAndTransfer(method, ...params) {
1274
+ return invokeAndTransfer(ipc, method, ...params);
1275
+ },
1276
+ async dispose() {
1277
+ await ipc?.dispose();
1278
+ }
1279
+ };
1280
+ return rpc;
1281
+ };
1282
+ const requiresSocket = () => {
1283
+ return false;
1284
+ };
1285
+ const preparePrettyError = error => {
1286
+ return error;
1287
+ };
1288
+ const logError = () => {
1289
+ // handled by renderer worker
1290
+ };
1291
+ const handleMessage = event => {
1292
+ const actualRequiresSocket = event?.target?.requiresSocket || requiresSocket;
1293
+ const actualExecute = event?.target?.execute || execute;
1294
+ return handleJsonRpcMessage(event.target, event.data, actualExecute, resolve, preparePrettyError, logError, actualRequiresSocket);
1295
+ };
1296
+ const handleIpc = ipc => {
1297
+ if ('addEventListener' in ipc) {
1298
+ ipc.addEventListener('message', handleMessage);
1299
+ } else if ('on' in ipc) {
1300
+ // deprecated
1301
+ ipc.on('message', handleMessage);
1302
+ }
1303
+ };
1304
+ const listen$2 = async (module, options) => {
1305
+ const rawIpc = await module.listen(options);
1306
+ if (module.signal) {
1307
+ module.signal(rawIpc);
1308
+ }
1309
+ const ipc = module.wrap(rawIpc);
1310
+ return ipc;
1311
+ };
1312
+ const create$e = async ({
1313
+ commandMap,
1314
+ messagePort,
1315
+ requiresSocket
1316
+ }) => {
1317
+ // TODO create a commandMap per rpc instance
1318
+ register(commandMap);
1319
+ const ipc = await listen$2(IpcChildWithElectronMessagePort$1, {
1320
+ messagePort
1321
+ });
1322
+ if (requiresSocket) {
1323
+ ipc.requiresSocket = requiresSocket;
1324
+ }
1325
+ handleIpc(ipc);
1326
+ const rpc = createRpc(ipc);
1327
+ return rpc;
1328
+ };
1329
+ const ElectronMessagePortRpcClient = {
1330
+ __proto__: null,
1331
+ create: create$e
1332
+ };
1333
+ const create$d = async ({
1334
+ commandMap
1335
+ }) => {
1336
+ // TODO create a commandMap per rpc instance
1337
+ register(commandMap);
1338
+ const ipc = await listen$2(IpcChildWithElectronUtilityProcess$1);
1339
+ handleIpc(ipc);
1340
+ const rpc = createRpc(ipc);
1341
+ return rpc;
1342
+ };
1343
+ const ElectronUtilityProcessRpcClient = {
1344
+ __proto__: null,
1345
+ create: create$d
1346
+ };
1347
+ const create$7 = async ({
1348
+ commandMap
1349
+ }) => {
1350
+ // TODO create a commandMap per rpc instance
1351
+ register(commandMap);
1352
+ const ipc = await listen$2(IpcChildWithNodeForkedProcess$1);
1353
+ handleIpc(ipc);
1354
+ const rpc = createRpc(ipc);
1355
+ return rpc;
1356
+ };
1357
+ const NodeForkedProcessRpcClient = {
1358
+ __proto__: null,
1359
+ create: create$7
1360
+ };
1361
+ const create$5 = async ({
1362
+ commandMap,
1363
+ request,
1364
+ handle,
1365
+ requiresSocket
1366
+ }) => {
1367
+ // TODO create a commandMap per rpc instance
1368
+ register(commandMap);
1369
+ const ipc = await listen$2(IpcChildWithWebSocket, {
1370
+ request,
1371
+ handle
1372
+ });
1373
+ if (requiresSocket) {
1374
+ ipc.requiresSocket = requiresSocket;
1375
+ }
1376
+ handleIpc(ipc);
1377
+ const rpc = createRpc(ipc);
1378
+ return rpc;
1379
+ };
1380
+ const NodeWebSocketRpcClient = {
1381
+ __proto__: null,
1382
+ create: create$5
1383
+ };
1384
+ const create$4 = async ({
1385
+ commandMap
1386
+ }) => {
1387
+ // TODO create a commandMap per rpc instance
1388
+ register(commandMap);
1389
+ const ipc = await listen$2(IpcChildWithNodeWorker$1);
1390
+ handleIpc(ipc);
1391
+ const rpc = createRpc(ipc);
1392
+ return rpc;
1393
+ };
1394
+ const NodeWorkerRpcClient = {
1395
+ __proto__: null,
1396
+ create: create$4
1397
+ };
1398
+
1399
+ const NodeWorker = 1;
1400
+ const NodeForkedProcess = 2;
1401
+ const ElectronUtilityProcess = 3;
1402
+ const ElectronMessagePort = 4;
1403
+ const WebSocket = 6;
1404
+ const Auto = argv => {
1405
+ if (argv.includes('--ipc-type=node-worker')) {
1406
+ return NodeWorker;
1407
+ }
1408
+ if (argv.includes('--ipc-type=node-forked-process')) {
1409
+ return NodeForkedProcess;
1410
+ }
1411
+ if (argv.includes('--ipc-type=electron-utility-process')) {
1412
+ return ElectronUtilityProcess;
1413
+ }
1414
+ throw new Error(`[search-process] unknown ipc type`);
1415
+ };
1416
+
1417
+ const getModule$1 = method => {
1418
+ switch (method) {
1419
+ case NodeForkedProcess:
1420
+ return NodeForkedProcessRpcClient.create;
1421
+ case NodeWorker:
1422
+ return NodeWorkerRpcClient.create;
1423
+ case ElectronUtilityProcess:
1424
+ return ElectronUtilityProcessRpcClient.create;
1425
+ case ElectronMessagePort:
1426
+ return ElectronMessagePortRpcClient.create;
1427
+ case WebSocket:
1428
+ return NodeWebSocketRpcClient.create;
1429
+ default:
1430
+ throw new Error('unexpected ipc type');
1431
+ }
1432
+ };
1433
+
1434
+ const listen$1 = async ({
1435
+ method,
1436
+ ...params
1437
+ }) => {
1438
+ const create = getModule$1(method);
1439
+ const rpc = await create(params);
1440
+ return rpc;
1441
+ };
1442
+
1443
+ const targetMessagePort$2 = async (messagePort, message) => {
1444
+ object(messagePort);
1445
+ const rpc = await listen$1({
1446
+ method: ElectronMessagePort,
1447
+ messagePort,
1448
+ commandMap: commandMapRef
1449
+ });
1450
+ // @ts-ignore
1451
+ const ipc = rpc.ipc;
1452
+ ipc.addEventListener('close', handleIpcClosed);
1453
+ return rpc;
1454
+ };
1455
+ const upgradeMessagePort$2 = () => {
1456
+ return {
1457
+ type: 'handle'
1458
+ };
1459
+ };
1460
+
1461
+ const HandleIpcEmbedsWorker = {
1462
+ __proto__: null,
1463
+ targetMessagePort: targetMessagePort$2,
1464
+ upgradeMessagePort: upgradeMessagePort$2
1465
+ };
1466
+
1467
+ const targetMessagePort$1 = async (messagePort, message) => {
1468
+ object(messagePort);
1469
+ const rpc = await listen$1({
1470
+ method: ElectronMessagePort,
1471
+ messagePort
1472
+ });
1473
+ set$2(rpc);
1474
+ return rpc;
1475
+ };
1476
+ const upgradeMessagePort$1 = () => {
1477
+ return {
1478
+ type: 'handle'
1479
+ };
1480
+ };
1481
+
1482
+ const HandleIpcMainProcess = {
1483
+ __proto__: null,
1484
+ targetMessagePort: targetMessagePort$1,
1485
+ upgradeMessagePort: upgradeMessagePort$1
1486
+ };
1487
+
1488
+ const {
1489
+ set
1490
+ } = SharedProcess$2;
1491
+
1492
+ const targetMessagePort = async (messagePort, message) => {
1493
+ object(messagePort);
1494
+ const rpc = await ElectronMessagePortRpcClient.create({
1495
+ messagePort,
1496
+ commandMap: commandMapRef
1497
+ });
1498
+ set(rpc);
1499
+ return rpc;
1500
+ };
1501
+ const upgradeMessagePort = () => {
1502
+ return {
1503
+ type: 'handle'
1504
+ };
1505
+ };
1506
+
1507
+ const HandleIpcSharedProcess = {
1508
+ __proto__: null,
1509
+ targetMessagePort,
1510
+ upgradeMessagePort
1511
+ };
1512
+
1513
+ const EmbedsWorker = 77;
1514
+ const MainProcess = -5;
1515
+ const SharedProcess = 1;
1516
+
1517
+ const getModule = ipcId => {
1518
+ number(ipcId);
1519
+ switch (ipcId) {
1520
+ case SharedProcess:
1521
+ return HandleIpcSharedProcess;
1522
+ case EmbedsWorker:
1523
+ return HandleIpcEmbedsWorker;
1524
+ case MainProcess:
1525
+ return HandleIpcMainProcess;
1526
+ default:
1527
+ throw new Error(`Embeds process encountered unexpected incoming ipc ${ipcId}`);
1528
+ }
1529
+ };
1530
+
1531
+ const getIpcAndResponse = (module, handle, message) => {
1532
+ return handleIncomingIpcMessagePort(module, handle, message);
1533
+ };
1534
+ const handleIncomingIpc = async (ipcId, handle, message) => {
1535
+ number(ipcId);
1536
+ const module = getModule(ipcId);
1537
+ const {
1538
+ target,
1539
+ response
1540
+ } = await getIpcAndResponse(module, handle, message);
1541
+ await applyIncomingIpcResponse(target, response);
1542
+ };
1543
+
1544
+ const handleElectronMessagePort = async (messagePort, ipcId) => {
1545
+ object(messagePort);
1546
+ number(ipcId);
1547
+ return handleIncomingIpc(ipcId, messagePort, {});
1548
+ };
1549
+
1550
+ const commandMap = {
1551
+ 'ElectronWebContentsView.backward': backward,
1552
+ 'ElectronWebContentsView.createWebContentsView': createWebContentsView,
1553
+ 'ElectronWebContentsView.disposeWebContentsView': disposeWebContentsView,
1554
+ 'ElectronWebContentsView.focus': focus,
1555
+ 'ElectronWebContentsView.forward': forward,
1556
+ 'ElectronWebContentsView.getStats': getStats,
1557
+ 'ElectronWebContentsView.inspectElement': inspectElement,
1558
+ 'ElectronWebContentsView.openDevtools': openDevtools,
1559
+ 'ElectronWebContentsView.reload': reload,
1560
+ 'ElectronWebContentsView.resizeBrowserView': resizeWebContentsView,
1561
+ 'ElectronWebContentsView.setIframeSrc': setIframeSrc,
1562
+ 'ElectronWebContentsView.setIframeSrcFallback': setIframeSrcFallback,
1563
+ 'ElectronWebContentsView.setFallthroughKeyBindings': setFallthroughKeyBindings,
1564
+ 'ElectronWebContentsView.handleKeyBinding': handleKeyBinding,
1565
+ 'ElectronWebContentsView.show': show,
1566
+ 'ElectronWebContents.handleDidNavigate': handleDidNavigate,
1567
+ 'ElectronWebContents.handleTitleUpdated': handleTitleUpdated,
1568
+ 'ElectronWebContents.handleBrowserViewDestroyed': handleBrowserViewDestroyed,
1569
+ 'ElectronWebContents.handleWillNavigate': handleWillNavigate,
1570
+ 'ElectronWebContents.handleContextMenu': handleContextMenu,
1571
+ 'HandleElectronMessagePort.handleElectronMessagePort': handleElectronMessagePort
1572
+ };
1573
+
1574
+ const listen = async argv => {
1575
+ Object.assign(commandMapRef, commandMap);
1576
+ await listen$1({
1577
+ method: Auto(argv),
1578
+ commandMap: commandMap
1579
+ });
1580
+ };
1581
+
1582
+ const main = async () => {
1583
+ await listen(process.argv);
1584
+ };
1585
+
1586
+ main();
1587
+
1588
+ const createWebSocketServer = async () => {
1589
+ const _ws = await import('ws');
1590
+ // workaround for jest or node bug
1591
+ const WebSocketServer = _ws.WebSocketServer ? _ws.WebSocketServer :
1592
+ // @ts-ignore
1593
+ _ws.default.WebSocketServer;
1594
+ const webSocketServer = new WebSocketServer({
1595
+ noServer: true
1596
+
1597
+ // TODO not sure if ws compress is working at all
1598
+ // perMessageDeflate: true
1599
+ });
1600
+ return webSocketServer;
1601
+ };
1602
+ const doSocketUpgrade = (webSocketServer, request, socket) => {
1603
+ const {
1604
+ promise,
1605
+ resolve
1606
+ } = Promise.withResolvers();
1607
+ webSocketServer.handleUpgrade(request, socket, Buffer.alloc(0), resolve);
1608
+ return promise;
1609
+ };
1610
+ const handleUpgrade = async (request, socket) => {
1611
+ const webSocketServer = await createWebSocketServer();
1612
+ const webSocket = await doSocketUpgrade(webSocketServer, request, socket);
1613
+ return webSocket;
1614
+ };
1615
+
1616
+ const index = {
1617
+ __proto__: null,
1618
+ handleUpgrade
1619
+ };