@univerjs/network 0.2.9 → 0.2.11
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
1
|
"use strict";var __defProp=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!="symbol"?key+"":key,value);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const core=require("@univerjs/core"),rxjs=require("rxjs"),operators=require("rxjs/operators"),ApplicationJSONType="application/json",_HTTPHeaders=class _HTTPHeaders{constructor(headers){__publicField(this,"_headers",new Map);typeof headers=="string"?this._handleHeadersString(headers):headers instanceof Headers?this._handleHeaders(headers):headers&&this._handleHeadersConstructorProps(headers)}forEach(callback){this._headers.forEach((v,key)=>callback(key,v))}has(key){return!!this._headers.has(key.toLowerCase())}get(key){const k=key.toLowerCase();return this._headers.has(k)?this._headers.get(k):null}toHeadersInit(){var _a2,_b;const headers={};return this._headers.forEach((values,key)=>{headers[key]=values.join(",")}),(_a2=headers.accept)!=null||(headers.accept="application/json, text/plain, */*"),(_b=headers["content-type"])!=null||(headers["content-type"]="application/json;charset=UTF-8"),headers}_setHeader(name,value){const lowerCase=name.toLowerCase();this._headers.has(lowerCase)?this._headers.get(lowerCase).push(value.toString()):this._headers.set(lowerCase,[value.toString()])}_handleHeadersString(headers){headers.split(`
|
|
2
|
-
`).forEach(header=>{const[name,value]=header.split(":");name&&value&&this._setHeader(name,value)})}_handleHeadersConstructorProps(headers){Object.entries(headers).forEach(([name,value])=>this._setHeader(name,value))}_handleHeaders(headers){headers.forEach((value,name)=>this._setHeader(name,value))}};__name(_HTTPHeaders,"HTTPHeaders");let HTTPHeaders=_HTTPHeaders;const IHTTPImplementation=core.createIdentifier("network.http-implementation"),_HTTPParams=class _HTTPParams{constructor(params){this.params=params}toString(){return this.params?Object.keys(this.params).map(key=>`${key}=${this.params[key]}`).join("&"):""}};__name(_HTTPParams,"HTTPParams");let HTTPParams=_HTTPParams,HTTPRequestUID=0;const _HTTPRequest=class _HTTPRequest{constructor(method,url,requestParams){__publicField(this,"uid",HTTPRequestUID++);this.method=method,this.url=url,this.requestParams=requestParams}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var _a2,_b;const params=(_b=(_a2=this.requestParams)==null?void 0:_a2.params)==null?void 0:_b.toString();return params?`${this.url}${this.url.includes("?")?"&":"?"}${params}`:this.url}getBody(){var _a2,_b;const contentType=(_a2=this.headers.get("Content-Type"))!=null?_a2:ApplicationJSONType,body=(_b=this.requestParams)==null?void 0:_b.body;return contentType===ApplicationJSONType&&body&&typeof body=="object"?JSON.stringify(body):body?`${body}`:null}getHeadersInit(){return this.headers.toHeadersInit()}};__name(_HTTPRequest,"HTTPRequest");let HTTPRequest=_HTTPRequest;var __defProp2=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp2(target,key,result),result},"__decorateClass"),__decorateParam=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam"),_a;exports.HTTPService=(_a=class extends core.Disposable{constructor(_http){super();__publicField(this,"_interceptors",[]);__publicField(this,"_pipe");this._http=_http}registerHTTPInterceptor(interceptor){if(this._interceptors.indexOf(interceptor)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(interceptor),this._interceptors=this._interceptors.sort((a,b)=>{var _a2,_b;return((_a2=a.priority)!=null?_a2:0)-((_b=b.priority)!=null?_b:0)}),this._pipe=null,core.toDisposable(()=>core.remove(this._interceptors,interceptor))}get(url,params){return this._request("GET",url,params)}post(url,params){return this._request("POST",url,params)}put(url,params){return this._request("PUT",url,params)}delete(url,params){return this._request("DELETE",url,params)}patch(url,options){return this._request("PATCH",url,options)}getSSE(method,url,options){var _a2,_b;const headers=new HTTPHeaders(options==null?void 0:options.headers),params=new HTTPParams(options==null?void 0:options.params),request=new HTTPRequest(method,url,{headers,params,withCredentials:(_a2=options==null?void 0:options.withCredentials)!=null?_a2:!1,reportProgress:!0,responseType:(_b=options==null?void 0:options.responseType)!=null?_b:"json",body:["GET","DELETE"].includes(method)||options==null?void 0:options.body});return rxjs.of(request).pipe(operators.concatMap(request2=>this._runInterceptorsAndImplementation(request2)))}async _request(method,url,options){var _a2,_b;const headers=new HTTPHeaders(options==null?void 0:options.headers),params=new HTTPParams(options==null?void 0:options.params),request=new HTTPRequest(method,url,{headers,params,withCredentials:(_a2=options==null?void 0:options.withCredentials)!=null?_a2:!1,responseType:(_b=options==null?void 0:options.responseType)!=null?_b:"json",body:["GET","DELETE"].includes(method)||options==null?void 0:options.body}),events$=rxjs.of(request).pipe(operators.concatMap(request2=>this._runInterceptorsAndImplementation(request2)));return await rxjs.firstValueFrom(events$)}_runInterceptorsAndImplementation(request){return this._pipe||(this._pipe=this._interceptors.map(handler=>handler.interceptor).reduceRight((nextHandlerFunction,interceptorFunction)=>chainInterceptorFn(nextHandlerFunction,interceptorFunction),(requestFromPrevInterceptor,finalHandler)=>finalHandler(requestFromPrevInterceptor))),this._pipe(request,requestToNext=>this._http.send(requestToNext))}},__name(_a,"HTTPService"),_a);exports.HTTPService=__decorateClass([__decorateParam(0,IHTTPImplementation)],exports.HTTPService);function chainInterceptorFn(afterInterceptorChain,currentInterceptorFn){return(prevRequest,nextHandlerFn)=>currentInterceptorFn(prevRequest,nextRequest=>afterInterceptorChain(nextRequest,nextHandlerFn))}__name(chainInterceptorFn,"chainInterceptorFn");var HTTPEventType=(HTTPEventType2=>(HTTPEventType2[HTTPEventType2.DownloadProgress=0]="DownloadProgress",HTTPEventType2[HTTPEventType2.Response=1]="Response",HTTPEventType2))(HTTPEventType||{});const _HTTPResponse=class _HTTPResponse{constructor({body,headers,status,statusText}){__publicField(this,"type",1);__publicField(this,"body");__publicField(this,"headers");__publicField(this,"status");__publicField(this,"statusText");this.body=body,this.headers=headers,this.status=status,this.statusText=statusText}};__name(_HTTPResponse,"HTTPResponse");let HTTPResponse=_HTTPResponse;const _HTTPProgress=class _HTTPProgress{constructor(total,loaded,partialText){__publicField(this,"type",0);this.total=total,this.loaded=loaded,this.partialText=partialText}};__name(_HTTPProgress,"HTTPProgress");let HTTPProgress=_HTTPProgress;const _ResponseHeader=class _ResponseHeader{constructor(headers,status,statusText){this.headers=headers,this.status=status,this.statusText=statusText}};__name(_ResponseHeader,"ResponseHeader");let ResponseHeader=_ResponseHeader;const _HTTPResponseError=class _HTTPResponseError{constructor({headers,status,statusText,error}){__publicField(this,"headers");__publicField(this,"status");__publicField(this,"statusText");__publicField(this,"error");this.headers=headers,this.status=status,this.statusText=statusText,this.error=error}};__name(_HTTPResponseError,"HTTPResponseError");let HTTPResponseError=_HTTPResponseError;const SuccessStatusCodeLowerBound=200,ErrorStatusCodeLowerBound=300;var HTTPStatusCode=(HTTPStatusCode2=>(HTTPStatusCode2[HTTPStatusCode2.Continue=100]="Continue",HTTPStatusCode2[HTTPStatusCode2.SwitchingProtocols=101]="SwitchingProtocols",HTTPStatusCode2[HTTPStatusCode2.Processing=102]="Processing",HTTPStatusCode2[HTTPStatusCode2.EarlyHints=103]="EarlyHints",HTTPStatusCode2[HTTPStatusCode2.Ok=200]="Ok",HTTPStatusCode2[HTTPStatusCode2.Created=201]="Created",HTTPStatusCode2[HTTPStatusCode2.Accepted=202]="Accepted",HTTPStatusCode2[HTTPStatusCode2.NonAuthoritativeInformation=203]="NonAuthoritativeInformation",HTTPStatusCode2[HTTPStatusCode2.NoContent=204]="NoContent",HTTPStatusCode2[HTTPStatusCode2.ResetContent=205]="ResetContent",HTTPStatusCode2[HTTPStatusCode2.PartialContent=206]="PartialContent",HTTPStatusCode2[HTTPStatusCode2.MultiStatus=207]="MultiStatus",HTTPStatusCode2[HTTPStatusCode2.AlreadyReported=208]="AlreadyReported",HTTPStatusCode2[HTTPStatusCode2.ImUsed=226]="ImUsed",HTTPStatusCode2[HTTPStatusCode2.MultipleChoices=300]="MultipleChoices",HTTPStatusCode2[HTTPStatusCode2.MovedPermanently=301]="MovedPermanently",HTTPStatusCode2[HTTPStatusCode2.Found=302]="Found",HTTPStatusCode2[HTTPStatusCode2.SeeOther=303]="SeeOther",HTTPStatusCode2[HTTPStatusCode2.NotModified=304]="NotModified",HTTPStatusCode2[HTTPStatusCode2.UseProxy=305]="UseProxy",HTTPStatusCode2[HTTPStatusCode2.Unused=306]="Unused",HTTPStatusCode2[HTTPStatusCode2.TemporaryRedirect=307]="TemporaryRedirect",HTTPStatusCode2[HTTPStatusCode2.PermanentRedirect=308]="PermanentRedirect",HTTPStatusCode2[HTTPStatusCode2.BadRequest=400]="BadRequest",HTTPStatusCode2[HTTPStatusCode2.Unauthorized=401]="Unauthorized",HTTPStatusCode2[HTTPStatusCode2.PaymentRequired=402]="PaymentRequired",HTTPStatusCode2[HTTPStatusCode2.Forbidden=403]="Forbidden",HTTPStatusCode2[HTTPStatusCode2.NotFound=404]="NotFound",HTTPStatusCode2[HTTPStatusCode2.MethodNotAllowed=405]="MethodNotAllowed",HTTPStatusCode2[HTTPStatusCode2.NotAcceptable=406]="NotAcceptable",HTTPStatusCode2[HTTPStatusCode2.ProxyAuthenticationRequired=407]="ProxyAuthenticationRequired",HTTPStatusCode2[HTTPStatusCode2.RequestTimeout=408]="RequestTimeout",HTTPStatusCode2[HTTPStatusCode2.Conflict=409]="Conflict",HTTPStatusCode2[HTTPStatusCode2.Gone=410]="Gone",HTTPStatusCode2[HTTPStatusCode2.LengthRequired=411]="LengthRequired",HTTPStatusCode2[HTTPStatusCode2.PreconditionFailed=412]="PreconditionFailed",HTTPStatusCode2[HTTPStatusCode2.PayloadTooLarge=413]="PayloadTooLarge",HTTPStatusCode2[HTTPStatusCode2.UriTooLong=414]="UriTooLong",HTTPStatusCode2[HTTPStatusCode2.UnsupportedMediaType=415]="UnsupportedMediaType",HTTPStatusCode2[HTTPStatusCode2.RangeNotSatisfiable=416]="RangeNotSatisfiable",HTTPStatusCode2[HTTPStatusCode2.ExpectationFailed=417]="ExpectationFailed",HTTPStatusCode2[HTTPStatusCode2.ImATeapot=418]="ImATeapot",HTTPStatusCode2[HTTPStatusCode2.MisdirectedRequest=421]="MisdirectedRequest",HTTPStatusCode2[HTTPStatusCode2.UnprocessableEntity=422]="UnprocessableEntity",HTTPStatusCode2[HTTPStatusCode2.Locked=423]="Locked",HTTPStatusCode2[HTTPStatusCode2.FailedDependency=424]="FailedDependency",HTTPStatusCode2[HTTPStatusCode2.TooEarly=425]="TooEarly",HTTPStatusCode2[HTTPStatusCode2.UpgradeRequired=426]="UpgradeRequired",HTTPStatusCode2[HTTPStatusCode2.PreconditionRequired=428]="PreconditionRequired",HTTPStatusCode2[HTTPStatusCode2.TooManyRequests=429]="TooManyRequests",HTTPStatusCode2[HTTPStatusCode2.RequestHeaderFieldsTooLarge=431]="RequestHeaderFieldsTooLarge",HTTPStatusCode2[HTTPStatusCode2.UnavailableForLegalReasons=451]="UnavailableForLegalReasons",HTTPStatusCode2[HTTPStatusCode2.InternalServerError=500]="InternalServerError",HTTPStatusCode2[HTTPStatusCode2.NotImplemented=501]="NotImplemented",HTTPStatusCode2[HTTPStatusCode2.BadGateway=502]="BadGateway",HTTPStatusCode2[HTTPStatusCode2.ServiceUnavailable=503]="ServiceUnavailable",HTTPStatusCode2[HTTPStatusCode2.GatewayTimeout=504]="GatewayTimeout",HTTPStatusCode2[HTTPStatusCode2.HttpVersionNotSupported=505]="HttpVersionNotSupported",HTTPStatusCode2[HTTPStatusCode2.VariantAlsoNegotiates=506]="VariantAlsoNegotiates",HTTPStatusCode2[HTTPStatusCode2.InsufficientStorage=507]="InsufficientStorage",HTTPStatusCode2[HTTPStatusCode2.LoopDetected=508]="LoopDetected",HTTPStatusCode2[HTTPStatusCode2.NotExtended=510]="NotExtended",HTTPStatusCode2[HTTPStatusCode2.NetworkAuthenticationRequired=511]="NetworkAuthenticationRequired",HTTPStatusCode2))(HTTPStatusCode||{});const _FetchHTTPImplementation=class _FetchHTTPImplementation{send(request){return new rxjs.Observable(subscriber=>{const abortController=new AbortController;return this._send(request,subscriber,abortController).then(()=>{},error=>{subscriber.error(new HTTPResponseError({error}))}),()=>abortController.abort()})}async _send(request,subscriber,abortController){var _a2,_b;let response;try{const fetchParams=this._parseFetchParamsFromRequest(request);response=await fetch(request.getUrlWithParams(),{signal:abortController.signal,...fetchParams})}catch(error){subscriber.error(new HTTPResponseError({error,status:(_a2=error.status)!=null?_a2:0,statusText:(_b=error.statusText)!=null?_b:"Unknown Error",headers:error.headers}));return}const responseHeaders=new HTTPHeaders(response.headers),status=response.status,statusText=response.statusText;let body=null;response.body&&(body=await this._readBody(request,response,subscriber)),status>=HTTPStatusCode.Ok&&status<HTTPStatusCode.MultipleChoices?subscriber.next(new HTTPResponse({body,headers:responseHeaders,status,statusText})):subscriber.error(new HTTPResponseError({error:body,status,statusText,headers:responseHeaders})),subscriber.complete()}async _readBody(request,response,subscriber){var _a2,_b;const chunks=[],reader=response.body.getReader(),contentLength=response.headers.get("content-length");let receivedLength=0;const reportProgress=(_a2=request.requestParams)==null?void 0:_a2.reportProgress,responseType=request.responseType;let partialText,decoder;for(;;){const{done,value}=await reader.read();if(done)break;chunks.push(value),receivedLength+=value.length,reportProgress&&responseType==="text"&&(partialText=(partialText!=null?partialText:"")+(decoder!=null?decoder:decoder=new TextDecoder).decode(value,{stream:!0}),subscriber.next(new HTTPProgress(contentLength?Number.parseInt(contentLength,10):void 0,receivedLength,partialText)))}const all=mergeChunks(chunks,receivedLength);try{const contentType=(_b=response.headers.get("content-type"))!=null?_b:"";return deserialize(request,all,contentType)}catch(error){return subscriber.error(new HTTPResponseError({error,status:response.status,statusText:response.statusText,headers:new HTTPHeaders(response.headers)})),null}}_parseFetchParamsFromRequest(request){return{method:request.method,headers:request.getHeadersInit(),body:request.getBody(),credentials:request.withCredentials?"include":void 0}}};__name(_FetchHTTPImplementation,"FetchHTTPImplementation");let FetchHTTPImplementation=_FetchHTTPImplementation;function mergeChunks(chunks,totalLength){const all=new Uint8Array(totalLength);let position=0;for(const chunk of chunks)all.set(chunk,position),position+=chunk.length;return all}__name(mergeChunks,"mergeChunks");const XSSI_PREFIX=/^\)\]\}',?\n/;function deserialize(request,bin,contentType){switch(request.responseType){case"json":const text=new TextDecoder().decode(bin).replace(XSSI_PREFIX,"");return text===""?null:JSON.parse(text);case"text":return new TextDecoder().decode(bin);case"blob":return new Blob([bin],{type:contentType});case"arraybuffer":return bin.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${request.responseType}.`)}}__name(deserialize,"deserialize");const _XHRHTTPImplementation=class _XHRHTTPImplementation{send(request){return new rxjs.Observable(observer=>{const xhr=new XMLHttpRequest;xhr.open(request.method,request.getUrlWithParams()),request.withCredentials&&(xhr.withCredentials=!0),request.headers.forEach((key,value)=>xhr.setRequestHeader(key,value.join(","))),request.headers.has("Accept")||xhr.setRequestHeader("Accept","application/json, text/plain, */*"),request.headers.has("Content-Type")||xhr.setRequestHeader("Content-Type","application/json;charset=UTF-8");const buildResponseHeader=__name(()=>{const statusText=xhr.statusText||"OK",headers=new HTTPHeaders(xhr.getAllResponseHeaders());return new ResponseHeader(headers,xhr.status,statusText)},"buildResponseHeader"),onLoadHandler=__name(()=>{const{headers,statusText,status}=buildResponseHeader(),{responseType}=request;let body2=null,error=null;status!==HTTPStatusCode.NoContent&&(body2=typeof xhr.response>"u"?xhr.responseText:xhr.response);let success=status>=SuccessStatusCodeLowerBound&&status<ErrorStatusCodeLowerBound;if(responseType==="json"&&typeof body2=="string"){const originalBody=body2;try{body2=body2?JSON.parse(body2):null}catch(e){success=!1,body2=originalBody,error=e}}success?observer.next(new HTTPResponse({body:body2,headers,status,statusText})):observer.error(new HTTPResponseError({error,headers,status,statusText}))},"onLoadHandler"),onErrorHandler=__name(error=>{const res=new HTTPResponseError({error,status:xhr.status||0,statusText:xhr.statusText||"Unknown Error",headers:buildResponseHeader().headers});observer.error(res)},"onErrorHandler");xhr.addEventListener("load",onLoadHandler),xhr.addEventListener("error",onErrorHandler),xhr.addEventListener("abort",onErrorHandler),xhr.addEventListener("timeout",onErrorHandler);const body=request.getBody();return xhr.send(body),()=>{xhr.readyState!==xhr.DONE&&xhr.abort(),xhr.removeEventListener("load",onLoadHandler),xhr.removeEventListener("error",onErrorHandler),xhr.removeEventListener("abort",onErrorHandler),xhr.removeEventListener("timeout",onErrorHandler)}})}};__name(_XHRHTTPImplementation,"XHRHTTPImplementation");let XHRHTTPImplementation=_XHRHTTPImplementation;const ISocketService=core.createIdentifier("univer.socket"),_WebSocketService=class _WebSocketService extends core.Disposable{createSocket(URL){try{const connection=new WebSocket(URL),disposables=new core.DisposableCollection;return{URL,close:__name((code,reason)=>{connection.close(code,reason),disposables.dispose()},"close"),send:__name(data=>{connection.send(data)},"send"),open$:new rxjs.Observable(subscriber=>{const callback=__name(event=>subscriber.next(event),"callback");connection.addEventListener("open",callback),disposables.add(core.toDisposable(()=>connection.removeEventListener("open",callback)))}).pipe(operators.share()),close$:new rxjs.Observable(subscriber=>{const callback=__name(event=>subscriber.next(event),"callback");connection.addEventListener("close",callback),disposables.add(core.toDisposable(()=>connection.removeEventListener("close",callback)))}).pipe(operators.share()),error$:new rxjs.Observable(subscriber=>{const callback=__name(event=>subscriber.next(event),"callback");connection.addEventListener("error",callback),disposables.add(core.toDisposable(()=>connection.removeEventListener("error",callback)))}).pipe(operators.share()),message$:new rxjs.Observable(subscriber=>{const callback=__name(event=>subscriber.next(event),"callback");connection.addEventListener("message",callback),disposables.add(core.toDisposable(()=>connection.removeEventListener("message",callback)))}).pipe(operators.share())}}catch(e){return console.error(e),null}}};__name(_WebSocketService,"WebSocketService");let WebSocketService=_WebSocketService;const DEFAULT_MAX_RETRY_ATTEMPTS=3,DELAY_INTERVAL=1e3,RetryInterceptorFactory=__name((_accessor,params)=>{var _a2,_b;const maxRetryAttempts=(_a2=params==null?void 0:params.maxRetryAttempts)!=null?_a2:DEFAULT_MAX_RETRY_ATTEMPTS,delayInterval=(_b=params==null?void 0:params.delayInterval)!=null?_b:DELAY_INTERVAL;return(request,next)=>next(request).pipe(operators.retry({delay:delayInterval,count:maxRetryAttempts}))},"RetryInterceptorFactory"),ThresholdInterceptorFactory=__name(params=>{const handlers=[],ongoingHandlers=new Set,tick=__name(()=>{var _a2;for(;ongoingHandlers.size<((_a2=params==null?void 0:params.maxParallel)!=null?_a2:1)&&handlers.length>0;){const handler=handlers.shift();ongoingHandlers.add(handler),handler()}},"tick");return(request,next)=>new rxjs.Observable(observer=>{const handler=__name(()=>next(request).subscribe({next:__name(event=>observer.next(event),"next"),error:__name(err=>observer.next(err),"error"),complete:__name(()=>observer.complete(),"complete")}),"handler"),teardown=__name(()=>{ongoingHandlers.delete(handler),core.remove(handlers,handler),tick()},"teardown");return handlers.push(handler),tick(),teardown})},"ThresholdInterceptorFactory"),AuthInterceptorFactory=__name(params=>{const{errorStatusCodes,onAuthError}=params;return __name((request,next)=>next(request).pipe(rxjs.catchError(error=>(error instanceof HTTPResponseError&&errorStatusCodes.some(c=>c===error.status)&&onAuthError(),rxjs.throwError(()=>error)))),"authInterceptor")},"AuthInterceptorFactory"),createDefaultFetchCheck=__name((time=300)=>{let cancel=__name(()=>{},"noop");return _currentConfig=>new Promise(res=>{cancel();const t=setTimeout(()=>{res(!0)},time);cancel=__name(()=>{clearTimeout(t),res(!1)},"cancel")})},"createDefaultFetchCheck"),createDistributeResult=__name(()=>(result,list)=>list.map(config=>({config,result})),"createDistributeResult"),MergeInterceptorFactory=__name((config,options={})=>{const{isMatch,getParamsFromRequest,mergeParamsToRequest}=config,{fetchCheck=createDefaultFetchCheck(300),distributeResult=createDistributeResult()}=options,hookList=[],getPlainList=__name(_list=>_list.map(item=>item.config),"getPlainList");return(requestConfig,next)=>isMatch(requestConfig)?new rxjs.Observable(observer=>{const params=getParamsFromRequest(requestConfig);hookList.push({next:__name(v=>observer.next(v),"next"),error:__name(error=>observer.error(error),"error"),config:params});const list=getPlainList(hookList);fetchCheck(requestConfig).then(isFetch=>{if(isFetch){const currentHookList=[];list.forEach(config2=>{const index=hookList.findIndex(item=>item.config===config2);if(index>=0){const[hook]=hookList.splice(index,1);currentHookList.push(hook)}}),next(mergeParamsToRequest(list,requestConfig)).subscribe({next:__name(e=>{if(e.type===HTTPEventType.Response){const body=e.body,configList=distributeResult(body,list);currentHookList.forEach(hookItem=>{const res=configList.find(item=>item.config===hookItem.config);if(res){const response=new HTTPResponse({body:res.result,headers:e.headers,status:e.status,statusText:e.statusText});hookItem.next(response)}else hookItem.error("batch error")})}},"next"),complete:__name(()=>observer.complete(),"complete"),error:__name(e=>observer.error(e),"error")})}})}):next(requestConfig)},"MergeInterceptorFactory");exports.AuthInterceptorFactory=AuthInterceptorFactory;exports.FetchHTTPImplementation=FetchHTTPImplementation;exports.HTTPEventType=HTTPEventType;exports.HTTPHeaders=HTTPHeaders;exports.HTTPProgress=HTTPProgress;exports.HTTPRequest=HTTPRequest;exports.HTTPResponse=HTTPResponse;exports.HTTPResponseError=HTTPResponseError;exports.HTTPStatusCode=HTTPStatusCode;exports.IHTTPImplementation=IHTTPImplementation;exports.ISocketService=ISocketService;exports.MergeInterceptorFactory=MergeInterceptorFactory;exports.ResponseHeader=ResponseHeader;exports.RetryInterceptorFactory=RetryInterceptorFactory;exports.ThresholdInterceptorFactory=ThresholdInterceptorFactory;exports.WebSocketService=WebSocketService;exports.XHRHTTPImplementation=XHRHTTPImplementation;
|
|
2
|
+
`).forEach(header=>{const[name,value]=header.split(":");name&&value&&this._setHeader(name,value)})}_handleHeadersConstructorProps(headers){Object.entries(headers).forEach(([name,value])=>this._setHeader(name,value))}_handleHeaders(headers){headers.forEach((value,name)=>this._setHeader(name,value))}};__name(_HTTPHeaders,"HTTPHeaders");let HTTPHeaders=_HTTPHeaders;const IHTTPImplementation=core.createIdentifier("network.http-implementation"),_HTTPParams=class _HTTPParams{constructor(params){this.params=params}toString(){return this.params?Object.keys(this.params).map(key=>`${key}=${this.params[key]}`).join("&"):""}};__name(_HTTPParams,"HTTPParams");let HTTPParams=_HTTPParams,HTTPRequestUID=0;const _HTTPRequest=class _HTTPRequest{constructor(method,url,requestParams){__publicField(this,"uid",HTTPRequestUID++);this.method=method,this.url=url,this.requestParams=requestParams}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var _a2,_b;const params=(_b=(_a2=this.requestParams)==null?void 0:_a2.params)==null?void 0:_b.toString();return params?`${this.url}${this.url.includes("?")?"&":"?"}${params}`:this.url}getBody(){var _a2,_b;const contentType=(_a2=this.headers.get("Content-Type"))!=null?_a2:ApplicationJSONType,body=(_b=this.requestParams)==null?void 0:_b.body;return contentType===ApplicationJSONType&&body&&typeof body=="object"?JSON.stringify(body):body?`${body}`:null}getHeadersInit(){return this.headers.toHeadersInit()}};__name(_HTTPRequest,"HTTPRequest");let HTTPRequest=_HTTPRequest;var __defProp2=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp2(target,key,result),result},"__decorateClass"),__decorateParam=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam"),_a;exports.HTTPService=(_a=class extends core.Disposable{constructor(_http){super();__publicField(this,"_interceptors",[]);__publicField(this,"_pipe");this._http=_http}registerHTTPInterceptor(interceptor){if(this._interceptors.indexOf(interceptor)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(interceptor),this._interceptors=this._interceptors.sort((a,b)=>{var _a2,_b;return((_a2=a.priority)!=null?_a2:0)-((_b=b.priority)!=null?_b:0)}),this._pipe=null,core.toDisposable(()=>core.remove(this._interceptors,interceptor))}get(url,params){return this._request("GET",url,params)}post(url,params){return this._request("POST",url,params)}put(url,params){return this._request("PUT",url,params)}delete(url,params){return this._request("DELETE",url,params)}patch(url,options){return this._request("PATCH",url,options)}getSSE(method,url,options){var _a2,_b;const headers=new HTTPHeaders(options==null?void 0:options.headers),params=new HTTPParams(options==null?void 0:options.params),request=new HTTPRequest(method,url,{headers,params,withCredentials:(_a2=options==null?void 0:options.withCredentials)!=null?_a2:!1,reportProgress:!0,responseType:(_b=options==null?void 0:options.responseType)!=null?_b:"json",body:["GET","DELETE"].includes(method)||options==null?void 0:options.body});return rxjs.of(request).pipe(operators.concatMap(request2=>this._runInterceptorsAndImplementation(request2)))}async _request(method,url,options){var _a2,_b;const headers=new HTTPHeaders(options==null?void 0:options.headers),params=new HTTPParams(options==null?void 0:options.params),request=new HTTPRequest(method,url,{headers,params,withCredentials:(_a2=options==null?void 0:options.withCredentials)!=null?_a2:!1,responseType:(_b=options==null?void 0:options.responseType)!=null?_b:"json",body:["GET","DELETE"].includes(method)||options==null?void 0:options.body}),events$=rxjs.of(request).pipe(operators.concatMap(request2=>this._runInterceptorsAndImplementation(request2)));return await rxjs.firstValueFrom(events$)}_runInterceptorsAndImplementation(request){return this._pipe||(this._pipe=this._interceptors.map(handler=>handler.interceptor).reduceRight((nextHandlerFunction,interceptorFunction)=>chainInterceptorFn(nextHandlerFunction,interceptorFunction),(requestFromPrevInterceptor,finalHandler)=>finalHandler(requestFromPrevInterceptor))),this._pipe(request,requestToNext=>this._http.send(requestToNext))}},__name(_a,"HTTPService"),_a);exports.HTTPService=__decorateClass([__decorateParam(0,IHTTPImplementation)],exports.HTTPService);function chainInterceptorFn(afterInterceptorChain,currentInterceptorFn){return(prevRequest,nextHandlerFn)=>currentInterceptorFn(prevRequest,nextRequest=>afterInterceptorChain(nextRequest,nextHandlerFn))}__name(chainInterceptorFn,"chainInterceptorFn");var HTTPEventType=(HTTPEventType2=>(HTTPEventType2[HTTPEventType2.DownloadProgress=0]="DownloadProgress",HTTPEventType2[HTTPEventType2.Response=1]="Response",HTTPEventType2))(HTTPEventType||{});const _HTTPResponse=class _HTTPResponse{constructor({body,headers,status,statusText}){__publicField(this,"type",1);__publicField(this,"body");__publicField(this,"headers");__publicField(this,"status");__publicField(this,"statusText");this.body=body,this.headers=headers,this.status=status,this.statusText=statusText}};__name(_HTTPResponse,"HTTPResponse");let HTTPResponse=_HTTPResponse;const _HTTPProgress=class _HTTPProgress{constructor(total,loaded,partialText){__publicField(this,"type",0);this.total=total,this.loaded=loaded,this.partialText=partialText}};__name(_HTTPProgress,"HTTPProgress");let HTTPProgress=_HTTPProgress;const _ResponseHeader=class _ResponseHeader{constructor(headers,status,statusText){this.headers=headers,this.status=status,this.statusText=statusText}};__name(_ResponseHeader,"ResponseHeader");let ResponseHeader=_ResponseHeader;const _HTTPResponseError=class _HTTPResponseError{constructor({headers,status,statusText,error}){__publicField(this,"headers");__publicField(this,"status");__publicField(this,"statusText");__publicField(this,"error");this.headers=headers,this.status=status,this.statusText=statusText,this.error=error}};__name(_HTTPResponseError,"HTTPResponseError");let HTTPResponseError=_HTTPResponseError;const SuccessStatusCodeLowerBound=200,ErrorStatusCodeLowerBound=300;var HTTPStatusCode=(HTTPStatusCode2=>(HTTPStatusCode2[HTTPStatusCode2.Continue=100]="Continue",HTTPStatusCode2[HTTPStatusCode2.SwitchingProtocols=101]="SwitchingProtocols",HTTPStatusCode2[HTTPStatusCode2.Processing=102]="Processing",HTTPStatusCode2[HTTPStatusCode2.EarlyHints=103]="EarlyHints",HTTPStatusCode2[HTTPStatusCode2.Ok=200]="Ok",HTTPStatusCode2[HTTPStatusCode2.Created=201]="Created",HTTPStatusCode2[HTTPStatusCode2.Accepted=202]="Accepted",HTTPStatusCode2[HTTPStatusCode2.NonAuthoritativeInformation=203]="NonAuthoritativeInformation",HTTPStatusCode2[HTTPStatusCode2.NoContent=204]="NoContent",HTTPStatusCode2[HTTPStatusCode2.ResetContent=205]="ResetContent",HTTPStatusCode2[HTTPStatusCode2.PartialContent=206]="PartialContent",HTTPStatusCode2[HTTPStatusCode2.MultiStatus=207]="MultiStatus",HTTPStatusCode2[HTTPStatusCode2.AlreadyReported=208]="AlreadyReported",HTTPStatusCode2[HTTPStatusCode2.ImUsed=226]="ImUsed",HTTPStatusCode2[HTTPStatusCode2.MultipleChoices=300]="MultipleChoices",HTTPStatusCode2[HTTPStatusCode2.MovedPermanently=301]="MovedPermanently",HTTPStatusCode2[HTTPStatusCode2.Found=302]="Found",HTTPStatusCode2[HTTPStatusCode2.SeeOther=303]="SeeOther",HTTPStatusCode2[HTTPStatusCode2.NotModified=304]="NotModified",HTTPStatusCode2[HTTPStatusCode2.UseProxy=305]="UseProxy",HTTPStatusCode2[HTTPStatusCode2.Unused=306]="Unused",HTTPStatusCode2[HTTPStatusCode2.TemporaryRedirect=307]="TemporaryRedirect",HTTPStatusCode2[HTTPStatusCode2.PermanentRedirect=308]="PermanentRedirect",HTTPStatusCode2[HTTPStatusCode2.BadRequest=400]="BadRequest",HTTPStatusCode2[HTTPStatusCode2.Unauthorized=401]="Unauthorized",HTTPStatusCode2[HTTPStatusCode2.PaymentRequired=402]="PaymentRequired",HTTPStatusCode2[HTTPStatusCode2.Forbidden=403]="Forbidden",HTTPStatusCode2[HTTPStatusCode2.NotFound=404]="NotFound",HTTPStatusCode2[HTTPStatusCode2.MethodNotAllowed=405]="MethodNotAllowed",HTTPStatusCode2[HTTPStatusCode2.NotAcceptable=406]="NotAcceptable",HTTPStatusCode2[HTTPStatusCode2.ProxyAuthenticationRequired=407]="ProxyAuthenticationRequired",HTTPStatusCode2[HTTPStatusCode2.RequestTimeout=408]="RequestTimeout",HTTPStatusCode2[HTTPStatusCode2.Conflict=409]="Conflict",HTTPStatusCode2[HTTPStatusCode2.Gone=410]="Gone",HTTPStatusCode2[HTTPStatusCode2.LengthRequired=411]="LengthRequired",HTTPStatusCode2[HTTPStatusCode2.PreconditionFailed=412]="PreconditionFailed",HTTPStatusCode2[HTTPStatusCode2.PayloadTooLarge=413]="PayloadTooLarge",HTTPStatusCode2[HTTPStatusCode2.UriTooLong=414]="UriTooLong",HTTPStatusCode2[HTTPStatusCode2.UnsupportedMediaType=415]="UnsupportedMediaType",HTTPStatusCode2[HTTPStatusCode2.RangeNotSatisfiable=416]="RangeNotSatisfiable",HTTPStatusCode2[HTTPStatusCode2.ExpectationFailed=417]="ExpectationFailed",HTTPStatusCode2[HTTPStatusCode2.ImATeapot=418]="ImATeapot",HTTPStatusCode2[HTTPStatusCode2.MisdirectedRequest=421]="MisdirectedRequest",HTTPStatusCode2[HTTPStatusCode2.UnprocessableEntity=422]="UnprocessableEntity",HTTPStatusCode2[HTTPStatusCode2.Locked=423]="Locked",HTTPStatusCode2[HTTPStatusCode2.FailedDependency=424]="FailedDependency",HTTPStatusCode2[HTTPStatusCode2.TooEarly=425]="TooEarly",HTTPStatusCode2[HTTPStatusCode2.UpgradeRequired=426]="UpgradeRequired",HTTPStatusCode2[HTTPStatusCode2.PreconditionRequired=428]="PreconditionRequired",HTTPStatusCode2[HTTPStatusCode2.TooManyRequests=429]="TooManyRequests",HTTPStatusCode2[HTTPStatusCode2.RequestHeaderFieldsTooLarge=431]="RequestHeaderFieldsTooLarge",HTTPStatusCode2[HTTPStatusCode2.UnavailableForLegalReasons=451]="UnavailableForLegalReasons",HTTPStatusCode2[HTTPStatusCode2.InternalServerError=500]="InternalServerError",HTTPStatusCode2[HTTPStatusCode2.NotImplemented=501]="NotImplemented",HTTPStatusCode2[HTTPStatusCode2.BadGateway=502]="BadGateway",HTTPStatusCode2[HTTPStatusCode2.ServiceUnavailable=503]="ServiceUnavailable",HTTPStatusCode2[HTTPStatusCode2.GatewayTimeout=504]="GatewayTimeout",HTTPStatusCode2[HTTPStatusCode2.HttpVersionNotSupported=505]="HttpVersionNotSupported",HTTPStatusCode2[HTTPStatusCode2.VariantAlsoNegotiates=506]="VariantAlsoNegotiates",HTTPStatusCode2[HTTPStatusCode2.InsufficientStorage=507]="InsufficientStorage",HTTPStatusCode2[HTTPStatusCode2.LoopDetected=508]="LoopDetected",HTTPStatusCode2[HTTPStatusCode2.NotExtended=510]="NotExtended",HTTPStatusCode2[HTTPStatusCode2.NetworkAuthenticationRequired=511]="NetworkAuthenticationRequired",HTTPStatusCode2))(HTTPStatusCode||{});const _FetchHTTPImplementation=class _FetchHTTPImplementation{send(request){return new rxjs.Observable(subscriber=>{const abortController=new AbortController;return this._send(request,subscriber,abortController).then(()=>{},error=>{subscriber.error(new HTTPResponseError({error}))}),()=>abortController.abort()})}async _send(request,subscriber,abortController){var _a2,_b;let response;try{const fetchParams=this._parseFetchParamsFromRequest(request);response=await fetch(request.getUrlWithParams(),{signal:abortController.signal,...fetchParams})}catch(error){subscriber.error(new HTTPResponseError({error,status:(_a2=error.status)!=null?_a2:0,statusText:(_b=error.statusText)!=null?_b:"Unknown Error",headers:error.headers}));return}const responseHeaders=new HTTPHeaders(response.headers),status=response.status,statusText=response.statusText;let body=null;response.body&&(body=await this._readBody(request,response,subscriber)),status>=HTTPStatusCode.Ok&&status<HTTPStatusCode.MultipleChoices?subscriber.next(new HTTPResponse({body,headers:responseHeaders,status,statusText})):subscriber.error(new HTTPResponseError({error:body,status,statusText,headers:responseHeaders})),subscriber.complete()}async _readBody(request,response,subscriber){var _a2,_b;const chunks=[],reader=response.body.getReader(),contentLength=response.headers.get("content-length");let receivedLength=0;const reportProgress=(_a2=request.requestParams)==null?void 0:_a2.reportProgress,responseType=request.responseType;let partialText,decoder;for(;;){const{done,value}=await reader.read();if(done)break;chunks.push(value),receivedLength+=value.length,reportProgress&&responseType==="text"&&(partialText=(partialText!=null?partialText:"")+(decoder!=null?decoder:decoder=new TextDecoder).decode(value,{stream:!0}),subscriber.next(new HTTPProgress(contentLength?Number.parseInt(contentLength,10):void 0,receivedLength,partialText)))}const all=mergeChunks(chunks,receivedLength);try{const contentType=(_b=response.headers.get("content-type"))!=null?_b:"";return deserialize(request,all,contentType)}catch(error){return subscriber.error(new HTTPResponseError({error,status:response.status,statusText:response.statusText,headers:new HTTPHeaders(response.headers)})),null}}_parseFetchParamsFromRequest(request){return{method:request.method,headers:request.getHeadersInit(),body:request.getBody(),credentials:request.withCredentials?"include":void 0}}};__name(_FetchHTTPImplementation,"FetchHTTPImplementation");let FetchHTTPImplementation=_FetchHTTPImplementation;function mergeChunks(chunks,totalLength){const all=new Uint8Array(totalLength);let position=0;for(const chunk of chunks)all.set(chunk,position),position+=chunk.length;return all}__name(mergeChunks,"mergeChunks");const XSSI_PREFIX=/^\)\]\}',?\n/;function deserialize(request,bin,contentType){switch(request.responseType){case"json":const text=new TextDecoder().decode(bin).replace(XSSI_PREFIX,"");return text===""?null:JSON.parse(text);case"text":return new TextDecoder().decode(bin);case"blob":return new Blob([bin],{type:contentType});case"arraybuffer":return bin.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${request.responseType}.`)}}__name(deserialize,"deserialize");const _XHRHTTPImplementation=class _XHRHTTPImplementation{send(request){return new rxjs.Observable(observer=>{const xhr=new XMLHttpRequest;xhr.open(request.method,request.getUrlWithParams()),request.withCredentials&&(xhr.withCredentials=!0),request.headers.forEach((key,value)=>xhr.setRequestHeader(key,value.join(","))),request.headers.has("Accept")||xhr.setRequestHeader("Accept","application/json, text/plain, */*"),request.headers.has("Content-Type")||xhr.setRequestHeader("Content-Type","application/json;charset=UTF-8");const buildResponseHeader=__name(()=>{const statusText=xhr.statusText||"OK",headers=new HTTPHeaders(xhr.getAllResponseHeaders());return new ResponseHeader(headers,xhr.status,statusText)},"buildResponseHeader"),onLoadHandler=__name(()=>{const{headers,statusText,status}=buildResponseHeader(),{responseType}=request;let body2=null,error=null;status!==HTTPStatusCode.NoContent&&(body2=typeof xhr.response>"u"?xhr.responseText:xhr.response);let success=status>=SuccessStatusCodeLowerBound&&status<ErrorStatusCodeLowerBound;if(responseType==="json"&&typeof body2=="string"){const originalBody=body2;try{body2=body2?JSON.parse(body2):null}catch(e){success=!1,body2=originalBody,error=e}}success?observer.next(new HTTPResponse({body:body2,headers,status,statusText})):observer.error(new HTTPResponseError({error,headers,status,statusText}))},"onLoadHandler"),onErrorHandler=__name(error=>{const res=new HTTPResponseError({error,status:xhr.status||0,statusText:xhr.statusText||"Unknown Error",headers:buildResponseHeader().headers});observer.error(res)},"onErrorHandler");xhr.addEventListener("load",onLoadHandler),xhr.addEventListener("error",onErrorHandler),xhr.addEventListener("abort",onErrorHandler),xhr.addEventListener("timeout",onErrorHandler);const body=request.getBody();return xhr.send(body),()=>{xhr.readyState!==xhr.DONE&&xhr.abort(),xhr.removeEventListener("load",onLoadHandler),xhr.removeEventListener("error",onErrorHandler),xhr.removeEventListener("abort",onErrorHandler),xhr.removeEventListener("timeout",onErrorHandler)}})}};__name(_XHRHTTPImplementation,"XHRHTTPImplementation");let XHRHTTPImplementation=_XHRHTTPImplementation;const ISocketService=core.createIdentifier("univer.socket"),_WebSocketService=class _WebSocketService extends core.Disposable{createSocket(URL){try{const connection=new WebSocket(URL),disposables=new core.DisposableCollection;return{URL,close:__name((code,reason)=>{connection.close(code,reason),disposables.dispose()},"close"),send:__name(data=>{connection.send(data)},"send"),open$:new rxjs.Observable(subscriber=>{const callback=__name(event=>subscriber.next(event),"callback");connection.addEventListener("open",callback),disposables.add(core.toDisposable(()=>connection.removeEventListener("open",callback)))}).pipe(operators.share()),close$:new rxjs.Observable(subscriber=>{const callback=__name(event=>subscriber.next(event),"callback");connection.addEventListener("close",callback),disposables.add(core.toDisposable(()=>connection.removeEventListener("close",callback)))}).pipe(operators.share()),error$:new rxjs.Observable(subscriber=>{const callback=__name(event=>subscriber.next(event),"callback");connection.addEventListener("error",callback),disposables.add(core.toDisposable(()=>connection.removeEventListener("error",callback)))}).pipe(operators.share()),message$:new rxjs.Observable(subscriber=>{const callback=__name(event=>subscriber.next(event),"callback");connection.addEventListener("message",callback),disposables.add(core.toDisposable(()=>connection.removeEventListener("message",callback)))}).pipe(operators.share())}}catch(e){return console.error(e),null}}};__name(_WebSocketService,"WebSocketService");let WebSocketService=_WebSocketService;const DEFAULT_MAX_RETRY_ATTEMPTS=3,DELAY_INTERVAL=1e3,RetryInterceptorFactory=__name(params=>{var _a2,_b;const maxRetryAttempts=(_a2=params==null?void 0:params.maxRetryAttempts)!=null?_a2:DEFAULT_MAX_RETRY_ATTEMPTS,delayInterval=(_b=params==null?void 0:params.delayInterval)!=null?_b:DELAY_INTERVAL;return(request,next)=>next(request).pipe(operators.retry({delay:delayInterval,count:maxRetryAttempts}))},"RetryInterceptorFactory"),ThresholdInterceptorFactory=__name(params=>{const handlers=[],ongoingHandlers=new Set,tick=__name(()=>{var _a2;for(;ongoingHandlers.size<((_a2=params==null?void 0:params.maxParallel)!=null?_a2:1)&&handlers.length>0;){const handler=handlers.shift();ongoingHandlers.add(handler),handler()}},"tick");return(request,next)=>new rxjs.Observable(observer=>{const handler=__name(()=>next(request).subscribe({next:__name(event=>observer.next(event),"next"),error:__name(err=>observer.next(err),"error"),complete:__name(()=>observer.complete(),"complete")}),"handler"),teardown=__name(()=>{ongoingHandlers.delete(handler),core.remove(handlers,handler),tick()},"teardown");return handlers.push(handler),tick(),teardown})},"ThresholdInterceptorFactory"),AuthInterceptorFactory=__name(params=>{const{errorStatusCodes,onAuthError}=params;return __name((request,next)=>next(request).pipe(rxjs.catchError(error=>(error instanceof HTTPResponseError&&errorStatusCodes.some(c=>c===error.status)&&onAuthError(),rxjs.throwError(()=>error)))),"authInterceptor")},"AuthInterceptorFactory"),createDefaultFetchCheck=__name((time=300)=>{let cancel=__name(()=>{},"noop");return _currentConfig=>new Promise(res=>{cancel();const t=setTimeout(()=>{res(!0)},time);cancel=__name(()=>{clearTimeout(t),res(!1)},"cancel")})},"createDefaultFetchCheck"),createDistributeResult=__name(()=>(result,list)=>list.map(config=>({config,result})),"createDistributeResult"),MergeInterceptorFactory=__name((config,options={})=>{const{isMatch,getParamsFromRequest,mergeParamsToRequest}=config,{fetchCheck=createDefaultFetchCheck(300),distributeResult=createDistributeResult()}=options,hookList=[],getPlainList=__name(_list=>_list.map(item=>item.config),"getPlainList");return(requestConfig,next)=>isMatch(requestConfig)?new rxjs.Observable(observer=>{const params=getParamsFromRequest(requestConfig);hookList.push({next:__name(v=>observer.next(v),"next"),error:__name(error=>observer.error(error),"error"),config:params});const list=getPlainList(hookList);fetchCheck(requestConfig).then(isFetch=>{if(isFetch){const currentHookList=[];list.forEach(config2=>{const index=hookList.findIndex(item=>item.config===config2);if(index>=0){const[hook]=hookList.splice(index,1);currentHookList.push(hook)}}),next(mergeParamsToRequest(list,requestConfig)).subscribe({next:__name(e=>{if(e.type===HTTPEventType.Response){const body=e.body,configList=distributeResult(body,list);currentHookList.forEach(hookItem=>{const res=configList.find(item=>item.config===hookItem.config);if(res){const response=new HTTPResponse({body:res.result,headers:e.headers,status:e.status,statusText:e.statusText});hookItem.next(response)}else hookItem.error("batch error")})}},"next"),complete:__name(()=>observer.complete(),"complete"),error:__name(e=>observer.error(e),"error")})}})}):next(requestConfig)},"MergeInterceptorFactory");exports.AuthInterceptorFactory=AuthInterceptorFactory;exports.FetchHTTPImplementation=FetchHTTPImplementation;exports.HTTPEventType=HTTPEventType;exports.HTTPHeaders=HTTPHeaders;exports.HTTPProgress=HTTPProgress;exports.HTTPRequest=HTTPRequest;exports.HTTPResponse=HTTPResponse;exports.HTTPResponseError=HTTPResponseError;exports.HTTPStatusCode=HTTPStatusCode;exports.IHTTPImplementation=IHTTPImplementation;exports.ISocketService=ISocketService;exports.MergeInterceptorFactory=MergeInterceptorFactory;exports.ResponseHeader=ResponseHeader;exports.RetryInterceptorFactory=RetryInterceptorFactory;exports.ThresholdInterceptorFactory=ThresholdInterceptorFactory;exports.WebSocketService=WebSocketService;exports.XHRHTTPImplementation=XHRHTTPImplementation;
|
package/lib/es/index.js
CHANGED
|
@@ -425,7 +425,7 @@ const ISocketService = createIdentifier("univer.socket"), _WebSocketService = cl
|
|
|
425
425
|
};
|
|
426
426
|
__name(_WebSocketService, "WebSocketService");
|
|
427
427
|
let WebSocketService = _WebSocketService;
|
|
428
|
-
const DEFAULT_MAX_RETRY_ATTEMPTS = 3, DELAY_INTERVAL = 1e3, RetryInterceptorFactory = /* @__PURE__ */ __name((
|
|
428
|
+
const DEFAULT_MAX_RETRY_ATTEMPTS = 3, DELAY_INTERVAL = 1e3, RetryInterceptorFactory = /* @__PURE__ */ __name((params) => {
|
|
429
429
|
var _a2, _b;
|
|
430
430
|
const maxRetryAttempts = (_a2 = params == null ? void 0 : params.maxRetryAttempts) != null ? _a2 : DEFAULT_MAX_RETRY_ATTEMPTS, delayInterval = (_b = params == null ? void 0 : params.delayInterval) != null ? _b : DELAY_INTERVAL;
|
|
431
431
|
return (request, next) => next(request).pipe(retry({ delay: delayInterval, count: maxRetryAttempts }));
|
|
@@ -4,4 +4,4 @@ export interface IRetryInterceptorFactoryParams {
|
|
|
4
4
|
maxRetryAttempts?: number;
|
|
5
5
|
delayInterval?: number;
|
|
6
6
|
}
|
|
7
|
-
export declare const RetryInterceptorFactory: HTTPInterceptorFnFactory<[Nullable<
|
|
7
|
+
export declare const RetryInterceptorFactory: HTTPInterceptorFnFactory<[Nullable<IRetryInterceptorFactoryParams>]>;
|
package/lib/umd/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
(function(global,factory){typeof exports=="object"&&typeof module<"u"?factory(exports,require("@univerjs/core"),require("rxjs"),require("rxjs/operators")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs","rxjs/operators"],factory):(global=typeof globalThis<"u"?globalThis:global||self,factory(global.UniverNetwork={},global.UniverCore,global.rxjs,global.rxjs.operators))})(this,function(exports2,core,rxjs,operators){"use strict";var __defProp=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!="symbol"?key+"":key,value);var _a;const ApplicationJSONType="application/json",_HTTPHeaders=class _HTTPHeaders{constructor(headers){__publicField(this,"_headers",new Map);typeof headers=="string"?this._handleHeadersString(headers):headers instanceof Headers?this._handleHeaders(headers):headers&&this._handleHeadersConstructorProps(headers)}forEach(callback){this._headers.forEach((v,key)=>callback(key,v))}has(key){return!!this._headers.has(key.toLowerCase())}get(key){const k=key.toLowerCase();return this._headers.has(k)?this._headers.get(k):null}toHeadersInit(){var _a2,_b;const headers={};return this._headers.forEach((values,key)=>{headers[key]=values.join(",")}),(_a2=headers.accept)!=null||(headers.accept="application/json, text/plain, */*"),(_b=headers["content-type"])!=null||(headers["content-type"]="application/json;charset=UTF-8"),headers}_setHeader(name,value){const lowerCase=name.toLowerCase();this._headers.has(lowerCase)?this._headers.get(lowerCase).push(value.toString()):this._headers.set(lowerCase,[value.toString()])}_handleHeadersString(headers){headers.split(`
|
|
2
|
-
`).forEach(header=>{const[name,value]=header.split(":");name&&value&&this._setHeader(name,value)})}_handleHeadersConstructorProps(headers){Object.entries(headers).forEach(([name,value])=>this._setHeader(name,value))}_handleHeaders(headers){headers.forEach((value,name)=>this._setHeader(name,value))}};__name(_HTTPHeaders,"HTTPHeaders");let HTTPHeaders=_HTTPHeaders;const IHTTPImplementation=core.createIdentifier("network.http-implementation"),_HTTPParams=class _HTTPParams{constructor(params){this.params=params}toString(){return this.params?Object.keys(this.params).map(key=>`${key}=${this.params[key]}`).join("&"):""}};__name(_HTTPParams,"HTTPParams");let HTTPParams=_HTTPParams,HTTPRequestUID=0;const _HTTPRequest=class _HTTPRequest{constructor(method,url,requestParams){__publicField(this,"uid",HTTPRequestUID++);this.method=method,this.url=url,this.requestParams=requestParams}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var _a2,_b;const params=(_b=(_a2=this.requestParams)==null?void 0:_a2.params)==null?void 0:_b.toString();return params?`${this.url}${this.url.includes("?")?"&":"?"}${params}`:this.url}getBody(){var _a2,_b;const contentType=(_a2=this.headers.get("Content-Type"))!=null?_a2:ApplicationJSONType,body=(_b=this.requestParams)==null?void 0:_b.body;return contentType===ApplicationJSONType&&body&&typeof body=="object"?JSON.stringify(body):body?`${body}`:null}getHeadersInit(){return this.headers.toHeadersInit()}};__name(_HTTPRequest,"HTTPRequest");let HTTPRequest=_HTTPRequest;var __defProp2=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp2(target,key,result),result},"__decorateClass"),__decorateParam=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam");exports2.HTTPService=(_a=class extends core.Disposable{constructor(_http){super();__publicField(this,"_interceptors",[]);__publicField(this,"_pipe");this._http=_http}registerHTTPInterceptor(interceptor){if(this._interceptors.indexOf(interceptor)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(interceptor),this._interceptors=this._interceptors.sort((a,b)=>{var _a2,_b;return((_a2=a.priority)!=null?_a2:0)-((_b=b.priority)!=null?_b:0)}),this._pipe=null,core.toDisposable(()=>core.remove(this._interceptors,interceptor))}get(url,params){return this._request("GET",url,params)}post(url,params){return this._request("POST",url,params)}put(url,params){return this._request("PUT",url,params)}delete(url,params){return this._request("DELETE",url,params)}patch(url,options){return this._request("PATCH",url,options)}getSSE(method,url,options){var _a2,_b;const headers=new HTTPHeaders(options==null?void 0:options.headers),params=new HTTPParams(options==null?void 0:options.params),request=new HTTPRequest(method,url,{headers,params,withCredentials:(_a2=options==null?void 0:options.withCredentials)!=null?_a2:!1,reportProgress:!0,responseType:(_b=options==null?void 0:options.responseType)!=null?_b:"json",body:["GET","DELETE"].includes(method)||options==null?void 0:options.body});return rxjs.of(request).pipe(operators.concatMap(request2=>this._runInterceptorsAndImplementation(request2)))}async _request(method,url,options){var _a2,_b;const headers=new HTTPHeaders(options==null?void 0:options.headers),params=new HTTPParams(options==null?void 0:options.params),request=new HTTPRequest(method,url,{headers,params,withCredentials:(_a2=options==null?void 0:options.withCredentials)!=null?_a2:!1,responseType:(_b=options==null?void 0:options.responseType)!=null?_b:"json",body:["GET","DELETE"].includes(method)||options==null?void 0:options.body}),events$=rxjs.of(request).pipe(operators.concatMap(request2=>this._runInterceptorsAndImplementation(request2)));return await rxjs.firstValueFrom(events$)}_runInterceptorsAndImplementation(request){return this._pipe||(this._pipe=this._interceptors.map(handler=>handler.interceptor).reduceRight((nextHandlerFunction,interceptorFunction)=>chainInterceptorFn(nextHandlerFunction,interceptorFunction),(requestFromPrevInterceptor,finalHandler)=>finalHandler(requestFromPrevInterceptor))),this._pipe(request,requestToNext=>this._http.send(requestToNext))}},__name(_a,"HTTPService"),_a),exports2.HTTPService=__decorateClass([__decorateParam(0,IHTTPImplementation)],exports2.HTTPService);function chainInterceptorFn(afterInterceptorChain,currentInterceptorFn){return(prevRequest,nextHandlerFn)=>currentInterceptorFn(prevRequest,nextRequest=>afterInterceptorChain(nextRequest,nextHandlerFn))}__name(chainInterceptorFn,"chainInterceptorFn");var HTTPEventType=(HTTPEventType2=>(HTTPEventType2[HTTPEventType2.DownloadProgress=0]="DownloadProgress",HTTPEventType2[HTTPEventType2.Response=1]="Response",HTTPEventType2))(HTTPEventType||{});const _HTTPResponse=class _HTTPResponse{constructor({body,headers,status,statusText}){__publicField(this,"type",1);__publicField(this,"body");__publicField(this,"headers");__publicField(this,"status");__publicField(this,"statusText");this.body=body,this.headers=headers,this.status=status,this.statusText=statusText}};__name(_HTTPResponse,"HTTPResponse");let HTTPResponse=_HTTPResponse;const _HTTPProgress=class _HTTPProgress{constructor(total,loaded,partialText){__publicField(this,"type",0);this.total=total,this.loaded=loaded,this.partialText=partialText}};__name(_HTTPProgress,"HTTPProgress");let HTTPProgress=_HTTPProgress;const _ResponseHeader=class _ResponseHeader{constructor(headers,status,statusText){this.headers=headers,this.status=status,this.statusText=statusText}};__name(_ResponseHeader,"ResponseHeader");let ResponseHeader=_ResponseHeader;const _HTTPResponseError=class _HTTPResponseError{constructor({headers,status,statusText,error}){__publicField(this,"headers");__publicField(this,"status");__publicField(this,"statusText");__publicField(this,"error");this.headers=headers,this.status=status,this.statusText=statusText,this.error=error}};__name(_HTTPResponseError,"HTTPResponseError");let HTTPResponseError=_HTTPResponseError;const SuccessStatusCodeLowerBound=200,ErrorStatusCodeLowerBound=300;var HTTPStatusCode=(HTTPStatusCode2=>(HTTPStatusCode2[HTTPStatusCode2.Continue=100]="Continue",HTTPStatusCode2[HTTPStatusCode2.SwitchingProtocols=101]="SwitchingProtocols",HTTPStatusCode2[HTTPStatusCode2.Processing=102]="Processing",HTTPStatusCode2[HTTPStatusCode2.EarlyHints=103]="EarlyHints",HTTPStatusCode2[HTTPStatusCode2.Ok=200]="Ok",HTTPStatusCode2[HTTPStatusCode2.Created=201]="Created",HTTPStatusCode2[HTTPStatusCode2.Accepted=202]="Accepted",HTTPStatusCode2[HTTPStatusCode2.NonAuthoritativeInformation=203]="NonAuthoritativeInformation",HTTPStatusCode2[HTTPStatusCode2.NoContent=204]="NoContent",HTTPStatusCode2[HTTPStatusCode2.ResetContent=205]="ResetContent",HTTPStatusCode2[HTTPStatusCode2.PartialContent=206]="PartialContent",HTTPStatusCode2[HTTPStatusCode2.MultiStatus=207]="MultiStatus",HTTPStatusCode2[HTTPStatusCode2.AlreadyReported=208]="AlreadyReported",HTTPStatusCode2[HTTPStatusCode2.ImUsed=226]="ImUsed",HTTPStatusCode2[HTTPStatusCode2.MultipleChoices=300]="MultipleChoices",HTTPStatusCode2[HTTPStatusCode2.MovedPermanently=301]="MovedPermanently",HTTPStatusCode2[HTTPStatusCode2.Found=302]="Found",HTTPStatusCode2[HTTPStatusCode2.SeeOther=303]="SeeOther",HTTPStatusCode2[HTTPStatusCode2.NotModified=304]="NotModified",HTTPStatusCode2[HTTPStatusCode2.UseProxy=305]="UseProxy",HTTPStatusCode2[HTTPStatusCode2.Unused=306]="Unused",HTTPStatusCode2[HTTPStatusCode2.TemporaryRedirect=307]="TemporaryRedirect",HTTPStatusCode2[HTTPStatusCode2.PermanentRedirect=308]="PermanentRedirect",HTTPStatusCode2[HTTPStatusCode2.BadRequest=400]="BadRequest",HTTPStatusCode2[HTTPStatusCode2.Unauthorized=401]="Unauthorized",HTTPStatusCode2[HTTPStatusCode2.PaymentRequired=402]="PaymentRequired",HTTPStatusCode2[HTTPStatusCode2.Forbidden=403]="Forbidden",HTTPStatusCode2[HTTPStatusCode2.NotFound=404]="NotFound",HTTPStatusCode2[HTTPStatusCode2.MethodNotAllowed=405]="MethodNotAllowed",HTTPStatusCode2[HTTPStatusCode2.NotAcceptable=406]="NotAcceptable",HTTPStatusCode2[HTTPStatusCode2.ProxyAuthenticationRequired=407]="ProxyAuthenticationRequired",HTTPStatusCode2[HTTPStatusCode2.RequestTimeout=408]="RequestTimeout",HTTPStatusCode2[HTTPStatusCode2.Conflict=409]="Conflict",HTTPStatusCode2[HTTPStatusCode2.Gone=410]="Gone",HTTPStatusCode2[HTTPStatusCode2.LengthRequired=411]="LengthRequired",HTTPStatusCode2[HTTPStatusCode2.PreconditionFailed=412]="PreconditionFailed",HTTPStatusCode2[HTTPStatusCode2.PayloadTooLarge=413]="PayloadTooLarge",HTTPStatusCode2[HTTPStatusCode2.UriTooLong=414]="UriTooLong",HTTPStatusCode2[HTTPStatusCode2.UnsupportedMediaType=415]="UnsupportedMediaType",HTTPStatusCode2[HTTPStatusCode2.RangeNotSatisfiable=416]="RangeNotSatisfiable",HTTPStatusCode2[HTTPStatusCode2.ExpectationFailed=417]="ExpectationFailed",HTTPStatusCode2[HTTPStatusCode2.ImATeapot=418]="ImATeapot",HTTPStatusCode2[HTTPStatusCode2.MisdirectedRequest=421]="MisdirectedRequest",HTTPStatusCode2[HTTPStatusCode2.UnprocessableEntity=422]="UnprocessableEntity",HTTPStatusCode2[HTTPStatusCode2.Locked=423]="Locked",HTTPStatusCode2[HTTPStatusCode2.FailedDependency=424]="FailedDependency",HTTPStatusCode2[HTTPStatusCode2.TooEarly=425]="TooEarly",HTTPStatusCode2[HTTPStatusCode2.UpgradeRequired=426]="UpgradeRequired",HTTPStatusCode2[HTTPStatusCode2.PreconditionRequired=428]="PreconditionRequired",HTTPStatusCode2[HTTPStatusCode2.TooManyRequests=429]="TooManyRequests",HTTPStatusCode2[HTTPStatusCode2.RequestHeaderFieldsTooLarge=431]="RequestHeaderFieldsTooLarge",HTTPStatusCode2[HTTPStatusCode2.UnavailableForLegalReasons=451]="UnavailableForLegalReasons",HTTPStatusCode2[HTTPStatusCode2.InternalServerError=500]="InternalServerError",HTTPStatusCode2[HTTPStatusCode2.NotImplemented=501]="NotImplemented",HTTPStatusCode2[HTTPStatusCode2.BadGateway=502]="BadGateway",HTTPStatusCode2[HTTPStatusCode2.ServiceUnavailable=503]="ServiceUnavailable",HTTPStatusCode2[HTTPStatusCode2.GatewayTimeout=504]="GatewayTimeout",HTTPStatusCode2[HTTPStatusCode2.HttpVersionNotSupported=505]="HttpVersionNotSupported",HTTPStatusCode2[HTTPStatusCode2.VariantAlsoNegotiates=506]="VariantAlsoNegotiates",HTTPStatusCode2[HTTPStatusCode2.InsufficientStorage=507]="InsufficientStorage",HTTPStatusCode2[HTTPStatusCode2.LoopDetected=508]="LoopDetected",HTTPStatusCode2[HTTPStatusCode2.NotExtended=510]="NotExtended",HTTPStatusCode2[HTTPStatusCode2.NetworkAuthenticationRequired=511]="NetworkAuthenticationRequired",HTTPStatusCode2))(HTTPStatusCode||{});const _FetchHTTPImplementation=class _FetchHTTPImplementation{send(request){return new rxjs.Observable(subscriber=>{const abortController=new AbortController;return this._send(request,subscriber,abortController).then(()=>{},error=>{subscriber.error(new HTTPResponseError({error}))}),()=>abortController.abort()})}async _send(request,subscriber,abortController){var _a2,_b;let response;try{const fetchParams=this._parseFetchParamsFromRequest(request);response=await fetch(request.getUrlWithParams(),{signal:abortController.signal,...fetchParams})}catch(error){subscriber.error(new HTTPResponseError({error,status:(_a2=error.status)!=null?_a2:0,statusText:(_b=error.statusText)!=null?_b:"Unknown Error",headers:error.headers}));return}const responseHeaders=new HTTPHeaders(response.headers),status=response.status,statusText=response.statusText;let body=null;response.body&&(body=await this._readBody(request,response,subscriber)),status>=HTTPStatusCode.Ok&&status<HTTPStatusCode.MultipleChoices?subscriber.next(new HTTPResponse({body,headers:responseHeaders,status,statusText})):subscriber.error(new HTTPResponseError({error:body,status,statusText,headers:responseHeaders})),subscriber.complete()}async _readBody(request,response,subscriber){var _a2,_b;const chunks=[],reader=response.body.getReader(),contentLength=response.headers.get("content-length");let receivedLength=0;const reportProgress=(_a2=request.requestParams)==null?void 0:_a2.reportProgress,responseType=request.responseType;let partialText,decoder;for(;;){const{done,value}=await reader.read();if(done)break;chunks.push(value),receivedLength+=value.length,reportProgress&&responseType==="text"&&(partialText=(partialText!=null?partialText:"")+(decoder!=null?decoder:decoder=new TextDecoder).decode(value,{stream:!0}),subscriber.next(new HTTPProgress(contentLength?Number.parseInt(contentLength,10):void 0,receivedLength,partialText)))}const all=mergeChunks(chunks,receivedLength);try{const contentType=(_b=response.headers.get("content-type"))!=null?_b:"";return deserialize(request,all,contentType)}catch(error){return subscriber.error(new HTTPResponseError({error,status:response.status,statusText:response.statusText,headers:new HTTPHeaders(response.headers)})),null}}_parseFetchParamsFromRequest(request){return{method:request.method,headers:request.getHeadersInit(),body:request.getBody(),credentials:request.withCredentials?"include":void 0}}};__name(_FetchHTTPImplementation,"FetchHTTPImplementation");let FetchHTTPImplementation=_FetchHTTPImplementation;function mergeChunks(chunks,totalLength){const all=new Uint8Array(totalLength);let position=0;for(const chunk of chunks)all.set(chunk,position),position+=chunk.length;return all}__name(mergeChunks,"mergeChunks");const XSSI_PREFIX=/^\)\]\}',?\n/;function deserialize(request,bin,contentType){switch(request.responseType){case"json":const text=new TextDecoder().decode(bin).replace(XSSI_PREFIX,"");return text===""?null:JSON.parse(text);case"text":return new TextDecoder().decode(bin);case"blob":return new Blob([bin],{type:contentType});case"arraybuffer":return bin.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${request.responseType}.`)}}__name(deserialize,"deserialize");const _XHRHTTPImplementation=class _XHRHTTPImplementation{send(request){return new rxjs.Observable(observer=>{const xhr=new XMLHttpRequest;xhr.open(request.method,request.getUrlWithParams()),request.withCredentials&&(xhr.withCredentials=!0),request.headers.forEach((key,value)=>xhr.setRequestHeader(key,value.join(","))),request.headers.has("Accept")||xhr.setRequestHeader("Accept","application/json, text/plain, */*"),request.headers.has("Content-Type")||xhr.setRequestHeader("Content-Type","application/json;charset=UTF-8");const buildResponseHeader=__name(()=>{const statusText=xhr.statusText||"OK",headers=new HTTPHeaders(xhr.getAllResponseHeaders());return new ResponseHeader(headers,xhr.status,statusText)},"buildResponseHeader"),onLoadHandler=__name(()=>{const{headers,statusText,status}=buildResponseHeader(),{responseType}=request;let body2=null,error=null;status!==HTTPStatusCode.NoContent&&(body2=typeof xhr.response>"u"?xhr.responseText:xhr.response);let success=status>=SuccessStatusCodeLowerBound&&status<ErrorStatusCodeLowerBound;if(responseType==="json"&&typeof body2=="string"){const originalBody=body2;try{body2=body2?JSON.parse(body2):null}catch(e){success=!1,body2=originalBody,error=e}}success?observer.next(new HTTPResponse({body:body2,headers,status,statusText})):observer.error(new HTTPResponseError({error,headers,status,statusText}))},"onLoadHandler"),onErrorHandler=__name(error=>{const res=new HTTPResponseError({error,status:xhr.status||0,statusText:xhr.statusText||"Unknown Error",headers:buildResponseHeader().headers});observer.error(res)},"onErrorHandler");xhr.addEventListener("load",onLoadHandler),xhr.addEventListener("error",onErrorHandler),xhr.addEventListener("abort",onErrorHandler),xhr.addEventListener("timeout",onErrorHandler);const body=request.getBody();return xhr.send(body),()=>{xhr.readyState!==xhr.DONE&&xhr.abort(),xhr.removeEventListener("load",onLoadHandler),xhr.removeEventListener("error",onErrorHandler),xhr.removeEventListener("abort",onErrorHandler),xhr.removeEventListener("timeout",onErrorHandler)}})}};__name(_XHRHTTPImplementation,"XHRHTTPImplementation");let XHRHTTPImplementation=_XHRHTTPImplementation;const ISocketService=core.createIdentifier("univer.socket"),_WebSocketService=class _WebSocketService extends core.Disposable{createSocket(URL){try{const connection=new WebSocket(URL),disposables=new core.DisposableCollection;return{URL,close:__name((code,reason)=>{connection.close(code,reason),disposables.dispose()},"close"),send:__name(data=>{connection.send(data)},"send"),open$:new rxjs.Observable(subscriber=>{const callback=__name(event=>subscriber.next(event),"callback");connection.addEventListener("open",callback),disposables.add(core.toDisposable(()=>connection.removeEventListener("open",callback)))}).pipe(operators.share()),close$:new rxjs.Observable(subscriber=>{const callback=__name(event=>subscriber.next(event),"callback");connection.addEventListener("close",callback),disposables.add(core.toDisposable(()=>connection.removeEventListener("close",callback)))}).pipe(operators.share()),error$:new rxjs.Observable(subscriber=>{const callback=__name(event=>subscriber.next(event),"callback");connection.addEventListener("error",callback),disposables.add(core.toDisposable(()=>connection.removeEventListener("error",callback)))}).pipe(operators.share()),message$:new rxjs.Observable(subscriber=>{const callback=__name(event=>subscriber.next(event),"callback");connection.addEventListener("message",callback),disposables.add(core.toDisposable(()=>connection.removeEventListener("message",callback)))}).pipe(operators.share())}}catch(e){return console.error(e),null}}};__name(_WebSocketService,"WebSocketService");let WebSocketService=_WebSocketService;const DEFAULT_MAX_RETRY_ATTEMPTS=3,DELAY_INTERVAL=1e3,RetryInterceptorFactory=__name((_accessor,params)=>{var _a2,_b;const maxRetryAttempts=(_a2=params==null?void 0:params.maxRetryAttempts)!=null?_a2:DEFAULT_MAX_RETRY_ATTEMPTS,delayInterval=(_b=params==null?void 0:params.delayInterval)!=null?_b:DELAY_INTERVAL;return(request,next)=>next(request).pipe(operators.retry({delay:delayInterval,count:maxRetryAttempts}))},"RetryInterceptorFactory"),ThresholdInterceptorFactory=__name(params=>{const handlers=[],ongoingHandlers=new Set,tick=__name(()=>{var _a2;for(;ongoingHandlers.size<((_a2=params==null?void 0:params.maxParallel)!=null?_a2:1)&&handlers.length>0;){const handler=handlers.shift();ongoingHandlers.add(handler),handler()}},"tick");return(request,next)=>new rxjs.Observable(observer=>{const handler=__name(()=>next(request).subscribe({next:__name(event=>observer.next(event),"next"),error:__name(err=>observer.next(err),"error"),complete:__name(()=>observer.complete(),"complete")}),"handler"),teardown=__name(()=>{ongoingHandlers.delete(handler),core.remove(handlers,handler),tick()},"teardown");return handlers.push(handler),tick(),teardown})},"ThresholdInterceptorFactory"),AuthInterceptorFactory=__name(params=>{const{errorStatusCodes,onAuthError}=params;return __name((request,next)=>next(request).pipe(rxjs.catchError(error=>(error instanceof HTTPResponseError&&errorStatusCodes.some(c=>c===error.status)&&onAuthError(),rxjs.throwError(()=>error)))),"authInterceptor")},"AuthInterceptorFactory"),createDefaultFetchCheck=__name((time=300)=>{let cancel=__name(()=>{},"noop");return _currentConfig=>new Promise(res=>{cancel();const t=setTimeout(()=>{res(!0)},time);cancel=__name(()=>{clearTimeout(t),res(!1)},"cancel")})},"createDefaultFetchCheck"),createDistributeResult=__name(()=>(result,list)=>list.map(config=>({config,result})),"createDistributeResult"),MergeInterceptorFactory=__name((config,options={})=>{const{isMatch,getParamsFromRequest,mergeParamsToRequest}=config,{fetchCheck=createDefaultFetchCheck(300),distributeResult=createDistributeResult()}=options,hookList=[],getPlainList=__name(_list=>_list.map(item=>item.config),"getPlainList");return(requestConfig,next)=>isMatch(requestConfig)?new rxjs.Observable(observer=>{const params=getParamsFromRequest(requestConfig);hookList.push({next:__name(v=>observer.next(v),"next"),error:__name(error=>observer.error(error),"error"),config:params});const list=getPlainList(hookList);fetchCheck(requestConfig).then(isFetch=>{if(isFetch){const currentHookList=[];list.forEach(config2=>{const index=hookList.findIndex(item=>item.config===config2);if(index>=0){const[hook]=hookList.splice(index,1);currentHookList.push(hook)}}),next(mergeParamsToRequest(list,requestConfig)).subscribe({next:__name(e=>{if(e.type===HTTPEventType.Response){const body=e.body,configList=distributeResult(body,list);currentHookList.forEach(hookItem=>{const res=configList.find(item=>item.config===hookItem.config);if(res){const response=new HTTPResponse({body:res.result,headers:e.headers,status:e.status,statusText:e.statusText});hookItem.next(response)}else hookItem.error("batch error")})}},"next"),complete:__name(()=>observer.complete(),"complete"),error:__name(e=>observer.error(e),"error")})}})}):next(requestConfig)},"MergeInterceptorFactory");exports2.AuthInterceptorFactory=AuthInterceptorFactory,exports2.FetchHTTPImplementation=FetchHTTPImplementation,exports2.HTTPEventType=HTTPEventType,exports2.HTTPHeaders=HTTPHeaders,exports2.HTTPProgress=HTTPProgress,exports2.HTTPRequest=HTTPRequest,exports2.HTTPResponse=HTTPResponse,exports2.HTTPResponseError=HTTPResponseError,exports2.HTTPStatusCode=HTTPStatusCode,exports2.IHTTPImplementation=IHTTPImplementation,exports2.ISocketService=ISocketService,exports2.MergeInterceptorFactory=MergeInterceptorFactory,exports2.ResponseHeader=ResponseHeader,exports2.RetryInterceptorFactory=RetryInterceptorFactory,exports2.ThresholdInterceptorFactory=ThresholdInterceptorFactory,exports2.WebSocketService=WebSocketService,exports2.XHRHTTPImplementation=XHRHTTPImplementation,Object.defineProperty(exports2,Symbol.toStringTag,{value:"Module"})});
|
|
2
|
+
`).forEach(header=>{const[name,value]=header.split(":");name&&value&&this._setHeader(name,value)})}_handleHeadersConstructorProps(headers){Object.entries(headers).forEach(([name,value])=>this._setHeader(name,value))}_handleHeaders(headers){headers.forEach((value,name)=>this._setHeader(name,value))}};__name(_HTTPHeaders,"HTTPHeaders");let HTTPHeaders=_HTTPHeaders;const IHTTPImplementation=core.createIdentifier("network.http-implementation"),_HTTPParams=class _HTTPParams{constructor(params){this.params=params}toString(){return this.params?Object.keys(this.params).map(key=>`${key}=${this.params[key]}`).join("&"):""}};__name(_HTTPParams,"HTTPParams");let HTTPParams=_HTTPParams,HTTPRequestUID=0;const _HTTPRequest=class _HTTPRequest{constructor(method,url,requestParams){__publicField(this,"uid",HTTPRequestUID++);this.method=method,this.url=url,this.requestParams=requestParams}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var _a2,_b;const params=(_b=(_a2=this.requestParams)==null?void 0:_a2.params)==null?void 0:_b.toString();return params?`${this.url}${this.url.includes("?")?"&":"?"}${params}`:this.url}getBody(){var _a2,_b;const contentType=(_a2=this.headers.get("Content-Type"))!=null?_a2:ApplicationJSONType,body=(_b=this.requestParams)==null?void 0:_b.body;return contentType===ApplicationJSONType&&body&&typeof body=="object"?JSON.stringify(body):body?`${body}`:null}getHeadersInit(){return this.headers.toHeadersInit()}};__name(_HTTPRequest,"HTTPRequest");let HTTPRequest=_HTTPRequest;var __defProp2=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp2(target,key,result),result},"__decorateClass"),__decorateParam=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam");exports2.HTTPService=(_a=class extends core.Disposable{constructor(_http){super();__publicField(this,"_interceptors",[]);__publicField(this,"_pipe");this._http=_http}registerHTTPInterceptor(interceptor){if(this._interceptors.indexOf(interceptor)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(interceptor),this._interceptors=this._interceptors.sort((a,b)=>{var _a2,_b;return((_a2=a.priority)!=null?_a2:0)-((_b=b.priority)!=null?_b:0)}),this._pipe=null,core.toDisposable(()=>core.remove(this._interceptors,interceptor))}get(url,params){return this._request("GET",url,params)}post(url,params){return this._request("POST",url,params)}put(url,params){return this._request("PUT",url,params)}delete(url,params){return this._request("DELETE",url,params)}patch(url,options){return this._request("PATCH",url,options)}getSSE(method,url,options){var _a2,_b;const headers=new HTTPHeaders(options==null?void 0:options.headers),params=new HTTPParams(options==null?void 0:options.params),request=new HTTPRequest(method,url,{headers,params,withCredentials:(_a2=options==null?void 0:options.withCredentials)!=null?_a2:!1,reportProgress:!0,responseType:(_b=options==null?void 0:options.responseType)!=null?_b:"json",body:["GET","DELETE"].includes(method)||options==null?void 0:options.body});return rxjs.of(request).pipe(operators.concatMap(request2=>this._runInterceptorsAndImplementation(request2)))}async _request(method,url,options){var _a2,_b;const headers=new HTTPHeaders(options==null?void 0:options.headers),params=new HTTPParams(options==null?void 0:options.params),request=new HTTPRequest(method,url,{headers,params,withCredentials:(_a2=options==null?void 0:options.withCredentials)!=null?_a2:!1,responseType:(_b=options==null?void 0:options.responseType)!=null?_b:"json",body:["GET","DELETE"].includes(method)||options==null?void 0:options.body}),events$=rxjs.of(request).pipe(operators.concatMap(request2=>this._runInterceptorsAndImplementation(request2)));return await rxjs.firstValueFrom(events$)}_runInterceptorsAndImplementation(request){return this._pipe||(this._pipe=this._interceptors.map(handler=>handler.interceptor).reduceRight((nextHandlerFunction,interceptorFunction)=>chainInterceptorFn(nextHandlerFunction,interceptorFunction),(requestFromPrevInterceptor,finalHandler)=>finalHandler(requestFromPrevInterceptor))),this._pipe(request,requestToNext=>this._http.send(requestToNext))}},__name(_a,"HTTPService"),_a),exports2.HTTPService=__decorateClass([__decorateParam(0,IHTTPImplementation)],exports2.HTTPService);function chainInterceptorFn(afterInterceptorChain,currentInterceptorFn){return(prevRequest,nextHandlerFn)=>currentInterceptorFn(prevRequest,nextRequest=>afterInterceptorChain(nextRequest,nextHandlerFn))}__name(chainInterceptorFn,"chainInterceptorFn");var HTTPEventType=(HTTPEventType2=>(HTTPEventType2[HTTPEventType2.DownloadProgress=0]="DownloadProgress",HTTPEventType2[HTTPEventType2.Response=1]="Response",HTTPEventType2))(HTTPEventType||{});const _HTTPResponse=class _HTTPResponse{constructor({body,headers,status,statusText}){__publicField(this,"type",1);__publicField(this,"body");__publicField(this,"headers");__publicField(this,"status");__publicField(this,"statusText");this.body=body,this.headers=headers,this.status=status,this.statusText=statusText}};__name(_HTTPResponse,"HTTPResponse");let HTTPResponse=_HTTPResponse;const _HTTPProgress=class _HTTPProgress{constructor(total,loaded,partialText){__publicField(this,"type",0);this.total=total,this.loaded=loaded,this.partialText=partialText}};__name(_HTTPProgress,"HTTPProgress");let HTTPProgress=_HTTPProgress;const _ResponseHeader=class _ResponseHeader{constructor(headers,status,statusText){this.headers=headers,this.status=status,this.statusText=statusText}};__name(_ResponseHeader,"ResponseHeader");let ResponseHeader=_ResponseHeader;const _HTTPResponseError=class _HTTPResponseError{constructor({headers,status,statusText,error}){__publicField(this,"headers");__publicField(this,"status");__publicField(this,"statusText");__publicField(this,"error");this.headers=headers,this.status=status,this.statusText=statusText,this.error=error}};__name(_HTTPResponseError,"HTTPResponseError");let HTTPResponseError=_HTTPResponseError;const SuccessStatusCodeLowerBound=200,ErrorStatusCodeLowerBound=300;var HTTPStatusCode=(HTTPStatusCode2=>(HTTPStatusCode2[HTTPStatusCode2.Continue=100]="Continue",HTTPStatusCode2[HTTPStatusCode2.SwitchingProtocols=101]="SwitchingProtocols",HTTPStatusCode2[HTTPStatusCode2.Processing=102]="Processing",HTTPStatusCode2[HTTPStatusCode2.EarlyHints=103]="EarlyHints",HTTPStatusCode2[HTTPStatusCode2.Ok=200]="Ok",HTTPStatusCode2[HTTPStatusCode2.Created=201]="Created",HTTPStatusCode2[HTTPStatusCode2.Accepted=202]="Accepted",HTTPStatusCode2[HTTPStatusCode2.NonAuthoritativeInformation=203]="NonAuthoritativeInformation",HTTPStatusCode2[HTTPStatusCode2.NoContent=204]="NoContent",HTTPStatusCode2[HTTPStatusCode2.ResetContent=205]="ResetContent",HTTPStatusCode2[HTTPStatusCode2.PartialContent=206]="PartialContent",HTTPStatusCode2[HTTPStatusCode2.MultiStatus=207]="MultiStatus",HTTPStatusCode2[HTTPStatusCode2.AlreadyReported=208]="AlreadyReported",HTTPStatusCode2[HTTPStatusCode2.ImUsed=226]="ImUsed",HTTPStatusCode2[HTTPStatusCode2.MultipleChoices=300]="MultipleChoices",HTTPStatusCode2[HTTPStatusCode2.MovedPermanently=301]="MovedPermanently",HTTPStatusCode2[HTTPStatusCode2.Found=302]="Found",HTTPStatusCode2[HTTPStatusCode2.SeeOther=303]="SeeOther",HTTPStatusCode2[HTTPStatusCode2.NotModified=304]="NotModified",HTTPStatusCode2[HTTPStatusCode2.UseProxy=305]="UseProxy",HTTPStatusCode2[HTTPStatusCode2.Unused=306]="Unused",HTTPStatusCode2[HTTPStatusCode2.TemporaryRedirect=307]="TemporaryRedirect",HTTPStatusCode2[HTTPStatusCode2.PermanentRedirect=308]="PermanentRedirect",HTTPStatusCode2[HTTPStatusCode2.BadRequest=400]="BadRequest",HTTPStatusCode2[HTTPStatusCode2.Unauthorized=401]="Unauthorized",HTTPStatusCode2[HTTPStatusCode2.PaymentRequired=402]="PaymentRequired",HTTPStatusCode2[HTTPStatusCode2.Forbidden=403]="Forbidden",HTTPStatusCode2[HTTPStatusCode2.NotFound=404]="NotFound",HTTPStatusCode2[HTTPStatusCode2.MethodNotAllowed=405]="MethodNotAllowed",HTTPStatusCode2[HTTPStatusCode2.NotAcceptable=406]="NotAcceptable",HTTPStatusCode2[HTTPStatusCode2.ProxyAuthenticationRequired=407]="ProxyAuthenticationRequired",HTTPStatusCode2[HTTPStatusCode2.RequestTimeout=408]="RequestTimeout",HTTPStatusCode2[HTTPStatusCode2.Conflict=409]="Conflict",HTTPStatusCode2[HTTPStatusCode2.Gone=410]="Gone",HTTPStatusCode2[HTTPStatusCode2.LengthRequired=411]="LengthRequired",HTTPStatusCode2[HTTPStatusCode2.PreconditionFailed=412]="PreconditionFailed",HTTPStatusCode2[HTTPStatusCode2.PayloadTooLarge=413]="PayloadTooLarge",HTTPStatusCode2[HTTPStatusCode2.UriTooLong=414]="UriTooLong",HTTPStatusCode2[HTTPStatusCode2.UnsupportedMediaType=415]="UnsupportedMediaType",HTTPStatusCode2[HTTPStatusCode2.RangeNotSatisfiable=416]="RangeNotSatisfiable",HTTPStatusCode2[HTTPStatusCode2.ExpectationFailed=417]="ExpectationFailed",HTTPStatusCode2[HTTPStatusCode2.ImATeapot=418]="ImATeapot",HTTPStatusCode2[HTTPStatusCode2.MisdirectedRequest=421]="MisdirectedRequest",HTTPStatusCode2[HTTPStatusCode2.UnprocessableEntity=422]="UnprocessableEntity",HTTPStatusCode2[HTTPStatusCode2.Locked=423]="Locked",HTTPStatusCode2[HTTPStatusCode2.FailedDependency=424]="FailedDependency",HTTPStatusCode2[HTTPStatusCode2.TooEarly=425]="TooEarly",HTTPStatusCode2[HTTPStatusCode2.UpgradeRequired=426]="UpgradeRequired",HTTPStatusCode2[HTTPStatusCode2.PreconditionRequired=428]="PreconditionRequired",HTTPStatusCode2[HTTPStatusCode2.TooManyRequests=429]="TooManyRequests",HTTPStatusCode2[HTTPStatusCode2.RequestHeaderFieldsTooLarge=431]="RequestHeaderFieldsTooLarge",HTTPStatusCode2[HTTPStatusCode2.UnavailableForLegalReasons=451]="UnavailableForLegalReasons",HTTPStatusCode2[HTTPStatusCode2.InternalServerError=500]="InternalServerError",HTTPStatusCode2[HTTPStatusCode2.NotImplemented=501]="NotImplemented",HTTPStatusCode2[HTTPStatusCode2.BadGateway=502]="BadGateway",HTTPStatusCode2[HTTPStatusCode2.ServiceUnavailable=503]="ServiceUnavailable",HTTPStatusCode2[HTTPStatusCode2.GatewayTimeout=504]="GatewayTimeout",HTTPStatusCode2[HTTPStatusCode2.HttpVersionNotSupported=505]="HttpVersionNotSupported",HTTPStatusCode2[HTTPStatusCode2.VariantAlsoNegotiates=506]="VariantAlsoNegotiates",HTTPStatusCode2[HTTPStatusCode2.InsufficientStorage=507]="InsufficientStorage",HTTPStatusCode2[HTTPStatusCode2.LoopDetected=508]="LoopDetected",HTTPStatusCode2[HTTPStatusCode2.NotExtended=510]="NotExtended",HTTPStatusCode2[HTTPStatusCode2.NetworkAuthenticationRequired=511]="NetworkAuthenticationRequired",HTTPStatusCode2))(HTTPStatusCode||{});const _FetchHTTPImplementation=class _FetchHTTPImplementation{send(request){return new rxjs.Observable(subscriber=>{const abortController=new AbortController;return this._send(request,subscriber,abortController).then(()=>{},error=>{subscriber.error(new HTTPResponseError({error}))}),()=>abortController.abort()})}async _send(request,subscriber,abortController){var _a2,_b;let response;try{const fetchParams=this._parseFetchParamsFromRequest(request);response=await fetch(request.getUrlWithParams(),{signal:abortController.signal,...fetchParams})}catch(error){subscriber.error(new HTTPResponseError({error,status:(_a2=error.status)!=null?_a2:0,statusText:(_b=error.statusText)!=null?_b:"Unknown Error",headers:error.headers}));return}const responseHeaders=new HTTPHeaders(response.headers),status=response.status,statusText=response.statusText;let body=null;response.body&&(body=await this._readBody(request,response,subscriber)),status>=HTTPStatusCode.Ok&&status<HTTPStatusCode.MultipleChoices?subscriber.next(new HTTPResponse({body,headers:responseHeaders,status,statusText})):subscriber.error(new HTTPResponseError({error:body,status,statusText,headers:responseHeaders})),subscriber.complete()}async _readBody(request,response,subscriber){var _a2,_b;const chunks=[],reader=response.body.getReader(),contentLength=response.headers.get("content-length");let receivedLength=0;const reportProgress=(_a2=request.requestParams)==null?void 0:_a2.reportProgress,responseType=request.responseType;let partialText,decoder;for(;;){const{done,value}=await reader.read();if(done)break;chunks.push(value),receivedLength+=value.length,reportProgress&&responseType==="text"&&(partialText=(partialText!=null?partialText:"")+(decoder!=null?decoder:decoder=new TextDecoder).decode(value,{stream:!0}),subscriber.next(new HTTPProgress(contentLength?Number.parseInt(contentLength,10):void 0,receivedLength,partialText)))}const all=mergeChunks(chunks,receivedLength);try{const contentType=(_b=response.headers.get("content-type"))!=null?_b:"";return deserialize(request,all,contentType)}catch(error){return subscriber.error(new HTTPResponseError({error,status:response.status,statusText:response.statusText,headers:new HTTPHeaders(response.headers)})),null}}_parseFetchParamsFromRequest(request){return{method:request.method,headers:request.getHeadersInit(),body:request.getBody(),credentials:request.withCredentials?"include":void 0}}};__name(_FetchHTTPImplementation,"FetchHTTPImplementation");let FetchHTTPImplementation=_FetchHTTPImplementation;function mergeChunks(chunks,totalLength){const all=new Uint8Array(totalLength);let position=0;for(const chunk of chunks)all.set(chunk,position),position+=chunk.length;return all}__name(mergeChunks,"mergeChunks");const XSSI_PREFIX=/^\)\]\}',?\n/;function deserialize(request,bin,contentType){switch(request.responseType){case"json":const text=new TextDecoder().decode(bin).replace(XSSI_PREFIX,"");return text===""?null:JSON.parse(text);case"text":return new TextDecoder().decode(bin);case"blob":return new Blob([bin],{type:contentType});case"arraybuffer":return bin.buffer;default:throw new Error(`[FetchHTTPImplementation]: unknown response type: ${request.responseType}.`)}}__name(deserialize,"deserialize");const _XHRHTTPImplementation=class _XHRHTTPImplementation{send(request){return new rxjs.Observable(observer=>{const xhr=new XMLHttpRequest;xhr.open(request.method,request.getUrlWithParams()),request.withCredentials&&(xhr.withCredentials=!0),request.headers.forEach((key,value)=>xhr.setRequestHeader(key,value.join(","))),request.headers.has("Accept")||xhr.setRequestHeader("Accept","application/json, text/plain, */*"),request.headers.has("Content-Type")||xhr.setRequestHeader("Content-Type","application/json;charset=UTF-8");const buildResponseHeader=__name(()=>{const statusText=xhr.statusText||"OK",headers=new HTTPHeaders(xhr.getAllResponseHeaders());return new ResponseHeader(headers,xhr.status,statusText)},"buildResponseHeader"),onLoadHandler=__name(()=>{const{headers,statusText,status}=buildResponseHeader(),{responseType}=request;let body2=null,error=null;status!==HTTPStatusCode.NoContent&&(body2=typeof xhr.response>"u"?xhr.responseText:xhr.response);let success=status>=SuccessStatusCodeLowerBound&&status<ErrorStatusCodeLowerBound;if(responseType==="json"&&typeof body2=="string"){const originalBody=body2;try{body2=body2?JSON.parse(body2):null}catch(e){success=!1,body2=originalBody,error=e}}success?observer.next(new HTTPResponse({body:body2,headers,status,statusText})):observer.error(new HTTPResponseError({error,headers,status,statusText}))},"onLoadHandler"),onErrorHandler=__name(error=>{const res=new HTTPResponseError({error,status:xhr.status||0,statusText:xhr.statusText||"Unknown Error",headers:buildResponseHeader().headers});observer.error(res)},"onErrorHandler");xhr.addEventListener("load",onLoadHandler),xhr.addEventListener("error",onErrorHandler),xhr.addEventListener("abort",onErrorHandler),xhr.addEventListener("timeout",onErrorHandler);const body=request.getBody();return xhr.send(body),()=>{xhr.readyState!==xhr.DONE&&xhr.abort(),xhr.removeEventListener("load",onLoadHandler),xhr.removeEventListener("error",onErrorHandler),xhr.removeEventListener("abort",onErrorHandler),xhr.removeEventListener("timeout",onErrorHandler)}})}};__name(_XHRHTTPImplementation,"XHRHTTPImplementation");let XHRHTTPImplementation=_XHRHTTPImplementation;const ISocketService=core.createIdentifier("univer.socket"),_WebSocketService=class _WebSocketService extends core.Disposable{createSocket(URL){try{const connection=new WebSocket(URL),disposables=new core.DisposableCollection;return{URL,close:__name((code,reason)=>{connection.close(code,reason),disposables.dispose()},"close"),send:__name(data=>{connection.send(data)},"send"),open$:new rxjs.Observable(subscriber=>{const callback=__name(event=>subscriber.next(event),"callback");connection.addEventListener("open",callback),disposables.add(core.toDisposable(()=>connection.removeEventListener("open",callback)))}).pipe(operators.share()),close$:new rxjs.Observable(subscriber=>{const callback=__name(event=>subscriber.next(event),"callback");connection.addEventListener("close",callback),disposables.add(core.toDisposable(()=>connection.removeEventListener("close",callback)))}).pipe(operators.share()),error$:new rxjs.Observable(subscriber=>{const callback=__name(event=>subscriber.next(event),"callback");connection.addEventListener("error",callback),disposables.add(core.toDisposable(()=>connection.removeEventListener("error",callback)))}).pipe(operators.share()),message$:new rxjs.Observable(subscriber=>{const callback=__name(event=>subscriber.next(event),"callback");connection.addEventListener("message",callback),disposables.add(core.toDisposable(()=>connection.removeEventListener("message",callback)))}).pipe(operators.share())}}catch(e){return console.error(e),null}}};__name(_WebSocketService,"WebSocketService");let WebSocketService=_WebSocketService;const DEFAULT_MAX_RETRY_ATTEMPTS=3,DELAY_INTERVAL=1e3,RetryInterceptorFactory=__name(params=>{var _a2,_b;const maxRetryAttempts=(_a2=params==null?void 0:params.maxRetryAttempts)!=null?_a2:DEFAULT_MAX_RETRY_ATTEMPTS,delayInterval=(_b=params==null?void 0:params.delayInterval)!=null?_b:DELAY_INTERVAL;return(request,next)=>next(request).pipe(operators.retry({delay:delayInterval,count:maxRetryAttempts}))},"RetryInterceptorFactory"),ThresholdInterceptorFactory=__name(params=>{const handlers=[],ongoingHandlers=new Set,tick=__name(()=>{var _a2;for(;ongoingHandlers.size<((_a2=params==null?void 0:params.maxParallel)!=null?_a2:1)&&handlers.length>0;){const handler=handlers.shift();ongoingHandlers.add(handler),handler()}},"tick");return(request,next)=>new rxjs.Observable(observer=>{const handler=__name(()=>next(request).subscribe({next:__name(event=>observer.next(event),"next"),error:__name(err=>observer.next(err),"error"),complete:__name(()=>observer.complete(),"complete")}),"handler"),teardown=__name(()=>{ongoingHandlers.delete(handler),core.remove(handlers,handler),tick()},"teardown");return handlers.push(handler),tick(),teardown})},"ThresholdInterceptorFactory"),AuthInterceptorFactory=__name(params=>{const{errorStatusCodes,onAuthError}=params;return __name((request,next)=>next(request).pipe(rxjs.catchError(error=>(error instanceof HTTPResponseError&&errorStatusCodes.some(c=>c===error.status)&&onAuthError(),rxjs.throwError(()=>error)))),"authInterceptor")},"AuthInterceptorFactory"),createDefaultFetchCheck=__name((time=300)=>{let cancel=__name(()=>{},"noop");return _currentConfig=>new Promise(res=>{cancel();const t=setTimeout(()=>{res(!0)},time);cancel=__name(()=>{clearTimeout(t),res(!1)},"cancel")})},"createDefaultFetchCheck"),createDistributeResult=__name(()=>(result,list)=>list.map(config=>({config,result})),"createDistributeResult"),MergeInterceptorFactory=__name((config,options={})=>{const{isMatch,getParamsFromRequest,mergeParamsToRequest}=config,{fetchCheck=createDefaultFetchCheck(300),distributeResult=createDistributeResult()}=options,hookList=[],getPlainList=__name(_list=>_list.map(item=>item.config),"getPlainList");return(requestConfig,next)=>isMatch(requestConfig)?new rxjs.Observable(observer=>{const params=getParamsFromRequest(requestConfig);hookList.push({next:__name(v=>observer.next(v),"next"),error:__name(error=>observer.error(error),"error"),config:params});const list=getPlainList(hookList);fetchCheck(requestConfig).then(isFetch=>{if(isFetch){const currentHookList=[];list.forEach(config2=>{const index=hookList.findIndex(item=>item.config===config2);if(index>=0){const[hook]=hookList.splice(index,1);currentHookList.push(hook)}}),next(mergeParamsToRequest(list,requestConfig)).subscribe({next:__name(e=>{if(e.type===HTTPEventType.Response){const body=e.body,configList=distributeResult(body,list);currentHookList.forEach(hookItem=>{const res=configList.find(item=>item.config===hookItem.config);if(res){const response=new HTTPResponse({body:res.result,headers:e.headers,status:e.status,statusText:e.statusText});hookItem.next(response)}else hookItem.error("batch error")})}},"next"),complete:__name(()=>observer.complete(),"complete"),error:__name(e=>observer.error(e),"error")})}})}):next(requestConfig)},"MergeInterceptorFactory");exports2.AuthInterceptorFactory=AuthInterceptorFactory,exports2.FetchHTTPImplementation=FetchHTTPImplementation,exports2.HTTPEventType=HTTPEventType,exports2.HTTPHeaders=HTTPHeaders,exports2.HTTPProgress=HTTPProgress,exports2.HTTPRequest=HTTPRequest,exports2.HTTPResponse=HTTPResponse,exports2.HTTPResponseError=HTTPResponseError,exports2.HTTPStatusCode=HTTPStatusCode,exports2.IHTTPImplementation=IHTTPImplementation,exports2.ISocketService=ISocketService,exports2.MergeInterceptorFactory=MergeInterceptorFactory,exports2.ResponseHeader=ResponseHeader,exports2.RetryInterceptorFactory=RetryInterceptorFactory,exports2.ThresholdInterceptorFactory=ThresholdInterceptorFactory,exports2.WebSocketService=WebSocketService,exports2.XHRHTTPImplementation=XHRHTTPImplementation,Object.defineProperty(exports2,Symbol.toStringTag,{value:"Module"})});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@univerjs/network",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.11",
|
|
4
4
|
"private": false,
|
|
5
5
|
"author": "DreamNum <developer@univer.ai>",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -46,15 +46,15 @@
|
|
|
46
46
|
],
|
|
47
47
|
"peerDependencies": {
|
|
48
48
|
"rxjs": ">=7.0.0",
|
|
49
|
-
"@univerjs/core": "0.2.
|
|
49
|
+
"@univerjs/core": "0.2.11"
|
|
50
50
|
},
|
|
51
51
|
"devDependencies": {
|
|
52
52
|
"rxjs": "^7.8.1",
|
|
53
53
|
"typescript": "^5.5.4",
|
|
54
|
-
"vite": "^5.4.
|
|
54
|
+
"vite": "^5.4.2",
|
|
55
55
|
"vitest": "^2.0.5",
|
|
56
|
-
"@univerjs/core": "0.2.
|
|
57
|
-
"@univerjs/shared": "0.2.
|
|
56
|
+
"@univerjs/core": "0.2.11",
|
|
57
|
+
"@univerjs/shared": "0.2.11"
|
|
58
58
|
},
|
|
59
59
|
"univerSpace": {
|
|
60
60
|
".": {
|