@univerjs/rpc 0.1.0-alpha.3 → 0.1.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cjs/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var A=Object.defineProperty;var F=(s,t,e)=>t in s?A(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var h=(s,t,e)=>(F(s,typeof t!="symbol"?t+"":t,e),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("@univerjs/core"),l=require("@wendellhu/redi"),p=require("rxjs/operators"),_=require("rxjs");var H=Object.defineProperty,k=Object.getOwnPropertyDescriptor,j=(s,t,e,n)=>{for(var r=n>1?void 0:n?k(t,e):t,i=s.length-1,c;i>=0;i--)(c=s[i])&&(r=(n?c(t,e,r):c(r))||r);return n&&r&&H(t,e,r),r},w=(s,t)=>(e,n)=>t(e,n,s);const E="univer.remote-sync-service",b=l.createIdentifier(E);let M=class{constructor(s){this._commandService=s}async syncMutation(s){return this._commandService.syncExecuteCommand(s.mutationInfo.id,s.mutationInfo.params,{onlyLocal:!0,fromSync:!0})}};M=j([w(0,a.ICommandService)],M);const O="univer.remote-instance-service",C=l.createIdentifier(O);let q=class{constructor(s,t){this._univerInstanceService=s,this._commandService=t}async syncMutation(s){return this._commandService.syncExecuteCommand(s.mutationInfo.id,s.mutationInfo.params,{onlyLocal:!0,fromSync:!0})}async createInstance(s){const{type:t,snapshot:e}=s;try{switch(t){case a.DocumentType.SHEET:return!!this._univerInstanceService.createSheet(e);default:throw new Error(`[RemoteInstanceReplicaService]: cannot create replica for document type: ${t}.`)}}catch(n){throw n instanceof Error?n:new Error(`${n}`)}}async disposeInstance(s){return this._univerInstanceService.disposeDocument(s.unitID)}};q=j([w(0,a.IUniverInstanceService),w(1,a.ICommandService)],q);function U(s){const t=s;return new class{call(e,n){const r=t[e];if(typeof r=="function"){let i=r.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 r=t[e];if(typeof r=="function"){const i=r.apply(t,n);return _.isObservable(i)?i:_.of(i)}throw new Error(`[RPC]: observable method not found for ${e}!`)}}}function $(s){return new Proxy({},{get(t,e){return function(...n){return z(e)?s.subscribe(e,n[0]):s.call(e,n[0])}}})}function z(s){return s.endsWith("$")}class D extends a.RxDisposable{constructor(e){super();h(this,"_initialized",new _.BehaviorSubject(!1));h(this,"_lastRequestCounter",0);h(this,"_pendingRequests",new Map);h(this,"_pendingSubscriptions",new Map);this._protocol=e,this._protocol.onMessage.pipe(p.takeUntil(this.dispose$)).subscribe(n=>this._onMessage(n))}getChannel(e){const n=this;return{call(r,i){return n._disposed?Promise.reject():n._remoteCall(e,r,i)},subscribe(r,i){if(n._disposed)throw new Error("[ChannelClient]: client is disposed!");return n._remoteSubscribe(e,r,i)}}}_whenReady(){return _.firstValueFrom(this._initialized.pipe(p.filter(e=>e),p.take(1)))}async _remoteCall(e,n,r){await this._whenReady();const i=++this._lastRequestCounter,u={seq:i,type:100,channelName:e,method:n,args:r},o=this;return new Promise((g,d)=>{const N={handle(R){switch(R.type){case 201:o._pendingRequests.delete(i),g(R.data);break;case 202:o._pendingRequests.delete(i),d(R.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(i,N),this._sendRequest(u)})}_remoteSubscribe(e,n,r){return new _.Observable(i=>{let c=-1;return this._whenReady().then(()=>{c=++this._lastRequestCounter;const o={seq:c,type:101,channelName:e,method:n,args:r},g={handle(d){switch(d.type){case 300:i.next(d.data);break;case 301:i.error(d.data);break;case 302:i.complete();break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(c,g),this._sendRequest(o)}),()=>{if(c===-1)return;const u={type:102,seq:c,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 T extends a.RxDisposable{constructor(e){super();h(this,"_channels",new Map);h(this,"_subscriptions",new Map);this._protocol=e,this._protocol.onMessage.pipe(p.takeUntil(this.dispose$)).subscribe(n=>this._onRequest(n)),this._sendResponse({seq:-1,type:0})}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:r,args:i}=e,c=this._channels.get(n);let u;try{if(!c)throw new Error(`[ChannelServer]: Channel ${n} not found!`);u=c.call(r,i)}catch(o){u=Promise.reject(o)}u.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:n,seq:r}=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:o=>{this._sendResponse({seq:r,type:300,data:o})},error:o=>{this._sendResponse({seq:r,type:301,data:o.message}),this._sendResponse({seq:r,type:302})},complete:()=>{this._sendResponse({seq:r,type:302})}});this._subscriptions.set(e.seq,u)}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 n=this._subscriptions.get(e.seq);n&&(n.unsubscribe(),this._subscriptions.delete(e.seq))}_sendResponse(e){this._protocol.send(e)}}const S=l.createIdentifier("IRPChannelService");class x{constructor(t){h(this,"_client");h(this,"_server");this._client=new D(t),this._server=new T(t)}requestChannel(t){return this._client.getChannel(t)}registerChannel(t,e){this._server.registerChannel(t,e)}}var V=Object.defineProperty,G=Object.getOwnPropertyDescriptor,B=(s,t,e,n)=>{for(var r=n>1?void 0:n?G(t,e):t,i=s.length-1,c;i>=0;i--)(c=s[i])&&(r=(n?c(t,e,r):c(r))||r);return n&&r&&V(t,e,r),r},v=(s,t)=>(e,n)=>t(e,n,s);let m=class extends a.RxDisposable{constructor(t,e,n,r,i,c){super();h(this,"_remoteInstanceService");this._unsyncMutations=t,this._injector=e,this._commandService=n,this._univerInstanceService=r,this._rpcChannelService=i,this._remoteSyncService=c,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(E,U(this._remoteSyncService)),this._injector.add([C,{useFactory:()=>$(this._rpcChannelService.requestChannel(O))}]),this._remoteInstanceService=this._injector.get(C)}_init(){this._univerInstanceService.sheetAdded$.pipe(p.takeUntil(this.dispose$)).subscribe(t=>{this._remoteInstanceService.createInstance({unitID:t.getUnitId(),type:a.DocumentType.SHEET,snapshot:t.getSnapshot()})}),this._univerInstanceService.sheetDisposed$.pipe(p.takeUntil(this.dispose$)).subscribe(t=>{this._remoteInstanceService.disposeInstance({unitID:t.getUnitId()})}),this.disposeWithMe(this._commandService.onCommandExecuted((t,e)=>{t.type===a.CommandType.MUTATION&&!(e!=null&&e.fromSync)&&!this._unsyncMutations.has(t.id)&&this._remoteInstanceService.syncMutation({mutationInfo:t})}))}};m=B([a.OnLifecycle(a.LifecycleStages.Starting,m),v(1,l.Inject(l.Injector)),v(2,a.ICommandService),v(3,a.IUniverInstanceService),v(4,S),v(5,b)],m);var J=Object.defineProperty,Q=Object.getOwnPropertyDescriptor,X=(s,t,e,n)=>{for(var r=n>1?void 0:n?Q(t,e):t,i=s.length-1,c;i>=0;i--)(c=s[i])&&(r=(n?c(t,e,r):c(r))||r);return n&&r&&J(t,e,r),r},f=(s,t)=>(e,n)=>t(e,n,s);let y=class extends a.Disposable{constructor(t,e,n,r){super();h(this,"_remoteSyncService");this._injector=t,this._remoteInstanceService=e,this._commandService=n,this._rpcChannelService=r,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(O,U(this._remoteInstanceService)),this._injector.add([b,{useFactory:()=>$(this._rpcChannelService.requestChannel(E))}]),this._remoteSyncService=this._injector.get(b)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((t,e)=>{t.type===a.CommandType.MUTATION&&!(e!=null&&e.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:t})}))}};y=X([a.OnLifecycle(a.LifecycleStages.Starting,y),f(0,l.Inject(l.Injector)),f(1,C),f(2,a.ICommandService),f(3,S)],y);function Y(){return{send(s){postMessage(s)},onMessage:new _.Observable(s=>{const t=e=>{s.next(e.data)};return addEventListener("message",t),()=>removeEventListener("message",t)}).pipe(_.shareReplay(1))}}function Z(s){return{send(t){s.postMessage(t)},onMessage:new _.Observable(t=>{const e=n=>{t.next(n.data)};return s.addEventListener("message",e),()=>s.removeEventListener("message",e)}).pipe(_.shareReplay(1))}}var K=Object.defineProperty,ee=Object.getOwnPropertyDescriptor,W=(s,t,e,n)=>{for(var r=n>1?void 0:n?ee(t,e):t,i=s.length-1,c;i>=0;i--)(c=s[i])&&(r=(n?c(t,e,r):c(r))||r);return n&&r&&K(t,e,r),r},L=(s,t)=>(e,n)=>t(e,n,s),P;exports.UniverRPCMainThreadPlugin=(P=class extends a.Plugin{constructor(t,e){super("UNIVER_RPC_MAIN_THREAD_PLUGIN"),this._config=t,this._injector=e}async onStarting(t){const e=new Worker(this._config.workerURL),n=Z(e);[[S,{useFactory:()=>new x(n)}],[m,{useFactory:()=>{var i;return t.createInstance(m,((i=this._config)==null?void 0:i.unsyncMutations)??new Set)}}],[b,{useClass:M}]].forEach(i=>t.add(i))}},h(P,"type",a.PluginType.Univer),P);exports.UniverRPCMainThreadPlugin=W([L(1,l.Inject(l.Injector))],exports.UniverRPCMainThreadPlugin);var I;exports.UniverRPCWorkerThreadPlugin=(I=class extends a.Plugin{constructor(t,e){super("UNIVER_RPC_WORKER_THREAD_PLUGIN"),this._config=t,this._injector=e}onStarting(t){[[y],[S,{useFactory:()=>new x(Y())}],[C,{useClass:q}]].forEach(e=>t.add(e)),t.get(y)}},h(I,"type",a.PluginType.Univer),I);exports.UniverRPCWorkerThreadPlugin=W([L(1,l.Inject(l.Injector))],exports.UniverRPCWorkerThreadPlugin);exports.ChannelClient=D;exports.ChannelServer=T;exports.IRPChannelService=S;
1
+ "use strict";var A=Object.defineProperty;var H=(r,n,e)=>n in r?A(r,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[n]=e;var h=(r,n,e)=>(H(r,typeof n!="symbol"?n+"":n,e),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("@univerjs/core"),l=require("@wendellhu/redi"),d=require("rxjs/operators"),_=require("rxjs");var F=Object.defineProperty,k=Object.getOwnPropertyDescriptor,O=(r,n,e,t)=>{for(var s=t>1?void 0:t?k(n,e):n,i=r.length-1,c;i>=0;i--)(c=r[i])&&(s=(t?c(n,e,s):c(s))||s);return t&&s&&F(n,e,s),s},w=(r,n)=>(e,t)=>n(e,t,r);const E="univer.remote-sync-service",C=l.createIdentifier(E);let U=class{constructor(r){this._commandService=r}async syncMutation(r){return this._commandService.syncExecuteCommand(r.mutationInfo.id,r.mutationInfo.params,{onlyLocal:!0,fromSync:!0})}};U=O([w(0,a.ICommandService)],U);const M="univer.remote-instance-service",S=l.createIdentifier(M);let q=class{constructor(r,n){this._univerInstanceService=r,this._commandService=n}whenReady(){return Promise.resolve(!0)}async syncMutation(r){return this._commandService.syncExecuteCommand(r.mutationInfo.id,r.mutationInfo.params,{onlyLocal:!0,fromSync:!0})}async createInstance(r){const{type:n,snapshot:e}=r;try{switch(n){case a.UniverInstanceType.SHEET:return!!this._univerInstanceService.createSheet(e);default:throw new Error(`[RemoteInstanceReplicaService]: cannot create replica for document type: ${n}.`)}}catch(t){throw t instanceof Error?t:new Error(`${t}`)}}async disposeInstance(r){return this._univerInstanceService.disposeDocument(r.unitID)}};q=O([w(0,a.IUniverInstanceService),w(1,a.ICommandService)],q);function j(r){const n=r;return new class{call(e,t){const s=n[e];if(typeof s=="function"){let i=s.apply(n,[t]);return i instanceof Promise||(i=Promise.resolve(i)),i}throw new Error(`[RPC]: method not found for ${e}!`)}subscribe(e,t){const s=n[e];if(typeof s=="function"){const i=s.apply(n,t);return _.isObservable(i)?i:_.of(i)}throw new Error(`[RPC]: observable method not found for ${e}!`)}}}function $(r){return new Proxy({},{get(n,e){return function(...t){return z(e)?r.subscribe(e,t[0]):r.call(e,t[0])}}})}function z(r){return r.endsWith("$")}class T extends a.RxDisposable{constructor(e){super();h(this,"_initialized",new _.BehaviorSubject(!1));h(this,"_lastRequestCounter",0);h(this,"_pendingRequests",new Map);h(this,"_pendingSubscriptions",new Map);this._protocol=e,this._protocol.onMessage.pipe(d.takeUntil(this.dispose$)).subscribe(t=>this._onMessage(t))}getChannel(e){const t=this;return{call(s,i){return t._disposed?Promise.reject():t._remoteCall(e,s,i)},subscribe(s,i){if(t._disposed)throw new Error("[ChannelClient]: client is disposed!");return t._remoteSubscribe(e,s,i)}}}_whenReady(){return _.firstValueFrom(this._initialized.pipe(d.filter(e=>e),d.take(1)))}async _remoteCall(e,t,s){await this._whenReady();const i=++this._lastRequestCounter,u={seq:i,type:100,channelName:e,method:t,args:s},o=this;return new Promise((g,p)=>{const N={handle(R){switch(R.type){case 201:o._pendingRequests.delete(i),g(R.data);break;case 202:o._pendingRequests.delete(i),p(R.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(i,N),this._sendRequest(u)})}_remoteSubscribe(e,t,s){return new _.Observable(i=>{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:i.next(p.data);break;case 301:i.error(p.data);break;case 302:i.complete();break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(c,g),this._sendRequest(o)}),()=>{if(c===-1)return;const u={type:102,seq:c,channelName:e,method:t};this._sendRequest(u)}})}_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();h(this,"_channels",new Map);h(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})}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:i}=e,c=this._channels.get(t);let u;try{if(!c)throw new Error(`[ChannelServer]: Channel ${t} not found!`);u=c.call(s,i)}catch(o){u=Promise.reject(o)}u.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,i=this._channels.get(t);try{if(!i)throw new Error(`[ChannelServer]: Channel ${t} not found!`);const u=i.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,u)}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 f=l.createIdentifier("IRPChannelService");class x{constructor(n){h(this,"_client");h(this,"_server");this._client=new T(n),this._server=new D(n)}requestChannel(n){return this._client.getChannel(n)}registerChannel(n,e){this._server.registerChannel(n,e)}}var V=Object.defineProperty,G=Object.getOwnPropertyDescriptor,B=(r,n,e,t)=>{for(var s=t>1?void 0:t?G(n,e):n,i=r.length-1,c;i>=0;i--)(c=r[i])&&(s=(t?c(n,e,s):c(s))||s);return t&&s&&V(n,e,s),s},v=(r,n)=>(e,t)=>n(e,t,r);let m=class extends a.RxDisposable{constructor(n,e,t,s,i){super();h(this,"_remoteInstanceService");h(this,"_syncingUnits",new Set);this._injector=n,this._commandService=e,this._univerInstanceService=t,this._rpcChannelService=s,this._remoteSyncService=i,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(E,j(this._remoteSyncService)),this._injector.add([S,{useFactory:()=>$(this._rpcChannelService.requestChannel(M))}]),this._remoteInstanceService=this._injector.get(S)}_init(){this._univerInstanceService.sheetAdded$.pipe(d.takeUntil(this.dispose$)).subscribe(n=>{this._syncingUnits.add(n.getUnitId()),this._remoteInstanceService.createInstance({unitID:n.getUnitId(),type:a.UniverInstanceType.SHEET,snapshot:n.getSnapshot()})}),this._univerInstanceService.sheetDisposed$.pipe(d.takeUntil(this.dispose$)).subscribe(n=>{this._syncingUnits.delete(n.getUnitId()),this._remoteInstanceService.disposeInstance({unitID:n.getUnitId()})}),this.disposeWithMe(this._commandService.onCommandExecuted((n,e)=>{const{type:t,params:s}=n,i=(s==null?void 0:s.unitId)||"";t===a.CommandType.MUTATION&&(!i||this._syncingUnits.has(i))&&!(e!=null&&e.fromSync)&&this._remoteInstanceService.syncMutation({mutationInfo:n})}))}};m=B([a.OnLifecycle(a.LifecycleStages.Starting,m),v(0,l.Inject(l.Injector)),v(1,a.ICommandService),v(2,a.IUniverInstanceService),v(3,f),v(4,C)],m);var J=Object.defineProperty,Q=Object.getOwnPropertyDescriptor,X=(r,n,e,t)=>{for(var s=t>1?void 0:t?Q(n,e):n,i=r.length-1,c;i>=0;i--)(c=r[i])&&(s=(t?c(n,e,s):c(s))||s);return t&&s&&J(n,e,s),s},b=(r,n)=>(e,t)=>n(e,t,r);let y=class extends a.Disposable{constructor(n,e,t,s){super();h(this,"_remoteSyncService");this._injector=n,this._remoteInstanceService=e,this._commandService=t,this._rpcChannelService=s,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(M,j(this._remoteInstanceService)),this._injector.add([C,{useFactory:()=>$(this._rpcChannelService.requestChannel(E))}]),this._remoteSyncService=this._injector.get(C)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((n,e)=>{n.type===a.CommandType.MUTATION&&!(e!=null&&e.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:n})}))}};y=X([a.OnLifecycle(a.LifecycleStages.Starting,y),b(0,l.Inject(l.Injector)),b(1,S),b(2,a.ICommandService),b(3,f)],y);function Y(){return{send(r){postMessage(r)},onMessage:new _.Observable(r=>{const n=e=>{r.next(e.data)};return addEventListener("message",n),()=>removeEventListener("message",n)}).pipe(_.shareReplay(1))}}function Z(r){return{send(n){r.postMessage(n)},onMessage:new _.Observable(n=>{const e=t=>{n.next(t.data)};return r.addEventListener("message",e),()=>r.removeEventListener("message",e)}).pipe(_.shareReplay(1))}}var K=Object.defineProperty,ee=Object.getOwnPropertyDescriptor,W=(r,n,e,t)=>{for(var s=t>1?void 0:t?ee(n,e):n,i=r.length-1,c;i>=0;i--)(c=r[i])&&(s=(t?c(n,e,s):c(s))||s);return t&&s&&K(n,e,s),s},L=(r,n)=>(e,t)=>n(e,t,r),I;exports.UniverRPCMainThreadPlugin=(I=class extends a.Plugin{constructor(n,e){super("UNIVER_RPC_MAIN_THREAD_PLUGIN"),this._config=n,this._injector=e}async onStarting(n){const e=new Worker(this._config.workerURL),t=Z(e);[[f,{useFactory:()=>new x(t)}],[m],[C,{useClass:U}]].forEach(i=>n.add(i)),n.get(m)}},h(I,"type",a.PluginType.Univer),I);exports.UniverRPCMainThreadPlugin=W([L(1,l.Inject(l.Injector))],exports.UniverRPCMainThreadPlugin);var P;exports.UniverRPCWorkerThreadPlugin=(P=class extends a.Plugin{constructor(n,e){super("UNIVER_RPC_WORKER_THREAD_PLUGIN"),this._config=n,this._injector=e}onStarting(n){[[y],[f,{useFactory:()=>new x(Y())}],[S,{useClass:q}]].forEach(e=>n.add(e)),n.get(y)}},h(P,"type",a.PluginType.Univer),P);exports.UniverRPCWorkerThreadPlugin=W([L(1,l.Inject(l.Injector))],exports.UniverRPCWorkerThreadPlugin);exports.ChannelClient=T;exports.ChannelServer=D;exports.IRPChannelService=f;exports.IRemoteInstanceService=S;
package/lib/es/index.js CHANGED
@@ -1,22 +1,22 @@
1
1
  var Z = Object.defineProperty;
2
- var k = (n, t, e) => t in n ? Z(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e;
3
- var o = (n, t, e) => (k(n, typeof t != "symbol" ? t + "" : t, e), e);
4
- import { DocumentType as T, ICommandService as y, IUniverInstanceService as L, RxDisposable as q, OnLifecycle as W, LifecycleStages as N, CommandType as A, Disposable as K, Plugin as F, PluginType as H } from "@univerjs/core";
2
+ var K = (s, t, e) => t in s ? Z(s, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : s[t] = e;
3
+ var a = (s, t, e) => (K(s, typeof t != "symbol" ? t + "" : t, e), e);
4
+ import { UniverInstanceType as T, ICommandService as y, IUniverInstanceService as L, RxDisposable as M, OnLifecycle as W, LifecycleStages as N, CommandType as A, Disposable as k, Plugin as H, PluginType as F } from "@univerjs/core";
5
5
  import { createIdentifier as O, Inject as S, Injector as b } from "@wendellhu/redi";
6
6
  import { takeUntil as v, filter as ee, take as te } from "rxjs/operators";
7
- import { BehaviorSubject as se, firstValueFrom as ne, Observable as $, isObservable as re, of as ie, shareReplay as z } from "rxjs";
8
- var ce = Object.defineProperty, ae = Object.getOwnPropertyDescriptor, V = (n, t, e, s) => {
9
- for (var r = s > 1 ? void 0 : s ? ae(t, e) : t, i = n.length - 1, c; i >= 0; i--)
10
- (c = n[i]) && (r = (s ? c(t, e, r) : c(r)) || r);
11
- return s && r && ce(t, e, r), r;
12
- }, P = (n, t) => (e, s) => t(e, s, n);
13
- const D = "univer.remote-sync-service", m = O(D);
7
+ import { BehaviorSubject as ne, firstValueFrom as se, Observable as $, isObservable as re, of as ie, shareReplay as z } from "rxjs";
8
+ var ce = Object.defineProperty, oe = Object.getOwnPropertyDescriptor, V = (s, t, e, n) => {
9
+ for (var r = n > 1 ? void 0 : n ? oe(t, e) : t, i = s.length - 1, c; i >= 0; i--)
10
+ (c = s[i]) && (r = (n ? c(t, e, r) : c(r)) || r);
11
+ return n && r && ce(t, e, r), r;
12
+ }, P = (s, t) => (e, n) => t(e, n, s);
13
+ const U = "univer.remote-sync-service", m = O(U);
14
14
  let E = class {
15
- constructor(n) {
16
- this._commandService = n;
15
+ constructor(s) {
16
+ this._commandService = s;
17
17
  }
18
- async syncMutation(n) {
19
- return this._commandService.syncExecuteCommand(n.mutationInfo.id, n.mutationInfo.params, {
18
+ async syncMutation(s) {
19
+ return this._commandService.syncExecuteCommand(s.mutationInfo.id, s.mutationInfo.params, {
20
20
  onlyLocal: !0,
21
21
  fromSync: !0
22
22
  });
@@ -25,19 +25,22 @@ let E = class {
25
25
  E = V([
26
26
  P(0, y)
27
27
  ], E);
28
- const j = "univer.remote-instance-service", f = O(j);
29
- let M = class {
30
- constructor(n, t) {
31
- this._univerInstanceService = n, this._commandService = t;
28
+ const D = "univer.remote-instance-service", f = O(D);
29
+ let q = class {
30
+ constructor(s, t) {
31
+ this._univerInstanceService = s, this._commandService = t;
32
32
  }
33
- async syncMutation(n) {
34
- return this._commandService.syncExecuteCommand(n.mutationInfo.id, n.mutationInfo.params, {
33
+ whenReady() {
34
+ return Promise.resolve(!0);
35
+ }
36
+ async syncMutation(s) {
37
+ return this._commandService.syncExecuteCommand(s.mutationInfo.id, s.mutationInfo.params, {
35
38
  onlyLocal: !0,
36
39
  fromSync: !0
37
40
  });
38
41
  }
39
- async createInstance(n) {
40
- const { type: t, snapshot: e } = n;
42
+ async createInstance(s) {
43
+ const { type: t, snapshot: e } = s;
41
44
  try {
42
45
  switch (t) {
43
46
  case T.SHEET:
@@ -47,93 +50,93 @@ let M = class {
47
50
  `[RemoteInstanceReplicaService]: cannot create replica for document type: ${t}.`
48
51
  );
49
52
  }
50
- } catch (s) {
51
- throw s instanceof Error ? s : new Error(`${s}`);
53
+ } catch (n) {
54
+ throw n instanceof Error ? n : new Error(`${n}`);
52
55
  }
53
56
  }
54
- async disposeInstance(n) {
55
- return this._univerInstanceService.disposeDocument(n.unitID);
57
+ async disposeInstance(s) {
58
+ return this._univerInstanceService.disposeDocument(s.unitID);
56
59
  }
57
60
  };
58
- M = V([
61
+ q = V([
59
62
  P(0, L),
60
63
  P(1, y)
61
- ], M);
62
- function G(n) {
63
- const t = n;
64
+ ], q);
65
+ function G(s) {
66
+ const t = s;
64
67
  return new class {
65
- call(e, s) {
68
+ call(e, n) {
66
69
  const r = t[e];
67
70
  if (typeof r == "function") {
68
- let i = r.apply(t, [s]);
71
+ let i = r.apply(t, [n]);
69
72
  return i instanceof Promise || (i = Promise.resolve(i)), i;
70
73
  }
71
74
  throw new Error(`[RPC]: method not found for ${e}!`);
72
75
  }
73
- subscribe(e, s) {
76
+ subscribe(e, n) {
74
77
  const r = t[e];
75
78
  if (typeof r == "function") {
76
- const i = r.apply(t, s);
79
+ const i = r.apply(t, n);
77
80
  return re(i) ? i : ie(i);
78
81
  }
79
82
  throw new Error(`[RPC]: observable method not found for ${e}!`);
80
83
  }
81
84
  }();
82
85
  }
83
- function B(n) {
86
+ function B(s) {
84
87
  return new Proxy({}, {
85
88
  get(t, e) {
86
- return function(...s) {
87
- return oe(e) ? n.subscribe(e, s[0]) : n.call(e, s[0]);
89
+ return function(...n) {
90
+ return ae(e) ? s.subscribe(e, n[0]) : s.call(e, n[0]);
88
91
  };
89
92
  }
90
93
  });
91
94
  }
92
- function oe(n) {
93
- return n.endsWith("$");
95
+ function ae(s) {
96
+ return s.endsWith("$");
94
97
  }
95
- class he extends q {
98
+ class he extends M {
96
99
  constructor(e) {
97
100
  super();
98
- o(this, "_initialized", new se(!1));
99
- o(this, "_lastRequestCounter", 0);
100
- o(this, "_pendingRequests", /* @__PURE__ */ new Map());
101
- o(this, "_pendingSubscriptions", /* @__PURE__ */ new Map());
102
- this._protocol = e, this._protocol.onMessage.pipe(v(this.dispose$)).subscribe((s) => this._onMessage(s));
101
+ a(this, "_initialized", new ne(!1));
102
+ a(this, "_lastRequestCounter", 0);
103
+ a(this, "_pendingRequests", /* @__PURE__ */ new Map());
104
+ a(this, "_pendingSubscriptions", /* @__PURE__ */ new Map());
105
+ this._protocol = e, this._protocol.onMessage.pipe(v(this.dispose$)).subscribe((n) => this._onMessage(n));
103
106
  }
104
107
  getChannel(e) {
105
- const s = this;
108
+ const n = this;
106
109
  return {
107
110
  call(r, i) {
108
- return s._disposed ? Promise.reject() : s._remoteCall(e, r, i);
111
+ return n._disposed ? Promise.reject() : n._remoteCall(e, r, i);
109
112
  },
110
113
  subscribe(r, i) {
111
- if (s._disposed)
114
+ if (n._disposed)
112
115
  throw new Error("[ChannelClient]: client is disposed!");
113
- return s._remoteSubscribe(e, r, i);
116
+ return n._remoteSubscribe(e, r, i);
114
117
  }
115
118
  };
116
119
  }
117
120
  _whenReady() {
118
- return ne(
121
+ return se(
119
122
  this._initialized.pipe(
120
123
  ee((e) => e),
121
124
  te(1)
122
125
  )
123
126
  );
124
127
  }
125
- async _remoteCall(e, s, r) {
128
+ async _remoteCall(e, n, r) {
126
129
  await this._whenReady();
127
- const i = ++this._lastRequestCounter, h = { seq: i, type: 100, channelName: e, method: s, args: r }, a = this;
128
- return new Promise((R, l) => {
130
+ const i = ++this._lastRequestCounter, h = { seq: i, type: 100, channelName: e, method: n, args: r }, o = this;
131
+ return new Promise((g, l) => {
129
132
  const Y = {
130
- handle(g) {
131
- switch (g.type) {
133
+ handle(R) {
134
+ switch (R.type) {
132
135
  case 201:
133
- a._pendingRequests.delete(i), R(g.data);
136
+ o._pendingRequests.delete(i), g(R.data);
134
137
  break;
135
138
  case 202:
136
- a._pendingRequests.delete(i), l(g.data);
139
+ o._pendingRequests.delete(i), l(R.data);
137
140
  break;
138
141
  default:
139
142
  throw new Error("[ChannelClient]: unknown response type!");
@@ -143,12 +146,12 @@ class he extends q {
143
146
  this._pendingRequests.set(i, Y), this._sendRequest(h);
144
147
  });
145
148
  }
146
- _remoteSubscribe(e, s, r) {
149
+ _remoteSubscribe(e, n, r) {
147
150
  return new $((i) => {
148
151
  let c = -1;
149
152
  return this._whenReady().then(() => {
150
153
  c = ++this._lastRequestCounter;
151
- const a = { seq: c, type: 101, channelName: e, method: s, args: r }, R = {
154
+ const o = { seq: c, type: 101, channelName: e, method: n, args: r }, g = {
152
155
  handle(l) {
153
156
  switch (l.type) {
154
157
  case 300:
@@ -165,7 +168,7 @@ class he extends q {
165
168
  }
166
169
  }
167
170
  };
168
- this._pendingRequests.set(c, R), this._sendRequest(a);
171
+ this._pendingRequests.set(c, g), this._sendRequest(o);
169
172
  }), () => {
170
173
  if (c === -1)
171
174
  return;
@@ -173,7 +176,7 @@ class he extends q {
173
176
  type: 102,
174
177
  seq: c,
175
178
  channelName: e,
176
- method: s
179
+ method: n
177
180
  };
178
181
  this._sendRequest(h);
179
182
  };
@@ -183,7 +186,7 @@ class he extends q {
183
186
  this._protocol.send(e);
184
187
  }
185
188
  _onMessage(e) {
186
- var s;
189
+ var n;
187
190
  switch (e.type) {
188
191
  case 0:
189
192
  this._initialized.next(!0);
@@ -193,24 +196,24 @@ class he extends q {
193
196
  case 300:
194
197
  case 302:
195
198
  case 301:
196
- (s = this._pendingRequests.get(e.seq)) == null || s.handle(e);
199
+ (n = this._pendingRequests.get(e.seq)) == null || n.handle(e);
197
200
  break;
198
201
  }
199
202
  }
200
203
  }
201
- class le extends q {
204
+ class le extends M {
202
205
  constructor(e) {
203
206
  super();
204
- o(this, "_channels", /* @__PURE__ */ new Map());
205
- o(this, "_subscriptions", /* @__PURE__ */ new Map());
206
- this._protocol = e, this._protocol.onMessage.pipe(v(this.dispose$)).subscribe((s) => this._onRequest(s)), this._sendResponse({
207
+ a(this, "_channels", /* @__PURE__ */ new Map());
208
+ a(this, "_subscriptions", /* @__PURE__ */ new Map());
209
+ this._protocol = e, this._protocol.onMessage.pipe(v(this.dispose$)).subscribe((n) => this._onRequest(n)), this._sendResponse({
207
210
  seq: -1,
208
211
  type: 0
209
212
  /* INITIALIZE */
210
213
  });
211
214
  }
212
- registerChannel(e, s) {
213
- this._channels.set(e, s);
215
+ registerChannel(e, n) {
216
+ this._channels.set(e, n);
214
217
  }
215
218
  _onRequest(e) {
216
219
  switch (e.type) {
@@ -226,32 +229,32 @@ class le extends q {
226
229
  }
227
230
  }
228
231
  _onMethodCall(e) {
229
- const { channelName: s, method: r, args: i } = e, c = this._channels.get(s);
232
+ const { channelName: n, method: r, args: i } = e, c = this._channels.get(n);
230
233
  let h;
231
234
  try {
232
235
  if (!c)
233
- throw new Error(`[ChannelServer]: Channel ${s} not found!`);
236
+ throw new Error(`[ChannelServer]: Channel ${n} not found!`);
234
237
  h = c.call(r, i);
235
- } catch (a) {
236
- h = Promise.reject(a);
238
+ } catch (o) {
239
+ h = Promise.reject(o);
237
240
  }
238
- h.then((a) => {
239
- this._sendResponse({ seq: e.seq, type: 201, data: a });
240
- }).catch((a) => {
241
- a instanceof Error ? this._sendResponse({ seq: e.seq, type: 202, data: a.message }) : this._sendResponse({ seq: e.seq, type: 202, data: String(a) });
241
+ h.then((o) => {
242
+ this._sendResponse({ seq: e.seq, type: 201, data: o });
243
+ }).catch((o) => {
244
+ o instanceof Error ? this._sendResponse({ seq: e.seq, type: 202, data: o.message }) : this._sendResponse({ seq: e.seq, type: 202, data: String(o) });
242
245
  });
243
246
  }
244
247
  _onSubscribe(e) {
245
- const { channelName: s, seq: r } = e, i = this._channels.get(s);
248
+ const { channelName: n, seq: r } = e, i = this._channels.get(n);
246
249
  try {
247
250
  if (!i)
248
- throw new Error(`[ChannelServer]: Channel ${s} not found!`);
251
+ throw new Error(`[ChannelServer]: Channel ${n} not found!`);
249
252
  const h = i.subscribe(e.method, e.args).subscribe({
250
- next: (a) => {
251
- this._sendResponse({ seq: r, type: 300, data: a });
253
+ next: (o) => {
254
+ this._sendResponse({ seq: r, type: 300, data: o });
252
255
  },
253
- error: (a) => {
254
- this._sendResponse({ seq: r, type: 301, data: a.message }), this._sendResponse({
256
+ error: (o) => {
257
+ this._sendResponse({ seq: r, type: 301, data: o.message }), this._sendResponse({
255
258
  seq: r,
256
259
  type: 302
257
260
  /* SUBSCRIBE_COMPLETE */
@@ -271,8 +274,8 @@ class le extends q {
271
274
  }
272
275
  }
273
276
  _onUnsubscribe(e) {
274
- const s = this._subscriptions.get(e.seq);
275
- s && (s.unsubscribe(), this._subscriptions.delete(e.seq));
277
+ const n = this._subscriptions.get(e.seq);
278
+ n && (n.unsubscribe(), this._subscriptions.delete(e.seq));
276
279
  }
277
280
  _sendResponse(e) {
278
281
  this._protocol.send(e);
@@ -281,8 +284,8 @@ class le extends q {
281
284
  const C = O("IRPChannelService");
282
285
  class J {
283
286
  constructor(t) {
284
- o(this, "_client");
285
- o(this, "_server");
287
+ a(this, "_client");
288
+ a(this, "_server");
286
289
  this._client = new he(t), this._server = new le(t);
287
290
  }
288
291
  requestChannel(t) {
@@ -292,70 +295,72 @@ class J {
292
295
  this._server.registerChannel(t, e);
293
296
  }
294
297
  }
295
- var _e = Object.defineProperty, ue = Object.getOwnPropertyDescriptor, pe = (n, t, e, s) => {
296
- for (var r = s > 1 ? void 0 : s ? ue(t, e) : t, i = n.length - 1, c; i >= 0; i--)
297
- (c = n[i]) && (r = (s ? c(t, e, r) : c(r)) || r);
298
- return s && r && _e(t, e, r), r;
299
- }, _ = (n, t) => (e, s) => t(e, s, n);
300
- let u = class extends q {
301
- constructor(t, e, s, r, i, c) {
298
+ var _e = Object.defineProperty, ue = Object.getOwnPropertyDescriptor, pe = (s, t, e, n) => {
299
+ for (var r = n > 1 ? void 0 : n ? ue(t, e) : t, i = s.length - 1, c; i >= 0; i--)
300
+ (c = s[i]) && (r = (n ? c(t, e, r) : c(r)) || r);
301
+ return n && r && _e(t, e, r), r;
302
+ }, _ = (s, t) => (e, n) => t(e, n, s);
303
+ let u = class extends M {
304
+ constructor(t, e, n, r, i) {
302
305
  super();
303
- o(this, "_remoteInstanceService");
304
- this._unsyncMutations = t, this._injector = e, this._commandService = s, this._univerInstanceService = r, this._rpcChannelService = i, this._remoteSyncService = c, this._initRPCChannels(), this._init();
306
+ a(this, "_remoteInstanceService");
307
+ a(this, "_syncingUnits", /* @__PURE__ */ new Set());
308
+ this._injector = t, this._commandService = e, this._univerInstanceService = n, this._rpcChannelService = r, this._remoteSyncService = i, this._initRPCChannels(), this._init();
305
309
  }
306
310
  _initRPCChannels() {
307
- this._rpcChannelService.registerChannel(D, G(this._remoteSyncService)), this._injector.add([
311
+ this._rpcChannelService.registerChannel(U, G(this._remoteSyncService)), this._injector.add([
308
312
  f,
309
313
  {
310
- useFactory: () => B(this._rpcChannelService.requestChannel(j))
314
+ useFactory: () => B(this._rpcChannelService.requestChannel(D))
311
315
  }
312
316
  ]), this._remoteInstanceService = this._injector.get(f);
313
317
  }
314
318
  _init() {
315
319
  this._univerInstanceService.sheetAdded$.pipe(v(this.dispose$)).subscribe((t) => {
316
- this._remoteInstanceService.createInstance({
320
+ this._syncingUnits.add(t.getUnitId()), this._remoteInstanceService.createInstance({
317
321
  unitID: t.getUnitId(),
318
322
  type: T.SHEET,
319
323
  snapshot: t.getSnapshot()
320
324
  });
321
325
  }), this._univerInstanceService.sheetDisposed$.pipe(v(this.dispose$)).subscribe((t) => {
322
- this._remoteInstanceService.disposeInstance({
326
+ this._syncingUnits.delete(t.getUnitId()), this._remoteInstanceService.disposeInstance({
323
327
  unitID: t.getUnitId()
324
328
  });
325
329
  }), this.disposeWithMe(
326
330
  // Mutations executed on the main thread should be synced to the worker thread.
327
331
  this._commandService.onCommandExecuted((t, e) => {
328
- t.type === A.MUTATION && !(e != null && e.fromSync) && !this._unsyncMutations.has(t.id) && this._remoteInstanceService.syncMutation({
329
- mutationInfo: t
330
- });
332
+ const { type: n, params: r } = t, i = (r == null ? void 0 : r.unitId) || "";
333
+ // only sync mutations to the worker thread
334
+ n === A.MUTATION && (!i || this._syncingUnits.has(i)) && // do not sync mutations from the web worker back to the web worker
335
+ !(e != null && e.fromSync) && this._remoteInstanceService.syncMutation({ mutationInfo: t });
331
336
  })
332
337
  );
333
338
  }
334
339
  };
335
340
  u = pe([
336
341
  W(N.Starting, u),
337
- _(1, S(b)),
338
- _(2, y),
339
- _(3, L),
340
- _(4, C),
341
- _(5, m)
342
+ _(0, S(b)),
343
+ _(1, y),
344
+ _(2, L),
345
+ _(3, C),
346
+ _(4, m)
342
347
  ], u);
343
- var de = Object.defineProperty, ve = Object.getOwnPropertyDescriptor, me = (n, t, e, s) => {
344
- for (var r = s > 1 ? void 0 : s ? ve(t, e) : t, i = n.length - 1, c; i >= 0; i--)
345
- (c = n[i]) && (r = (s ? c(t, e, r) : c(r)) || r);
346
- return s && r && de(t, e, r), r;
347
- }, d = (n, t) => (e, s) => t(e, s, n);
348
- let p = class extends K {
349
- constructor(t, e, s, r) {
348
+ var de = Object.defineProperty, ve = Object.getOwnPropertyDescriptor, me = (s, t, e, n) => {
349
+ for (var r = n > 1 ? void 0 : n ? ve(t, e) : t, i = s.length - 1, c; i >= 0; i--)
350
+ (c = s[i]) && (r = (n ? c(t, e, r) : c(r)) || r);
351
+ return n && r && de(t, e, r), r;
352
+ }, d = (s, t) => (e, n) => t(e, n, s);
353
+ let p = class extends k {
354
+ constructor(t, e, n, r) {
350
355
  super();
351
- o(this, "_remoteSyncService");
352
- this._injector = t, this._remoteInstanceService = e, this._commandService = s, this._rpcChannelService = r, this._initRPCChannels(), this._init();
356
+ a(this, "_remoteSyncService");
357
+ this._injector = t, this._remoteInstanceService = e, this._commandService = n, this._rpcChannelService = r, this._initRPCChannels(), this._init();
353
358
  }
354
359
  _initRPCChannels() {
355
- this._rpcChannelService.registerChannel(j, G(this._remoteInstanceService)), this._injector.add([
360
+ this._rpcChannelService.registerChannel(D, G(this._remoteInstanceService)), this._injector.add([
356
361
  m,
357
362
  {
358
- useFactory: () => B(this._rpcChannelService.requestChannel(D))
363
+ useFactory: () => B(this._rpcChannelService.requestChannel(U))
359
364
  }
360
365
  ]), this._remoteSyncService = this._injector.get(m);
361
366
  }
@@ -379,40 +384,40 @@ p = me([
379
384
  ], p);
380
385
  function fe() {
381
386
  return {
382
- send(n) {
383
- postMessage(n);
387
+ send(s) {
388
+ postMessage(s);
384
389
  },
385
- onMessage: new $((n) => {
390
+ onMessage: new $((s) => {
386
391
  const t = (e) => {
387
- n.next(e.data);
392
+ s.next(e.data);
388
393
  };
389
394
  return addEventListener("message", t), () => removeEventListener("message", t);
390
395
  }).pipe(z(1))
391
396
  };
392
397
  }
393
- function ye(n) {
398
+ function ye(s) {
394
399
  return {
395
400
  send(t) {
396
- n.postMessage(t);
401
+ s.postMessage(t);
397
402
  },
398
403
  onMessage: new $((t) => {
399
- const e = (s) => {
400
- t.next(s.data);
404
+ const e = (n) => {
405
+ t.next(n.data);
401
406
  };
402
- return n.addEventListener("message", e), () => n.removeEventListener("message", e);
407
+ return s.addEventListener("message", e), () => s.removeEventListener("message", e);
403
408
  }).pipe(z(1))
404
409
  };
405
410
  }
406
- var Se = Object.defineProperty, be = Object.getOwnPropertyDescriptor, Q = (n, t, e, s) => {
407
- for (var r = s > 1 ? void 0 : s ? be(t, e) : t, i = n.length - 1, c; i >= 0; i--)
408
- (c = n[i]) && (r = (s ? c(t, e, r) : c(r)) || r);
409
- return s && r && Se(t, e, r), r;
410
- }, X = (n, t) => (e, s) => t(e, s, n), w;
411
- let x = (w = class extends F {
412
- constructor(n, t) {
413
- super("UNIVER_RPC_MAIN_THREAD_PLUGIN"), this._config = n, this._injector = t;
414
- }
415
- async onStarting(n) {
411
+ var Se = Object.defineProperty, be = Object.getOwnPropertyDescriptor, Q = (s, t, e, n) => {
412
+ for (var r = n > 1 ? void 0 : n ? be(t, e) : t, i = s.length - 1, c; i >= 0; i--)
413
+ (c = s[i]) && (r = (n ? c(t, e, r) : c(r)) || r);
414
+ return n && r && Se(t, e, r), r;
415
+ }, X = (s, t) => (e, n) => t(e, n, s), w;
416
+ let j = (w = class extends H {
417
+ constructor(s, t) {
418
+ super("UNIVER_RPC_MAIN_THREAD_PLUGIN"), this._config = s, this._injector = t;
419
+ }
420
+ async onStarting(s) {
416
421
  const t = new Worker(this._config.workerURL), e = ye(t);
417
422
  [
418
423
  [
@@ -421,28 +426,20 @@ let x = (w = class extends F {
421
426
  useFactory: () => new J(e)
422
427
  }
423
428
  ],
424
- [
425
- u,
426
- {
427
- useFactory: () => {
428
- var r;
429
- return n.createInstance(u, ((r = this._config) == null ? void 0 : r.unsyncMutations) ?? /* @__PURE__ */ new Set());
430
- }
431
- }
432
- ],
429
+ [u],
433
430
  [m, { useClass: E }]
434
- ].forEach((r) => n.add(r));
431
+ ].forEach((r) => s.add(r)), s.get(u);
435
432
  }
436
- }, o(w, "type", H.Univer), w);
437
- x = Q([
433
+ }, a(w, "type", F.Univer), w);
434
+ j = Q([
438
435
  X(1, S(b))
439
- ], x);
436
+ ], j);
440
437
  var I;
441
- let U = (I = class extends F {
442
- constructor(n, t) {
443
- super("UNIVER_RPC_WORKER_THREAD_PLUGIN"), this._config = n, this._injector = t;
438
+ let x = (I = class extends H {
439
+ constructor(s, t) {
440
+ super("UNIVER_RPC_WORKER_THREAD_PLUGIN"), this._config = s, this._injector = t;
444
441
  }
445
- onStarting(n) {
442
+ onStarting(s) {
446
443
  [
447
444
  [p],
448
445
  [
@@ -451,17 +448,18 @@ let U = (I = class extends F {
451
448
  useFactory: () => new J(fe())
452
449
  }
453
450
  ],
454
- [f, { useClass: M }]
455
- ].forEach((t) => n.add(t)), n.get(p);
451
+ [f, { useClass: q }]
452
+ ].forEach((t) => s.add(t)), s.get(p);
456
453
  }
457
- }, o(I, "type", H.Univer), I);
458
- U = Q([
454
+ }, a(I, "type", F.Univer), I);
455
+ x = Q([
459
456
  X(1, S(b))
460
- ], U);
457
+ ], x);
461
458
  export {
462
459
  he as ChannelClient,
463
460
  le as ChannelServer,
464
461
  C as IRPChannelService,
465
- x as UniverRPCMainThreadPlugin,
466
- U as UniverRPCWorkerThreadPlugin
462
+ f as IRemoteInstanceService,
463
+ j as UniverRPCMainThreadPlugin,
464
+ x as UniverRPCWorkerThreadPlugin
467
465
  };
@@ -22,14 +22,14 @@ import { IRPChannelService } from '../../services/rpc/channel.service';
22
22
  * the worker thread.
23
23
  */
24
24
  export declare class DataSyncPrimaryController extends RxDisposable {
25
- private readonly _unsyncMutations;
26
25
  private readonly _injector;
27
26
  private readonly _commandService;
28
27
  private readonly _univerInstanceService;
29
28
  private readonly _rpcChannelService;
30
29
  private readonly _remoteSyncService;
31
30
  private _remoteInstanceService;
32
- constructor(_unsyncMutations: Set<string>, _injector: Injector, _commandService: ICommandService, _univerInstanceService: IUniverInstanceService, _rpcChannelService: IRPChannelService, _remoteSyncService: IRemoteSyncService);
31
+ private readonly _syncingUnits;
32
+ constructor(_injector: Injector, _commandService: ICommandService, _univerInstanceService: IUniverInstanceService, _rpcChannelService: IRPChannelService, _remoteSyncService: IRemoteSyncService);
33
33
  private _initRPCChannels;
34
34
  private _init;
35
35
  }
@@ -14,5 +14,6 @@
14
14
  * limitations under the License.
15
15
  */
16
16
  export { type IUniverRPCMainThreadConfig, type IUniverRPCWorkerThreadPluginConfig, UniverRPCMainThreadPlugin, UniverRPCWorkerThreadPlugin, } from './plugin';
17
+ export { IRemoteInstanceService } from './services/remote-instance/remote-instance.service';
17
18
  export { IRPChannelService } from './services/rpc/channel.service';
18
19
  export { ChannelClient, ChannelServer, type IMessageProtocol } from './services/rpc/rpc.service';
@@ -17,7 +17,6 @@ import { Plugin, PluginType } from '@univerjs/core';
17
17
  import { Injector } from '@wendellhu/redi';
18
18
  export interface IUniverRPCMainThreadConfig {
19
19
  workerURL: string | URL;
20
- unsyncMutations?: Set<string>;
21
20
  }
22
21
  /**
23
22
  * This plugin is used to register the RPC services on the main thread. It
@@ -14,7 +14,7 @@
14
14
  * limitations under the License.
15
15
  */
16
16
  import type { IExecutionOptions, IMutationInfo, IWorkbookData } from '@univerjs/core';
17
- import { DocumentType, ICommandService, IUniverInstanceService } from '@univerjs/core';
17
+ import { ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
18
18
  export interface IRemoteSyncMutationOptions extends IExecutionOptions {
19
19
  /** If this mutation is executed after it was sent from the peer univer instance (e.g. in a web worker). */
20
20
  fromSync?: boolean;
@@ -47,9 +47,11 @@ export declare const RemoteInstanceServiceName = "univer.remote-instance-service
47
47
  */
48
48
  export declare const IRemoteInstanceService: import("@wendellhu/redi").IdentifierDecorator<IRemoteInstanceService>;
49
49
  export interface IRemoteInstanceService {
50
+ /** Tell other modules if the `IRemoteInstanceService` is ready to load files. */
51
+ whenReady(): Promise<true>;
50
52
  createInstance(params: {
51
53
  unitID: string;
52
- type: DocumentType;
54
+ type: UniverInstanceType;
53
55
  snapshot: IWorkbookData;
54
56
  }): Promise<boolean>;
55
57
  disposeInstance(params: {
@@ -63,12 +65,13 @@ export declare class RemoteInstanceReplicaService implements IRemoteInstanceServ
63
65
  private readonly _univerInstanceService;
64
66
  private readonly _commandService;
65
67
  constructor(_univerInstanceService: IUniverInstanceService, _commandService: ICommandService);
68
+ whenReady(): Promise<true>;
66
69
  syncMutation(params: {
67
70
  mutationInfo: IMutationInfo;
68
71
  }): Promise<boolean>;
69
72
  createInstance(params: {
70
73
  unitID: string;
71
- type: DocumentType;
74
+ type: UniverInstanceType;
72
75
  snapshot: IWorkbookData;
73
76
  }): Promise<boolean>;
74
77
  disposeInstance(params: {
package/lib/umd/index.js CHANGED
@@ -1 +1 @@
1
- (function(o,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):(o=typeof globalThis<"u"?globalThis:o||self,c(o.UniverRpc={},o.UniverCore,o["@wendellhu/redi"],o.rxjs.operators,o.rxjs))})(this,function(o,c,h,p,d){"use strict";var ee=Object.defineProperty;var ne=(o,c,h)=>c in o?ee(o,c,{enumerable:!0,configurable:!0,writable:!0,value:h}):o[c]=h;var u=(o,c,h)=>(ne(o,typeof c!="symbol"?c+"":c,h),h);var q,E;var A=Object.defineProperty,F=Object.getOwnPropertyDescriptor,j=(r,n,e,t)=>{for(var s=t>1?void 0:t?F(n,e):n,i=r.length-1,a;i>=0;i--)(a=r[i])&&(s=(t?a(n,e,s):a(s))||s);return t&&s&&A(n,e,s),s},g=(r,n)=>(e,t)=>n(e,t,r);const P="univer.remote-sync-service",b=h.createIdentifier(P);let I=class{constructor(r){this._commandService=r}async syncMutation(r){return this._commandService.syncExecuteCommand(r.mutationInfo.id,r.mutationInfo.params,{onlyLocal:!0,fromSync:!0})}};I=j([g(0,c.ICommandService)],I);const w="univer.remote-instance-service",C=h.createIdentifier(w);let M=class{constructor(r,n){this._univerInstanceService=r,this._commandService=n}async syncMutation(r){return this._commandService.syncExecuteCommand(r.mutationInfo.id,r.mutationInfo.params,{onlyLocal:!0,fromSync:!0})}async createInstance(r){const{type:n,snapshot:e}=r;try{switch(n){case c.DocumentType.SHEET:return!!this._univerInstanceService.createSheet(e);default:throw new Error(`[RemoteInstanceReplicaService]: cannot create replica for document type: ${n}.`)}}catch(t){throw t instanceof Error?t:new Error(`${t}`)}}async disposeInstance(r){return this._univerInstanceService.disposeDocument(r.unitID)}};M=j([g(0,c.IUniverInstanceService),g(1,c.ICommandService)],M);function T(r){const n=r;return new class{call(e,t){const s=n[e];if(typeof s=="function"){let i=s.apply(n,[t]);return i instanceof Promise||(i=Promise.resolve(i)),i}throw new Error(`[RPC]: method not found for ${e}!`)}subscribe(e,t){const s=n[e];if(typeof s=="function"){const i=s.apply(n,t);return d.isObservable(i)?i:d.of(i)}throw new Error(`[RPC]: observable method not found for ${e}!`)}}}function $(r){return new Proxy({},{get(n,e){return function(...t){return H(e)?r.subscribe(e,t[0]):r.call(e,t[0])}}})}function H(r){return r.endsWith("$")}class D extends c.RxDisposable{constructor(e){super();u(this,"_initialized",new d.BehaviorSubject(!1));u(this,"_lastRequestCounter",0);u(this,"_pendingRequests",new Map);u(this,"_pendingSubscriptions",new Map);this._protocol=e,this._protocol.onMessage.pipe(p.takeUntil(this.dispose$)).subscribe(t=>this._onMessage(t))}getChannel(e){const t=this;return{call(s,i){return t._disposed?Promise.reject():t._remoteCall(e,s,i)},subscribe(s,i){if(t._disposed)throw new Error("[ChannelClient]: client is disposed!");return t._remoteSubscribe(e,s,i)}}}_whenReady(){return d.firstValueFrom(this._initialized.pipe(p.filter(e=>e),p.take(1)))}async _remoteCall(e,t,s){await this._whenReady();const i=++this._lastRequestCounter,_={seq:i,type:100,channelName:e,method:t,args:s},l=this;return new Promise((O,S)=>{const K={handle(U){switch(U.type){case 201:l._pendingRequests.delete(i),O(U.data);break;case 202:l._pendingRequests.delete(i),S(U.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(i,K),this._sendRequest(_)})}_remoteSubscribe(e,t,s){return new d.Observable(i=>{let a=-1;return this._whenReady().then(()=>{a=++this._lastRequestCounter;const l={seq:a,type:101,channelName:e,method:t,args:s},O={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(a,O),this._sendRequest(l)}),()=>{if(a===-1)return;const _={type:102,seq:a,channelName:e,method:t};this._sendRequest(_)}})}_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 W extends c.RxDisposable{constructor(e){super();u(this,"_channels",new Map);u(this,"_subscriptions",new Map);this._protocol=e,this._protocol.onMessage.pipe(p.takeUntil(this.dispose$)).subscribe(t=>this._onRequest(t)),this._sendResponse({seq:-1,type:0})}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:i}=e,a=this._channels.get(t);let _;try{if(!a)throw new Error(`[ChannelServer]: Channel ${t} not found!`);_=a.call(s,i)}catch(l){_=Promise.reject(l)}_.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:t,seq:s}=e,i=this._channels.get(t);try{if(!i)throw new Error(`[ChannelServer]: Channel ${t} not found!`);const _=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,_)}catch(a){a instanceof Error?this._sendResponse({seq:e.seq,type:301,data:a.message}):this._sendResponse({seq:e.seq,type:301,data:String(a)})}}_onUnsubscribe(e){const t=this._subscriptions.get(e.seq);t&&(t.unsubscribe(),this._subscriptions.delete(e.seq))}_sendResponse(e){this._protocol.send(e)}}const v=h.createIdentifier("IRPChannelService");class L{constructor(n){u(this,"_client");u(this,"_server");this._client=new D(n),this._server=new W(n)}requestChannel(n){return this._client.getChannel(n)}registerChannel(n,e){this._server.registerChannel(n,e)}}var k=Object.defineProperty,z=Object.getOwnPropertyDescriptor,V=(r,n,e,t)=>{for(var s=t>1?void 0:t?z(n,e):n,i=r.length-1,a;i>=0;i--)(a=r[i])&&(s=(t?a(n,e,s):a(s))||s);return t&&s&&k(n,e,s),s},m=(r,n)=>(e,t)=>n(e,t,r);let f=class extends c.RxDisposable{constructor(n,e,t,s,i,a){super();u(this,"_remoteInstanceService");this._unsyncMutations=n,this._injector=e,this._commandService=t,this._univerInstanceService=s,this._rpcChannelService=i,this._remoteSyncService=a,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(P,T(this._remoteSyncService)),this._injector.add([C,{useFactory:()=>$(this._rpcChannelService.requestChannel(w))}]),this._remoteInstanceService=this._injector.get(C)}_init(){this._univerInstanceService.sheetAdded$.pipe(p.takeUntil(this.dispose$)).subscribe(n=>{this._remoteInstanceService.createInstance({unitID:n.getUnitId(),type:c.DocumentType.SHEET,snapshot:n.getSnapshot()})}),this._univerInstanceService.sheetDisposed$.pipe(p.takeUntil(this.dispose$)).subscribe(n=>{this._remoteInstanceService.disposeInstance({unitID:n.getUnitId()})}),this.disposeWithMe(this._commandService.onCommandExecuted((n,e)=>{n.type===c.CommandType.MUTATION&&!(e!=null&&e.fromSync)&&!this._unsyncMutations.has(n.id)&&this._remoteInstanceService.syncMutation({mutationInfo:n})}))}};f=V([c.OnLifecycle(c.LifecycleStages.Starting,f),m(1,h.Inject(h.Injector)),m(2,c.ICommandService),m(3,c.IUniverInstanceService),m(4,v),m(5,b)],f);var G=Object.defineProperty,B=Object.getOwnPropertyDescriptor,J=(r,n,e,t)=>{for(var s=t>1?void 0:t?B(n,e):n,i=r.length-1,a;i>=0;i--)(a=r[i])&&(s=(t?a(n,e,s):a(s))||s);return t&&s&&G(n,e,s),s},R=(r,n)=>(e,t)=>n(e,t,r);let y=class extends c.Disposable{constructor(n,e,t,s){super();u(this,"_remoteSyncService");this._injector=n,this._remoteInstanceService=e,this._commandService=t,this._rpcChannelService=s,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(w,T(this._remoteInstanceService)),this._injector.add([b,{useFactory:()=>$(this._rpcChannelService.requestChannel(P))}]),this._remoteSyncService=this._injector.get(b)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((n,e)=>{n.type===c.CommandType.MUTATION&&!(e!=null&&e.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:n})}))}};y=J([c.OnLifecycle(c.LifecycleStages.Starting,y),R(0,h.Inject(h.Injector)),R(1,C),R(2,c.ICommandService),R(3,v)],y);function Q(){return{send(r){postMessage(r)},onMessage:new d.Observable(r=>{const n=e=>{r.next(e.data)};return addEventListener("message",n),()=>removeEventListener("message",n)}).pipe(d.shareReplay(1))}}function X(r){return{send(n){r.postMessage(n)},onMessage:new d.Observable(n=>{const e=t=>{n.next(t.data)};return r.addEventListener("message",e),()=>r.removeEventListener("message",e)}).pipe(d.shareReplay(1))}}var Y=Object.defineProperty,Z=Object.getOwnPropertyDescriptor,x=(r,n,e,t)=>{for(var s=t>1?void 0:t?Z(n,e):n,i=r.length-1,a;i>=0;i--)(a=r[i])&&(s=(t?a(n,e,s):a(s))||s);return t&&s&&Y(n,e,s),s},N=(r,n)=>(e,t)=>n(e,t,r);o.UniverRPCMainThreadPlugin=(q=class extends c.Plugin{constructor(n,e){super("UNIVER_RPC_MAIN_THREAD_PLUGIN"),this._config=n,this._injector=e}async onStarting(n){const e=new Worker(this._config.workerURL),t=X(e);[[v,{useFactory:()=>new L(t)}],[f,{useFactory:()=>{var i;return n.createInstance(f,((i=this._config)==null?void 0:i.unsyncMutations)??new Set)}}],[b,{useClass:I}]].forEach(i=>n.add(i))}},u(q,"type",c.PluginType.Univer),q),o.UniverRPCMainThreadPlugin=x([N(1,h.Inject(h.Injector))],o.UniverRPCMainThreadPlugin),o.UniverRPCWorkerThreadPlugin=(E=class extends c.Plugin{constructor(n,e){super("UNIVER_RPC_WORKER_THREAD_PLUGIN"),this._config=n,this._injector=e}onStarting(n){[[y],[v,{useFactory:()=>new L(Q())}],[C,{useClass:M}]].forEach(e=>n.add(e)),n.get(y)}},u(E,"type",c.PluginType.Univer),E),o.UniverRPCWorkerThreadPlugin=x([N(1,h.Inject(h.Injector))],o.UniverRPCWorkerThreadPlugin),o.ChannelClient=D,o.ChannelServer=W,o.IRPChannelService=v,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})});
1
+ (function(o,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):(o=typeof globalThis<"u"?globalThis:o||self,c(o.UniverRpc={},o.UniverCore,o["@wendellhu/redi"],o.rxjs.operators,o.rxjs))})(this,function(o,c,h,p,d){"use strict";var ee=Object.defineProperty;var ne=(o,c,h)=>c in o?ee(o,c,{enumerable:!0,configurable:!0,writable:!0,value:h}):o[c]=h;var u=(o,c,h)=>(ne(o,typeof c!="symbol"?c+"":c,h),h);var q,E;var A=Object.defineProperty,H=Object.getOwnPropertyDescriptor,j=(r,n,e,t)=>{for(var s=t>1?void 0:t?H(n,e):n,i=r.length-1,a;i>=0;i--)(a=r[i])&&(s=(t?a(n,e,s):a(s))||s);return t&&s&&A(n,e,s),s},g=(r,n)=>(e,t)=>n(e,t,r);const I="univer.remote-sync-service",b=h.createIdentifier(I);let P=class{constructor(r){this._commandService=r}async syncMutation(r){return this._commandService.syncExecuteCommand(r.mutationInfo.id,r.mutationInfo.params,{onlyLocal:!0,fromSync:!0})}};P=j([g(0,c.ICommandService)],P);const w="univer.remote-instance-service",v=h.createIdentifier(w);let U=class{constructor(r,n){this._univerInstanceService=r,this._commandService=n}whenReady(){return Promise.resolve(!0)}async syncMutation(r){return this._commandService.syncExecuteCommand(r.mutationInfo.id,r.mutationInfo.params,{onlyLocal:!0,fromSync:!0})}async createInstance(r){const{type:n,snapshot:e}=r;try{switch(n){case c.UniverInstanceType.SHEET:return!!this._univerInstanceService.createSheet(e);default:throw new Error(`[RemoteInstanceReplicaService]: cannot create replica for document type: ${n}.`)}}catch(t){throw t instanceof Error?t:new Error(`${t}`)}}async disposeInstance(r){return this._univerInstanceService.disposeDocument(r.unitID)}};U=j([g(0,c.IUniverInstanceService),g(1,c.ICommandService)],U);function T(r){const n=r;return new class{call(e,t){const s=n[e];if(typeof s=="function"){let i=s.apply(n,[t]);return i instanceof Promise||(i=Promise.resolve(i)),i}throw new Error(`[RPC]: method not found for ${e}!`)}subscribe(e,t){const s=n[e];if(typeof s=="function"){const i=s.apply(n,t);return d.isObservable(i)?i:d.of(i)}throw new Error(`[RPC]: observable method not found for ${e}!`)}}}function $(r){return new Proxy({},{get(n,e){return function(...t){return F(e)?r.subscribe(e,t[0]):r.call(e,t[0])}}})}function F(r){return r.endsWith("$")}class D extends c.RxDisposable{constructor(e){super();u(this,"_initialized",new d.BehaviorSubject(!1));u(this,"_lastRequestCounter",0);u(this,"_pendingRequests",new Map);u(this,"_pendingSubscriptions",new Map);this._protocol=e,this._protocol.onMessage.pipe(p.takeUntil(this.dispose$)).subscribe(t=>this._onMessage(t))}getChannel(e){const t=this;return{call(s,i){return t._disposed?Promise.reject():t._remoteCall(e,s,i)},subscribe(s,i){if(t._disposed)throw new Error("[ChannelClient]: client is disposed!");return t._remoteSubscribe(e,s,i)}}}_whenReady(){return d.firstValueFrom(this._initialized.pipe(p.filter(e=>e),p.take(1)))}async _remoteCall(e,t,s){await this._whenReady();const i=++this._lastRequestCounter,_={seq:i,type:100,channelName:e,method:t,args:s},l=this;return new Promise((M,C)=>{const K={handle(O){switch(O.type){case 201:l._pendingRequests.delete(i),M(O.data);break;case 202:l._pendingRequests.delete(i),C(O.data);break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(i,K),this._sendRequest(_)})}_remoteSubscribe(e,t,s){return new d.Observable(i=>{let a=-1;return this._whenReady().then(()=>{a=++this._lastRequestCounter;const l={seq:a,type:101,channelName:e,method:t,args:s},M={handle(C){switch(C.type){case 300:i.next(C.data);break;case 301:i.error(C.data);break;case 302:i.complete();break;default:throw new Error("[ChannelClient]: unknown response type!")}}};this._pendingRequests.set(a,M),this._sendRequest(l)}),()=>{if(a===-1)return;const _={type:102,seq:a,channelName:e,method:t};this._sendRequest(_)}})}_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 W extends c.RxDisposable{constructor(e){super();u(this,"_channels",new Map);u(this,"_subscriptions",new Map);this._protocol=e,this._protocol.onMessage.pipe(p.takeUntil(this.dispose$)).subscribe(t=>this._onRequest(t)),this._sendResponse({seq:-1,type:0})}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:i}=e,a=this._channels.get(t);let _;try{if(!a)throw new Error(`[ChannelServer]: Channel ${t} not found!`);_=a.call(s,i)}catch(l){_=Promise.reject(l)}_.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:t,seq:s}=e,i=this._channels.get(t);try{if(!i)throw new Error(`[ChannelServer]: Channel ${t} not found!`);const _=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,_)}catch(a){a instanceof Error?this._sendResponse({seq:e.seq,type:301,data:a.message}):this._sendResponse({seq:e.seq,type:301,data:String(a)})}}_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=h.createIdentifier("IRPChannelService");class L{constructor(n){u(this,"_client");u(this,"_server");this._client=new D(n),this._server=new W(n)}requestChannel(n){return this._client.getChannel(n)}registerChannel(n,e){this._server.registerChannel(n,e)}}var k=Object.defineProperty,z=Object.getOwnPropertyDescriptor,V=(r,n,e,t)=>{for(var s=t>1?void 0:t?z(n,e):n,i=r.length-1,a;i>=0;i--)(a=r[i])&&(s=(t?a(n,e,s):a(s))||s);return t&&s&&k(n,e,s),s},f=(r,n)=>(e,t)=>n(e,t,r);let y=class extends c.RxDisposable{constructor(n,e,t,s,i){super();u(this,"_remoteInstanceService");u(this,"_syncingUnits",new Set);this._injector=n,this._commandService=e,this._univerInstanceService=t,this._rpcChannelService=s,this._remoteSyncService=i,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(I,T(this._remoteSyncService)),this._injector.add([v,{useFactory:()=>$(this._rpcChannelService.requestChannel(w))}]),this._remoteInstanceService=this._injector.get(v)}_init(){this._univerInstanceService.sheetAdded$.pipe(p.takeUntil(this.dispose$)).subscribe(n=>{this._syncingUnits.add(n.getUnitId()),this._remoteInstanceService.createInstance({unitID:n.getUnitId(),type:c.UniverInstanceType.SHEET,snapshot:n.getSnapshot()})}),this._univerInstanceService.sheetDisposed$.pipe(p.takeUntil(this.dispose$)).subscribe(n=>{this._syncingUnits.delete(n.getUnitId()),this._remoteInstanceService.disposeInstance({unitID:n.getUnitId()})}),this.disposeWithMe(this._commandService.onCommandExecuted((n,e)=>{const{type:t,params:s}=n,i=(s==null?void 0:s.unitId)||"";t===c.CommandType.MUTATION&&(!i||this._syncingUnits.has(i))&&!(e!=null&&e.fromSync)&&this._remoteInstanceService.syncMutation({mutationInfo:n})}))}};y=V([c.OnLifecycle(c.LifecycleStages.Starting,y),f(0,h.Inject(h.Injector)),f(1,c.ICommandService),f(2,c.IUniverInstanceService),f(3,m),f(4,b)],y);var G=Object.defineProperty,B=Object.getOwnPropertyDescriptor,J=(r,n,e,t)=>{for(var s=t>1?void 0:t?B(n,e):n,i=r.length-1,a;i>=0;i--)(a=r[i])&&(s=(t?a(n,e,s):a(s))||s);return t&&s&&G(n,e,s),s},R=(r,n)=>(e,t)=>n(e,t,r);let S=class extends c.Disposable{constructor(n,e,t,s){super();u(this,"_remoteSyncService");this._injector=n,this._remoteInstanceService=e,this._commandService=t,this._rpcChannelService=s,this._initRPCChannels(),this._init()}_initRPCChannels(){this._rpcChannelService.registerChannel(w,T(this._remoteInstanceService)),this._injector.add([b,{useFactory:()=>$(this._rpcChannelService.requestChannel(I))}]),this._remoteSyncService=this._injector.get(b)}_init(){this.disposeWithMe(this._commandService.onCommandExecuted((n,e)=>{n.type===c.CommandType.MUTATION&&!(e!=null&&e.fromSync)&&this._remoteSyncService.syncMutation({mutationInfo:n})}))}};S=J([c.OnLifecycle(c.LifecycleStages.Starting,S),R(0,h.Inject(h.Injector)),R(1,v),R(2,c.ICommandService),R(3,m)],S);function Q(){return{send(r){postMessage(r)},onMessage:new d.Observable(r=>{const n=e=>{r.next(e.data)};return addEventListener("message",n),()=>removeEventListener("message",n)}).pipe(d.shareReplay(1))}}function X(r){return{send(n){r.postMessage(n)},onMessage:new d.Observable(n=>{const e=t=>{n.next(t.data)};return r.addEventListener("message",e),()=>r.removeEventListener("message",e)}).pipe(d.shareReplay(1))}}var Y=Object.defineProperty,Z=Object.getOwnPropertyDescriptor,x=(r,n,e,t)=>{for(var s=t>1?void 0:t?Z(n,e):n,i=r.length-1,a;i>=0;i--)(a=r[i])&&(s=(t?a(n,e,s):a(s))||s);return t&&s&&Y(n,e,s),s},N=(r,n)=>(e,t)=>n(e,t,r);o.UniverRPCMainThreadPlugin=(q=class extends c.Plugin{constructor(n,e){super("UNIVER_RPC_MAIN_THREAD_PLUGIN"),this._config=n,this._injector=e}async onStarting(n){const e=new Worker(this._config.workerURL),t=X(e);[[m,{useFactory:()=>new L(t)}],[y],[b,{useClass:P}]].forEach(i=>n.add(i)),n.get(y)}},u(q,"type",c.PluginType.Univer),q),o.UniverRPCMainThreadPlugin=x([N(1,h.Inject(h.Injector))],o.UniverRPCMainThreadPlugin),o.UniverRPCWorkerThreadPlugin=(E=class extends c.Plugin{constructor(n,e){super("UNIVER_RPC_WORKER_THREAD_PLUGIN"),this._config=n,this._injector=e}onStarting(n){[[S],[m,{useFactory:()=>new L(Q())}],[v,{useClass:U}]].forEach(e=>n.add(e)),n.get(S)}},u(E,"type",c.PluginType.Univer),E),o.UniverRPCWorkerThreadPlugin=x([N(1,h.Inject(h.Injector))],o.UniverRPCWorkerThreadPlugin),o.ChannelClient=D,o.ChannelServer=W,o.IRPChannelService=m,o.IRemoteInstanceService=v,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@univerjs/rpc",
3
- "version": "0.1.0-alpha.3",
3
+ "version": "0.1.0-beta.0",
4
4
  "keywords": [],
5
5
  "author": "DreamNum <developer@univer.ai>",
6
6
  "license": "Apache-2.0",
@@ -39,12 +39,12 @@
39
39
  "vite-plugin-dts": "^3.6.4",
40
40
  "vite-plugin-externals": "^0.6.2",
41
41
  "vitest": "^1.0.4",
42
- "@univerjs/core": "0.1.0-alpha.3"
42
+ "@univerjs/core": "0.1.0-beta.0"
43
43
  },
44
44
  "peerDependencies": {
45
45
  "@wendellhu/redi": ">=0.12.12",
46
46
  "rxjs": ">=7.0.0",
47
- "@univerjs/core": "0.1.0-alpha.3"
47
+ "@univerjs/core": "0.1.0-beta.0"
48
48
  },
49
49
  "scripts": {
50
50
  "build": "tsc && vite build"