New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@univerjs/rpc

Package Overview
Dependencies
Maintainers
0
Versions
268
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@univerjs/rpc - npm Package Compare versions

Comparing version 0.2.4 to 0.2.5

2

lib/cjs/index.js

@@ -1,1 +0,1 @@

"use strict";var $=Object.defineProperty;var x=(i,n,e)=>n in i?$(i,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[n]=e;var l=(i,n,e)=>x(i,typeof n!="symbol"?n+"":n,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("@univerjs/core"),u=require("@wendellhu/redi"),d=require("rxjs/operators"),_=require("rxjs");var N=Object.defineProperty,L=Object.getOwnPropertyDescriptor,q=(i,n,e,t)=>{for(var s=t>1?void 0:t?L(n,e):n,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=(t?c(n,e,s):c(s))||s);return t&&s&&N(n,e,s),s},R=(i,n)=>(e,t)=>n(e,t,i);const b="rpc.remote-sync.service",y=u.createIdentifier(b);exports.RemoteSyncPrimaryService=class{constructor(n){this._commandService=n}async syncMutation(n){return this._commandService.syncExecuteCommand(n.mutationInfo.id,n.mutationInfo.params,{onlyLocal:!0,fromSync:!0})}};exports.RemoteSyncPrimaryService=q([R(0,a.ICommandService)],exports.RemoteSyncPrimaryService);const f="univer.remote-instance-service",m=u.createIdentifier(f);exports.WebWorkerRemoteInstanceService=class{constructor(n,e,t){this._univerInstanceService=n,this._commandService=e,this._logService=t}whenReady(){return Promise.resolve(!0)}async syncMutation(n){return this._applyMutation(n.mutationInfo)}async createInstance(n){const{type:e,snapshot:t}=n;try{switch(e){case a.UniverInstanceType.UNIVER_SHEET:return this._univerInstanceService.createUnit(a.UniverInstanceType.UNIVER_SHEET,t),!0;default:throw new Error(`[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${e}.`)}}catch(s){throw s instanceof Error?s:new TypeError(`${s}`)}}async disposeInstance(n){return this._univerInstanceService.disposeUnit(n.unitID)}_applyMutation(n){const{id:e,params:t}=n;return this._commandService.syncExecuteCommand(e,t,{onlyLocal:!0,fromSync:!0})}};exports.WebWorkerRemoteInstanceService=q([R(0,a.IUniverInstanceService),R(1,a.ICommandService),R(2,a.ILogService)],exports.WebWorkerRemoteInstanceService);function U(i){const n=i;return new class{call(e,t){const s=n[e];if(typeof s=="function"){let r=s.apply(n,[t]);return r instanceof Promise||(r=Promise.resolve(r)),r}throw new Error(`[RPC]: method not found for ${e}!`)}subscribe(e,t){const s=n[e];if(typeof s=="function"){const r=s.apply(n,t);return _.isObservable(r)?r:_.of(r)}throw new Error(`[RPC]: observable method not found for ${e}!`)}}}function E(i){return new Proxy({},{get(n,e){if(e!=="dispose")return function(...t){return k(e)?i.subscribe(e,t[0]):i.call(e,t[0])}}})}function k(i){return i.endsWith("$")}class D extends a.RxDisposable{constructor(e){super();l(this,"_initialized",new _.BehaviorSubject(!1));l(this,"_lastRequestCounter",0);l(this,"_pendingRequests",new Map);this._protocol=e,this._protocol.onMessage.pipe(d.takeUntil(this.dispose$)).subscribe(t=>this._onMessage(t))}dispose(){this._pendingRequests.clear()}getChannel(e){const t=this;return{call(s,r){return t._disposed?Promise.reject():t._remoteCall(e,s,r)},subscribe(s,r){if(t._disposed)throw new Error("[ChannelClient]: client is disposed!");return t._remoteSubscribe(e,s,r)}}}_whenReady(){return _.firstValueFrom(this._initialized.pipe(d.filter(e=>e),d.take(1)))}async _remoteCall(e,t,s){await this._whenReady();const r=++this._lastRequestCounter,h={seq:r,type:100,channelName:e,method:t,args:s},o=this;return new Promise((g,p)=>{const W={handle(I){switch(I.type){case 201:o._pendingRequests.delete(r),g(I.data);break;case 202:o._pendingRequests.delete(r),p(I.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(r,W),this._sendRequest(h)})}_remoteSubscribe(e,t,s){return new _.Observable(r=>{let c=-1;return this._whenReady().then(()=>{c=++this._lastRequestCounter;const o={seq:c,type:101,channelName:e,method:t,args:s},g={handle(p){switch(p.type){case 300:r.next(p.data);break;case 301:r.error(p.data);break;case 302:r.complete();break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(c,g),this._sendRequest(o)}),()=>{if(c===-1)return;const h={type:102,seq:c,channelName:e,method:t};this._sendRequest(h)}})}_sendRequest(e){this._protocol.send(e)}_onMessage(e){var t;switch(e.type){case 0:this._initialized.next(!0);break;case 201:case 202:case 300:case 302:case 301:(t=this._pendingRequests.get(e.seq))==null||t.handle(e);break}}}class O extends a.RxDisposable{constructor(e){super();l(this,"_channels",new Map);l(this,"_subscriptions",new Map);this._protocol=e,this._protocol.onMessage.pipe(d.takeUntil(this.dispose$)).subscribe(t=>this._onRequest(t)),this._sendResponse({seq:-1,type:0})}dispose(){super.dispose(),this._subscriptions.clear(),this._channels.clear()}registerChannel(e,t){this._channels.set(e,t)}_onRequest(e){switch(e.type){case 100:this._onMethodCall(e);break;case 101:this._onSubscribe(e);break;case 102:this._onUnsubscribe(e);break}}_onMethodCall(e){const{channelName:t,method:s,args:r}=e,c=this._channels.get(t);let h;try{if(!c)throw new Error(`[ChannelServer]: Channel ${t} not found!`);h=c.call(s,r)}catch(o){h=Promise.reject(o)}h.then(o=>{this._sendResponse({seq:e.seq,type:201,data:o})}).catch(o=>{o instanceof Error?this._sendResponse({seq:e.seq,type:202,data:o.message}):this._sendResponse({seq:e.seq,type:202,data:String(o)})})}_onSubscribe(e){const{channelName:t,seq:s}=e,r=this._channels.get(t);try{if(!r)throw new Error(`[ChannelServer]: Channel ${t} not found!`);const h=r.subscribe(e.method,e.args).subscribe({next:o=>{this._sendResponse({seq:s,type:300,data:o})},error:o=>{this._sendResponse({seq:s,type:301,data:o.message}),this._sendResponse({seq:s,type:302})},complete:()=>{this._sendResponse({seq:s,type:302})}});this._subscriptions.set(e.seq,h)}catch(c){c instanceof Error?this._sendResponse({seq:e.seq,type:301,data:c.message}):this._sendResponse({seq:e.seq,type:301,data:String(c)})}}_onUnsubscribe(e){const t=this._subscriptions.get(e.seq);t&&(t.unsubscribe(),this._subscriptions.delete(e.seq))}_sendResponse(e){this._protocol.send(e)}}const S=u.createIdentifier("IRPCChannelService");class M{constructor(n){l(this,"_client");l(this,"_server");this._client=new D(n),this._server=new O(n)}dispose(){this._client.dispose(),this._server.dispose()}requestChannel(n){return this._client.getChannel(n)}registerChannel(n,e){this._server.registerChannel(n,e)}}var H=Object.defineProperty,V=Object.getOwnPropertyDescriptor,A=(i,n,e,t)=>{for(var s=t>1?void 0:t?V(n,e):n,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=(t?c(n,e,s):c(s))||s);return t&&s&&H(n,e,s),s},v=(i,n)=>(e,t)=>n(e,t,i);exports.DataSyncPrimaryController=class extends a.RxDisposable{constructor(e,t,s,r,c){super();l(this,"_remoteInstanceService");l(this,"_syncingUnits",new Set);l(this,"_syncingMutations",new Set);this._injector=e,this._commandService=t,this._univerInstanceService=s,this._rpcChannelService=r,this._remoteSyncService=c,this._initRPCChannels(),this._init()}registerSyncingMutations(e){this._syncingMutations.add(e.id)}syncUnit(e){return this._syncingUnits.add(e),a.toDisposable(()=>this._syncingUnits.delete(e))}_initRPCChannels(){this._rpcChannelService.registerChannel(b,U(this._remoteSyncService)),this._injector.add([m,{useFactory:()=>E(this._rpcChannelService.requestChannel(f))}]),this._remoteInstanceService=this._injector.get(m)}_init(){this._univerInstanceService.getTypeOfUnitAdded$(a.UniverInstanceType.UNIVER_SHEET).pipe(d.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.add(e.getUnitId()),this._remoteInstanceService.createInstance({unitID:e.getUnitId(),type:a.UniverInstanceType.UNIVER_SHEET,snapshot:e.getSnapshot()})}),this._univerInstanceService.getTypeOfUnitDisposed$(a.UniverInstanceType.UNIVER_SHEET).pipe(d.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.delete(e.getUnitId()),this._remoteInstanceService.disposeInstance({unitID:e.getUnitId()})}),this.disposeWithMe(this._commandService.onCommandExecuted((e,t)=>{const{type:s,params:r,id:c}=e,h=(r==null?void 0:r.unitId)||"";s===a.CommandType.MUTATION&&(!h||this._syncingUnits.has(h))&&!(t!=null&&t.fromSync)&&this._syncingMutations.has(c)&&this._remoteInstanceService.syncMutation({mutationInfo:e})}))}};exports.DataSyncPrimaryController=A([a.OnLifecycle(a.LifecycleStages.Starting,exports.DataSyncPrimaryController),v(0,u.Inject(u.Injector)),v(1,a.ICommandService),v(2,a.IUniverInstanceService),v(3,S),v(4,y)],exports.DataSyncPrimaryController);var F=Object.defineProperty,z=Object.getOwnPropertyDescriptor,G=(i,n,e,t)=>{for(var s=t>1?void 0:t?z(n,e):n,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=(t?c(n,e,s):c(s))||s);return t&&s&&F(n,e,s),s},C=(i,n)=>(e,t)=>n(e,t,i);exports.DataSyncReplicaController=class extends a.Disposable{constructor(e,t,s,r){super();l(this,"_remoteSyncService");this._injector=e,this._remoteInstanceService=t,this._commandService=s,this._rpcChannelService=r,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(f,U(this._remoteInstanceService)),this._injector.add([y,{useFactory:()=>E(this._rpcChannelService.requestChannel(b))}]),this._remoteSyncService=this._injector.get(y)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((e,t)=>{e.type===a.CommandType.MUTATION&&!(t!=null&&t.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:e})}))}};exports.DataSyncReplicaController=G([a.OnLifecycle(a.LifecycleStages.Starting,exports.DataSyncReplicaController),C(0,u.Inject(u.Injector)),C(1,m),C(2,a.ICommandService),C(3,S)],exports.DataSyncReplicaController);function B(){return{send(i){postMessage(i)},onMessage:new _.Observable(i=>{const n=e=>{i.next(e.data)};return addEventListener("message",n),()=>removeEventListener("message",n)}).pipe(_.shareReplay(1))}}function J(i){return{send(n){i.postMessage(n)},onMessage:new _.Observable(n=>{const e=t=>{n.next(t.data)};return i.addEventListener("message",e),()=>i.removeEventListener("message",e)}).pipe(_.shareReplay(1))}}var Q=Object.defineProperty,X=Object.getOwnPropertyDescriptor,T=(i,n,e,t)=>{for(var s=t>1?void 0:t?X(n,e):n,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=(t?c(n,e,s):c(s))||s);return t&&s&&Q(n,e,s),s},j=(i,n)=>(e,t)=>n(e,t,i),P;exports.UniverRPCMainThreadPlugin=(P=class extends a.Plugin{constructor(n,e){super(),this._config=n,this._injector=e}async onStarting(n){const{workerURL:e}=this._config,t=e instanceof Worker?e:new Worker(e),s=J(t);[[S,{useFactory:()=>new M(s)}],[exports.DataSyncPrimaryController],[y,{useClass:exports.RemoteSyncPrimaryService}]].forEach(c=>n.add(c)),n.get(exports.DataSyncPrimaryController)}},l(P,"pluginName","UNIVER_RPC_MAIN_THREAD_PLUGIN"),P);exports.UniverRPCMainThreadPlugin=T([j(1,u.Inject(u.Injector))],exports.UniverRPCMainThreadPlugin);var w;exports.UniverRPCWorkerThreadPlugin=(w=class extends a.Plugin{constructor(n,e){super(),this._config=n,this._injector=e}onStarting(n){[[exports.DataSyncReplicaController],[S,{useFactory:()=>new M(B())}],[m,{useClass:exports.WebWorkerRemoteInstanceService}]].forEach(e=>n.add(e)),n.get(exports.DataSyncReplicaController)}},l(w,"pluginName","UNIVER_RPC_WORKER_THREAD_PLUGIN"),w);exports.UniverRPCWorkerThreadPlugin=T([j(1,u.Inject(u.Injector))],exports.UniverRPCWorkerThreadPlugin);exports.ChannelClient=D;exports.ChannelServer=O;exports.ChannelService=M;exports.IRPCChannelService=S;exports.IRemoteInstanceService=m;exports.IRemoteSyncService=y;exports.RemoteInstanceServiceName=f;exports.RemoteSyncServiceName=b;exports.fromModule=U;exports.toModule=E;
"use strict";var W=Object.defineProperty;var $=(i,n,e)=>n in i?W(i,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[n]=e;var l=(i,n,e)=>$(i,typeof n!="symbol"?n+"":n,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("@univerjs/core"),_=require("rxjs/operators"),u=require("rxjs");var x=Object.defineProperty,N=Object.getOwnPropertyDescriptor,M=(i,n,e,t)=>{for(var s=t>1?void 0:t?N(n,e):n,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=(t?c(n,e,s):c(s))||s);return t&&s&&x(n,e,s),s},C=(i,n)=>(e,t)=>n(e,t,i);const R="rpc.remote-sync.service",v=a.createIdentifier(R);exports.RemoteSyncPrimaryService=class{constructor(n){this._commandService=n}async syncMutation(n){return this._commandService.syncExecuteCommand(n.mutationInfo.id,n.mutationInfo.params,{onlyLocal:!0,fromSync:!0})}};exports.RemoteSyncPrimaryService=M([C(0,a.ICommandService)],exports.RemoteSyncPrimaryService);const b="univer.remote-instance-service",y=a.createIdentifier(b);exports.WebWorkerRemoteInstanceService=class{constructor(n,e,t){this._univerInstanceService=n,this._commandService=e,this._logService=t}whenReady(){return Promise.resolve(!0)}async syncMutation(n){return this._applyMutation(n.mutationInfo)}async createInstance(n){const{type:e,snapshot:t}=n;try{switch(e){case a.UniverInstanceType.UNIVER_SHEET:return this._univerInstanceService.createUnit(a.UniverInstanceType.UNIVER_SHEET,t),!0;default:throw new Error(`[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${e}.`)}}catch(s){throw s instanceof Error?s:new TypeError(`${s}`)}}async disposeInstance(n){return this._univerInstanceService.disposeUnit(n.unitID)}_applyMutation(n){const{id:e,params:t}=n;return this._commandService.syncExecuteCommand(e,t,{onlyLocal:!0,fromSync:!0})}};exports.WebWorkerRemoteInstanceService=M([C(0,a.IUniverInstanceService),C(1,a.ICommandService),C(2,a.ILogService)],exports.WebWorkerRemoteInstanceService);function w(i){const n=i;return new class{call(e,t){const s=n[e];if(typeof s=="function"){let r=s.apply(n,[t]);return r instanceof Promise||(r=Promise.resolve(r)),r}throw new Error(`[RPC]: method not found for ${e}!`)}subscribe(e,t){const s=n[e];if(typeof s=="function"){const r=s.apply(n,t);return u.isObservable(r)?r:u.of(r)}throw new Error(`[RPC]: observable method not found for ${e}!`)}}}function U(i){return new Proxy({},{get(n,e){if(e!=="dispose")return function(...t){return L(e)?i.subscribe(e,t[0]):i.call(e,t[0])}}})}function L(i){return i.endsWith("$")}class q extends a.RxDisposable{constructor(e){super();l(this,"_initialized",new u.BehaviorSubject(!1));l(this,"_lastRequestCounter",0);l(this,"_pendingRequests",new Map);this._protocol=e,this._protocol.onMessage.pipe(_.takeUntil(this.dispose$)).subscribe(t=>this._onMessage(t))}dispose(){this._pendingRequests.clear()}getChannel(e){const t=this;return{call(s,r){return t._disposed?Promise.reject():t._remoteCall(e,s,r)},subscribe(s,r){if(t._disposed)throw new Error("[ChannelClient]: client is disposed!");return t._remoteSubscribe(e,s,r)}}}_whenReady(){return u.firstValueFrom(this._initialized.pipe(_.filter(e=>e),_.take(1)))}async _remoteCall(e,t,s){await this._whenReady();const r=++this._lastRequestCounter,h={seq:r,type:100,channelName:e,method:t,args:s},o=this;return new Promise((f,d)=>{const j={handle(g){switch(g.type){case 201:o._pendingRequests.delete(r),f(g.data);break;case 202:o._pendingRequests.delete(r),d(g.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(r,j),this._sendRequest(h)})}_remoteSubscribe(e,t,s){return new u.Observable(r=>{let c=-1;return this._whenReady().then(()=>{c=++this._lastRequestCounter;const o={seq:c,type:101,channelName:e,method:t,args:s},f={handle(d){switch(d.type){case 300:r.next(d.data);break;case 301:r.error(d.data);break;case 302:r.complete();break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(c,f),this._sendRequest(o)}),()=>{if(c===-1)return;const h={type:102,seq:c,channelName:e,method:t};this._sendRequest(h)}})}_sendRequest(e){this._protocol.send(e)}_onMessage(e){var t;switch(e.type){case 0:this._initialized.next(!0);break;case 201:case 202:case 300:case 302:case 301:(t=this._pendingRequests.get(e.seq))==null||t.handle(e);break}}}class D extends a.RxDisposable{constructor(e){super();l(this,"_channels",new Map);l(this,"_subscriptions",new Map);this._protocol=e,this._protocol.onMessage.pipe(_.takeUntil(this.dispose$)).subscribe(t=>this._onRequest(t)),this._sendResponse({seq:-1,type:0})}dispose(){super.dispose(),this._subscriptions.clear(),this._channels.clear()}registerChannel(e,t){this._channels.set(e,t)}_onRequest(e){switch(e.type){case 100:this._onMethodCall(e);break;case 101:this._onSubscribe(e);break;case 102:this._onUnsubscribe(e);break}}_onMethodCall(e){const{channelName:t,method:s,args:r}=e,c=this._channels.get(t);let h;try{if(!c)throw new Error(`[ChannelServer]: Channel ${t} not found!`);h=c.call(s,r)}catch(o){h=Promise.reject(o)}h.then(o=>{this._sendResponse({seq:e.seq,type:201,data:o})}).catch(o=>{o instanceof Error?this._sendResponse({seq:e.seq,type:202,data:o.message}):this._sendResponse({seq:e.seq,type:202,data:String(o)})})}_onSubscribe(e){const{channelName:t,seq:s}=e,r=this._channels.get(t);try{if(!r)throw new Error(`[ChannelServer]: Channel ${t} not found!`);const h=r.subscribe(e.method,e.args).subscribe({next:o=>{this._sendResponse({seq:s,type:300,data:o})},error:o=>{this._sendResponse({seq:s,type:301,data:o.message}),this._sendResponse({seq:s,type:302})},complete:()=>{this._sendResponse({seq:s,type:302})}});this._subscriptions.set(e.seq,h)}catch(c){c instanceof Error?this._sendResponse({seq:e.seq,type:301,data:c.message}):this._sendResponse({seq:e.seq,type:301,data:String(c)})}}_onUnsubscribe(e){const t=this._subscriptions.get(e.seq);t&&(t.unsubscribe(),this._subscriptions.delete(e.seq))}_sendResponse(e){this._protocol.send(e)}}const m=a.createIdentifier("IRPCChannelService");class E{constructor(n){l(this,"_client");l(this,"_server");this._client=new q(n),this._server=new D(n)}dispose(){this._client.dispose(),this._server.dispose()}requestChannel(n){return this._client.getChannel(n)}registerChannel(n,e){this._server.registerChannel(n,e)}}var k=Object.defineProperty,H=Object.getOwnPropertyDescriptor,V=(i,n,e,t)=>{for(var s=t>1?void 0:t?H(n,e):n,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=(t?c(n,e,s):c(s))||s);return t&&s&&k(n,e,s),s},p=(i,n)=>(e,t)=>n(e,t,i);exports.DataSyncPrimaryController=class extends a.RxDisposable{constructor(e,t,s,r,c){super();l(this,"_remoteInstanceService");l(this,"_syncingUnits",new Set);l(this,"_syncingMutations",new Set);this._injector=e,this._commandService=t,this._univerInstanceService=s,this._rpcChannelService=r,this._remoteSyncService=c,this._initRPCChannels(),this._init()}registerSyncingMutations(e){this._syncingMutations.add(e.id)}syncUnit(e){return this._syncingUnits.add(e),a.toDisposable(()=>this._syncingUnits.delete(e))}_initRPCChannels(){this._rpcChannelService.registerChannel(R,w(this._remoteSyncService)),this._injector.add([y,{useFactory:()=>U(this._rpcChannelService.requestChannel(b))}]),this._remoteInstanceService=this._injector.get(y)}_init(){this._univerInstanceService.getTypeOfUnitAdded$(a.UniverInstanceType.UNIVER_SHEET).pipe(_.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.add(e.getUnitId()),this._remoteInstanceService.createInstance({unitID:e.getUnitId(),type:a.UniverInstanceType.UNIVER_SHEET,snapshot:e.getSnapshot()})}),this._univerInstanceService.getTypeOfUnitDisposed$(a.UniverInstanceType.UNIVER_SHEET).pipe(_.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.delete(e.getUnitId()),this._remoteInstanceService.disposeInstance({unitID:e.getUnitId()})}),this.disposeWithMe(this._commandService.onCommandExecuted((e,t)=>{const{type:s,params:r,id:c}=e,h=(r==null?void 0:r.unitId)||"";s===a.CommandType.MUTATION&&(!h||this._syncingUnits.has(h))&&!(t!=null&&t.fromSync)&&this._syncingMutations.has(c)&&this._remoteInstanceService.syncMutation({mutationInfo:e})}))}};exports.DataSyncPrimaryController=V([a.OnLifecycle(a.LifecycleStages.Starting,exports.DataSyncPrimaryController),p(0,a.Inject(a.Injector)),p(1,a.ICommandService),p(2,a.IUniverInstanceService),p(3,m),p(4,v)],exports.DataSyncPrimaryController);var A=Object.defineProperty,F=Object.getOwnPropertyDescriptor,z=(i,n,e,t)=>{for(var s=t>1?void 0:t?F(n,e):n,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=(t?c(n,e,s):c(s))||s);return t&&s&&A(n,e,s),s},S=(i,n)=>(e,t)=>n(e,t,i);exports.DataSyncReplicaController=class extends a.Disposable{constructor(e,t,s,r){super();l(this,"_remoteSyncService");this._injector=e,this._remoteInstanceService=t,this._commandService=s,this._rpcChannelService=r,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(b,w(this._remoteInstanceService)),this._injector.add([v,{useFactory:()=>U(this._rpcChannelService.requestChannel(R))}]),this._remoteSyncService=this._injector.get(v)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((e,t)=>{e.type===a.CommandType.MUTATION&&!(t!=null&&t.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:e})}))}};exports.DataSyncReplicaController=z([a.OnLifecycle(a.LifecycleStages.Starting,exports.DataSyncReplicaController),S(0,a.Inject(a.Injector)),S(1,y),S(2,a.ICommandService),S(3,m)],exports.DataSyncReplicaController);function G(){return{send(i){postMessage(i)},onMessage:new u.Observable(i=>{const n=e=>{i.next(e.data)};return addEventListener("message",n),()=>removeEventListener("message",n)}).pipe(u.shareReplay(1))}}function B(i){return{send(n){i.postMessage(n)},onMessage:new u.Observable(n=>{const e=t=>{n.next(t.data)};return i.addEventListener("message",e),()=>i.removeEventListener("message",e)}).pipe(u.shareReplay(1))}}var J=Object.defineProperty,Q=Object.getOwnPropertyDescriptor,O=(i,n,e,t)=>{for(var s=t>1?void 0:t?Q(n,e):n,r=i.length-1,c;r>=0;r--)(c=i[r])&&(s=(t?c(n,e,s):c(s))||s);return t&&s&&J(n,e,s),s},T=(i,n)=>(e,t)=>n(e,t,i),I;exports.UniverRPCMainThreadPlugin=(I=class extends a.Plugin{constructor(n,e){super(),this._config=n,this._injector=e}async onStarting(n){const{workerURL:e}=this._config,t=e instanceof Worker?e:new Worker(e),s=B(t);[[m,{useFactory:()=>new E(s)}],[exports.DataSyncPrimaryController],[v,{useClass:exports.RemoteSyncPrimaryService}]].forEach(c=>n.add(c)),n.get(exports.DataSyncPrimaryController)}},l(I,"pluginName","UNIVER_RPC_MAIN_THREAD_PLUGIN"),I);exports.UniverRPCMainThreadPlugin=O([T(1,a.Inject(a.Injector))],exports.UniverRPCMainThreadPlugin);var P;exports.UniverRPCWorkerThreadPlugin=(P=class extends a.Plugin{constructor(n,e){super(),this._config=n,this._injector=e}onStarting(n){[[exports.DataSyncReplicaController],[m,{useFactory:()=>new E(G())}],[y,{useClass:exports.WebWorkerRemoteInstanceService}]].forEach(e=>n.add(e)),n.get(exports.DataSyncReplicaController)}},l(P,"pluginName","UNIVER_RPC_WORKER_THREAD_PLUGIN"),P);exports.UniverRPCWorkerThreadPlugin=O([T(1,a.Inject(a.Injector))],exports.UniverRPCWorkerThreadPlugin);exports.ChannelClient=q;exports.ChannelServer=D;exports.ChannelService=E;exports.IRPCChannelService=m;exports.IRemoteInstanceService=y;exports.IRemoteSyncService=v;exports.RemoteInstanceServiceName=b;exports.RemoteSyncServiceName=R;exports.fromModule=w;exports.toModule=U;
var X = Object.defineProperty;
var Y = (n, t, e) => t in n ? X(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e;
var a = (n, t, e) => Y(n, typeof t != "symbol" ? t + "" : t, e);
import { UniverInstanceType as u, ICommandService as b, IUniverInstanceService as N, ILogService as Z, RxDisposable as q, OnLifecycle as W, LifecycleStages as L, toDisposable as K, CommandType as H, Disposable as ee, Plugin as V } from "@univerjs/core";
import { createIdentifier as O, Inject as g, Injector as C } from "@wendellhu/redi";
var o = (n, t, e) => Y(n, typeof t != "symbol" ? t + "" : t, e);
import { createIdentifier as q, UniverInstanceType as u, ICommandService as b, IUniverInstanceService as N, ILogService as Z, RxDisposable as O, OnLifecycle as W, LifecycleStages as L, Inject as g, Injector as C, toDisposable as K, CommandType as H, Disposable as ee, Plugin as V } from "@univerjs/core";
import { takeUntil as y, filter as te, take as se } from "rxjs/operators";
import { isObservable as ne, of as re, BehaviorSubject as ie, firstValueFrom as ce, Observable as $, shareReplay as A } from "rxjs";
var oe = Object.defineProperty, ae = Object.getOwnPropertyDescriptor, F = (n, t, e, s) => {
for (var r = s > 1 ? void 0 : s ? ae(t, e) : t, i = n.length - 1, c; i >= 0; i--)
var ae = Object.defineProperty, oe = Object.getOwnPropertyDescriptor, F = (n, t, e, s) => {
for (var r = s > 1 ? void 0 : s ? oe(t, e) : t, i = n.length - 1, c; i >= 0; i--)
(c = n[i]) && (r = (s ? c(t, e, r) : c(r)) || r);
return s && r && oe(t, e, r), r;
return s && r && ae(t, e, r), r;
}, m = (n, t) => (e, s) => t(e, s, n);
const j = "rpc.remote-sync.service", f = O(j);
const j = "rpc.remote-sync.service", f = q(j);
let U = class {

@@ -28,3 +27,3 @@ constructor(n) {

], U);
const D = "univer.remote-instance-service", S = O(D);
const D = "univer.remote-instance-service", S = q(D);
let M = class {

@@ -105,8 +104,8 @@ constructor(n, t, e) {

}
class _e extends q {
class _e extends O {
constructor(e) {
super();
a(this, "_initialized", new ie(!1));
a(this, "_lastRequestCounter", 0);
a(this, "_pendingRequests", /* @__PURE__ */ new Map());
o(this, "_initialized", new ie(!1));
o(this, "_lastRequestCounter", 0);
o(this, "_pendingRequests", /* @__PURE__ */ new Map());
this._protocol = e, this._protocol.onMessage.pipe(y(this.dispose$)).subscribe((s) => this._onMessage(s));

@@ -140,3 +139,3 @@ }

await this._whenReady();
const i = ++this._lastRequestCounter, h = { seq: i, type: 100, channelName: e, method: s, args: r }, o = this;
const i = ++this._lastRequestCounter, h = { seq: i, type: 100, channelName: e, method: s, args: r }, a = this;
return new Promise((I, _) => {

@@ -147,6 +146,6 @@ const Q = {

case 201:
o._pendingRequests.delete(i), I(w.data);
a._pendingRequests.delete(i), I(w.data);
break;
case 202:
o._pendingRequests.delete(i), _(w.data);
a._pendingRequests.delete(i), _(w.data);
break;

@@ -166,3 +165,3 @@ default:

c = ++this._lastRequestCounter;
const o = { seq: c, type: 101, channelName: e, method: s, args: r }, I = {
const a = { seq: c, type: 101, channelName: e, method: s, args: r }, I = {
handle(_) {

@@ -184,3 +183,3 @@ switch (_.type) {

};
this._pendingRequests.set(c, I), this._sendRequest(o);
this._pendingRequests.set(c, I), this._sendRequest(a);
}), () => {

@@ -218,7 +217,7 @@ if (c === -1)

}
class le extends q {
class le extends O {
constructor(e) {
super();
a(this, "_channels", /* @__PURE__ */ new Map());
a(this, "_subscriptions", /* @__PURE__ */ new Map());
o(this, "_channels", /* @__PURE__ */ new Map());
o(this, "_subscriptions", /* @__PURE__ */ new Map());
this._protocol = e, this._protocol.onMessage.pipe(y(this.dispose$)).subscribe((s) => this._onRequest(s)), this._sendResponse({

@@ -256,9 +255,9 @@ seq: -1,

h = c.call(r, i);
} catch (o) {
h = Promise.reject(o);
} catch (a) {
h = Promise.reject(a);
}
h.then((o) => {
this._sendResponse({ seq: e.seq, type: 201, data: o });
}).catch((o) => {
o instanceof Error ? this._sendResponse({ seq: e.seq, type: 202, data: o.message }) : this._sendResponse({ seq: e.seq, type: 202, data: String(o) });
h.then((a) => {
this._sendResponse({ seq: e.seq, type: 201, data: a });
}).catch((a) => {
a instanceof Error ? this._sendResponse({ seq: e.seq, type: 202, data: a.message }) : this._sendResponse({ seq: e.seq, type: 202, data: String(a) });
});

@@ -272,7 +271,7 @@ }

const h = i.subscribe(e.method, e.args).subscribe({
next: (o) => {
this._sendResponse({ seq: r, type: 300, data: o });
next: (a) => {
this._sendResponse({ seq: r, type: 300, data: a });
},
error: (o) => {
this._sendResponse({ seq: r, type: 301, data: o.message }), this._sendResponse({
error: (a) => {
this._sendResponse({ seq: r, type: 301, data: a.message }), this._sendResponse({
seq: r,

@@ -304,7 +303,7 @@ type: 302

}
const R = O("IRPCChannelService");
const R = q("IRPCChannelService");
class B {
constructor(t) {
a(this, "_client");
a(this, "_server");
o(this, "_client");
o(this, "_server");
this._client = new _e(t), this._server = new le(t);

@@ -327,8 +326,8 @@ }

}, l = (n, t) => (e, s) => t(e, s, n);
let p = class extends q {
let p = class extends O {
constructor(t, e, s, r, i) {
super();
a(this, "_remoteInstanceService");
a(this, "_syncingUnits", /* @__PURE__ */ new Set());
a(this, "_syncingMutations", /* @__PURE__ */ new Set());
o(this, "_remoteInstanceService");
o(this, "_syncingUnits", /* @__PURE__ */ new Set());
o(this, "_syncingMutations", /* @__PURE__ */ new Set());
this._injector = t, this._commandService = e, this._univerInstanceService = s, this._rpcChannelService = r, this._remoteSyncService = i, this._initRPCChannels(), this._init();

@@ -388,3 +387,3 @@ }

super();
a(this, "_remoteSyncService");
o(this, "_remoteSyncService");
this._injector = t, this._remoteInstanceService = e, this._commandService = s, this._rpcChannelService = r, this._initRPCChannels(), this._init();

@@ -464,3 +463,3 @@ }

}
}, a(P, "pluginName", "UNIVER_RPC_MAIN_THREAD_PLUGIN"), P);
}, o(P, "pluginName", "UNIVER_RPC_MAIN_THREAD_PLUGIN"), P);
x = k([

@@ -486,3 +485,3 @@ J(1, g(C))

}
}, a(E, "pluginName", "UNIVER_RPC_WORKER_THREAD_PLUGIN"), E);
}, o(E, "pluginName", "UNIVER_RPC_WORKER_THREAD_PLUGIN"), E);
T = k([

@@ -489,0 +488,0 @@ J(1, g(C))

@@ -1,3 +0,2 @@

import { IMutation, ICommandService, IUniverInstanceService, RxDisposable } from '@univerjs/core';
import { IDisposable, Injector } from '@wendellhu/redi';
import { IDisposable, IMutation, ICommandService, Injector, IUniverInstanceService, RxDisposable } from '@univerjs/core';
import { IRemoteSyncService } from '../../services/remote-instance/remote-instance.service';

@@ -4,0 +3,0 @@ import { IRPCChannelService } from '../../services/rpc/channel.service';

@@ -1,3 +0,2 @@

import { Disposable, ICommandService } from '@univerjs/core';
import { Injector } from '@wendellhu/redi';
import { Disposable, ICommandService, Injector } from '@univerjs/core';
import { IRemoteInstanceService } from '../../services/remote-instance/remote-instance.service';

@@ -4,0 +3,0 @@ import { IRPCChannelService } from '../../services/rpc/channel.service';

@@ -1,3 +0,2 @@

import { Plugin } from '@univerjs/core';
import { Injector } from '@wendellhu/redi';
import { Injector, Plugin } from '@univerjs/core';

@@ -4,0 +3,0 @@ export interface IUniverRPCMainThreadConfig {

@@ -13,3 +13,3 @@ import { IExecutionOptions, IMutationInfo, IWorkbookData, ICommandService, ILogService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';

*/
export declare const IRemoteSyncService: import('@wendellhu/redi').IdentifierDecorator<IRemoteSyncService>;
export declare const IRemoteSyncService: import('@univerjs/core').IdentifierDecorator<IRemoteSyncService>;
export interface IRemoteSyncService {

@@ -34,3 +34,3 @@ syncMutation(params: {

*/
export declare const IRemoteInstanceService: import('@wendellhu/redi').IdentifierDecorator<IRemoteInstanceService>;
export declare const IRemoteInstanceService: import('@univerjs/core').IdentifierDecorator<IRemoteInstanceService>;
export interface IRemoteInstanceService {

@@ -37,0 +37,0 @@ /** Tell other modules if the `IRemoteInstanceService` is ready to load files. */

@@ -1,2 +0,2 @@

import { IDisposable } from '@wendellhu/redi';
import { IDisposable } from '@univerjs/core';
import { IChannel, IMessageProtocol } from './rpc.service';

@@ -8,3 +8,3 @@

}
export declare const IRPCChannelService: import('@wendellhu/redi').IdentifierDecorator<IRPCChannelService>;
export declare const IRPCChannelService: import('@univerjs/core').IdentifierDecorator<IRPCChannelService>;
/**

@@ -11,0 +11,0 @@ * This service is responsible for managing the RPC channels.

@@ -1,1 +0,1 @@

(function(i,c){typeof exports=="object"&&typeof module<"u"?c(exports,require("@univerjs/core"),require("@wendellhu/redi"),require("rxjs/operators"),require("rxjs")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","@wendellhu/redi","rxjs/operators","rxjs"],c):(i=typeof globalThis<"u"?globalThis:i||self,c(i.UniverRpc={},i.UniverCore,i["@wendellhu/redi"],i.rxjs.operators,i.rxjs))})(this,function(i,c,l,v,d){"use strict";var Y=Object.defineProperty;var Z=(i,c,l)=>c in i?Y(i,c,{enumerable:!0,configurable:!0,writable:!0,value:l}):i[c]=l;var u=(i,c,l)=>Z(i,typeof c!="symbol"?c+"":c,l);var U,E;var $=Object.defineProperty,N=Object.getOwnPropertyDescriptor,D=(a,t,e,n)=>{for(var s=n>1?void 0:n?N(t,e):t,r=a.length-1,o;r>=0;r--)(o=a[r])&&(s=(n?o(t,e,s):o(s))||s);return n&&s&&$(t,e,s),s},C=(a,t)=>(e,n)=>t(e,n,a);const R="rpc.remote-sync.service",p=l.createIdentifier(R);i.RemoteSyncPrimaryService=class{constructor(t){this._commandService=t}async syncMutation(t){return this._commandService.syncExecuteCommand(t.mutationInfo.id,t.mutationInfo.params,{onlyLocal:!0,fromSync:!0})}},i.RemoteSyncPrimaryService=D([C(0,c.ICommandService)],i.RemoteSyncPrimaryService);const b="univer.remote-instance-service",y=l.createIdentifier(b);i.WebWorkerRemoteInstanceService=class{constructor(t,e,n){this._univerInstanceService=t,this._commandService=e,this._logService=n}whenReady(){return Promise.resolve(!0)}async syncMutation(t){return this._applyMutation(t.mutationInfo)}async createInstance(t){const{type:e,snapshot:n}=t;try{switch(e){case c.UniverInstanceType.UNIVER_SHEET:return this._univerInstanceService.createUnit(c.UniverInstanceType.UNIVER_SHEET,n),!0;default:throw new Error(`[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${e}.`)}}catch(s){throw s instanceof Error?s:new TypeError(`${s}`)}}async disposeInstance(t){return this._univerInstanceService.disposeUnit(t.unitID)}_applyMutation(t){const{id:e,params:n}=t;return this._commandService.syncExecuteCommand(e,n,{onlyLocal:!0,fromSync:!0})}},i.WebWorkerRemoteInstanceService=D([C(0,c.IUniverInstanceService),C(1,c.ICommandService),C(2,c.ILogService)],i.WebWorkerRemoteInstanceService);function I(a){const t=a;return new class{call(e,n){const s=t[e];if(typeof s=="function"){let r=s.apply(t,[n]);return r instanceof Promise||(r=Promise.resolve(r)),r}throw new Error(`[RPC]: method not found for ${e}!`)}subscribe(e,n){const s=t[e];if(typeof s=="function"){const r=s.apply(t,n);return d.isObservable(r)?r:d.of(r)}throw new Error(`[RPC]: observable method not found for ${e}!`)}}}function P(a){return new Proxy({},{get(t,e){if(e!=="dispose")return function(...n){return L(e)?a.subscribe(e,n[0]):a.call(e,n[0])}}})}function L(a){return a.endsWith("$")}class O extends c.RxDisposable{constructor(e){super();u(this,"_initialized",new d.BehaviorSubject(!1));u(this,"_lastRequestCounter",0);u(this,"_pendingRequests",new Map);this._protocol=e,this._protocol.onMessage.pipe(v.takeUntil(this.dispose$)).subscribe(n=>this._onMessage(n))}dispose(){this._pendingRequests.clear()}getChannel(e){const n=this;return{call(s,r){return n._disposed?Promise.reject():n._remoteCall(e,s,r)},subscribe(s,r){if(n._disposed)throw new Error("[ChannelClient]: client is disposed!");return n._remoteSubscribe(e,s,r)}}}_whenReady(){return d.firstValueFrom(this._initialized.pipe(v.filter(e=>e),v.take(1)))}async _remoteCall(e,n,s){await this._whenReady();const r=++this._lastRequestCounter,_={seq:r,type:100,channelName:e,method:n,args:s},h=this;return new Promise((M,f)=>{const X={handle(q){switch(q.type){case 201:h._pendingRequests.delete(r),M(q.data);break;case 202:h._pendingRequests.delete(r),f(q.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(r,X),this._sendRequest(_)})}_remoteSubscribe(e,n,s){return new d.Observable(r=>{let o=-1;return this._whenReady().then(()=>{o=++this._lastRequestCounter;const h={seq:o,type:101,channelName:e,method:n,args:s},M={handle(f){switch(f.type){case 300:r.next(f.data);break;case 301:r.error(f.data);break;case 302:r.complete();break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(o,M),this._sendRequest(h)}),()=>{if(o===-1)return;const _={type:102,seq:o,channelName:e,method:n};this._sendRequest(_)}})}_sendRequest(e){this._protocol.send(e)}_onMessage(e){var n;switch(e.type){case 0:this._initialized.next(!0);break;case 201:case 202:case 300:case 302:case 301:(n=this._pendingRequests.get(e.seq))==null||n.handle(e);break}}}class T extends c.RxDisposable{constructor(e){super();u(this,"_channels",new Map);u(this,"_subscriptions",new Map);this._protocol=e,this._protocol.onMessage.pipe(v.takeUntil(this.dispose$)).subscribe(n=>this._onRequest(n)),this._sendResponse({seq:-1,type:0})}dispose(){super.dispose(),this._subscriptions.clear(),this._channels.clear()}registerChannel(e,n){this._channels.set(e,n)}_onRequest(e){switch(e.type){case 100:this._onMethodCall(e);break;case 101:this._onSubscribe(e);break;case 102:this._onUnsubscribe(e);break}}_onMethodCall(e){const{channelName:n,method:s,args:r}=e,o=this._channels.get(n);let _;try{if(!o)throw new Error(`[ChannelServer]: Channel ${n} not found!`);_=o.call(s,r)}catch(h){_=Promise.reject(h)}_.then(h=>{this._sendResponse({seq:e.seq,type:201,data:h})}).catch(h=>{h instanceof Error?this._sendResponse({seq:e.seq,type:202,data:h.message}):this._sendResponse({seq:e.seq,type:202,data:String(h)})})}_onSubscribe(e){const{channelName:n,seq:s}=e,r=this._channels.get(n);try{if(!r)throw new Error(`[ChannelServer]: Channel ${n} not found!`);const _=r.subscribe(e.method,e.args).subscribe({next:h=>{this._sendResponse({seq:s,type:300,data:h})},error:h=>{this._sendResponse({seq:s,type:301,data:h.message}),this._sendResponse({seq:s,type:302})},complete:()=>{this._sendResponse({seq:s,type:302})}});this._subscriptions.set(e.seq,_)}catch(o){o instanceof Error?this._sendResponse({seq:e.seq,type:301,data:o.message}):this._sendResponse({seq:e.seq,type:301,data:String(o)})}}_onUnsubscribe(e){const n=this._subscriptions.get(e.seq);n&&(n.unsubscribe(),this._subscriptions.delete(e.seq))}_sendResponse(e){this._protocol.send(e)}}const m=l.createIdentifier("IRPCChannelService");class w{constructor(t){u(this,"_client");u(this,"_server");this._client=new O(t),this._server=new T(t)}dispose(){this._client.dispose(),this._server.dispose()}requestChannel(t){return this._client.getChannel(t)}registerChannel(t,e){this._server.registerChannel(t,e)}}var k=Object.defineProperty,H=Object.getOwnPropertyDescriptor,V=(a,t,e,n)=>{for(var s=n>1?void 0:n?H(t,e):t,r=a.length-1,o;r>=0;r--)(o=a[r])&&(s=(n?o(t,e,s):o(s))||s);return n&&s&&k(t,e,s),s},S=(a,t)=>(e,n)=>t(e,n,a);i.DataSyncPrimaryController=class extends c.RxDisposable{constructor(e,n,s,r,o){super();u(this,"_remoteInstanceService");u(this,"_syncingUnits",new Set);u(this,"_syncingMutations",new Set);this._injector=e,this._commandService=n,this._univerInstanceService=s,this._rpcChannelService=r,this._remoteSyncService=o,this._initRPCChannels(),this._init()}registerSyncingMutations(e){this._syncingMutations.add(e.id)}syncUnit(e){return this._syncingUnits.add(e),c.toDisposable(()=>this._syncingUnits.delete(e))}_initRPCChannels(){this._rpcChannelService.registerChannel(R,I(this._remoteSyncService)),this._injector.add([y,{useFactory:()=>P(this._rpcChannelService.requestChannel(b))}]),this._remoteInstanceService=this._injector.get(y)}_init(){this._univerInstanceService.getTypeOfUnitAdded$(c.UniverInstanceType.UNIVER_SHEET).pipe(v.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.add(e.getUnitId()),this._remoteInstanceService.createInstance({unitID:e.getUnitId(),type:c.UniverInstanceType.UNIVER_SHEET,snapshot:e.getSnapshot()})}),this._univerInstanceService.getTypeOfUnitDisposed$(c.UniverInstanceType.UNIVER_SHEET).pipe(v.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.delete(e.getUnitId()),this._remoteInstanceService.disposeInstance({unitID:e.getUnitId()})}),this.disposeWithMe(this._commandService.onCommandExecuted((e,n)=>{const{type:s,params:r,id:o}=e,_=(r==null?void 0:r.unitId)||"";s===c.CommandType.MUTATION&&(!_||this._syncingUnits.has(_))&&!(n!=null&&n.fromSync)&&this._syncingMutations.has(o)&&this._remoteInstanceService.syncMutation({mutationInfo:e})}))}},i.DataSyncPrimaryController=V([c.OnLifecycle(c.LifecycleStages.Starting,i.DataSyncPrimaryController),S(0,l.Inject(l.Injector)),S(1,c.ICommandService),S(2,c.IUniverInstanceService),S(3,m),S(4,p)],i.DataSyncPrimaryController);var A=Object.defineProperty,F=Object.getOwnPropertyDescriptor,z=(a,t,e,n)=>{for(var s=n>1?void 0:n?F(t,e):t,r=a.length-1,o;r>=0;r--)(o=a[r])&&(s=(n?o(t,e,s):o(s))||s);return n&&s&&A(t,e,s),s},g=(a,t)=>(e,n)=>t(e,n,a);i.DataSyncReplicaController=class extends c.Disposable{constructor(e,n,s,r){super();u(this,"_remoteSyncService");this._injector=e,this._remoteInstanceService=n,this._commandService=s,this._rpcChannelService=r,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(b,I(this._remoteInstanceService)),this._injector.add([p,{useFactory:()=>P(this._rpcChannelService.requestChannel(R))}]),this._remoteSyncService=this._injector.get(p)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((e,n)=>{e.type===c.CommandType.MUTATION&&!(n!=null&&n.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:e})}))}},i.DataSyncReplicaController=z([c.OnLifecycle(c.LifecycleStages.Starting,i.DataSyncReplicaController),g(0,l.Inject(l.Injector)),g(1,y),g(2,c.ICommandService),g(3,m)],i.DataSyncReplicaController);function G(){return{send(a){postMessage(a)},onMessage:new d.Observable(a=>{const t=e=>{a.next(e.data)};return addEventListener("message",t),()=>removeEventListener("message",t)}).pipe(d.shareReplay(1))}}function B(a){return{send(t){a.postMessage(t)},onMessage:new d.Observable(t=>{const e=n=>{t.next(n.data)};return a.addEventListener("message",e),()=>a.removeEventListener("message",e)}).pipe(d.shareReplay(1))}}var J=Object.defineProperty,Q=Object.getOwnPropertyDescriptor,j=(a,t,e,n)=>{for(var s=n>1?void 0:n?Q(t,e):t,r=a.length-1,o;r>=0;r--)(o=a[r])&&(s=(n?o(t,e,s):o(s))||s);return n&&s&&J(t,e,s),s},W=(a,t)=>(e,n)=>t(e,n,a);i.UniverRPCMainThreadPlugin=(U=class extends c.Plugin{constructor(t,e){super(),this._config=t,this._injector=e}async onStarting(t){const{workerURL:e}=this._config,n=e instanceof Worker?e:new Worker(e),s=B(n);[[m,{useFactory:()=>new w(s)}],[i.DataSyncPrimaryController],[p,{useClass:i.RemoteSyncPrimaryService}]].forEach(o=>t.add(o)),t.get(i.DataSyncPrimaryController)}},u(U,"pluginName","UNIVER_RPC_MAIN_THREAD_PLUGIN"),U),i.UniverRPCMainThreadPlugin=j([W(1,l.Inject(l.Injector))],i.UniverRPCMainThreadPlugin),i.UniverRPCWorkerThreadPlugin=(E=class extends c.Plugin{constructor(t,e){super(),this._config=t,this._injector=e}onStarting(t){[[i.DataSyncReplicaController],[m,{useFactory:()=>new w(G())}],[y,{useClass:i.WebWorkerRemoteInstanceService}]].forEach(e=>t.add(e)),t.get(i.DataSyncReplicaController)}},u(E,"pluginName","UNIVER_RPC_WORKER_THREAD_PLUGIN"),E),i.UniverRPCWorkerThreadPlugin=j([W(1,l.Inject(l.Injector))],i.UniverRPCWorkerThreadPlugin),i.ChannelClient=O,i.ChannelServer=T,i.ChannelService=w,i.IRPCChannelService=m,i.IRemoteInstanceService=y,i.IRemoteSyncService=p,i.RemoteInstanceServiceName=b,i.RemoteSyncServiceName=R,i.fromModule=I,i.toModule=P,Object.defineProperty(i,Symbol.toStringTag,{value:"Module"})});
(function(r,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("@univerjs/core"),require("rxjs/operators"),require("rxjs")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs/operators","rxjs"],a):(r=typeof globalThis<"u"?globalThis:r||self,a(r.UniverRpc={},r.UniverCore,r.rxjs.operators,r.rxjs))})(this,function(r,a,_,d){"use strict";var X=Object.defineProperty;var Y=(r,a,_)=>a in r?X(r,a,{enumerable:!0,configurable:!0,writable:!0,value:_}):r[a]=_;var h=(r,a,_)=>Y(r,typeof a!="symbol"?a+"":a,_);var w,U;var W=Object.defineProperty,$=Object.getOwnPropertyDescriptor,q=(c,t,e,n)=>{for(var s=n>1?void 0:n?$(t,e):t,i=c.length-1,o;i>=0;i--)(o=c[i])&&(s=(n?o(t,e,s):o(s))||s);return n&&s&&W(t,e,s),s},f=(c,t)=>(e,n)=>t(e,n,c);const C="rpc.remote-sync.service",v=a.createIdentifier(C);r.RemoteSyncPrimaryService=class{constructor(t){this._commandService=t}async syncMutation(t){return this._commandService.syncExecuteCommand(t.mutationInfo.id,t.mutationInfo.params,{onlyLocal:!0,fromSync:!0})}},r.RemoteSyncPrimaryService=q([f(0,a.ICommandService)],r.RemoteSyncPrimaryService);const R="univer.remote-instance-service",p=a.createIdentifier(R);r.WebWorkerRemoteInstanceService=class{constructor(t,e,n){this._univerInstanceService=t,this._commandService=e,this._logService=n}whenReady(){return Promise.resolve(!0)}async syncMutation(t){return this._applyMutation(t.mutationInfo)}async createInstance(t){const{type:e,snapshot:n}=t;try{switch(e){case a.UniverInstanceType.UNIVER_SHEET:return this._univerInstanceService.createUnit(a.UniverInstanceType.UNIVER_SHEET,n),!0;default:throw new Error(`[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${e}.`)}}catch(s){throw s instanceof Error?s:new TypeError(`${s}`)}}async disposeInstance(t){return this._univerInstanceService.disposeUnit(t.unitID)}_applyMutation(t){const{id:e,params:n}=t;return this._commandService.syncExecuteCommand(e,n,{onlyLocal:!0,fromSync:!0})}},r.WebWorkerRemoteInstanceService=q([f(0,a.IUniverInstanceService),f(1,a.ICommandService),f(2,a.ILogService)],r.WebWorkerRemoteInstanceService);function g(c){const t=c;return new class{call(e,n){const s=t[e];if(typeof s=="function"){let i=s.apply(t,[n]);return i instanceof Promise||(i=Promise.resolve(i)),i}throw new Error(`[RPC]: method not found for ${e}!`)}subscribe(e,n){const s=t[e];if(typeof s=="function"){const i=s.apply(t,n);return d.isObservable(i)?i:d.of(i)}throw new Error(`[RPC]: observable method not found for ${e}!`)}}}function I(c){return new Proxy({},{get(t,e){if(e!=="dispose")return function(...n){return N(e)?c.subscribe(e,n[0]):c.call(e,n[0])}}})}function N(c){return c.endsWith("$")}class D extends a.RxDisposable{constructor(e){super();h(this,"_initialized",new d.BehaviorSubject(!1));h(this,"_lastRequestCounter",0);h(this,"_pendingRequests",new Map);this._protocol=e,this._protocol.onMessage.pipe(_.takeUntil(this.dispose$)).subscribe(n=>this._onMessage(n))}dispose(){this._pendingRequests.clear()}getChannel(e){const n=this;return{call(s,i){return n._disposed?Promise.reject():n._remoteCall(e,s,i)},subscribe(s,i){if(n._disposed)throw new Error("[ChannelClient]: client is disposed!");return n._remoteSubscribe(e,s,i)}}}_whenReady(){return d.firstValueFrom(this._initialized.pipe(_.filter(e=>e),_.take(1)))}async _remoteCall(e,n,s){await this._whenReady();const i=++this._lastRequestCounter,u={seq:i,type:100,channelName:e,method:n,args:s},l=this;return new Promise((E,S)=>{const Q={handle(M){switch(M.type){case 201:l._pendingRequests.delete(i),E(M.data);break;case 202:l._pendingRequests.delete(i),S(M.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(i,Q),this._sendRequest(u)})}_remoteSubscribe(e,n,s){return new d.Observable(i=>{let o=-1;return this._whenReady().then(()=>{o=++this._lastRequestCounter;const l={seq:o,type:101,channelName:e,method:n,args:s},E={handle(S){switch(S.type){case 300:i.next(S.data);break;case 301:i.error(S.data);break;case 302:i.complete();break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(o,E),this._sendRequest(l)}),()=>{if(o===-1)return;const u={type:102,seq:o,channelName:e,method:n};this._sendRequest(u)}})}_sendRequest(e){this._protocol.send(e)}_onMessage(e){var n;switch(e.type){case 0:this._initialized.next(!0);break;case 201:case 202:case 300:case 302:case 301:(n=this._pendingRequests.get(e.seq))==null||n.handle(e);break}}}class O extends a.RxDisposable{constructor(e){super();h(this,"_channels",new Map);h(this,"_subscriptions",new Map);this._protocol=e,this._protocol.onMessage.pipe(_.takeUntil(this.dispose$)).subscribe(n=>this._onRequest(n)),this._sendResponse({seq:-1,type:0})}dispose(){super.dispose(),this._subscriptions.clear(),this._channels.clear()}registerChannel(e,n){this._channels.set(e,n)}_onRequest(e){switch(e.type){case 100:this._onMethodCall(e);break;case 101:this._onSubscribe(e);break;case 102:this._onUnsubscribe(e);break}}_onMethodCall(e){const{channelName:n,method:s,args:i}=e,o=this._channels.get(n);let u;try{if(!o)throw new Error(`[ChannelServer]: Channel ${n} not found!`);u=o.call(s,i)}catch(l){u=Promise.reject(l)}u.then(l=>{this._sendResponse({seq:e.seq,type:201,data:l})}).catch(l=>{l instanceof Error?this._sendResponse({seq:e.seq,type:202,data:l.message}):this._sendResponse({seq:e.seq,type:202,data:String(l)})})}_onSubscribe(e){const{channelName:n,seq:s}=e,i=this._channels.get(n);try{if(!i)throw new Error(`[ChannelServer]: Channel ${n} not found!`);const u=i.subscribe(e.method,e.args).subscribe({next:l=>{this._sendResponse({seq:s,type:300,data:l})},error:l=>{this._sendResponse({seq:s,type:301,data:l.message}),this._sendResponse({seq:s,type:302})},complete:()=>{this._sendResponse({seq:s,type:302})}});this._subscriptions.set(e.seq,u)}catch(o){o instanceof Error?this._sendResponse({seq:e.seq,type:301,data:o.message}):this._sendResponse({seq:e.seq,type:301,data:String(o)})}}_onUnsubscribe(e){const n=this._subscriptions.get(e.seq);n&&(n.unsubscribe(),this._subscriptions.delete(e.seq))}_sendResponse(e){this._protocol.send(e)}}const y=a.createIdentifier("IRPCChannelService");class P{constructor(t){h(this,"_client");h(this,"_server");this._client=new D(t),this._server=new O(t)}dispose(){this._client.dispose(),this._server.dispose()}requestChannel(t){return this._client.getChannel(t)}registerChannel(t,e){this._server.registerChannel(t,e)}}var L=Object.defineProperty,k=Object.getOwnPropertyDescriptor,H=(c,t,e,n)=>{for(var s=n>1?void 0:n?k(t,e):t,i=c.length-1,o;i>=0;i--)(o=c[i])&&(s=(n?o(t,e,s):o(s))||s);return n&&s&&L(t,e,s),s},m=(c,t)=>(e,n)=>t(e,n,c);r.DataSyncPrimaryController=class extends a.RxDisposable{constructor(e,n,s,i,o){super();h(this,"_remoteInstanceService");h(this,"_syncingUnits",new Set);h(this,"_syncingMutations",new Set);this._injector=e,this._commandService=n,this._univerInstanceService=s,this._rpcChannelService=i,this._remoteSyncService=o,this._initRPCChannels(),this._init()}registerSyncingMutations(e){this._syncingMutations.add(e.id)}syncUnit(e){return this._syncingUnits.add(e),a.toDisposable(()=>this._syncingUnits.delete(e))}_initRPCChannels(){this._rpcChannelService.registerChannel(C,g(this._remoteSyncService)),this._injector.add([p,{useFactory:()=>I(this._rpcChannelService.requestChannel(R))}]),this._remoteInstanceService=this._injector.get(p)}_init(){this._univerInstanceService.getTypeOfUnitAdded$(a.UniverInstanceType.UNIVER_SHEET).pipe(_.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.add(e.getUnitId()),this._remoteInstanceService.createInstance({unitID:e.getUnitId(),type:a.UniverInstanceType.UNIVER_SHEET,snapshot:e.getSnapshot()})}),this._univerInstanceService.getTypeOfUnitDisposed$(a.UniverInstanceType.UNIVER_SHEET).pipe(_.takeUntil(this.dispose$)).subscribe(e=>{this._syncingUnits.delete(e.getUnitId()),this._remoteInstanceService.disposeInstance({unitID:e.getUnitId()})}),this.disposeWithMe(this._commandService.onCommandExecuted((e,n)=>{const{type:s,params:i,id:o}=e,u=(i==null?void 0:i.unitId)||"";s===a.CommandType.MUTATION&&(!u||this._syncingUnits.has(u))&&!(n!=null&&n.fromSync)&&this._syncingMutations.has(o)&&this._remoteInstanceService.syncMutation({mutationInfo:e})}))}},r.DataSyncPrimaryController=H([a.OnLifecycle(a.LifecycleStages.Starting,r.DataSyncPrimaryController),m(0,a.Inject(a.Injector)),m(1,a.ICommandService),m(2,a.IUniverInstanceService),m(3,y),m(4,v)],r.DataSyncPrimaryController);var V=Object.defineProperty,A=Object.getOwnPropertyDescriptor,F=(c,t,e,n)=>{for(var s=n>1?void 0:n?A(t,e):t,i=c.length-1,o;i>=0;i--)(o=c[i])&&(s=(n?o(t,e,s):o(s))||s);return n&&s&&V(t,e,s),s},b=(c,t)=>(e,n)=>t(e,n,c);r.DataSyncReplicaController=class extends a.Disposable{constructor(e,n,s,i){super();h(this,"_remoteSyncService");this._injector=e,this._remoteInstanceService=n,this._commandService=s,this._rpcChannelService=i,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(R,g(this._remoteInstanceService)),this._injector.add([v,{useFactory:()=>I(this._rpcChannelService.requestChannel(C))}]),this._remoteSyncService=this._injector.get(v)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((e,n)=>{e.type===a.CommandType.MUTATION&&!(n!=null&&n.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:e})}))}},r.DataSyncReplicaController=F([a.OnLifecycle(a.LifecycleStages.Starting,r.DataSyncReplicaController),b(0,a.Inject(a.Injector)),b(1,p),b(2,a.ICommandService),b(3,y)],r.DataSyncReplicaController);function z(){return{send(c){postMessage(c)},onMessage:new d.Observable(c=>{const t=e=>{c.next(e.data)};return addEventListener("message",t),()=>removeEventListener("message",t)}).pipe(d.shareReplay(1))}}function G(c){return{send(t){c.postMessage(t)},onMessage:new d.Observable(t=>{const e=n=>{t.next(n.data)};return c.addEventListener("message",e),()=>c.removeEventListener("message",e)}).pipe(d.shareReplay(1))}}var B=Object.defineProperty,J=Object.getOwnPropertyDescriptor,T=(c,t,e,n)=>{for(var s=n>1?void 0:n?J(t,e):t,i=c.length-1,o;i>=0;i--)(o=c[i])&&(s=(n?o(t,e,s):o(s))||s);return n&&s&&B(t,e,s),s},j=(c,t)=>(e,n)=>t(e,n,c);r.UniverRPCMainThreadPlugin=(w=class extends a.Plugin{constructor(t,e){super(),this._config=t,this._injector=e}async onStarting(t){const{workerURL:e}=this._config,n=e instanceof Worker?e:new Worker(e),s=G(n);[[y,{useFactory:()=>new P(s)}],[r.DataSyncPrimaryController],[v,{useClass:r.RemoteSyncPrimaryService}]].forEach(o=>t.add(o)),t.get(r.DataSyncPrimaryController)}},h(w,"pluginName","UNIVER_RPC_MAIN_THREAD_PLUGIN"),w),r.UniverRPCMainThreadPlugin=T([j(1,a.Inject(a.Injector))],r.UniverRPCMainThreadPlugin),r.UniverRPCWorkerThreadPlugin=(U=class extends a.Plugin{constructor(t,e){super(),this._config=t,this._injector=e}onStarting(t){[[r.DataSyncReplicaController],[y,{useFactory:()=>new P(z())}],[p,{useClass:r.WebWorkerRemoteInstanceService}]].forEach(e=>t.add(e)),t.get(r.DataSyncReplicaController)}},h(U,"pluginName","UNIVER_RPC_WORKER_THREAD_PLUGIN"),U),r.UniverRPCWorkerThreadPlugin=T([j(1,a.Inject(a.Injector))],r.UniverRPCWorkerThreadPlugin),r.ChannelClient=D,r.ChannelServer=O,r.ChannelService=P,r.IRPCChannelService=y,r.IRemoteInstanceService=p,r.IRemoteSyncService=v,r.RemoteInstanceServiceName=R,r.RemoteSyncServiceName=C,r.fromModule=g,r.toModule=I,Object.defineProperty(r,Symbol.toStringTag,{value:"Module"})});
{
"name": "@univerjs/rpc",
"version": "0.2.4",
"version": "0.2.5",
"private": false,

@@ -48,8 +48,6 @@ "author": "DreamNum <developer@univer.ai>",

"peerDependencies": {
"@wendellhu/redi": "0.16.0",
"rxjs": ">=7.0.0",
"@univerjs/core": "0.2.4"
"@univerjs/core": "0.2.5"
},
"devDependencies": {
"@wendellhu/redi": "0.16.0",
"rxjs": "^7.8.1",

@@ -59,4 +57,4 @@ "typescript": "^5.5.3",

"vitest": "^2.0.3",
"@univerjs/core": "0.2.4",
"@univerjs/shared": "0.2.4"
"@univerjs/core": "0.2.5",
"@univerjs/shared": "0.2.5"
},

@@ -63,0 +61,0 @@ "univerSpace": {

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc