@univerjs/network 0.2.2 → 0.2.3

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
@@ -1,7 +1,10 @@
1
1
  # @univerjs/network
2
2
 
3
- [![npm version](https://img.shields.io/npm/v/@univerjs/network)](https://npmjs.org/package/@univerjs/network)
4
- [![license](https://img.shields.io/npm/l/@univerjs/network)](https://img.shields.io/npm/l/@univerjs/network)
3
+ ## Package Overview
4
+
5
+ | Package Name | UMD Namespace | Version | License | Downloads | Contains CSS | Contains i18n locales |
6
+ | --- | --- | --- | --- | --- | :---: | :---: |
7
+ | `@univerjs/network` | `UniverNetwork` | [![][npm-version-shield]][npm-version-link] | ![][npm-license-shield] | ![][npm-downloads-shield] | ❌ | ❌ |
5
8
 
6
9
  ## Introduction
7
10
 
@@ -22,3 +25,9 @@ pnpm add @univerjs/network
22
25
  ## Credit
23
26
 
24
27
  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.
28
+
29
+ <!-- Links -->
30
+ [npm-version-shield]: https://img.shields.io/npm/v/@univerjs/network?style=flat-square
31
+ [npm-version-link]: https://npmjs.com/package/@univerjs/network
32
+ [npm-license-shield]: https://img.shields.io/npm/l/@univerjs/network?style=flat-square
33
+ [npm-downloads-shield]: https://img.shields.io/npm/dm/@univerjs/network?style=flat-square
package/lib/cjs/index.js CHANGED
@@ -1,2 +1,2 @@
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);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;
1
+ "use strict";var $=Object.defineProperty;var G=(e,t,r)=>t in e?$(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var y=(e,t,r)=>G(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const b=require("@univerjs/core"),m=require("rxjs"),v=require("rxjs/operators"),O=require("@wendellhu/redi"),U="application/json";class E{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((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,c)=>{t[c]=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 M=O.createIdentifier("network.http-implementation");class D{constructor(t){this.params=t}toString(){return this.params?Object.keys(this.params).map(t=>`${t}=${this.params[t]}`).join("&"):""}}let V=0;class q{constructor(t,r,n){y(this,"uid",V++);this.method=t,this.url=r,this.requestParams=n}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var r,n;const t=(n=(r=this.requestParams)==null?void 0:r.params)==null?void 0:n.toString();return t?`${this.url}${this.url.includes("?")?"&":"?"}${t}`:this.url}getBody(){var n,s;const t=(n=this.headers.get("Content-Type"))!=null?n:U,r=(s=this.requestParams)==null?void 0:s.body;return t===U&&r&&typeof r=="object"?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}var W=Object.defineProperty,X=Object.getOwnPropertyDescriptor,z=(e,t,r,n)=>{for(var s=n>1?void 0:n?X(t,r):t,c=e.length-1,o;c>=0;c--)(o=e[c])&&(s=(n?o(t,r,s):o(s))||s);return n&&s&&W(t,r,s),s},J=(e,t)=>(r,n)=>t(r,n,e);exports.HTTPService=class extends b.Disposable{constructor(r){super();y(this,"_interceptors",[]);y(this,"_pipe");this._http=r}registerHTTPInterceptor(r){if(this._interceptors.indexOf(r)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(r),this._interceptors=this._interceptors.sort((n,s)=>{var c,o;return((c=n.priority)!=null?c:0)-((o=s.priority)!=null?o:0)}),this._pipe=null,b.toDisposable(()=>b.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 h,a;const c=new E(s==null?void 0:s.headers),o=new D(s==null?void 0:s.params),i=new q(r,n,{headers:c,params:o,withCredentials:(h=s==null?void 0:s.withCredentials)!=null?h:!1,reportProgress:!0,responseType:(a=s==null?void 0:s.responseType)!=null?a:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body});return m.of(i).pipe(v.concatMap(l=>this._runInterceptorsAndImplementation(l)))}async _request(r,n,s){var l,p;const c=new E(s==null?void 0:s.headers),o=new D(s==null?void 0:s.params),i=new q(r,n,{headers:c,params:o,withCredentials:(l=s==null?void 0:s.withCredentials)!=null?l:!1,responseType:(p=s==null?void 0:s.responseType)!=null?p:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body}),h=m.of(i).pipe(v.concatMap(d=>this._runInterceptorsAndImplementation(d)));return await m.firstValueFrom(h)}_runInterceptorsAndImplementation(r){return this._pipe||(this._pipe=this._interceptors.map(n=>n.interceptor).reduceRight((n,s)=>Y(n,s),(n,s)=>s(n))),this._pipe(r,n=>this._http.send(n))}};exports.HTTPService=z([J(0,M)],exports.HTTPService);function Y(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 L{constructor({body:t,headers:r,status:n,statusText:s}){y(this,"type",1);y(this,"body");y(this,"headers");y(this,"status");y(this,"statusText");this.body=t,this.headers=r,this.status=n,this.statusText=s}}class j{constructor(t,r,n){y(this,"type",0);this.total=t,this.loaded=r,this.partialText=n}}class B{constructor(t,r,n){this.headers=t,this.status=r,this.statusText=n}}class R{constructor({headers:t,status:r,statusText:n,error:s}){y(this,"headers");y(this,"status");y(this,"statusText");y(this,"error");this.headers=t,this.status=r,this.statusText=n,this.error=s}}const K=200,Q=300;var x=(e=>(e[e.Continue=100]="Continue",e[e.SwitchingProtocols=101]="SwitchingProtocols",e[e.Processing=102]="Processing",e[e.EarlyHints=103]="EarlyHints",e[e.Ok=200]="Ok",e[e.Created=201]="Created",e[e.Accepted=202]="Accepted",e[e.NonAuthoritativeInformation=203]="NonAuthoritativeInformation",e[e.NoContent=204]="NoContent",e[e.ResetContent=205]="ResetContent",e[e.PartialContent=206]="PartialContent",e[e.MultiStatus=207]="MultiStatus",e[e.AlreadyReported=208]="AlreadyReported",e[e.ImUsed=226]="ImUsed",e[e.MultipleChoices=300]="MultipleChoices",e[e.MovedPermanently=301]="MovedPermanently",e[e.Found=302]="Found",e[e.SeeOther=303]="SeeOther",e[e.NotModified=304]="NotModified",e[e.UseProxy=305]="UseProxy",e[e.Unused=306]="Unused",e[e.TemporaryRedirect=307]="TemporaryRedirect",e[e.PermanentRedirect=308]="PermanentRedirect",e[e.BadRequest=400]="BadRequest",e[e.Unauthorized=401]="Unauthorized",e[e.PaymentRequired=402]="PaymentRequired",e[e.Forbidden=403]="Forbidden",e[e.NotFound=404]="NotFound",e[e.MethodNotAllowed=405]="MethodNotAllowed",e[e.NotAcceptable=406]="NotAcceptable",e[e.ProxyAuthenticationRequired=407]="ProxyAuthenticationRequired",e[e.RequestTimeout=408]="RequestTimeout",e[e.Conflict=409]="Conflict",e[e.Gone=410]="Gone",e[e.LengthRequired=411]="LengthRequired",e[e.PreconditionFailed=412]="PreconditionFailed",e[e.PayloadTooLarge=413]="PayloadTooLarge",e[e.UriTooLong=414]="UriTooLong",e[e.UnsupportedMediaType=415]="UnsupportedMediaType",e[e.RangeNotSatisfiable=416]="RangeNotSatisfiable",e[e.ExpectationFailed=417]="ExpectationFailed",e[e.ImATeapot=418]="ImATeapot",e[e.MisdirectedRequest=421]="MisdirectedRequest",e[e.UnprocessableEntity=422]="UnprocessableEntity",e[e.Locked=423]="Locked",e[e.FailedDependency=424]="FailedDependency",e[e.TooEarly=425]="TooEarly",e[e.UpgradeRequired=426]="UpgradeRequired",e[e.PreconditionRequired=428]="PreconditionRequired",e[e.TooManyRequests=429]="TooManyRequests",e[e.RequestHeaderFieldsTooLarge=431]="RequestHeaderFieldsTooLarge",e[e.UnavailableForLegalReasons=451]="UnavailableForLegalReasons",e[e.InternalServerError=500]="InternalServerError",e[e.NotImplemented=501]="NotImplemented",e[e.BadGateway=502]="BadGateway",e[e.ServiceUnavailable=503]="ServiceUnavailable",e[e.GatewayTimeout=504]="GatewayTimeout",e[e.HttpVersionNotSupported=505]="HttpVersionNotSupported",e[e.VariantAlsoNegotiates=506]="VariantAlsoNegotiates",e[e.InsufficientStorage=507]="InsufficientStorage",e[e.LoopDetected=508]="LoopDetected",e[e.NotExtended=510]="NotExtended",e[e.NetworkAuthenticationRequired=511]="NetworkAuthenticationRequired",e))(x||{});class Z{send(t){return new m.Observable(r=>{const n=new AbortController;return this._send(t,r,n).then(()=>{},s=>{r.error(new R({error:s}))}),()=>n.abort()})}async _send(t,r,n){var l,p;let s;try{const d=this._parseFetchParamsFromRequest(t);s=await fetch(t.getUrlWithParams(),{signal:n.signal,...d})}catch(d){r.error(new R({error:d,status:(l=d.status)!=null?l:0,statusText:(p=d.statusText)!=null?p:"Unknown Error",headers:d.headers}));return}const c=new E(s.headers),o=s.status,i=s.statusText;let h=null;s.body&&(h=await this._readBody(t,s,r)),o>=x.Ok&&o<x.MultipleChoices?r.next(new L({body:h,headers:c,status:o,statusText:i})):r.error(new R({error:h,status:o,statusText:i,headers:c})),r.complete()}async _readBody(t,r,n){var w,f;const s=[],c=r.body.getReader(),o=r.headers.get("content-length");let i=0;const h=(w=t.requestParams)==null?void 0:w.reportProgress,a=t.responseType;let l,p;for(;;){const{done:g,value:u}=await c.read();if(g)break;s.push(u),i+=u.length,h&&a==="text"&&(l=(l!=null?l:"")+(p!=null?p:p=new TextDecoder).decode(u,{stream:!0}),n.next(new j(o?Number.parseInt(o,10):void 0,i,l)))}const d=P(s,i);try{const g=(f=r.headers.get("content-type"))!=null?f:"";return S(t,d,g)}catch(g){return n.error(new R({error:g,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 P(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 H=/^\)\]\}',?\n/;function S(e,t,r){switch(e.responseType){case"json":const n=new TextDecoder().decode(t).replace(H,"");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 C{send(t){return new m.Observable(r=>{const n=new XMLHttpRequest;n.open(t.method,t.getUrlWithParams()),t.withCredentials&&(n.withCredentials=!0),t.headers.forEach((h,a)=>n.setRequestHeader(h,a.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 h=n.statusText||"OK",a=new E(n.getAllResponseHeaders());return new B(a,n.status,h)},c=()=>{const{headers:h,statusText:a,status:l}=s(),{responseType:p}=t;let d=null,w=null;l!==x.NoContent&&(d=typeof n.response>"u"?n.responseText:n.response);let f=l>=K&&l<Q;if(p==="json"&&typeof d=="string"){const g=d;try{d=d?JSON.parse(d):null}catch(u){f=!1,d=g,w=u}}f?r.next(new L({body:d,headers:h,status:l,statusText:a})):r.error(new R({error:w,headers:h,status:l,statusText:a}))},o=h=>{const a=new R({error:h,status:n.status||0,statusText:n.statusText||"Unknown Error",headers:s().headers});r.error(a)};n.addEventListener("load",c),n.addEventListener("error",o),n.addEventListener("abort",o),n.addEventListener("timeout",o);const i=t.getBody();return n.send(i),()=>{n.readyState!==n.DONE&&n.abort(),n.removeEventListener("load",c),n.removeEventListener("error",o),n.removeEventListener("abort",o),n.removeEventListener("timeout",o)}})}}const T=O.createIdentifier("univer.socket");class ee extends b.Disposable{createSocket(t){try{const r=new WebSocket(t),n=new b.DisposableCollection;return{URL:t,close:(c,o)=>{r.close(c,o),n.dispose()},send:c=>{r.send(c)},open$:new m.Observable(c=>{const o=i=>c.next(i);r.addEventListener("open",o),n.add(b.toDisposable(()=>r.removeEventListener("open",o)))}).pipe(v.share()),close$:new m.Observable(c=>{const o=i=>c.next(i);r.addEventListener("close",o),n.add(b.toDisposable(()=>r.removeEventListener("close",o)))}).pipe(v.share()),error$:new m.Observable(c=>{const o=i=>c.next(i);r.addEventListener("error",o),n.add(b.toDisposable(()=>r.removeEventListener("error",o)))}).pipe(v.share()),message$:new m.Observable(c=>{const o=i=>c.next(i);r.addEventListener("message",o),n.add(b.toDisposable(()=>r.removeEventListener("message",o)))}).pipe(v.share())}}catch(r){return console.error(r),null}}}const re=3,te=1e3,ne=(e,t)=>{var s,c;const r=(s=t==null?void 0:t.maxRetryAttempts)!=null?s:re,n=(c=t==null?void 0:t.delayInterval)!=null?c:te;return(o,i)=>i(o).pipe(v.retry({delay:n,count:r}))},se=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 c=t.shift();r.add(c),c()}};return(s,c)=>new m.Observable(o=>{const i=()=>c(s).subscribe({next:a=>o.next(a),error:a=>o.next(a),complete:()=>o.complete()}),h=()=>{r.delete(i),b.remove(t,i),n()};return t.push(i),n(),h})},oe=e=>{const{errorStatusCodes:t,onAuthError:r}=e;return(s,c)=>c(s).pipe(m.catchError(o=>(o instanceof R&&t.some(i=>i===o.status)&&r(),m.throwError(()=>o))))},ce=(e=300)=>{let r=()=>{};return n=>new Promise(s=>{r();const c=setTimeout(()=>{s(!0)},e);r=()=>{clearTimeout(c),s(!1)}})},ie=()=>(e,t)=>t.map(r=>({config:r,result:e})),ae=(e,t={})=>{const{isMatch:r,getParamsFromRequest:n,mergeParamsToRequest:s}=e,{fetchCheck:c=ce(300),distributeResult:o=ie()}=t,i=[],h=a=>a.map(l=>l.config);return(a,l)=>r(a)?new m.Observable(p=>{const d=n(a);i.push({next:f=>p.next(f),error:f=>p.error(f),config:d});const w=h(i);c(a).then(f=>{if(f){const g=[];w.forEach(u=>{const I=i.findIndex(_=>_.config===u);if(I>=0){const[_]=i.splice(I,1);g.push(_)}}),l(s(w,a)).subscribe({next:u=>{if(u.type===N.Response){const I=u.body,_=o(I,w);g.forEach(F=>{const k=_.find(A=>A.config===F.config);if(k){const A=new L({body:k.result,headers:u.headers,status:u.status,statusText:u.statusText});F.next(A)}else F.error("batch error")})}},complete:()=>p.complete(),error:u=>p.error(u)})}})}):l(a)};exports.AuthInterceptorFactory=oe;exports.FetchHTTPImplementation=Z;exports.HTTPEventType=N;exports.HTTPHeaders=E;exports.HTTPProgress=j;exports.HTTPRequest=q;exports.HTTPResponse=L;exports.HTTPResponseError=R;exports.HTTPStatusCode=x;exports.IHTTPImplementation=M;exports.ISocketService=T;exports.MergeInterceptorFactory=ae;exports.ResponseHeader=B;exports.RetryInterceptorFactory=ne;exports.ThresholdInterceptorFactory=se;exports.WebSocketService=ee;exports.XHRHTTPImplementation=C;
package/lib/es/index.js CHANGED
@@ -1,14 +1,14 @@
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);
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
- const L = "application/json";
9
- class R {
1
+ var V = Object.defineProperty;
2
+ var W = (e, r, n) => r in e ? V(e, r, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[r] = n;
3
+ var m = (e, r, n) => W(e, typeof r != "symbol" ? r + "" : r, n);
4
+ import { Disposable as j, toDisposable as _, remove as B, DisposableCollection as X } from "@univerjs/core";
5
+ import { of as U, firstValueFrom as z, Observable as g, catchError as J, throwError as Y } from "rxjs";
6
+ import { concatMap as k, share as v, retry as K } from "rxjs/operators";
7
+ import { createIdentifier as $ } from "@wendellhu/redi";
8
+ const q = "application/json";
9
+ class x {
10
10
  constructor(r) {
11
- p(this, "_headers", /* @__PURE__ */ new Map());
11
+ m(this, "_headers", /* @__PURE__ */ new Map());
12
12
  typeof r == "string" ? this._handleHeadersString(r) : r instanceof Headers ? this._handleHeaders(r) : r && this._handleHeadersConstructorProps(r);
13
13
  }
14
14
  forEach(r) {
@@ -24,8 +24,8 @@ class R {
24
24
  toHeadersInit() {
25
25
  var n, t;
26
26
  const r = {};
27
- return this._headers.forEach((s, o) => {
28
- r[o] = s.join(",");
27
+ return this._headers.forEach((s, i) => {
28
+ r[i] = s.join(",");
29
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
30
  }
31
31
  _setHeader(r, n) {
@@ -46,8 +46,8 @@ class R {
46
46
  r.forEach((n, t) => this._setHeader(t, n));
47
47
  }
48
48
  }
49
- const W = k("network.http-implementation");
50
- class A {
49
+ const Q = $("network.http-implementation");
50
+ class M {
51
51
  constructor(r) {
52
52
  this.params = r;
53
53
  }
@@ -55,10 +55,10 @@ class A {
55
55
  return this.params ? Object.keys(this.params).map((r) => `${r}=${this.params[r]}`).join("&") : "";
56
56
  }
57
57
  }
58
- let X = 0;
59
- class N {
58
+ let Z = 0;
59
+ class D {
60
60
  constructor(r, n, t) {
61
- p(this, "uid", X++);
61
+ m(this, "uid", Z++);
62
62
  this.method = r, this.url = n, this.requestParams = t;
63
63
  }
64
64
  get headers() {
@@ -77,24 +77,24 @@ class N {
77
77
  }
78
78
  getBody() {
79
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;
80
+ const r = (t = this.headers.get("Content-Type")) != null ? t : q, n = (s = this.requestParams) == null ? void 0 : s.body;
81
+ return r === q && 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
- 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 {
87
+ var P = Object.defineProperty, S = Object.getOwnPropertyDescriptor, H = (e, r, n, t) => {
88
+ for (var s = t > 1 ? void 0 : t ? S(r, n) : r, i = e.length - 1, o; i >= 0; i--)
89
+ (o = e[i]) && (s = (t ? o(r, n, s) : o(s)) || s);
90
+ return t && s && P(r, n, s), s;
91
+ }, C = (e, r) => (n, t) => r(n, t, e);
92
+ let O = class extends j {
93
93
  constructor(r) {
94
94
  super();
95
- p(this, "_interceptors", []);
95
+ m(this, "_interceptors", []);
96
96
  // eslint-disable-next-line ts/no-explicit-any
97
- p(this, "_pipe");
97
+ m(this, "_pipe");
98
98
  this._http = r;
99
99
  }
100
100
  /**
@@ -107,9 +107,9 @@ let F = class extends q {
107
107
  if (this._interceptors.indexOf(r) !== -1)
108
108
  throw new Error("[HTTPService]: The interceptor has already been registered!");
109
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));
110
+ var s, i;
111
+ return ((s = n.priority) != null ? s : 0) - ((i = t.priority) != null ? i : 0);
112
+ }), this._pipe = null, _(() => B(this._interceptors, r));
113
113
  }
114
114
  get(r, n) {
115
115
  return this._request("GET", r, n);
@@ -127,36 +127,36 @@ let F = class extends q {
127
127
  return this._request("PATCH", r, n);
128
128
  }
129
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, {
130
+ var c, l;
131
+ const s = new x(t == null ? void 0 : t.headers), i = new M(t == null ? void 0 : t.params), o = new D(r, n, {
132
132
  headers: s,
133
- params: o,
134
- withCredentials: (a = t == null ? void 0 : t.withCredentials) != null ? a : !1,
133
+ params: i,
134
+ withCredentials: (c = t == null ? void 0 : t.withCredentials) != null ? c : !1,
135
135
  reportProgress: !0,
136
- responseType: (c = t == null ? void 0 : t.responseType) != null ? c : "json",
136
+ responseType: (l = t == null ? void 0 : t.responseType) != null ? l : "json",
137
137
  body: ["GET", "DELETE"].includes(r) || t == null ? void 0 : t.body
138
138
  });
139
- return b(i).pipe(I((l) => this._runInterceptorsAndImplementation(l)));
139
+ return U(o).pipe(k((a) => this._runInterceptorsAndImplementation(a)));
140
140
  }
141
141
  /** The HTTP request implementations */
142
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, {
143
+ var a, h;
144
+ const s = new x(t == null ? void 0 : t.headers), i = new M(t == null ? void 0 : t.params), o = new D(r, n, {
145
145
  headers: s,
146
- params: o,
147
- withCredentials: (l = t == null ? void 0 : t.withCredentials) != null ? l : !1,
146
+ params: i,
147
+ withCredentials: (a = t == null ? void 0 : t.withCredentials) != null ? a : !1,
148
148
  // default value for withCredentials is false by MDN
149
149
  responseType: (h = t == null ? void 0 : t.responseType) != null ? h : "json",
150
150
  body: ["GET", "DELETE"].includes(r) || t == null ? void 0 : t.body
151
- }), a = b(i).pipe(
152
- I((y) => this._runInterceptorsAndImplementation(y))
151
+ }), c = U(o).pipe(
152
+ k((u) => this._runInterceptorsAndImplementation(u))
153
153
  );
154
- return await B(a);
154
+ return await z(c);
155
155
  }
156
156
  // eslint-disable-next-line ts/no-explicit-any
157
157
  _runInterceptorsAndImplementation(r) {
158
158
  return this._pipe || (this._pipe = this._interceptors.map((n) => n.interceptor).reduceRight(
159
- (n, t) => Q(n, t),
159
+ (n, t) => T(n, t),
160
160
  (n, t) => t(n)
161
161
  )), this._pipe(
162
162
  r,
@@ -165,69 +165,69 @@ let F = class extends q {
165
165
  );
166
166
  }
167
167
  };
168
- F = Y([
169
- K(0, W)
170
- ], F);
171
- function Q(e, r) {
168
+ O = H([
169
+ C(0, Q)
170
+ ], O);
171
+ function T(e, r) {
172
172
  return (n, t) => r(n, (s) => e(s, t));
173
173
  }
174
- var Z = /* @__PURE__ */ ((e) => (e[e.DownloadProgress = 0] = "DownloadProgress", e[e.Response = 1] = "Response", e))(Z || {});
175
- class M {
174
+ var G = /* @__PURE__ */ ((e) => (e[e.DownloadProgress = 0] = "DownloadProgress", e[e.Response = 1] = "Response", e))(G || {});
175
+ class F {
176
176
  constructor({
177
177
  body: r,
178
178
  headers: n,
179
179
  status: t,
180
180
  statusText: s
181
181
  }) {
182
- p(this, "type", 1);
183
- p(this, "body");
184
- p(this, "headers");
185
- p(this, "status");
186
- p(this, "statusText");
182
+ m(this, "type", 1);
183
+ m(this, "body");
184
+ m(this, "headers");
185
+ m(this, "status");
186
+ m(this, "statusText");
187
187
  this.body = r, this.headers = n, this.status = t, this.statusText = s;
188
188
  }
189
189
  }
190
- class P {
190
+ class ee {
191
191
  constructor(r, n, t) {
192
- p(this, "type", 0);
192
+ m(this, "type", 0);
193
193
  this.total = r, this.loaded = n, this.partialText = t;
194
194
  }
195
195
  }
196
- class S {
196
+ class re {
197
197
  constructor(r, n, t) {
198
198
  this.headers = r, this.status = n, this.statusText = t;
199
199
  }
200
200
  }
201
- class w {
201
+ class E {
202
202
  constructor({
203
203
  headers: r,
204
204
  status: n,
205
205
  statusText: t,
206
206
  error: s
207
207
  }) {
208
- p(this, "headers");
209
- p(this, "status");
210
- p(this, "statusText");
211
- p(this, "error");
208
+ m(this, "headers");
209
+ m(this, "status");
210
+ m(this, "statusText");
211
+ m(this, "error");
212
212
  this.headers = r, this.status = n, this.statusText = t, this.error = s;
213
213
  }
214
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 {
215
+ const te = 200, ne = 300;
216
+ var L = /* @__PURE__ */ ((e) => (e[e.Continue = 100] = "Continue", e[e.SwitchingProtocols = 101] = "SwitchingProtocols", e[e.Processing = 102] = "Processing", e[e.EarlyHints = 103] = "EarlyHints", e[e.Ok = 200] = "Ok", e[e.Created = 201] = "Created", e[e.Accepted = 202] = "Accepted", e[e.NonAuthoritativeInformation = 203] = "NonAuthoritativeInformation", e[e.NoContent = 204] = "NoContent", e[e.ResetContent = 205] = "ResetContent", e[e.PartialContent = 206] = "PartialContent", e[e.MultiStatus = 207] = "MultiStatus", e[e.AlreadyReported = 208] = "AlreadyReported", e[e.ImUsed = 226] = "ImUsed", e[e.MultipleChoices = 300] = "MultipleChoices", e[e.MovedPermanently = 301] = "MovedPermanently", e[e.Found = 302] = "Found", e[e.SeeOther = 303] = "SeeOther", e[e.NotModified = 304] = "NotModified", e[e.UseProxy = 305] = "UseProxy", e[e.Unused = 306] = "Unused", e[e.TemporaryRedirect = 307] = "TemporaryRedirect", e[e.PermanentRedirect = 308] = "PermanentRedirect", e[e.BadRequest = 400] = "BadRequest", e[e.Unauthorized = 401] = "Unauthorized", e[e.PaymentRequired = 402] = "PaymentRequired", e[e.Forbidden = 403] = "Forbidden", e[e.NotFound = 404] = "NotFound", e[e.MethodNotAllowed = 405] = "MethodNotAllowed", e[e.NotAcceptable = 406] = "NotAcceptable", e[e.ProxyAuthenticationRequired = 407] = "ProxyAuthenticationRequired", e[e.RequestTimeout = 408] = "RequestTimeout", e[e.Conflict = 409] = "Conflict", e[e.Gone = 410] = "Gone", e[e.LengthRequired = 411] = "LengthRequired", e[e.PreconditionFailed = 412] = "PreconditionFailed", e[e.PayloadTooLarge = 413] = "PayloadTooLarge", e[e.UriTooLong = 414] = "UriTooLong", e[e.UnsupportedMediaType = 415] = "UnsupportedMediaType", e[e.RangeNotSatisfiable = 416] = "RangeNotSatisfiable", e[e.ExpectationFailed = 417] = "ExpectationFailed", e[e.ImATeapot = 418] = "ImATeapot", e[e.MisdirectedRequest = 421] = "MisdirectedRequest", e[e.UnprocessableEntity = 422] = "UnprocessableEntity", e[e.Locked = 423] = "Locked", e[e.FailedDependency = 424] = "FailedDependency", e[e.TooEarly = 425] = "TooEarly", e[e.UpgradeRequired = 426] = "UpgradeRequired", e[e.PreconditionRequired = 428] = "PreconditionRequired", e[e.TooManyRequests = 429] = "TooManyRequests", e[e.RequestHeaderFieldsTooLarge = 431] = "RequestHeaderFieldsTooLarge", e[e.UnavailableForLegalReasons = 451] = "UnavailableForLegalReasons", e[e.InternalServerError = 500] = "InternalServerError", e[e.NotImplemented = 501] = "NotImplemented", e[e.BadGateway = 502] = "BadGateway", e[e.ServiceUnavailable = 503] = "ServiceUnavailable", e[e.GatewayTimeout = 504] = "GatewayTimeout", e[e.HttpVersionNotSupported = 505] = "HttpVersionNotSupported", e[e.VariantAlsoNegotiates = 506] = "VariantAlsoNegotiates", e[e.InsufficientStorage = 507] = "InsufficientStorage", e[e.LoopDetected = 508] = "LoopDetected", e[e.NotExtended = 510] = "NotExtended", e[e.NetworkAuthenticationRequired = 511] = "NetworkAuthenticationRequired", e))(L || {});
217
+ class fe {
218
218
  send(r) {
219
- return new u((n) => {
219
+ return new g((n) => {
220
220
  const t = new AbortController();
221
221
  return this._send(r, n, t).then(() => {
222
222
  }, (s) => {
223
- n.error(new w({
223
+ n.error(new E({
224
224
  error: s
225
225
  }));
226
226
  }), () => t.abort();
227
227
  });
228
228
  }
229
229
  async _send(r, n, t) {
230
- var h, y;
230
+ var h, u;
231
231
  let s;
232
232
  try {
233
233
  const d = this._parseFetchParamsFromRequest(r);
@@ -236,53 +236,53 @@ class le {
236
236
  ...d
237
237
  });
238
238
  } catch (d) {
239
- n.error(new w({
239
+ n.error(new E({
240
240
  error: d,
241
241
  status: (h = d.status) != null ? h : 0,
242
- statusText: (y = d.statusText) != null ? y : "Unknown Error",
242
+ statusText: (u = d.statusText) != null ? u : "Unknown Error",
243
243
  headers: d.headers
244
244
  }));
245
245
  return;
246
246
  }
247
- const o = new R(s.headers), i = s.status, a = s.statusText;
248
- let c = null;
249
- s.body && (c = await this._readBody(r, s, n)), i >= x.Ok && i < x.MultipleChoices ? n.next(new M({
250
- body: c,
251
- headers: o,
252
- status: i,
253
- statusText: a
254
- })) : n.error(new w({
255
- error: c,
256
- status: i,
257
- statusText: a,
258
- headers: o
247
+ const i = new x(s.headers), o = s.status, c = s.statusText;
248
+ let l = null;
249
+ s.body && (l = await this._readBody(r, s, n)), o >= L.Ok && o < L.MultipleChoices ? n.next(new F({
250
+ body: l,
251
+ headers: i,
252
+ status: o,
253
+ statusText: c
254
+ })) : n.error(new E({
255
+ error: l,
256
+ status: o,
257
+ statusText: c,
258
+ headers: i
259
259
  })), n.complete();
260
260
  }
261
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;
262
+ var f, y;
263
+ const s = [], i = n.body.getReader(), o = n.headers.get("content-length");
264
+ let c = 0;
265
+ const l = (f = r.requestParams) == null ? void 0 : f.reportProgress, a = r.responseType;
266
+ let h, u;
267
267
  for (; ; ) {
268
- const { done: m, value: g } = await o.read();
269
- if (m) break;
270
- 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(
271
- i ? Number.parseInt(i, 10) : void 0,
272
- a,
268
+ const { done: w, value: p } = await i.read();
269
+ if (w) break;
270
+ s.push(p), c += p.length, l && a === "text" && (h = (h != null ? h : "") + (u != null ? u : u = new TextDecoder()).decode(p, { stream: !0 }), t.next(new ee(
271
+ o ? Number.parseInt(o, 10) : void 0,
272
+ c,
273
273
  h
274
274
  )));
275
275
  }
276
- const d = T(s, a);
276
+ const d = se(s, c);
277
277
  try {
278
- const m = (E = n.headers.get("content-type")) != null ? E : "";
279
- return re(r, d, m);
280
- } catch (m) {
281
- return t.error(new w({
282
- error: m,
278
+ const w = (y = n.headers.get("content-type")) != null ? y : "";
279
+ return ie(r, d, w);
280
+ } catch (w) {
281
+ return t.error(new E({
282
+ error: w,
283
283
  status: n.status,
284
284
  statusText: n.statusText,
285
- headers: new R(n.headers)
285
+ headers: new x(n.headers)
286
286
  })), null;
287
287
  }
288
288
  }
@@ -295,18 +295,18 @@ class le {
295
295
  };
296
296
  }
297
297
  }
298
- function T(e, r) {
298
+ function se(e, r) {
299
299
  const n = new Uint8Array(r);
300
300
  let t = 0;
301
301
  for (const s of e)
302
302
  n.set(s, t), t += s.length;
303
303
  return n;
304
304
  }
305
- const ee = /^\)\]\}',?\n/;
306
- function re(e, r, n) {
305
+ const oe = /^\)\]\}',?\n/;
306
+ function ie(e, r, n) {
307
307
  switch (e.responseType) {
308
308
  case "json":
309
- const t = new TextDecoder().decode(r).replace(ee, "");
309
+ const t = new TextDecoder().decode(r).replace(oe, "");
310
310
  return t === "" ? null : JSON.parse(t);
311
311
  case "text":
312
312
  return new TextDecoder().decode(r);
@@ -318,87 +318,87 @@ function re(e, r, n) {
318
318
  throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`);
319
319
  }
320
320
  }
321
- class he {
321
+ class we {
322
322
  send(r) {
323
- return new u((n) => {
323
+ return new g((n) => {
324
324
  const t = new XMLHttpRequest();
325
- 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");
325
+ t.open(r.method, r.getUrlWithParams()), r.withCredentials && (t.withCredentials = !0), r.headers.forEach((l, a) => t.setRequestHeader(l, a.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");
326
326
  const s = () => {
327
- const c = t.statusText || "OK", l = new R(t.getAllResponseHeaders());
328
- return new S(l, t.status, c);
329
- }, o = () => {
330
- const { headers: c, statusText: l, status: h } = s(), { responseType: y } = r;
327
+ const l = t.statusText || "OK", a = new x(t.getAllResponseHeaders());
328
+ return new re(a, t.status, l);
329
+ }, i = () => {
330
+ const { headers: l, statusText: a, status: h } = s(), { responseType: u } = r;
331
331
  let d = null, f = null;
332
- h !== x.NoContent && (d = typeof t.response > "u" ? t.responseText : t.response);
333
- let E = h >= H && h < C;
334
- if (y === "json" && typeof d == "string") {
335
- const m = d;
332
+ h !== L.NoContent && (d = typeof t.response > "u" ? t.responseText : t.response);
333
+ let y = h >= te && h < ne;
334
+ if (u === "json" && typeof d == "string") {
335
+ const w = d;
336
336
  try {
337
337
  d = d ? JSON.parse(d) : null;
338
- } catch (g) {
339
- E = !1, d = m, f = g;
338
+ } catch (p) {
339
+ y = !1, d = w, f = p;
340
340
  }
341
341
  }
342
- E ? n.next(
343
- new M({
342
+ y ? n.next(
343
+ new F({
344
344
  body: d,
345
- headers: c,
345
+ headers: l,
346
346
  status: h,
347
- statusText: l
347
+ statusText: a
348
348
  })
349
349
  ) : n.error(
350
- new w({
350
+ new E({
351
351
  error: f,
352
- headers: c,
352
+ headers: l,
353
353
  status: h,
354
- statusText: l
354
+ statusText: a
355
355
  })
356
356
  );
357
- }, i = (c) => {
358
- const l = new w({
359
- error: c,
357
+ }, o = (l) => {
358
+ const a = new E({
359
+ error: l,
360
360
  status: t.status || 0,
361
361
  statusText: t.statusText || "Unknown Error",
362
362
  headers: s().headers
363
363
  });
364
- n.error(l);
364
+ n.error(a);
365
365
  };
366
- t.addEventListener("load", o), t.addEventListener("error", i), t.addEventListener("abort", i), t.addEventListener("timeout", i);
367
- const a = r.getBody();
368
- return t.send(a), () => {
369
- t.readyState !== t.DONE && t.abort(), t.removeEventListener("load", o), t.removeEventListener("error", i), t.removeEventListener("abort", i), t.removeEventListener("timeout", i);
366
+ t.addEventListener("load", i), t.addEventListener("error", o), t.addEventListener("abort", o), t.addEventListener("timeout", o);
367
+ const c = r.getBody();
368
+ return t.send(c), () => {
369
+ t.readyState !== t.DONE && t.abort(), t.removeEventListener("load", i), t.removeEventListener("error", o), t.removeEventListener("abort", o), t.removeEventListener("timeout", o);
370
370
  };
371
371
  });
372
372
  }
373
373
  }
374
- const de = k("univer.socket");
375
- class pe extends q {
374
+ const ge = $("univer.socket");
375
+ class Ee extends j {
376
376
  createSocket(r) {
377
377
  try {
378
- const n = new WebSocket(r), t = new j();
378
+ const n = new WebSocket(r), t = new X();
379
379
  return {
380
380
  URL: r,
381
- close: (o, i) => {
382
- n.close(o, i), t.dispose();
381
+ close: (i, o) => {
382
+ n.close(i, o), t.dispose();
383
383
  },
384
- send: (o) => {
385
- n.send(o);
384
+ send: (i) => {
385
+ n.send(i);
386
386
  },
387
- open$: new u((o) => {
388
- const i = (a) => o.next(a);
389
- n.addEventListener("open", i), t.add(_(() => n.removeEventListener("open", i)));
387
+ open$: new g((i) => {
388
+ const o = (c) => i.next(c);
389
+ n.addEventListener("open", o), t.add(_(() => n.removeEventListener("open", o)));
390
390
  }).pipe(v()),
391
- close$: new u((o) => {
392
- const i = (a) => o.next(a);
393
- n.addEventListener("close", i), t.add(_(() => n.removeEventListener("close", i)));
391
+ close$: new g((i) => {
392
+ const o = (c) => i.next(c);
393
+ n.addEventListener("close", o), t.add(_(() => n.removeEventListener("close", o)));
394
394
  }).pipe(v()),
395
- error$: new u((o) => {
396
- const i = (a) => o.next(a);
397
- n.addEventListener("error", i), t.add(_(() => n.removeEventListener("error", i)));
395
+ error$: new g((i) => {
396
+ const o = (c) => i.next(c);
397
+ n.addEventListener("error", o), t.add(_(() => n.removeEventListener("error", o)));
398
398
  }).pipe(v()),
399
- message$: new u((o) => {
400
- const i = (a) => o.next(a);
401
- n.addEventListener("message", i), t.add(_(() => n.removeEventListener("message", i)));
399
+ message$: new g((i) => {
400
+ const o = (c) => i.next(c);
401
+ n.addEventListener("message", o), t.add(_(() => n.removeEventListener("message", o)));
402
402
  }).pipe(v())
403
403
  };
404
404
  } catch (n) {
@@ -406,50 +406,107 @@ class pe extends q {
406
406
  }
407
407
  }
408
408
  }
409
- const te = 3, ne = 1e3, ye = (e, r) => {
410
- var s, o;
411
- const n = (s = r == null ? void 0 : r.maxRetryAttempts) != null ? s : te, t = (o = r == null ? void 0 : r.delayInterval) != null ? o : ne;
412
- return (i, a) => a(i).pipe(V({ delay: t, count: n }));
413
- }, me = (e) => {
409
+ const ce = 3, ae = 1e3, Re = (e, r) => {
410
+ var s, i;
411
+ const n = (s = r == null ? void 0 : r.maxRetryAttempts) != null ? s : ce, t = (i = r == null ? void 0 : r.delayInterval) != null ? i : ae;
412
+ return (o, c) => c(o).pipe(K({ delay: t, count: n }));
413
+ }, _e = (e) => {
414
414
  const r = [], n = /* @__PURE__ */ new Set(), t = () => {
415
415
  var s;
416
416
  for (; n.size < ((s = e == null ? void 0 : e.maxParallel) != null ? s : 1) && r.length > 0; ) {
417
- const o = r.shift();
418
- n.add(o), o();
417
+ const i = r.shift();
418
+ n.add(i), i();
419
419
  }
420
420
  };
421
- return (s, o) => new u((i) => {
422
- const a = () => o(s).subscribe({
423
- next: (l) => i.next(l),
424
- error: (l) => i.next(l),
425
- complete: () => i.complete()
426
- }), c = () => {
427
- n.delete(a), U(r, a), t();
421
+ return (s, i) => new g((o) => {
422
+ const c = () => i(s).subscribe({
423
+ next: (a) => o.next(a),
424
+ error: (a) => o.next(a),
425
+ complete: () => o.complete()
426
+ }), l = () => {
427
+ n.delete(c), B(r, c), t();
428
428
  };
429
- return r.push(a), t(), c;
429
+ return r.push(c), t(), l;
430
430
  });
431
- }, ue = (e) => {
431
+ }, xe = (e) => {
432
432
  const { errorStatusCodes: r, onAuthError: n } = e;
433
- return (s, o) => o(s).pipe(
434
- $((i) => (i instanceof w && r.some((a) => a === i.status) && n(), G(() => i)))
433
+ return (s, i) => i(s).pipe(
434
+ J((o) => (o instanceof E && r.some((c) => c === o.status) && n(), Y(() => o)))
435
435
  );
436
+ }, le = (e = 300) => {
437
+ let n = () => {
438
+ };
439
+ return (t) => new Promise((s) => {
440
+ n();
441
+ const i = setTimeout(() => {
442
+ s(!0);
443
+ }, e);
444
+ n = () => {
445
+ clearTimeout(i), s(!1);
446
+ };
447
+ });
448
+ }, he = () => (e, r) => r.map((n) => ({ config: n, result: e })), be = (e, r = {}) => {
449
+ const { isMatch: n, getParamsFromRequest: t, mergeParamsToRequest: s } = e, { fetchCheck: i = le(300), distributeResult: o = he() } = r, c = [], l = (a) => a.map((h) => h.config);
450
+ return (a, h) => n(a) ? new g((u) => {
451
+ const d = t(a);
452
+ c.push({
453
+ next: (y) => u.next(y),
454
+ error: (y) => u.error(y),
455
+ config: d
456
+ });
457
+ const f = l(c);
458
+ i(a).then((y) => {
459
+ if (y) {
460
+ const w = [];
461
+ f.forEach((p) => {
462
+ const b = c.findIndex((R) => R.config === p);
463
+ if (b >= 0) {
464
+ const [R] = c.splice(b, 1);
465
+ w.push(R);
466
+ }
467
+ }), h(s(f, a)).subscribe({
468
+ next: (p) => {
469
+ if (p.type === G.Response) {
470
+ const b = p.body, R = o(b, f);
471
+ w.forEach((I) => {
472
+ const N = R.find((A) => A.config === I.config);
473
+ if (N) {
474
+ const A = new F({
475
+ body: N.result,
476
+ headers: p.headers,
477
+ status: p.status,
478
+ statusText: p.statusText
479
+ });
480
+ I.next(A);
481
+ } else
482
+ I.error("batch error");
483
+ });
484
+ }
485
+ },
486
+ complete: () => u.complete(),
487
+ error: (p) => u.error(p)
488
+ });
489
+ }
490
+ });
491
+ }) : h(a);
436
492
  };
437
493
  export {
438
- ue as AuthInterceptorFactory,
439
- le as FetchHTTPImplementation,
440
- Z as HTTPEventType,
441
- R as HTTPHeaders,
442
- P as HTTPProgress,
443
- N as HTTPRequest,
444
- M as HTTPResponse,
445
- w as HTTPResponseError,
446
- F as HTTPService,
447
- x as HTTPStatusCode,
448
- W as IHTTPImplementation,
449
- de as ISocketService,
450
- S as ResponseHeader,
451
- ye as RetryInterceptorFactory,
452
- me as ThresholdInterceptorFactory,
453
- pe as WebSocketService,
454
- he as XHRHTTPImplementation
494
+ xe as AuthInterceptorFactory,
495
+ fe as FetchHTTPImplementation,
496
+ G as HTTPEventType,
497
+ x as HTTPHeaders,
498
+ ee as HTTPProgress,
499
+ D as HTTPRequest,
500
+ F as HTTPResponse,
501
+ E as HTTPResponseError,
502
+ O as HTTPService,
503
+ L as HTTPStatusCode,
504
+ Q as IHTTPImplementation,
505
+ ge as ISocketService,
506
+ be as MergeInterceptorFactory,
507
+ re as ResponseHeader,
508
+ Re as RetryInterceptorFactory,
509
+ _e as ThresholdInterceptorFactory,
510
+ Ee as WebSocketService,
511
+ we as XHRHTTPImplementation
455
512
  };
@@ -27,3 +27,4 @@ export type { HTTPHandlerFn, HTTPInterceptorFn, HTTPInterceptorFnFactory } from
27
27
  export { RetryInterceptorFactory, type IRetryInterceptorFactoryParams } from './services/http/interceptors/retry-interceptor';
28
28
  export { ThresholdInterceptorFactory } from './services/http/interceptors/threshold-interceptor';
29
29
  export { AuthInterceptorFactory, type IAuthInterceptorParams } from './services/http/interceptors/auth-interceptor';
30
+ export { MergeInterceptorFactory } from './services/http/interceptors/merge-interceptor';
@@ -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,33 @@
1
+ import { Observable } from 'rxjs';
2
+ import { HTTPRequest } from '../request';
3
+ import { HTTPHandlerFn } from '../interceptor';
4
+
5
+ export declare const MergeInterceptorFactory: <T, C>(config: {
6
+ /**
7
+ * Filter requests that need to be merged
8
+ */
9
+ isMatch: (requestConfig: HTTPRequest) => boolean;
10
+ /**
11
+ * Pre-process request parameters, the return value will be used as input parameters for subsequent operations
12
+ * The result is used as an index key
13
+ */
14
+ getParamsFromRequest: (requestConfig: HTTPRequest) => T;
15
+ /**
16
+ * The request parameters are merged to initiate the request
17
+ */
18
+ mergeParamsToRequest: (list: T[], requestConfig: HTTPRequest) => HTTPRequest;
19
+ }, options?: {
20
+ /**
21
+ * Determine when to initiate a request
22
+ * By default, requests up to 300ms are automatically aggregated
23
+ */
24
+ fetchCheck?: (currentConfig: HTTPRequest) => Promise<boolean>;
25
+ /**
26
+ * The result of the request is dispatched based on the request parameters.
27
+ * By default each request gets the full result of the batch request
28
+ */
29
+ distributeResult?: (result: C, list: T[]) => {
30
+ config: T;
31
+ result: C;
32
+ }[];
33
+ }) => (requestConfig: HTTPRequest, next: HTTPHandlerFn) => Observable<import('../response').HTTPEvent<unknown>>;
@@ -21,7 +21,7 @@ export declare class HTTPRequest {
21
21
  readonly requestParams?: IHTTPRequestParams | undefined;
22
22
  get headers(): HTTPHeaders;
23
23
  get withCredentials(): boolean;
24
- get responseType(): string;
24
+ get responseType(): HTTPResponseType;
25
25
  readonly uid: number;
26
26
  constructor(method: HTTPRequestMethod, url: string, requestParams?: IHTTPRequestParams | undefined);
27
27
  getUrlWithParams(): string;
package/lib/umd/index.js CHANGED
@@ -1,2 +1,2 @@
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);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"})});
1
+ (function(c,p){typeof exports=="object"&&typeof module<"u"?p(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"],p):(c=typeof globalThis<"u"?globalThis:c||self,p(c.UniverNetwork={},c.UniverCore,c.rxjs,c.rxjs.operators,c["@wendellhu/redi"]))})(this,function(c,p,y,E,k){"use strict";var ae=Object.defineProperty;var le=(c,p,y)=>p in c?ae(c,p,{enumerable:!0,configurable:!0,writable:!0,value:y}):c[p]=y;var w=(c,p,y)=>le(c,typeof p!="symbol"?p+"":p,y);const D="application/json";class _{constructor(n){w(this,"_headers",new Map);typeof n=="string"?this._handleHeadersString(n):n instanceof Headers?this._handleHeaders(n):n&&this._handleHeadersConstructorProps(n)}forEach(n){this._headers.forEach((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,o)=>{n[o]=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 O=k.createIdentifier("network.http-implementation");class M{constructor(n){this.params=n}toString(){return this.params?Object.keys(this.params).map(n=>`${n}=${this.params[n]}`).join("&"):""}}let G=0;class x{constructor(n,r,t){w(this,"uid",G++);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:D,r=(s=this.requestParams)==null?void 0:s.body;return n===D&&r&&typeof r=="object"?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){return this.headers.toHeadersInit()}}var V=Object.defineProperty,W=Object.getOwnPropertyDescriptor,X=(e,n,r,t)=>{for(var s=t>1?void 0:t?W(n,r):n,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(t?i(n,r,s):i(s))||s);return t&&s&&V(n,r,s),s},z=(e,n)=>(r,t)=>n(r,t,e);c.HTTPService=class extends p.Disposable{constructor(r){super();w(this,"_interceptors",[]);w(this,"_pipe");this._http=r}registerHTTPInterceptor(r){if(this._interceptors.indexOf(r)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(r),this._interceptors=this._interceptors.sort((t,s)=>{var o,i;return((o=t.priority)!=null?o:0)-((i=s.priority)!=null?i:0)}),this._pipe=null,p.toDisposable(()=>p.remove(this._interceptors,r))}get(r,t){return this._request("GET",r,t)}post(r,t){return this._request("POST",r,t)}put(r,t){return this._request("PUT",r,t)}delete(r,t){return this._request("DELETE",r,t)}patch(r,t){return this._request("PATCH",r,t)}getSSE(r,t,s){var d,l;const o=new _(s==null?void 0:s.headers),i=new M(s==null?void 0:s.params),a=new x(r,t,{headers:o,params:i,withCredentials:(d=s==null?void 0:s.withCredentials)!=null?d:!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(E.concatMap(h=>this._runInterceptorsAndImplementation(h)))}async _request(r,t,s){var h,m;const o=new _(s==null?void 0:s.headers),i=new M(s==null?void 0:s.params),a=new x(r,t,{headers:o,params:i,withCredentials:(h=s==null?void 0:s.withCredentials)!=null?h:!1,responseType:(m=s==null?void 0:s.responseType)!=null?m:"json",body:["GET","DELETE"].includes(r)||s==null?void 0:s.body}),d=y.of(a).pipe(E.concatMap(u=>this._runInterceptorsAndImplementation(u)));return await y.firstValueFrom(d)}_runInterceptorsAndImplementation(r){return this._pipe||(this._pipe=this._interceptors.map(t=>t.interceptor).reduceRight((t,s)=>J(t,s),(t,s)=>s(t))),this._pipe(r,t=>this._http.send(t))}},c.HTTPService=X([z(0,O)],c.HTTPService);function J(e,n){return(r,t)=>n(r,s=>e(s,t))}var q=(e=>(e[e.DownloadProgress=0]="DownloadProgress",e[e.Response=1]="Response",e))(q||{});class F{constructor({body:n,headers:r,status:t,statusText:s}){w(this,"type",1);w(this,"body");w(this,"headers");w(this,"status");w(this,"statusText");this.body=n,this.headers=r,this.status=t,this.statusText=s}}class j{constructor(n,r,t){w(this,"type",0);this.total=n,this.loaded=r,this.partialText=t}}class B{constructor(n,r,t){this.headers=n,this.status=r,this.statusText=t}}class R{constructor({headers:n,status:r,statusText:t,error:s}){w(this,"headers");w(this,"status");w(this,"statusText");w(this,"error");this.headers=n,this.status=r,this.statusText=t,this.error=s}}const Y=200,K=300;var I=(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))(I||{});class Q{send(n){return new y.Observable(r=>{const t=new AbortController;return this._send(n,r,t).then(()=>{},s=>{r.error(new R({error:s}))}),()=>t.abort()})}async _send(n,r,t){var h,m;let s;try{const u=this._parseFetchParamsFromRequest(n);s=await fetch(n.getUrlWithParams(),{signal:t.signal,...u})}catch(u){r.error(new R({error:u,status:(h=u.status)!=null?h:0,statusText:(m=u.statusText)!=null?m:"Unknown Error",headers:u.headers}));return}const o=new _(s.headers),i=s.status,a=s.statusText;let d=null;s.body&&(d=await this._readBody(n,s,r)),i>=I.Ok&&i<I.MultipleChoices?r.next(new F({body:d,headers:o,status:i,statusText:a})):r.error(new R({error:d,status:i,statusText:a,headers:o})),r.complete()}async _readBody(n,r,t){var b,g;const s=[],o=r.body.getReader(),i=r.headers.get("content-length");let a=0;const d=(b=n.requestParams)==null?void 0:b.reportProgress,l=n.responseType;let h,m;for(;;){const{done:v,value:f}=await o.read();if(v)break;s.push(f),a+=f.length,d&&l==="text"&&(h=(h!=null?h:"")+(m!=null?m:m=new TextDecoder).decode(f,{stream:!0}),t.next(new j(i?Number.parseInt(i,10):void 0,a,h)))}const u=Z(s,a);try{const v=(g=r.headers.get("content-type"))!=null?g:"";return H(n,u,v)}catch(v){return t.error(new R({error:v,status:r.status,statusText:r.statusText,headers:new _(r.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 r=new Uint8Array(n);let t=0;for(const s of e)r.set(s,t),t+=s.length;return r}const P=/^\)\]\}',?\n/;function H(e,n,r){switch(e.responseType){case"json":const t=new TextDecoder().decode(n).replace(P,"");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 S{send(n){return new y.Observable(r=>{const t=new XMLHttpRequest;t.open(n.method,n.getUrlWithParams()),n.withCredentials&&(t.withCredentials=!0),n.headers.forEach((d,l)=>t.setRequestHeader(d,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 d=t.statusText||"OK",l=new _(t.getAllResponseHeaders());return new B(l,t.status,d)},o=()=>{const{headers:d,statusText:l,status:h}=s(),{responseType:m}=n;let u=null,b=null;h!==I.NoContent&&(u=typeof t.response>"u"?t.responseText:t.response);let g=h>=Y&&h<K;if(m==="json"&&typeof u=="string"){const v=u;try{u=u?JSON.parse(u):null}catch(f){g=!1,u=v,b=f}}g?r.next(new F({body:u,headers:d,status:h,statusText:l})):r.error(new R({error:b,headers:d,status:h,statusText:l}))},i=d=>{const l=new R({error:d,status:t.status||0,statusText:t.statusText||"Unknown Error",headers:s().headers});r.error(l)};t.addEventListener("load",o),t.addEventListener("error",i),t.addEventListener("abort",i),t.addEventListener("timeout",i);const a=n.getBody();return t.send(a),()=>{t.readyState!==t.DONE&&t.abort(),t.removeEventListener("load",o),t.removeEventListener("error",i),t.removeEventListener("abort",i),t.removeEventListener("timeout",i)}})}}const C=k.createIdentifier("univer.socket");class T extends p.Disposable{createSocket(n){try{const r=new WebSocket(n),t=new p.DisposableCollection;return{URL:n,close:(o,i)=>{r.close(o,i),t.dispose()},send:o=>{r.send(o)},open$:new y.Observable(o=>{const i=a=>o.next(a);r.addEventListener("open",i),t.add(p.toDisposable(()=>r.removeEventListener("open",i)))}).pipe(E.share()),close$:new y.Observable(o=>{const i=a=>o.next(a);r.addEventListener("close",i),t.add(p.toDisposable(()=>r.removeEventListener("close",i)))}).pipe(E.share()),error$:new y.Observable(o=>{const i=a=>o.next(a);r.addEventListener("error",i),t.add(p.toDisposable(()=>r.removeEventListener("error",i)))}).pipe(E.share()),message$:new y.Observable(o=>{const i=a=>o.next(a);r.addEventListener("message",i),t.add(p.toDisposable(()=>r.removeEventListener("message",i)))}).pipe(E.share())}}catch(r){return console.error(r),null}}}const ee=3,re=1e3,te=(e,n)=>{var s,o;const r=(s=n==null?void 0:n.maxRetryAttempts)!=null?s:ee,t=(o=n==null?void 0:n.delayInterval)!=null?o:re;return(i,a)=>a(i).pipe(E.retry({delay:t,count:r}))},ne=e=>{const n=[],r=new Set,t=()=>{var s;for(;r.size<((s=e==null?void 0:e.maxParallel)!=null?s:1)&&n.length>0;){const o=n.shift();r.add(o),o()}};return(s,o)=>new y.Observable(i=>{const a=()=>o(s).subscribe({next:l=>i.next(l),error:l=>i.next(l),complete:()=>i.complete()}),d=()=>{r.delete(a),p.remove(n,a),t()};return n.push(a),t(),d})},se=e=>{const{errorStatusCodes:n,onAuthError:r}=e;return(s,o)=>o(s).pipe(y.catchError(i=>(i instanceof R&&n.some(a=>a===i.status)&&r(),y.throwError(()=>i))))},ie=(e=300)=>{let r=()=>{};return t=>new Promise(s=>{r();const o=setTimeout(()=>{s(!0)},e);r=()=>{clearTimeout(o),s(!1)}})},oe=()=>(e,n)=>n.map(r=>({config:r,result:e})),ce=(e,n={})=>{const{isMatch:r,getParamsFromRequest:t,mergeParamsToRequest:s}=e,{fetchCheck:o=ie(300),distributeResult:i=oe()}=n,a=[],d=l=>l.map(h=>h.config);return(l,h)=>r(l)?new y.Observable(m=>{const u=t(l);a.push({next:g=>m.next(g),error:g=>m.error(g),config:u});const b=d(a);o(l).then(g=>{if(g){const v=[];b.forEach(f=>{const A=a.findIndex(L=>L.config===f);if(A>=0){const[L]=a.splice(A,1);v.push(L)}}),h(s(b,l)).subscribe({next:f=>{if(f.type===q.Response){const A=f.body,L=i(A,b);v.forEach(N=>{const $=L.find(U=>U.config===N.config);if($){const U=new F({body:$.result,headers:f.headers,status:f.status,statusText:f.statusText});N.next(U)}else N.error("batch error")})}},complete:()=>m.complete(),error:f=>m.error(f)})}})}):h(l)};c.AuthInterceptorFactory=se,c.FetchHTTPImplementation=Q,c.HTTPEventType=q,c.HTTPHeaders=_,c.HTTPProgress=j,c.HTTPRequest=x,c.HTTPResponse=F,c.HTTPResponseError=R,c.HTTPStatusCode=I,c.IHTTPImplementation=O,c.ISocketService=C,c.MergeInterceptorFactory=ce,c.ResponseHeader=B,c.RetryInterceptorFactory=te,c.ThresholdInterceptorFactory=ne,c.WebSocketService=T,c.XHRHTTPImplementation=S,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@univerjs/network",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "private": false,
5
5
  "author": "DreamNum <developer@univer.ai>",
6
6
  "license": "Apache-2.0",
@@ -47,7 +47,7 @@
47
47
  "peerDependencies": {
48
48
  "@wendellhu/redi": "0.15.5",
49
49
  "rxjs": ">=7.0.0",
50
- "@univerjs/core": "0.2.2"
50
+ "@univerjs/core": "0.2.3"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@wendellhu/redi": "0.15.5",
@@ -55,8 +55,8 @@
55
55
  "typescript": "^5.5.3",
56
56
  "vite": "^5.3.3",
57
57
  "vitest": "^1.6.0",
58
- "@univerjs/core": "0.2.2",
59
- "@univerjs/shared": "0.2.2"
58
+ "@univerjs/core": "0.2.3",
59
+ "@univerjs/shared": "0.2.3"
60
60
  },
61
61
  "univerSpace": {
62
62
  ".": {