@navios/di-react 1.0.0-alpha.3 → 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 (58) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +45 -665
  3. package/lib/{index.js → index.cjs} +249 -255
  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 -255
  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.map +0 -1
  34. package/lib/index.js.map +0 -1
  35. package/project.json +0 -61
  36. package/src/hooks/__tests__/use-container.spec.mts +0 -143
  37. package/src/hooks/__tests__/use-invalidate.spec.mts +0 -80
  38. package/src/hooks/__tests__/use-optional-service.spec.mts +0 -233
  39. package/src/hooks/__tests__/use-scope.spec.mts +0 -293
  40. package/src/hooks/__tests__/use-service.spec.mts +0 -212
  41. package/src/hooks/__tests__/use-suspense-service.spec.mts +0 -286
  42. package/src/hooks/index.mts +0 -14
  43. package/src/hooks/use-container.mts +0 -61
  44. package/src/hooks/use-invalidate.mts +0 -41
  45. package/src/hooks/use-optional-service.mts +0 -275
  46. package/src/hooks/use-scope.mts +0 -87
  47. package/src/hooks/use-service.mts +0 -225
  48. package/src/hooks/use-suspense-service.mts +0 -233
  49. package/src/index.mts +0 -8
  50. package/src/providers/__tests__/scope-provider.spec.mts +0 -366
  51. package/src/providers/container-provider.mts +0 -18
  52. package/src/providers/context.mts +0 -15
  53. package/src/providers/index.mts +0 -5
  54. package/src/providers/scope-provider.mts +0 -90
  55. package/src/types.mts +0 -21
  56. package/tsconfig.json +0 -13
  57. package/tsdown.config.mts +0 -14
  58. package/vitest.config.mts +0 -12
