@univerjs/network 0.20.1 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cjs/index.js CHANGED
@@ -1,2 +1,920 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require(`@univerjs/core`),t=require(`rxjs`),n=require(`rxjs/operators`);var r=`@univerjs/network`,i=`0.20.1`;const a=`network.config`;Symbol(a);const o={};function s(e){"@babel/helpers - typeof";return s=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},s(e)}function c(e,t){if(s(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(s(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function l(e){var t=c(e,`string`);return s(t)==`symbol`?t:t+``}function u(e,t,n){return(t=l(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const d=`application/json`;function f(e){return Array.isArray(e)?e.some(e=>e.includes(d)):e.includes(d)}var p=class{constructor(e){u(this,`_headers`,new Map),typeof e==`string`?this._handleHeadersString(e):e instanceof Headers?this._handleHeaders(e):e&&this._handleHeadersConstructorProps(e)}forEach(e){this._headers.forEach((t,n)=>e(n,t))}has(e){return!!this._headers.has(e.toLowerCase())}get(e){let t=e.toLowerCase();return this._headers.has(t)?this._headers.get(t):null}set(e,t){this._setHeader(e,t)}toHeadersInit(e){let t={};return this._headers.forEach((e,n)=>{t[n]=e.join(`,`)}),t.accept!=null||(t.accept=`application/json, text/plain, */*`),!(e instanceof FormData)&&(t[`content-type`]!=null||(t[`content-type`]=`application/json;charset=UTF-8`)),t}_setHeader(e,t){let n=e.toLowerCase();this._headers.has(n)?this._headers.get(n).push(t.toString()):this._headers.set(n,[t.toString()])}_handleHeadersString(e){e.split(`
2
- `).forEach(e=>{let[t,n]=e.split(`:`);t&&n&&this._setHeader(t,n)})}_handleHeadersConstructorProps(e){Object.entries(e).forEach(([e,t])=>this._setHeader(e,t))}_handleHeaders(e){e.forEach((e,t)=>this._setHeader(t,e))}};const m=(0,e.createIdentifier)(`network.http-implementation`);var h=class{constructor(e){this.params=e}toString(){return this.params?Object.keys(this.params).map(e=>{let t=this.params[e];return Array.isArray(t)?t.map(t=>`${e}=${t}`).join(`&`):`${e}=${t}`}).join(`&`):``}};let g=0;var _=class{get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}constructor(e,t,n){this.method=e,this.url=t,this.requestParams=n,u(this,`uid`,g++)}getUrlWithParams(){var e;let t=(e=this.requestParams)==null||(e=e.params)==null?void 0:e.toString();return t?`${this.url}${this.url.includes(`?`)?`&`:`?`}${t}`:this.url}getBody(){var e,t;let n=(e=this.headers.get(`Content-Type`))==null?d:e,r=(t=this.requestParams)==null?void 0:t.body;return r instanceof FormData?r:f(n)&&r&&typeof r==`object`?JSON.stringify(r):r?`${r}`:null}getHeadersInit(){var e;return this.headers.toHeadersInit((e=this.requestParams)==null?void 0:e.body)}};function v(e,t){return function(n,r){t(n,r,e)}}function y(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}let b=class extends e.Disposable{constructor(e){super(),this._http=e,u(this,`_interceptors`,[]),u(this,`_pipe`,void 0)}registerHTTPInterceptor(t){if(this._interceptors.indexOf(t)!==-1)throw Error(`[HTTPService]: The interceptor has already been registered!`);return this._interceptors.push(t),this._interceptors=this._interceptors.sort((e,t)=>{var n,r;return((n=e.priority)==null?0:n)-((r=t.priority)==null?0:r)}),this._pipe=null,(0,e.toDisposable)(()=>(0,e.remove)(this._interceptors,t))}get(e,t){return this.request(`GET`,e,t)}post(e,t){return this.request(`POST`,e,t)}put(e,t){return this.request(`PUT`,e,t)}delete(e,t){return this.request(`DELETE`,e,t)}patch(e,t){return this.request(`PATCH`,e,t)}async request(e,r,i){var a,o;return await(0,t.firstValueFrom)((0,t.of)(new _(e,r,{headers:new p(i==null?void 0:i.headers),params:new h(i==null?void 0:i.params),withCredentials:(a=i==null?void 0:i.withCredentials)==null?!1:a,responseType:(o=i==null?void 0:i.responseType)==null?`json`:o,body:[`GET`,`DELETE`].includes(e)||i==null?void 0:i.body})).pipe((0,n.concatMap)(e=>this._runInterceptorsAndImplementation(e))))}stream(e,t,n){return this.getSSE(e,t,n)}getSSE(e,r,i){var a,o;return(0,t.of)(new _(e,r,{headers:new p(i==null?void 0:i.headers),params:new h(i==null?void 0:i.params),withCredentials:(a=i==null?void 0:i.withCredentials)==null?!1:a,reportProgress:!0,responseType:(o=i==null?void 0:i.responseType)==null?`json`:o,body:[`GET`,`DELETE`].includes(e)||i==null?void 0:i.body})).pipe((0,n.concatMap)(e=>this._runInterceptorsAndImplementation(e)))}_runInterceptorsAndImplementation(e){return this._pipe||(this._pipe=this._interceptors.map(e=>e.interceptor).reduceRight((e,t)=>x(e,t),(e,t)=>t(e))),this._pipe(e,e=>this._http.send(e))}};b=y([v(0,m)],b);function x(e,t){return(n,r)=>t(n,t=>e(t,r))}let S=function(e){return 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}({}),C=function(e){return e[e.DownloadProgress=0]=`DownloadProgress`,e[e.Response=1]=`Response`,e}({});var w=class{constructor({body:e,headers:t,status:n,statusText:r}){u(this,`type`,C.Response),u(this,`body`,void 0),u(this,`headers`,void 0),u(this,`status`,void 0),u(this,`statusText`,void 0),this.body=e,this.headers=t,this.status=n,this.statusText=r}},T=class{constructor(e,t,n){this.total=e,this.loaded=t,this.partialText=n,u(this,`type`,C.DownloadProgress)}},E=class{constructor(e,t,n){this.headers=e,this.status=t,this.statusText=n}},D=class{constructor({request:e,headers:t,status:n,statusText:r,error:i}){u(this,`request`,void 0),u(this,`headers`,void 0),u(this,`status`,void 0),u(this,`statusText`,void 0),u(this,`error`,void 0),this.request=e,this.headers=t,this.status=n,this.statusText=r,this.error=i}};function O(e){return{method:e.method,headers:e.getHeadersInit(),body:e.getBody(),credentials:e.withCredentials?`include`:void 0}}let k=class{constructor(e){this._logService=e}send(e){return new t.Observable(t=>{let n=new AbortController;return this._send(e,t,n).catch(n=>{t.error(new D({error:n,request:e}))}),()=>n.abort()})}async _send(e,t,n){let r;try{let t=O(e),i=e.getUrlWithParams(),a=fetch(i,{signal:n.signal,...t});this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${i} with params ${t}`),r=await a}catch(n){var i,a;let r=new D({request:e,error:n,status:(i=n.status)==null?0:i,statusText:(a=n.statusText)==null?`Unknown Error`:a,headers:n.headers});this._logService.error(`[FetchHTTPImplementation]: network error`,r),t.error(r);return}let o=new p(r.headers),s=r.status,c=r.statusText,l=null;if(r.body&&(l=await this._readBody(e,r,t)),s>=S.Ok&&s<S.MultipleChoices)t.next(new w({body:l,headers:o,status:s,statusText:c}));else{let n=new D({request:e,error:l,status:s,statusText:c,headers:o});this._logService.error(`[FetchHTTPImplementation]: network error`,n),t.error(n)}t.complete()}async _readBody(e,t,n){var r;let i=[],a=t.body.getReader(),o=t.headers.get(`content-length`),s=0,c=(r=e.requestParams)==null?void 0:r.reportProgress,l=e.responseType,u,d;for(;;){let{done:e,value:t}=await a.read();if(e)break;if(i.push(t),s+=t.length,c&&l===`text`){var f,m;u=((f=u)==null?``:f)+((m=d)==null?d=new TextDecoder:m).decode(t,{stream:!0}),n.next(new T(o?Number.parseInt(o,10):void 0,s,u))}}let h=A(i,s);try{var g;return M(e,h,(g=t.headers.get(`content-type`))==null?``:g)}catch(r){let i=new D({request:e,error:r,status:t.status,statusText:t.statusText,headers:new p(t.headers)});return this._logService.error(`[FetchHTTPImplementation]: network error`,i),n.error(i),null}}};k=y([v(0,e.ILogService)],k);function A(e,t){let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}const j=/^\)\]\}',?\n/;function M(e,t,n){switch(e.responseType){case`json`:let r=new TextDecoder().decode(t).replace(j,``);return r===``?null:JSON.parse(r);case`text`:return new TextDecoder().decode(t);case`blob`:return new Blob([t.buffer],{type:n});case`arraybuffer`:return t.buffer;default:throw Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`)}}let N=class{constructor(e){this._logService=e}send(e){return new t.Observable(t=>{let n=new XMLHttpRequest,r=e.getUrlWithParams(),i=O(e),{responseType:a}=e;n.open(e.method,r),e.withCredentials&&(n.withCredentials=!0),i.headers&&Object.entries(i.headers).forEach(([e,t])=>n.setRequestHeader(e,t));let o=()=>{let e=n.statusText||`OK`;return new E(new p(n.getAllResponseHeaders()),n.status,e)},s=()=>{let{headers:r,statusText:i,status:s}=o(),c=null,l=null;s!==S.NoContent&&(c=n.response===void 0?n.responseText:n.response);let u=s>=200&&s<300;if(a===`json`&&typeof c==`string`){let e=c;try{c=c?JSON.parse(c):null}catch(t){u=!1,c=e,l=t}}if(a===`blob`&&!(c instanceof Blob)&&(u=!1,l=Error(`Response is not a Blob object`)),u)t.next(new w({body:c,headers:r,status:s,statusText:i}));else{let n=new D({request:e,error:l,headers:r,status:s,statusText:i});this._logService.error(`[XHRHTTPImplementation]: network error`,n),t.error(n)}},c=r=>{let i=new D({request:e,error:r,status:n.status||0,statusText:n.statusText||`Unknown Error`,headers:o().headers});this._logService.error(`[XHRHTTPImplementation]: network error`,i),t.error(i)};n.responseType=a||``,n.addEventListener(`load`,s),n.addEventListener(`error`,c),n.addEventListener(`abort`,c),n.addEventListener(`timeout`,c);let l=e.getBody();return n.send(l),this._logService.debug(`[XHRHTTPImplementation]`,`sending request to url ${r} with params ${i}`),()=>{n.readyState!==n.DONE&&n.abort(),n.removeEventListener(`load`,s),n.removeEventListener(`error`,c),n.removeEventListener(`abort`,c),n.removeEventListener(`timeout`,c)}})}};N=y([v(0,e.ILogService)],N);let P=class extends e.Plugin{constructor(t=o,n,r,i){super(),this._config=t,this._logger=n,this._injector=r,this._configService=i;let{...s}=(0,e.merge)({},o,this._config);this._configService.setConfig(a,s)}onStarting(){var t,n,r;if(this._injector.get(b,e.Quantity.OPTIONAL,e.LookUp.SKIP_SELF)&&!((t=this._config)!=null&&t.forceUseNewInstance)){this._logger.warn(`[UniverNetworkPlugin]`,`HTTPService is already registered in an ancestor interceptor. Skipping registration. If you want to force a new instance, set "forceUseNewInstance" to true in the plugin configuration.`);return}let i=(n=this._config)!=null&&n.useFetchImpl?k:typeof window<`u`?N:k;(0,e.registerDependencies)(this._injector,(0,e.mergeOverrideWithDependencies)([[b],[m,{useClass:i}]],(r=this._config)==null?void 0:r.override))}};u(P,`pluginName`,`UNIVER_NETWORK_PLUGIN`),u(P,`packageName`,r),u(P,`version`,i),P=y([v(1,e.ILogService),v(2,(0,e.Inject)(e.Injector)),v(3,e.IConfigService)],P);const F=e=>{let{errorStatusCodes:n,onAuthError:r}=e;return(e,i)=>i(e).pipe((0,t.catchError)(e=>(e instanceof D&&n.some(t=>t===e.status)&&r(),(0,t.throwError)(()=>e))))},I=(e=300)=>{let t=()=>{};return n=>new Promise(n=>{t();let r=setTimeout(()=>{n(!0)},e);t=()=>{clearTimeout(r),n(!1)}})},L=()=>(e,t)=>t.map(t=>({config:t,result:e})),R=(e,n={})=>{let{isMatch:r,getParamsFromRequest:i,mergeParamsToRequest:a}=e,{fetchCheck:o=I(300),distributeResult:s=L()}=n,c=[],l=e=>e.map(e=>e.config);return(e,n)=>r(e)?new t.Observable(t=>{let r=i(e);c.push({next:e=>t.next(e),error:e=>t.error(e),config:r});let u=l(c);o(e).then(r=>{if(r){let r=[];u.forEach(e=>{let t=c.findIndex(t=>t.config===e);if(t>=0){let[e]=c.splice(t,1);r.push(e)}}),n(a(u,e)).subscribe({next:e=>{if(e.type===C.Response){let t=e.body,n=s(t,u);r.forEach(t=>{let r=n.find(e=>e.config===t.config);if(r){let n=new w({body:r.result,headers:e.headers,status:e.status,statusText:e.statusText});t.next(n)}else t.error(`batch error`)})}},complete:()=>t.complete(),error:e=>t.error(e)})}})}):n(e)},z=e=>{var t,r;let i=(t=e==null?void 0:e.maxRetryAttempts)==null?3:t,a=(r=e==null?void 0:e.delayInterval)==null?1e3:r;return(e,t)=>t(e).pipe((0,n.retry)({delay:a,count:i}))},B=n=>{let r=[],i=new Set,a=()=>{for(var e;i.size<((e=n==null?void 0:n.maxParallel)==null?1:e)&&r.length>0;){let e=r.shift();i.add(e),e()}};return(n,o)=>new t.Observable(t=>{let s=()=>o(n).subscribe({next:e=>t.next(e),error:e=>t.error(e),complete:()=>t.complete()});return r.push(s),a(),()=>{i.delete(s),(0,e.remove)(r,s),a()}})},V=(0,e.createIdentifier)(`univer.network.socket.service`);var H=class extends e.Disposable{createSocket(r){try{let i=new WebSocket(r),a=new e.DisposableCollection;return{URL:r,close:(e,t)=>{i.close(e,t),a.dispose()},send:e=>{i.send(e)},open$:new t.Observable(t=>{let n=e=>t.next(e);i.addEventListener(`open`,n),a.add((0,e.toDisposable)(()=>i.removeEventListener(`open`,n)))}).pipe((0,n.share)()),close$:new t.Observable(t=>{let n=e=>t.next(e);i.addEventListener(`close`,n),a.add((0,e.toDisposable)(()=>i.removeEventListener(`close`,n)))}).pipe((0,n.share)()),error$:new t.Observable(t=>{let n=e=>t.next(e);i.addEventListener(`error`,n),a.add((0,e.toDisposable)(()=>i.removeEventListener(`error`,n)))}).pipe((0,n.share)()),message$:new t.Observable(t=>{let n=e=>t.next(e);i.addEventListener(`message`,n),a.add((0,e.toDisposable)(()=>i.removeEventListener(`message`,n)))}).pipe((0,n.share)())}}catch(e){return console.error(e),null}}};exports.AuthInterceptorFactory=F,Object.defineProperty(exports,`FetchHTTPImplementation`,{enumerable:!0,get:function(){return k}}),exports.HTTPEventType=C,exports.HTTPHeaders=p,exports.HTTPProgress=T,exports.HTTPRequest=_,exports.HTTPResponse=w,exports.HTTPResponseError=D,Object.defineProperty(exports,`HTTPService`,{enumerable:!0,get:function(){return b}}),exports.HTTPStatusCode=S,exports.IHTTPImplementation=m,exports.ISocketService=V,exports.MergeInterceptorFactory=R,exports.ResponseHeader=E,exports.RetryInterceptorFactory=z,exports.ThresholdInterceptorFactory=B,Object.defineProperty(exports,`UniverNetworkPlugin`,{enumerable:!0,get:function(){return P}}),exports.WebSocketService=H,Object.defineProperty(exports,`XHRHTTPImplementation`,{enumerable:!0,get:function(){return N}});
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ let _univerjs_core = require("@univerjs/core");
3
+ let rxjs = require("rxjs");
4
+ let rxjs_operators = require("rxjs/operators");
5
+
6
+ //#region package.json
7
+ var name = "@univerjs/network";
8
+ var version = "0.21.0";
9
+
10
+ //#endregion
11
+ //#region src/config/config.ts
12
+ const NETWORK_PLUGIN_CONFIG_KEY = "network.config";
13
+ const configSymbol = Symbol(NETWORK_PLUGIN_CONFIG_KEY);
14
+ const defaultPluginConfig = {};
15
+
16
+ //#endregion
17
+ //#region \0@oxc-project+runtime@0.124.0/helpers/typeof.js
18
+ function _typeof(o) {
19
+ "@babel/helpers - typeof";
20
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
21
+ return typeof o;
22
+ } : function(o) {
23
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
24
+ }, _typeof(o);
25
+ }
26
+
27
+ //#endregion
28
+ //#region \0@oxc-project+runtime@0.124.0/helpers/toPrimitive.js
29
+ function toPrimitive(t, r) {
30
+ if ("object" != _typeof(t) || !t) return t;
31
+ var e = t[Symbol.toPrimitive];
32
+ if (void 0 !== e) {
33
+ var i = e.call(t, r || "default");
34
+ if ("object" != _typeof(i)) return i;
35
+ throw new TypeError("@@toPrimitive must return a primitive value.");
36
+ }
37
+ return ("string" === r ? String : Number)(t);
38
+ }
39
+
40
+ //#endregion
41
+ //#region \0@oxc-project+runtime@0.124.0/helpers/toPropertyKey.js
42
+ function toPropertyKey(t) {
43
+ var i = toPrimitive(t, "string");
44
+ return "symbol" == _typeof(i) ? i : i + "";
45
+ }
46
+
47
+ //#endregion
48
+ //#region \0@oxc-project+runtime@0.124.0/helpers/defineProperty.js
49
+ function _defineProperty(e, r, t) {
50
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
51
+ value: t,
52
+ enumerable: !0,
53
+ configurable: !0,
54
+ writable: !0
55
+ }) : e[r] = t, e;
56
+ }
57
+
58
+ //#endregion
59
+ //#region src/services/http/headers.ts
60
+ const ApplicationJSONType = "application/json";
61
+ /**
62
+ * Check if the content type is application/json
63
+ * "application/json" or "application/json; charset=utf-8" or ["application/json"]
64
+ * @param contentType
65
+ */
66
+ function isApplicationJSONType(contentType) {
67
+ if (Array.isArray(contentType)) return contentType.some((type) => type.includes(ApplicationJSONType));
68
+ return contentType.includes(ApplicationJSONType);
69
+ }
70
+ /**
71
+ * It wraps headers of HTTP requests' and responses' headers.
72
+ */
73
+ var HTTPHeaders = class {
74
+ constructor(headers) {
75
+ _defineProperty(this, "_headers", /* @__PURE__ */ new Map());
76
+ if (typeof headers === "string") this._handleHeadersString(headers);
77
+ else if (headers instanceof Headers) this._handleHeaders(headers);
78
+ else if (headers) this._handleHeadersConstructorProps(headers);
79
+ }
80
+ forEach(callback) {
81
+ this._headers.forEach((v, key) => callback(key, v));
82
+ }
83
+ has(key) {
84
+ return !!this._headers.has(key.toLowerCase());
85
+ }
86
+ get(key) {
87
+ const k = key.toLowerCase();
88
+ return this._headers.has(k) ? this._headers.get(k) : null;
89
+ }
90
+ set(key, value) {
91
+ this._setHeader(key, value);
92
+ }
93
+ toHeadersInit(body) {
94
+ var _headers$accept;
95
+ const headers = {};
96
+ this._headers.forEach((values, key) => {
97
+ headers[key] = values.join(",");
98
+ });
99
+ (_headers$accept = headers.accept) !== null && _headers$accept !== void 0 || (headers.accept = "application/json, text/plain, */*");
100
+ if (!(body instanceof FormData)) {
101
+ var _headers$contentType;
102
+ (_headers$contentType = headers["content-type"]) !== null && _headers$contentType !== void 0 || (headers["content-type"] = "application/json;charset=UTF-8");
103
+ }
104
+ return headers;
105
+ }
106
+ _setHeader(name, value) {
107
+ const lowerCase = name.toLowerCase();
108
+ if (this._headers.has(lowerCase)) this._headers.get(lowerCase).push(value.toString());
109
+ else this._headers.set(lowerCase, [value.toString()]);
110
+ }
111
+ _handleHeadersString(headers) {
112
+ headers.split("\n").forEach((header) => {
113
+ const [name, value] = header.split(":");
114
+ if (name && value) this._setHeader(name, value);
115
+ });
116
+ }
117
+ _handleHeadersConstructorProps(headers) {
118
+ Object.entries(headers).forEach(([name, value]) => this._setHeader(name, value));
119
+ }
120
+ _handleHeaders(headers) {
121
+ headers.forEach((value, name) => this._setHeader(name, value));
122
+ }
123
+ };
124
+
125
+ //#endregion
126
+ //#region src/services/http/implementations/implementation.ts
127
+ const IHTTPImplementation = (0, _univerjs_core.createIdentifier)("network.http-implementation");
128
+
129
+ //#endregion
130
+ //#region src/services/http/params.ts
131
+ var HTTPParams = class {
132
+ constructor(params) {
133
+ this.params = params;
134
+ }
135
+ toString() {
136
+ if (!this.params) return "";
137
+ return Object.keys(this.params).map((key) => {
138
+ const value = this.params[key];
139
+ if (Array.isArray(value)) return value.map((v) => `${key}=${v}`).join("&");
140
+ return `${key}=${value}`;
141
+ }).join("&");
142
+ }
143
+ };
144
+
145
+ //#endregion
146
+ //#region src/services/http/request.ts
147
+ let HTTPRequestUID = 0;
148
+ var HTTPRequest = class {
149
+ get headers() {
150
+ return this.requestParams.headers;
151
+ }
152
+ get withCredentials() {
153
+ return this.requestParams.withCredentials;
154
+ }
155
+ get responseType() {
156
+ return this.requestParams.responseType;
157
+ }
158
+ constructor(method, url, requestParams) {
159
+ this.method = method;
160
+ this.url = url;
161
+ this.requestParams = requestParams;
162
+ _defineProperty(this, "uid", HTTPRequestUID++);
163
+ }
164
+ getUrlWithParams() {
165
+ var _this$requestParams;
166
+ const params = (_this$requestParams = this.requestParams) === null || _this$requestParams === void 0 || (_this$requestParams = _this$requestParams.params) === null || _this$requestParams === void 0 ? void 0 : _this$requestParams.toString();
167
+ if (!params) return this.url;
168
+ return `${this.url}${this.url.includes("?") ? "&" : "?"}${params}`;
169
+ }
170
+ getBody() {
171
+ var _this$headers$get, _this$requestParams2;
172
+ const contentType = (_this$headers$get = this.headers.get("Content-Type")) !== null && _this$headers$get !== void 0 ? _this$headers$get : ApplicationJSONType;
173
+ const body = (_this$requestParams2 = this.requestParams) === null || _this$requestParams2 === void 0 ? void 0 : _this$requestParams2.body;
174
+ if (body instanceof FormData) return body;
175
+ if (isApplicationJSONType(contentType) && body && typeof body === "object") return JSON.stringify(body);
176
+ return body ? `${body}` : null;
177
+ }
178
+ getHeadersInit() {
179
+ var _this$requestParams3;
180
+ return this.headers.toHeadersInit((_this$requestParams3 = this.requestParams) === null || _this$requestParams3 === void 0 ? void 0 : _this$requestParams3.body);
181
+ }
182
+ };
183
+
184
+ //#endregion
185
+ //#region \0@oxc-project+runtime@0.124.0/helpers/decorateParam.js
186
+ function __decorateParam(paramIndex, decorator) {
187
+ return function(target, key) {
188
+ decorator(target, key, paramIndex);
189
+ };
190
+ }
191
+
192
+ //#endregion
193
+ //#region \0@oxc-project+runtime@0.124.0/helpers/decorate.js
194
+ function __decorate(decorators, target, key, desc) {
195
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
196
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
197
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
198
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
199
+ }
200
+
201
+ //#endregion
202
+ //#region src/services/http/http.service.ts
203
+ let HTTPService = class HTTPService extends _univerjs_core.Disposable {
204
+ constructor(_http) {
205
+ super();
206
+ this._http = _http;
207
+ _defineProperty(this, "_interceptors", []);
208
+ _defineProperty(this, "_pipe", void 0);
209
+ }
210
+ /**
211
+ * Register an HTTP interceptor.
212
+ *
213
+ * @param interceptor the http interceptor
214
+ * @returns a disposable handler to remove the interceptor
215
+ */
216
+ registerHTTPInterceptor(interceptor) {
217
+ if (this._interceptors.indexOf(interceptor) !== -1) throw new Error("[HTTPService]: The interceptor has already been registered!");
218
+ this._interceptors.push(interceptor);
219
+ this._interceptors = this._interceptors.sort((a, b) => {
220
+ var _a$priority, _b$priority;
221
+ return ((_a$priority = a.priority) !== null && _a$priority !== void 0 ? _a$priority : 0) - ((_b$priority = b.priority) !== null && _b$priority !== void 0 ? _b$priority : 0);
222
+ });
223
+ this._pipe = null;
224
+ return (0, _univerjs_core.toDisposable)(() => (0, _univerjs_core.remove)(this._interceptors, interceptor));
225
+ }
226
+ get(url, params) {
227
+ return this.request("GET", url, params);
228
+ }
229
+ post(url, params) {
230
+ return this.request("POST", url, params);
231
+ }
232
+ put(url, params) {
233
+ return this.request("PUT", url, params);
234
+ }
235
+ delete(url, params) {
236
+ return this.request("DELETE", url, params);
237
+ }
238
+ patch(url, params) {
239
+ return this.request("PATCH", url, params);
240
+ }
241
+ /**
242
+ * The HTTP request implementations. Normally you should use the `get`, `post`, `put`, `delete`,
243
+ * `patch` methods instead.
244
+ * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
245
+ * @param url The URL to send the request to.
246
+ * @param options Optional parameters for the request.
247
+ * @returns A promise that resolves to the HTTP response.
248
+ */
249
+ async request(method, url, options) {
250
+ var _options$withCredenti, _options$responseType;
251
+ return await (0, rxjs.firstValueFrom)((0, rxjs.of)(new HTTPRequest(method, url, {
252
+ headers: new HTTPHeaders(options === null || options === void 0 ? void 0 : options.headers),
253
+ params: new HTTPParams(options === null || options === void 0 ? void 0 : options.params),
254
+ withCredentials: (_options$withCredenti = options === null || options === void 0 ? void 0 : options.withCredentials) !== null && _options$withCredenti !== void 0 ? _options$withCredenti : false,
255
+ responseType: (_options$responseType = options === null || options === void 0 ? void 0 : options.responseType) !== null && _options$responseType !== void 0 ? _options$responseType : "json",
256
+ body: ["GET", "DELETE"].includes(method) ? void 0 : options === null || options === void 0 ? void 0 : options.body
257
+ })).pipe((0, rxjs_operators.concatMap)((request) => this._runInterceptorsAndImplementation(request))));
258
+ }
259
+ /**
260
+ * Send an HTTP request. It returns an observable that emits HTTP events. For example, it can be used to
261
+ * send Server-Sent Events (SSE) requests.
262
+ * @deprecated Please use `stream` method instead.
263
+ * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
264
+ * @param url The URL to send the request to.
265
+ * @param _params Optional parameters for the request.
266
+ * @returns An observable of the HTTP event.
267
+ */
268
+ stream(method, url, _params) {
269
+ return this.getSSE(method, url, _params);
270
+ }
271
+ /**
272
+ * Send a Server-Sent Events (SSE) request. It returns an observable that emits HTTP events. It is the observable
273
+ * pair of the `request` method.
274
+ * @deprecated Please use `stream` method instead.
275
+ * @param method HTTP request method, e.g. GET, POST, PUT, DELETE, etc.
276
+ * @param url The URL to send the request to.
277
+ * @param _params Optional parameters for the request.
278
+ * @returns An observable of the HTTP event.
279
+ */
280
+ getSSE(method, url, _params) {
281
+ var _params$withCredentia, _params$responseType;
282
+ return (0, rxjs.of)(new HTTPRequest(method, url, {
283
+ headers: new HTTPHeaders(_params === null || _params === void 0 ? void 0 : _params.headers),
284
+ params: new HTTPParams(_params === null || _params === void 0 ? void 0 : _params.params),
285
+ withCredentials: (_params$withCredentia = _params === null || _params === void 0 ? void 0 : _params.withCredentials) !== null && _params$withCredentia !== void 0 ? _params$withCredentia : false,
286
+ reportProgress: true,
287
+ responseType: (_params$responseType = _params === null || _params === void 0 ? void 0 : _params.responseType) !== null && _params$responseType !== void 0 ? _params$responseType : "json",
288
+ body: ["GET", "DELETE"].includes(method) ? void 0 : _params === null || _params === void 0 ? void 0 : _params.body
289
+ })).pipe((0, rxjs_operators.concatMap)((request) => this._runInterceptorsAndImplementation(request)));
290
+ }
291
+ _runInterceptorsAndImplementation(request) {
292
+ if (!this._pipe) this._pipe = this._interceptors.map((handler) => handler.interceptor).reduceRight((nextHandlerFunction, interceptorFunction) => chainInterceptorFn(nextHandlerFunction, interceptorFunction), (requestFromPrevInterceptor, finalHandler) => finalHandler(requestFromPrevInterceptor));
293
+ return this._pipe(request, (requestToNext) => this._http.send(requestToNext));
294
+ }
295
+ };
296
+ HTTPService = __decorate([__decorateParam(0, IHTTPImplementation)], HTTPService);
297
+ function chainInterceptorFn(afterInterceptorChain, currentInterceptorFn) {
298
+ return (prevRequest, nextHandlerFn) => currentInterceptorFn(prevRequest, (nextRequest) => afterInterceptorChain(nextRequest, nextHandlerFn));
299
+ }
300
+
301
+ //#endregion
302
+ //#region src/services/http/http.ts
303
+ /**
304
+ * Http status codes.
305
+ *
306
+ * https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
307
+ */
308
+ let HTTPStatusCode = /* @__PURE__ */ function(HTTPStatusCode) {
309
+ HTTPStatusCode[HTTPStatusCode["Continue"] = 100] = "Continue";
310
+ HTTPStatusCode[HTTPStatusCode["SwitchingProtocols"] = 101] = "SwitchingProtocols";
311
+ HTTPStatusCode[HTTPStatusCode["Processing"] = 102] = "Processing";
312
+ HTTPStatusCode[HTTPStatusCode["EarlyHints"] = 103] = "EarlyHints";
313
+ HTTPStatusCode[HTTPStatusCode["Ok"] = 200] = "Ok";
314
+ HTTPStatusCode[HTTPStatusCode["Created"] = 201] = "Created";
315
+ HTTPStatusCode[HTTPStatusCode["Accepted"] = 202] = "Accepted";
316
+ HTTPStatusCode[HTTPStatusCode["NonAuthoritativeInformation"] = 203] = "NonAuthoritativeInformation";
317
+ HTTPStatusCode[HTTPStatusCode["NoContent"] = 204] = "NoContent";
318
+ HTTPStatusCode[HTTPStatusCode["ResetContent"] = 205] = "ResetContent";
319
+ HTTPStatusCode[HTTPStatusCode["PartialContent"] = 206] = "PartialContent";
320
+ HTTPStatusCode[HTTPStatusCode["MultiStatus"] = 207] = "MultiStatus";
321
+ HTTPStatusCode[HTTPStatusCode["AlreadyReported"] = 208] = "AlreadyReported";
322
+ HTTPStatusCode[HTTPStatusCode["ImUsed"] = 226] = "ImUsed";
323
+ HTTPStatusCode[HTTPStatusCode["MultipleChoices"] = 300] = "MultipleChoices";
324
+ HTTPStatusCode[HTTPStatusCode["MovedPermanently"] = 301] = "MovedPermanently";
325
+ HTTPStatusCode[HTTPStatusCode["Found"] = 302] = "Found";
326
+ HTTPStatusCode[HTTPStatusCode["SeeOther"] = 303] = "SeeOther";
327
+ HTTPStatusCode[HTTPStatusCode["NotModified"] = 304] = "NotModified";
328
+ HTTPStatusCode[HTTPStatusCode["UseProxy"] = 305] = "UseProxy";
329
+ HTTPStatusCode[HTTPStatusCode["Unused"] = 306] = "Unused";
330
+ HTTPStatusCode[HTTPStatusCode["TemporaryRedirect"] = 307] = "TemporaryRedirect";
331
+ HTTPStatusCode[HTTPStatusCode["PermanentRedirect"] = 308] = "PermanentRedirect";
332
+ HTTPStatusCode[HTTPStatusCode["BadRequest"] = 400] = "BadRequest";
333
+ HTTPStatusCode[HTTPStatusCode["Unauthorized"] = 401] = "Unauthorized";
334
+ HTTPStatusCode[HTTPStatusCode["PaymentRequired"] = 402] = "PaymentRequired";
335
+ HTTPStatusCode[HTTPStatusCode["Forbidden"] = 403] = "Forbidden";
336
+ HTTPStatusCode[HTTPStatusCode["NotFound"] = 404] = "NotFound";
337
+ HTTPStatusCode[HTTPStatusCode["MethodNotAllowed"] = 405] = "MethodNotAllowed";
338
+ HTTPStatusCode[HTTPStatusCode["NotAcceptable"] = 406] = "NotAcceptable";
339
+ HTTPStatusCode[HTTPStatusCode["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
340
+ HTTPStatusCode[HTTPStatusCode["RequestTimeout"] = 408] = "RequestTimeout";
341
+ HTTPStatusCode[HTTPStatusCode["Conflict"] = 409] = "Conflict";
342
+ HTTPStatusCode[HTTPStatusCode["Gone"] = 410] = "Gone";
343
+ HTTPStatusCode[HTTPStatusCode["LengthRequired"] = 411] = "LengthRequired";
344
+ HTTPStatusCode[HTTPStatusCode["PreconditionFailed"] = 412] = "PreconditionFailed";
345
+ HTTPStatusCode[HTTPStatusCode["PayloadTooLarge"] = 413] = "PayloadTooLarge";
346
+ HTTPStatusCode[HTTPStatusCode["UriTooLong"] = 414] = "UriTooLong";
347
+ HTTPStatusCode[HTTPStatusCode["UnsupportedMediaType"] = 415] = "UnsupportedMediaType";
348
+ HTTPStatusCode[HTTPStatusCode["RangeNotSatisfiable"] = 416] = "RangeNotSatisfiable";
349
+ HTTPStatusCode[HTTPStatusCode["ExpectationFailed"] = 417] = "ExpectationFailed";
350
+ HTTPStatusCode[HTTPStatusCode["ImATeapot"] = 418] = "ImATeapot";
351
+ HTTPStatusCode[HTTPStatusCode["MisdirectedRequest"] = 421] = "MisdirectedRequest";
352
+ HTTPStatusCode[HTTPStatusCode["UnprocessableEntity"] = 422] = "UnprocessableEntity";
353
+ HTTPStatusCode[HTTPStatusCode["Locked"] = 423] = "Locked";
354
+ HTTPStatusCode[HTTPStatusCode["FailedDependency"] = 424] = "FailedDependency";
355
+ HTTPStatusCode[HTTPStatusCode["TooEarly"] = 425] = "TooEarly";
356
+ HTTPStatusCode[HTTPStatusCode["UpgradeRequired"] = 426] = "UpgradeRequired";
357
+ HTTPStatusCode[HTTPStatusCode["PreconditionRequired"] = 428] = "PreconditionRequired";
358
+ HTTPStatusCode[HTTPStatusCode["TooManyRequests"] = 429] = "TooManyRequests";
359
+ HTTPStatusCode[HTTPStatusCode["RequestHeaderFieldsTooLarge"] = 431] = "RequestHeaderFieldsTooLarge";
360
+ HTTPStatusCode[HTTPStatusCode["UnavailableForLegalReasons"] = 451] = "UnavailableForLegalReasons";
361
+ HTTPStatusCode[HTTPStatusCode["InternalServerError"] = 500] = "InternalServerError";
362
+ HTTPStatusCode[HTTPStatusCode["NotImplemented"] = 501] = "NotImplemented";
363
+ HTTPStatusCode[HTTPStatusCode["BadGateway"] = 502] = "BadGateway";
364
+ HTTPStatusCode[HTTPStatusCode["ServiceUnavailable"] = 503] = "ServiceUnavailable";
365
+ HTTPStatusCode[HTTPStatusCode["GatewayTimeout"] = 504] = "GatewayTimeout";
366
+ HTTPStatusCode[HTTPStatusCode["HttpVersionNotSupported"] = 505] = "HttpVersionNotSupported";
367
+ HTTPStatusCode[HTTPStatusCode["VariantAlsoNegotiates"] = 506] = "VariantAlsoNegotiates";
368
+ HTTPStatusCode[HTTPStatusCode["InsufficientStorage"] = 507] = "InsufficientStorage";
369
+ HTTPStatusCode[HTTPStatusCode["LoopDetected"] = 508] = "LoopDetected";
370
+ HTTPStatusCode[HTTPStatusCode["NotExtended"] = 510] = "NotExtended";
371
+ HTTPStatusCode[HTTPStatusCode["NetworkAuthenticationRequired"] = 511] = "NetworkAuthenticationRequired";
372
+ return HTTPStatusCode;
373
+ }({});
374
+
375
+ //#endregion
376
+ //#region src/services/http/response.ts
377
+ let HTTPEventType = /* @__PURE__ */ function(HTTPEventType) {
378
+ HTTPEventType[HTTPEventType["DownloadProgress"] = 0] = "DownloadProgress";
379
+ HTTPEventType[HTTPEventType["Response"] = 1] = "Response";
380
+ return HTTPEventType;
381
+ }({});
382
+ /**
383
+ * Wraps success response info.
384
+ */
385
+ var HTTPResponse = class {
386
+ constructor({ body, headers, status, statusText }) {
387
+ _defineProperty(this, "type", HTTPEventType.Response);
388
+ _defineProperty(this, "body", void 0);
389
+ _defineProperty(this, "headers", void 0);
390
+ _defineProperty(this, "status", void 0);
391
+ _defineProperty(this, "statusText", void 0);
392
+ this.body = body;
393
+ this.headers = headers;
394
+ this.status = status;
395
+ this.statusText = statusText;
396
+ }
397
+ };
398
+ /**
399
+ * Progress event for HTTP request. Usually used for reporting download/upload progress or SSE streaming.
400
+ */
401
+ var HTTPProgress = class {
402
+ constructor(total, loaded, partialText) {
403
+ this.total = total;
404
+ this.loaded = loaded;
405
+ this.partialText = partialText;
406
+ _defineProperty(this, "type", HTTPEventType.DownloadProgress);
407
+ }
408
+ };
409
+ var ResponseHeader = class {
410
+ constructor(headers, status, statusText) {
411
+ this.headers = headers;
412
+ this.status = status;
413
+ this.statusText = statusText;
414
+ }
415
+ };
416
+ var HTTPResponseError = class {
417
+ constructor({ request, headers, status, statusText, error }) {
418
+ _defineProperty(this, "request", void 0);
419
+ _defineProperty(this, "headers", void 0);
420
+ _defineProperty(this, "status", void 0);
421
+ _defineProperty(this, "statusText", void 0);
422
+ _defineProperty(this, "error", void 0);
423
+ this.request = request;
424
+ this.headers = headers;
425
+ this.status = status;
426
+ this.statusText = statusText;
427
+ this.error = error;
428
+ }
429
+ };
430
+
431
+ //#endregion
432
+ //#region src/services/http/implementations/util.ts
433
+ function parseFetchParamsFromRequest(request) {
434
+ return {
435
+ method: request.method,
436
+ headers: request.getHeadersInit(),
437
+ body: request.getBody(),
438
+ credentials: request.withCredentials ? "include" : void 0
439
+ };
440
+ }
441
+
442
+ //#endregion
443
+ //#region src/services/http/implementations/fetch.ts
444
+ let FetchHTTPImplementation = class FetchHTTPImplementation {
445
+ constructor(_logService) {
446
+ this._logService = _logService;
447
+ }
448
+ send(request) {
449
+ return new rxjs.Observable((subscriber) => {
450
+ const abortController = new AbortController();
451
+ this._send(request, subscriber, abortController).catch((error) => {
452
+ subscriber.error(new HTTPResponseError({
453
+ error,
454
+ request
455
+ }));
456
+ });
457
+ return () => abortController.abort();
458
+ });
459
+ }
460
+ async _send(request, subscriber, abortController) {
461
+ let response;
462
+ try {
463
+ const fetchParams = parseFetchParamsFromRequest(request);
464
+ const urlWithParams = request.getUrlWithParams();
465
+ const fetchPromise = fetch(urlWithParams, {
466
+ signal: abortController.signal,
467
+ ...fetchParams
468
+ });
469
+ this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${urlWithParams} with params ${fetchParams}`);
470
+ response = await fetchPromise;
471
+ } catch (error) {
472
+ var _error$status, _error$statusText;
473
+ const e = new HTTPResponseError({
474
+ request,
475
+ error,
476
+ status: (_error$status = error.status) !== null && _error$status !== void 0 ? _error$status : 0,
477
+ statusText: (_error$statusText = error.statusText) !== null && _error$statusText !== void 0 ? _error$statusText : "Unknown Error",
478
+ headers: error.headers
479
+ });
480
+ this._logService.error("[FetchHTTPImplementation]: network error", e);
481
+ subscriber.error(e);
482
+ return;
483
+ }
484
+ const responseHeaders = new HTTPHeaders(response.headers);
485
+ const status = response.status;
486
+ const statusText = response.statusText;
487
+ let body = null;
488
+ if (response.body) body = await this._readBody(request, response, subscriber);
489
+ if (status >= HTTPStatusCode.Ok && status < HTTPStatusCode.MultipleChoices) subscriber.next(new HTTPResponse({
490
+ body,
491
+ headers: responseHeaders,
492
+ status,
493
+ statusText
494
+ }));
495
+ else {
496
+ const e = new HTTPResponseError({
497
+ request,
498
+ error: body,
499
+ status,
500
+ statusText,
501
+ headers: responseHeaders
502
+ });
503
+ this._logService.error("[FetchHTTPImplementation]: network error", e);
504
+ subscriber.error(e);
505
+ }
506
+ subscriber.complete();
507
+ }
508
+ async _readBody(request, response, subscriber) {
509
+ var _request$requestParam;
510
+ const chunks = [];
511
+ const reader = response.body.getReader();
512
+ const contentLength = response.headers.get("content-length");
513
+ let receivedLength = 0;
514
+ const reportProgress = (_request$requestParam = request.requestParams) === null || _request$requestParam === void 0 ? void 0 : _request$requestParam.reportProgress;
515
+ const responseType = request.responseType;
516
+ let partialText;
517
+ let decoder;
518
+ while (true) {
519
+ const { done, value } = await reader.read();
520
+ if (done) break;
521
+ chunks.push(value);
522
+ receivedLength += value.length;
523
+ if (reportProgress && responseType === "text") {
524
+ var _partialText, _decoder;
525
+ partialText = ((_partialText = partialText) !== null && _partialText !== void 0 ? _partialText : "") + ((_decoder = decoder) !== null && _decoder !== void 0 ? _decoder : decoder = new TextDecoder()).decode(value, { stream: true });
526
+ subscriber.next(new HTTPProgress(contentLength ? Number.parseInt(contentLength, 10) : void 0, receivedLength, partialText));
527
+ }
528
+ }
529
+ const all = mergeChunks(chunks, receivedLength);
530
+ try {
531
+ var _response$headers$get;
532
+ return deserialize(request, all, (_response$headers$get = response.headers.get("content-type")) !== null && _response$headers$get !== void 0 ? _response$headers$get : "");
533
+ } catch (error) {
534
+ const e = new HTTPResponseError({
535
+ request,
536
+ error,
537
+ status: response.status,
538
+ statusText: response.statusText,
539
+ headers: new HTTPHeaders(response.headers)
540
+ });
541
+ this._logService.error("[FetchHTTPImplementation]: network error", e);
542
+ subscriber.error(e);
543
+ return null;
544
+ }
545
+ }
546
+ };
547
+ FetchHTTPImplementation = __decorate([__decorateParam(0, _univerjs_core.ILogService)], FetchHTTPImplementation);
548
+ function mergeChunks(chunks, totalLength) {
549
+ const all = new Uint8Array(totalLength);
550
+ let position = 0;
551
+ for (const chunk of chunks) {
552
+ all.set(chunk, position);
553
+ position += chunk.length;
554
+ }
555
+ return all;
556
+ }
557
+ const XSSI_PREFIX = /^\)\]\}',?\n/;
558
+ function deserialize(request, bin, contentType) {
559
+ switch (request.responseType) {
560
+ case "json":
561
+ const text = new TextDecoder().decode(bin).replace(XSSI_PREFIX, "");
562
+ return text === "" ? null : JSON.parse(text);
563
+ case "text": return new TextDecoder().decode(bin);
564
+ case "blob": return new Blob([bin.buffer], { type: contentType });
565
+ case "arraybuffer": return bin.buffer;
566
+ default: throw new Error(`[FetchHTTPImplementation]: unknown response type: ${request.responseType}.`);
567
+ }
568
+ }
569
+
570
+ //#endregion
571
+ //#region src/services/http/implementations/xhr.ts
572
+ let XHRHTTPImplementation = class XHRHTTPImplementation {
573
+ constructor(_logService) {
574
+ this._logService = _logService;
575
+ }
576
+ send(request) {
577
+ return new rxjs.Observable((observer) => {
578
+ const xhr = new XMLHttpRequest();
579
+ const urlWithParams = request.getUrlWithParams();
580
+ const fetchParams = parseFetchParamsFromRequest(request);
581
+ const { responseType } = request;
582
+ xhr.open(request.method, urlWithParams);
583
+ if (request.withCredentials) xhr.withCredentials = true;
584
+ if (fetchParams.headers) Object.entries(fetchParams.headers).forEach(([key, value]) => xhr.setRequestHeader(key, value));
585
+ const buildResponseHeader = () => {
586
+ const statusText = xhr.statusText || "OK";
587
+ return new ResponseHeader(new HTTPHeaders(xhr.getAllResponseHeaders()), xhr.status, statusText);
588
+ };
589
+ const onLoadHandler = () => {
590
+ const { headers, statusText, status } = buildResponseHeader();
591
+ let body = null;
592
+ let error = null;
593
+ if (status !== HTTPStatusCode.NoContent) body = typeof xhr.response === "undefined" ? xhr.responseText : xhr.response;
594
+ let success = status >= 200 && status < 300;
595
+ if (responseType === "json" && typeof body === "string") {
596
+ const originalBody = body;
597
+ try {
598
+ body = body ? JSON.parse(body) : null;
599
+ } catch (e) {
600
+ success = false;
601
+ body = originalBody;
602
+ error = e;
603
+ }
604
+ }
605
+ if (responseType === "blob" && !(body instanceof Blob)) {
606
+ success = false;
607
+ error = /* @__PURE__ */ new Error("Response is not a Blob object");
608
+ }
609
+ if (success) observer.next(new HTTPResponse({
610
+ body,
611
+ headers,
612
+ status,
613
+ statusText
614
+ }));
615
+ else {
616
+ const e = new HTTPResponseError({
617
+ request,
618
+ error,
619
+ headers,
620
+ status,
621
+ statusText
622
+ });
623
+ this._logService.error("[XHRHTTPImplementation]: network error", e);
624
+ observer.error(e);
625
+ }
626
+ };
627
+ const onErrorHandler = (error) => {
628
+ const e = new HTTPResponseError({
629
+ request,
630
+ error,
631
+ status: xhr.status || 0,
632
+ statusText: xhr.statusText || "Unknown Error",
633
+ headers: buildResponseHeader().headers
634
+ });
635
+ this._logService.error("[XHRHTTPImplementation]: network error", e);
636
+ observer.error(e);
637
+ };
638
+ xhr.responseType = responseType || "";
639
+ xhr.addEventListener("load", onLoadHandler);
640
+ xhr.addEventListener("error", onErrorHandler);
641
+ xhr.addEventListener("abort", onErrorHandler);
642
+ xhr.addEventListener("timeout", onErrorHandler);
643
+ const body = request.getBody();
644
+ xhr.send(body);
645
+ this._logService.debug("[XHRHTTPImplementation]", `sending request to url ${urlWithParams} with params ${fetchParams}`);
646
+ return () => {
647
+ if (xhr.readyState !== xhr.DONE) xhr.abort();
648
+ xhr.removeEventListener("load", onLoadHandler);
649
+ xhr.removeEventListener("error", onErrorHandler);
650
+ xhr.removeEventListener("abort", onErrorHandler);
651
+ xhr.removeEventListener("timeout", onErrorHandler);
652
+ };
653
+ });
654
+ }
655
+ };
656
+ XHRHTTPImplementation = __decorate([__decorateParam(0, _univerjs_core.ILogService)], XHRHTTPImplementation);
657
+
658
+ //#endregion
659
+ //#region src/plugin.ts
660
+ let UniverNetworkPlugin = class UniverNetworkPlugin extends _univerjs_core.Plugin {
661
+ constructor(_config = defaultPluginConfig, _logger, _injector, _configService) {
662
+ super();
663
+ this._config = _config;
664
+ this._logger = _logger;
665
+ this._injector = _injector;
666
+ this._configService = _configService;
667
+ const { ...rest } = (0, _univerjs_core.merge)({}, defaultPluginConfig, this._config);
668
+ this._configService.setConfig(NETWORK_PLUGIN_CONFIG_KEY, rest);
669
+ }
670
+ onStarting() {
671
+ var _this$_config, _this$_config2, _this$_config3;
672
+ if (this._injector.get(HTTPService, _univerjs_core.Quantity.OPTIONAL, _univerjs_core.LookUp.SKIP_SELF) && !((_this$_config = this._config) === null || _this$_config === void 0 ? void 0 : _this$_config.forceUseNewInstance)) {
673
+ this._logger.warn("[UniverNetworkPlugin]", "HTTPService is already registered in an ancestor interceptor. Skipping registration. If you want to force a new instance, set \"forceUseNewInstance\" to true in the plugin configuration.");
674
+ return;
675
+ }
676
+ const impl = ((_this$_config2 = this._config) === null || _this$_config2 === void 0 ? void 0 : _this$_config2.useFetchImpl) ? FetchHTTPImplementation : typeof window !== "undefined" ? XHRHTTPImplementation : FetchHTTPImplementation;
677
+ (0, _univerjs_core.registerDependencies)(this._injector, (0, _univerjs_core.mergeOverrideWithDependencies)([[HTTPService], [IHTTPImplementation, { useClass: impl }]], (_this$_config3 = this._config) === null || _this$_config3 === void 0 ? void 0 : _this$_config3.override));
678
+ }
679
+ };
680
+ _defineProperty(UniverNetworkPlugin, "pluginName", "UNIVER_NETWORK_PLUGIN");
681
+ _defineProperty(UniverNetworkPlugin, "packageName", name);
682
+ _defineProperty(UniverNetworkPlugin, "version", version);
683
+ UniverNetworkPlugin = __decorate([
684
+ __decorateParam(1, _univerjs_core.ILogService),
685
+ __decorateParam(2, (0, _univerjs_core.Inject)(_univerjs_core.Injector)),
686
+ __decorateParam(3, _univerjs_core.IConfigService)
687
+ ], UniverNetworkPlugin);
688
+
689
+ //#endregion
690
+ //#region src/services/http/interceptors/auth-interceptor.ts
691
+ const AuthInterceptorFactory = (params) => {
692
+ const { errorStatusCodes, onAuthError } = params;
693
+ const authInterceptor = (request, next) => {
694
+ return next(request).pipe((0, rxjs.catchError)((error) => {
695
+ if (error instanceof HTTPResponseError && errorStatusCodes.some((c) => c === error.status)) onAuthError();
696
+ return (0, rxjs.throwError)(() => error);
697
+ }));
698
+ };
699
+ return authInterceptor;
700
+ };
701
+
702
+ //#endregion
703
+ //#region src/services/http/interceptors/merge-interceptor.ts
704
+ const createDefaultFetchCheck = (time = 300) => {
705
+ const noop = () => {};
706
+ let cancel = noop;
707
+ return (_currentConfig) => {
708
+ return new Promise((res) => {
709
+ cancel();
710
+ const t = setTimeout(() => {
711
+ res(true);
712
+ }, time);
713
+ cancel = () => {
714
+ clearTimeout(t);
715
+ res(false);
716
+ };
717
+ });
718
+ };
719
+ };
720
+ const createDistributeResult = () => {
721
+ return (result, list) => {
722
+ return list.map((config) => ({
723
+ config,
724
+ result
725
+ }));
726
+ };
727
+ };
728
+ const MergeInterceptorFactory = (config, options = {}) => {
729
+ const { isMatch, getParamsFromRequest, mergeParamsToRequest } = config;
730
+ const { fetchCheck = createDefaultFetchCheck(300), distributeResult = createDistributeResult() } = options;
731
+ const hookList = [];
732
+ const getPlainList = (_list) => _list.map((item) => item.config);
733
+ return (requestConfig, next) => {
734
+ if (!isMatch(requestConfig)) return next(requestConfig);
735
+ return new rxjs.Observable((observer) => {
736
+ const params = getParamsFromRequest(requestConfig);
737
+ hookList.push({
738
+ next: (v) => observer.next(v),
739
+ error: (error) => observer.error(error),
740
+ config: params
741
+ });
742
+ const list = getPlainList(hookList);
743
+ fetchCheck(requestConfig).then((isFetch) => {
744
+ if (isFetch) {
745
+ const currentHookList = [];
746
+ list.forEach((config) => {
747
+ const index = hookList.findIndex((item) => item.config === config);
748
+ if (index >= 0) {
749
+ const [hook] = hookList.splice(index, 1);
750
+ currentHookList.push(hook);
751
+ }
752
+ });
753
+ next(mergeParamsToRequest(list, requestConfig)).subscribe({
754
+ next: (e) => {
755
+ if (e.type === HTTPEventType.Response) {
756
+ const body = e.body;
757
+ const configList = distributeResult(body, list);
758
+ currentHookList.forEach((hookItem) => {
759
+ const res = configList.find((item) => item.config === hookItem.config);
760
+ if (res) {
761
+ const response = new HTTPResponse({
762
+ body: res.result,
763
+ headers: e.headers,
764
+ status: e.status,
765
+ statusText: e.statusText
766
+ });
767
+ hookItem.next(response);
768
+ } else hookItem.error("batch error");
769
+ });
770
+ }
771
+ },
772
+ complete: () => observer.complete(),
773
+ error: (e) => observer.error(e)
774
+ });
775
+ }
776
+ });
777
+ });
778
+ };
779
+ };
780
+
781
+ //#endregion
782
+ //#region src/services/http/interceptors/retry-interceptor.ts
783
+ const DEFAULT_MAX_RETRY_ATTEMPTS = 3;
784
+ const DELAY_INTERVAL = 1e3;
785
+ const RetryInterceptorFactory = (params) => {
786
+ var _params$maxRetryAttem, _params$delayInterval;
787
+ const maxRetryAttempts = (_params$maxRetryAttem = params === null || params === void 0 ? void 0 : params.maxRetryAttempts) !== null && _params$maxRetryAttem !== void 0 ? _params$maxRetryAttem : DEFAULT_MAX_RETRY_ATTEMPTS;
788
+ const delayInterval = (_params$delayInterval = params === null || params === void 0 ? void 0 : params.delayInterval) !== null && _params$delayInterval !== void 0 ? _params$delayInterval : DELAY_INTERVAL;
789
+ return (request, next) => next(request).pipe((0, rxjs_operators.retry)({
790
+ delay: delayInterval,
791
+ count: maxRetryAttempts
792
+ }));
793
+ };
794
+
795
+ //#endregion
796
+ //#region src/services/http/interceptors/threshold-interceptor.ts
797
+ const ThresholdInterceptorFactory = (params) => {
798
+ /**
799
+ * The local variable to store handles.
800
+ */
801
+ const handlers = [];
802
+ const ongoingHandlers = /* @__PURE__ */ new Set();
803
+ const tick = () => {
804
+ var _params$maxParallel;
805
+ while (ongoingHandlers.size < ((_params$maxParallel = params === null || params === void 0 ? void 0 : params.maxParallel) !== null && _params$maxParallel !== void 0 ? _params$maxParallel : 1) && handlers.length > 0) {
806
+ const handler = handlers.shift();
807
+ ongoingHandlers.add(handler);
808
+ handler();
809
+ }
810
+ };
811
+ return (request, next) => {
812
+ return new rxjs.Observable((observer) => {
813
+ const handler = () => next(request).subscribe({
814
+ next: (event) => observer.next(event),
815
+ error: (err) => observer.error(err),
816
+ complete: () => observer.complete()
817
+ });
818
+ const teardown = () => {
819
+ ongoingHandlers.delete(handler);
820
+ (0, _univerjs_core.remove)(handlers, handler);
821
+ tick();
822
+ };
823
+ handlers.push(handler);
824
+ tick();
825
+ return teardown;
826
+ });
827
+ };
828
+ };
829
+
830
+ //#endregion
831
+ //#region src/services/web-socket/web-socket.service.ts
832
+ /**
833
+ * This service is responsible for establishing bidi-directional connection to a remote server.
834
+ */
835
+ const ISocketService = (0, _univerjs_core.createIdentifier)("univer.network.socket.service");
836
+ /**
837
+ * This service create a WebSocket connection to a remote server.
838
+ */
839
+ var WebSocketService = class extends _univerjs_core.Disposable {
840
+ createSocket(URL) {
841
+ try {
842
+ const connection = new WebSocket(URL);
843
+ const disposables = new _univerjs_core.DisposableCollection();
844
+ return {
845
+ URL,
846
+ close: (code, reason) => {
847
+ connection.close(code, reason);
848
+ disposables.dispose();
849
+ },
850
+ send: (data) => {
851
+ connection.send(data);
852
+ },
853
+ open$: new rxjs.Observable((subscriber) => {
854
+ const callback = (event) => subscriber.next(event);
855
+ connection.addEventListener("open", callback);
856
+ disposables.add((0, _univerjs_core.toDisposable)(() => connection.removeEventListener("open", callback)));
857
+ }).pipe((0, rxjs_operators.share)()),
858
+ close$: new rxjs.Observable((subscriber) => {
859
+ const callback = (event) => subscriber.next(event);
860
+ connection.addEventListener("close", callback);
861
+ disposables.add((0, _univerjs_core.toDisposable)(() => connection.removeEventListener("close", callback)));
862
+ }).pipe((0, rxjs_operators.share)()),
863
+ error$: new rxjs.Observable((subscriber) => {
864
+ const callback = (event) => subscriber.next(event);
865
+ connection.addEventListener("error", callback);
866
+ disposables.add((0, _univerjs_core.toDisposable)(() => connection.removeEventListener("error", callback)));
867
+ }).pipe((0, rxjs_operators.share)()),
868
+ message$: new rxjs.Observable((subscriber) => {
869
+ const callback = (event) => subscriber.next(event);
870
+ connection.addEventListener("message", callback);
871
+ disposables.add((0, _univerjs_core.toDisposable)(() => connection.removeEventListener("message", callback)));
872
+ }).pipe((0, rxjs_operators.share)())
873
+ };
874
+ } catch (e) {
875
+ console.error(e);
876
+ return null;
877
+ }
878
+ }
879
+ };
880
+
881
+ //#endregion
882
+ exports.AuthInterceptorFactory = AuthInterceptorFactory;
883
+ Object.defineProperty(exports, 'FetchHTTPImplementation', {
884
+ enumerable: true,
885
+ get: function () {
886
+ return FetchHTTPImplementation;
887
+ }
888
+ });
889
+ exports.HTTPEventType = HTTPEventType;
890
+ exports.HTTPHeaders = HTTPHeaders;
891
+ exports.HTTPProgress = HTTPProgress;
892
+ exports.HTTPRequest = HTTPRequest;
893
+ exports.HTTPResponse = HTTPResponse;
894
+ exports.HTTPResponseError = HTTPResponseError;
895
+ Object.defineProperty(exports, 'HTTPService', {
896
+ enumerable: true,
897
+ get: function () {
898
+ return HTTPService;
899
+ }
900
+ });
901
+ exports.HTTPStatusCode = HTTPStatusCode;
902
+ exports.IHTTPImplementation = IHTTPImplementation;
903
+ exports.ISocketService = ISocketService;
904
+ exports.MergeInterceptorFactory = MergeInterceptorFactory;
905
+ exports.ResponseHeader = ResponseHeader;
906
+ exports.RetryInterceptorFactory = RetryInterceptorFactory;
907
+ exports.ThresholdInterceptorFactory = ThresholdInterceptorFactory;
908
+ Object.defineProperty(exports, 'UniverNetworkPlugin', {
909
+ enumerable: true,
910
+ get: function () {
911
+ return UniverNetworkPlugin;
912
+ }
913
+ });
914
+ exports.WebSocketService = WebSocketService;
915
+ Object.defineProperty(exports, 'XHRHTTPImplementation', {
916
+ enumerable: true,
917
+ get: function () {
918
+ return XHRHTTPImplementation;
919
+ }
920
+ });