@univerjs/network 0.8.0-nightly.202506091607 → 0.8.0-nightly.202506111607

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
- "use strict";var G=Object.defineProperty;var W=(e,n,r)=>n in e?G(e,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[n]=r;var f=(e,n,r)=>W(e,typeof n!="symbol"?n+"":n,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("@univerjs/core"),w=require("rxjs"),_=require("rxjs/operators"),A="application/json";function V(e){return Array.isArray(e)?e.some(n=>n.includes(A)):e.includes(A)}class E{constructor(n){f(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((r,t)=>n(t,r))}has(n){return!!this._headers.has(n.toLowerCase())}get(n){const r=n.toLowerCase();return this._headers.has(r)?this._headers.get(r):null}set(n,r){this._setHeader(n,r)}toHeadersInit(n){var t,s;const r={};return this._headers.forEach((o,i)=>{r[i]=o.join(",")}),(t=r.accept)!=null||(r.accept="application/json, text/plain, */*"),n instanceof FormData||(s=r["content-type"])!=null||(r["content-type"]="application/json;charset=UTF-8"),r}_setHeader(n,r){const t=n.toLowerCase();this._headers.has(t)?this._headers.get(t).push(r.toString()):this._headers.set(t,[r.toString()])}_handleHeadersString(n){n.split(`
2
- `).forEach(r=>{const[t,s]=r.split(":");t&&s&&this._setHeader(t,s)})}_handleHeadersConstructorProps(n){Object.entries(n).forEach(([r,t])=>this._setHeader(r,t))}_handleHeaders(n){n.forEach((r,t)=>this._setHeader(t,r))}}const U=p.createIdentifier("network.http-implementation");class M{constructor(n){this.params=n}toString(){return this.params?Object.keys(this.params).map(n=>{const r=this.params[n];return Array.isArray(r)?r.map(t=>`${n}=${t}`).join("&"):`${n}=${r}`}).join("&"):""}}let J=0;class O{constructor(n,r,t){f(this,"uid",J++);this.method=n,this.url=r,this.requestParams=t}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var r,t;const n=(t=(r=this.requestParams)==null?void 0:r.params)==null?void 0:t.toString();return n?`${this.url}${this.url.includes("?")?"&":"?"}${n}`:this.url}getBody(){var t,s;const n=(t=this.headers.get("Content-Type"))!=null?t:A,r=(s=this.requestParams)==null?void 0:s.body;return r instanceof FormData?r:V(n)&&r&&typeof r=="object"?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){var r;return this.headers.toHeadersInit((r=this.requestParams)==null?void 0:r.body)}}var z=Object.getOwnPropertyDescriptor,K=(e,n,r,t)=>{for(var s=t>1?void 0:t?z(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},Y=(e,n)=>(r,t)=>n(r,t,e);exports.HTTPService=class extends p.Disposable{constructor(r){super();f(this,"_interceptors",[]);f(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((t,s)=>{var o,i;return((o=t.priority)!=null?o:0)-((i=s.priority)!=null?i:0)}),this._pipe=null,p.toDisposable(()=>p.remove(this._interceptors,r))}get(r,t){return this._request("GET",r,t)}post(r,t){return this._request("POST",r,t)}put(r,t){return this._request("PUT",r,t)}delete(r,t){return this._request("DELETE",r,t)}patch(r,t){return this._request("PATCH",r,t)}getSSE(r,t,s){var y,l;const o=new E(s==null?void 0:s.headers),i=new M(s==null?void 0:s.params),c=new O(r,t,{headers:o,params:i,withCredentials:(y=s==null?void 0:s.withCredentials)!=null?y:!1,reportProgress:!0,responseType:(l=s==null?void 0:s.responseType)!=null?l:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body});return w.of(c).pipe(_.concatMap(u=>this._runInterceptorsAndImplementation(u)))}async _request(r,t,s){var u,h;const o=new E(s==null?void 0:s.headers),i=new M(s==null?void 0:s.params),c=new O(r,t,{headers:o,params:i,withCredentials:(u=s==null?void 0:s.withCredentials)!=null?u:!1,responseType:(h=s==null?void 0:s.responseType)!=null?h:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body}),y=w.of(c).pipe(_.concatMap(a=>this._runInterceptorsAndImplementation(a)));return await w.firstValueFrom(y)}_runInterceptorsAndImplementation(r){return this._pipe||(this._pipe=this._interceptors.map(t=>t.interceptor).reduceRight((t,s)=>Q(t,s),(t,s)=>s(t))),this._pipe(r,t=>this._http.send(t))}};exports.HTTPService=K([Y(0,U)],exports.HTTPService);function Q(e,n){return(r,t)=>n(r,s=>e(s,t))}const Z=200,P=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||{}),D=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(D||{});class L{constructor({body:n,headers:r,status:t,statusText:s}){f(this,"type",1);f(this,"body");f(this,"headers");f(this,"status");f(this,"statusText");this.body=n,this.headers=r,this.status=t,this.statusText=s}}class j{constructor(n,r,t){f(this,"type",0);this.total=n,this.loaded=r,this.partialText=t}}class B{constructor(n,r,t){this.headers=n,this.status=r,this.statusText=t}}class I{constructor({request:n,headers:r,status:t,statusText:s,error:o}){f(this,"request");f(this,"headers");f(this,"status");f(this,"statusText");f(this,"error");this.request=n,this.headers=r,this.status=t,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 H=Object.getOwnPropertyDescriptor,S=(e,n,r,t)=>{for(var s=t>1?void 0:t?H(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},C=(e,n)=>(r,t)=>n(r,t,e);exports.FetchHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new w.Observable(r=>{const t=new AbortController;return this._send(n,r,t).catch(s=>{r.error(new I({error:s,request:n}))}),()=>t.abort()})}async _send(n,r,t){var u,h;let s;try{const a=X(n),m=n.getUrlWithParams(),g=fetch(m,{signal:t.signal,...a});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${m} with params ${a}`),s=await g}catch(a){const m=new I({request:n,error:a,status:(u=a.status)!=null?u:0,statusText:(h=a.statusText)!=null?h:"Unknown Error",headers:a.headers});this._logService.error("[FetchHTTPImplementation]: network error",m),r.error(m);return}const o=new E(s.headers),i=s.status,c=s.statusText;let y=null;if(s.body&&(y=await this._readBody(n,s,r)),i>=x.Ok&&i<x.MultipleChoices)r.next(new L({body:y,headers:o,status:i,statusText:c}));else{const a=new I({request:n,error:y,status:i,statusText:c,headers:o});this._logService.error("[FetchHTTPImplementation]: network error",a),r.error(a)}r.complete()}async _readBody(n,r,t){var m,g;const s=[],o=r.body.getReader(),i=r.headers.get("content-length");let c=0;const y=(m=n.requestParams)==null?void 0:m.reportProgress,l=n.responseType;let u,h;for(;;){const{done:v,value:d}=await o.read();if(v)break;s.push(d),c+=d.length,y&&l==="text"&&(u=(u!=null?u:"")+(h!=null?h:h=new TextDecoder).decode(d,{stream:!0}),t.next(new j(i?Number.parseInt(i,10):void 0,c,u)))}const a=T(s,c);try{const v=(g=r.headers.get("content-type"))!=null?g:"";return re(n,a,v)}catch(v){const d=new I({request:n,error:v,status:r.status,statusText:r.statusText,headers:new E(r.headers)});return this._logService.error("[FetchHTTPImplementation]: network error",d),t.error(d),null}}};exports.FetchHTTPImplementation=S([C(0,p.ILogService)],exports.FetchHTTPImplementation);function T(e,n){const r=new Uint8Array(n);let t=0;for(const s of e)r.set(s,t),t+=s.length;return r}const ee=/^\)\]\}',?\n/;function re(e,n,r){switch(e.responseType){case"json":const t=new TextDecoder().decode(n).replace(ee,"");return t===""?null:JSON.parse(t);case"text":return new TextDecoder().decode(n);case"blob":return new Blob([n],{type:r});case"arraybuffer":return n.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}var te=Object.getOwnPropertyDescriptor,ne=(e,n,r,t)=>{for(var s=t>1?void 0:t?te(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},se=(e,n)=>(r,t)=>n(r,t,e);exports.XHRHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new w.Observable(r=>{const t=new XMLHttpRequest,s=n.getUrlWithParams(),o=X(n),{responseType:i}=n;t.open(n.method,s),n.withCredentials&&(t.withCredentials=!0),o.headers&&Object.entries(o.headers).forEach(([h,a])=>t.setRequestHeader(h,a));const c=()=>{const h=t.statusText||"OK",a=new E(t.getAllResponseHeaders());return new B(a,t.status,h)},y=()=>{const{headers:h,statusText:a,status:m}=c();let g=null,v=null;m!==x.NoContent&&(g=typeof t.response>"u"?t.responseText:t.response);let d=m>=Z&&m<P;if(i==="json"&&typeof g=="string"){const b=g;try{g=g?JSON.parse(g):null}catch(R){d=!1,g=b,v=R}}if(i==="blob"&&!(g instanceof Blob)&&(d=!1,v=new Error("Response is not a Blob object")),d)r.next(new L({body:g,headers:h,status:m,statusText:a}));else{const b=new I({request:n,error:v,headers:h,status:m,statusText:a});this._logService.error("[XHRHTTPImplementation]: network error",b),r.error(b)}},l=h=>{const a=new I({request:n,error:h,status:t.status||0,statusText:t.statusText||"Unknown Error",headers:c().headers});this._logService.error("[XHRHTTPImplementation]: network error",a),r.error(a)};t.responseType=i||"",t.addEventListener("load",y),t.addEventListener("error",l),t.addEventListener("abort",l),t.addEventListener("timeout",l);const u=n.getBody();return t.send(u),this._logService.debug("[XHRHTTPImplementation]",`sending request to url ${s} with params ${o}`),()=>{t.readyState!==t.DONE&&t.abort(),t.removeEventListener("load",y),t.removeEventListener("error",l),t.removeEventListener("abort",l),t.removeEventListener("timeout",l)}})}};exports.XHRHTTPImplementation=ne([se(0,p.ILogService)],exports.XHRHTTPImplementation);var oe=Object.getOwnPropertyDescriptor,ie=(e,n,r,t)=>{for(var s=t>1?void 0:t?oe(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},$=(e,n)=>(r,t)=>n(r,t,e),k;exports.UniverNetworkPlugin=(k=class extends p.Plugin{constructor(n=void 0,r,t){super(),this._config=n,this._logger=r,this._injector=t}onStarting(){var t,s,o;if(this._injector.get(exports.HTTPService,p.Quantity.OPTIONAL,p.LookUp.SKIP_SELF)&&!((t=this._config)!=null&&t.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],[U,{useClass:r}]],(o=this._config)==null?void 0:o.override))}},f(k,"pluginName","UNIVER_NETWORK_PLUGIN"),k);exports.UniverNetworkPlugin=ie([$(1,p.ILogService),$(2,p.Inject(p.Injector))],exports.UniverNetworkPlugin);const ce=p.createIdentifier("univer.network.socket.service");class ae extends p.Disposable{createSocket(n){try{const r=new WebSocket(n),t=new p.DisposableCollection;return{URL:n,close:(o,i)=>{r.close(o,i),t.dispose()},send:o=>{r.send(o)},open$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("open",i),t.add(p.toDisposable(()=>r.removeEventListener("open",i)))}).pipe(_.share()),close$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("close",i),t.add(p.toDisposable(()=>r.removeEventListener("close",i)))}).pipe(_.share()),error$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("error",i),t.add(p.toDisposable(()=>r.removeEventListener("error",i)))}).pipe(_.share()),message$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("message",i),t.add(p.toDisposable(()=>r.removeEventListener("message",i)))}).pipe(_.share())}}catch(r){return console.error(r),null}}}const le=3,he=1e3,pe=e=>{var t,s;const n=(t=e==null?void 0:e.maxRetryAttempts)!=null?t:le,r=(s=e==null?void 0:e.delayInterval)!=null?s:he;return(o,i)=>i(o).pipe(_.retry({delay:r,count:n}))},de=e=>{const n=[],r=new Set,t=()=>{var s;for(;r.size<((s=e==null?void 0:e.maxParallel)!=null?s:1)&&n.length>0;){const o=n.shift();r.add(o),o()}};return(s,o)=>new w.Observable(i=>{const c=()=>o(s).subscribe({next:l=>i.next(l),error:l=>i.error(l),complete:()=>i.complete()}),y=()=>{r.delete(c),p.remove(n,c),t()};return n.push(c),t(),y})},ue=e=>{const{errorStatusCodes:n,onAuthError:r}=e;return(s,o)=>o(s).pipe(w.catchError(i=>(i instanceof I&&n.some(c=>c===i.status)&&r(),w.throwError(()=>i))))},ge=(e=300)=>{let r=()=>{};return t=>new Promise(s=>{r();const o=setTimeout(()=>{s(!0)},e);r=()=>{clearTimeout(o),s(!1)}})},me=()=>(e,n)=>n.map(r=>({config:r,result:e})),ye=(e,n={})=>{const{isMatch:r,getParamsFromRequest:t,mergeParamsToRequest:s}=e,{fetchCheck:o=ge(300),distributeResult:i=me()}=n,c=[],y=l=>l.map(u=>u.config);return(l,u)=>r(l)?new w.Observable(h=>{const a=t(l);c.push({next:g=>h.next(g),error:g=>h.error(g),config:a});const m=y(c);o(l).then(g=>{if(g){const v=[];m.forEach(d=>{const b=c.findIndex(R=>R.config===d);if(b>=0){const[R]=c.splice(b,1);v.push(R)}}),u(s(m,l)).subscribe({next:d=>{if(d.type===D.Response){const b=d.body,R=i(b,m);v.forEach(F=>{const q=R.find(N=>N.config===F.config);if(q){const N=new L({body:q.result,headers:d.headers,status:d.status,statusText:d.statusText});F.next(N)}else F.error("batch error")})}},complete:()=>h.complete(),error:d=>h.error(d)})}})}):u(l)};exports.AuthInterceptorFactory=ue;exports.HTTPEventType=D;exports.HTTPHeaders=E;exports.HTTPProgress=j;exports.HTTPRequest=O;exports.HTTPResponse=L;exports.HTTPResponseError=I;exports.HTTPStatusCode=x;exports.IHTTPImplementation=U;exports.ISocketService=ce;exports.MergeInterceptorFactory=ye;exports.ResponseHeader=B;exports.RetryInterceptorFactory=pe;exports.ThresholdInterceptorFactory=de;exports.WebSocketService=ae;
1
+ "use strict";var G=Object.defineProperty;var W=(e,n,r)=>n in e?G(e,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[n]=r;var f=(e,n,r)=>W(e,typeof n!="symbol"?n+"":n,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("@univerjs/core"),w=require("rxjs"),E=require("rxjs/operators"),A="application/json";function V(e){return Array.isArray(e)?e.some(n=>n.includes(A)):e.includes(A)}class _{constructor(n){f(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((r,t)=>n(t,r))}has(n){return!!this._headers.has(n.toLowerCase())}get(n){const r=n.toLowerCase();return this._headers.has(r)?this._headers.get(r):null}set(n,r){this._setHeader(n,r)}toHeadersInit(n){var t,s;const r={};return this._headers.forEach((o,i)=>{r[i]=o.join(",")}),(t=r.accept)!=null||(r.accept="application/json, text/plain, */*"),n instanceof FormData||(s=r["content-type"])!=null||(r["content-type"]="application/json;charset=UTF-8"),r}_setHeader(n,r){const t=n.toLowerCase();this._headers.has(t)?this._headers.get(t).push(r.toString()):this._headers.set(t,[r.toString()])}_handleHeadersString(n){n.split(`
2
+ `).forEach(r=>{const[t,s]=r.split(":");t&&s&&this._setHeader(t,s)})}_handleHeadersConstructorProps(n){Object.entries(n).forEach(([r,t])=>this._setHeader(r,t))}_handleHeaders(n){n.forEach((r,t)=>this._setHeader(t,r))}}const U=p.createIdentifier("network.http-implementation");class M{constructor(n){this.params=n}toString(){return this.params?Object.keys(this.params).map(n=>{const r=this.params[n];return Array.isArray(r)?r.map(t=>`${n}=${t}`).join("&"):`${n}=${r}`}).join("&"):""}}let J=0;class O{constructor(n,r,t){f(this,"uid",J++);this.method=n,this.url=r,this.requestParams=t}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var r,t;const n=(t=(r=this.requestParams)==null?void 0:r.params)==null?void 0:t.toString();return n?`${this.url}${this.url.includes("?")?"&":"?"}${n}`:this.url}getBody(){var t,s;const n=(t=this.headers.get("Content-Type"))!=null?t:A,r=(s=this.requestParams)==null?void 0:s.body;return r instanceof FormData?r:V(n)&&r&&typeof r=="object"?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){var r;return this.headers.toHeadersInit((r=this.requestParams)==null?void 0:r.body)}}var z=Object.getOwnPropertyDescriptor,K=(e,n,r,t)=>{for(var s=t>1?void 0:t?z(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},Y=(e,n)=>(r,t)=>n(r,t,e);exports.HTTPService=class extends p.Disposable{constructor(r){super();f(this,"_interceptors",[]);f(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((t,s)=>{var o,i;return((o=t.priority)!=null?o:0)-((i=s.priority)!=null?i:0)}),this._pipe=null,p.toDisposable(()=>p.remove(this._interceptors,r))}get(r,t){return this.request("GET",r,t)}post(r,t){return this.request("POST",r,t)}put(r,t){return this.request("PUT",r,t)}delete(r,t){return this.request("DELETE",r,t)}patch(r,t){return this.request("PATCH",r,t)}async request(r,t,s){var u,h;const o=new _(s==null?void 0:s.headers),i=new M(s==null?void 0:s.params),c=new O(r,t,{headers:o,params:i,withCredentials:(u=s==null?void 0:s.withCredentials)!=null?u:!1,responseType:(h=s==null?void 0:s.responseType)!=null?h:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body}),y=w.of(c).pipe(E.concatMap(a=>this._runInterceptorsAndImplementation(a)));return await w.firstValueFrom(y)}stream(r,t,s){return this.getSSE(r,t,s)}getSSE(r,t,s){var y,l;const o=new _(s==null?void 0:s.headers),i=new M(s==null?void 0:s.params),c=new O(r,t,{headers:o,params:i,withCredentials:(y=s==null?void 0:s.withCredentials)!=null?y:!1,reportProgress:!0,responseType:(l=s==null?void 0:s.responseType)!=null?l:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body});return w.of(c).pipe(E.concatMap(u=>this._runInterceptorsAndImplementation(u)))}_runInterceptorsAndImplementation(r){return this._pipe||(this._pipe=this._interceptors.map(t=>t.interceptor).reduceRight((t,s)=>Q(t,s),(t,s)=>s(t))),this._pipe(r,t=>this._http.send(t))}};exports.HTTPService=K([Y(0,U)],exports.HTTPService);function Q(e,n){return(r,t)=>n(r,s=>e(s,t))}const Z=200,P=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||{}),D=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(D||{});class L{constructor({body:n,headers:r,status:t,statusText:s}){f(this,"type",1);f(this,"body");f(this,"headers");f(this,"status");f(this,"statusText");this.body=n,this.headers=r,this.status=t,this.statusText=s}}class j{constructor(n,r,t){f(this,"type",0);this.total=n,this.loaded=r,this.partialText=t}}class B{constructor(n,r,t){this.headers=n,this.status=r,this.statusText=t}}class I{constructor({request:n,headers:r,status:t,statusText:s,error:o}){f(this,"request");f(this,"headers");f(this,"status");f(this,"statusText");f(this,"error");this.request=n,this.headers=r,this.status=t,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 H=Object.getOwnPropertyDescriptor,S=(e,n,r,t)=>{for(var s=t>1?void 0:t?H(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},C=(e,n)=>(r,t)=>n(r,t,e);exports.FetchHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new w.Observable(r=>{const t=new AbortController;return this._send(n,r,t).catch(s=>{r.error(new I({error:s,request:n}))}),()=>t.abort()})}async _send(n,r,t){var u,h;let s;try{const a=X(n),m=n.getUrlWithParams(),g=fetch(m,{signal:t.signal,...a});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${m} with params ${a}`),s=await g}catch(a){const m=new I({request:n,error:a,status:(u=a.status)!=null?u:0,statusText:(h=a.statusText)!=null?h:"Unknown Error",headers:a.headers});this._logService.error("[FetchHTTPImplementation]: network error",m),r.error(m);return}const o=new _(s.headers),i=s.status,c=s.statusText;let y=null;if(s.body&&(y=await this._readBody(n,s,r)),i>=x.Ok&&i<x.MultipleChoices)r.next(new L({body:y,headers:o,status:i,statusText:c}));else{const a=new I({request:n,error:y,status:i,statusText:c,headers:o});this._logService.error("[FetchHTTPImplementation]: network error",a),r.error(a)}r.complete()}async _readBody(n,r,t){var m,g;const s=[],o=r.body.getReader(),i=r.headers.get("content-length");let c=0;const y=(m=n.requestParams)==null?void 0:m.reportProgress,l=n.responseType;let u,h;for(;;){const{done:v,value:d}=await o.read();if(v)break;s.push(d),c+=d.length,y&&l==="text"&&(u=(u!=null?u:"")+(h!=null?h:h=new TextDecoder).decode(d,{stream:!0}),t.next(new j(i?Number.parseInt(i,10):void 0,c,u)))}const a=T(s,c);try{const v=(g=r.headers.get("content-type"))!=null?g:"";return re(n,a,v)}catch(v){const d=new I({request:n,error:v,status:r.status,statusText:r.statusText,headers:new _(r.headers)});return this._logService.error("[FetchHTTPImplementation]: network error",d),t.error(d),null}}};exports.FetchHTTPImplementation=S([C(0,p.ILogService)],exports.FetchHTTPImplementation);function T(e,n){const r=new Uint8Array(n);let t=0;for(const s of e)r.set(s,t),t+=s.length;return r}const ee=/^\)\]\}',?\n/;function re(e,n,r){switch(e.responseType){case"json":const t=new TextDecoder().decode(n).replace(ee,"");return t===""?null:JSON.parse(t);case"text":return new TextDecoder().decode(n);case"blob":return new Blob([n],{type:r});case"arraybuffer":return n.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}var te=Object.getOwnPropertyDescriptor,ne=(e,n,r,t)=>{for(var s=t>1?void 0:t?te(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},se=(e,n)=>(r,t)=>n(r,t,e);exports.XHRHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new w.Observable(r=>{const t=new XMLHttpRequest,s=n.getUrlWithParams(),o=X(n),{responseType:i}=n;t.open(n.method,s),n.withCredentials&&(t.withCredentials=!0),o.headers&&Object.entries(o.headers).forEach(([h,a])=>t.setRequestHeader(h,a));const c=()=>{const h=t.statusText||"OK",a=new _(t.getAllResponseHeaders());return new B(a,t.status,h)},y=()=>{const{headers:h,statusText:a,status:m}=c();let g=null,v=null;m!==x.NoContent&&(g=typeof t.response>"u"?t.responseText:t.response);let d=m>=Z&&m<P;if(i==="json"&&typeof g=="string"){const b=g;try{g=g?JSON.parse(g):null}catch(R){d=!1,g=b,v=R}}if(i==="blob"&&!(g instanceof Blob)&&(d=!1,v=new Error("Response is not a Blob object")),d)r.next(new L({body:g,headers:h,status:m,statusText:a}));else{const b=new I({request:n,error:v,headers:h,status:m,statusText:a});this._logService.error("[XHRHTTPImplementation]: network error",b),r.error(b)}},l=h=>{const a=new I({request:n,error:h,status:t.status||0,statusText:t.statusText||"Unknown Error",headers:c().headers});this._logService.error("[XHRHTTPImplementation]: network error",a),r.error(a)};t.responseType=i||"",t.addEventListener("load",y),t.addEventListener("error",l),t.addEventListener("abort",l),t.addEventListener("timeout",l);const u=n.getBody();return t.send(u),this._logService.debug("[XHRHTTPImplementation]",`sending request to url ${s} with params ${o}`),()=>{t.readyState!==t.DONE&&t.abort(),t.removeEventListener("load",y),t.removeEventListener("error",l),t.removeEventListener("abort",l),t.removeEventListener("timeout",l)}})}};exports.XHRHTTPImplementation=ne([se(0,p.ILogService)],exports.XHRHTTPImplementation);var oe=Object.getOwnPropertyDescriptor,ie=(e,n,r,t)=>{for(var s=t>1?void 0:t?oe(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},$=(e,n)=>(r,t)=>n(r,t,e),k;exports.UniverNetworkPlugin=(k=class extends p.Plugin{constructor(n=void 0,r,t){super(),this._config=n,this._logger=r,this._injector=t}onStarting(){var t,s,o;if(this._injector.get(exports.HTTPService,p.Quantity.OPTIONAL,p.LookUp.SKIP_SELF)&&!((t=this._config)!=null&&t.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],[U,{useClass:r}]],(o=this._config)==null?void 0:o.override))}},f(k,"pluginName","UNIVER_NETWORK_PLUGIN"),k);exports.UniverNetworkPlugin=ie([$(1,p.ILogService),$(2,p.Inject(p.Injector))],exports.UniverNetworkPlugin);const ce=p.createIdentifier("univer.network.socket.service");class ae extends p.Disposable{createSocket(n){try{const r=new WebSocket(n),t=new p.DisposableCollection;return{URL:n,close:(o,i)=>{r.close(o,i),t.dispose()},send:o=>{r.send(o)},open$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("open",i),t.add(p.toDisposable(()=>r.removeEventListener("open",i)))}).pipe(E.share()),close$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("close",i),t.add(p.toDisposable(()=>r.removeEventListener("close",i)))}).pipe(E.share()),error$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("error",i),t.add(p.toDisposable(()=>r.removeEventListener("error",i)))}).pipe(E.share()),message$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("message",i),t.add(p.toDisposable(()=>r.removeEventListener("message",i)))}).pipe(E.share())}}catch(r){return console.error(r),null}}}const le=3,he=1e3,pe=e=>{var t,s;const n=(t=e==null?void 0:e.maxRetryAttempts)!=null?t:le,r=(s=e==null?void 0:e.delayInterval)!=null?s:he;return(o,i)=>i(o).pipe(E.retry({delay:r,count:n}))},de=e=>{const n=[],r=new Set,t=()=>{var s;for(;r.size<((s=e==null?void 0:e.maxParallel)!=null?s:1)&&n.length>0;){const o=n.shift();r.add(o),o()}};return(s,o)=>new w.Observable(i=>{const c=()=>o(s).subscribe({next:l=>i.next(l),error:l=>i.error(l),complete:()=>i.complete()}),y=()=>{r.delete(c),p.remove(n,c),t()};return n.push(c),t(),y})},ue=e=>{const{errorStatusCodes:n,onAuthError:r}=e;return(s,o)=>o(s).pipe(w.catchError(i=>(i instanceof I&&n.some(c=>c===i.status)&&r(),w.throwError(()=>i))))},ge=(e=300)=>{let r=()=>{};return t=>new Promise(s=>{r();const o=setTimeout(()=>{s(!0)},e);r=()=>{clearTimeout(o),s(!1)}})},me=()=>(e,n)=>n.map(r=>({config:r,result:e})),ye=(e,n={})=>{const{isMatch:r,getParamsFromRequest:t,mergeParamsToRequest:s}=e,{fetchCheck:o=ge(300),distributeResult:i=me()}=n,c=[],y=l=>l.map(u=>u.config);return(l,u)=>r(l)?new w.Observable(h=>{const a=t(l);c.push({next:g=>h.next(g),error:g=>h.error(g),config:a});const m=y(c);o(l).then(g=>{if(g){const v=[];m.forEach(d=>{const b=c.findIndex(R=>R.config===d);if(b>=0){const[R]=c.splice(b,1);v.push(R)}}),u(s(m,l)).subscribe({next:d=>{if(d.type===D.Response){const b=d.body,R=i(b,m);v.forEach(F=>{const q=R.find(N=>N.config===F.config);if(q){const N=new L({body:q.result,headers:d.headers,status:d.status,statusText:d.statusText});F.next(N)}else F.error("batch error")})}},complete:()=>h.complete(),error:d=>h.error(d)})}})}):u(l)};exports.AuthInterceptorFactory=ue;exports.HTTPEventType=D;exports.HTTPHeaders=_;exports.HTTPProgress=j;exports.HTTPRequest=O;exports.HTTPResponse=L;exports.HTTPResponseError=I;exports.HTTPStatusCode=x;exports.IHTTPImplementation=U;exports.ISocketService=ce;exports.MergeInterceptorFactory=ye;exports.ResponseHeader=B;exports.RetryInterceptorFactory=pe;exports.ThresholdInterceptorFactory=de;exports.WebSocketService=ae;
package/lib/es/index.js CHANGED
@@ -121,34 +121,29 @@ let x = class extends J {
121
121
  }), this._pipe = null, R(() => z(this._interceptors, t));
122
122
  }
