@univerjs/network 0.5.3 → 0.5.4

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/facade.js CHANGED
@@ -1 +1 @@
1
- "use strict";const i=require("@univerjs/core"),o=require("@univerjs/network");var _=Object.defineProperty,u=Object.getOwnPropertyDescriptor,a=(t,e,r,c)=>{for(var s=c>1?void 0:c?u(e,r):e,n=t.length-1,h;n>=0;n--)(h=t[n])&&(s=(c?h(e,r,s):h(s))||s);return c&&s&&_(e,r,s),s},v=(t,e)=>(r,c)=>e(r,c,t);let p=class extends i.FBase{constructor(t,e){super(),this._injector=t,this._httpService=e}get(t,e){return this._httpService.get(t,e)}post(t,e){return this._httpService.post(t,e)}put(t,e){return this._httpService.put(t,e)}delete(t,e){return this._httpService.delete(t,e)}patch(t,e){return this._httpService.patch(t,e)}getSSE(t,e,r){return this._httpService.getSSE(t,e,r)}};p=a([v(0,i.Inject(i.Injector)),v(1,i.Inject(o.HTTPService))],p);class S extends i.FUniver{getNetwork(){return this._injector.createInstance(p)}}i.FUniver.extend(S);
1
+ "use strict";const c=require("@univerjs/core"),v=require("@univerjs/network");var _=Object.defineProperty,o=Object.getOwnPropertyDescriptor,a=(t,e,r,s)=>{for(var n=s>1?void 0:s?o(e,r):e,i=t.length-1,h;i>=0;i--)(h=t[i])&&(n=(s?h(e,r,n):h(n))||n);return s&&n&&_(e,r,n),n},u=(t,e)=>(r,s)=>e(r,s,t);let p=class extends c.FBase{constructor(t,e){super(),this._injector=t,this._httpService=e}get(t,e){return this._httpService.get(t,e)}post(t,e){return this._httpService.post(t,e)}put(t,e){return this._httpService.put(t,e)}delete(t,e){return this._httpService.delete(t,e)}patch(t,e){return this._httpService.patch(t,e)}getSSE(t,e,r){return this._httpService.getSSE(t,e,r)}};p=a([u(0,c.Inject(c.Injector)),u(1,c.Inject(v.HTTPService))],p);class S extends c.FUniver{getNetwork(){return this._injector.createInstance(p)}}c.FUniver.extend(S);
package/lib/cjs/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  "use strict";var G=Object.defineProperty;var W=(e,t,r)=>t in e?G(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var m=(e,t,r)=>W(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("@univerjs/core"),w=require("rxjs"),R=require("rxjs/operators"),j="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 k{constructor(t){this.params=t}toString(){return this.params?Object.keys(this.params).map(t=>`${t}=${this.params[t]}`).join("&"):""}}let V=0;class U{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:j,r=(s=this.requestParams)==null?void 0:s.body;return t===j&&r&&typeof r=="object"?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}var P=Object.defineProperty,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=(n?i(t,r,s):i(s))||s);return n&&s&&P(t,r,s),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 k(s==null?void 0:s.params),c=new U(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 w.of(c).pipe(R.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 k(s==null?void 0:s.params),c=new U(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=w.of(c).pipe(R.concatMap(h=>this._runInterceptorsAndImplementation(h)));return await w.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||{}),D=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(D||{});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 M{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 I{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 H=Object.defineProperty,S=Object.getOwnPropertyDescriptor,C=(e,t,r,n)=>{for(var s=n>1?void 0:n?S(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&H(t,r,s),s},T=(e,t)=>(r,n)=>t(r,n,e);exports.FetchHTTPImplementation=class{constructor(t){this._logService=t}send(t){return new w.Observable(r=>{const n=new AbortController;return this._send(t,r,n).catch(s=>{r.error(new I({error:s,request:t}))}),()=>n.abort()})}async _send(t,r,n){var a,l;let s;try{const h=X(t),y=t.getUrlWithParams(),f=fetch(y,{signal:n.signal,...h});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${y} with params ${h}`),s=await f}catch(h){const y=new I({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",y),r.error(y);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 I({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 y,f;const s=[],o=r.body.getReader(),i=r.headers.get("content-length");let c=0;const d=(y=t.requestParams)==null?void 0:y.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 M(i?Number.parseInt(i,10):void 0,c,a)))}const h=ee(s,c);try{const v=(f=r.headers.get("content-type"))!=null?f:"";return te(t,h,v)}catch(v){const g=new I({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=C([T(0,p.ILogService)],exports.FetchHTTPImplementation);function ee(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 re=/^\)\]\}',?\n/;function te(e,t,r){switch(e.responseType){case"json":const n=new TextDecoder().decode(t).replace(re,"");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 ne=Object.defineProperty,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=(n?i(t,r,s):i(s))||s);return n&&s&&ne(t,r,s),s},ie=(e,t)=>(r,n)=>t(r,n,e);exports.XHRHTTPImplementation=class{constructor(t){this._logService=t}send(t){return new w.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:y}=t;let f=null,v=null;h!==x.NoContent&&(f=typeof n.response>"u"?n.responseText:n.response);let g=h>=Q&&h<Z;if(y==="json"&&typeof f=="string"){const b=f;try{f=f?JSON.parse(f):null}catch(_){g=!1,f=b,v=_}}if(g)r.next(new L({body:f,headers:a,status:h,statusText:l}));else{const b=new I({request:t,error:v,headers:a,status:h,statusText:l});this._logService.error("[XHRHTTPImplementation]: network error",b),r.error(b)}},d=a=>{const l=new I({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=oe([ie(0,p.ILogService)],exports.XHRHTTPImplementation);var ce=Object.defineProperty,ae=Object.getOwnPropertyDescriptor,le=(e,t,r,n)=>{for(var s=n>1?void 0:n?ae(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&ce(t,r,s),s},$=(e,t)=>(r,n)=>t(r,n,e),N;exports.UniverNetworkPlugin=(N=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(N,"pluginName","UNIVER_NETWORK_PLUGIN"),N);exports.UniverNetworkPlugin=le([$(1,p.ILogService),$(2,p.Inject(p.Injector))],exports.UniverNetworkPlugin);const he=p.createIdentifier("univer.network.socket.service");class pe 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 w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("open",i),n.add(p.toDisposable(()=>r.removeEventListener("open",i)))}).pipe(R.share()),close$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("close",i),n.add(p.toDisposable(()=>r.removeEventListener("close",i)))}).pipe(R.share()),error$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("error",i),n.add(p.toDisposable(()=>r.removeEventListener("error",i)))}).pipe(R.share()),message$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("message",i),n.add(p.toDisposable(()=>r.removeEventListener("message",i)))}).pipe(R.share())}}catch(r){return console.error(r),null}}}const de=3,ue=1e3,ge=e=>{var n,s;const t=(n=e==null?void 0:e.maxRetryAttempts)!=null?n:de,r=(s=e==null?void 0:e.delayInterval)!=null?s:ue;return(o,i)=>i(o).pipe(R.retry({delay:r,count:t}))},fe=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 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(t,c),n()};return t.push(c),n(),d})},me=e=>{const{errorStatusCodes:t,onAuthError:r}=e;return(s,o)=>o(s).pipe(w.catchError(i=>(i instanceof I&&t.some(c=>c===i.status)&&r(),w.throwError(()=>i))))},ye=(e=300)=>{let r=()=>{};return n=>new Promise(s=>{r();const o=setTimeout(()=>{s(!0)},e);r=()=>{clearTimeout(o),s(!1)}})},we=()=>(e,t)=>t.map(r=>({config:r,result:e})),ve=(e,t={})=>{const{isMatch:r,getParamsFromRequest:n,mergeParamsToRequest:s}=e,{fetchCheck:o=ye(300),distributeResult:i=we()}=t,c=[],d=u=>u.map(a=>a.config);return(u,a)=>r(u)?new w.Observable(l=>{const h=n(u);c.push({next:f=>l.next(f),error:f=>l.error(f),config:h});const y=d(c);o(u).then(f=>{if(f){const v=[];y.forEach(g=>{const b=c.findIndex(_=>_.config===g);if(b>=0){const[_]=c.splice(b,1);v.push(_)}}),a(s(y,u)).subscribe({next:g=>{if(g.type===D.Response){const b=g.body,_=i(b,y);v.forEach(F=>{const q=_.find(O=>O.config===F.config);if(q){const O=new L({body:q.result,headers:g.headers,status:g.status,statusText:g.statusText});F.next(O)}else F.error("batch error")})}},complete:()=>l.complete(),error:g=>l.error(g)})}})}):a(u)};exports.AuthInterceptorFactory=me;exports.HTTPEventType=D;exports.HTTPHeaders=E;exports.HTTPProgress=M;exports.HTTPRequest=U;exports.HTTPResponse=L;exports.HTTPResponseError=I;exports.HTTPStatusCode=x;exports.IHTTPImplementation=A;exports.ISocketService=he;exports.MergeInterceptorFactory=ve;exports.ResponseHeader=B;exports.RetryInterceptorFactory=ge;exports.ThresholdInterceptorFactory=fe;exports.WebSocketService=pe;
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 k{constructor(t){this.params=t}toString(){return this.params?Object.keys(this.params).map(t=>`${t}=${this.params[t]}`).join("&"):""}}let V=0;class U{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:j,r=(s=this.requestParams)==null?void 0:s.body;return t===j&&r&&typeof r=="object"?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}var P=Object.defineProperty,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=(n?i(t,r,s):i(s))||s);return n&&s&&P(t,r,s),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 k(s==null?void 0:s.params),c=new U(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 w.of(c).pipe(R.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 k(s==null?void 0:s.params),c=new U(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=w.of(c).pipe(R.concatMap(h=>this._runInterceptorsAndImplementation(h)));return await w.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||{}),D=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(D||{});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 M{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 I{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 H=Object.defineProperty,S=Object.getOwnPropertyDescriptor,C=(e,t,r,n)=>{for(var s=n>1?void 0:n?S(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&H(t,r,s),s},T=(e,t)=>(r,n)=>t(r,n,e);exports.FetchHTTPImplementation=class{constructor(t){this._logService=t}send(t){return new w.Observable(r=>{const n=new AbortController;return this._send(t,r,n).catch(s=>{r.error(new I({error:s,request:t}))}),()=>n.abort()})}async _send(t,r,n){var a,l;let s;try{const h=X(t),y=t.getUrlWithParams(),g=fetch(y,{signal:n.signal,...h});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${y} with params ${h}`),s=await g}catch(h){const y=new I({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",y),r.error(y);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 I({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 y,g;const s=[],o=r.body.getReader(),i=r.headers.get("content-length");let c=0;const d=(y=t.requestParams)==null?void 0:y.reportProgress,u=t.responseType;let a,l;for(;;){const{done:v,value:f}=await o.read();if(v)break;s.push(f),c+=f.length,d&&u==="text"&&(a=(a!=null?a:"")+(l!=null?l:l=new TextDecoder).decode(f,{stream:!0}),n.next(new M(i?Number.parseInt(i,10):void 0,c,a)))}const h=ee(s,c);try{const v=(g=r.headers.get("content-type"))!=null?g:"";return te(t,h,v)}catch(v){const f=new I({request:t,error:v,status:r.status,statusText:r.statusText,headers:new E(r.headers)});return this._logService.error("[FetchHTTPImplementation]: network error",f),n.error(f),null}}};exports.FetchHTTPImplementation=C([T(0,p.ILogService)],exports.FetchHTTPImplementation);function ee(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 re=/^\)\]\}',?\n/;function te(e,t,r){switch(e.responseType){case"json":const n=new TextDecoder().decode(t).replace(re,"");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 ne=Object.defineProperty,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=(n?i(t,r,s):i(s))||s);return n&&s&&ne(t,r,s),s},ie=(e,t)=>(r,n)=>t(r,n,e);exports.XHRHTTPImplementation=class{constructor(t){this._logService=t}send(t){return new w.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:y}=t;let g=null,v=null;h!==x.NoContent&&(g=typeof n.response>"u"?n.responseText:n.response);let f=h>=Q&&h<Z;if(y==="json"&&typeof g=="string"){const b=g;try{g=g?JSON.parse(g):null}catch(_){f=!1,g=b,v=_}}if(f)r.next(new L({body:g,headers:a,status:h,statusText:l}));else{const b=new I({request:t,error:v,headers:a,status:h,statusText:l});this._logService.error("[XHRHTTPImplementation]: network error",b),r.error(b)}},d=a=>{const l=new I({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=oe([ie(0,p.ILogService)],exports.XHRHTTPImplementation);var ce=Object.defineProperty,ae=Object.getOwnPropertyDescriptor,le=(e,t,r,n)=>{for(var s=n>1?void 0:n?ae(t,r):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(n?i(t,r,s):i(s))||s);return n&&s&&ce(t,r,s),s},$=(e,t)=>(r,n)=>t(r,n,e),N;exports.UniverNetworkPlugin=(N=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(N,"pluginName","UNIVER_NETWORK_PLUGIN"),N);exports.UniverNetworkPlugin=le([$(1,p.ILogService),$(2,p.Inject(p.Injector))],exports.UniverNetworkPlugin);const he=p.createIdentifier("univer.network.socket.service");class pe 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 w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("open",i),n.add(p.toDisposable(()=>r.removeEventListener("open",i)))}).pipe(R.share()),close$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("close",i),n.add(p.toDisposable(()=>r.removeEventListener("close",i)))}).pipe(R.share()),error$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("error",i),n.add(p.toDisposable(()=>r.removeEventListener("error",i)))}).pipe(R.share()),message$:new w.Observable(o=>{const i=c=>o.next(c);r.addEventListener("message",i),n.add(p.toDisposable(()=>r.removeEventListener("message",i)))}).pipe(R.share())}}catch(r){return console.error(r),null}}}const de=3,ue=1e3,fe=e=>{var n,s;const t=(n=e==null?void 0:e.maxRetryAttempts)!=null?n:de,r=(s=e==null?void 0:e.delayInterval)!=null?s:ue;return(o,i)=>i(o).pipe(R.retry({delay:r,count:t}))},ge=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 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(t,c),n()};return t.push(c),n(),d})},me=e=>{const{errorStatusCodes:t,onAuthError:r}=e;return(s,o)=>o(s).pipe(w.catchError(i=>(i instanceof I&&t.some(c=>c===i.status)&&r(),w.throwError(()=>i))))},ye=(e=300)=>{let r=()=>{};return n=>new Promise(s=>{r();const o=setTimeout(()=>{s(!0)},e);r=()=>{clearTimeout(o),s(!1)}})},we=()=>(e,t)=>t.map(r=>({config:r,result:e})),ve=(e,t={})=>{const{isMatch:r,getParamsFromRequest:n,mergeParamsToRequest:s}=e,{fetchCheck:o=ye(300),distributeResult:i=we()}=t,c=[],d=u=>u.map(a=>a.config);return(u,a)=>r(u)?new w.Observable(l=>{const h=n(u);c.push({next:g=>l.next(g),error:g=>l.error(g),config:h});const y=d(c);o(u).then(g=>{if(g){const v=[];y.forEach(f=>{const b=c.findIndex(_=>_.config===f);if(b>=0){const[_]=c.splice(b,1);v.push(_)}}),a(s(y,u)).subscribe({next:f=>{if(f.type===D.Response){const b=f.body,_=i(b,y);v.forEach(F=>{const q=_.find(O=>O.config===F.config);if(q){const O=new L({body:q.result,headers:f.headers,status:f.status,statusText:f.statusText});F.next(O)}else F.error("batch error")})}},complete:()=>l.complete(),error:f=>l.error(f)})}})}):a(u)};exports.AuthInterceptorFactory=me;exports.HTTPEventType=D;exports.HTTPHeaders=E;exports.HTTPProgress=M;exports.HTTPRequest=U;exports.HTTPResponse=L;exports.HTTPResponseError=I;exports.HTTPStatusCode=x;exports.IHTTPImplementation=A;exports.ISocketService=he;exports.MergeInterceptorFactory=ve;exports.ResponseHeader=B;exports.RetryInterceptorFactory=fe;exports.ThresholdInterceptorFactory=ge;exports.WebSocketService=pe;
package/lib/es/facade.js CHANGED
@@ -1,10 +1,10 @@
1
- import { Inject as h, Injector as _, FBase as u, FUniver as v } from "@univerjs/core";
1
+ import { Inject as h, Injector as v, FBase as u, FUniver as o } from "@univerjs/core";
2
2
  import { HTTPService as a } from "@univerjs/network";
3
- var S = Object.defineProperty, l = Object.getOwnPropertyDescriptor, f = (t, e, r, s) => {
4
- for (var i = s > 1 ? void 0 : s ? l(e, r) : e, c = t.length - 1, n; c >= 0; c--)
5
- (n = t[c]) && (i = (s ? n(e, r, i) : n(i)) || i);
3
+ var S = Object.defineProperty, f = Object.getOwnPropertyDescriptor, l = (t, e, r, s) => {
4
+ for (var i = s > 1 ? void 0 : s ? f(e, r) : e, n = t.length - 1, c; n >= 0; n--)
5
+ (c = t[n]) && (i = (s ? c(e, r, i) : c(i)) || i);
6
6
  return s && i && S(e, r, i), i;
7
- }, o = (t, e) => (r, s) => e(r, s, t);
7
+ }, _ = (t, e) => (r, s) => e(r, s, t);
8
8
  let p = class extends u {
9
9
  constructor(t, e) {
10
10
  super(), this._injector = t, this._httpService = e;
@@ -66,13 +66,13 @@ let p = class extends u {
66
66
  return this._httpService.getSSE(t, e, r);
67
67
  }
68
68
  };
69
- p = f([
70
- o(0, h(_)),
71
- o(1, h(a))
69
+ p = l([
70
+ _(0, h(v)),
71
+ _(1, h(a))
72
72
  ], p);
73
- class j extends v {
73
+ class j extends o {
74
74
  getNetwork() {
75
75
  return this._injector.createInstance(p);
76
76
  }
77
77
  }
78
- v.extend(j);
78
+ o.extend(j);
package/lib/es/index.js CHANGED
@@ -201,7 +201,7 @@ class ye {
201
201
  this.headers = r, this.status = t, this.statusText = n;
202
202
  }
203
203
  }
204
- class v {
204
+ class _ {
205
205
  constructor({
206
206
  request: r,
207
207
  headers: t,
@@ -225,8 +225,8 @@ function Q(e) {
225
225
  credentials: e.withCredentials ? "include" : void 0
226
226
  };
227
227
  }
228
- var me = Object.defineProperty, ve = Object.getOwnPropertyDescriptor, _e = (e, r, t, n) => {
229
- for (var s = n > 1 ? void 0 : n ? ve(r, t) : r, o = e.length - 1, i; o >= 0; o--)
228
+ var me = Object.defineProperty, _e = Object.getOwnPropertyDescriptor, ve = (e, r, t, n) => {
229
+ for (var s = n > 1 ? void 0 : n ? _e(r, t) : r, o = e.length - 1, i; o >= 0; o--)
230
230
  (i = e[o]) && (s = (n ? i(r, t, s) : i(s)) || s);
231
231
  return n && s && me(r, t, s), s;
232
232
  }, Ee = (e, r) => (t, n) => r(t, n, e);
@@ -238,7 +238,7 @@ let N = class {
238
238
  return new m((r) => {
239
239
  const t = new AbortController();
240
240
  return this._send(e, r, t).catch((n) => {
241
- r.error(new v({
241
+ r.error(new _({
242
242
  error: n,
243
243
  request: e
244
244
  }));
@@ -255,7 +255,7 @@ let N = class {
255
255
  });
256
256
  this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${y} with params ${l}`), n = await p;
257
257
  } catch (l) {
258
- const y = new v({
258
+ const y = new _({
259
259
  request: e,
260
260
  error: l,
261
261
  status: (a = l.status) != null ? a : 0,
@@ -275,7 +275,7 @@ let N = class {
275
275
  statusText: i
276
276
  }));
277
277
  else {
278
- const l = new v({
278
+ const l = new _({
279
279
  request: e,
280
280
  error: c,
281
281
  status: o,
@@ -306,7 +306,7 @@ let N = class {
306
306
  const u = (p = r.headers.get("content-type")) != null ? p : "";
307
307
  return be(e, l, u);
308
308
  } catch (u) {
309
- const g = new v({
309
+ const g = new _({
310
310
  request: e,
311
311
  error: u,
312
312
  status: r.status,
@@ -317,7 +317,7 @@ let N = class {
317
317
  }
318
318
  }
319
319
  };
320
- N = _e([
320
+ N = ve([
321
321
  Ee(0, D)
322
322
  ], N);
323
323
  function Re(e, r) {
@@ -368,8 +368,8 @@ let U = class {
368
368
  const f = p;
369
369
  try {
370
370
  p = p ? JSON.parse(p) : null;
371
- } catch (_) {
372
- g = !1, p = f, u = _;
371
+ } catch (v) {
372
+ g = !1, p = f, u = v;
373
373
  }
374
374
  }
375
375
  if (g)
@@ -382,7 +382,7 @@ let U = class {
382
382
  })
383
383
  );
384
384
  else {
385
- const f = new v({
385
+ const f = new _({
386
386
  request: e,
387
387
  error: u,
388
388
  headers: a,
@@ -392,7 +392,7 @@ let U = class {
392
392
  this._logService.error("[XHRHTTPImplementation]: network error", f), r.error(f);
393
393
  }
394
394
  }, c = (a) => {
395
- const h = new v({
395
+ const h = new _({
396
396
  request: e,
397
397
  error: a,
398
398
  status: t.status || 0,
@@ -501,7 +501,7 @@ const De = 3, $e = 1e3, Ve = (e) => {
501
501
  }, Je = (e) => {
502
502
  const { errorStatusCodes: r, onAuthError: t } = e;
503
503
  return (s, o) => o(s).pipe(
504
- oe((i) => (i instanceof v && r.some((c) => c === i.status) && t(), ie(() => i)))
504
+ oe((i) => (i instanceof _ && r.some((c) => c === i.status) && t(), ie(() => i)))
505
505
  );
506
506
  }, je = (e = 300) => {
507
507
  let t = () => {
@@ -529,15 +529,15 @@ const De = 3, $e = 1e3, Ve = (e) => {
529
529
  if (u) {
530
530
  const g = [];
531
531
  p.forEach((f) => {
532
- const _ = c.findIndex((E) => E.config === f);
533
- if (_ >= 0) {
534
- const [E] = c.splice(_, 1);
532
+ const v = c.findIndex((E) => E.config === f);
533
+ if (v >= 0) {
534
+ const [E] = c.splice(v, 1);
535
535
  g.push(E);
536
536
  }
537
537
  }), h(s(p, a)).subscribe({
538
538
  next: (f) => {
539
539
  if (f.type === Y.Response) {
540
- const _ = f.body, E = i(_, p);
540
+ const v = f.body, E = i(v, p);
541
541
  g.forEach((F) => {
542
542
  const j = E.find((O) => O.config === F.config);
543
543
  if (j) {
@@ -568,7 +568,7 @@ export {
568
568
  we as HTTPProgress,
569
569
  G as HTTPRequest,
570
570
  $ as HTTPResponse,
571
- v as HTTPResponseError,
571
+ _ as HTTPResponseError,
572
572
  x as HTTPService,
573
573
  L as HTTPStatusCode,
574
574
  K as IHTTPImplementation,
package/lib/umd/facade.js CHANGED
@@ -1 +1 @@
1
- (function(r,u){typeof exports=="object"&&typeof module<"u"?u(require("@univerjs/core"),require("@univerjs/network")):typeof define=="function"&&define.amd?define(["@univerjs/core","@univerjs/network"],u):(r=typeof globalThis<"u"?globalThis:r||self,u(r.UniverCore,r.UniverNetwork))})(this,function(r,u){"use strict";var o=Object.defineProperty,_=Object.getOwnPropertyDescriptor,f=(t,e,n,s)=>{for(var i=s>1?void 0:s?_(e,n):e,p=t.length-1,v;p>=0;p--)(v=t[p])&&(i=(s?v(e,n,i):v(i))||i);return s&&i&&o(e,n,i),i},h=(t,e)=>(n,s)=>e(n,s,t);let c=class extends r.FBase{constructor(t,e){super(),this._injector=t,this._httpService=e}get(t,e){return this._httpService.get(t,e)}post(t,e){return this._httpService.post(t,e)}put(t,e){return this._httpService.put(t,e)}delete(t,e){return this._httpService.delete(t,e)}patch(t,e){return this._httpService.patch(t,e)}getSSE(t,e,n){return this._httpService.getSSE(t,e,n)}};c=f([h(0,r.Inject(r.Injector)),h(1,r.Inject(u.HTTPService))],c);class d extends r.FUniver{getNetwork(){return this._injector.createInstance(c)}}r.FUniver.extend(d)});
1
+ (function(r,u){typeof exports=="object"&&typeof module<"u"?u(require("@univerjs/core"),require("@univerjs/network")):typeof define=="function"&&define.amd?define(["@univerjs/core","@univerjs/network"],u):(r=typeof globalThis<"u"?globalThis:r||self,u(r.UniverCore,r.UniverNetwork))})(this,function(r,u){"use strict";var o=Object.defineProperty,f=Object.getOwnPropertyDescriptor,_=(t,e,n,s)=>{for(var i=s>1?void 0:s?f(e,n):e,p=t.length-1,v;p>=0;p--)(v=t[p])&&(i=(s?v(e,n,i):v(i))||i);return s&&i&&o(e,n,i),i},h=(t,e)=>(n,s)=>e(n,s,t);let c=class extends r.FBase{constructor(t,e){super(),this._injector=t,this._httpService=e}get(t,e){return this._httpService.get(t,e)}post(t,e){return this._httpService.post(t,e)}put(t,e){return this._httpService.put(t,e)}delete(t,e){return this._httpService.delete(t,e)}patch(t,e){return this._httpService.patch(t,e)}getSSE(t,e,n){return this._httpService.getSSE(t,e,n)}};c=_([h(0,r.Inject(r.Injector)),h(1,r.Inject(u.HTTPService))],c);class d extends r.FUniver{getNetwork(){return this._injector.createInstance(c)}}r.FUniver.extend(d)});
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,y,R){"use strict";var we=Object.defineProperty;var Ie=(c,a,y)=>a in c?we(c,a,{enumerable:!0,configurable:!0,writable:!0,value:y}):c[a]=y;var v=(c,a,y)=>Ie(c,typeof a!="symbol"?a+"":a,y);var D;const $="application/json";class L{constructor(n){v(this,"_headers",new Map);typeof n=="string"?this._handleHeadersString(n):n instanceof Headers?this._handleHeaders(n):n&&this._handleHeadersConstructorProps(n)}forEach(n){this._headers.forEach((t,r)=>n(r,t))}has(n){return!!this._headers.has(n.toLowerCase())}get(n){const t=n.toLowerCase();return this._headers.has(t)?this._headers.get(t):null}set(n,t){this._setHeader(n,t)}toHeadersInit(){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 O=a.createIdentifier("network.http-implementation");class M{constructor(n){this.params=n}toString(){return this.params?Object.keys(this.params).map(n=>`${n}=${this.params[n]}`).join("&"):""}}let W=0;class U{constructor(n,t,r){v(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:$,t=(s=this.requestParams)==null?void 0:s.body;return n===$&&t&&typeof t=="object"?JSON.stringify(t):t?`${t}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}var V=Object.defineProperty,P=Object.getOwnPropertyDescriptor,z=(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=(r?o(n,t,s):o(s))||s);return r&&s&&V(n,t,s),s},J=(e,n)=>(t,r)=>n(t,r,e);c.HTTPService=class extends a.Disposable{constructor(t){super();v(this,"_interceptors",[]);v(this,"_pipe");this._http=t}registerHTTPInterceptor(t){if(this._interceptors.indexOf(t)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(t),this._interceptors=this._interceptors.sort((r,s)=>{var i,o;return((i=r.priority)!=null?i:0)-((o=s.priority)!=null?o:0)}),this._pipe=null,a.toDisposable(()=>a.remove(this._interceptors,t))}get(t,r){return this._request("GET",t,r)}post(t,r){return this._request("POST",t,r)}put(t,r){return this._request("PUT",t,r)}delete(t,r){return this._request("DELETE",t,r)}patch(t,r){return this._request("PATCH",t,r)}getSSE(t,r,s){var u,f;const i=new L(s==null?void 0:s.headers),o=new M(s==null?void 0:s.params),l=new U(t,r,{headers:i,params:o,withCredentials:(u=s==null?void 0:s.withCredentials)!=null?u:!1,reportProgress:!0,responseType:(f=s==null?void 0:s.responseType)!=null?f:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body});return y.of(l).pipe(R.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 M(s==null?void 0:s.params),l=new U(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(R.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)=>K(r,s),(r,s)=>s(r))),this._pipe(t,r=>this._http.send(r))}},c.HTTPService=z([J(0,O)],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||{}),A=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(A||{});class N{constructor({body:n,headers:t,status:r,statusText:s}){v(this,"type",1);v(this,"body");v(this,"headers");v(this,"status");v(this,"statusText");this.body=n,this.headers=t,this.status=r,this.statusText=s}}class j{constructor(n,t,r){v(this,"type",0);this.total=n,this.loaded=t,this.partialText=r}}class x{constructor(n,t,r){this.headers=n,this.status=t,this.statusText=r}}class b{constructor({request:n,headers:t,status:r,statusText:s,error:i}){v(this,"request");v(this,"headers");v(this,"status");v(this,"statusText");v(this,"error");this.request=n,this.headers=t,this.status=r,this.statusText=s,this.error=i}}function B(e){return{method:e.method,headers:e.getHeadersInit(),body:e.getBody(),credentials:e.withCredentials?"include":void 0}}var Z=Object.defineProperty,H=Object.getOwnPropertyDescriptor,S=(e,n,t,r)=>{for(var s=r>1?void 0:r?H(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=(r?o(n,t,s):o(s))||s);return r&&s&&Z(n,t,s),s},C=(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 b({error:s,request:n}))}),()=>r.abort()})}async _send(n,t,r){var h,d;let s;try{const p=B(n),w=n.getUrlWithParams(),m=fetch(w,{signal:r.signal,...p});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${w} with params ${p}`),s=await m}catch(p){const w=new b({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",w),t.error(w);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 b({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 w,m;const s=[],i=t.body.getReader(),o=t.headers.get("content-length");let l=0;const u=(w=n.requestParams)==null?void 0:w.reportProgress,f=n.responseType;let h,d;for(;;){const{done:I,value:g}=await i.read();if(I)break;s.push(g),l+=g.length,u&&f==="text"&&(h=(h!=null?h:"")+(d!=null?d:d=new TextDecoder).decode(g,{stream:!0}),r.next(new j(o?Number.parseInt(o,10):void 0,l,h)))}const p=T(s,l);try{const I=(m=t.headers.get("content-type"))!=null?m:"";return te(n,p,I)}catch(I){const g=new b({request:n,error:I,status:t.status,statusText:t.statusText,headers:new L(t.headers)});return this._logService.error("[FetchHTTPImplementation]: network error",g),r.error(g),null}}},c.FetchHTTPImplementation=S([C(0,a.ILogService)],c.FetchHTTPImplementation);function T(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 ee=/^\)\]\}',?\n/;function te(e,n,t){switch(e.responseType){case"json":const r=new TextDecoder().decode(n).replace(ee,"");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 re=Object.defineProperty,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=(r?o(n,t,s):o(s))||s);return r&&s&&re(n,t,s),s},ie=(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:w}=n;let m=null,I=null;p!==F.NoContent&&(m=typeof r.response>"u"?r.responseText:r.response);let g=p>=Y&&p<Q;if(w==="json"&&typeof m=="string"){const _=m;try{m=m?JSON.parse(m):null}catch(E){g=!1,m=_,I=E}}if(g)t.next(new N({body:m,headers:h,status:p,statusText:d}));else{const _=new b({request:n,error:I,headers:h,status:p,statusText:d});this._logService.error("[XHRHTTPImplementation]: network error",_),t.error(_)}},u=h=>{const d=new b({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 f=n.getBody();return r.send(f),this._logService.debug(`[XHRHTTPImplementation]: sending request to url ${s} with params ${i}`),()=>{r.readyState!==r.DONE&&r.abort(),r.removeEventListener("load",l),r.removeEventListener("error",u),r.removeEventListener("abort",u),r.removeEventListener("timeout",u)}})}},c.XHRHTTPImplementation=se([ie(0,a.ILogService)],c.XHRHTTPImplementation);var oe=Object.defineProperty,ce=Object.getOwnPropertyDescriptor,ae=(e,n,t,r)=>{for(var s=r>1?void 0:r?ce(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=(r?o(n,t,s):o(s))||s);return r&&s&&oe(n,t,s),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],[O,{useClass:t}]],(i=this._config)==null?void 0:i.override))}},v(D,"pluginName","UNIVER_NETWORK_PLUGIN"),D),c.UniverNetworkPlugin=ae([X(1,a.ILogService),X(2,a.Inject(a.Injector))],c.UniverNetworkPlugin);const le=a.createIdentifier("univer.network.socket.service");class he 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(R.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(R.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(R.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(R.share())}}catch(t){return console.error(t),null}}}const de=3,pe=1e3,ue=e=>{var r,s;const n=(r=e==null?void 0:e.maxRetryAttempts)!=null?r:de,t=(s=e==null?void 0:e.delayInterval)!=null?s:pe;return(i,o)=>o(i).pipe(R.retry({delay:t,count:n}))},fe=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:f=>o.next(f),error:f=>o.error(f),complete:()=>o.complete()}),u=()=>{t.delete(l),a.remove(n,l),r()};return n.push(l),r(),u})},ge=e=>{const{errorStatusCodes:n,onAuthError:t}=e;return(s,i)=>i(s).pipe(y.catchError(o=>(o instanceof b&&n.some(l=>l===o.status)&&t(),y.throwError(()=>o))))},me=(e=300)=>{let t=()=>{};return r=>new Promise(s=>{t();const i=setTimeout(()=>{s(!0)},e);t=()=>{clearTimeout(i),s(!1)}})},ye=()=>(e,n)=>n.map(t=>({config:t,result:e})),ve=(e,n={})=>{const{isMatch:t,getParamsFromRequest:r,mergeParamsToRequest:s}=e,{fetchCheck:i=me(300),distributeResult:o=ye()}=n,l=[],u=f=>f.map(h=>h.config);return(f,h)=>t(f)?new y.Observable(d=>{const p=r(f);l.push({next:m=>d.next(m),error:m=>d.error(m),config:p});const w=u(l);i(f).then(m=>{if(m){const I=[];w.forEach(g=>{const _=l.findIndex(E=>E.config===g);if(_>=0){const[E]=l.splice(_,1);I.push(E)}}),h(s(w,f)).subscribe({next:g=>{if(g.type===A.Response){const _=g.body,E=o(_,w);I.forEach(k=>{const G=E.find(q=>q.config===k.config);if(G){const q=new N({body:G.result,headers:g.headers,status:g.status,statusText:g.statusText});k.next(q)}else k.error("batch error")})}},complete:()=>d.complete(),error:g=>d.error(g)})}})}):h(f)};c.AuthInterceptorFactory=ge,c.HTTPEventType=A,c.HTTPHeaders=L,c.HTTPProgress=j,c.HTTPRequest=U,c.HTTPResponse=N,c.HTTPResponseError=b,c.HTTPStatusCode=F,c.IHTTPImplementation=O,c.ISocketService=le,c.MergeInterceptorFactory=ve,c.ResponseHeader=x,c.RetryInterceptorFactory=ue,c.ThresholdInterceptorFactory=fe,c.WebSocketService=he,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,R){"use strict";var ve=Object.defineProperty;var Ie=(c,a,y)=>a in c?ve(c,a,{enumerable:!0,configurable:!0,writable:!0,value:y}):c[a]=y;var w=(c,a,y)=>Ie(c,typeof a!="symbol"?a+"":a,y);var D;const $="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 O=a.createIdentifier("network.http-implementation");class M{constructor(n){this.params=n}toString(){return this.params?Object.keys(this.params).map(n=>`${n}=${this.params[n]}`).join("&"):""}}let W=0;class U{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:$,t=(s=this.requestParams)==null?void 0:s.body;return n===$&&t&&typeof t=="object"?JSON.stringify(t):t?`${t}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}var V=Object.defineProperty,P=Object.getOwnPropertyDescriptor,z=(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=(r?o(n,t,s):o(s))||s);return r&&s&&V(n,t,s),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,f;const i=new L(s==null?void 0:s.headers),o=new M(s==null?void 0:s.params),l=new U(t,r,{headers:i,params:o,withCredentials:(u=s==null?void 0:s.withCredentials)!=null?u:!1,reportProgress:!0,responseType:(f=s==null?void 0:s.responseType)!=null?f:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body});return y.of(l).pipe(R.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 M(s==null?void 0:s.params),l=new U(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(R.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)=>K(r,s),(r,s)=>s(r))),this._pipe(t,r=>this._http.send(r))}},c.HTTPService=z([J(0,O)],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||{}),A=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(A||{});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 b{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.defineProperty,H=Object.getOwnPropertyDescriptor,S=(e,n,t,r)=>{for(var s=r>1?void 0:r?H(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=(r?o(n,t,s):o(s))||s);return r&&s&&Z(n,t,s),s},C=(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 b({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 b({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 b({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,f=n.responseType;let h,d;for(;;){const{done:I,value:g}=await i.read();if(I)break;s.push(g),l+=g.length,u&&f==="text"&&(h=(h!=null?h:"")+(d!=null?d:d=new TextDecoder).decode(g,{stream:!0}),r.next(new j(o?Number.parseInt(o,10):void 0,l,h)))}const p=T(s,l);try{const I=(m=t.headers.get("content-type"))!=null?m:"";return te(n,p,I)}catch(I){const g=new b({request:n,error:I,status:t.status,statusText:t.statusText,headers:new L(t.headers)});return this._logService.error("[FetchHTTPImplementation]: network error",g),r.error(g),null}}},c.FetchHTTPImplementation=S([C(0,a.ILogService)],c.FetchHTTPImplementation);function T(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 ee=/^\)\]\}',?\n/;function te(e,n,t){switch(e.responseType){case"json":const r=new TextDecoder().decode(n).replace(ee,"");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 re=Object.defineProperty,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=(r?o(n,t,s):o(s))||s);return r&&s&&re(n,t,s),s},ie=(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 g=p>=Y&&p<Q;if(v==="json"&&typeof m=="string"){const _=m;try{m=m?JSON.parse(m):null}catch(E){g=!1,m=_,I=E}}if(g)t.next(new N({body:m,headers:h,status:p,statusText:d}));else{const _=new b({request:n,error:I,headers:h,status:p,statusText:d});this._logService.error("[XHRHTTPImplementation]: network error",_),t.error(_)}},u=h=>{const d=new b({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 f=n.getBody();return r.send(f),this._logService.debug(`[XHRHTTPImplementation]: sending request to url ${s} with params ${i}`),()=>{r.readyState!==r.DONE&&r.abort(),r.removeEventListener("load",l),r.removeEventListener("error",u),r.removeEventListener("abort",u),r.removeEventListener("timeout",u)}})}},c.XHRHTTPImplementation=se([ie(0,a.ILogService)],c.XHRHTTPImplementation);var oe=Object.defineProperty,ce=Object.getOwnPropertyDescriptor,ae=(e,n,t,r)=>{for(var s=r>1?void 0:r?ce(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=(r?o(n,t,s):o(s))||s);return r&&s&&oe(n,t,s),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],[O,{useClass:t}]],(i=this._config)==null?void 0:i.override))}},w(D,"pluginName","UNIVER_NETWORK_PLUGIN"),D),c.UniverNetworkPlugin=ae([X(1,a.ILogService),X(2,a.Inject(a.Injector))],c.UniverNetworkPlugin);const le=a.createIdentifier("univer.network.socket.service");class he 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(R.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(R.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(R.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(R.share())}}catch(t){return console.error(t),null}}}const de=3,pe=1e3,ue=e=>{var r,s;const n=(r=e==null?void 0:e.maxRetryAttempts)!=null?r:de,t=(s=e==null?void 0:e.delayInterval)!=null?s:pe;return(i,o)=>o(i).pipe(R.retry({delay:t,count:n}))},fe=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:f=>o.next(f),error:f=>o.error(f),complete:()=>o.complete()}),u=()=>{t.delete(l),a.remove(n,l),r()};return n.push(l),r(),u})},ge=e=>{const{errorStatusCodes:n,onAuthError:t}=e;return(s,i)=>i(s).pipe(y.catchError(o=>(o instanceof b&&n.some(l=>l===o.status)&&t(),y.throwError(()=>o))))},me=(e=300)=>{let t=()=>{};return r=>new Promise(s=>{t();const i=setTimeout(()=>{s(!0)},e);t=()=>{clearTimeout(i),s(!1)}})},ye=()=>(e,n)=>n.map(t=>({config:t,result:e})),we=(e,n={})=>{const{isMatch:t,getParamsFromRequest:r,mergeParamsToRequest:s}=e,{fetchCheck:i=me(300),distributeResult:o=ye()}=n,l=[],u=f=>f.map(h=>h.config);return(f,h)=>t(f)?new y.Observable(d=>{const p=r(f);l.push({next:m=>d.next(m),error:m=>d.error(m),config:p});const v=u(l);i(f).then(m=>{if(m){const I=[];v.forEach(g=>{const _=l.findIndex(E=>E.config===g);if(_>=0){const[E]=l.splice(_,1);I.push(E)}}),h(s(v,f)).subscribe({next:g=>{if(g.type===A.Response){const _=g.body,E=o(_,v);I.forEach(k=>{const G=E.find(q=>q.config===k.config);if(G){const q=new N({body:G.result,headers:g.headers,status:g.status,statusText:g.statusText});k.next(q)}else k.error("batch error")})}},complete:()=>d.complete(),error:g=>d.error(g)})}})}):h(f)};c.AuthInterceptorFactory=ge,c.HTTPEventType=A,c.HTTPHeaders=L,c.HTTPProgress=j,c.HTTPRequest=U,c.HTTPResponse=N,c.HTTPResponseError=b,c.HTTPStatusCode=F,c.IHTTPImplementation=O,c.ISocketService=le,c.MergeInterceptorFactory=we,c.ResponseHeader=x,c.RetryInterceptorFactory=ue,c.ThresholdInterceptorFactory=fe,c.WebSocketService=he,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.5.3",
3
+ "version": "0.5.4",
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.5.3"
55
+ "@univerjs/core": "0.5.4"
56
56
  },
57
57
  "devDependencies": {
58
58
  "rxjs": "^7.8.1",
59
59
  "typescript": "^5.7.2",
60
- "vite": "^6.0.6",
60
+ "vite": "^6.0.7",
61
61
  "vitest": "^2.1.8",
62
- "@univerjs-infra/shared": "0.5.3"
62
+ "@univerjs-infra/shared": "0.5.4"
63
63
  },
64
64
  "scripts": {
65
65
  "test": "vitest run",