@univerjs/rpc 0.2.7 → 0.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cjs/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var __defProp=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!="symbol"?key+"":key,value);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const core=require("@univerjs/core"),operators=require("rxjs/operators"),rxjs=require("rxjs");var __defProp$3=Object.defineProperty,__getOwnPropDesc$3=Object.getOwnPropertyDescriptor,__decorateClass$3=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$3(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$3(target,key,result),result},"__decorateClass$3"),__decorateParam$3=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$3");const RemoteSyncServiceName="rpc.remote-sync.service",IRemoteSyncService=core.createIdentifier(RemoteSyncServiceName);var _a;exports.RemoteSyncPrimaryService=(_a=class{constructor(_commandService){this._commandService=_commandService}async syncMutation(params){return this._commandService.syncExecuteCommand(params.mutationInfo.id,params.mutationInfo.params,{onlyLocal:!0,fromSync:!0})}},__name(_a,"RemoteSyncPrimaryService"),_a);exports.RemoteSyncPrimaryService=__decorateClass$3([__decorateParam$3(0,core.ICommandService)],exports.RemoteSyncPrimaryService);const RemoteInstanceServiceName="univer.remote-instance-service",IRemoteInstanceService=core.createIdentifier(RemoteInstanceServiceName);var _a2;exports.WebWorkerRemoteInstanceService=(_a2=class{constructor(_univerInstanceService,_commandService,_logService){this._univerInstanceService=_univerInstanceService,this._commandService=_commandService,this._logService=_logService}whenReady(){return Promise.resolve(!0)}async syncMutation(params){return this._applyMutation(params.mutationInfo)}async createInstance(params){const{type,snapshot}=params;try{switch(type){case core.UniverInstanceType.UNIVER_SHEET:return this._univerInstanceService.createUnit(core.UniverInstanceType.UNIVER_SHEET,snapshot),!0;default:throw new Error(`[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${type}.`)}}catch(err){throw err instanceof Error?err:new TypeError(`${err}`)}}async disposeInstance(params){return this._univerInstanceService.disposeUnit(params.unitID)}_applyMutation(mutationInfo){const{id,params:mutationParams}=mutationInfo;return this._commandService.syncExecuteCommand(id,mutationParams,{onlyLocal:!0,fromSync:!0})}},__name(_a2,"WebWorkerRemoteInstanceService"),_a2);exports.WebWorkerRemoteInstanceService=__decorateClass$3([__decorateParam$3(0,core.IUniverInstanceService),__decorateParam$3(1,core.ICommandService),__decorateParam$3(2,core.ILogService)],exports.WebWorkerRemoteInstanceService);function fromModule(module2){const handler=module2;return new class{call(method,args){const target=handler[method];if(typeof target=="function"){let res=target.apply(handler,[args]);return res instanceof Promise||(res=Promise.resolve(res)),res}throw new Error(`[RPC]: method not found for ${method}!`)}subscribe(eventMethod,args){const target=handler[eventMethod];if(typeof target=="function"){const res=target.apply(handler,args);return rxjs.isObservable(res)?res:rxjs.of(res)}throw new Error(`[RPC]: observable method not found for ${eventMethod}!`)}}}__name(fromModule,"fromModule");function toModule(channel){return new Proxy({},{get(_,propKey){if(propKey!=="dispose")return function(...args){return propertyIsEventSource(propKey)?channel.subscribe(propKey,args[0]):channel.call(propKey,args[0])}}})}__name(toModule,"toModule");function propertyIsEventSource(name){return name.endsWith("$")}__name(propertyIsEventSource,"propertyIsEventSource");const _ChannelClient=class _ChannelClient extends core.RxDisposable{constructor(_protocol){super();__publicField(this,"_initialized",new rxjs.BehaviorSubject(!1));__publicField(this,"_lastRequestCounter",0);__publicField(this,"_pendingRequests",new Map);this._protocol=_protocol,this._protocol.onMessage.pipe(operators.takeUntil(this.dispose$)).subscribe(message=>this._onMessage(message))}dispose(){this._pendingRequests.clear()}getChannel(channelName){const self=this;return{call(method,args){return self._disposed?Promise.reject():self._remoteCall(channelName,method,args)},subscribe(eventMethod,args){if(self._disposed)throw new Error("[ChannelClient]: client is disposed!");return self._remoteSubscribe(channelName,eventMethod,args)}}}_whenReady(){return rxjs.firstValueFrom(this._initialized.pipe(operators.filter(v=>v),operators.take(1)))}async _remoteCall(channelName,method,args){await this._whenReady();const sequence=++this._lastRequestCounter,request={seq:sequence,type:100,channelName,method,args},client=this;return new Promise((resolve,reject)=>{const responseHandler={handle(response){switch(response.type){case 201:client._pendingRequests.delete(sequence),resolve(response.data);break;case 202:client._pendingRequests.delete(sequence),reject(response.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(sequence,responseHandler),this._sendRequest(request)})}_remoteSubscribe(channelName,method,args){return new rxjs.Observable(subscriber=>{let sequence=-1;return this._whenReady().then(()=>{sequence=++this._lastRequestCounter;const request={seq:sequence,type:101,channelName,method,args},responseHandler={handle(response){switch(response.type){case 300:subscriber.next(response.data);break;case 301:subscriber.error(response.data);break;case 302:subscriber.complete();break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(sequence,responseHandler),this._sendRequest(request)}),()=>{if(sequence===-1)return;const cancelSubscriptionRequest={type:102,seq:sequence,channelName,method};this._sendRequest(cancelSubscriptionRequest)}})}_sendRequest(request){this._protocol.send(request)}_onMessage(response){var _a7;switch(response.type){case 0:this._initialized.next(!0);break;case 201:case 202:case 300:case 302:case 301:(_a7=this._pendingRequests.get(response.seq))==null||_a7.handle(response);break}}};__name(_ChannelClient,"ChannelClient");let ChannelClient=_ChannelClient;const _ChannelServer=class _ChannelServer extends core.RxDisposable{constructor(_protocol){super();__publicField(this,"_channels",new Map);__publicField(this,"_subscriptions",new Map);this._protocol=_protocol,this._protocol.onMessage.pipe(operators.takeUntil(this.dispose$)).subscribe(message=>this._onRequest(message)),this._sendResponse({seq:-1,type:0})}dispose(){super.dispose(),this._subscriptions.clear(),this._channels.clear()}registerChannel(channelName,channel){this._channels.set(channelName,channel)}_onRequest(request){switch(request.type){case 100:this._onMethodCall(request);break;case 101:this._onSubscribe(request);break;case 102:this._onUnsubscribe(request);break}}_onMethodCall(request){const{channelName,method,args}=request,channel=this._channels.get(channelName);let promise;try{if(!channel)throw new Error(`[ChannelServer]: Channel ${channelName} not found!`);promise=channel.call(method,args)}catch(err){promise=Promise.reject(err)}promise.then(data=>{this._sendResponse({seq:request.seq,type:201,data})}).catch(err=>{err instanceof Error?this._sendResponse({seq:request.seq,type:202,data:err.message}):this._sendResponse({seq:request.seq,type:202,data:String(err)})})}_onSubscribe(request){const{channelName,seq}=request,channel=this._channels.get(channelName);try{if(!channel)throw new Error(`[ChannelServer]: Channel ${channelName} not found!`);const subscription=channel.subscribe(request.method,request.args).subscribe({next:__name(data=>{this._sendResponse({seq,type:300,data})},"next"),error:__name(err=>{this._sendResponse({seq,type:301,data:err.message}),this._sendResponse({seq,type:302})},"error"),complete:__name(()=>{this._sendResponse({seq,type:302})},"complete")});this._subscriptions.set(request.seq,subscription)}catch(err){err instanceof Error?this._sendResponse({seq:request.seq,type:301,data:err.message}):this._sendResponse({seq:request.seq,type:301,data:String(err)})}}_onUnsubscribe(request){const subscription=this._subscriptions.get(request.seq);subscription&&(subscription.unsubscribe(),this._subscriptions.delete(request.seq))}_sendResponse(response){this._protocol.send(response)}};__name(_ChannelServer,"ChannelServer");let ChannelServer=_ChannelServer;const IRPCChannelService=core.createIdentifier("IRPCChannelService"),_ChannelService=class _ChannelService{constructor(_messageProtocol){__publicField(this,"_client");__publicField(this,"_server");this._client=new ChannelClient(_messageProtocol),this._server=new ChannelServer(_messageProtocol)}dispose(){this._client.dispose(),this._server.dispose()}requestChannel(name){return this._client.getChannel(name)}registerChannel(name,channel){this._server.registerChannel(name,channel)}};__name(_ChannelService,"ChannelService");let ChannelService=_ChannelService;var __defProp$2=Object.defineProperty,__getOwnPropDesc$2=Object.getOwnPropertyDescriptor,__decorateClass$2=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$2(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$2(target,key,result),result},"__decorateClass$2"),__decorateParam$2=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$2"),_a3;exports.DataSyncPrimaryController=(_a3=class extends core.RxDisposable{constructor(_injector,_commandService,_univerInstanceService,_rpcChannelService,_remoteSyncService){super();__publicField(this,"_remoteInstanceService");__publicField(this,"_syncingUnits",new Set);__publicField(this,"_syncingMutations",new Set);this._injector=_injector,this._commandService=_commandService,this._univerInstanceService=_univerInstanceService,this._rpcChannelService=_rpcChannelService,this._remoteSyncService=_remoteSyncService,this._initRPCChannels(),this._init()}registerSyncingMutations(mutation){this._syncingMutations.add(mutation.id)}syncUnit(unitId){return this._syncingUnits.add(unitId),core.toDisposable(()=>this._syncingUnits.delete(unitId))}_initRPCChannels(){this._rpcChannelService.registerChannel(RemoteSyncServiceName,fromModule(this._remoteSyncService)),this._injector.add([IRemoteInstanceService,{useFactory:__name(()=>toModule(this._rpcChannelService.requestChannel(RemoteInstanceServiceName)),"useFactory")}]),this._remoteInstanceService=this._injector.get(IRemoteInstanceService)}_init(){this._univerInstanceService.getTypeOfUnitAdded$(core.UniverInstanceType.UNIVER_SHEET).pipe(operators.takeUntil(this.dispose$)).subscribe(sheet=>{this._syncingUnits.add(sheet.getUnitId()),this._remoteInstanceService.createInstance({unitID:sheet.getUnitId(),type:core.UniverInstanceType.UNIVER_SHEET,snapshot:sheet.getSnapshot()})}),this._univerInstanceService.getTypeOfUnitDisposed$(core.UniverInstanceType.UNIVER_SHEET).pipe(operators.takeUntil(this.dispose$)).subscribe(workbook=>{this._syncingUnits.delete(workbook.getUnitId()),this._remoteInstanceService.disposeInstance({unitID:workbook.getUnitId()})}),this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo,options)=>{const{type,params,id}=commandInfo,unitId=(params==null?void 0:params.unitId)||"";type===core.CommandType.MUTATION&&(!unitId||this._syncingUnits.has(unitId))&&!(options!=null&&options.fromSync)&&this._syncingMutations.has(id)&&this._remoteInstanceService.syncMutation({mutationInfo:commandInfo})}))}},__name(_a3,"DataSyncPrimaryController"),_a3);exports.DataSyncPrimaryController=__decorateClass$2([core.OnLifecycle(core.LifecycleStages.Starting,exports.DataSyncPrimaryController),__decorateParam$2(0,core.Inject(core.Injector)),__decorateParam$2(1,core.ICommandService),__decorateParam$2(2,core.IUniverInstanceService),__decorateParam$2(3,IRPCChannelService),__decorateParam$2(4,IRemoteSyncService)],exports.DataSyncPrimaryController);var __defProp$1=Object.defineProperty,__getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__decorateClass$1=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$1(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$1(target,key,result),result},"__decorateClass$1"),__decorateParam$1=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$1"),_a4;exports.DataSyncReplicaController=(_a4=class extends core.Disposable{constructor(_injector,_remoteInstanceService,_commandService,_rpcChannelService){super();__publicField(this,"_remoteSyncService");this._injector=_injector,this._remoteInstanceService=_remoteInstanceService,this._commandService=_commandService,this._rpcChannelService=_rpcChannelService,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(RemoteInstanceServiceName,fromModule(this._remoteInstanceService)),this._injector.add([IRemoteSyncService,{useFactory:__name(()=>toModule(this._rpcChannelService.requestChannel(RemoteSyncServiceName)),"useFactory")}]),this._remoteSyncService=this._injector.get(IRemoteSyncService)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo,options)=>{commandInfo.type===core.CommandType.MUTATION&&!(options!=null&&options.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:commandInfo})}))}},__name(_a4,"DataSyncReplicaController"),_a4);exports.DataSyncReplicaController=__decorateClass$1([core.OnLifecycle(core.LifecycleStages.Starting,exports.DataSyncReplicaController),__decorateParam$1(0,core.Inject(core.Injector)),__decorateParam$1(1,IRemoteInstanceService),__decorateParam$1(2,core.ICommandService),__decorateParam$1(3,IRPCChannelService)],exports.DataSyncReplicaController);function createWebWorkerMessagePortOnWorker(){return{send(message){postMessage(message)},onMessage:new rxjs.Observable(subscriber=>{const handler=__name(event=>{subscriber.next(event.data)},"handler");return addEventListener("message",handler),()=>removeEventListener("message",handler)}).pipe(rxjs.shareReplay(1))}}__name(createWebWorkerMessagePortOnWorker,"createWebWorkerMessagePortOnWorker");function createWebWorkerMessagePortOnMain(worker){return{send(message){worker.postMessage(message)},onMessage:new rxjs.Observable(subscriber=>{const handler=__name(event=>{subscriber.next(event.data)},"handler");return worker.addEventListener("message",handler),()=>worker.removeEventListener("message",handler)}).pipe(rxjs.shareReplay(1))}}__name(createWebWorkerMessagePortOnMain,"createWebWorkerMessagePortOnMain");var __defProp2=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp2(target,key,result),result},"__decorateClass"),__decorateParam=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam"),_a5;exports.UniverRPCMainThreadPlugin=(_a5=class extends core.Plugin{constructor(_config,_injector){super(),this._config=_config,this._injector=_injector}onStarting(){const{workerURL}=this._config,worker=workerURL instanceof Worker?workerURL:new Worker(workerURL),messageProtocol=createWebWorkerMessagePortOnMain(worker);[[IRPCChannelService,{useFactory:__name(()=>new ChannelService(messageProtocol),"useFactory")}],[exports.DataSyncPrimaryController],[IRemoteSyncService,{useClass:exports.RemoteSyncPrimaryService}]].forEach(dependency=>this._injector.add(dependency)),this._injector.get(exports.DataSyncPrimaryController)}},__name(_a5,"UniverRPCMainThreadPlugin"),__publicField(_a5,"pluginName","UNIVER_RPC_MAIN_THREAD_PLUGIN"),_a5);exports.UniverRPCMainThreadPlugin=__decorateClass([__decorateParam(1,core.Inject(core.Injector))],exports.UniverRPCMainThreadPlugin);var _a6;exports.UniverRPCWorkerThreadPlugin=(_a6=class extends core.Plugin{constructor(_config,_injector){super(),this._config=_config,this._injector=_injector}onStarting(){[[exports.DataSyncReplicaController],[IRPCChannelService,{useFactory:__name(()=>new ChannelService(createWebWorkerMessagePortOnWorker()),"useFactory")}],[IRemoteInstanceService,{useClass:exports.WebWorkerRemoteInstanceService}]].forEach(dependency=>this._injector.add(dependency)),this._injector.get(exports.DataSyncReplicaController)}},__name(_a6,"UniverRPCWorkerThreadPlugin"),__publicField(_a6,"pluginName","UNIVER_RPC_WORKER_THREAD_PLUGIN"),_a6);exports.UniverRPCWorkerThreadPlugin=__decorateClass([__decorateParam(1,core.Inject(core.Injector))],exports.UniverRPCWorkerThreadPlugin);exports.ChannelClient=ChannelClient;exports.ChannelServer=ChannelServer;exports.ChannelService=ChannelService;exports.IRPCChannelService=IRPCChannelService;exports.IRemoteInstanceService=IRemoteInstanceService;exports.IRemoteSyncService=IRemoteSyncService;exports.RemoteInstanceServiceName=RemoteInstanceServiceName;exports.RemoteSyncServiceName=RemoteSyncServiceName;exports.fromModule=fromModule;exports.toModule=toModule;
1
+ "use strict";var __defProp=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!="symbol"?key+"":key,value);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const core=require("@univerjs/core"),operators=require("rxjs/operators"),rxjs=require("rxjs");var __defProp$3=Object.defineProperty,__getOwnPropDesc$3=Object.getOwnPropertyDescriptor,__decorateClass$3=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$3(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$3(target,key,result),result},"__decorateClass$3"),__decorateParam$3=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$3");const RemoteSyncServiceName="rpc.remote-sync.service",IRemoteSyncService=core.createIdentifier(RemoteSyncServiceName);var _a;exports.RemoteSyncPrimaryService=(_a=class{constructor(_commandService){this._commandService=_commandService}async syncMutation(params){return this._commandService.syncExecuteCommand(params.mutationInfo.id,params.mutationInfo.params,{onlyLocal:!0,fromSync:!0})}},__name(_a,"RemoteSyncPrimaryService"),_a);exports.RemoteSyncPrimaryService=__decorateClass$3([__decorateParam$3(0,core.ICommandService)],exports.RemoteSyncPrimaryService);const RemoteInstanceServiceName="univer.remote-instance-service",IRemoteInstanceService=core.createIdentifier(RemoteInstanceServiceName);var _a2;exports.WebWorkerRemoteInstanceService=(_a2=class{constructor(_univerInstanceService,_commandService,_logService){this._univerInstanceService=_univerInstanceService,this._commandService=_commandService,this._logService=_logService}whenReady(){return Promise.resolve(!0)}async syncMutation(params){return this._applyMutation(params.mutationInfo)}async createInstance(params){const{type,snapshot}=params;try{switch(type){case core.UniverInstanceType.UNIVER_SHEET:return this._univerInstanceService.createUnit(core.UniverInstanceType.UNIVER_SHEET,snapshot),!0;default:throw new Error(`[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${type}.`)}}catch(err){throw err instanceof Error?err:new TypeError(`${err}`)}}async disposeInstance(params){return this._univerInstanceService.disposeUnit(params.unitID)}_applyMutation(mutationInfo){const{id,params:mutationParams}=mutationInfo;return this._commandService.syncExecuteCommand(id,mutationParams,{onlyLocal:!0,fromSync:!0})}},__name(_a2,"WebWorkerRemoteInstanceService"),_a2);exports.WebWorkerRemoteInstanceService=__decorateClass$3([__decorateParam$3(0,core.IUniverInstanceService),__decorateParam$3(1,core.ICommandService),__decorateParam$3(2,core.ILogService)],exports.WebWorkerRemoteInstanceService);function fromModule(module2){const handler=module2;return new class{call(method,args){const target=handler[method];if(typeof target=="function"){let res=target.apply(handler,[args]);return res instanceof Promise||(res=Promise.resolve(res)),res}throw new Error(`[RPC]: method not found for ${method}!`)}subscribe(eventMethod,args){const target=handler[eventMethod];if(typeof target=="function"){const res=target.apply(handler,args);return rxjs.isObservable(res)?res:rxjs.of(res)}throw new Error(`[RPC]: observable method not found for ${eventMethod}!`)}}}__name(fromModule,"fromModule");function toModule(channel){return new Proxy({},{get(_,propKey){if(propKey!=="dispose")return function(...args){return propertyIsEventSource(propKey)?channel.subscribe(propKey,args[0]):channel.call(propKey,args[0])}}})}__name(toModule,"toModule");function propertyIsEventSource(name){return name.endsWith("$")}__name(propertyIsEventSource,"propertyIsEventSource");const _ChannelClient=class _ChannelClient extends core.RxDisposable{constructor(_protocol){super();__publicField(this,"_initialized",new rxjs.BehaviorSubject(!1));__publicField(this,"_lastRequestCounter",0);__publicField(this,"_pendingRequests",new Map);this._protocol=_protocol,this._protocol.onMessage.pipe(operators.takeUntil(this.dispose$)).subscribe(message=>this._onMessage(message))}dispose(){this._pendingRequests.clear()}getChannel(channelName){const self=this;return{call(method,args){return self._disposed?Promise.reject():self._remoteCall(channelName,method,args)},subscribe(eventMethod,args){if(self._disposed)throw new Error("[ChannelClient]: client is disposed!");return self._remoteSubscribe(channelName,eventMethod,args)}}}_whenReady(){return rxjs.firstValueFrom(this._initialized.pipe(operators.filter(v=>v),operators.take(1)))}async _remoteCall(channelName,method,args){await this._whenReady();const sequence=++this._lastRequestCounter,request={seq:sequence,type:100,channelName,method,args},client=this;return new Promise((resolve,reject)=>{const responseHandler={handle(response){switch(response.type){case 201:client._pendingRequests.delete(sequence),resolve(response.data);break;case 202:client._pendingRequests.delete(sequence),reject(response.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(sequence,responseHandler),this._sendRequest(request)})}_remoteSubscribe(channelName,method,args){return new rxjs.Observable(subscriber=>{let sequence=-1;return this._whenReady().then(()=>{sequence=++this._lastRequestCounter;const request={seq:sequence,type:101,channelName,method,args},responseHandler={handle(response){switch(response.type){case 300:subscriber.next(response.data);break;case 301:subscriber.error(response.data);break;case 302:subscriber.complete();break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(sequence,responseHandler),this._sendRequest(request)}),()=>{if(sequence===-1)return;const cancelSubscriptionRequest={type:102,seq:sequence,channelName,method};this._sendRequest(cancelSubscriptionRequest)}})}_sendRequest(request){this._protocol.send(request)}_onMessage(response){var _a7;switch(response.type){case 0:this._initialized.next(!0);break;case 201:case 202:case 300:case 302:case 301:(_a7=this._pendingRequests.get(response.seq))==null||_a7.handle(response);break}}};__name(_ChannelClient,"ChannelClient");let ChannelClient=_ChannelClient;const _ChannelServer=class _ChannelServer extends core.RxDisposable{constructor(_protocol){super();__publicField(this,"_channels",new Map);__publicField(this,"_subscriptions",new Map);this._protocol=_protocol,this._protocol.onMessage.pipe(operators.takeUntil(this.dispose$)).subscribe(message=>this._onRequest(message)),this._sendResponse({seq:-1,type:0})}dispose(){super.dispose(),this._subscriptions.clear(),this._channels.clear()}registerChannel(channelName,channel){this._channels.set(channelName,channel)}_onRequest(request){switch(request.type){case 100:this._onMethodCall(request);break;case 101:this._onSubscribe(request);break;case 102:this._onUnsubscribe(request);break}}_onMethodCall(request){const{channelName,method,args}=request,channel=this._channels.get(channelName);let promise;try{if(!channel)throw new Error(`[ChannelServer]: Channel ${channelName} not found!`);promise=channel.call(method,args)}catch(err){promise=Promise.reject(err)}promise.then(data=>{this._sendResponse({seq:request.seq,type:201,data})}).catch(err=>{err instanceof Error?this._sendResponse({seq:request.seq,type:202,data:err.message}):this._sendResponse({seq:request.seq,type:202,data:String(err)})})}_onSubscribe(request){const{channelName,seq}=request,channel=this._channels.get(channelName);try{if(!channel)throw new Error(`[ChannelServer]: Channel ${channelName} not found!`);const subscription=channel.subscribe(request.method,request.args).subscribe({next:__name(data=>{this._sendResponse({seq,type:300,data})},"next"),error:__name(err=>{this._sendResponse({seq,type:301,data:err.message}),this._sendResponse({seq,type:302})},"error"),complete:__name(()=>{this._sendResponse({seq,type:302})},"complete")});this._subscriptions.set(request.seq,subscription)}catch(err){err instanceof Error?this._sendResponse({seq:request.seq,type:301,data:err.message}):this._sendResponse({seq:request.seq,type:301,data:String(err)})}}_onUnsubscribe(request){const subscription=this._subscriptions.get(request.seq);subscription&&(subscription.unsubscribe(),this._subscriptions.delete(request.seq))}_sendResponse(response){this._protocol.send(response)}};__name(_ChannelServer,"ChannelServer");let ChannelServer=_ChannelServer;const IRPCChannelService=core.createIdentifier("IRPCChannelService"),_ChannelService=class _ChannelService{constructor(_messageProtocol){__publicField(this,"_client");__publicField(this,"_server");this._client=new ChannelClient(_messageProtocol),this._server=new ChannelServer(_messageProtocol)}dispose(){this._client.dispose(),this._server.dispose()}requestChannel(name){return this._client.getChannel(name)}registerChannel(name,channel){this._server.registerChannel(name,channel)}};__name(_ChannelService,"ChannelService");let ChannelService=_ChannelService;var __defProp$2=Object.defineProperty,__getOwnPropDesc$2=Object.getOwnPropertyDescriptor,__decorateClass$2=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$2(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$2(target,key,result),result},"__decorateClass$2"),__decorateParam$2=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$2"),_a3;exports.DataSyncPrimaryController=(_a3=class extends core.RxDisposable{constructor(_injector,_commandService,_univerInstanceService,_rpcChannelService,_remoteSyncService){super();__publicField(this,"_remoteInstanceService");__publicField(this,"_syncingUnits",new Set);__publicField(this,"_syncingMutations",new Set);this._injector=_injector,this._commandService=_commandService,this._univerInstanceService=_univerInstanceService,this._rpcChannelService=_rpcChannelService,this._remoteSyncService=_remoteSyncService,this._initRPCChannels(),this._init()}registerSyncingMutations(mutation){this._syncingMutations.add(mutation.id)}syncUnit(unitId){return this._syncingUnits.add(unitId),core.toDisposable(()=>this._syncingUnits.delete(unitId))}_initRPCChannels(){this._rpcChannelService.registerChannel(RemoteSyncServiceName,fromModule(this._remoteSyncService)),this._injector.add([IRemoteInstanceService,{useFactory:__name(()=>toModule(this._rpcChannelService.requestChannel(RemoteInstanceServiceName)),"useFactory")}]),this._remoteInstanceService=this._injector.get(IRemoteInstanceService)}_init(){this._univerInstanceService.getTypeOfUnitAdded$(core.UniverInstanceType.UNIVER_SHEET).pipe(operators.takeUntil(this.dispose$)).subscribe(sheet=>{this._syncingUnits.add(sheet.getUnitId()),this._remoteInstanceService.createInstance({unitID:sheet.getUnitId(),type:core.UniverInstanceType.UNIVER_SHEET,snapshot:sheet.getSnapshot()})}),this._univerInstanceService.getTypeOfUnitDisposed$(core.UniverInstanceType.UNIVER_SHEET).pipe(operators.takeUntil(this.dispose$)).subscribe(workbook=>{this._syncingUnits.delete(workbook.getUnitId()),this._remoteInstanceService.disposeInstance({unitID:workbook.getUnitId()})}),this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo,options)=>{const{type,params,id}=commandInfo,unitId=(params==null?void 0:params.unitId)||"";type===core.CommandType.MUTATION&&(!unitId||this._syncingUnits.has(unitId))&&!(options!=null&&options.fromSync)&&this._syncingMutations.has(id)&&this._remoteInstanceService.syncMutation({mutationInfo:commandInfo})}))}},__name(_a3,"DataSyncPrimaryController"),_a3);exports.DataSyncPrimaryController=__decorateClass$2([core.OnLifecycle(core.LifecycleStages.Starting,exports.DataSyncPrimaryController),__decorateParam$2(0,core.Inject(core.Injector)),__decorateParam$2(1,core.ICommandService),__decorateParam$2(2,core.IUniverInstanceService),__decorateParam$2(3,IRPCChannelService),__decorateParam$2(4,IRemoteSyncService)],exports.DataSyncPrimaryController);var __defProp$1=Object.defineProperty,__getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__decorateClass$1=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$1(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$1(target,key,result),result},"__decorateClass$1"),__decorateParam$1=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$1"),_a4;exports.DataSyncReplicaController=(_a4=class extends core.Disposable{constructor(_injector,_remoteInstanceService,_commandService,_rpcChannelService){super();__publicField(this,"_remoteSyncService");this._injector=_injector,this._remoteInstanceService=_remoteInstanceService,this._commandService=_commandService,this._rpcChannelService=_rpcChannelService,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(RemoteInstanceServiceName,fromModule(this._remoteInstanceService)),this._injector.add([IRemoteSyncService,{useFactory:__name(()=>toModule(this._rpcChannelService.requestChannel(RemoteSyncServiceName)),"useFactory")}]),this._remoteSyncService=this._injector.get(IRemoteSyncService)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo,options)=>{commandInfo.type===core.CommandType.MUTATION&&!(options!=null&&options.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:commandInfo})}))}},__name(_a4,"DataSyncReplicaController"),_a4);exports.DataSyncReplicaController=__decorateClass$1([core.OnLifecycle(core.LifecycleStages.Starting,exports.DataSyncReplicaController),__decorateParam$1(0,core.Inject(core.Injector)),__decorateParam$1(1,IRemoteInstanceService),__decorateParam$1(2,core.ICommandService),__decorateParam$1(3,IRPCChannelService)],exports.DataSyncReplicaController);function createWebWorkerMessagePortOnWorker(){return{send(message){postMessage(message)},onMessage:new rxjs.Observable(subscriber=>{const handler=__name(event=>{subscriber.next(event.data)},"handler");return addEventListener("message",handler),()=>removeEventListener("message",handler)}).pipe(rxjs.shareReplay(1))}}__name(createWebWorkerMessagePortOnWorker,"createWebWorkerMessagePortOnWorker");function createWebWorkerMessagePortOnMain(worker){return{send(message){worker.postMessage(message)},onMessage:new rxjs.Observable(subscriber=>{const handler=__name(event=>{subscriber.next(event.data)},"handler");return worker.addEventListener("message",handler),()=>worker.removeEventListener("message",handler)}).pipe(rxjs.shareReplay(1))}}__name(createWebWorkerMessagePortOnMain,"createWebWorkerMessagePortOnMain");var __defProp2=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp2(target,key,result),result},"__decorateClass"),__decorateParam=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam"),_a5;exports.UniverRPCMainThreadPlugin=(_a5=class extends core.Plugin{constructor(_config,_injector){super();__publicField(this,"_internalWorker",null);this._config=_config,this._injector=_injector}dispose(){super.dispose(),this._internalWorker&&(this._internalWorker.terminate(),this._internalWorker=null)}onStarting(){const{workerURL}=this._config,worker=workerURL instanceof Worker?workerURL:new Worker(workerURL);this._internalWorker=workerURL instanceof Worker?null:worker;const messageProtocol=createWebWorkerMessagePortOnMain(worker);[[IRPCChannelService,{useFactory:__name(()=>new ChannelService(messageProtocol),"useFactory")}],[exports.DataSyncPrimaryController],[IRemoteSyncService,{useClass:exports.RemoteSyncPrimaryService}]].forEach(dependency=>this._injector.add(dependency)),this._injector.get(exports.DataSyncPrimaryController)}},__name(_a5,"UniverRPCMainThreadPlugin"),__publicField(_a5,"pluginName","UNIVER_RPC_MAIN_THREAD_PLUGIN"),_a5);exports.UniverRPCMainThreadPlugin=__decorateClass([__decorateParam(1,core.Inject(core.Injector))],exports.UniverRPCMainThreadPlugin);var _a6;exports.UniverRPCWorkerThreadPlugin=(_a6=class extends core.Plugin{constructor(_config,_injector){super(),this._config=_config,this._injector=_injector}onStarting(){[[exports.DataSyncReplicaController],[IRPCChannelService,{useFactory:__name(()=>new ChannelService(createWebWorkerMessagePortOnWorker()),"useFactory")}],[IRemoteInstanceService,{useClass:exports.WebWorkerRemoteInstanceService}]].forEach(dependency=>this._injector.add(dependency)),this._injector.get(exports.DataSyncReplicaController)}},__name(_a6,"UniverRPCWorkerThreadPlugin"),__publicField(_a6,"pluginName","UNIVER_RPC_WORKER_THREAD_PLUGIN"),_a6);exports.UniverRPCWorkerThreadPlugin=__decorateClass([__decorateParam(1,core.Inject(core.Injector))],exports.UniverRPCWorkerThreadPlugin);exports.ChannelClient=ChannelClient;exports.ChannelServer=ChannelServer;exports.ChannelService=ChannelService;exports.IRPCChannelService=IRPCChannelService;exports.IRemoteInstanceService=IRemoteInstanceService;exports.IRemoteSyncService=IRemoteSyncService;exports.RemoteInstanceServiceName=RemoteInstanceServiceName;exports.RemoteSyncServiceName=RemoteSyncServiceName;exports.fromModule=fromModule;exports.toModule=toModule;
package/lib/es/index.js CHANGED
@@ -446,10 +446,17 @@ var __defProp2 = Object.defineProperty, __getOwnPropDesc = Object.getOwnProperty
446
446
  }, "__decorateClass"), __decorateParam = /* @__PURE__ */ __name((index, decorator) => (target, key) => decorator(target, key, index), "__decorateParam"), _a5;
