@navios/di-react 0.9.0 → 2.0.0-alpha.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 (36) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +45 -665
  3. package/lib/{index.js → index.cjs} +249 -258
  4. package/lib/index.cjs.map +1 -0
  5. package/lib/{index.d.ts → index.d.cts} +94 -123
  6. package/lib/index.d.cts.map +1 -0
  7. package/lib/index.d.mts +93 -122
  8. package/lib/index.d.mts.map +1 -1
  9. package/lib/index.mjs +248 -258
  10. package/lib/index.mjs.map +1 -1
  11. package/package.json +32 -18
  12. package/lib/index.d.ts.map +0 -1
  13. package/lib/index.js.map +0 -1
  14. package/project.json +0 -61
  15. package/src/hooks/__tests__/use-container.spec.mts +0 -53
  16. package/src/hooks/__tests__/use-invalidate.spec.mts +0 -80
  17. package/src/hooks/__tests__/use-optional-service.spec.mts +0 -233
  18. package/src/hooks/__tests__/use-service.spec.mts +0 -212
  19. package/src/hooks/__tests__/use-suspense-service.spec.mts +0 -286
  20. package/src/hooks/index.mts +0 -14
  21. package/src/hooks/use-container.mts +0 -61
  22. package/src/hooks/use-invalidate.mts +0 -41
  23. package/src/hooks/use-optional-service.mts +0 -276
  24. package/src/hooks/use-scope.mts +0 -87
  25. package/src/hooks/use-service.mts +0 -226
  26. package/src/hooks/use-suspense-service.mts +0 -234
  27. package/src/index.mts +0 -8
  28. package/src/providers/__tests__/scope-provider.spec.mts +0 -366
  29. package/src/providers/container-provider.mts +0 -18
  30. package/src/providers/context.mts +0 -15
  31. package/src/providers/index.mts +0 -5
  32. package/src/providers/scope-provider.mts +0 -90
  33. package/src/types.mts +0 -21
  34. package/tsconfig.json +0 -13
  35. package/tsdown.config.mts +0 -14
  36. package/vitest.config.mts +0 -12
