@univerjs/network 0.16.1 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
- import { Observable } from 'rxjs';
1
+ import { HTTPRequest } from '../request';
2
+ import { HTTPEvent, HTTPResponseError } from '../response';
2
3
  import { Disposable, Injector } from '@univerjs/core';
4
+ import { Observable } from 'rxjs';
3
5
  import { IHTTPImplementation } from '../implementations/implementation';
4
- import { HTTPRequest } from '../request';
5
- import { HTTPEvent, HTTPResponse, HTTPResponseError } from '../response';
6
6
  /**
7
7
  * A mocked HTTP implementation service for testing purposes. Besides methods in the interface, it
8
8
  * provides several public methods to control the process of http request.
@@ -24,7 +24,7 @@ export interface IMockHTTPHandler {
24
24
  /**
25
25
  * Emit a response event to the observer.
26
26
  */
27
- emitResponse<T>(response: HTTPResponse<T>): void;
27
+ emitResponse<T>(response: HTTPEvent<T>): void;
28
28
  /**
29
29
  * Emit an error event to the observer.
30
30
  */
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Copyright 2023-present DreamNum Co., Ltd.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ export {};
@@ -1,6 +1,6 @@
1
- import { Observable } from 'rxjs';
2
- import { HTTPRequest } from '../request';
3
1
  import { HTTPHandlerFn } from '../interceptor';
