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