@hyper-fetch/core 9.6.1 → 9.7.0

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.
Files changed (134) hide show
  1. package/__tests__/features/adapter/adapter.bindings.progress.spec.ts +120 -0
  2. package/__tests__/features/adapter/adapter.bindings.spec.ts +4 -6
  3. package/__tests__/features/adapter/adapter.defaults.spec.ts +87 -0
  4. package/__tests__/features/adapter/adapter.mapping.spec.ts +257 -0
  5. package/__tests__/features/cache/cache.lazy-storage.clear.spec.ts +145 -0
  6. package/__tests__/features/cache/cache.lazy-storage.resilience.spec.ts +667 -0
  7. package/__tests__/features/cache/cache.scoped-events.spec.ts +183 -0
  8. package/__tests__/features/cache/cache.semantics.spec.ts +785 -0
  9. package/__tests__/features/cache/cache.structural-sharing.spec.ts +565 -0
  10. package/__tests__/features/cache/cache.timing.spec.ts +448 -0
  11. package/__tests__/features/client/client.clear.spec.ts +313 -0
  12. package/__tests__/features/client/client.configuration.spec.ts +416 -0
  13. package/__tests__/features/client/client.hydration.round-trip.spec.ts +324 -0
  14. package/__tests__/features/client/client.interceptor.spec.ts +54 -45
  15. package/__tests__/features/client/client.interceptors.pipeline.spec.ts +599 -0
  16. package/__tests__/features/client/client.user-errors.spec.ts +220 -0
  17. package/__tests__/features/dispatcher/dispatcher.cleanup.spec.ts +534 -0
  18. package/__tests__/features/dispatcher/dispatcher.control.spec.ts +381 -0
  19. package/__tests__/features/dispatcher/dispatcher.modes.spec.ts +527 -0
  20. package/__tests__/features/dispatcher/dispatcher.offline.spec.ts +278 -0
  21. package/__tests__/features/dispatcher/dispatcher.queue.spec.ts +35 -12
  22. package/__tests__/features/dispatcher/dispatcher.reentrancy.spec.ts +309 -0
  23. package/__tests__/features/dispatcher/dispatcher.response-order.spec.ts +241 -0
  24. package/__tests__/features/dispatcher/dispatcher.retry-flow.spec.ts +554 -0
  25. package/__tests__/features/dispatcher/dispatcher.retry-removal.spec.ts +196 -0
  26. package/__tests__/features/dispatcher/dispatcher.retry.spec.ts +4 -3
  27. package/__tests__/features/http-adapter/http-adapter.e2e.spec.ts +917 -0
  28. package/__tests__/features/managers/app/app.manager.events.spec.ts +434 -0
  29. package/__tests__/features/managers/logger/logger.levels.spec.ts +199 -0
  30. package/__tests__/features/managers/request/request.manager.abort.spec.ts +449 -0
  31. package/__tests__/features/mocker/mocker.base.spec.ts +22 -3
  32. package/__tests__/features/mocker/mocker.errors.spec.ts +99 -0
  33. package/__tests__/features/mocker/mocker.outcomes.spec.ts +308 -0
  34. package/__tests__/features/optimistic/optimistic.concurrency.spec.ts +278 -0
  35. package/__tests__/features/optimistic/optimistic.helpers.spec.ts +307 -0
  36. package/__tests__/features/optimistic/optimistic.matrix.spec.ts +315 -0
  37. package/__tests__/features/optimistic/optimistic.races.spec.ts +270 -0
  38. package/__tests__/features/optimistic/optimistic.random.spec.ts +191 -0
  39. package/__tests__/features/optimistic/optimistic.rollback.spec.ts +1001 -0
  40. package/__tests__/features/optimistic/optimistic.typescript.spec.ts +196 -0
  41. package/__tests__/features/plugin/plugin.lifecycle.spec.ts +457 -0
  42. package/__tests__/features/request/request.async-mapper-removal.spec.ts +138 -0
  43. package/__tests__/features/request/request.immutability.spec.ts +259 -0
  44. package/__tests__/features/request/request.inference.spec.ts +269 -0
  45. package/__tests__/features/request/request.lifecycle.spec.ts +682 -0
  46. package/__tests__/features/request/request.optimistic-settlement.spec.ts +35 -17
  47. package/__tests__/features/request/request.optimistic.spec.ts +12 -1
  48. package/__tests__/features/request/request.values.spec.ts +408 -0
  49. package/__tests__/features/sdk/sdk.builder.spec.ts +304 -0
  50. package/__tests__/features/utils/emitter.listeners.spec.ts +202 -0
  51. package/__tests__/utils/controlled-adapter.utils.ts +119 -0
  52. package/__tests__/utils/fixtures.utils.ts +193 -0
  53. package/__tests__/utils/optimistic.utils.ts +124 -0
  54. package/dist/adapter/adapter.bindings.d.ts.map +1 -1
  55. package/dist/adapter/adapter.utils.d.ts.map +1 -1
  56. package/dist/cache/cache.d.ts +12 -1
  57. package/dist/cache/cache.d.ts.map +1 -1
  58. package/dist/cache/cache.events.d.ts +20 -6
  59. package/dist/cache/cache.events.d.ts.map +1 -1
  60. package/dist/cache/cache.utils.d.ts +1 -0
  61. package/dist/cache/cache.utils.d.ts.map +1 -1
  62. package/dist/client/client.d.ts +3 -3
  63. package/dist/client/client.d.ts.map +1 -1
  64. package/dist/client/client.utils.d.ts.map +1 -1
  65. package/dist/dispatcher/dispatcher.d.ts +26 -5
  66. package/dist/dispatcher/dispatcher.d.ts.map +1 -1
  67. package/dist/http-adapter/http-adapter.fetch.d.ts.map +1 -1
  68. package/dist/index.d.ts +1 -0
  69. package/dist/index.d.ts.map +1 -1
  70. package/dist/index.mjs +2787 -1893
  71. package/dist/index.mjs.map +1 -1
  72. package/dist/managers/app/app.manager.constants.d.ts.map +1 -1
  73. package/dist/managers/app/app.manager.d.ts +9 -0
  74. package/dist/managers/app/app.manager.d.ts.map +1 -1
  75. package/dist/managers/app/app.manager.utils.d.ts.map +1 -1
  76. package/dist/managers/logger/logger.manager.d.ts.map +1 -1
  77. package/dist/managers/request/request.manager.d.ts.map +1 -1
  78. package/dist/managers/request/request.manager.types.d.ts +2 -0
  79. package/dist/managers/request/request.manager.types.d.ts.map +1 -1
  80. package/dist/mocker/mocker.d.ts +1 -1
  81. package/dist/mocker/mocker.d.ts.map +1 -1
  82. package/dist/optimistic/index.d.ts +5 -0
  83. package/dist/optimistic/index.d.ts.map +1 -0
  84. package/dist/optimistic/optimistic.d.ts +67 -0
  85. package/dist/optimistic/optimistic.d.ts.map +1 -0
  86. package/dist/optimistic/optimistic.settlement.d.ts +60 -0
  87. package/dist/optimistic/optimistic.settlement.d.ts.map +1 -0
  88. package/dist/optimistic/optimistic.types.d.ts +109 -0
  89. package/dist/optimistic/optimistic.types.d.ts.map +1 -0
  90. package/dist/optimistic/optimistic.utils.d.ts +29 -0
  91. package/dist/optimistic/optimistic.utils.d.ts.map +1 -0
  92. package/dist/plugin/plugin.d.ts +2 -0
  93. package/dist/plugin/plugin.d.ts.map +1 -1
  94. package/dist/request/request.d.ts +14 -6
  95. package/dist/request/request.d.ts.map +1 -1
  96. package/dist/request/request.types.d.ts +40 -1
  97. package/dist/request/request.types.d.ts.map +1 -1
  98. package/dist/request/request.utils.d.ts.map +1 -1
  99. package/dist/utils/emitter.utils.d.ts.map +1 -1
  100. package/dist/utils/error.utils.d.ts +17 -0
  101. package/dist/utils/error.utils.d.ts.map +1 -0
  102. package/dist/utils/index.d.ts +1 -0
  103. package/dist/utils/index.d.ts.map +1 -1
  104. package/package.json +1 -1
  105. package/src/adapter/adapter.bindings.ts +46 -18
  106. package/src/adapter/adapter.utils.ts +47 -7
  107. package/src/cache/cache.events.ts +24 -8
  108. package/src/cache/cache.ts +110 -21
  109. package/src/cache/cache.utils.ts +33 -10
  110. package/src/client/client.ts +101 -7
  111. package/src/client/client.utils.ts +10 -4
  112. package/src/dispatcher/dispatcher.ts +285 -132
  113. package/src/http-adapter/http-adapter.fetch.ts +15 -3
  114. package/src/index.ts +4 -0
  115. package/src/managers/app/app.manager.constants.ts +12 -1
  116. package/src/managers/app/app.manager.ts +43 -23
  117. package/src/managers/app/app.manager.utils.ts +8 -4
  118. package/src/managers/logger/logger.manager.ts +21 -8
  119. package/src/managers/request/request.manager.ts +7 -1
  120. package/src/managers/request/request.manager.types.ts +2 -0
  121. package/src/mocker/mocker.ts +14 -11
  122. package/src/optimistic/index.ts +4 -0
  123. package/src/optimistic/optimistic.settlement.ts +406 -0
  124. package/src/optimistic/optimistic.ts +162 -0
  125. package/src/optimistic/optimistic.types.ts +175 -0
  126. package/src/optimistic/optimistic.utils.ts +112 -0
  127. package/src/plugin/plugin.ts +6 -0
  128. package/src/request/request.ts +50 -28
  129. package/src/request/request.types.ts +41 -1
  130. package/src/request/request.utils.ts +51 -66
  131. package/src/utils/emitter.utils.ts +9 -2
  132. package/src/utils/error.utils.ts +29 -0
  133. package/src/utils/index.ts +1 -0
  134. package/tsconfig.json +2 -0