447
447
  let UniverRPCMainThreadPlugin = (_a5 = class extends Plugin {
448
448
  constructor(_config, _injector) {
449
- super(), this._config = _config, this._injector = _injector;
449
+ super();
450
+ __publicField(this, "_internalWorker", null);
451
+ this._config = _config, this._injector = _injector;
452
+ }
453
+ dispose() {
454
+ super.dispose(), this._internalWorker && (this._internalWorker.terminate(), this._internalWorker = null);
450
455
  }
451
456
  onStarting() {
452
- const { workerURL } = this._config, worker = workerURL instanceof Worker ? workerURL : new Worker(workerURL), messageProtocol = createWebWorkerMessagePortOnMain(worker);
457
+ const { workerURL } = this._config, worker = workerURL instanceof Worker ? workerURL : new Worker(workerURL);
458
+ this._internalWorker = workerURL instanceof Worker ? null : worker;
459
+ const messageProtocol = createWebWorkerMessagePortOnMain(worker);
453
460
  [
454
461
  [
455
462
  IRPCChannelService,
@@ -1,7 +1,6 @@
1
1
  import { IDisposable, IMutation, ICommandService, Injector, IUniverInstanceService, RxDisposable } from '@univerjs/core';
2
2
  import { IRemoteSyncService } from '../../services/remote-instance/remote-instance.service';
3
3
  import { IRPCChannelService } from '../../services/rpc/channel.service';
4
-
5
4
  /**
6
5
  * This controller is responsible for syncing data from the primary thread to
7
6
  * the worker thread.
@@ -1,7 +1,6 @@
1
1
  import { Disposable, ICommandService, Injector } from '@univerjs/core';
2
2
  import { IRemoteInstanceService } from '../../services/remote-instance/remote-instance.service';
3
3
  import { IRPCChannelService } from '../../services/rpc/channel.service';
4
-
5
4
  /**
6
5
  * This controller is responsible for syncing data from the worker thread to
7
6
  * the primary thread.
@@ -1,5 +1,4 @@
1
1
  import { Injector, Plugin } from '@univerjs/core';
2
-
3
2
  export interface IUniverRPCMainThreadConfig {
4
3
  workerURL: string | URL | Worker;
5
4
  }
@@ -11,7 +10,9 @@ export declare class UniverRPCMainThreadPlugin extends Plugin {
11
10
  private readonly _config;
12
11
  protected readonly _injector: Injector;
13
12
  static pluginName: string;
13
+ private _internalWorker;
14
14
  constructor(_config: IUniverRPCMainThreadConfig, _injector: Injector);
15
+ dispose(): void;
15
16
  onStarting(): void;
16
17
  }
17
18
  /**
@@ -1,5 +1,4 @@
1
1
  import { IExecutionOptions, IMutationInfo, IWorkbookData, ICommandService, ILogService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
2
-
3
2
  export interface IRemoteSyncMutationOptions extends IExecutionOptions {
4
3
  /** If this mutation is executed after it was sent from the peer univer instance (e.g. in a web worker). */
5
4
  fromSync?: boolean;
@@ -1,6 +1,5 @@
1
1
  import { IDisposable } from '@univerjs/core';
2
2
  import { IChannel, IMessageProtocol } from './rpc.service';
3
-
4
3
  export interface IRPCChannelService {
5
4
  requestChannel(name: string): IChannel;
6
5
  registerChannel(name: string, channel: IChannel): void;
@@ -1,5 +1,4 @@
1
1
  import { IMessageProtocol } from '../rpc.service';
2
-
3
2
  /**
4
3
  * Generate an `IMessageProtocol` on the web worker.
5
4
  */
@@ -1,6 +1,5 @@
1
1
  import { RxDisposable } from '@univerjs/core';
2
2
  import { Observable } from 'rxjs';
3
-
4
3
  /** This protocol is for transferring data from the two peer univer instance running in different locations. */
5
4
  export interface IMessageProtocol {
6
5
  send(message: any): void;
package/lib/umd/index.js CHANGED
@@ -1 +1 @@
1
- (function(global,factory){typeof exports=="object"&&typeof module<"u"?factory(exports,require("@univerjs/core"),require("rxjs/operators"),require("rxjs")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs/operators","rxjs"],factory):(global=typeof globalThis<"u"?globalThis:global||self,factory(global.UniverRpc={},global.UniverCore,global.rxjs.operators,global.rxjs))})(this,function(exports2,core,operators,rxjs){"use strict";var __defProp=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!="symbol"?key+"":key,value);var _a,_b,_c,_d,_e,_f;var __defProp$3=Object.defineProperty,__getOwnPropDesc$3=Object.getOwnPropertyDescriptor,__decorateClass$3=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$3(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$3(target,key,result),result},"__decorateClass$3"),__decorateParam$3=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$3");const RemoteSyncServiceName="rpc.remote-sync.service",IRemoteSyncService=core.createIdentifier(RemoteSyncServiceName);exports2.RemoteSyncPrimaryService=(_a=class{constructor(_commandService){this._commandService=_commandService}async syncMutation(params){return this._commandService.syncExecuteCommand(params.mutationInfo.id,params.mutationInfo.params,{onlyLocal:!0,fromSync:!0})}},__name(_a,"RemoteSyncPrimaryService"),_a),exports2.RemoteSyncPrimaryService=__decorateClass$3([__decorateParam$3(0,core.ICommandService)],exports2.RemoteSyncPrimaryService);const RemoteInstanceServiceName="univer.remote-instance-service",IRemoteInstanceService=core.createIdentifier(RemoteInstanceServiceName);exports2.WebWorkerRemoteInstanceService=(_b=class{constructor(_univerInstanceService,_commandService,_logService){this._univerInstanceService=_univerInstanceService,this._commandService=_commandService,this._logService=_logService}whenReady(){return Promise.resolve(!0)}async syncMutation(params){return this._applyMutation(params.mutationInfo)}async createInstance(params){const{type,snapshot}=params;try{switch(type){case core.UniverInstanceType.UNIVER_SHEET:return this._univerInstanceService.createUnit(core.UniverInstanceType.UNIVER_SHEET,snapshot),!0;default:throw new Error(`[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${type}.`)}}catch(err){throw err instanceof Error?err:new TypeError(`${err}`)}}async disposeInstance(params){return this._univerInstanceService.disposeUnit(params.unitID)}_applyMutation(mutationInfo){const{id,params:mutationParams}=mutationInfo;return this._commandService.syncExecuteCommand(id,mutationParams,{onlyLocal:!0,fromSync:!0})}},__name(_b,"WebWorkerRemoteInstanceService"),_b),exports2.WebWorkerRemoteInstanceService=__decorateClass$3([__decorateParam$3(0,core.IUniverInstanceService),__decorateParam$3(1,core.ICommandService),__decorateParam$3(2,core.ILogService)],exports2.WebWorkerRemoteInstanceService);function fromModule(module2){const handler=module2;return new class{call(method,args){const target=handler[method];if(typeof target=="function"){let res=target.apply(handler,[args]);return res instanceof Promise||(res=Promise.resolve(res)),res}throw new Error(`[RPC]: method not found for ${method}!`)}subscribe(eventMethod,args){const target=handler[eventMethod];if(typeof target=="function"){const res=target.apply(handler,args);return rxjs.isObservable(res)?res:rxjs.of(res)}throw new Error(`[RPC]: observable method not found for ${eventMethod}!`)}}}__name(fromModule,"fromModule");function toModule(channel){return new Proxy({},{get(_,propKey){if(propKey!=="dispose")return function(...args){return propertyIsEventSource(propKey)?channel.subscribe(propKey,args[0]):channel.call(propKey,args[0])}}})}__name(toModule,"toModule");function propertyIsEventSource(name){return name.endsWith("$")}__name(propertyIsEventSource,"propertyIsEventSource");const _ChannelClient=class _ChannelClient extends core.RxDisposable{constructor(_protocol){super();__publicField(this,"_initialized",new rxjs.BehaviorSubject(!1));__publicField(this,"_lastRequestCounter",0);__publicField(this,"_pendingRequests",new Map);this._protocol=_protocol,this._protocol.onMessage.pipe(operators.takeUntil(this.dispose$)).subscribe(message=>this._onMessage(message))}dispose(){this._pendingRequests.clear()}getChannel(channelName){const self2=this;return{call(method,args){return self2._disposed?Promise.reject():self2._remoteCall(channelName,method,args)},subscribe(eventMethod,args){if(self2._disposed)throw new Error("[ChannelClient]: client is disposed!");return self2._remoteSubscribe(channelName,eventMethod,args)}}}_whenReady(){return rxjs.firstValueFrom(this._initialized.pipe(operators.filter(v=>v),operators.take(1)))}async _remoteCall(channelName,method,args){await this._whenReady();const sequence=++this._lastRequestCounter,request={seq:sequence,type:100,channelName,method,args},client=this;return new Promise((resolve,reject)=>{const responseHandler={handle(response){switch(response.type){case 201:client._pendingRequests.delete(sequence),resolve(response.data);break;case 202:client._pendingRequests.delete(sequence),reject(response.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(sequence,responseHandler),this._sendRequest(request)})}_remoteSubscribe(channelName,method,args){return new rxjs.Observable(subscriber=>{let sequence=-1;return this._whenReady().then(()=>{sequence=++this._lastRequestCounter;const request={seq:sequence,type:101,channelName,method,args},responseHandler={handle(response){switch(response.type){case 300:subscriber.next(response.data);break;case 301:subscriber.error(response.data);break;case 302:subscriber.complete();break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(sequence,responseHandler),this._sendRequest(request)}),()=>{if(sequence===-1)return;const cancelSubscriptionRequest={type:102,seq:sequence,channelName,method};this._sendRequest(cancelSubscriptionRequest)}})}_sendRequest(request){this._protocol.send(request)}_onMessage(response){var _a2;switch(response.type){case 0:this._initialized.next(!0);break;case 201:case 202:case 300:case 302:case 301:(_a2=this._pendingRequests.get(response.seq))==null||_a2.handle(response);break}}};__name(_ChannelClient,"ChannelClient");let ChannelClient=_ChannelClient;const _ChannelServer=class _ChannelServer extends core.RxDisposable{constructor(_protocol){super();__publicField(this,"_channels",new Map);__publicField(this,"_subscriptions",new Map);this._protocol=_protocol,this._protocol.onMessage.pipe(operators.takeUntil(this.dispose$)).subscribe(message=>this._onRequest(message)),this._sendResponse({seq:-1,type:0})}dispose(){super.dispose(),this._subscriptions.clear(),this._channels.clear()}registerChannel(channelName,channel){this._channels.set(channelName,channel)}_onRequest(request){switch(request.type){case 100:this._onMethodCall(request);break;case 101:this._onSubscribe(request);break;case 102:this._onUnsubscribe(request);break}}_onMethodCall(request){const{channelName,method,args}=request,channel=this._channels.get(channelName);let promise;try{if(!channel)throw new Error(`[ChannelServer]: Channel ${channelName} not found!`);promise=channel.call(method,args)}catch(err){promise=Promise.reject(err)}promise.then(data=>{this._sendResponse({seq:request.seq,type:201,data})}).catch(err=>{err instanceof Error?this._sendResponse({seq:request.seq,type:202,data:err.message}):this._sendResponse({seq:request.seq,type:202,data:String(err)})})}_onSubscribe(request){const{channelName,seq}=request,channel=this._channels.get(channelName);try{if(!channel)throw new Error(`[ChannelServer]: Channel ${channelName} not found!`);const subscription=channel.subscribe(request.method,request.args).subscribe({next:__name(data=>{this._sendResponse({seq,type:300,data})},"next"),error:__name(err=>{this._sendResponse({seq,type:301,data:err.message}),this._sendResponse({seq,type:302})},"error"),complete:__name(()=>{this._sendResponse({seq,type:302})},"complete")});this._subscriptions.set(request.seq,subscription)}catch(err){err instanceof Error?this._sendResponse({seq:request.seq,type:301,data:err.message}):this._sendResponse({seq:request.seq,type:301,data:String(err)})}}_onUnsubscribe(request){const subscription=this._subscriptions.get(request.seq);subscription&&(subscription.unsubscribe(),this._subscriptions.delete(request.seq))}_sendResponse(response){this._protocol.send(response)}};__name(_ChannelServer,"ChannelServer");let ChannelServer=_ChannelServer;const IRPCChannelService=core.createIdentifier("IRPCChannelService"),_ChannelService=class _ChannelService{constructor(_messageProtocol){__publicField(this,"_client");__publicField(this,"_server");this._client=new ChannelClient(_messageProtocol),this._server=new ChannelServer(_messageProtocol)}dispose(){this._client.dispose(),this._server.dispose()}requestChannel(name){return this._client.getChannel(name)}registerChannel(name,channel){this._server.registerChannel(name,channel)}};__name(_ChannelService,"ChannelService");let ChannelService=_ChannelService;var __defProp$2=Object.defineProperty,__getOwnPropDesc$2=Object.getOwnPropertyDescriptor,__decorateClass$2=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$2(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$2(target,key,result),result},"__decorateClass$2"),__decorateParam$2=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$2");exports2.DataSyncPrimaryController=(_c=class extends core.RxDisposable{constructor(_injector,_commandService,_univerInstanceService,_rpcChannelService,_remoteSyncService){super();__publicField(this,"_remoteInstanceService");__publicField(this,"_syncingUnits",new Set);__publicField(this,"_syncingMutations",new Set);this._injector=_injector,this._commandService=_commandService,this._univerInstanceService=_univerInstanceService,this._rpcChannelService=_rpcChannelService,this._remoteSyncService=_remoteSyncService,this._initRPCChannels(),this._init()}registerSyncingMutations(mutation){this._syncingMutations.add(mutation.id)}syncUnit(unitId){return this._syncingUnits.add(unitId),core.toDisposable(()=>this._syncingUnits.delete(unitId))}_initRPCChannels(){this._rpcChannelService.registerChannel(RemoteSyncServiceName,fromModule(this._remoteSyncService)),this._injector.add([IRemoteInstanceService,{useFactory:__name(()=>toModule(this._rpcChannelService.requestChannel(RemoteInstanceServiceName)),"useFactory")}]),this._remoteInstanceService=this._injector.get(IRemoteInstanceService)}_init(){this._univerInstanceService.getTypeOfUnitAdded$(core.UniverInstanceType.UNIVER_SHEET).pipe(operators.takeUntil(this.dispose$)).subscribe(sheet=>{this._syncingUnits.add(sheet.getUnitId()),this._remoteInstanceService.createInstance({unitID:sheet.getUnitId(),type:core.UniverInstanceType.UNIVER_SHEET,snapshot:sheet.getSnapshot()})}),this._univerInstanceService.getTypeOfUnitDisposed$(core.UniverInstanceType.UNIVER_SHEET).pipe(operators.takeUntil(this.dispose$)).subscribe(workbook=>{this._syncingUnits.delete(workbook.getUnitId()),this._remoteInstanceService.disposeInstance({unitID:workbook.getUnitId()})}),this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo,options)=>{const{type,params,id}=commandInfo,unitId=(params==null?void 0:params.unitId)||"";type===core.CommandType.MUTATION&&(!unitId||this._syncingUnits.has(unitId))&&!(options!=null&&options.fromSync)&&this._syncingMutations.has(id)&&this._remoteInstanceService.syncMutation({mutationInfo:commandInfo})}))}},__name(_c,"DataSyncPrimaryController"),_c),exports2.DataSyncPrimaryController=__decorateClass$2([core.OnLifecycle(core.LifecycleStages.Starting,exports2.DataSyncPrimaryController),__decorateParam$2(0,core.Inject(core.Injector)),__decorateParam$2(1,core.ICommandService),__decorateParam$2(2,core.IUniverInstanceService),__decorateParam$2(3,IRPCChannelService),__decorateParam$2(4,IRemoteSyncService)],exports2.DataSyncPrimaryController);var __defProp$1=Object.defineProperty,__getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__decorateClass$1=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$1(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$1(target,key,result),result},"__decorateClass$1"),__decorateParam$1=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$1");exports2.DataSyncReplicaController=(_d=class extends core.Disposable{constructor(_injector,_remoteInstanceService,_commandService,_rpcChannelService){super();__publicField(this,"_remoteSyncService");this._injector=_injector,this._remoteInstanceService=_remoteInstanceService,this._commandService=_commandService,this._rpcChannelService=_rpcChannelService,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(RemoteInstanceServiceName,fromModule(this._remoteInstanceService)),this._injector.add([IRemoteSyncService,{useFactory:__name(()=>toModule(this._rpcChannelService.requestChannel(RemoteSyncServiceName)),"useFactory")}]),this._remoteSyncService=this._injector.get(IRemoteSyncService)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo,options)=>{commandInfo.type===core.CommandType.MUTATION&&!(options!=null&&options.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:commandInfo})}))}},__name(_d,"DataSyncReplicaController"),_d),exports2.DataSyncReplicaController=__decorateClass$1([core.OnLifecycle(core.LifecycleStages.Starting,exports2.DataSyncReplicaController),__decorateParam$1(0,core.Inject(core.Injector)),__decorateParam$1(1,IRemoteInstanceService),__decorateParam$1(2,core.ICommandService),__decorateParam$1(3,IRPCChannelService)],exports2.DataSyncReplicaController);function createWebWorkerMessagePortOnWorker(){return{send(message){postMessage(message)},onMessage:new rxjs.Observable(subscriber=>{const handler=__name(event=>{subscriber.next(event.data)},"handler");return addEventListener("message",handler),()=>removeEventListener("message",handler)}).pipe(rxjs.shareReplay(1))}}__name(createWebWorkerMessagePortOnWorker,"createWebWorkerMessagePortOnWorker");function createWebWorkerMessagePortOnMain(worker){return{send(message){worker.postMessage(message)},onMessage:new rxjs.Observable(subscriber=>{const handler=__name(event=>{subscriber.next(event.data)},"handler");return worker.addEventListener("message",handler),()=>worker.removeEventListener("message",handler)}).pipe(rxjs.shareReplay(1))}}__name(createWebWorkerMessagePortOnMain,"createWebWorkerMessagePortOnMain");var __defProp2=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp2(target,key,result),result},"__decorateClass"),__decorateParam=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam");exports2.UniverRPCMainThreadPlugin=(_e=class extends core.Plugin{constructor(_config,_injector){super(),this._config=_config,this._injector=_injector}onStarting(){const{workerURL}=this._config,worker=workerURL instanceof Worker?workerURL:new Worker(workerURL),messageProtocol=createWebWorkerMessagePortOnMain(worker);[[IRPCChannelService,{useFactory:__name(()=>new ChannelService(messageProtocol),"useFactory")}],[exports2.DataSyncPrimaryController],[IRemoteSyncService,{useClass:exports2.RemoteSyncPrimaryService}]].forEach(dependency=>this._injector.add(dependency)),this._injector.get(exports2.DataSyncPrimaryController)}},__name(_e,"UniverRPCMainThreadPlugin"),__publicField(_e,"pluginName","UNIVER_RPC_MAIN_THREAD_PLUGIN"),_e),exports2.UniverRPCMainThreadPlugin=__decorateClass([__decorateParam(1,core.Inject(core.Injector))],exports2.UniverRPCMainThreadPlugin),exports2.UniverRPCWorkerThreadPlugin=(_f=class extends core.Plugin{constructor(_config,_injector){super(),this._config=_config,this._injector=_injector}onStarting(){[[exports2.DataSyncReplicaController],[IRPCChannelService,{useFactory:__name(()=>new ChannelService(createWebWorkerMessagePortOnWorker()),"useFactory")}],[IRemoteInstanceService,{useClass:exports2.WebWorkerRemoteInstanceService}]].forEach(dependency=>this._injector.add(dependency)),this._injector.get(exports2.DataSyncReplicaController)}},__name(_f,"UniverRPCWorkerThreadPlugin"),__publicField(_f,"pluginName","UNIVER_RPC_WORKER_THREAD_PLUGIN"),_f),exports2.UniverRPCWorkerThreadPlugin=__decorateClass([__decorateParam(1,core.Inject(core.Injector))],exports2.UniverRPCWorkerThreadPlugin),exports2.ChannelClient=ChannelClient,exports2.ChannelServer=ChannelServer,exports2.ChannelService=ChannelService,exports2.IRPCChannelService=IRPCChannelService,exports2.IRemoteInstanceService=IRemoteInstanceService,exports2.IRemoteSyncService=IRemoteSyncService,exports2.RemoteInstanceServiceName=RemoteInstanceServiceName,exports2.RemoteSyncServiceName=RemoteSyncServiceName,exports2.fromModule=fromModule,exports2.toModule=toModule,Object.defineProperty(exports2,Symbol.toStringTag,{value:"Module"})});
1
+ (function(global,factory){typeof exports=="object"&&typeof module<"u"?factory(exports,require("@univerjs/core"),require("rxjs/operators"),require("rxjs")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs/operators","rxjs"],factory):(global=typeof globalThis<"u"?globalThis:global||self,factory(global.UniverRpc={},global.UniverCore,global.rxjs.operators,global.rxjs))})(this,function(exports2,core,operators,rxjs){"use strict";var __defProp=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!="symbol"?key+"":key,value);var _a,_b,_c,_d,_e,_f;var __defProp$3=Object.defineProperty,__getOwnPropDesc$3=Object.getOwnPropertyDescriptor,__decorateClass$3=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$3(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$3(target,key,result),result},"__decorateClass$3"),__decorateParam$3=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$3");const RemoteSyncServiceName="rpc.remote-sync.service",IRemoteSyncService=core.createIdentifier(RemoteSyncServiceName);exports2.RemoteSyncPrimaryService=(_a=class{constructor(_commandService){this._commandService=_commandService}async syncMutation(params){return this._commandService.syncExecuteCommand(params.mutationInfo.id,params.mutationInfo.params,{onlyLocal:!0,fromSync:!0})}},__name(_a,"RemoteSyncPrimaryService"),_a),exports2.RemoteSyncPrimaryService=__decorateClass$3([__decorateParam$3(0,core.ICommandService)],exports2.RemoteSyncPrimaryService);const RemoteInstanceServiceName="univer.remote-instance-service",IRemoteInstanceService=core.createIdentifier(RemoteInstanceServiceName);exports2.WebWorkerRemoteInstanceService=(_b=class{constructor(_univerInstanceService,_commandService,_logService){this._univerInstanceService=_univerInstanceService,this._commandService=_commandService,this._logService=_logService}whenReady(){return Promise.resolve(!0)}async syncMutation(params){return this._applyMutation(params.mutationInfo)}async createInstance(params){const{type,snapshot}=params;try{switch(type){case core.UniverInstanceType.UNIVER_SHEET:return this._univerInstanceService.createUnit(core.UniverInstanceType.UNIVER_SHEET,snapshot),!0;default:throw new Error(`[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${type}.`)}}catch(err){throw err instanceof Error?err:new TypeError(`${err}`)}}async disposeInstance(params){return this._univerInstanceService.disposeUnit(params.unitID)}_applyMutation(mutationInfo){const{id,params:mutationParams}=mutationInfo;return this._commandService.syncExecuteCommand(id,mutationParams,{onlyLocal:!0,fromSync:!0})}},__name(_b,"WebWorkerRemoteInstanceService"),_b),exports2.WebWorkerRemoteInstanceService=__decorateClass$3([__decorateParam$3(0,core.IUniverInstanceService),__decorateParam$3(1,core.ICommandService),__decorateParam$3(2,core.ILogService)],exports2.WebWorkerRemoteInstanceService);function fromModule(module2){const handler=module2;return new class{call(method,args){const target=handler[method];if(typeof target=="function"){let res=target.apply(handler,[args]);return res instanceof Promise||(res=Promise.resolve(res)),res}throw new Error(`[RPC]: method not found for ${method}!`)}subscribe(eventMethod,args){const target=handler[eventMethod];if(typeof target=="function"){const res=target.apply(handler,args);return rxjs.isObservable(res)?res:rxjs.of(res)}throw new Error(`[RPC]: observable method not found for ${eventMethod}!`)}}}__name(fromModule,"fromModule");function toModule(channel){return new Proxy({},{get(_,propKey){if(propKey!=="dispose")return function(...args){return propertyIsEventSource(propKey)?channel.subscribe(propKey,args[0]):channel.call(propKey,args[0])}}})}__name(toModule,"toModule");function propertyIsEventSource(name){return name.endsWith("$")}__name(propertyIsEventSource,"propertyIsEventSource");const _ChannelClient=class _ChannelClient extends core.RxDisposable{constructor(_protocol){super();__publicField(this,"_initialized",new rxjs.BehaviorSubject(!1));__publicField(this,"_lastRequestCounter",0);__publicField(this,"_pendingRequests",new Map);this._protocol=_protocol,this._protocol.onMessage.pipe(operators.takeUntil(this.dispose$)).subscribe(message=>this._onMessage(message))}dispose(){this._pendingRequests.clear()}getChannel(channelName){const self2=this;return{call(method,args){return self2._disposed?Promise.reject():self2._remoteCall(channelName,method,args)},subscribe(eventMethod,args){if(self2._disposed)throw new Error("[ChannelClient]: client is disposed!");return self2._remoteSubscribe(channelName,eventMethod,args)}}}_whenReady(){return rxjs.firstValueFrom(this._initialized.pipe(operators.filter(v=>v),operators.take(1)))}async _remoteCall(channelName,method,args){await this._whenReady();const sequence=++this._lastRequestCounter,request={seq:sequence,type:100,channelName,method,args},client=this;return new Promise((resolve,reject)=>{const responseHandler={handle(response){switch(response.type){case 201:client._pendingRequests.delete(sequence),resolve(response.data);break;case 202:client._pendingRequests.delete(sequence),reject(response.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(sequence,responseHandler),this._sendRequest(request)})}_remoteSubscribe(channelName,method,args){return new rxjs.Observable(subscriber=>{let sequence=-1;return this._whenReady().then(()=>{sequence=++this._lastRequestCounter;const request={seq:sequence,type:101,channelName,method,args},responseHandler={handle(response){switch(response.type){case 300:subscriber.next(response.data);break;case 301:subscriber.error(response.data);break;case 302:subscriber.complete();break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(sequence,responseHandler),this._sendRequest(request)}),()=>{if(sequence===-1)return;const cancelSubscriptionRequest={type:102,seq:sequence,channelName,method};this._sendRequest(cancelSubscriptionRequest)}})}_sendRequest(request){this._protocol.send(request)}_onMessage(response){var _a2;switch(response.type){case 0:this._initialized.next(!0);break;case 201:case 202:case 300:case 302:case 301:(_a2=this._pendingRequests.get(response.seq))==null||_a2.handle(response);break}}};__name(_ChannelClient,"ChannelClient");let ChannelClient=_ChannelClient;const _ChannelServer=class _ChannelServer extends core.RxDisposable{constructor(_protocol){super();__publicField(this,"_channels",new Map);__publicField(this,"_subscriptions",new Map);this._protocol=_protocol,this._protocol.onMessage.pipe(operators.takeUntil(this.dispose$)).subscribe(message=>this._onRequest(message)),this._sendResponse({seq:-1,type:0})}dispose(){super.dispose(),this._subscriptions.clear(),this._channels.clear()}registerChannel(channelName,channel){this._channels.set(channelName,channel)}_onRequest(request){switch(request.type){case 100:this._onMethodCall(request);break;case 101:this._onSubscribe(request);break;case 102:this._onUnsubscribe(request);break}}_onMethodCall(request){const{channelName,method,args}=request,channel=this._channels.get(channelName);let promise;try{if(!channel)throw new Error(`[ChannelServer]: Channel ${channelName} not found!`);promise=channel.call(method,args)}catch(err){promise=Promise.reject(err)}promise.then(data=>{this._sendResponse({seq:request.seq,type:201,data})}).catch(err=>{err instanceof Error?this._sendResponse({seq:request.seq,type:202,data:err.message}):this._sendResponse({seq:request.seq,type:202,data:String(err)})})}_onSubscribe(request){const{channelName,seq}=request,channel=this._channels.get(channelName);try{if(!channel)throw new Error(`[ChannelServer]: Channel ${channelName} not found!`);const subscription=channel.subscribe(request.method,request.args).subscribe({next:__name(data=>{this._sendResponse({seq,type:300,data})},"next"),error:__name(err=>{this._sendResponse({seq,type:301,data:err.message}),this._sendResponse({seq,type:302})},"error"),complete:__name(()=>{this._sendResponse({seq,type:302})},"complete")});this._subscriptions.set(request.seq,subscription)}catch(err){err instanceof Error?this._sendResponse({seq:request.seq,type:301,data:err.message}):this._sendResponse({seq:request.seq,type:301,data:String(err)})}}_onUnsubscribe(request){const subscription=this._subscriptions.get(request.seq);subscription&&(subscription.unsubscribe(),this._subscriptions.delete(request.seq))}_sendResponse(response){this._protocol.send(response)}};__name(_ChannelServer,"ChannelServer");let ChannelServer=_ChannelServer;const IRPCChannelService=core.createIdentifier("IRPCChannelService"),_ChannelService=class _ChannelService{constructor(_messageProtocol){__publicField(this,"_client");__publicField(this,"_server");this._client=new ChannelClient(_messageProtocol),this._server=new ChannelServer(_messageProtocol)}dispose(){this._client.dispose(),this._server.dispose()}requestChannel(name){return this._client.getChannel(name)}registerChannel(name,channel){this._server.registerChannel(name,channel)}};__name(_ChannelService,"ChannelService");let ChannelService=_ChannelService;var __defProp$2=Object.defineProperty,__getOwnPropDesc$2=Object.getOwnPropertyDescriptor,__decorateClass$2=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$2(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$2(target,key,result),result},"__decorateClass$2"),__decorateParam$2=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$2");exports2.DataSyncPrimaryController=(_c=class extends core.RxDisposable{constructor(_injector,_commandService,_univerInstanceService,_rpcChannelService,_remoteSyncService){super();__publicField(this,"_remoteInstanceService");__publicField(this,"_syncingUnits",new Set);__publicField(this,"_syncingMutations",new Set);this._injector=_injector,this._commandService=_commandService,this._univerInstanceService=_univerInstanceService,this._rpcChannelService=_rpcChannelService,this._remoteSyncService=_remoteSyncService,this._initRPCChannels(),this._init()}registerSyncingMutations(mutation){this._syncingMutations.add(mutation.id)}syncUnit(unitId){return this._syncingUnits.add(unitId),core.toDisposable(()=>this._syncingUnits.delete(unitId))}_initRPCChannels(){this._rpcChannelService.registerChannel(RemoteSyncServiceName,fromModule(this._remoteSyncService)),this._injector.add([IRemoteInstanceService,{useFactory:__name(()=>toModule(this._rpcChannelService.requestChannel(RemoteInstanceServiceName)),"useFactory")}]),this._remoteInstanceService=this._injector.get(IRemoteInstanceService)}_init(){this._univerInstanceService.getTypeOfUnitAdded$(core.UniverInstanceType.UNIVER_SHEET).pipe(operators.takeUntil(this.dispose$)).subscribe(sheet=>{this._syncingUnits.add(sheet.getUnitId()),this._remoteInstanceService.createInstance({unitID:sheet.getUnitId(),type:core.UniverInstanceType.UNIVER_SHEET,snapshot:sheet.getSnapshot()})}),this._univerInstanceService.getTypeOfUnitDisposed$(core.UniverInstanceType.UNIVER_SHEET).pipe(operators.takeUntil(this.dispose$)).subscribe(workbook=>{this._syncingUnits.delete(workbook.getUnitId()),this._remoteInstanceService.disposeInstance({unitID:workbook.getUnitId()})}),this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo,options)=>{const{type,params,id}=commandInfo,unitId=(params==null?void 0:params.unitId)||"";type===core.CommandType.MUTATION&&(!unitId||this._syncingUnits.has(unitId))&&!(options!=null&&options.fromSync)&&this._syncingMutations.has(id)&&this._remoteInstanceService.syncMutation({mutationInfo:commandInfo})}))}},__name(_c,"DataSyncPrimaryController"),_c),exports2.DataSyncPrimaryController=__decorateClass$2([core.OnLifecycle(core.LifecycleStages.Starting,exports2.DataSyncPrimaryController),__decorateParam$2(0,core.Inject(core.Injector)),__decorateParam$2(1,core.ICommandService),__decorateParam$2(2,core.IUniverInstanceService),__decorateParam$2(3,IRPCChannelService),__decorateParam$2(4,IRemoteSyncService)],exports2.DataSyncPrimaryController);var __defProp$1=Object.defineProperty,__getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__decorateClass$1=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$1(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$1(target,key,result),result},"__decorateClass$1"),__decorateParam$1=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$1");exports2.DataSyncReplicaController=(_d=class extends core.Disposable{constructor(_injector,_remoteInstanceService,_commandService,_rpcChannelService){super();__publicField(this,"_remoteSyncService");this._injector=_injector,this._remoteInstanceService=_remoteInstanceService,this._commandService=_commandService,this._rpcChannelService=_rpcChannelService,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(RemoteInstanceServiceName,fromModule(this._remoteInstanceService)),this._injector.add([IRemoteSyncService,{useFactory:__name(()=>toModule(this._rpcChannelService.requestChannel(RemoteSyncServiceName)),"useFactory")}]),this._remoteSyncService=this._injector.get(IRemoteSyncService)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo,options)=>{commandInfo.type===core.CommandType.MUTATION&&!(options!=null&&options.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:commandInfo})}))}},__name(_d,"DataSyncReplicaController"),_d),exports2.DataSyncReplicaController=__decorateClass$1([core.OnLifecycle(core.LifecycleStages.Starting,exports2.DataSyncReplicaController),__decorateParam$1(0,core.Inject(core.Injector)),__decorateParam$1(1,IRemoteInstanceService),__decorateParam$1(2,core.ICommandService),__decorateParam$1(3,IRPCChannelService)],exports2.DataSyncReplicaController);function createWebWorkerMessagePortOnWorker(){return{send(message){postMessage(message)},onMessage:new rxjs.Observable(subscriber=>{const handler=__name(event=>{subscriber.next(event.data)},"handler");return addEventListener("message",handler),()=>removeEventListener("message",handler)}).pipe(rxjs.shareReplay(1))}}__name(createWebWorkerMessagePortOnWorker,"createWebWorkerMessagePortOnWorker");function createWebWorkerMessagePortOnMain(worker){return{send(message){worker.postMessage(message)},onMessage:new rxjs.Observable(subscriber=>{const handler=__name(event=>{subscriber.next(event.data)},"handler");return worker.addEventListener("message",handler),()=>worker.removeEventListener("message",handler)}).pipe(rxjs.shareReplay(1))}}__name(createWebWorkerMessagePortOnMain,"createWebWorkerMessagePortOnMain");var __defProp2=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp2(target,key,result),result},"__decorateClass"),__decorateParam=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam");exports2.UniverRPCMainThreadPlugin=(_e=class extends core.Plugin{constructor(_config,_injector){super();__publicField(this,"_internalWorker",null);this._config=_config,this._injector=_injector}dispose(){super.dispose(),this._internalWorker&&(this._internalWorker.terminate(),this._internalWorker=null)}onStarting(){const{workerURL}=this._config,worker=workerURL instanceof Worker?workerURL:new Worker(workerURL);this._internalWorker=workerURL instanceof Worker?null:worker;const messageProtocol=createWebWorkerMessagePortOnMain(worker);[[IRPCChannelService,{useFactory:__name(()=>new ChannelService(messageProtocol),"useFactory")}],[exports2.DataSyncPrimaryController],[IRemoteSyncService,{useClass:exports2.RemoteSyncPrimaryService}]].forEach(dependency=>this._injector.add(dependency)),this._injector.get(exports2.DataSyncPrimaryController)}},__name(_e,"UniverRPCMainThreadPlugin"),__publicField(_e,"pluginName","UNIVER_RPC_MAIN_THREAD_PLUGIN"),_e),exports2.UniverRPCMainThreadPlugin=__decorateClass([__decorateParam(1,core.Inject(core.Injector))],exports2.UniverRPCMainThreadPlugin),exports2.UniverRPCWorkerThreadPlugin=(_f=class extends core.Plugin{constructor(_config,_injector){super(),this._config=_config,this._injector=_injector}onStarting(){[[exports2.DataSyncReplicaController],[IRPCChannelService,{useFactory:__name(()=>new ChannelService(createWebWorkerMessagePortOnWorker()),"useFactory")}],[IRemoteInstanceService,{useClass:exports2.WebWorkerRemoteInstanceService}]].forEach(dependency=>this._injector.add(dependency)),this._injector.get(exports2.DataSyncReplicaController)}},__name(_f,"UniverRPCWorkerThreadPlugin"),__publicField(_f,"pluginName","UNIVER_RPC_WORKER_THREAD_PLUGIN"),_f),exports2.UniverRPCWorkerThreadPlugin=__decorateClass([__decorateParam(1,core.Inject(core.Injector))],exports2.UniverRPCWorkerThreadPlugin),exports2.ChannelClient=ChannelClient,exports2.ChannelServer=ChannelServer,exports2.ChannelService=ChannelService,exports2.IRPCChannelService=IRPCChannelService,exports2.IRemoteInstanceService=IRemoteInstanceService,exports2.IRemoteSyncService=IRemoteSyncService,exports2.RemoteInstanceServiceName=RemoteInstanceServiceName,exports2.RemoteSyncServiceName=RemoteSyncServiceName,exports2.fromModule=fromModule,exports2.toModule=toModule,Object.defineProperty(exports2,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@univerjs/rpc",
3
- "version": "0.2.7",
3
+ "version": "0.2.9",
4
4
  "private": false,
5
5
  "author": "DreamNum <developer@univer.ai>",
6
6
  "license": "Apache-2.0",
@@ -46,15 +46,15 @@
46
46
  ],
47
47
  "peerDependencies": {
48
48
  "rxjs": ">=7.0.0",
49
- "@univerjs/core": "0.2.7"
49
+ "@univerjs/core": "0.2.9"
50
50
  },
51
51
  "devDependencies": {
52
52
  "rxjs": "^7.8.1",
53
53
  "typescript": "^5.5.4",
54
- "vite": "^5.3.5",
54
+ "vite": "^5.4.0",
55
55
  "vitest": "^2.0.5",
56
- "@univerjs/shared": "0.2.7",
57
- "@univerjs/core": "0.2.7"
56
+ "@univerjs/core": "0.2.9",
57
+ "@univerjs/shared": "0.2.9"
58
58
  },
59
59
  "univerSpace": {
60
60
  ".": {