@apollo-office/rpc 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,749 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ let _univerjs_core = require("@apollo-office/core");
3
+ let rxjs_operators = require("rxjs/operators");
4
+ let rxjs = require("rxjs");
5
+
6
+ //#region src/config/config.ts
7
+ /**
8
+ * Copyright 2023-present DreamNum Co., Ltd.
9
+ *
10
+ * Licensed under the Apache License, Version 2.0 (the "License");
11
+ * you may not use this file except in compliance with the License.
12
+ * You may obtain a copy of the License at
13
+ *
14
+ * http://www.apache.org/licenses/LICENSE-2.0
15
+ *
16
+ * Unless required by applicable law or agreed to in writing, software
17
+ * distributed under the License is distributed on an "AS IS" BASIS,
18
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ * See the License for the specific language governing permissions and
20
+ * limitations under the License.
21
+ */
22
+ const PLUGIN_CONFIG_KEY_MAIN_THREAD = "rpc.main-thread.config";
23
+ const configSymbolMainThread = Symbol(PLUGIN_CONFIG_KEY_MAIN_THREAD);
24
+ const defaultPluginMainThreadConfig = {};
25
+ const PLUGIN_CONFIG_KEY_WORKER_THREAD = "rpc.worker-thread.config";
26
+ const configSymbolWorkerThread = Symbol(PLUGIN_CONFIG_KEY_WORKER_THREAD);
27
+ const defaultPluginWorkerThreadConfig = {};
28
+
29
+ //#endregion
30
+ //#region \0@oxc-project+runtime@0.133.0/helpers/esm/decorateParam.js
31
+ function __decorateParam(paramIndex, decorator) {
32
+ return function(target, key) {
33
+ decorator(target, key, paramIndex);
34
+ };
35
+ }
36
+
37
+ //#endregion
38
+ //#region \0@oxc-project+runtime@0.133.0/helpers/esm/decorate.js
39
+ function __decorate(decorators, target, key, desc) {
40
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
41
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
42
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
43
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
44
+ }
45
+
46
+ //#endregion
47
+ //#region src/services/remote-instance/remote-instance.service.ts
48
+ const RemoteSyncServiceName = "rpc.remote-sync.service";
49
+ /**
50
+ * This service is provided by the primary Univer.
51
+ *
52
+ * Replica Univer could call this service to update mutations back to the primary Univer.
53
+ */
54
+ const IRemoteSyncService = (0, _univerjs_core.createIdentifier)(RemoteSyncServiceName);
55
+ let RemoteSyncPrimaryService = class RemoteSyncPrimaryService {
56
+ constructor(_commandService) {
57
+ this._commandService = _commandService;
58
+ }
59
+ async syncMutation(params, options) {
60
+ const { fromCollab, ...restOptions } = options || {};
61
+ return this._commandService.syncExecuteCommand(params.mutationInfo.id, params.mutationInfo.params, {
62
+ ...restOptions,
63
+ onlyLocal: true,
64
+ fromSync: true
65
+ });
66
+ }
67
+ };
68
+ RemoteSyncPrimaryService = __decorate([__decorateParam(0, _univerjs_core.ICommandService)], RemoteSyncPrimaryService);
69
+ const RemoteInstanceServiceName = "univer.remote-instance-service";
70
+ /**
71
+ * This service is provided by the replica Univer.
72
+ *
73
+ * Primary univer could call this service to init and dispose univer business instances
74
+ * and sync mutations to replica univer.
75
+ */
76
+ const IRemoteInstanceService = (0, _univerjs_core.createIdentifier)(RemoteInstanceServiceName);
77
+ let WebWorkerRemoteInstanceService = class WebWorkerRemoteInstanceService {
78
+ constructor(_univerInstanceService, _commandService, _logService) {
79
+ this._univerInstanceService = _univerInstanceService;
80
+ this._commandService = _commandService;
81
+ this._logService = _logService;
82
+ }
83
+ whenReady() {
84
+ return Promise.resolve(true);
85
+ }
86
+ async syncMutation(params, options) {
87
+ return this._applyMutation(params.mutationInfo, options);
88
+ }
89
+ async createInstance(params) {
90
+ this._logService.debug(`[WebWorkerRemoteInstanceService]: Creating instance with id ${params.unitID}`);
91
+ const { type, snapshot } = params;
92
+ try {
93
+ switch (type) {
94
+ case _univerjs_core.UniverInstanceType.UNIVER_SHEET:
95
+ this._univerInstanceService.createUnit(_univerjs_core.UniverInstanceType.UNIVER_SHEET, snapshot);
96
+ return true;
97
+ default: throw new Error(`[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${type}.`);
98
+ }
99
+ } catch (err) {
100
+ if (err instanceof Error) throw err;
101
+ else throw new TypeError(`${err}`);
102
+ }
103
+ }
104
+ async disposeInstance(params) {
105
+ this._logService.debug(`[WebWorkerRemoteInstanceService]: Disposing instance with id ${params.unitID}`);
106
+ return this._univerInstanceService.disposeUnit(params.unitID);
107
+ }
108
+ _applyMutation(mutationInfo, options) {
109
+ const { id, params: mutationParams } = mutationInfo;
110
+ const { fromCollab, ...restOptions } = options || {};
111
+ return this._commandService.syncExecuteCommand(id, mutationParams, {
112
+ ...restOptions,
113
+ onlyLocal: true,
114
+ fromSync: true
115
+ });
116
+ }
117
+ };
118
+ WebWorkerRemoteInstanceService = __decorate([
119
+ __decorateParam(0, _univerjs_core.IUniverInstanceService),
120
+ __decorateParam(1, _univerjs_core.ICommandService),
121
+ __decorateParam(2, _univerjs_core.ILogService)
122
+ ], WebWorkerRemoteInstanceService);
123
+
124
+ //#endregion
125
+ //#region \0@oxc-project+runtime@0.133.0/helpers/esm/typeof.js
126
+ function _typeof(o) {
127
+ "@babel/helpers - typeof";
128
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
129
+ return typeof o;
130
+ } : function(o) {
131
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
132
+ }, _typeof(o);
133
+ }
134
+
135
+ //#endregion
136
+ //#region \0@oxc-project+runtime@0.133.0/helpers/esm/toPrimitive.js
137
+ function toPrimitive(t, r) {
138
+ if ("object" != _typeof(t) || !t) return t;
139
+ var e = t[Symbol.toPrimitive];
140
+ if (void 0 !== e) {
141
+ var i = e.call(t, r || "default");
142
+ if ("object" != _typeof(i)) return i;
143
+ throw new TypeError("@@toPrimitive must return a primitive value.");
144
+ }
145
+ return ("string" === r ? String : Number)(t);
146
+ }
147
+
148
+ //#endregion
149
+ //#region \0@oxc-project+runtime@0.133.0/helpers/esm/toPropertyKey.js
150
+ function toPropertyKey(t) {
151
+ var i = toPrimitive(t, "string");
152
+ return "symbol" == _typeof(i) ? i : i + "";
153
+ }
154
+
155
+ //#endregion
156
+ //#region \0@oxc-project+runtime@0.133.0/helpers/esm/defineProperty.js
157
+ function _defineProperty(e, r, t) {
158
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
159
+ value: t,
160
+ enumerable: !0,
161
+ configurable: !0,
162
+ writable: !0
163
+ }) : e[r] = t, e;
164
+ }
165
+
166
+ //#endregion
167
+ //#region src/services/rpc/rpc.service.ts
168
+ /**
169
+ * Wrapper a service or a controller into a channel so it could be invoked by
170
+ * a remote client. When the protocol is called, it would forward to the
171
+ * underlying service or controller.
172
+ *
173
+ * @param module the wrapper service or controller
174
+ * @returns the channel instance
175
+ */
176
+ function fromModule(module) {
177
+ const handler = module;
178
+ return new class {
179
+ call(method, args) {
180
+ const target = handler[method];
181
+ if (typeof target === "function") {
182
+ let res = args ? target.apply(handler, args) : target.call(handler);
183
+ if (!(res instanceof Promise)) res = Promise.resolve(res);
184
+ return res;
185
+ }
186
+ throw new Error(`[RPC]: method not found for ${method}!`);
187
+ }
188
+ subscribe(eventMethod, args) {
189
+ const target = handler[eventMethod];
190
+ if (typeof target === "function") {
191
+ const res = args ? target.apply(handler, args) : target.call(handler);
192
+ if (!(0, rxjs.isObservable)(res)) return (0, rxjs.of)(res);
193
+ return res;
194
+ }
195
+ throw new Error(`[RPC]: observable method not found for ${eventMethod}!`);
196
+ }
197
+ }();
198
+ }
199
+ /**
200
+ * Wrap a channel into a service or a controller so it could be invoked by
201
+ * the upper layer modules. When the service or controller is called, it would
202
+ * request the remote server by calling the channel.
203
+ *
204
+ * @param channel
205
+ * @returns A proxy object that forwards calls/subscriptions to the remote channel.
206
+ */
207
+ function toModule(channel) {
208
+ return new Proxy({}, { get(_, propKey) {
209
+ if (propKey === "dispose") return;
210
+ return function(...args) {
211
+ if (propertyIsEventSource(propKey)) return channel.subscribe(propKey, args);
212
+ return channel.call(propKey, args);
213
+ };
214
+ } });
215
+ }
216
+ function propertyIsEventSource(name) {
217
+ return name.endsWith("$");
218
+ }
219
+ /**
220
+ * This method provides implementation for `IChannel` and is responsible for
221
+ * transforming a local calling to a RPC calling.
222
+ */
223
+ var ChannelClient = class extends _univerjs_core.RxDisposable {
224
+ constructor(_protocol) {
225
+ super();
226
+ this._protocol = _protocol;
227
+ _defineProperty(this, "_initialized", new rxjs.BehaviorSubject(false));
228
+ _defineProperty(this, "_lastRequestCounter", 0);
229
+ _defineProperty(this, "_pendingRequests", /* @__PURE__ */ new Map());
230
+ this._protocol.send({ type: 50 });
231
+ this._protocol.onMessage.pipe((0, rxjs_operators.takeUntil)(this.dispose$)).subscribe((message) => this._onMessage(message));
232
+ }
233
+ dispose() {
234
+ this._pendingRequests.clear();
235
+ }
236
+ getChannel(channelName) {
237
+ return {
238
+ call: (method, args) => {
239
+ if (this._disposed) return Promise.reject(/* @__PURE__ */ new Error("[ChannelClient]: client is disposed!"));
240
+ return this._remoteCall(channelName, method, args);
241
+ },
242
+ subscribe: (eventMethod, args) => {
243
+ if (this._disposed) throw new Error("[ChannelClient]: client is disposed!");
244
+ return this._remoteSubscribe(channelName, eventMethod, args);
245
+ }
246
+ };
247
+ }
248
+ _whenReady() {
249
+ return (0, rxjs.firstValueFrom)(this._initialized.pipe((0, rxjs_operators.filter)((v) => v), (0, rxjs_operators.take)(1)));
250
+ }
251
+ _remoteCall(channelName, method, args) {
252
+ if (this._initialized.getValue()) return this._doRemoteCall(channelName, method, args);
253
+ return this._whenReady().then(() => this._doRemoteCall(channelName, method, args));
254
+ }
255
+ _doRemoteCall(channelName, method, args) {
256
+ const sequence = ++this._lastRequestCounter;
257
+ const request = {
258
+ seq: sequence,
259
+ type: 100,
260
+ channelName,
261
+ method,
262
+ args
263
+ };
264
+ const pendingRequests = this._pendingRequests;
265
+ return new Promise((resolve, reject) => {
266
+ this._pendingRequests.set(sequence, { handle(response) {
267
+ switch (response.type) {
268
+ case 201:
269
+ pendingRequests.delete(sequence);
270
+ resolve(response.data);
271
+ break;
272
+ case 202:
273
+ pendingRequests.delete(sequence);
274
+ reject(response.data);
275
+ break;
276
+ default: throw new Error("[ChannelClient]: unknown response type!");
277
+ }
278
+ } });
279
+ this._sendRequest(request);
280
+ });
281
+ }
282
+ _remoteSubscribe(channelName, method, args) {
283
+ return new rxjs.Observable((subscriber) => {
284
+ let sequence = -1;
285
+ const doSubscribe = () => {
286
+ sequence = ++this._lastRequestCounter;
287
+ const request = {
288
+ seq: sequence,
289
+ type: 101,
290
+ channelName,
291
+ method,
292
+ args
293
+ };
294
+ this._pendingRequests.set(sequence, { handle(response) {
295
+ switch (response.type) {
296
+ case 300:
297
+ subscriber.next(response.data);
298
+ break;
299
+ case 301:
300
+ subscriber.error(response.data);
301
+ break;
302
+ case 302:
303
+ subscriber.complete();
304
+ break;
305
+ default: throw new Error("[ChannelClient]: unknown response type!");
306
+ }
307
+ } });
308
+ this._sendRequest(request);
309
+ };
310
+ if (this._initialized.getValue()) doSubscribe();
311
+ else this._whenReady().then(doSubscribe);
312
+ return () => {
313
+ if (sequence === -1) return;
314
+ const cancelSubscriptionRequest = {
315
+ type: 102,
316
+ seq: sequence,
317
+ channelName,
318
+ method
319
+ };
320
+ this._sendRequest(cancelSubscriptionRequest);
321
+ };
322
+ });
323
+ }
324
+ _sendRequest(request) {
325
+ this._protocol.send(request);
326
+ }
327
+ _onMessage(response) {
328
+ const { type: responseType, seq } = response;
329
+ switch (responseType) {
330
+ case 0:
331
+ this._initialized.next(true);
332
+ break;
333
+ case 201:
334
+ case 202:
335
+ case 300:
336
+ case 302:
337
+ case 301: {
338
+ var _pendingRequests$get;
339
+ const { _pendingRequests } = this;
340
+ (_pendingRequests$get = _pendingRequests.get(seq)) === null || _pendingRequests$get === void 0 || _pendingRequests$get.handle(response);
341
+ responseType !== 300 && _pendingRequests.delete(seq);
342
+ break;
343
+ }
344
+ }
345
+ }
346
+ };
347
+ var ChannelServer = class extends _univerjs_core.RxDisposable {
348
+ constructor(_protocol) {
349
+ super();
350
+ this._protocol = _protocol;
351
+ _defineProperty(this, "_channels", /* @__PURE__ */ new Map());
352
+ _defineProperty(this, "_subscriptions", /* @__PURE__ */ new Map());
353
+ this._protocol.onMessage.pipe((0, rxjs_operators.takeUntil)(this.dispose$)).subscribe((message) => this._onRequest(message));
354
+ this._sendInitialize();
355
+ }
356
+ dispose() {
357
+ super.dispose();
358
+ this._subscriptions.clear();
359
+ this._channels.clear();
360
+ }
361
+ registerChannel(channelName, channel) {
362
+ this._channels.set(channelName, channel);
363
+ }
364
+ _onRequest(request) {
365
+ switch (request.type) {
366
+ case 50:
367
+ this._sendInitialize();
368
+ break;
369
+ case 100:
370
+ this._onMethodCall(request);
371
+ break;
372
+ case 101:
373
+ this._onSubscribe(request);
374
+ break;
375
+ case 102:
376
+ this._onUnsubscribe(request);
377
+ break;
378
+ default: break;
379
+ }
380
+ }
381
+ _sendInitialize() {
382
+ this._sendResponse({
383
+ seq: -1,
384
+ type: 0
385
+ });
386
+ }
387
+ _onMethodCall(request) {
388
+ const { channelName, method, args } = request;
389
+ const channel = this._channels.get(channelName);
390
+ let promise;
391
+ try {
392
+ if (!channel) throw new Error(`[ChannelServer]: Channel ${channelName} not found!`);
393
+ promise = args ? channel.call(method, args) : channel.call(method);
394
+ } catch (err) {
395
+ promise = Promise.reject(err instanceof Error ? err : new Error(String(err)));
396
+ }
397
+ promise.then((data) => {
398
+ this._sendResponse({
399
+ seq: request.seq,
400
+ type: 201,
401
+ data
402
+ });
403
+ }).catch((err) => {
404
+ if (err instanceof Error) this._sendResponse({
405
+ seq: request.seq,
406
+ type: 202,
407
+ data: err.message
408
+ });
409
+ else this._sendResponse({
410
+ seq: request.seq,
411
+ type: 202,
412
+ data: String(err)
413
+ });
414
+ });
415
+ }
416
+ _onSubscribe(request) {
417
+ const { channelName, seq } = request;
418
+ const channel = this._channels.get(channelName);
419
+ try {
420
+ if (!channel) throw new Error(`[ChannelServer]: Channel ${channelName} not found!`);
421
+ const subscription = channel.subscribe(request.method, request.args).subscribe({
422
+ next: (data) => {
423
+ this._sendResponse({
424
+ seq,
425
+ type: 300,
426
+ data
427
+ });
428
+ },
429
+ error: (err) => {
430
+ this._sendResponse({
431
+ seq,
432
+ type: 301,
433
+ data: err.message
434
+ });
435
+ this._sendResponse({
436
+ seq,
437
+ type: 302
438
+ });
439
+ },
440
+ complete: () => {
441
+ this._sendResponse({
442
+ seq,
443
+ type: 302
444
+ });
445
+ }
446
+ });
447
+ this._subscriptions.set(request.seq, subscription);
448
+ } catch (err) {
449
+ if (err instanceof Error) this._sendResponse({
450
+ seq: request.seq,
451
+ type: 301,
452
+ data: err.message
453
+ });
454
+ else this._sendResponse({
455
+ seq: request.seq,
456
+ type: 301,
457
+ data: String(err)
458
+ });
459
+ }
460
+ }
461
+ _onUnsubscribe(request) {
462
+ const subscription = this._subscriptions.get(request.seq);
463
+ if (subscription) {
464
+ subscription.unsubscribe();
465
+ this._subscriptions.delete(request.seq);
466
+ }
467
+ }
468
+ _sendResponse(response) {
469
+ this._protocol.send(response);
470
+ }
471
+ };
472
+
473
+ //#endregion
474
+ //#region src/services/rpc/channel.service.ts
475
+ const IRPCChannelService = (0, _univerjs_core.createIdentifier)("IRPCChannelService");
476
+ /**
477
+ * This service is responsible for managing the RPC channels.
478
+ */
479
+ var ChannelService = class {
480
+ constructor(_messageProtocol) {
481
+ _defineProperty(this, "_client", void 0);
482
+ _defineProperty(this, "_server", void 0);
483
+ this._client = new ChannelClient(_messageProtocol);
484
+ this._server = new ChannelServer(_messageProtocol);
485
+ }
486
+ dispose() {
487
+ this._client.dispose();
488
+ this._server.dispose();
489
+ }
490
+ requestChannel(name) {
491
+ return this._client.getChannel(name);
492
+ }
493
+ registerChannel(name, channel) {
494
+ this._server.registerChannel(name, channel);
495
+ }
496
+ };
497
+
498
+ //#endregion
499
+ //#region src/controllers/data-sync/data-sync-primary.controller.ts
500
+ let DataSyncPrimaryController = class DataSyncPrimaryController extends _univerjs_core.RxDisposable {
501
+ constructor(_injector, _commandService, _univerInstanceService, _rpcChannelService, _remoteSyncService) {
502
+ super();
503
+ this._injector = _injector;
504
+ this._commandService = _commandService;
505
+ this._univerInstanceService = _univerInstanceService;
506
+ this._rpcChannelService = _rpcChannelService;
507
+ this._remoteSyncService = _remoteSyncService;
508
+ _defineProperty(this, "_remoteInstanceService", void 0);
509
+ _defineProperty(this, "_syncingUnits", /* @__PURE__ */ new Set());
510
+ _defineProperty(this, "_syncingMutations", /* @__PURE__ */ new Set());
511
+ this._initRPCChannels();
512
+ this._init();
513
+ }
514
+ registerSyncingMutations(mutation) {
515
+ this._syncingMutations.add(mutation.id);
516
+ }
517
+ /**
518
+ * Only spreadsheets would be synced to the web worker in normal situations. If you would like to
519
+ * sync other types of documents, you should manually call this method with that document's id.
520
+ */
521
+ syncUnit(unitId) {
522
+ this._syncingUnits.add(unitId);
523
+ return (0, _univerjs_core.toDisposable)(() => this._syncingUnits.delete(unitId));
524
+ }
525
+ _initRPCChannels() {
526
+ this._rpcChannelService.registerChannel(RemoteSyncServiceName, fromModule(this._remoteSyncService));
527
+ this._injector.add([IRemoteInstanceService, { useFactory: () => toModule(this._rpcChannelService.requestChannel(RemoteInstanceServiceName)) }]);
528
+ this._remoteInstanceService = this._injector.get(IRemoteInstanceService);
529
+ }
530
+ _init() {
531
+ this._univerInstanceService.getTypeOfUnitAdded$(_univerjs_core.UniverInstanceType.UNIVER_SHEET).pipe((0, rxjs_operators.takeUntil)(this.dispose$)).subscribe((event) => {
532
+ const { unit: sheet } = event;
533
+ this._syncingUnits.add(sheet.getUnitId());
534
+ this._remoteInstanceService.createInstance({
535
+ unitID: sheet.getUnitId(),
536
+ type: _univerjs_core.UniverInstanceType.UNIVER_SHEET,
537
+ snapshot: sheet.getSnapshot()
538
+ });
539
+ });
540
+ this._univerInstanceService.getTypeOfUnitDisposed$(_univerjs_core.UniverInstanceType.UNIVER_SHEET).pipe((0, rxjs_operators.takeUntil)(this.dispose$)).subscribe((workbook) => {
541
+ this._syncingUnits.delete(workbook.getUnitId());
542
+ this._remoteInstanceService.disposeInstance({ unitID: workbook.getUnitId() });
543
+ });
544
+ this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo, options) => {
545
+ const { type, params, id } = commandInfo;
546
+ const unitId = (params === null || params === void 0 ? void 0 : params.unitId) || "";
547
+ if (type === _univerjs_core.CommandType.MUTATION && (!unitId || this._syncingUnits.has(unitId)) && !(options === null || options === void 0 ? void 0 : options.fromSync) && this._syncingMutations.has(id)) this._remoteInstanceService.syncMutation({ mutationInfo: commandInfo }, options);
548
+ }));
549
+ }
550
+ };
551
+ DataSyncPrimaryController = __decorate([
552
+ __decorateParam(0, (0, _univerjs_core.Inject)(_univerjs_core.Injector)),
553
+ __decorateParam(1, _univerjs_core.ICommandService),
554
+ __decorateParam(2, _univerjs_core.IUniverInstanceService),
555
+ __decorateParam(3, IRPCChannelService),
556
+ __decorateParam(4, IRemoteSyncService)
557
+ ], DataSyncPrimaryController);
558
+
559
+ //#endregion
560
+ //#region src/controllers/data-sync/data-sync-replica.controller.ts
561
+ let DataSyncReplicaController = class DataSyncReplicaController extends _univerjs_core.Disposable {
562
+ constructor(_injector, _remoteInstanceService, _commandService, _rpcChannelService) {
563
+ super();
564
+ this._injector = _injector;
565
+ this._remoteInstanceService = _remoteInstanceService;
566
+ this._commandService = _commandService;
567
+ this._rpcChannelService = _rpcChannelService;
568
+ _defineProperty(this, "_remoteSyncService", void 0);
569
+ this._initRPCChannels();
570
+ this._init();
571
+ }
572
+ _initRPCChannels() {
573
+ this._rpcChannelService.registerChannel(RemoteInstanceServiceName, fromModule(this._remoteInstanceService));
574
+ this._injector.add([IRemoteSyncService, { useFactory: () => toModule(this._rpcChannelService.requestChannel(RemoteSyncServiceName)) }]);
575
+ this._remoteSyncService = this._injector.get(IRemoteSyncService);
576
+ }
577
+ _init() {
578
+ this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo, options) => {
579
+ if (commandInfo.type === _univerjs_core.CommandType.MUTATION && !(options === null || options === void 0 ? void 0 : options.fromSync)) this._remoteSyncService.syncMutation({ mutationInfo: commandInfo }, options);
580
+ }));
581
+ }
582
+ };
583
+ DataSyncReplicaController = __decorate([
584
+ __decorateParam(0, (0, _univerjs_core.Inject)(_univerjs_core.Injector)),
585
+ __decorateParam(1, IRemoteInstanceService),
586
+ __decorateParam(2, _univerjs_core.ICommandService),
587
+ __decorateParam(3, IRPCChannelService)
588
+ ], DataSyncReplicaController);
589
+
590
+ //#endregion
591
+ //#region package.json
592
+ var name = "@apollo-office/rpc";
593
+ var version = "0.25.1";
594
+
595
+ //#endregion
596
+ //#region src/services/rpc/implementations/web-worker-rpc.service.ts
597
+ /**
598
+ * Generate an `IMessageProtocol` on the web worker.
599
+ * @returns A protocol wrapper around worker global messaging APIs.
600
+ */
601
+ function createWebWorkerMessagePortOnWorker() {
602
+ return {
603
+ send(message) {
604
+ postMessage(message);
605
+ },
606
+ onMessage: new rxjs.Observable((subscriber) => {
607
+ const handler = (event) => {
608
+ subscriber.next(event.data);
609
+ };
610
+ addEventListener("message", handler);
611
+ return () => removeEventListener("message", handler);
612
+ }).pipe((0, rxjs.shareReplay)({
613
+ bufferSize: 1,
614
+ refCount: true
615
+ }))
616
+ };
617
+ }
618
+ /**
619
+ * Generate an `IMessageProtocol` on the main thread side.
620
+ * @param worker The Web Worker object
621
+ * @returns A protocol wrapper around the given worker messaging APIs.
622
+ */
623
+ function createWebWorkerMessagePortOnMain(worker) {
624
+ return {
625
+ send(message) {
626
+ worker.postMessage(message);
627
+ },
628
+ onMessage: new rxjs.Observable((subscriber) => {
629
+ const handler = (event) => {
630
+ subscriber.next(event.data);
631
+ };
632
+ worker.addEventListener("message", handler);
633
+ return () => worker.removeEventListener("message", handler);
634
+ }).pipe((0, rxjs.shareReplay)({
635
+ bufferSize: 1,
636
+ refCount: true
637
+ }))
638
+ };
639
+ }
640
+
641
+ //#endregion
642
+ //#region src/plugin.ts
643
+ let UniverRPCMainThreadPlugin = class UniverRPCMainThreadPlugin extends _univerjs_core.Plugin {
644
+ constructor(_config = defaultPluginMainThreadConfig, _injector, _configService) {
645
+ super();
646
+ this._config = _config;
647
+ this._injector = _injector;
648
+ this._configService = _configService;
649
+ _defineProperty(this, "_internalWorker", null);
650
+ const { ...rest } = (0, _univerjs_core.merge)({}, defaultPluginMainThreadConfig, this._config);
651
+ this._configService.setConfig(PLUGIN_CONFIG_KEY_MAIN_THREAD, rest);
652
+ }
653
+ dispose() {
654
+ super.dispose();
655
+ if (this._internalWorker) {
656
+ this._internalWorker.terminate();
657
+ this._internalWorker = null;
658
+ }
659
+ }
660
+ onStarting() {
661
+ const { workerURL } = this._config;
662
+ if (!workerURL) throw new Error("[UniverRPCMainThreadPlugin]: The workerURL is required for the RPC main thread plugin.");
663
+ const worker = workerURL instanceof Worker ? workerURL : new Worker(workerURL);
664
+ this._internalWorker = workerURL instanceof Worker ? null : worker;
665
+ const messageProtocol = createWebWorkerMessagePortOnMain(worker);
666
+ [
667
+ [IRPCChannelService, { useFactory: () => new ChannelService(messageProtocol) }],
668
+ [DataSyncPrimaryController],
669
+ [IRemoteSyncService, { useClass: RemoteSyncPrimaryService }]
670
+ ].forEach((dependency) => this._injector.add(dependency));
671
+ this._injector.get(DataSyncPrimaryController);
672
+ }
673
+ };
674
+ _defineProperty(UniverRPCMainThreadPlugin, "pluginName", "UNIVER_RPC_MAIN_THREAD_PLUGIN");
675
+ _defineProperty(UniverRPCMainThreadPlugin, "packageName", name);
676
+ _defineProperty(UniverRPCMainThreadPlugin, "version", version);
677
+ UniverRPCMainThreadPlugin = __decorate([__decorateParam(1, (0, _univerjs_core.Inject)(_univerjs_core.Injector)), __decorateParam(2, _univerjs_core.IConfigService)], UniverRPCMainThreadPlugin);
678
+ let UniverRPCWorkerThreadPlugin = class UniverRPCWorkerThreadPlugin extends _univerjs_core.Plugin {
679
+ constructor(_config = defaultPluginWorkerThreadConfig, _injector, _configService) {
680
+ super();
681
+ this._config = _config;
682
+ this._injector = _injector;
683
+ this._configService = _configService;
684
+ const { ...rest } = (0, _univerjs_core.merge)({}, defaultPluginWorkerThreadConfig, this._config);
685
+ this._configService.setConfig(PLUGIN_CONFIG_KEY_WORKER_THREAD, rest);
686
+ }
687
+ onStarting() {
688
+ [
689
+ [DataSyncReplicaController],
690
+ [IRPCChannelService, { useFactory: () => new ChannelService(createWebWorkerMessagePortOnWorker()) }],
691
+ [IRemoteInstanceService, { useClass: WebWorkerRemoteInstanceService }]
692
+ ].forEach((dependency) => this._injector.add(dependency));
693
+ this._injector.get(DataSyncReplicaController);
694
+ }
695
+ };
696
+ _defineProperty(UniverRPCWorkerThreadPlugin, "pluginName", "UNIVER_RPC_WORKER_THREAD_PLUGIN");
697
+ _defineProperty(UniverRPCWorkerThreadPlugin, "packageName", name);
698
+ _defineProperty(UniverRPCWorkerThreadPlugin, "version", version);
699
+ UniverRPCWorkerThreadPlugin = __decorate([__decorateParam(1, (0, _univerjs_core.Inject)(_univerjs_core.Injector)), __decorateParam(2, _univerjs_core.IConfigService)], UniverRPCWorkerThreadPlugin);
700
+
701
+ //#endregion
702
+ exports.ChannelClient = ChannelClient;
703
+ exports.ChannelServer = ChannelServer;
704
+ exports.ChannelService = ChannelService;
705
+ Object.defineProperty(exports, 'DataSyncPrimaryController', {
706
+ enumerable: true,
707
+ get: function () {
708
+ return DataSyncPrimaryController;
709
+ }
710
+ });
711
+ Object.defineProperty(exports, 'DataSyncReplicaController', {
712
+ enumerable: true,
713
+ get: function () {
714
+ return DataSyncReplicaController;
715
+ }
716
+ });
717
+ exports.IRPCChannelService = IRPCChannelService;
718
+ exports.IRemoteInstanceService = IRemoteInstanceService;
719
+ exports.IRemoteSyncService = IRemoteSyncService;
720
+ exports.PLUGIN_CONFIG_KEY_MAIN_THREAD = PLUGIN_CONFIG_KEY_MAIN_THREAD;
721
+ exports.PLUGIN_CONFIG_KEY_WORKER_THREAD = PLUGIN_CONFIG_KEY_WORKER_THREAD;
722
+ exports.RemoteInstanceServiceName = RemoteInstanceServiceName;
723
+ Object.defineProperty(exports, 'RemoteSyncPrimaryService', {
724
+ enumerable: true,
725
+ get: function () {
726
+ return RemoteSyncPrimaryService;
727
+ }
728
+ });
729
+ exports.RemoteSyncServiceName = RemoteSyncServiceName;
730
+ Object.defineProperty(exports, 'UniverRPCMainThreadPlugin', {
731
+ enumerable: true,
732
+ get: function () {
733
+ return UniverRPCMainThreadPlugin;
734
+ }
735
+ });
736
+ Object.defineProperty(exports, 'UniverRPCWorkerThreadPlugin', {
737
+ enumerable: true,
738
+ get: function () {
739
+ return UniverRPCWorkerThreadPlugin;
740
+ }
741
+ });
742
+ Object.defineProperty(exports, 'WebWorkerRemoteInstanceService', {
743
+ enumerable: true,
744
+ get: function () {
745
+ return WebWorkerRemoteInstanceService;
746
+ }
747
+ });
748
+ exports.fromModule = fromModule;
749
+ exports.toModule = toModule;