@univerjs/network 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cjs/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var A=Object.defineProperty;var U=(e,t,n)=>t in e?A(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var c=(e,t,n)=>(U(e,typeof t!="symbol"?t+"":t,n),n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("@univerjs/core"),y=require("rxjs"),v=require("rxjs/operators"),q=require("@wendellhu/redi"),E="application/json";class f{constructor(t){c(this,"_headers",new Map);typeof t=="string"?t.split(`
2
- `).forEach(n=>{const[r,i]=n.split(":");r&&i&&this._setHeader(r,i)}):t&&Object.keys(t).forEach(([n,r])=>{this._setHeader(n,r)})}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}_setHeader(t,n){const r=t.toLowerCase();this._headers.has(r)?this._headers.get(r).push(n.toString()):this._headers.set(r,[n.toString()])}}const L=q.createIdentifier("univer-pro.network.http-implementation");class O{constructor(t){this.params=t}toString(){return this.params?Object.keys(this.params).map(t=>`${t}=${this.params[t]}`).join("&"):""}}class u{constructor(t,n,r){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,i;const t=(r=this.headers.get("Content-Type"))!=null?r:E,n=(i=this.requestParams)==null?void 0:i.body;return t===E&&n&&typeof n=="object"?JSON.stringify(n):n?`${n}`:null}}class g{constructor({body:t,headers:n,status:r,statusText:i}){c(this,"body");c(this,"headers");c(this,"status");c(this,"statusText");this.body=t,this.headers=n,this.status=r,this.statusText=i}}class _{constructor({headers:t,status:n,statusText:r,error:i}){c(this,"headers");c(this,"status");c(this,"statusText");c(this,"error");this.headers=t,this.status=n,this.statusText=r,this.error=i}}class M{constructor(t,n,r){this.headers=t,this.status=n,this.statusText=r}}var F=Object.defineProperty,k=Object.getOwnPropertyDescriptor,D=(e,t,n,r)=>{for(var i=r>1?void 0:r?k(t,n):t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=(r?s(t,n,i):s(i))||i);return r&&i&&F(t,n,i),i},j=(e,t)=>(n,r)=>t(n,r,e);exports.HTTPService=class extends d.Disposable{constructor(n){super();c(this,"_interceptors",[]);c(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,i)=>{var o,s;return((o=r.priority)!=null?o:0)-((s=i.priority)!=null?s: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)}async _request(n,r,i){var m,b;const o=new f(i==null?void 0:i.headers),s=new O(i==null?void 0:i.params),l=new u(n,r,{headers:o,params:s,withCredentials:(m=i==null?void 0:i.withCredentials)!=null?m:!1,responseType:(b=i==null?void 0:i.responseType)!=null?b:"json",body:i==null?void 0:i.body}),p=y.of(l).pipe(v.concatMap(h=>this._runInterceptorsAndImplementation(h))),a=await y.firstValueFrom(p);if(a instanceof g)return a;throw new Error(`${a.error}`)}_runInterceptorsAndImplementation(n){return this._pipe||(this._pipe=this._interceptors.map(r=>r.interceptor).reduceRight((r,i)=>$(r,i),(r,i)=>i(r))),this._pipe(n,r=>this._http.send(r))}};exports.HTTPService=D([j(0,L)],exports.HTTPService);function $(e,t){return(n,r)=>t(n,i=>e(i,r))}const B=200,G=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 V{send(t){return new y.Observable(n=>{const r=new XMLHttpRequest;r.open(t.method,t.getUrlWithParams()),t.withCredentials&&(r.withCredentials=!0),t.headers.forEach((p,a)=>r.setRequestHeader(p,a.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 i=()=>{const p=r.statusText||"OK",a=new f(r.getAllResponseHeaders());return new M(a,r.status,p)},o=()=>{const{headers:p,statusText:a,status:m}=i(),{responseType:b}=t;let h=null,w=null;m!==x.NoContent&&(h=typeof r.response>"u"?r.responseText:r.response);let R=m>=B&&m<G;if(b==="json"&&typeof h=="string"){const N=h;try{h=h?JSON.parse(h):null}catch(I){R=!1,h=N,w=I}}R?n.next(new g({body:h,headers:p,status:m,statusText:a})):n.next(new _({error:w,headers:p,status:m,statusText:a}))},s=p=>{const a=new _({error:p,status:r.status||0,statusText:r.statusText||"Unknown Error",headers:i().headers});n.next(a)};r.addEventListener("load",o),r.addEventListener("error",s),r.addEventListener("abort",s),r.addEventListener("timeout",s);const l=t.getBody();return r.send(l),()=>{r.readyState!==r.DONE&&r.abort(),r.removeEventListener("load",o),r.removeEventListener("error",s),r.removeEventListener("abort",s),r.removeEventListener("timeout",s)}})}}const W=q.createIdentifier("univer.socket");class J extends d.Disposable{createSocket(t){try{const n=new WebSocket(t),r=new d.DisposableCollection;return{URL:t,close:(o,s)=>{n.close(o,s),r.dispose()},send:o=>{n.send(o)},open$:new y.Observable(o=>{const s=l=>o.next(l);n.addEventListener("open",s),r.add(d.toDisposable(()=>n.removeEventListener("open",s)))}).pipe(v.share()),close$:new y.Observable(o=>{const s=l=>o.next(l);n.addEventListener("close",s),r.add(d.toDisposable(()=>n.removeEventListener("close",s)))}).pipe(v.share()),error$:new y.Observable(o=>{const s=l=>o.next(l);n.addEventListener("error",s),r.add(d.toDisposable(()=>n.removeEventListener("error",s)))}).pipe(v.share()),message$:new y.Observable(o=>{const s=l=>o.next(l);n.addEventListener("message",s),r.add(d.toDisposable(()=>n.removeEventListener("message",s)))}).pipe(v.share())}}catch(n){return console.error(n),null}}}exports.HTTPHeaders=f;exports.HTTPRequest=u;exports.HTTPResponse=g;exports.IHTTPImplementation=L;exports.ISocketService=W;exports.WebSocketService=J;exports.XHRHTTPImplementation=V;
1
+ "use strict";var A=Object.defineProperty;var U=(e,t,n)=>t in e?A(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var h=(e,t,n)=>(U(e,typeof t!="symbol"?t+"":t,n),n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("@univerjs/core"),d=require("rxjs"),b=require("rxjs/operators"),_=require("@wendellhu/redi"),E="application/json";class f{constructor(t){h(this,"_headers",new Map);typeof t=="string"?t.split(`
2
+ `).forEach(n=>{const[r,s]=n.split(":");r&&s&&this._setHeader(r,s)}):t&&Object.keys(t).forEach(([n,r])=>{this._setHeader(n,r)})}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}_setHeader(t,n){const r=t.toLowerCase();this._headers.has(r)?this._headers.get(r).push(n.toString()):this._headers.set(r,[n.toString()])}}const L=_.createIdentifier("network.http-implementation");class O{constructor(t){this.params=t}toString(){return this.params?Object.keys(this.params).map(t=>`${t}=${this.params[t]}`).join("&"):""}}let M=0;class q{constructor(t,n,r){h(this,"uid",M++);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:E,n=(s=this.requestParams)==null?void 0:s.body;return t===E&&n&&typeof n=="object"?JSON.stringify(n):n?`${n}`:null}}class w{constructor({body:t,headers:n,status:r,statusText:s}){h(this,"body");h(this,"headers");h(this,"status");h(this,"statusText");this.body=t,this.headers=n,this.status=r,this.statusText=s}}class u{constructor({headers:t,status:n,statusText:r,error:s}){h(this,"headers");h(this,"status");h(this,"statusText");h(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,D=Object.getOwnPropertyDescriptor,j=(e,t,n,r)=>{for(var s=r>1?void 0:r?D(t,n):t,o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=(r?i(t,n,s):i(s))||s);return r&&s&&k(t,n,s),s},$=(e,t)=>(n,r)=>t(n,r,e);exports.HTTPService=class extends y.Disposable{constructor(n){super();h(this,"_interceptors",[]);h(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 o,i;return((o=r.priority)!=null?o:0)-((i=s.priority)!=null?i:0)}),this._pipe=null,y.toDisposable(()=>y.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)}async _request(n,r,s){var p,v;const o=new f(s==null?void 0:s.headers),i=new O(s==null?void 0:s.params),c=new q(n,r,{headers:o,params:i,withCredentials:(p=s==null?void 0:s.withCredentials)!=null?p:!1,responseType:(v=s==null?void 0:s.responseType)!=null?v:"json",body:n==="GET"||s==null?void 0:s.body}),a=d.of(c).pipe(b.concatMap(m=>this._runInterceptorsAndImplementation(m))),l=await d.firstValueFrom(a);if(l instanceof w)return l;throw new Error(`${l.error}`)}_runInterceptorsAndImplementation(n){return this._pipe||(this._pipe=this._interceptors.map(r=>r.interceptor).reduceRight((r,s)=>B(r,s),(r,s)=>s(r))),this._pipe(n,r=>this._http.send(r))}};exports.HTTPService=j([$(0,L)],exports.HTTPService);function B(e,t){return(n,r)=>t(n,s=>e(s,r))}const G=200,V=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 W{send(t){return new d.Observable(n=>{const r=new XMLHttpRequest;r.open(t.method,t.getUrlWithParams()),t.withCredentials&&(r.withCredentials=!0),t.headers.forEach((a,l)=>r.setRequestHeader(a,l.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 a=r.statusText||"OK",l=new f(r.getAllResponseHeaders());return new F(l,r.status,a)},o=()=>{const{headers:a,statusText:l,status:p}=s(),{responseType:v}=t;let m=null,g=null;p!==x.NoContent&&(m=typeof r.response>"u"?r.responseText:r.response);let R=p>=G&&p<V;if(v==="json"&&typeof m=="string"){const I=m;try{m=m?JSON.parse(m):null}catch(N){R=!1,m=I,g=N}}R?n.next(new w({body:m,headers:a,status:p,statusText:l})):n.next(new u({error:g,headers:a,status:p,statusText:l}))},i=a=>{const l=new u({error:a,status:r.status||0,statusText:r.statusText||"Unknown Error",headers:s().headers});n.next(l)};r.addEventListener("load",o),r.addEventListener("error",i),r.addEventListener("abort",i),r.addEventListener("timeout",i);const c=t.getBody();return r.send(c),()=>{r.readyState!==r.DONE&&r.abort(),r.removeEventListener("load",o),r.removeEventListener("error",i),r.removeEventListener("abort",i),r.removeEventListener("timeout",i)}})}}const X=_.createIdentifier("univer.socket");class z extends y.Disposable{createSocket(t){try{const n=new WebSocket(t),r=new y.DisposableCollection;return{URL:t,close:(o,i)=>{n.close(o,i),r.dispose()},send:o=>{n.send(o)},open$:new d.Observable(o=>{const i=c=>o.next(c);n.addEventListener("open",i),r.add(y.toDisposable(()=>n.removeEventListener("open",i)))}).pipe(b.share()),close$:new d.Observable(o=>{const i=c=>o.next(c);n.addEventListener("close",i),r.add(y.toDisposable(()=>n.removeEventListener("close",i)))}).pipe(b.share()),error$:new d.Observable(o=>{const i=c=>o.next(c);n.addEventListener("error",i),r.add(y.toDisposable(()=>n.removeEventListener("error",i)))}).pipe(b.share()),message$:new d.Observable(o=>{const i=c=>o.next(c);n.addEventListener("message",i),r.add(y.toDisposable(()=>n.removeEventListener("message",i)))}).pipe(b.share())}}catch(n){return console.error(n),null}}}const J=2,Y=1e3,K=(e,t)=>t(e).pipe(b.retryWhen(n=>n.pipe(b.concatMap((r,s)=>s>J?d.throwError(r):d.of(r)),d.delay(Y)))),Q=(e,t)=>{const n=[],r=new Set,s=()=>{var o;for(;r.size<((o=t==null?void 0:t.maxParallel)!=null?o:1)&&n.length>0;){const i=n.shift();r.add(i),i()}};return(o,i)=>new d.Observable(c=>{const a=()=>i(o).subscribe({next:p=>c.next(p),error:p=>c.next(p),complete:()=>c.complete()}),l=()=>{r.delete(a),y.remove(n,a),s()};return n.push(a),s(),l})};exports.HTTPHeaders=f;exports.HTTPRequest=q;exports.HTTPResponse=w;exports.IHTTPImplementation=L;exports.ISocketService=X;exports.ThresholdInterceptorFactory=Q;exports.WebSocketService=z;exports.XHRHTTPImplementation=W;exports.retryInterceptor=K;
package/lib/es/index.js CHANGED
@@ -1,14 +1,14 @@
1
- var U = Object.defineProperty;
2
- var I = (e, t, n) => t in e ? U(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
- var a = (e, t, n) => (I(e, typeof t != "symbol" ? t + "" : t, n), n);
4
- import { Disposable as _, toDisposable as d, remove as F, DisposableCollection as M } from "@univerjs/core";
5
- import { of as O, firstValueFrom as k, Observable as y } from "rxjs";
6
- import { concatMap as j, share as f } from "rxjs/operators";
7
- import { createIdentifier as L } from "@wendellhu/redi";
8
- const R = "application/json";
9
- class q {
1
+ var F = Object.defineProperty;
2
+ var O = (e, t, n) => t in e ? F(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
+ var h = (e, t, n) => (O(e, typeof t != "symbol" ? t + "" : t, n), n);
4
+ import { Disposable as b, toDisposable as y, remove as L, DisposableCollection as k } from "@univerjs/core";
5
+ import { of as u, firstValueFrom as D, Observable as m, throwError as j, delay as $ } from "rxjs";
6
+ import { concatMap as x, share as f, retryWhen as B } from "rxjs/operators";
7
+ import { createIdentifier as q } from "@wendellhu/redi";
8
+ const v = "application/json";
9
+ class N {
10
10
  constructor(t) {
11
- a(this, "_headers", /* @__PURE__ */ new Map());
11
+ h(this, "_headers", /* @__PURE__ */ new Map());
12
12
  typeof t == "string" ? t.split(`
13
13
  `).forEach((n) => {
14
14
  const [r, i] = n.split(":");
@@ -32,8 +32,8 @@ class q {
32
32
  this._headers.has(r) ? this._headers.get(r).push(n.toString()) : this._headers.set(r, [n.toString()]);
33
33
  }
34
34
  }
35
- const $ = L("univer-pro.network.http-implementation");
36
- class D {
35
+ const G = q("network.http-implementation");
36
+ class V {
37
37
  constructor(t) {
38
38
  this.params = t;
39
39
  }
@@ -41,8 +41,10 @@ class D {
41
41
  return this.params ? Object.keys(this.params).map((t) => `${t}=${this.params[t]}`).join("&") : "";
42
42
  }
43
43
  }
44
- class B {
44
+ let W = 0;
45
+ class z {
45
46
  constructor(t, n, r) {
47
+ h(this, "uid", W++);
46
48
  this.method = t, this.url = n, this.requestParams = r;
47
49
  }
48
50
  get headers() {
@@ -61,62 +63,69 @@ class B {
61
63
  }
62
64
  getBody() {
63
65
  var r, i;
64
- const t = (r = this.headers.get("Content-Type")) != null ? r : R, n = (i = this.requestParams) == null ? void 0 : i.body;
65
- return t === R && n && typeof n == "object" ? JSON.stringify(n) : n ? `${n}` : null;
66
+ const t = (r = this.headers.get("Content-Type")) != null ? r : v, n = (i = this.requestParams) == null ? void 0 : i.body;
67
+ return t === v && n && typeof n == "object" ? JSON.stringify(n) : n ? `${n}` : null;
66
68
  }
67
69
  }
68
- class x {
70
+ class A {
69
71
  constructor({
70
72
  body: t,
71
73
  headers: n,
72
74
  status: r,
73
75
  statusText: i
74
76
  }) {
75
- a(this, "body");
76
- a(this, "headers");
77
- a(this, "status");
78
- a(this, "statusText");
77
+ h(this, "body");
78
+ h(this, "headers");
79
+ h(this, "status");
80
+ h(this, "statusText");
79
81
  this.body = t, this.headers = n, this.status = r, this.statusText = i;
80
82
  }
81
83
  }
82
- class E {
84
+ class R {
83
85
  constructor({
84
86
  headers: t,
85
87
  status: n,
86
88
  statusText: r,
87
89
  error: i
88
90
  }) {
89
- a(this, "headers");
90
- a(this, "status");
91
- a(this, "statusText");
92
- a(this, "error");
91
+ h(this, "headers");
92
+ h(this, "status");
93
+ h(this, "statusText");
94
+ h(this, "error");
93
95
  this.headers = t, this.status = n, this.statusText = r, this.error = i;
94
96
  }
95
97
  }
96
- class G {
98
+ class J {
97
99
  constructor(t, n, r) {
98
100
  this.headers = t, this.status = n, this.statusText = r;
99
101
  }
100
102
  }
101
- var V = Object.defineProperty, W = Object.getOwnPropertyDescriptor, J = (e, t, n, r) => {
102
- for (var i = r > 1 ? void 0 : r ? W(t, n) : t, o = e.length - 1, s; o >= 0; o--)
103
+ var X = Object.defineProperty, Y = Object.getOwnPropertyDescriptor, K = (e, t, n, r) => {
104
+ for (var i = r > 1 ? void 0 : r ? Y(t, n) : t, o = e.length - 1, s; o >= 0; o--)
103
105
  (s = e[o]) && (i = (r ? s(t, n, i) : s(i)) || i);
104
- return r && i && V(t, n, i), i;
105
- }, z = (e, t) => (n, r) => t(n, r, e);
106
- let b = class extends _ {
106
+ return r && i && X(t, n, i), i;
107
+ }, Q = (e, t) => (n, r) => t(n, r, e);
108
+ let _ = class extends b {
107
109
  constructor(t) {
108
110
  super();
109
- a(this, "_interceptors", []);
110
- a(this, "_pipe");
111
+ h(this, "_interceptors", []);
112
+ // eslint-disable-next-line ts/no-explicit-any
113
+ h(this, "_pipe");
111
114
  this._http = t;
112
115
  }
116
+ /**
117
+ * Register an HTTP interceptor.
118
+ *
119
+ * @param interceptor the http interceptor
120
+ * @returns a disposable handler to remove the interceptor
121
+ */
113
122
  registerHTTPInterceptor(t) {
114
123
  if (this._interceptors.indexOf(t) !== -1)
115
124
  throw new Error("[HTTPService]: The interceptor has already been registered!");
116
125
  return this._interceptors.push(t), this._interceptors = this._interceptors.sort((n, r) => {
117
126
  var i, o;
118
127
  return ((i = n.priority) != null ? i : 0) - ((o = r.priority) != null ? o : 0);
119
- }), this._pipe = null, d(() => F(this._interceptors, t));
128
+ }), this._pipe = null, y(() => L(this._interceptors, t));
120
129
  }
121
130
  get(t, n) {
122
131
  return this._request("GET", t, n);
@@ -132,24 +141,25 @@ let b = class extends _ {
132
141
  }
133
142
  /** The HTTP request implementations */
134
143
  async _request(t, n, r) {
135
- var p, h;
136
- const i = new q(r == null ? void 0 : r.headers), o = new D(r == null ? void 0 : r.params), s = new B(t, n, {
144
+ var l, p;
145
+ const i = new N(r == null ? void 0 : r.headers), o = new V(r == null ? void 0 : r.params), s = new z(t, n, {
137
146
  headers: i,
138
147
  params: o,
139
- withCredentials: (p = r == null ? void 0 : r.withCredentials) != null ? p : !1,
148
+ withCredentials: (l = r == null ? void 0 : r.withCredentials) != null ? l : !1,
140
149
  // default value for withCredentials is false by MDN
141
- responseType: (h = r == null ? void 0 : r.responseType) != null ? h : "json",
142
- body: r == null ? void 0 : r.body
143
- }), l = O(s).pipe(
144
- j((v) => this._runInterceptorsAndImplementation(v))
145
- ), c = await k(l);
146
- if (c instanceof x)
150
+ responseType: (p = r == null ? void 0 : r.responseType) != null ? p : "json",
151
+ body: t === "GET" || r == null ? void 0 : r.body
152
+ }), a = u(s).pipe(
153
+ x((w) => this._runInterceptorsAndImplementation(w))
154
+ ), c = await D(a);
155
+ if (c instanceof A)
147
156
  return c;
148
157
  throw new Error(`${c.error}`);
149
158
  }
159
+ // eslint-disable-next-line ts/no-explicit-any
150
160
  _runInterceptorsAndImplementation(t) {
151
161
  return this._pipe || (this._pipe = this._interceptors.map((n) => n.interceptor).reduceRight(
152
- (n, r) => X(n, r),
162
+ (n, r) => Z(n, r),
153
163
  (n, r) => r(n)
154
164
  )), this._pipe(
155
165
  t,
@@ -158,72 +168,72 @@ let b = class extends _ {
158
168
  );
159
169
  }
160
170
  };
161
- b = J([
162
- z(0, $)
163
- ], b);
164
- function X(e, t) {
171
+ _ = K([
172
+ Q(0, G)
173
+ ], _);
174
+ function Z(e, t) {
165
175
  return (n, r) => t(n, (i) => e(i, r));
166
176
  }
167
- const K = 200, Q = 300;
168
- var N = /* @__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))(N || {});
169
- class H {
177
+ const P = 200, S = 300;
178
+ var I = /* @__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))(I || {});
179
+ class ie {
170
180
  send(t) {
171
- return new y((n) => {
181
+ return new m((n) => {
172
182
  const r = new XMLHttpRequest();
173
- r.open(t.method, t.getUrlWithParams()), t.withCredentials && (r.withCredentials = !0), t.headers.forEach((c, p) => r.setRequestHeader(c, p.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");
183
+ r.open(t.method, t.getUrlWithParams()), t.withCredentials && (r.withCredentials = !0), t.headers.forEach((c, l) => r.setRequestHeader(c, l.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");
174
184
  const i = () => {
175
- const c = r.statusText || "OK", p = new q(r.getAllResponseHeaders());
176
- return new G(p, r.status, c);
185
+ const c = r.statusText || "OK", l = new N(r.getAllResponseHeaders());
186
+ return new J(l, r.status, c);
177
187
  }, o = () => {
178
- const { headers: c, statusText: p, status: h } = i(), { responseType: v } = t;
179
- let m = null, w = null;
180
- h !== N.NoContent && (m = typeof r.response > "u" ? r.responseText : r.response);
181
- let g = h >= K && h < Q;
182
- if (v === "json" && typeof m == "string") {
183
- const u = m;
188
+ const { headers: c, statusText: l, status: p } = i(), { responseType: w } = t;
189
+ let d = null, g = null;
190
+ p !== I.NoContent && (d = typeof r.response > "u" ? r.responseText : r.response);
191
+ let E = p >= P && p < S;
192
+ if (w === "json" && typeof d == "string") {
193
+ const U = d;
184
194
  try {
185
- m = m ? JSON.parse(m) : null;
186
- } catch (A) {
187
- g = !1, m = u, w = A;
195
+ d = d ? JSON.parse(d) : null;
196
+ } catch (M) {
197
+ E = !1, d = U, g = M;
188
198
  }
189
199
  }
190
- g ? n.next(
191
- new x({
192
- body: m,
200
+ E ? n.next(
201
+ new A({
202
+ body: d,
193
203
  headers: c,
194
- status: h,
195
- statusText: p
204
+ status: p,
205
+ statusText: l
196
206
  })
197
207
  ) : n.next(
198
- new E({
199
- error: w,
208
+ new R({
209
+ error: g,
200
210
  headers: c,
201
- status: h,
202
- statusText: p
211
+ status: p,
212
+ statusText: l
203
213
  })
204
214
  );
205
215
  }, s = (c) => {
206
- const p = new E({
216
+ const l = new R({
207
217
  error: c,
208
218
  status: r.status || 0,
209
219
  statusText: r.statusText || "Unknown Error",
210
220
  headers: i().headers
211
221
  });
212
- n.next(p);
222
+ n.next(l);
213
223
  };
214
224
  r.addEventListener("load", o), r.addEventListener("error", s), r.addEventListener("abort", s), r.addEventListener("timeout", s);
215
- const l = t.getBody();
216
- return r.send(l), () => {
225
+ const a = t.getBody();
226
+ return r.send(a), () => {
217
227
  r.readyState !== r.DONE && r.abort(), r.removeEventListener("load", o), r.removeEventListener("error", s), r.removeEventListener("abort", s), r.removeEventListener("timeout", s);
218
228
  };
219
229
  });
220
230
  }
221
231
  }
222
- const T = L("univer.socket");
223
- class ee extends _ {
232
+ const se = q("univer.socket");
233
+ class oe extends b {
224
234
  createSocket(t) {
225
235
  try {
226
- const n = new WebSocket(t), r = new M();
236
+ const n = new WebSocket(t), r = new k();
227
237
  return {
228
238
  URL: t,
229
239
  close: (o, s) => {
@@ -232,21 +242,21 @@ class ee extends _ {
232
242
  send: (o) => {
233
243
  n.send(o);
234
244
  },
235
- open$: new y((o) => {
236
- const s = (l) => o.next(l);
237
- n.addEventListener("open", s), r.add(d(() => n.removeEventListener("open", s)));
245
+ open$: new m((o) => {
246
+ const s = (a) => o.next(a);
247
+ n.addEventListener("open", s), r.add(y(() => n.removeEventListener("open", s)));
238
248
  }).pipe(f()),
239
- close$: new y((o) => {
240
- const s = (l) => o.next(l);
241
- n.addEventListener("close", s), r.add(d(() => n.removeEventListener("close", s)));
249
+ close$: new m((o) => {
250
+ const s = (a) => o.next(a);
251
+ n.addEventListener("close", s), r.add(y(() => n.removeEventListener("close", s)));
242
252
  }).pipe(f()),
243
- error$: new y((o) => {
244
- const s = (l) => o.next(l);
245
- n.addEventListener("error", s), r.add(d(() => n.removeEventListener("error", s)));
253
+ error$: new m((o) => {
254
+ const s = (a) => o.next(a);
255
+ n.addEventListener("error", s), r.add(y(() => n.removeEventListener("error", s)));
246
256
  }).pipe(f()),
247
- message$: new y((o) => {
248
- const s = (l) => o.next(l);
249
- n.addEventListener("message", s), r.add(d(() => n.removeEventListener("message", s)));
257
+ message$: new m((o) => {
258
+ const s = (a) => o.next(a);
259
+ n.addEventListener("message", s), r.add(y(() => n.removeEventListener("message", s)));
250
260
  }).pipe(f())
251
261
  };
252
262
  } catch (n) {
@@ -254,13 +264,39 @@ class ee extends _ {
254
264
  }
255
265
  }
256
266
  }
267
+ const C = 2, H = 1e3, ce = (e, t) => t(e).pipe(
268
+ B((n) => n.pipe(
269
+ x((r, i) => i > C ? j(r) : u(r)),
270
+ $(H)
271
+ ))
272
+ ), ae = (e, t) => {
273
+ const n = [], r = /* @__PURE__ */ new Set(), i = () => {
274
+ var o;
275
+ for (; r.size < ((o = t == null ? void 0 : t.maxParallel) != null ? o : 1) && n.length > 0; ) {
276
+ const s = n.shift();
277
+ r.add(s), s();
278
+ }
279
+ };
280
+ return (o, s) => new m((a) => {
281
+ const c = () => s(o).subscribe({
282
+ next: (p) => a.next(p),
283
+ error: (p) => a.next(p),
284
+ complete: () => a.complete()
285
+ }), l = () => {
286
+ r.delete(c), L(n, c), i();
287
+ };
288
+ return n.push(c), i(), l;
289
+ });
290
+ };
257
291
  export {
258
- q as HTTPHeaders,
259
- B as HTTPRequest,
260
- x as HTTPResponse,
261
- b as HTTPService,
262
- $ as IHTTPImplementation,
263
- T as ISocketService,
264
- ee as WebSocketService,
265
- H as XHRHTTPImplementation
292
+ N as HTTPHeaders,
293
+ z as HTTPRequest,
294
+ A as HTTPResponse,
295
+ _ as HTTPService,
296
+ G as IHTTPImplementation,
297
+ se as ISocketService,
298
+ ae as ThresholdInterceptorFactory,
299
+ oe as WebSocketService,
300
+ ie as XHRHTTPImplementation,
301
+ ce as retryInterceptor
266
302
  };
@@ -20,4 +20,7 @@ export { XHRHTTPImplementation } from './services/http/implementations/xhr';
20
20
  export { HTTPRequest } from './services/http/request';
21
21
  export { HTTPResponse } from './services/http/response';
22
22
  export { type ISocket, ISocketService, type SocketBodyType, WebSocketService, } from './services/web-socket/web-socket.service';
23
- export { type IRequestParams } from './services/http/http.service';
23
+ export type { IRequestParams, IPostRequestParams } from './services/http/http.service';
24
+ export type { HTTPHandlerFn, HTTPInterceptorFn, HTTPInterceptorFnFactory } from './services/http/interceptor';
25
+ export { retryInterceptor } from './services/http/interceptors/retry-interceptor';
26
+ export { ThresholdInterceptorFactory } from './services/http/interceptors/threshold-interceptor';
@@ -0,0 +1,51 @@
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
+ import { Observable } from 'rxjs';
17
+ import { Disposable } from '@univerjs/core';
18
+ import { Injector } from '@wendellhu/redi';
19
+ import { IHTTPImplementation } from '../implementations/implementation';
20
+ import type { HTTPRequest } from '../request';
21
+ import type { HTTPEvent, HTTPResponse, HTTPResponseError } from '../response';
22
+ /**
23
+ * A mocked HTTP implementation service for testing purposes. Besides methods in the interface, it
24
+ * provides several public methods to control the process of http request.
25
+ */
26
+ export declare class MockHTTPImplementation extends Disposable implements IHTTPImplementation {
27
+ private readonly _newRequest$;
28
+ readonly newRequest$: Observable<HTTPRequest>;
29
+ private readonly _handlers;
30
+ dispose(): void;
31
+ send(request: HTTPRequest): Observable<HTTPEvent<any>>;
32
+ /**
33
+ * Get a handler to interact with the request.
34
+ * @param uid the request's unique identifier
35
+ * @returns the handler for the request
36
+ */
37
+ getHandler(uid: number): IMockHTTPHandler;
38
+ }
39
+ export interface IMockHTTPHandler {
40
+ /**
41
+ * Emit a response event to the observer.
42
+ */
43
+ emitResponse<T>(response: HTTPResponse<T>): void;
44
+ /**
45
+ * Emit an error event to the observer.
46
+ */
47
+ emitError(error: HTTPResponseError): void;
48
+ }
49
+ export declare function createHTTPTestBed(): {
50
+ injector: Injector;
51
+ };
@@ -15,41 +15,55 @@
15
15
  */
16
16
  import { Disposable } from '@univerjs/core';
17
17
  import type { IDisposable } from '@wendellhu/redi';
18
- import type { Observable } from 'rxjs';
19
18
  import type { HTTPResponseType } from './http';
20
19
  import { IHTTPImplementation } from './implementations/implementation';
21
- import { HTTPRequest } from './request';
22
- import type { HTTPEvent } from './response';
23
20
  import { HTTPResponse } from './response';
21
+ import type { HTTPInterceptorFn } from './interceptor';
24
22
  export interface IRequestParams {
25
- body?: any;
26
23
  /** Query params. These params would be append to the url before the request is sent. */
27
24
  params?: {
28
25
  [param: string]: string | number | boolean;
29
26
  };
27
+ /** Query headers. */
30
28
  headers?: {
31
29
  [key: string]: string | number | boolean;
32
30
  };
31
+ /** Expected types of the response data. */
33
32
  responseType?: HTTPResponseType;
34
33
  withCredentials?: boolean;
35
34
  }
36
35
  export interface IPostRequestParams extends IRequestParams {
37
- body?: any;
36
+ body?: unknown;
38
37
  }
39
- type HTTPHandlerFn = (request: HTTPRequest) => Observable<HTTPEvent<unknown>>;
40
- type HTTPInterceptorFn = (request: HTTPRequest, next: HTTPHandlerFn) => Observable<HTTPEvent<unknown>>;
41
38
  /**
42
39
  * Register an HTTP interceptor. Interceptor could modify requests, responses, headers or errors.
43
40
  */
44
41
  export interface IHTTPInterceptor {
42
+ /** The priority of the interceptor. The higher the value, the earlier the interceptor is called. */
45
43
  priority?: number;
44
+ /** The interceptor function. */
46
45
  interceptor: HTTPInterceptorFn;
47
46
  }
47
+ /**
48
+ * This service provides http request methods and allows to register http interceptors.
49
+ *
50
+ * You can use interceptors to:
51
+ *
52
+ * 1. modify requests (headers included) before they are sent, or modify responses before they are returned to the caller.
53
+ * 2. thresholding, logging, caching, etc.
54
+ * 3. authentication, authorization, etc.
55
+ */
48
56
  export declare class HTTPService extends Disposable {
49
57
  private readonly _http;
50
58
  private _interceptors;
51
59
  private _pipe;
52
60
  constructor(_http: IHTTPImplementation);
61
+ /**
62
+ * Register an HTTP interceptor.
63
+ *
64
+ * @param interceptor the http interceptor
65
+ * @returns a disposable handler to remove the interceptor
66
+ */
53
67
  registerHTTPInterceptor(interceptor: IHTTPInterceptor): IDisposable;
54
68
  get<T>(url: string, options?: IRequestParams): Promise<HTTPResponse<T>>;
55
69
  post<T>(url: string, options?: IPostRequestParams): Promise<HTTPResponse<T>>;
@@ -59,4 +73,3 @@ export declare class HTTPService extends Disposable {
59
73
  private _request;
60
74
  private _runInterceptorsAndImplementation;
61
75
  }
62
- export {};
@@ -20,6 +20,10 @@ import type { HTTPEvent } from '../response';
20
20
  * HTTP service could be implemented differently on platforms.
21
21
  */
22
22
  export interface IHTTPImplementation {
23
+ /**
24
+ * Send a request. The result would be returned in an observable for possible stream response.
25
+ * @param request the request to be sent
26
+ */
23
27
  send(request: HTTPRequest): Observable<HTTPEvent<any>>;
24
28
  }
25
29
  export declare const IHTTPImplementation: import("@wendellhu/redi").IdentifierDecorator<IHTTPImplementation>;
@@ -18,7 +18,7 @@ import type { HTTPRequest } from '../request';
18
18
  import type { HTTPEvent } from '../response';
19
19
  import type { IHTTPImplementation } from './implementation';
20
20
  /**
21
- * A HTTP implementation using XHR. XHR could only be async.
21
+ * A HTTP implementation using XHR. HTTP service provided by this service could only be async (we do not support sync XHR now).
22
22
  */
23
23
  export declare class XHRHTTPImplementation implements IHTTPImplementation {
24
24
  send(request: HTTPRequest): Observable<HTTPEvent<any>>;
@@ -0,0 +1,42 @@
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
+ import type { Observable } from 'rxjs';
17
+ import type { IAccessor } from '@wendellhu/redi';
18
+ import type { HTTPRequest } from './request';
19
+ import type { HTTPEvent } from './response';
20
+ export type HTTPHandlerFn = (request: HTTPRequest) => Observable<HTTPEvent<unknown>>;
21
+ /**
22
+ * HTTP interceptor function. When the interceptor is called, it would receive a request object and a next function.
23
+ *
24
+ * @param request The `request` could be been modified by interceptors whose priority is higher than the current interceptor.
25
+ *
26
+ * @param next When the interceptor decides to pass the request to the next interceptor, it should call the `next` function with
27
+ * the request.
28
+ * The `next` function would return an `Observable`. The current interceptor should subscribe to it and emit the messages
29
+ * from next interceptor to the previous interceptor.
30
+ *
31
+ * @returns An `Observable` that emits the response of the request. It would be subscribed by the previous interceptor.
32
+ *
33
+ * An interceptor the logs the request and response would look like this:
34
+ * @example
35
+ * function logInterceptor(request: HTTPRequest, next: HTTPHandlerFn): Observable<HTTPEvent<unknown>> {
36
+ * console.log('Request:', request);
37
+ * return next(request).pipe(cat(response => console.log('Response:', response)));
38
+ * }
39
+ */
40
+ export type HTTPInterceptorFn = (request: HTTPRequest, next: HTTPHandlerFn) => Observable<HTTPEvent<unknown>>;
41
+ export type RequestPipe<T> = (req: HTTPRequest, finalHandlerFn: HTTPHandlerFn) => Observable<HTTPEvent<T>>;
42
+ export type HTTPInterceptorFnFactory = (accessor: IAccessor, params?: any) => 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,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,17 @@
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
+ import type { HTTPInterceptorFn } from '../interceptor';
17
+ export declare const retryInterceptor: HTTPInterceptorFn;
@@ -0,0 +1,20 @@
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
+ import type { HTTPInterceptorFnFactory } from '../interceptor';
17
+ export interface IThresholdInterceptorFactoryParams {
18
+ maxParallel?: number;
19
+ }
20
+ export declare const ThresholdInterceptorFactory: HTTPInterceptorFnFactory;
@@ -24,6 +24,7 @@ export interface IHTTPRequestParams {
24
24
  responseType: HTTPResponseType;
25
25
  withCredentials: boolean;
26
26
  }
27
+ export declare function __TEST_ONLY_RESET_REQUEST_UID_DO_NOT_USE_IN_PRODUCTION(): void;
27
28
  export declare class HTTPRequest {
28
29
  readonly method: HTTPRequestMethod;
29
30
  readonly url: string;
@@ -31,6 +32,7 @@ export declare class HTTPRequest {
31
32
  get headers(): HTTPHeaders;
32
33
  get withCredentials(): boolean;
33
34
  get responseType(): string;
35
+ readonly uid: number;
34
36
  constructor(method: HTTPRequestMethod, url: string, requestParams?: IHTTPRequestParams | undefined);
35
37
  getUrlWithParams(): string;
36
38
  getBody(): string | null;
package/lib/umd/index.js CHANGED
@@ -1,2 +1,2 @@
1
- (function(o,c){typeof exports=="object"&&typeof module<"u"?c(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"],c):(o=typeof globalThis<"u"?globalThis:o||self,c(o.UniverNetwork={},o.UniverCore,o.rxjs,o.rxjs.operators,o["@wendellhu/redi"]))})(this,function(o,c,l,v,g){"use strict";var J=Object.defineProperty;var X=(o,c,l)=>c in o?J(o,c,{enumerable:!0,configurable:!0,writable:!0,value:l}):o[c]=l;var p=(o,c,l)=>(X(o,typeof c!="symbol"?c+"":c,l),l);const u="application/json";class w{constructor(t){p(this,"_headers",new Map);typeof t=="string"?t.split(`
2
- `).forEach(n=>{const[r,i]=n.split(":");r&&i&&this._setHeader(r,i)}):t&&Object.keys(t).forEach(([n,r])=>{this._setHeader(n,r)})}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}_setHeader(t,n){const r=t.toLowerCase();this._headers.has(r)?this._headers.get(r).push(n.toString()):this._headers.set(r,[n.toString()])}}const E=g.createIdentifier("univer-pro.network.http-implementation");class U{constructor(t){this.params=t}toString(){return this.params?Object.keys(this.params).map(t=>`${t}=${this.params[t]}`).join("&"):""}}class _{constructor(t,n,r){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,i;const t=(r=this.headers.get("Content-Type"))!=null?r:u,n=(i=this.requestParams)==null?void 0:i.body;return t===u&&n&&typeof n=="object"?JSON.stringify(n):n?`${n}`:null}}class R{constructor({body:t,headers:n,status:r,statusText:i}){p(this,"body");p(this,"headers");p(this,"status");p(this,"statusText");this.body=t,this.headers=n,this.status=r,this.statusText=i}}class q{constructor({headers:t,status:n,statusText:r,error:i}){p(this,"headers");p(this,"status");p(this,"statusText");p(this,"error");this.headers=t,this.status=n,this.statusText=r,this.error=i}}class x{constructor(t,n,r){this.headers=t,this.status=n,this.statusText=r}}var A=Object.defineProperty,O=Object.getOwnPropertyDescriptor,M=(e,t,n,r)=>{for(var i=r>1?void 0:r?O(t,n):t,a=e.length-1,s;a>=0;a--)(s=e[a])&&(i=(r?s(t,n,i):s(i))||i);return r&&i&&A(t,n,i),i},k=(e,t)=>(n,r)=>t(n,r,e);o.HTTPService=class extends c.Disposable{constructor(n){super();p(this,"_interceptors",[]);p(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,i)=>{var a,s;return((a=r.priority)!=null?a:0)-((s=i.priority)!=null?s:0)}),this._pipe=null,c.toDisposable(()=>c.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)}async _request(n,r,i){var f,b;const a=new w(i==null?void 0:i.headers),s=new U(i==null?void 0:i.params),d=new _(n,r,{headers:a,params:s,withCredentials:(f=i==null?void 0:i.withCredentials)!=null?f:!1,responseType:(b=i==null?void 0:i.responseType)!=null?b:"json",body:i==null?void 0:i.body}),m=l.of(d).pipe(v.concatMap(y=>this._runInterceptorsAndImplementation(y))),h=await l.firstValueFrom(m);if(h instanceof R)return h;throw new Error(`${h.error}`)}_runInterceptorsAndImplementation(n){return this._pipe||(this._pipe=this._interceptors.map(r=>r.interceptor).reduceRight((r,i)=>F(r,i),(r,i)=>i(r))),this._pipe(n,r=>this._http.send(r))}},o.HTTPService=M([k(0,E)],o.HTTPService);function F(e,t){return(n,r)=>t(n,i=>e(i,r))}const j=200,D=300;var L=(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||{});class ${send(t){return new l.Observable(n=>{const r=new XMLHttpRequest;r.open(t.method,t.getUrlWithParams()),t.withCredentials&&(r.withCredentials=!0),t.headers.forEach((m,h)=>r.setRequestHeader(m,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 i=()=>{const m=r.statusText||"OK",h=new w(r.getAllResponseHeaders());return new x(h,r.status,m)},a=()=>{const{headers:m,statusText:h,status:f}=i(),{responseType:b}=t;let y=null,N=null;f!==L.NoContent&&(y=typeof r.response>"u"?r.responseText:r.response);let I=f>=j&&f<D;if(b==="json"&&typeof y=="string"){const V=y;try{y=y?JSON.parse(y):null}catch(W){I=!1,y=V,N=W}}I?n.next(new R({body:y,headers:m,status:f,statusText:h})):n.next(new q({error:N,headers:m,status:f,statusText:h}))},s=m=>{const h=new q({error:m,status:r.status||0,statusText:r.statusText||"Unknown Error",headers:i().headers});n.next(h)};r.addEventListener("load",a),r.addEventListener("error",s),r.addEventListener("abort",s),r.addEventListener("timeout",s);const d=t.getBody();return r.send(d),()=>{r.readyState!==r.DONE&&r.abort(),r.removeEventListener("load",a),r.removeEventListener("error",s),r.removeEventListener("abort",s),r.removeEventListener("timeout",s)}})}}const B=g.createIdentifier("univer.socket");class G extends c.Disposable{createSocket(t){try{const n=new WebSocket(t),r=new c.DisposableCollection;return{URL:t,close:(a,s)=>{n.close(a,s),r.dispose()},send:a=>{n.send(a)},open$:new l.Observable(a=>{const s=d=>a.next(d);n.addEventListener("open",s),r.add(c.toDisposable(()=>n.removeEventListener("open",s)))}).pipe(v.share()),close$:new l.Observable(a=>{const s=d=>a.next(d);n.addEventListener("close",s),r.add(c.toDisposable(()=>n.removeEventListener("close",s)))}).pipe(v.share()),error$:new l.Observable(a=>{const s=d=>a.next(d);n.addEventListener("error",s),r.add(c.toDisposable(()=>n.removeEventListener("error",s)))}).pipe(v.share()),message$:new l.Observable(a=>{const s=d=>a.next(d);n.addEventListener("message",s),r.add(c.toDisposable(()=>n.removeEventListener("message",s)))}).pipe(v.share())}}catch(n){return console.error(n),null}}}o.HTTPHeaders=w,o.HTTPRequest=_,o.HTTPResponse=R,o.IHTTPImplementation=E,o.ISocketService=B,o.WebSocketService=G,o.XHRHTTPImplementation=$,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})});
1
+ (function(c,a){typeof exports=="object"&&typeof module<"u"?a(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"],a):(c=typeof globalThis<"u"?globalThis:c||self,a(c.UniverNetwork={},c.UniverCore,c.rxjs,c.rxjs.operators,c["@wendellhu/redi"]))})(this,function(c,a,l,v,R){"use strict";var Q=Object.defineProperty;var Z=(c,a,l)=>a in c?Q(c,a,{enumerable:!0,configurable:!0,writable:!0,value:l}):c[a]=l;var m=(c,a,l)=>(Z(c,typeof a!="symbol"?a+"":a,l),l);const g="application/json";class b{constructor(t){m(this,"_headers",new Map);typeof t=="string"?t.split(`
2
+ `).forEach(n=>{const[r,i]=n.split(":");r&&i&&this._setHeader(r,i)}):t&&Object.keys(t).forEach(([n,r])=>{this._setHeader(n,r)})}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}_setHeader(t,n){const r=t.toLowerCase();this._headers.has(r)?this._headers.get(r).push(n.toString()):this._headers.set(r,[n.toString()])}}const E=R.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){m(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,i;const t=(r=this.headers.get("Content-Type"))!=null?r:g,n=(i=this.requestParams)==null?void 0:i.body;return t===g&&n&&typeof n=="object"?JSON.stringify(n):n?`${n}`:null}}class u{constructor({body:t,headers:n,status:r,statusText:i}){m(this,"body");m(this,"headers");m(this,"status");m(this,"statusText");this.body=t,this.headers=n,this.status=r,this.statusText=i}}class L{constructor({headers:t,status:n,statusText:r,error:i}){m(this,"headers");m(this,"status");m(this,"statusText");m(this,"error");this.headers=t,this.status=n,this.statusText=r,this.error=i}}class O{constructor(t,n,r){this.headers=t,this.status=n,this.statusText=r}}var M=Object.defineProperty,x=Object.getOwnPropertyDescriptor,F=(e,t,n,r)=>{for(var i=r>1?void 0:r?x(t,n):t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=(r?s(t,n,i):s(i))||i);return r&&i&&M(t,n,i),i},k=(e,t)=>(n,r)=>t(n,r,e);c.HTTPService=class extends a.Disposable{constructor(n){super();m(this,"_interceptors",[]);m(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,i)=>{var o,s;return((o=r.priority)!=null?o:0)-((s=i.priority)!=null?s:0)}),this._pipe=null,a.toDisposable(()=>a.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)}async _request(n,r,i){var y,w;const o=new b(i==null?void 0:i.headers),s=new A(i==null?void 0:i.params),h=new _(n,r,{headers:o,params:s,withCredentials:(y=i==null?void 0:i.withCredentials)!=null?y:!1,responseType:(w=i==null?void 0:i.responseType)!=null?w:"json",body:n==="GET"||i==null?void 0:i.body}),p=l.of(h).pipe(v.concatMap(f=>this._runInterceptorsAndImplementation(f))),d=await l.firstValueFrom(p);if(d instanceof u)return d;throw new Error(`${d.error}`)}_runInterceptorsAndImplementation(n){return this._pipe||(this._pipe=this._interceptors.map(r=>r.interceptor).reduceRight((r,i)=>D(r,i),(r,i)=>i(r))),this._pipe(n,r=>this._http.send(r))}},c.HTTPService=F([k(0,E)],c.HTTPService);function D(e,t){return(n,r)=>t(n,i=>e(i,r))}const j=200,$=300;var q=(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))(q||{});class B{send(t){return new l.Observable(n=>{const r=new XMLHttpRequest;r.open(t.method,t.getUrlWithParams()),t.withCredentials&&(r.withCredentials=!0),t.headers.forEach((p,d)=>r.setRequestHeader(p,d.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 i=()=>{const p=r.statusText||"OK",d=new b(r.getAllResponseHeaders());return new O(d,r.status,p)},o=()=>{const{headers:p,statusText:d,status:y}=i(),{responseType:w}=t;let f=null,I=null;y!==q.NoContent&&(f=typeof r.response>"u"?r.responseText:r.response);let N=y>=j&&y<$;if(w==="json"&&typeof f=="string"){const Y=f;try{f=f?JSON.parse(f):null}catch(K){N=!1,f=Y,I=K}}N?n.next(new u({body:f,headers:p,status:y,statusText:d})):n.next(new L({error:I,headers:p,status:y,statusText:d}))},s=p=>{const d=new L({error:p,status:r.status||0,statusText:r.statusText||"Unknown Error",headers:i().headers});n.next(d)};r.addEventListener("load",o),r.addEventListener("error",s),r.addEventListener("abort",s),r.addEventListener("timeout",s);const h=t.getBody();return r.send(h),()=>{r.readyState!==r.DONE&&r.abort(),r.removeEventListener("load",o),r.removeEventListener("error",s),r.removeEventListener("abort",s),r.removeEventListener("timeout",s)}})}}const G=R.createIdentifier("univer.socket");class V extends a.Disposable{createSocket(t){try{const n=new WebSocket(t),r=new a.DisposableCollection;return{URL:t,close:(o,s)=>{n.close(o,s),r.dispose()},send:o=>{n.send(o)},open$:new l.Observable(o=>{const s=h=>o.next(h);n.addEventListener("open",s),r.add(a.toDisposable(()=>n.removeEventListener("open",s)))}).pipe(v.share()),close$:new l.Observable(o=>{const s=h=>o.next(h);n.addEventListener("close",s),r.add(a.toDisposable(()=>n.removeEventListener("close",s)))}).pipe(v.share()),error$:new l.Observable(o=>{const s=h=>o.next(h);n.addEventListener("error",s),r.add(a.toDisposable(()=>n.removeEventListener("error",s)))}).pipe(v.share()),message$:new l.Observable(o=>{const s=h=>o.next(h);n.addEventListener("message",s),r.add(a.toDisposable(()=>n.removeEventListener("message",s)))}).pipe(v.share())}}catch(n){return console.error(n),null}}}const W=2,X=1e3,z=(e,t)=>t(e).pipe(v.retryWhen(n=>n.pipe(v.concatMap((r,i)=>i>W?l.throwError(r):l.of(r)),l.delay(X)))),J=(e,t)=>{const n=[],r=new Set,i=()=>{var o;for(;r.size<((o=t==null?void 0:t.maxParallel)!=null?o:1)&&n.length>0;){const s=n.shift();r.add(s),s()}};return(o,s)=>new l.Observable(h=>{const p=()=>s(o).subscribe({next:y=>h.next(y),error:y=>h.next(y),complete:()=>h.complete()}),d=()=>{r.delete(p),a.remove(n,p),i()};return n.push(p),i(),d})};c.HTTPHeaders=b,c.HTTPRequest=_,c.HTTPResponse=u,c.IHTTPImplementation=E,c.ISocketService=G,c.ThresholdInterceptorFactory=J,c.WebSocketService=V,c.XHRHTTPImplementation=B,c.retryInterceptor=z,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.1.2",
3
+ "version": "0.1.4",
4
4
  "private": false,
5
5
  "author": "DreamNum <developer@univer.ai>",
6
6
  "license": "Apache-2.0",
@@ -16,7 +16,9 @@
16
16
  "bugs": {
17
17
  "url": "https://github.com/dream-num/univer/issues"
18
18
  },
19
- "keywords": [],
19
+ "keywords": [
20
+ "univer"
21
+ ],
20
22
  "exports": {
21
23
  ".": {
22
24
  "import": "./lib/es/index.js",
@@ -47,21 +49,24 @@
47
49
  "npm": ">=8.0.0"
48
50
  },
49
51
  "peerDependencies": {
50
- "@wendellhu/redi": "^0.13.0",
52
+ "@wendellhu/redi": "0.13.0",
51
53
  "rxjs": ">=7.0.0",
52
- "@univerjs/core": "0.1.2"
54
+ "@univerjs/core": "0.1.4"
53
55
  },
54
56
  "dependencies": {},
55
57
  "devDependencies": {
56
58
  "@wendellhu/redi": "^0.13.0",
57
59
  "rxjs": "^7.8.1",
58
- "typescript": "^5.3.3",
59
- "vite": "^5.1.4",
60
- "vitest": "^1.3.1",
61
- "@univerjs/shared": "0.1.2",
62
- "@univerjs/core": "0.1.2"
60
+ "typescript": "^5.4.2",
61
+ "vite": "^5.1.6",
62
+ "vitest": "^1.4.0",
63
+ "@univerjs/core": "0.1.4",
64
+ "@univerjs/shared": "0.1.4"
63
65
  },
64
66
  "scripts": {
67
+ "test": "vitest run",
68
+ "test:watch": "vitest",
69
+ "coverage": "vitest run --coverage",
65
70
  "lint:types": "tsc --noEmit",
66
71
  "build": "tsc && vite build"
67
72
  }