@hyper-fetch/core 9.4.0 → 9.4.2

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.
@@ -2,6 +2,7 @@
2
2
  * @vitest-environment jsdom
3
3
  */
4
4
  import { createHttpMockingServer } from "@hyper-fetch/testing";
5
+ import type { QueryParamsType } from "adapter";
5
6
  import { getErrorMessage } from "adapter";
6
7
  import { Client } from "client";
7
8
  import { HttpAdapter } from "http-adapter";
@@ -42,6 +43,38 @@ describe("Http Adapter [ Browser ]", () => {
42
43
  expect(extra).toStrictEqual({ headers: { "content-type": "application/json", "content-length": "15" } });
43
44
  });
44
45
 
46
+ it("should build the request url from the adapter-mapped query params", async () => {
47
+ const fetchSpy = vi.spyOn(globalThis, "fetch");
48
+ client.adapter.setQueryParamsMapperConfig({ arrayFormat: "comma" });
49
+ const queryRequest = client
50
+ .createRequest<{ response: any; queryParams: QueryParamsType }>()({ endpoint: "/shared-endpoint" })
51
+ .setQueryParams({ tags: ["a b", "c&d"], q: "x&y=1", nil: null });
52
+ mockRequest(queryRequest, { data: { response: [] } });
53
+
54
+ const { status } = await client.adapter.fetch(queryRequest, requestId);
55
+
56
+ expect(status).toBe(200);
57
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
58
+ expect(String(fetchSpy.mock.calls[0][0])).toBe(
59
+ "https://shared-base-url/shared-endpoint?tags=a%20b,c%26d&q=x%26y%3D1",
60
+ );
61
+ fetchSpy.mockRestore();
62
+ });
63
+
64
+ it("should build the request url with a custom query params mapper", async () => {
65
+ const fetchSpy = vi.spyOn(globalThis, "fetch");
66
+ client.adapter.setQueryParamsMapper(() => "?custom=1");
67
+ const queryRequest = client
68
+ .createRequest<{ response: any; queryParams: QueryParamsType }>()({ endpoint: "/shared-endpoint" })
69
+ .setQueryParams({ ignored: true });
70
+ mockRequest(queryRequest, { data: { response: [] } });
71
+
72
+ await client.adapter.fetch(queryRequest, requestId);
73
+
74
+ expect(String(fetchSpy.mock.calls[0][0])).toBe("https://shared-base-url/shared-endpoint?custom=1");
75
+ fetchSpy.mockRestore();
76
+ });
77
+
45
78
  it("should make a request and return error data with status", async () => {
46
79
  const data = mockRequest(request, { status: 400 });
47
80
 
@@ -91,6 +91,20 @@ describe("Client [ Base ]", () => {
91
91
  client.clear();
92
92
  expect(spy).toHaveBeenCalledTimes(2);
93
93
  });
94
+ it("should remove the window listeners of the previous appManager", async () => {
95
+ const client = new Client({ url: "shared-base-url" });
96
+ const previousAppManager = client.appManager;
97
+
98
+ client.clear();
99
+ window.dispatchEvent(new Event("offline"));
100
+
101
+ expect(previousAppManager.isOnline).toBeTrue();
102
+ expect(client.appManager.isOnline).toBeFalse();
103
+
104
+ window.dispatchEvent(new Event("online"));
105
+ expect(client.appManager.isOnline).toBeTrue();
106
+ client.appManager.unmount();
107
+ });
94
108
  it("should assign new cache", async () => {
95
109
  const spy = vi.fn();
96
110
  const cache = new Cache();
@@ -146,6 +146,61 @@ describe("Client [ Utils ]", () => {
146
146
  expect(stringifyQueryParams(null, options)).toBe("");
147
147
  expect(stringifyQueryParams(undefined, options)).toBe("");
148
148
  });
149
+ it("should use default options when none are passed", async () => {
150
+ expect(stringifyQueryParams({ tags: ["a b", "c&d"], q: "x&y=1", nil: null, empty: "" })).toBe(
151
+ "?tags[]=a%20b&tags[]=c%26d&q=x%26y%3D1",
152
+ );
153
+ });
154
+ it("should merge partial options with the defaults", async () => {
155
+ expect(
156
+ stringifyQueryParams({ tags: ["a b", "c&d"], q: "x&y=1", nil: null, empty: "" }, { arrayFormat: "comma" }),
157
+ ).toBe("?tags=a%20b,c%26d&q=x%26y%3D1");
158
+ expect(stringifyQueryParams({ value: "(a)" }, { arrayFormat: "comma" })).toBe("?value=%28a%29");
159
+ expect(stringifyQueryParams({ tags: [null, "", "a"] }, { arrayFormat: "index" })).toBe("?tags[0]=a");
160
+ });
161
+ it("should allow partial options to override the defaults", async () => {
162
+ expect(stringifyQueryParams({ q: "a b", nil: null }, { encode: false, skipNull: false })).toBe("?q=a b&nil=null");
163
+ });
164
+ it("should merge partial adapter mapper config with the defaults", async () => {
165
+ const newClient = new Client({ url: "shared-base-url" });
166
+ newClient.adapter.setQueryParamsMapperConfig({ arrayFormat: "comma" });
167
+ expect(newClient.adapter.unstable_queryParamsMapper({ tags: ["a b", "c&d"], q: "x&y=1", nil: null })).toBe(
168
+ "?tags=a%20b,c%26d&q=x%26y%3D1",
169
+ );
170
+ });
171
+ it("should serialize dates and objects inside arrays like scalar values", async () => {
172
+ const date = new Date(Date.UTC(2024, 0, 2));
173
+ expect(stringifyQueryParams({ from: date, f: { id: 1 } })).toBe(
174
+ "?from=2024-01-02T00%3A00%3A00.000Z&f=%7B%22id%22%3A1%7D",
175
+ );
176
+ expect(stringifyQueryParams({ from: [date], f: [{ id: 1 }] })).toBe(
177
+ "?from[]=2024-01-02T00%3A00%3A00.000Z&f[]=%7B%22id%22%3A1%7D",
178
+ );
179
+ expect(stringifyQueryParams({ from: [date, date] }, { arrayFormat: "comma" })).toBe(
180
+ "?from=2024-01-02T00%3A00%3A00.000Z,2024-01-02T00%3A00%3A00.000Z",
181
+ );
182
+ });
183
+ it("should apply custom date and object parsers to array items", async () => {
184
+ const date = new Date(Date.UTC(2024, 0, 2));
185
+ const parsers = {
186
+ dateParser: (value: unknown) => (value as Date).toISOString().slice(0, 10),
187
+ objectParser: (value: unknown) => `id-${(value as { id: number }).id}`,
188
+ };
189
+ expect(stringifyQueryParams({ from: [date], f: [{ id: 1 }, { id: 2 }] }, parsers)).toBe(
190
+ "?from[]=2024-01-02&f[]=id-1&f[]=id-2",
191
+ );
192
+ expect(stringifyQueryParams({ from: date, f: { id: 1 } }, parsers)).toBe("?from=2024-01-02&f=id-1");
193
+ });
194
+ it("should use the pipe separator by default for separator array formats", async () => {
195
+ expect(stringifyDefaultOptions.arraySeparator).toBe("|");
196
+ expect(stringifyQueryParams({ a: [1, 2] }, { ...stringifyDefaultOptions, arrayFormat: "separator" })).toBe(
197
+ "?a=1|2",
198
+ );
199
+ expect(
200
+ stringifyQueryParams({ a: [1, 2] }, { ...stringifyDefaultOptions, arrayFormat: "bracket-separator" }),
201
+ ).toBe("?a[]=1|2");
202
+ expect(stringifyQueryParams({ a: [1, 2] }, { arrayFormat: "separator" })).toBe("?a=1|2");
203
+ });
149
204
  });
150
205
 
151
206
  describe("When using headerMapper", () => {
@@ -1,7 +1,7 @@
1
1
  import { createHttpMockingServer } from "@hyper-fetch/testing";
2
2
  import { waitFor } from "@testing-library/dom";
3
3
  import { Client } from "client";
4
- import { AppManager, appManagerInitialOptions, hasDocument, hasWindow } from "managers";
4
+ import { AppManager, appManagerInitialOptions, hasDocument, hasWindow, isNavigatorOnline } from "managers";
5
5
 
6
6
  const { resetMocks, startServer, stopServer } = createHttpMockingServer();
7
7
 
@@ -15,9 +15,14 @@ describe("AppManager [ Base ]", () => {
15
15
  beforeEach(() => {
16
16
  resetMocks();
17
17
  vi.resetAllMocks();
18
+ client.appManager.unmount();
18
19
  client = new Client({ url: "shared-base-url" });
19
20
  });
20
21
 
22
+ afterEach(() => {
23
+ vi.restoreAllMocks();
24
+ });
25
+
21
26
  afterAll(() => {
22
27
  stopServer();
23
28
  });
@@ -121,6 +126,173 @@ describe("AppManager [ Base ]", () => {
121
126
  expect(offlineSpy).toHaveBeenCalledTimes(1);
122
127
  });
123
128
  });
129
+ describe("When app manager reads the initial state", () => {
130
+ it("should apply synchronous initial getters right away", () => {
131
+ const manager = new AppManager({ initiallyOnline: () => false, initiallyFocused: () => false });
132
+
133
+ expect(manager.isOnline).toBeFalse();
134
+ expect(manager.isFocused).toBeFalse();
135
+
136
+ const onlineManager = new AppManager({ initiallyOnline: () => true, initiallyFocused: () => true });
137
+
138
+ expect(onlineManager.isOnline).toBeTrue();
139
+ expect(onlineManager.isFocused).toBeTrue();
140
+ });
141
+ it("should await asynchronous initial getters", async () => {
142
+ const manager = new AppManager({ initiallyOnline: async () => true, initiallyFocused: async () => true });
143
+
144
+ expect(manager.isOnline).toBeFalse();
145
+ expect(manager.isFocused).toBeFalse();
146
+ await waitFor(() => {
147
+ expect(manager.isOnline).toBeTrue();
148
+ expect(manager.isFocused).toBeTrue();
149
+ });
150
+ });
151
+ it("should start offline when the browser is offline", () => {
152
+ vi.spyOn(window.navigator, "onLine", "get").mockReturnValue(false);
153
+
154
+ expect(new AppManager().isOnline).toBeFalse();
155
+ expect(new Client({ url: "shared-base-url" }).appManager.isOnline).toBeFalse();
156
+ });
157
+ it("should start online when the browser is online", () => {
158
+ vi.spyOn(window.navigator, "onLine", "get").mockReturnValue(true);
159
+
160
+ expect(new AppManager().isOnline).toBeTrue();
161
+ });
162
+ it("should prefer the initiallyOnline option over the browser state", () => {
163
+ vi.spyOn(window.navigator, "onLine", "get").mockReturnValue(false);
164
+
165
+ expect(new AppManager({ initiallyOnline: true }).isOnline).toBeTrue();
166
+ });
167
+ it("should assume online when the browser state is unknown", () => {
168
+ vi.spyOn(window.navigator, "onLine", "get").mockReturnValue(undefined as unknown as boolean);
169
+ expect(isNavigatorOnline()).toBeTrue();
170
+
171
+ vi.spyOn(global, "navigator", "get").mockReturnValue(undefined as unknown as Navigator);
172
+ expect(isNavigatorOnline()).toBeTrue();
173
+ });
174
+ });
175
+
176
+ describe("When app manager listens to the browser events", () => {
177
+ it("should track the window online and offline events", () => {
178
+ const manager = new AppManager();
179
+ const onlineSpy = vi.fn();
180
+ const offlineSpy = vi.fn();
181
+ manager.events.onOnline(onlineSpy);
182
+ manager.events.onOffline(offlineSpy);
183
+ manager.initialize();
184
+
185
+ window.dispatchEvent(new Event("offline"));
186
+ expect(manager.isOnline).toBeFalse();
187
+ expect(offlineSpy).toHaveBeenCalledTimes(1);
188
+
189
+ window.dispatchEvent(new Event("online"));
190
+ expect(manager.isOnline).toBeTrue();
191
+ expect(onlineSpy).toHaveBeenCalledTimes(1);
192
+ manager.unmount();
193
+ });
194
+ it("should track the window focus, blur and visibility events", () => {
195
+ const manager = new AppManager();
196
+ const focusSpy = vi.fn();
197
+ const blurSpy = vi.fn();
198
+ manager.events.onFocus(focusSpy);
199
+ manager.events.onBlur(blurSpy);
200
+ manager.initialize();
201
+
202
+ window.dispatchEvent(new Event("blur"));
203
+ expect(manager.isFocused).toBeFalse();
204
+ window.dispatchEvent(new Event("focus"));
205
+ expect(manager.isFocused).toBeTrue();
206
+ window.document.dispatchEvent(new Event("visibilitychange"));
207
+
208
+ expect(blurSpy).toHaveBeenCalledTimes(1);
209
+ expect(focusSpy).toHaveBeenCalledTimes(2);
210
+ manager.unmount();
211
+ });
212
+ it("should not react to the browser events before initialization", () => {
213
+ const manager = new AppManager();
214
+ const offlineSpy = vi.fn();
215
+ manager.events.onOffline(offlineSpy);
216
+
217
+ window.dispatchEvent(new Event("offline"));
218
+
219
+ expect(manager.isOnline).toBeTrue();
220
+ expect(offlineSpy).not.toHaveBeenCalled();
221
+ window.dispatchEvent(new Event("online"));
222
+ });
223
+ it("should remove the browser listeners on unmount and keep the event subscriptions", () => {
224
+ const manager = new AppManager();
225
+ const offlineSpy = vi.fn();
226
+ manager.events.onOffline(offlineSpy);
227
+ manager.initialize();
228
+ manager.unmount();
229
+
230
+ window.dispatchEvent(new Event("offline"));
231
+ window.dispatchEvent(new Event("blur"));
232
+
233
+ expect(manager.isOnline).toBeTrue();
234
+ expect(manager.isFocused).toBeTrue();
235
+ expect(offlineSpy).not.toHaveBeenCalled();
236
+
237
+ manager.setOnline(false);
238
+ expect(offlineSpy).toHaveBeenCalledTimes(1);
239
+ window.dispatchEvent(new Event("online"));
240
+ window.dispatchEvent(new Event("focus"));
241
+ });
242
+ it("should not register the browser listeners twice when initialized again", () => {
243
+ const manager = new AppManager();
244
+ const offlineSpy = vi.fn();
245
+ manager.events.onOffline(offlineSpy);
246
+ manager.initialize();
247
+ manager.initialize();
248
+
249
+ window.dispatchEvent(new Event("offline"));
250
+
251
+ expect(offlineSpy).toHaveBeenCalledTimes(1);
252
+ manager.unmount();
253
+ window.dispatchEvent(new Event("online"));
254
+ });
255
+ it("should allow to initialize again after unmount", () => {
256
+ const manager = new AppManager();
257
+ manager.initialize();
258
+ manager.unmount();
259
+ manager.initialize();
260
+
261
+ window.dispatchEvent(new Event("offline"));
262
+ expect(manager.isOnline).toBeFalse();
263
+ window.dispatchEvent(new Event("online"));
264
+ expect(manager.isOnline).toBeTrue();
265
+ manager.unmount();
266
+ });
267
+ it("should call the cleanup functions returned by custom handlers", () => {
268
+ const unmountFocus = vi.fn();
269
+ const unmountOnline = vi.fn();
270
+ const manager = new AppManager({ focusEvent: () => unmountFocus, onlineEvent: () => unmountOnline });
271
+
272
+ manager.unmount();
273
+ expect(unmountFocus).not.toHaveBeenCalled();
274
+
275
+ manager.initialize();
276
+ expect(unmountFocus).not.toHaveBeenCalled();
277
+ expect(unmountOnline).not.toHaveBeenCalled();
278
+
279
+ manager.unmount();
280
+ manager.unmount();
281
+ expect(unmountFocus).toHaveBeenCalledTimes(1);
282
+ expect(unmountOnline).toHaveBeenCalledTimes(1);
283
+ });
284
+ it("should clean up the previous custom subscription when initialized again", () => {
285
+ const unmountOnline = vi.fn();
286
+ const onlineEvent = vi.fn().mockReturnValue(unmountOnline);
287
+ const manager = new AppManager({ onlineEvent, focusEvent: () => {} });
288
+
289
+ manager.initialize();
290
+ manager.initialize();
291
+
292
+ expect(onlineEvent).toHaveBeenCalledTimes(2);
293
+ expect(unmountOnline).toHaveBeenCalledTimes(1);
294
+ });
295
+ });
124
296
  describe("When using app manager utils", () => {
125
297
  it("should allow to detect window", async () => {
126
298
  expect(hasWindow()).toBeTrue();
@@ -2,7 +2,7 @@ export declare const stringifyDefaultOptions: {
2
2
  readonly strict: true;
3
3
  readonly encode: true;
4
4
  readonly arrayFormat: "bracket";
5
- readonly arraySeparator: "bracket";
5
+ readonly arraySeparator: "|";
6
6
  readonly sort: false;
7
7
  readonly skipNull: true;
8
8
  readonly skipEmptyString: true;
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/client/client.ts"],"names":[],"mappings":"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,QAAQ,kBAAkB,CAAC,YAAY,EAAE,cAAc,EAAE,UAAU,CAAC,GAAG,gCAAgC,CAAC,OAAO,CAAC;gBAUpG,UAAU;iBACT,cAAc;;;gBADf,UAAU;iBACT,cAAc;;yCA4B7B;CACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"http-adapter.fetch.d.ts","sourceRoot":"","sources":["../../src/http-adapter/http-adapter.fetch.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAE/C,OAAO,KAAK,EAAE,eAAe,EAAkB,MAAM,OAAO,CAAC;AAE7D,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAE7C,OAAO,KAAK,EAAE,oBAAoB,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AAK1F,eAAO,MAAM,UAAU,kZA4KlB,CAAC"}
1
+ {"version":3,"file":"http-adapter.fetch.d.ts","sourceRoot":"","sources":["../../src/http-adapter/http-adapter.fetch.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAE/C,OAAO,KAAK,EAAE,eAAe,EAAkB,MAAM,OAAO,CAAC;AAE7D,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAE7C,OAAO,KAAK,EAAE,oBAAoB,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AAK1F,eAAO,MAAM,UAAU,kZA8KlB,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"http-adapter.utils.d.ts","sourceRoot":"","sources":["../../src/http-adapter/http-adapter.utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAwC,MAAM,SAAS,CAAC;AAGrF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAC/C,OAAO,KAAK,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,OAAO,CAAC;AAE1D,OAAO,KAAK,EAAE,c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,CAEnG,CAAC;AAiGF,eAAO,MAAM,oBAAoB,GAC/B,aAAa,eAAe,GAAG,MAAM,GAAG,UAAU,EAClD,UAAU,yBAAyB,KAClC,MA4BF,CAAC"}
package/dist/index.mjs CHANGED
@@ -982,6 +982,7 @@ var AppManager = class {
982
982
  isBrowser;
983
983
  isOnline;
984
984
  isFocused;
985
+ unmountCallbacks = [];
985
986
  constructor(options) {
986
987
  this.options = options;
987
988
  this.emitter?.setMaxListeners(1e3);
@@ -990,22 +991,48 @@ var AppManager = class {
990
991
  this.setInitialOnline(initiallyOnline);
991
992
  this.isBrowser = hasDocument();
992
993
  }
994
+ /**
995
+ * Subscribes to the environment focus and network changes. Calling it again replaces the previous subscriptions,
996
+ * so the listeners are never registered twice.
997
+ */
993
998
  initialize = () => {
994
999
  const { focusEvent = appManagerInitialOptions.focusEvent, onlineEvent = appManagerInitialOptions.onlineEvent } = this.options || appManagerInitialOptions;
995
- focusEvent(this.setFocused);
996
- onlineEvent(this.setOnline);
1000
+ this.unmount();
1001
+ [focusEvent(this.setFocused), onlineEvent(this.setOnline)].forEach((unmount) => {
1002
+ if (typeof unmount === "function") this.unmountCallbacks.push(unmount);
1003
+ });
1004
+ };
1005
+ /**
1006
+ * Removes the environment listeners registered by `initialize()`. Listeners added with `events` are kept.
1007
+ */
1008
+ unmount = () => {
1009
+ const callbacks = this.unmountCallbacks;
1010
+ this.unmountCallbacks = [];
1011
+ callbacks.forEach((unmount) => unmount());
997
1012
  };
998
1013
  setInitialFocus = async (initValue) => {
999
- if (typeof initValue === "function") {
1014
+ if (typeof initValue !== "function") {
1015
+ this.isFocused = initValue;
1016
+ return;
1017
+ }
1018
+ const value = initValue();
1019
+ if (typeof value === "boolean") this.isFocused = value;
1020
+ else {
1000
1021
  this.isFocused = false;
1001
- this.isFocused = await initValue();
1002
- } else this.isFocused = initValue;
1022
+ this.isFocused = await value;
1023
+ }
1003
1024
  };
1004
1025
  setInitialOnline = async (initValue) => {
1005
- if (typeof initValue === "function") {
1026
+ if (typeof initValue !== "function") {
1027
+ this.isOnline = initValue;
1028
+ return;
1029
+ }
1030
+ const value = initValue();
1031
+ if (typeof value === "boolean") this.isOnline = value;
1032
+ else {
1006
1033
  this.isOnline = false;
1007
- this.isOnline = await initValue();
1008
- } else this.isOnline = initValue;
1034
+ this.isOnline = await value;
1035
+ }
1009
1036
  };
1010
1037
  setFocused = (isFocused) => {
1011
1038
  this.isFocused = isFocused;
@@ -1036,6 +1063,18 @@ var hasDocument = () => {
1036
1063
  return false;
1037
1064
  }
1038
1065
  };
1066
+ /**
1067
+ * Reads the current network state from the browser. Falls back to `true` when it is unknown - e.g. in Node.js or
1068
+ * React Native, where `navigator.onLine` is not available.
1069
+ */
1070
+ var isNavigatorOnline = () => {
1071
+ try {
1072
+ return typeof navigator.onLine === "boolean" ? navigator.onLine : true;
1073
+ } catch {
1074
+ /* istanbul ignore next */
1075
+ return true;
1076
+ }
1077
+ };
1039
1078
  var onWindowEvent = (key, listener, options) => {
1040
1079
  /* istanbul ignore next */
1041
1080
  if (hasWindow()) {
@@ -1098,15 +1137,24 @@ var AppEvents = /* @__PURE__ */ function(AppEvents) {
1098
1137
  }({});
1099
1138
  var appManagerInitialOptions = {
1100
1139
  initiallyFocused: true,
1101
- initiallyOnline: true,
1140
+ initiallyOnline: isNavigatorOnline,
1102
1141
  focusEvent: (setFocused) => {
1103
- onDocumentEvent("visibilitychange", () => setFocused(true));
1104
- onWindowEvent("focus", () => setFocused(true));
1105
- onWindowEvent("blur", () => setFocused(false));
1142
+ const unmountVisibility = onDocumentEvent("visibilitychange", () => setFocused(true));
1143
+ const unmountFocus = onWindowEvent("focus", () => setFocused(true));
1144
+ const unmountBlur = onWindowEvent("blur", () => setFocused(false));
1145
+ return () => {
1146
+ unmountVisibility();
1147
+ unmountFocus();
1148
+ unmountBlur();
1149
+ };
1106
1150
  },
1107
1151
  onlineEvent: (setOnline) => {
1108
- onWindowEvent("online", () => setOnline(true));
1109
- onWindowEvent("offline", () => setOnline(false));
1152
+ const unmountOnline = onWindowEvent("online", () => setOnline(true));
1153
+ const unmountOffline = onWindowEvent("offline", () => setOnline(false));
1154
+ return () => {
1155
+ unmountOnline();
1156
+ unmountOffline();
1157
+ };
1110
1158
  }
1111
1159
  };
1112
1160
  //#endregion
@@ -3606,56 +3654,56 @@ var encodeValue = (value, { encode, strict }) => {
3606
3654
  if (encode) return encodeURIComponent(value);
3607
3655
  return value;
3608
3656
  };
3657
+ var parseValue = (value, options) => {
3658
+ if (value instanceof Date) return options.dateParser?.(value) || value.toISOString();
3659
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) return options.objectParser?.(value) || JSON.stringify(value);
3660
+ return String(value);
3661
+ };
3609
3662
  var encodeParams = (key, value, options) => {
3610
3663
  const shouldSkip = !isValidValue(options)(value);
3611
3664
  if (!key || shouldSkip) return "";
3612
- const parsedValue = () => {
3613
- if (value instanceof Date) return options.dateParser?.(value) || value.toISOString();
3614
- if (typeof value === "object" && !Array.isArray(value)) return options.objectParser?.(value) || JSON.stringify(value);
3615
- return String(value);
3616
- };
3617
- return `${encodeValue(key, options)}=${encodeValue(parsedValue(), options)}`;
3665
+ return `${encodeValue(key, options)}=${encodeValue(parseValue(value, options), options)}`;
3618
3666
  };
3619
3667
  var encodeArray = (key, array, options) => {
3620
3668
  const { arrayFormat, arraySeparator } = options;
3669
+ const separator = arraySeparator || "|";
3670
+ const encodedKey = encodeValue(key, options);
3621
3671
  return array.filter(isValidValue(options)).reduce((acc, value, index) => {
3672
+ const encodedValue = encodeValue(parseValue(value, options), options);
3622
3673
  switch (arrayFormat) {
3623
- case "index": {
3624
- const keyValue = `${encodeValue(key, options)}[${encodeValue(String(index), options)}]=`;
3625
- acc.push(`${keyValue}${encodeValue(String(value), options)}`);
3674
+ case "index":
3675
+ acc.push(`${encodedKey}[${encodeValue(String(index), options)}]=${encodedValue}`);
3626
3676
  break;
3627
- }
3628
- case "bracket": {
3629
- const keyValue = `${encodeValue(key, options)}[]=`;
3630
- acc.push(`${keyValue}${encodeValue(String(value), options)}`);
3677
+ case "bracket":
3678
+ acc.push(`${encodedKey}[]=${encodedValue}`);
3631
3679
  break;
3632
- }
3633
3680
  case "comma": {
3634
- const keyValue = acc.length === 0 && `${encodeValue(key, options)}=` || "";
3635
- return [[...acc, `${keyValue}${encodeValue(String(value), options)}`].join(",")];
3681
+ const keyValue = acc.length === 0 && `${encodedKey}=` || "";
3682
+ return [[...acc, `${keyValue}${encodedValue}`].join(",")];
3636
3683
  }
3637
3684
  case "separator": {
3638
- const keyValue = acc.length === 0 && `${encodeValue(key, options)}=` || "";
3639
- return [[...acc, `${keyValue}${encodeValue(String(value), options)}`].join(arraySeparator || "|")];
3685
+ const keyValue = acc.length === 0 && `${encodedKey}=` || "";
3686
+ return [[...acc, `${keyValue}${encodedValue}`].join(separator)];
3640
3687
  }
3641
3688
  case "bracket-separator": {
3642
- const keyValue = acc.length === 0 && `${encodeValue(key, options)}[]=` || "";
3643
- return [[...acc, `${keyValue}${encodeValue(String(value), options)}`].join(arraySeparator || "|")];
3644
- }
3645
- default: {
3646
- const keyValue = `${encodeValue(key, options)}=`;
3647
- acc.push(`${keyValue}${encodeValue(String(value), options)}`);
3689
+ const keyValue = acc.length === 0 && `${encodedKey}[]=` || "";
3690
+ return [[...acc, `${keyValue}${encodedValue}`].join(separator)];
3648
3691
  }
3692
+ default: acc.push(`${encodedKey}=${encodedValue}`);
3649
3693
  }
3650
3694
  return acc;
3651
3695
  }, []).join("&");
3652
3696
  };
3653
- var stringifyQueryParams = (queryParams, options = stringifyDefaultOptions) => {
3697
+ var stringifyQueryParams = (queryParams, options) => {
3698
+ const config = {
3699
+ ...stringifyDefaultOptions,
3700
+ ...options
3701
+ };
3654
3702
  if (!queryParams || Object.keys(queryParams).length === 0) return "";
3655
3703
  if (typeof queryParams === "string") return queryParams[0] === "?" ? queryParams : `?${queryParams}`;
3656
3704
  const stringified = Object.entries(queryParams).map(([key, value]) => {
3657
- if (Array.isArray(value)) return encodeArray(key, value, options);
3658
- return encodeParams(key, value, options);
3705
+ if (Array.isArray(value)) return encodeArray(key, value, config);
3706
+ return encodeParams(key, value, config);
3659
3707
  }).filter(Boolean).join("&");
3660
3708
  if (stringified) return `?${stringified}`;
3661
3709
  return "";
@@ -3673,10 +3721,9 @@ var getAdapter = () => new Adapter({
3673
3721
  const method = options.method ?? HttpMethods.GET;
3674
3722
  if (SAFE_HTTP_METHODS.includes(method)) return { deduplicate: true };
3675
3723
  return {};
3676
- }).setFetcher(async ({ request, adapterOptions, headers, payload, onError, onResponseEnd, onTimeoutError, onRequestEnd, createAbortListener, getAbortController, onResponseProgress, onResponseStart, onBeforeRequest, onRequestStart, onRequestProgress, onSuccess }) => {
3677
- const { method, client, endpoint, queryParams } = request;
3678
- const queryString = queryParams ? stringifyQueryParams(queryParams) : "";
3679
- const fullUrl = `${client.url}${endpoint}${queryString}`;
3724
+ }).setFetcher(async ({ request, url, endpoint, queryParams, adapterOptions, headers, payload, onError, onResponseEnd, onTimeoutError, onRequestEnd, createAbortListener, getAbortController, onResponseProgress, onResponseStart, onBeforeRequest, onRequestStart, onRequestProgress, onSuccess }) => {
3725
+ const { method } = request;
3726
+ const fullUrl = `${url}${endpoint}${queryParams}`;
3680
3727
  const controller = getAbortController();
3681
3728
  const { timeout: timeoutMs = defaultTimeout, streaming = false, ...restOptions } = adapterOptions || {};
3682
3729
  let timedOut = false;
@@ -4089,6 +4136,7 @@ var Client = class {
4089
4136
  this.fetchDispatcher.emitter.removeAllListeners();
4090
4137
  this.submitDispatcher.emitter.removeAllListeners();
4091
4138
  this.cache.emitter.removeAllListeners();
4139
+ this.appManager.unmount();
4092
4140
  this.cache = cache?.() || new Cache();
4093
4141
  this.appManager = appManager?.() || new AppManager();
4094
4142
  this.fetchDispatcher = fetchDispatcher?.() || new Dispatcher();
@@ -4155,7 +4203,7 @@ var stringifyDefaultOptions = {
4155
4203
  strict: true,
4156
4204
  encode: true,
4157
4205
  arrayFormat: "bracket",
4158
- arraySeparator: "bracket",
4206
+ arraySeparator: "|",
4159
4207
  sort: false,
4160
4208
  skipNull: true,
4161
4209
  skipEmptyString: true
@@ -4304,6 +4352,6 @@ var createConfiguration = () => {
4304
4352
  return (defaults) => defaults;
4305
4353
  };
4306
4354
  //#endregion
4307
- export { AbortError, Adapter, AppEvents, AppManager, Cache, Client, DeletedError, Dispatcher, DispatcherMode, EventEmitter, HttpAdapter, HttpMethods, LoggerManager, Plugin, Request, RequestManager, RequestProcessingError, SAFE_HTTP_METHODS, Time, TimeoutError, UnexpectedError, appManagerInitialOptions, canRetryRequest, createClient, createConfiguration, createRequestHooks, createSdk, defaultMapper, defaultTimeout, getAbortByAbortKey, getAbortByIdKey, getAbortKey, getAdapter, getAdapterBindings, getAdapterHeaders, getAdapterOnError, getAdapterPayload, getAppManagerEvents, getCacheByKey, getCacheData, getCacheEvents, getCacheKey, getDeleteByKey, getDeleteKey, getDispatcherChangeByKey, getDispatcherChangeKey, getDispatcherDrainedByKey, getDispatcherDrainedKey, getDispatcherEvents, getDispatcherRunningByKey, getDispatcherRunningKey, getDispatcherStatusByKey, getDispatcherStatusKey, getDownloadProgressByIdKey, getDownloadProgressByQueryKey, getDownloadProgressKey, getErrorMessage, getInvalidateByKey, getInvalidateKey, getIsEqualTimestamp, getLoadingByCacheKey, getLoadingByIdKey, getLoadingByQueryKey, getLoadingKey, getProgressData, getProgressValue, getRemoveByIdKey, getRemoveByQueryKey, getRemoveKey, getRequestDeduplicatedByCacheKey, getRequestDeduplicatedByIdKey, getRequestDeduplicatedByQueryKey, getRequestDeduplicatedKey, getRequestDispatcher, getRequestEta, getRequestKey, getRequestManagerEvents, getRequestStarByQueryKey, getRequestStartByIdKey, getRequestStartKey, getRequestType, getResponseByCacheKey, getResponseByIdKey, getResponseHeaders, getResponseKey, getResponseStartByIdKey, getResponseStartByQueryKey, getResponseStartKey, getSimpleKey, getTime, getUniqueRequestId, getUploadProgressByIdKey, getUploadProgressByQueryKey, getUploadProgressKey, handleResponse, hasDocument, hasWindow, interceptRequest, interceptResponse, isPlainObject, logLevelOrder, logger, loggerColors, loggerStyles, mapResponseForSend, mocker, onDocumentEvent, onWindowEvent, parseErrorResponse, parseResponse, replaceEqualDeep, resolveClientMode, scopeKey, sendRequest, stringifyDefaultOptions, stringifyKey, stringifyQueryParams, stringifyValue, xhrExtra };
4355
+ export { AbortError, Adapter, AppEvents, AppManager, Cache, Client, DeletedError, Dispatcher, DispatcherMode, EventEmitter, HttpAdapter, HttpMethods, LoggerManager, Plugin, Request, RequestManager, RequestProcessingError, SAFE_HTTP_METHODS, Time, TimeoutError, UnexpectedError, appManagerInitialOptions, canRetryRequest, createClient, createConfiguration, createRequestHooks, createSdk, defaultMapper, defaultTimeout, getAbortByAbortKey, getAbortByIdKey, getAbortKey, getAdapter, getAdapterBindings, getAdapterHeaders, getAdapterOnError, getAdapterPayload, getAppManagerEvents, getCacheByKey, getCacheData, getCacheEvents, getCacheKey, getDeleteByKey, getDeleteKey, getDispatcherChangeByKey, getDispatcherChangeKey, getDispatcherDrainedByKey, getDispatcherDrainedKey, getDispatcherEvents, getDispatcherRunningByKey, getDispatcherRunningKey, getDispatcherStatusByKey, getDispatcherStatusKey, getDownloadProgressByIdKey, getDownloadProgressByQueryKey, getDownloadProgressKey, getErrorMessage, getInvalidateByKey, getInvalidateKey, getIsEqualTimestamp, getLoadingByCacheKey, getLoadingByIdKey, getLoadingByQueryKey, getLoadingKey, getProgressData, getProgressValue, getRemoveByIdKey, getRemoveByQueryKey, getRemoveKey, getRequestDeduplicatedByCacheKey, getRequestDeduplicatedByIdKey, getRequestDeduplicatedByQueryKey, getRequestDeduplicatedKey, getRequestDispatcher, getRequestEta, getRequestKey, getRequestManagerEvents, getRequestStarByQueryKey, getRequestStartByIdKey, getRequestStartKey, getRequestType, getResponseByCacheKey, getResponseByIdKey, getResponseHeaders, getResponseKey, getResponseStartByIdKey, getResponseStartByQueryKey, getResponseStartKey, getSimpleKey, getTime, getUniqueRequestId, getUploadProgressByIdKey, getUploadProgressByQueryKey, getUploadProgressKey, handleResponse, hasDocument, hasWindow, interceptRequest, interceptResponse, isNavigatorOnline, isPlainObject, logLevelOrder, logger, loggerColors, loggerStyles, mapResponseForSend, mocker, onDocumentEvent, onWindowEvent, parseErrorResponse, parseResponse, replaceEqualDeep, resolveClientMode, scopeKey, sendRequest, stringifyDefaultOptions, stringifyKey, stringifyQueryParams, stringifyValue, xhrExtra };
4308
4356
 
4309
4357
  //# sourceMappingURL=index.mjs.map