@navios/di-react 1.0.0-alpha.3 → 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.
Files changed (60) hide show
  1. package/CHANGELOG.md +47 -1
  2. package/README.md +45 -665
  3. package/lib/index.cjs +573 -0
  4. package/lib/index.cjs.map +1 -0
  5. package/lib/index.d.cts +262 -0
  6. package/lib/index.d.cts.map +1 -0
  7. package/lib/index.d.mts +159 -140
  8. package/lib/index.d.mts.map +1 -1
  9. package/lib/index.mjs +371 -381
  10. package/lib/index.mjs.map +1 -1
  11. package/package.json +32 -18
  12. package/coverage/base.css +0 -224
  13. package/coverage/block-navigation.js +0 -87
  14. package/coverage/clover.xml +0 -270
  15. package/coverage/coverage-final.json +0 -10
  16. package/coverage/favicon.png +0 -0
  17. package/coverage/hooks/index.html +0 -191
  18. package/coverage/hooks/use-container.mts.html +0 -268
  19. package/coverage/hooks/use-invalidate.mts.html +0 -208
  20. package/coverage/hooks/use-optional-service.mts.html +0 -910
  21. package/coverage/hooks/use-scope.mts.html +0 -346
  22. package/coverage/hooks/use-service.mts.html +0 -760
  23. package/coverage/hooks/use-suspense-service.mts.html +0 -784
  24. package/coverage/index.html +0 -131
  25. package/coverage/prettify.css +0 -1
  26. package/coverage/prettify.js +0 -2
  27. package/coverage/providers/container-provider.mts.html +0 -139
  28. package/coverage/providers/context.mts.html +0 -130
  29. package/coverage/providers/index.html +0 -146
  30. package/coverage/providers/scope-provider.mts.html +0 -355
  31. package/coverage/sort-arrow-sprite.png +0 -0
  32. package/coverage/sorter.js +0 -210
  33. package/lib/index.d.ts +0 -243
  34. package/lib/index.d.ts.map +0 -1
  35. package/lib/index.js +0 -582
  36. package/lib/index.js.map +0 -1
  37. package/project.json +0 -61
  38. package/src/hooks/__tests__/use-container.spec.mts +0 -143
  39. package/src/hooks/__tests__/use-invalidate.spec.mts +0 -80
  40. package/src/hooks/__tests__/use-optional-service.spec.mts +0 -233
  41. package/src/hooks/__tests__/use-scope.spec.mts +0 -293
  42. package/src/hooks/__tests__/use-service.spec.mts +0 -212
  43. package/src/hooks/__tests__/use-suspense-service.spec.mts +0 -286
  44. package/src/hooks/index.mts +0 -14
  45. package/src/hooks/use-container.mts +0 -61
  46. package/src/hooks/use-invalidate.mts +0 -41
  47. package/src/hooks/use-optional-service.mts +0 -275
  48. package/src/hooks/use-scope.mts +0 -87
  49. package/src/hooks/use-service.mts +0 -225
  50. package/src/hooks/use-suspense-service.mts +0 -233
  51. package/src/index.mts +0 -8
  52. package/src/providers/__tests__/scope-provider.spec.mts +0 -366
  53. package/src/providers/container-provider.mts +0 -18
  54. package/src/providers/context.mts +0 -15
  55. package/src/providers/index.mts +0 -5
  56. package/src/providers/scope-provider.mts +0 -90
  57. package/src/types.mts +0 -21
  58. package/tsconfig.json +0 -13
  59. package/tsdown.config.mts +0 -14
  60. package/vitest.config.mts +0 -12
