emr-bridge 1.7.1 → 2.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.
Files changed (157) hide show
  1. package/LICENCE +1 -1
  2. package/README.md +173 -366
  3. package/cjs/entries/index.d.ts +1 -0
  4. package/cjs/entries/index.js +6 -0
  5. package/cjs/entries/main.d.ts +2 -0
  6. package/cjs/entries/main.js +27 -0
  7. package/cjs/entries/preload.d.ts +3 -0
  8. package/cjs/entries/preload.js +29 -0
  9. package/cjs/entries/renderer.d.ts +2 -0
  10. package/cjs/entries/renderer.js +27 -0
  11. package/cjs/enums.d.ts +5 -14
  12. package/cjs/enums.js +12 -23
  13. package/cjs/errors.d.ts +42 -10
  14. package/cjs/errors.js +77 -23
  15. package/cjs/index.d.ts +4 -4
  16. package/cjs/index.js +11 -13
  17. package/cjs/main.d.ts +2 -4
  18. package/cjs/main.js +4 -13
  19. package/cjs/preload.d.ts +2 -2
  20. package/cjs/preload.js +3 -3
  21. package/cjs/renderer.d.ts +1 -1
  22. package/cjs/scripts/base-bridge.d.ts +95 -0
  23. package/cjs/scripts/base-bridge.js +128 -0
  24. package/cjs/scripts/bridge.d.ts +3 -3
  25. package/cjs/scripts/bridge.js +48 -36
  26. package/cjs/scripts/helpers/env.d.ts +19 -0
  27. package/cjs/scripts/helpers/env.js +28 -0
  28. package/cjs/scripts/helpers/error-thrower.d.ts +3 -0
  29. package/cjs/scripts/helpers/error-thrower.js +8 -0
  30. package/cjs/scripts/helpers/errors.d.ts +12 -0
  31. package/cjs/scripts/helpers/errors.js +17 -0
  32. package/cjs/scripts/helpers/id.d.ts +9 -0
  33. package/cjs/scripts/helpers/id.js +14 -0
  34. package/cjs/scripts/helpers/index.d.ts +8 -0
  35. package/cjs/scripts/helpers/index.js +22 -0
  36. package/cjs/scripts/helpers/ipc-channel.d.ts +75 -0
  37. package/cjs/scripts/helpers/ipc-channel.js +78 -0
  38. package/cjs/scripts/helpers/ipc-event-in-main.d.ts +24 -0
  39. package/cjs/scripts/helpers/ipc-event-in-main.js +30 -0
  40. package/cjs/scripts/helpers/ipc-result.d.ts +26 -0
  41. package/cjs/scripts/helpers/ipc-result.js +48 -0
  42. package/cjs/scripts/helpers/main-event.d.ts +8 -0
  43. package/cjs/scripts/helpers/main-event.js +15 -0
  44. package/cjs/scripts/helpers/transfer.d.ts +33 -0
  45. package/cjs/scripts/helpers/transfer.js +57 -0
  46. package/cjs/scripts/helpers/web-contents-container.d.ts +12 -0
  47. package/cjs/scripts/helpers/web-contents-container.js +34 -0
  48. package/cjs/scripts/helpers/web-contents-events-container.d.ts +56 -0
  49. package/cjs/scripts/helpers/web-contents-events-container.js +81 -0
  50. package/cjs/scripts/main/publish.d.ts +36 -0
  51. package/cjs/scripts/main/publish.js +186 -0
  52. package/cjs/scripts/preload/bridge.d.ts +27 -0
  53. package/cjs/scripts/preload/bridge.js +85 -0
  54. package/cjs/scripts/preload/provider.d.ts +7 -0
  55. package/cjs/scripts/preload/provider.js +89 -0
  56. package/cjs/scripts/preload-bridge.d.ts +20 -0
  57. package/cjs/scripts/preload-bridge.js +76 -0
  58. package/cjs/scripts/preload-provider.js +34 -50
  59. package/cjs/scripts/provider.d.ts +17 -15
  60. package/cjs/scripts/provider.js +69 -90
  61. package/cjs/scripts/publish.d.ts +19 -18
  62. package/cjs/scripts/publish.js +96 -174
  63. package/cjs/scripts/renderer/bridge.d.ts +6 -0
  64. package/cjs/scripts/renderer/bridge.js +74 -0
  65. package/cjs/scripts/renderer/tunnels.d.ts +171 -0
  66. package/cjs/scripts/renderer/tunnels.js +205 -0
  67. package/cjs/scripts/renderer-tunnels.d.ts +19 -21
  68. package/cjs/scripts/renderer-tunnels.js +52 -57
  69. package/cjs/types.d.ts +189 -64
  70. package/esm/entries/index.d.ts +1 -0
  71. package/esm/entries/index.js +5 -0
  72. package/esm/entries/main.d.ts +2 -0
  73. package/esm/entries/main.js +5 -0
  74. package/esm/entries/preload.d.ts +3 -0
  75. package/esm/entries/preload.js +7 -0
  76. package/esm/entries/renderer.d.ts +2 -0
  77. package/esm/entries/renderer.js +6 -0
  78. package/esm/enums.d.ts +5 -14
  79. package/esm/enums.js +11 -22
  80. package/esm/errors.d.ts +42 -10
  81. package/esm/errors.js +69 -16
  82. package/esm/helpers.d.ts +41 -0
  83. package/esm/helpers.js +96 -0
  84. package/esm/index.d.ts +4 -4
  85. package/esm/index.js +3 -3
  86. package/esm/main.d.ts +2 -4
  87. package/esm/main.js +1 -3
  88. package/esm/preload.d.ts +2 -2
  89. package/esm/preload.js +1 -1
  90. package/esm/renderer.d.ts +1 -1
  91. package/esm/scripts/base-bridge.d.ts +95 -0
  92. package/esm/scripts/base-bridge.js +125 -0
  93. package/esm/scripts/bridge.d.ts +3 -3
  94. package/esm/scripts/bridge.js +49 -37
  95. package/esm/scripts/helpers/electron-importer.d.ts +4 -0
  96. package/esm/scripts/helpers/electron-importer.js +16 -0
  97. package/esm/scripts/helpers/env.d.ts +19 -0
  98. package/esm/scripts/helpers/env.js +25 -0
  99. package/esm/scripts/helpers/error-thrower.d.ts +3 -0
  100. package/esm/scripts/helpers/error-thrower.js +5 -0
  101. package/esm/scripts/helpers/errors.d.ts +12 -0
  102. package/esm/scripts/helpers/errors.js +14 -0
  103. package/esm/scripts/helpers/id.d.ts +9 -0
  104. package/esm/scripts/helpers/id.js +11 -0
  105. package/esm/scripts/helpers/index.d.ts +8 -0
  106. package/esm/scripts/helpers/index.js +8 -0
  107. package/esm/scripts/helpers/ipc-channel.d.ts +75 -0
  108. package/esm/scripts/helpers/ipc-channel.js +76 -0
  109. package/esm/scripts/helpers/ipc-event-in-main.d.ts +24 -0
  110. package/esm/scripts/helpers/ipc-event-in-main.js +27 -0
  111. package/esm/scripts/helpers/ipc-result.d.ts +26 -0
  112. package/esm/scripts/helpers/ipc-result.js +42 -0
  113. package/esm/scripts/helpers/main-event.d.ts +8 -0
  114. package/esm/scripts/helpers/main-event.js +12 -0
  115. package/esm/scripts/helpers/transfer.d.ts +33 -0
  116. package/esm/scripts/helpers/transfer.js +54 -0
  117. package/esm/scripts/helpers/web-contents-container.d.ts +12 -0
  118. package/esm/scripts/helpers/web-contents-container.js +31 -0
  119. package/esm/scripts/helpers/web-contents-events-container.d.ts +56 -0
  120. package/esm/scripts/helpers/web-contents-events-container.js +78 -0
  121. package/esm/scripts/main/publish.d.ts +36 -0
  122. package/esm/scripts/main/publish.js +179 -0
  123. package/esm/scripts/main.d.ts +3 -3
  124. package/esm/scripts/main.js +41 -39
  125. package/esm/scripts/preload/bridge.d.ts +27 -0
  126. package/esm/scripts/preload/bridge.js +77 -0
  127. package/esm/scripts/preload/provider.d.ts +7 -0
  128. package/esm/scripts/preload/provider.js +84 -0
  129. package/esm/scripts/preload-bridge.d.ts +20 -0
  130. package/esm/scripts/preload-bridge.js +68 -0
  131. package/esm/scripts/preload-provider.js +34 -50
  132. package/esm/scripts/provider.d.ts +17 -15
  133. package/esm/scripts/provider.js +70 -91
  134. package/esm/scripts/publish.d.ts +19 -18
  135. package/esm/scripts/publish.js +89 -162
  136. package/esm/scripts/renderer/bridge.d.ts +6 -0
  137. package/esm/scripts/renderer/bridge.js +69 -0
  138. package/esm/scripts/renderer/tunnels.d.ts +171 -0
  139. package/esm/scripts/renderer/tunnels.js +203 -0
  140. package/esm/scripts/renderer-tunnels.d.ts +19 -21
  141. package/esm/scripts/renderer-tunnels.js +53 -55
  142. package/esm/types.d.ts +189 -64
  143. package/package.json +23 -41
  144. package/cjs/exp.d.ts +0 -4
  145. package/cjs/exp.js +0 -19
  146. package/cjs/scripts/main.d.ts +0 -8
  147. package/cjs/scripts/main.js +0 -72
  148. package/cjs/scripts/new-decorators.d.ts +0 -150
  149. package/cjs/scripts/new-decorators.js +0 -141
  150. package/cjs/scripts/old-decorators.d.ts +0 -185
  151. package/cjs/scripts/old-decorators.js +0 -132
  152. package/esm/exp.d.ts +0 -4
  153. package/esm/exp.js +0 -3
  154. package/esm/scripts/new-decorators.d.ts +0 -150
  155. package/esm/scripts/new-decorators.js +0 -132
  156. package/esm/scripts/old-decorators.d.ts +0 -185
  157. package/esm/scripts/old-decorators.js +0 -122
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const transfer_js_1 = __importDefault(require("./transfer.js"));
7
+ /**
8
+ * Хелпер для работы с результатом IPC.
9
+ */
10
+ class IpcResult {
11
+ /**
12
+ * Создать результат с обещанием.
13
+ * @param promiseChannel - Канал обработки обещания.
14
+ * @returns Результат с обещанием.
15
+ */
16
+ static createWithPromise(promiseChannel) {
17
+ return { promiseChannel };
18
+ }
19
+ /**
20
+ * Создать результат со значением.
21
+ * @param value - Значение. **Должно быть передаваемым**.
22
+ * @param id - Уникальный идентификатор.
23
+ * @returns Результат со значением.
24
+ */
25
+ static createWithValue(value, id) {
26
+ return { value: transfer_js_1.default.toTransferable(value), id };
27
+ }
28
+ /**
29
+ * Создать результат с ошибкой.
30
+ * @param error - Ошибка.
31
+ * @param id - Уникальный идентификатор.
32
+ * @returns Результат с ошибкой.
33
+ */
34
+ static createWithError(error, id) {
35
+ let resultError;
36
+ if (error === undefined) {
37
+ resultError = "Unknown error";
38
+ }
39
+ else if (typeof error === 'string') {
40
+ resultError = error;
41
+ }
42
+ else {
43
+ resultError = error.stack ?? error.message;
44
+ }
45
+ return { error: resultError, id };
46
+ }
47
+ }
48
+ exports.default = IpcResult;
@@ -0,0 +1,8 @@
1
+ import type { IpcMainEvent } from 'electron';
2
+ import type { IResult } from '../../types.js';
3
+ export default class MainEvent {
4
+ private event;
5
+ constructor(event: IpcMainEvent);
6
+ send(channel: string, result: IResult): void;
7
+ return(value: any): void;
8
+ }
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ class MainEvent {
4
+ event;
5
+ constructor(event) {
6
+ this.event = event;
7
+ }
8
+ send(channel, result) {
9
+ this.event.sender.send(channel, result);
10
+ }
11
+ return(value) {
12
+ this.event.returnValue = value;
13
+ }
14
+ }
15
+ exports.default = MainEvent;
@@ -0,0 +1,33 @@
1
+ import type { IHasSnapshot, ISnapshotValue } from '../../types.js';
2
+ /**
3
+ * Хелпер для передачи значений через IPC.
4
+ */
5
+ export default class Transfer {
6
+ /**
7
+ * Получить значение из снимка.
8
+ * @param value - Значение-снимок.
9
+ * @param Class - Класс, экземпляр которого будет создан из снимка.
10
+ * @returns Значение из снимка.
11
+ */
12
+ static getFromSnapshot<TSnapshot, TClass extends {
13
+ new (): IHasSnapshot<TSnapshot>;
14
+ }>(value: ISnapshotValue<TSnapshot>, Class: TClass): InstanceType<TClass>;
15
+ /**
16
+ * Преобразовать значение в передаваемое по IPC.
17
+ *
18
+ * Если возможно, создаст снимок.
19
+ * @param value - Преобразуемое значение.
20
+ * @returns Значение, передаваемое по IPC.
21
+ */
22
+ static toTransferable<T>(value: T): ISnapshotValue | T;
23
+ /**
24
+ * Является ли переданное по IPC значение снимком.
25
+ * @param value - Значение из IPC.
26
+ */
27
+ static isSnapshotValue(value: unknown): value is ISnapshotValue;
28
+ /**
29
+ * Может ли значение вернуть снимок.
30
+ * @param value - Значение.
31
+ */
32
+ static isHasSnapshot(value: unknown): value is IHasSnapshot;
33
+ }
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ /**
4
+ * Хелпер для передачи значений через IPC.
5
+ */
6
+ class Transfer {
7
+ /**
8
+ * Получить значение из снимка.
9
+ * @param value - Значение-снимок.
10
+ * @param Class - Класс, экземпляр которого будет создан из снимка.
11
+ * @returns Значение из снимка.
12
+ */
13
+ static getFromSnapshot(value, Class) {
14
+ const instance = new Class();
15
+ instance.updateFromSnapshot(value.__snapshot__);
16
+ return instance;
17
+ }
18
+ /**
19
+ * Преобразовать значение в передаваемое по IPC.
20
+ *
21
+ * Если возможно, создаст снимок.
22
+ * @param value - Преобразуемое значение.
23
+ * @returns Значение, передаваемое по IPC.
24
+ */
25
+ static toTransferable(value) {
26
+ if (this.isHasSnapshot(value)) {
27
+ return {
28
+ __type__: 'snapshot',
29
+ __snapshot__: value.takeSnapshot()
30
+ };
31
+ }
32
+ return value;
33
+ }
34
+ /**
35
+ * Является ли переданное по IPC значение снимком.
36
+ * @param value - Значение из IPC.
37
+ */
38
+ static isSnapshotValue(value) {
39
+ return (!!value
40
+ && typeof value === 'object'
41
+ && '__type__' in value
42
+ && '__snapshot__' in value
43
+ && value.__type__ === 'snapshot'
44
+ && !!value.__snapshot__);
45
+ }
46
+ /**
47
+ * Может ли значение вернуть снимок.
48
+ * @param value - Значение.
49
+ */
50
+ static isHasSnapshot(value) {
51
+ return (!!value
52
+ && typeof value === 'object'
53
+ && 'takeSnapshot' in value
54
+ && 'fromSnapshot' in value);
55
+ }
56
+ }
57
+ exports.default = Transfer;
@@ -0,0 +1,12 @@
1
+ import type { WebContents } from 'electron';
2
+ export default class WebContentsContainer {
3
+ private container;
4
+ addOn(event: string, sender: WebContents): void;
5
+ addOnce(event: string, sender: WebContents): void;
6
+ getOn(event: string): WebContents[];
7
+ getOnce(event: string): WebContents[];
8
+ getAll(event: string): WebContents[];
9
+ clearOnce(event: string): void;
10
+ private addEvent;
11
+ private getEvent;
12
+ }
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ class WebContentsContainer {
4
+ container = {};
5
+ addOn(event, sender) {
6
+ this.addEvent(event);
7
+ this.container[event].on.push(sender);
8
+ }
9
+ addOnce(event, sender) {
10
+ this.addEvent(event);
11
+ this.container[event].once.push(sender);
12
+ }
13
+ getOn(event) {
14
+ return this.getEvent(event).on.filter(sender => !sender.isDestroyed());
15
+ }
16
+ getOnce(event) {
17
+ return this.getEvent(event).once.filter(sender => !sender.isDestroyed());
18
+ }
19
+ getAll(event) {
20
+ const senders = this.getEvent(event);
21
+ return [...senders.on, ...senders.once];
22
+ }
23
+ clearOnce(event) {
24
+ this.getEvent(event).once = [];
25
+ }
26
+ addEvent(name) {
27
+ this.container[name] ??= { on: [], once: [] };
28
+ }
29
+ getEvent(name) {
30
+ this.addEvent(name);
31
+ return this.container[name];
32
+ }
33
+ }
34
+ exports.default = WebContentsContainer;
@@ -0,0 +1,56 @@
1
+ import type { WebContents } from 'electron';
2
+ /**
3
+ * Обёртка над стандартным `WebContents`, позволяющая использовать события.
4
+ */
5
+ export default class WebContentsEventContainer {
6
+ /**
7
+ * Контейнер событий.
8
+ */
9
+ private container;
10
+ /**
11
+ * Добавить многоразового отправителя для события.
12
+ * @param event - Имя события.
13
+ * @param sender - Отправитель.
14
+ */
15
+ addOn(event: string, sender: WebContents): void;
16
+ /**
17
+ * Добавить одноразового отправителя для события.
18
+ * @param event - Имя события.
19
+ * @param sender - Отправитель.
20
+ */
21
+ addOnce(event: string, sender: WebContents): void;
22
+ /**
23
+ * Получить многоразовых отправителей для события.
24
+ * @param event - Имя события.
25
+ * @returns многоразовые отправители для события.
26
+ */
27
+ getOn(event: string): WebContents[];
28
+ /**
29
+ * Получить одноразовых отправителей для события.
30
+ * @param event - Имя события.
31
+ * @returns Одноразовые отправители для события.
32
+ */
33
+ getOnce(event: string): WebContents[];
34
+ /**
35
+ * Получить всех отправителей для события.
36
+ * @param event - Имя события.
37
+ * @returns Отправители для события.
38
+ */
39
+ getAll(event: string): WebContents[];
40
+ /**
41
+ * Удалить одноразовых отправителей для события.
42
+ * @param event - Имя события.
43
+ */
44
+ clearOnce(event: string): void;
45
+ /**
46
+ * Добавить контейнер события.
47
+ * @param name - Имя события.
48
+ */
49
+ private addEvent;
50
+ /**
51
+ * Получить контейнер события.
52
+ * @param name - Имя события.
53
+ * @returns Контейнер события.
54
+ */
55
+ private getEvent;
56
+ }
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ /**
4
+ * Обёртка над стандартным `WebContents`, позволяющая использовать события.
5
+ */
6
+ class WebContentsEventContainer {
7
+ constructor() {
8
+ /**
9
+ * Контейнер событий.
10
+ */
11
+ this.container = {};
12
+ }
13
+ /**
14
+ * Добавить многоразового отправителя для события.
15
+ * @param event - Имя события.
16
+ * @param sender - Отправитель.
17
+ */
18
+ addOn(event, sender) {
19
+ this.addEvent(event);
20
+ this.container[event].on.push(sender);
21
+ }
22
+ /**
23
+ * Добавить одноразового отправителя для события.
24
+ * @param event - Имя события.
25
+ * @param sender - Отправитель.
26
+ */
27
+ addOnce(event, sender) {
28
+ this.addEvent(event);
29
+ this.container[event].once.push(sender);
30
+ }
31
+ /**
32
+ * Получить многоразовых отправителей для события.
33
+ * @param event - Имя события.
34
+ * @returns многоразовые отправители для события.
35
+ */
36
+ getOn(event) {
37
+ return this.getEvent(event).on.filter(sender => !sender.isDestroyed());
38
+ }
39
+ /**
40
+ * Получить одноразовых отправителей для события.
41
+ * @param event - Имя события.
42
+ * @returns Одноразовые отправители для события.
43
+ */
44
+ getOnce(event) {
45
+ return this.getEvent(event).once.filter(sender => !sender.isDestroyed());
46
+ }
47
+ /**
48
+ * Получить всех отправителей для события.
49
+ * @param event - Имя события.
50
+ * @returns Отправители для события.
51
+ */
52
+ getAll(event) {
53
+ const senders = this.getEvent(event);
54
+ return [...senders.on, ...senders.once];
55
+ }
56
+ /**
57
+ * Удалить одноразовых отправителей для события.
58
+ * @param event - Имя события.
59
+ */
60
+ clearOnce(event) {
61
+ this.getEvent(event).once = [];
62
+ }
63
+ /**
64
+ * Добавить контейнер события.
65
+ * @param name - Имя события.
66
+ */
67
+ addEvent(name) {
68
+ var _a;
69
+ (_a = this.container)[name] ?? (_a[name] = { on: [], once: [] });
70
+ }
71
+ /**
72
+ * Получить контейнер события.
73
+ * @param name - Имя события.
74
+ * @returns Контейнер события.
75
+ */
76
+ getEvent(name) {
77
+ this.addEvent(name);
78
+ return this.container[name];
79
+ }
80
+ }
81
+ exports.default = WebContentsEventContainer;
@@ -0,0 +1,36 @@
1
+ import type { EventListener, EventUnsubscribe, HasSnapshotClass } from '../../types.js';
2
+ /**
3
+ * Вызвать событие из main процесса.
4
+ * @param name - Имя события.
5
+ * @param value - Передаваемое значение.
6
+ */
7
+ export declare function emitEvent<T = unknown>(name: string, value?: T): void;
8
+ /**
9
+ * Добавить обработчик renderer события.
10
+ * @param name - Имя события.
11
+ * @param listener - Обработчик.
12
+ * @param receives - Принимаемые классы, недоступные для транспортировки по умолчанию. _Порядок важен._
13
+ * @returns Функция отписки от события.
14
+ */
15
+ export declare function on<TValue = any>(name: string, listener: EventListener<TValue>, receives: HasSnapshotClass<TValue>): EventUnsubscribe;
16
+ /**
17
+ * Добавить одноразовый обработчик renderer события.
18
+ * @param name - Имя события.
19
+ * @param listener - Обработчик.
20
+ * @param receives - Класс передаваемого значения, если оно не может быть передано стандартным способом.
21
+ * @returns Функция отписки от события.
22
+ */
23
+ export declare function once<TValue = any>(name: string, listener: EventListener<TValue>, receives: HasSnapshotClass<TValue>): EventUnsubscribe;
24
+ /**
25
+ * Опубликовать (сделать доступной) функцию из main процесса.
26
+ * @param name - Имя, по которому будет доступна функция в renderer процессе.
27
+ * @param func - Публикуемая функция.
28
+ * @param receives - Принимаемые классы, недоступные для транспортировки по умолчанию. _Порядок важен._
29
+ */
30
+ export declare function publishFunction<TFunc extends (...args: any[]) => any>(name: string, func: TFunc, receives?: HasSnapshotClass[]): void;
31
+ /**
32
+ * Опубликовать (сделать доступной) переменную из main процесса.
33
+ * @param name - Имя переменной, по которому она будет доступна в renderer процессе.
34
+ * @param descriptor - Дескриптор. Используется только get/set/value.
35
+ */
36
+ export declare function publishVariable<T>(name: string, descriptor: TypedPropertyDescriptor<T>): void;
@@ -0,0 +1,186 @@
1
+ "use strict";
2
+ /*
3
+ Методы публикации в main процессе.
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.emitEvent = emitEvent;
7
+ exports.on = on;
8
+ exports.once = once;
9
+ exports.publishFunction = publishFunction;
10
+ exports.publishVariable = publishVariable;
11
+ const electron_1 = require("electron");
12
+ const errors_js_1 = require("../../errors.js");
13
+ const index_js_1 = require("../helpers/index.js");
14
+ /**
15
+ * Информация о сущностях.
16
+ */
17
+ const entitiesInfo = {
18
+ variables: new Set(),
19
+ functions: new Set()
20
+ };
21
+ /**
22
+ * Контейнер отправителей для событий.
23
+ */
24
+ const eventsContainer = new index_js_1.WebContentsEventsContainer();
25
+ /**
26
+ * Выбросить ошибку если есть причина.
27
+ */
28
+ const canThrowError = (index_js_1.Env.hasWindow || !electron_1.ipcMain)
29
+ ? index_js_1.Errors.getThrower(errors_js_1.PublishMethodsUnavailableError)
30
+ : () => { };
31
+ if (electron_1.ipcMain) {
32
+ electron_1.ipcMain.on(index_js_1.IpcChannel.publicInfo.get(), event => new index_js_1.IpcEventInMain(event).return(entitiesInfo));
33
+ electron_1.ipcMain.on(index_js_1.IpcChannel.event.on(), (event, { value }) => eventsContainer.addOn(value, event.sender));
34
+ electron_1.ipcMain.on(index_js_1.IpcChannel.event.once(), (event, { value }) => eventsContainer.addOn(value, event.sender));
35
+ }
36
+ /**
37
+ * Вызвать событие из main процесса.
38
+ * @param name - Имя события.
39
+ * @param value - Передаваемое значение.
40
+ */
41
+ function emitEvent(name, value) {
42
+ canThrowError();
43
+ const emitChannel = index_js_1.IpcChannel.event.emit(name);
44
+ try {
45
+ if (value instanceof Promise) {
46
+ value
47
+ .then(val => {
48
+ for (const sender of eventsContainer.getAll(name)) {
49
+ sender.send(emitChannel, index_js_1.IpcResult.createWithValue(val));
50
+ }
51
+ eventsContainer.clearOnce(name);
52
+ })
53
+ .catch(reason => {
54
+ eventsContainer.getAll(name).forEach(sender => sender.send(emitChannel, index_js_1.IpcResult.createWithError(reason)));
55
+ eventsContainer.clearOnce(name);
56
+ });
57
+ return;
58
+ }
59
+ for (const sender of eventsContainer.getAll(name)) {
60
+ sender.send(emitChannel, index_js_1.IpcResult.createWithValue(value));
61
+ }
62
+ eventsContainer.clearOnce(name);
63
+ }
64
+ catch (error) {
65
+ eventsContainer.getAll(name).forEach(sender => sender.send(emitChannel, index_js_1.IpcResult.createWithError(error)));
66
+ eventsContainer.clearOnce(name);
67
+ }
68
+ }
69
+ /**
70
+ * Добавить обработчик renderer события.
71
+ * @param name - Имя события.
72
+ * @param listener - Обработчик.
73
+ * @param receives - Принимаемые классы, недоступные для транспортировки по умолчанию. _Порядок важен._
74
+ * @returns Функция отписки от события.
75
+ */
76
+ function on(name, listener, receives) {
77
+ canThrowError();
78
+ const emitChannel = index_js_1.IpcChannel.event.emit(name);
79
+ const handler = (_, { value }) => {
80
+ if (index_js_1.Transfer.isSnapshotValue(value)) {
81
+ listener(index_js_1.Transfer.getFromSnapshot(value, receives));
82
+ }
83
+ else {
84
+ listener(value);
85
+ }
86
+ };
87
+ electron_1.ipcMain.on(emitChannel, handler);
88
+ return () => electron_1.ipcMain.removeListener(emitChannel, handler);
89
+ }
90
+ /**
91
+ * Добавить одноразовый обработчик renderer события.
92
+ * @param name - Имя события.
93
+ * @param listener - Обработчик.
94
+ * @param receives - Класс передаваемого значения, если оно не может быть передано стандартным способом.
95
+ * @returns Функция отписки от события.
96
+ */
97
+ function once(name, listener, receives) {
98
+ canThrowError();
99
+ const emitChannel = index_js_1.IpcChannel.event.emit(name);
100
+ const handler = (_, { value }) => {
101
+ if (index_js_1.Transfer.isSnapshotValue(value)) {
102
+ listener(index_js_1.Transfer.getFromSnapshot(value, receives));
103
+ }
104
+ else {
105
+ listener(value);
106
+ }
107
+ };
108
+ electron_1.ipcMain.once(emitChannel, handler);
109
+ return () => electron_1.ipcMain.removeListener(emitChannel, handler);
110
+ }
111
+ /**
112
+ * Опубликовать (сделать доступной) функцию из main процесса.
113
+ * @param name - Имя, по которому будет доступна функция в renderer процессе.
114
+ * @param func - Публикуемая функция.
115
+ * @param receives - Принимаемые классы, недоступные для транспортировки по умолчанию. _Порядок важен._
116
+ */
117
+ function publishFunction(name, func, receives = []) {
118
+ canThrowError();
119
+ const channel = index_js_1.IpcChannel.func.call(name);
120
+ entitiesInfo.functions.add(name);
121
+ electron_1.ipcMain.removeAllListeners(channel);
122
+ electron_1.ipcMain.on(channel, (e, { args, id }) => {
123
+ const event = new index_js_1.IpcEventInMain(e);
124
+ const receivesCopy = [...receives];
125
+ try {
126
+ const preparedArgs = args.map(arg => (index_js_1.Transfer.isSnapshotValue(arg) && receivesCopy[0]
127
+ ? index_js_1.Transfer.getFromSnapshot(arg, receivesCopy.shift())
128
+ : arg));
129
+ const result = func(...preparedArgs);
130
+ if (result instanceof Promise) {
131
+ const promiseChannel = index_js_1.IpcChannel.promise.get(channel);
132
+ result
133
+ .then(value => event.send(promiseChannel, index_js_1.IpcResult.createWithValue(value, id)))
134
+ .catch(reason => event.send(promiseChannel, index_js_1.IpcResult.createWithError(reason, id)));
135
+ event.return(index_js_1.IpcResult.createWithPromise(promiseChannel));
136
+ }
137
+ else {
138
+ event.return(index_js_1.IpcResult.createWithValue(result));
139
+ }
140
+ }
141
+ catch (error) {
142
+ event.return(index_js_1.IpcResult.createWithError(error));
143
+ }
144
+ });
145
+ }
146
+ /**
147
+ * Опубликовать (сделать доступной) переменную из main процесса.
148
+ * @param name - Имя переменной, по которому она будет доступна в renderer процессе.
149
+ * @param descriptor - Дескриптор. Используется только get/set/value.
150
+ */
151
+ function publishVariable(name, descriptor) {
152
+ canThrowError();
153
+ const getChannel = index_js_1.IpcChannel.prop.get(name);
154
+ const setChannel = index_js_1.IpcChannel.prop.set(name);
155
+ const { set: setter, value } = descriptor;
156
+ let { get: getter } = descriptor;
157
+ entitiesInfo.variables.add(name);
158
+ if (value) {
159
+ getter = () => value;
160
+ }
161
+ if (getter) {
162
+ electron_1.ipcMain.removeAllListeners(getChannel);
163
+ electron_1.ipcMain.on(getChannel, e => {
164
+ const event = new index_js_1.IpcEventInMain(e);
165
+ try {
166
+ event.return(index_js_1.IpcResult.createWithValue(getter()));
167
+ }
168
+ catch (error) {
169
+ event.return(index_js_1.IpcResult.createWithError(error));
170
+ }
171
+ });
172
+ }
173
+ if (setter) {
174
+ electron_1.ipcMain.removeAllListeners(setChannel);
175
+ electron_1.ipcMain.on(setChannel, (e, { args }) => {
176
+ const event = new index_js_1.IpcEventInMain(e);
177
+ try {
178
+ setter(args.at(0));
179
+ event.return(index_js_1.IpcResult.createWithValue(null));
180
+ }
181
+ catch (error) {
182
+ event.return(index_js_1.IpcResult.createWithError(error));
183
+ }
184
+ });
185
+ }
186
+ }
@@ -0,0 +1,27 @@
1
+ import type { EventListener, EventUnsubscribe, IBridge, IResult } from '../../types.js';
2
+ import BaseBridge from '../base-bridge.js';
3
+ /**
4
+ * Мост preload-main.
5
+ */
6
+ export declare class PreloadBridge extends BaseBridge {
7
+ protected readonly entitiesInfo: any;
8
+ /**
9
+ * Создать мост preload-main.
10
+ */
11
+ constructor();
12
+ protected callFunction(name: string, secret: string, args: any[]): IResult;
13
+ protected getVariable(name: string): IResult;
14
+ protected setVariable(name: string, value: any): IResult;
15
+ protected waitPromise(channel: string, id?: string): Promise<any>;
16
+ protected handleEvent(name: string, type: 'on' | 'once', listener: EventListener<IResult>): EventUnsubscribe;
17
+ protected emitEvent(name: string, value: any): void;
18
+ }
19
+ /**
20
+ * Получить мост preload-main.
21
+ */
22
+ export declare function getBridge(): IBridge;
23
+ /**
24
+ * Мост preload-main.
25
+ */
26
+ declare const _default: IBridge;
27
+ export default _default;