@univerjs/network 0.16.1 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cjs/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var W=Object.defineProperty;var V=(e,n,r)=>n in e?W(e,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[n]=r;var y=(e,n,r)=>V(e,typeof n!="symbol"?n+"":n,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("@univerjs/core"),w=require("rxjs"),_=require("rxjs/operators"),J="network.config",$={},A="application/json";function K(e){return Array.isArray(e)?e.some(n=>n.includes(A)):e.includes(A)}class E{constructor(n){y(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 D=h.createIdentifier("network.http-implementation");class j{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 z=0;class U{constructor(n,r,t){y(this,"uid",z++);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:K(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 Y=Object.getOwnPropertyDescriptor,P=(e,n,r,t)=>{for(var s=t>1?void 0:t?Y(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},Q=(e,n)=>(r,t)=>n(r,t,e);exports.HTTPService=class extends h.Disposable{constructor(r){super();y(this,"_interceptors",[]);y(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,h.toDisposable(()=>h.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,p;const o=new E(s==null?void 0:s.headers),i=new j(s==null?void 0:s.params),c=new U(r,t,{headers:o,params:i,withCredentials:(u=s==null?void 0:s.withCredentials)!=null?u:!1,responseType:(p=s==null?void 0:s.responseType)!=null?p:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body}),m=w.of(c).pipe(_.concatMap(a=>this._runInterceptorsAndImplementation(a)));return await w.firstValueFrom(m)}stream(r,t,s){return this.getSSE(r,t,s)}getSSE(r,t,s){var m,l;const o=new E(s==null?void 0:s.headers),i=new j(s==null?void 0:s.params),c=new U(r,t,{headers:o,params:i,withCredentials:(m=s==null?void 0:s.withCredentials)!=null?m:!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)))}_runInterceptorsAndImplementation(r){return this._pipe||(this._pipe=this._interceptors.map(t=>t.interceptor).reduceRight((t,s)=>Z(t,s),(t,s)=>s(t))),this._pipe(r,t=>this._http.send(t))}};exports.HTTPService=P([Q(0,D)],exports.HTTPService);function Z(e,n){return(r,t)=>n(r,s=>e(s,t))}const H=200,S=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||{}),q=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(q||{});class L{constructor({body:n,headers:r,status:t,statusText:s}){y(this,"type",1);y(this,"body");y(this,"headers");y(this,"status");y(this,"statusText");this.body=n,this.headers=r,this.status=t,this.statusText=s}}class B{constructor(n,r,t){y(this,"type",0);this.total=n,this.loaded=r,this.partialText=t}}class G{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}){y(this,"request");y(this,"headers");y(this,"status");y(this,"statusText");y(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 C=Object.getOwnPropertyDescriptor,T=(e,n,r,t)=>{for(var s=t>1?void 0:t?C(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},ee=(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,p;let s;try{const a=X(n),f=n.getUrlWithParams(),g=fetch(f,{signal:t.signal,...a});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${f} with params ${a}`),s=await g}catch(a){const f=new I({request:n,error:a,status:(u=a.status)!=null?u:0,statusText:(p=a.statusText)!=null?p:"Unknown Error",headers:a.headers});this._logService.error("[FetchHTTPImplementation]: network error",f),r.error(f);return}const o=new E(s.headers),i=s.status,c=s.statusText;let m=null;if(s.body&&(m=await this._readBody(n,s,r)),i>=x.Ok&&i<x.MultipleChoices)r.next(new L({body:m,headers:o,status:i,statusText:c}));else{const a=new I({request:n,error:m,status:i,statusText:c,headers:o});this._logService.error("[FetchHTTPImplementation]: network error",a),r.error(a)}r.complete()}async _readBody(n,r,t){var f,g;const s=[],o=r.body.getReader(),i=r.headers.get("content-length");let c=0;const m=(f=n.requestParams)==null?void 0:f.reportProgress,l=n.responseType;let u,p;for(;;){const{done:v,value:d}=await o.read();if(v)break;s.push(d),c+=d.length,m&&l==="text"&&(u=(u!=null?u:"")+(p!=null?p:p=new TextDecoder).decode(d,{stream:!0}),t.next(new B(i?Number.parseInt(i,10):void 0,c,u)))}const a=re(s,c);try{const v=(g=r.headers.get("content-type"))!=null?g:"";return ne(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=T([ee(0,h.ILogService)],exports.FetchHTTPImplementation);function re(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 te=/^\)\]\}',?\n/;function ne(e,n,r){switch(e.responseType){case"json":const t=new TextDecoder().decode(n).replace(te,"");return t===""?null:JSON.parse(t);case"text":return new TextDecoder().decode(n);case"blob":return new Blob([n.buffer],{type:r});case"arraybuffer":return n.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}var se=Object.getOwnPropertyDescriptor,oe=(e,n,r,t)=>{for(var s=t>1?void 0:t?se(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},ie=(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(([p,a])=>t.setRequestHeader(p,a));const c=()=>{const p=t.statusText||"OK",a=new E(t.getAllResponseHeaders());return new G(a,t.status,p)},m=()=>{const{headers:p,statusText:a,status:f}=c();let g=null,v=null;f!==x.NoContent&&(g=typeof t.response>"u"?t.responseText:t.response);let d=f>=H&&f<S;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:p,status:f,statusText:a}));else{const b=new I({request:n,error:v,headers:p,status:f,statusText:a});this._logService.error("[XHRHTTPImplementation]: network error",b),r.error(b)}},l=p=>{const a=new I({request:n,error:p,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",m),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",m),t.removeEventListener("error",l),t.removeEventListener("abort",l),t.removeEventListener("timeout",l)}})}};exports.XHRHTTPImplementation=oe([ie(0,h.ILogService)],exports.XHRHTTPImplementation);var ce=Object.getOwnPropertyDescriptor,ae=(e,n,r,t)=>{for(var s=t>1?void 0:t?ce(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},k=(e,n)=>(r,t)=>n(r,t,e),O;exports.UniverNetworkPlugin=(O=class extends h.Plugin{constructor(n=$,r,t,s){super(),this._config=n,this._logger=r,this._injector=t,this._configService=s;const{...o}=h.merge({},$,this._config);this._configService.setConfig(J,o)}onStarting(){var t,s,o;if(this._injector.get(exports.HTTPService,h.Quantity.OPTIONAL,h.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;h.registerDependencies(this._injector,h.mergeOverrideWithDependencies([[exports.HTTPService],[D,{useClass:r}]],(o=this._config)==null?void 0:o.override))}},y(O,"pluginName","UNIVER_NETWORK_PLUGIN"),O);exports.UniverNetworkPlugin=ae([k(1,h.ILogService),k(2,h.Inject(h.Injector)),k(3,h.IConfigService)],exports.UniverNetworkPlugin);const le=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))))},he=(e=300)=>{let r=()=>{};return t=>new Promise(s=>{r();const o=setTimeout(()=>{s(!0)},e);r=()=>{clearTimeout(o),s(!1)}})},pe=()=>(e,n)=>n.map(r=>({config:r,result:e})),de=(e,n={})=>{const{isMatch:r,getParamsFromRequest:t,mergeParamsToRequest:s}=e,{fetchCheck:o=he(300),distributeResult:i=pe()}=n,c=[],m=l=>l.map(u=>u.config);return(l,u)=>r(l)?new w.Observable(p=>{const a=t(l);c.push({next:g=>p.next(g),error:g=>p.error(g),config:a});const f=m(c);o(l).then(g=>{if(g){const v=[];f.forEach(d=>{const b=c.findIndex(R=>R.config===d);if(b>=0){const[R]=c.splice(b,1);v.push(R)}}),u(s(f,l)).subscribe({next:d=>{if(d.type===q.Response){const b=d.body,R=i(b,f);v.forEach(F=>{const M=R.find(N=>N.config===F.config);if(M){const N=new L({body:M.result,headers:d.headers,status:d.status,statusText:d.statusText});F.next(N)}else F.error("batch error")})}},complete:()=>p.complete(),error:d=>p.error(d)})}})}):u(l)},ue=3,ge=1e3,fe=e=>{var t,s;const n=(t=e==null?void 0:e.maxRetryAttempts)!=null?t:ue,r=(s=e==null?void 0:e.delayInterval)!=null?s:ge;return(o,i)=>i(o).pipe(_.retry({delay:r,count:n}))},me=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()}),m=()=>{r.delete(c),h.remove(n,c),t()};return n.push(c),t(),m})},ye=h.createIdentifier("univer.network.socket.service");class we extends h.Disposable{createSocket(n){try{const r=new WebSocket(n),t=new h.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(h.toDisposable(()=>r.removeEventListener("open",i)))}).pipe(_.share()),close$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("close",i),t.add(h.toDisposable(()=>r.removeEventListener("close",i)))}).pipe(_.share()),error$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("error",i),t.add(h.toDisposable(()=>r.removeEventListener("error",i)))}).pipe(_.share()),message$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("message",i),t.add(h.toDisposable(()=>r.removeEventListener("message",i)))}).pipe(_.share())}}catch(r){return console.error(r),null}}}exports.AuthInterceptorFactory=le;exports.HTTPEventType=q;exports.HTTPHeaders=E;exports.HTTPProgress=B;exports.HTTPRequest=U;exports.HTTPResponse=L;exports.HTTPResponseError=I;exports.HTTPStatusCode=x;exports.IHTTPImplementation=D;exports.ISocketService=ye;exports.MergeInterceptorFactory=de;exports.ResponseHeader=G;exports.RetryInterceptorFactory=fe;exports.ThresholdInterceptorFactory=me;exports.WebSocketService=we;
1
+ "use strict";var V=Object.defineProperty;var J=(e,n,r)=>n in e?V(e,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[n]=r;var f=(e,n,r)=>J(e,typeof n!="symbol"?n+"":n,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("@univerjs/core"),w=require("rxjs"),_=require("rxjs/operators"),K="@univerjs/network",z="0.17.0",M={name:K,version:z},Y="network.config",$={},A="application/json";function P(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 D=h.createIdentifier("network.http-implementation");class B{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 Q=0;class U{constructor(n,r,t){f(this,"uid",Q++);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:P(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,H=(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},S=(e,n)=>(r,t)=>n(r,t,e);exports.HTTPService=class extends h.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,h.toDisposable(()=>h.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,p;const o=new E(s==null?void 0:s.headers),i=new B(s==null?void 0:s.params),c=new U(r,t,{headers:o,params:i,withCredentials:(u=s==null?void 0:s.withCredentials)!=null?u:!1,responseType:(p=s==null?void 0:s.responseType)!=null?p:"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)}stream(r,t,s){return this.getSSE(r,t,s)}getSSE(r,t,s){var y,l;const o=new E(s==null?void 0:s.headers),i=new B(s==null?void 0:s.params),c=new U(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)))}_runInterceptorsAndImplementation(r){return this._pipe||(this._pipe=this._interceptors.map(t=>t.interceptor).reduceRight((t,s)=>C(t,s),(t,s)=>s(t))),this._pipe(r,t=>this._http.send(t))}};exports.HTTPService=H([S(0,D)],exports.HTTPService);function C(e,n){return(r,t)=>n(r,s=>e(s,t))}const T=200,ee=300;var L=(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))(L||{}),q=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(q||{});class F{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 G{constructor(n,r,t){f(this,"type",0);this.total=n,this.loaded=r,this.partialText=t}}class X{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 W(e){return{method:e.method,headers:e.getHeadersInit(),body:e.getBody(),credentials:e.withCredentials?"include":void 0}}var re=Object.getOwnPropertyDescriptor,te=(e,n,r,t)=>{for(var s=t>1?void 0:t?re(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},ne=(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,p;let s;try{const a=W(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:(p=a.statusText)!=null?p:"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>=L.Ok&&i<L.MultipleChoices)r.next(new F({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,p;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:"")+(p!=null?p:p=new TextDecoder).decode(d,{stream:!0}),t.next(new G(i?Number.parseInt(i,10):void 0,c,u)))}const a=se(s,c);try{const v=(g=r.headers.get("content-type"))!=null?g:"";return ie(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=te([ne(0,h.ILogService)],exports.FetchHTTPImplementation);function se(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 oe=/^\)\]\}',?\n/;function ie(e,n,r){switch(e.responseType){case"json":const t=new TextDecoder().decode(n).replace(oe,"");return t===""?null:JSON.parse(t);case"text":return new TextDecoder().decode(n);case"blob":return new Blob([n.buffer],{type:r});case"arraybuffer":return n.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}var ce=Object.getOwnPropertyDescriptor,ae=(e,n,r,t)=>{for(var s=t>1?void 0:t?ce(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},le=(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=W(n),{responseType:i}=n;t.open(n.method,s),n.withCredentials&&(t.withCredentials=!0),o.headers&&Object.entries(o.headers).forEach(([p,a])=>t.setRequestHeader(p,a));const c=()=>{const p=t.statusText||"OK",a=new E(t.getAllResponseHeaders());return new X(a,t.status,p)},y=()=>{const{headers:p,statusText:a,status:m}=c();let g=null,v=null;m!==L.NoContent&&(g=typeof t.response>"u"?t.responseText:t.response);let d=m>=T&&m<ee;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 F({body:g,headers:p,status:m,statusText:a}));else{const b=new I({request:n,error:v,headers:p,status:m,statusText:a});this._logService.error("[XHRHTTPImplementation]: network error",b),r.error(b)}},l=p=>{const a=new I({request:n,error:p,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=ae([le(0,h.ILogService)],exports.XHRHTTPImplementation);var he=Object.getOwnPropertyDescriptor,pe=(e,n,r,t)=>{for(var s=t>1?void 0:t?he(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},O=(e,n)=>(r,t)=>n(r,t,e),x;exports.UniverNetworkPlugin=(x=class extends h.Plugin{constructor(n=$,r,t,s){super(),this._config=n,this._logger=r,this._injector=t,this._configService=s;const{...o}=h.merge({},$,this._config);this._configService.setConfig(Y,o)}onStarting(){var t,s,o;if(this._injector.get(exports.HTTPService,h.Quantity.OPTIONAL,h.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;h.registerDependencies(this._injector,h.mergeOverrideWithDependencies([[exports.HTTPService],[D,{useClass:r}]],(o=this._config)==null?void 0:o.override))}},f(x,"pluginName","UNIVER_NETWORK_PLUGIN"),f(x,"packageName",M.name),f(x,"version",M.version),x);exports.UniverNetworkPlugin=pe([O(1,h.ILogService),O(2,h.Inject(h.Injector)),O(3,h.IConfigService)],exports.UniverNetworkPlugin);const de=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))))},ue=(e=300)=>{let r=()=>{};return t=>new Promise(s=>{r();const o=setTimeout(()=>{s(!0)},e);r=()=>{clearTimeout(o),s(!1)}})},ge=()=>(e,n)=>n.map(r=>({config:r,result:e})),fe=(e,n={})=>{const{isMatch:r,getParamsFromRequest:t,mergeParamsToRequest:s}=e,{fetchCheck:o=ue(300),distributeResult:i=ge()}=n,c=[],y=l=>l.map(u=>u.config);return(l,u)=>r(l)?new w.Observable(p=>{const a=t(l);c.push({next:g=>p.next(g),error:g=>p.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===q.Response){const b=d.body,R=i(b,m);v.forEach(N=>{const j=R.find(k=>k.config===N.config);if(j){const k=new F({body:j.result,headers:d.headers,status:d.status,statusText:d.statusText});N.next(k)}else N.error("batch error")})}},complete:()=>p.complete(),error:d=>p.error(d)})}})}):u(l)},me=3,ye=1e3,we=e=>{var t,s;const n=(t=e==null?void 0:e.maxRetryAttempts)!=null?t:me,r=(s=e==null?void 0:e.delayInterval)!=null?s:ye;return(o,i)=>i(o).pipe(_.retry({delay:r,count:n}))},ve=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),h.remove(n,c),t()};return n.push(c),t(),y})},be=h.createIdentifier("univer.network.socket.service");class Ie extends h.Disposable{createSocket(n){try{const r=new WebSocket(n),t=new h.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(h.toDisposable(()=>r.removeEventListener("open",i)))}).pipe(_.share()),close$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("close",i),t.add(h.toDisposable(()=>r.removeEventListener("close",i)))}).pipe(_.share()),error$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("error",i),t.add(h.toDisposable(()=>r.removeEventListener("error",i)))}).pipe(_.share()),message$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("message",i),t.add(h.toDisposable(()=>r.removeEventListener("message",i)))}).pipe(_.share())}}catch(r){return console.error(r),null}}}exports.AuthInterceptorFactory=de;exports.HTTPEventType=q;exports.HTTPHeaders=E;exports.HTTPProgress=G;exports.HTTPRequest=U;exports.HTTPResponse=F;exports.HTTPResponseError=I;exports.HTTPStatusCode=L;exports.IHTTPImplementation=D;exports.ISocketService=be;exports.MergeInterceptorFactory=fe;exports.ResponseHeader=X;exports.RetryInterceptorFactory=we;exports.ThresholdInterceptorFactory=ve;exports.WebSocketService=Ie;