package/lib/index.cjs ADDED
@@ -0,0 +1,573 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let react = require("react");
3
+ let react_jsx_runtime = require("react/jsx-runtime");
4
+ let _navios_di = require("@navios/di");
5
+ // src/container/context.mts
6
+ /**
7
+ * Context for the root Container.
8
+ * This is set by ContainerProvider and provides the base container.
9
+ */
10
+ const ContainerContext = (0, react.createContext)(null);
11
+ /**
12
+ * Context for the current ScopedContainer (if inside a ScopeProvider).
13
+ * This allows nested components to access request-scoped services.
14
+ */
15
+ const ScopedContainerContext = (0, react.createContext)(null);
16
+ // src/container/container-provider.mts
17
+ function ContainerProvider({ container, children }) {
18
+ return (0, react_jsx_runtime.jsx)(ContainerContext.Provider, {
19
+ value: container,
20
+ children
21
+ });
22
+ }
23
+ // src/container/use-container.mts
24
+ /**
25
+ * Hook to get the current container (ScopedContainer if inside ScopeProvider, otherwise Container).
26
+ *
27
+ * This is the primary hook for accessing the DI container. It automatically
28
+ * returns the correct container based on context:
29
+ * - Inside a ScopeProvider: returns the ScopedContainer for request-scoped services
30
+ * - Outside a ScopeProvider: returns the root Container
31
+ *
32
+ * @returns The current container (ScopedContainer or Container)
33
+ */
34
+ function useContainer() {
35
+ const scopedContainer = (0, react.useContext)(ScopedContainerContext);
36
+ const container = (0, react.useContext)(ContainerContext);
37
+ if (scopedContainer) return scopedContainer;
38
+ if (!container) throw new Error("useContainer must be used within a ContainerProvider");
39
+ return container;
40
+ }
41
+ /**
42
+ * Hook to get the root Container, regardless of whether we're inside a ScopeProvider.
43
+ *
44
+ * Use this when you need access to the root container specifically,
45
+ * for example to create new request scopes programmatically.
46
+ *
47
+ * @returns The root Container
48
+ */
49
+ function useRootContainer() {
50
+ const container = (0, react.useContext)(ContainerContext);
51
+ if (!container) throw new Error("useRootContainer must be used within a ContainerProvider");
52
+ return container;
53
+ }
54
+ // src/scope/scope-provider.mts
55
+ /**
56
+ * ScopeProvider creates a new request scope for dependency injection.
57
+ *
58
+ * Services with `scope: 'Request'` will be instantiated once per ScopeProvider
59
+ * and shared among all components within that provider.
60
+ *
61
+ * This is useful for:
62
+ * - Table rows that need isolated state
63
+ * - Modal dialogs with their own service instances
64
+ * - Multi-tenant scenarios
65
+ * - Any case where you need isolated service instances
66
+ *
67
+ * @example
68
+ * ```tsx
69
+ * // Each row gets its own RowStateService instance
70
+ * {rows.map(row => (
71
+ * <ScopeProvider key={row.id} scopeId={row.id} metadata={{ rowData: row }}>
72
+ * <TableRow />
73
+ * </ScopeProvider>
74
+ * ))}
75
+ * ```
76
+ */
77
+ function ScopeProvider({ scopeId, metadata, children }) {
78
+ const container = (0, react.useContext)(ContainerContext);
79
+ if (!container) throw new Error("ScopeProvider must be used within a ContainerProvider");
80
+ const generatedId = (0, react.useId)();
81
+ const effectiveScopeId = scopeId ?? generatedId;
82
+ const scopedContainerRef = (0, react.useRef)(null);
83
+ const isMountedRef = (0, react.useRef)(false);
84
+ const isDisposedRef = (0, react.useRef)(false);
85
+ const [, rerender] = (0, react.useReducer)((count) => count + 1, 0);
86
+ const createScope = () => container.createScope({
87
+ ...metadata,
88
+ scopeId: effectiveScopeId
89
+ });
90
+ const createScopeRef = (0, react.useRef)(createScope);
91
+ createScopeRef.current = createScope;
92
+ if (!scopedContainerRef.current) scopedContainerRef.current = createScope();
93
+ (0, react.useEffect)(() => {
94
+ isMountedRef.current = true;
95
+ if (isDisposedRef.current) {
96
+ isDisposedRef.current = false;
97
+ scopedContainerRef.current = createScopeRef.current();
98
+ rerender();
99
+ }
100
+ return () => {
101
+ isMountedRef.current = false;
102
+ queueMicrotask(() => {
103
+ if (isMountedRef.current || isDisposedRef.current) return;
104
+ isDisposedRef.current = true;
105
+ scopedContainerRef.current?.dispose();
106
+ });
107
+ };
108
+ }, []);
109
+ return (0, react_jsx_runtime.jsx)(ScopedContainerContext.Provider, {
110
+ value: scopedContainerRef.current,
111
+ children
112
+ });
113
+ }
114
+ // src/scope/use-scope.mts
115
+ /**
116
+ * Hook to get the current scope ID.
117
+ * Returns null if not inside a ScopeProvider.
118
+ */
119
+ function useScope() {
120
+ return (0, react.useContext)(ScopedContainerContext)?.getMetadata("scopeId") ?? null;
121
+ }
122
+ /**
123
+ * Hook to get the current scope ID, throwing if not inside a ScopeProvider.
124
+ * Use this when your component requires a scope to function correctly.
125
+ */
126
+ function useScopeOrThrow() {
127
+ const scopeId = useScope();
128
+ if (scopeId === null) throw new Error("useScopeOrThrow must be used within a ScopeProvider. Wrap your component tree with <ScopeProvider> to create a request scope.");
129
+ return scopeId;
130
+ }
131
+ /**
132
+ * Hook to get the current ScopedContainer.
133
+ * Returns null if not inside a ScopeProvider.
134
+ *
135
+ * Use this to access scope metadata or other ScopedContainer methods.
136
+ *
137
+ * @example
138
+ * ```tsx
139
+ * function TableRow() {
140
+ * const scope = useScopedContainer()
141
+ * const rowData = scope?.getMetadata('rowData')
142
+ * // ...
143
+ * }
144
+ * ```
145
+ */
146
+ function useScopedContainer() {
147
+ return (0, react.useContext)(ScopedContainerContext);
148
+ }
149
+ /**
150
+ * Hook to get the current ScopedContainer, throwing if not inside a ScopeProvider.
151
+ * Use this when your component requires a scope to function correctly.
152
+ */
153
+ function useScopedContainerOrThrow() {
154
+ const scopedContainer = useScopedContainer();
155
+ if (scopedContainer === null) throw new Error("useScopedContainerOrThrow must be used within a ScopeProvider. Wrap your component tree with <ScopeProvider> to create a request scope.");
156
+ return scopedContainer;
157
+ }
158
+ /**
159
+ * Hook to get metadata from the current scope.
160
+ * Returns undefined if not inside a ScopeProvider or if the key doesn't exist.
161
+ *
162
+ * @example
163
+ * ```tsx
164
+ * // In parent component:
165
+ * <ScopeProvider metadata={{ userId: '123', theme: 'dark' }}>
166
+ * <ChildComponent />
167
+ * </ScopeProvider>
168
+ *
169
+ * // In child component:
170
+ * function ChildComponent() {
171
+ * const userId = useScopeMetadata<string>('userId')
172
+ * const theme = useScopeMetadata<'light' | 'dark'>('theme')
173
+ * // ...
174
+ * }
175
+ * ```
176
+ */
177
+ function useScopeMetadata(key) {
178
+ return (0, react.useContext)(ScopedContainerContext)?.getMetadata(key);
179
+ }
180
+ // src/service/args-key.mts
181
+ let nextId = 0;
182
+ const objectIds = /* @__PURE__ */ new WeakMap();
183
+ /** What the container compares by value, and JSON would leave out. */
184
+ function replacer(_key, value) {
185
+ if (typeof value === "bigint" || value instanceof RegExp) return { [typeof value]: String(value) };
186
+ if (value instanceof Map || value instanceof Set) return { [value.constructor.name]: Array.from(value) };
187
+ return value;
188
+ }
189
+ /**
190
+ * Key that identifies the args of a hook call. Args that serialize to the same
191
+ * JSON share a key, so an object literal written in the call, or a function in
192
+ * it, does not count as a change on every render.
193
+ *
194
+ * Args JSON cannot serialize, which contain themselves, are keyed by identity.
195
+ */
196
+ function getArgsKey(args) {
197
+ try {
198
+ return JSON.stringify(args, replacer) ?? "";
199
+ } catch {
200
+ const object = args;
201
+ let id = objectIds.get(object);
202
+ if (id === void 0) {
203
+ id = ++nextId;
204
+ objectIds.set(object, id);
205
+ }
206
+ return `#${id}`;
207
+ }
208
+ }
209
+ // src/service/use-resolved-service.mts
210
+ const LOADING = { status: "loading" };
211
+ const NOT_FOUND = { status: "not-found" };
212
+ /** Whether `error` says that `token` itself has no provider. */
213
+ function isMissingProvider(container, token, error) {
214
+ return error instanceof _navios_di.DIError && error.code === _navios_di.DIErrorCode.ProviderNotFound && !container.isRegistered(token);
215
+ }
216
+ /** What the container holds for `token` and `args` now, or `null`. */
217
+ function peekInstance(container, token, args) {
218
+ try {
219
+ return container.peek(token, args);
220
+ } catch {
221
+ return null;
222
+ }
223
+ }
224
+ /**
225
+ * Resolution behind `useService` and `useOptionalService`. With `optional`,
226
+ * a token without a provider ends in `not-found` instead of `error`.
227
+ */
228
+ function useResolvedService(token, args, { optional }) {
229
+ const container = useContainer();
230
+ const argsKey = getArgsKey(args);
231
+ const stableArgs = (0, react.useMemo)(() => args, [argsKey]);
232
+ const initialSyncRef = (0, react.useRef)(void 0);
233
+ if (initialSyncRef.current === void 0) {
234
+ const instance = peekInstance(container, token, args);
235
+ initialSyncRef.current = instance === null ? null : {
236
+ container,
237
+ token,
238
+ argsKey,
239
+ instance
240
+ };
241
+ }
242
+ const [state, setState] = (0, react.useState)(() => initialSyncRef.current ? {
243
+ status: "success",
244
+ data: initialSyncRef.current.instance
245
+ } : LOADING);
246
+ const [refetchCount, setRefetchCount] = (0, react.useState)(0);
247
+ (0, react.useEffect)(() => {
248
+ let isCurrent = true;
249
+ let unsubscribe;
250
+ let latest = 0;
251
+ const subscribe = () => {
252
+ if (unsubscribe) return;
253
+ unsubscribe = container.onInvalidate(token, stableArgs, () => {
254
+ if (!isCurrent) return;
255
+ latest++;
256
+ setState(LOADING);
257
+ queueMicrotask(() => {
258
+ if (isCurrent) resolve();
259
+ });
260
+ });
261
+ };
262
+ const resolve = async () => {
263
+ const run = ++latest;
264
+ try {
265
+ subscribe();
266
+ } catch {}
267
+ try {
268
+ const instance = await container.get(token, stableArgs);
269
+ if (!isCurrent || run !== latest) return;
270
+ setState({
271
+ status: "success",
272
+ data: instance
273
+ });
274
+ subscribe();
275
+ } catch (error) {
276
+ if (!isCurrent || run !== latest) return;
277
+ setState(optional && isMissingProvider(container, token, error) ? NOT_FOUND : {
278
+ status: "error",
279
+ error
280
+ });
281
+ }
282
+ };
283
+ const initial = initialSyncRef.current;
284
+ if (initial && initial.container === container && initial.token === token && initial.argsKey === argsKey && refetchCount === 0) {
285
+ subscribe();
286
+ if (peekInstance(container, token, stableArgs) !== initial.instance) {
287
+ initialSyncRef.current = null;
288
+ setState(LOADING);
289
+ resolve();
290
+ }
291
+ } else {
292
+ initialSyncRef.current = null;
293
+ setState(LOADING);
294
+ resolve();
295
+ }
296
+ return () => {
297
+ isCurrent = false;
298
+ unsubscribe?.();
299
+ };
300
+ }, [
301
+ container,
302
+ token,
303
+ stableArgs,
304
+ argsKey,
305
+ refetchCount,
306
+ optional
307
+ ]);
308
+ return {
309
+ state,
310
+ refetch: (0, react.useCallback)(() => {
311
+ setRefetchCount((count) => count + 1);
312
+ }, [])
313
+ };
314
+ }
315
+ /** The result object of `useService` for a state. */
316
+ function serviceResult(state, refetch) {
317
+ return {
318
+ data: state.status === "success" ? state.data : void 0,
319
+ error: state.status === "error" ? state.error : void 0,
320
+ isLoading: state.status === "loading",
321
+ isSuccess: state.status === "success",
322
+ isError: state.status === "error",
323
+ refetch
324
+ };
325
+ }
326
+ // src/service/use-service.mts
327
+ /**
328
+ * Hook to load a service from the DI container, with its loading and error
329
+ * state. Resolves again when the instance is invalidated.
330
+ *
331
+ * @example
332
+ * ```tsx
333
+ * function UserCard() {
334
+ * const { data: users, error } = useService(UserService)
335
+ *
336
+ * if (error) return <p>{error.message}</p>
337
+ * if (!users) return <p>Loading…</p>
338
+ *
339
+ * return <UserList users={users} />
340
+ * }
341
+ * ```
342
+ */
343
+ const useService = function useService(token, args) {
344
+ const { state, refetch } = useResolvedService(token, args, { optional: false });
345
+ return serviceResult(state, refetch);
346
+ };
347
+ // src/service/use-suspense-service.mts
348
+ const cacheMap = /* @__PURE__ */ new WeakMap();
349
+ function getCache(container, token) {
350
+ let byToken = cacheMap.get(container);
351
+ if (!byToken) {
352
+ byToken = /* @__PURE__ */ new WeakMap();
353
+ cacheMap.set(container, byToken);
354
+ }
355
+ let cache = byToken.get(token);
356
+ if (!cache) {
357
+ cache = /* @__PURE__ */ new Map();
358
+ byToken.set(token, cache);
359
+ }
360
+ return cache;
361
+ }
362
+ /**
363
+ * The cache entry for `key`, created on first use. An instance the container
364
+ * already holds makes it resolved, so the first render does not suspend. The
365
+ * entry listens for the invalidation of that instance from the start: an
366
+ * effect would subscribe after the render, and miss one in between.
367
+ */
368
+ function getEntry(cache, key, container, token, args) {
369
+ let entry = cache.get(key);
370
+ if (!entry) {
371
+ const syncInstance = container.peek(token, args);
372
+ entry = {
373
+ promise: null,
374
+ result: syncInstance !== null ? syncInstance : void 0,
375
+ error: void 0,
376
+ status: syncInstance !== null ? "resolved" : "pending",
377
+ version: 0,
378
+ subscribers: /* @__PURE__ */ new Set(),
379
+ unsubscribe: void 0,
380
+ eviction: void 0,
381
+ release: void 0,
382
+ renders: 0
383
+ };
384
+ cache.set(key, entry);
385
+ if (syncInstance !== null) setupInvalidationSubscription(entry, container, token, args);
386
+ }
387
+ return entry;
388
+ }
389
+ /**
390
+ * Sets up invalidation subscription for a cache entry if not already subscribed.
391
+ * When the service is destroyed, clears the cache and notifies subscribers.
392
+ */
393
+ function setupInvalidationSubscription(entry, container, token, args) {
394
+ if (entry.unsubscribe) return;
395
+ entry.unsubscribe = container.onInvalidate(token, args, () => {
396
+ entry.result = void 0;
397
+ entry.error = void 0;
398
+ entry.status = "pending";
399
+ entry.promise = null;
400
+ entry.subscribers.forEach((callback) => callback());
401
+ });
402
+ }
403
+ function fetchService(entry, container, token, args) {
404
+ entry.status = "pending";
405
+ entry.version++;
406
+ entry.promise = container.get(token, args).then((instance) => {
407
+ entry.result = instance;
408
+ entry.status = "resolved";
409
+ setupInvalidationSubscription(entry, container, token, args);
410
+ entry.subscribers.forEach((callback) => callback());
411
+ return instance;
412
+ }).catch((error) => {
413
+ entry.error = error;
414
+ entry.status = "rejected";
415
+ throw error;
416
+ });
417
+ }
418
+ /**
419
+ * Drops a rejected entry two timer turns after the last render that threw its
420
+ * error. Every render until then throws the error again: React renders a
421
+ * failed component a second time before it shows the error boundary, and when
422
+ * the first of those renders used up its time slice, the second one runs in a
423
+ * later task. That task is queued before the second timer is, so it still
424
+ * finds the entry; with one turn it found the cache empty and resolved the
425
+ * service again. The next render after that, such as the one of an error
426
+ * boundary reset, resolves the service again.
427
+ */
428
+ function evictAfterRender(cache, key, entry) {
429
+ clearTimeout(entry.eviction);
430
+ entry.eviction = setTimeout(() => {
431
+ entry.eviction = setTimeout(() => {
432
+ if (cache.get(key) === entry && entry.status === "rejected") {
433
+ cache.delete(key);
434
+ entry.unsubscribe?.();
435
+ }
436
+ }, 0);
437
+ }, 0);
438
+ }
439
+ /**
440
+ * Drops a resolved entry, and its invalidation listener, one timer turn after
441
+ * its last subscriber left, unless a component subscribed or rendered with it
442
+ * in the meantime. A component that shows the service later reads the instance
443
+ * from the container again.
444
+ */
445
+ function releaseWhenUnused(cache, key, entry) {
446
+ clearTimeout(entry.release);
447
+ const renders = entry.renders;
448
+ entry.release = setTimeout(() => {
449
+ if (cache.get(key) === entry && entry.status === "resolved" && entry.subscribers.size === 0 && entry.renders === renders) {
450
+ cache.delete(key);
451
+ entry.unsubscribe?.();
452
+ entry.unsubscribe = void 0;
453
+ }
454
+ }, 0);
455
+ }
456
+ /**
457
+ * Hook that returns a service from the DI container and suspends while it is
458
+ * resolved. A failed resolution is thrown to the nearest error boundary.
459
+ * Resolves again, suspending, when the instance is invalidated.
460
+ */
461
+ const useSuspenseService = function useSuspenseService(token, args) {
462
+ const container = useContainer();
463
+ const cache = getCache(container, token);
464
+ const cacheKey = getArgsKey(args);
465
+ const entry = getEntry(cache, cacheKey, container, token, args);
466
+ entry.renders++;
467
+ const subscribe = (0, react.useCallback)((callback) => {
468
+ entry.subscribers.add(callback);
469
+ return () => {
470
+ entry.subscribers.delete(callback);
471
+ if (entry.subscribers.size === 0) releaseWhenUnused(cache, cacheKey, entry);
472
+ };
473
+ }, [
474
+ cache,
475
+ cacheKey,
476
+ entry
477
+ ]);
478
+ const getSnapshot = (0, react.useCallback)(() => {
479
+ return `${entry.status}:${entry.version}`;
480
+ }, [entry]);
481
+ (0, react.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
482
+ if (entry.status === "pending" && !entry.promise) fetchService(entry, container, token, args);
483
+ if (entry.status === "pending") throw entry.promise;
484
+ if (entry.status === "rejected") {
485
+ evictAfterRender(cache, cacheKey, entry);
486
+ throw entry.error;
487
+ }
488
+ return entry.result;
489
+ };
490
+ // src/service/use-optional-service.mts
491
+ /**
492
+ * Hook to optionally load a service from the DI container.
493
+ *
494
+ * Unlike useService, a token without a provider is not an error: the hook
495
+ * returns `isNotFound: true` instead.
496
+ *
497
+ * This is useful for:
498
+ * - Optional dependencies that may or may not be configured
499
+ * - Feature flags where a service might not be available
500
+ * - Plugins or extensions that are conditionally registered
501
+ *
502
+ * @example
503
+ * ```tsx
504
+ * function Analytics() {
505
+ * const { data: analytics, isNotFound } = useOptionalService(AnalyticsService)
506
+ *
507
+ * if (isNotFound) {
508
+ * // Analytics service not configured, skip tracking
509
+ * return null
510
+ * }
511
+ *
512
+ * return <AnalyticsTracker service={analytics} />
513
+ * }
514
+ * ```
515
+ */
516
+ const useOptionalService = function useOptionalService(token, args) {
517
+ const { state, refetch } = useResolvedService(token, args, { optional: true });
518
+ return {
519
+ ...serviceResult(state, refetch),
520
+ isNotFound: state.status === "not-found"
521
+ };
522
+ };
523
+ // src/service/use-invalidate-instance.mts
524
+ /**
525
+ * Hook that returns a function to invalidate a service instance directly.
526
+ *
527
+ * This is useful when you have the service instance and want to invalidate it
528
+ * without knowing its token.
529
+ *
530
+ * @example
531
+ * ```tsx
532
+ * function UserProfile() {
533
+ * const { data: user } = useService(UserService)
534
+ * const invalidateInstance = useInvalidateInstance()
535
+ *
536
+ * const handleRefresh = () => {
537
+ * if (user) {
538
+ * invalidateInstance(user)
539
+ * }
540
+ * }
541
+ *
542
+ * return (
543
+ * <div>
544
+ * <span>{user?.name}</span>
545
+ * <button onClick={handleRefresh}>Refresh</button>
546
+ * </div>
547
+ * )
548
+ * }
549
+ * ```
550
+ */
551
+ function useInvalidateInstance() {
552
+ const container = useContainer();
553
+ return (0, react.useCallback)(async (instance) => {
554
+ await container.invalidate(instance);
555
+ }, [container]);
556
+ }
557
+ exports.ContainerContext = ContainerContext;
558
+ exports.ContainerProvider = ContainerProvider;
559
+ exports.ScopeProvider = ScopeProvider;
560
+ exports.ScopedContainerContext = ScopedContainerContext;
561
+ exports.useContainer = useContainer;
562
+ exports.useInvalidateInstance = useInvalidateInstance;
563
+ exports.useOptionalService = useOptionalService;
564
+ exports.useRootContainer = useRootContainer;
565
+ exports.useScope = useScope;
566
+ exports.useScopeMetadata = useScopeMetadata;
567
+ exports.useScopeOrThrow = useScopeOrThrow;
568
+ exports.useScopedContainer = useScopedContainer;
569
+ exports.useScopedContainerOrThrow = useScopedContainerOrThrow;
570
+ exports.useService = useService;
571
+ exports.useSuspenseService = useSuspenseService;
572
+
573
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["createContext","jsx","useContext","useContext","useId","useRef","useReducer","useEffect","jsx","useContext","DIError","DIErrorCode","useMemo","useRef","useState","useEffect","useCallback","useCallback","useSyncExternalStore","useCallback"],"sources":["../src/container/context.mts","../src/container/container-provider.mts","../src/container/use-container.mts","../src/scope/scope-provider.mts","../src/scope/use-scope.mts","../src/service/args-key.mts","../src/service/use-resolved-service.mts","../src/service/use-service.mts","../src/service/use-suspense-service.mts","../src/service/use-optional-service.mts","../src/service/use-invalidate-instance.mts"],"sourcesContent":["import { createContext } from 'react'\n\nimport type { Container, ScopedContainer } from '@navios/di'\n\n/**\n * Context for the root Container.\n * This is set by ContainerProvider and provides the base container.\n */\nexport const ContainerContext = createContext<Container | null>(null)\n\n/**\n * Context for the current ScopedContainer (if inside a ScopeProvider).\n * This allows nested components to access request-scoped services.\n */\nexport const ScopedContainerContext = createContext<ScopedContainer | null>(null)\n","import { jsx } from 'react/jsx-runtime'\n\nimport type { Container } from '@navios/di'\nimport type { ReactNode } from 'react'\n\nimport { ContainerContext } from './context.mjs'\n\nexport interface ContainerProviderProps {\n container: Container\n children: ReactNode\n}\n\nexport function ContainerProvider({ container, children }: ContainerProviderProps) {\n return jsx(ContainerContext.Provider, { value: container, children })\n}\n","import { useContext } from 'react'\n\nimport type { Container, ScopedContainer } from '@navios/di'\n\nimport { ContainerContext, ScopedContainerContext } from './context.mjs'\n\n/**\n * Hook to get the current container (ScopedContainer if inside ScopeProvider, otherwise Container).\n *\n * This is the primary hook for accessing the DI container. It automatically\n * returns the correct container based on context:\n * - Inside a ScopeProvider: returns the ScopedContainer for request-scoped services\n * - Outside a ScopeProvider: returns the root Container\n *\n * @returns The current container (ScopedContainer or Container)\n */\nexport function useContainer(): Container | ScopedContainer {\n const scopedContainer = useContext(ScopedContainerContext)\n const container = useContext(ContainerContext)\n\n // Prefer scoped container if available (we're inside a ScopeProvider)\n if (scopedContainer) {\n return scopedContainer\n }\n\n if (!container) {\n throw new Error('useContainer must be used within a ContainerProvider')\n }\n\n return container\n}\n\n/**\n * Hook to get the root Container, regardless of whether we're inside a ScopeProvider.\n *\n * Use this when you need access to the root container specifically,\n * for example to create new request scopes programmatically.\n *\n * @returns The root Container\n */\nexport function useRootContainer(): Container {\n const container = useContext(ContainerContext)\n\n if (!container) {\n throw new Error('useRootContainer must be used within a ContainerProvider')\n }\n\n return container\n}\n","import { useContext, useEffect, useId, useReducer, useRef } from 'react'\nimport { jsx } from 'react/jsx-runtime'\n\nimport type { ScopedContainer } from '@navios/di'\nimport type { ReactNode } from 'react'\n\nimport { ContainerContext, ScopedContainerContext } from '../container/context.mjs'\n\nexport interface ScopeProviderProps {\n /**\n * Optional explicit scope ID. If not provided, a unique ID will be generated.\n * Useful when you need to reference the scope externally.\n */\n scopeId?: string\n /**\n * Optional metadata to attach to the scope.\n * The key `scopeId` is reserved: it always holds the effective scope ID.\n * Can be used to pass data like user info, request headers, etc.\n */\n metadata?: Record<string, unknown>\n children: ReactNode\n}\n\n/**\n * ScopeProvider creates a new request scope for dependency injection.\n *\n * Services with `scope: 'Request'` will be instantiated once per ScopeProvider\n * and shared among all components within that provider.\n *\n * This is useful for:\n * - Table rows that need isolated state\n * - Modal dialogs with their own service instances\n * - Multi-tenant scenarios\n * - Any case where you need isolated service instances\n *\n * @example\n * ```tsx\n * // Each row gets its own RowStateService instance\n * {rows.map(row => (\n * <ScopeProvider key={row.id} scopeId={row.id} metadata={{ rowData: row }}>\n * <TableRow />\n * </ScopeProvider>\n * ))}\n * ```\n */\nexport function ScopeProvider({ scopeId, metadata, children }: ScopeProviderProps) {\n const container = useContext(ContainerContext)\n if (!container) {\n throw new Error('ScopeProvider must be used within a ContainerProvider')\n }\n\n const generatedId = useId()\n const effectiveScopeId = scopeId ?? generatedId\n const scopedContainerRef = useRef<ScopedContainer | null>(null)\n // True between an effect setup and its cleanup.\n const isMountedRef = useRef(false)\n // True once the scope in the ref has been disposed.\n const isDisposedRef = useRef(false)\n const [, rerender] = useReducer((count: number) => count + 1, 0)\n\n // DI scopes have no ids, so the effective scope id lives in the scope's\n // metadata under `scopeId`.\n const createScope = () => container.createScope({ ...metadata, scopeId: effectiveScopeId })\n const createScopeRef = useRef(createScope)\n createScopeRef.current = createScope\n\n // Create the ScopedContainer once per mounted provider.\n // The ref keeps it stable across re-renders.\n if (!scopedContainerRef.current) {\n scopedContainerRef.current = createScope()\n }\n\n useEffect(() => {\n isMountedRef.current = true\n // React re-ran the effect after the scope was disposed (an `<Activity>`\n // shown again): the old scope is gone for good, so start a new one.\n if (isDisposedRef.current) {\n isDisposedRef.current = false\n scopedContainerRef.current = createScopeRef.current()\n rerender()\n }\n return () => {\n isMountedRef.current = false\n // Disposal waits one microtask. StrictMode's simulated unmount is\n // followed by a re-mount in the same commit, which sets the flag again\n // and keeps the scope; a real unmount leaves it unset.\n queueMicrotask(() => {\n if (isMountedRef.current || isDisposedRef.current) {\n return\n }\n isDisposedRef.current = true\n void scopedContainerRef.current?.dispose()\n })\n }\n }, [])\n\n return jsx(ScopedContainerContext.Provider, {\n value: scopedContainerRef.current,\n children,\n })\n}\n","import { useContext } from 'react'\n\nimport type { ScopedContainer } from '@navios/di'\n\nimport { ScopedContainerContext } from '../container/context.mjs'\n\n/**\n * Hook to get the current scope ID.\n * Returns null if not inside a ScopeProvider.\n */\nexport function useScope(): string | null {\n const scopedContainer = useContext(ScopedContainerContext)\n return (scopedContainer?.getMetadata('scopeId') as string | undefined) ?? null\n}\n\n/**\n * Hook to get the current scope ID, throwing if not inside a ScopeProvider.\n * Use this when your component requires a scope to function correctly.\n */\nexport function useScopeOrThrow(): string {\n const scopeId = useScope()\n if (scopeId === null) {\n throw new Error(\n 'useScopeOrThrow must be used within a ScopeProvider. ' +\n 'Wrap your component tree with <ScopeProvider> to create a request scope.',\n )\n }\n return scopeId\n}\n\n/**\n * Hook to get the current ScopedContainer.\n * Returns null if not inside a ScopeProvider.\n *\n * Use this to access scope metadata or other ScopedContainer methods.\n *\n * @example\n * ```tsx\n * function TableRow() {\n * const scope = useScopedContainer()\n * const rowData = scope?.getMetadata('rowData')\n * // ...\n * }\n * ```\n */\nexport function useScopedContainer(): ScopedContainer | null {\n return useContext(ScopedContainerContext)\n}\n\n/**\n * Hook to get the current ScopedContainer, throwing if not inside a ScopeProvider.\n * Use this when your component requires a scope to function correctly.\n */\nexport function useScopedContainerOrThrow(): ScopedContainer {\n const scopedContainer = useScopedContainer()\n if (scopedContainer === null) {\n throw new Error(\n 'useScopedContainerOrThrow must be used within a ScopeProvider. ' +\n 'Wrap your component tree with <ScopeProvider> to create a request scope.',\n )\n }\n return scopedContainer\n}\n\n/**\n * Hook to get metadata from the current scope.\n * Returns undefined if not inside a ScopeProvider or if the key doesn't exist.\n *\n * @example\n * ```tsx\n * // In parent component:\n * <ScopeProvider metadata={{ userId: '123', theme: 'dark' }}>\n * <ChildComponent />\n * </ScopeProvider>\n *\n * // In child component:\n * function ChildComponent() {\n * const userId = useScopeMetadata<string>('userId')\n * const theme = useScopeMetadata<'light' | 'dark'>('theme')\n * // ...\n * }\n * ```\n */\nexport function useScopeMetadata<T = unknown>(key: string): T | undefined {\n const scopedContainer = useContext(ScopedContainerContext)\n return scopedContainer?.getMetadata(key) as T | undefined\n}\n","let nextId = 0\nconst objectIds = new WeakMap<object, number>()\n\n/** What the container compares by value, and JSON would leave out. */\nfunction replacer(_key: string, value: unknown): unknown {\n if (typeof value === 'bigint' || value instanceof RegExp) {\n return { [typeof value]: String(value) }\n }\n if (value instanceof Map || value instanceof Set) {\n return { [value.constructor.name]: Array.from(value as Iterable<unknown>) }\n }\n return value\n}\n\n/**\n * Key that identifies the args of a hook call. Args that serialize to the same\n * JSON share a key, so an object literal written in the call, or a function in\n * it, does not count as a change on every render.\n *\n * Args JSON cannot serialize, which contain themselves, are keyed by identity.\n */\nexport function getArgsKey(args: unknown): string {\n try {\n return JSON.stringify(args, replacer) ?? ''\n } catch {\n const object = args as object\n let id = objectIds.get(object)\n if (id === undefined) {\n id = ++nextId\n objectIds.set(object, id)\n }\n return `#${id}`\n }\n}\n","import { DIError, DIErrorCode } from '@navios/di'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\n\nimport type { AnyInjectableType, Container, InjectionToken, ScopedContainer } from '@navios/di'\n\nimport { useContainer } from '../container/use-container.mjs'\n\nimport { getArgsKey } from './args-key.mjs'\n\nimport type { AnyServiceToken, UseServiceResult } from './types.mjs'\n\nexport type ResolvedServiceState<T> =\n | { status: 'loading' }\n | { status: 'success'; data: T }\n | { status: 'not-found' }\n | { status: 'error'; error: Error }\n\n// One object each, so setting a state the hook is already in does not render.\nconst LOADING: ResolvedServiceState<never> = { status: 'loading' }\nconst NOT_FOUND: ResolvedServiceState<never> = { status: 'not-found' }\n\n/**\n * The instance read synchronously during the first render, with the\n * container, token and args it was read for.\n */\ninterface InitialSync {\n container: object\n token: object\n argsKey: string\n instance: unknown\n}\n\ninterface ResolvedService<T> {\n state: ResolvedServiceState<T>\n refetch: () => void\n}\n\n/** Whether `error` says that `token` itself has no provider. */\nfunction isMissingProvider(\n container: Container | ScopedContainer,\n token: AnyServiceToken,\n error: unknown,\n): boolean {\n return (\n error instanceof DIError &&\n error.code === DIErrorCode.ProviderNotFound &&\n // It may be something the service depends on.\n !container.isRegistered(token)\n )\n}\n\n/** What the container holds for `token` and `args` now, or `null`. */\nfunction peekInstance(\n container: Container | ScopedContainer,\n token: AnyServiceToken,\n args: unknown,\n): unknown {\n try {\n return container.peek(token as InjectionToken<any, any>, args)\n } catch {\n // A token the container cannot read, an alias cycle or args that contain\n // themselves. The resolution in the effect reports the error.\n return null\n }\n}\n\n/**\n * Resolution behind `useService` and `useOptionalService`. With `optional`,\n * a token without a provider ends in `not-found` instead of `error`.\n */\nexport function useResolvedService(\n token: AnyServiceToken,\n args: unknown,\n { optional }: { optional: boolean },\n): ResolvedService<any> {\n // useContainer returns ScopedContainer if inside ScopeProvider, otherwise Container\n // This automatically handles request-scoped services correctly\n const container = useContainer()\n\n // Args that serialize the same are the same args: an object literal in the\n // call must not restart the hook on every render.\n const argsKey = getArgsKey(args)\n // oxlint-disable-next-line react-hooks/exhaustive-deps\n const stableArgs = useMemo(() => args, [argsKey])\n\n // An instance the container already holds is returned by the first render,\n // without a loading state. The ref remembers what it was read for, so the\n // shortcut is only taken for that container, token and args.\n const initialSyncRef = useRef<InitialSync | null | undefined>(undefined)\n\n if (initialSyncRef.current === undefined) {\n const instance = peekInstance(container, token, args)\n initialSyncRef.current = instance === null ? null : { container, token, argsKey, instance }\n }\n\n const [state, setState] = useState<ResolvedServiceState<any>>(() =>\n initialSyncRef.current ? { status: 'success', data: initialSyncRef.current.instance } : LOADING,\n )\n const [refetchCount, setRefetchCount] = useState(0)\n\n useEffect(() => {\n // False once the container, token or args change, refetch is called or\n // the component unmounts: a resolution started by this run is then stale.\n let isCurrent = true\n let unsubscribe: (() => void) | undefined\n // The resolution whose result counts: the one started last, unless the\n // instance was invalidated since.\n let latest = 0\n\n // The container routes the listener to the store that owns the instance\n // (the root store for singletons, the scope's store for request-scoped).\n const subscribe = () => {\n if (unsubscribe) return\n unsubscribe = container.onInvalidate(token, stableArgs, () => {\n if (!isCurrent) return\n // What a resolution in flight is about to return may be the instance\n // that is gone.\n latest++\n setState(LOADING)\n // Listeners run once the invalidation has finished, so resolving here\n // builds the service once. The microtask only keeps the resolution out\n // of the container's notification loop.\n queueMicrotask(() => {\n if (isCurrent) {\n void resolve()\n }\n })\n })\n }\n\n const resolve = async () => {\n const run = ++latest\n try {\n // Before the instance is asked for: an invalidation between its\n // resolution and a subscription made afterwards would be missed.\n subscribe()\n } catch {\n // The resolution reports what is wrong with the token.\n }\n try {\n const instance = await container.get(\n // @ts-expect-error - token is valid\n token as AnyInjectableType,\n stableArgs as any,\n )\n if (!isCurrent || run !== latest) return\n setState({ status: 'success', data: instance })\n subscribe()\n } catch (error) {\n if (!isCurrent || run !== latest) return\n setState(\n optional && isMissingProvider(container, token, error)\n ? NOT_FOUND\n : { status: 'error', error: error as Error },\n )\n }\n }\n\n // If the instance read during the first render is still the one asked\n // for, just set up the subscription. Otherwise, resolve. So too when it\n // was destroyed between that render and this effect, which no listener\n // was there to see.\n const initial = initialSyncRef.current\n if (\n initial &&\n initial.container === container &&\n initial.token === token &&\n initial.argsKey === argsKey &&\n refetchCount === 0\n ) {\n subscribe()\n if (peekInstance(container, token, stableArgs) !== initial.instance) {\n initialSyncRef.current = null\n setState(LOADING)\n void resolve()\n }\n } else {\n initialSyncRef.current = null\n setState(LOADING)\n void resolve()\n }\n\n return () => {\n isCurrent = false\n unsubscribe?.()\n }\n }, [container, token, stableArgs, argsKey, refetchCount, optional])\n\n const refetch = useCallback(() => {\n setRefetchCount((count) => count + 1)\n }, [])\n\n return { state, refetch }\n}\n\n/** The result object of `useService` for a state. */\nexport function serviceResult<T>(\n state: ResolvedServiceState<T>,\n refetch: () => void,\n): UseServiceResult<T> {\n return {\n data: state.status === 'success' ? state.data : undefined,\n error: state.status === 'error' ? state.error : undefined,\n isLoading: state.status === 'loading',\n isSuccess: state.status === 'success',\n isError: state.status === 'error',\n refetch,\n }\n}\n","import { serviceResult, useResolvedService } from './use-resolved-service.mjs'\n\nimport type { AnyServiceToken, ServiceHook, UseServiceResult } from './types.mjs'\n\n/**\n * Hook to load a service from the DI container, with its loading and error\n * state. Resolves again when the instance is invalidated.\n *\n * @example\n * ```tsx\n * function UserCard() {\n * const { data: users, error } = useService(UserService)\n *\n * if (error) return <p>{error.message}</p>\n * if (!users) return <p>Loading…</p>\n *\n * return <UserList users={users} />\n * }\n * ```\n */\nexport const useService = function useService(\n token: AnyServiceToken,\n args?: unknown,\n): UseServiceResult<any> {\n const { state, refetch } = useResolvedService(token, args, { optional: false })\n return serviceResult(state, refetch)\n} as ServiceHook<'service'>\n","import { useCallback, useSyncExternalStore } from 'react'\n\nimport type { Container, InjectionToken, ScopedContainer } from '@navios/di'\n\nimport { useContainer } from '../container/use-container.mjs'\n\nimport { getArgsKey } from './args-key.mjs'\n\nimport type { AnyServiceToken, ServiceHook } from './types.mjs'\n\n// Cache entry for suspense\ninterface CacheEntry<T> {\n promise: Promise<T> | null\n result: T | undefined\n error: Error | undefined\n status: 'pending' | 'resolved' | 'rejected'\n version: number // Increment on each fetch to track changes\n subscribers: Set<() => void>\n unsubscribe: (() => void) | undefined\n // The timer after which a rejected entry leaves the cache\n eviction: ReturnType<typeof setTimeout> | undefined\n // The timer after which an entry no component shows leaves the cache\n release: ReturnType<typeof setTimeout> | undefined\n // How many renders read the entry\n renders: number\n}\n\ntype AnyContainer = Container | ScopedContainer\ntype Cache = Map<string, CacheEntry<any>>\n\n// Global cache for service instances: container -> token object -> args key.\n// Tokens have no ids, so the token object itself (class, token, or the\n// Bound/Factory wrapper) is the identity.\nconst cacheMap = new WeakMap<object, WeakMap<object, Cache>>()\n\nfunction getCache(container: object, token: object): Cache {\n let byToken = cacheMap.get(container)\n if (!byToken) {\n byToken = new WeakMap()\n cacheMap.set(container, byToken)\n }\n let cache = byToken.get(token)\n if (!cache) {\n cache = new Map()\n byToken.set(token, cache)\n }\n return cache\n}\n\n/**\n * The cache entry for `key`, created on first use. An instance the container\n * already holds makes it resolved, so the first render does not suspend. The\n * entry listens for the invalidation of that instance from the start: an\n * effect would subscribe after the render, and miss one in between.\n */\nfunction getEntry(\n cache: Cache,\n key: string,\n container: AnyContainer,\n token: AnyServiceToken,\n args: unknown,\n): CacheEntry<any> {\n let entry = cache.get(key)\n if (!entry) {\n const syncInstance = container.peek(token as InjectionToken<any, any>, args)\n entry = {\n promise: null,\n result: syncInstance !== null ? syncInstance : undefined,\n error: undefined,\n status: syncInstance !== null ? 'resolved' : 'pending',\n version: 0,\n subscribers: new Set(),\n unsubscribe: undefined,\n eviction: undefined,\n release: undefined,\n renders: 0,\n }\n cache.set(key, entry)\n if (syncInstance !== null) {\n setupInvalidationSubscription(entry, container, token, args)\n }\n }\n return entry\n}\n\n/**\n * Sets up invalidation subscription for a cache entry if not already subscribed.\n * When the service is destroyed, clears the cache and notifies subscribers.\n */\nfunction setupInvalidationSubscription(\n entry: CacheEntry<any>,\n container: AnyContainer,\n token: AnyServiceToken,\n args: unknown,\n): void {\n if (entry.unsubscribe) return\n\n entry.unsubscribe = container.onInvalidate(token, args, () => {\n // Clear cache and notify subscribers to re-fetch\n entry.result = undefined\n entry.error = undefined\n entry.status = 'pending'\n entry.promise = null\n // Notify all subscribers\n entry.subscribers.forEach((callback) => callback())\n })\n}\n\nfunction fetchService(\n entry: CacheEntry<any>,\n container: AnyContainer,\n token: AnyServiceToken,\n args: unknown,\n): void {\n entry.status = 'pending'\n entry.version++ // Increment version to signal change to useSyncExternalStore\n entry.promise = (container.get as any)(token, args)\n .then((instance: unknown) => {\n entry.result = instance\n entry.status = 'resolved'\n\n // Subscribe to invalidation events if not already subscribed\n setupInvalidationSubscription(entry, container, token, args)\n\n // Notify subscribers\n entry.subscribers.forEach((callback) => callback())\n return instance\n })\n .catch((error: Error) => {\n entry.error = error\n entry.status = 'rejected'\n throw error\n })\n}\n\n/**\n * Drops a rejected entry two timer turns after the last render that threw its\n * error. Every render until then throws the error again: React renders a\n * failed component a second time before it shows the error boundary, and when\n * the first of those renders used up its time slice, the second one runs in a\n * later task. That task is queued before the second timer is, so it still\n * finds the entry; with one turn it found the cache empty and resolved the\n * service again. The next render after that, such as the one of an error\n * boundary reset, resolves the service again.\n */\nfunction evictAfterRender(cache: Cache, key: string, entry: CacheEntry<any>): void {\n clearTimeout(entry.eviction)\n entry.eviction = setTimeout(() => {\n entry.eviction = setTimeout(() => {\n if (cache.get(key) === entry && entry.status === 'rejected') {\n cache.delete(key)\n entry.unsubscribe?.()\n }\n }, 0)\n }, 0)\n}\n\n/**\n * Drops a resolved entry, and its invalidation listener, one timer turn after\n * its last subscriber left, unless a component subscribed or rendered with it\n * in the meantime. A component that shows the service later reads the instance\n * from the container again.\n */\nfunction releaseWhenUnused(cache: Cache, key: string, entry: CacheEntry<any>): void {\n clearTimeout(entry.release)\n const renders = entry.renders\n entry.release = setTimeout(() => {\n if (\n cache.get(key) === entry &&\n entry.status === 'resolved' &&\n entry.subscribers.size === 0 &&\n entry.renders === renders\n ) {\n cache.delete(key)\n entry.unsubscribe?.()\n entry.unsubscribe = undefined\n }\n }, 0)\n}\n\n/**\n * Hook that returns a service from the DI container and suspends while it is\n * resolved. A failed resolution is thrown to the nearest error boundary.\n * Resolves again, suspending, when the instance is invalidated.\n */\nexport const useSuspenseService = function useSuspenseService(\n token: AnyServiceToken,\n args?: unknown,\n): any {\n // useContainer returns ScopedContainer if inside ScopeProvider, otherwise Container\n const container = useContainer()\n const cache = getCache(container, token)\n const cacheKey = getArgsKey(args)\n const entry = getEntry(cache, cacheKey, container, token, args)\n entry.renders++\n\n // Subscribe to cache changes\n const subscribe = useCallback(\n (callback: () => void) => {\n entry.subscribers.add(callback)\n return () => {\n entry.subscribers.delete(callback)\n if (entry.subscribers.size === 0) {\n releaseWhenUnused(cache, cacheKey, entry)\n }\n }\n },\n [cache, cacheKey, entry],\n )\n\n // Get snapshot of current state - include version to detect invalidation\n const getSnapshot = useCallback(() => {\n return `${entry.status}:${entry.version}`\n }, [entry])\n\n // Use sync external store to track cache state\n useSyncExternalStore(subscribe, getSnapshot, getSnapshot)\n\n // Start fetching if not already\n if (entry.status === 'pending' && !entry.promise) {\n fetchService(entry, container, token, args)\n }\n\n // Suspense behavior\n if (entry.status === 'pending') {\n throw entry.promise\n }\n\n if (entry.status === 'rejected') {\n // A later render tries again\n evictAfterRender(cache, cacheKey, entry)\n throw entry.error\n }\n\n return entry.result\n} as ServiceHook<'suspense'>\n","import { serviceResult, useResolvedService } from './use-resolved-service.mjs'\n\nimport type { AnyServiceToken, ServiceHook, UseOptionalServiceResult } from './types.mjs'\n\n/**\n * Hook to optionally load a service from the DI container.\n *\n * Unlike useService, a token without a provider is not an error: the hook\n * returns `isNotFound: true` instead.\n *\n * This is useful for:\n * - Optional dependencies that may or may not be configured\n * - Feature flags where a service might not be available\n * - Plugins or extensions that are conditionally registered\n *\n * @example\n * ```tsx\n * function Analytics() {\n * const { data: analytics, isNotFound } = useOptionalService(AnalyticsService)\n *\n * if (isNotFound) {\n * // Analytics service not configured, skip tracking\n * return null\n * }\n *\n * return <AnalyticsTracker service={analytics} />\n * }\n * ```\n */\nexport const useOptionalService = function useOptionalService(\n token: AnyServiceToken,\n args?: unknown,\n): UseOptionalServiceResult<any> {\n const { state, refetch } = useResolvedService(token, args, { optional: true })\n return { ...serviceResult(state, refetch), isNotFound: state.status === 'not-found' }\n} as ServiceHook<'optional'>\n","import { useCallback } from 'react'\n\nimport { useContainer } from '../container/use-container.mjs'\n\n/**\n * Hook that returns a function to invalidate a service instance directly.\n *\n * This is useful when you have the service instance and want to invalidate it\n * without knowing its token.\n *\n * @example\n * ```tsx\n * function UserProfile() {\n * const { data: user } = useService(UserService)\n * const invalidateInstance = useInvalidateInstance()\n *\n * const handleRefresh = () => {\n * if (user) {\n * invalidateInstance(user)\n * }\n * }\n *\n * return (\n * <div>\n * <span>{user?.name}</span>\n * <button onClick={handleRefresh}>Refresh</button>\n * </div>\n * )\n * }\n * ```\n */\nexport function useInvalidateInstance(): (instance: unknown) => Promise<void> {\n const container = useContainer()\n\n return useCallback(\n async (instance: unknown) => {\n await container.invalidate(instance)\n },\n [container],\n )\n}\n"],"mappings":";;;;;;;;;AAQA,MAAa,oBAAA,GAAmBA,MAAAA,cAAAA,CAAgC,IAAI;;;;;AAMpE,MAAa,0BAAA,GAAyBA,MAAAA,cAAAA,CAAsC,IAAI;;ACFhF,SAAgB,kBAAkB,EAAE,WAAW,YAAoC;CACjF,QAAA,GAAOC,kBAAAA,IAAAA,CAAI,iBAAiB,UAAU;EAAE,OAAO;EAAW;CAAS,CAAC;AACtE;;;;;;;;;;;;ACEA,SAAgB,eAA4C;CAC1D,MAAM,mBAAA,GAAkBC,MAAAA,WAAAA,CAAW,sBAAsB;CACzD,MAAM,aAAA,GAAYA,MAAAA,WAAAA,CAAW,gBAAgB;CAG7C,IAAI,iBACF,OAAO;CAGT,IAAI,CAAC,WACH,MAAM,IAAI,MAAM,sDAAsD;CAGxE,OAAO;AACT;;;;;;;;;AAUA,SAAgB,mBAA8B;CAC5C,MAAM,aAAA,GAAYA,MAAAA,WAAAA,CAAW,gBAAgB;CAE7C,IAAI,CAAC,WACH,MAAM,IAAI,MAAM,0DAA0D;CAG5E,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;ACHA,SAAgB,cAAc,EAAE,SAAS,UAAU,YAAgC;CACjF,MAAM,aAAA,GAAYC,MAAAA,WAAAA,CAAW,gBAAgB;CAC7C,IAAI,CAAC,WACH,MAAM,IAAI,MAAM,uDAAuD;CAGzE,MAAM,eAAA,GAAcC,MAAAA,MAAAA,CAAM;CAC1B,MAAM,mBAAmB,WAAW;CACpC,MAAM,sBAAA,GAAqBC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