2
+ import { HTTPRequest } from '../request';
3
+ import { Observable } from 'rxjs';
4
4
  export declare const MergeInterceptorFactory: <T, C>(config: {
5
5
  /**
6
6
  * Filter requests that need to be merged
package/lib/umd/index.js CHANGED
@@ -1,2 +1,2 @@
1
- (function(c,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("@univerjs/core"),require("rxjs"),require("rxjs/operators")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs","rxjs/operators"],a):(c=typeof globalThis<"u"?globalThis:c||self,a(c.UniverNetwork={},c.UniverCore,c.rxjs,c.rxjs.operators))})(this,(function(c,a,m,_){"use strict";var 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 f,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:(f=s==null?void 0:s.withCredentials)!=null?f:!1,responseType:(p=s==null?void 0:s.responseType)!=null?p:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body}),w=m.of(l).pipe(_.concatMap(h=>this._runInterceptorsAndImplementation(h)));return await m.firstValueFrom(w)}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(f=>this._runInterceptorsAndImplementation(f)))}_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 f,p;let s;try{const h=X(n),y=n.getUrlWithParams(),g=fetch(y,{signal:r.signal,...h});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${y} with params ${h}`),s=await g}catch(h){const y=new R({request:n,error:h,status:(f=h.status)!=null?f:0,statusText:(p=h.statusText)!=null?p:"Unknown Error",headers:h.headers});this._logService.error("[FetchHTTPImplementation]: network error",y),t.error(y);return}const i=new L(s.headers),o=s.status,l=s.statusText;let w=null;if(s.body&&(w=await this._readBody(n,s,t)),o>=F.Ok&&o<F.MultipleChoices)t.next(new N({body:w,headers:i,status:o,statusText:l}));else{const h=new R({request:n,error:w,status:o,statusText:l,headers:i});this._logService.error("[FetchHTTPImplementation]: network error",h),t.error(h)}t.complete()}async _readBody(n,t,r){var y,g;const s=[],i=t.body.getReader(),o=t.headers.get("content-length");let l=0;const w=(y=n.requestParams)==null?void 0:y.reportProgress,d=n.responseType;let f,p;for(;;){const{done:I,value:u}=await i.read();if(I)break;s.push(u),l+=u.length,w&&d==="text"&&(f=(f!=null?f:"")+(p!=null?p:p=new TextDecoder).decode(u,{stream:!0}),r.next(new B(o?Number.parseInt(o,10):void 0,l,f)))}const h=ee(s,l);try{const I=(g=t.headers.get("content-type"))!=null?g:"";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.buffer],{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 g=null,I=null;y!==F.NoContent&&(g=typeof r.response>"u"?r.responseText:r.response);let u=y>=Z&&y<H;if(o==="json"&&typeof g=="string"){const b=g;try{g=g?JSON.parse(g):null}catch(E){u=!1,g=b,I=E}}if(o==="blob"&&!(g instanceof Blob)&&(u=!1,I=new Error("Response is not a Blob object")),u)t.next(new N({body:g,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 f=n.getBody();return r.send(f),this._logService.debug("[XHRHTTPImplementation]",`sending request to url ${s} with params ${i}`),()=>{r.readyState!==r.DONE&&r.abort(),r.removeEventListener("load",w),r.removeEventListener("error",d),r.removeEventListener("abort",d),r.removeEventListener("timeout",d)}})}},c.XHRHTTPImplementation=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(f=>f.config);return(d,f)=>t(d)?new m.Observable(p=>{const h=r(d);l.push({next:g=>p.next(g),error:g=>p.error(g),config:h});const y=w(l);i(d).then(g=>{if(g){const I=[];y.forEach(u=>{const b=l.findIndex(E=>E.config===u);if(b>=0){const[E]=l.splice(b,1);I.push(E)}}),f(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)})}})}):f(d)},pe=3,ue=1e3,fe=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}))},ge=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=fe,c.ThresholdInterceptorFactory=ge,c.WebSocketService=ye,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(c,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("@univerjs/core"),require("rxjs"),require("rxjs/operators")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs","rxjs/operators"],a):(c=typeof globalThis<"u"?globalThis:c||self,a(c.UniverNetwork={},c.UniverCore,c.rxjs,c.rxjs.operators))})(this,(function(c,a,y,_){"use strict";var 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 m=(c,a,y)=>Ie(c,typeof a!="symbol"?a+"":a,y);var F;const j={name:"@univerjs/network",version:"0.17.0"},J="network.config",x={},O="application/json";function K(e){return Array.isArray(e)?e.some(n=>n.includes(O)):e.includes(O)}class L{constructor(n){m(this,"_headers",new Map);typeof n=="string"?this._handleHeadersString(n):n instanceof Headers?this._handleHeaders(n):n&&this._handleHeadersConstructorProps(n)}forEach(n){this._headers.forEach((t,r)=>n(r,t))}has(n){return!!this._headers.has(n.toLowerCase())}get(n){const t=n.toLowerCase();return this._headers.has(t)?this._headers.get(t):null}set(n,t){this._setHeader(n,t)}toHeadersInit(n){var r,s;const t={};return this._headers.forEach((i,o)=>{t[o]=i.join(",")}),(r=t.accept)!=null||(t.accept="application/json, text/plain, */*"),n instanceof FormData||(s=t["content-type"])!=null||(t["content-type"]="application/json;charset=UTF-8"),t}_setHeader(n,t){const r=n.toLowerCase();this._headers.has(r)?this._headers.get(r).push(t.toString()):this._headers.set(r,[t.toString()])}_handleHeadersString(n){n.split(`
2
+ `).forEach(t=>{const[r,s]=t.split(":");r&&s&&this._setHeader(r,s)})}_handleHeadersConstructorProps(n){Object.entries(n).forEach(([t,r])=>this._setHeader(t,r))}_handleHeaders(n){n.forEach((t,r)=>this._setHeader(r,t))}}const A=a.createIdentifier("network.http-implementation");class B{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 z=0;class U{constructor(n,t,r){m(this,"uid",z++);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:O,t=(s=this.requestParams)==null?void 0:s.body;return t instanceof FormData?t:K(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 Y=Object.getOwnPropertyDescriptor,P=(e,n,t,r)=>{for(var s=r>1?void 0:r?Y(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},Q=(e,n)=>(t,r)=>n(t,r,e);c.HTTPService=class extends a.Disposable{constructor(t){super();m(this,"_interceptors",[]);m(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 B(s==null?void 0:s.params),l=new U(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=y.of(l).pipe(_.concatMap(h=>this._runInterceptorsAndImplementation(h)));return await y.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 B(s==null?void 0:s.params),l=new U(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 y.of(l).pipe(_.concatMap(g=>this._runInterceptorsAndImplementation(g)))}_runInterceptorsAndImplementation(t){return this._pipe||(this._pipe=this._interceptors.map(r=>r.interceptor).reduceRight((r,s)=>Z(r,s),(r,s)=>s(r))),this._pipe(t,r=>this._http.send(r))}},c.HTTPService=P([Q(0,A)],c.HTTPService);function Z(e,n){return(t,r)=>n(t,s=>e(s,r))}const H=200,S=300;var N=(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))(N||{}),D=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(D||{});class k{constructor({body:n,headers:t,status:r,statusText:s}){m(this,"type",1);m(this,"body");m(this,"headers");m(this,"status");m(this,"statusText");this.body=n,this.headers=t,this.status=r,this.statusText=s}}class G{constructor(n,t,r){m(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}){m(this,"request");m(this,"headers");m(this,"status");m(this,"statusText");m(this,"error");this.request=n,this.headers=t,this.status=r,this.statusText=s,this.error=i}}function W(e){return{method:e.method,headers:e.getHeadersInit(),body:e.getBody(),credentials:e.withCredentials?"include":void 0}}var C=Object.getOwnPropertyDescriptor,T=(e,n,t,r)=>{for(var s=r>1?void 0:r?C(n,t):n,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=o(s)||s);return s},ee=(e,n)=>(t,r)=>n(t,r,e);c.FetchHTTPImplementation=class{constructor(n){this._logService=n}send(n){return new y.Observable(t=>{const r=new AbortController;return this._send(n,t,r).catch(s=>{t.error(new R({error:s,request:n}))}),()=>r.abort()})}async _send(n,t,r){var g,p;let s;try{const h=W(n),v=n.getUrlWithParams(),f=fetch(v,{signal:r.signal,...h});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${v} with params ${h}`),s=await f}catch(h){const v=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",v),t.error(v);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>=N.Ok&&o<N.MultipleChoices)t.next(new k({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 v,f;const s=[],i=t.body.getReader(),o=t.headers.get("content-length");let l=0;const w=(v=n.requestParams)==null?void 0:v.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 G(o?Number.parseInt(o,10):void 0,l,g)))}const h=te(s,l);try{const I=(f=t.headers.get("content-type"))!=null?f:"";return ne(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=T([ee(0,a.ILogService)],c.FetchHTTPImplementation);function te(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 re=/^\)\]\}',?\n/;function ne(e,n,t){switch(e.responseType){case"json":const r=new TextDecoder().decode(n).replace(re,"");return r===""?null:JSON.parse(r);case"text":return new TextDecoder().decode(n);case"blob":return new Blob([n.buffer],{type:t});case"arraybuffer":return n.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}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},oe=(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=W(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:v}=l();let f=null,I=null;v!==N.NoContent&&(f=typeof r.response>"u"?r.responseText:r.response);let u=v>=H&&v<S;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 k({body:f,headers:p,status:v,statusText:h}));else{const b=new R({request:n,error:I,headers:p,status:v,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=ie([oe(0,a.ILogService)],c.XHRHTTPImplementation);var 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=o(s)||s);return s},q=(e,n)=>(t,r)=>n(t,r,e);c.UniverNetworkPlugin=(F=class extends a.Plugin{constructor(n=x,t,r,s){super(),this._config=n,this._logger=t,this._injector=r,this._configService=s;const{...i}=a.merge({},x,this._config);this._configService.setConfig(J,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],[A,{useClass:t}]],(i=this._config)==null?void 0:i.override))}},m(F,"pluginName","UNIVER_NETWORK_PLUGIN"),m(F,"packageName",j.name),m(F,"version",j.version),F),c.UniverNetworkPlugin=ae([q(1,a.ILogService),q(2,a.Inject(a.Injector)),q(3,a.IConfigService)],c.UniverNetworkPlugin);const le=e=>{const{errorStatusCodes:n,onAuthError:t}=e;return(s,i)=>i(s).pipe(y.catchError(o=>(o instanceof R&&n.some(l=>l===o.status)&&t(),y.throwError(()=>o))))},he=(e=300)=>{let t=()=>{};return r=>new Promise(s=>{t();const i=setTimeout(()=>{s(!0)},e);t=()=>{clearTimeout(i),s(!1)}})},de=()=>(e,n)=>n.map(t=>({config:t,result:e})),pe=(e,n={})=>{const{isMatch:t,getParamsFromRequest:r,mergeParamsToRequest:s}=e,{fetchCheck:i=he(300),distributeResult:o=de()}=n,l=[],w=d=>d.map(g=>g.config);return(d,g)=>t(d)?new y.Observable(p=>{const h=r(d);l.push({next:f=>p.next(f),error:f=>p.error(f),config:h});const v=w(l);i(d).then(f=>{if(f){const I=[];v.forEach(u=>{const b=l.findIndex(E=>E.config===u);if(b>=0){const[E]=l.splice(b,1);I.push(E)}}),g(s(v,d)).subscribe({next:u=>{if(u.type===D.Response){const b=u.body,E=o(b,v);I.forEach(M=>{const V=E.find($=>$.config===M.config);if(V){const $=new k({body:V.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)},ue=3,ge=1e3,fe=e=>{var r,s;const n=(r=e==null?void 0:e.maxRetryAttempts)!=null?r:ue,t=(s=e==null?void 0:e.delayInterval)!=null?s:ge;return(i,o)=>o(i).pipe(_.retry({delay:t,count:n}))},me=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: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})},ye=a.createIdentifier("univer.network.socket.service");class ve extends a.Disposable{createSocket(n){try{const t=new WebSocket(n),r=new a.DisposableCollection;return{URL:n,close:(i,o)=>{t.close(i,o),r.dispose()},send:i=>{t.send(i)},open$:new y.Observable(i=>{const o=l=>i.next(l);t.addEventListener("open",o),r.add(a.toDisposable(()=>t.removeEventListener("open",o)))}).pipe(_.share()),close$:new y.Observable(i=>{const o=l=>i.next(l);t.addEventListener("close",o),r.add(a.toDisposable(()=>t.removeEventListener("close",o)))}).pipe(_.share()),error$:new y.Observable(i=>{const o=l=>i.next(l);t.addEventListener("error",o),r.add(a.toDisposable(()=>t.removeEventListener("error",o)))}).pipe(_.share()),message$:new y.Observable(i=>{const o=l=>i.next(l);t.addEventListener("message",o),r.add(a.toDisposable(()=>t.removeEventListener("message",o)))}).pipe(_.share())}}catch(t){return console.error(t),null}}}c.AuthInterceptorFactory=le,c.HTTPEventType=D,c.HTTPHeaders=L,c.HTTPProgress=G,c.HTTPRequest=U,c.HTTPResponse=k,c.HTTPResponseError=R,c.HTTPStatusCode=N,c.IHTTPImplementation=A,c.ISocketService=ye,c.MergeInterceptorFactory=pe,c.ResponseHeader=X,c.RetryInterceptorFactory=fe,c.ThresholdInterceptorFactory=me,c.WebSocketService=ve,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.16.1",
3
+ "version": "0.17.0",
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.16.1"
60
+ "@univerjs/core": "0.17.0"
61
61
  },
62
62
  "devDependencies": {
63
63
  "rxjs": "^7.8.2",
64
64
  "typescript": "^5.9.3",
65
65
  "vite": "^7.3.1",
66
66
  "vitest": "^4.0.18",
67
- "@univerjs-infra/shared": "0.16.1"
67
+ "@univerjs-infra/shared": "0.17.0"
68
68
  },
69
69
  "scripts": {
70
70
  "test": "vitest run",