123
123
  get(t, r) {
124
- return this._request("GET", t, r);
124
+ return this.request("GET", t, r);
125
125
  }
126
126
  post(t, r) {
127
- return this._request("POST", t, r);
127
+ return this.request("POST", t, r);
128
128
  }
129
129
  put(t, r) {
130
- return this._request("PUT", t, r);
130
+ return this.request("PUT", t, r);
131
131
  }
132
132
  delete(t, r) {
133
- return this._request("DELETE", t, r);
133
+ return this.request("DELETE", t, r);
134
134
  }
135
135
  patch(t, r) {
136
- return this._request("PATCH", t, r);
136
+ return this.request("PATCH", t, r);
137
137
  }
138
- getSSE(t, r, n) {
139
- var c, d;
140
- const s = new I(n == null ? void 0 : n.headers), o = new B(n == null ? void 0 : n.params), i = new G(t, r, {
141
- headers: s,
142
- params: o,
143
- withCredentials: (c = n == null ? void 0 : n.withCredentials) != null ? c : !1,
144
- reportProgress: !0,
145
- responseType: (d = n == null ? void 0 : n.responseType) != null ? d : "json",
146
- body: ["GET", "DELETE"].includes(t) || n == null ? void 0 : n.body
147
- });
148
- return j(i).pipe(M((l) => this._runInterceptorsAndImplementation(l)));
149
- }
150
- /** The HTTP request implementations */
151
- async _request(t, r, n) {
138
+ /**
139
+ * The HTTP request implementations. Normally you should use the `get`, `post`, `put`, `delete`,
140
+ * `patch` methods instead.
141
+ * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
142
+ * @param url The URL to send the request to.
143
+ * @param options Optional parameters for the request.
144
+ * @returns A promise that resolves to the HTTP response.
145
+ */
146
+ async request(t, r, n) {
152
147
  var l, h;
153
148
  const s = new I(n == null ? void 0 : n.headers), o = new B(n == null ? void 0 : n.params), i = new G(t, r, {
154
149
  headers: s,
@@ -162,6 +157,39 @@ let x = class extends J {
162
157
  );
163
158
  return await se(c);
164
159
  }
160
+ /**
161
+ * Send an HTTP request. It returns an observable that emits HTTP events. For example, it can be used to
162
+ * send Server-Sent Events (SSE) requests.
163
+ * @deprecated Please use `stream` method instead.
164
+ * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
165
+ * @param url The URL to send the request to.
166
+ * @param _params Optional parameters for the request.
167
+ * @returns An observable of the HTTP event.
168
+ */
169
+ stream(t, r, n) {
170
+ return this.getSSE(t, r, n);
171
+ }
172
+ /**
173
+ * Send a Server-Sent Events (SSE) request. It returns an observable that emits HTTP events. It is the observable
174
+ * pair of the `request` method.
175
+ * @deprecated Please use `stream` method instead.
176
+ * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
177
+ * @param url The URL to send the request to.
178
+ * @param _params Optional parameters for the request.
179
+ * @returns An observable of the HTTP event.
180
+ */
181
+ getSSE(t, r, n) {
182
+ var c, d;
183
+ const s = new I(n == null ? void 0 : n.headers), o = new B(n == null ? void 0 : n.params), i = new G(t, r, {
184
+ headers: s,
185
+ params: o,
186
+ withCredentials: (c = n == null ? void 0 : n.withCredentials) != null ? c : !1,
187
+ reportProgress: !0,
188
+ responseType: (d = n == null ? void 0 : n.responseType) != null ? d : "json",
189
+ body: ["GET", "DELETE"].includes(t) || n == null ? void 0 : n.body
190
+ });
191
+ return j(i).pipe(M((l) => this._runInterceptorsAndImplementation(l)));
192
+ }
165
193
  // eslint-disable-next-line ts/no-explicit-any
166
194
  _runInterceptorsAndImplementation(t) {
167
195
  return this._pipe || (this._pipe = this._interceptors.map((r) => r.interceptor).reduceRight(
@@ -236,7 +264,7 @@ var me = Object.getOwnPropertyDescriptor, ve = (e, t, r, n) => {
236
264
  for (var s = n > 1 ? void 0 : n ? me(t, r) : t, o = e.length - 1, i; o >= 0; o--)
237
265
  (i = e[o]) && (s = i(s) || s);
238
266
  return s;
239
- }, _e = (e, t) => (r, n) => t(r, n, e);
267
+ }, Ee = (e, t) => (r, n) => t(r, n, e);
240
268
  let N = class {
241
269
  constructor(e) {
242
270
  this._logService = e;
@@ -308,7 +336,7 @@ let N = class {
308
336
  l
309
337
  )));
310
338
  }
311
- const a = Ee(n, i);
339
+ const a = _e(n, i);
312
340
  try {
313
341
  const f = (p = t.headers.get("content-type")) != null ? p : "";
314
342
  return Ie(e, a, f);
@@ -325,9 +353,9 @@ let N = class {
325
353
  }
326
354
  };
327
355
  N = ve([
328
- _e(0, D)
356
+ Ee(0, D)
329
357
  ], N);
330
- function Ee(e, t) {
358
+ function _e(e, t) {
331
359
  const r = new Uint8Array(t);
332
360
  let n = 0;
333
361
  for (const s of e)
@@ -375,8 +403,8 @@ let O = class {
375
403
  const w = p;
376
404
  try {
377
405
  p = p ? JSON.parse(p) : null;
378
- } catch (_) {
379
- y = !1, p = w, f = _;
406
+ } catch (E) {
407
+ y = !1, p = w, f = E;
380
408
  }
381
409
  }
382
410
  if (o === "blob" && !(p instanceof Blob) && (y = !1, f = new Error("Response is not a Blob object")), y)
@@ -536,17 +564,17 @@ const Fe = 3, ke = 1e3, Ge = (e) => {
536
564
  if (f) {
537
565
  const y = [];
538
566
  p.forEach((w) => {
539
- const _ = c.findIndex((E) => E.config === w);
540
- if (_ >= 0) {
541
- const [E] = c.splice(_, 1);
542
- y.push(E);
567
+ const E = c.findIndex((_) => _.config === w);
568
+ if (E >= 0) {
569
+ const [_] = c.splice(E, 1);
570
+ y.push(_);
543
571
  }
544
572
  }), h(s(p, l)).subscribe({
545
573
  next: (w) => {
546
574
  if (w.type === Y.Response) {
547
- const _ = w.body, E = i(_, p);
575
+ const E = w.body, _ = i(E, p);
548
576
  y.forEach((A) => {
549
- const q = E.find((F) => F.config === A.config);
577
+ const q = _.find((F) => F.config === A.config);
550
578
  if (q) {
551
579
  const F = new $({
552
580
  body: q.result,
package/lib/index.js CHANGED
@@ -121,34 +121,29 @@ let x = class extends J {
121
121
  }), this._pipe = null, R(() => z(this._interceptors, t));
122
122
  }
123
123
  get(t, r) {
124
- return this._request("GET", t, r);
124
+ return this.request("GET", t, r);
125
125
  }
126
126
  post(t, r) {
127
- return this._request("POST", t, r);
127
+ return this.request("POST", t, r);
128
128
  }
129
129
  put(t, r) {
130
- return this._request("PUT", t, r);
130
+ return this.request("PUT", t, r);
131
131
  }
132
132
  delete(t, r) {
133
- return this._request("DELETE", t, r);
133
+ return this.request("DELETE", t, r);
134
134
  }
135
135
  patch(t, r) {
136
- return this._request("PATCH", t, r);
136
+ return this.request("PATCH", t, r);
137
137
  }
138
- getSSE(t, r, n) {
139
- var c, d;
140
- const s = new I(n == null ? void 0 : n.headers), o = new B(n == null ? void 0 : n.params), i = new G(t, r, {
141
- headers: s,
142
- params: o,
143
- withCredentials: (c = n == null ? void 0 : n.withCredentials) != null ? c : !1,
144
- reportProgress: !0,
145
- responseType: (d = n == null ? void 0 : n.responseType) != null ? d : "json",
146
- body: ["GET", "DELETE"].includes(t) || n == null ? void 0 : n.body
147
- });
148
- return j(i).pipe(M((l) => this._runInterceptorsAndImplementation(l)));
149
- }
150
- /** The HTTP request implementations */
151
- async _request(t, r, n) {
138
+ /**
139
+ * The HTTP request implementations. Normally you should use the `get`, `post`, `put`, `delete`,
140
+ * `patch` methods instead.
141
+ * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
142
+ * @param url The URL to send the request to.
143
+ * @param options Optional parameters for the request.
144
+ * @returns A promise that resolves to the HTTP response.
145
+ */
146
+ async request(t, r, n) {
152
147
  var l, h;
153
148
  const s = new I(n == null ? void 0 : n.headers), o = new B(n == null ? void 0 : n.params), i = new G(t, r, {
154
149
  headers: s,
@@ -162,6 +157,39 @@ let x = class extends J {
162
157
  );
163
158
  return await se(c);
164
159
  }
160
+ /**
161
+ * Send an HTTP request. It returns an observable that emits HTTP events. For example, it can be used to
162
+ * send Server-Sent Events (SSE) requests.
163
+ * @deprecated Please use `stream` method instead.
164
+ * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
165
+ * @param url The URL to send the request to.
166
+ * @param _params Optional parameters for the request.
167
+ * @returns An observable of the HTTP event.
168
+ */
169
+ stream(t, r, n) {
170
+ return this.getSSE(t, r, n);
171
+ }
172
+ /**
173
+ * Send a Server-Sent Events (SSE) request. It returns an observable that emits HTTP events. It is the observable
174
+ * pair of the `request` method.
175
+ * @deprecated Please use `stream` method instead.
176
+ * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
177
+ * @param url The URL to send the request to.
178
+ * @param _params Optional parameters for the request.
179
+ * @returns An observable of the HTTP event.
180
+ */
181
+ getSSE(t, r, n) {
182
+ var c, d;
183
+ const s = new I(n == null ? void 0 : n.headers), o = new B(n == null ? void 0 : n.params), i = new G(t, r, {
184
+ headers: s,
185
+ params: o,
186
+ withCredentials: (c = n == null ? void 0 : n.withCredentials) != null ? c : !1,
187
+ reportProgress: !0,
188
+ responseType: (d = n == null ? void 0 : n.responseType) != null ? d : "json",
189
+ body: ["GET", "DELETE"].includes(t) || n == null ? void 0 : n.body
190
+ });
191
+ return j(i).pipe(M((l) => this._runInterceptorsAndImplementation(l)));
192
+ }
165
193
  // eslint-disable-next-line ts/no-explicit-any
166
194
  _runInterceptorsAndImplementation(t) {
167
195
  return this._pipe || (this._pipe = this._interceptors.map((r) => r.interceptor).reduceRight(
@@ -236,7 +264,7 @@ var me = Object.getOwnPropertyDescriptor, ve = (e, t, r, n) => {
236
264
  for (var s = n > 1 ? void 0 : n ? me(t, r) : t, o = e.length - 1, i; o >= 0; o--)
237
265
  (i = e[o]) && (s = i(s) || s);
238
266
  return s;
239
- }, _e = (e, t) => (r, n) => t(r, n, e);
267
+ }, Ee = (e, t) => (r, n) => t(r, n, e);
240
268
  let N = class {
241
269
  constructor(e) {
242
270
  this._logService = e;
@@ -308,7 +336,7 @@ let N = class {
308
336
  l
309
337
  )));
310
338
  }
311
- const a = Ee(n, i);
339
+ const a = _e(n, i);
312
340
  try {
313
341
  const f = (p = t.headers.get("content-type")) != null ? p : "";
314
342
  return Ie(e, a, f);
@@ -325,9 +353,9 @@ let N = class {
325
353
  }
326
354
  };
327
355
  N = ve([
328
- _e(0, D)
356
+ Ee(0, D)
329
357
  ], N);
330
- function Ee(e, t) {
358
+ function _e(e, t) {
331
359
  const r = new Uint8Array(t);
332
360
  let n = 0;
333
361
  for (const s of e)
@@ -375,8 +403,8 @@ let O = class {
375
403
  const w = p;
376
404
  try {
377
405
  p = p ? JSON.parse(p) : null;
378
- } catch (_) {
379
- y = !1, p = w, f = _;
406
+ } catch (E) {
407
+ y = !1, p = w, f = E;
380
408
  }
381
409
  }
382
410
  if (o === "blob" && !(p instanceof Blob) && (y = !1, f = new Error("Response is not a Blob object")), y)
@@ -536,17 +564,17 @@ const Fe = 3, ke = 1e3, Ge = (e) => {
536
564
  if (f) {
537
565
  const y = [];
538
566
  p.forEach((w) => {
539
- const _ = c.findIndex((E) => E.config === w);
540
- if (_ >= 0) {
541
- const [E] = c.splice(_, 1);
542
- y.push(E);
567
+ const E = c.findIndex((_) => _.config === w);
568
+ if (E >= 0) {
569
+ const [_] = c.splice(E, 1);
570
+ y.push(_);
543
571
  }
544
572
  }), h(s(p, l)).subscribe({
545
573
  next: (w) => {
546
574
  if (w.type === Y.Response) {
547
- const _ = w.body, E = i(_, p);
575
+ const E = w.body, _ = i(E, p);
548
576
  y.forEach((A) => {
549
- const q = E.find((F) => F.config === A.config);
577
+ const q = _.find((F) => F.config === A.config);
550
578
  if (q) {
551
579
  const F = new $({
552
580
  body: q.result,
@@ -3,7 +3,7 @@ import { Observable } from 'rxjs';
3
3
  import { HTTPResponseType } from './http';
4
4
  import { HTTPInterceptorFn } from './interceptor';
5
5
  import { HTTPRequestMethod } from './request';
6
- import { HTTPEvent } from './response';
6
+ import { HTTPEvent, HTTPResponse } from './response';
7
7
  import { IHTTPImplementation } from './implementations/implementation';
8
8
  export interface IRequestParams {
9
9
  /** Query params. These params would be append to the url before the request is sent. */
@@ -56,13 +56,39 @@ export declare class HTTPService extends Disposable {
56
56
  * @returns a disposable handler to remove the interceptor
57
57
  */
58
58
  registerHTTPInterceptor(interceptor: IHTTPInterceptor): IDisposable;
59
- get<T>(url: string, params?: IRequestParams): Promise<HTTPEvent<T>>;
60
- post<T>(url: string, params?: IPostRequestParams): Promise<HTTPEvent<T>>;
61
- put<T>(url: string, params?: IPostRequestParams): Promise<HTTPEvent<T>>;
62
- delete<T>(url: string, params?: IRequestParams): Promise<HTTPEvent<T>>;
63
- patch<T>(url: string, params?: IPostRequestParams): Promise<HTTPEvent<T>>;
59
+ get<T>(url: string, params?: IRequestParams): Promise<HTTPResponse<T>>;
60
+ post<T>(url: string, params?: IPostRequestParams): Promise<HTTPResponse<T>>;
61
+ put<T>(url: string, params?: IPostRequestParams): Promise<HTTPResponse<T>>;
62
+ delete<T>(url: string, params?: IRequestParams): Promise<HTTPResponse<T>>;
63
+ patch<T>(url: string, params?: IPostRequestParams): Promise<HTTPResponse<T>>;
64
+ /**
65
+ * The HTTP request implementations. Normally you should use the `get`, `post`, `put`, `delete`,
66
+ * `patch` methods instead.
67
+ * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
68
+ * @param url The URL to send the request to.
69
+ * @param options Optional parameters for the request.
70
+ * @returns A promise that resolves to the HTTP response.
71
+ */
72
+ request<T>(method: HTTPRequestMethod, url: string, options?: IRequestParams): Promise<HTTPResponse<T>>;
73
+ /**
74
+ * Send an HTTP request. It returns an observable that emits HTTP events. For example, it can be used to
75
+ * send Server-Sent Events (SSE) requests.
76
+ * @deprecated Please use `stream` method instead.
77
+ * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
78
+ * @param url The URL to send the request to.
79
+ * @param _params Optional parameters for the request.
80
+ * @returns An observable of the HTTP event.
81
+ */
82
+ stream<T>(method: HTTPRequestMethod, url: string, _params?: IRequestParams): Observable<HTTPEvent<T>>;
83
+ /**
84
+ * Send a Server-Sent Events (SSE) request. It returns an observable that emits HTTP events. It is the observable
85
+ * pair of the `request` method.
86
+ * @deprecated Please use `stream` method instead.
87
+ * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
88
+ * @param url The URL to send the request to.
89
+ * @param _params Optional parameters for the request.
90
+ * @returns An observable of the HTTP event.
91
+ */
64
92
  getSSE<T>(method: HTTPRequestMethod, url: string, _params?: IPostRequestParams): Observable<HTTPEvent<T>>;
65
- /** The HTTP request implementations */
66
- private _request;
67
93
  private _runInterceptorsAndImplementation;
68
94
  }
package/lib/umd/index.js CHANGED
@@ -1,2 +1,2 @@
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 me=Object.defineProperty;var ye=(c,a,m)=>a in c?me(c,a,{enumerable:!0,configurable:!0,writable:!0,value:m}):c[a]=m;var v=(c,a,m)=>ye(c,typeof a!="symbol"?a+"":a,m);var D;const k="application/json";function W(e){return Array.isArray(e)?e.some(n=>n.includes(k)):e.includes(k)}class L{constructor(n){v(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(n){var r,s;const t={};return this._headers.forEach((i,o)=>{t[o]=i.join(",")}),(r=t.accept)!=null||(t.accept="application/json, text/plain, */*"),n instanceof FormData||(s=t["content-type"])!=null||(t["content-type"]="application/json;charset=UTF-8"),t}_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 A=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 V=0;class O{constructor(n,t,r){v(this,"uid",V++);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:k,t=(s=this.requestParams)==null?void 0:s.body;return t instanceof FormData?t:W(n)&&t&&typeof t=="object"?JSON.stringify(t):t?`${t}`:null}getHeadersInit(){var t;return this.headers.toHeadersInit((t=this.requestParams)==null?void 0:t.body)}}var J=Object.getOwnPropertyDescriptor,z=(e,n,t,r)=>{for(var s=r>1?void 0:r?J(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},K=(e,n)=>(t,r)=>n(t,r,e);c.HTTPService=class extends a.Disposable{constructor(t){super();v(this,"_interceptors",[]);v(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 w,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:(w=s==null?void 0:s.withCredentials)!=null?w:!1,reportProgress:!0,responseType:(d=s==null?void 0:s.responseType)!=null?d:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body});return m.of(l).pipe(_.concatMap(f=>this._runInterceptorsAndImplementation(f)))}async _request(t,r,s){var f,p;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:(f=s==null?void 0:s.withCredentials)!=null?f:!1,responseType:(p=s==null?void 0:s.responseType)!=null?p:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body}),w=m.of(l).pipe(_.concatMap(h=>this._runInterceptorsAndImplementation(h)));return await m.firstValueFrom(w)}_runInterceptorsAndImplementation(t){return this._pipe||(this._pipe=this._interceptors.map(r=>r.interceptor).reduceRight((r,s)=>Y(r,s),(r,s)=>s(r))),this._pipe(t,r=>this._http.send(r))}},c.HTTPService=z([K(0,A)],c.HTTPService);function Y(e,n){return(t,r)=>n(t,s=>e(s,r))}const Q=200,Z=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}){v(this,"type",1);v(this,"body");v(this,"headers");v(this,"status");v(this,"statusText");this.body=n,this.headers=t,this.status=r,this.statusText=s}}class j{constructor(n,t,r){v(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}){v(this,"request");v(this,"headers");v(this,"status");v(this,"statusText");v(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 P=Object.getOwnPropertyDescriptor,H=(e,n,t,r)=>{for(var s=r>1?void 0:r?P(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},S=(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 f,p;let s;try{const h=B(n),y=n.getUrlWithParams(),g=fetch(y,{signal:r.signal,...h});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${y} with params ${h}`),s=await g}catch(h){const y=new R({request:n,error:h,status:(f=h.status)!=null?f:0,statusText:(p=h.statusText)!=null?p:"Unknown Error",headers:h.headers});this._logService.error("[FetchHTTPImplementation]: network error",y),t.error(y);return}const i=new L(s.headers),o=s.status,l=s.statusText;let w=null;if(s.body&&(w=await this._readBody(n,s,t)),o>=F.Ok&&o<F.MultipleChoices)t.next(new N({body:w,headers:i,status:o,statusText:l}));else{const h=new R({request:n,error:w,status:o,statusText:l,headers:i});this._logService.error("[FetchHTTPImplementation]: network error",h),t.error(h)}t.complete()}async _readBody(n,t,r){var y,g;const s=[],i=t.body.getReader(),o=t.headers.get("content-length");let l=0;const w=(y=n.requestParams)==null?void 0:y.reportProgress,d=n.responseType;let f,p;for(;;){const{done:b,value:u}=await i.read();if(b)break;s.push(u),l+=u.length,w&&d==="text"&&(f=(f!=null?f:"")+(p!=null?p:p=new TextDecoder).decode(u,{stream:!0}),r.next(new j(o?Number.parseInt(o,10):void 0,l,f)))}const h=C(s,l);try{const b=(g=t.headers.get("content-type"))!=null?g:"";return ee(n,h,b)}catch(b){const u=new R({request:n,error:b,status:t.status,statusText:t.statusText,headers:new L(t.headers)});return this._logService.error("[FetchHTTPImplementation]: network error",u),r.error(u),null}}},c.FetchHTTPImplementation=H([S(0,a.ILogService)],c.FetchHTTPImplementation);function C(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 T=/^\)\]\}',?\n/;function ee(e,n,t){switch(e.responseType){case"json":const r=new TextDecoder().decode(n).replace(T,"");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 te=Object.getOwnPropertyDescriptor,re=(e,n,t,r)=>{for(var s=r>1?void 0:r?te(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},ne=(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),{responseType:o}=n;r.open(n.method,s),n.withCredentials&&(r.withCredentials=!0),i.headers&&Object.entries(i.headers).forEach(([p,h])=>r.setRequestHeader(p,h));const l=()=>{const p=r.statusText||"OK",h=new L(r.getAllResponseHeaders());return new x(h,r.status,p)},w=()=>{const{headers:p,statusText:h,status:y}=l();let g=null,b=null;y!==F.NoContent&&(g=typeof r.response>"u"?r.responseText:r.response);let u=y>=Q&&y<Z;if(o==="json"&&typeof g=="string"){const I=g;try{g=g?JSON.parse(g):null}catch(E){u=!1,g=I,b=E}}if(o==="blob"&&!(g instanceof Blob)&&(u=!1,b=new Error("Response is not a Blob object")),u)t.next(new N({body:g,headers:p,status:y,statusText:h}));else{const I=new R({request:n,error:b,headers:p,status:y,statusText:h});this._logService.error("[XHRHTTPImplementation]: network error",I),t.error(I)}},d=p=>{const h=new R({request:n,error:p,status:r.status||0,statusText:r.statusText||"Unknown Error",headers:l().headers});this._logService.error("[XHRHTTPImplementation]: network error",h),t.error(h)};r.responseType=o||"",r.addEventListener("load",w),r.addEventListener("error",d),r.addEventListener("abort",d),r.addEventListener("timeout",d);const f=n.getBody();return r.send(f),this._logService.debug("[XHRHTTPImplementation]",`sending request to url ${s} with params ${i}`),()=>{r.readyState!==r.DONE&&r.abort(),r.removeEventListener("load",w),r.removeEventListener("error",d),r.removeEventListener("abort",d),r.removeEventListener("timeout",d)}})}},c.XHRHTTPImplementation=re([ne(0,a.ILogService)],c.XHRHTTPImplementation);var se=Object.getOwnPropertyDescriptor,ie=(e,n,t,r)=>{for(var s=r>1?void 0:r?se(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=(D=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],[A,{useClass:t}]],(i=this._config)==null?void 0:i.override))}},v(D,"pluginName","UNIVER_NETWORK_PLUGIN"),D),c.UniverNetworkPlugin=ie([X(1,a.ILogService),X(2,a.Inject(a.Injector))],c.UniverNetworkPlugin);const oe=a.createIdentifier("univer.network.socket.service");class ce 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 ae=3,le=1e3,he=e=>{var r,s;const n=(r=e==null?void 0:e.maxRetryAttempts)!=null?r:ae,t=(s=e==null?void 0:e.delayInterval)!=null?s:le;return(i,o)=>o(i).pipe(_.retry({delay:t,count:n}))},de=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:d=>o.next(d),error:d=>o.error(d),complete:()=>o.complete()}),w=()=>{t.delete(l),a.remove(n,l),r()};return n.push(l),r(),w})},pe=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))))},ue=(e=300)=>{let t=()=>{};return r=>new Promise(s=>{t();const i=setTimeout(()=>{s(!0)},e);t=()=>{clearTimeout(i),s(!1)}})},fe=()=>(e,n)=>n.map(t=>({config:t,result:e})),ge=(e,n={})=>{const{isMatch:t,getParamsFromRequest:r,mergeParamsToRequest:s}=e,{fetchCheck:i=ue(300),distributeResult:o=fe()}=n,l=[],w=d=>d.map(f=>f.config);return(d,f)=>t(d)?new m.Observable(p=>{const h=r(d);l.push({next:g=>p.next(g),error:g=>p.error(g),config:h});const y=w(l);i(d).then(g=>{if(g){const b=[];y.forEach(u=>{const I=l.findIndex(E=>E.config===u);if(I>=0){const[E]=l.splice(I,1);b.push(E)}}),f(s(y,d)).subscribe({next:u=>{if(u.type===U.Response){const I=u.body,E=o(I,y);b.forEach(q=>{const G=E.find(M=>M.config===q.config);if(G){const M=new N({body:G.result,headers:u.headers,status:u.status,statusText:u.statusText});q.next(M)}else q.error("batch error")})}},complete:()=>p.complete(),error:u=>p.error(u)})}})}):f(d)};c.AuthInterceptorFactory=pe,c.HTTPEventType=U,c.HTTPHeaders=L,c.HTTPProgress=j,c.HTTPRequest=O,c.HTTPResponse=N,c.HTTPResponseError=R,c.HTTPStatusCode=F,c.IHTTPImplementation=A,c.ISocketService=oe,c.MergeInterceptorFactory=ge,c.ResponseHeader=x,c.RetryInterceptorFactory=he,c.ThresholdInterceptorFactory=de,c.WebSocketService=ce,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})});
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,E){"use strict";var me=Object.defineProperty;var ye=(c,a,m)=>a in c?me(c,a,{enumerable:!0,configurable:!0,writable:!0,value:m}):c[a]=m;var v=(c,a,m)=>ye(c,typeof a!="symbol"?a+"":a,m);var D;const k="application/json";function W(e){return Array.isArray(e)?e.some(n=>n.includes(k)):e.includes(k)}class L{constructor(n){v(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(n){var r,s;const t={};return this._headers.forEach((i,o)=>{t[o]=i.join(",")}),(r=t.accept)!=null||(t.accept="application/json, text/plain, */*"),n instanceof FormData||(s=t["content-type"])!=null||(t["content-type"]="application/json;charset=UTF-8"),t}_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 A=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 V=0;class O{constructor(n,t,r){v(this,"uid",V++);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:k,t=(s=this.requestParams)==null?void 0:s.body;return t instanceof FormData?t:W(n)&&t&&typeof t=="object"?JSON.stringify(t):t?`${t}`:null}getHeadersInit(){var t;return this.headers.toHeadersInit((t=this.requestParams)==null?void 0:t.body)}}var J=Object.getOwnPropertyDescriptor,z=(e,n,t,r)=>{for(var s=r>1?void 0:r?J(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},K=(e,n)=>(t,r)=>n(t,r,e);c.HTTPService=class extends a.Disposable{constructor(t){super();v(this,"_interceptors",[]);v(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)}async request(t,r,s){var g,p;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:(g=s==null?void 0:s.withCredentials)!=null?g:!1,responseType:(p=s==null?void 0:s.responseType)!=null?p:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body}),w=m.of(l).pipe(E.concatMap(h=>this._runInterceptorsAndImplementation(h)));return await m.firstValueFrom(w)}stream(t,r,s){return this.getSSE(t,r,s)}getSSE(t,r,s){var w,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:(w=s==null?void 0:s.withCredentials)!=null?w:!1,reportProgress:!0,responseType:(d=s==null?void 0:s.responseType)!=null?d:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body});return m.of(l).pipe(E.concatMap(g=>this._runInterceptorsAndImplementation(g)))}_runInterceptorsAndImplementation(t){return this._pipe||(this._pipe=this._interceptors.map(r=>r.interceptor).reduceRight((r,s)=>Y(r,s),(r,s)=>s(r))),this._pipe(t,r=>this._http.send(r))}},c.HTTPService=z([K(0,A)],c.HTTPService);function Y(e,n){return(t,r)=>n(t,s=>e(s,r))}const Q=200,Z=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}){v(this,"type",1);v(this,"body");v(this,"headers");v(this,"status");v(this,"statusText");this.body=n,this.headers=t,this.status=r,this.statusText=s}}class j{constructor(n,t,r){v(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}){v(this,"request");v(this,"headers");v(this,"status");v(this,"statusText");v(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 P=Object.getOwnPropertyDescriptor,H=(e,n,t,r)=>{for(var s=r>1?void 0:r?P(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},S=(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 g,p;let s;try{const h=B(n),y=n.getUrlWithParams(),f=fetch(y,{signal:r.signal,...h});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${y} with params ${h}`),s=await f}catch(h){const y=new R({request:n,error:h,status:(g=h.status)!=null?g:0,statusText:(p=h.statusText)!=null?p:"Unknown Error",headers:h.headers});this._logService.error("[FetchHTTPImplementation]: network error",y),t.error(y);return}const i=new L(s.headers),o=s.status,l=s.statusText;let w=null;if(s.body&&(w=await this._readBody(n,s,t)),o>=F.Ok&&o<F.MultipleChoices)t.next(new N({body:w,headers:i,status:o,statusText:l}));else{const h=new R({request:n,error:w,status:o,statusText:l,headers:i});this._logService.error("[FetchHTTPImplementation]: network error",h),t.error(h)}t.complete()}async _readBody(n,t,r){var y,f;const s=[],i=t.body.getReader(),o=t.headers.get("content-length");let l=0;const w=(y=n.requestParams)==null?void 0:y.reportProgress,d=n.responseType;let g,p;for(;;){const{done:b,value:u}=await i.read();if(b)break;s.push(u),l+=u.length,w&&d==="text"&&(g=(g!=null?g:"")+(p!=null?p:p=new TextDecoder).decode(u,{stream:!0}),r.next(new j(o?Number.parseInt(o,10):void 0,l,g)))}const h=C(s,l);try{const b=(f=t.headers.get("content-type"))!=null?f:"";return ee(n,h,b)}catch(b){const u=new R({request:n,error:b,status:t.status,statusText:t.statusText,headers:new L(t.headers)});return this._logService.error("[FetchHTTPImplementation]: network error",u),r.error(u),null}}},c.FetchHTTPImplementation=H([S(0,a.ILogService)],c.FetchHTTPImplementation);function C(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 T=/^\)\]\}',?\n/;function ee(e,n,t){switch(e.responseType){case"json":const r=new TextDecoder().decode(n).replace(T,"");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 te=Object.getOwnPropertyDescriptor,re=(e,n,t,r)=>{for(var s=r>1?void 0:r?te(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},ne=(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),{responseType:o}=n;r.open(n.method,s),n.withCredentials&&(r.withCredentials=!0),i.headers&&Object.entries(i.headers).forEach(([p,h])=>r.setRequestHeader(p,h));const l=()=>{const p=r.statusText||"OK",h=new L(r.getAllResponseHeaders());return new x(h,r.status,p)},w=()=>{const{headers:p,statusText:h,status:y}=l();let f=null,b=null;y!==F.NoContent&&(f=typeof r.response>"u"?r.responseText:r.response);let u=y>=Q&&y<Z;if(o==="json"&&typeof f=="string"){const I=f;try{f=f?JSON.parse(f):null}catch(_){u=!1,f=I,b=_}}if(o==="blob"&&!(f instanceof Blob)&&(u=!1,b=new Error("Response is not a Blob object")),u)t.next(new N({body:f,headers:p,status:y,statusText:h}));else{const I=new R({request:n,error:b,headers:p,status:y,statusText:h});this._logService.error("[XHRHTTPImplementation]: network error",I),t.error(I)}},d=p=>{const h=new R({request:n,error:p,status:r.status||0,statusText:r.statusText||"Unknown Error",headers:l().headers});this._logService.error("[XHRHTTPImplementation]: network error",h),t.error(h)};r.responseType=o||"",r.addEventListener("load",w),r.addEventListener("error",d),r.addEventListener("abort",d),r.addEventListener("timeout",d);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",w),r.removeEventListener("error",d),r.removeEventListener("abort",d),r.removeEventListener("timeout",d)}})}},c.XHRHTTPImplementation=re([ne(0,a.ILogService)],c.XHRHTTPImplementation);var se=Object.getOwnPropertyDescriptor,ie=(e,n,t,r)=>{for(var s=r>1?void 0:r?se(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=(D=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],[A,{useClass:t}]],(i=this._config)==null?void 0:i.override))}},v(D,"pluginName","UNIVER_NETWORK_PLUGIN"),D),c.UniverNetworkPlugin=ie([X(1,a.ILogService),X(2,a.Inject(a.Injector))],c.UniverNetworkPlugin);const oe=a.createIdentifier("univer.network.socket.service");class ce 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(E.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(E.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(E.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(E.share())}}catch(t){return console.error(t),null}}}const ae=3,le=1e3,he=e=>{var r,s;const n=(r=e==null?void 0:e.maxRetryAttempts)!=null?r:ae,t=(s=e==null?void 0:e.delayInterval)!=null?s:le;return(i,o)=>o(i).pipe(E.retry({delay:t,count:n}))},de=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:d=>o.next(d),error:d=>o.error(d),complete:()=>o.complete()}),w=()=>{t.delete(l),a.remove(n,l),r()};return n.push(l),r(),w})},pe=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))))},ue=(e=300)=>{let t=()=>{};return r=>new Promise(s=>{t();const i=setTimeout(()=>{s(!0)},e);t=()=>{clearTimeout(i),s(!1)}})},ge=()=>(e,n)=>n.map(t=>({config:t,result:e})),fe=(e,n={})=>{const{isMatch:t,getParamsFromRequest:r,mergeParamsToRequest:s}=e,{fetchCheck:i=ue(300),distributeResult:o=ge()}=n,l=[],w=d=>d.map(g=>g.config);return(d,g)=>t(d)?new m.Observable(p=>{const h=r(d);l.push({next:f=>p.next(f),error:f=>p.error(f),config:h});const y=w(l);i(d).then(f=>{if(f){const b=[];y.forEach(u=>{const I=l.findIndex(_=>_.config===u);if(I>=0){const[_]=l.splice(I,1);b.push(_)}}),g(s(y,d)).subscribe({next:u=>{if(u.type===U.Response){const I=u.body,_=o(I,y);b.forEach(q=>{const G=_.find(M=>M.config===q.config);if(G){const M=new N({body:G.result,headers:u.headers,status:u.status,statusText:u.statusText});q.next(M)}else q.error("batch error")})}},complete:()=>p.complete(),error:u=>p.error(u)})}})}):g(d)};c.AuthInterceptorFactory=pe,c.HTTPEventType=U,c.HTTPHeaders=L,c.HTTPProgress=j,c.HTTPRequest=O,c.HTTPResponse=N,c.HTTPResponseError=R,c.HTTPStatusCode=F,c.IHTTPImplementation=A,c.ISocketService=oe,c.MergeInterceptorFactory=fe,c.ResponseHeader=x,c.RetryInterceptorFactory=he,c.ThresholdInterceptorFactory=de,c.WebSocketService=ce,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.8.0-nightly.202506091607",
3
+ "version": "0.8.0-nightly.202506111607",
4
4
  "private": false,
5
5
  "author": "DreamNum <developer@univer.ai>",
6
6
  "license": "Apache-2.0",
@@ -57,7 +57,7 @@
57
57
  "rxjs": ">=7.0.0"
58
58
  },
59
59
  "dependencies": {
60
- "@univerjs/core": "0.8.0-nightly.202506091607"
60
+ "@univerjs/core": "0.8.0-nightly.202506111607"
61
61
  },
62
62
  "devDependencies": {
63
63
  "rxjs": "^7.8.2",