package/lib/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","names":["unsubscribe: (() => void) | undefined","entry: CacheEntry<any>","entry","unsubscribe: (() => void) | undefined"],"sources":["../src/providers/context.mts","../src/providers/container-provider.mts","../src/providers/scope-provider.mts","../src/hooks/use-container.mts","../src/hooks/use-service.mts","../src/hooks/use-suspense-service.mts","../src/hooks/use-optional-service.mts","../src/hooks/use-invalidate.mts","../src/hooks/use-scope.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 type { Container } from '@navios/di'\nimport type { ReactNode } from 'react'\n\nimport { jsx } from 'react/jsx-runtime'\n\nimport { ContainerContext } from './context.mjs'\n\nexport interface ContainerProviderProps {\n container: Container\n children: ReactNode\n}\n\nexport function ContainerProvider({\n container,\n children,\n}: ContainerProviderProps) {\n return jsx(ContainerContext.Provider, { value: container, children })\n}\n","import type { ScopedContainer } from '@navios/di'\nimport type { ReactNode } from 'react'\n\nimport { useContext, useEffect, useId, useRef } from 'react'\nimport { jsx } from 'react/jsx-runtime'\n\nimport { ContainerContext, ScopedContainerContext } from './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 request context.\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({\n scopeId,\n metadata,\n children,\n}: 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\n // Create ScopedContainer on first render only\n // We use a ref to track initialization to handle React StrictMode double-renders\n if (!scopedContainerRef.current) {\n // Check if this request ID already exists (e.g., from StrictMode double render)\n if (!container.hasActiveRequest(effectiveScopeId)) {\n scopedContainerRef.current = container.beginRequest(\n effectiveScopeId,\n metadata,\n )\n }\n }\n\n // End request context on unmount\n useEffect(() => {\n const scopedContainer = scopedContainerRef.current\n return () => {\n if (scopedContainer) {\n void scopedContainer.endRequest()\n }\n }\n }, [])\n\n // If we don't have a scoped container (shouldn't happen normally), don't render\n if (!scopedContainerRef.current) {\n return null\n }\n\n return jsx(ScopedContainerContext.Provider, {\n value: scopedContainerRef.current,\n children,\n })\n}\n","import type { Container, ScopedContainer } from '@navios/di'\n\nimport { useContext } from 'react'\n\nimport {\n ContainerContext,\n ScopedContainerContext,\n} from '../providers/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\n/**\n * Hook to get the current ScopedContainer if inside a ScopeProvider.\n *\n * @returns The ScopedContainer or null if not inside a ScopeProvider\n */\nexport function useScopedContainer(): ScopedContainer | null {\n return useContext(ScopedContainerContext)\n}\n","import type {\n AnyInjectableType,\n BoundInjectionToken,\n ClassType,\n Factorable,\n FactoryInjectionToken,\n InjectionToken,\n InjectionTokenSchemaType,\n} from '@navios/di'\nimport type { z, ZodType } from 'zod/v4'\n\nimport { useCallback, useEffect, useReducer, useRef, useState } from 'react'\n\nimport type { Join, UnionToArray } from '../types.mjs'\n\nimport { useContainer, useRootContainer } from './use-container.mjs'\n\ntype ServiceState<T> =\n | { status: 'idle' }\n | { status: 'loading' }\n | { status: 'success'; data: T }\n | { status: 'error'; error: Error }\n\ntype ServiceAction<T> =\n | { type: 'loading' }\n | { type: 'success'; data: T }\n | { type: 'error'; error: Error }\n | { type: 'reset' }\n\nfunction serviceReducer<T>(\n state: ServiceState<T>,\n action: ServiceAction<T>,\n): ServiceState<T> {\n switch (action.type) {\n case 'loading':\n return { status: 'loading' }\n case 'success':\n return { status: 'success', data: action.data }\n case 'error':\n return { status: 'error', error: action.error }\n case 'reset':\n return { status: 'idle' }\n default:\n return state\n }\n}\n\nexport interface UseServiceResult<T> {\n data: T | undefined\n error: Error | undefined\n isLoading: boolean\n isSuccess: boolean\n isError: boolean\n refetch: () => void\n}\n\n// #1 Simple class\nexport function useService<T extends ClassType>(\n token: T,\n): UseServiceResult<\n InstanceType<T> extends Factorable<infer R> ? R : InstanceType<T>\n>\n\n// #2 Token with required Schema\nexport function useService<T, S extends InjectionTokenSchemaType>(\n token: InjectionToken<T, S>,\n args: z.input<S>,\n): UseServiceResult<T>\n\n// #3 Token with optional Schema\nexport function useService<\n T,\n S extends InjectionTokenSchemaType,\n R extends boolean,\n>(\n token: InjectionToken<T, S, R>,\n): R extends false\n ? UseServiceResult<T>\n : S extends ZodType<infer Type>\n ? `Error: Your token requires args: ${Join<UnionToArray<keyof Type>, ', '>}`\n : 'Error: Your token requires args'\n\n// #4 Token with no Schema\nexport function useService<T>(\n token: InjectionToken<T, undefined>,\n): UseServiceResult<T>\n\nexport function useService<T>(\n token: BoundInjectionToken<T, any>,\n): UseServiceResult<T>\n\nexport function useService<T>(\n token: FactoryInjectionToken<T, any>,\n): UseServiceResult<T>\n\nexport function useService(\n token:\n | ClassType\n | InjectionToken<any, any>\n | BoundInjectionToken<any, any>\n | FactoryInjectionToken<any, any>,\n args?: unknown,\n): UseServiceResult<any> {\n // useContainer returns ScopedContainer if inside ScopeProvider, otherwise Container\n // This automatically handles request-scoped services correctly\n const container = useContainer()\n const rootContainer = useRootContainer()\n\n // Try to get the instance synchronously first for better performance\n // This avoids the async loading state when the instance is already cached\n // We use a ref to track this so it doesn't cause effect re-runs\n const initialSyncInstanceRef = useRef<any>(undefined)\n const isFirstRenderRef = useRef(true)\n\n if (isFirstRenderRef.current) {\n initialSyncInstanceRef.current = container.tryGetSync(token, args)\n isFirstRenderRef.current = false\n }\n\n const initialState: ServiceState<any> = initialSyncInstanceRef.current\n ? { status: 'success', data: initialSyncInstanceRef.current }\n : { status: 'idle' }\n\n const [state, dispatch] = useReducer(serviceReducer, initialState)\n const instanceNameRef = useRef<string | null>(null)\n const [refetchCounter, setRefetchCounter] = useState(0)\n\n if (process.env.NODE_ENV === 'development') {\n const argsRef = useRef<unknown>(args)\n useEffect(() => {\n if (argsRef.current !== args) {\n if (JSON.stringify(argsRef.current) === JSON.stringify(args)) {\n console.warn(`useService called with args that look the same but are different instances: ${JSON.stringify(argsRef.current)} !== ${JSON.stringify(args)}!\nThis is likely because you are using a value that is not memoized.\nPlease use a memoized value or use a different approach to pass the args.\nExample:\n const args = useMemo(() => ({ userId: '123' }), [])\n return useService(UserToken, args)`)\n }\n argsRef.current = args\n }\n }, [args])\n }\n\n // Subscribe to invalidation events\n useEffect(() => {\n const eventBus = rootContainer.getEventBus()\n let unsubscribe: (() => void) | undefined\n let isMounted = true\n\n // Fetch the service and set up subscription\n const fetchAndSubscribe = async () => {\n try {\n // The container (either ScopedContainer or Container) handles resolution correctly\n const instance = await container.get(\n // @ts-expect-error - token is valid\n token as AnyInjectableType,\n args as any,\n )\n\n if (!isMounted) return\n\n // Get instance name for event subscription\n const instanceName = container.calculateInstanceName(token, args)\n if (instanceName) {\n instanceNameRef.current = instanceName\n }\n\n dispatch({ type: 'success', data: instance })\n\n // Set up subscription after we have the instance\n if (instanceName) {\n unsubscribe = eventBus.on(instanceName, 'destroy', () => {\n // Re-fetch when the service is invalidated\n if (isMounted) {\n dispatch({ type: 'loading' })\n void fetchAndSubscribe()\n }\n })\n }\n } catch (error) {\n if (isMounted) {\n dispatch({ type: 'error', error: error as Error })\n }\n }\n }\n\n // If we already have a sync instance from initial render, just set up subscription\n // Otherwise, fetch async\n const syncInstance = initialSyncInstanceRef.current\n if (syncInstance && refetchCounter === 0) {\n const instanceName = container.calculateInstanceName(token, args)\n if (instanceName) {\n instanceNameRef.current = instanceName\n unsubscribe = eventBus.on(instanceName, 'destroy', () => {\n if (isMounted) {\n dispatch({ type: 'loading' })\n void fetchAndSubscribe()\n }\n })\n }\n } else {\n dispatch({ type: 'loading' })\n void fetchAndSubscribe()\n }\n\n return () => {\n isMounted = false\n unsubscribe?.()\n }\n }, [container, rootContainer, token, args, refetchCounter])\n\n const refetch = useCallback(() => {\n setRefetchCounter((c) => c + 1)\n }, [])\n\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 type {\n BoundInjectionToken,\n ClassType,\n Container,\n Factorable,\n FactoryInjectionToken,\n InjectionToken,\n InjectionTokenSchemaType,\n} from '@navios/di'\nimport type { z, ZodType } from 'zod/v4'\n\n\nimport { useCallback, useEffect, useRef, useSyncExternalStore } from 'react'\n\nimport type { Join, UnionToArray } from '../types.mjs'\n\nimport { useContainer, useRootContainer } from './use-container.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 instanceName: string | null\n unsubscribe: (() => void) | undefined\n}\n\n// Global cache for service instances (per container + token + args combination)\nconst cacheMap = new WeakMap<object, Map<string, CacheEntry<any>>>()\n\nfunction getCacheKey(token: any, args: unknown): string {\n const tokenId =\n typeof token === 'function'\n ? token.name\n : token.id || token.token?.id || String(token)\n return `${tokenId}:${JSON.stringify(args ?? null)}`\n}\n\nfunction getCache(container: object): Map<string, CacheEntry<any>> {\n let cache = cacheMap.get(container)\n if (!cache) {\n cache = new Map()\n cacheMap.set(container, cache)\n }\n return cache\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 rootContainer: Container,\n): void {\n if (entry.unsubscribe || !entry.instanceName) return\n\n const eventBus = rootContainer.getEventBus()\n entry.unsubscribe = eventBus.on(entry.instanceName, 'destroy', () => {\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\n// #1 Simple class\nexport function useSuspenseService<T extends ClassType>(\n token: T,\n): InstanceType<T> extends Factorable<infer R> ? R : InstanceType<T>\n\n// #2 Token with required Schema\nexport function useSuspenseService<T, S extends InjectionTokenSchemaType>(\n token: InjectionToken<T, S>,\n args: z.input<S>,\n): T\n\n// #3 Token with optional Schema\nexport function useSuspenseService<\n T,\n S extends InjectionTokenSchemaType,\n R extends boolean,\n>(\n token: InjectionToken<T, S, R>,\n): R extends false\n ? T\n : S extends ZodType<infer Type>\n ? `Error: Your token requires args: ${Join<UnionToArray<keyof Type>, ', '>}`\n : 'Error: Your token requires args'\n\n// #4 Token with no Schema\nexport function useSuspenseService<T>(token: InjectionToken<T, undefined>): T\n\nexport function useSuspenseService<T>(token: BoundInjectionToken<T, any>): T\n\nexport function useSuspenseService<T>(token: FactoryInjectionToken<T, any>): T\n\nexport function useSuspenseService(\n token:\n | ClassType\n | InjectionToken<any, any>\n | BoundInjectionToken<any, any>\n | FactoryInjectionToken<any, any>,\n args?: unknown,\n): any {\n // useContainer returns ScopedContainer if inside ScopeProvider, otherwise Container\n const container = useContainer()\n const rootContainer = useRootContainer()\n const cache = getCache(container)\n const cacheKey = getCacheKey(token, args)\n const entryRef = useRef<CacheEntry<any> | null>(null)\n if (process.env.NODE_ENV === 'development') {\n const argsRef = useRef<unknown>(args)\n useEffect(() => {\n if (argsRef.current !== args) {\n if (JSON.stringify(argsRef.current) === JSON.stringify(args)) {\n console.warn(`useSuspenseService called with args that look the same but are different instances: ${JSON.stringify(argsRef.current)} !== ${JSON.stringify(args)}!\nThis is likely because you are using a value that is not memoized.\nPlease use a memoized value or use a different approach to pass the args.\nExample:\n const args = useMemo(() => ({ userId: '123' }), [])\n return useSuspenseService(UserToken, args)`)\n }\n argsRef.current = args\n }\n }, [args])\n }\n\n // Initialize or get cache entry\n if (!cache.has(cacheKey)) {\n // Try to get the instance synchronously first for better performance\n // This avoids suspense when the instance is already cached\n const syncInstance = container.tryGetSync(token, args)\n\n const instanceName = container.calculateInstanceName(token, args)\n const entry: CacheEntry<any> = {\n promise: null,\n result: syncInstance ?? undefined,\n error: undefined,\n status: syncInstance ? 'resolved' : 'pending',\n version: 0,\n subscribers: new Set(),\n instanceName,\n unsubscribe: undefined,\n }\n cache.set(cacheKey, entry)\n }\n\n const entry = cache.get(cacheKey)!\n entryRef.current = entry\n\n // Function to fetch the service\n const fetchService = useCallback(() => {\n const currentEntry = entryRef.current\n if (!currentEntry) return\n\n currentEntry.status = 'pending'\n currentEntry.version++ // Increment version to signal change to useSyncExternalStore\n currentEntry.promise = (container.get as any)(token, args)\n .then((instance: any) => {\n currentEntry.result = instance\n currentEntry.status = 'resolved'\n\n // Subscribe to invalidation events if not already subscribed\n setupInvalidationSubscription(currentEntry, rootContainer)\n\n // Notify subscribers\n currentEntry.subscribers.forEach((callback) => callback())\n return instance\n })\n .catch((error: Error) => {\n currentEntry.error = error\n currentEntry.status = 'rejected'\n throw error\n })\n\n return currentEntry.promise\n }, [container, rootContainer, token, args])\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 }\n },\n [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 // Set up subscription for sync instances that don't have one yet\n useEffect(() => {\n const currentEntry = entryRef.current\n if (\n currentEntry &&\n currentEntry.status === 'resolved' &&\n currentEntry.instanceName &&\n !currentEntry.unsubscribe\n ) {\n setupInvalidationSubscription(currentEntry, rootContainer)\n }\n }, [rootContainer, entry])\n\n // Start fetching if not already\n if (entry.status === 'pending' && !entry.promise) {\n fetchService()\n }\n\n // Suspense behavior\n if (entry.status === 'pending') {\n throw entry.promise\n }\n\n if (entry.status === 'rejected') {\n throw entry.error\n }\n\n return entry.result\n}\n","import type {\n AnyInjectableType,\n BoundInjectionToken,\n ClassType,\n Factorable,\n FactoryInjectionToken,\n InjectionToken,\n InjectionTokenSchemaType,\n} from '@navios/di'\nimport type { z, ZodType } from 'zod/v4'\n\nimport { useCallback, useEffect, useReducer, useRef } from 'react'\n\nimport type { Join, UnionToArray } from '../types.mjs'\n\nimport { useContainer, useRootContainer } from './use-container.mjs'\n\ntype OptionalServiceState<T> =\n | { status: 'idle' }\n | { status: 'loading' }\n | { status: 'success'; data: T }\n | { status: 'not-found' }\n | { status: 'error'; error: Error }\n\ntype OptionalServiceAction<T> =\n | { type: 'loading' }\n | { type: 'success'; data: T }\n | { type: 'not-found' }\n | { type: 'error'; error: Error }\n | { type: 'reset' }\n\nfunction optionalServiceReducer<T>(\n state: OptionalServiceState<T>,\n action: OptionalServiceAction<T>,\n): OptionalServiceState<T> {\n switch (action.type) {\n case 'loading':\n return { status: 'loading' }\n case 'success':\n return { status: 'success', data: action.data }\n case 'not-found':\n return { status: 'not-found' }\n case 'error':\n return { status: 'error', error: action.error }\n case 'reset':\n return { status: 'idle' }\n default:\n return state\n }\n}\n\nexport interface UseOptionalServiceResult<T> {\n /**\n * The service instance if found and loaded successfully, otherwise undefined.\n */\n data: T | undefined\n /**\n * Error that occurred during loading (excludes \"not found\" which is not an error).\n */\n error: Error | undefined\n /**\n * True while the service is being loaded.\n */\n isLoading: boolean\n /**\n * True if the service was loaded successfully.\n */\n isSuccess: boolean\n /**\n * True if the service was not found (not registered in the container).\n */\n isNotFound: boolean\n /**\n * True if an error occurred during loading.\n */\n isError: boolean\n /**\n * Function to manually re-fetch the service.\n */\n refetch: () => void\n}\n\n// #1 Simple class\nexport function useOptionalService<T extends ClassType>(\n token: T,\n): UseOptionalServiceResult<\n InstanceType<T> extends Factorable<infer R> ? R : InstanceType<T>\n>\n\n// #2 Token with required Schema\nexport function useOptionalService<T, S extends InjectionTokenSchemaType>(\n token: InjectionToken<T, S>,\n args: z.input<S>,\n): UseOptionalServiceResult<T>\n\n// #3 Token with optional Schema\nexport function useOptionalService<\n T,\n S extends InjectionTokenSchemaType,\n R extends boolean,\n>(\n token: InjectionToken<T, S, R>,\n): R extends false\n ? UseOptionalServiceResult<T>\n : S extends ZodType<infer Type>\n ? `Error: Your token requires args: ${Join<UnionToArray<keyof Type>, ', '>}`\n : 'Error: Your token requires args'\n\n// #4 Token with no Schema\nexport function useOptionalService<T>(\n token: InjectionToken<T, undefined>,\n): UseOptionalServiceResult<T>\n\nexport function useOptionalService<T>(\n token: BoundInjectionToken<T, any>,\n): UseOptionalServiceResult<T>\n\nexport function useOptionalService<T>(\n token: FactoryInjectionToken<T, any>,\n): UseOptionalServiceResult<T>\n\n/**\n * Hook to optionally load a service from the DI container.\n *\n * Unlike useService, this hook does NOT throw an error if the service is not registered.\n * Instead, it returns `isNotFound: true` when the service doesn't exist.\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 function useOptionalService(\n token:\n | ClassType\n | InjectionToken<any, any>\n | BoundInjectionToken<any, any>\n | FactoryInjectionToken<any, any>,\n args?: unknown,\n): UseOptionalServiceResult<any> {\n // useContainer returns ScopedContainer if inside ScopeProvider, otherwise Container\n const container = useContainer()\n const rootContainer = useRootContainer()\n\n // Try to get the instance synchronously first for better performance\n // This avoids the async loading state when the instance is already cached\n // We use a ref to track this so it doesn't cause effect re-runs\n const initialSyncInstanceRef = useRef<any>(undefined)\n const isFirstRenderRef = useRef(true)\n\n if (isFirstRenderRef.current) {\n try {\n initialSyncInstanceRef.current = container.tryGetSync(token, args)\n } catch {\n // Service not registered, leave as undefined\n }\n isFirstRenderRef.current = false\n }\n\n const initialState: OptionalServiceState<any> = initialSyncInstanceRef.current\n ? { status: 'success', data: initialSyncInstanceRef.current }\n : { status: 'idle' }\n\n const [state, dispatch] = useReducer(optionalServiceReducer, initialState)\n const instanceNameRef = useRef<string | null>(null)\n\n if (process.env.NODE_ENV === 'development') {\n const argsRef = useRef<unknown>(args)\n useEffect(() => {\n if (argsRef.current !== args) {\n if (JSON.stringify(argsRef.current) === JSON.stringify(args)) {\n console.warn(`useOptionalService called with args that look the same but are different instances: ${JSON.stringify(argsRef.current)} !== ${JSON.stringify(args)}!\nThis is likely because you are using a value that is not memoized.\nPlease use a memoized value or use a different approach to pass the args.\nExample:\n const args = useMemo(() => ({ userId: '123' }), [])\n return useOptionalService(UserToken, args)`)\n }\n argsRef.current = args\n }\n }, [args])\n }\n\n const fetchService = useCallback(async () => {\n dispatch({ type: 'loading' })\n try {\n // Use the container (ScopedContainer or Container) for resolution\n const instance = await container.get(\n // @ts-expect-error - token is valid\n token as AnyInjectableType,\n args as any,\n )\n // Get instance name for event subscription\n const instanceName = container.calculateInstanceName(token, args)\n if (instanceName) {\n instanceNameRef.current = instanceName\n }\n dispatch({ type: 'success', data: instance })\n } catch (error) {\n // Caught exceptions are treated as errors\n const err = error as Error\n const errorMessage = err.message?.toLowerCase() ?? ''\n if (\n errorMessage.includes('not found') ||\n errorMessage.includes('not registered') ||\n errorMessage.includes('no provider')\n ) {\n dispatch({ type: 'not-found' })\n } else {\n dispatch({ type: 'error', error: err })\n }\n }\n }, [container, token, args])\n\n // Subscribe to invalidation events\n useEffect(() => {\n const eventBus = rootContainer.getEventBus()\n let unsubscribe: (() => void) | undefined\n\n // If we already have a sync instance from initial render, just set up subscription\n // Otherwise, fetch async\n const syncInstance = initialSyncInstanceRef.current\n if (syncInstance) {\n const instanceName = container.calculateInstanceName(token, args)\n if (instanceName) {\n instanceNameRef.current = instanceName\n unsubscribe = eventBus.on(instanceName, 'destroy', () => {\n // Re-fetch when the service is invalidated\n void fetchService()\n })\n }\n } else {\n void fetchService().then(() => {\n if (instanceNameRef.current) {\n unsubscribe = eventBus.on(instanceNameRef.current, 'destroy', () => {\n // Re-fetch when the service is invalidated\n void fetchService()\n })\n }\n })\n\n return () => {\n unsubscribe?.()\n }\n }\n\n return () => {\n unsubscribe?.()\n }\n }, [fetchService, rootContainer, token, args])\n\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 isNotFound: state.status === 'not-found',\n isError: state.status === 'error',\n refetch: fetchService,\n }\n}\n","import { useCallback } from 'react'\n\nimport { useContainer } from './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","import type { ScopedContainer } from '@navios/di'\n\nimport { useContext } from 'react'\n\nimport { ScopedContainerContext } from '../providers/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?.getRequestId() ?? 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"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SAAgB,iBAA8B,KAA4B;AAExE,8BADmC,uBAAuB,EAClC,YAAY,IAAI"}
package/project.json DELETED
@@ -1,61 +0,0 @@
1
- {
2
- "name": "@navios/di-react",
3
- "$schema": "../../node_modules/nx/schemas/project-schema.json",
4
- "sourceRoot": "packages/di-react/src",
5
- "prefix": "di-react",
6
- "tags": [],
7
- "projectType": "library",
8
- "targets": {
9
- "check": {
10
- "executor": "nx:run-commands",
11
- "outputs": ["{projectRoot}/dist"],
12
- "inputs": ["^projectSources", "projectSources"],
13
- "options": {
14
- "command": ["tsc -b"],
15
- "cwd": "packages/di-react"
16
- }
17
- },
18
- "lint": {
19
- "executor": "nx:run-commands",
20
- "inputs": ["^projectSources", "project"],
21
- "options": {
22
- "command": "oxlint --fix",
23
- "cwd": "packages/di-react"
24
- }
25
- },
26
- "test:ci": {
27
- "executor": "nx:run-commands",
28
- "inputs": ["^projectSources", "project"],
29
- "options": {
30
- "command": "vitest run",
31
- "cwd": "packages/di-react"
32
- }
33
- },
34
- "build": {
35
- "executor": "nx:run-commands",
36
- "inputs": ["projectSources", "{projectRoot}/tsdown.config.mts"],
37
- "outputs": ["{projectRoot}/lib"],
38
- "dependsOn": ["check", "test:ci", "lint"],
39
- "options": {
40
- "command": "tsdown",
41
- "cwd": "packages/di-react"
42
- }
43
- },
44
- "publish": {
45
- "executor": "nx:run-commands",
46
- "dependsOn": ["build"],
47
- "options": {
48
- "command": "yarn npm publish --access public",
49
- "cwd": "packages/di-react"
50
- }
51
- },
52
- "publish:next": {
53
- "executor": "nx:run-commands",
54
- "dependsOn": ["build"],
55
- "options": {
56
- "command": "yarn npm publish --access public --tag next",
57
- "cwd": "packages/di-react"
58
- }
59
- }
60
- }
61
- }
@@ -1,143 +0,0 @@
1
- import { Container, globalRegistry, Injectable, Registry } from '@navios/di'
2
-
3
- import { renderHook } from '@testing-library/react'
4
- import { createElement } from 'react'
5
- import { afterEach, beforeEach, describe, expect, it } from 'vitest'
6
-
7
- import { ContainerProvider } from '../../providers/container-provider.mjs'
8
- import { ScopeProvider } from '../../providers/scope-provider.mjs'
9
- import { useContainer, useRootContainer } from '../use-container.mjs'
10
-
11
- describe('useContainer', () => {
12
- let container: Container
13
- let registry: Registry
14
-
15
- beforeEach(() => {
16
- registry = new Registry(globalRegistry)
17
- container = new Container(registry)
18
- })
19
-
20
- afterEach(async () => {
21
- await container.dispose()
22
- })
23
-
24
- it('should return the container from context', () => {
25
- const wrapper = ({ children }: { children: React.ReactNode }) =>
26
- // @ts-expect-error - container is required
27
- createElement(ContainerProvider, { container }, children)
28
-
29
- const { result } = renderHook(() => useContainer(), { wrapper })
30
-
31
- expect(result.current).toBe(container)
32
- })
33
-
34
- it('should throw an error when used outside of ContainerProvider', () => {
35
- expect(() => {
36
- renderHook(() => useContainer())
37
- }).toThrow('useContainer must be used within a ContainerProvider')
38
- })
39
-
40
- it('should provide access to container methods', async () => {
41
- @Injectable({ registry })
42
- class TestService {
43
- getValue() {
44
- return 'test-value'
45
- }
46
- }
47
-
48
- const wrapper = ({ children }: { children: React.ReactNode }) =>
49
- // @ts-expect-error - props are not typed
50
- createElement(ContainerProvider, { container }, children)
51
-
52
- const { result } = renderHook(() => useContainer(), { wrapper })
53
-
54
- // @ts-expect-error - token is valid
55
- const service = await result.current.get(TestService)
56
- expect(service.getValue()).toBe('test-value')
57
- })
58
-
59
- it('should return ScopedContainer when inside ScopeProvider', () => {
60
- const wrapper = ({ children }: { children: React.ReactNode }) =>
61
- createElement(
62
- ContainerProvider,
63
- // @ts-expect-error - props are not typed
64
- { container },
65
- // @ts-expect-error - props are not typed
66
- createElement(ScopeProvider, { scopeId: 'test-scope' }, children),
67
- )
68
-
69
- const { result } = renderHook(() => useContainer(), { wrapper })
70
-
71
- // Should return the scoped container, not the root container
72
- expect(result.current).not.toBe(container)
73
- // @ts-expect-error - getRequestId exists on ScopedContainer
74
- expect(result.current.getRequestId?.()).toBe('test-scope')
75
- })
76
- })
77
-
78
- describe('useRootContainer', () => {
79
- let container: Container
80
- let registry: Registry
81
-
82
- beforeEach(() => {
83
- registry = new Registry(globalRegistry)
84
- container = new Container(registry)
85
- })
86
-
87
- afterEach(async () => {
88
- await container.dispose()
89
- })
90
-
91
- it('should return the root container from context', () => {
92
- const wrapper = ({ children }: { children: React.ReactNode }) =>
93
- // @ts-expect-error - container is required
94
- createElement(ContainerProvider, { container }, children)
95
-
96
- const { result } = renderHook(() => useRootContainer(), { wrapper })
97
-
98
- expect(result.current).toBe(container)
99
- })
100
-
101
- it('should throw an error when used outside of ContainerProvider', () => {
102
- expect(() => {
103
- renderHook(() => useRootContainer())
104
- }).toThrow('useRootContainer must be used within a ContainerProvider')
105
- })
106
-
107
- it('should return root container even when inside ScopeProvider', () => {
108
- const wrapper = ({ children }: { children: React.ReactNode }) =>
109
- createElement(
110
- ContainerProvider,
111
- // @ts-expect-error - props are not typed
112
- { container },
113
- // @ts-expect-error - props are not typed
114
- createElement(ScopeProvider, { scopeId: 'test-scope' }, children),
115
- )
116
-
117
- const { result } = renderHook(() => useRootContainer(), { wrapper })
118
-
119
- // Should always return the root container, not the scoped container
120
- expect(result.current).toBe(container)
121
- })
122
-
123
- it('should return root container from deeply nested scopes', () => {
124
- const wrapper = ({ children }: { children: React.ReactNode }) =>
125
- createElement(
126
- ContainerProvider,
127
- // @ts-expect-error - props are not typed
128
- { container },
129
- createElement(
130
- ScopeProvider,
131
- // @ts-expect-error - props are not typed
132
- { scopeId: 'outer-scope' },
133
- // @ts-expect-error - props are not typed
134
- createElement(ScopeProvider, { scopeId: 'inner-scope' }, children),
135
- ),
136
- )
137
-
138
- const { result } = renderHook(() => useRootContainer(), { wrapper })
139
-
140
- // Should always return the root container
141
- expect(result.current).toBe(container)
142
- })
143
- })
@@ -1,80 +0,0 @@
1
- import { Container, Injectable, Registry } from '@navios/di'
2
-
3
- import { act, render, screen, waitFor } from '@testing-library/react'
4
- import { createElement } from 'react'
5
- import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
6
-
7
- import { ContainerProvider } from '../../providers/container-provider.mjs'
8
- import { useInvalidateInstance } from '../use-invalidate.mjs'
9
- import { useService } from '../use-service.mjs'
10
-
11
- describe('useInvalidateInstance', () => {
12
- let container: Container
13
- let registry: Registry
14
-
15
- beforeEach(() => {
16
- registry = new Registry()
17
- container = new Container(registry)
18
- })
19
-
20
- afterEach(async () => {
21
- await container.dispose()
22
- vi.clearAllMocks()
23
- })
24
-
25
- const createWrapper = (children: React.ReactNode) =>
26
- createElement(ContainerProvider, { container, children })
27
-
28
- it('should invalidate a service instance directly', async () => {
29
- let instanceCount = 0
30
-
31
- @Injectable({ registry })
32
- class CounterService {
33
- public readonly id: number
34
-
35
- constructor() {
36
- instanceCount++
37
- this.id = instanceCount
38
- }
39
- }
40
-
41
- let invalidateInstanceFn: ((instance: unknown) => Promise<void>) | null =
42
- null
43
- let currentInstance: CounterService | undefined
44
-
45
- function TestComponent() {
46
- const { data, isSuccess } = useService(CounterService)
47
- const invalidateInstance = useInvalidateInstance()
48
- invalidateInstanceFn = invalidateInstance
49
- currentInstance = data
50
-
51
- if (!isSuccess) {
52
- return createElement('div', { 'data-testid': 'loading' }, 'Loading...')
53
- }
54
-
55
- return createElement(
56
- 'div',
57
- { 'data-testid': 'counter' },
58
- String(data!.id),
59
- )
60
- }
61
-
62
- render(createWrapper(createElement(TestComponent)))
63
-
64
- await waitFor(() => {
65
- expect(screen.getByTestId('counter')).toBeDefined()
66
- })
67
-
68
- expect(screen.getByTestId('counter').textContent).toBe('1')
69
-
70
- // Invalidate the instance directly
71
- await act(async () => {
72
- await invalidateInstanceFn!(currentInstance!)
73
- })
74
-
75
- // Wait for re-fetch
76
- await waitFor(() => {
77
- expect(screen.getByTestId('counter').textContent).toBe('2')
78
- })
79
- })
80
- })
@@ -1,233 +0,0 @@
1
- import { Container, Injectable, InjectionToken, Registry } from '@navios/di'
2
-
3
- import { render, screen, waitFor } from '@testing-library/react'
4
- import { createElement, useMemo } from 'react'
5
- import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
6
- import { z } from 'zod/v4'
7
-
8
- import { ContainerProvider } from '../../providers/container-provider.mjs'
9
- import { useOptionalService } from '../use-optional-service.mjs'
10
-
11
- describe('useOptionalService', () => {
12
- let container: Container
13
- let registry: Registry
14
-
15
- beforeEach(() => {
16
- registry = new Registry()
17
- container = new Container(registry)
18
- })
19
-
20
- afterEach(async () => {
21
- await container.dispose()
22
- vi.clearAllMocks()
23
- })
24
-
25
- const createWrapper = (children: React.ReactNode) =>
26
- createElement(ContainerProvider, { container, children })
27
-
28
- describe('when service is registered', () => {
29
- it('should load the service successfully', async () => {
30
- @Injectable({ registry })
31
- class TestService {
32
- getValue() {
33
- return 'test-value'
34
- }
35
- }
36
-
37
- function TestComponent() {
38
- const { data, isSuccess, isNotFound, isLoading } = useOptionalService(TestService)
39
-
40
- if (isLoading) {
41
- return createElement('div', { 'data-testid': 'loading' }, 'Loading...')
42
- }
43
-
44
- if (isNotFound) {
45
- return createElement('div', { 'data-testid': 'not-found' }, 'Not Found')
46
- }
47
-
48
- if (isSuccess) {
49
- return createElement('div', { 'data-testid': 'result' }, data!.getValue())
50
- }
51
-
52
- return createElement('div', { 'data-testid': 'idle' }, 'Idle')
53
- }
54
-
55
- render(createWrapper(createElement(TestComponent)))
56
-
57
- await waitFor(() => {
58
- expect(screen.getByTestId('result')).toBeDefined()
59
- })
60
-
61
- expect(screen.getByTestId('result').textContent).toBe('test-value')
62
- })
63
-
64
- it('should load service with injection token and args', async () => {
65
- const UserSchema = z.object({ userId: z.string() })
66
- const UserToken = InjectionToken.create<
67
- { userId: string; name: string },
68
- typeof UserSchema
69
- >('User', UserSchema)
70
-
71
- @Injectable({ registry, token: UserToken })
72
- class _UserService {
73
- public userId: string
74
- public name: string
75
-
76
- constructor(args: z.infer<typeof UserSchema>) {
77
- this.userId = args.userId
78
- this.name = `User ${args.userId}`
79
- }
80
- }
81
-
82
- function TestComponent() {
83
- const args = useMemo(() => ({ userId: '123' }), [])
84
- const { data, isSuccess, isNotFound } = useOptionalService(UserToken, args)
85
-
86
- if (isNotFound) {
87
- return createElement('div', { 'data-testid': 'not-found' }, 'Not Found')
88
- }
89
-
90
- if (isSuccess) {
91
- return createElement('div', { 'data-testid': 'result' }, data!.name)
92
- }
93
-
94
- return createElement('div', { 'data-testid': 'loading' }, 'Loading...')
95
- }
96
-
97
- render(createWrapper(createElement(TestComponent)))
98
-
99
- await waitFor(() => {
100
- expect(screen.getByTestId('result')).toBeDefined()
101
- })
102
-
103
- expect(screen.getByTestId('result').textContent).toBe('User 123')
104
- })
105
- })
106
-
107
- describe('when service is not registered', () => {
108
- it('should return isNotFound true for unregistered class token', async () => {
109
- // Create a class that is NOT registered with Injectable
110
- class UnregisteredService {
111
- getValue() {
112
- return 'value'
113
- }
114
- }
115
-
116
- function TestComponent() {
117
- const { isSuccess, isNotFound, isError, isLoading } =
118
- useOptionalService(UnregisteredService)
119
-
120
- if (isLoading) {
121
- return createElement('div', { 'data-testid': 'loading' }, 'Loading...')
122
- }
123
-
124
- if (isNotFound) {
125
- return createElement('div', { 'data-testid': 'not-found' }, 'Service Not Found')
126
- }
127
-
128
- if (isError) {
129
- return createElement('div', { 'data-testid': 'error' }, 'Error')
130
- }
131
-
132
- if (isSuccess) {
133
- return createElement('div', { 'data-testid': 'success' }, 'Success')
134
- }
135
-
136
- return createElement('div', { 'data-testid': 'idle' }, 'Idle')
137
- }
138
-
139
- render(createWrapper(createElement(TestComponent)))
140
-
141
- await waitFor(() => {
142
- const notFound = screen.queryByTestId('not-found')
143
- const error = screen.queryByTestId('error')
144
- // Either not-found or error is acceptable for unregistered services
145
- expect(notFound || error).toBeTruthy()
146
- })
147
- })
148
-
149
- it('should return isNotFound true for unregistered injection token', async () => {
150
- const UnregisteredToken = InjectionToken.create<{ value: string }>('Unregistered')
151
-
152
- function TestComponent() {
153
- const { isSuccess, isNotFound, isError, isLoading } =
154
- useOptionalService(UnregisteredToken)
155
-
156
- if (isLoading) {
157
- return createElement('div', { 'data-testid': 'loading' }, 'Loading...')
158
- }
159
-
160
- if (isNotFound) {
161
- return createElement('div', { 'data-testid': 'not-found' }, 'Token Not Found')
162
- }
163
-
164
- if (isError) {
165
- return createElement('div', { 'data-testid': 'error' }, 'Error')
166
- }
167
-
168
- if (isSuccess) {
169
- return createElement('div', { 'data-testid': 'success' }, 'Success')
170
- }
171
-
172
- return createElement('div', { 'data-testid': 'idle' }, 'Idle')
173
- }
174
-
175
- render(createWrapper(createElement(TestComponent)))
176
-
177
- await waitFor(() => {
178
- const notFound = screen.queryByTestId('not-found')
179
- const error = screen.queryByTestId('error')
180
- // Either not-found or error is acceptable for unregistered tokens
181
- expect(notFound || error).toBeTruthy()
182
- })
183
- })
184
- })
185
-
186
- describe('refetch functionality', () => {
187
- it('should allow manual refetch', async () => {
188
- let instanceCount = 0
189
-
190
- @Injectable({ registry })
191
- class CounterService {
192
- public readonly id: number
193
-
194
- constructor() {
195
- instanceCount++
196
- this.id = instanceCount
197
- }
198
- }
199
-
200
- let refetchFn: (() => void) | null = null
201
-
202
- function TestComponent() {
203
- const { data, isSuccess, refetch } = useOptionalService(CounterService)
204
- refetchFn = refetch
205
-
206
- if (!isSuccess) {
207
- return createElement('div', { 'data-testid': 'loading' }, 'Loading...')
208
- }
209
-
210
- return createElement('div', { 'data-testid': 'counter' }, String(data!.id))
211
- }
212
-
213
- render(createWrapper(createElement(TestComponent)))
214
-
215
- await waitFor(() => {
216
- expect(screen.getByTestId('counter')).toBeDefined()
217
- })
218
-
219
- expect(screen.getByTestId('counter').textContent).toBe('1')
220
-
221
- // Note: refetch alone won't create a new instance since the service is cached
222
- // It will return the same cached instance
223
- refetchFn!()
224
-
225
- await waitFor(() => {
226
- expect(screen.getByTestId('counter')).toBeDefined()
227
- })
228
-
229
- // Same instance because it's cached
230
- expect(screen.getByTestId('counter').textContent).toBe('1')
231
- })
232
- })
233
- })