@univerjs/network 0.6.0 → 0.6.1

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,2 +1,2 @@
1
1
  "use strict";var G=Object.defineProperty;var W=(e,t,r)=>t in e?G(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var m=(e,t,r)=>W(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("@univerjs/core"),f=require("rxjs"),_=require("rxjs/operators"),q="application/json";class E{constructor(t){m(this,"_headers",new Map);typeof t=="string"?this._handleHeadersString(t):t instanceof Headers?this._handleHeaders(t):t&&this._handleHeadersConstructorProps(t)}forEach(t){this._headers.forEach((r,n)=>t(n,r))}has(t){return!!this._headers.has(t.toLowerCase())}get(t){const r=t.toLowerCase();return this._headers.has(r)?this._headers.get(r):null}set(t,r){this._setHeader(t,r)}toHeadersInit(){var r,n;const t={};return this._headers.forEach((s,o)=>{t[o]=s.join(",")}),(r=t.accept)!=null||(t.accept="application/json, text/plain, */*"),(n=t["content-type"])!=null||(t["content-type"]="application/json;charset=UTF-8"),t}_setHeader(t,r){const n=t.toLowerCase();this._headers.has(n)?this._headers.get(n).push(r.toString()):this._headers.set(n,[r.toString()])}_handleHeadersString(t){t.split(`
2
- `).forEach(r=>{const[n,s]=r.split(":");n&&s&&this._setHeader(n,s)})}_handleHeadersConstructorProps(t){Object.entries(t).forEach(([r,n])=>this._setHeader(r,n))}_handleHeaders(t){t.forEach((r,n)=>this._setHeader(n,r))}}const A=p.createIdentifier("network.http-implementation");class M{constructor(t){this.params=t}toString(){return this.params?Object.keys(this.params).map(t=>{const r=this.params[t];return Array.isArray(r)?r.map(n=>`${t}=${n}`).join("&"):`${t}=${r}`}).join("&"):""}}let V=0;class O{constructor(t,r,n){m(this,"uid",V++);this.method=t,this.url=r,this.requestParams=n}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var r,n;const t=(n=(r=this.requestParams)==null?void 0:r.params)==null?void 0:n.toString();return t?`${this.url}${this.url.includes("?")?"&":"?"}${t}`:this.url}getBody(){var n,s;const t=(n=this.headers.get("Content-Type"))!=null?n:q,r=(s=this.requestParams)==null?void 0:s.body;return t===q&&r&&typeof r=="object"?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}var z=Object.getOwnPropertyDescriptor,J=(e,t,r,n)=>{for(var s=n>1?void 0:n?z(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},K=(e,t)=>(r,n)=>t(r,n,e);exports.HTTPService=class extends p.Disposable{constructor(r){super();m(this,"_interceptors",[]);m(this,"_pipe");this._http=r}registerHTTPInterceptor(r){if(this._interceptors.indexOf(r)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(r),this._interceptors=this._interceptors.sort((n,s)=>{var o,i;return((o=n.priority)!=null?o:0)-((i=s.priority)!=null?i:0)}),this._pipe=null,p.toDisposable(()=>p.remove(this._interceptors,r))}get(r,n){return this._request("GET",r,n)}post(r,n){return this._request("POST",r,n)}put(r,n){return this._request("PUT",r,n)}delete(r,n){return this._request("DELETE",r,n)}patch(r,n){return this._request("PATCH",r,n)}getSSE(r,n,s){var d,u;const o=new E(s==null?void 0:s.headers),i=new M(s==null?void 0:s.params),c=new O(r,n,{headers:o,params:i,withCredentials:(d=s==null?void 0:s.withCredentials)!=null?d:!1,reportProgress:!0,responseType:(u=s==null?void 0:s.responseType)!=null?u:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body});return f.of(c).pipe(_.concatMap(a=>this._runInterceptorsAndImplementation(a)))}async _request(r,n,s){var a,l;const o=new E(s==null?void 0:s.headers),i=new M(s==null?void 0:s.params),c=new O(r,n,{headers:o,params:i,withCredentials:(a=s==null?void 0:s.withCredentials)!=null?a:!1,responseType:(l=s==null?void 0:s.responseType)!=null?l:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body}),d=f.of(c).pipe(_.concatMap(h=>this._runInterceptorsAndImplementation(h)));return await f.firstValueFrom(d)}_runInterceptorsAndImplementation(r){return this._pipe||(this._pipe=this._interceptors.map(n=>n.interceptor).reduceRight((n,s)=>Y(n,s),(n,s)=>s(n))),this._pipe(r,n=>this._http.send(n))}};exports.HTTPService=J([K(0,A)],exports.HTTPService);function Y(e,t){return(r,n)=>t(r,s=>e(s,n))}const Q=200,Z=300;var x=(e=>(e[e.Continue=100]="Continue",e[e.SwitchingProtocols=101]="SwitchingProtocols",e[e.Processing=102]="Processing",e[e.EarlyHints=103]="EarlyHints",e[e.Ok=200]="Ok",e[e.Created=201]="Created",e[e.Accepted=202]="Accepted",e[e.NonAuthoritativeInformation=203]="NonAuthoritativeInformation",e[e.NoContent=204]="NoContent",e[e.ResetContent=205]="ResetContent",e[e.PartialContent=206]="PartialContent",e[e.MultiStatus=207]="MultiStatus",e[e.AlreadyReported=208]="AlreadyReported",e[e.ImUsed=226]="ImUsed",e[e.MultipleChoices=300]="MultipleChoices",e[e.MovedPermanently=301]="MovedPermanently",e[e.Found=302]="Found",e[e.SeeOther=303]="SeeOther",e[e.NotModified=304]="NotModified",e[e.UseProxy=305]="UseProxy",e[e.Unused=306]="Unused",e[e.TemporaryRedirect=307]="TemporaryRedirect",e[e.PermanentRedirect=308]="PermanentRedirect",e[e.BadRequest=400]="BadRequest",e[e.Unauthorized=401]="Unauthorized",e[e.PaymentRequired=402]="PaymentRequired",e[e.Forbidden=403]="Forbidden",e[e.NotFound=404]="NotFound",e[e.MethodNotAllowed=405]="MethodNotAllowed",e[e.NotAcceptable=406]="NotAcceptable",e[e.ProxyAuthenticationRequired=407]="ProxyAuthenticationRequired",e[e.RequestTimeout=408]="RequestTimeout",e[e.Conflict=409]="Conflict",e[e.Gone=410]="Gone",e[e.LengthRequired=411]="LengthRequired",e[e.PreconditionFailed=412]="PreconditionFailed",e[e.PayloadTooLarge=413]="PayloadTooLarge",e[e.UriTooLong=414]="UriTooLong",e[e.UnsupportedMediaType=415]="UnsupportedMediaType",e[e.RangeNotSatisfiable=416]="RangeNotSatisfiable",e[e.ExpectationFailed=417]="ExpectationFailed",e[e.ImATeapot=418]="ImATeapot",e[e.MisdirectedRequest=421]="MisdirectedRequest",e[e.UnprocessableEntity=422]="UnprocessableEntity",e[e.Locked=423]="Locked",e[e.FailedDependency=424]="FailedDependency",e[e.TooEarly=425]="TooEarly",e[e.UpgradeRequired=426]="UpgradeRequired",e[e.PreconditionRequired=428]="PreconditionRequired",e[e.TooManyRequests=429]="TooManyRequests",e[e.RequestHeaderFieldsTooLarge=431]="RequestHeaderFieldsTooLarge",e[e.UnavailableForLegalReasons=451]="UnavailableForLegalReasons",e[e.InternalServerError=500]="InternalServerError",e[e.NotImplemented=501]="NotImplemented",e[e.BadGateway=502]="BadGateway",e[e.ServiceUnavailable=503]="ServiceUnavailable",e[e.GatewayTimeout=504]="GatewayTimeout",e[e.HttpVersionNotSupported=505]="HttpVersionNotSupported",e[e.VariantAlsoNegotiates=506]="VariantAlsoNegotiates",e[e.InsufficientStorage=507]="InsufficientStorage",e[e.LoopDetected=508]="LoopDetected",e[e.NotExtended=510]="NotExtended",e[e.NetworkAuthenticationRequired=511]="NetworkAuthenticationRequired",e))(x||{}),U=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(U||{});class L{constructor({body:t,headers:r,status:n,statusText:s}){m(this,"type",1);m(this,"body");m(this,"headers");m(this,"status");m(this,"statusText");this.body=t,this.headers=r,this.status=n,this.statusText=s}}class j{constructor(t,r,n){m(this,"type",0);this.total=t,this.loaded=r,this.partialText=n}}class B{constructor(t,r,n){this.headers=t,this.status=r,this.statusText=n}}class b{constructor({request:t,headers:r,status:n,statusText:s,error:o}){m(this,"request");m(this,"headers");m(this,"status");m(this,"statusText");m(this,"error");this.request=t,this.headers=r,this.status=n,this.statusText=s,this.error=o}}function X(e){return{method:e.method,headers:e.getHeadersInit(),body:e.getBody(),credentials:e.withCredentials?"include":void 0}}var P=Object.getOwnPropertyDescriptor,H=(e,t,r,n)=>{for(var s=n>1?void 0:n?P(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},S=(e,t)=>(r,n)=>t(r,n,e);exports.FetchHTTPImplementation=class{constructor(t){this._logService=t}send(t){return new f.Observable(r=>{const n=new AbortController;return this._send(t,r,n).catch(s=>{r.error(new b({error:s,request:t}))}),()=>n.abort()})}async _send(t,r,n){var a,l;let s;try{const h=X(t),w=t.getUrlWithParams(),y=fetch(w,{signal:n.signal,...h});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${w} with params ${h}`),s=await y}catch(h){const w=new b({request:t,error:h,status:(a=h.status)!=null?a:0,statusText:(l=h.statusText)!=null?l:"Unknown Error",headers:h.headers});this._logService.error("[FetchHTTPImplementation]: network error",w),r.error(w);return}const o=new E(s.headers),i=s.status,c=s.statusText;let d=null;if(s.body&&(d=await this._readBody(t,s,r)),i>=x.Ok&&i<x.MultipleChoices)r.next(new L({body:d,headers:o,status:i,statusText:c}));else{const h=new b({request:t,error:d,status:i,statusText:c,headers:o});this._logService.error("[FetchHTTPImplementation]: network error",h),r.error(h)}r.complete()}async _readBody(t,r,n){var w,y;const s=[],o=r.body.getReader(),i=r.headers.get("content-length");let c=0;const d=(w=t.requestParams)==null?void 0:w.reportProgress,u=t.responseType;let a,l;for(;;){const{done:v,value:g}=await o.read();if(v)break;s.push(g),c+=g.length,d&&u==="text"&&(a=(a!=null?a:"")+(l!=null?l:l=new TextDecoder).decode(g,{stream:!0}),n.next(new j(i?Number.parseInt(i,10):void 0,c,a)))}const h=C(s,c);try{const v=(y=r.headers.get("content-type"))!=null?y:"";return ee(t,h,v)}catch(v){const g=new b({request:t,error:v,status:r.status,statusText:r.statusText,headers:new E(r.headers)});return this._logService.error("[FetchHTTPImplementation]: network error",g),n.error(g),null}}};exports.FetchHTTPImplementation=H([S(0,p.ILogService)],exports.FetchHTTPImplementation);function C(e,t){const r=new Uint8Array(t);let n=0;for(const s of e)r.set(s,n),n+=s.length;return r}const T=/^\)\]\}',?\n/;function ee(e,t,r){switch(e.responseType){case"json":const n=new TextDecoder().decode(t).replace(T,"");return n===""?null:JSON.parse(n);case"text":return new TextDecoder().decode(t);case"blob":return new Blob([t],{type:r});case"arraybuffer":return t.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}var re=Object.getOwnPropertyDescriptor,te=(e,t,r,n)=>{for(var s=n>1?void 0:n?re(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},ne=(e,t)=>(r,n)=>t(r,n,e);exports.XHRHTTPImplementation=class{constructor(t){this._logService=t}send(t){return new f.Observable(r=>{const n=new XMLHttpRequest,s=t.getUrlWithParams(),o=X(t);n.open(t.method,s),t.withCredentials&&(n.withCredentials=!0),o.headers&&Object.entries(o.headers).forEach(([a,l])=>n.setRequestHeader(a,l));const i=()=>{const a=n.statusText||"OK",l=new E(n.getAllResponseHeaders());return new B(l,n.status,a)},c=()=>{const{headers:a,statusText:l,status:h}=i(),{responseType:w}=t;let y=null,v=null;h!==x.NoContent&&(y=typeof n.response>"u"?n.responseText:n.response);let g=h>=Q&&h<Z;if(w==="json"&&typeof y=="string"){const I=y;try{y=y?JSON.parse(y):null}catch(R){g=!1,y=I,v=R}}if(g)r.next(new L({body:y,headers:a,status:h,statusText:l}));else{const I=new b({request:t,error:v,headers:a,status:h,statusText:l});this._logService.error("[XHRHTTPImplementation]: network error",I),r.error(I)}},d=a=>{const l=new b({request:t,error:a,status:n.status||0,statusText:n.statusText||"Unknown Error",headers:i().headers});this._logService.error("[XHRHTTPImplementation]: network error",l),r.error(l)};n.addEventListener("load",c),n.addEventListener("error",d),n.addEventListener("abort",d),n.addEventListener("timeout",d);const u=t.getBody();return n.send(u),this._logService.debug(`[XHRHTTPImplementation]: sending request to url ${s} with params ${o}`),()=>{n.readyState!==n.DONE&&n.abort(),n.removeEventListener("load",c),n.removeEventListener("error",d),n.removeEventListener("abort",d),n.removeEventListener("timeout",d)}})}};exports.XHRHTTPImplementation=te([ne(0,p.ILogService)],exports.XHRHTTPImplementation);var se=Object.getOwnPropertyDescriptor,oe=(e,t,r,n)=>{for(var s=n>1?void 0:n?se(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},$=(e,t)=>(r,n)=>t(r,n,e),k;exports.UniverNetworkPlugin=(k=class extends p.Plugin{constructor(t=void 0,r,n){super(),this._config=t,this._logger=r,this._injector=n}onStarting(){var n,s,o;if(this._injector.get(exports.HTTPService,p.Quantity.OPTIONAL,p.LookUp.SKIP_SELF)&&!((n=this._config)!=null&&n.forceUseNewInstance)){this._logger.warn("[UniverNetworkPlugin]",'HTTPService is already registered in an ancestor interceptor. Skipping registration. If you want to force a new instance, set "forceUseNewInstance" to true in the plugin configuration.');return}const r=(s=this._config)!=null&&s.useFetchImpl?exports.FetchHTTPImplementation:typeof window<"u"?exports.XHRHTTPImplementation:exports.FetchHTTPImplementation;p.registerDependencies(this._injector,p.mergeOverrideWithDependencies([[exports.HTTPService],[A,{useClass:r}]],(o=this._config)==null?void 0:o.override))}},m(k,"pluginName","UNIVER_NETWORK_PLUGIN"),k);exports.UniverNetworkPlugin=oe([$(1,p.ILogService),$(2,p.Inject(p.Injector))],exports.UniverNetworkPlugin);const ie=p.createIdentifier("univer.network.socket.service");class ce extends p.Disposable{createSocket(t){try{const r=new WebSocket(t),n=new p.DisposableCollection;return{URL:t,close:(o,i)=>{r.close(o,i),n.dispose()},send:o=>{r.send(o)},open$:new f.Observable(o=>{const i=c=>o.next(c);r.addEventListener("open",i),n.add(p.toDisposable(()=>r.removeEventListener("open",i)))}).pipe(_.share()),close$:new f.Observable(o=>{const i=c=>o.next(c);r.addEventListener("close",i),n.add(p.toDisposable(()=>r.removeEventListener("close",i)))}).pipe(_.share()),error$:new f.Observable(o=>{const i=c=>o.next(c);r.addEventListener("error",i),n.add(p.toDisposable(()=>r.removeEventListener("error",i)))}).pipe(_.share()),message$:new f.Observable(o=>{const i=c=>o.next(c);r.addEventListener("message",i),n.add(p.toDisposable(()=>r.removeEventListener("message",i)))}).pipe(_.share())}}catch(r){return console.error(r),null}}}const ae=3,le=1e3,he=e=>{var n,s;const t=(n=e==null?void 0:e.maxRetryAttempts)!=null?n:ae,r=(s=e==null?void 0:e.delayInterval)!=null?s:le;return(o,i)=>i(o).pipe(_.retry({delay:r,count:t}))},pe=e=>{const t=[],r=new Set,n=()=>{var s;for(;r.size<((s=e==null?void 0:e.maxParallel)!=null?s:1)&&t.length>0;){const o=t.shift();r.add(o),o()}};return(s,o)=>new f.Observable(i=>{const c=()=>o(s).subscribe({next:u=>i.next(u),error:u=>i.error(u),complete:()=>i.complete()}),d=()=>{r.delete(c),p.remove(t,c),n()};return t.push(c),n(),d})},de=e=>{const{errorStatusCodes:t,onAuthError:r}=e;return(s,o)=>o(s).pipe(f.catchError(i=>(i instanceof b&&t.some(c=>c===i.status)&&r(),f.throwError(()=>i))))},ue=(e=300)=>{let r=()=>{};return n=>new Promise(s=>{r();const o=setTimeout(()=>{s(!0)},e);r=()=>{clearTimeout(o),s(!1)}})},ge=()=>(e,t)=>t.map(r=>({config:r,result:e})),ye=(e,t={})=>{const{isMatch:r,getParamsFromRequest:n,mergeParamsToRequest:s}=e,{fetchCheck:o=ue(300),distributeResult:i=ge()}=t,c=[],d=u=>u.map(a=>a.config);return(u,a)=>r(u)?new f.Observable(l=>{const h=n(u);c.push({next:y=>l.next(y),error:y=>l.error(y),config:h});const w=d(c);o(u).then(y=>{if(y){const v=[];w.forEach(g=>{const I=c.findIndex(R=>R.config===g);if(I>=0){const[R]=c.splice(I,1);v.push(R)}}),a(s(w,u)).subscribe({next:g=>{if(g.type===U.Response){const I=g.body,R=i(I,w);v.forEach(F=>{const D=R.find(N=>N.config===F.config);if(D){const N=new L({body:D.result,headers:g.headers,status:g.status,statusText:g.statusText});F.next(N)}else F.error("batch error")})}},complete:()=>l.complete(),error:g=>l.error(g)})}})}):a(u)};exports.AuthInterceptorFactory=de;exports.HTTPEventType=U;exports.HTTPHeaders=E;exports.HTTPProgress=j;exports.HTTPRequest=O;exports.HTTPResponse=L;exports.HTTPResponseError=b;exports.HTTPStatusCode=x;exports.IHTTPImplementation=A;exports.ISocketService=ie;exports.MergeInterceptorFactory=ye;exports.ResponseHeader=B;exports.RetryInterceptorFactory=he;exports.ThresholdInterceptorFactory=pe;exports.WebSocketService=ce;
2
+ `).forEach(r=>{const[n,s]=r.split(":");n&&s&&this._setHeader(n,s)})}_handleHeadersConstructorProps(t){Object.entries(t).forEach(([r,n])=>this._setHeader(r,n))}_handleHeaders(t){t.forEach((r,n)=>this._setHeader(n,r))}}const A=p.createIdentifier("network.http-implementation");class M{constructor(t){this.params=t}toString(){return this.params?Object.keys(this.params).map(t=>{const r=this.params[t];return Array.isArray(r)?r.map(n=>`${t}=${n}`).join("&"):`${t}=${r}`}).join("&"):""}}let V=0;class O{constructor(t,r,n){m(this,"uid",V++);this.method=t,this.url=r,this.requestParams=n}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var r,n;const t=(n=(r=this.requestParams)==null?void 0:r.params)==null?void 0:n.toString();return t?`${this.url}${this.url.includes("?")?"&":"?"}${t}`:this.url}getBody(){var n,s;const t=(n=this.headers.get("Content-Type"))!=null?n:q,r=(s=this.requestParams)==null?void 0:s.body;return t===q&&r&&typeof r=="object"?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}var z=Object.getOwnPropertyDescriptor,J=(e,t,r,n)=>{for(var s=n>1?void 0:n?z(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},K=(e,t)=>(r,n)=>t(r,n,e);exports.HTTPService=class extends p.Disposable{constructor(r){super();m(this,"_interceptors",[]);m(this,"_pipe");this._http=r}registerHTTPInterceptor(r){if(this._interceptors.indexOf(r)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(r),this._interceptors=this._interceptors.sort((n,s)=>{var o,i;return((o=n.priority)!=null?o:0)-((i=s.priority)!=null?i:0)}),this._pipe=null,p.toDisposable(()=>p.remove(this._interceptors,r))}get(r,n){return this._request("GET",r,n)}post(r,n){return this._request("POST",r,n)}put(r,n){return this._request("PUT",r,n)}delete(r,n){return this._request("DELETE",r,n)}patch(r,n){return this._request("PATCH",r,n)}getSSE(r,n,s){var d,u;const o=new E(s==null?void 0:s.headers),i=new M(s==null?void 0:s.params),c=new O(r,n,{headers:o,params:i,withCredentials:(d=s==null?void 0:s.withCredentials)!=null?d:!1,reportProgress:!0,responseType:(u=s==null?void 0:s.responseType)!=null?u:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body});return f.of(c).pipe(_.concatMap(a=>this._runInterceptorsAndImplementation(a)))}async _request(r,n,s){var a,l;const o=new E(s==null?void 0:s.headers),i=new M(s==null?void 0:s.params),c=new O(r,n,{headers:o,params:i,withCredentials:(a=s==null?void 0:s.withCredentials)!=null?a:!1,responseType:(l=s==null?void 0:s.responseType)!=null?l:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body}),d=f.of(c).pipe(_.concatMap(h=>this._runInterceptorsAndImplementation(h)));return await f.firstValueFrom(d)}_runInterceptorsAndImplementation(r){return this._pipe||(this._pipe=this._interceptors.map(n=>n.interceptor).reduceRight((n,s)=>Y(n,s),(n,s)=>s(n))),this._pipe(r,n=>this._http.send(n))}};exports.HTTPService=J([K(0,A)],exports.HTTPService);function Y(e,t){return(r,n)=>t(r,s=>e(s,n))}const Q=200,Z=300;var x=(e=>(e[e.Continue=100]="Continue",e[e.SwitchingProtocols=101]="SwitchingProtocols",e[e.Processing=102]="Processing",e[e.EarlyHints=103]="EarlyHints",e[e.Ok=200]="Ok",e[e.Created=201]="Created",e[e.Accepted=202]="Accepted",e[e.NonAuthoritativeInformation=203]="NonAuthoritativeInformation",e[e.NoContent=204]="NoContent",e[e.ResetContent=205]="ResetContent",e[e.PartialContent=206]="PartialContent",e[e.MultiStatus=207]="MultiStatus",e[e.AlreadyReported=208]="AlreadyReported",e[e.ImUsed=226]="ImUsed",e[e.MultipleChoices=300]="MultipleChoices",e[e.MovedPermanently=301]="MovedPermanently",e[e.Found=302]="Found",e[e.SeeOther=303]="SeeOther",e[e.NotModified=304]="NotModified",e[e.UseProxy=305]="UseProxy",e[e.Unused=306]="Unused",e[e.TemporaryRedirect=307]="TemporaryRedirect",e[e.PermanentRedirect=308]="PermanentRedirect",e[e.BadRequest=400]="BadRequest",e[e.Unauthorized=401]="Unauthorized",e[e.PaymentRequired=402]="PaymentRequired",e[e.Forbidden=403]="Forbidden",e[e.NotFound=404]="NotFound",e[e.MethodNotAllowed=405]="MethodNotAllowed",e[e.NotAcceptable=406]="NotAcceptable",e[e.ProxyAuthenticationRequired=407]="ProxyAuthenticationRequired",e[e.RequestTimeout=408]="RequestTimeout",e[e.Conflict=409]="Conflict",e[e.Gone=410]="Gone",e[e.LengthRequired=411]="LengthRequired",e[e.PreconditionFailed=412]="PreconditionFailed",e[e.PayloadTooLarge=413]="PayloadTooLarge",e[e.UriTooLong=414]="UriTooLong",e[e.UnsupportedMediaType=415]="UnsupportedMediaType",e[e.RangeNotSatisfiable=416]="RangeNotSatisfiable",e[e.ExpectationFailed=417]="ExpectationFailed",e[e.ImATeapot=418]="ImATeapot",e[e.MisdirectedRequest=421]="MisdirectedRequest",e[e.UnprocessableEntity=422]="UnprocessableEntity",e[e.Locked=423]="Locked",e[e.FailedDependency=424]="FailedDependency",e[e.TooEarly=425]="TooEarly",e[e.UpgradeRequired=426]="UpgradeRequired",e[e.PreconditionRequired=428]="PreconditionRequired",e[e.TooManyRequests=429]="TooManyRequests",e[e.RequestHeaderFieldsTooLarge=431]="RequestHeaderFieldsTooLarge",e[e.UnavailableForLegalReasons=451]="UnavailableForLegalReasons",e[e.InternalServerError=500]="InternalServerError",e[e.NotImplemented=501]="NotImplemented",e[e.BadGateway=502]="BadGateway",e[e.ServiceUnavailable=503]="ServiceUnavailable",e[e.GatewayTimeout=504]="GatewayTimeout",e[e.HttpVersionNotSupported=505]="HttpVersionNotSupported",e[e.VariantAlsoNegotiates=506]="VariantAlsoNegotiates",e[e.InsufficientStorage=507]="InsufficientStorage",e[e.LoopDetected=508]="LoopDetected",e[e.NotExtended=510]="NotExtended",e[e.NetworkAuthenticationRequired=511]="NetworkAuthenticationRequired",e))(x||{}),U=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(U||{});class L{constructor({body:t,headers:r,status:n,statusText:s}){m(this,"type",1);m(this,"body");m(this,"headers");m(this,"status");m(this,"statusText");this.body=t,this.headers=r,this.status=n,this.statusText=s}}class j{constructor(t,r,n){m(this,"type",0);this.total=t,this.loaded=r,this.partialText=n}}class B{constructor(t,r,n){this.headers=t,this.status=r,this.statusText=n}}class b{constructor({request:t,headers:r,status:n,statusText:s,error:o}){m(this,"request");m(this,"headers");m(this,"status");m(this,"statusText");m(this,"error");this.request=t,this.headers=r,this.status=n,this.statusText=s,this.error=o}}function X(e){return{method:e.method,headers:e.getHeadersInit(),body:e.getBody(),credentials:e.withCredentials?"include":void 0}}var P=Object.getOwnPropertyDescriptor,H=(e,t,r,n)=>{for(var s=n>1?void 0:n?P(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},S=(e,t)=>(r,n)=>t(r,n,e);exports.FetchHTTPImplementation=class{constructor(t){this._logService=t}send(t){return new f.Observable(r=>{const n=new AbortController;return this._send(t,r,n).catch(s=>{r.error(new b({error:s,request:t}))}),()=>n.abort()})}async _send(t,r,n){var a,l;let s;try{const h=X(t),w=t.getUrlWithParams(),y=fetch(w,{signal:n.signal,...h});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${w} with params ${h}`),s=await y}catch(h){const w=new b({request:t,error:h,status:(a=h.status)!=null?a:0,statusText:(l=h.statusText)!=null?l:"Unknown Error",headers:h.headers});this._logService.error("[FetchHTTPImplementation]: network error",w),r.error(w);return}const o=new E(s.headers),i=s.status,c=s.statusText;let d=null;if(s.body&&(d=await this._readBody(t,s,r)),i>=x.Ok&&i<x.MultipleChoices)r.next(new L({body:d,headers:o,status:i,statusText:c}));else{const h=new b({request:t,error:d,status:i,statusText:c,headers:o});this._logService.error("[FetchHTTPImplementation]: network error",h),r.error(h)}r.complete()}async _readBody(t,r,n){var w,y;const s=[],o=r.body.getReader(),i=r.headers.get("content-length");let c=0;const d=(w=t.requestParams)==null?void 0:w.reportProgress,u=t.responseType;let a,l;for(;;){const{done:v,value:g}=await o.read();if(v)break;s.push(g),c+=g.length,d&&u==="text"&&(a=(a!=null?a:"")+(l!=null?l:l=new TextDecoder).decode(g,{stream:!0}),n.next(new j(i?Number.parseInt(i,10):void 0,c,a)))}const h=C(s,c);try{const v=(y=r.headers.get("content-type"))!=null?y:"";return ee(t,h,v)}catch(v){const g=new b({request:t,error:v,status:r.status,statusText:r.statusText,headers:new E(r.headers)});return this._logService.error("[FetchHTTPImplementation]: network error",g),n.error(g),null}}};exports.FetchHTTPImplementation=H([S(0,p.ILogService)],exports.FetchHTTPImplementation);function C(e,t){const r=new Uint8Array(t);let n=0;for(const s of e)r.set(s,n),n+=s.length;return r}const T=/^\)\]\}',?\n/;function ee(e,t,r){switch(e.responseType){case"json":const n=new TextDecoder().decode(t).replace(T,"");return n===""?null:JSON.parse(n);case"text":return new TextDecoder().decode(t);case"blob":return new Blob([t],{type:r});case"arraybuffer":return t.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}var re=Object.getOwnPropertyDescriptor,te=(e,t,r,n)=>{for(var s=n>1?void 0:n?re(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},ne=(e,t)=>(r,n)=>t(r,n,e);exports.XHRHTTPImplementation=class{constructor(t){this._logService=t}send(t){return new f.Observable(r=>{const n=new XMLHttpRequest,s=t.getUrlWithParams(),o=X(t);n.open(t.method,s),t.withCredentials&&(n.withCredentials=!0),o.headers&&Object.entries(o.headers).forEach(([a,l])=>n.setRequestHeader(a,l));const i=()=>{const a=n.statusText||"OK",l=new E(n.getAllResponseHeaders());return new B(l,n.status,a)},c=()=>{const{headers:a,statusText:l,status:h}=i(),{responseType:w}=t;let y=null,v=null;h!==x.NoContent&&(y=typeof n.response>"u"?n.responseText:n.response);let g=h>=Q&&h<Z;if(w==="json"&&typeof y=="string"){const I=y;try{y=y?JSON.parse(y):null}catch(R){g=!1,y=I,v=R}}if(g)r.next(new L({body:y,headers:a,status:h,statusText:l}));else{const I=new b({request:t,error:v,headers:a,status:h,statusText:l});this._logService.error("[XHRHTTPImplementation]: network error",I),r.error(I)}},d=a=>{const l=new b({request:t,error:a,status:n.status||0,statusText:n.statusText||"Unknown Error",headers:i().headers});this._logService.error("[XHRHTTPImplementation]: network error",l),r.error(l)};n.addEventListener("load",c),n.addEventListener("error",d),n.addEventListener("abort",d),n.addEventListener("timeout",d);const u=t.getBody();return n.send(u),this._logService.debug("[XHRHTTPImplementation]",`sending request to url ${s} with params ${o}`),()=>{n.readyState!==n.DONE&&n.abort(),n.removeEventListener("load",c),n.removeEventListener("error",d),n.removeEventListener("abort",d),n.removeEventListener("timeout",d)}})}};exports.XHRHTTPImplementation=te([ne(0,p.ILogService)],exports.XHRHTTPImplementation);var se=Object.getOwnPropertyDescriptor,oe=(e,t,r,n)=>{for(var s=n>1?void 0:n?se(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},$=(e,t)=>(r,n)=>t(r,n,e),k;exports.UniverNetworkPlugin=(k=class extends p.Plugin{constructor(t=void 0,r,n){super(),this._config=t,this._logger=r,this._injector=n}onStarting(){var n,s,o;if(this._injector.get(exports.HTTPService,p.Quantity.OPTIONAL,p.LookUp.SKIP_SELF)&&!((n=this._config)!=null&&n.forceUseNewInstance)){this._logger.warn("[UniverNetworkPlugin]",'HTTPService is already registered in an ancestor interceptor. Skipping registration. If you want to force a new instance, set "forceUseNewInstance" to true in the plugin configuration.');return}const r=(s=this._config)!=null&&s.useFetchImpl?exports.FetchHTTPImplementation:typeof window<"u"?exports.XHRHTTPImplementation:exports.FetchHTTPImplementation;p.registerDependencies(this._injector,p.mergeOverrideWithDependencies([[exports.HTTPService],[A,{useClass:r}]],(o=this._config)==null?void 0:o.override))}},m(k,"pluginName","UNIVER_NETWORK_PLUGIN"),k);exports.UniverNetworkPlugin=oe([$(1,p.ILogService),$(2,p.Inject(p.Injector))],exports.UniverNetworkPlugin);const ie=p.createIdentifier("univer.network.socket.service");class ce extends p.Disposable{createSocket(t){try{const r=new WebSocket(t),n=new p.DisposableCollection;return{URL:t,close:(o,i)=>{r.close(o,i),n.dispose()},send:o=>{r.send(o)},open$:new f.Observable(o=>{const i=c=>o.next(c);r.addEventListener("open",i),n.add(p.toDisposable(()=>r.removeEventListener("open",i)))}).pipe(_.share()),close$:new f.Observable(o=>{const i=c=>o.next(c);r.addEventListener("close",i),n.add(p.toDisposable(()=>r.removeEventListener("close",i)))}).pipe(_.share()),error$:new f.Observable(o=>{const i=c=>o.next(c);r.addEventListener("error",i),n.add(p.toDisposable(()=>r.removeEventListener("error",i)))}).pipe(_.share()),message$:new f.Observable(o=>{const i=c=>o.next(c);r.addEventListener("message",i),n.add(p.toDisposable(()=>r.removeEventListener("message",i)))}).pipe(_.share())}}catch(r){return console.error(r),null}}}const ae=3,le=1e3,he=e=>{var n,s;const t=(n=e==null?void 0:e.maxRetryAttempts)!=null?n:ae,r=(s=e==null?void 0:e.delayInterval)!=null?s:le;return(o,i)=>i(o).pipe(_.retry({delay:r,count:t}))},pe=e=>{const t=[],r=new Set,n=()=>{var s;for(;r.size<((s=e==null?void 0:e.maxParallel)!=null?s:1)&&t.length>0;){const o=t.shift();r.add(o),o()}};return(s,o)=>new f.Observable(i=>{const c=()=>o(s).subscribe({next:u=>i.next(u),error:u=>i.error(u),complete:()=>i.complete()}),d=()=>{r.delete(c),p.remove(t,c),n()};return t.push(c),n(),d})},de=e=>{const{errorStatusCodes:t,onAuthError:r}=e;return(s,o)=>o(s).pipe(f.catchError(i=>(i instanceof b&&t.some(c=>c===i.status)&&r(),f.throwError(()=>i))))},ue=(e=300)=>{let r=()=>{};return n=>new Promise(s=>{r();const o=setTimeout(()=>{s(!0)},e);r=()=>{clearTimeout(o),s(!1)}})},ge=()=>(e,t)=>t.map(r=>({config:r,result:e})),ye=(e,t={})=>{const{isMatch:r,getParamsFromRequest:n,mergeParamsToRequest:s}=e,{fetchCheck:o=ue(300),distributeResult:i=ge()}=t,c=[],d=u=>u.map(a=>a.config);return(u,a)=>r(u)?new f.Observable(l=>{const h=n(u);c.push({next:y=>l.next(y),error:y=>l.error(y),config:h});const w=d(c);o(u).then(y=>{if(y){const v=[];w.forEach(g=>{const I=c.findIndex(R=>R.config===g);if(I>=0){const[R]=c.splice(I,1);v.push(R)}}),a(s(w,u)).subscribe({next:g=>{if(g.type===U.Response){const I=g.body,R=i(I,w);v.forEach(F=>{const D=R.find(N=>N.config===F.config);if(D){const N=new L({body:D.result,headers:g.headers,status:g.status,statusText:g.statusText});F.next(N)}else F.error("batch error")})}},complete:()=>l.complete(),error:g=>l.error(g)})}})}):a(u)};exports.AuthInterceptorFactory=de;exports.HTTPEventType=U;exports.HTTPHeaders=E;exports.HTTPProgress=j;exports.HTTPRequest=O;exports.HTTPResponse=L;exports.HTTPResponseError=b;exports.HTTPStatusCode=x;exports.IHTTPImplementation=A;exports.ISocketService=ie;exports.MergeInterceptorFactory=ye;exports.ResponseHeader=B;exports.RetryInterceptorFactory=he;exports.ThresholdInterceptorFactory=pe;exports.WebSocketService=ce;
package/lib/es/index.js CHANGED
@@ -406,7 +406,7 @@ let U = class {
406
406
  };
407
407
  r.addEventListener("load", i), r.addEventListener("error", c), r.addEventListener("abort", c), r.addEventListener("timeout", c);
408
408
  const f = e.getBody();
409
- return r.send(f), this._logService.debug(`[XHRHTTPImplementation]: sending request to url ${n} with params ${s}`), () => {
409
+ return r.send(f), this._logService.debug("[XHRHTTPImplementation]", `sending request to url ${n} with params ${s}`), () => {
410
410
  r.readyState !== r.DONE && r.abort(), r.removeEventListener("load", i), r.removeEventListener("error", c), r.removeEventListener("abort", c), r.removeEventListener("timeout", c);
411
411
  };
412
412
  });
package/lib/umd/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  (function(c,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("@univerjs/core"),require("rxjs"),require("rxjs/operators")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs","rxjs/operators"],a):(c=typeof globalThis<"u"?globalThis:c||self,a(c.UniverNetwork={},c.UniverCore,c.rxjs,c.rxjs.operators))})(this,function(c,a,m,_){"use strict";var fe=Object.defineProperty;var ye=(c,a,m)=>a in c?fe(c,a,{enumerable:!0,configurable:!0,writable:!0,value:m}):c[a]=m;var w=(c,a,m)=>ye(c,typeof a!="symbol"?a+"":a,m);var A;const M="application/json";class L{constructor(n){w(this,"_headers",new Map);typeof n=="string"?this._handleHeadersString(n):n instanceof Headers?this._handleHeaders(n):n&&this._handleHeadersConstructorProps(n)}forEach(n){this._headers.forEach((t,r)=>n(r,t))}has(n){return!!this._headers.has(n.toLowerCase())}get(n){const t=n.toLowerCase();return this._headers.has(t)?this._headers.get(t):null}set(n,t){this._setHeader(n,t)}toHeadersInit(){var t,r;const n={};return this._headers.forEach((s,i)=>{n[i]=s.join(",")}),(t=n.accept)!=null||(n.accept="application/json, text/plain, */*"),(r=n["content-type"])!=null||(n["content-type"]="application/json;charset=UTF-8"),n}_setHeader(n,t){const r=n.toLowerCase();this._headers.has(r)?this._headers.get(r).push(t.toString()):this._headers.set(r,[t.toString()])}_handleHeadersString(n){n.split(`
2
- `).forEach(t=>{const[r,s]=t.split(":");r&&s&&this._setHeader(r,s)})}_handleHeadersConstructorProps(n){Object.entries(n).forEach(([t,r])=>this._setHeader(t,r))}_handleHeaders(n){n.forEach((t,r)=>this._setHeader(r,t))}}const k=a.createIdentifier("network.http-implementation");class ${constructor(n){this.params=n}toString(){return this.params?Object.keys(this.params).map(n=>{const t=this.params[n];return Array.isArray(t)?t.map(r=>`${n}=${r}`).join("&"):`${n}=${t}`}).join("&"):""}}let W=0;class O{constructor(n,t,r){w(this,"uid",W++);this.method=n,this.url=t,this.requestParams=r}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var t,r;const n=(r=(t=this.requestParams)==null?void 0:t.params)==null?void 0:r.toString();return n?`${this.url}${this.url.includes("?")?"&":"?"}${n}`:this.url}getBody(){var r,s;const n=(r=this.headers.get("Content-Type"))!=null?r:M,t=(s=this.requestParams)==null?void 0:s.body;return n===M&&t&&typeof t=="object"?JSON.stringify(t):t?`${t}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}var V=Object.getOwnPropertyDescriptor,z=(e,n,t,r)=>{for(var s=r>1?void 0:r?V(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},J=(e,n)=>(t,r)=>n(t,r,e);c.HTTPService=class extends a.Disposable{constructor(t){super();w(this,"_interceptors",[]);w(this,"_pipe");this._http=t}registerHTTPInterceptor(t){if(this._interceptors.indexOf(t)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(t),this._interceptors=this._interceptors.sort((r,s)=>{var i,o;return((i=r.priority)!=null?i:0)-((o=s.priority)!=null?o:0)}),this._pipe=null,a.toDisposable(()=>a.remove(this._interceptors,t))}get(t,r){return this._request("GET",t,r)}post(t,r){return this._request("POST",t,r)}put(t,r){return this._request("PUT",t,r)}delete(t,r){return this._request("DELETE",t,r)}patch(t,r){return this._request("PATCH",t,r)}getSSE(t,r,s){var u,g;const i=new L(s==null?void 0:s.headers),o=new $(s==null?void 0:s.params),l=new O(t,r,{headers:i,params:o,withCredentials:(u=s==null?void 0:s.withCredentials)!=null?u:!1,reportProgress:!0,responseType:(g=s==null?void 0:s.responseType)!=null?g:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body});return m.of(l).pipe(_.concatMap(h=>this._runInterceptorsAndImplementation(h)))}async _request(t,r,s){var h,d;const i=new L(s==null?void 0:s.headers),o=new $(s==null?void 0:s.params),l=new O(t,r,{headers:i,params:o,withCredentials:(h=s==null?void 0:s.withCredentials)!=null?h:!1,responseType:(d=s==null?void 0:s.responseType)!=null?d:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body}),u=m.of(l).pipe(_.concatMap(p=>this._runInterceptorsAndImplementation(p)));return await m.firstValueFrom(u)}_runInterceptorsAndImplementation(t){return this._pipe||(this._pipe=this._interceptors.map(r=>r.interceptor).reduceRight((r,s)=>K(r,s),(r,s)=>s(r))),this._pipe(t,r=>this._http.send(r))}},c.HTTPService=z([J(0,k)],c.HTTPService);function K(e,n){return(t,r)=>n(t,s=>e(s,r))}const Y=200,Q=300;var F=(e=>(e[e.Continue=100]="Continue",e[e.SwitchingProtocols=101]="SwitchingProtocols",e[e.Processing=102]="Processing",e[e.EarlyHints=103]="EarlyHints",e[e.Ok=200]="Ok",e[e.Created=201]="Created",e[e.Accepted=202]="Accepted",e[e.NonAuthoritativeInformation=203]="NonAuthoritativeInformation",e[e.NoContent=204]="NoContent",e[e.ResetContent=205]="ResetContent",e[e.PartialContent=206]="PartialContent",e[e.MultiStatus=207]="MultiStatus",e[e.AlreadyReported=208]="AlreadyReported",e[e.ImUsed=226]="ImUsed",e[e.MultipleChoices=300]="MultipleChoices",e[e.MovedPermanently=301]="MovedPermanently",e[e.Found=302]="Found",e[e.SeeOther=303]="SeeOther",e[e.NotModified=304]="NotModified",e[e.UseProxy=305]="UseProxy",e[e.Unused=306]="Unused",e[e.TemporaryRedirect=307]="TemporaryRedirect",e[e.PermanentRedirect=308]="PermanentRedirect",e[e.BadRequest=400]="BadRequest",e[e.Unauthorized=401]="Unauthorized",e[e.PaymentRequired=402]="PaymentRequired",e[e.Forbidden=403]="Forbidden",e[e.NotFound=404]="NotFound",e[e.MethodNotAllowed=405]="MethodNotAllowed",e[e.NotAcceptable=406]="NotAcceptable",e[e.ProxyAuthenticationRequired=407]="ProxyAuthenticationRequired",e[e.RequestTimeout=408]="RequestTimeout",e[e.Conflict=409]="Conflict",e[e.Gone=410]="Gone",e[e.LengthRequired=411]="LengthRequired",e[e.PreconditionFailed=412]="PreconditionFailed",e[e.PayloadTooLarge=413]="PayloadTooLarge",e[e.UriTooLong=414]="UriTooLong",e[e.UnsupportedMediaType=415]="UnsupportedMediaType",e[e.RangeNotSatisfiable=416]="RangeNotSatisfiable",e[e.ExpectationFailed=417]="ExpectationFailed",e[e.ImATeapot=418]="ImATeapot",e[e.MisdirectedRequest=421]="MisdirectedRequest",e[e.UnprocessableEntity=422]="UnprocessableEntity",e[e.Locked=423]="Locked",e[e.FailedDependency=424]="FailedDependency",e[e.TooEarly=425]="TooEarly",e[e.UpgradeRequired=426]="UpgradeRequired",e[e.PreconditionRequired=428]="PreconditionRequired",e[e.TooManyRequests=429]="TooManyRequests",e[e.RequestHeaderFieldsTooLarge=431]="RequestHeaderFieldsTooLarge",e[e.UnavailableForLegalReasons=451]="UnavailableForLegalReasons",e[e.InternalServerError=500]="InternalServerError",e[e.NotImplemented=501]="NotImplemented",e[e.BadGateway=502]="BadGateway",e[e.ServiceUnavailable=503]="ServiceUnavailable",e[e.GatewayTimeout=504]="GatewayTimeout",e[e.HttpVersionNotSupported=505]="HttpVersionNotSupported",e[e.VariantAlsoNegotiates=506]="VariantAlsoNegotiates",e[e.InsufficientStorage=507]="InsufficientStorage",e[e.LoopDetected=508]="LoopDetected",e[e.NotExtended=510]="NotExtended",e[e.NetworkAuthenticationRequired=511]="NetworkAuthenticationRequired",e))(F||{}),U=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(U||{});class N{constructor({body:n,headers:t,status:r,statusText:s}){w(this,"type",1);w(this,"body");w(this,"headers");w(this,"status");w(this,"statusText");this.body=n,this.headers=t,this.status=r,this.statusText=s}}class j{constructor(n,t,r){w(this,"type",0);this.total=n,this.loaded=t,this.partialText=r}}class x{constructor(n,t,r){this.headers=n,this.status=t,this.statusText=r}}class R{constructor({request:n,headers:t,status:r,statusText:s,error:i}){w(this,"request");w(this,"headers");w(this,"status");w(this,"statusText");w(this,"error");this.request=n,this.headers=t,this.status=r,this.statusText=s,this.error=i}}function B(e){return{method:e.method,headers:e.getHeadersInit(),body:e.getBody(),credentials:e.withCredentials?"include":void 0}}var Z=Object.getOwnPropertyDescriptor,P=(e,n,t,r)=>{for(var s=r>1?void 0:r?Z(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},H=(e,n)=>(t,r)=>n(t,r,e);c.FetchHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new m.Observable(t=>{const r=new AbortController;return this._send(n,t,r).catch(s=>{t.error(new R({error:s,request:n}))}),()=>r.abort()})}async _send(n,t,r){var h,d;let s;try{const p=B(n),v=n.getUrlWithParams(),y=fetch(v,{signal:r.signal,...p});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${v} with params ${p}`),s=await y}catch(p){const v=new R({request:n,error:p,status:(h=p.status)!=null?h:0,statusText:(d=p.statusText)!=null?d:"Unknown Error",headers:p.headers});this._logService.error("[FetchHTTPImplementation]: network error",v),t.error(v);return}const i=new L(s.headers),o=s.status,l=s.statusText;let u=null;if(s.body&&(u=await this._readBody(n,s,t)),o>=F.Ok&&o<F.MultipleChoices)t.next(new N({body:u,headers:i,status:o,statusText:l}));else{const p=new R({request:n,error:u,status:o,statusText:l,headers:i});this._logService.error("[FetchHTTPImplementation]: network error",p),t.error(p)}t.complete()}async _readBody(n,t,r){var v,y;const s=[],i=t.body.getReader(),o=t.headers.get("content-length");let l=0;const u=(v=n.requestParams)==null?void 0:v.reportProgress,g=n.responseType;let h,d;for(;;){const{done:I,value:f}=await i.read();if(I)break;s.push(f),l+=f.length,u&&g==="text"&&(h=(h!=null?h:"")+(d!=null?d:d=new TextDecoder).decode(f,{stream:!0}),r.next(new j(o?Number.parseInt(o,10):void 0,l,h)))}const p=S(s,l);try{const I=(y=t.headers.get("content-type"))!=null?y:"";return T(n,p,I)}catch(I){const f=new R({request:n,error:I,status:t.status,statusText:t.statusText,headers:new L(t.headers)});return this._logService.error("[FetchHTTPImplementation]: network error",f),r.error(f),null}}},c.FetchHTTPImplementation=P([H(0,a.ILogService)],c.FetchHTTPImplementation);function S(e,n){const t=new Uint8Array(n);let r=0;for(const s of e)t.set(s,r),r+=s.length;return t}const C=/^\)\]\}',?\n/;function T(e,n,t){switch(e.responseType){case"json":const r=new TextDecoder().decode(n).replace(C,"");return r===""?null:JSON.parse(r);case"text":return new TextDecoder().decode(n);case"blob":return new Blob([n],{type:t});case"arraybuffer":return n.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}var ee=Object.getOwnPropertyDescriptor,te=(e,n,t,r)=>{for(var s=r>1?void 0:r?ee(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},re=(e,n)=>(t,r)=>n(t,r,e);c.XHRHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new m.Observable(t=>{const r=new XMLHttpRequest,s=n.getUrlWithParams(),i=B(n);r.open(n.method,s),n.withCredentials&&(r.withCredentials=!0),i.headers&&Object.entries(i.headers).forEach(([h,d])=>r.setRequestHeader(h,d));const o=()=>{const h=r.statusText||"OK",d=new L(r.getAllResponseHeaders());return new x(d,r.status,h)},l=()=>{const{headers:h,statusText:d,status:p}=o(),{responseType:v}=n;let y=null,I=null;p!==F.NoContent&&(y=typeof r.response>"u"?r.responseText:r.response);let f=p>=Y&&p<Q;if(v==="json"&&typeof y=="string"){const b=y;try{y=y?JSON.parse(y):null}catch(E){f=!1,y=b,I=E}}if(f)t.next(new N({body:y,headers:h,status:p,statusText:d}));else{const b=new R({request:n,error:I,headers:h,status:p,statusText:d});this._logService.error("[XHRHTTPImplementation]: network error",b),t.error(b)}},u=h=>{const d=new R({request:n,error:h,status:r.status||0,statusText:r.statusText||"Unknown Error",headers:o().headers});this._logService.error("[XHRHTTPImplementation]: network error",d),t.error(d)};r.addEventListener("load",l),r.addEventListener("error",u),r.addEventListener("abort",u),r.addEventListener("timeout",u);const g=n.getBody();return r.send(g),this._logService.debug(`[XHRHTTPImplementation]: sending request to url ${s} with params ${i}`),()=>{r.readyState!==r.DONE&&r.abort(),r.removeEventListener("load",l),r.removeEventListener("error",u),r.removeEventListener("abort",u),r.removeEventListener("timeout",u)}})}},c.XHRHTTPImplementation=te([re(0,a.ILogService)],c.XHRHTTPImplementation);var ne=Object.getOwnPropertyDescriptor,se=(e,n,t,r)=>{for(var s=r>1?void 0:r?ne(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},X=(e,n)=>(t,r)=>n(t,r,e);c.UniverNetworkPlugin=(A=class extends a.Plugin{constructor(n=void 0,t,r){super(),this._config=n,this._logger=t,this._injector=r}onStarting(){var r,s,i;if(this._injector.get(c.HTTPService,a.Quantity.OPTIONAL,a.LookUp.SKIP_SELF)&&!((r=this._config)!=null&&r.forceUseNewInstance)){this._logger.warn("[UniverNetworkPlugin]",'HTTPService is already registered in an ancestor interceptor. Skipping registration. If you want to force a new instance, set "forceUseNewInstance" to true in the plugin configuration.');return}const t=(s=this._config)!=null&&s.useFetchImpl?c.FetchHTTPImplementation:typeof window<"u"?c.XHRHTTPImplementation:c.FetchHTTPImplementation;a.registerDependencies(this._injector,a.mergeOverrideWithDependencies([[c.HTTPService],[k,{useClass:t}]],(i=this._config)==null?void 0:i.override))}},w(A,"pluginName","UNIVER_NETWORK_PLUGIN"),A),c.UniverNetworkPlugin=se([X(1,a.ILogService),X(2,a.Inject(a.Injector))],c.UniverNetworkPlugin);const ie=a.createIdentifier("univer.network.socket.service");class oe extends a.Disposable{createSocket(n){try{const t=new WebSocket(n),r=new a.DisposableCollection;return{URL:n,close:(i,o)=>{t.close(i,o),r.dispose()},send:i=>{t.send(i)},open$:new m.Observable(i=>{const o=l=>i.next(l);t.addEventListener("open",o),r.add(a.toDisposable(()=>t.removeEventListener("open",o)))}).pipe(_.share()),close$:new m.Observable(i=>{const o=l=>i.next(l);t.addEventListener("close",o),r.add(a.toDisposable(()=>t.removeEventListener("close",o)))}).pipe(_.share()),error$:new m.Observable(i=>{const o=l=>i.next(l);t.addEventListener("error",o),r.add(a.toDisposable(()=>t.removeEventListener("error",o)))}).pipe(_.share()),message$:new m.Observable(i=>{const o=l=>i.next(l);t.addEventListener("message",o),r.add(a.toDisposable(()=>t.removeEventListener("message",o)))}).pipe(_.share())}}catch(t){return console.error(t),null}}}const ce=3,ae=1e3,le=e=>{var r,s;const n=(r=e==null?void 0:e.maxRetryAttempts)!=null?r:ce,t=(s=e==null?void 0:e.delayInterval)!=null?s:ae;return(i,o)=>o(i).pipe(_.retry({delay:t,count:n}))},he=e=>{const n=[],t=new Set,r=()=>{var s;for(;t.size<((s=e==null?void 0:e.maxParallel)!=null?s:1)&&n.length>0;){const i=n.shift();t.add(i),i()}};return(s,i)=>new m.Observable(o=>{const l=()=>i(s).subscribe({next:g=>o.next(g),error:g=>o.error(g),complete:()=>o.complete()}),u=()=>{t.delete(l),a.remove(n,l),r()};return n.push(l),r(),u})},de=e=>{const{errorStatusCodes:n,onAuthError:t}=e;return(s,i)=>i(s).pipe(m.catchError(o=>(o instanceof R&&n.some(l=>l===o.status)&&t(),m.throwError(()=>o))))},pe=(e=300)=>{let t=()=>{};return r=>new Promise(s=>{t();const i=setTimeout(()=>{s(!0)},e);t=()=>{clearTimeout(i),s(!1)}})},ue=()=>(e,n)=>n.map(t=>({config:t,result:e})),ge=(e,n={})=>{const{isMatch:t,getParamsFromRequest:r,mergeParamsToRequest:s}=e,{fetchCheck:i=pe(300),distributeResult:o=ue()}=n,l=[],u=g=>g.map(h=>h.config);return(g,h)=>t(g)?new m.Observable(d=>{const p=r(g);l.push({next:y=>d.next(y),error:y=>d.error(y),config:p});const v=u(l);i(g).then(y=>{if(y){const I=[];v.forEach(f=>{const b=l.findIndex(E=>E.config===f);if(b>=0){const[E]=l.splice(b,1);I.push(E)}}),h(s(v,g)).subscribe({next:f=>{if(f.type===U.Response){const b=f.body,E=o(b,v);I.forEach(D=>{const G=E.find(q=>q.config===D.config);if(G){const q=new N({body:G.result,headers:f.headers,status:f.status,statusText:f.statusText});D.next(q)}else D.error("batch error")})}},complete:()=>d.complete(),error:f=>d.error(f)})}})}):h(g)};c.AuthInterceptorFactory=de,c.HTTPEventType=U,c.HTTPHeaders=L,c.HTTPProgress=j,c.HTTPRequest=O,c.HTTPResponse=N,c.HTTPResponseError=R,c.HTTPStatusCode=F,c.IHTTPImplementation=k,c.ISocketService=ie,c.MergeInterceptorFactory=ge,c.ResponseHeader=x,c.RetryInterceptorFactory=le,c.ThresholdInterceptorFactory=he,c.WebSocketService=oe,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})});
2
+ `).forEach(t=>{const[r,s]=t.split(":");r&&s&&this._setHeader(r,s)})}_handleHeadersConstructorProps(n){Object.entries(n).forEach(([t,r])=>this._setHeader(t,r))}_handleHeaders(n){n.forEach((t,r)=>this._setHeader(r,t))}}const k=a.createIdentifier("network.http-implementation");class ${constructor(n){this.params=n}toString(){return this.params?Object.keys(this.params).map(n=>{const t=this.params[n];return Array.isArray(t)?t.map(r=>`${n}=${r}`).join("&"):`${n}=${t}`}).join("&"):""}}let W=0;class O{constructor(n,t,r){w(this,"uid",W++);this.method=n,this.url=t,this.requestParams=r}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var t,r;const n=(r=(t=this.requestParams)==null?void 0:t.params)==null?void 0:r.toString();return n?`${this.url}${this.url.includes("?")?"&":"?"}${n}`:this.url}getBody(){var r,s;const n=(r=this.headers.get("Content-Type"))!=null?r:M,t=(s=this.requestParams)==null?void 0:s.body;return n===M&&t&&typeof t=="object"?JSON.stringify(t):t?`${t}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}var V=Object.getOwnPropertyDescriptor,z=(e,n,t,r)=>{for(var s=r>1?void 0:r?V(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},J=(e,n)=>(t,r)=>n(t,r,e);c.HTTPService=class extends a.Disposable{constructor(t){super();w(this,"_interceptors",[]);w(this,"_pipe");this._http=t}registerHTTPInterceptor(t){if(this._interceptors.indexOf(t)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(t),this._interceptors=this._interceptors.sort((r,s)=>{var i,o;return((i=r.priority)!=null?i:0)-((o=s.priority)!=null?o:0)}),this._pipe=null,a.toDisposable(()=>a.remove(this._interceptors,t))}get(t,r){return this._request("GET",t,r)}post(t,r){return this._request("POST",t,r)}put(t,r){return this._request("PUT",t,r)}delete(t,r){return this._request("DELETE",t,r)}patch(t,r){return this._request("PATCH",t,r)}getSSE(t,r,s){var u,g;const i=new L(s==null?void 0:s.headers),o=new $(s==null?void 0:s.params),l=new O(t,r,{headers:i,params:o,withCredentials:(u=s==null?void 0:s.withCredentials)!=null?u:!1,reportProgress:!0,responseType:(g=s==null?void 0:s.responseType)!=null?g:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body});return m.of(l).pipe(_.concatMap(h=>this._runInterceptorsAndImplementation(h)))}async _request(t,r,s){var h,d;const i=new L(s==null?void 0:s.headers),o=new $(s==null?void 0:s.params),l=new O(t,r,{headers:i,params:o,withCredentials:(h=s==null?void 0:s.withCredentials)!=null?h:!1,responseType:(d=s==null?void 0:s.responseType)!=null?d:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body}),u=m.of(l).pipe(_.concatMap(p=>this._runInterceptorsAndImplementation(p)));return await m.firstValueFrom(u)}_runInterceptorsAndImplementation(t){return this._pipe||(this._pipe=this._interceptors.map(r=>r.interceptor).reduceRight((r,s)=>K(r,s),(r,s)=>s(r))),this._pipe(t,r=>this._http.send(r))}},c.HTTPService=z([J(0,k)],c.HTTPService);function K(e,n){return(t,r)=>n(t,s=>e(s,r))}const Y=200,Q=300;var F=(e=>(e[e.Continue=100]="Continue",e[e.SwitchingProtocols=101]="SwitchingProtocols",e[e.Processing=102]="Processing",e[e.EarlyHints=103]="EarlyHints",e[e.Ok=200]="Ok",e[e.Created=201]="Created",e[e.Accepted=202]="Accepted",e[e.NonAuthoritativeInformation=203]="NonAuthoritativeInformation",e[e.NoContent=204]="NoContent",e[e.ResetContent=205]="ResetContent",e[e.PartialContent=206]="PartialContent",e[e.MultiStatus=207]="MultiStatus",e[e.AlreadyReported=208]="AlreadyReported",e[e.ImUsed=226]="ImUsed",e[e.MultipleChoices=300]="MultipleChoices",e[e.MovedPermanently=301]="MovedPermanently",e[e.Found=302]="Found",e[e.SeeOther=303]="SeeOther",e[e.NotModified=304]="NotModified",e[e.UseProxy=305]="UseProxy",e[e.Unused=306]="Unused",e[e.TemporaryRedirect=307]="TemporaryRedirect",e[e.PermanentRedirect=308]="PermanentRedirect",e[e.BadRequest=400]="BadRequest",e[e.Unauthorized=401]="Unauthorized",e[e.PaymentRequired=402]="PaymentRequired",e[e.Forbidden=403]="Forbidden",e[e.NotFound=404]="NotFound",e[e.MethodNotAllowed=405]="MethodNotAllowed",e[e.NotAcceptable=406]="NotAcceptable",e[e.ProxyAuthenticationRequired=407]="ProxyAuthenticationRequired",e[e.RequestTimeout=408]="RequestTimeout",e[e.Conflict=409]="Conflict",e[e.Gone=410]="Gone",e[e.LengthRequired=411]="LengthRequired",e[e.PreconditionFailed=412]="PreconditionFailed",e[e.PayloadTooLarge=413]="PayloadTooLarge",e[e.UriTooLong=414]="UriTooLong",e[e.UnsupportedMediaType=415]="UnsupportedMediaType",e[e.RangeNotSatisfiable=416]="RangeNotSatisfiable",e[e.ExpectationFailed=417]="ExpectationFailed",e[e.ImATeapot=418]="ImATeapot",e[e.MisdirectedRequest=421]="MisdirectedRequest",e[e.UnprocessableEntity=422]="UnprocessableEntity",e[e.Locked=423]="Locked",e[e.FailedDependency=424]="FailedDependency",e[e.TooEarly=425]="TooEarly",e[e.UpgradeRequired=426]="UpgradeRequired",e[e.PreconditionRequired=428]="PreconditionRequired",e[e.TooManyRequests=429]="TooManyRequests",e[e.RequestHeaderFieldsTooLarge=431]="RequestHeaderFieldsTooLarge",e[e.UnavailableForLegalReasons=451]="UnavailableForLegalReasons",e[e.InternalServerError=500]="InternalServerError",e[e.NotImplemented=501]="NotImplemented",e[e.BadGateway=502]="BadGateway",e[e.ServiceUnavailable=503]="ServiceUnavailable",e[e.GatewayTimeout=504]="GatewayTimeout",e[e.HttpVersionNotSupported=505]="HttpVersionNotSupported",e[e.VariantAlsoNegotiates=506]="VariantAlsoNegotiates",e[e.InsufficientStorage=507]="InsufficientStorage",e[e.LoopDetected=508]="LoopDetected",e[e.NotExtended=510]="NotExtended",e[e.NetworkAuthenticationRequired=511]="NetworkAuthenticationRequired",e))(F||{}),U=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(U||{});class N{constructor({body:n,headers:t,status:r,statusText:s}){w(this,"type",1);w(this,"body");w(this,"headers");w(this,"status");w(this,"statusText");this.body=n,this.headers=t,this.status=r,this.statusText=s}}class j{constructor(n,t,r){w(this,"type",0);this.total=n,this.loaded=t,this.partialText=r}}class x{constructor(n,t,r){this.headers=n,this.status=t,this.statusText=r}}class R{constructor({request:n,headers:t,status:r,statusText:s,error:i}){w(this,"request");w(this,"headers");w(this,"status");w(this,"statusText");w(this,"error");this.request=n,this.headers=t,this.status=r,this.statusText=s,this.error=i}}function B(e){return{method:e.method,headers:e.getHeadersInit(),body:e.getBody(),credentials:e.withCredentials?"include":void 0}}var Z=Object.getOwnPropertyDescriptor,P=(e,n,t,r)=>{for(var s=r>1?void 0:r?Z(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},H=(e,n)=>(t,r)=>n(t,r,e);c.FetchHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new m.Observable(t=>{const r=new AbortController;return this._send(n,t,r).catch(s=>{t.error(new R({error:s,request:n}))}),()=>r.abort()})}async _send(n,t,r){var h,d;let s;try{const p=B(n),v=n.getUrlWithParams(),y=fetch(v,{signal:r.signal,...p});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${v} with params ${p}`),s=await y}catch(p){const v=new R({request:n,error:p,status:(h=p.status)!=null?h:0,statusText:(d=p.statusText)!=null?d:"Unknown Error",headers:p.headers});this._logService.error("[FetchHTTPImplementation]: network error",v),t.error(v);return}const i=new L(s.headers),o=s.status,l=s.statusText;let u=null;if(s.body&&(u=await this._readBody(n,s,t)),o>=F.Ok&&o<F.MultipleChoices)t.next(new N({body:u,headers:i,status:o,statusText:l}));else{const p=new R({request:n,error:u,status:o,statusText:l,headers:i});this._logService.error("[FetchHTTPImplementation]: network error",p),t.error(p)}t.complete()}async _readBody(n,t,r){var v,y;const s=[],i=t.body.getReader(),o=t.headers.get("content-length");let l=0;const u=(v=n.requestParams)==null?void 0:v.reportProgress,g=n.responseType;let h,d;for(;;){const{done:I,value:f}=await i.read();if(I)break;s.push(f),l+=f.length,u&&g==="text"&&(h=(h!=null?h:"")+(d!=null?d:d=new TextDecoder).decode(f,{stream:!0}),r.next(new j(o?Number.parseInt(o,10):void 0,l,h)))}const p=S(s,l);try{const I=(y=t.headers.get("content-type"))!=null?y:"";return T(n,p,I)}catch(I){const f=new R({request:n,error:I,status:t.status,statusText:t.statusText,headers:new L(t.headers)});return this._logService.error("[FetchHTTPImplementation]: network error",f),r.error(f),null}}},c.FetchHTTPImplementation=P([H(0,a.ILogService)],c.FetchHTTPImplementation);function S(e,n){const t=new Uint8Array(n);let r=0;for(const s of e)t.set(s,r),r+=s.length;return t}const C=/^\)\]\}',?\n/;function T(e,n,t){switch(e.responseType){case"json":const r=new TextDecoder().decode(n).replace(C,"");return r===""?null:JSON.parse(r);case"text":return new TextDecoder().decode(n);case"blob":return new Blob([n],{type:t});case"arraybuffer":return n.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}var ee=Object.getOwnPropertyDescriptor,te=(e,n,t,r)=>{for(var s=r>1?void 0:r?ee(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},re=(e,n)=>(t,r)=>n(t,r,e);c.XHRHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new m.Observable(t=>{const r=new XMLHttpRequest,s=n.getUrlWithParams(),i=B(n);r.open(n.method,s),n.withCredentials&&(r.withCredentials=!0),i.headers&&Object.entries(i.headers).forEach(([h,d])=>r.setRequestHeader(h,d));const o=()=>{const h=r.statusText||"OK",d=new L(r.getAllResponseHeaders());return new x(d,r.status,h)},l=()=>{const{headers:h,statusText:d,status:p}=o(),{responseType:v}=n;let y=null,I=null;p!==F.NoContent&&(y=typeof r.response>"u"?r.responseText:r.response);let f=p>=Y&&p<Q;if(v==="json"&&typeof y=="string"){const b=y;try{y=y?JSON.parse(y):null}catch(E){f=!1,y=b,I=E}}if(f)t.next(new N({body:y,headers:h,status:p,statusText:d}));else{const b=new R({request:n,error:I,headers:h,status:p,statusText:d});this._logService.error("[XHRHTTPImplementation]: network error",b),t.error(b)}},u=h=>{const d=new R({request:n,error:h,status:r.status||0,statusText:r.statusText||"Unknown Error",headers:o().headers});this._logService.error("[XHRHTTPImplementation]: network error",d),t.error(d)};r.addEventListener("load",l),r.addEventListener("error",u),r.addEventListener("abort",u),r.addEventListener("timeout",u);const g=n.getBody();return r.send(g),this._logService.debug("[XHRHTTPImplementation]",`sending request to url ${s} with params ${i}`),()=>{r.readyState!==r.DONE&&r.abort(),r.removeEventListener("load",l),r.removeEventListener("error",u),r.removeEventListener("abort",u),r.removeEventListener("timeout",u)}})}},c.XHRHTTPImplementation=te([re(0,a.ILogService)],c.XHRHTTPImplementation);var ne=Object.getOwnPropertyDescriptor,se=(e,n,t,r)=>{for(var s=r>1?void 0:r?ne(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},X=(e,n)=>(t,r)=>n(t,r,e);c.UniverNetworkPlugin=(A=class extends a.Plugin{constructor(n=void 0,t,r){super(),this._config=n,this._logger=t,this._injector=r}onStarting(){var r,s,i;if(this._injector.get(c.HTTPService,a.Quantity.OPTIONAL,a.LookUp.SKIP_SELF)&&!((r=this._config)!=null&&r.forceUseNewInstance)){this._logger.warn("[UniverNetworkPlugin]",'HTTPService is already registered in an ancestor interceptor. Skipping registration. If you want to force a new instance, set "forceUseNewInstance" to true in the plugin configuration.');return}const t=(s=this._config)!=null&&s.useFetchImpl?c.FetchHTTPImplementation:typeof window<"u"?c.XHRHTTPImplementation:c.FetchHTTPImplementation;a.registerDependencies(this._injector,a.mergeOverrideWithDependencies([[c.HTTPService],[k,{useClass:t}]],(i=this._config)==null?void 0:i.override))}},w(A,"pluginName","UNIVER_NETWORK_PLUGIN"),A),c.UniverNetworkPlugin=se([X(1,a.ILogService),X(2,a.Inject(a.Injector))],c.UniverNetworkPlugin);const ie=a.createIdentifier("univer.network.socket.service");class oe extends a.Disposable{createSocket(n){try{const t=new WebSocket(n),r=new a.DisposableCollection;return{URL:n,close:(i,o)=>{t.close(i,o),r.dispose()},send:i=>{t.send(i)},open$:new m.Observable(i=>{const o=l=>i.next(l);t.addEventListener("open",o),r.add(a.toDisposable(()=>t.removeEventListener("open",o)))}).pipe(_.share()),close$:new m.Observable(i=>{const o=l=>i.next(l);t.addEventListener("close",o),r.add(a.toDisposable(()=>t.removeEventListener("close",o)))}).pipe(_.share()),error$:new m.Observable(i=>{const o=l=>i.next(l);t.addEventListener("error",o),r.add(a.toDisposable(()=>t.removeEventListener("error",o)))}).pipe(_.share()),message$:new m.Observable(i=>{const o=l=>i.next(l);t.addEventListener("message",o),r.add(a.toDisposable(()=>t.removeEventListener("message",o)))}).pipe(_.share())}}catch(t){return console.error(t),null}}}const ce=3,ae=1e3,le=e=>{var r,s;const n=(r=e==null?void 0:e.maxRetryAttempts)!=null?r:ce,t=(s=e==null?void 0:e.delayInterval)!=null?s:ae;return(i,o)=>o(i).pipe(_.retry({delay:t,count:n}))},he=e=>{const n=[],t=new Set,r=()=>{var s;for(;t.size<((s=e==null?void 0:e.maxParallel)!=null?s:1)&&n.length>0;){const i=n.shift();t.add(i),i()}};return(s,i)=>new m.Observable(o=>{const l=()=>i(s).subscribe({next:g=>o.next(g),error:g=>o.error(g),complete:()=>o.complete()}),u=()=>{t.delete(l),a.remove(n,l),r()};return n.push(l),r(),u})},de=e=>{const{errorStatusCodes:n,onAuthError:t}=e;return(s,i)=>i(s).pipe(m.catchError(o=>(o instanceof R&&n.some(l=>l===o.status)&&t(),m.throwError(()=>o))))},pe=(e=300)=>{let t=()=>{};return r=>new Promise(s=>{t();const i=setTimeout(()=>{s(!0)},e);t=()=>{clearTimeout(i),s(!1)}})},ue=()=>(e,n)=>n.map(t=>({config:t,result:e})),ge=(e,n={})=>{const{isMatch:t,getParamsFromRequest:r,mergeParamsToRequest:s}=e,{fetchCheck:i=pe(300),distributeResult:o=ue()}=n,l=[],u=g=>g.map(h=>h.config);return(g,h)=>t(g)?new m.Observable(d=>{const p=r(g);l.push({next:y=>d.next(y),error:y=>d.error(y),config:p});const v=u(l);i(g).then(y=>{if(y){const I=[];v.forEach(f=>{const b=l.findIndex(E=>E.config===f);if(b>=0){const[E]=l.splice(b,1);I.push(E)}}),h(s(v,g)).subscribe({next:f=>{if(f.type===U.Response){const b=f.body,E=o(b,v);I.forEach(D=>{const G=E.find(q=>q.config===D.config);if(G){const q=new N({body:G.result,headers:f.headers,status:f.status,statusText:f.statusText});D.next(q)}else D.error("batch error")})}},complete:()=>d.complete(),error:f=>d.error(f)})}})}):h(g)};c.AuthInterceptorFactory=de,c.HTTPEventType=U,c.HTTPHeaders=L,c.HTTPProgress=j,c.HTTPRequest=O,c.HTTPResponse=N,c.HTTPResponseError=R,c.HTTPStatusCode=F,c.IHTTPImplementation=k,c.ISocketService=ie,c.MergeInterceptorFactory=ge,c.ResponseHeader=x,c.RetryInterceptorFactory=le,c.ThresholdInterceptorFactory=he,c.WebSocketService=oe,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@univerjs/network",
3
- "version": "0.6.0",
3
+ "version": "0.6.1",
4
4
  "private": false,
5
5
  "author": "DreamNum <developer@univer.ai>",
6
6
  "license": "Apache-2.0",
@@ -52,14 +52,14 @@
52
52
  "rxjs": ">=7.0.0"
53
53
  },
54
54
  "dependencies": {
55
- "@univerjs/core": "0.6.0"
55
+ "@univerjs/core": "0.6.1"
56
56
  },
57
57
  "devDependencies": {
58
58
  "rxjs": "^7.8.1",
59
59
  "typescript": "^5.7.3",
60
- "vite": "^6.1.0",
61
- "vitest": "^3.0.5",
62
- "@univerjs-infra/shared": "0.6.0"
60
+ "vite": "^6.1.1",
61
+ "vitest": "^3.0.6",
62
+ "@univerjs-infra/shared": "0.6.1"
63
63
  },
64
64
  "scripts": {
65
65
  "test": "vitest run",