@univerjs/network 0.1.0-beta.2 → 0.1.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/umd/index.js CHANGED
@@ -1,422 +1,2 @@
1
- (function(global, factory) {
2
- typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require("@univerjs/core"), require("rxjs"), require("rxjs/operators"), require("@wendellhu/redi")) : typeof define === "function" && define.amd ? define(["exports", "@univerjs/core", "rxjs", "rxjs/operators", "@wendellhu/redi"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.UniverNetwork = {}, global.UniverCore, global.rxjs, global.rxjs.operators, global["@wendellhu/redi"]));
3
- })(this, function(exports2, core, rxjs, operators, redi) {
4
- "use strict";var __defProp = Object.defineProperty;
5
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
- var __publicField = (obj, key, value) => {
7
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
8
- return value;
9
- };
10
-
11
- const ApplicationJSONType = "application/json";
12
- class HTTPHeaders {
13
- constructor(headers) {
14
- __publicField(this, "_headers", /* @__PURE__ */ new Map());
15
- if (typeof headers === "string") {
16
- headers.split("\n").forEach((header) => {
17
- const [name, value] = header.split(":");
18
- if (name && value) {
19
- this._setHeader(name, value);
20
- }
21
- });
22
- } else {
23
- if (headers) {
24
- Object.keys(headers).forEach(([name, value]) => {
25
- this._setHeader(name, value);
26
- });
27
- }
28
- }
29
- }
30
- forEach(callback) {
31
- this._headers.forEach((v, key) => callback(key, v));
32
- }
33
- has(key) {
34
- return !!this._headers.has(key.toLowerCase());
35
- }
36
- get(key) {
37
- const k = key.toLowerCase();
38
- return this._headers.has(k) ? this._headers.get(k) : null;
39
- }
40
- _setHeader(name, value) {
41
- const lowerCase = name.toLowerCase();
42
- if (this._headers.has(lowerCase)) {
43
- this._headers.get(lowerCase).push(value.toString());
44
- } else {
45
- this._headers.set(lowerCase, [value.toString()]);
46
- }
47
- }
48
- }
49
- const IHTTPImplementation = redi.createIdentifier("univer-pro.network.http-implementation");
50
- class HTTPParams {
51
- constructor(params) {
52
- this.params = params;
53
- }
54
- toString() {
55
- if (!this.params) {
56
- return "";
57
- }
58
- return Object.keys(this.params).map((key) => `${key}=${this.params[key]}`).join("&");
59
- }
60
- }
61
- class HTTPRequest {
62
- constructor(method, url, requestParams) {
63
- this.method = method;
64
- this.url = url;
65
- this.requestParams = requestParams;
66
- }
67
- get headers() {
68
- return this.requestParams.headers;
69
- }
70
- get withCredentials() {
71
- return this.requestParams.withCredentials;
72
- }
73
- get responseType() {
74
- return this.requestParams.responseType;
75
- }
76
- getUrlWithParams() {
77
- var _a, _b;
78
- const params = (_b = (_a = this.requestParams) == null ? void 0 : _a.params) == null ? void 0 : _b.toString();
79
- if (!params) {
80
- return this.url;
81
- }
82
- return `${this.url}${this.url.includes("?") ? "&" : "?"}${params}`;
83
- }
84
- getBody() {
85
- var _a;
86
- const contentType = this.headers.get("Content-Type") ?? ApplicationJSONType;
87
- const body = (_a = this.requestParams) == null ? void 0 : _a.body;
88
- if (contentType === ApplicationJSONType && body && typeof body === "object") {
89
- return JSON.stringify(body);
90
- }
91
- return body ? `${body}` : null;
92
- }
93
- }
94
- class HTTPResponse {
95
- constructor({
96
- body,
97
- headers,
98
- status,
99
- statusText
100
- }) {
101
- __publicField(this, "body");
102
- __publicField(this, "headers");
103
- __publicField(this, "status");
104
- __publicField(this, "statusText");
105
- this.body = body;
106
- this.headers = headers;
107
- this.status = status;
108
- this.statusText = statusText;
109
- }
110
- }
111
- class HTTPResponseError {
112
- constructor({
113
- headers,
114
- status,
115
- statusText,
116
- error
117
- }) {
118
- __publicField(this, "headers");
119
- __publicField(this, "status");
120
- __publicField(this, "statusText");
121
- __publicField(this, "error");
122
- this.headers = headers;
123
- this.status = status;
124
- this.statusText = statusText;
125
- this.error = error;
126
- }
127
- }
128
- class ResponseHeader {
129
- constructor(headers, status, statusText) {
130
- this.headers = headers;
131
- this.status = status;
132
- this.statusText = statusText;
133
- }
134
- }
135
- var __defProp2 = Object.defineProperty;
136
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
137
- var __decorateClass = (decorators, target, key, kind) => {
138
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
139
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
140
- if (decorator = decorators[i])
141
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
142
- if (kind && result)
143
- __defProp2(target, key, result);
144
- return result;
145
- };
146
- var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
147
- exports2.HTTPService = class HTTPService extends core.Disposable {
148
- constructor(_http) {
149
- super();
150
- __publicField(this, "_interceptors", []);
151
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
152
- __publicField(this, "_pipe");
153
- this._http = _http;
154
- }
155
- registerHTTPInterceptor(interceptor) {
156
- if (this._interceptors.indexOf(interceptor) !== -1) {
157
- throw new Error("[HTTPService]: The interceptor has already been registered!");
158
- }
159
- this._interceptors.push(interceptor);
160
- this._interceptors = this._interceptors.sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));
161
- this._pipe = null;
162
- return core.toDisposable(() => core.remove(this._interceptors, interceptor));
163
- }
164
- get(url, options) {
165
- return this._request("GET", url, options);
166
- }
167
- post(url, options) {
168
- return this._request("POST", url, options);
169
- }
170
- put(url, options) {
171
- return this._request("PUT", url, options);
172
- }
173
- delete(url, options) {
174
- return this._request("DELETE", url, options);
175
- }
176
- /** The HTTP request implementations */
177
- async _request(method, url, options) {
178
- const headers = new HTTPHeaders(options == null ? void 0 : options.headers);
179
- const params = new HTTPParams(options == null ? void 0 : options.params);
180
- const request = new HTTPRequest(method, url, {
181
- headers,
182
- params,
183
- withCredentials: (options == null ? void 0 : options.withCredentials) ?? false,
184
- // default value for withCredentials is false by MDN
185
- responseType: (options == null ? void 0 : options.responseType) ?? "json",
186
- body: options == null ? void 0 : options.body
187
- });
188
- const events$ = rxjs.of(request).pipe(
189
- operators.concatMap((request2) => this._runInterceptorsAndImplementation(request2))
190
- );
191
- const result = await rxjs.firstValueFrom(events$);
192
- if (result instanceof HTTPResponse) {
193
- return result;
194
- }
195
- throw new Error(`${result.error}`);
196
- }
197
- _runInterceptorsAndImplementation(request) {
198
- if (!this._pipe) {
199
- this._pipe = this._interceptors.map((handler) => handler.interceptor).reduceRight(
200
- (nextHandlerFunction, interceptorFunction) => chainInterceptorFn(nextHandlerFunction, interceptorFunction),
201
- (requestFromPrevInterceptor, finalHandler) => finalHandler(requestFromPrevInterceptor)
202
- );
203
- }
204
- return this._pipe(
205
- request,
206
- (requestToNext) => this._http.send(requestToNext)
207
- /* final handler */
208
- );
209
- }
210
- };
211
- exports2.HTTPService = __decorateClass([
212
- __decorateParam(0, IHTTPImplementation)
213
- ], exports2.HTTPService);
214
- function chainInterceptorFn(afterInterceptorChain, currentInterceptorFn) {
215
- return (prevRequest, nextHandlerFn) => currentInterceptorFn(prevRequest, (nextRequest) => afterInterceptorChain(nextRequest, nextHandlerFn));
216
- }
217
- const SuccessStatusCodeLowerBound = 200;
218
- const ErrorStatusCodeLowerBound = 300;
219
- var HTTPStatusCode = /* @__PURE__ */ ((HTTPStatusCode2) => {
220
- HTTPStatusCode2[HTTPStatusCode2["Continue"] = 100] = "Continue";
221
- HTTPStatusCode2[HTTPStatusCode2["SwitchingProtocols"] = 101] = "SwitchingProtocols";
222
- HTTPStatusCode2[HTTPStatusCode2["Processing"] = 102] = "Processing";
223
- HTTPStatusCode2[HTTPStatusCode2["EarlyHints"] = 103] = "EarlyHints";
224
- HTTPStatusCode2[HTTPStatusCode2["Ok"] = 200] = "Ok";
225
- HTTPStatusCode2[HTTPStatusCode2["Created"] = 201] = "Created";
226
- HTTPStatusCode2[HTTPStatusCode2["Accepted"] = 202] = "Accepted";
227
- HTTPStatusCode2[HTTPStatusCode2["NonAuthoritativeInformation"] = 203] = "NonAuthoritativeInformation";
228
- HTTPStatusCode2[HTTPStatusCode2["NoContent"] = 204] = "NoContent";
229
- HTTPStatusCode2[HTTPStatusCode2["ResetContent"] = 205] = "ResetContent";
230
- HTTPStatusCode2[HTTPStatusCode2["PartialContent"] = 206] = "PartialContent";
231
- HTTPStatusCode2[HTTPStatusCode2["MultiStatus"] = 207] = "MultiStatus";
232
- HTTPStatusCode2[HTTPStatusCode2["AlreadyReported"] = 208] = "AlreadyReported";
233
- HTTPStatusCode2[HTTPStatusCode2["ImUsed"] = 226] = "ImUsed";
234
- HTTPStatusCode2[HTTPStatusCode2["MultipleChoices"] = 300] = "MultipleChoices";
235
- HTTPStatusCode2[HTTPStatusCode2["MovedPermanently"] = 301] = "MovedPermanently";
236
- HTTPStatusCode2[HTTPStatusCode2["Found"] = 302] = "Found";
237
- HTTPStatusCode2[HTTPStatusCode2["SeeOther"] = 303] = "SeeOther";
238
- HTTPStatusCode2[HTTPStatusCode2["NotModified"] = 304] = "NotModified";
239
- HTTPStatusCode2[HTTPStatusCode2["UseProxy"] = 305] = "UseProxy";
240
- HTTPStatusCode2[HTTPStatusCode2["Unused"] = 306] = "Unused";
241
- HTTPStatusCode2[HTTPStatusCode2["TemporaryRedirect"] = 307] = "TemporaryRedirect";
242
- HTTPStatusCode2[HTTPStatusCode2["PermanentRedirect"] = 308] = "PermanentRedirect";
243
- HTTPStatusCode2[HTTPStatusCode2["BadRequest"] = 400] = "BadRequest";
244
- HTTPStatusCode2[HTTPStatusCode2["Unauthorized"] = 401] = "Unauthorized";
245
- HTTPStatusCode2[HTTPStatusCode2["PaymentRequired"] = 402] = "PaymentRequired";
246
- HTTPStatusCode2[HTTPStatusCode2["Forbidden"] = 403] = "Forbidden";
247
- HTTPStatusCode2[HTTPStatusCode2["NotFound"] = 404] = "NotFound";
248
- HTTPStatusCode2[HTTPStatusCode2["MethodNotAllowed"] = 405] = "MethodNotAllowed";
249
- HTTPStatusCode2[HTTPStatusCode2["NotAcceptable"] = 406] = "NotAcceptable";
250
- HTTPStatusCode2[HTTPStatusCode2["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired";
251
- HTTPStatusCode2[HTTPStatusCode2["RequestTimeout"] = 408] = "RequestTimeout";
252
- HTTPStatusCode2[HTTPStatusCode2["Conflict"] = 409] = "Conflict";
253
- HTTPStatusCode2[HTTPStatusCode2["Gone"] = 410] = "Gone";
254
- HTTPStatusCode2[HTTPStatusCode2["LengthRequired"] = 411] = "LengthRequired";
255
- HTTPStatusCode2[HTTPStatusCode2["PreconditionFailed"] = 412] = "PreconditionFailed";
256
- HTTPStatusCode2[HTTPStatusCode2["PayloadTooLarge"] = 413] = "PayloadTooLarge";
257
- HTTPStatusCode2[HTTPStatusCode2["UriTooLong"] = 414] = "UriTooLong";
258
- HTTPStatusCode2[HTTPStatusCode2["UnsupportedMediaType"] = 415] = "UnsupportedMediaType";
259
- HTTPStatusCode2[HTTPStatusCode2["RangeNotSatisfiable"] = 416] = "RangeNotSatisfiable";
260
- HTTPStatusCode2[HTTPStatusCode2["ExpectationFailed"] = 417] = "ExpectationFailed";
261
- HTTPStatusCode2[HTTPStatusCode2["ImATeapot"] = 418] = "ImATeapot";
262
- HTTPStatusCode2[HTTPStatusCode2["MisdirectedRequest"] = 421] = "MisdirectedRequest";
263
- HTTPStatusCode2[HTTPStatusCode2["UnprocessableEntity"] = 422] = "UnprocessableEntity";
264
- HTTPStatusCode2[HTTPStatusCode2["Locked"] = 423] = "Locked";
265
- HTTPStatusCode2[HTTPStatusCode2["FailedDependency"] = 424] = "FailedDependency";
266
- HTTPStatusCode2[HTTPStatusCode2["TooEarly"] = 425] = "TooEarly";
267
- HTTPStatusCode2[HTTPStatusCode2["UpgradeRequired"] = 426] = "UpgradeRequired";
268
- HTTPStatusCode2[HTTPStatusCode2["PreconditionRequired"] = 428] = "PreconditionRequired";
269
- HTTPStatusCode2[HTTPStatusCode2["TooManyRequests"] = 429] = "TooManyRequests";
270
- HTTPStatusCode2[HTTPStatusCode2["RequestHeaderFieldsTooLarge"] = 431] = "RequestHeaderFieldsTooLarge";
271
- HTTPStatusCode2[HTTPStatusCode2["UnavailableForLegalReasons"] = 451] = "UnavailableForLegalReasons";
272
- HTTPStatusCode2[HTTPStatusCode2["InternalServerError"] = 500] = "InternalServerError";
273
- HTTPStatusCode2[HTTPStatusCode2["NotImplemented"] = 501] = "NotImplemented";
274
- HTTPStatusCode2[HTTPStatusCode2["BadGateway"] = 502] = "BadGateway";
275
- HTTPStatusCode2[HTTPStatusCode2["ServiceUnavailable"] = 503] = "ServiceUnavailable";
276
- HTTPStatusCode2[HTTPStatusCode2["GatewayTimeout"] = 504] = "GatewayTimeout";
277
- HTTPStatusCode2[HTTPStatusCode2["HttpVersionNotSupported"] = 505] = "HttpVersionNotSupported";
278
- HTTPStatusCode2[HTTPStatusCode2["VariantAlsoNegotiates"] = 506] = "VariantAlsoNegotiates";
279
- HTTPStatusCode2[HTTPStatusCode2["InsufficientStorage"] = 507] = "InsufficientStorage";
280
- HTTPStatusCode2[HTTPStatusCode2["LoopDetected"] = 508] = "LoopDetected";
281
- HTTPStatusCode2[HTTPStatusCode2["NotExtended"] = 510] = "NotExtended";
282
- HTTPStatusCode2[HTTPStatusCode2["NetworkAuthenticationRequired"] = 511] = "NetworkAuthenticationRequired";
283
- return HTTPStatusCode2;
284
- })(HTTPStatusCode || {});
285
- class XHRHTTPImplementation {
286
- send(request) {
287
- return new rxjs.Observable((observer) => {
288
- const xhr = new XMLHttpRequest();
289
- xhr.open(request.method, request.getUrlWithParams());
290
- if (request.withCredentials) {
291
- xhr.withCredentials = true;
292
- }
293
- request.headers.forEach((key, value) => xhr.setRequestHeader(key, value.join(",")));
294
- if (!request.headers.has("Accept")) {
295
- xhr.setRequestHeader("Accept", "application/json, text/plain, */*");
296
- }
297
- if (!request.headers.has("Content-Type")) {
298
- xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
299
- }
300
- const buildResponseHeader = () => {
301
- const statusText = xhr.statusText || "OK";
302
- const headers = new HTTPHeaders(xhr.getAllResponseHeaders());
303
- return new ResponseHeader(headers, xhr.status, statusText);
304
- };
305
- const onLoadHandler = () => {
306
- const { headers, statusText, status } = buildResponseHeader();
307
- const { responseType } = request;
308
- let body2 = null;
309
- let error = null;
310
- if (status !== HTTPStatusCode.NoContent) {
311
- body2 = typeof xhr.response === "undefined" ? xhr.responseText : xhr.response;
312
- }
313
- let success = status >= SuccessStatusCodeLowerBound && status < ErrorStatusCodeLowerBound;
314
- if (responseType === "json" && typeof body2 === "string") {
315
- const originalBody = body2;
316
- try {
317
- body2 = body2 ? JSON.parse(body2) : null;
318
- } catch (e) {
319
- success = false;
320
- body2 = originalBody;
321
- error = e;
322
- }
323
- }
324
- if (success) {
325
- observer.next(
326
- new HTTPResponse({
327
- body: body2,
328
- headers,
329
- status,
330
- statusText
331
- })
332
- );
333
- } else {
334
- observer.next(
335
- new HTTPResponseError({
336
- error,
337
- headers,
338
- status,
339
- statusText
340
- })
341
- );
342
- }
343
- };
344
- const onErrorHandler = (error) => {
345
- const res = new HTTPResponseError({
346
- error,
347
- status: xhr.status || 0,
348
- statusText: xhr.statusText || "Unknown Error",
349
- headers: buildResponseHeader().headers
350
- });
351
- observer.next(res);
352
- };
353
- xhr.addEventListener("load", onLoadHandler);
354
- xhr.addEventListener("error", onErrorHandler);
355
- xhr.addEventListener("abort", onErrorHandler);
356
- xhr.addEventListener("timeout", onErrorHandler);
357
- const body = request.getBody();
358
- xhr.send(body);
359
- return () => {
360
- if (xhr.readyState !== xhr.DONE) {
361
- xhr.abort();
362
- }
363
- xhr.removeEventListener("load", onLoadHandler);
364
- xhr.removeEventListener("error", onErrorHandler);
365
- xhr.removeEventListener("abort", onErrorHandler);
366
- xhr.removeEventListener("timeout", onErrorHandler);
367
- };
368
- });
369
- }
370
- }
371
- const ISocketService = redi.createIdentifier("univer.socket");
372
- class WebSocketService extends core.Disposable {
373
- createSocket(URL) {
374
- try {
375
- const connection = new WebSocket(URL);
376
- const disposables = new core.DisposableCollection();
377
- const webSocket = {
378
- URL,
379
- close: (code, reason) => {
380
- connection.close(code, reason);
381
- disposables.dispose();
382
- },
383
- send: (data) => {
384
- connection.send(data);
385
- },
386
- open$: new rxjs.Observable((subscriber) => {
387
- const callback = (event) => subscriber.next(event);
388
- connection.addEventListener("open", callback);
389
- disposables.add(core.toDisposable(() => connection.removeEventListener("open", callback)));
390
- }).pipe(operators.share()),
391
- close$: new rxjs.Observable((subscriber) => {
392
- const callback = (event) => subscriber.next(event);
393
- connection.addEventListener("close", callback);
394
- disposables.add(core.toDisposable(() => connection.removeEventListener("close", callback)));
395
- }).pipe(operators.share()),
396
- error$: new rxjs.Observable((subscriber) => {
397
- const callback = (event) => subscriber.next(event);
398
- connection.addEventListener("error", callback);
399
- disposables.add(core.toDisposable(() => connection.removeEventListener("error", callback)));
400
- }).pipe(operators.share()),
401
- message$: new rxjs.Observable((subscriber) => {
402
- const callback = (event) => subscriber.next(event);
403
- connection.addEventListener("message", callback);
404
- disposables.add(core.toDisposable(() => connection.removeEventListener("message", callback)));
405
- }).pipe(operators.share())
406
- };
407
- return webSocket;
408
- } catch (e) {
409
- console.error(e);
410
- return null;
411
- }
412
- }
413
- }
414
- exports2.HTTPHeaders = HTTPHeaders;
415
- exports2.HTTPRequest = HTTPRequest;
416
- exports2.HTTPResponse = HTTPResponse;
417
- exports2.IHTTPImplementation = IHTTPImplementation;
418
- exports2.ISocketService = ISocketService;
419
- exports2.WebSocketService = WebSocketService;
420
- exports2.XHRHTTPImplementation = XHRHTTPImplementation;
421
- Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
422
- });
1
+ (function(o,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("@univerjs/core"),require("rxjs"),require("rxjs/operators"),require("@wendellhu/redi")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs","rxjs/operators","@wendellhu/redi"],a):(o=typeof globalThis<"u"?globalThis:o||self,a(o.UniverNetwork={},o.UniverCore,o.rxjs,o.rxjs.operators,o["@wendellhu/redi"]))})(this,function(o,a,l,v,R){"use strict";var J=Object.defineProperty;var X=(o,a,l)=>a in o?J(o,a,{enumerable:!0,configurable:!0,writable:!0,value:l}):o[a]=l;var p=(o,a,l)=>(X(o,typeof a!="symbol"?a+"":a,l),l);const g="application/json";class b{constructor(t){p(this,"_headers",new Map);typeof t=="string"?t.split(`
2
+ `).forEach(n=>{const[r,i]=n.split(":");r&&i&&this._setHeader(r,i)}):t&&Object.keys(t).forEach(([n,r])=>{this._setHeader(n,r)})}forEach(t){this._headers.forEach((n,r)=>t(r,n))}has(t){return!!this._headers.has(t.toLowerCase())}get(t){const n=t.toLowerCase();return this._headers.has(n)?this._headers.get(n):null}_setHeader(t,n){const r=t.toLowerCase();this._headers.has(r)?this._headers.get(r).push(n.toString()):this._headers.set(r,[n.toString()])}}const u=R.createIdentifier("univer-pro.network.http-implementation");class I{constructor(t){this.params=t}toString(){return this.params?Object.keys(this.params).map(t=>`${t}=${this.params[t]}`).join("&"):""}}class E{constructor(t,n,r){this.method=t,this.url=n,this.requestParams=r}get headers(){return this.requestParams.headers}get withCredentials(){return this.requestParams.withCredentials}get responseType(){return this.requestParams.responseType}getUrlWithParams(){var n,r;const t=(r=(n=this.requestParams)==null?void 0:n.params)==null?void 0:r.toString();return t?`${this.url}${this.url.includes("?")?"&":"?"}${t}`:this.url}getBody(){var r;const t=this.headers.get("Content-Type")??g,n=(r=this.requestParams)==null?void 0:r.body;return t===g&&n&&typeof n=="object"?JSON.stringify(n):n?`${n}`:null}}class w{constructor({body:t,headers:n,status:r,statusText:i}){p(this,"body");p(this,"headers");p(this,"status");p(this,"statusText");this.body=t,this.headers=n,this.status=r,this.statusText=i}}class _{constructor({headers:t,status:n,statusText:r,error:i}){p(this,"headers");p(this,"status");p(this,"statusText");p(this,"error");this.headers=t,this.status=n,this.statusText=r,this.error=i}}class U{constructor(t,n,r){this.headers=t,this.status=n,this.statusText=r}}var x=Object.defineProperty,A=Object.getOwnPropertyDescriptor,O=(e,t,n,r)=>{for(var i=r>1?void 0:r?A(t,n):t,c=e.length-1,s;c>=0;c--)(s=e[c])&&(i=(r?s(t,n,i):s(i))||i);return r&&i&&x(t,n,i),i},M=(e,t)=>(n,r)=>t(n,r,e);o.HTTPService=class extends a.Disposable{constructor(n){super();p(this,"_interceptors",[]);p(this,"_pipe");this._http=n}registerHTTPInterceptor(n){if(this._interceptors.indexOf(n)!==-1)throw new Error("[HTTPService]: The interceptor has already been registered!");return this._interceptors.push(n),this._interceptors=this._interceptors.sort((r,i)=>(r.priority??0)-(i.priority??0)),this._pipe=null,a.toDisposable(()=>a.remove(this._interceptors,n))}get(n,r){return this._request("GET",n,r)}post(n,r){return this._request("POST",n,r)}put(n,r){return this._request("PUT",n,r)}delete(n,r){return this._request("DELETE",n,r)}async _request(n,r,i){const c=new b(i==null?void 0:i.headers),s=new I(i==null?void 0:i.params),d=new E(n,r,{headers:c,params:s,withCredentials:(i==null?void 0:i.withCredentials)??!1,responseType:(i==null?void 0:i.responseType)??"json",body:i==null?void 0:i.body}),m=l.of(d).pipe(v.concatMap(f=>this._runInterceptorsAndImplementation(f))),h=await l.firstValueFrom(m);if(h instanceof w)return h;throw new Error(`${h.error}`)}_runInterceptorsAndImplementation(n){return this._pipe||(this._pipe=this._interceptors.map(r=>r.interceptor).reduceRight((r,i)=>k(r,i),(r,i)=>i(r))),this._pipe(n,r=>this._http.send(r))}},o.HTTPService=O([M(0,u)],o.HTTPService);function k(e,t){return(n,r)=>t(n,i=>e(i,r))}const F=200,j=300;var q=(e=>(e[e.Continue=100]="Continue",e[e.SwitchingProtocols=101]="SwitchingProtocols",e[e.Processing=102]="Processing",e[e.EarlyHints=103]="EarlyHints",e[e.Ok=200]="Ok",e[e.Created=201]="Created",e[e.Accepted=202]="Accepted",e[e.NonAuthoritativeInformation=203]="NonAuthoritativeInformation",e[e.NoContent=204]="NoContent",e[e.ResetContent=205]="ResetContent",e[e.PartialContent=206]="PartialContent",e[e.MultiStatus=207]="MultiStatus",e[e.AlreadyReported=208]="AlreadyReported",e[e.ImUsed=226]="ImUsed",e[e.MultipleChoices=300]="MultipleChoices",e[e.MovedPermanently=301]="MovedPermanently",e[e.Found=302]="Found",e[e.SeeOther=303]="SeeOther",e[e.NotModified=304]="NotModified",e[e.UseProxy=305]="UseProxy",e[e.Unused=306]="Unused",e[e.TemporaryRedirect=307]="TemporaryRedirect",e[e.PermanentRedirect=308]="PermanentRedirect",e[e.BadRequest=400]="BadRequest",e[e.Unauthorized=401]="Unauthorized",e[e.PaymentRequired=402]="PaymentRequired",e[e.Forbidden=403]="Forbidden",e[e.NotFound=404]="NotFound",e[e.MethodNotAllowed=405]="MethodNotAllowed",e[e.NotAcceptable=406]="NotAcceptable",e[e.ProxyAuthenticationRequired=407]="ProxyAuthenticationRequired",e[e.RequestTimeout=408]="RequestTimeout",e[e.Conflict=409]="Conflict",e[e.Gone=410]="Gone",e[e.LengthRequired=411]="LengthRequired",e[e.PreconditionFailed=412]="PreconditionFailed",e[e.PayloadTooLarge=413]="PayloadTooLarge",e[e.UriTooLong=414]="UriTooLong",e[e.UnsupportedMediaType=415]="UnsupportedMediaType",e[e.RangeNotSatisfiable=416]="RangeNotSatisfiable",e[e.ExpectationFailed=417]="ExpectationFailed",e[e.ImATeapot=418]="ImATeapot",e[e.MisdirectedRequest=421]="MisdirectedRequest",e[e.UnprocessableEntity=422]="UnprocessableEntity",e[e.Locked=423]="Locked",e[e.FailedDependency=424]="FailedDependency",e[e.TooEarly=425]="TooEarly",e[e.UpgradeRequired=426]="UpgradeRequired",e[e.PreconditionRequired=428]="PreconditionRequired",e[e.TooManyRequests=429]="TooManyRequests",e[e.RequestHeaderFieldsTooLarge=431]="RequestHeaderFieldsTooLarge",e[e.UnavailableForLegalReasons=451]="UnavailableForLegalReasons",e[e.InternalServerError=500]="InternalServerError",e[e.NotImplemented=501]="NotImplemented",e[e.BadGateway=502]="BadGateway",e[e.ServiceUnavailable=503]="ServiceUnavailable",e[e.GatewayTimeout=504]="GatewayTimeout",e[e.HttpVersionNotSupported=505]="HttpVersionNotSupported",e[e.VariantAlsoNegotiates=506]="VariantAlsoNegotiates",e[e.InsufficientStorage=507]="InsufficientStorage",e[e.LoopDetected=508]="LoopDetected",e[e.NotExtended=510]="NotExtended",e[e.NetworkAuthenticationRequired=511]="NetworkAuthenticationRequired",e))(q||{});class D{send(t){return new l.Observable(n=>{const r=new XMLHttpRequest;r.open(t.method,t.getUrlWithParams()),t.withCredentials&&(r.withCredentials=!0),t.headers.forEach((m,h)=>r.setRequestHeader(m,h.join(","))),t.headers.has("Accept")||r.setRequestHeader("Accept","application/json, text/plain, */*"),t.headers.has("Content-Type")||r.setRequestHeader("Content-Type","application/json;charset=UTF-8");const i=()=>{const m=r.statusText||"OK",h=new b(r.getAllResponseHeaders());return new U(h,r.status,m)},c=()=>{const{headers:m,statusText:h,status:f}=i(),{responseType:G}=t;let y=null,L=null;f!==q.NoContent&&(y=typeof r.response>"u"?r.responseText:r.response);let N=f>=F&&f<j;if(G==="json"&&typeof y=="string"){const V=y;try{y=y?JSON.parse(y):null}catch(W){N=!1,y=V,L=W}}N?n.next(new w({body:y,headers:m,status:f,statusText:h})):n.next(new _({error:L,headers:m,status:f,statusText:h}))},s=m=>{const h=new _({error:m,status:r.status||0,statusText:r.statusText||"Unknown Error",headers:i().headers});n.next(h)};r.addEventListener("load",c),r.addEventListener("error",s),r.addEventListener("abort",s),r.addEventListener("timeout",s);const d=t.getBody();return r.send(d),()=>{r.readyState!==r.DONE&&r.abort(),r.removeEventListener("load",c),r.removeEventListener("error",s),r.removeEventListener("abort",s),r.removeEventListener("timeout",s)}})}}const $=R.createIdentifier("univer.socket");class B extends a.Disposable{createSocket(t){try{const n=new WebSocket(t),r=new a.DisposableCollection;return{URL:t,close:(c,s)=>{n.close(c,s),r.dispose()},send:c=>{n.send(c)},open$:new l.Observable(c=>{const s=d=>c.next(d);n.addEventListener("open",s),r.add(a.toDisposable(()=>n.removeEventListener("open",s)))}).pipe(v.share()),close$:new l.Observable(c=>{const s=d=>c.next(d);n.addEventListener("close",s),r.add(a.toDisposable(()=>n.removeEventListener("close",s)))}).pipe(v.share()),error$:new l.Observable(c=>{const s=d=>c.next(d);n.addEventListener("error",s),r.add(a.toDisposable(()=>n.removeEventListener("error",s)))}).pipe(v.share()),message$:new l.Observable(c=>{const s=d=>c.next(d);n.addEventListener("message",s),r.add(a.toDisposable(()=>n.removeEventListener("message",s)))}).pipe(v.share())}}catch(n){return console.error(n),null}}}o.HTTPHeaders=b,o.HTTPRequest=E,o.HTTPResponse=w,o.IHTTPImplementation=u,o.ISocketService=$,o.WebSocketService=B,o.XHRHTTPImplementation=D,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,15 +1,10 @@
1
1
  {
2
2
  "name": "@univerjs/network",
3
- "version": "0.1.0-beta.2",
4
- "keywords": [],
3
+ "version": "0.1.0-beta.3",
4
+ "private": false,
5
5
  "author": "DreamNum <developer@univer.ai>",
6
6
  "license": "Apache-2.0",
7
- "main": "./lib/cjs/index.js",
8
- "module": "./lib/es/index.js",
9
- "types": "./lib/types/index.d.ts",
10
- "publishConfig": {
11
- "access": "public"
12
- },
7
+ "keywords": [],
13
8
  "exports": {
14
9
  ".": {
15
10
  "import": "./lib/es/index.js",
@@ -22,31 +17,39 @@
22
17
  "types": "./lib/types/index.d.ts"
23
18
  }
24
19
  },
20
+ "main": "./lib/cjs/index.js",
21
+ "module": "./lib/es/index.js",
22
+ "types": "./lib/types/index.d.ts",
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
25
26
  "directories": {
26
27
  "lib": "lib"
27
28
  },
28
29
  "files": [
29
30
  "lib"
30
31
  ],
31
- "private": false,
32
- "dependencies": {
33
- "@wendellhu/redi": "^0.12.13",
34
- "rxjs": "^7.8.1",
35
- "@univerjs/core": "0.1.0-beta.2"
36
- },
37
- "devDependencies": {
38
- "typescript": "^5.3.3",
39
- "vite": "^5.0.10",
40
- "vite-plugin-dts": "^3.7.0",
41
- "vite-plugin-externals": "^0.6.2",
42
- "vitest": "^1.1.1"
32
+ "engines": {
33
+ "node": ">=16.0.0",
34
+ "npm": ">=8.0.0"
43
35
  },
44
36
  "peerDependencies": {
45
- "@wendellhu/redi": ">=0.12.12",
37
+ "@wendellhu/redi": ">=0.12.13",
46
38
  "rxjs": ">=7.0.0",
47
- "@univerjs/core": "0.1.0-beta.2"
39
+ "@univerjs/core": "0.1.0-beta.3"
40
+ },
41
+ "dependencies": {},
42
+ "devDependencies": {
43
+ "@wendellhu/redi": "^0.12.13",
44
+ "rxjs": "^7.8.1",
45
+ "typescript": "^5.3.3",
46
+ "vite": "^5.0.12",
47
+ "vitest": "^1.2.1",
48
+ "@univerjs/core": "0.1.0-beta.3",
49
+ "@univerjs/shared": "0.1.0-beta.3"
48
50
  },
49
51
  "scripts": {
52
+ "lint:types": "tsc --noEmit",
50
53
  "build": "tsc && vite build"
51
54
  }
52
55
  }