@@ -1,6 +1,7 @@
1
1
  import type { RequestResponseType, ResponseSuccessType, ResponseErrorType } from "adapter";
2
2
  import type { ClientInstance } from "client";
3
3
  import type { RequestEventType, RequestProgressEventType, RequestResponseEventType } from "managers";
4
+ import type { OptimisticFactoryType, OptimisticUpdatesType } from "optimistic/optimistic.types";
4
5
  /* eslint-disable @typescript-eslint/no-shadow */
5
6
  import type {
6
7
  NullableKeys,
@@ -372,6 +373,11 @@ export type RequestDynamicSendOptionsType<Request extends RequestInstance> = Omi
372
373
  > & {
373
374
  dispatcherType?: "auto" | "fetch" | "submit";
374
375
  cachePolicy?: RequestCachePolicyType;
376
+ /**
377
+ * Optimistic update of this call - `optimistic()` operations or a callback like the one of `setOptimistic`.
378
+ * Replaces the request's own optimistic callback for this call.
379
+ */
380
+ optimistic?: OptimisticSendOptionType<Request>;
375
381
  };
376
382
 
377
383
  // Request making
@@ -429,6 +435,15 @@ export type OptimisticCallbackArgs<Req extends RequestInstance> = {
429
435
  request: Req;
430
436
  client: Req["client"];
431
437
  payload: ExtractPayloadType<Req>;
438
+ /** Endpoint params of the mutation */
439
+ params: ExtractParamsType<Req>;
440
+ /** Query params of the mutation */
441
+ queryParams: ExtractQueryParamsType<Req>;
442
+ /**
443
+ * The `optimistic()` builder with `.commit()` and `.rollback()` typed by this mutation's response.
444
+ * Same as the exported `optimistic`, whose callbacks receive an erased mutation type.
445
+ */
446
+ optimistic: OptimisticFactoryType<Req>;
432
447
  };
433
448
 
434
449
  /**
@@ -441,17 +456,42 @@ export type OptimisticRollbackArgs<Req extends RequestInstance> =
441
456
  | { reason: "error" | "abort"; response: RequestResponseType<Req>; request: Req }
442
457
  | { reason: "removed"; response?: undefined; request: Req };
443
458
 
459
+ /**
460
+ * Object form of the optimistic result. All fields are optional.
461
+ */
444
462
  export type OptimisticCallbackResult<Ctx, Req extends RequestInstance = RequestInstance> = {
463
+ /** Value delivered as `mutationContext` to the lifecycle callbacks */
445
464
  context?: Ctx;
465
+ /** Operations built with `optimistic()`, applied in order and reverted in reverse order */
466
+ updates?: OptimisticUpdatesType;
446
467
  /** Runs once when the request settles without success, also outside of any framework */
447
468
  rollback?: (args: OptimisticRollbackArgs<Req>) => void;
448
469
  /** Requests invalidated in the cache once the request succeeds */
449
470
  invalidate?: RequestInstance[];
471
+ /**
472
+ * Decides if a final error reverts the change (`true` by default). Aborted and removed requests are always reverted.
473
+ * With `false` the change stays, no rollback runs and nothing is refreshed.
474
+ */
475
+ rollbackOnError?: boolean | ((args: { response: RequestResponseType<Req>; request: Req }) => boolean);
476
+ /** Refresh the targets of `updates` once the last pending mutation on them settles (`true` by default) */
477
+ revalidate?: boolean;
450
478
  };
451
479
 
480
+ /**
481
+ * What an optimistic callback returns: an array of `optimistic()` operations, or the object form.
482
+ */
483
+ export type OptimisticCallbackReturnType<Ctx, Req extends RequestInstance = RequestInstance> =
484
+ | OptimisticUpdatesType
485
+ | OptimisticCallbackResult<Ctx, Req>;
486
+
452
487
  export type OptimisticCallback<Req extends RequestInstance, Ctx = undefined> = (
453
488
  args: OptimisticCallbackArgs<Req>,
454
- ) => OptimisticCallbackResult<Ctx, Req> | Promise<OptimisticCallbackResult<Ctx, Req>>;
489
+ ) => OptimisticCallbackReturnType<Ctx, Req> | Promise<OptimisticCallbackReturnType<Ctx, Req>>;
490
+
491
+ /**
492
+ * Per-call optimistic update - operations or a callback like the one of `setOptimistic`. Replaces the request's own.
493
+ */
494
+ export type OptimisticSendOptionType<Req extends RequestInstance> = OptimisticUpdatesType | OptimisticCallback<Req, any>;
455
495
 
