@navios/di-react 2.0.0-alpha.0 → 2.0.0-alpha.1

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/index.mjs CHANGED
@@ -205,29 +205,32 @@ function getArgsKey(args) {
205
205
  return `#${id}`;
206
206
  }
207
207
  }
208
- // src/service/use-service.mts
209
- function serviceReducer(state, action) {
210
- switch (action.type) {
211
- case "loading": return { status: "loading" };
212
- case "success": return {
213
- status: "success",
214
- data: action.data
215
- };
216
- case "error": return {
217
- status: "error",
218
- error: action.error
219
- };
220
- case "reset": return { status: "idle" };
221
- default: return state;
208
+ // src/service/use-resolved-service.mts
209
+ const LOADING = { status: "loading" };
210
+ const NOT_FOUND = { status: "not-found" };
211
+ /** Whether `error` says that `token` itself has no provider. */
212
+ function isMissingProvider(container, token, error) {
213
+ return error instanceof DIError && error.code === DIErrorCode.ProviderNotFound && !container.isRegistered(token);
214
+ }
215
+ /** What the container holds for `token` and `args` now, or `null`. */
216
+ function peekInstance(container, token, args) {
217
+ try {
218
+ return container.peek(token, args);
219
+ } catch {
220
+ return null;
222
221
  }
223
222
  }
224
- function useService(token, args) {
223
+ /**
224
+ * Resolution behind `useService` and `useOptionalService`. With `optional`,
225
+ * a token without a provider ends in `not-found` instead of `error`.
226
+ */
227
+ function useResolvedService(token, args, { optional }) {
225
228
  const container = useContainer();
226
229
  const argsKey = getArgsKey(args);
227
230
  const stableArgs = useMemo(() => args, [argsKey]);
228
231
  const initialSyncRef = useRef(void 0);
229
232
  if (initialSyncRef.current === void 0) {
230
- const instance = container.peek(token, args);
233
+ const instance = peekInstance(container, token, args);
231
234
  initialSyncRef.current = instance === null ? null : {
232
235
  container,
233
236
  token,
@@ -235,50 +238,62 @@ function useService(token, args) {
235
238
  instance
236
239
  };
237
240
  }
238
- const initialState = initialSyncRef.current !== null ? {
241
+ const [state, setState] = useState(() => initialSyncRef.current ? {
239
242
  status: "success",
240
243
  data: initialSyncRef.current.instance
241
- } : { status: "idle" };
242
- const [state, dispatch] = useReducer(serviceReducer, initialState);
243
- const [refetchCounter, setRefetchCounter] = useState(0);
244
+ } : LOADING);
245
+ const [refetchCount, setRefetchCount] = useState(0);
244
246
  useEffect(() => {
247
+ let isCurrent = true;
245
248
  let unsubscribe;
246
- let isMounted = true;
249
+ let latest = 0;
247
250
  const subscribe = () => {
248
251
  if (unsubscribe) return;
249
252
  unsubscribe = container.onInvalidate(token, stableArgs, () => {
250
- if (!isMounted) return;
251
- dispatch({ type: "loading" });
253
+ if (!isCurrent) return;
254
+ latest++;
255
+ setState(LOADING);
252
256
  queueMicrotask(() => {
253
- if (isMounted) fetchAndSubscribe();
257
+ if (isCurrent) resolve();
254
258
  });
255
259
  });
256
260
  };
257
- const fetchAndSubscribe = async () => {
261
+ const resolve = async () => {
262
+ const run = ++latest;
263
+ try {
264
+ subscribe();
265
+ } catch {}
258
266
  try {
259
267
  const instance = await container.get(token, stableArgs);
260
- if (!isMounted) return;
261
- dispatch({
262
- type: "success",
268
+ if (!isCurrent || run !== latest) return;
269
+ setState({
270
+ status: "success",
263
271
  data: instance
264
272
  });
265
273
  subscribe();
266
274
  } catch (error) {
267
- if (isMounted) dispatch({
268
- type: "error",
275
+ if (!isCurrent || run !== latest) return;
276
+ setState(optional && isMissingProvider(container, token, error) ? NOT_FOUND : {
277
+ status: "error",
269
278
  error
270
279
  });
271
280
  }
272
281
  };
273
282
  const initial = initialSyncRef.current;
274
- if (initial != null && initial.container === container && initial.token === token && initial.argsKey === argsKey && refetchCounter === 0) subscribe();
275
- else {
283
+ if (initial && initial.container === container && initial.token === token && initial.argsKey === argsKey && refetchCount === 0) {
284
+ subscribe();
285
+ if (peekInstance(container, token, stableArgs) !== initial.instance) {
286
+ initialSyncRef.current = null;
287
+ setState(LOADING);
288
+ resolve();
289
+ }
290
+ } else {
276
291
  initialSyncRef.current = null;
277
- dispatch({ type: "loading" });
278
- fetchAndSubscribe();
292
+ setState(LOADING);
293
+ resolve();
279
294
  }
280
295
  return () => {
281
- isMounted = false;
296
+ isCurrent = false;
282
297
  unsubscribe?.();
283
298
  };
284
299
  }, [
@@ -286,11 +301,18 @@ function useService(token, args) {
286
301
  token,
287
302
  stableArgs,
288
303
  argsKey,
289
- refetchCounter
304
+ refetchCount,
305
+ optional
290
306
  ]);
291
- const refetch = useCallback(() => {
292
- setRefetchCounter((c) => c + 1);
293
- }, []);
307
+ return {
308
+ state,
309
+ refetch: useCallback(() => {
310
+ setRefetchCount((count) => count + 1);
311
+ }, [])
312
+ };
313
+ }
314
+ /** The result object of `useService` for a state. */
315
+ function serviceResult(state, refetch) {
294
316
  return {
295
317
  data: state.status === "success" ? state.data : void 0,
296
318
  error: state.status === "error" ? state.error : void 0,
@@ -300,6 +322,27 @@ function useService(token, args) {
300
322
  refetch
301
323
  };
302
324
  }
325
+ // src/service/use-service.mts
326
+ /**
327
+ * Hook to load a service from the DI container, with its loading and error
328
+ * state. Resolves again when the instance is invalidated.
329
+ *
330
+ * @example
331
+ * ```tsx
332
+ * function UserCard() {
333
+ * const { data: users, error } = useService(UserService)
334
+ *
335
+ * if (error) return <p>{error.message}</p>
336
+ * if (!users) return <p>Loading…</p>
337
+ *
338
+ * return <UserList users={users} />
339
+ * }
340
+ * ```
341
+ */
342
+ const useService = function useService(token, args) {
343
+ const { state, refetch } = useResolvedService(token, args, { optional: false });
344
+ return serviceResult(state, refetch);
345
+ };
303
346
  // src/service/use-suspense-service.mts
304
347
  const cacheMap = /* @__PURE__ */ new WeakMap();
305
348
  function getCache(container, token) {
@@ -316,6 +359,33 @@ function getCache(container, token) {
316
359
  return cache;
317
360
  }
318
361
  /**
362
+ * The cache entry for `key`, created on first use. An instance the container
363
+ * already holds makes it resolved, so the first render does not suspend. The
364
+ * entry listens for the invalidation of that instance from the start: an
365
+ * effect would subscribe after the render, and miss one in between.
366
+ */
367
+ function getEntry(cache, key, container, token, args) {
368
+ let entry = cache.get(key);
369
+ if (!entry) {
370
+ const syncInstance = container.peek(token, args);
371
+ entry = {
372
+ promise: null,
373
+ result: syncInstance !== null ? syncInstance : void 0,
374
+ error: void 0,
375
+ status: syncInstance !== null ? "resolved" : "pending",
376
+ version: 0,
377
+ subscribers: /* @__PURE__ */ new Set(),
378
+ unsubscribe: void 0,
379
+ eviction: void 0,
380
+ release: void 0,
381
+ renders: 0
382
+ };
383
+ cache.set(key, entry);
384
+ if (syncInstance !== null) setupInvalidationSubscription(entry, container, token, args);
385
+ }
386
+ return entry;
387
+ }
388
+ /**
319
389
  * Sets up invalidation subscription for a cache entry if not already subscribed.
320
390
  * When the service is destroyed, clears the cache and notifies subscribers.
321
391
  */
@@ -329,94 +399,99 @@ function setupInvalidationSubscription(entry, container, token, args) {
329
399
  entry.subscribers.forEach((callback) => callback());
330
400
  });
331
401
  }
332
- function useSuspenseService(token, args) {
402
+ function fetchService(entry, container, token, args) {
403
+ entry.status = "pending";
404
+ entry.version++;
405
+ entry.promise = container.get(token, args).then((instance) => {
406
+ entry.result = instance;
407
+ entry.status = "resolved";
408
+ setupInvalidationSubscription(entry, container, token, args);
409
+ entry.subscribers.forEach((callback) => callback());
410
+ return instance;
411
+ }).catch((error) => {
412
+ entry.error = error;
413
+ entry.status = "rejected";
414
+ throw error;
415
+ });
416
+ }
417
+ /**
418
+ * Drops a rejected entry two timer turns after the last render that threw its
419
+ * error. Every render until then throws the error again: React renders a
420
+ * failed component a second time before it shows the error boundary, and when
421
+ * the first of those renders used up its time slice, the second one runs in a
422
+ * later task. That task is queued before the second timer is, so it still
423
+ * finds the entry; with one turn it found the cache empty and resolved the
424
+ * service again. The next render after that, such as the one of an error
425
+ * boundary reset, resolves the service again.
426
+ */
427
+ function evictAfterRender(cache, key, entry) {
428
+ clearTimeout(entry.eviction);
429
+ entry.eviction = setTimeout(() => {
430
+ entry.eviction = setTimeout(() => {
431
+ if (cache.get(key) === entry && entry.status === "rejected") {
432
+ cache.delete(key);
433
+ entry.unsubscribe?.();
434
+ }
435
+ }, 0);
436
+ }, 0);
437
+ }
438
+ /**
439
+ * Drops a resolved entry, and its invalidation listener, one timer turn after
440
+ * its last subscriber left, unless a component subscribed or rendered with it
441
+ * in the meantime. A component that shows the service later reads the instance
442
+ * from the container again.
443
+ */
444
+ function releaseWhenUnused(cache, key, entry) {
445
+ clearTimeout(entry.release);
446
+ const renders = entry.renders;
447
+ entry.release = setTimeout(() => {
448
+ if (cache.get(key) === entry && entry.status === "resolved" && entry.subscribers.size === 0 && entry.renders === renders) {
449
+ cache.delete(key);
450
+ entry.unsubscribe?.();
451
+ entry.unsubscribe = void 0;
452
+ }
453
+ }, 0);
454
+ }
455
+ /**
456
+ * Hook that returns a service from the DI container and suspends while it is
457
+ * resolved. A failed resolution is thrown to the nearest error boundary.
458
+ * Resolves again, suspending, when the instance is invalidated.
459
+ */
460
+ const useSuspenseService = function useSuspenseService(token, args) {
333
461
  const container = useContainer();
334
462
  const cache = getCache(container, token);
335
463
  const cacheKey = getArgsKey(args);
336
- const entryRef = useRef(null);
337
- if (!cache.has(cacheKey)) {
338
- const syncInstance = container.peek(token, args);
339
- const entry = {
340
- promise: null,
341
- result: syncInstance !== null ? syncInstance : void 0,
342
- error: void 0,
343
- status: syncInstance !== null ? "resolved" : "pending",
344
- version: 0,
345
- subscribers: /* @__PURE__ */ new Set(),
346
- unsubscribe: void 0
347
- };
348
- cache.set(cacheKey, entry);
349
- }
350
- const entry = cache.get(cacheKey);
351
- entryRef.current = entry;
352
- const fetchService = useCallback(() => {
353
- const currentEntry = entryRef.current;
354
- if (!currentEntry) return;
355
- currentEntry.status = "pending";
356
- currentEntry.version++;
357
- currentEntry.promise = container.get(token, args).then((instance) => {
358
- currentEntry.result = instance;
359
- currentEntry.status = "resolved";
360
- setupInvalidationSubscription(currentEntry, container, token, args);
361
- currentEntry.subscribers.forEach((callback) => callback());
362
- return instance;
363
- }).catch((error) => {
364
- currentEntry.error = error;
365
- currentEntry.status = "rejected";
366
- throw error;
367
- });
368
- return currentEntry.promise;
369
- }, [
370
- container,
371
- token,
372
- args
373
- ]);
464
+ const entry = getEntry(cache, cacheKey, container, token, args);
465
+ entry.renders++;
374
466
  const subscribe = useCallback((callback) => {
375
467
  entry.subscribers.add(callback);
376
468
  return () => {
377
469
  entry.subscribers.delete(callback);
470
+ if (entry.subscribers.size === 0) releaseWhenUnused(cache, cacheKey, entry);
378
471
  };
379
- }, [entry]);
472
+ }, [
473
+ cache,
474
+ cacheKey,
475
+ entry
476
+ ]);
380
477
  const getSnapshot = useCallback(() => {
381
478
  return `${entry.status}:${entry.version}`;
382
479
  }, [entry]);
383
480
  useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
384
- useEffect(() => {
385
- const currentEntry = entryRef.current;
386
- if (currentEntry && currentEntry.status === "resolved" && !currentEntry.unsubscribe) setupInvalidationSubscription(currentEntry, container, token, args);
387
- }, [
388
- container,
389
- token,
390
- args,
391
- entry
392
- ]);
393
- if (entry.status === "pending" && !entry.promise) fetchService();
481
+ if (entry.status === "pending" && !entry.promise) fetchService(entry, container, token, args);
394
482
  if (entry.status === "pending") throw entry.promise;
395
- if (entry.status === "rejected") throw entry.error;
483
+ if (entry.status === "rejected") {
484
+ evictAfterRender(cache, cacheKey, entry);
485
+ throw entry.error;
486
+ }
396
487
  return entry.result;
397
- }
488
+ };
398
489
  // src/service/use-optional-service.mts
399
- function optionalServiceReducer(state, action) {
400
- switch (action.type) {
401
- case "loading": return { status: "loading" };
402
- case "success": return {
403
- status: "success",
404
- data: action.data
405
- };
406
- case "not-found": return { status: "not-found" };
407
- case "error": return {
408
- status: "error",
409
- error: action.error
410
- };
411
- case "reset": return { status: "idle" };
412
- default: return state;
413
- }
414
- }
415
490
  /**
416
491
  * Hook to optionally load a service from the DI container.
417
492
  *
418
- * Unlike useService, this hook does NOT throw an error if the service is not registered.
419
- * Instead, it returns `isNotFound: true` when the service doesn't exist.
493
+ * Unlike useService, a token without a provider is not an error: the hook
494
+ * returns `isNotFound: true` instead.
420
495
  *
421
496
  * This is useful for:
422
497
  * - Optional dependencies that may or may not be configured
@@ -437,91 +512,13 @@ function optionalServiceReducer(state, action) {
437
512
  * }
438
513
  * ```
439
514
  */
440
- function useOptionalService(token, args) {
441
- const container = useContainer();
442
- const argsKey = getArgsKey(args);
443
- const stableArgs = useMemo(() => args, [argsKey]);
444
- const initialSyncRef = useRef(void 0);
445
- if (initialSyncRef.current === void 0) {
446
- let instance = null;
447
- try {
448
- instance = container.peek(token, args);
449
- } catch {}
450
- initialSyncRef.current = instance === null ? null : {
451
- container,
452
- token,
453
- argsKey,
454
- instance
455
- };
456
- }
457
- const initialState = initialSyncRef.current !== null ? {
458
- status: "success",
459
- data: initialSyncRef.current.instance
460
- } : { status: "idle" };
461
- const [state, dispatch] = useReducer(optionalServiceReducer, initialState);
462
- const fetchService = useCallback(async () => {
463
- dispatch({ type: "loading" });
464
- try {
465
- const instance = await container.get(token, stableArgs);
466
- dispatch({
467
- type: "success",
468
- data: instance
469
- });
470
- return true;
471
- } catch (error) {
472
- if (error instanceof DIError && error.code === DIErrorCode.ProviderNotFound && !container.isRegistered(token)) dispatch({ type: "not-found" });
473
- else dispatch({
474
- type: "error",
475
- error
476
- });
477
- return false;
478
- }
479
- }, [
480
- container,
481
- token,
482
- stableArgs
483
- ]);
484
- useEffect(() => {
485
- let unsubscribe;
486
- let isMounted = true;
487
- const subscribe = () => {
488
- if (unsubscribe || !isMounted) return;
489
- unsubscribe = container.onInvalidate(token, stableArgs, () => {
490
- dispatch({ type: "loading" });
491
- queueMicrotask(() => {
492
- if (isMounted) fetchService();
493
- });
494
- });
495
- };
496
- const initial = initialSyncRef.current;
497
- if (initial != null && initial.container === container && initial.token === token && initial.argsKey === argsKey) subscribe();
498
- else {
499
- initialSyncRef.current = null;
500
- fetchService().then((loaded) => {
501
- if (loaded) subscribe();
502
- });
503
- }
504
- return () => {
505
- isMounted = false;
506
- unsubscribe?.();
507
- };
508
- }, [
509
- fetchService,
510
- container,
511
- token,
512
- stableArgs,
513
- argsKey
514
- ]);
515
+ const useOptionalService = function useOptionalService(token, args) {
516
+ const { state, refetch } = useResolvedService(token, args, { optional: true });
515
517
  return {
516
- data: state.status === "success" ? state.data : void 0,
517
- error: state.status === "error" ? state.error : void 0,
518
- isLoading: state.status === "loading",
519
- isSuccess: state.status === "success",
520
- isNotFound: state.status === "not-found",
521
- isError: state.status === "error",
522
- refetch: fetchService
518
+ ...serviceResult(state, refetch),
519
+ isNotFound: state.status === "not-found"
523
520
  };
524
- }
521
+ };
525
522
  // src/service/use-invalidate-instance.mts
526
523
  /**
527
524
  * Hook that returns a function to invalidate a service instance directly.