@univerjs/network 0.6.9 → 0.6.10-alpha.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 G=Object.defineProperty;var W=(e,t,r)=>t in e?G(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var m=(e,t,r)=>W(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("@univerjs/core"),f=require("rxjs"),_=require("rxjs/operators"),q="application/json";class E{constructor(t){m(this,"_headers",new Map);typeof t=="string"?this._handleHeadersString(t):t instanceof Headers?this._handleHeaders(t):t&&this._handleHeadersConstructorProps(t)}forEach(t){this._headers.forEach((r,n)=>t(n,r))}has(t){return!!this._headers.has(t.toLowerCase())}get(t){const r=t.toLowerCase();return this._headers.has(r)?this._headers.get(r):null}set(t,r){this._setHeader(t,r)}toHeadersInit(){var r,n;const t={};return this._headers.forEach((s,o)=>{t[o]=s.join(",")}),(r=t.accept)!=null||(t.accept="application/json, text/plain, */*"),(n=t["content-type"])!=null||(t["content-type"]="application/json;charset=UTF-8"),t}_setHeader(t,r){const n=t.toLowerCase();this._headers.has(n)?this._headers.get(n).push(r.toString()):this._headers.set(n,[r.toString()])}_handleHeadersString(t){t.split(`
2
- `).forEach(r=>{const[n,s]=r.split(":");n&&s&&this._setHeader(n,s)})}_handleHeadersConstructorProps(t){Object.entries(t).forEach(([r,n])=>this._setHeader(r,n))}_handleHeaders(t){t.forEach((r,n)=>this._setHeader(n,r))}}const A=p.createIdentifier("network.http-implementation");class M{constructor(t){this.params=t}toString(){return this.params?Object.keys(this.params).map(t=>{const r=this.params[t];return Array.isArray(r)?r.map(n=>`${t}=${n}`).join("&"):`${t}=${r}`}).join("&"):""}}let V=0;class O{constructor(t,r,n){m(this,"uid",V++);this.method=t,this.url=r,this.requestParams=n}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var r,n;const t=(n=(r=this.requestParams)==null?void 0:r.params)==null?void 0:n.toString();return t?`${this.url}${this.url.includes("?")?"&":"?"}${t}`:this.url}getBody(){var n,s;const t=(n=this.headers.get("Content-Type"))!=null?n:q,r=(s=this.requestParams)==null?void 0:s.body;return t===q&&r&&typeof r=="object"?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}var z=Object.getOwnPropertyDescriptor,J=(e,t,r,n)=>{for(var s=n>1?void 0:n?z(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},K=(e,t)=>(r,n)=>t(r,n,e);exports.HTTPService=class extends p.Disposable{constructor(r){super();m(this,"_interceptors",[]);m(this,"_pipe");this._http=r}registerHTTPInterceptor(r){if(this._interceptors.indexOf(r)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(r),this._interceptors=this._interceptors.sort((n,s)=>{var o,i;return((o=n.priority)!=null?o:0)-((i=s.priority)!=null?i:0)}),this._pipe=null,p.toDisposable(()=>p.remove(this._interceptors,r))}get(r,n){return this._request("GET",r,n)}post(r,n){return this._request("POST",r,n)}put(r,n){return this._request("PUT",r,n)}delete(r,n){return this._request("DELETE",r,n)}patch(r,n){return this._request("PATCH",r,n)}getSSE(r,n,s){var d,u;const o=new E(s==null?void 0:s.headers),i=new M(s==null?void 0:s.params),c=new O(r,n,{headers:o,params:i,withCredentials:(d=s==null?void 0:s.withCredentials)!=null?d:!1,reportProgress:!0,responseType:(u=s==null?void 0:s.responseType)!=null?u:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body});return f.of(c).pipe(_.concatMap(a=>this._runInterceptorsAndImplementation(a)))}async _request(r,n,s){var a,l;const o=new E(s==null?void 0:s.headers),i=new M(s==null?void 0:s.params),c=new O(r,n,{headers:o,params:i,withCredentials:(a=s==null?void 0:s.withCredentials)!=null?a:!1,responseType:(l=s==null?void 0:s.responseType)!=null?l:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body}),d=f.of(c).pipe(_.concatMap(h=>this._runInterceptorsAndImplementation(h)));return await f.firstValueFrom(d)}_runInterceptorsAndImplementation(r){return this._pipe||(this._pipe=this._interceptors.map(n=>n.interceptor).reduceRight((n,s)=>Y(n,s),(n,s)=>s(n))),this._pipe(r,n=>this._http.send(n))}};exports.HTTPService=J([K(0,A)],exports.HTTPService);function Y(e,t){return(r,n)=>t(r,s=>e(s,n))}const Q=200,Z=300;var x=(e=>(e[e.Continue=100]="Continue",e[e.SwitchingProtocols=101]="SwitchingProtocols",e[e.Processing=102]="Processing",e[e.EarlyHints=103]="EarlyHints",e[e.Ok=200]="Ok",e[e.Created=201]="Created",e[e.Accepted=202]="Accepted",e[e.NonAuthoritativeInformation=203]="NonAuthoritativeInformation",e[e.NoContent=204]="NoContent",e[e.ResetContent=205]="ResetContent",e[e.PartialContent=206]="PartialContent",e[e.MultiStatus=207]="MultiStatus",e[e.AlreadyReported=208]="AlreadyReported",e[e.ImUsed=226]="ImUsed",e[e.MultipleChoices=300]="MultipleChoices",e[e.MovedPermanently=301]="MovedPermanently",e[e.Found=302]="Found",e[e.SeeOther=303]="SeeOther",e[e.NotModified=304]="NotModified",e[e.UseProxy=305]="UseProxy",e[e.Unused=306]="Unused",e[e.TemporaryRedirect=307]="TemporaryRedirect",e[e.PermanentRedirect=308]="PermanentRedirect",e[e.BadRequest=400]="BadRequest",e[e.Unauthorized=401]="Unauthorized",e[e.PaymentRequired=402]="PaymentRequired",e[e.Forbidden=403]="Forbidden",e[e.NotFound=404]="NotFound",e[e.MethodNotAllowed=405]="MethodNotAllowed",e[e.NotAcceptable=406]="NotAcceptable",e[e.ProxyAuthenticationRequired=407]="ProxyAuthenticationRequired",e[e.RequestTimeout=408]="RequestTimeout",e[e.Conflict=409]="Conflict",e[e.Gone=410]="Gone",e[e.LengthRequired=411]="LengthRequired",e[e.PreconditionFailed=412]="PreconditionFailed",e[e.PayloadTooLarge=413]="PayloadTooLarge",e[e.UriTooLong=414]="UriTooLong",e[e.UnsupportedMediaType=415]="UnsupportedMediaType",e[e.RangeNotSatisfiable=416]="RangeNotSatisfiable",e[e.ExpectationFailed=417]="ExpectationFailed",e[e.ImATeapot=418]="ImATeapot",e[e.MisdirectedRequest=421]="MisdirectedRequest",e[e.UnprocessableEntity=422]="UnprocessableEntity",e[e.Locked=423]="Locked",e[e.FailedDependency=424]="FailedDependency",e[e.TooEarly=425]="TooEarly",e[e.UpgradeRequired=426]="UpgradeRequired",e[e.PreconditionRequired=428]="PreconditionRequired",e[e.TooManyRequests=429]="TooManyRequests",e[e.RequestHeaderFieldsTooLarge=431]="RequestHeaderFieldsTooLarge",e[e.UnavailableForLegalReasons=451]="UnavailableForLegalReasons",e[e.InternalServerError=500]="InternalServerError",e[e.NotImplemented=501]="NotImplemented",e[e.BadGateway=502]="BadGateway",e[e.ServiceUnavailable=503]="ServiceUnavailable",e[e.GatewayTimeout=504]="GatewayTimeout",e[e.HttpVersionNotSupported=505]="HttpVersionNotSupported",e[e.VariantAlsoNegotiates=506]="VariantAlsoNegotiates",e[e.InsufficientStorage=507]="InsufficientStorage",e[e.LoopDetected=508]="LoopDetected",e[e.NotExtended=510]="NotExtended",e[e.NetworkAuthenticationRequired=511]="NetworkAuthenticationRequired",e))(x||{}),U=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(U||{});class L{constructor({body:t,headers:r,status:n,statusText:s}){m(this,"type",1);m(this,"body");m(this,"headers");m(this,"status");m(this,"statusText");this.body=t,this.headers=r,this.status=n,this.statusText=s}}class j{constructor(t,r,n){m(this,"type",0);this.total=t,this.loaded=r,this.partialText=n}}class B{constructor(t,r,n){this.headers=t,this.status=r,this.statusText=n}}class b{constructor({request:t,headers:r,status:n,statusText:s,error:o}){m(this,"request");m(this,"headers");m(this,"status");m(this,"statusText");m(this,"error");this.request=t,this.headers=r,this.status=n,this.statusText=s,this.error=o}}function X(e){return{method:e.method,headers:e.getHeadersInit(),body:e.getBody(),credentials:e.withCredentials?"include":void 0}}var P=Object.getOwnPropertyDescriptor,H=(e,t,r,n)=>{for(var s=n>1?void 0:n?P(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},S=(e,t)=>(r,n)=>t(r,n,e);exports.FetchHTTPImplementation=class{constructor(t){this._logService=t}send(t){return new f.Observable(r=>{const n=new AbortController;return this._send(t,r,n).catch(s=>{r.error(new b({error:s,request:t}))}),()=>n.abort()})}async _send(t,r,n){var a,l;let s;try{const h=X(t),w=t.getUrlWithParams(),y=fetch(w,{signal:n.signal,...h});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${w} with params ${h}`),s=await y}catch(h){const w=new b({request:t,error:h,status:(a=h.status)!=null?a:0,statusText:(l=h.statusText)!=null?l:"Unknown Error",headers:h.headers});this._logService.error("[FetchHTTPImplementation]: network error",w),r.error(w);return}const o=new E(s.headers),i=s.status,c=s.statusText;let d=null;if(s.body&&(d=await this._readBody(t,s,r)),i>=x.Ok&&i<x.MultipleChoices)r.next(new L({body:d,headers:o,status:i,statusText:c}));else{const h=new b({request:t,error:d,status:i,statusText:c,headers:o});this._logService.error("[FetchHTTPImplementation]: network error",h),r.error(h)}r.complete()}async _readBody(t,r,n){var w,y;const s=[],o=r.body.getReader(),i=r.headers.get("content-length");let c=0;const d=(w=t.requestParams)==null?void 0:w.reportProgress,u=t.responseType;let a,l;for(;;){const{done:v,value:g}=await o.read();if(v)break;s.push(g),c+=g.length,d&&u==="text"&&(a=(a!=null?a:"")+(l!=null?l:l=new TextDecoder).decode(g,{stream:!0}),n.next(new j(i?Number.parseInt(i,10):void 0,c,a)))}const h=C(s,c);try{const v=(y=r.headers.get("content-type"))!=null?y:"";return ee(t,h,v)}catch(v){const g=new b({request:t,error:v,status:r.status,statusText:r.statusText,headers:new E(r.headers)});return this._logService.error("[FetchHTTPImplementation]: network error",g),n.error(g),null}}};exports.FetchHTTPImplementation=H([S(0,p.ILogService)],exports.FetchHTTPImplementation);function C(e,t){const r=new Uint8Array(t);let n=0;for(const s of e)r.set(s,n),n+=s.length;return r}const T=/^\)\]\}',?\n/;function ee(e,t,r){switch(e.responseType){case"json":const n=new TextDecoder().decode(t).replace(T,"");return n===""?null:JSON.parse(n);case"text":return new TextDecoder().decode(t);case"blob":return new Blob([t],{type:r});case"arraybuffer":return t.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}var re=Object.getOwnPropertyDescriptor,te=(e,t,r,n)=>{for(var s=n>1?void 0:n?re(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},ne=(e,t)=>(r,n)=>t(r,n,e);exports.XHRHTTPImplementation=class{constructor(t){this._logService=t}send(t){return new f.Observable(r=>{const n=new XMLHttpRequest,s=t.getUrlWithParams(),o=X(t);n.open(t.method,s),t.withCredentials&&(n.withCredentials=!0),o.headers&&Object.entries(o.headers).forEach(([a,l])=>n.setRequestHeader(a,l));const i=()=>{const a=n.statusText||"OK",l=new E(n.getAllResponseHeaders());return new B(l,n.status,a)},c=()=>{const{headers:a,statusText:l,status:h}=i(),{responseType:w}=t;let y=null,v=null;h!==x.NoContent&&(y=typeof n.response>"u"?n.responseText:n.response);let g=h>=Q&&h<Z;if(w==="json"&&typeof y=="string"){const I=y;try{y=y?JSON.parse(y):null}catch(R){g=!1,y=I,v=R}}if(g)r.next(new L({body:y,headers:a,status:h,statusText:l}));else{const I=new b({request:t,error:v,headers:a,status:h,statusText:l});this._logService.error("[XHRHTTPImplementation]: network error",I),r.error(I)}},d=a=>{const l=new b({request:t,error:a,status:n.status||0,statusText:n.statusText||"Unknown Error",headers:i().headers});this._logService.error("[XHRHTTPImplementation]: network error",l),r.error(l)};n.addEventListener("load",c),n.addEventListener("error",d),n.addEventListener("abort",d),n.addEventListener("timeout",d);const u=t.getBody();return n.send(u),this._logService.debug("[XHRHTTPImplementation]",`sending request to url ${s} with params ${o}`),()=>{n.readyState!==n.DONE&&n.abort(),n.removeEventListener("load",c),n.removeEventListener("error",d),n.removeEventListener("abort",d),n.removeEventListener("timeout",d)}})}};exports.XHRHTTPImplementation=te([ne(0,p.ILogService)],exports.XHRHTTPImplementation);var se=Object.getOwnPropertyDescriptor,oe=(e,t,r,n)=>{for(var s=n>1?void 0:n?se(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(s)||s);return s},$=(e,t)=>(r,n)=>t(r,n,e),k;exports.UniverNetworkPlugin=(k=class extends p.Plugin{constructor(t=void 0,r,n){super(),this._config=t,this._logger=r,this._injector=n}onStarting(){var n,s,o;if(this._injector.get(exports.HTTPService,p.Quantity.OPTIONAL,p.LookUp.SKIP_SELF)&&!((n=this._config)!=null&&n.forceUseNewInstance)){this._logger.warn("[UniverNetworkPlugin]",'HTTPService is already registered in an ancestor interceptor. Skipping registration. If you want to force a new instance, set "forceUseNewInstance" to true in the plugin configuration.');return}const r=(s=this._config)!=null&&s.useFetchImpl?exports.FetchHTTPImplementation:typeof window<"u"?exports.XHRHTTPImplementation:exports.FetchHTTPImplementation;p.registerDependencies(this._injector,p.mergeOverrideWithDependencies([[exports.HTTPService],[A,{useClass:r}]],(o=this._config)==null?void 0:o.override))}},m(k,"pluginName","UNIVER_NETWORK_PLUGIN"),k);exports.UniverNetworkPlugin=oe([$(1,p.ILogService),$(2,p.Inject(p.Injector))],exports.UniverNetworkPlugin);const ie=p.createIdentifier("univer.network.socket.service");class ce extends p.Disposable{createSocket(t){try{const r=new WebSocket(t),n=new p.DisposableCollection;return{URL:t,close:(o,i)=>{r.close(o,i),n.dispose()},send:o=>{r.send(o)},open$:new f.Observable(o=>{const i=c=>o.next(c);r.addEventListener("open",i),n.add(p.toDisposable(()=>r.removeEventListener("open",i)))}).pipe(_.share()),close$:new f.Observable(o=>{const i=c=>o.next(c);r.addEventListener("close",i),n.add(p.toDisposable(()=>r.removeEventListener("close",i)))}).pipe(_.share()),error$:new f.Observable(o=>{const i=c=>o.next(c);r.addEventListener("error",i),n.add(p.toDisposable(()=>r.removeEventListener("error",i)))}).pipe(_.share()),message$:new f.Observable(o=>{const i=c=>o.next(c);r.addEventListener("message",i),n.add(p.toDisposable(()=>r.removeEventListener("message",i)))}).pipe(_.share())}}catch(r){return console.error(r),null}}}const ae=3,le=1e3,he=e=>{var n,s;const t=(n=e==null?void 0:e.maxRetryAttempts)!=null?n:ae,r=(s=e==null?void 0:e.delayInterval)!=null?s:le;return(o,i)=>i(o).pipe(_.retry({delay:r,count:t}))},pe=e=>{const t=[],r=new Set,n=()=>{var s;for(;r.size<((s=e==null?void 0:e.maxParallel)!=null?s:1)&&t.length>0;){const o=t.shift();r.add(o),o()}};return(s,o)=>new f.Observable(i=>{const c=()=>o(s).subscribe({next:u=>i.next(u),error:u=>i.error(u),complete:()=>i.complete()}),d=()=>{r.delete(c),p.remove(t,c),n()};return t.push(c),n(),d})},de=e=>{const{errorStatusCodes:t,onAuthError:r}=e;return(s,o)=>o(s).pipe(f.catchError(i=>(i instanceof b&&t.some(c=>c===i.status)&&r(),f.throwError(()=>i))))},ue=(e=300)=>{let r=()=>{};return n=>new Promise(s=>{r();const o=setTimeout(()=>{s(!0)},e);r=()=>{clearTimeout(o),s(!1)}})},ge=()=>(e,t)=>t.map(r=>({config:r,result:e})),ye=(e,t={})=>{const{isMatch:r,getParamsFromRequest:n,mergeParamsToRequest:s}=e,{fetchCheck:o=ue(300),distributeResult:i=ge()}=t,c=[],d=u=>u.map(a=>a.config);return(u,a)=>r(u)?new f.Observable(l=>{const h=n(u);c.push({next:y=>l.next(y),error:y=>l.error(y),config:h});const w=d(c);o(u).then(y=>{if(y){const v=[];w.forEach(g=>{const I=c.findIndex(R=>R.config===g);if(I>=0){const[R]=c.splice(I,1);v.push(R)}}),a(s(w,u)).subscribe({next:g=>{if(g.type===U.Response){const I=g.body,R=i(I,w);v.forEach(F=>{const D=R.find(N=>N.config===F.config);if(D){const N=new L({body:D.result,headers:g.headers,status:g.status,statusText:g.statusText});F.next(N)}else F.error("batch error")})}},complete:()=>l.complete(),error:g=>l.error(g)})}})}):a(u)};exports.AuthInterceptorFactory=de;exports.HTTPEventType=U;exports.HTTPHeaders=E;exports.HTTPProgress=j;exports.HTTPRequest=O;exports.HTTPResponse=L;exports.HTTPResponseError=b;exports.HTTPStatusCode=x;exports.IHTTPImplementation=A;exports.ISocketService=ie;exports.MergeInterceptorFactory=ye;exports.ResponseHeader=B;exports.RetryInterceptorFactory=he;exports.ThresholdInterceptorFactory=pe;exports.WebSocketService=ce;
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 y=(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){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 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){y(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();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,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 d,u;const o=new E(s==null?void 0:s.headers),i=new M(s==null?void 0:s.params),c=new O(r,t,{headers:o,params:i,withCredentials:(d=s==null?void 0:s.withCredentials)!=null?d:!1,reportProgress:!0,responseType:(u=s==null?void 0:s.responseType)!=null?u:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body});return w.of(c).pipe(_.concatMap(a=>this._runInterceptorsAndImplementation(a)))}async _request(r,t,s){var a,l;const o=new E(s==null?void 0:s.headers),i=new M(s==null?void 0:s.params),c=new O(r,t,{headers:o,params:i,withCredentials:(a=s==null?void 0:s.withCredentials)!=null?a:!1,responseType:(l=s==null?void 0:s.responseType)!=null?l:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body}),d=w.of(c).pipe(_.concatMap(h=>this._runInterceptorsAndImplementation(h)));return await w.firstValueFrom(d)}_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}){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 j{constructor(n,r,t){y(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 b{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 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 b({error:s,request:n}))}),()=>t.abort()})}async _send(n,r,t){var a,l;let s;try{const h=X(n),f=n.getUrlWithParams(),m=fetch(f,{signal:t.signal,...h});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${f} with params ${h}`),s=await m}catch(h){const f=new b({request:n,error:h,status:(a=h.status)!=null?a:0,statusText:(l=h.statusText)!=null?l:"Unknown Error",headers:h.headers});this._logService.error("[FetchHTTPImplementation]: network error",f),r.error(f);return}const o=new E(s.headers),i=s.status,c=s.statusText;let d=null;if(s.body&&(d=await this._readBody(n,s,r)),i>=x.Ok&&i<x.MultipleChoices)r.next(new L({body:d,headers:o,status:i,statusText:c}));else{const h=new b({request:n,error:d,status:i,statusText:c,headers:o});this._logService.error("[FetchHTTPImplementation]: network error",h),r.error(h)}r.complete()}async _readBody(n,r,t){var f,m;const s=[],o=r.body.getReader(),i=r.headers.get("content-length");let c=0;const d=(f=n.requestParams)==null?void 0:f.reportProgress,u=n.responseType;let a,l;for(;;){const{done:v,value:g}=await o.read();if(v)break;s.push(g),c+=g.length,d&&u==="text"&&(a=(a!=null?a:"")+(l!=null?l:l=new TextDecoder).decode(g,{stream:!0}),t.next(new j(i?Number.parseInt(i,10):void 0,c,a)))}const h=T(s,c);try{const v=(m=r.headers.get("content-type"))!=null?m:"";return re(n,h,v)}catch(v){const g=new b({request:n,error:v,status:r.status,statusText:r.statusText,headers:new E(r.headers)});return this._logService.error("[FetchHTTPImplementation]: network error",g),t.error(g),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);t.open(n.method,s),n.withCredentials&&(t.withCredentials=!0),o.headers&&Object.entries(o.headers).forEach(([a,l])=>t.setRequestHeader(a,l));const i=()=>{const a=t.statusText||"OK",l=new E(t.getAllResponseHeaders());return new B(l,t.status,a)},c=()=>{const{headers:a,statusText:l,status:h}=i(),{responseType:f}=n;let m=null,v=null;h!==x.NoContent&&(m=typeof t.response>"u"?t.responseText:t.response);let g=h>=Z&&h<P;if(f==="json"&&typeof m=="string"){const I=m;try{m=m?JSON.parse(m):null}catch(R){g=!1,m=I,v=R}}if(g)r.next(new L({body:m,headers:a,status:h,statusText:l}));else{const I=new b({request:n,error:v,headers:a,status:h,statusText:l});this._logService.error("[XHRHTTPImplementation]: network error",I),r.error(I)}},d=a=>{const l=new b({request:n,error:a,status:t.status||0,statusText:t.statusText||"Unknown Error",headers:i().headers});this._logService.error("[XHRHTTPImplementation]: network error",l),r.error(l)};t.addEventListener("load",c),t.addEventListener("error",d),t.addEventListener("abort",d),t.addEventListener("timeout",d);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",c),t.removeEventListener("error",d),t.removeEventListener("abort",d),t.removeEventListener("timeout",d)}})}};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))}},y(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:u=>i.next(u),error:u=>i.error(u),complete:()=>i.complete()}),d=()=>{r.delete(c),p.remove(n,c),t()};return n.push(c),t(),d})},ue=e=>{const{errorStatusCodes:n,onAuthError:r}=e;return(s,o)=>o(s).pipe(w.catchError(i=>(i instanceof b&&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=[],d=u=>u.map(a=>a.config);return(u,a)=>r(u)?new w.Observable(l=>{const h=t(u);c.push({next:m=>l.next(m),error:m=>l.error(m),config:h});const f=d(c);o(u).then(m=>{if(m){const v=[];f.forEach(g=>{const I=c.findIndex(R=>R.config===g);if(I>=0){const[R]=c.splice(I,1);v.push(R)}}),a(s(f,u)).subscribe({next:g=>{if(g.type===D.Response){const I=g.body,R=i(I,f);v.forEach(F=>{const q=R.find(N=>N.config===F.config);if(q){const N=new L({body:q.result,headers:g.headers,status:g.status,statusText:g.statusText});F.next(N)}else F.error("batch error")})}},complete:()=>l.complete(),error:g=>l.error(g)})}})}):a(u)};exports.AuthInterceptorFactory=ue;exports.HTTPEventType=D;exports.HTTPHeaders=E;exports.HTTPProgress=j;exports.HTTPRequest=O;exports.HTTPResponse=L;exports.HTTPResponseError=b;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
@@ -1,10 +1,13 @@
1
1
  var Z = Object.defineProperty;
2
2
  var P = (e, t, r) => t in e ? Z(e, t, { enumerable: !0, configurable: !0, writable: !0, value: r }) : e[t] = r;
3
3
  var p = (e, t, r) => P(e, typeof t != "symbol" ? t + "" : t, r);
4
- import { createIdentifier as V, Disposable as z, toDisposable as R, remove as J, ILogService as O, Inject as S, Injector as H, Plugin as C, Quantity as T, LookUp as ee, registerDependencies as re, mergeOverrideWithDependencies as te, DisposableCollection as ne } from "@univerjs/core";
5
- import { of as q, firstValueFrom as se, Observable as m, catchError as oe, throwError as ie } from "rxjs";
6
- import { concatMap as M, share as x, retry as ce } from "rxjs/operators";
7
- const j = "application/json";
4
+ import { createIdentifier as V, Disposable as J, toDisposable as R, remove as z, ILogService as D, Inject as S, Injector as H, Plugin as C, Quantity as T, LookUp as ee, registerDependencies as re, mergeOverrideWithDependencies as te, DisposableCollection as ne } from "@univerjs/core";
5
+ import { of as M, firstValueFrom as se, Observable as m, catchError as oe, throwError as ie } from "rxjs";
6
+ import { concatMap as j, share as b, retry as ce } from "rxjs/operators";
7
+ const U = "application/json";
8
+ function ae(e) {
9
+ return Array.isArray(e) ? e.some((t) => t.includes(U)) : e.includes(U);
10
+ }
8
11
  class I {
9
12
  constructor(t) {
10
13
  p(this, "_headers", /* @__PURE__ */ new Map());
@@ -23,12 +26,12 @@ class I {
23
26
  set(t, r) {
24
27
  this._setHeader(t, r);
25
28
  }
26
- toHeadersInit() {
27
- var r, n;
28
- const t = {};
29
- return this._headers.forEach((s, o) => {
30
- t[o] = s.join(",");
31
- }), (r = t.accept) != null || (t.accept = "application/json, text/plain, */*"), (n = t["content-type"]) != null || (t["content-type"] = "application/json;charset=UTF-8"), t;
29
+ toHeadersInit(t) {
30
+ var n, s;
31
+ const r = {};
32
+ return this._headers.forEach((o, i) => {
33
+ r[i] = o.join(",");
34
+ }), (n = r.accept) != null || (r.accept = "application/json, text/plain, */*"), t instanceof FormData || (s = r["content-type"]) != null || (r["content-type"] = "application/json;charset=UTF-8"), r;
32
35
  }
33
36
  _setHeader(t, r) {
34
37
  const n = t.toLowerCase();
@@ -60,10 +63,10 @@ class B {
60
63
  }).join("&") : "";
61
64
  }
62
65
  }
63
- let ae = 0;
66
+ let le = 0;
64
67
  class G {
65
68
  constructor(t, r, n) {
66
- p(this, "uid", ae++);
69
+ p(this, "uid", le++);
67
70
  this.method = t, this.url = r, this.requestParams = n;
68
71
  }
69
72
  get headers() {
@@ -82,19 +85,20 @@ class G {
82
85
  }
83
86
  getBody() {
84
87
  var n, s;
85
- const t = (n = this.headers.get("Content-Type")) != null ? n : j, r = (s = this.requestParams) == null ? void 0 : s.body;
86
- return t === j && r && typeof r == "object" ? JSON.stringify(r) : r ? `${r}` : null;
88
+ const t = (n = this.headers.get("Content-Type")) != null ? n : U, r = (s = this.requestParams) == null ? void 0 : s.body;
89
+ return r instanceof FormData ? r : ae(t) && r && typeof r == "object" ? JSON.stringify(r) : r ? `${r}` : null;
87
90
  }
88
91
  getHeadersInit() {
89
- return this.headers.toHeadersInit();
92
+ var r;
93
+ return this.headers.toHeadersInit((r = this.requestParams) == null ? void 0 : r.body);
90
94
  }
91
95
  }
92
- var le = Object.getOwnPropertyDescriptor, he = (e, t, r, n) => {
93
- for (var s = n > 1 ? void 0 : n ? le(t, r) : t, o = e.length - 1, i; o >= 0; o--)
96
+ var he = Object.getOwnPropertyDescriptor, de = (e, t, r, n) => {
97
+ for (var s = n > 1 ? void 0 : n ? he(t, r) : t, o = e.length - 1, i; o >= 0; o--)
94
98
  (i = e[o]) && (s = i(s) || s);
95
99
  return s;
96
- }, de = (e, t) => (r, n) => t(r, n, e);
97
- let b = class extends z {
100
+ }, pe = (e, t) => (r, n) => t(r, n, e);
101
+ let x = class extends J {
98
102
  constructor(t) {
99
103
  super();
100
104
  p(this, "_interceptors", []);
@@ -114,7 +118,7 @@ let b = class extends z {
114
118
  return this._interceptors.push(t), this._interceptors = this._interceptors.sort((r, n) => {
115
119
  var s, o;
116
120
  return ((s = r.priority) != null ? s : 0) - ((o = n.priority) != null ? o : 0);
117
- }), this._pipe = null, R(() => J(this._interceptors, t));
121
+ }), this._pipe = null, R(() => z(this._interceptors, t));
118
122
  }
119
123
  get(t, r) {
120
124
  return this._request("GET", t, r);
@@ -132,16 +136,16 @@ let b = class extends z {
132
136
  return this._request("PATCH", t, r);
133
137
  }
134
138
  getSSE(t, r, n) {
135
- var c, f;
139
+ var c, y;
136
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, {
137
141
  headers: s,
138
142
  params: o,
139
143
  withCredentials: (c = n == null ? void 0 : n.withCredentials) != null ? c : !1,
140
144
  reportProgress: !0,
141
- responseType: (f = n == null ? void 0 : n.responseType) != null ? f : "json",
145
+ responseType: (y = n == null ? void 0 : n.responseType) != null ? y : "json",
142
146
  body: ["GET", "DELETE"].includes(t) || n == null ? void 0 : n.body
143
147
  });
144
- return q(i).pipe(M((a) => this._runInterceptorsAndImplementation(a)));
148
+ return M(i).pipe(j((a) => this._runInterceptorsAndImplementation(a)));
145
149
  }
146
150
  /** The HTTP request implementations */
147
151
  async _request(t, r, n) {
@@ -153,15 +157,15 @@ let b = class extends z {
153
157
  // default value for withCredentials is false by MDN
154
158
  responseType: (h = n == null ? void 0 : n.responseType) != null ? h : "json",
155
159
  body: ["GET", "DELETE"].includes(t) || n == null ? void 0 : n.body
156
- }), c = q(i).pipe(
157
- M((l) => this._runInterceptorsAndImplementation(l))
160
+ }), c = M(i).pipe(
161
+ j((l) => this._runInterceptorsAndImplementation(l))
158
162
  );
159
163
  return await se(c);
160
164
  }
161
165
  // eslint-disable-next-line ts/no-explicit-any
162
166
  _runInterceptorsAndImplementation(t) {
163
167
  return this._pipe || (this._pipe = this._interceptors.map((r) => r.interceptor).reduceRight(
164
- (r, n) => pe(r, n),
168
+ (r, n) => ue(r, n),
165
169
  (r, n) => n(r)
166
170
  )), this._pipe(
167
171
  t,
@@ -170,15 +174,15 @@ let b = class extends z {
170
174
  );
171
175
  }
172
176
  };
173
- b = he([
174
- de(0, K)
175
- ], b);
176
- function pe(e, t) {
177
+ x = de([
178
+ pe(0, K)
179
+ ], x);
180
+ function ue(e, t) {
177
181
  return (r, n) => t(r, (s) => e(s, n));
178
182
  }
179
- const ue = 200, ge = 300;
183
+ const ge = 200, fe = 300;
180
184
  var L = /* @__PURE__ */ ((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 || {}), Y = /* @__PURE__ */ ((e) => (e[e.DownloadProgress = 0] = "DownloadProgress", e[e.Response = 1] = "Response", e))(Y || {});
181
- class D {
185
+ class $ {
182
186
  constructor({
183
187
  body: t,
184
188
  headers: r,
@@ -199,7 +203,7 @@ class ye {
199
203
  this.total = t, this.loaded = r, this.partialText = n;
200
204
  }
201
205
  }
202
- class fe {
206
+ class we {
203
207
  constructor(t, r, n) {
204
208
  this.headers = t, this.status = r, this.statusText = n;
205
209
  }
@@ -228,11 +232,11 @@ function Q(e) {
228
232
  credentials: e.withCredentials ? "include" : void 0
229
233
  };
230
234
  }
231
- var we = Object.getOwnPropertyDescriptor, me = (e, t, r, n) => {
232
- for (var s = n > 1 ? void 0 : n ? we(t, r) : t, o = e.length - 1, i; o >= 0; o--)
235
+ var me = Object.getOwnPropertyDescriptor, ve = (e, t, r, n) => {
236
+ for (var s = n > 1 ? void 0 : n ? me(t, r) : t, o = e.length - 1, i; o >= 0; o--)
233
237
  (i = e[o]) && (s = i(s) || s);
234
238
  return s;
235
- }, ve = (e, t) => (r, n) => t(r, n, e);
239
+ }, _e = (e, t) => (r, n) => t(r, n, e);
236
240
  let N = class {
237
241
  constructor(e) {
238
242
  this._logService = e;
@@ -271,7 +275,7 @@ let N = class {
271
275
  const s = new I(n.headers), o = n.status, i = n.statusText;
272
276
  let c = null;
273
277
  if (n.body && (c = await this._readBody(e, n, t)), o >= L.Ok && o < L.MultipleChoices)
274
- t.next(new D({
278
+ t.next(new $({
275
279
  body: c,
276
280
  headers: s,
277
281
  status: o,
@@ -293,48 +297,48 @@ let N = class {
293
297
  var w, d;
294
298
  const n = [], s = t.body.getReader(), o = t.headers.get("content-length");
295
299
  let i = 0;
296
- const c = (w = e.requestParams) == null ? void 0 : w.reportProgress, f = e.responseType;
300
+ const c = (w = e.requestParams) == null ? void 0 : w.reportProgress, y = e.responseType;
297
301
  let a, h;
298
302
  for (; ; ) {
299
- const { done: u, value: y } = await s.read();
303
+ const { done: u, value: f } = await s.read();
300
304
  if (u) break;
301
- n.push(y), i += y.length, c && f === "text" && (a = (a != null ? a : "") + (h != null ? h : h = new TextDecoder()).decode(y, { stream: !0 }), r.next(new ye(
305
+ n.push(f), i += f.length, c && y === "text" && (a = (a != null ? a : "") + (h != null ? h : h = new TextDecoder()).decode(f, { stream: !0 }), r.next(new ye(
302
306
  o ? Number.parseInt(o, 10) : void 0,
303
307
  i,
304
308
  a
305
309
  )));
306
310
  }
307
- const l = _e(n, i);
311
+ const l = Ee(n, i);
308
312
  try {
309
313
  const u = (d = t.headers.get("content-type")) != null ? d : "";
310
- return Re(e, l, u);
314
+ return Ie(e, l, u);
311
315
  } catch (u) {
312
- const y = new v({
316
+ const f = new v({
313
317
  request: e,
314
318
  error: u,
315
319
  status: t.status,
316
320
  statusText: t.statusText,
317
321
  headers: new I(t.headers)
318
322
  });
319
- return this._logService.error("[FetchHTTPImplementation]: network error", y), r.error(y), null;
323
+ return this._logService.error("[FetchHTTPImplementation]: network error", f), r.error(f), null;
320
324
  }
321
325
  }
322
326
  };
323
- N = me([
324
- ve(0, O)
327
+ N = ve([
328
+ _e(0, D)
325
329
  ], N);
326
- function _e(e, t) {
330
+ function Ee(e, t) {
327
331
  const r = new Uint8Array(t);
328
332
  let n = 0;
329
333
  for (const s of e)
330
334
  r.set(s, n), n += s.length;
331
335
  return r;
332
336
  }
333
- const Ee = /^\)\]\}',?\n/;
334
- function Re(e, t, r) {
337
+ const Re = /^\)\]\}',?\n/;
338
+ function Ie(e, t, r) {
335
339
  switch (e.responseType) {
336
340
  case "json":
337
- const n = new TextDecoder().decode(t).replace(Ee, "");
341
+ const n = new TextDecoder().decode(t).replace(Re, "");
338
342
  return n === "" ? null : JSON.parse(n);
339
343
  case "text":
340
344
  return new TextDecoder().decode(t);
@@ -346,12 +350,12 @@ function Re(e, t, r) {
346
350
  throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`);
347
351
  }
348
352
  }
349
- var Ie = Object.getOwnPropertyDescriptor, xe = (e, t, r, n) => {
350
- for (var s = n > 1 ? void 0 : n ? Ie(t, r) : t, o = e.length - 1, i; o >= 0; o--)
353
+ var be = Object.getOwnPropertyDescriptor, xe = (e, t, r, n) => {
354
+ for (var s = n > 1 ? void 0 : n ? be(t, r) : t, o = e.length - 1, i; o >= 0; o--)
351
355
  (i = e[o]) && (s = i(s) || s);
352
356
  return s;
353
- }, be = (e, t) => (r, n) => t(r, n, e);
354
- let U = class {
357
+ }, Le = (e, t) => (r, n) => t(r, n, e);
358
+ let O = class {
355
359
  constructor(e) {
356
360
  this._logService = e;
357
361
  }
@@ -361,23 +365,23 @@ let U = class {
361
365
  r.open(e.method, n), e.withCredentials && (r.withCredentials = !0), s.headers && Object.entries(s.headers).forEach(([a, h]) => r.setRequestHeader(a, h));
362
366
  const o = () => {
363
367
  const a = r.statusText || "OK", h = new I(r.getAllResponseHeaders());
364
- return new fe(h, r.status, a);
368
+ return new we(h, r.status, a);
365
369
  }, i = () => {
366
370
  const { headers: a, statusText: h, status: l } = o(), { responseType: w } = e;
367
371
  let d = null, u = null;
368
372
  l !== L.NoContent && (d = typeof r.response > "u" ? r.responseText : r.response);
369
- let y = l >= ue && l < ge;
373
+ let f = l >= ge && l < fe;
370
374
  if (w === "json" && typeof d == "string") {
371
375
  const g = d;
372
376
  try {
373
377
  d = d ? JSON.parse(d) : null;
374
378
  } catch (_) {
375
- y = !1, d = g, u = _;
379
+ f = !1, d = g, u = _;
376
380
  }
377
381
  }
378
- if (y)
382
+ if (f)
379
383
  t.next(
380
- new D({
384
+ new $({
381
385
  body: d,
382
386
  headers: a,
383
387
  status: l,
@@ -405,47 +409,47 @@ let U = class {
405
409
  this._logService.error("[XHRHTTPImplementation]: network error", h), t.error(h);
406
410
  };
407
411
  r.addEventListener("load", i), r.addEventListener("error", c), r.addEventListener("abort", c), r.addEventListener("timeout", c);
408
- const f = e.getBody();
409
- return r.send(f), this._logService.debug("[XHRHTTPImplementation]", `sending request to url ${n} with params ${s}`), () => {
412
+ const y = e.getBody();
413
+ return r.send(y), this._logService.debug("[XHRHTTPImplementation]", `sending request to url ${n} with params ${s}`), () => {
410
414
  r.readyState !== r.DONE && r.abort(), r.removeEventListener("load", i), r.removeEventListener("error", c), r.removeEventListener("abort", c), r.removeEventListener("timeout", c);
411
415
  };
412
416
  });
413
417
  }
414
418
  };
415
- U = xe([
416
- be(0, O)
417
- ], U);
418
- var Le = Object.getOwnPropertyDescriptor, Ne = (e, t, r, n) => {
419
- for (var s = n > 1 ? void 0 : n ? Le(t, r) : t, o = e.length - 1, i; o >= 0; o--)
419
+ O = xe([
420
+ Le(0, D)
421
+ ], O);
422
+ var Ne = Object.getOwnPropertyDescriptor, Ae = (e, t, r, n) => {
423
+ for (var s = n > 1 ? void 0 : n ? Ne(t, r) : t, o = e.length - 1, i; o >= 0; o--)
420
424
  (i = e[o]) && (s = i(s) || s);
421
425
  return s;
422
- }, W = (e, t) => (r, n) => t(r, n, e), F;
423
- let X = (F = class extends C {
426
+ }, W = (e, t) => (r, n) => t(r, n, e), k;
427
+ let X = (k = class extends C {
424
428
  constructor(e = void 0, t, r) {
425
429
  super(), this._config = e, this._logger = t, this._injector = r;
426
430
  }
427
431
  onStarting() {
428
432
  var r, n, s;
429
- if (this._injector.get(b, T.OPTIONAL, ee.SKIP_SELF) && !((r = this._config) != null && r.forceUseNewInstance)) {
433
+ if (this._injector.get(x, T.OPTIONAL, ee.SKIP_SELF) && !((r = this._config) != null && r.forceUseNewInstance)) {
430
434
  this._logger.warn(
431
435
  "[UniverNetworkPlugin]",
432
436
  '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.'
433
437
  );
434
438
  return;
435
439
  }
436
- const t = (n = this._config) != null && n.useFetchImpl ? N : typeof window < "u" ? U : N;
440
+ const t = (n = this._config) != null && n.useFetchImpl ? N : typeof window < "u" ? O : N;
437
441
  re(this._injector, te([
438
- [b],
442
+ [x],
439
443
  [K, { useClass: t }]
440
444
  ], (s = this._config) == null ? void 0 : s.override));
441
445
  }
442
- }, p(F, "pluginName", "UNIVER_NETWORK_PLUGIN"), F);
443
- X = Ne([
444
- W(1, O),
446
+ }, p(k, "pluginName", "UNIVER_NETWORK_PLUGIN"), k);
447
+ X = Ae([
448
+ W(1, D),
445
449
  W(2, S(H))
446
450
  ], X);
447
- const Me = V("univer.network.socket.service");
448
- class je extends z {
451
+ const je = V("univer.network.socket.service");
452
+ class Be extends J {
449
453
  createSocket(t) {
450
454
  try {
451
455
  const r = new WebSocket(t), n = new ne();
@@ -460,30 +464,30 @@ class je extends z {
460
464
  open$: new m((o) => {
461
465
  const i = (c) => o.next(c);
462
466
  r.addEventListener("open", i), n.add(R(() => r.removeEventListener("open", i)));
463
- }).pipe(x()),
467
+ }).pipe(b()),
464
468
  close$: new m((o) => {
465
469
  const i = (c) => o.next(c);
466
470
  r.addEventListener("close", i), n.add(R(() => r.removeEventListener("close", i)));
467
- }).pipe(x()),
471
+ }).pipe(b()),
468
472
  error$: new m((o) => {
469
473
  const i = (c) => o.next(c);
470
474
  r.addEventListener("error", i), n.add(R(() => r.removeEventListener("error", i)));
471
- }).pipe(x()),
475
+ }).pipe(b()),
472
476
  message$: new m((o) => {
473
477
  const i = (c) => o.next(c);
474
478
  r.addEventListener("message", i), n.add(R(() => r.removeEventListener("message", i)));
475
- }).pipe(x())
479
+ }).pipe(b())
476
480
  };
477
481
  } catch (r) {
478
482
  return console.error(r), null;
479
483
  }
480
484
  }
481
485
  }
482
- const ke = 3, Ae = 1e3, Be = (e) => {
486
+ const Fe = 3, ke = 1e3, Ge = (e) => {
483
487
  var n, s;
484
- const t = (n = e == null ? void 0 : e.maxRetryAttempts) != null ? n : ke, r = (s = e == null ? void 0 : e.delayInterval) != null ? s : Ae;
488
+ const t = (n = e == null ? void 0 : e.maxRetryAttempts) != null ? n : Fe, r = (s = e == null ? void 0 : e.delayInterval) != null ? s : ke;
485
489
  return (o, i) => i(o).pipe(ce({ delay: r, count: t }));
486
- }, Ge = (e) => {
490
+ }, We = (e) => {
487
491
  const t = [], r = /* @__PURE__ */ new Set(), n = () => {
488
492
  var s;
489
493
  for (; r.size < ((s = e == null ? void 0 : e.maxParallel) != null ? s : 1) && t.length > 0; ) {
@@ -496,17 +500,17 @@ const ke = 3, Ae = 1e3, Be = (e) => {
496
500
  next: (a) => i.next(a),
497
501
  error: (a) => i.error(a),
498
502
  complete: () => i.complete()
499
- }), f = () => {
500
- r.delete(c), J(t, c), n();
503
+ }), y = () => {
504
+ r.delete(c), z(t, c), n();
501
505
  };
502
- return t.push(c), n(), f;
506
+ return t.push(c), n(), y;
503
507
  });
504
- }, We = (e) => {
508
+ }, Xe = (e) => {
505
509
  const { errorStatusCodes: t, onAuthError: r } = e;
506
510
  return (s, o) => o(s).pipe(
507
511
  oe((i) => (i instanceof v && t.some((c) => c === i.status) && r(), ie(() => i)))
508
512
  );
509
- }, Fe = (e = 300) => {
513
+ }, Ue = (e = 300) => {
510
514
  let r = () => {
511
515
  };
512
516
  return (n) => new Promise((s) => {
@@ -518,8 +522,8 @@ const ke = 3, Ae = 1e3, Be = (e) => {
518
522
  clearTimeout(o), s(!1);
519
523
  };
520
524
  });
521
- }, Ue = () => (e, t) => t.map((r) => ({ config: r, result: e })), Xe = (e, t = {}) => {
522
- const { isMatch: r, getParamsFromRequest: n, mergeParamsToRequest: s } = e, { fetchCheck: o = Fe(300), distributeResult: i = Ue() } = t, c = [], f = (a) => a.map((h) => h.config);
525
+ }, Oe = () => (e, t) => t.map((r) => ({ config: r, result: e })), Ve = (e, t = {}) => {
526
+ const { isMatch: r, getParamsFromRequest: n, mergeParamsToRequest: s } = e, { fetchCheck: o = Ue(300), distributeResult: i = Oe() } = t, c = [], y = (a) => a.map((h) => h.config);
523
527
  return (a, h) => r(a) ? new m((l) => {
524
528
  const w = n(a);
525
529
  c.push({
@@ -527,32 +531,32 @@ const ke = 3, Ae = 1e3, Be = (e) => {
527
531
  error: (u) => l.error(u),
528
532
  config: w
529
533
  });
530
- const d = f(c);
534
+ const d = y(c);
531
535
  o(a).then((u) => {
532
536
  if (u) {
533
- const y = [];
537
+ const f = [];
534
538
  d.forEach((g) => {
535
539
  const _ = c.findIndex((E) => E.config === g);
536
540
  if (_ >= 0) {
537
541
  const [E] = c.splice(_, 1);
538
- y.push(E);
542
+ f.push(E);
539
543
  }
540
544
  }), h(s(d, a)).subscribe({
541
545
  next: (g) => {
542
546
  if (g.type === Y.Response) {
543
547
  const _ = g.body, E = i(_, d);
544
- y.forEach((k) => {
545
- const $ = E.find((A) => A.config === k.config);
546
- if ($) {
547
- const A = new D({
548
- body: $.result,
548
+ f.forEach((A) => {
549
+ const q = E.find((F) => F.config === A.config);
550
+ if (q) {
551
+ const F = new $({
552
+ body: q.result,
549
553
  headers: g.headers,
550
554
  status: g.status,
551
555
  statusText: g.statusText
552
556
  });
553
- k.next(A);
557
+ A.next(F);
554
558
  } else
555
- k.error("batch error");
559
+ A.error("batch error");
556
560
  });
557
561
  }
558
562
  },
@@ -564,23 +568,23 @@ const ke = 3, Ae = 1e3, Be = (e) => {
564
568
  }) : h(a);
565
569
  };
566
570
  export {
567
- We as AuthInterceptorFactory,
571
+ Xe as AuthInterceptorFactory,
568
572
  N as FetchHTTPImplementation,
569
573
  Y as HTTPEventType,
570
574
  I as HTTPHeaders,
571
575
  ye as HTTPProgress,
572
576
  G as HTTPRequest,
573
- D as HTTPResponse,
577
+ $ as HTTPResponse,
574
578
  v as HTTPResponseError,
575
- b as HTTPService,
579
+ x as HTTPService,
576
580
  L as HTTPStatusCode,
577
581
  K as IHTTPImplementation,
578
- Me as ISocketService,
579
- Xe as MergeInterceptorFactory,
580
- fe as ResponseHeader,
581
- Be as RetryInterceptorFactory,
582
- Ge as ThresholdInterceptorFactory,
582
+ je as ISocketService,
583
+ Ve as MergeInterceptorFactory,
584
+ we as ResponseHeader,
585
+ Ge as RetryInterceptorFactory,
586
+ We as ThresholdInterceptorFactory,
583
587
  X as UniverNetworkPlugin,
584
- je as WebSocketService,
585
- U as XHRHTTPImplementation
588
+ Be as WebSocketService,
589
+ O as XHRHTTPImplementation
586
590
  };
package/lib/index.js CHANGED
@@ -1,10 +1,13 @@
1
1
  var Z = Object.defineProperty;
2
2
  var P = (e, t, r) => t in e ? Z(e, t, { enumerable: !0, configurable: !0, writable: !0, value: r }) : e[t] = r;
3
3
  var p = (e, t, r) => P(e, typeof t != "symbol" ? t + "" : t, r);
4
- import { createIdentifier as V, Disposable as z, toDisposable as R, remove as J, ILogService as O, Inject as S, Injector as H, Plugin as C, Quantity as T, LookUp as ee, registerDependencies as re, mergeOverrideWithDependencies as te, DisposableCollection as ne } from "@univerjs/core";
5
- import { of as q, firstValueFrom as se, Observable as m, catchError as oe, throwError as ie } from "rxjs";
6
- import { concatMap as M, share as x, retry as ce } from "rxjs/operators";
7
- const j = "application/json";
4
+ import { createIdentifier as V, Disposable as J, toDisposable as R, remove as z, ILogService as D, Inject as S, Injector as H, Plugin as C, Quantity as T, LookUp as ee, registerDependencies as re, mergeOverrideWithDependencies as te, DisposableCollection as ne } from "@univerjs/core";
5
+ import { of as M, firstValueFrom as se, Observable as m, catchError as oe, throwError as ie } from "rxjs";
6
+ import { concatMap as j, share as b, retry as ce } from "rxjs/operators";
7
+ const U = "application/json";
8
+ function ae(e) {
9
+ return Array.isArray(e) ? e.some((t) => t.includes(U)) : e.includes(U);
10
+ }
8
11
  class I {
9
12
  constructor(t) {
10
13
  p(this, "_headers", /* @__PURE__ */ new Map());
@@ -23,12 +26,12 @@ class I {
23
26
  set(t, r) {
24
27
  this._setHeader(t, r);
25
28
  }
26
- toHeadersInit() {
27
- var r, n;
28
- const t = {};
29
- return this._headers.forEach((s, o) => {
30
- t[o] = s.join(",");
31
- }), (r = t.accept) != null || (t.accept = "application/json, text/plain, */*"), (n = t["content-type"]) != null || (t["content-type"] = "application/json;charset=UTF-8"), t;
29
+ toHeadersInit(t) {
30
+ var n, s;
31
+ const r = {};
32
+ return this._headers.forEach((o, i) => {
33
+ r[i] = o.join(",");
34
+ }), (n = r.accept) != null || (r.accept = "application/json, text/plain, */*"), t instanceof FormData || (s = r["content-type"]) != null || (r["content-type"] = "application/json;charset=UTF-8"), r;
32
35
  }
33
36
  _setHeader(t, r) {
34
37
  const n = t.toLowerCase();
@@ -60,10 +63,10 @@ class B {
60
63
  }).join("&") : "";
61
64
  }
62
65
  }
63
- let ae = 0;
66
+ let le = 0;
64
67
  class G {
65
68
  constructor(t, r, n) {
66
- p(this, "uid", ae++);
69
+ p(this, "uid", le++);
67
70
  this.method = t, this.url = r, this.requestParams = n;
68
71
  }
69
72
  get headers() {
@@ -82,19 +85,20 @@ class G {
82
85
  }
83
86
  getBody() {
84
87
  var n, s;
85
- const t = (n = this.headers.get("Content-Type")) != null ? n : j, r = (s = this.requestParams) == null ? void 0 : s.body;
86
- return t === j && r && typeof r == "object" ? JSON.stringify(r) : r ? `${r}` : null;
88
+ const t = (n = this.headers.get("Content-Type")) != null ? n : U, r = (s = this.requestParams) == null ? void 0 : s.body;
89
+ return r instanceof FormData ? r : ae(t) && r && typeof r == "object" ? JSON.stringify(r) : r ? `${r}` : null;
87
90
  }
88
91
  getHeadersInit() {
89
- return this.headers.toHeadersInit();
92
+ var r;
93
+ return this.headers.toHeadersInit((r = this.requestParams) == null ? void 0 : r.body);
90
94
  }
91
95
  }
92
- var le = Object.getOwnPropertyDescriptor, he = (e, t, r, n) => {
93
- for (var s = n > 1 ? void 0 : n ? le(t, r) : t, o = e.length - 1, i; o >= 0; o--)
96
+ var he = Object.getOwnPropertyDescriptor, de = (e, t, r, n) => {
97
+ for (var s = n > 1 ? void 0 : n ? he(t, r) : t, o = e.length - 1, i; o >= 0; o--)
94
98
  (i = e[o]) && (s = i(s) || s);
95
99
  return s;
96
- }, de = (e, t) => (r, n) => t(r, n, e);
97
- let b = class extends z {
100
+ }, pe = (e, t) => (r, n) => t(r, n, e);
101
+ let x = class extends J {
98
102
  constructor(t) {
99
103
  super();
100
104
  p(this, "_interceptors", []);
@@ -114,7 +118,7 @@ let b = class extends z {
114
118
  return this._interceptors.push(t), this._interceptors = this._interceptors.sort((r, n) => {
115
119
  var s, o;
116
120
  return ((s = r.priority) != null ? s : 0) - ((o = n.priority) != null ? o : 0);
117
- }), this._pipe = null, R(() => J(this._interceptors, t));
121
+ }), this._pipe = null, R(() => z(this._interceptors, t));
118
122
  }
119
123
  get(t, r) {
120
124
  return this._request("GET", t, r);
@@ -132,16 +136,16 @@ let b = class extends z {
132
136
  return this._request("PATCH", t, r);
133
137
  }
134
138
  getSSE(t, r, n) {
135
- var c, f;
139
+ var c, y;
136
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, {
137
141
  headers: s,
138
142
  params: o,
139
143
  withCredentials: (c = n == null ? void 0 : n.withCredentials) != null ? c : !1,
140
144
  reportProgress: !0,
141
- responseType: (f = n == null ? void 0 : n.responseType) != null ? f : "json",
145
+ responseType: (y = n == null ? void 0 : n.responseType) != null ? y : "json",
142
146
  body: ["GET", "DELETE"].includes(t) || n == null ? void 0 : n.body
143
147
  });
144
- return q(i).pipe(M((a) => this._runInterceptorsAndImplementation(a)));
148
+ return M(i).pipe(j((a) => this._runInterceptorsAndImplementation(a)));
145
149
  }
146
150
  /** The HTTP request implementations */
147
151
  async _request(t, r, n) {
@@ -153,15 +157,15 @@ let b = class extends z {
153
157
  // default value for withCredentials is false by MDN
154
158
  responseType: (h = n == null ? void 0 : n.responseType) != null ? h : "json",
155
159
  body: ["GET", "DELETE"].includes(t) || n == null ? void 0 : n.body
156
- }), c = q(i).pipe(
157
- M((l) => this._runInterceptorsAndImplementation(l))
160
+ }), c = M(i).pipe(
161
+ j((l) => this._runInterceptorsAndImplementation(l))
158
162
  );
159
163
  return await se(c);
160
164
  }
161
165
  // eslint-disable-next-line ts/no-explicit-any
162
166
  _runInterceptorsAndImplementation(t) {
163
167
  return this._pipe || (this._pipe = this._interceptors.map((r) => r.interceptor).reduceRight(
164
- (r, n) => pe(r, n),
168
+ (r, n) => ue(r, n),
165
169
  (r, n) => n(r)
166
170
  )), this._pipe(
167
171
  t,
@@ -170,15 +174,15 @@ let b = class extends z {
170
174
  );
171
175
  }
172
176
  };
173
- b = he([
174
- de(0, K)
175
- ], b);
176
- function pe(e, t) {
177
+ x = de([
178
+ pe(0, K)
179
+ ], x);
180
+ function ue(e, t) {
177
181
  return (r, n) => t(r, (s) => e(s, n));
178
182
  }
179
- const ue = 200, ge = 300;
183
+ const ge = 200, fe = 300;
180
184
  var L = /* @__PURE__ */ ((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 || {}), Y = /* @__PURE__ */ ((e) => (e[e.DownloadProgress = 0] = "DownloadProgress", e[e.Response = 1] = "Response", e))(Y || {});
181
- class D {
185
+ class $ {
182
186
  constructor({
183
187
  body: t,
184
188
  headers: r,
@@ -199,7 +203,7 @@ class ye {
199
203
  this.total = t, this.loaded = r, this.partialText = n;
200
204
  }
201
205
  }
202
- class fe {
206
+ class we {
203
207
  constructor(t, r, n) {
204
208
  this.headers = t, this.status = r, this.statusText = n;
205
209
  }
@@ -228,11 +232,11 @@ function Q(e) {
228
232
  credentials: e.withCredentials ? "include" : void 0
229
233
  };
230
234
  }
231
- var we = Object.getOwnPropertyDescriptor, me = (e, t, r, n) => {
232
- for (var s = n > 1 ? void 0 : n ? we(t, r) : t, o = e.length - 1, i; o >= 0; o--)
235
+ var me = Object.getOwnPropertyDescriptor, ve = (e, t, r, n) => {
236
+ for (var s = n > 1 ? void 0 : n ? me(t, r) : t, o = e.length - 1, i; o >= 0; o--)
233
237
  (i = e[o]) && (s = i(s) || s);
234
238
  return s;
235
- }, ve = (e, t) => (r, n) => t(r, n, e);
239
+ }, _e = (e, t) => (r, n) => t(r, n, e);
236
240
  let N = class {
237
241
  constructor(e) {
238
242
  this._logService = e;
@@ -271,7 +275,7 @@ let N = class {
271
275
  const s = new I(n.headers), o = n.status, i = n.statusText;
272
276
  let c = null;
273
277
  if (n.body && (c = await this._readBody(e, n, t)), o >= L.Ok && o < L.MultipleChoices)
274
- t.next(new D({
278
+ t.next(new $({
275
279
  body: c,
276
280
  headers: s,
277
281
  status: o,
@@ -293,48 +297,48 @@ let N = class {
293
297
  var w, d;
294
298
  const n = [], s = t.body.getReader(), o = t.headers.get("content-length");
295
299
  let i = 0;
296
- const c = (w = e.requestParams) == null ? void 0 : w.reportProgress, f = e.responseType;
300
+ const c = (w = e.requestParams) == null ? void 0 : w.reportProgress, y = e.responseType;
297
301
  let a, h;
298
302
  for (; ; ) {
299
- const { done: u, value: y } = await s.read();
303
+ const { done: u, value: f } = await s.read();
300
304
  if (u) break;
301
- n.push(y), i += y.length, c && f === "text" && (a = (a != null ? a : "") + (h != null ? h : h = new TextDecoder()).decode(y, { stream: !0 }), r.next(new ye(
305
+ n.push(f), i += f.length, c && y === "text" && (a = (a != null ? a : "") + (h != null ? h : h = new TextDecoder()).decode(f, { stream: !0 }), r.next(new ye(
302
306
  o ? Number.parseInt(o, 10) : void 0,
303
307
  i,
304
308
  a
305
309
  )));
306
310
  }
307
- const l = _e(n, i);
311
+ const l = Ee(n, i);
308
312
  try {
309
313
  const u = (d = t.headers.get("content-type")) != null ? d : "";
310
- return Re(e, l, u);
314
+ return Ie(e, l, u);
311
315
  } catch (u) {
312
- const y = new v({
316
+ const f = new v({
313
317
  request: e,
314
318
  error: u,
315
319
  status: t.status,
316
320
  statusText: t.statusText,
317
321
  headers: new I(t.headers)
318
322
  });
319
- return this._logService.error("[FetchHTTPImplementation]: network error", y), r.error(y), null;
323
+ return this._logService.error("[FetchHTTPImplementation]: network error", f), r.error(f), null;
320
324
  }
321
325
  }
322
326
  };
323
- N = me([
324
- ve(0, O)
327
+ N = ve([
328
+ _e(0, D)
325
329
  ], N);
326
- function _e(e, t) {
330
+ function Ee(e, t) {
327
331
  const r = new Uint8Array(t);
328
332
  let n = 0;
329
333
  for (const s of e)
330
334
  r.set(s, n), n += s.length;
331
335
  return r;
332
336
  }
333
- const Ee = /^\)\]\}',?\n/;
334
- function Re(e, t, r) {
337
+ const Re = /^\)\]\}',?\n/;
338
+ function Ie(e, t, r) {
335
339
  switch (e.responseType) {
336
340
  case "json":
337
- const n = new TextDecoder().decode(t).replace(Ee, "");
341
+ const n = new TextDecoder().decode(t).replace(Re, "");
338
342
  return n === "" ? null : JSON.parse(n);
339
343
  case "text":
340
344
  return new TextDecoder().decode(t);
@@ -346,12 +350,12 @@ function Re(e, t, r) {
346
350
  throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`);
347
351
  }
348
352
  }
349
- var Ie = Object.getOwnPropertyDescriptor, xe = (e, t, r, n) => {
350
- for (var s = n > 1 ? void 0 : n ? Ie(t, r) : t, o = e.length - 1, i; o >= 0; o--)
353
+ var be = Object.getOwnPropertyDescriptor, xe = (e, t, r, n) => {
354
+ for (var s = n > 1 ? void 0 : n ? be(t, r) : t, o = e.length - 1, i; o >= 0; o--)
351
355
  (i = e[o]) && (s = i(s) || s);
352
356
  return s;
353
- }, be = (e, t) => (r, n) => t(r, n, e);
354
- let U = class {
357
+ }, Le = (e, t) => (r, n) => t(r, n, e);
358
+ let O = class {
355
359
  constructor(e) {
356
360
  this._logService = e;
357
361
  }
@@ -361,23 +365,23 @@ let U = class {
361
365
  r.open(e.method, n), e.withCredentials && (r.withCredentials = !0), s.headers && Object.entries(s.headers).forEach(([a, h]) => r.setRequestHeader(a, h));
362
366
  const o = () => {
363
367
  const a = r.statusText || "OK", h = new I(r.getAllResponseHeaders());
364
- return new fe(h, r.status, a);
368
+ return new we(h, r.status, a);
365
369
  }, i = () => {
366
370
  const { headers: a, statusText: h, status: l } = o(), { responseType: w } = e;
367
371
  let d = null, u = null;
368
372
  l !== L.NoContent && (d = typeof r.response > "u" ? r.responseText : r.response);
369
- let y = l >= ue && l < ge;
373
+ let f = l >= ge && l < fe;
370
374
  if (w === "json" && typeof d == "string") {
371
375
  const g = d;
372
376
  try {
373
377
  d = d ? JSON.parse(d) : null;
374
378
  } catch (_) {
375
- y = !1, d = g, u = _;
379
+ f = !1, d = g, u = _;
376
380
  }
377
381
  }
378
- if (y)
382
+ if (f)
379
383
  t.next(
380
- new D({
384
+ new $({
381
385
  body: d,
382
386
  headers: a,
383
387
  status: l,
@@ -405,47 +409,47 @@ let U = class {
405
409
  this._logService.error("[XHRHTTPImplementation]: network error", h), t.error(h);
406
410
  };
407
411
  r.addEventListener("load", i), r.addEventListener("error", c), r.addEventListener("abort", c), r.addEventListener("timeout", c);
408
- const f = e.getBody();
409
- return r.send(f), this._logService.debug("[XHRHTTPImplementation]", `sending request to url ${n} with params ${s}`), () => {
412
+ const y = e.getBody();
413
+ return r.send(y), this._logService.debug("[XHRHTTPImplementation]", `sending request to url ${n} with params ${s}`), () => {
410
414
  r.readyState !== r.DONE && r.abort(), r.removeEventListener("load", i), r.removeEventListener("error", c), r.removeEventListener("abort", c), r.removeEventListener("timeout", c);
411
415
  };
412
416
  });
413
417
  }
414
418
  };
415
- U = xe([
416
- be(0, O)
417
- ], U);
418
- var Le = Object.getOwnPropertyDescriptor, Ne = (e, t, r, n) => {
419
- for (var s = n > 1 ? void 0 : n ? Le(t, r) : t, o = e.length - 1, i; o >= 0; o--)
419
+ O = xe([
420
+ Le(0, D)
421
+ ], O);
422
+ var Ne = Object.getOwnPropertyDescriptor, Ae = (e, t, r, n) => {
423
+ for (var s = n > 1 ? void 0 : n ? Ne(t, r) : t, o = e.length - 1, i; o >= 0; o--)
420
424
  (i = e[o]) && (s = i(s) || s);
421
425
  return s;
422
- }, W = (e, t) => (r, n) => t(r, n, e), F;
423
- let X = (F = class extends C {
426
+ }, W = (e, t) => (r, n) => t(r, n, e), k;
427
+ let X = (k = class extends C {
424
428
  constructor(e = void 0, t, r) {
425
429
  super(), this._config = e, this._logger = t, this._injector = r;
426
430
  }
427
431
  onStarting() {
428
432
  var r, n, s;
429
- if (this._injector.get(b, T.OPTIONAL, ee.SKIP_SELF) && !((r = this._config) != null && r.forceUseNewInstance)) {
433
+ if (this._injector.get(x, T.OPTIONAL, ee.SKIP_SELF) && !((r = this._config) != null && r.forceUseNewInstance)) {
430
434
  this._logger.warn(
431
435
  "[UniverNetworkPlugin]",
432
436
  '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.'
433
437
  );
434
438
  return;
435
439
  }
436
- const t = (n = this._config) != null && n.useFetchImpl ? N : typeof window < "u" ? U : N;
440
+ const t = (n = this._config) != null && n.useFetchImpl ? N : typeof window < "u" ? O : N;
437
441
  re(this._injector, te([
438
- [b],
442
+ [x],
439
443
  [K, { useClass: t }]
440
444
  ], (s = this._config) == null ? void 0 : s.override));
441
445
  }
442
- }, p(F, "pluginName", "UNIVER_NETWORK_PLUGIN"), F);
443
- X = Ne([
444
- W(1, O),
446
+ }, p(k, "pluginName", "UNIVER_NETWORK_PLUGIN"), k);
447
+ X = Ae([
448
+ W(1, D),
445
449
  W(2, S(H))
446
450
  ], X);
447
- const Me = V("univer.network.socket.service");
448
- class je extends z {
451
+ const je = V("univer.network.socket.service");
452
+ class Be extends J {
449
453
  createSocket(t) {
450
454
  try {
451
455
  const r = new WebSocket(t), n = new ne();
@@ -460,30 +464,30 @@ class je extends z {
460
464
  open$: new m((o) => {
461
465
  const i = (c) => o.next(c);
462
466
  r.addEventListener("open", i), n.add(R(() => r.removeEventListener("open", i)));
463
- }).pipe(x()),
467
+ }).pipe(b()),
464
468
  close$: new m((o) => {
465
469
  const i = (c) => o.next(c);
466
470
  r.addEventListener("close", i), n.add(R(() => r.removeEventListener("close", i)));
467
- }).pipe(x()),
471
+ }).pipe(b()),
468
472
  error$: new m((o) => {
469
473
  const i = (c) => o.next(c);
470
474
  r.addEventListener("error", i), n.add(R(() => r.removeEventListener("error", i)));
471
- }).pipe(x()),
475
+ }).pipe(b()),
472
476
  message$: new m((o) => {
473
477
  const i = (c) => o.next(c);
474
478
  r.addEventListener("message", i), n.add(R(() => r.removeEventListener("message", i)));
475
- }).pipe(x())
479
+ }).pipe(b())
476
480
  };
477
481
  } catch (r) {
478
482
  return console.error(r), null;
479
483
  }
480
484
  }
481
485
  }
482
- const ke = 3, Ae = 1e3, Be = (e) => {
486
+ const Fe = 3, ke = 1e3, Ge = (e) => {
483
487
  var n, s;
484
- const t = (n = e == null ? void 0 : e.maxRetryAttempts) != null ? n : ke, r = (s = e == null ? void 0 : e.delayInterval) != null ? s : Ae;
488
+ const t = (n = e == null ? void 0 : e.maxRetryAttempts) != null ? n : Fe, r = (s = e == null ? void 0 : e.delayInterval) != null ? s : ke;
485
489
  return (o, i) => i(o).pipe(ce({ delay: r, count: t }));
486
- }, Ge = (e) => {
490
+ }, We = (e) => {
487
491
  const t = [], r = /* @__PURE__ */ new Set(), n = () => {
488
492
  var s;
489
493
  for (; r.size < ((s = e == null ? void 0 : e.maxParallel) != null ? s : 1) && t.length > 0; ) {
@@ -496,17 +500,17 @@ const ke = 3, Ae = 1e3, Be = (e) => {
496
500
  next: (a) => i.next(a),
497
501
  error: (a) => i.error(a),
498
502
  complete: () => i.complete()
499
- }), f = () => {
500
- r.delete(c), J(t, c), n();
503
+ }), y = () => {
504
+ r.delete(c), z(t, c), n();
501
505
  };
502
- return t.push(c), n(), f;
506
+ return t.push(c), n(), y;
503
507
  });
504
- }, We = (e) => {
508
+ }, Xe = (e) => {
505
509
  const { errorStatusCodes: t, onAuthError: r } = e;
506
510
  return (s, o) => o(s).pipe(
507
511
  oe((i) => (i instanceof v && t.some((c) => c === i.status) && r(), ie(() => i)))
508
512
  );
509
- }, Fe = (e = 300) => {
513
+ }, Ue = (e = 300) => {
510
514
  let r = () => {
511
515
  };
512
516
  return (n) => new Promise((s) => {
@@ -518,8 +522,8 @@ const ke = 3, Ae = 1e3, Be = (e) => {
518
522
  clearTimeout(o), s(!1);
519
523
  };
520
524
  });
521
- }, Ue = () => (e, t) => t.map((r) => ({ config: r, result: e })), Xe = (e, t = {}) => {
522
- const { isMatch: r, getParamsFromRequest: n, mergeParamsToRequest: s } = e, { fetchCheck: o = Fe(300), distributeResult: i = Ue() } = t, c = [], f = (a) => a.map((h) => h.config);
525
+ }, Oe = () => (e, t) => t.map((r) => ({ config: r, result: e })), Ve = (e, t = {}) => {
526
+ const { isMatch: r, getParamsFromRequest: n, mergeParamsToRequest: s } = e, { fetchCheck: o = Ue(300), distributeResult: i = Oe() } = t, c = [], y = (a) => a.map((h) => h.config);
523
527
  return (a, h) => r(a) ? new m((l) => {
524
528
  const w = n(a);
525
529
  c.push({
@@ -527,32 +531,32 @@ const ke = 3, Ae = 1e3, Be = (e) => {
527
531
  error: (u) => l.error(u),
528
532
  config: w
529
533
  });
530
- const d = f(c);
534
+ const d = y(c);
531
535
  o(a).then((u) => {
532
536
  if (u) {
533
- const y = [];
537
+ const f = [];
534
538
  d.forEach((g) => {
535
539
  const _ = c.findIndex((E) => E.config === g);
536
540
  if (_ >= 0) {
537
541
  const [E] = c.splice(_, 1);
538
- y.push(E);
542
+ f.push(E);
539
543
  }
540
544
  }), h(s(d, a)).subscribe({
541
545
  next: (g) => {
542
546
  if (g.type === Y.Response) {
543
547
  const _ = g.body, E = i(_, d);
544
- y.forEach((k) => {
545
- const $ = E.find((A) => A.config === k.config);
546
- if ($) {
547
- const A = new D({
548
- body: $.result,
548
+ f.forEach((A) => {
549
+ const q = E.find((F) => F.config === A.config);
550
+ if (q) {
551
+ const F = new $({
552
+ body: q.result,
549
553
  headers: g.headers,
550
554
  status: g.status,
551
555
  statusText: g.statusText
552
556
  });
553
- k.next(A);
557
+ A.next(F);
554
558
  } else
555
- k.error("batch error");
559
+ A.error("batch error");
556
560
  });
557
561
  }
558
562
  },
@@ -564,23 +568,23 @@ const ke = 3, Ae = 1e3, Be = (e) => {
564
568
  }) : h(a);
565
569
  };
566
570
  export {
567
- We as AuthInterceptorFactory,
571
+ Xe as AuthInterceptorFactory,
568
572
  N as FetchHTTPImplementation,
569
573
  Y as HTTPEventType,
570
574
  I as HTTPHeaders,
571
575
  ye as HTTPProgress,
572
576
  G as HTTPRequest,
573
- D as HTTPResponse,
577
+ $ as HTTPResponse,
574
578
  v as HTTPResponseError,
575
- b as HTTPService,
579
+ x as HTTPService,
576
580
  L as HTTPStatusCode,
577
581
  K as IHTTPImplementation,
578
- Me as ISocketService,
579
- Xe as MergeInterceptorFactory,
580
- fe as ResponseHeader,
581
- Be as RetryInterceptorFactory,
582
- Ge as ThresholdInterceptorFactory,
582
+ je as ISocketService,
583
+ Ve as MergeInterceptorFactory,
584
+ we as ResponseHeader,
585
+ Ge as RetryInterceptorFactory,
586
+ We as ThresholdInterceptorFactory,
583
587
  X as UniverNetworkPlugin,
584
- je as WebSocketService,
585
- U as XHRHTTPImplementation
588
+ Be as WebSocketService,
589
+ O as XHRHTTPImplementation
586
590
  };
@@ -13,7 +13,7 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
- export { UniverNetworkPlugin } from './plugin';
16
+ export { type IUniverNetworkPluginConfig, UniverNetworkPlugin } from './plugin';
17
17
  export { HTTPHeaders } from './services/http/headers';
18
18
  export { HTTPService } from './services/http/http.service';
19
19
  export { IHTTPImplementation } from './services/http/implementations/implementation';
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Copyright 2023-present DreamNum Co., Ltd.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ export {};
@@ -17,6 +17,12 @@ interface IHeadersConstructorProps {
17
17
  [key: string]: string | number | boolean;
18
18
  }
19
19
  export declare const ApplicationJSONType = "application/json";
20
+ /**
21
+ * Check if the content type is application/json
22
+ * "application/json" or "application/json; charset=utf-8" or ["application/json"]
23
+ * @param contentType
24
+ */
25
+ export declare function isApplicationJSONType(contentType: string | string[]): boolean;
20
26
  /**
21
27
  * It wraps headers of HTTP requests' and responses' headers.
22
28
  */
@@ -27,7 +33,7 @@ export declare class HTTPHeaders {
27
33
  has(key: string): boolean;
28
34
  get(key: string): string[] | null;
29
35
  set(key: string, value: string | number | boolean): void;
30
- toHeadersInit(): HeadersInit;
36
+ toHeadersInit(body?: any): HeadersInit;
31
37
  private _setHeader;
32
38
  private _handleHeadersString;
33
39
  private _handleHeadersConstructorProps;
@@ -24,6 +24,6 @@ export declare class HTTPRequest {
24
24
  readonly uid: number;
25
25
  constructor(method: HTTPRequestMethod, url: string, requestParams?: IHTTPRequestParams | undefined);
26
26
  getUrlWithParams(): string;
27
- getBody(): string | null;
27
+ getBody(): string | FormData | null;
28
28
  getHeadersInit(): HeadersInit;
29
29
  }
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 fe=Object.defineProperty;var ye=(c,a,m)=>a in c?fe(c,a,{enumerable:!0,configurable:!0,writable:!0,value:m}):c[a]=m;var w=(c,a,m)=>ye(c,typeof a!="symbol"?a+"":a,m);var A;const M="application/json";class L{constructor(n){w(this,"_headers",new Map);typeof n=="string"?this._handleHeadersString(n):n instanceof Headers?this._handleHeaders(n):n&&this._handleHeadersConstructorProps(n)}forEach(n){this._headers.forEach((t,r)=>n(r,t))}has(n){return!!this._headers.has(n.toLowerCase())}get(n){const t=n.toLowerCase();return this._headers.has(t)?this._headers.get(t):null}set(n,t){this._setHeader(n,t)}toHeadersInit(){var t,r;const n={};return this._headers.forEach((s,i)=>{n[i]=s.join(",")}),(t=n.accept)!=null||(n.accept="application/json, text/plain, */*"),(r=n["content-type"])!=null||(n["content-type"]="application/json;charset=UTF-8"),n}_setHeader(n,t){const r=n.toLowerCase();this._headers.has(r)?this._headers.get(r).push(t.toString()):this._headers.set(r,[t.toString()])}_handleHeadersString(n){n.split(`
2
- `).forEach(t=>{const[r,s]=t.split(":");r&&s&&this._setHeader(r,s)})}_handleHeadersConstructorProps(n){Object.entries(n).forEach(([t,r])=>this._setHeader(t,r))}_handleHeaders(n){n.forEach((t,r)=>this._setHeader(r,t))}}const k=a.createIdentifier("network.http-implementation");class ${constructor(n){this.params=n}toString(){return this.params?Object.keys(this.params).map(n=>{const t=this.params[n];return Array.isArray(t)?t.map(r=>`${n}=${r}`).join("&"):`${n}=${t}`}).join("&"):""}}let W=0;class O{constructor(n,t,r){w(this,"uid",W++);this.method=n,this.url=t,this.requestParams=r}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var t,r;const n=(r=(t=this.requestParams)==null?void 0:t.params)==null?void 0:r.toString();return n?`${this.url}${this.url.includes("?")?"&":"?"}${n}`:this.url}getBody(){var r,s;const n=(r=this.headers.get("Content-Type"))!=null?r:M,t=(s=this.requestParams)==null?void 0:s.body;return n===M&&t&&typeof t=="object"?JSON.stringify(t):t?`${t}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}var V=Object.getOwnPropertyDescriptor,z=(e,n,t,r)=>{for(var s=r>1?void 0:r?V(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},J=(e,n)=>(t,r)=>n(t,r,e);c.HTTPService=class extends a.Disposable{constructor(t){super();w(this,"_interceptors",[]);w(this,"_pipe");this._http=t}registerHTTPInterceptor(t){if(this._interceptors.indexOf(t)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(t),this._interceptors=this._interceptors.sort((r,s)=>{var i,o;return((i=r.priority)!=null?i:0)-((o=s.priority)!=null?o:0)}),this._pipe=null,a.toDisposable(()=>a.remove(this._interceptors,t))}get(t,r){return this._request("GET",t,r)}post(t,r){return this._request("POST",t,r)}put(t,r){return this._request("PUT",t,r)}delete(t,r){return this._request("DELETE",t,r)}patch(t,r){return this._request("PATCH",t,r)}getSSE(t,r,s){var u,g;const i=new L(s==null?void 0:s.headers),o=new $(s==null?void 0:s.params),l=new O(t,r,{headers:i,params:o,withCredentials:(u=s==null?void 0:s.withCredentials)!=null?u:!1,reportProgress:!0,responseType:(g=s==null?void 0:s.responseType)!=null?g:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body});return m.of(l).pipe(_.concatMap(h=>this._runInterceptorsAndImplementation(h)))}async _request(t,r,s){var h,d;const i=new L(s==null?void 0:s.headers),o=new $(s==null?void 0:s.params),l=new O(t,r,{headers:i,params:o,withCredentials:(h=s==null?void 0:s.withCredentials)!=null?h:!1,responseType:(d=s==null?void 0:s.responseType)!=null?d:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body}),u=m.of(l).pipe(_.concatMap(p=>this._runInterceptorsAndImplementation(p)));return await m.firstValueFrom(u)}_runInterceptorsAndImplementation(t){return this._pipe||(this._pipe=this._interceptors.map(r=>r.interceptor).reduceRight((r,s)=>K(r,s),(r,s)=>s(r))),this._pipe(t,r=>this._http.send(r))}},c.HTTPService=z([J(0,k)],c.HTTPService);function K(e,n){return(t,r)=>n(t,s=>e(s,r))}const Y=200,Q=300;var F=(e=>(e[e.Continue=100]="Continue",e[e.SwitchingProtocols=101]="SwitchingProtocols",e[e.Processing=102]="Processing",e[e.EarlyHints=103]="EarlyHints",e[e.Ok=200]="Ok",e[e.Created=201]="Created",e[e.Accepted=202]="Accepted",e[e.NonAuthoritativeInformation=203]="NonAuthoritativeInformation",e[e.NoContent=204]="NoContent",e[e.ResetContent=205]="ResetContent",e[e.PartialContent=206]="PartialContent",e[e.MultiStatus=207]="MultiStatus",e[e.AlreadyReported=208]="AlreadyReported",e[e.ImUsed=226]="ImUsed",e[e.MultipleChoices=300]="MultipleChoices",e[e.MovedPermanently=301]="MovedPermanently",e[e.Found=302]="Found",e[e.SeeOther=303]="SeeOther",e[e.NotModified=304]="NotModified",e[e.UseProxy=305]="UseProxy",e[e.Unused=306]="Unused",e[e.TemporaryRedirect=307]="TemporaryRedirect",e[e.PermanentRedirect=308]="PermanentRedirect",e[e.BadRequest=400]="BadRequest",e[e.Unauthorized=401]="Unauthorized",e[e.PaymentRequired=402]="PaymentRequired",e[e.Forbidden=403]="Forbidden",e[e.NotFound=404]="NotFound",e[e.MethodNotAllowed=405]="MethodNotAllowed",e[e.NotAcceptable=406]="NotAcceptable",e[e.ProxyAuthenticationRequired=407]="ProxyAuthenticationRequired",e[e.RequestTimeout=408]="RequestTimeout",e[e.Conflict=409]="Conflict",e[e.Gone=410]="Gone",e[e.LengthRequired=411]="LengthRequired",e[e.PreconditionFailed=412]="PreconditionFailed",e[e.PayloadTooLarge=413]="PayloadTooLarge",e[e.UriTooLong=414]="UriTooLong",e[e.UnsupportedMediaType=415]="UnsupportedMediaType",e[e.RangeNotSatisfiable=416]="RangeNotSatisfiable",e[e.ExpectationFailed=417]="ExpectationFailed",e[e.ImATeapot=418]="ImATeapot",e[e.MisdirectedRequest=421]="MisdirectedRequest",e[e.UnprocessableEntity=422]="UnprocessableEntity",e[e.Locked=423]="Locked",e[e.FailedDependency=424]="FailedDependency",e[e.TooEarly=425]="TooEarly",e[e.UpgradeRequired=426]="UpgradeRequired",e[e.PreconditionRequired=428]="PreconditionRequired",e[e.TooManyRequests=429]="TooManyRequests",e[e.RequestHeaderFieldsTooLarge=431]="RequestHeaderFieldsTooLarge",e[e.UnavailableForLegalReasons=451]="UnavailableForLegalReasons",e[e.InternalServerError=500]="InternalServerError",e[e.NotImplemented=501]="NotImplemented",e[e.BadGateway=502]="BadGateway",e[e.ServiceUnavailable=503]="ServiceUnavailable",e[e.GatewayTimeout=504]="GatewayTimeout",e[e.HttpVersionNotSupported=505]="HttpVersionNotSupported",e[e.VariantAlsoNegotiates=506]="VariantAlsoNegotiates",e[e.InsufficientStorage=507]="InsufficientStorage",e[e.LoopDetected=508]="LoopDetected",e[e.NotExtended=510]="NotExtended",e[e.NetworkAuthenticationRequired=511]="NetworkAuthenticationRequired",e))(F||{}),U=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(U||{});class N{constructor({body:n,headers:t,status:r,statusText:s}){w(this,"type",1);w(this,"body");w(this,"headers");w(this,"status");w(this,"statusText");this.body=n,this.headers=t,this.status=r,this.statusText=s}}class j{constructor(n,t,r){w(this,"type",0);this.total=n,this.loaded=t,this.partialText=r}}class x{constructor(n,t,r){this.headers=n,this.status=t,this.statusText=r}}class R{constructor({request:n,headers:t,status:r,statusText:s,error:i}){w(this,"request");w(this,"headers");w(this,"status");w(this,"statusText");w(this,"error");this.request=n,this.headers=t,this.status=r,this.statusText=s,this.error=i}}function B(e){return{method:e.method,headers:e.getHeadersInit(),body:e.getBody(),credentials:e.withCredentials?"include":void 0}}var Z=Object.getOwnPropertyDescriptor,P=(e,n,t,r)=>{for(var s=r>1?void 0:r?Z(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},H=(e,n)=>(t,r)=>n(t,r,e);c.FetchHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new m.Observable(t=>{const r=new AbortController;return this._send(n,t,r).catch(s=>{t.error(new R({error:s,request:n}))}),()=>r.abort()})}async _send(n,t,r){var h,d;let s;try{const p=B(n),v=n.getUrlWithParams(),y=fetch(v,{signal:r.signal,...p});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${v} with params ${p}`),s=await y}catch(p){const v=new R({request:n,error:p,status:(h=p.status)!=null?h:0,statusText:(d=p.statusText)!=null?d:"Unknown Error",headers:p.headers});this._logService.error("[FetchHTTPImplementation]: network error",v),t.error(v);return}const i=new L(s.headers),o=s.status,l=s.statusText;let u=null;if(s.body&&(u=await this._readBody(n,s,t)),o>=F.Ok&&o<F.MultipleChoices)t.next(new N({body:u,headers:i,status:o,statusText:l}));else{const p=new R({request:n,error:u,status:o,statusText:l,headers:i});this._logService.error("[FetchHTTPImplementation]: network error",p),t.error(p)}t.complete()}async _readBody(n,t,r){var v,y;const s=[],i=t.body.getReader(),o=t.headers.get("content-length");let l=0;const u=(v=n.requestParams)==null?void 0:v.reportProgress,g=n.responseType;let h,d;for(;;){const{done:I,value:f}=await i.read();if(I)break;s.push(f),l+=f.length,u&&g==="text"&&(h=(h!=null?h:"")+(d!=null?d:d=new TextDecoder).decode(f,{stream:!0}),r.next(new j(o?Number.parseInt(o,10):void 0,l,h)))}const p=S(s,l);try{const I=(y=t.headers.get("content-type"))!=null?y:"";return T(n,p,I)}catch(I){const f=new R({request:n,error:I,status:t.status,statusText:t.statusText,headers:new L(t.headers)});return this._logService.error("[FetchHTTPImplementation]: network error",f),r.error(f),null}}},c.FetchHTTPImplementation=P([H(0,a.ILogService)],c.FetchHTTPImplementation);function S(e,n){const t=new Uint8Array(n);let r=0;for(const s of e)t.set(s,r),r+=s.length;return t}const C=/^\)\]\}',?\n/;function T(e,n,t){switch(e.responseType){case"json":const r=new TextDecoder().decode(n).replace(C,"");return r===""?null:JSON.parse(r);case"text":return new TextDecoder().decode(n);case"blob":return new Blob([n],{type:t});case"arraybuffer":return n.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}var ee=Object.getOwnPropertyDescriptor,te=(e,n,t,r)=>{for(var s=r>1?void 0:r?ee(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},re=(e,n)=>(t,r)=>n(t,r,e);c.XHRHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new m.Observable(t=>{const r=new XMLHttpRequest,s=n.getUrlWithParams(),i=B(n);r.open(n.method,s),n.withCredentials&&(r.withCredentials=!0),i.headers&&Object.entries(i.headers).forEach(([h,d])=>r.setRequestHeader(h,d));const o=()=>{const h=r.statusText||"OK",d=new L(r.getAllResponseHeaders());return new x(d,r.status,h)},l=()=>{const{headers:h,statusText:d,status:p}=o(),{responseType:v}=n;let y=null,I=null;p!==F.NoContent&&(y=typeof r.response>"u"?r.responseText:r.response);let f=p>=Y&&p<Q;if(v==="json"&&typeof y=="string"){const b=y;try{y=y?JSON.parse(y):null}catch(E){f=!1,y=b,I=E}}if(f)t.next(new N({body:y,headers:h,status:p,statusText:d}));else{const b=new R({request:n,error:I,headers:h,status:p,statusText:d});this._logService.error("[XHRHTTPImplementation]: network error",b),t.error(b)}},u=h=>{const d=new R({request:n,error:h,status:r.status||0,statusText:r.statusText||"Unknown Error",headers:o().headers});this._logService.error("[XHRHTTPImplementation]: network error",d),t.error(d)};r.addEventListener("load",l),r.addEventListener("error",u),r.addEventListener("abort",u),r.addEventListener("timeout",u);const g=n.getBody();return r.send(g),this._logService.debug("[XHRHTTPImplementation]",`sending request to url ${s} with params ${i}`),()=>{r.readyState!==r.DONE&&r.abort(),r.removeEventListener("load",l),r.removeEventListener("error",u),r.removeEventListener("abort",u),r.removeEventListener("timeout",u)}})}},c.XHRHTTPImplementation=te([re(0,a.ILogService)],c.XHRHTTPImplementation);var ne=Object.getOwnPropertyDescriptor,se=(e,n,t,r)=>{for(var s=r>1?void 0:r?ne(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},X=(e,n)=>(t,r)=>n(t,r,e);c.UniverNetworkPlugin=(A=class extends a.Plugin{constructor(n=void 0,t,r){super(),this._config=n,this._logger=t,this._injector=r}onStarting(){var r,s,i;if(this._injector.get(c.HTTPService,a.Quantity.OPTIONAL,a.LookUp.SKIP_SELF)&&!((r=this._config)!=null&&r.forceUseNewInstance)){this._logger.warn("[UniverNetworkPlugin]",'HTTPService is already registered in an ancestor interceptor. Skipping registration. If you want to force a new instance, set "forceUseNewInstance" to true in the plugin configuration.');return}const t=(s=this._config)!=null&&s.useFetchImpl?c.FetchHTTPImplementation:typeof window<"u"?c.XHRHTTPImplementation:c.FetchHTTPImplementation;a.registerDependencies(this._injector,a.mergeOverrideWithDependencies([[c.HTTPService],[k,{useClass:t}]],(i=this._config)==null?void 0:i.override))}},w(A,"pluginName","UNIVER_NETWORK_PLUGIN"),A),c.UniverNetworkPlugin=se([X(1,a.ILogService),X(2,a.Inject(a.Injector))],c.UniverNetworkPlugin);const ie=a.createIdentifier("univer.network.socket.service");class oe extends a.Disposable{createSocket(n){try{const t=new WebSocket(n),r=new a.DisposableCollection;return{URL:n,close:(i,o)=>{t.close(i,o),r.dispose()},send:i=>{t.send(i)},open$:new m.Observable(i=>{const o=l=>i.next(l);t.addEventListener("open",o),r.add(a.toDisposable(()=>t.removeEventListener("open",o)))}).pipe(_.share()),close$:new m.Observable(i=>{const o=l=>i.next(l);t.addEventListener("close",o),r.add(a.toDisposable(()=>t.removeEventListener("close",o)))}).pipe(_.share()),error$:new m.Observable(i=>{const o=l=>i.next(l);t.addEventListener("error",o),r.add(a.toDisposable(()=>t.removeEventListener("error",o)))}).pipe(_.share()),message$:new m.Observable(i=>{const o=l=>i.next(l);t.addEventListener("message",o),r.add(a.toDisposable(()=>t.removeEventListener("message",o)))}).pipe(_.share())}}catch(t){return console.error(t),null}}}const ce=3,ae=1e3,le=e=>{var r,s;const n=(r=e==null?void 0:e.maxRetryAttempts)!=null?r:ce,t=(s=e==null?void 0:e.delayInterval)!=null?s:ae;return(i,o)=>o(i).pipe(_.retry({delay:t,count:n}))},he=e=>{const n=[],t=new Set,r=()=>{var s;for(;t.size<((s=e==null?void 0:e.maxParallel)!=null?s:1)&&n.length>0;){const i=n.shift();t.add(i),i()}};return(s,i)=>new m.Observable(o=>{const l=()=>i(s).subscribe({next:g=>o.next(g),error:g=>o.error(g),complete:()=>o.complete()}),u=()=>{t.delete(l),a.remove(n,l),r()};return n.push(l),r(),u})},de=e=>{const{errorStatusCodes:n,onAuthError:t}=e;return(s,i)=>i(s).pipe(m.catchError(o=>(o instanceof R&&n.some(l=>l===o.status)&&t(),m.throwError(()=>o))))},pe=(e=300)=>{let t=()=>{};return r=>new Promise(s=>{t();const i=setTimeout(()=>{s(!0)},e);t=()=>{clearTimeout(i),s(!1)}})},ue=()=>(e,n)=>n.map(t=>({config:t,result:e})),ge=(e,n={})=>{const{isMatch:t,getParamsFromRequest:r,mergeParamsToRequest:s}=e,{fetchCheck:i=pe(300),distributeResult:o=ue()}=n,l=[],u=g=>g.map(h=>h.config);return(g,h)=>t(g)?new m.Observable(d=>{const p=r(g);l.push({next:y=>d.next(y),error:y=>d.error(y),config:p});const v=u(l);i(g).then(y=>{if(y){const I=[];v.forEach(f=>{const b=l.findIndex(E=>E.config===f);if(b>=0){const[E]=l.splice(b,1);I.push(E)}}),h(s(v,g)).subscribe({next:f=>{if(f.type===U.Response){const b=f.body,E=o(b,v);I.forEach(D=>{const G=E.find(q=>q.config===D.config);if(G){const q=new N({body:G.result,headers:f.headers,status:f.status,statusText:f.statusText});D.next(q)}else D.error("batch error")})}},complete:()=>d.complete(),error:f=>d.error(f)})}})}):h(g)};c.AuthInterceptorFactory=de,c.HTTPEventType=U,c.HTTPHeaders=L,c.HTTPProgress=j,c.HTTPRequest=O,c.HTTPResponse=N,c.HTTPResponseError=R,c.HTTPStatusCode=F,c.IHTTPImplementation=k,c.ISocketService=ie,c.MergeInterceptorFactory=ge,c.ResponseHeader=x,c.RetryInterceptorFactory=le,c.ThresholdInterceptorFactory=he,c.WebSocketService=oe,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})});
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,y,_){"use strict";var me=Object.defineProperty;var ye=(c,a,y)=>a in c?me(c,a,{enumerable:!0,configurable:!0,writable:!0,value:y}):c[a]=y;var w=(c,a,y)=>ye(c,typeof a!="symbol"?a+"":a,y);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){w(this,"_headers",new Map);typeof n=="string"?this._handleHeadersString(n):n instanceof Headers?this._handleHeaders(n):n&&this._handleHeadersConstructorProps(n)}forEach(n){this._headers.forEach((t,r)=>n(r,t))}has(n){return!!this._headers.has(n.toLowerCase())}get(n){const t=n.toLowerCase();return this._headers.has(t)?this._headers.get(t):null}set(n,t){this._setHeader(n,t)}toHeadersInit(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){w(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();w(this,"_interceptors",[]);w(this,"_pipe");this._http=t}registerHTTPInterceptor(t){if(this._interceptors.indexOf(t)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(t),this._interceptors=this._interceptors.sort((r,s)=>{var i,o;return((i=r.priority)!=null?i:0)-((o=s.priority)!=null?o:0)}),this._pipe=null,a.toDisposable(()=>a.remove(this._interceptors,t))}get(t,r){return this._request("GET",t,r)}post(t,r){return this._request("POST",t,r)}put(t,r){return this._request("PUT",t,r)}delete(t,r){return this._request("DELETE",t,r)}patch(t,r){return this._request("PATCH",t,r)}getSSE(t,r,s){var u,g;const i=new L(s==null?void 0:s.headers),o=new $(s==null?void 0:s.params),l=new O(t,r,{headers:i,params:o,withCredentials:(u=s==null?void 0:s.withCredentials)!=null?u:!1,reportProgress:!0,responseType:(g=s==null?void 0:s.responseType)!=null?g:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body});return y.of(l).pipe(_.concatMap(h=>this._runInterceptorsAndImplementation(h)))}async _request(t,r,s){var h,d;const i=new L(s==null?void 0:s.headers),o=new $(s==null?void 0:s.params),l=new O(t,r,{headers:i,params:o,withCredentials:(h=s==null?void 0:s.withCredentials)!=null?h:!1,responseType:(d=s==null?void 0:s.responseType)!=null?d:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body}),u=y.of(l).pipe(_.concatMap(p=>this._runInterceptorsAndImplementation(p)));return await y.firstValueFrom(u)}_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}){w(this,"type",1);w(this,"body");w(this,"headers");w(this,"status");w(this,"statusText");this.body=n,this.headers=t,this.status=r,this.statusText=s}}class j{constructor(n,t,r){w(this,"type",0);this.total=n,this.loaded=t,this.partialText=r}}class x{constructor(n,t,r){this.headers=n,this.status=t,this.statusText=r}}class R{constructor({request:n,headers:t,status:r,statusText:s,error:i}){w(this,"request");w(this,"headers");w(this,"status");w(this,"statusText");w(this,"error");this.request=n,this.headers=t,this.status=r,this.statusText=s,this.error=i}}function B(e){return{method:e.method,headers:e.getHeadersInit(),body:e.getBody(),credentials:e.withCredentials?"include":void 0}}var 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 y.Observable(t=>{const r=new AbortController;return this._send(n,t,r).catch(s=>{t.error(new R({error:s,request:n}))}),()=>r.abort()})}async _send(n,t,r){var h,d;let s;try{const p=B(n),v=n.getUrlWithParams(),m=fetch(v,{signal:r.signal,...p});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${v} with params ${p}`),s=await m}catch(p){const v=new R({request:n,error:p,status:(h=p.status)!=null?h:0,statusText:(d=p.statusText)!=null?d:"Unknown Error",headers:p.headers});this._logService.error("[FetchHTTPImplementation]: network error",v),t.error(v);return}const i=new L(s.headers),o=s.status,l=s.statusText;let u=null;if(s.body&&(u=await this._readBody(n,s,t)),o>=F.Ok&&o<F.MultipleChoices)t.next(new N({body:u,headers:i,status:o,statusText:l}));else{const p=new R({request:n,error:u,status:o,statusText:l,headers:i});this._logService.error("[FetchHTTPImplementation]: network error",p),t.error(p)}t.complete()}async _readBody(n,t,r){var v,m;const s=[],i=t.body.getReader(),o=t.headers.get("content-length");let l=0;const u=(v=n.requestParams)==null?void 0:v.reportProgress,g=n.responseType;let h,d;for(;;){const{done:I,value:f}=await i.read();if(I)break;s.push(f),l+=f.length,u&&g==="text"&&(h=(h!=null?h:"")+(d!=null?d:d=new TextDecoder).decode(f,{stream:!0}),r.next(new j(o?Number.parseInt(o,10):void 0,l,h)))}const p=C(s,l);try{const I=(m=t.headers.get("content-type"))!=null?m:"";return ee(n,p,I)}catch(I){const f=new R({request:n,error:I,status:t.status,statusText:t.statusText,headers:new L(t.headers)});return this._logService.error("[FetchHTTPImplementation]: network error",f),r.error(f),null}}},c.FetchHTTPImplementation=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 y.Observable(t=>{const r=new XMLHttpRequest,s=n.getUrlWithParams(),i=B(n);r.open(n.method,s),n.withCredentials&&(r.withCredentials=!0),i.headers&&Object.entries(i.headers).forEach(([h,d])=>r.setRequestHeader(h,d));const o=()=>{const h=r.statusText||"OK",d=new L(r.getAllResponseHeaders());return new x(d,r.status,h)},l=()=>{const{headers:h,statusText:d,status:p}=o(),{responseType:v}=n;let m=null,I=null;p!==F.NoContent&&(m=typeof r.response>"u"?r.responseText:r.response);let f=p>=Q&&p<Z;if(v==="json"&&typeof m=="string"){const b=m;try{m=m?JSON.parse(m):null}catch(E){f=!1,m=b,I=E}}if(f)t.next(new N({body:m,headers:h,status:p,statusText:d}));else{const b=new R({request:n,error:I,headers:h,status:p,statusText:d});this._logService.error("[XHRHTTPImplementation]: network error",b),t.error(b)}},u=h=>{const d=new R({request:n,error:h,status:r.status||0,statusText:r.statusText||"Unknown Error",headers:o().headers});this._logService.error("[XHRHTTPImplementation]: network error",d),t.error(d)};r.addEventListener("load",l),r.addEventListener("error",u),r.addEventListener("abort",u),r.addEventListener("timeout",u);const g=n.getBody();return r.send(g),this._logService.debug("[XHRHTTPImplementation]",`sending request to url ${s} with params ${i}`),()=>{r.readyState!==r.DONE&&r.abort(),r.removeEventListener("load",l),r.removeEventListener("error",u),r.removeEventListener("abort",u),r.removeEventListener("timeout",u)}})}},c.XHRHTTPImplementation=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))}},w(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 y.Observable(i=>{const o=l=>i.next(l);t.addEventListener("open",o),r.add(a.toDisposable(()=>t.removeEventListener("open",o)))}).pipe(_.share()),close$:new y.Observable(i=>{const o=l=>i.next(l);t.addEventListener("close",o),r.add(a.toDisposable(()=>t.removeEventListener("close",o)))}).pipe(_.share()),error$:new y.Observable(i=>{const o=l=>i.next(l);t.addEventListener("error",o),r.add(a.toDisposable(()=>t.removeEventListener("error",o)))}).pipe(_.share()),message$:new y.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 y.Observable(o=>{const l=()=>i(s).subscribe({next:g=>o.next(g),error:g=>o.error(g),complete:()=>o.complete()}),u=()=>{t.delete(l),a.remove(n,l),r()};return n.push(l),r(),u})},pe=e=>{const{errorStatusCodes:n,onAuthError:t}=e;return(s,i)=>i(s).pipe(y.catchError(o=>(o instanceof R&&n.some(l=>l===o.status)&&t(),y.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=[],u=g=>g.map(h=>h.config);return(g,h)=>t(g)?new y.Observable(d=>{const p=r(g);l.push({next:m=>d.next(m),error:m=>d.error(m),config:p});const v=u(l);i(g).then(m=>{if(m){const I=[];v.forEach(f=>{const b=l.findIndex(E=>E.config===f);if(b>=0){const[E]=l.splice(b,1);I.push(E)}}),h(s(v,g)).subscribe({next:f=>{if(f.type===U.Response){const b=f.body,E=o(b,v);I.forEach(q=>{const G=E.find(M=>M.config===q.config);if(G){const M=new N({body:G.result,headers:f.headers,status:f.status,statusText:f.statusText});q.next(M)}else q.error("batch error")})}},complete:()=>d.complete(),error:f=>d.error(f)})}})}):h(g)};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.6.9",
3
+ "version": "0.6.10-alpha.0",
4
4
  "private": false,
5
5
  "author": "DreamNum <developer@univer.ai>",
6
6
  "license": "Apache-2.0",
@@ -52,14 +52,14 @@
52
52
  "rxjs": ">=7.0.0"
53
53
  },
54
54
  "dependencies": {
55
- "@univerjs/core": "0.6.9"
55
+ "@univerjs/core": "0.6.10-alpha.0"
56
56
  },
57
57
  "devDependencies": {
58
58
  "rxjs": "^7.8.1",
59
59
  "typescript": "^5.8.2",
60
60
  "vite": "^6.2.3",
61
61
  "vitest": "^3.0.9",
62
- "@univerjs-infra/shared": "0.6.9"
62
+ "@univerjs-infra/shared": "0.6.10-alpha.0"
63
63
  },
64
64
  "scripts": {
65
65
  "test": "vitest run",