456
496
  // Mappers
457
497
 
@@ -3,11 +3,15 @@ import type { AdapterInstance, ProgressType, RequestResponseType, ResponseType }
3
3
  import { SAFE_HTTP_METHODS } from "constants/http.constants";
4
4
  import type { Dispatcher } from "dispatcher";
5
5
  import type { RequestResponseEventType } from "managers";
6
+ import { optimistic } from "optimistic/optimistic";
7
+ import type { OptimisticPendingType } from "optimistic/optimistic.settlement";
8
+ import { applyOptimistic, getOptimisticResult, settleOptimistic } from "optimistic/optimistic.settlement";
6
9
  import type { ExtractAdapterType, ExtractErrorType } from "types";
10
+ import { runUserCode } from "utils";
7
11
 
8
12
  import type {
9
13
  OptimisticCallbackResult,
10
- OptimisticRollbackArgs,
14
+ OptimisticSendOptionType,
11
15
  ProgressEventType,
12
16
  RequestInstance,
13
17
  RequestJSON,
@@ -183,43 +187,6 @@ export const mapResponseForSend = async <Request extends RequestInstance>(
183
187
  return (mapping || response) as RequestResponseType<Request>;
184
188
  };
185
189
 
186
- /**
187
- * Rollback is user code running in the middle of the response handling, its failure can't affect the request
188
- */
189
- const rollbackOptimistic = (
190
- optimistic: OptimisticCallbackResult<any>,
191
- args: OptimisticRollbackArgs<RequestInstance>,
192
- ): void => {
193
- const logFailure = (error: unknown) => {
194
- args.request.client.logger.error({
195
- title: "Optimistic rollback failed",
196
- type: "system",
197
- extra: { error, reason: args.reason, request: args.request },
198
- });
199
- };
200
-
201
- try {
202
- // Async rollback is not awaited, but its rejection can't stay unhandled
203
- Promise.resolve(optimistic.rollback?.(args)).catch(logFailure);
204
- } catch (error) {
205
- logFailure(error);
206
- }
207
- };
208
-
209
- const invalidateOptimistic = (optimistic: OptimisticCallbackResult<any>, request: RequestInstance): void => {
210
- optimistic.invalidate?.forEach((target) => {
211
- try {
212
- request.client.cache.invalidate(target);
213
- } catch (error) {
214
- request.client.logger.error({
215
- title: "Optimistic invalidation failed",
216
- type: "system",
217
- extra: { error, target, request },
218
- });
219
- }
220
- });
221
- };
222
-
223
190
  export const sendRequest = async <Request extends RequestInstance>(
224
191
  request: Request,
225
192
  options?: RequestSendOptionsType<Request>,
@@ -229,14 +196,26 @@ export const sendRequest = async <Request extends RequestInstance>(
229
196
  const [dispatcher] = getRequestDispatcher(request, options?.dispatcherType);
230
197
 
231
198
  let mutationContext: OptimisticCallbackResult<any> | undefined;
199
+ let pendingOptimistic: OptimisticPendingType | undefined;
200
+ // The per-call option replaces the optimistic callback of the request
201
+ const optimisticSource = (options?.optimistic ?? request.optimistic) as
202
+ | OptimisticSendOptionType<RequestInstance>
203
+ | undefined;
232
204
 
233
- if (request.optimistic) {
205
+ if (optimisticSource) {
234
206
  try {
235
- mutationContext = await request.optimistic({
236
- request,
237
- client: request.client,
238
- payload: request.payload,
239
- });
207
+ const result = Array.isArray(optimisticSource)
208
+ ? optimisticSource
209
+ : optimisticSource({
210
+ request,
211
+ client: request.client,
212
+ payload: request.payload,
213
+ params: request.params,
214
+ queryParams: request.queryParams,
215
+ optimistic,
216
+ });
217
+ // Synchronous callbacks change the cache within the send() call, async ones once they resolve
218
+ mutationContext = getOptimisticResult(result instanceof Promise ? await result : result);
240
219
  } catch (error) {
241
220
  return {
242
221
  data: null,
@@ -250,6 +229,7 @@ export const sendRequest = async <Request extends RequestInstance>(
250
229
  responseTimestamp: Date.now(),
251
230
  };
252
231
  }
232
+ pendingOptimistic = applyOptimistic(client, mutationContext);
253
233
  }
254
234
 
255
235
  return new Promise<RequestResponseType<Request>>((resolve) => {
@@ -258,6 +238,7 @@ export const sendRequest = async <Request extends RequestInstance>(
258
238
  let isDelivered = false;
259
239
  let isSettled = false;
260
240
  const requestId = dispatcher.add(request);
241
+ const queryKey = scopeKey(request.queryKey, request.scope);
261
242
  const { $hooks } = request;
262
243
 
263
244
  // Failed attempts stay in the dispatcher queue when they are going to be sent again
@@ -265,6 +246,10 @@ export const sendRequest = async <Request extends RequestInstance>(
265
246
  if (response.success || details.isCanceled) {
266
247
  return false;
267
248
  }
249
+ // One that was taken out of the queue while it was running (cleared queue) has just given its last response
250
+ if (!dispatcher.getRequest(queryKey, requestId)) {
251
+ return false;
252
+ }
268
253
  return details.willRetry || (request.offline && details.isOffline);
269
254
  };
270
255
 
@@ -278,9 +263,9 @@ export const sendRequest = async <Request extends RequestInstance>(
278
263
  };
279
264
 
280
265
  // Attached ahead of `onBeforeSent`, so listeners added there already observe the settled cache
281
- const unmountSettlement = mutationContext
266
+ const unmountSettlement = pendingOptimistic
282
267
  ? requestManager.events.onResponseById<Request>(requestId, (values) => {
283
- const optimistic = mutationContext as OptimisticCallbackResult<any>;
268
+ const pending = pendingOptimistic as OptimisticPendingType;
284
269
  const willBeResent = getWillBeResent(values);
285
270
 
286
271
  const settle = (response: ResponseType<any, any, AdapterInstance>) => {
@@ -290,11 +275,11 @@ export const sendRequest = async <Request extends RequestInstance>(
290
275
  isSettled = true;
291
276
 
292
277
  if (values.details.isCanceled) {
293
- rollbackOptimistic(optimistic, { reason: "abort", response, request });
278
+ settleOptimistic(pending, { type: "rollback", reason: "abort", response, request });
294
279
  } else if (response.success) {
295
- invalidateOptimistic(optimistic, request);
280
+ settleOptimistic(pending, { type: "success", response, request });
296
281
  } else {
297
- rollbackOptimistic(optimistic, { reason: "error", response, request });
282
+ settleOptimistic(pending, { type: "rollback", reason: "error", response, request });
298
283
  }
299
284
  };
300
285
 
@@ -308,31 +293,31 @@ export const sendRequest = async <Request extends RequestInstance>(
308
293
  : undefined;
309
294
 
310
295
  const beforeSentData = { requestId, request, mutationContext };
311
- options?.onBeforeSent?.(beforeSentData);
312
- $hooks.__emit("onBeforeSent", beforeSentData);
296
+ runUserCode(() => options?.onBeforeSent?.(beforeSentData));
297
+ runUserCode(() => $hooks.__emit("onBeforeSent", beforeSentData));
313
298
 
314
299
  const unmountRequestStart = requestManager.events.onRequestStartById<Request>(requestId, (data) => {
315
300
  const enriched = { ...data, mutationContext };
316
- options?.onRequestStart?.(enriched);
317
- $hooks.__emit("onRequestStart", enriched);
301
+ runUserCode(() => options?.onRequestStart?.(enriched));
302
+ runUserCode(() => $hooks.__emit("onRequestStart", enriched));
318
303
  });
319
304
 
320
305
  const unmountResponseStart = requestManager.events.onResponseStartById<Request>(requestId, (data) => {
321
306
  const enriched = { ...data, mutationContext };
322
- options?.onResponseStart?.(enriched);
323
- $hooks.__emit("onResponseStart", enriched);
307
+ runUserCode(() => options?.onResponseStart?.(enriched));
308
+ runUserCode(() => $hooks.__emit("onResponseStart", enriched));
324
309
  });
325
310
 
326
311
  const unmountUpload = requestManager.events.onUploadProgressById<Request>(requestId, (data) => {
327
312
  const enriched = { ...data, mutationContext };
328
- options?.onUploadProgress?.(enriched);
329
- $hooks.__emit("onUploadProgress", enriched);
313
+ runUserCode(() => options?.onUploadProgress?.(enriched));
314
+ runUserCode(() => $hooks.__emit("onUploadProgress", enriched));
330
315
  });
331
316
 
332
317
  const unmountDownload = requestManager.events.onDownloadProgressById<Request>(requestId, (data) => {
333
318
  const enriched = { ...data, mutationContext };
334
- options?.onDownloadProgress?.(enriched);
335
- $hooks.__emit("onDownloadProgress", enriched);
319
+ runUserCode(() => options?.onDownloadProgress?.(enriched));
320
+ runUserCode(() => $hooks.__emit("onDownloadProgress", enriched));
336
321
  });
337
322
 
338
323
  // When resolved
@@ -351,8 +336,8 @@ export const sendRequest = async <Request extends RequestInstance>(
351
336
  }
352
337
  isDelivered = true;
353
338
 
354
- options?.onResponse?.(enrichedValues);
355
- $hooks.__emit("onResponse", enrichedValues);
339
+ runUserCode(() => options?.onResponse?.(enrichedValues));
340
+ runUserCode(() => $hooks.__emit("onResponse", enrichedValues));
356
341
  resolve(data);
357
342
 
358
343
  // Unmount Listeners
@@ -373,7 +358,7 @@ export const sendRequest = async <Request extends RequestInstance>(
373
358
  else {
374
359
  const data = mapping || response;
375
360
  const { success } = data;
376
- handleResponse(success, data as ResponseType<any, any, ExtractAdapterType<Request>>);
361
+ handleResponse(success, data);
377
362
  }
378
363
  });
379
364
 
@@ -383,14 +368,14 @@ export const sendRequest = async <Request extends RequestInstance>(
383
368
  isResolved = true;
384
369
  isDelivered = true;
385
370
 
386
- if (mutationContext && !isSettled) {
371
+ if (pendingOptimistic && !isSettled) {
387
372
  isSettled = true;
388
- rollbackOptimistic(mutationContext, { reason: "removed", request });
373
+ settleOptimistic(pendingOptimistic, { type: "rollback", reason: "removed", request });
389
374
  }
390
375
 
391
376
  const enriched = { ...data, mutationContext };
392
- options?.onRemove?.(enriched);
393
- $hooks.__emit("onRemove", enriched);
377
+ runUserCode(() => options?.onRemove?.(enriched));
378
+ runUserCode(() => $hooks.__emit("onRemove", enriched));
394
379
  resolve({
395
380
  data: null,
396
381
  status: null,
@@ -1,5 +1,7 @@
1
1
  import Emitter from "events";
2
2
 
3
+ import { runUserCode } from "./error.utils";
4
+
3
5
  const getListenName = (event: string | symbol) => `listen_${String(event)}`;
4
6
 
5
7
  export class EventEmitter extends Emitter {
@@ -17,8 +19,13 @@ export class EventEmitter extends Emitter {
17
19
  params.push(isTriggeredExternally);
18
20
  }
19
21
 
20
- this.emitCallbacks?.forEach((callback) => callback(...params));
21
- return super.emit(...params);
22
+ this.emitCallbacks?.forEach((callback) => runUserCode(() => callback(...params)));
23
+
24
+ // Every listener gets the event - a throwing one can't keep it from the listeners added after it
25
+ const listeners = this.rawListeners(type);
26
+ listeners.forEach((listener) => runUserCode(() => listener.call(this, ...params.slice(1))));
27
+
28
+ return listeners.length > 0;
22
29
  }
23
30
 
24
31
  onEmit = (callback: (event: string, data: any, isTriggeredExternally?: true) => void) => {
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Callbacks, listeners, plugins and optimistic handlers are the code of the user running inside of the request
3
+ * lifecycle. Their error can't break it, and it can't get lost either - it is thrown from a timer, outside of the
4
+ * lifecycle, so it reaches the error handlers of the environment (`window.onerror`, `uncaughtException`).
5
+ * @internal
6
+ * @param error value thrown by the user code
7
+ */
8
+ export const throwOutsideLifecycle = (error: unknown): void => {
9
+ setTimeout(() => {
10
+ throw error;
11
+ });
12
+ };
13
+
14
+ /**
15
+ * Runs the code of the user in the middle of the request lifecycle. When it throws, the lifecycle goes on
16
+ * and the error is thrown outside of it.
17
+ * @internal
18
+ * @param callback code of the user to run
19
+ * @returns `true` when the callback finished, `false` when it threw
20
+ */
21
+ export const runUserCode = (callback: VoidFunction): boolean => {
22
+ try {
23
+ callback();
24
+ return true;
25
+ } catch (error) {
26
+ throwOutsideLifecycle(error);
27
+ return false;
28
+ }
29
+ };
@@ -1,2 +1,3 @@
1
+ export * from "./error.utils";
1
2
  export * from "./uuid.utils";
2
3
  export * from "./emitter.utils";
package/tsconfig.json CHANGED
@@ -19,6 +19,8 @@
19
19
  "managers/*": ["./src/managers/*"],
20
20
  "mocker": ["./src/mocker"],
21
21
  "mocker/*": ["./src/mocker/*"],
22
+ "optimistic": ["./src/optimistic"],
23
+ "optimistic/*": ["./src/optimistic/*"],
22
24
  "plugin": ["./src/plugin"],
23
25
  "plugin/*": ["./src/plugin/*"],
24
26
  "request": ["./src/request"],