@univerjs/network 0.1.13 → 0.1.15

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/README.md CHANGED
@@ -18,3 +18,7 @@ npm install @univerjs/network
18
18
  # Using pnpm
19
19
  pnpm add @univerjs/network
20
20
  ```
21
+
22
+ ## Credit
23
+
24
+ This package is inspired by [Angular's implementation](https://github.com/angular/angular/tree/main/packages/common/http). Removed zone.js dependency and features that are not necessary for Univer.
package/lib/cjs/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var F=Object.defineProperty;var U=(e,n,r)=>n in e?F(e,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[n]=r;var p=(e,n,r)=>(U(e,typeof n!="symbol"?n+"":n,r),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("@univerjs/core"),m=require("rxjs"),u=require("rxjs/operators"),L=require("@wendellhu/redi"),I="application/json";class g{constructor(n){p(this,"_headers",new Map);typeof n=="string"?this._handleHeadersString(n):n instanceof Headers?this._handleHeaders(n):n&&this._handleHeadersConstructorProps(n)}forEach(n){this._headers.forEach((r,t)=>n(t,r))}has(n){return!!this._headers.has(n.toLowerCase())}get(n){const r=n.toLowerCase();return this._headers.has(r)?this._headers.get(r):null}toHeadersInit(){var r,t;const n={};return this._headers.forEach((s,a)=>{n[a]=s.join(",")}),(r=n.accept)!=null||(n.accept="application/json, text/plain, */*"),(t=n["content-type"])!=null||(n["content-type"]="application/json;charset=UTF-8"),n}_setHeader(n,r){const t=n.toLowerCase();this._headers.has(t)?this._headers.get(t).push(r.toString()):this._headers.set(t,[r.toString()])}_handleHeadersString(n){n.split(`
2
- `).forEach(r=>{const[t,s]=r.split(":");t&&s&&this._setHeader(t,s)})}_handleHeadersConstructorProps(n){Object.entries(n).forEach(([r,t])=>this._setHeader(r,t))}_handleHeaders(n){n.forEach((r,t)=>this._setHeader(t,r))}}const q=L.createIdentifier("network.http-implementation");class x{constructor(n){this.params=n}toString(){return this.params?Object.keys(this.params).map(n=>`${n}=${this.params[n]}`).join("&"):""}}let k=0;class _{constructor(n,r,t){p(this,"uid",k++);this.method=n,this.url=r,this.requestParams=t}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var r,t;const n=(t=(r=this.requestParams)==null?void 0:r.params)==null?void 0:t.toString();return n?`${this.url}${this.url.includes("?")?"&":"?"}${n}`:this.url}getBody(){var t,s;const n=(t=this.headers.get("Content-Type"))!=null?t:I,r=(s=this.requestParams)==null?void 0:s.body;return n===I&&r&&typeof r=="object"?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}class v{constructor({body:n,headers:r,status:t,statusText:s}){p(this,"body");p(this,"headers");p(this,"status");p(this,"statusText");this.body=n,this.headers=r,this.status=t,this.statusText=s}}class f{constructor({headers:n,status:r,statusText:t,error:s}){p(this,"headers");p(this,"status");p(this,"statusText");p(this,"error");this.headers=n,this.status=r,this.statusText=t,this.error=s}}class O{constructor(n,r,t){this.headers=n,this.status=r,this.statusText=t}}var M=Object.defineProperty,D=Object.getOwnPropertyDescriptor,j=(e,n,r,t)=>{for(var s=t>1?void 0:t?D(n,r):n,a=e.length-1,i;a>=0;a--)(i=e[a])&&(s=(t?i(n,r,s):i(s))||s);return t&&s&&M(n,r,s),s},B=(e,n)=>(r,t)=>n(r,t,e);exports.HTTPService=class extends y.Disposable{constructor(r){super();p(this,"_interceptors",[]);p(this,"_pipe");this._http=r}registerHTTPInterceptor(r){if(this._interceptors.indexOf(r)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(r),this._interceptors=this._interceptors.sort((t,s)=>{var a,i;return((a=t.priority)!=null?a:0)-((i=s.priority)!=null?i:0)}),this._pipe=null,y.toDisposable(()=>y.remove(this._interceptors,r))}get(r,t){return this._request("GET",r,t)}post(r,t){return this._request("POST",r,t)}put(r,t){return this._request("PUT",r,t)}delete(r,t){return this._request("DELETE",r,t)}patch(r,t){return this._request("PATCH",r,t)}getSSE(r,t,s){var c,l;const a=new g(s==null?void 0:s.headers),i=new x(s==null?void 0:s.params),h=new _(r,t,{headers:a,params:i,withCredentials:(c=s==null?void 0:s.withCredentials)!=null?c:!1,responseType:(l=s==null?void 0:s.responseType)!=null?l:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body});return m.of(h).pipe(u.concatMap(o=>this._runInterceptorsAndImplementation(o)),u.map(o=>{if(o instanceof f)throw o;return o}))}async _request(r,t,s){var o,w;const a=new g(s==null?void 0:s.headers),i=new x(s==null?void 0:s.params),h=new _(r,t,{headers:a,params:i,withCredentials:(o=s==null?void 0:s.withCredentials)!=null?o:!1,responseType:(w=s==null?void 0:s.responseType)!=null?w:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body}),c=m.of(h).pipe(u.concatMap(d=>this._runInterceptorsAndImplementation(d))),l=await m.firstValueFrom(c);if(l instanceof v)return l;throw new Error(`${l.error}`)}_runInterceptorsAndImplementation(r){return this._pipe||(this._pipe=this._interceptors.map(t=>t.interceptor).reduceRight((t,s)=>$(t,s),(t,s)=>s(t))),this._pipe(r,t=>this._http.send(t))}};exports.HTTPService=j([B(0,q)],exports.HTTPService);function $(e,n){return(r,t)=>n(r,s=>e(s,t))}const G=200,W=300;var b=(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))(b||{});class V{send(n){return new m.Observable(r=>{const t=new AbortController;return this._send(n,r,t).then(()=>{},s=>{r.error(new f({error:s}))}),()=>t.abort()})}async _send(n,r,t){var o,w;let s;try{const d=this._parseFetchParamsFromRequest(n);s=await fetch(n.getUrlWithParams(),{signal:t.signal,...d})}catch(d){r.error(new f({error:d,status:(o=d.status)!=null?o:0,statusText:(w=d.statusText)!=null?w:"Unknown Error",headers:d.headers}));return}const a=new g(s.headers),i=s.status,h=s.statusText;let c=null;s.body&&(c=await this._readBody(n,s,r)),i>=b.Ok&&i<b.MultipleChoices?r.next(new v({body:c,headers:a,status:i,statusText:h})):r.error(new f({error:c,status:i,statusText:h,headers:a})),r.complete()}async _readBody(n,r,t){var c;const s=[],a=r.body.getReader();let i=0;for(;;){const{done:l,value:o}=await a.read();if(l)break;s.push(o),i+=o.length}const h=X(s,i);try{const l=(c=r.headers.get("content-type"))!=null?c:"";return J(n,h,l)}catch(l){return t.error(new f({error:l,status:r.status,statusText:r.statusText,headers:new g(r.headers)})),null}}_parseFetchParamsFromRequest(n){return{method:n.method,headers:n.getHeadersInit(),body:n.getBody(),credentials:n.withCredentials?"include":void 0}}}function X(e,n){const r=new Uint8Array(n);let t=0;for(const s of e)r.set(s,t),t+=s.length;return r}const z=/^\)\]\}',?\n/;function J(e,n,r){switch(e.responseType){case"json":const t=new TextDecoder().decode(n).replace(z,"");return t===""?null:JSON.parse(t);case"text":return new TextDecoder().decode(n);case"blob":return new Blob([n],{type:r});case"arraybuffer":return n.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}class Y{send(n){return new m.Observable(r=>{const t=new XMLHttpRequest;t.open(n.method,n.getUrlWithParams()),n.withCredentials&&(t.withCredentials=!0),n.headers.forEach((c,l)=>t.setRequestHeader(c,l.join(","))),n.headers.has("Accept")||t.setRequestHeader("Accept","application/json, text/plain, */*"),n.headers.has("Content-Type")||t.setRequestHeader("Content-Type","application/json;charset=UTF-8");const s=()=>{const c=t.statusText||"OK",l=new g(t.getAllResponseHeaders());return new O(l,t.status,c)},a=()=>{const{headers:c,statusText:l,status:o}=s(),{responseType:w}=n;let d=null,E=null;o!==b.NoContent&&(d=typeof t.response>"u"?t.responseText:t.response);let R=o>=G&&o<W;if(w==="json"&&typeof d=="string"){const A=d;try{d=d?JSON.parse(d):null}catch(N){R=!1,d=A,E=N}}R?r.next(new v({body:d,headers:c,status:o,statusText:l})):r.error(new f({error:E,headers:c,status:o,statusText:l}))},i=c=>{const l=new f({error:c,status:t.status||0,statusText:t.statusText||"Unknown Error",headers:s().headers});r.error(l)};t.addEventListener("load",a),t.addEventListener("error",i),t.addEventListener("abort",i),t.addEventListener("timeout",i);const h=n.getBody();return t.send(h),()=>{t.readyState!==t.DONE&&t.abort(),t.removeEventListener("load",a),t.removeEventListener("error",i),t.removeEventListener("abort",i),t.removeEventListener("timeout",i)}})}}const K=L.createIdentifier("univer.socket");class Q extends y.Disposable{createSocket(n){try{const r=new WebSocket(n),t=new y.DisposableCollection;return{URL:n,close:(a,i)=>{r.close(a,i),t.dispose()},send:a=>{r.send(a)},open$:new m.Observable(a=>{const i=h=>a.next(h);r.addEventListener("open",i),t.add(y.toDisposable(()=>r.removeEventListener("open",i)))}).pipe(u.share()),close$:new m.Observable(a=>{const i=h=>a.next(h);r.addEventListener("close",i),t.add(y.toDisposable(()=>r.removeEventListener("close",i)))}).pipe(u.share()),error$:new m.Observable(a=>{const i=h=>a.next(h);r.addEventListener("error",i),t.add(y.toDisposable(()=>r.removeEventListener("error",i)))}).pipe(u.share()),message$:new m.Observable(a=>{const i=h=>a.next(h);r.addEventListener("message",i),t.add(y.toDisposable(()=>r.removeEventListener("message",i)))}).pipe(u.share())}}catch(r){return console.error(r),null}}}const Z=2,P=1e3,H=(e,n)=>n(e).pipe(u.retryWhen(r=>r.pipe(u.concatMap((t,s)=>s>Z?m.throwError(t):m.of(t)),m.delay(P)))),S=(e,n)=>{const r=[],t=new Set,s=()=>{var a;for(;t.size<((a=n==null?void 0:n.maxParallel)!=null?a:1)&&r.length>0;){const i=r.shift();t.add(i),i()}};return(a,i)=>new m.Observable(h=>{const c=()=>i(a).subscribe({next:o=>h.next(o),error:o=>h.next(o),complete:()=>h.complete()}),l=()=>{t.delete(c),y.remove(r,c),s()};return r.push(c),s(),l})};exports.FetchHTTPImplementation=V;exports.HTTPHeaders=g;exports.HTTPRequest=_;exports.HTTPResponse=v;exports.HTTPResponseError=f;exports.HTTPStatusCode=b;exports.IHTTPImplementation=q;exports.ISocketService=K;exports.ThresholdInterceptorFactory=S;exports.WebSocketService=Q;exports.XHRHTTPImplementation=Y;exports.retryInterceptor=H;
1
+ "use strict";var O=Object.defineProperty;var D=(e,t,r)=>t in e?O(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var p=(e,t,r)=>(D(e,typeof t!="symbol"?t+"":t,r),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const m=require("@univerjs/core"),y=require("rxjs"),g=require("rxjs/operators"),q=require("@wendellhu/redi"),L="application/json";class E{constructor(t){p(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}toHeadersInit(){var r,n;const t={};return this._headers.forEach((s,i)=>{t[i]=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 F=q.createIdentifier("network.http-implementation");class A{constructor(t){this.params=t}toString(){return this.params?Object.keys(this.params).map(t=>`${t}=${this.params[t]}`).join("&"):""}}let M=0;class I{constructor(t,r,n){p(this,"uid",M++);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:L,r=(s=this.requestParams)==null?void 0:s.body;return t===L&&r&&typeof r=="object"?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}var j=Object.defineProperty,B=Object.getOwnPropertyDescriptor,$=(e,t,r,n)=>{for(var s=n>1?void 0:n?B(t,r):t,i=e.length-1,o;i>=0;i--)(o=e[i])&&(s=(n?o(t,r,s):o(s))||s);return n&&s&&j(t,r,s),s},G=(e,t)=>(r,n)=>t(r,n,e);exports.HTTPService=class extends m.Disposable{constructor(r){super();p(this,"_interceptors",[]);p(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 i,o;return((i=n.priority)!=null?i:0)-((o=s.priority)!=null?o:0)}),this._pipe=null,m.toDisposable(()=>m.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 c,l;const i=new E(s==null?void 0:s.headers),o=new A(s==null?void 0:s.params),a=new I(r,n,{headers:i,params:o,withCredentials:(c=s==null?void 0:s.withCredentials)!=null?c:!1,reportProgress:!0,responseType:(l=s==null?void 0:s.responseType)!=null?l:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body});return y.of(a).pipe(g.concatMap(h=>this._runInterceptorsAndImplementation(h)))}async _request(r,n,s){var h,u;const i=new E(s==null?void 0:s.headers),o=new A(s==null?void 0:s.params),a=new I(r,n,{headers:i,params:o,withCredentials:(h=s==null?void 0:s.withCredentials)!=null?h:!1,responseType:(u=s==null?void 0:s.responseType)!=null?u:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body}),c=y.of(a).pipe(g.concatMap(d=>this._runInterceptorsAndImplementation(d)));return await y.firstValueFrom(c)}_runInterceptorsAndImplementation(r){return this._pipe||(this._pipe=this._interceptors.map(n=>n.interceptor).reduceRight((n,s)=>V(n,s),(n,s)=>s(n))),this._pipe(r,n=>this._http.send(n))}};exports.HTTPService=$([G(0,F)],exports.HTTPService);function V(e,t){return(r,n)=>t(r,s=>e(s,n))}var N=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(N||{});class x{constructor({body:t,headers:r,status:n,statusText:s}){p(this,"type",1);p(this,"body");p(this,"headers");p(this,"status");p(this,"statusText");this.body=t,this.headers=r,this.status=n,this.statusText=s}}class U{constructor(t,r,n){p(this,"type",0);this.total=t,this.loaded=r,this.partialText=n}}class k{constructor(t,r,n){this.headers=t,this.status=r,this.statusText=n}}class w{constructor({headers:t,status:r,statusText:n,error:s}){p(this,"headers");p(this,"status");p(this,"statusText");p(this,"error");this.headers=t,this.status=r,this.statusText=n,this.error=s}}const W=200,X=300;var _=(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))(_||{});class z{send(t){return new y.Observable(r=>{const n=new AbortController;return this._send(t,r,n).then(()=>{},s=>{r.error(new w({error:s}))}),()=>n.abort()})}async _send(t,r,n){var h,u;let s;try{const d=this._parseFetchParamsFromRequest(t);s=await fetch(t.getUrlWithParams(),{signal:n.signal,...d})}catch(d){r.error(new w({error:d,status:(h=d.status)!=null?h:0,statusText:(u=d.statusText)!=null?u:"Unknown Error",headers:d.headers}));return}const i=new E(s.headers),o=s.status,a=s.statusText;let c=null;s.body&&(c=await this._readBody(t,s,r)),o>=_.Ok&&o<_.MultipleChoices?r.next(new x({body:c,headers:i,status:o,statusText:a})):r.error(new w({error:c,status:o,statusText:a,headers:i})),r.complete()}async _readBody(t,r,n){var v,R;const s=[],i=r.body.getReader(),o=r.headers.get("content-length");let a=0;const c=(v=t.requestParams)==null?void 0:v.reportProgress,l=t.responseType;let h,u;for(;;){const{done:f,value:b}=await i.read();if(f)break;s.push(b),a+=b.length,c&&l==="text"&&(h=(h!=null?h:"")+(u!=null?u:u=new TextDecoder).decode(b,{stream:!0}),n.next(new U(o?Number.parseInt(o,10):void 0,a,h)))}const d=J(s,a);try{const f=(R=r.headers.get("content-type"))!=null?R:"";return K(t,d,f)}catch(f){return n.error(new w({error:f,status:r.status,statusText:r.statusText,headers:new E(r.headers)})),null}}_parseFetchParamsFromRequest(t){return{method:t.method,headers:t.getHeadersInit(),body:t.getBody(),credentials:t.withCredentials?"include":void 0}}}function J(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 Y=/^\)\]\}',?\n/;function K(e,t,r){switch(e.responseType){case"json":const n=new TextDecoder().decode(t).replace(Y,"");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}.`)}}class Q{send(t){return new y.Observable(r=>{const n=new XMLHttpRequest;n.open(t.method,t.getUrlWithParams()),t.withCredentials&&(n.withCredentials=!0),t.headers.forEach((c,l)=>n.setRequestHeader(c,l.join(","))),t.headers.has("Accept")||n.setRequestHeader("Accept","application/json, text/plain, */*"),t.headers.has("Content-Type")||n.setRequestHeader("Content-Type","application/json;charset=UTF-8");const s=()=>{const c=n.statusText||"OK",l=new E(n.getAllResponseHeaders());return new k(l,n.status,c)},i=()=>{const{headers:c,statusText:l,status:h}=s(),{responseType:u}=t;let d=null,v=null;h!==_.NoContent&&(d=typeof n.response>"u"?n.responseText:n.response);let R=h>=W&&h<X;if(u==="json"&&typeof d=="string"){const f=d;try{d=d?JSON.parse(d):null}catch(b){R=!1,d=f,v=b}}R?r.next(new x({body:d,headers:c,status:h,statusText:l})):r.error(new w({error:v,headers:c,status:h,statusText:l}))},o=c=>{const l=new w({error:c,status:n.status||0,statusText:n.statusText||"Unknown Error",headers:s().headers});r.error(l)};n.addEventListener("load",i),n.addEventListener("error",o),n.addEventListener("abort",o),n.addEventListener("timeout",o);const a=t.getBody();return n.send(a),()=>{n.readyState!==n.DONE&&n.abort(),n.removeEventListener("load",i),n.removeEventListener("error",o),n.removeEventListener("abort",o),n.removeEventListener("timeout",o)}})}}const Z=q.createIdentifier("univer.socket");class P extends m.Disposable{createSocket(t){try{const r=new WebSocket(t),n=new m.DisposableCollection;return{URL:t,close:(i,o)=>{r.close(i,o),n.dispose()},send:i=>{r.send(i)},open$:new y.Observable(i=>{const o=a=>i.next(a);r.addEventListener("open",o),n.add(m.toDisposable(()=>r.removeEventListener("open",o)))}).pipe(g.share()),close$:new y.Observable(i=>{const o=a=>i.next(a);r.addEventListener("close",o),n.add(m.toDisposable(()=>r.removeEventListener("close",o)))}).pipe(g.share()),error$:new y.Observable(i=>{const o=a=>i.next(a);r.addEventListener("error",o),n.add(m.toDisposable(()=>r.removeEventListener("error",o)))}).pipe(g.share()),message$:new y.Observable(i=>{const o=a=>i.next(a);r.addEventListener("message",o),n.add(m.toDisposable(()=>r.removeEventListener("message",o)))}).pipe(g.share())}}catch(r){return console.error(r),null}}}const H=3,S=1e3,C=(e,t)=>{var s,i;const r=(s=t==null?void 0:t.maxRetryAttempts)!=null?s:H,n=(i=t==null?void 0:t.delayInterval)!=null?i:S;return(o,a)=>a(o).pipe(g.retry({delay:n,count:r}))},T=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 i=t.shift();r.add(i),i()}};return(s,i)=>new y.Observable(o=>{const a=()=>i(s).subscribe({next:l=>o.next(l),error:l=>o.next(l),complete:()=>o.complete()}),c=()=>{r.delete(a),m.remove(t,a),n()};return t.push(a),n(),c})},ee=e=>{const{errorStatusCodes:t,onAuthError:r}=e;return(s,i)=>i(s).pipe(y.catchError(o=>(o instanceof w&&t.some(a=>a===o.status)&&r(),y.throwError(()=>o))))};exports.AuthInterceptorFactory=ee;exports.FetchHTTPImplementation=z;exports.HTTPEventType=N;exports.HTTPHeaders=E;exports.HTTPProgress=U;exports.HTTPRequest=I;exports.HTTPResponse=x;exports.HTTPResponseError=w;exports.HTTPStatusCode=_;exports.IHTTPImplementation=F;exports.ISocketService=Z;exports.ResponseHeader=k;exports.RetryInterceptorFactory=C;exports.ThresholdInterceptorFactory=T;exports.WebSocketService=P;exports.XHRHTTPImplementation=Q;
package/lib/es/index.js CHANGED
@@ -1,65 +1,65 @@
1
- var O = Object.defineProperty;
2
- var j = (e, t, n) => t in e ? O(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
- var p = (e, t, n) => (j(e, typeof t != "symbol" ? t + "" : t, n), n);
4
- import { Disposable as N, toDisposable as w, remove as U, DisposableCollection as D } from "@univerjs/core";
5
- import { of as v, firstValueFrom as B, Observable as m, throwError as $, delay as G } from "rxjs";
6
- import { concatMap as R, map as V, share as g, retryWhen as W } from "rxjs/operators";
7
- import { createIdentifier as F } from "@wendellhu/redi";
1
+ var D = Object.defineProperty;
2
+ var O = (e, r, n) => r in e ? D(e, r, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[r] = n;
3
+ var p = (e, r, n) => (O(e, typeof r != "symbol" ? r + "" : r, n), n);
4
+ import { Disposable as q, toDisposable as _, remove as U, DisposableCollection as j } from "@univerjs/core";
5
+ import { of as b, firstValueFrom as B, Observable as u, catchError as $, throwError as G } from "rxjs";
6
+ import { concatMap as I, share as v, retry as V } from "rxjs/operators";
7
+ import { createIdentifier as k } from "@wendellhu/redi";
8
8
  const L = "application/json";
9
- class u {
10
- constructor(t) {
9
+ class R {
10
+ constructor(r) {
11
11
  p(this, "_headers", /* @__PURE__ */ new Map());
12
- typeof t == "string" ? this._handleHeadersString(t) : t instanceof Headers ? this._handleHeaders(t) : t && this._handleHeadersConstructorProps(t);
12
+ typeof r == "string" ? this._handleHeadersString(r) : r instanceof Headers ? this._handleHeaders(r) : r && this._handleHeadersConstructorProps(r);
13
13
  }
14
- forEach(t) {
15
- this._headers.forEach((n, r) => t(r, n));
14
+ forEach(r) {
15
+ this._headers.forEach((n, t) => r(t, n));
16
16
  }
17
- has(t) {
18
- return !!this._headers.has(t.toLowerCase());
17
+ has(r) {
18
+ return !!this._headers.has(r.toLowerCase());
19
19
  }
20
- get(t) {
21
- const n = t.toLowerCase();
20
+ get(r) {
21
+ const n = r.toLowerCase();
22
22
  return this._headers.has(n) ? this._headers.get(n) : null;
23
23
  }
24
24
  toHeadersInit() {
25
- var n, r;
26
- const t = {};
27
- return this._headers.forEach((s, a) => {
28
- t[a] = s.join(",");
29
- }), (n = t.accept) != null || (t.accept = "application/json, text/plain, */*"), (r = t["content-type"]) != null || (t["content-type"] = "application/json;charset=UTF-8"), t;
30
- }
31
- _setHeader(t, n) {
32
- const r = t.toLowerCase();
33
- this._headers.has(r) ? this._headers.get(r).push(n.toString()) : this._headers.set(r, [n.toString()]);
34
- }
35
- _handleHeadersString(t) {
36
- t.split(`
25
+ var n, t;
26
+ const r = {};
27
+ return this._headers.forEach((s, o) => {
28
+ r[o] = s.join(",");
29
+ }), (n = r.accept) != null || (r.accept = "application/json, text/plain, */*"), (t = r["content-type"]) != null || (r["content-type"] = "application/json;charset=UTF-8"), r;
30
+ }
31
+ _setHeader(r, n) {
32
+ const t = r.toLowerCase();
33
+ this._headers.has(t) ? this._headers.get(t).push(n.toString()) : this._headers.set(t, [n.toString()]);
34
+ }
35
+ _handleHeadersString(r) {
36
+ r.split(`
37
37
  `).forEach((n) => {
38
- const [r, s] = n.split(":");
39
- r && s && this._setHeader(r, s);
38
+ const [t, s] = n.split(":");
39
+ t && s && this._setHeader(t, s);
40
40
  });
41
41
  }
42
- _handleHeadersConstructorProps(t) {
43
- Object.entries(t).forEach(([n, r]) => this._setHeader(n, r));
42
+ _handleHeadersConstructorProps(r) {
43
+ Object.entries(r).forEach(([n, t]) => this._setHeader(n, t));
44
44
  }
45
- _handleHeaders(t) {
46
- t.forEach((n, r) => this._setHeader(r, n));
45
+ _handleHeaders(r) {
46
+ r.forEach((n, t) => this._setHeader(t, n));
47
47
  }
48
48
  }
49
- const X = F("network.http-implementation");
50
- class I {
51
- constructor(t) {
52
- this.params = t;
49
+ const W = k("network.http-implementation");
50
+ class A {
51
+ constructor(r) {
52
+ this.params = r;
53
53
  }
54
54
  toString() {
55
- return this.params ? Object.keys(this.params).map((t) => `${t}=${this.params[t]}`).join("&") : "";
55
+ return this.params ? Object.keys(this.params).map((r) => `${r}=${this.params[r]}`).join("&") : "";
56
56
  }
57
57
  }
58
- let z = 0;
59
- class A {
60
- constructor(t, n, r) {
61
- p(this, "uid", z++);
62
- this.method = t, this.url = n, this.requestParams = r;
58
+ let X = 0;
59
+ class N {
60
+ constructor(r, n, t) {
61
+ p(this, "uid", X++);
62
+ this.method = r, this.url = n, this.requestParams = t;
63
63
  }
64
64
  get headers() {
65
65
  return this.requestParams.headers;
@@ -71,64 +71,31 @@ class A {
71
71
  return this.requestParams.responseType;
72
72
  }
73
73
  getUrlWithParams() {
74
- var n, r;
75
- const t = (r = (n = this.requestParams) == null ? void 0 : n.params) == null ? void 0 : r.toString();
76
- return t ? `${this.url}${this.url.includes("?") ? "&" : "?"}${t}` : this.url;
74
+ var n, t;
75
+ const r = (t = (n = this.requestParams) == null ? void 0 : n.params) == null ? void 0 : t.toString();
76
+ return r ? `${this.url}${this.url.includes("?") ? "&" : "?"}${r}` : this.url;
77
77
  }
78
78
  getBody() {
79
- var r, s;
80
- const t = (r = this.headers.get("Content-Type")) != null ? r : L, n = (s = this.requestParams) == null ? void 0 : s.body;
81
- return t === L && n && typeof n == "object" ? JSON.stringify(n) : n ? `${n}` : null;
79
+ var t, s;
80
+ const r = (t = this.headers.get("Content-Type")) != null ? t : L, n = (s = this.requestParams) == null ? void 0 : s.body;
81
+ return r === L && n && typeof n == "object" ? JSON.stringify(n) : n ? `${n}` : null;
82
82
  }
83
83
  getHeadersInit() {
84
84
  return this.headers.toHeadersInit();
85
85
  }
86
86
  }
87
- class b {
88
- constructor({
89
- body: t,
90
- headers: n,
91
- status: r,
92
- statusText: s
93
- }) {
94
- p(this, "body");
95
- p(this, "headers");
96
- p(this, "status");
97
- p(this, "statusText");
98
- this.body = t, this.headers = n, this.status = r, this.statusText = s;
99
- }
100
- }
101
- class y {
102
- constructor({
103
- headers: t,
104
- status: n,
105
- statusText: r,
106
- error: s
107
- }) {
108
- p(this, "headers");
109
- p(this, "status");
110
- p(this, "statusText");
111
- p(this, "error");
112
- this.headers = t, this.status = n, this.statusText = r, this.error = s;
113
- }
114
- }
115
- class J {
116
- constructor(t, n, r) {
117
- this.headers = t, this.status = n, this.statusText = r;
118
- }
119
- }
120
- var Y = Object.defineProperty, K = Object.getOwnPropertyDescriptor, Q = (e, t, n, r) => {
121
- for (var s = r > 1 ? void 0 : r ? K(t, n) : t, a = e.length - 1, i; a >= 0; a--)
122
- (i = e[a]) && (s = (r ? i(t, n, s) : i(s)) || s);
123
- return r && s && Y(t, n, s), s;
124
- }, Z = (e, t) => (n, r) => t(n, r, e);
125
- let q = class extends N {
126
- constructor(t) {
87
+ var z = Object.defineProperty, J = Object.getOwnPropertyDescriptor, Y = (e, r, n, t) => {
88
+ for (var s = t > 1 ? void 0 : t ? J(r, n) : r, o = e.length - 1, i; o >= 0; o--)
89
+ (i = e[o]) && (s = (t ? i(r, n, s) : i(s)) || s);
90
+ return t && s && z(r, n, s), s;
91
+ }, K = (e, r) => (n, t) => r(n, t, e);
92
+ let F = class extends q {
93
+ constructor(r) {
127
94
  super();
128
95
  p(this, "_interceptors", []);
129
96
  // eslint-disable-next-line ts/no-explicit-any
130
97
  p(this, "_pipe");
131
- this._http = t;
98
+ this._http = r;
132
99
  }
133
100
  /**
134
101
  * Register an HTTP interceptor.
@@ -136,308 +103,354 @@ let q = class extends N {
136
103
  * @param interceptor the http interceptor
137
104
  * @returns a disposable handler to remove the interceptor
138
105
  */
139
- registerHTTPInterceptor(t) {
140
- if (this._interceptors.indexOf(t) !== -1)
106
+ registerHTTPInterceptor(r) {
107
+ if (this._interceptors.indexOf(r) !== -1)
141
108
  throw new Error("[HTTPService]: The interceptor has already been registered!");
142
- return this._interceptors.push(t), this._interceptors = this._interceptors.sort((n, r) => {
143
- var s, a;
144
- return ((s = n.priority) != null ? s : 0) - ((a = r.priority) != null ? a : 0);
145
- }), this._pipe = null, w(() => U(this._interceptors, t));
109
+ return this._interceptors.push(r), this._interceptors = this._interceptors.sort((n, t) => {
110
+ var s, o;
111
+ return ((s = n.priority) != null ? s : 0) - ((o = t.priority) != null ? o : 0);
112
+ }), this._pipe = null, _(() => U(this._interceptors, r));
146
113
  }
147
- get(t, n) {
148
- return this._request("GET", t, n);
114
+ get(r, n) {
115
+ return this._request("GET", r, n);
149
116
  }
150
- post(t, n) {
151
- return this._request("POST", t, n);
117
+ post(r, n) {
118
+ return this._request("POST", r, n);
152
119
  }
153
- put(t, n) {
154
- return this._request("PUT", t, n);
120
+ put(r, n) {
121
+ return this._request("PUT", r, n);
155
122
  }
156
- delete(t, n) {
157
- return this._request("DELETE", t, n);
123
+ delete(r, n) {
124
+ return this._request("DELETE", r, n);
158
125
  }
159
- patch(t, n) {
160
- return this._request("PATCH", t, n);
126
+ patch(r, n) {
127
+ return this._request("PATCH", r, n);
161
128
  }
162
- getSSE(t, n, r) {
163
- var l, c;
164
- const s = new u(r == null ? void 0 : r.headers), a = new I(r == null ? void 0 : r.params), i = new A(t, n, {
129
+ getSSE(r, n, t) {
130
+ var a, c;
131
+ const s = new R(t == null ? void 0 : t.headers), o = new A(t == null ? void 0 : t.params), i = new N(r, n, {
165
132
  headers: s,
166
- params: a,
167
- withCredentials: (l = r == null ? void 0 : r.withCredentials) != null ? l : !1,
168
- // default value for withCredentials is false by MDN
169
- responseType: (c = r == null ? void 0 : r.responseType) != null ? c : "json",
170
- body: ["GET", "DELETE"].includes(t) || r == null ? void 0 : r.body
133
+ params: o,
134
+ withCredentials: (a = t == null ? void 0 : t.withCredentials) != null ? a : !1,
135
+ reportProgress: !0,
136
+ responseType: (c = t == null ? void 0 : t.responseType) != null ? c : "json",
137
+ body: ["GET", "DELETE"].includes(r) || t == null ? void 0 : t.body
171
138
  });
172
- return v(i).pipe(
173
- R((o) => this._runInterceptorsAndImplementation(o)),
174
- V((o) => {
175
- if (o instanceof y)
176
- throw o;
177
- return o;
178
- })
179
- );
139
+ return b(i).pipe(I((l) => this._runInterceptorsAndImplementation(l)));
180
140
  }
181
141
  /** The HTTP request implementations */
182
- async _request(t, n, r) {
183
- var o, h;
184
- const s = new u(r == null ? void 0 : r.headers), a = new I(r == null ? void 0 : r.params), i = new A(t, n, {
142
+ async _request(r, n, t) {
143
+ var l, h;
144
+ const s = new R(t == null ? void 0 : t.headers), o = new A(t == null ? void 0 : t.params), i = new N(r, n, {
185
145
  headers: s,
186
- params: a,
187
- withCredentials: (o = r == null ? void 0 : r.withCredentials) != null ? o : !1,
146
+ params: o,
147
+ withCredentials: (l = t == null ? void 0 : t.withCredentials) != null ? l : !1,
188
148
  // default value for withCredentials is false by MDN
189
- responseType: (h = r == null ? void 0 : r.responseType) != null ? h : "json",
190
- body: ["GET", "DELETE"].includes(t) || r == null ? void 0 : r.body
191
- }), l = v(i).pipe(
192
- R((f) => this._runInterceptorsAndImplementation(f))
193
- ), c = await B(l);
194
- if (c instanceof b)
195
- return c;
196
- throw new Error(`${c.error}`);
149
+ responseType: (h = t == null ? void 0 : t.responseType) != null ? h : "json",
150
+ body: ["GET", "DELETE"].includes(r) || t == null ? void 0 : t.body
151
+ }), a = b(i).pipe(
152
+ I((y) => this._runInterceptorsAndImplementation(y))
153
+ );
154
+ return await B(a);
197
155
  }
198
156
  // eslint-disable-next-line ts/no-explicit-any
199
- _runInterceptorsAndImplementation(t) {
157
+ _runInterceptorsAndImplementation(r) {
200
158
  return this._pipe || (this._pipe = this._interceptors.map((n) => n.interceptor).reduceRight(
201
- (n, r) => P(n, r),
202
- (n, r) => r(n)
159
+ (n, t) => Q(n, t),
160
+ (n, t) => t(n)
203
161
  )), this._pipe(
204
- t,
162
+ r,
205
163
  (n) => this._http.send(n)
206
164
  /* final handler */
207
165
  );
208
166
  }
209
167
  };
210
- q = Q([
211
- Z(0, X)
212
- ], q);
213
- function P(e, t) {
214
- return (n, r) => t(n, (s) => e(s, r));
168
+ F = Y([
169
+ K(0, W)
170
+ ], F);
171
+ function Q(e, r) {
172
+ return (n, t) => r(n, (s) => e(s, t));
215
173
  }
216
- const H = 200, S = 300;
217
- var E = /* @__PURE__ */ ((e) => (e[e.Continue = 100] = "Continue", e[e.SwitchingProtocols = 101] = "SwitchingProtocols", e[e.Processing = 102] = "Processing", e[e.EarlyHints = 103] = "EarlyHints", e[e.Ok = 200] = "Ok", e[e.Created = 201] = "Created", e[e.Accepted = 202] = "Accepted", e[e.NonAuthoritativeInformation = 203] = "NonAuthoritativeInformation", e[e.NoContent = 204] = "NoContent", e[e.ResetContent = 205] = "ResetContent", e[e.PartialContent = 206] = "PartialContent", e[e.MultiStatus = 207] = "MultiStatus", e[e.AlreadyReported = 208] = "AlreadyReported", e[e.ImUsed = 226] = "ImUsed", e[e.MultipleChoices = 300] = "MultipleChoices", e[e.MovedPermanently = 301] = "MovedPermanently", e[e.Found = 302] = "Found", e[e.SeeOther = 303] = "SeeOther", e[e.NotModified = 304] = "NotModified", e[e.UseProxy = 305] = "UseProxy", e[e.Unused = 306] = "Unused", e[e.TemporaryRedirect = 307] = "TemporaryRedirect", e[e.PermanentRedirect = 308] = "PermanentRedirect", e[e.BadRequest = 400] = "BadRequest", e[e.Unauthorized = 401] = "Unauthorized", e[e.PaymentRequired = 402] = "PaymentRequired", e[e.Forbidden = 403] = "Forbidden", e[e.NotFound = 404] = "NotFound", e[e.MethodNotAllowed = 405] = "MethodNotAllowed", e[e.NotAcceptable = 406] = "NotAcceptable", e[e.ProxyAuthenticationRequired = 407] = "ProxyAuthenticationRequired", e[e.RequestTimeout = 408] = "RequestTimeout", e[e.Conflict = 409] = "Conflict", e[e.Gone = 410] = "Gone", e[e.LengthRequired = 411] = "LengthRequired", e[e.PreconditionFailed = 412] = "PreconditionFailed", e[e.PayloadTooLarge = 413] = "PayloadTooLarge", e[e.UriTooLong = 414] = "UriTooLong", e[e.UnsupportedMediaType = 415] = "UnsupportedMediaType", e[e.RangeNotSatisfiable = 416] = "RangeNotSatisfiable", e[e.ExpectationFailed = 417] = "ExpectationFailed", e[e.ImATeapot = 418] = "ImATeapot", e[e.MisdirectedRequest = 421] = "MisdirectedRequest", e[e.UnprocessableEntity = 422] = "UnprocessableEntity", e[e.Locked = 423] = "Locked", e[e.FailedDependency = 424] = "FailedDependency", e[e.TooEarly = 425] = "TooEarly", e[e.UpgradeRequired = 426] = "UpgradeRequired", e[e.PreconditionRequired = 428] = "PreconditionRequired", e[e.TooManyRequests = 429] = "TooManyRequests", e[e.RequestHeaderFieldsTooLarge = 431] = "RequestHeaderFieldsTooLarge", e[e.UnavailableForLegalReasons = 451] = "UnavailableForLegalReasons", e[e.InternalServerError = 500] = "InternalServerError", e[e.NotImplemented = 501] = "NotImplemented", e[e.BadGateway = 502] = "BadGateway", e[e.ServiceUnavailable = 503] = "ServiceUnavailable", e[e.GatewayTimeout = 504] = "GatewayTimeout", e[e.HttpVersionNotSupported = 505] = "HttpVersionNotSupported", e[e.VariantAlsoNegotiates = 506] = "VariantAlsoNegotiates", e[e.InsufficientStorage = 507] = "InsufficientStorage", e[e.LoopDetected = 508] = "LoopDetected", e[e.NotExtended = 510] = "NotExtended", e[e.NetworkAuthenticationRequired = 511] = "NetworkAuthenticationRequired", e))(E || {});
218
- class oe {
219
- send(t) {
220
- return new m((n) => {
221
- const r = new AbortController();
222
- return this._send(t, n, r).then(() => {
174
+ var Z = /* @__PURE__ */ ((e) => (e[e.DownloadProgress = 0] = "DownloadProgress", e[e.Response = 1] = "Response", e))(Z || {});
175
+ class M {
176
+ constructor({
177
+ body: r,
178
+ headers: n,
179
+ status: t,
180
+ statusText: s
181
+ }) {
182
+ p(this, "type", 1);
183
+ p(this, "body");
184
+ p(this, "headers");
185
+ p(this, "status");
186
+ p(this, "statusText");
187
+ this.body = r, this.headers = n, this.status = t, this.statusText = s;
188
+ }
189
+ }
190
+ class P {
191
+ constructor(r, n, t) {
192
+ p(this, "type", 0);
193
+ this.total = r, this.loaded = n, this.partialText = t;
194
+ }
195
+ }
196
+ class S {
197
+ constructor(r, n, t) {
198
+ this.headers = r, this.status = n, this.statusText = t;
199
+ }
200
+ }
201
+ class w {
202
+ constructor({
203
+ headers: r,
204
+ status: n,
205
+ statusText: t,
206
+ error: s
207
+ }) {
208
+ p(this, "headers");
209
+ p(this, "status");
210
+ p(this, "statusText");
211
+ p(this, "error");
212
+ this.headers = r, this.status = n, this.statusText = t, this.error = s;
213
+ }
214
+ }
215
+ const H = 200, C = 300;
216
+ var x = /* @__PURE__ */ ((e) => (e[e.Continue = 100] = "Continue", e[e.SwitchingProtocols = 101] = "SwitchingProtocols", e[e.Processing = 102] = "Processing", e[e.EarlyHints = 103] = "EarlyHints", e[e.Ok = 200] = "Ok", e[e.Created = 201] = "Created", e[e.Accepted = 202] = "Accepted", e[e.NonAuthoritativeInformation = 203] = "NonAuthoritativeInformation", e[e.NoContent = 204] = "NoContent", e[e.ResetContent = 205] = "ResetContent", e[e.PartialContent = 206] = "PartialContent", e[e.MultiStatus = 207] = "MultiStatus", e[e.AlreadyReported = 208] = "AlreadyReported", e[e.ImUsed = 226] = "ImUsed", e[e.MultipleChoices = 300] = "MultipleChoices", e[e.MovedPermanently = 301] = "MovedPermanently", e[e.Found = 302] = "Found", e[e.SeeOther = 303] = "SeeOther", e[e.NotModified = 304] = "NotModified", e[e.UseProxy = 305] = "UseProxy", e[e.Unused = 306] = "Unused", e[e.TemporaryRedirect = 307] = "TemporaryRedirect", e[e.PermanentRedirect = 308] = "PermanentRedirect", e[e.BadRequest = 400] = "BadRequest", e[e.Unauthorized = 401] = "Unauthorized", e[e.PaymentRequired = 402] = "PaymentRequired", e[e.Forbidden = 403] = "Forbidden", e[e.NotFound = 404] = "NotFound", e[e.MethodNotAllowed = 405] = "MethodNotAllowed", e[e.NotAcceptable = 406] = "NotAcceptable", e[e.ProxyAuthenticationRequired = 407] = "ProxyAuthenticationRequired", e[e.RequestTimeout = 408] = "RequestTimeout", e[e.Conflict = 409] = "Conflict", e[e.Gone = 410] = "Gone", e[e.LengthRequired = 411] = "LengthRequired", e[e.PreconditionFailed = 412] = "PreconditionFailed", e[e.PayloadTooLarge = 413] = "PayloadTooLarge", e[e.UriTooLong = 414] = "UriTooLong", e[e.UnsupportedMediaType = 415] = "UnsupportedMediaType", e[e.RangeNotSatisfiable = 416] = "RangeNotSatisfiable", e[e.ExpectationFailed = 417] = "ExpectationFailed", e[e.ImATeapot = 418] = "ImATeapot", e[e.MisdirectedRequest = 421] = "MisdirectedRequest", e[e.UnprocessableEntity = 422] = "UnprocessableEntity", e[e.Locked = 423] = "Locked", e[e.FailedDependency = 424] = "FailedDependency", e[e.TooEarly = 425] = "TooEarly", e[e.UpgradeRequired = 426] = "UpgradeRequired", e[e.PreconditionRequired = 428] = "PreconditionRequired", e[e.TooManyRequests = 429] = "TooManyRequests", e[e.RequestHeaderFieldsTooLarge = 431] = "RequestHeaderFieldsTooLarge", e[e.UnavailableForLegalReasons = 451] = "UnavailableForLegalReasons", e[e.InternalServerError = 500] = "InternalServerError", e[e.NotImplemented = 501] = "NotImplemented", e[e.BadGateway = 502] = "BadGateway", e[e.ServiceUnavailable = 503] = "ServiceUnavailable", e[e.GatewayTimeout = 504] = "GatewayTimeout", e[e.HttpVersionNotSupported = 505] = "HttpVersionNotSupported", e[e.VariantAlsoNegotiates = 506] = "VariantAlsoNegotiates", e[e.InsufficientStorage = 507] = "InsufficientStorage", e[e.LoopDetected = 508] = "LoopDetected", e[e.NotExtended = 510] = "NotExtended", e[e.NetworkAuthenticationRequired = 511] = "NetworkAuthenticationRequired", e))(x || {});
217
+ class le {
218
+ send(r) {
219
+ return new u((n) => {
220
+ const t = new AbortController();
221
+ return this._send(r, n, t).then(() => {
223
222
  }, (s) => {
224
- n.error(new y({
223
+ n.error(new w({
225
224
  error: s
226
225
  }));
227
- }), () => r.abort();
226
+ }), () => t.abort();
228
227
  });
229
228
  }
230
- async _send(t, n, r) {
231
- var h, f;
229
+ async _send(r, n, t) {
230
+ var h, y;
232
231
  let s;
233
232
  try {
234
- const d = this._parseFetchParamsFromRequest(t);
235
- s = await fetch(t.getUrlWithParams(), {
236
- signal: r.signal,
233
+ const d = this._parseFetchParamsFromRequest(r);
234
+ s = await fetch(r.getUrlWithParams(), {
235
+ signal: t.signal,
237
236
  ...d
238
237
  });
239
238
  } catch (d) {
240
- n.error(new y({
239
+ n.error(new w({
241
240
  error: d,
242
241
  status: (h = d.status) != null ? h : 0,
243
- statusText: (f = d.statusText) != null ? f : "Unknown Error",
242
+ statusText: (y = d.statusText) != null ? y : "Unknown Error",
244
243
  headers: d.headers
245
244
  }));
246
245
  return;
247
246
  }
248
- const a = new u(s.headers), i = s.status, l = s.statusText;
247
+ const o = new R(s.headers), i = s.status, a = s.statusText;
249
248
  let c = null;
250
- s.body && (c = await this._readBody(t, s, n)), i >= E.Ok && i < E.MultipleChoices ? n.next(new b({
249
+ s.body && (c = await this._readBody(r, s, n)), i >= x.Ok && i < x.MultipleChoices ? n.next(new M({
251
250
  body: c,
252
- headers: a,
251
+ headers: o,
253
252
  status: i,
254
- statusText: l
255
- })) : n.error(new y({
253
+ statusText: a
254
+ })) : n.error(new w({
256
255
  error: c,
257
256
  status: i,
258
- statusText: l,
259
- headers: a
257
+ statusText: a,
258
+ headers: o
260
259
  })), n.complete();
261
260
  }
262
- async _readBody(t, n, r) {
263
- var c;
264
- const s = [], a = n.body.getReader();
265
- let i = 0;
261
+ async _readBody(r, n, t) {
262
+ var f, E;
263
+ const s = [], o = n.body.getReader(), i = n.headers.get("content-length");
264
+ let a = 0;
265
+ const c = (f = r.requestParams) == null ? void 0 : f.reportProgress, l = r.responseType;
266
+ let h, y;
266
267
  for (; ; ) {
267
- const { done: o, value: h } = await a.read();
268
- if (o)
268
+ const { done: m, value: g } = await o.read();
269
+ if (m)
269
270
  break;
270
- s.push(h), i += h.length;
271
+ s.push(g), a += g.length, c && l === "text" && (h = (h != null ? h : "") + (y != null ? y : y = new TextDecoder()).decode(g, { stream: !0 }), t.next(new P(
272
+ i ? Number.parseInt(i, 10) : void 0,
273
+ a,
274
+ h
275
+ )));
271
276
  }
272
- const l = C(s, i);
277
+ const d = T(s, a);
273
278
  try {
274
- const o = (c = n.headers.get("content-type")) != null ? c : "";
275
- return ee(t, l, o);
276
- } catch (o) {
277
- return r.error(new y({
278
- error: o,
279
+ const m = (E = n.headers.get("content-type")) != null ? E : "";
280
+ return re(r, d, m);
281
+ } catch (m) {
282
+ return t.error(new w({
283
+ error: m,
279
284
  status: n.status,
280
285
  statusText: n.statusText,
281
- headers: new u(n.headers)
286
+ headers: new R(n.headers)
282
287
  })), null;
283
288
  }
284
289
  }
285
- _parseFetchParamsFromRequest(t) {
290
+ _parseFetchParamsFromRequest(r) {
286
291
  return {
287
- method: t.method,
288
- headers: t.getHeadersInit(),
289
- body: t.getBody(),
290
- credentials: t.withCredentials ? "include" : void 0
292
+ method: r.method,
293
+ headers: r.getHeadersInit(),
294
+ body: r.getBody(),
295
+ credentials: r.withCredentials ? "include" : void 0
291
296
  };
292
297
  }
293
298
  }
294
- function C(e, t) {
295
- const n = new Uint8Array(t);
296
- let r = 0;
299
+ function T(e, r) {
300
+ const n = new Uint8Array(r);
301
+ let t = 0;
297
302
  for (const s of e)
298
- n.set(s, r), r += s.length;
303
+ n.set(s, t), t += s.length;
299
304
  return n;
300
305
  }
301
- const T = /^\)\]\}',?\n/;
302
- function ee(e, t, n) {
306
+ const ee = /^\)\]\}',?\n/;
307
+ function re(e, r, n) {
303
308
  switch (e.responseType) {
304
309
  case "json":
305
- const r = new TextDecoder().decode(t).replace(T, "");
306
- return r === "" ? null : JSON.parse(r);
310
+ const t = new TextDecoder().decode(r).replace(ee, "");
311
+ return t === "" ? null : JSON.parse(t);
307
312
  case "text":
308
- return new TextDecoder().decode(t);
313
+ return new TextDecoder().decode(r);
309
314
  case "blob":
310
- return new Blob([t], { type: n });
315
+ return new Blob([r], { type: n });
311
316
  case "arraybuffer":
312
- return t.buffer;
317
+ return r.buffer;
313
318
  default:
314
319
  throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`);
315
320
  }
316
321
  }
317
- class le {
318
- send(t) {
319
- return new m((n) => {
320
- const r = new XMLHttpRequest();
321
- r.open(t.method, t.getUrlWithParams()), t.withCredentials && (r.withCredentials = !0), t.headers.forEach((c, o) => r.setRequestHeader(c, o.join(","))), t.headers.has("Accept") || r.setRequestHeader("Accept", "application/json, text/plain, */*"), t.headers.has("Content-Type") || r.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
322
+ class he {
323
+ send(r) {
324
+ return new u((n) => {
325
+ const t = new XMLHttpRequest();
326
+ t.open(r.method, r.getUrlWithParams()), r.withCredentials && (t.withCredentials = !0), r.headers.forEach((c, l) => t.setRequestHeader(c, l.join(","))), r.headers.has("Accept") || t.setRequestHeader("Accept", "application/json, text/plain, */*"), r.headers.has("Content-Type") || t.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
322
327
  const s = () => {
323
- const c = r.statusText || "OK", o = new u(r.getAllResponseHeaders());
324
- return new J(o, r.status, c);
325
- }, a = () => {
326
- const { headers: c, statusText: o, status: h } = s(), { responseType: f } = t;
327
- let d = null, _ = null;
328
- h !== E.NoContent && (d = typeof r.response > "u" ? r.responseText : r.response);
329
- let x = h >= H && h < S;
330
- if (f === "json" && typeof d == "string") {
331
- const k = d;
328
+ const c = t.statusText || "OK", l = new R(t.getAllResponseHeaders());
329
+ return new S(l, t.status, c);
330
+ }, o = () => {
331
+ const { headers: c, statusText: l, status: h } = s(), { responseType: y } = r;
332
+ let d = null, f = null;
333
+ h !== x.NoContent && (d = typeof t.response > "u" ? t.responseText : t.response);
334
+ let E = h >= H && h < C;
335
+ if (y === "json" && typeof d == "string") {
336
+ const m = d;
332
337
  try {
333
338
  d = d ? JSON.parse(d) : null;
334
- } catch (M) {
335
- x = !1, d = k, _ = M;
339
+ } catch (g) {
340
+ E = !1, d = m, f = g;
336
341
  }
337
342
  }
338
- x ? n.next(
339
- new b({
343
+ E ? n.next(
344
+ new M({
340
345
  body: d,
341
346
  headers: c,
342
347
  status: h,
343
- statusText: o
348
+ statusText: l
344
349
  })
345
350
  ) : n.error(
346
- new y({
347
- error: _,
351
+ new w({
352
+ error: f,
348
353
  headers: c,
349
354
  status: h,
350
- statusText: o
355
+ statusText: l
351
356
  })
352
357
  );
353
358
  }, i = (c) => {
354
- const o = new y({
359
+ const l = new w({
355
360
  error: c,
356
- status: r.status || 0,
357
- statusText: r.statusText || "Unknown Error",
361
+ status: t.status || 0,
362
+ statusText: t.statusText || "Unknown Error",
358
363
  headers: s().headers
359
364
  });
360
- n.error(o);
365
+ n.error(l);
361
366
  };
362
- r.addEventListener("load", a), r.addEventListener("error", i), r.addEventListener("abort", i), r.addEventListener("timeout", i);
363
- const l = t.getBody();
364
- return r.send(l), () => {
365
- r.readyState !== r.DONE && r.abort(), r.removeEventListener("load", a), r.removeEventListener("error", i), r.removeEventListener("abort", i), r.removeEventListener("timeout", i);
367
+ t.addEventListener("load", o), t.addEventListener("error", i), t.addEventListener("abort", i), t.addEventListener("timeout", i);
368
+ const a = r.getBody();
369
+ return t.send(a), () => {
370
+ t.readyState !== t.DONE && t.abort(), t.removeEventListener("load", o), t.removeEventListener("error", i), t.removeEventListener("abort", i), t.removeEventListener("timeout", i);
366
371
  };
367
372
  });
368
373
  }
369
374
  }
370
- const he = F("univer.socket");
371
- class de extends N {
372
- createSocket(t) {
375
+ const de = k("univer.socket");
376
+ class pe extends q {
377
+ createSocket(r) {
373
378
  try {
374
- const n = new WebSocket(t), r = new D();
379
+ const n = new WebSocket(r), t = new j();
375
380
  return {
376
- URL: t,
377
- close: (a, i) => {
378
- n.close(a, i), r.dispose();
381
+ URL: r,
382
+ close: (o, i) => {
383
+ n.close(o, i), t.dispose();
379
384
  },
380
- send: (a) => {
381
- n.send(a);
385
+ send: (o) => {
386
+ n.send(o);
382
387
  },
383
- open$: new m((a) => {
384
- const i = (l) => a.next(l);
385
- n.addEventListener("open", i), r.add(w(() => n.removeEventListener("open", i)));
386
- }).pipe(g()),
387
- close$: new m((a) => {
388
- const i = (l) => a.next(l);
389
- n.addEventListener("close", i), r.add(w(() => n.removeEventListener("close", i)));
390
- }).pipe(g()),
391
- error$: new m((a) => {
392
- const i = (l) => a.next(l);
393
- n.addEventListener("error", i), r.add(w(() => n.removeEventListener("error", i)));
394
- }).pipe(g()),
395
- message$: new m((a) => {
396
- const i = (l) => a.next(l);
397
- n.addEventListener("message", i), r.add(w(() => n.removeEventListener("message", i)));
398
- }).pipe(g())
388
+ open$: new u((o) => {
389
+ const i = (a) => o.next(a);
390
+ n.addEventListener("open", i), t.add(_(() => n.removeEventListener("open", i)));
391
+ }).pipe(v()),
392
+ close$: new u((o) => {
393
+ const i = (a) => o.next(a);
394
+ n.addEventListener("close", i), t.add(_(() => n.removeEventListener("close", i)));
395
+ }).pipe(v()),
396
+ error$: new u((o) => {
397
+ const i = (a) => o.next(a);
398
+ n.addEventListener("error", i), t.add(_(() => n.removeEventListener("error", i)));
399
+ }).pipe(v()),
400
+ message$: new u((o) => {
401
+ const i = (a) => o.next(a);
402
+ n.addEventListener("message", i), t.add(_(() => n.removeEventListener("message", i)));
403
+ }).pipe(v())
399
404
  };
400
405
  } catch (n) {
401
406
  return console.error(n), null;
402
407
  }
403
408
  }
404
409
  }
405
- const re = 2, te = 1e3, pe = (e, t) => t(e).pipe(
406
- W((n) => n.pipe(
407
- R((r, s) => s > re ? $(r) : v(r)),
408
- G(te)
409
- ))
410
- ), me = (e, t) => {
411
- const n = [], r = /* @__PURE__ */ new Set(), s = () => {
412
- var a;
413
- for (; r.size < ((a = t == null ? void 0 : t.maxParallel) != null ? a : 1) && n.length > 0; ) {
414
- const i = n.shift();
415
- r.add(i), i();
410
+ const te = 3, ne = 1e3, ye = (e, r) => {
411
+ var s, o;
412
+ const n = (s = r == null ? void 0 : r.maxRetryAttempts) != null ? s : te, t = (o = r == null ? void 0 : r.delayInterval) != null ? o : ne;
413
+ return (i, a) => a(i).pipe(V({ delay: t, count: n }));
414
+ }, me = (e) => {
415
+ const r = [], n = /* @__PURE__ */ new Set(), t = () => {
416
+ var s;
417
+ for (; n.size < ((s = e == null ? void 0 : e.maxParallel) != null ? s : 1) && r.length > 0; ) {
418
+ const o = r.shift();
419
+ n.add(o), o();
416
420
  }
417
421
  };
418
- return (a, i) => new m((l) => {
419
- const c = () => i(a).subscribe({
420
- next: (h) => l.next(h),
421
- error: (h) => l.next(h),
422
- complete: () => l.complete()
423
- }), o = () => {
424
- r.delete(c), U(n, c), s();
422
+ return (s, o) => new u((i) => {
423
+ const a = () => o(s).subscribe({
424
+ next: (l) => i.next(l),
425
+ error: (l) => i.next(l),
426
+ complete: () => i.complete()
427
+ }), c = () => {
428
+ n.delete(a), U(r, a), t();
425
429
  };
426
- return n.push(c), s(), o;
430
+ return r.push(a), t(), c;
427
431
  });
432
+ }, ue = (e) => {
433
+ const { errorStatusCodes: r, onAuthError: n } = e;
434
+ return (s, o) => o(s).pipe(
435
+ $((i) => (i instanceof w && r.some((a) => a === i.status) && n(), G(() => i)))
436
+ );
428
437
  };
429
438
  export {
430
- oe as FetchHTTPImplementation,
431
- u as HTTPHeaders,
432
- A as HTTPRequest,
433
- b as HTTPResponse,
434
- y as HTTPResponseError,
435
- q as HTTPService,
436
- E as HTTPStatusCode,
437
- X as IHTTPImplementation,
438
- he as ISocketService,
439
+ ue as AuthInterceptorFactory,
440
+ le as FetchHTTPImplementation,
441
+ Z as HTTPEventType,
442
+ R as HTTPHeaders,
443
+ P as HTTPProgress,
444
+ N as HTTPRequest,
445
+ M as HTTPResponse,
446
+ w as HTTPResponseError,
447
+ F as HTTPService,
448
+ x as HTTPStatusCode,
449
+ W as IHTTPImplementation,
450
+ de as ISocketService,
451
+ S as ResponseHeader,
452
+ ye as RetryInterceptorFactory,
439
453
  me as ThresholdInterceptorFactory,
440
- de as WebSocketService,
441
- le as XHRHTTPImplementation,
442
- pe as retryInterceptor
454
+ pe as WebSocketService,
455
+ he as XHRHTTPImplementation
443
456
  };
@@ -20,9 +20,10 @@ export { FetchHTTPImplementation } from './services/http/implementations/fetch';
20
20
  export { XHRHTTPImplementation } from './services/http/implementations/xhr';
21
21
  export { HTTPRequest, type HTTPRequestMethod } from './services/http/request';
22
22
  export { type HTTPResponseType, HTTPStatusCode } from './services/http/http';
23
- export { HTTPResponse, type HTTPEvent, HTTPResponseError } from './services/http/response';
23
+ export { HTTPResponse, type HTTPEvent, HTTPResponseError, HTTPEventType, HTTPProgress, ResponseHeader, type HTTPResponseBody } from './services/http/response';
24
24
  export { type ISocket, ISocketService, type SocketBodyType, WebSocketService, } from './services/web-socket/web-socket.service';
25
25
  export type { IRequestParams, IPostRequestParams } from './services/http/http.service';
26
26
  export type { HTTPHandlerFn, HTTPInterceptorFn, HTTPInterceptorFnFactory } from './services/http/interceptor';
27
- export { retryInterceptor } from './services/http/interceptors/retry-interceptor';
27
+ export { RetryInterceptorFactory, type IRetryInterceptorFactoryParams } from './services/http/interceptors/retry-interceptor';
28
28
  export { ThresholdInterceptorFactory } from './services/http/interceptors/threshold-interceptor';
29
+ export { AuthInterceptorFactory, type IAuthInterceptorParams } from './services/http/interceptors/auth-interceptor';
@@ -4,7 +4,7 @@ import { Observable } from 'rxjs';
4
4
  import { HTTPResponseType } from './http';
5
5
  import { IHTTPImplementation } from './implementations/implementation';
6
6
  import { HTTPRequestMethod } from './request';
7
- import { HTTPResponse } from './response';
7
+ import { HTTPEvent } from './response';
8
8
  import { HTTPInterceptorFn } from './interceptor';
9
9
 
10
10
  export interface IRequestParams {
@@ -19,6 +19,10 @@ export interface IRequestParams {
19
19
  /** Expected types of the response data. */
20
20
  responseType?: HTTPResponseType;
21
21
  withCredentials?: boolean;
22
+ /**
23
+ * Should report progress.
24
+ */
25
+ reportProgress?: boolean;
22
26
  }
23
27
  export interface IPostRequestParams extends IRequestParams {
24
28
  body?: unknown;
@@ -37,8 +41,9 @@ export interface IHTTPInterceptor {
37
41
  *
38
42
  * You can use interceptors to:
39
43
  *
40
- * 1. modify requests (headers included) before they are sent, or modify responses before they are returned to the caller.
41
- * 2. thresholding, logging, caching, etc.
44
+ * 1. modify requests (headers included) before they are sent, or modify responses
45
+ * before they are returned to the caller.
46
+ * 2. threshold, logging, caching, etc.
42
47
  * 3. authentication, authorization, etc.
43
48
  */
44
49
  export declare class HTTPService extends Disposable {
@@ -53,12 +58,12 @@ export declare class HTTPService extends Disposable {
53
58
  * @returns a disposable handler to remove the interceptor
54
59
  */
55
60
  registerHTTPInterceptor(interceptor: IHTTPInterceptor): IDisposable;
56
- get<T>(url: string, options?: IRequestParams): Promise<HTTPResponse<T>>;
57
- post<T>(url: string, options?: IPostRequestParams): Promise<HTTPResponse<T>>;
58
- put<T>(url: string, options?: IPostRequestParams): Promise<HTTPResponse<T>>;
59
- delete<T>(url: string, options?: IRequestParams): Promise<HTTPResponse<T>>;
60
- patch<T>(url: string, options?: IPostRequestParams): Promise<HTTPResponse<T>>;
61
- getSSE<T>(method: HTTPRequestMethod, url: string, options?: IPostRequestParams): Observable<HTTPResponse<T>>;
61
+ get<T>(url: string, params?: IRequestParams): Promise<HTTPEvent<T>>;
62
+ post<T>(url: string, params?: IPostRequestParams): Promise<HTTPEvent<T>>;
63
+ put<T>(url: string, params?: IPostRequestParams): Promise<HTTPEvent<T>>;
64
+ delete<T>(url: string, params?: IRequestParams): Promise<HTTPEvent<T>>;
65
+ patch<T>(url: string, options?: IPostRequestParams): Promise<HTTPEvent<T>>;
66
+ getSSE<T>(method: HTTPRequestMethod, url: string, options?: IPostRequestParams): Observable<HTTPEvent<T>>;
62
67
  /** The HTTP request implementations */
63
68
  private _request;
64
69
  private _runInterceptorsAndImplementation;
@@ -1,5 +1,4 @@
1
1
  import { Observable } from 'rxjs';
2
- import { IAccessor } from '@wendellhu/redi';
3
2
  import { HTTPRequest } from './request';
4
3
  import { HTTPEvent } from './response';
5
4
 
@@ -25,4 +24,4 @@ export type HTTPHandlerFn = (request: HTTPRequest) => Observable<HTTPEvent<unkno
25
24
  */
26
25
  export type HTTPInterceptorFn = (request: HTTPRequest, next: HTTPHandlerFn) => Observable<HTTPEvent<unknown>>;
27
26
  export type RequestPipe<T> = (req: HTTPRequest, finalHandlerFn: HTTPHandlerFn) => Observable<HTTPEvent<T>>;
28
- export type HTTPInterceptorFnFactory = (accessor: IAccessor, params?: any) => HTTPInterceptorFn;
27
+ export type HTTPInterceptorFnFactory<T extends unknown[] = []> = (...args: T) => HTTPInterceptorFn;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Copyright 2023-present DreamNum Inc.
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 {};
@@ -0,0 +1,7 @@
1
+ import { HTTPInterceptorFnFactory } from '../interceptor';
2
+
3
+ export interface IAuthInterceptorParams {
4
+ errorStatusCodes: number[];
5
+ onAuthError: () => void;
6
+ }
7
+ export declare const AuthInterceptorFactory: HTTPInterceptorFnFactory<[IAuthInterceptorParams]>;
@@ -1,3 +1,8 @@
1
- import { HTTPInterceptorFn } from '../interceptor';
1
+ import { Nullable } from '@univerjs/core';
2
+ import { HTTPInterceptorFnFactory } from '../interceptor';
2
3
 
3
- export declare const retryInterceptor: HTTPInterceptorFn;
4
+ export interface IRetryInterceptorFactoryParams {
5
+ maxRetryAttempts?: number;
6
+ delayInterval?: number;
7
+ }
8
+ export declare const RetryInterceptorFactory: HTTPInterceptorFnFactory<[Nullable<undefined>, Nullable<IRetryInterceptorFactoryParams>]>;
@@ -1,6 +1,7 @@
1
+ import { Nullable } from '@univerjs/core';
1
2
  import { HTTPInterceptorFnFactory } from '../interceptor';
2
3
 
3
4
  export interface IThresholdInterceptorFactoryParams {
4
5
  maxParallel?: number;
5
6
  }
6
- export declare const ThresholdInterceptorFactory: HTTPInterceptorFnFactory;
7
+ export declare const ThresholdInterceptorFactory: HTTPInterceptorFnFactory<[Nullable<IThresholdInterceptorFactoryParams>]>;
@@ -3,12 +3,16 @@ import { HTTPResponseType } from './http';
3
3
  import { HTTPParams } from './params';
4
4
 
5
5
  export type HTTPRequestMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
6
+ /**
7
+ * @internal
8
+ */
6
9
  export interface IHTTPRequestParams {
7
10
  body?: any;
8
11
  headers: HTTPHeaders;
9
12
  params?: HTTPParams;
10
13
  responseType: HTTPResponseType;
11
14
  withCredentials: boolean;
15
+ reportProgress?: boolean;
12
16
  }
13
17
  export declare function __TEST_ONLY_RESET_REQUEST_UID_DO_NOT_USE_IN_PRODUCTION(): void;
14
18
  export declare class HTTPRequest {
@@ -1,12 +1,19 @@
1
1
  import { HTTPHeaders } from './headers';
2
2
 
3
+ export type HTTPEvent<T> = HTTPResponse<T> | HTTPProgress;
4
+ export declare enum HTTPEventType {
5
+ DownloadProgress = 0,
6
+ Response = 1
7
+ }
8
+ interface IHTTPEvent {
9
+ type: HTTPEventType;
10
+ }
11
+ export type HTTPResponseBody = string | ArrayBuffer | Blob | object | null;
3
12
  /**
4
- * There are multiple events could be resolved from the HTTP server.
13
+ * Wraps success response info.
5
14
  */
6
- export type HTTPEvent<T> = HTTPResponse<T> | HTTPResponseError;
7
- export type HTTPResponseBody = string | ArrayBuffer | Blob | object | null;
8
- /** Wraps (success) response info. */
9
- export declare class HTTPResponse<T> {
15
+ export declare class HTTPResponse<T> implements IHTTPEvent {
16
+ readonly type = HTTPEventType.Response;
10
17
  readonly body: T;
11
18
  readonly headers: HTTPHeaders;
12
19
  readonly status: number;
@@ -18,6 +25,49 @@ export declare class HTTPResponse<T> {
18
25
  statusText: string;
19
26
  });
20
27
  }
28
+ /**
29
+ * Progress event for HTTP request. Usually used for reporting download/upload progress or SSE streaming.
30
+ */
31
+ export declare class HTTPProgress implements IHTTPEvent {
32
+ /**
33
+ * Total number of bytes to download. Depending on the request or
34
+ * response, this may not be computable and thus may not be present.
35
+ */
36
+ readonly total: number | undefined;
37
+ /**
38
+ * Number of bytes downloaded.
39
+ */
40
+ readonly loaded: number;
41
+ /**
42
+ * The partial response body as downloaded so far.
43
+ *
44
+ * Only present if the responseType was `text`.
45
+ */
46
+ readonly partialText?: string | undefined;
47
+ readonly type = HTTPEventType.DownloadProgress;
48
+ constructor(
49
+ /**
50
+ * Total number of bytes to download. Depending on the request or
51
+ * response, this may not be computable and thus may not be present.
52
+ */
53
+ total: number | undefined,
54
+ /**
55
+ * Number of bytes downloaded.
56
+ */
57
+ loaded: number,
58
+ /**
59
+ * The partial response body as downloaded so far.
60
+ *
61
+ * Only present if the responseType was `text`.
62
+ */
63
+ partialText?: string | undefined);
64
+ }
65
+ export declare class ResponseHeader {
66
+ readonly headers: HTTPHeaders;
67
+ readonly status: number;
68
+ readonly statusText: string;
69
+ constructor(headers: HTTPHeaders, status: number, statusText: string);
70
+ }
21
71
  export declare class HTTPResponseError {
22
72
  readonly headers?: HTTPHeaders;
23
73
  readonly status?: number;
@@ -30,9 +80,4 @@ export declare class HTTPResponseError {
30
80
  error: any;
31
81
  });
32
82
  }
33
- export declare class ResponseHeader {
34
- readonly headers: HTTPHeaders;
35
- readonly status: number;
36
- readonly statusText: string;
37
- constructor(headers: HTTPHeaders, status: number, statusText: string);
38
- }
83
+ export {};
package/lib/umd/index.js CHANGED
@@ -1,2 +1,2 @@
1
- (function(c,d){typeof exports=="object"&&typeof module<"u"?d(exports,require("@univerjs/core"),require("rxjs"),require("rxjs/operators"),require("@wendellhu/redi")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs","rxjs/operators","@wendellhu/redi"],d):(c=typeof globalThis<"u"?globalThis:c||self,d(c.UniverNetwork={},c.UniverCore,c.rxjs,c.rxjs.operators,c["@wendellhu/redi"]))})(this,function(c,d,m,f,I){"use strict";var S=Object.defineProperty;var C=(c,d,m)=>d in c?S(c,d,{enumerable:!0,configurable:!0,writable:!0,value:m}):c[d]=m;var y=(c,d,m)=>(C(c,typeof d!="symbol"?d+"":d,m),m);const L="application/json";class g{constructor(t){y(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((n,r)=>t(r,n))}has(t){return!!this._headers.has(t.toLowerCase())}get(t){const n=t.toLowerCase();return this._headers.has(n)?this._headers.get(n):null}toHeadersInit(){var n,r;const t={};return this._headers.forEach((s,a)=>{t[a]=s.join(",")}),(n=t.accept)!=null||(t.accept="application/json, text/plain, */*"),(r=t["content-type"])!=null||(t["content-type"]="application/json;charset=UTF-8"),t}_setHeader(t,n){const r=t.toLowerCase();this._headers.has(r)?this._headers.get(r).push(n.toString()):this._headers.set(r,[n.toString()])}_handleHeadersString(t){t.split(`
2
- `).forEach(n=>{const[r,s]=n.split(":");r&&s&&this._setHeader(r,s)})}_handleHeadersConstructorProps(t){Object.entries(t).forEach(([n,r])=>this._setHeader(n,r))}_handleHeaders(t){t.forEach((n,r)=>this._setHeader(r,n))}}const q=I.createIdentifier("network.http-implementation");class A{constructor(t){this.params=t}toString(){return this.params?Object.keys(this.params).map(t=>`${t}=${this.params[t]}`).join("&"):""}}let U=0;class _{constructor(t,n,r){y(this,"uid",U++);this.method=t,this.url=n,this.requestParams=r}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var n,r;const t=(r=(n=this.requestParams)==null?void 0:n.params)==null?void 0:r.toString();return t?`${this.url}${this.url.includes("?")?"&":"?"}${t}`:this.url}getBody(){var r,s;const t=(r=this.headers.get("Content-Type"))!=null?r:L,n=(s=this.requestParams)==null?void 0:s.body;return t===L&&n&&typeof n=="object"?JSON.stringify(n):n?`${n}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}class E{constructor({body:t,headers:n,status:r,statusText:s}){y(this,"body");y(this,"headers");y(this,"status");y(this,"statusText");this.body=t,this.headers=n,this.status=r,this.statusText=s}}class w{constructor({headers:t,status:n,statusText:r,error:s}){y(this,"headers");y(this,"status");y(this,"statusText");y(this,"error");this.headers=t,this.status=n,this.statusText=r,this.error=s}}class F{constructor(t,n,r){this.headers=t,this.status=n,this.statusText=r}}var k=Object.defineProperty,x=Object.getOwnPropertyDescriptor,O=(e,t,n,r)=>{for(var s=r>1?void 0:r?x(t,n):t,a=e.length-1,i;a>=0;a--)(i=e[a])&&(s=(r?i(t,n,s):i(s))||s);return r&&s&&k(t,n,s),s},M=(e,t)=>(n,r)=>t(n,r,e);c.HTTPService=class extends d.Disposable{constructor(n){super();y(this,"_interceptors",[]);y(this,"_pipe");this._http=n}registerHTTPInterceptor(n){if(this._interceptors.indexOf(n)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(n),this._interceptors=this._interceptors.sort((r,s)=>{var a,i;return((a=r.priority)!=null?a:0)-((i=s.priority)!=null?i:0)}),this._pipe=null,d.toDisposable(()=>d.remove(this._interceptors,n))}get(n,r){return this._request("GET",n,r)}post(n,r){return this._request("POST",n,r)}put(n,r){return this._request("PUT",n,r)}delete(n,r){return this._request("DELETE",n,r)}patch(n,r){return this._request("PATCH",n,r)}getSSE(n,r,s){var l,h;const a=new g(s==null?void 0:s.headers),i=new A(s==null?void 0:s.params),p=new _(n,r,{headers:a,params:i,withCredentials:(l=s==null?void 0:s.withCredentials)!=null?l:!1,responseType:(h=s==null?void 0:s.responseType)!=null?h:"json",body:["GET","DELETE"].includes(n)||s==null?void 0:s.body});return m.of(p).pipe(f.concatMap(o=>this._runInterceptorsAndImplementation(o)),f.map(o=>{if(o instanceof w)throw o;return o}))}async _request(n,r,s){var o,v;const a=new g(s==null?void 0:s.headers),i=new A(s==null?void 0:s.params),p=new _(n,r,{headers:a,params:i,withCredentials:(o=s==null?void 0:s.withCredentials)!=null?o:!1,responseType:(v=s==null?void 0:s.responseType)!=null?v:"json",body:["GET","DELETE"].includes(n)||s==null?void 0:s.body}),l=m.of(p).pipe(f.concatMap(u=>this._runInterceptorsAndImplementation(u))),h=await m.firstValueFrom(l);if(h instanceof E)return h;throw new Error(`${h.error}`)}_runInterceptorsAndImplementation(n){return this._pipe||(this._pipe=this._interceptors.map(r=>r.interceptor).reduceRight((r,s)=>D(r,s),(r,s)=>s(r))),this._pipe(n,r=>this._http.send(r))}},c.HTTPService=O([M(0,q)],c.HTTPService);function D(e,t){return(n,r)=>t(n,s=>e(s,r))}const j=200,B=300;var b=(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))(b||{});class ${send(t){return new m.Observable(n=>{const r=new AbortController;return this._send(t,n,r).then(()=>{},s=>{n.error(new w({error:s}))}),()=>r.abort()})}async _send(t,n,r){var o,v;let s;try{const u=this._parseFetchParamsFromRequest(t);s=await fetch(t.getUrlWithParams(),{signal:r.signal,...u})}catch(u){n.error(new w({error:u,status:(o=u.status)!=null?o:0,statusText:(v=u.statusText)!=null?v:"Unknown Error",headers:u.headers}));return}const a=new g(s.headers),i=s.status,p=s.statusText;let l=null;s.body&&(l=await this._readBody(t,s,n)),i>=b.Ok&&i<b.MultipleChoices?n.next(new E({body:l,headers:a,status:i,statusText:p})):n.error(new w({error:l,status:i,statusText:p,headers:a})),n.complete()}async _readBody(t,n,r){var l;const s=[],a=n.body.getReader();let i=0;for(;;){const{done:h,value:o}=await a.read();if(h)break;s.push(o),i+=o.length}const p=G(s,i);try{const h=(l=n.headers.get("content-type"))!=null?l:"";return V(t,p,h)}catch(h){return r.error(new w({error:h,status:n.status,statusText:n.statusText,headers:new g(n.headers)})),null}}_parseFetchParamsFromRequest(t){return{method:t.method,headers:t.getHeadersInit(),body:t.getBody(),credentials:t.withCredentials?"include":void 0}}}function G(e,t){const n=new Uint8Array(t);let r=0;for(const s of e)n.set(s,r),r+=s.length;return n}const W=/^\)\]\}',?\n/;function V(e,t,n){switch(e.responseType){case"json":const r=new TextDecoder().decode(t).replace(W,"");return r===""?null:JSON.parse(r);case"text":return new TextDecoder().decode(t);case"blob":return new Blob([t],{type:n});case"arraybuffer":return t.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}class X{send(t){return new m.Observable(n=>{const r=new XMLHttpRequest;r.open(t.method,t.getUrlWithParams()),t.withCredentials&&(r.withCredentials=!0),t.headers.forEach((l,h)=>r.setRequestHeader(l,h.join(","))),t.headers.has("Accept")||r.setRequestHeader("Accept","application/json, text/plain, */*"),t.headers.has("Content-Type")||r.setRequestHeader("Content-Type","application/json;charset=UTF-8");const s=()=>{const l=r.statusText||"OK",h=new g(r.getAllResponseHeaders());return new F(h,r.status,l)},a=()=>{const{headers:l,statusText:h,status:o}=s(),{responseType:v}=t;let u=null,R=null;o!==b.NoContent&&(u=typeof r.response>"u"?r.responseText:r.response);let N=o>=j&&o<B;if(v==="json"&&typeof u=="string"){const P=u;try{u=u?JSON.parse(u):null}catch(H){N=!1,u=P,R=H}}N?n.next(new E({body:u,headers:l,status:o,statusText:h})):n.error(new w({error:R,headers:l,status:o,statusText:h}))},i=l=>{const h=new w({error:l,status:r.status||0,statusText:r.statusText||"Unknown Error",headers:s().headers});n.error(h)};r.addEventListener("load",a),r.addEventListener("error",i),r.addEventListener("abort",i),r.addEventListener("timeout",i);const p=t.getBody();return r.send(p),()=>{r.readyState!==r.DONE&&r.abort(),r.removeEventListener("load",a),r.removeEventListener("error",i),r.removeEventListener("abort",i),r.removeEventListener("timeout",i)}})}}const z=I.createIdentifier("univer.socket");class J extends d.Disposable{createSocket(t){try{const n=new WebSocket(t),r=new d.DisposableCollection;return{URL:t,close:(a,i)=>{n.close(a,i),r.dispose()},send:a=>{n.send(a)},open$:new m.Observable(a=>{const i=p=>a.next(p);n.addEventListener("open",i),r.add(d.toDisposable(()=>n.removeEventListener("open",i)))}).pipe(f.share()),close$:new m.Observable(a=>{const i=p=>a.next(p);n.addEventListener("close",i),r.add(d.toDisposable(()=>n.removeEventListener("close",i)))}).pipe(f.share()),error$:new m.Observable(a=>{const i=p=>a.next(p);n.addEventListener("error",i),r.add(d.toDisposable(()=>n.removeEventListener("error",i)))}).pipe(f.share()),message$:new m.Observable(a=>{const i=p=>a.next(p);n.addEventListener("message",i),r.add(d.toDisposable(()=>n.removeEventListener("message",i)))}).pipe(f.share())}}catch(n){return console.error(n),null}}}const Y=2,K=1e3,Q=(e,t)=>t(e).pipe(f.retryWhen(n=>n.pipe(f.concatMap((r,s)=>s>Y?m.throwError(r):m.of(r)),m.delay(K)))),Z=(e,t)=>{const n=[],r=new Set,s=()=>{var a;for(;r.size<((a=t==null?void 0:t.maxParallel)!=null?a:1)&&n.length>0;){const i=n.shift();r.add(i),i()}};return(a,i)=>new m.Observable(p=>{const l=()=>i(a).subscribe({next:o=>p.next(o),error:o=>p.next(o),complete:()=>p.complete()}),h=()=>{r.delete(l),d.remove(n,l),s()};return n.push(l),s(),h})};c.FetchHTTPImplementation=$,c.HTTPHeaders=g,c.HTTPRequest=_,c.HTTPResponse=E,c.HTTPResponseError=w,c.HTTPStatusCode=b,c.IHTTPImplementation=q,c.ISocketService=z,c.ThresholdInterceptorFactory=Z,c.WebSocketService=J,c.XHRHTTPImplementation=X,c.retryInterceptor=Q,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})});
1
+ (function(o,l){typeof exports=="object"&&typeof module<"u"?l(exports,require("@univerjs/core"),require("rxjs"),require("rxjs/operators"),require("@wendellhu/redi")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs","rxjs/operators","@wendellhu/redi"],l):(o=typeof globalThis<"u"?globalThis:o||self,l(o.UniverNetwork={},o.UniverCore,o.rxjs,o.rxjs.operators,o["@wendellhu/redi"]))})(this,function(o,l,y,g,q){"use strict";var ee=Object.defineProperty;var re=(o,l,y)=>l in o?ee(o,l,{enumerable:!0,configurable:!0,writable:!0,value:y}):o[l]=y;var m=(o,l,y)=>(re(o,typeof l!="symbol"?l+"":l,y),y);const F="application/json";class E{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}toHeadersInit(){var t,r;const n={};return this._headers.forEach((s,a)=>{n[a]=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 N=q.createIdentifier("network.http-implementation");class U{constructor(n){this.params=n}toString(){return this.params?Object.keys(this.params).map(n=>`${n}=${this.params[n]}`).join("&"):""}}let D=0;class L{constructor(n,t,r){m(this,"uid",D++);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:F,t=(s=this.requestParams)==null?void 0:s.body;return n===F&&t&&typeof t=="object"?JSON.stringify(t):t?`${t}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}var M=Object.defineProperty,j=Object.getOwnPropertyDescriptor,B=(e,n,t,r)=>{for(var s=r>1?void 0:r?j(n,t):n,a=e.length-1,i;a>=0;a--)(i=e[a])&&(s=(r?i(n,t,s):i(s))||s);return r&&s&&M(n,t,s),s},$=(e,n)=>(t,r)=>n(t,r,e);o.HTTPService=class extends l.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 a,i;return((a=r.priority)!=null?a:0)-((i=s.priority)!=null?i:0)}),this._pipe=null,l.toDisposable(()=>l.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 h,d;const a=new E(s==null?void 0:s.headers),i=new U(s==null?void 0:s.params),c=new L(t,r,{headers:a,params:i,withCredentials:(h=s==null?void 0:s.withCredentials)!=null?h:!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(c).pipe(g.concatMap(p=>this._runInterceptorsAndImplementation(p)))}async _request(t,r,s){var p,f;const a=new E(s==null?void 0:s.headers),i=new U(s==null?void 0:s.params),c=new L(t,r,{headers:a,params:i,withCredentials:(p=s==null?void 0:s.withCredentials)!=null?p:!1,responseType:(f=s==null?void 0:s.responseType)!=null?f:"json",body:["GET","DELETE"].includes(t)||s==null?void 0:s.body}),h=y.of(c).pipe(g.concatMap(u=>this._runInterceptorsAndImplementation(u)));return await y.firstValueFrom(h)}_runInterceptorsAndImplementation(t){return this._pipe||(this._pipe=this._interceptors.map(r=>r.interceptor).reduceRight((r,s)=>G(r,s),(r,s)=>s(r))),this._pipe(t,r=>this._http.send(r))}},o.HTTPService=B([$(0,N)],o.HTTPService);function G(e,n){return(t,r)=>n(t,s=>e(s,r))}var x=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(x||{});class A{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 k{constructor(n,t,r){m(this,"type",0);this.total=n,this.loaded=t,this.partialText=r}}class O{constructor(n,t,r){this.headers=n,this.status=t,this.statusText=r}}class w{constructor({headers:n,status:t,statusText:r,error:s}){m(this,"headers");m(this,"status");m(this,"statusText");m(this,"error");this.headers=n,this.status=t,this.statusText=r,this.error=s}}const V=200,W=300;var _=(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))(_||{});class X{send(n){return new y.Observable(t=>{const r=new AbortController;return this._send(n,t,r).then(()=>{},s=>{t.error(new w({error:s}))}),()=>r.abort()})}async _send(n,t,r){var p,f;let s;try{const u=this._parseFetchParamsFromRequest(n);s=await fetch(n.getUrlWithParams(),{signal:r.signal,...u})}catch(u){t.error(new w({error:u,status:(p=u.status)!=null?p:0,statusText:(f=u.statusText)!=null?f:"Unknown Error",headers:u.headers}));return}const a=new E(s.headers),i=s.status,c=s.statusText;let h=null;s.body&&(h=await this._readBody(n,s,t)),i>=_.Ok&&i<_.MultipleChoices?t.next(new A({body:h,headers:a,status:i,statusText:c})):t.error(new w({error:h,status:i,statusText:c,headers:a})),t.complete()}async _readBody(n,t,r){var R,I;const s=[],a=t.body.getReader(),i=t.headers.get("content-length");let c=0;const h=(R=n.requestParams)==null?void 0:R.reportProgress,d=n.responseType;let p,f;for(;;){const{done:v,value:b}=await a.read();if(v)break;s.push(b),c+=b.length,h&&d==="text"&&(p=(p!=null?p:"")+(f!=null?f:f=new TextDecoder).decode(b,{stream:!0}),r.next(new k(i?Number.parseInt(i,10):void 0,c,p)))}const u=z(s,c);try{const v=(I=t.headers.get("content-type"))!=null?I:"";return Y(n,u,v)}catch(v){return r.error(new w({error:v,status:t.status,statusText:t.statusText,headers:new E(t.headers)})),null}}_parseFetchParamsFromRequest(n){return{method:n.method,headers:n.getHeadersInit(),body:n.getBody(),credentials:n.withCredentials?"include":void 0}}}function z(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 J=/^\)\]\}',?\n/;function Y(e,n,t){switch(e.responseType){case"json":const r=new TextDecoder().decode(n).replace(J,"");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}.`)}}class K{send(n){return new y.Observable(t=>{const r=new XMLHttpRequest;r.open(n.method,n.getUrlWithParams()),n.withCredentials&&(r.withCredentials=!0),n.headers.forEach((h,d)=>r.setRequestHeader(h,d.join(","))),n.headers.has("Accept")||r.setRequestHeader("Accept","application/json, text/plain, */*"),n.headers.has("Content-Type")||r.setRequestHeader("Content-Type","application/json;charset=UTF-8");const s=()=>{const h=r.statusText||"OK",d=new E(r.getAllResponseHeaders());return new O(d,r.status,h)},a=()=>{const{headers:h,statusText:d,status:p}=s(),{responseType:f}=n;let u=null,R=null;p!==_.NoContent&&(u=typeof r.response>"u"?r.responseText:r.response);let I=p>=V&&p<W;if(f==="json"&&typeof u=="string"){const v=u;try{u=u?JSON.parse(u):null}catch(b){I=!1,u=v,R=b}}I?t.next(new A({body:u,headers:h,status:p,statusText:d})):t.error(new w({error:R,headers:h,status:p,statusText:d}))},i=h=>{const d=new w({error:h,status:r.status||0,statusText:r.statusText||"Unknown Error",headers:s().headers});t.error(d)};r.addEventListener("load",a),r.addEventListener("error",i),r.addEventListener("abort",i),r.addEventListener("timeout",i);const c=n.getBody();return r.send(c),()=>{r.readyState!==r.DONE&&r.abort(),r.removeEventListener("load",a),r.removeEventListener("error",i),r.removeEventListener("abort",i),r.removeEventListener("timeout",i)}})}}const Q=q.createIdentifier("univer.socket");class Z extends l.Disposable{createSocket(n){try{const t=new WebSocket(n),r=new l.DisposableCollection;return{URL:n,close:(a,i)=>{t.close(a,i),r.dispose()},send:a=>{t.send(a)},open$:new y.Observable(a=>{const i=c=>a.next(c);t.addEventListener("open",i),r.add(l.toDisposable(()=>t.removeEventListener("open",i)))}).pipe(g.share()),close$:new y.Observable(a=>{const i=c=>a.next(c);t.addEventListener("close",i),r.add(l.toDisposable(()=>t.removeEventListener("close",i)))}).pipe(g.share()),error$:new y.Observable(a=>{const i=c=>a.next(c);t.addEventListener("error",i),r.add(l.toDisposable(()=>t.removeEventListener("error",i)))}).pipe(g.share()),message$:new y.Observable(a=>{const i=c=>a.next(c);t.addEventListener("message",i),r.add(l.toDisposable(()=>t.removeEventListener("message",i)))}).pipe(g.share())}}catch(t){return console.error(t),null}}}const P=3,H=1e3,S=(e,n)=>{var s,a;const t=(s=n==null?void 0:n.maxRetryAttempts)!=null?s:P,r=(a=n==null?void 0:n.delayInterval)!=null?a:H;return(i,c)=>c(i).pipe(g.retry({delay:r,count:t}))},C=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 a=n.shift();t.add(a),a()}};return(s,a)=>new y.Observable(i=>{const c=()=>a(s).subscribe({next:d=>i.next(d),error:d=>i.next(d),complete:()=>i.complete()}),h=()=>{t.delete(c),l.remove(n,c),r()};return n.push(c),r(),h})},T=e=>{const{errorStatusCodes:n,onAuthError:t}=e;return(s,a)=>a(s).pipe(y.catchError(i=>(i instanceof w&&n.some(c=>c===i.status)&&t(),y.throwError(()=>i))))};o.AuthInterceptorFactory=T,o.FetchHTTPImplementation=X,o.HTTPEventType=x,o.HTTPHeaders=E,o.HTTPProgress=k,o.HTTPRequest=L,o.HTTPResponse=A,o.HTTPResponseError=w,o.HTTPStatusCode=_,o.IHTTPImplementation=N,o.ISocketService=Q,o.ResponseHeader=O,o.RetryInterceptorFactory=S,o.ThresholdInterceptorFactory=C,o.WebSocketService=Z,o.XHRHTTPImplementation=K,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@univerjs/network",
3
- "version": "0.1.13",
3
+ "version": "0.1.15",
4
4
  "private": false,
5
5
  "author": "DreamNum <developer@univer.ai>",
6
6
  "license": "Apache-2.0",
@@ -44,29 +44,39 @@
44
44
  "files": [
45
45
  "lib"
46
46
  ],
47
- "engines": {
48
- "node": ">=16.0.0",
49
- "npm": ">=8.0.0"
50
- },
51
47
  "peerDependencies": {
52
- "@wendellhu/redi": "0.15.2",
48
+ "@wendellhu/redi": "0.15.4",
53
49
  "rxjs": ">=7.0.0",
54
- "@univerjs/core": "0.1.13"
50
+ "@univerjs/core": "0.1.15"
55
51
  },
56
52
  "devDependencies": {
57
- "@wendellhu/redi": "0.15.2",
53
+ "@wendellhu/redi": "0.15.4",
58
54
  "rxjs": "^7.8.1",
59
55
  "typescript": "^5.4.5",
60
- "vite": "^5.2.12",
56
+ "vite": "^5.2.13",
61
57
  "vitest": "^1.6.0",
62
- "@univerjs/core": "0.1.13",
63
- "@univerjs/shared": "0.1.13"
58
+ "@univerjs/core": "0.1.15",
59
+ "@univerjs/shared": "0.1.15"
60
+ },
61
+ "univerSpace": {
62
+ ".": {
63
+ "import": "./lib/es/index.js",
64
+ "require": "./lib/cjs/index.js",
65
+ "types": "./lib/types/index.d.ts"
66
+ },
67
+ "./*": {
68
+ "import": "./lib/es/*",
69
+ "require": "./lib/cjs/*",
70
+ "types": "./lib/types/index.d.ts"
71
+ },
72
+ "./lib/*": "./lib/*"
64
73
  },
65
74
  "scripts": {
66
75
  "test": "vitest run",
67
76
  "test:watch": "vitest",
68
77
  "coverage": "vitest run --coverage",
69
78
  "lint:types": "tsc --noEmit",
70
- "build": "tsc && vite build"
79
+ "build": "tsc && vite build",
80
+ "sync:cnpm": "cnpm sync"
71
81
  }
72
82
  }