@univerjs/network 0.5.4 → 0.5.5-experimental.20250123-34738ff

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/es/index.js CHANGED
@@ -1,67 +1,69 @@
1
- var Z = Object.defineProperty;
2
- var P = (e, r, t) => r in e ? Z(e, r, { enumerable: !0, configurable: !0, writable: !0, value: t }) : e[r] = t;
3
- var d = (e, r, t) => P(e, typeof r != "symbol" ? r + "" : r, t);
4
- import { createIdentifier as V, Disposable as z, toDisposable as R, remove as J, ILogService as D, Inject as S, Injector as H, Plugin as C, Quantity as T, LookUp as ee, registerDependencies as re, mergeOverrideWithDependencies as te, DisposableCollection as ne } from "@univerjs/core";
5
- import { of as q, firstValueFrom as se, Observable as m, catchError as oe, throwError as ie } from "rxjs";
6
- import { concatMap as M, share as b, retry as ce } from "rxjs/operators";
7
- const k = "application/json";
8
- class I {
9
- constructor(r) {
10
- d(this, "_headers", /* @__PURE__ */ new Map());
11
- typeof r == "string" ? this._handleHeadersString(r) : r instanceof Headers ? this._handleHeaders(r) : r && this._handleHeadersConstructorProps(r);
12
- }
13
- forEach(r) {
14
- this._headers.forEach((t, n) => r(n, t));
15
- }
16
- has(r) {
17
- return !!this._headers.has(r.toLowerCase());
18
- }
19
- get(r) {
20
- const t = r.toLowerCase();
21
- return this._headers.has(t) ? this._headers.get(t) : null;
22
- }
23
- set(r, t) {
24
- this._setHeader(r, t);
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: !0, configurable: !0, writable: !0, value }) : obj[key] = value;
3
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: !0 });
4
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key != "symbol" ? key + "" : key, value);
5
+ import { createIdentifier, Disposable, toDisposable, remove, ILogService, Inject, Injector, Plugin, Quantity, LookUp, registerDependencies, mergeOverrideWithDependencies, DisposableCollection } from "@univerjs/core";
6
+ import { of, firstValueFrom, Observable, catchError, throwError } from "rxjs";
7
+ import { concatMap, share, retry } from "rxjs/operators";
8
+ const ApplicationJSONType = "application/json", _HTTPHeaders = class _HTTPHeaders {
9
+ constructor(headers) {
10
+ __publicField(this, "_headers", /* @__PURE__ */ new Map());
11
+ typeof headers == "string" ? this._handleHeadersString(headers) : headers instanceof Headers ? this._handleHeaders(headers) : headers && this._handleHeadersConstructorProps(headers);
12
+ }
13
+ forEach(callback) {
14
+ this._headers.forEach((v, key) => callback(key, v));
15
+ }
16
+ has(key) {
17
+ return !!this._headers.has(key.toLowerCase());
18
+ }
19
+ get(key) {
20
+ const k = key.toLowerCase();
21
+ return this._headers.has(k) ? this._headers.get(k) : null;
22
+ }
23
+ set(key, value) {
24
+ this._setHeader(key, value);
25
25
  }
26
26
  toHeadersInit() {
27
- var t, n;
28
- const r = {};
29
- return this._headers.forEach((s, o) => {
30
- r[o] = s.join(",");
31
- }), (t = r.accept) != null || (r.accept = "application/json, text/plain, */*"), (n = r["content-type"]) != null || (r["content-type"] = "application/json;charset=UTF-8"), r;
32
- }
33
- _setHeader(r, t) {
34
- const n = r.toLowerCase();
35
- this._headers.has(n) ? this._headers.get(n).push(t.toString()) : this._headers.set(n, [t.toString()]);
36
- }
37
- _handleHeadersString(r) {
38
- r.split(`
39
- `).forEach((t) => {
40
- const [n, s] = t.split(":");
41
- n && s && this._setHeader(n, s);
27
+ var _a5, _b;
28
+ const headers = {};
29
+ return this._headers.forEach((values, key) => {
30
+ headers[key] = values.join(",");
31
+ }), (_a5 = headers.accept) != null || (headers.accept = "application/json, text/plain, */*"), (_b = headers["content-type"]) != null || (headers["content-type"] = "application/json;charset=UTF-8"), headers;
32
+ }
33
+ _setHeader(name, value) {
34
+ const lowerCase = name.toLowerCase();
35
+ this._headers.has(lowerCase) ? this._headers.get(lowerCase).push(value.toString()) : this._headers.set(lowerCase, [value.toString()]);
36
+ }
37
+ _handleHeadersString(headers) {
38
+ headers.split(`
39
+ `).forEach((header) => {
40
+ const [name, value] = header.split(":");
41
+ name && value && this._setHeader(name, value);
42
42
  });
43
43
  }
44
- _handleHeadersConstructorProps(r) {
45
- Object.entries(r).forEach(([t, n]) => this._setHeader(t, n));
44
+ _handleHeadersConstructorProps(headers) {
45
+ Object.entries(headers).forEach(([name, value]) => this._setHeader(name, value));
46
46
  }
47
- _handleHeaders(r) {
48
- r.forEach((t, n) => this._setHeader(n, t));
47
+ _handleHeaders(headers) {
48
+ headers.forEach((value, name) => this._setHeader(name, value));
49
49
  }
50
- }
51
- const K = V("network.http-implementation");
52
- class B {
53
- constructor(r) {
54
- this.params = r;
50
+ };
51
+ __name(_HTTPHeaders, "HTTPHeaders");
52
+ let HTTPHeaders = _HTTPHeaders;
53
+ const IHTTPImplementation = createIdentifier("network.http-implementation"), _HTTPParams = class _HTTPParams {
54
+ constructor(params) {
55
+ this.params = params;
55
56
  }
56
57
  toString() {
57
- return this.params ? Object.keys(this.params).map((r) => `${r}=${this.params[r]}`).join("&") : "";
58
+ return this.params ? Object.keys(this.params).map((key) => `${key}=${this.params[key]}`).join("&") : "";
58
59
  }
59
- }
60
- let ae = 0;
61
- class G {
62
- constructor(r, t, n) {
63
- d(this, "uid", ae++);
64
- this.method = r, this.url = t, this.requestParams = n;
60
+ };
61
+ __name(_HTTPParams, "HTTPParams");
62
+ let HTTPParams = _HTTPParams, HTTPRequestUID = 0;
63
+ const _HTTPRequest = class _HTTPRequest {
64
+ constructor(method, url, requestParams) {
65
+ __publicField(this, "uid", HTTPRequestUID++);
66
+ this.method = method, this.url = url, this.requestParams = requestParams;
65
67
  }
66
68
  get headers() {
67
69
  return this.requestParams.headers;
@@ -73,31 +75,33 @@ class G {
73
75
  return this.requestParams.responseType;
74
76
  }
75
77
  getUrlWithParams() {
76
- var t, n;
77
- const r = (n = (t = this.requestParams) == null ? void 0 : t.params) == null ? void 0 : n.toString();
78
- return r ? `${this.url}${this.url.includes("?") ? "&" : "?"}${r}` : this.url;
78
+ var _a5, _b;
79
+ const params = (_b = (_a5 = this.requestParams) == null ? void 0 : _a5.params) == null ? void 0 : _b.toString();
80
+ return params ? `${this.url}${this.url.includes("?") ? "&" : "?"}${params}` : this.url;
79
81
  }
80
82
  getBody() {
81
- var n, s;
82
- const r = (n = this.headers.get("Content-Type")) != null ? n : k, t = (s = this.requestParams) == null ? void 0 : s.body;
83
- return r === k && t && typeof t == "object" ? JSON.stringify(t) : t ? `${t}` : null;
83
+ var _a5, _b;
84
+ const contentType = (_a5 = this.headers.get("Content-Type")) != null ? _a5 : ApplicationJSONType, body = (_b = this.requestParams) == null ? void 0 : _b.body;
85
+ return contentType === ApplicationJSONType && body && typeof body == "object" ? JSON.stringify(body) : body ? `${body}` : null;
84
86
  }
85
87
  getHeadersInit() {
86
88
  return this.headers.toHeadersInit();
87
89
  }
88
- }
89
- var le = Object.defineProperty, he = Object.getOwnPropertyDescriptor, pe = (e, r, t, n) => {
90
- for (var s = n > 1 ? void 0 : n ? he(r, t) : r, o = e.length - 1, i; o >= 0; o--)
91
- (i = e[o]) && (s = (n ? i(r, t, s) : i(s)) || s);
92
- return n && s && le(r, t, s), s;
93
- }, de = (e, r) => (t, n) => r(t, n, e);
94
- let x = class extends z {
95
- constructor(r) {
90
+ };
91
+ __name(_HTTPRequest, "HTTPRequest");
92
+ let HTTPRequest = _HTTPRequest;
93
+ var __defProp$3 = Object.defineProperty, __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor, __decorateClass$3 = /* @__PURE__ */ __name((decorators, target, key, kind) => {
94
+ for (var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$3(target, key) : target, i = decorators.length - 1, decorator; i >= 0; i--)
95
+ (decorator = decorators[i]) && (result = (kind ? decorator(target, key, result) : decorator(result)) || result);
96
+ return kind && result && __defProp$3(target, key, result), result;
97
+ }, "__decorateClass$3"), __decorateParam$3 = /* @__PURE__ */ __name((index, decorator) => (target, key) => decorator(target, key, index), "__decorateParam$3"), _a;
98
+ let HTTPService = (_a = class extends Disposable {
99
+ constructor(_http) {
96
100
  super();
97
- d(this, "_interceptors", []);
101
+ __publicField(this, "_interceptors", []);
98
102
  // eslint-disable-next-line ts/no-explicit-any
99
- d(this, "_pipe");
100
- this._http = r;
103
+ __publicField(this, "_pipe");
104
+ this._http = _http;
101
105
  }
102
106
  /**
103
107
  * Register an HTTP interceptor.
@@ -105,479 +109,492 @@ let x = class extends z {
105
109
  * @param interceptor the http interceptor
106
110
  * @returns a disposable handler to remove the interceptor
107
111
  */
108
- registerHTTPInterceptor(r) {
109
- if (this._interceptors.indexOf(r) !== -1)
112
+ registerHTTPInterceptor(interceptor) {
113
+ if (this._interceptors.indexOf(interceptor) !== -1)
110
114
  throw new Error("[HTTPService]: The interceptor has already been registered!");
111
- return this._interceptors.push(r), this._interceptors = this._interceptors.sort((t, n) => {
112
- var s, o;
113
- return ((s = t.priority) != null ? s : 0) - ((o = n.priority) != null ? o : 0);
114
- }), this._pipe = null, R(() => J(this._interceptors, r));
115
+ return this._interceptors.push(interceptor), this._interceptors = this._interceptors.sort((a, b) => {
116
+ var _a5, _b;
117
+ return ((_a5 = a.priority) != null ? _a5 : 0) - ((_b = b.priority) != null ? _b : 0);
118
+ }), this._pipe = null, toDisposable(() => remove(this._interceptors, interceptor));
115
119
  }
116
- get(r, t) {
117
- return this._request("GET", r, t);
120
+ get(url, params) {
121
+ return this._request("GET", url, params);
118
122
  }
119
- post(r, t) {
120
- return this._request("POST", r, t);
123
+ post(url, params) {
124
+ return this._request("POST", url, params);
121
125
  }
122
- put(r, t) {
123
- return this._request("PUT", r, t);
126
+ put(url, params) {
127
+ return this._request("PUT", url, params);
124
128
  }
125
- delete(r, t) {
126
- return this._request("DELETE", r, t);
129
+ delete(url, params) {
130
+ return this._request("DELETE", url, params);
127
131
  }
128
- patch(r, t) {
129
- return this._request("PATCH", r, t);
132
+ patch(url, params) {
133
+ return this._request("PATCH", url, params);
130
134
  }
131
- getSSE(r, t, n) {
132
- var c, w;
133
- const s = new I(n == null ? void 0 : n.headers), o = new B(n == null ? void 0 : n.params), i = new G(r, t, {
134
- headers: s,
135
- params: o,
136
- withCredentials: (c = n == null ? void 0 : n.withCredentials) != null ? c : !1,
135
+ getSSE(method, url, _params) {
136
+ var _a5, _b;
137
+ const headers = new HTTPHeaders(_params == null ? void 0 : _params.headers), params = new HTTPParams(_params == null ? void 0 : _params.params), request = new HTTPRequest(method, url, {
138
+ headers,
139
+ params,
140
+ withCredentials: (_a5 = _params == null ? void 0 : _params.withCredentials) != null ? _a5 : !1,
137
141
  reportProgress: !0,
138
- responseType: (w = n == null ? void 0 : n.responseType) != null ? w : "json",
139
- body: ["GET", "DELETE"].includes(r) || n == null ? void 0 : n.body
142
+ responseType: (_b = _params == null ? void 0 : _params.responseType) != null ? _b : "json",
143
+ body: ["GET", "DELETE"].includes(method) || _params == null ? void 0 : _params.body
140
144
  });
141
- return q(i).pipe(M((a) => this._runInterceptorsAndImplementation(a)));
145
+ return of(request).pipe(concatMap((request2) => this._runInterceptorsAndImplementation(request2)));
142
146
  }
143
147
  /** The HTTP request implementations */
144
- async _request(r, t, n) {
145
- var a, h;
146
- const s = new I(n == null ? void 0 : n.headers), o = new B(n == null ? void 0 : n.params), i = new G(r, t, {
147
- headers: s,
148
- params: o,
149
- withCredentials: (a = n == null ? void 0 : n.withCredentials) != null ? a : !1,
148
+ async _request(method, url, options) {
149
+ var _a5, _b;
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
+ headers,
152
+ params,
153
+ withCredentials: (_a5 = options == null ? void 0 : options.withCredentials) != null ? _a5 : !1,
150
154
  // default value for withCredentials is false by MDN
151
- responseType: (h = n == null ? void 0 : n.responseType) != null ? h : "json",
152
- body: ["GET", "DELETE"].includes(r) || n == null ? void 0 : n.body
153
- }), c = q(i).pipe(
154
- M((l) => this._runInterceptorsAndImplementation(l))
155
+ responseType: (_b = options == null ? void 0 : options.responseType) != null ? _b : "json",
156
+ body: ["GET", "DELETE"].includes(method) || options == null ? void 0 : options.body
157
+ }), events$ = of(request).pipe(
158
+ concatMap((request2) => this._runInterceptorsAndImplementation(request2))
155
159
  );
156
- return await se(c);
160
+ return await firstValueFrom(events$);
157
161
  }
158
162
  // eslint-disable-next-line ts/no-explicit-any
159
- _runInterceptorsAndImplementation(r) {
160
- return this._pipe || (this._pipe = this._interceptors.map((t) => t.interceptor).reduceRight(
161
- (t, n) => ue(t, n),
162
- (t, n) => n(t)
163
+ _runInterceptorsAndImplementation(request) {
164
+ return this._pipe || (this._pipe = this._interceptors.map((handler) => handler.interceptor).reduceRight(
165
+ (nextHandlerFunction, interceptorFunction) => chainInterceptorFn(nextHandlerFunction, interceptorFunction),
166
+ (requestFromPrevInterceptor, finalHandler) => finalHandler(requestFromPrevInterceptor)
163
167
  )), this._pipe(
164
- r,
165
- (t) => this._http.send(t)
168
+ request,
169
+ (requestToNext) => this._http.send(requestToNext)
166
170
  /* final handler */
167
171
  );
168
172
  }
169
- };
170
- x = pe([
171
- de(0, K)
172
- ], x);
173
- function ue(e, r) {
174
- return (t, n) => r(t, (s) => e(s, n));
173
+ }, __name(_a, "HTTPService"), _a);
174
+ HTTPService = __decorateClass$3([
175
+ __decorateParam$3(0, IHTTPImplementation)
176
+ ], HTTPService);
177
+ function chainInterceptorFn(afterInterceptorChain, currentInterceptorFn) {
178
+ return (prevRequest, nextHandlerFn) => currentInterceptorFn(prevRequest, (nextRequest) => afterInterceptorChain(nextRequest, nextHandlerFn));
175
179
  }
176
- const fe = 200, ge = 300;
177
- var L = /* @__PURE__ */ ((e) => (e[e.Continue = 100] = "Continue", e[e.SwitchingProtocols = 101] = "SwitchingProtocols", e[e.Processing = 102] = "Processing", e[e.EarlyHints = 103] = "EarlyHints", e[e.Ok = 200] = "Ok", e[e.Created = 201] = "Created", e[e.Accepted = 202] = "Accepted", e[e.NonAuthoritativeInformation = 203] = "NonAuthoritativeInformation", e[e.NoContent = 204] = "NoContent", e[e.ResetContent = 205] = "ResetContent", e[e.PartialContent = 206] = "PartialContent", e[e.MultiStatus = 207] = "MultiStatus", e[e.AlreadyReported = 208] = "AlreadyReported", e[e.ImUsed = 226] = "ImUsed", e[e.MultipleChoices = 300] = "MultipleChoices", e[e.MovedPermanently = 301] = "MovedPermanently", e[e.Found = 302] = "Found", e[e.SeeOther = 303] = "SeeOther", e[e.NotModified = 304] = "NotModified", e[e.UseProxy = 305] = "UseProxy", e[e.Unused = 306] = "Unused", e[e.TemporaryRedirect = 307] = "TemporaryRedirect", e[e.PermanentRedirect = 308] = "PermanentRedirect", e[e.BadRequest = 400] = "BadRequest", e[e.Unauthorized = 401] = "Unauthorized", e[e.PaymentRequired = 402] = "PaymentRequired", e[e.Forbidden = 403] = "Forbidden", e[e.NotFound = 404] = "NotFound", e[e.MethodNotAllowed = 405] = "MethodNotAllowed", e[e.NotAcceptable = 406] = "NotAcceptable", e[e.ProxyAuthenticationRequired = 407] = "ProxyAuthenticationRequired", e[e.RequestTimeout = 408] = "RequestTimeout", e[e.Conflict = 409] = "Conflict", e[e.Gone = 410] = "Gone", e[e.LengthRequired = 411] = "LengthRequired", e[e.PreconditionFailed = 412] = "PreconditionFailed", e[e.PayloadTooLarge = 413] = "PayloadTooLarge", e[e.UriTooLong = 414] = "UriTooLong", e[e.UnsupportedMediaType = 415] = "UnsupportedMediaType", e[e.RangeNotSatisfiable = 416] = "RangeNotSatisfiable", e[e.ExpectationFailed = 417] = "ExpectationFailed", e[e.ImATeapot = 418] = "ImATeapot", e[e.MisdirectedRequest = 421] = "MisdirectedRequest", e[e.UnprocessableEntity = 422] = "UnprocessableEntity", e[e.Locked = 423] = "Locked", e[e.FailedDependency = 424] = "FailedDependency", e[e.TooEarly = 425] = "TooEarly", e[e.UpgradeRequired = 426] = "UpgradeRequired", e[e.PreconditionRequired = 428] = "PreconditionRequired", e[e.TooManyRequests = 429] = "TooManyRequests", e[e.RequestHeaderFieldsTooLarge = 431] = "RequestHeaderFieldsTooLarge", e[e.UnavailableForLegalReasons = 451] = "UnavailableForLegalReasons", e[e.InternalServerError = 500] = "InternalServerError", e[e.NotImplemented = 501] = "NotImplemented", e[e.BadGateway = 502] = "BadGateway", e[e.ServiceUnavailable = 503] = "ServiceUnavailable", e[e.GatewayTimeout = 504] = "GatewayTimeout", e[e.HttpVersionNotSupported = 505] = "HttpVersionNotSupported", e[e.VariantAlsoNegotiates = 506] = "VariantAlsoNegotiates", e[e.InsufficientStorage = 507] = "InsufficientStorage", e[e.LoopDetected = 508] = "LoopDetected", e[e.NotExtended = 510] = "NotExtended", e[e.NetworkAuthenticationRequired = 511] = "NetworkAuthenticationRequired", e))(L || {}), Y = /* @__PURE__ */ ((e) => (e[e.DownloadProgress = 0] = "DownloadProgress", e[e.Response = 1] = "Response", e))(Y || {});
178
- class $ {
180
+ __name(chainInterceptorFn, "chainInterceptorFn");
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 || {});
183
+ const _HTTPResponse = class _HTTPResponse {
179
184
  constructor({
180
- body: r,
181
- headers: t,
182
- status: n,
183
- statusText: s
185
+ body,
186
+ headers,
187
+ status,
188
+ statusText
184
189
  }) {
185
- d(this, "type", 1);
186
- d(this, "body");
187
- d(this, "headers");
188
- d(this, "status");
189
- d(this, "statusText");
190
- this.body = r, this.headers = t, this.status = n, this.statusText = s;
190
+ __publicField(this, "type", 1);
191
+ __publicField(this, "body");
192
+ __publicField(this, "headers");
193
+ __publicField(this, "status");
194
+ __publicField(this, "statusText");
195
+ this.body = body, this.headers = headers, this.status = status, this.statusText = statusText;
191
196
  }
192
- }
193
- class we {
194
- constructor(r, t, n) {
195
- d(this, "type", 0);
196
- this.total = r, this.loaded = t, this.partialText = n;
197
+ };
198
+ __name(_HTTPResponse, "HTTPResponse");
199
+ let HTTPResponse = _HTTPResponse;
200
+ const _HTTPProgress = class _HTTPProgress {
201
+ constructor(total, loaded, partialText) {
202
+ __publicField(this, "type", 0);
203
+ this.total = total, this.loaded = loaded, this.partialText = partialText;
197
204
  }
198
- }
199
- class ye {
200
- constructor(r, t, n) {
201
- this.headers = r, this.status = t, this.statusText = n;
205
+ };
206
+ __name(_HTTPProgress, "HTTPProgress");
207
+ let HTTPProgress = _HTTPProgress;
208
+ const _ResponseHeader = class _ResponseHeader {
209
+ constructor(headers, status, statusText) {
210
+ this.headers = headers, this.status = status, this.statusText = statusText;
202
211
  }
203
- }
204
- class _ {
212
+ };
213
+ __name(_ResponseHeader, "ResponseHeader");
214
+ let ResponseHeader = _ResponseHeader;
215
+ const _HTTPResponseError = class _HTTPResponseError {
205
216
  constructor({
206
- request: r,
207
- headers: t,
208
- status: n,
209
- statusText: s,
210
- error: o
217
+ request,
218
+ headers,
219
+ status,
220
+ statusText,
221
+ error
211
222
  }) {
212
- d(this, "request");
213
- d(this, "headers");
214
- d(this, "status");
215
- d(this, "statusText");
216
- d(this, "error");
217
- this.request = r, this.headers = t, this.status = n, this.statusText = s, this.error = o;
223
+ __publicField(this, "request");
224
+ __publicField(this, "headers");
225
+ __publicField(this, "status");
226
+ __publicField(this, "statusText");
227
+ __publicField(this, "error");
228
+ this.request = request, this.headers = headers, this.status = status, this.statusText = statusText, this.error = error;
218
229
  }
219
- }
220
- function Q(e) {
230
+ };
231
+ __name(_HTTPResponseError, "HTTPResponseError");
232
+ let HTTPResponseError = _HTTPResponseError;
233
+ function parseFetchParamsFromRequest(request) {
221
234
  return {
222
- method: e.method,
223
- headers: e.getHeadersInit(),
224
- body: e.getBody(),
225
- credentials: e.withCredentials ? "include" : void 0
235
+ method: request.method,
236
+ headers: request.getHeadersInit(),
237
+ body: request.getBody(),
238
+ credentials: request.withCredentials ? "include" : void 0
226
239
  };
227
240
  }
228
- var me = Object.defineProperty, _e = Object.getOwnPropertyDescriptor, ve = (e, r, t, n) => {
229
- for (var s = n > 1 ? void 0 : n ? _e(r, t) : r, o = e.length - 1, i; o >= 0; o--)
230
- (i = e[o]) && (s = (n ? i(r, t, s) : i(s)) || s);
231
- return n && s && me(r, t, s), s;
232
- }, Ee = (e, r) => (t, n) => r(t, n, e);
233
- let N = class {
234
- constructor(e) {
235
- this._logService = e;
236
- }
237
- send(e) {
238
- return new m((r) => {
239
- const t = new AbortController();
240
- return this._send(e, r, t).catch((n) => {
241
- r.error(new _({
242
- error: n,
243
- request: e
241
+ __name(parseFetchParamsFromRequest, "parseFetchParamsFromRequest");
242
+ var __defProp$2 = Object.defineProperty, __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor, __decorateClass$2 = /* @__PURE__ */ __name((decorators, target, key, kind) => {
243
+ for (var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$2(target, key) : target, i = decorators.length - 1, decorator; i >= 0; i--)
244
+ (decorator = decorators[i]) && (result = (kind ? decorator(target, key, result) : decorator(result)) || result);
245
+ return kind && result && __defProp$2(target, key, result), result;
246
+ }, "__decorateClass$2"), __decorateParam$2 = /* @__PURE__ */ __name((index, decorator) => (target, key) => decorator(target, key, index), "__decorateParam$2"), _a2;
247
+ let FetchHTTPImplementation = (_a2 = class {
248
+ constructor(_logService) {
249
+ this._logService = _logService;
250
+ }
251
+ send(request) {
252
+ return new Observable((subscriber) => {
253
+ const abortController = new AbortController();
254
+ return this._send(request, subscriber, abortController).catch((error) => {
255
+ subscriber.error(new HTTPResponseError({
256
+ error,
257
+ request
244
258
  }));
245
- }), () => t.abort();
259
+ }), () => abortController.abort();
246
260
  });
247
261
  }
248
- async _send(e, r, t) {
249
- var a, h;
250
- let n;
262
+ async _send(request, subscriber, abortController) {
263
+ var _a5, _b;
264
+ let response;
251
265
  try {
252
- const l = Q(e), y = e.getUrlWithParams(), p = fetch(y, {
253
- signal: t.signal,
254
- ...l
266
+ const fetchParams = parseFetchParamsFromRequest(request), urlWithParams = request.getUrlWithParams(), fetchPromise = fetch(urlWithParams, {
267
+ signal: abortController.signal,
268
+ ...fetchParams
255
269
  });
256
- this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${y} with params ${l}`), n = await p;
257
- } catch (l) {
258
- const y = new _({
259
- request: e,
260
- error: l,
261
- status: (a = l.status) != null ? a : 0,
262
- statusText: (h = l.statusText) != null ? h : "Unknown Error",
263
- headers: l.headers
270
+ this._logService.debug(`[FetchHTTPImplementation]: sending request to url ${urlWithParams} with params ${fetchParams}`), response = await fetchPromise;
271
+ } catch (error) {
272
+ const e = new HTTPResponseError({
273
+ request,
274
+ error,
275
+ status: (_a5 = error.status) != null ? _a5 : 0,
276
+ statusText: (_b = error.statusText) != null ? _b : "Unknown Error",
277
+ headers: error.headers
264
278
  });
265
- this._logService.error("[FetchHTTPImplementation]: network error", y), r.error(y);
279
+ this._logService.error("[FetchHTTPImplementation]: network error", e), subscriber.error(e);
266
280
  return;
267
281
  }
268
- const s = new I(n.headers), o = n.status, i = n.statusText;
269
- let c = null;
270
- if (n.body && (c = await this._readBody(e, n, r)), o >= L.Ok && o < L.MultipleChoices)
271
- r.next(new $({
272
- body: c,
273
- headers: s,
274
- status: o,
275
- statusText: i
282
+ const responseHeaders = new HTTPHeaders(response.headers), status = response.status, statusText = response.statusText;
283
+ let body = null;
284
+ if (response.body && (body = await this._readBody(request, response, subscriber)), status >= HTTPStatusCode.Ok && status < HTTPStatusCode.MultipleChoices)
285
+ subscriber.next(new HTTPResponse({
286
+ body,
287
+ headers: responseHeaders,
288
+ status,
289
+ statusText
276
290
  }));
277
291
  else {
278
- const l = new _({
279
- request: e,
280
- error: c,
281
- status: o,
282
- statusText: i,
283
- headers: s
292
+ const e = new HTTPResponseError({
293
+ request,
294
+ error: body,
295
+ status,
296
+ statusText,
297
+ headers: responseHeaders
284
298
  });
285
- this._logService.error("[FetchHTTPImplementation]: network error", l), r.error(l);
299
+ this._logService.error("[FetchHTTPImplementation]: network error", e), subscriber.error(e);
286
300
  }
287
- r.complete();
288
- }
289
- async _readBody(e, r, t) {
290
- var y, p;
291
- const n = [], s = r.body.getReader(), o = r.headers.get("content-length");
292
- let i = 0;
293
- const c = (y = e.requestParams) == null ? void 0 : y.reportProgress, w = e.responseType;
294
- let a, h;
301
+ subscriber.complete();
302
+ }
303
+ async _readBody(request, response, subscriber) {
304
+ var _a5, _b;
305
+ const chunks = [], reader = response.body.getReader(), contentLength = response.headers.get("content-length");
306
+ let receivedLength = 0;
307
+ const reportProgress = (_a5 = request.requestParams) == null ? void 0 : _a5.reportProgress, responseType = request.responseType;
308
+ let partialText, decoder;
295
309
  for (; ; ) {
296
- const { done: u, value: g } = await s.read();
297
- if (u) break;
298
- n.push(g), i += g.length, c && w === "text" && (a = (a != null ? a : "") + (h != null ? h : h = new TextDecoder()).decode(g, { stream: !0 }), t.next(new we(
299
- o ? Number.parseInt(o, 10) : void 0,
300
- i,
301
- a
310
+ const { done, value } = await reader.read();
311
+ if (done) break;
312
+ 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(
313
+ contentLength ? Number.parseInt(contentLength, 10) : void 0,
314
+ receivedLength,
315
+ partialText
302
316
  )));
303
317
  }
304
- const l = Re(n, i);
318
+ const all = mergeChunks(chunks, receivedLength);
305
319
  try {
306
- const u = (p = r.headers.get("content-type")) != null ? p : "";
307
- return be(e, l, u);
308
- } catch (u) {
309
- const g = new _({
310
- request: e,
311
- error: u,
312
- status: r.status,
313
- statusText: r.statusText,
314
- headers: new I(r.headers)
320
+ const contentType = (_b = response.headers.get("content-type")) != null ? _b : "";
321
+ return deserialize(request, all, contentType);
322
+ } catch (error) {
323
+ const e = new HTTPResponseError({
324
+ request,
325
+ error,
326
+ status: response.status,
327
+ statusText: response.statusText,
328
+ headers: new HTTPHeaders(response.headers)
315
329
  });
316
- return this._logService.error("[FetchHTTPImplementation]: network error", g), t.error(g), null;
330
+ return this._logService.error("[FetchHTTPImplementation]: network error", e), subscriber.error(e), null;
317
331
  }
318
332
  }
319
- };
320
- N = ve([
321
- Ee(0, D)
322
- ], N);
323
- function Re(e, r) {
324
- const t = new Uint8Array(r);
325
- let n = 0;
326
- for (const s of e)
327
- t.set(s, n), n += s.length;
328
- return t;
333
+ }, __name(_a2, "FetchHTTPImplementation"), _a2);
334
+ FetchHTTPImplementation = __decorateClass$2([
335
+ __decorateParam$2(0, ILogService)
336
+ ], FetchHTTPImplementation);
337
+ function mergeChunks(chunks, totalLength) {
338
+ const all = new Uint8Array(totalLength);
339
+ let position = 0;
340
+ for (const chunk of chunks)
341
+ all.set(chunk, position), position += chunk.length;
342
+ return all;
329
343
  }
330
- const Ie = /^\)\]\}',?\n/;
331
- function be(e, r, t) {
332
- switch (e.responseType) {
344
+ __name(mergeChunks, "mergeChunks");
345
+ const XSSI_PREFIX = /^\)\]\}',?\n/;
346
+ function deserialize(request, bin, contentType) {
347
+ switch (request.responseType) {
333
348
  case "json":
334
- const n = new TextDecoder().decode(r).replace(Ie, "");
335
- return n === "" ? null : JSON.parse(n);
349
+ const text = new TextDecoder().decode(bin).replace(XSSI_PREFIX, "");
350
+ return text === "" ? null : JSON.parse(text);
336
351
  case "text":
337
- return new TextDecoder().decode(r);
352
+ return new TextDecoder().decode(bin);
338
353
  case "blob":
339
- return new Blob([r], { type: t });
354
+ return new Blob([bin], { type: contentType });
340
355
  case "arraybuffer":
341
- return r.buffer;
356
+ return bin.buffer;
342
357
  default:
343
- throw new Error(`[FetchHTTPImplementation]: unknown response type: ${e.responseType}.`);
358
+ throw new Error(`[FetchHTTPImplementation]: unknown response type: ${request.responseType}.`);
344
359
  }
345
360
  }
346
- var xe = Object.defineProperty, Le = Object.getOwnPropertyDescriptor, Ne = (e, r, t, n) => {
347
- for (var s = n > 1 ? void 0 : n ? Le(r, t) : r, o = e.length - 1, i; o >= 0; o--)
348
- (i = e[o]) && (s = (n ? i(r, t, s) : i(s)) || s);
349
- return n && s && xe(r, t, s), s;
350
- }, Fe = (e, r) => (t, n) => r(t, n, e);
351
- let U = class {
352
- constructor(e) {
353
- this._logService = e;
354
- }
355
- send(e) {
356
- return new m((r) => {
357
- const t = new XMLHttpRequest(), n = e.getUrlWithParams(), s = Q(e);
358
- t.open(e.method, n), e.withCredentials && (t.withCredentials = !0), s.headers && Object.entries(s.headers).forEach(([a, h]) => t.setRequestHeader(a, h));
359
- const o = () => {
360
- const a = t.statusText || "OK", h = new I(t.getAllResponseHeaders());
361
- return new ye(h, t.status, a);
362
- }, i = () => {
363
- const { headers: a, statusText: h, status: l } = o(), { responseType: y } = e;
364
- let p = null, u = null;
365
- l !== L.NoContent && (p = typeof t.response > "u" ? t.responseText : t.response);
366
- let g = l >= fe && l < ge;
367
- if (y === "json" && typeof p == "string") {
368
- const f = p;
361
+ __name(deserialize, "deserialize");
362
+ var __defProp$1 = Object.defineProperty, __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor, __decorateClass$1 = /* @__PURE__ */ __name((decorators, target, key, kind) => {
363
+ for (var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$1(target, key) : target, i = decorators.length - 1, decorator; i >= 0; i--)
364
+ (decorator = decorators[i]) && (result = (kind ? decorator(target, key, result) : decorator(result)) || result);
365
+ return kind && result && __defProp$1(target, key, result), result;
366
+ }, "__decorateClass$1"), __decorateParam$1 = /* @__PURE__ */ __name((index, decorator) => (target, key) => decorator(target, key, index), "__decorateParam$1"), _a3;
367
+ let XHRHTTPImplementation = (_a3 = class {
368
+ constructor(_logService) {
369
+ this._logService = _logService;
370
+ }
371
+ send(request) {
372
+ return new Observable((observer) => {
373
+ const xhr = new XMLHttpRequest(), urlWithParams = request.getUrlWithParams(), fetchParams = parseFetchParamsFromRequest(request);
374
+ xhr.open(request.method, urlWithParams), request.withCredentials && (xhr.withCredentials = !0), fetchParams.headers && Object.entries(fetchParams.headers).forEach(([key, value]) => xhr.setRequestHeader(key, value));
375
+ const buildResponseHeader = /* @__PURE__ */ __name(() => {
376
+ const statusText = xhr.statusText || "OK", headers = new HTTPHeaders(xhr.getAllResponseHeaders());
377
+ return new ResponseHeader(headers, xhr.status, statusText);
378
+ }, "buildResponseHeader"), onLoadHandler = /* @__PURE__ */ __name(() => {
379
+ const { headers, statusText, status } = buildResponseHeader(), { responseType } = request;
380
+ let body2 = null, error = null;
381
+ status !== HTTPStatusCode.NoContent && (body2 = typeof xhr.response > "u" ? xhr.responseText : xhr.response);
382
+ let success = status >= SuccessStatusCodeLowerBound && status < ErrorStatusCodeLowerBound;
383
+ if (responseType === "json" && typeof body2 == "string") {
384
+ const originalBody = body2;
369
385
  try {
370
- p = p ? JSON.parse(p) : null;
371
- } catch (v) {
372
- g = !1, p = f, u = v;
386
+ body2 = body2 ? JSON.parse(body2) : null;
387
+ } catch (e) {
388
+ success = !1, body2 = originalBody, error = e;
373
389
  }
374
390
  }
375
- if (g)
376
- r.next(
377
- new $({
378
- body: p,
379
- headers: a,
380
- status: l,
381
- statusText: h
391
+ if (success)
392
+ observer.next(
393
+ new HTTPResponse({
394
+ body: body2,
395
+ headers,
396
+ status,
397
+ statusText
382
398
  })
383
399
  );
384
400
  else {
385
- const f = new _({
386
- request: e,
387
- error: u,
388
- headers: a,
389
- status: l,
390
- statusText: h
401
+ const e = new HTTPResponseError({
402
+ request,
403
+ error,
404
+ headers,
405
+ status,
406
+ statusText
391
407
  });
392
- this._logService.error("[XHRHTTPImplementation]: network error", f), r.error(f);
408
+ this._logService.error("[XHRHTTPImplementation]: network error", e), observer.error(e);
393
409
  }
394
- }, c = (a) => {
395
- const h = new _({
396
- request: e,
397
- error: a,
398
- status: t.status || 0,
399
- statusText: t.statusText || "Unknown Error",
400
- headers: o().headers
410
+ }, "onLoadHandler"), onErrorHandler = /* @__PURE__ */ __name((error) => {
411
+ const e = new HTTPResponseError({
412
+ request,
413
+ error,
414
+ status: xhr.status || 0,
415
+ statusText: xhr.statusText || "Unknown Error",
416
+ headers: buildResponseHeader().headers
401
417
  });
402
- this._logService.error("[XHRHTTPImplementation]: network error", h), r.error(h);
403
- };
404
- t.addEventListener("load", i), t.addEventListener("error", c), t.addEventListener("abort", c), t.addEventListener("timeout", c);
405
- const w = e.getBody();
406
- return t.send(w), this._logService.debug(`[XHRHTTPImplementation]: sending request to url ${n} with params ${s}`), () => {
407
- t.readyState !== t.DONE && t.abort(), t.removeEventListener("load", i), t.removeEventListener("error", c), t.removeEventListener("abort", c), t.removeEventListener("timeout", c);
418
+ this._logService.error("[XHRHTTPImplementation]: network error", e), observer.error(e);
419
+ }, "onErrorHandler");
420
+ xhr.addEventListener("load", onLoadHandler), xhr.addEventListener("error", onErrorHandler), xhr.addEventListener("abort", onErrorHandler), xhr.addEventListener("timeout", onErrorHandler);
421
+ const body = request.getBody();
422
+ return xhr.send(body), this._logService.debug(`[XHRHTTPImplementation]: sending request to url ${urlWithParams} with params ${fetchParams}`), () => {
423
+ xhr.readyState !== xhr.DONE && xhr.abort(), xhr.removeEventListener("load", onLoadHandler), xhr.removeEventListener("error", onErrorHandler), xhr.removeEventListener("abort", onErrorHandler), xhr.removeEventListener("timeout", onErrorHandler);
408
424
  };
409
425
  });
410
426
  }
411
- };
412
- U = Ne([
413
- Fe(0, D)
414
- ], U);
415
- var Oe = Object.defineProperty, Ae = Object.getOwnPropertyDescriptor, Ue = (e, r, t, n) => {
416
- for (var s = n > 1 ? void 0 : n ? Ae(r, t) : r, o = e.length - 1, i; o >= 0; o--)
417
- (i = e[o]) && (s = (n ? i(r, t, s) : i(s)) || s);
418
- return n && s && Oe(r, t, s), s;
419
- }, W = (e, r) => (t, n) => r(t, n, e), A;
420
- let X = (A = class extends C {
421
- constructor(e = void 0, r, t) {
422
- super(), this._config = e, this._logger = r, this._injector = t;
427
+ }, __name(_a3, "XHRHTTPImplementation"), _a3);
428
+ XHRHTTPImplementation = __decorateClass$1([
429
+ __decorateParam$1(0, ILogService)
430
+ ], XHRHTTPImplementation);
431
+ var __defProp2 = Object.defineProperty, __getOwnPropDesc = Object.getOwnPropertyDescriptor, __decorateClass = /* @__PURE__ */ __name((decorators, target, key, kind) => {
432
+ for (var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target, i = decorators.length - 1, decorator; i >= 0; i--)
433
+ (decorator = decorators[i]) && (result = (kind ? decorator(target, key, result) : decorator(result)) || result);
434
+ return kind && result && __defProp2(target, key, result), result;
435
+ }, "__decorateClass"), __decorateParam = /* @__PURE__ */ __name((index, decorator) => (target, key) => decorator(target, key, index), "__decorateParam"), _a4;
436
+ let UniverNetworkPlugin = (_a4 = class extends Plugin {
437
+ constructor(_config = void 0, _logger, _injector) {
438
+ super(), this._config = _config, this._logger = _logger, this._injector = _injector;
423
439
  }
424
440
  onStarting() {
425
- var t, n, s;
426
- if (this._injector.get(x, T.OPTIONAL, ee.SKIP_SELF) && !((t = this._config) != null && t.forceUseNewInstance)) {
441
+ var _a5, _b, _c;
442
+ if (this._injector.get(HTTPService, Quantity.OPTIONAL, LookUp.SKIP_SELF) && !((_a5 = this._config) != null && _a5.forceUseNewInstance)) {
427
443
  this._logger.warn(
428
444
  "[UniverNetworkPlugin]",
429
445
  'HTTPService is already registered in an ancestor interceptor. Skipping registration. If you want to force a new instance, set "forceUseNewInstance" to true in the plugin configuration.'
430
446
  );
431
447
  return;
432
448
  }
433
- const r = (n = this._config) != null && n.useFetchImpl ? N : typeof window < "u" ? U : N;
434
- re(this._injector, te([
435
- [x],
436
- [K, { useClass: r }]
437
- ], (s = this._config) == null ? void 0 : s.override));
438
- }
439
- }, d(A, "pluginName", "UNIVER_NETWORK_PLUGIN"), A);
440
- X = Ue([
441
- W(1, D),
442
- W(2, S(H))
443
- ], X);
444
- const We = V("univer.network.socket.service");
445
- class Xe extends z {
446
- createSocket(r) {
449
+ const impl = (_b = this._config) != null && _b.useFetchImpl ? FetchHTTPImplementation : typeof window < "u" ? XHRHTTPImplementation : FetchHTTPImplementation;
450
+ registerDependencies(this._injector, mergeOverrideWithDependencies([
451
+ [HTTPService],
452
+ [IHTTPImplementation, { useClass: impl }]
453
+ ], (_c = this._config) == null ? void 0 : _c.override));
454
+ }
455
+ }, __name(_a4, "UniverNetworkPlugin"), __publicField(_a4, "pluginName", "UNIVER_NETWORK_PLUGIN"), _a4);
456
+ UniverNetworkPlugin = __decorateClass([
457
+ __decorateParam(1, ILogService),
458
+ __decorateParam(2, Inject(Injector))
459
+ ], UniverNetworkPlugin);
460
+ const ISocketService = createIdentifier("univer.network.socket.service"), _WebSocketService = class _WebSocketService extends Disposable {
461
+ createSocket(URL) {
447
462
  try {
448
- const t = new WebSocket(r), n = new ne();
463
+ const connection = new WebSocket(URL), disposables = new DisposableCollection();
449
464
  return {
450
- URL: r,
451
- close: (o, i) => {
452
- t.close(o, i), n.dispose();
453
- },
454
- send: (o) => {
455
- t.send(o);
456
- },
457
- open$: new m((o) => {
458
- const i = (c) => o.next(c);
459
- t.addEventListener("open", i), n.add(R(() => t.removeEventListener("open", i)));
460
- }).pipe(b()),
461
- close$: new m((o) => {
462
- const i = (c) => o.next(c);
463
- t.addEventListener("close", i), n.add(R(() => t.removeEventListener("close", i)));
464
- }).pipe(b()),
465
- error$: new m((o) => {
466
- const i = (c) => o.next(c);
467
- t.addEventListener("error", i), n.add(R(() => t.removeEventListener("error", i)));
468
- }).pipe(b()),
469
- message$: new m((o) => {
470
- const i = (c) => o.next(c);
471
- t.addEventListener("message", i), n.add(R(() => t.removeEventListener("message", i)));
472
- }).pipe(b())
465
+ URL,
466
+ close: /* @__PURE__ */ __name((code, reason) => {
467
+ connection.close(code, reason), disposables.dispose();
468
+ }, "close"),
469
+ send: /* @__PURE__ */ __name((data) => {
470
+ connection.send(data);
471
+ }, "send"),
472
+ open$: new Observable((subscriber) => {
473
+ const callback = /* @__PURE__ */ __name((event) => subscriber.next(event), "callback");
474
+ connection.addEventListener("open", callback), disposables.add(toDisposable(() => connection.removeEventListener("open", callback)));
475
+ }).pipe(share()),
476
+ close$: new Observable((subscriber) => {
477
+ const callback = /* @__PURE__ */ __name((event) => subscriber.next(event), "callback");
478
+ connection.addEventListener("close", callback), disposables.add(toDisposable(() => connection.removeEventListener("close", callback)));
479
+ }).pipe(share()),
480
+ error$: new Observable((subscriber) => {
481
+ const callback = /* @__PURE__ */ __name((event) => subscriber.next(event), "callback");
482
+ connection.addEventListener("error", callback), disposables.add(toDisposable(() => connection.removeEventListener("error", callback)));
483
+ }).pipe(share()),
484
+ message$: new Observable((subscriber) => {
485
+ const callback = /* @__PURE__ */ __name((event) => subscriber.next(event), "callback");
486
+ connection.addEventListener("message", callback), disposables.add(toDisposable(() => connection.removeEventListener("message", callback)));
487
+ }).pipe(share())
473
488
  };
474
- } catch (t) {
475
- return console.error(t), null;
489
+ } catch (e) {
490
+ return console.error(e), null;
476
491
  }
477
492
  }
478
- }
479
- const De = 3, $e = 1e3, Ve = (e) => {
480
- var n, s;
481
- const r = (n = e == null ? void 0 : e.maxRetryAttempts) != null ? n : De, t = (s = e == null ? void 0 : e.delayInterval) != null ? s : $e;
482
- return (o, i) => i(o).pipe(ce({ delay: t, count: r }));
483
- }, ze = (e) => {
484
- const r = [], t = /* @__PURE__ */ new Set(), n = () => {
485
- var s;
486
- for (; t.size < ((s = e == null ? void 0 : e.maxParallel) != null ? s : 1) && r.length > 0; ) {
487
- const o = r.shift();
488
- t.add(o), o();
493
+ };
494
+ __name(_WebSocketService, "WebSocketService");
495
+ let WebSocketService = _WebSocketService;
496
+ const DEFAULT_MAX_RETRY_ATTEMPTS = 3, DELAY_INTERVAL = 1e3, RetryInterceptorFactory = /* @__PURE__ */ __name((params) => {
497
+ var _a5, _b;
498
+ const maxRetryAttempts = (_a5 = params == null ? void 0 : params.maxRetryAttempts) != null ? _a5 : DEFAULT_MAX_RETRY_ATTEMPTS, delayInterval = (_b = params == null ? void 0 : params.delayInterval) != null ? _b : DELAY_INTERVAL;
499
+ return (request, next) => next(request).pipe(retry({ delay: delayInterval, count: maxRetryAttempts }));
500
+ }, "RetryInterceptorFactory"), ThresholdInterceptorFactory = /* @__PURE__ */ __name((params) => {
501
+ const handlers = [], ongoingHandlers = /* @__PURE__ */ new Set(), tick = /* @__PURE__ */ __name(() => {
502
+ var _a5;
503
+ for (; ongoingHandlers.size < ((_a5 = params == null ? void 0 : params.maxParallel) != null ? _a5 : 1) && handlers.length > 0; ) {
504
+ const handler = handlers.shift();
505
+ ongoingHandlers.add(handler), handler();
489
506
  }
490
- };
491
- return (s, o) => new m((i) => {
492
- const c = () => o(s).subscribe({
493
- next: (a) => i.next(a),
494
- error: (a) => i.error(a),
495
- complete: () => i.complete()
496
- }), w = () => {
497
- t.delete(c), J(r, c), n();
498
- };
499
- return r.push(c), n(), w;
507
+ }, "tick");
508
+ return (request, next) => new Observable((observer) => {
509
+ const handler = /* @__PURE__ */ __name(() => next(request).subscribe({
510
+ next: /* @__PURE__ */ __name((event) => observer.next(event), "next"),
511
+ error: /* @__PURE__ */ __name((err) => observer.error(err), "error"),
512
+ complete: /* @__PURE__ */ __name(() => observer.complete(), "complete")
513
+ }), "handler"), teardown = /* @__PURE__ */ __name(() => {
514
+ ongoingHandlers.delete(handler), remove(handlers, handler), tick();
515
+ }, "teardown");
516
+ return handlers.push(handler), tick(), teardown;
500
517
  });
501
- }, Je = (e) => {
502
- const { errorStatusCodes: r, onAuthError: t } = e;
503
- return (s, o) => o(s).pipe(
504
- oe((i) => (i instanceof _ && r.some((c) => c === i.status) && t(), ie(() => i)))
505
- );
506
- }, je = (e = 300) => {
507
- let t = () => {
508
- };
509
- return (n) => new Promise((s) => {
510
- t();
511
- const o = setTimeout(() => {
512
- s(!0);
513
- }, e);
514
- t = () => {
515
- clearTimeout(o), s(!1);
516
- };
518
+ }, "ThresholdInterceptorFactory"), AuthInterceptorFactory = /* @__PURE__ */ __name((params) => {
519
+ const { errorStatusCodes, onAuthError } = params;
520
+ return /* @__PURE__ */ __name((request, next) => next(request).pipe(
521
+ catchError((error) => (error instanceof HTTPResponseError && errorStatusCodes.some((c) => c === error.status) && onAuthError(), throwError(() => error)))
522
+ ), "authInterceptor");
523
+ }, "AuthInterceptorFactory"), createDefaultFetchCheck = /* @__PURE__ */ __name((time = 300) => {
524
+ let cancel = /* @__PURE__ */ __name(() => {
525
+ }, "noop");
526
+ return (_currentConfig) => new Promise((res) => {
527
+ cancel();
528
+ const t = setTimeout(() => {
529
+ res(!0);
530
+ }, time);
531
+ cancel = /* @__PURE__ */ __name(() => {
532
+ clearTimeout(t), res(!1);
533
+ }, "cancel");
517
534
  });
518
- }, qe = () => (e, r) => r.map((t) => ({ config: t, result: e })), Ke = (e, r = {}) => {
519
- const { isMatch: t, getParamsFromRequest: n, mergeParamsToRequest: s } = e, { fetchCheck: o = je(300), distributeResult: i = qe() } = r, c = [], w = (a) => a.map((h) => h.config);
520
- return (a, h) => t(a) ? new m((l) => {
521
- const y = n(a);
522
- c.push({
523
- next: (u) => l.next(u),
524
- error: (u) => l.error(u),
525
- config: y
535
+ }, "createDefaultFetchCheck"), createDistributeResult = /* @__PURE__ */ __name(() => (result, list) => list.map((config) => ({ config, result })), "createDistributeResult"), MergeInterceptorFactory = /* @__PURE__ */ __name((config, options = {}) => {
536
+ const { isMatch, getParamsFromRequest, mergeParamsToRequest } = config, { fetchCheck = createDefaultFetchCheck(300), distributeResult = createDistributeResult() } = options, hookList = [], getPlainList = /* @__PURE__ */ __name((_list) => _list.map((item) => item.config), "getPlainList");
537
+ return (requestConfig, next) => isMatch(requestConfig) ? new Observable((observer) => {
538
+ const params = getParamsFromRequest(requestConfig);
539
+ hookList.push({
540
+ next: /* @__PURE__ */ __name((v) => observer.next(v), "next"),
541
+ error: /* @__PURE__ */ __name((error) => observer.error(error), "error"),
542
+ config: params
526
543
  });
527
- const p = w(c);
528
- o(a).then((u) => {
529
- if (u) {
530
- const g = [];
531
- p.forEach((f) => {
532
- const v = c.findIndex((E) => E.config === f);
533
- if (v >= 0) {
534
- const [E] = c.splice(v, 1);
535
- g.push(E);
544
+ const list = getPlainList(hookList);
545
+ fetchCheck(requestConfig).then((isFetch) => {
546
+ if (isFetch) {
547
+ const currentHookList = [];
548
+ list.forEach((config2) => {
549
+ const index = hookList.findIndex((item) => item.config === config2);
550
+ if (index >= 0) {
551
+ const [hook] = hookList.splice(index, 1);
552
+ currentHookList.push(hook);
536
553
  }
537
- }), h(s(p, a)).subscribe({
538
- next: (f) => {
539
- if (f.type === Y.Response) {
540
- const v = f.body, E = i(v, p);
541
- g.forEach((F) => {
542
- const j = E.find((O) => O.config === F.config);
543
- if (j) {
544
- const O = new $({
545
- body: j.result,
546
- headers: f.headers,
547
- status: f.status,
548
- statusText: f.statusText
554
+ }), next(mergeParamsToRequest(list, requestConfig)).subscribe({
555
+ next: /* @__PURE__ */ __name((e) => {
556
+ if (e.type === HTTPEventType.Response) {
557
+ const body = e.body, configList = distributeResult(body, list);
558
+ currentHookList.forEach((hookItem) => {
559
+ const res = configList.find((item) => item.config === hookItem.config);
560
+ if (res) {
561
+ const response = new HTTPResponse({
562
+ body: res.result,
563
+ headers: e.headers,
564
+ status: e.status,
565
+ statusText: e.statusText
549
566
  });
550
- F.next(O);
567
+ hookItem.next(response);
551
568
  } else
552
- F.error("batch error");
569
+ hookItem.error("batch error");
553
570
  });
554
571
  }
555
- },
556
- complete: () => l.complete(),
557
- error: (f) => l.error(f)
572
+ }, "next"),
573
+ complete: /* @__PURE__ */ __name(() => observer.complete(), "complete"),
574
+ error: /* @__PURE__ */ __name((e) => observer.error(e), "error")
558
575
  });
559
576
  }
560
577
  });
561
- }) : h(a);
562
- };
578
+ }) : next(requestConfig);
579
+ }, "MergeInterceptorFactory");
563
580
  export {
564
- Je as AuthInterceptorFactory,
565
- N as FetchHTTPImplementation,
566
- Y as HTTPEventType,
567
- I as HTTPHeaders,
568
- we as HTTPProgress,
569
- G as HTTPRequest,
570
- $ as HTTPResponse,
571
- _ as HTTPResponseError,
572
- x as HTTPService,
573
- L as HTTPStatusCode,
574
- K as IHTTPImplementation,
575
- We as ISocketService,
576
- Ke as MergeInterceptorFactory,
577
- ye as ResponseHeader,
578
- Ve as RetryInterceptorFactory,
579
- ze as ThresholdInterceptorFactory,
580
- X as UniverNetworkPlugin,
581
- Xe as WebSocketService,
582
- U as XHRHTTPImplementation
581
+ AuthInterceptorFactory,
582
+ FetchHTTPImplementation,
583
+ HTTPEventType,
584
+ HTTPHeaders,
585
+ HTTPProgress,
586
+ HTTPRequest,
587
+ HTTPResponse,
588
+ HTTPResponseError,
589
+ HTTPService,
590
+ HTTPStatusCode,
591
+ IHTTPImplementation,
592
+ ISocketService,
593
+ MergeInterceptorFactory,
594
+ ResponseHeader,
595
+ RetryInterceptorFactory,
596
+ ThresholdInterceptorFactory,
597
+ UniverNetworkPlugin,
598
+ WebSocketService,
599
+ XHRHTTPImplementation
583
600
  };