package/lib/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import { createContext, useCallback, useContext, useEffect, useId, useReducer, useRef, useState, useSyncExternalStore } from "react";
1
+ import { createContext, useCallback, useContext, useEffect, useId, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
2
2
  import { jsx } from "react/jsx-runtime";
3
-
4
- //#region src/providers/context.mts
3
+ import { DIError, DIErrorCode } from "@navios/di";
4
+ // src/container/context.mts
5
5
  /**
6
6
  * Context for the root Container.
7
7
  * This is set by ContainerProvider and provides the base container.
@@ -12,18 +12,45 @@ const ContainerContext = createContext(null);
12
12
  * This allows nested components to access request-scoped services.
13
13
  */
14
14
  const ScopedContainerContext = createContext(null);
15
-
16
- //#endregion
17
- //#region src/providers/container-provider.mts
15
+ // src/container/container-provider.mts
18
16
  function ContainerProvider({ container, children }) {
19
17
  return jsx(ContainerContext.Provider, {
20
18
  value: container,
21
19
  children
22
20
  });
23
21
  }
24
-
25
- //#endregion
26
- //#region src/providers/scope-provider.mts
22
+ // src/container/use-container.mts
23
+ /**
24
+ * Hook to get the current container (ScopedContainer if inside ScopeProvider, otherwise Container).
25
+ *
26
+ * This is the primary hook for accessing the DI container. It automatically
27
+ * returns the correct container based on context:
28
+ * - Inside a ScopeProvider: returns the ScopedContainer for request-scoped services
29
+ * - Outside a ScopeProvider: returns the root Container
30
+ *
31
+ * @returns The current container (ScopedContainer or Container)
32
+ */
33
+ function useContainer() {
34
+ const scopedContainer = useContext(ScopedContainerContext);
35
+ const container = useContext(ContainerContext);
36
+ if (scopedContainer) return scopedContainer;
37
+ if (!container) throw new Error("useContainer must be used within a ContainerProvider");
38
+ return container;
39
+ }
40
+ /**
41
+ * Hook to get the root Container, regardless of whether we're inside a ScopeProvider.
42
+ *
43
+ * Use this when you need access to the root container specifically,
44
+ * for example to create new request scopes programmatically.
45
+ *
46
+ * @returns The root Container
47
+ */
48
+ function useRootContainer() {
49
+ const container = useContext(ContainerContext);
50
+ if (!container) throw new Error("useRootContainer must be used within a ContainerProvider");
51
+ return container;
52
+ }
53
+ // src/scope/scope-provider.mts
27
54
  /**
28
55
  * ScopeProvider creates a new request scope for dependency injection.
29
56
  *
@@ -52,57 +79,133 @@ function ScopeProvider({ scopeId, metadata, children }) {
52
79
  const generatedId = useId();
53
80
  const effectiveScopeId = scopeId ?? generatedId;
54
81
  const scopedContainerRef = useRef(null);
55
- if (!scopedContainerRef.current) {
56
- if (!container.hasActiveRequest(effectiveScopeId)) scopedContainerRef.current = container.beginRequest(effectiveScopeId, metadata);
57
- }
82
+ const isMountedRef = useRef(false);
83
+ const isDisposedRef = useRef(false);
84
+ const [, rerender] = useReducer((count) => count + 1, 0);
85
+ const createScope = () => container.createScope({
86
+ ...metadata,
87
+ scopeId: effectiveScopeId
88
+ });
89
+ const createScopeRef = useRef(createScope);
90
+ createScopeRef.current = createScope;
91
+ if (!scopedContainerRef.current) scopedContainerRef.current = createScope();
58
92
  useEffect(() => {
59
- const scopedContainer = scopedContainerRef.current;
93
+ isMountedRef.current = true;
94
+ if (isDisposedRef.current) {
95
+ isDisposedRef.current = false;
96
+ scopedContainerRef.current = createScopeRef.current();
97
+ rerender();
98
+ }
60
99
  return () => {
61
- if (scopedContainer) scopedContainer.endRequest();
100
+ isMountedRef.current = false;
101
+ queueMicrotask(() => {
102
+ if (isMountedRef.current || isDisposedRef.current) return;
103
+ isDisposedRef.current = true;
104
+ scopedContainerRef.current?.dispose();
105
+ });
62
106
  };
63
107
  }, []);
64
- if (!scopedContainerRef.current) return null;
65
108
  return jsx(ScopedContainerContext.Provider, {
66
109
  value: scopedContainerRef.current,
67
110
  children
68
111
  });
69
112
  }
70
-
71
- //#endregion
72
- //#region src/hooks/use-container.mts
113
+ // src/scope/use-scope.mts
73
114
  /**
74
- * Hook to get the current container (ScopedContainer if inside ScopeProvider, otherwise Container).
115
+ * Hook to get the current scope ID.
116
+ * Returns null if not inside a ScopeProvider.
117
+ */
118
+ function useScope() {
119
+ return useContext(ScopedContainerContext)?.getMetadata("scopeId") ?? null;
120
+ }
121
+ /**
122
+ * Hook to get the current scope ID, throwing if not inside a ScopeProvider.
123
+ * Use this when your component requires a scope to function correctly.
124
+ */
125
+ function useScopeOrThrow() {
126
+ const scopeId = useScope();
127
+ if (scopeId === null) throw new Error("useScopeOrThrow must be used within a ScopeProvider. Wrap your component tree with <ScopeProvider> to create a request scope.");
128
+ return scopeId;
129
+ }
130
+ /**
131
+ * Hook to get the current ScopedContainer.
132
+ * Returns null if not inside a ScopeProvider.
75
133
  *
76
- * This is the primary hook for accessing the DI container. It automatically
77
- * returns the correct container based on context:
78
- * - Inside a ScopeProvider: returns the ScopedContainer for request-scoped services
79
- * - Outside a ScopeProvider: returns the root Container
134
+ * Use this to access scope metadata or other ScopedContainer methods.
80
135
  *
81
- * @returns The current container (ScopedContainer or Container)
136
+ * @example
137
+ * ```tsx
138
+ * function TableRow() {
139
+ * const scope = useScopedContainer()
140
+ * const rowData = scope?.getMetadata('rowData')
141
+ * // ...
142
+ * }
143
+ * ```
82
144
  */
83
- function useContainer() {
84
- const scopedContainer = useContext(ScopedContainerContext);
85
- const container = useContext(ContainerContext);
86
- if (scopedContainer) return scopedContainer;
87
- if (!container) throw new Error("useContainer must be used within a ContainerProvider");
88
- return container;
145
+ function useScopedContainer() {
146
+ return useContext(ScopedContainerContext);
89
147
  }
90
148
  /**
91
- * Hook to get the root Container, regardless of whether we're inside a ScopeProvider.
149
+ * Hook to get the current ScopedContainer, throwing if not inside a ScopeProvider.
150
+ * Use this when your component requires a scope to function correctly.
151
+ */
152
+ function useScopedContainerOrThrow() {
153
+ const scopedContainer = useScopedContainer();
154
+ if (scopedContainer === null) throw new Error("useScopedContainerOrThrow must be used within a ScopeProvider. Wrap your component tree with <ScopeProvider> to create a request scope.");
155
+ return scopedContainer;
156
+ }
157
+ /**
158
+ * Hook to get metadata from the current scope.
159
+ * Returns undefined if not inside a ScopeProvider or if the key doesn't exist.
92
160
  *
93
- * Use this when you need access to the root container specifically,
94
- * for example to create new request scopes programmatically.
161
+ * @example
162
+ * ```tsx
163
+ * // In parent component:
164
+ * <ScopeProvider metadata={{ userId: '123', theme: 'dark' }}>
165
+ * <ChildComponent />
166
+ * </ScopeProvider>
95
167
  *
96
- * @returns The root Container
168
+ * // In child component:
169
+ * function ChildComponent() {
170
+ * const userId = useScopeMetadata<string>('userId')
171
+ * const theme = useScopeMetadata<'light' | 'dark'>('theme')
172
+ * // ...
173
+ * }
174
+ * ```
97
175
  */
98
- function useRootContainer() {
99
- const container = useContext(ContainerContext);
100
- if (!container) throw new Error("useRootContainer must be used within a ContainerProvider");
101
- return container;
176
+ function useScopeMetadata(key) {
177
+ return useContext(ScopedContainerContext)?.getMetadata(key);
102
178
  }
103
-
104
- //#endregion
105
- //#region src/hooks/use-service.mts
179
+ // src/service/args-key.mts
180
+ let nextId = 0;
181
+ const objectIds = /* @__PURE__ */ new WeakMap();
182
+ /** What the container compares by value, and JSON would leave out. */
183
+ function replacer(_key, value) {
184
+ if (typeof value === "bigint" || value instanceof RegExp) return { [typeof value]: String(value) };
185
+ if (value instanceof Map || value instanceof Set) return { [value.constructor.name]: Array.from(value) };
186
+ return value;
187
+ }
188
+ /**
189
+ * Key that identifies the args of a hook call. Args that serialize to the same
190
+ * JSON share a key, so an object literal written in the call, or a function in
191
+ * it, does not count as a change on every render.
192
+ *
193
+ * Args JSON cannot serialize, which contain themselves, are keyed by identity.
194
+ */
195
+ function getArgsKey(args) {
196
+ try {
197
+ return JSON.stringify(args, replacer) ?? "";
198
+ } catch {
199
+ const object = args;
200
+ let id = objectIds.get(object);
201
+ if (id === void 0) {
202
+ id = ++nextId;
203
+ objectIds.set(object, id);
204
+ }
205
+ return `#${id}`;
206
+ }
207
+ }
208
+ // src/service/use-service.mts
106
209
  function serviceReducer(state, action) {
107
210
  switch (action.type) {
108
211
  case "loading": return { status: "loading" };
@@ -120,54 +223,46 @@ function serviceReducer(state, action) {
120
223
  }
121
224
  function useService(token, args) {
122
225
  const container = useContainer();
123
- const rootContainer = useRootContainer();
124
- const initialSyncInstanceRef = useRef(void 0);
125
- const isFirstRenderRef = useRef(true);
126
- if (isFirstRenderRef.current) {
127
- initialSyncInstanceRef.current = container.tryGetSync(token, args);
128
- isFirstRenderRef.current = false;
226
+ const argsKey = getArgsKey(args);
227
+ const stableArgs = useMemo(() => args, [argsKey]);
228
+ const initialSyncRef = useRef(void 0);
229
+ if (initialSyncRef.current === void 0) {
230
+ const instance = container.peek(token, args);
231
+ initialSyncRef.current = instance === null ? null : {
232
+ container,
233
+ token,
234
+ argsKey,
235
+ instance
236
+ };
129
237
  }
130
- const [state, dispatch] = useReducer(serviceReducer, initialSyncInstanceRef.current ? {
238
+ const initialState = initialSyncRef.current !== null ? {
131
239
  status: "success",
132
- data: initialSyncInstanceRef.current
133
- } : { status: "idle" });
134
- const instanceNameRef = useRef(null);
240
+ data: initialSyncRef.current.instance
241
+ } : { status: "idle" };
242
+ const [state, dispatch] = useReducer(serviceReducer, initialState);
135
243
  const [refetchCounter, setRefetchCounter] = useState(0);
136
- {
137
- const argsRef = useRef(args);
138
- useEffect(() => {
139
- if (argsRef.current !== args) {
140
- if (JSON.stringify(argsRef.current) === JSON.stringify(args)) console.log(`WARNING: useService called with args that look the same but are different instances: ${JSON.stringify(argsRef.current)} !== ${JSON.stringify(args)}!
141
- This is likely because you are using not memoized value that is not stable.
142
- Please use a memoized value or use a different approach to pass the args.
143
- Example:
144
- const args = useMemo(() => ({ userId: '123' }), [])
145
- return useService(UserToken, args)
146
- `);
147
- argsRef.current = args;
148
- }
149
- }, [args]);
150
- }
151
244
  useEffect(() => {
152
- const eventBus = rootContainer.getEventBus();
153
245
  let unsubscribe;
154
246
  let isMounted = true;
247
+ const subscribe = () => {
248
+ if (unsubscribe) return;
249
+ unsubscribe = container.onInvalidate(token, stableArgs, () => {
250
+ if (!isMounted) return;
251
+ dispatch({ type: "loading" });
252
+ queueMicrotask(() => {
253
+ if (isMounted) fetchAndSubscribe();
254
+ });
255
+ });
256
+ };
155
257
  const fetchAndSubscribe = async () => {
156
258
  try {
157
- const instance = await container.get(token, args);
259
+ const instance = await container.get(token, stableArgs);
158
260
  if (!isMounted) return;
159
- const instanceName = container.calculateInstanceName(token, args);
160
- if (instanceName) instanceNameRef.current = instanceName;
161
261
  dispatch({
162
262
  type: "success",
163
263
  data: instance
164
264
  });
165
- if (instanceName) unsubscribe = eventBus.on(instanceName, "destroy", () => {
166
- if (isMounted) {
167
- dispatch({ type: "loading" });
168
- fetchAndSubscribe();
169
- }
170
- });
265
+ subscribe();
171
266
  } catch (error) {
172
267
  if (isMounted) dispatch({
173
268
  type: "error",
@@ -175,18 +270,10 @@ function useService(token, args) {
175
270
  });
176
271
  }
177
272
  };
178
- if (initialSyncInstanceRef.current && refetchCounter === 0) {
179
- const instanceName = container.calculateInstanceName(token, args);
180
- if (instanceName) {
181
- instanceNameRef.current = instanceName;
182
- unsubscribe = eventBus.on(instanceName, "destroy", () => {
183
- if (isMounted) {
184
- dispatch({ type: "loading" });
185
- fetchAndSubscribe();
186
- }
187
- });
188
- }
189
- } else {
273
+ const initial = initialSyncRef.current;
274
+ if (initial != null && initial.container === container && initial.token === token && initial.argsKey === argsKey && refetchCounter === 0) subscribe();
275
+ else {
276
+ initialSyncRef.current = null;
190
277
  dispatch({ type: "loading" });
191
278
  fetchAndSubscribe();
192
279
  }
@@ -196,9 +283,9 @@ function useService(token, args) {
196
283
  };
197
284
  }, [
198
285
  container,
199
- rootContainer,
200
286
  token,
201
- args,
287
+ stableArgs,
288
+ argsKey,
202
289
  refetchCounter
203
290
  ]);
204
291
  const refetch = useCallback(() => {
@@ -213,18 +300,18 @@ function useService(token, args) {
213
300
  refetch
214
301
  };
215
302
  }
216
-
217
- //#endregion
218
- //#region src/hooks/use-suspense-service.mts
303
+ // src/service/use-suspense-service.mts
219
304
  const cacheMap = /* @__PURE__ */ new WeakMap();
220
- function getCacheKey(token, args) {
221
- return `${typeof token === "function" ? token.name : token.id || token.token?.id || String(token)}:${JSON.stringify(args ?? null)}`;
222
- }
223
- function getCache(container) {
224
- let cache = cacheMap.get(container);
305
+ function getCache(container, token) {
306
+ let byToken = cacheMap.get(container);
307
+ if (!byToken) {
308
+ byToken = /* @__PURE__ */ new WeakMap();
309
+ cacheMap.set(container, byToken);
310
+ }
311
+ let cache = byToken.get(token);
225
312
  if (!cache) {
226
313
  cache = /* @__PURE__ */ new Map();
227
- cacheMap.set(container, cache);
314
+ byToken.set(token, cache);
228
315
  }
229
316
  return cache;
230
317
  }
@@ -232,9 +319,9 @@ function getCache(container) {
232
319
  * Sets up invalidation subscription for a cache entry if not already subscribed.
233
320
  * When the service is destroyed, clears the cache and notifies subscribers.
234
321
  */
235
- function setupInvalidationSubscription(entry, rootContainer) {
236
- if (entry.unsubscribe || !entry.instanceName) return;
237
- entry.unsubscribe = rootContainer.getEventBus().on(entry.instanceName, "destroy", () => {
322
+ function setupInvalidationSubscription(entry, container, token, args) {
323
+ if (entry.unsubscribe) return;
324
+ entry.unsubscribe = container.onInvalidate(token, args, () => {
238
325
  entry.result = void 0;
239
326
  entry.error = void 0;
240
327
  entry.status = "pending";
@@ -244,39 +331,21 @@ function setupInvalidationSubscription(entry, rootContainer) {
244
331
  }
245
332
  function useSuspenseService(token, args) {
246
333
  const container = useContainer();
247
- const rootContainer = useRootContainer();
248
- const cache = getCache(container);
249
- const cacheKey = getCacheKey(token, args);
334
+ const cache = getCache(container, token);
335
+ const cacheKey = getArgsKey(args);
250
336
  const entryRef = useRef(null);
251
- {
252
- const argsRef = useRef(args);
253
- useEffect(() => {
254
- if (argsRef.current !== args) {
255
- if (JSON.stringify(argsRef.current) === JSON.stringify(args)) console.log(`WARNING: useService called with args that look the same but are different instances: ${JSON.stringify(argsRef.current)} !== ${JSON.stringify(args)}!
256
- This is likely because you are using not memoized value that is not stable.
257
- Please use a memoized value or use a different approach to pass the args.
258
- Example:
259
- const args = useMemo(() => ({ userId: '123' }), [])
260
- return useService(UserToken, args)
261
- `);
262
- argsRef.current = args;
263
- }
264
- }, [args]);
265
- }
266
337
  if (!cache.has(cacheKey)) {
267
- const syncInstance = container.tryGetSync(token, args);
268
- const instanceName = container.calculateInstanceName(token, args);
269
- const entry$1 = {
338
+ const syncInstance = container.peek(token, args);
339
+ const entry = {
270
340
  promise: null,
271
- result: syncInstance ?? void 0,
341
+ result: syncInstance !== null ? syncInstance : void 0,
272
342
  error: void 0,
273
- status: syncInstance ? "resolved" : "pending",
343
+ status: syncInstance !== null ? "resolved" : "pending",
274
344
  version: 0,
275
345
  subscribers: /* @__PURE__ */ new Set(),
276
- instanceName,
277
346
  unsubscribe: void 0
278
347
  };
279
- cache.set(cacheKey, entry$1);
348
+ cache.set(cacheKey, entry);
280
349
  }
281
350
  const entry = cache.get(cacheKey);
282
351
  entryRef.current = entry;
@@ -288,7 +357,7 @@ function useSuspenseService(token, args) {
288
357
  currentEntry.promise = container.get(token, args).then((instance) => {
289
358
  currentEntry.result = instance;
290
359
  currentEntry.status = "resolved";
291
- setupInvalidationSubscription(currentEntry, rootContainer);
360
+ setupInvalidationSubscription(currentEntry, container, token, args);
292
361
  currentEntry.subscribers.forEach((callback) => callback());
293
362
  return instance;
294
363
  }).catch((error) => {
@@ -299,7 +368,6 @@ function useSuspenseService(token, args) {
299
368
  return currentEntry.promise;
300
369
  }, [
301
370
  container,
302
- rootContainer,
303
371
  token,
304
372
  args
305
373
  ]);
@@ -315,16 +383,19 @@ function useSuspenseService(token, args) {
315
383
  useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
316
384
  useEffect(() => {
317
385
  const currentEntry = entryRef.current;
318
- if (currentEntry && currentEntry.status === "resolved" && currentEntry.instanceName && !currentEntry.unsubscribe) setupInvalidationSubscription(currentEntry, rootContainer);
319
- }, [rootContainer, entry]);
386
+ if (currentEntry && currentEntry.status === "resolved" && !currentEntry.unsubscribe) setupInvalidationSubscription(currentEntry, container, token, args);
387
+ }, [
388
+ container,
389
+ token,
390
+ args,
391
+ entry
392
+ ]);
320
393
  if (entry.status === "pending" && !entry.promise) fetchService();
321
394
  if (entry.status === "pending") throw entry.promise;
322
395
  if (entry.status === "rejected") throw entry.error;
323
396
  return entry.result;
324
397
  }
325
-
326
- //#endregion
327
- //#region src/hooks/use-optional-service.mts
398
+ // src/service/use-optional-service.mts
328
399
  function optionalServiceReducer(state, action) {
329
400
  switch (action.type) {
330
401
  case "loading": return { status: "loading" };
@@ -368,88 +439,78 @@ function optionalServiceReducer(state, action) {
368
439
  */
369
440
  function useOptionalService(token, args) {
370
441
  const container = useContainer();
371
- const rootContainer = useRootContainer();
372
- const initialSyncInstanceRef = useRef(void 0);
373
- const isFirstRenderRef = useRef(true);
374
- if (isFirstRenderRef.current) {
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;
375
447
  try {
376
- initialSyncInstanceRef.current = container.tryGetSync(token, args);
448
+ instance = container.peek(token, args);
377
449
  } catch {}
378
- isFirstRenderRef.current = false;
450
+ initialSyncRef.current = instance === null ? null : {
451
+ container,
452
+ token,
453
+ argsKey,
454
+ instance
455
+ };
379
456
  }
380
- const [state, dispatch] = useReducer(optionalServiceReducer, initialSyncInstanceRef.current ? {
457
+ const initialState = initialSyncRef.current !== null ? {
381
458
  status: "success",
382
- data: initialSyncInstanceRef.current
383
- } : { status: "idle" });
384
- const instanceNameRef = useRef(null);
385
- {
386
- const argsRef = useRef(args);
387
- useEffect(() => {
388
- if (argsRef.current !== args) {
389
- if (JSON.stringify(argsRef.current) === JSON.stringify(args)) console.log(`WARNING: useOptionalService called with args that look the same but are different instances: ${JSON.stringify(argsRef.current)} !== ${JSON.stringify(args)}!
390
- This is likely because you are using not memoized value that is not stable.
391
- Please use a memoized value or use a different approach to pass the args.
392
- Example:
393
- const args = useMemo(() => ({ userId: '123' }), [])
394
- return useOptionalService(UserToken, args)
395
- `);
396
- argsRef.current = args;
397
- }
398
- }, [args]);
399
- }
459
+ data: initialSyncRef.current.instance
460
+ } : { status: "idle" };
461
+ const [state, dispatch] = useReducer(optionalServiceReducer, initialState);
400
462
  const fetchService = useCallback(async () => {
401
463
  dispatch({ type: "loading" });
402
464
  try {
403
- const instance = await container.get(token, args);
404
- const instanceName = container.calculateInstanceName(token, args);
405
- if (instanceName) instanceNameRef.current = instanceName;
465
+ const instance = await container.get(token, stableArgs);
406
466
  dispatch({
407
467
  type: "success",
408
468
  data: instance
409
469
  });
470
+ return true;
410
471
  } catch (error) {
411
- const err = error;
412
- const errorMessage = err.message?.toLowerCase() ?? "";
413
- if (errorMessage.includes("not found") || errorMessage.includes("not registered") || errorMessage.includes("no provider")) dispatch({ type: "not-found" });
472
+ if (error instanceof DIError && error.code === DIErrorCode.ProviderNotFound && !container.isRegistered(token)) dispatch({ type: "not-found" });
414
473
  else dispatch({
415
474
  type: "error",
416
- error: err
475
+ error
417
476
  });
477
+ return false;
418
478
  }
419
479
  }, [
420
480
  container,
421
481
  token,
422
- args
482
+ stableArgs
423
483
  ]);
424
484
  useEffect(() => {
425
- const eventBus = rootContainer.getEventBus();
426
485
  let unsubscribe;
427
- if (initialSyncInstanceRef.current) {
428
- const instanceName = container.calculateInstanceName(token, args);
429
- if (instanceName) {
430
- instanceNameRef.current = instanceName;
431
- unsubscribe = eventBus.on(instanceName, "destroy", () => {
432
- fetchService();
433
- });
434
- }
435
- } else {
436
- fetchService().then(() => {
437
- if (instanceNameRef.current) unsubscribe = eventBus.on(instanceNameRef.current, "destroy", () => {
438
- fetchService();
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();
439
493
  });
440
494
  });
441
- return () => {
442
- unsubscribe?.();
443
- };
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
+ });
444
503
  }
445
504
  return () => {
505
+ isMounted = false;
446
506
  unsubscribe?.();
447
507
  };
448
508
  }, [
449
509
  fetchService,
450
- rootContainer,
510
+ container,
451
511
  token,
452
- args
512
+ stableArgs,
513
+ argsKey
453
514
  ]);
454
515
  return {
455
516
  data: state.status === "success" ? state.data : void 0,
@@ -461,9 +522,7 @@ function useOptionalService(token, args) {
461
522
  refetch: fetchService
462
523
  };
463
524
  }
464
-
465
- //#endregion
466
- //#region src/hooks/use-invalidate.mts
525
+ // src/service/use-invalidate-instance.mts
467
526
  /**
468
527
  * Hook that returns a function to invalidate a service instance directly.
469
528
  *
@@ -497,75 +556,6 @@ function useInvalidateInstance() {
497
556
  await container.invalidate(instance);
498
557
  }, [container]);
499
558
  }
500
-
501
- //#endregion
502
- //#region src/hooks/use-scope.mts
503
- /**
504
- * Hook to get the current scope ID.
505
- * Returns null if not inside a ScopeProvider.
506
- */
507
- function useScope() {
508
- return useContext(ScopedContainerContext)?.getRequestId() ?? null;
509
- }
510
- /**
511
- * Hook to get the current scope ID, throwing if not inside a ScopeProvider.
512
- * Use this when your component requires a scope to function correctly.
513
- */
514
- function useScopeOrThrow() {
515
- const scopeId = useScope();
516
- if (scopeId === null) throw new Error("useScopeOrThrow must be used within a ScopeProvider. Wrap your component tree with <ScopeProvider> to create a request scope.");
517
- return scopeId;
518
- }
519
- /**
520
- * Hook to get the current ScopedContainer.
521
- * Returns null if not inside a ScopeProvider.
522
- *
523
- * Use this to access scope metadata or other ScopedContainer methods.
524
- *
525
- * @example
526
- * ```tsx
527
- * function TableRow() {
528
- * const scope = useScopedContainer()
529
- * const rowData = scope?.getMetadata('rowData')
530
- * // ...
531
- * }
532
- * ```
533
- */
534
- function useScopedContainer() {
535
- return useContext(ScopedContainerContext);
536
- }
537
- /**
538
- * Hook to get the current ScopedContainer, throwing if not inside a ScopeProvider.
539
- * Use this when your component requires a scope to function correctly.
540
- */
541
- function useScopedContainerOrThrow() {
542
- const scopedContainer = useScopedContainer();
543
- if (scopedContainer === null) throw new Error("useScopedContainerOrThrow must be used within a ScopeProvider. Wrap your component tree with <ScopeProvider> to create a request scope.");
544
- return scopedContainer;
545
- }
546
- /**
547
- * Hook to get metadata from the current scope.
548
- * Returns undefined if not inside a ScopeProvider or if the key doesn't exist.
549
- *
550
- * @example
551
- * ```tsx
552
- * // In parent component:
553
- * <ScopeProvider metadata={{ userId: '123', theme: 'dark' }}>
554
- * <ChildComponent />
555
- * </ScopeProvider>
556
- *
557
- * // In child component:
558
- * function ChildComponent() {
559
- * const userId = useScopeMetadata<string>('userId')
560
- * const theme = useScopeMetadata<'light' | 'dark'>('theme')
561
- * // ...
562
- * }
563
- * ```
564
- */
565
- function useScopeMetadata(key) {
566
- return useContext(ScopedContainerContext)?.getMetadata(key);
567
- }
568
-
569
- //#endregion
570
559
  export { ContainerContext, ContainerProvider, ScopeProvider, ScopedContainerContext, useContainer, useInvalidateInstance, useOptionalService, useRootContainer, useScope, useScopeMetadata, useScopeOrThrow, useScopedContainer, useScopedContainerOrThrow, useService, useSuspenseService };
560
+
571
561
  //# sourceMappingURL=index.mjs.map