@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
@@ -1,286 +0,0 @@
1
- import { Container, Injectable, InjectionToken, Registry } from '@navios/di'
2
-
3
- import { act, render, screen, waitFor } from '@testing-library/react'
4
- import { createElement, Suspense, 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 { useSuspenseService } from '../use-suspense-service.mjs'
10
-
11
- describe('useSuspenseService', () => {
12
- let container: Container
13
- let registry: Registry
14
-
15
- beforeEach(() => {
16
- registry = new Registry()
17
- container = new Container(registry)
18
- })
19
-
20
- afterEach(() => {
21
- vi.clearAllMocks()
22
- })
23
-
24
- const createWrapper = (children: React.ReactNode) =>
25
- createElement(ContainerProvider, { container, children })
26
-
27
- describe('with class tokens', () => {
28
- it('should suspend while loading and render data when resolved', async () => {
29
- @Injectable({ registry })
30
- class TestService {
31
- getValue() {
32
- return 'suspense-value'
33
- }
34
- }
35
-
36
- function TestComponent() {
37
- const service = useSuspenseService(TestService)
38
- return createElement(
39
- 'div',
40
- { 'data-testid': 'result' },
41
- service.getValue(),
42
- )
43
- }
44
-
45
- render(
46
- createWrapper(
47
- createElement(
48
- Suspense,
49
- {
50
- fallback: createElement(
51
- 'div',
52
- { 'data-testid': 'loading' },
53
- 'Loading...',
54
- ),
55
- },
56
- createElement(TestComponent),
57
- ),
58
- ),
59
- )
60
-
61
- // Should show loading initially
62
- expect(screen.getByTestId('loading')).toBeDefined()
63
-
64
- // Should show result after loading
65
- await waitFor(() => {
66
- expect(screen.getByTestId('result')).toBeDefined()
67
- })
68
-
69
- expect(screen.getByTestId('result').textContent).toBe('suspense-value')
70
- })
71
-
72
- // Skip error boundary test - causes memory issues in vitest
73
- // Error throwing behavior is implicitly tested by the suspense mechanism
74
- it.skip('should throw error to error boundary when service fails', async () => {
75
- // Test skipped
76
- })
77
- })
78
-
79
- describe('with injection tokens', () => {
80
- it('should load service with injection token', async () => {
81
- const ConfigToken = InjectionToken.create<{ apiUrl: string }>('Config')
82
-
83
- @Injectable({ registry, token: ConfigToken })
84
- class _ConfigService {
85
- apiUrl = 'https://api.example.com'
86
- }
87
-
88
- function TestComponent() {
89
- const config = useSuspenseService(ConfigToken)
90
- return createElement('div', { 'data-testid': 'url' }, config.apiUrl)
91
- }
92
-
93
- render(
94
- createWrapper(
95
- createElement(
96
- Suspense,
97
- {
98
- fallback: createElement(
99
- 'div',
100
- { 'data-testid': 'loading' },
101
- 'Loading...',
102
- ),
103
- },
104
- createElement(TestComponent),
105
- ),
106
- ),
107
- )
108
-
109
- await waitFor(() => {
110
- expect(screen.getByTestId('url')).toBeDefined()
111
- })
112
-
113
- expect(screen.getByTestId('url').textContent).toBe(
114
- 'https://api.example.com',
115
- )
116
- })
117
-
118
- it('should load service with injection token and args', async () => {
119
- const UserSchema = z.object({ userId: z.string() })
120
- const UserToken = InjectionToken.create<
121
- { userId: string; displayName: string },
122
- typeof UserSchema
123
- >('User', UserSchema)
124
-
125
- @Injectable({ registry, token: UserToken })
126
- class _UserService {
127
- public userId: string
128
- public displayName: string
129
-
130
- constructor(args: z.infer<typeof UserSchema>) {
131
- this.userId = args.userId
132
- this.displayName = `User #${args.userId}`
133
- }
134
- }
135
-
136
- function TestComponent() {
137
- const args = useMemo(() => ({ userId: '456' }), [])
138
- const user = useSuspenseService(UserToken, args)
139
- return createElement('div', { 'data-testid': 'user' }, user.displayName)
140
- }
141
-
142
- render(
143
- createWrapper(
144
- createElement(
145
- Suspense,
146
- {
147
- fallback: createElement(
148
- 'div',
149
- { 'data-testid': 'loading' },
150
- 'Loading...',
151
- ),
152
- },
153
- createElement(TestComponent),
154
- ),
155
- ),
156
- )
157
-
158
- await waitFor(() => {
159
- expect(screen.getByTestId('user')).toBeDefined()
160
- })
161
-
162
- expect(screen.getByTestId('user').textContent).toBe('User #456')
163
- })
164
- })
165
-
166
- describe('caching behavior', () => {
167
- it('should return cached instance on subsequent renders', async () => {
168
- let constructorCallCount = 0
169
-
170
- @Injectable({ registry })
171
- class CachedService {
172
- public instanceId: number
173
-
174
- constructor() {
175
- constructorCallCount++
176
- this.instanceId = constructorCallCount
177
- }
178
- }
179
-
180
- function TestComponent() {
181
- const service = useSuspenseService(CachedService)
182
- return createElement(
183
- 'div',
184
- { 'data-testid': 'id' },
185
- String(service.instanceId),
186
- )
187
- }
188
-
189
- const { rerender } = render(
190
- createWrapper(
191
- createElement(
192
- Suspense,
193
- { fallback: createElement('div', null, 'Loading...') },
194
- createElement(TestComponent),
195
- ),
196
- ),
197
- )
198
-
199
- await waitFor(() => {
200
- expect(screen.getByTestId('id')).toBeDefined()
201
- })
202
-
203
- expect(screen.getByTestId('id').textContent).toBe('1')
204
-
205
- // Re-render the component
206
- rerender(
207
- createWrapper(
208
- createElement(
209
- Suspense,
210
- { fallback: createElement('div', null, 'Loading...') },
211
- createElement(TestComponent),
212
- ),
213
- ),
214
- )
215
-
216
- // Should still have the same instance (cached)
217
- expect(screen.getByTestId('id').textContent).toBe('1')
218
- expect(constructorCallCount).toBe(1)
219
- })
220
- })
221
-
222
- describe('service invalidation', () => {
223
- // Skip this test - invalidation with suspense cache is complex to test
224
- // The functionality is tested in useService tests
225
- it('should re-fetch when service is invalidated', async () => {
226
- let instanceCount = 0
227
-
228
- @Injectable({ registry })
229
- class InvalidatableService {
230
- public instanceId: number
231
-
232
- constructor() {
233
- instanceCount++
234
- this.instanceId = instanceCount
235
- }
236
-
237
- getId() {
238
- return this.instanceId
239
- }
240
- }
241
-
242
- function TestComponent() {
243
- const service = useSuspenseService(InvalidatableService)
244
- return createElement('div', { 'data-testid': 'instance-id' }, [
245
- String(service.getId()),
246
- ])
247
- }
248
-
249
- render(
250
- createWrapper(
251
- createElement(
252
- Suspense,
253
- {
254
- fallback: createElement(
255
- 'div',
256
- { 'data-testid': 'loading' },
257
- 'Loading...',
258
- ),
259
- },
260
- createElement(TestComponent),
261
- ),
262
- ),
263
- )
264
-
265
- await waitFor(() => {
266
- expect(screen.getByTestId('instance-id')).toBeDefined()
267
- })
268
-
269
- expect(screen.getByTestId('instance-id').textContent).toBe('1')
270
-
271
- // Get the current instance and invalidate it
272
- const currentInstance = await container.get(InvalidatableService)
273
- await act(async () => {
274
- await container.invalidate(currentInstance)
275
- })
276
-
277
- // Wait for re-fetch
278
- await waitFor(
279
- () => {
280
- expect(screen.getByTestId('instance-id').textContent).toBe('2')
281
- },
282
- { timeout: 2000 },
283
- )
284
- })
285
- })
286
- })
@@ -1,14 +0,0 @@
1
- export { useContainer, useRootContainer } from './use-container.mjs'
2
- export { useService } from './use-service.mjs'
3
- export type { UseServiceResult } from './use-service.mjs'
4
- export { useSuspenseService } from './use-suspense-service.mjs'
5
- export { useOptionalService } from './use-optional-service.mjs'
6
- export type { UseOptionalServiceResult } from './use-optional-service.mjs'
7
- export { useInvalidateInstance } from './use-invalidate.mjs'
8
- export {
9
- useScope,
10
- useScopeOrThrow,
11
- useScopedContainer,
12
- useScopedContainerOrThrow,
13
- useScopeMetadata,
14
- } from './use-scope.mjs'
@@ -1,61 +0,0 @@
1
- import type { Container, ScopedContainer } from '@navios/di'
2
-
3
- import { useContext } from 'react'
4
-
5
- import {
6
- ContainerContext,
7
- ScopedContainerContext,
8
- } from '../providers/context.mjs'
9
-
10
- /**
11
- * Hook to get the current container (ScopedContainer if inside ScopeProvider, otherwise Container).
12
- *
13
- * This is the primary hook for accessing the DI container. It automatically
14
- * returns the correct container based on context:
15
- * - Inside a ScopeProvider: returns the ScopedContainer for request-scoped services
16
- * - Outside a ScopeProvider: returns the root Container
17
- *
18
- * @returns The current container (ScopedContainer or Container)
19
- */
20
- export function useContainer(): Container | ScopedContainer {
21
- const scopedContainer = useContext(ScopedContainerContext)
22
- const container = useContext(ContainerContext)
23
-
24
- // Prefer scoped container if available (we're inside a ScopeProvider)
25
- if (scopedContainer) {
26
- return scopedContainer
27
- }
28
-
29
- if (!container) {
30
- throw new Error('useContainer must be used within a ContainerProvider')
31
- }
32
-
33
- return container
34
- }
35
-
36
- /**
37
- * Hook to get the root Container, regardless of whether we're inside a ScopeProvider.
38
- *
39
- * Use this when you need access to the root container specifically,
40
- * for example to create new request scopes programmatically.
41
- *
42
- * @returns The root Container
43
- */
44
- export function useRootContainer(): Container {
45
- const container = useContext(ContainerContext)
46
-
47
- if (!container) {
48
- throw new Error('useRootContainer must be used within a ContainerProvider')
49
- }
50
-
51
- return container
52
- }
53
-
54
- /**
55
- * Hook to get the current ScopedContainer if inside a ScopeProvider.
56
- *
57
- * @returns The ScopedContainer or null if not inside a ScopeProvider
58
- */
59
- export function useScopedContainer(): ScopedContainer | null {
60
- return useContext(ScopedContainerContext)
61
- }
@@ -1,41 +0,0 @@
1
- import { useCallback } from 'react'
2
-
3
- import { useContainer } from './use-container.mjs'
4
-
5
- /**
6
- * Hook that returns a function to invalidate a service instance directly.
7
- *
8
- * This is useful when you have the service instance and want to invalidate it
9
- * without knowing its token.
10
- *
11
- * @example
12
- * ```tsx
13
- * function UserProfile() {
14
- * const { data: user } = useService(UserService)
15
- * const invalidateInstance = useInvalidateInstance()
16
- *
17
- * const handleRefresh = () => {
18
- * if (user) {
19
- * invalidateInstance(user)
20
- * }
21
- * }
22
- *
23
- * return (
24
- * <div>
25
- * <span>{user?.name}</span>
26
- * <button onClick={handleRefresh}>Refresh</button>
27
- * </div>
28
- * )
29
- * }
30
- * ```
31
- */
32
- export function useInvalidateInstance(): (instance: unknown) => Promise<void> {
33
- const container = useContainer()
34
-
35
- return useCallback(
36
- async (instance: unknown) => {
37
- await container.invalidate(instance)
38
- },
39
- [container],
40
- )
41
- }
@@ -1,276 +0,0 @@
1
- import type {
2
- AnyInjectableType,
3
- BoundInjectionToken,
4
- ClassType,
5
- Factorable,
6
- FactoryInjectionToken,
7
- InjectionToken,
8
- InjectionTokenSchemaType,
9
- } from '@navios/di'
10
- import type { z, ZodType } from 'zod/v4'
11
-
12
- import { useCallback, useEffect, useReducer, useRef } from 'react'
13
-
14
- import type { Join, UnionToArray } from '../types.mjs'
15
-
16
- import { useContainer, useRootContainer } from './use-container.mjs'
17
-
18
- type OptionalServiceState<T> =
19
- | { status: 'idle' }
20
- | { status: 'loading' }
21
- | { status: 'success'; data: T }
22
- | { status: 'not-found' }
23
- | { status: 'error'; error: Error }
24
-
25
- type OptionalServiceAction<T> =
26
- | { type: 'loading' }
27
- | { type: 'success'; data: T }
28
- | { type: 'not-found' }
29
- | { type: 'error'; error: Error }
30
- | { type: 'reset' }
31
-
32
- function optionalServiceReducer<T>(
33
- state: OptionalServiceState<T>,
34
- action: OptionalServiceAction<T>,
35
- ): OptionalServiceState<T> {
36
- switch (action.type) {
37
- case 'loading':
38
- return { status: 'loading' }
39
- case 'success':
40
- return { status: 'success', data: action.data }
41
- case 'not-found':
42
- return { status: 'not-found' }
43
- case 'error':
44
- return { status: 'error', error: action.error }
45
- case 'reset':
46
- return { status: 'idle' }
47
- default:
48
- return state
49
- }
50
- }
51
-
52
- export interface UseOptionalServiceResult<T> {
53
- /**
54
- * The service instance if found and loaded successfully, otherwise undefined.
55
- */
56
- data: T | undefined
57
- /**
58
- * Error that occurred during loading (excludes "not found" which is not an error).
59
- */
60
- error: Error | undefined
61
- /**
62
- * True while the service is being loaded.
63
- */
64
- isLoading: boolean
65
- /**
66
- * True if the service was loaded successfully.
67
- */
68
- isSuccess: boolean
69
- /**
70
- * True if the service was not found (not registered in the container).
71
- */
72
- isNotFound: boolean
73
- /**
74
- * True if an error occurred during loading.
75
- */
76
- isError: boolean
77
- /**
78
- * Function to manually re-fetch the service.
79
- */
80
- refetch: () => void
81
- }
82
-
83
- // #1 Simple class
84
- export function useOptionalService<T extends ClassType>(
85
- token: T,
86
- ): UseOptionalServiceResult<
87
- InstanceType<T> extends Factorable<infer R> ? R : InstanceType<T>
88
- >
89
-
90
- // #2 Token with required Schema
91
- export function useOptionalService<T, S extends InjectionTokenSchemaType>(
92
- token: InjectionToken<T, S>,
93
- args: z.input<S>,
94
- ): UseOptionalServiceResult<T>
95
-
96
- // #3 Token with optional Schema
97
- export function useOptionalService<
98
- T,
99
- S extends InjectionTokenSchemaType,
100
- R extends boolean,
101
- >(
102
- token: InjectionToken<T, S, R>,
103
- ): R extends false
104
- ? UseOptionalServiceResult<T>
105
- : S extends ZodType<infer Type>
106
- ? `Error: Your token requires args: ${Join<UnionToArray<keyof Type>, ', '>}`
107
- : 'Error: Your token requires args'
108
-
109
- // #4 Token with no Schema
110
- export function useOptionalService<T>(
111
- token: InjectionToken<T, undefined>,
112
- ): UseOptionalServiceResult<T>
113
-
114
- export function useOptionalService<T>(
115
- token: BoundInjectionToken<T, any>,
116
- ): UseOptionalServiceResult<T>
117
-
118
- export function useOptionalService<T>(
119
- token: FactoryInjectionToken<T, any>,
120
- ): UseOptionalServiceResult<T>
121
-
122
- /**
123
- * Hook to optionally load a service from the DI container.
124
- *
125
- * Unlike useService, this hook does NOT throw an error if the service is not registered.
126
- * Instead, it returns `isNotFound: true` when the service doesn't exist.
127
- *
128
- * This is useful for:
129
- * - Optional dependencies that may or may not be configured
130
- * - Feature flags where a service might not be available
131
- * - Plugins or extensions that are conditionally registered
132
- *
133
- * @example
134
- * ```tsx
135
- * function Analytics() {
136
- * const { data: analytics, isNotFound } = useOptionalService(AnalyticsService)
137
- *
138
- * if (isNotFound) {
139
- * // Analytics service not configured, skip tracking
140
- * return null
141
- * }
142
- *
143
- * return <AnalyticsTracker service={analytics} />
144
- * }
145
- * ```
146
- */
147
- export function useOptionalService(
148
- token:
149
- | ClassType
150
- | InjectionToken<any, any>
151
- | BoundInjectionToken<any, any>
152
- | FactoryInjectionToken<any, any>,
153
- args?: unknown,
154
- ): UseOptionalServiceResult<any> {
155
- // useContainer returns ScopedContainer if inside ScopeProvider, otherwise Container
156
- const container = useContainer()
157
- const rootContainer = useRootContainer()
158
-
159
- // Try to get the instance synchronously first for better performance
160
- // This avoids the async loading state when the instance is already cached
161
- // We use a ref to track this so it doesn't cause effect re-runs
162
- const initialSyncInstanceRef = useRef<any>(undefined)
163
- const isFirstRenderRef = useRef(true)
164
-
165
- if (isFirstRenderRef.current) {
166
- try {
167
- initialSyncInstanceRef.current = container.tryGetSync(token, args)
168
- } catch {
169
- // Service not registered, leave as undefined
170
- }
171
- isFirstRenderRef.current = false
172
- }
173
-
174
- const initialState: OptionalServiceState<any> = initialSyncInstanceRef.current
175
- ? { status: 'success', data: initialSyncInstanceRef.current }
176
- : { status: 'idle' }
177
-
178
- const [state, dispatch] = useReducer(optionalServiceReducer, initialState)
179
- const instanceNameRef = useRef<string | null>(null)
180
-
181
- if (process.env.NODE_ENV === 'development') {
182
- const argsRef = useRef<unknown>(args)
183
- useEffect(() => {
184
- if (argsRef.current !== args) {
185
- if (JSON.stringify(argsRef.current) === JSON.stringify(args)) {
186
- console.log(`WARNING: useOptionalService called with args that look the same but are different instances: ${JSON.stringify(argsRef.current)} !== ${JSON.stringify(args)}!
187
- This is likely because you are using not memoized value that is not stable.
188
- Please use a memoized value or use a different approach to pass the args.
189
- Example:
190
- const args = useMemo(() => ({ userId: '123' }), [])
191
- return useOptionalService(UserToken, args)
192
- `)
193
- }
194
- argsRef.current = args
195
- }
196
- }, [args])
197
- }
198
-
199
- const fetchService = useCallback(async () => {
200
- dispatch({ type: 'loading' })
201
- try {
202
- // Use the container (ScopedContainer or Container) for resolution
203
- const instance = await container.get(
204
- // @ts-expect-error - token is valid
205
- token as AnyInjectableType,
206
- args as any,
207
- )
208
- // Get instance name for event subscription
209
- const instanceName = container.calculateInstanceName(token, args)
210
- if (instanceName) {
211
- instanceNameRef.current = instanceName
212
- }
213
- dispatch({ type: 'success', data: instance })
214
- } catch (error) {
215
- // Caught exceptions are treated as errors
216
- const err = error as Error
217
- const errorMessage = err.message?.toLowerCase() ?? ''
218
- if (
219
- errorMessage.includes('not found') ||
220
- errorMessage.includes('not registered') ||
221
- errorMessage.includes('no provider')
222
- ) {
223
- dispatch({ type: 'not-found' })
224
- } else {
225
- dispatch({ type: 'error', error: err })
226
- }
227
- }
228
- }, [container, token, args])
229
-
230
- // Subscribe to invalidation events
231
- useEffect(() => {
232
- const eventBus = rootContainer.getEventBus()
233
- let unsubscribe: (() => void) | undefined
234
-
235
- // If we already have a sync instance from initial render, just set up subscription
236
- // Otherwise, fetch async
237
- const syncInstance = initialSyncInstanceRef.current
238
- if (syncInstance) {
239
- const instanceName = container.calculateInstanceName(token, args)
240
- if (instanceName) {
241
- instanceNameRef.current = instanceName
242
- unsubscribe = eventBus.on(instanceName, 'destroy', () => {
243
- // Re-fetch when the service is invalidated
244
- void fetchService()
245
- })
246
- }
247
- } else {
248
- void fetchService().then(() => {
249
- if (instanceNameRef.current) {
250
- unsubscribe = eventBus.on(instanceNameRef.current, 'destroy', () => {
251
- // Re-fetch when the service is invalidated
252
- void fetchService()
253
- })
254
- }
255
- })
256
-
257
- return () => {
258
- unsubscribe?.()
259
- }
260
- }
261
-
262
- return () => {
263
- unsubscribe?.()
264
- }
265
- }, [fetchService, rootContainer, token, args])
266
-
267
- return {
268
- data: state.status === 'success' ? state.data : undefined,
269
- error: state.status === 'error' ? state.error : undefined,
270
- isLoading: state.status === 'loading',
271
- isSuccess: state.status === 'success',
272
- isNotFound: state.status === 'not-found',
273
- isError: state.status === 'error',
274
- refetch: fetchService,
275
- }
276
- }