@univerjs/network 0.4.1 → 0.4.2-nightly.202410291606
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 +2 -2
- package/lib/es/index.js +105 -85
- package/lib/types/index.d.ts +1 -0
- package/lib/types/plugin.d.ts +20 -0
- package/lib/umd/index.js +2 -2
- package/package.json +3 -3
- package/LICENSE +0 -176
package/lib/cjs/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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}set(key,value){this._setHeader(key,value)}toHeadersInit(){var
|
|
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.error(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;
|
|
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}set(key,value){this._setHeader(key,value)}toHeadersInit(){var _a3,_b;const headers={};return this._headers.forEach((values,key)=>{headers[key]=values.join(",")}),(_a3=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 _a3,_b;const params=(_b=(_a3=this.requestParams)==null?void 0:_a3.params)==null?void 0:_b.toString();return params?`${this.url}${this.url.includes("?")?"&":"?"}${params}`:this.url}getBody(){var _a3,_b;const contentType=(_a3=this.headers.get("Content-Type"))!=null?_a3: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 __defProp$1=Object.defineProperty,__getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__decorateClass$1=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$1(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&&__defProp$1(target,key,result),result},"__decorateClass$1"),__decorateParam$1=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$1"),_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 _a3,_b;return((_a3=a.priority)!=null?_a3: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 _a3,_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:(_a3=options==null?void 0:options.withCredentials)!=null?_a3:!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 _a3,_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:(_a3=options==null?void 0:options.withCredentials)!=null?_a3:!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$1([__decorateParam$1(0,IHTTPImplementation)],exports.HTTPService);function chainInterceptorFn(afterInterceptorChain,currentInterceptorFn){return(prevRequest,nextHandlerFn)=>currentInterceptorFn(prevRequest,nextRequest=>afterInterceptorChain(nextRequest,nextHandlerFn))}__name(chainInterceptorFn,"chainInterceptorFn");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||{}),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 _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;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"),_a2;exports.UniverNetworkPlugin=(_a2=class extends core.Plugin{constructor(_config=void 0,_injector){super(),this._config=_config,this._injector=_injector}onStarting(){var _a3;core.registerDependencies(this._injector,core.mergeOverrideWithDependencies([[exports.HTTPService],[IHTTPImplementation,{useClass:XHRHTTPImplementation}]],(_a3=this._config)==null?void 0:_a3.override))}},__name(_a2,"UniverNetworkPlugin"),__publicField(_a2,"pluginName","UNIVER_NETWORK_PLUGIN"),_a2);exports.UniverNetworkPlugin=__decorateClass([__decorateParam(1,core.Inject(core.Injector))],exports.UniverNetworkPlugin);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 _a3,_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:(_a3=error.status)!=null?_a3: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 _a3,_b;const chunks=[],reader=response.body.getReader(),contentLength=response.headers.get("content-length");let receivedLength=0;const reportProgress=(_a3=request.requestParams)==null?void 0:_a3.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 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 _a3,_b;const maxRetryAttempts=(_a3=params==null?void 0:params.maxRetryAttempts)!=null?_a3: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 _a3;for(;ongoingHandlers.size<((_a3=params==null?void 0:params.maxParallel)!=null?_a3: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.error(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
|
@@ -2,7 +2,7 @@ var __defProp = Object.defineProperty;
|
|
|
2
2
|
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value;
|
|
3
3
|
var __name = (target, value) => __defProp(target, "name", { value, configurable: !0 });
|
|
4
4
|
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key != "symbol" ? key + "" : key, value);
|
|
5
|
-
import { createIdentifier, Disposable, toDisposable, remove, DisposableCollection } from "@univerjs/core";
|
|
5
|
+
import { createIdentifier, Disposable, toDisposable, remove, Inject, Injector, Plugin, registerDependencies, mergeOverrideWithDependencies, DisposableCollection } from "@univerjs/core";
|
|
6
6
|
import { of, firstValueFrom, Observable, catchError, throwError } from "rxjs";
|
|
7
7
|
import { concatMap, share, retry } from "rxjs/operators";
|
|
8
8
|
const ApplicationJSONType = "application/json", _HTTPHeaders = class _HTTPHeaders {
|
|
@@ -24,11 +24,11 @@ const ApplicationJSONType = "application/json", _HTTPHeaders = class _HTTPHeader
|
|
|
24
24
|
this._setHeader(key, value);
|
|
25
25
|
}
|
|
26
26
|
toHeadersInit() {
|
|
27
|
-
var
|
|
27
|
+
var _a3, _b;
|
|
28
28
|
const headers = {};
|
|
29
29
|
return this._headers.forEach((values, key) => {
|
|
30
30
|
headers[key] = values.join(",");
|
|
31
|
-
}), (
|
|
31
|
+
}), (_a3 = headers.accept) != null || (headers.accept = "application/json, text/plain, */*"), (_b = headers["content-type"]) != null || (headers["content-type"] = "application/json;charset=UTF-8"), headers;
|
|
32
32
|
}
|
|
33
33
|
_setHeader(name, value) {
|
|
34
34
|
const lowerCase = name.toLowerCase();
|
|
@@ -75,13 +75,13 @@ const _HTTPRequest = class _HTTPRequest {
|
|
|
75
75
|
return this.requestParams.responseType;
|
|
76
76
|
}
|
|
77
77
|
getUrlWithParams() {
|
|
78
|
-
var
|
|
79
|
-
const params = (_b = (
|
|
78
|
+
var _a3, _b;
|
|
79
|
+
const params = (_b = (_a3 = this.requestParams) == null ? void 0 : _a3.params) == null ? void 0 : _b.toString();
|
|
80
80
|
return params ? `${this.url}${this.url.includes("?") ? "&" : "?"}${params}` : this.url;
|
|
81
81
|
}
|
|
82
82
|
getBody() {
|
|
83
|
-
var
|
|
84
|
-
const contentType = (
|
|
83
|
+
var _a3, _b;
|
|
84
|
+
const contentType = (_a3 = this.headers.get("Content-Type")) != null ? _a3 : ApplicationJSONType, body = (_b = this.requestParams) == null ? void 0 : _b.body;
|
|
85
85
|
return contentType === ApplicationJSONType && body && typeof body == "object" ? JSON.stringify(body) : body ? `${body}` : null;
|
|
86
86
|
}
|
|
87
87
|
getHeadersInit() {
|
|
@@ -90,11 +90,11 @@ const _HTTPRequest = class _HTTPRequest {
|
|
|
90
90
|
};
|
|
91
91
|
__name(_HTTPRequest, "HTTPRequest");
|
|
92
92
|
let HTTPRequest = _HTTPRequest;
|
|
93
|
-
var
|
|
94
|
-
for (var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target, i = decorators.length - 1, decorator; i >= 0; i--)
|
|
93
|
+
var __defProp$1 = Object.defineProperty, __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor, __decorateClass$1 = /* @__PURE__ */ __name((decorators, target, key, kind) => {
|
|
94
|
+
for (var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$1(target, key) : target, i = decorators.length - 1, decorator; i >= 0; i--)
|
|
95
95
|
(decorator = decorators[i]) && (result = (kind ? decorator(target, key, result) : decorator(result)) || result);
|
|
96
|
-
return kind && result &&
|
|
97
|
-
}, "__decorateClass"), __decorateParam = /* @__PURE__ */ __name((index, decorator) => (target, key) => decorator(target, key, index), "__decorateParam"), _a;
|
|
96
|
+
return kind && result && __defProp$1(target, key, result), result;
|
|
97
|
+
}, "__decorateClass$1"), __decorateParam$1 = /* @__PURE__ */ __name((index, decorator) => (target, key) => decorator(target, key, index), "__decorateParam$1"), _a;
|
|
98
98
|
let HTTPService = (_a = class extends Disposable {
|
|
99
99
|
constructor(_http) {
|
|
100
100
|
super();
|
|
@@ -113,8 +113,8 @@ let HTTPService = (_a = class extends Disposable {
|
|
|
113
113
|
if (this._interceptors.indexOf(interceptor) !== -1)
|
|
114
114
|
throw new Error("[HTTPService]: The interceptor has already been registered!");
|
|
115
115
|
return this._interceptors.push(interceptor), this._interceptors = this._interceptors.sort((a, b) => {
|
|
116
|
-
var
|
|
117
|
-
return ((
|
|
116
|
+
var _a3, _b;
|
|
117
|
+
return ((_a3 = a.priority) != null ? _a3 : 0) - ((_b = b.priority) != null ? _b : 0);
|
|
118
118
|
}), this._pipe = null, toDisposable(() => remove(this._interceptors, interceptor));
|
|
119
119
|
}
|
|
120
120
|
get(url, params) {
|
|
@@ -133,11 +133,11 @@ let HTTPService = (_a = class extends Disposable {
|
|
|
133
133
|
return this._request("PATCH", url, options);
|
|
134
134
|
}
|
|
135
135
|
getSSE(method, url, options) {
|
|
136
|
-
var
|
|
136
|
+
var _a3, _b;
|
|
137
137
|
const headers = new HTTPHeaders(options == null ? void 0 : options.headers), params = new HTTPParams(options == null ? void 0 : options.params), request = new HTTPRequest(method, url, {
|
|
138
138
|
headers,
|
|
139
139
|
params,
|
|
140
|
-
withCredentials: (
|
|
140
|
+
withCredentials: (_a3 = options == null ? void 0 : options.withCredentials) != null ? _a3 : !1,
|
|
141
141
|
reportProgress: !0,
|
|
142
142
|
responseType: (_b = options == null ? void 0 : options.responseType) != null ? _b : "json",
|
|
143
143
|
body: ["GET", "DELETE"].includes(method) || options == null ? void 0 : options.body
|
|
@@ -146,11 +146,11 @@ let HTTPService = (_a = class extends Disposable {
|
|
|
146
146
|
}
|
|
147
147
|
/** The HTTP request implementations */
|
|
148
148
|
async _request(method, url, options) {
|
|
149
|
-
var
|
|
149
|
+
var _a3, _b;
|
|
150
150
|
const headers = new HTTPHeaders(options == null ? void 0 : options.headers), params = new HTTPParams(options == null ? void 0 : options.params), request = new HTTPRequest(method, url, {
|
|
151
151
|
headers,
|
|
152
152
|
params,
|
|
153
|
-
withCredentials: (
|
|
153
|
+
withCredentials: (_a3 = options == null ? void 0 : options.withCredentials) != null ? _a3 : !1,
|
|
154
154
|
// default value for withCredentials is false by MDN
|
|
155
155
|
responseType: (_b = options == null ? void 0 : options.responseType) != null ? _b : "json",
|
|
156
156
|
body: ["GET", "DELETE"].includes(method) || options == null ? void 0 : options.body
|
|
@@ -171,14 +171,15 @@ let HTTPService = (_a = class extends Disposable {
|
|
|
171
171
|
);
|
|
172
172
|
}
|
|
173
173
|
}, __name(_a, "HTTPService"), _a);
|
|
174
|
-
HTTPService = __decorateClass([
|
|
175
|
-
__decorateParam(0, IHTTPImplementation)
|
|
174
|
+
HTTPService = __decorateClass$1([
|
|
175
|
+
__decorateParam$1(0, IHTTPImplementation)
|
|
176
176
|
], HTTPService);
|
|
177
177
|
function chainInterceptorFn(afterInterceptorChain, currentInterceptorFn) {
|
|
178
178
|
return (prevRequest, nextHandlerFn) => currentInterceptorFn(prevRequest, (nextRequest) => afterInterceptorChain(nextRequest, nextHandlerFn));
|
|
179
179
|
}
|
|
180
180
|
__name(chainInterceptorFn, "chainInterceptorFn");
|
|
181
|
-
|
|
181
|
+
const SuccessStatusCodeLowerBound = 200, ErrorStatusCodeLowerBound = 300;
|
|
182
|
+
var HTTPStatusCode = /* @__PURE__ */ ((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 || {}), HTTPEventType = /* @__PURE__ */ ((HTTPEventType2) => (HTTPEventType2[HTTPEventType2.DownloadProgress = 0] = "DownloadProgress", HTTPEventType2[HTTPEventType2.Response = 1] = "Response", HTTPEventType2))(HTTPEventType || {});
|
|
182
183
|
const _HTTPResponse = class _HTTPResponse {
|
|
183
184
|
constructor({
|
|
184
185
|
body,
|
|
@@ -227,8 +228,81 @@ const _HTTPResponseError = class _HTTPResponseError {
|
|
|
227
228
|
};
|
|
228
229
|
__name(_HTTPResponseError, "HTTPResponseError");
|
|
229
230
|
let HTTPResponseError = _HTTPResponseError;
|
|
230
|
-
const
|
|
231
|
-
|
|
231
|
+
const _XHRHTTPImplementation = class _XHRHTTPImplementation {
|
|
232
|
+
send(request) {
|
|
233
|
+
return new Observable((observer) => {
|
|
234
|
+
const xhr = new XMLHttpRequest();
|
|
235
|
+
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");
|
|
236
|
+
const buildResponseHeader = /* @__PURE__ */ __name(() => {
|
|
237
|
+
const statusText = xhr.statusText || "OK", headers = new HTTPHeaders(xhr.getAllResponseHeaders());
|
|
238
|
+
return new ResponseHeader(headers, xhr.status, statusText);
|
|
239
|
+
}, "buildResponseHeader"), onLoadHandler = /* @__PURE__ */ __name(() => {
|
|
240
|
+
const { headers, statusText, status } = buildResponseHeader(), { responseType } = request;
|
|
241
|
+
let body2 = null, error = null;
|
|
242
|
+
status !== HTTPStatusCode.NoContent && (body2 = typeof xhr.response > "u" ? xhr.responseText : xhr.response);
|
|
243
|
+
let success = status >= SuccessStatusCodeLowerBound && status < ErrorStatusCodeLowerBound;
|
|
244
|
+
if (responseType === "json" && typeof body2 == "string") {
|
|
245
|
+
const originalBody = body2;
|
|
246
|
+
try {
|
|
247
|
+
body2 = body2 ? JSON.parse(body2) : null;
|
|
248
|
+
} catch (e) {
|
|
249
|
+
success = !1, body2 = originalBody, error = e;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
success ? observer.next(
|
|
253
|
+
new HTTPResponse({
|
|
254
|
+
body: body2,
|
|
255
|
+
headers,
|
|
256
|
+
status,
|
|
257
|
+
statusText
|
|
258
|
+
})
|
|
259
|
+
) : observer.error(
|
|
260
|
+
new HTTPResponseError({
|
|
261
|
+
error,
|
|
262
|
+
headers,
|
|
263
|
+
status,
|
|
264
|
+
statusText
|
|
265
|
+
})
|
|
266
|
+
);
|
|
267
|
+
}, "onLoadHandler"), onErrorHandler = /* @__PURE__ */ __name((error) => {
|
|
268
|
+
const res = new HTTPResponseError({
|
|
269
|
+
error,
|
|
270
|
+
status: xhr.status || 0,
|
|
271
|
+
statusText: xhr.statusText || "Unknown Error",
|
|
272
|
+
headers: buildResponseHeader().headers
|
|
273
|
+
});
|
|
274
|
+
observer.error(res);
|
|
275
|
+
}, "onErrorHandler");
|
|
276
|
+
xhr.addEventListener("load", onLoadHandler), xhr.addEventListener("error", onErrorHandler), xhr.addEventListener("abort", onErrorHandler), xhr.addEventListener("timeout", onErrorHandler);
|
|
277
|
+
const body = request.getBody();
|
|
278
|
+
return xhr.send(body), () => {
|
|
279
|
+
xhr.readyState !== xhr.DONE && xhr.abort(), xhr.removeEventListener("load", onLoadHandler), xhr.removeEventListener("error", onErrorHandler), xhr.removeEventListener("abort", onErrorHandler), xhr.removeEventListener("timeout", onErrorHandler);
|
|
280
|
+
};
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
__name(_XHRHTTPImplementation, "XHRHTTPImplementation");
|
|
285
|
+
let XHRHTTPImplementation = _XHRHTTPImplementation;
|
|
286
|
+
var __defProp2 = Object.defineProperty, __getOwnPropDesc = Object.getOwnPropertyDescriptor, __decorateClass = /* @__PURE__ */ __name((decorators, target, key, kind) => {
|
|
287
|
+
for (var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target, i = decorators.length - 1, decorator; i >= 0; i--)
|
|
288
|
+
(decorator = decorators[i]) && (result = (kind ? decorator(target, key, result) : decorator(result)) || result);
|
|
289
|
+
return kind && result && __defProp2(target, key, result), result;
|
|
290
|
+
}, "__decorateClass"), __decorateParam = /* @__PURE__ */ __name((index, decorator) => (target, key) => decorator(target, key, index), "__decorateParam"), _a2;
|
|
291
|
+
let UniverNetworkPlugin = (_a2 = class extends Plugin {
|
|
292
|
+
constructor(_config = void 0, _injector) {
|
|
293
|
+
super(), this._config = _config, this._injector = _injector;
|
|
294
|
+
}
|
|
295
|
+
onStarting() {
|
|
296
|
+
var _a3;
|
|
297
|
+
registerDependencies(this._injector, mergeOverrideWithDependencies([
|
|
298
|
+
[HTTPService],
|
|
299
|
+
[IHTTPImplementation, { useClass: XHRHTTPImplementation }]
|
|
300
|
+
], (_a3 = this._config) == null ? void 0 : _a3.override));
|
|
301
|
+
}
|
|
302
|
+
}, __name(_a2, "UniverNetworkPlugin"), __publicField(_a2, "pluginName", "UNIVER_NETWORK_PLUGIN"), _a2);
|
|
303
|
+
UniverNetworkPlugin = __decorateClass([
|
|
304
|
+
__decorateParam(1, Inject(Injector))
|
|
305
|
+
], UniverNetworkPlugin);
|
|
232
306
|
const _FetchHTTPImplementation = class _FetchHTTPImplementation {
|
|
233
307
|
send(request) {
|
|
234
308
|
return new Observable((subscriber) => {
|
|
@@ -242,7 +316,7 @@ const _FetchHTTPImplementation = class _FetchHTTPImplementation {
|
|
|
242
316
|
});
|
|
243
317
|
}
|
|
244
318
|
async _send(request, subscriber, abortController) {
|
|
245
|
-
var
|
|
319
|
+
var _a3, _b;
|
|
246
320
|
let response;
|
|
247
321
|
try {
|
|
248
322
|
const fetchParams = this._parseFetchParamsFromRequest(request);
|
|
@@ -253,7 +327,7 @@ const _FetchHTTPImplementation = class _FetchHTTPImplementation {
|
|
|
253
327
|
} catch (error) {
|
|
254
328
|
subscriber.error(new HTTPResponseError({
|
|
255
329
|
error,
|
|
256
|
-
status: (
|
|
330
|
+
status: (_a3 = error.status) != null ? _a3 : 0,
|
|
257
331
|
statusText: (_b = error.statusText) != null ? _b : "Unknown Error",
|
|
258
332
|
headers: error.headers
|
|
259
333
|
}));
|
|
@@ -274,10 +348,10 @@ const _FetchHTTPImplementation = class _FetchHTTPImplementation {
|
|
|
274
348
|
})), subscriber.complete();
|
|
275
349
|
}
|
|
276
350
|
async _readBody(request, response, subscriber) {
|
|
277
|
-
var
|
|
351
|
+
var _a3, _b;
|
|
278
352
|
const chunks = [], reader = response.body.getReader(), contentLength = response.headers.get("content-length");
|
|
279
353
|
let receivedLength = 0;
|
|
280
|
-
const reportProgress = (
|
|
354
|
+
const reportProgress = (_a3 = request.requestParams) == null ? void 0 : _a3.reportProgress, responseType = request.responseType;
|
|
281
355
|
let partialText, decoder;
|
|
282
356
|
for (; ; ) {
|
|
283
357
|
const { done, value } = await reader.read();
|
|
@@ -337,61 +411,6 @@ function deserialize(request, bin, contentType) {
|
|
|
337
411
|
}
|
|
338
412
|
}
|
|
339
413
|
__name(deserialize, "deserialize");
|
|
340
|
-
const _XHRHTTPImplementation = class _XHRHTTPImplementation {
|
|
341
|
-
send(request) {
|
|
342
|
-
return new Observable((observer) => {
|
|
343
|
-
const xhr = new XMLHttpRequest();
|
|
344
|
-
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");
|
|
345
|
-
const buildResponseHeader = /* @__PURE__ */ __name(() => {
|
|
346
|
-
const statusText = xhr.statusText || "OK", headers = new HTTPHeaders(xhr.getAllResponseHeaders());
|
|
347
|
-
return new ResponseHeader(headers, xhr.status, statusText);
|
|
348
|
-
}, "buildResponseHeader"), onLoadHandler = /* @__PURE__ */ __name(() => {
|
|
349
|
-
const { headers, statusText, status } = buildResponseHeader(), { responseType } = request;
|
|
350
|
-
let body2 = null, error = null;
|
|
351
|
-
status !== HTTPStatusCode.NoContent && (body2 = typeof xhr.response > "u" ? xhr.responseText : xhr.response);
|
|
352
|
-
let success = status >= SuccessStatusCodeLowerBound && status < ErrorStatusCodeLowerBound;
|
|
353
|
-
if (responseType === "json" && typeof body2 == "string") {
|
|
354
|
-
const originalBody = body2;
|
|
355
|
-
try {
|
|
356
|
-
body2 = body2 ? JSON.parse(body2) : null;
|
|
357
|
-
} catch (e) {
|
|
358
|
-
success = !1, body2 = originalBody, error = e;
|
|
359
|
-
}
|
|
360
|
-
}
|
|
361
|
-
success ? observer.next(
|
|
362
|
-
new HTTPResponse({
|
|
363
|
-
body: body2,
|
|
364
|
-
headers,
|
|
365
|
-
status,
|
|
366
|
-
statusText
|
|
367
|
-
})
|
|
368
|
-
) : observer.error(
|
|
369
|
-
new HTTPResponseError({
|
|
370
|
-
error,
|
|
371
|
-
headers,
|
|
372
|
-
status,
|
|
373
|
-
statusText
|
|
374
|
-
})
|
|
375
|
-
);
|
|
376
|
-
}, "onLoadHandler"), onErrorHandler = /* @__PURE__ */ __name((error) => {
|
|
377
|
-
const res = new HTTPResponseError({
|
|
378
|
-
error,
|
|
379
|
-
status: xhr.status || 0,
|
|
380
|
-
statusText: xhr.statusText || "Unknown Error",
|
|
381
|
-
headers: buildResponseHeader().headers
|
|
382
|
-
});
|
|
383
|
-
observer.error(res);
|
|
384
|
-
}, "onErrorHandler");
|
|
385
|
-
xhr.addEventListener("load", onLoadHandler), xhr.addEventListener("error", onErrorHandler), xhr.addEventListener("abort", onErrorHandler), xhr.addEventListener("timeout", onErrorHandler);
|
|
386
|
-
const body = request.getBody();
|
|
387
|
-
return xhr.send(body), () => {
|
|
388
|
-
xhr.readyState !== xhr.DONE && xhr.abort(), xhr.removeEventListener("load", onLoadHandler), xhr.removeEventListener("error", onErrorHandler), xhr.removeEventListener("abort", onErrorHandler), xhr.removeEventListener("timeout", onErrorHandler);
|
|
389
|
-
};
|
|
390
|
-
});
|
|
391
|
-
}
|
|
392
|
-
};
|
|
393
|
-
__name(_XHRHTTPImplementation, "XHRHTTPImplementation");
|
|
394
|
-
let XHRHTTPImplementation = _XHRHTTPImplementation;
|
|
395
414
|
const ISocketService = createIdentifier("univer.socket"), _WebSocketService = class _WebSocketService extends Disposable {
|
|
396
415
|
createSocket(URL) {
|
|
397
416
|
try {
|
|
@@ -429,13 +448,13 @@ const ISocketService = createIdentifier("univer.socket"), _WebSocketService = cl
|
|
|
429
448
|
__name(_WebSocketService, "WebSocketService");
|
|
430
449
|
let WebSocketService = _WebSocketService;
|
|
431
450
|
const DEFAULT_MAX_RETRY_ATTEMPTS = 3, DELAY_INTERVAL = 1e3, RetryInterceptorFactory = /* @__PURE__ */ __name((params) => {
|
|
432
|
-
var
|
|
433
|
-
const maxRetryAttempts = (
|
|
451
|
+
var _a3, _b;
|
|
452
|
+
const maxRetryAttempts = (_a3 = params == null ? void 0 : params.maxRetryAttempts) != null ? _a3 : DEFAULT_MAX_RETRY_ATTEMPTS, delayInterval = (_b = params == null ? void 0 : params.delayInterval) != null ? _b : DELAY_INTERVAL;
|
|
434
453
|
return (request, next) => next(request).pipe(retry({ delay: delayInterval, count: maxRetryAttempts }));
|
|
435
454
|
}, "RetryInterceptorFactory"), ThresholdInterceptorFactory = /* @__PURE__ */ __name((params) => {
|
|
436
455
|
const handlers = [], ongoingHandlers = /* @__PURE__ */ new Set(), tick = /* @__PURE__ */ __name(() => {
|
|
437
|
-
var
|
|
438
|
-
for (; ongoingHandlers.size < ((
|
|
456
|
+
var _a3;
|
|
457
|
+
for (; ongoingHandlers.size < ((_a3 = params == null ? void 0 : params.maxParallel) != null ? _a3 : 1) && handlers.length > 0; ) {
|
|
439
458
|
const handler = handlers.shift();
|
|
440
459
|
ongoingHandlers.add(handler), handler();
|
|
441
460
|
}
|
|
@@ -529,6 +548,7 @@ export {
|
|
|
529
548
|
ResponseHeader,
|
|
530
549
|
RetryInterceptorFactory,
|
|
531
550
|
ThresholdInterceptorFactory,
|
|
551
|
+
UniverNetworkPlugin,
|
|
532
552
|
WebSocketService,
|
|
533
553
|
XHRHTTPImplementation
|
|
534
554
|
};
|
package/lib/types/index.d.ts
CHANGED
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
* See the License for the specific language governing permissions and
|
|
14
14
|
* limitations under the License.
|
|
15
15
|
*/
|
|
16
|
+
export { UniverNetworkPlugin } from './plugin';
|
|
16
17
|
export { HTTPHeaders } from './services/http/headers';
|
|
17
18
|
export { HTTPService } from './services/http/http.service';
|
|
18
19
|
export { IHTTPImplementation } from './services/http/implementations/implementation';
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { DependencyOverride, Injector, Plugin } from '@univerjs/core';
|
|
2
|
+
export interface IUniverNetworkPluginConfig {
|
|
3
|
+
/**
|
|
4
|
+
* Build in dependencies that can be overridden:
|
|
5
|
+
*
|
|
6
|
+
* - {@link HTTPService}
|
|
7
|
+
* - {@link IHTTPImplementation}
|
|
8
|
+
*/
|
|
9
|
+
override?: DependencyOverride;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* This plugin add network services to the Univer instance.
|
|
13
|
+
*/
|
|
14
|
+
export declare class UniverNetworkPlugin extends Plugin {
|
|
15
|
+
private readonly _config;
|
|
16
|
+
protected readonly _injector: Injector;
|
|
17
|
+
static pluginName: string;
|
|
18
|
+
constructor(_config: Partial<IUniverNetworkPluginConfig> | undefined, _injector: Injector);
|
|
19
|
+
onStarting(): void;
|
|
20
|
+
}
|
package/lib/umd/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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}set(key,value){this._setHeader(key,value)}toHeadersInit(){var _a2,
|
|
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.error(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"})});
|
|
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,_b;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}set(key,value){this._setHeader(key,value)}toHeadersInit(){var _a2,_b2;const headers={};return this._headers.forEach((values,key)=>{headers[key]=values.join(",")}),(_a2=headers.accept)!=null||(headers.accept="application/json, text/plain, */*"),(_b2=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,_b2;const params=(_b2=(_a2=this.requestParams)==null?void 0:_a2.params)==null?void 0:_b2.toString();return params?`${this.url}${this.url.includes("?")?"&":"?"}${params}`:this.url}getBody(){var _a2,_b2;const contentType=(_a2=this.headers.get("Content-Type"))!=null?_a2:ApplicationJSONType,body=(_b2=this.requestParams)==null?void 0:_b2.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 __defProp$1=Object.defineProperty,__getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__decorateClass$1=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$1(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&&__defProp$1(target,key,result),result},"__decorateClass$1"),__decorateParam$1=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$1");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,_b2;return((_a2=a.priority)!=null?_a2:0)-((_b2=b.priority)!=null?_b2: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,_b2;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:(_b2=options==null?void 0:options.responseType)!=null?_b2:"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,_b2;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:(_b2=options==null?void 0:options.responseType)!=null?_b2:"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$1([__decorateParam$1(0,IHTTPImplementation)],exports2.HTTPService);function chainInterceptorFn(afterInterceptorChain,currentInterceptorFn){return(prevRequest,nextHandlerFn)=>currentInterceptorFn(prevRequest,nextRequest=>afterInterceptorChain(nextRequest,nextHandlerFn))}__name(chainInterceptorFn,"chainInterceptorFn");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||{}),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 _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;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.UniverNetworkPlugin=(_b=class extends core.Plugin{constructor(_config=void 0,_injector){super(),this._config=_config,this._injector=_injector}onStarting(){var _a2;core.registerDependencies(this._injector,core.mergeOverrideWithDependencies([[exports2.HTTPService],[IHTTPImplementation,{useClass:XHRHTTPImplementation}]],(_a2=this._config)==null?void 0:_a2.override))}},__name(_b,"UniverNetworkPlugin"),__publicField(_b,"pluginName","UNIVER_NETWORK_PLUGIN"),_b),exports2.UniverNetworkPlugin=__decorateClass([__decorateParam(1,core.Inject(core.Injector))],exports2.UniverNetworkPlugin);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,_b2;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:(_b2=error.statusText)!=null?_b2:"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,_b2;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=(_b2=response.headers.get("content-type"))!=null?_b2:"";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 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,_b2;const maxRetryAttempts=(_a2=params==null?void 0:params.maxRetryAttempts)!=null?_a2:DEFAULT_MAX_RETRY_ATTEMPTS,delayInterval=(_b2=params==null?void 0:params.delayInterval)!=null?_b2: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.error(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.4.
|
|
3
|
+
"version": "0.4.2-nightly.202410291606",
|
|
4
4
|
"private": false,
|
|
5
5
|
"author": "DreamNum <developer@univer.ai>",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -48,14 +48,14 @@
|
|
|
48
48
|
"rxjs": ">=7.0.0"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@univerjs/core": "0.4.
|
|
51
|
+
"@univerjs/core": "0.4.2-nightly.202410291606"
|
|
52
52
|
},
|
|
53
53
|
"devDependencies": {
|
|
54
54
|
"rxjs": "^7.8.1",
|
|
55
55
|
"typescript": "^5.6.3",
|
|
56
56
|
"vite": "^5.4.8",
|
|
57
57
|
"vitest": "^2.1.2",
|
|
58
|
-
"@univerjs-infra/shared": "0.4.
|
|
58
|
+
"@univerjs-infra/shared": "0.4.2"
|
|
59
59
|
},
|
|
60
60
|
"univerSpace": {
|
|
61
61
|
".": {
|
package/LICENSE
DELETED
|
@@ -1,176 +0,0 @@
|
|
|
1
|
-
Apache License
|
|
2
|
-
Version 2.0, January 2004
|
|
3
|
-
http://www.apache.org/licenses/
|
|
4
|
-
|
|
5
|
-
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
-
|
|
7
|
-
1. Definitions.
|
|
8
|
-
|
|
9
|
-
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
-
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
-
|
|
12
|
-
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
-
the copyright owner that is granting the License.
|
|
14
|
-
|
|
15
|
-
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
-
other entities that control, are controlled by, or are under common
|
|
17
|
-
control with that entity. For the purposes of this definition,
|
|
18
|
-
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
-
direction or management of such entity, whether by contract or
|
|
20
|
-
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
-
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
-
|
|
23
|
-
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
-
exercising permissions granted by this License.
|
|
25
|
-
|
|
26
|
-
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
-
including but not limited to software source code, documentation
|
|
28
|
-
source, and configuration files.
|
|
29
|
-
|
|
30
|
-
"Object" form shall mean any form resulting from mechanical
|
|
31
|
-
transformation or translation of a Source form, including but
|
|
32
|
-
not limited to compiled object code, generated documentation,
|
|
33
|
-
and conversions to other media types.
|
|
34
|
-
|
|
35
|
-
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
-
Object form, made available under the License, as indicated by a
|
|
37
|
-
copyright notice that is included in or attached to the work
|
|
38
|
-
(an example is provided in the Appendix below).
|
|
39
|
-
|
|
40
|
-
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
-
form, that is based on (or derived from) the Work and for which the
|
|
42
|
-
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
-
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
-
of this License, Derivative Works shall not include works that remain
|
|
45
|
-
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
-
the Work and Derivative Works thereof.
|
|
47
|
-
|
|
48
|
-
"Contribution" shall mean any work of authorship, including
|
|
49
|
-
the original version of the Work and any modifications or additions
|
|
50
|
-
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
-
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
-
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
-
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
-
means any form of electronic, verbal, or written communication sent
|
|
55
|
-
to the Licensor or its representatives, including but not limited to
|
|
56
|
-
communication on electronic mailing lists, source code control systems,
|
|
57
|
-
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
-
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
-
excluding communication that is conspicuously marked or otherwise
|
|
60
|
-
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
-
|
|
62
|
-
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
-
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
-
subsequently incorporated within the Work.
|
|
65
|
-
|
|
66
|
-
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
-
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
-
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
-
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
-
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
-
Work and such Derivative Works in Source or Object form.
|
|
72
|
-
|
|
73
|
-
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
-
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
-
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
-
(except as stated in this section) patent license to make, have made,
|
|
77
|
-
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
-
where such license applies only to those patent claims licensable
|
|
79
|
-
by such Contributor that are necessarily infringed by their
|
|
80
|
-
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
-
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
-
institute patent litigation against any entity (including a
|
|
83
|
-
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
-
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
-
or contributory patent infringement, then any patent licenses
|
|
86
|
-
granted to You under this License for that Work shall terminate
|
|
87
|
-
as of the date such litigation is filed.
|
|
88
|
-
|
|
89
|
-
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
-
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
-
modifications, and in Source or Object form, provided that You
|
|
92
|
-
meet the following conditions:
|
|
93
|
-
|
|
94
|
-
(a) You must give any other recipients of the Work or
|
|
95
|
-
Derivative Works a copy of this License; and
|
|
96
|
-
|
|
97
|
-
(b) You must cause any modified files to carry prominent notices
|
|
98
|
-
stating that You changed the files; and
|
|
99
|
-
|
|
100
|
-
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
-
that You distribute, all copyright, patent, trademark, and
|
|
102
|
-
attribution notices from the Source form of the Work,
|
|
103
|
-
excluding those notices that do not pertain to any part of
|
|
104
|
-
the Derivative Works; and
|
|
105
|
-
|
|
106
|
-
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
-
distribution, then any Derivative Works that You distribute must
|
|
108
|
-
include a readable copy of the attribution notices contained
|
|
109
|
-
within such NOTICE file, excluding those notices that do not
|
|
110
|
-
pertain to any part of the Derivative Works, in at least one
|
|
111
|
-
of the following places: within a NOTICE text file distributed
|
|
112
|
-
as part of the Derivative Works; within the Source form or
|
|
113
|
-
documentation, if provided along with the Derivative Works; or,
|
|
114
|
-
within a display generated by the Derivative Works, if and
|
|
115
|
-
wherever such third-party notices normally appear. The contents
|
|
116
|
-
of the NOTICE file are for informational purposes only and
|
|
117
|
-
do not modify the License. You may add Your own attribution
|
|
118
|
-
notices within Derivative Works that You distribute, alongside
|
|
119
|
-
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
-
that such additional attribution notices cannot be construed
|
|
121
|
-
as modifying the License.
|
|
122
|
-
|
|
123
|
-
You may add Your own copyright statement to Your modifications and
|
|
124
|
-
may provide additional or different license terms and conditions
|
|
125
|
-
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
-
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
-
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
-
the conditions stated in this License.
|
|
129
|
-
|
|
130
|
-
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
-
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
-
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
-
this License, without any additional terms or conditions.
|
|
134
|
-
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
-
the terms of any separate license agreement you may have executed
|
|
136
|
-
with Licensor regarding such Contributions.
|
|
137
|
-
|
|
138
|
-
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
-
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
-
except as required for reasonable and customary use in describing the
|
|
141
|
-
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
-
|
|
143
|
-
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
-
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
-
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
-
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
-
implied, including, without limitation, any warranties or conditions
|
|
148
|
-
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
-
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
-
appropriateness of using or redistributing the Work and assume any
|
|
151
|
-
risks associated with Your exercise of permissions under this License.
|
|
152
|
-
|
|
153
|
-
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
-
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
-
unless required by applicable law (such as deliberate and grossly
|
|
156
|
-
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
-
liable to You for damages, including any direct, indirect, special,
|
|
158
|
-
incidental, or consequential damages of any character arising as a
|
|
159
|
-
result of this License or out of the use or inability to use the
|
|
160
|
-
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
-
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
-
other commercial damages or losses), even if such Contributor
|
|
163
|
-
has been advised of the possibility of such damages.
|
|
164
|
-
|
|
165
|
-
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
-
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
-
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
-
or other liability obligations and/or rights consistent with this
|
|
169
|
-
License. However, in accepting such obligations, You may act only
|
|
170
|
-
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
-
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
-
defend, and hold each Contributor harmless for any liability
|
|
173
|
-
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
-
of your accepting any such warranty or additional liability.
|
|
175
|
-
|
|
176
|
-
END OF TERMS AND CONDITIONS
|