@navios/di-react 1.0.0-alpha.3 → 2.0.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +47 -1
- package/README.md +45 -665
- package/lib/index.cjs +573 -0
- package/lib/index.cjs.map +1 -0
- package/lib/index.d.cts +262 -0
- package/lib/index.d.cts.map +1 -0
- package/lib/index.d.mts +159 -140
- package/lib/index.d.mts.map +1 -1
- package/lib/index.mjs +371 -381
- package/lib/index.mjs.map +1 -1
- package/package.json +32 -18
- package/coverage/base.css +0 -224
- package/coverage/block-navigation.js +0 -87
- package/coverage/clover.xml +0 -270
- package/coverage/coverage-final.json +0 -10
- package/coverage/favicon.png +0 -0
- package/coverage/hooks/index.html +0 -191
- package/coverage/hooks/use-container.mts.html +0 -268
- package/coverage/hooks/use-invalidate.mts.html +0 -208
- package/coverage/hooks/use-optional-service.mts.html +0 -910
- package/coverage/hooks/use-scope.mts.html +0 -346
- package/coverage/hooks/use-service.mts.html +0 -760
- package/coverage/hooks/use-suspense-service.mts.html +0 -784
- package/coverage/index.html +0 -131
- package/coverage/prettify.css +0 -1
- package/coverage/prettify.js +0 -2
- package/coverage/providers/container-provider.mts.html +0 -139
- package/coverage/providers/context.mts.html +0 -130
- package/coverage/providers/index.html +0 -146
- package/coverage/providers/scope-provider.mts.html +0 -355
- package/coverage/sort-arrow-sprite.png +0 -0
- package/coverage/sorter.js +0 -210
- package/lib/index.d.ts +0 -243
- package/lib/index.d.ts.map +0 -1
- package/lib/index.js +0 -582
- package/lib/index.js.map +0 -1
- package/project.json +0 -61
- package/src/hooks/__tests__/use-container.spec.mts +0 -143
- package/src/hooks/__tests__/use-invalidate.spec.mts +0 -80
- package/src/hooks/__tests__/use-optional-service.spec.mts +0 -233
- package/src/hooks/__tests__/use-scope.spec.mts +0 -293
- package/src/hooks/__tests__/use-service.spec.mts +0 -212
- package/src/hooks/__tests__/use-suspense-service.spec.mts +0 -286
- package/src/hooks/index.mts +0 -14
- package/src/hooks/use-container.mts +0 -61
- package/src/hooks/use-invalidate.mts +0 -41
- package/src/hooks/use-optional-service.mts +0 -275
- package/src/hooks/use-scope.mts +0 -87
- package/src/hooks/use-service.mts +0 -225
- package/src/hooks/use-suspense-service.mts +0 -233
- package/src/index.mts +0 -8
- package/src/providers/__tests__/scope-provider.spec.mts +0 -366
- package/src/providers/container-provider.mts +0 -18
- package/src/providers/context.mts +0 -15
- package/src/providers/index.mts +0 -5
- package/src/providers/scope-provider.mts +0 -90
- package/src/types.mts +0 -21
- package/tsconfig.json +0 -13
- package/tsdown.config.mts +0 -14
- 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
|
-
|
|
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
|
-
|
|
26
|
-
|
|
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,157 +79,240 @@ function ScopeProvider({ scopeId, metadata, children }) {
|
|
|
52
79
|
const generatedId = useId();
|
|
53
80
|
const effectiveScopeId = scopeId ?? generatedId;
|
|
54
81
|
const scopedContainerRef = useRef(null);
|
|
55
|
-
|
|
56
|
-
|
|
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
|
-
|
|
93
|
+
isMountedRef.current = true;
|
|
94
|
+
if (isDisposedRef.current) {
|
|
95
|
+
isDisposedRef.current = false;
|
|
96
|
+
scopedContainerRef.current = createScopeRef.current();
|
|
97
|
+
rerender();
|
|
98
|
+
}
|
|
60
99
|
return () => {
|
|
61
|
-
|
|
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
|
|
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
|
-
*
|
|
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
|
-
* @
|
|
136
|
+
* @example
|
|
137
|
+
* ```tsx
|
|
138
|
+
* function TableRow() {
|
|
139
|
+
* const scope = useScopedContainer()
|
|
140
|
+
* const rowData = scope?.getMetadata('rowData')
|
|
141
|
+
* // ...
|
|
142
|
+
* }
|
|
143
|
+
* ```
|
|
82
144
|
*/
|
|
83
|
-
function
|
|
84
|
-
|
|
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
|
|
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
|
-
*
|
|
94
|
-
*
|
|
161
|
+
* @example
|
|
162
|
+
* ```tsx
|
|
163
|
+
* // In parent component:
|
|
164
|
+
* <ScopeProvider metadata={{ userId: '123', theme: 'dark' }}>
|
|
165
|
+
* <ChildComponent />
|
|
166
|
+
* </ScopeProvider>
|
|
95
167
|
*
|
|
96
|
-
*
|
|
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
|
|
99
|
-
|
|
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
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
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}`;
|
|
119
206
|
}
|
|
120
207
|
}
|
|
121
|
-
|
|
208
|
+
// src/service/use-resolved-service.mts
|
|
209
|
+
const LOADING = { status: "loading" };
|
|
210
|
+
const NOT_FOUND = { status: "not-found" };
|
|
211
|
+
/** Whether `error` says that `token` itself has no provider. */
|
|
212
|
+
function isMissingProvider(container, token, error) {
|
|
213
|
+
return error instanceof DIError && error.code === DIErrorCode.ProviderNotFound && !container.isRegistered(token);
|
|
214
|
+
}
|
|
215
|
+
/** What the container holds for `token` and `args` now, or `null`. */
|
|
216
|
+
function peekInstance(container, token, args) {
|
|
217
|
+
try {
|
|
218
|
+
return container.peek(token, args);
|
|
219
|
+
} catch {
|
|
220
|
+
return null;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Resolution behind `useService` and `useOptionalService`. With `optional`,
|
|
225
|
+
* a token without a provider ends in `not-found` instead of `error`.
|
|
226
|
+
*/
|
|
227
|
+
function useResolvedService(token, args, { optional }) {
|
|
122
228
|
const container = useContainer();
|
|
123
|
-
const
|
|
124
|
-
const
|
|
125
|
-
const
|
|
126
|
-
if (
|
|
127
|
-
|
|
128
|
-
|
|
229
|
+
const argsKey = getArgsKey(args);
|
|
230
|
+
const stableArgs = useMemo(() => args, [argsKey]);
|
|
231
|
+
const initialSyncRef = useRef(void 0);
|
|
232
|
+
if (initialSyncRef.current === void 0) {
|
|
233
|
+
const instance = peekInstance(container, token, args);
|
|
234
|
+
initialSyncRef.current = instance === null ? null : {
|
|
235
|
+
container,
|
|
236
|
+
token,
|
|
237
|
+
argsKey,
|
|
238
|
+
instance
|
|
239
|
+
};
|
|
129
240
|
}
|
|
130
|
-
const [state,
|
|
241
|
+
const [state, setState] = useState(() => initialSyncRef.current ? {
|
|
131
242
|
status: "success",
|
|
132
|
-
data:
|
|
133
|
-
} :
|
|
134
|
-
const
|
|
135
|
-
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.warn(`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 a value that is not memoized.
|
|
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
|
-
argsRef.current = args;
|
|
147
|
-
}
|
|
148
|
-
}, [args]);
|
|
149
|
-
}
|
|
243
|
+
data: initialSyncRef.current.instance
|
|
244
|
+
} : LOADING);
|
|
245
|
+
const [refetchCount, setRefetchCount] = useState(0);
|
|
150
246
|
useEffect(() => {
|
|
151
|
-
|
|
247
|
+
let isCurrent = true;
|
|
152
248
|
let unsubscribe;
|
|
153
|
-
let
|
|
154
|
-
const
|
|
249
|
+
let latest = 0;
|
|
250
|
+
const subscribe = () => {
|
|
251
|
+
if (unsubscribe) return;
|
|
252
|
+
unsubscribe = container.onInvalidate(token, stableArgs, () => {
|
|
253
|
+
if (!isCurrent) return;
|
|
254
|
+
latest++;
|
|
255
|
+
setState(LOADING);
|
|
256
|
+
queueMicrotask(() => {
|
|
257
|
+
if (isCurrent) resolve();
|
|
258
|
+
});
|
|
259
|
+
});
|
|
260
|
+
};
|
|
261
|
+
const resolve = async () => {
|
|
262
|
+
const run = ++latest;
|
|
263
|
+
try {
|
|
264
|
+
subscribe();
|
|
265
|
+
} catch {}
|
|
155
266
|
try {
|
|
156
|
-
const instance = await container.get(token,
|
|
157
|
-
if (!
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
dispatch({
|
|
161
|
-
type: "success",
|
|
267
|
+
const instance = await container.get(token, stableArgs);
|
|
268
|
+
if (!isCurrent || run !== latest) return;
|
|
269
|
+
setState({
|
|
270
|
+
status: "success",
|
|
162
271
|
data: instance
|
|
163
272
|
});
|
|
164
|
-
|
|
165
|
-
if (isMounted) {
|
|
166
|
-
dispatch({ type: "loading" });
|
|
167
|
-
fetchAndSubscribe();
|
|
168
|
-
}
|
|
169
|
-
});
|
|
273
|
+
subscribe();
|
|
170
274
|
} catch (error) {
|
|
171
|
-
if (
|
|
172
|
-
|
|
275
|
+
if (!isCurrent || run !== latest) return;
|
|
276
|
+
setState(optional && isMissingProvider(container, token, error) ? NOT_FOUND : {
|
|
277
|
+
status: "error",
|
|
173
278
|
error
|
|
174
279
|
});
|
|
175
280
|
}
|
|
176
281
|
};
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
fetchAndSubscribe();
|
|
185
|
-
}
|
|
186
|
-
});
|
|
282
|
+
const initial = initialSyncRef.current;
|
|
283
|
+
if (initial && initial.container === container && initial.token === token && initial.argsKey === argsKey && refetchCount === 0) {
|
|
284
|
+
subscribe();
|
|
285
|
+
if (peekInstance(container, token, stableArgs) !== initial.instance) {
|
|
286
|
+
initialSyncRef.current = null;
|
|
287
|
+
setState(LOADING);
|
|
288
|
+
resolve();
|
|
187
289
|
}
|
|
188
290
|
} else {
|
|
189
|
-
|
|
190
|
-
|
|
291
|
+
initialSyncRef.current = null;
|
|
292
|
+
setState(LOADING);
|
|
293
|
+
resolve();
|
|
191
294
|
}
|
|
192
295
|
return () => {
|
|
193
|
-
|
|
296
|
+
isCurrent = false;
|
|
194
297
|
unsubscribe?.();
|
|
195
298
|
};
|
|
196
299
|
}, [
|
|
197
300
|
container,
|
|
198
|
-
rootContainer,
|
|
199
301
|
token,
|
|
200
|
-
|
|
201
|
-
|
|
302
|
+
stableArgs,
|
|
303
|
+
argsKey,
|
|
304
|
+
refetchCount,
|
|
305
|
+
optional
|
|
202
306
|
]);
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
307
|
+
return {
|
|
308
|
+
state,
|
|
309
|
+
refetch: useCallback(() => {
|
|
310
|
+
setRefetchCount((count) => count + 1);
|
|
311
|
+
}, [])
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
/** The result object of `useService` for a state. */
|
|
315
|
+
function serviceResult(state, refetch) {
|
|
206
316
|
return {
|
|
207
317
|
data: state.status === "success" ? state.data : void 0,
|
|
208
318
|
error: state.status === "error" ? state.error : void 0,
|
|
@@ -212,28 +322,76 @@ Example:
|
|
|
212
322
|
refetch
|
|
213
323
|
};
|
|
214
324
|
}
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
325
|
+
// src/service/use-service.mts
|
|
326
|
+
/**
|
|
327
|
+
* Hook to load a service from the DI container, with its loading and error
|
|
328
|
+
* state. Resolves again when the instance is invalidated.
|
|
329
|
+
*
|
|
330
|
+
* @example
|
|
331
|
+
* ```tsx
|
|
332
|
+
* function UserCard() {
|
|
333
|
+
* const { data: users, error } = useService(UserService)
|
|
334
|
+
*
|
|
335
|
+
* if (error) return <p>{error.message}</p>
|
|
336
|
+
* if (!users) return <p>Loading…</p>
|
|
337
|
+
*
|
|
338
|
+
* return <UserList users={users} />
|
|
339
|
+
* }
|
|
340
|
+
* ```
|
|
341
|
+
*/
|
|
342
|
+
const useService = function useService(token, args) {
|
|
343
|
+
const { state, refetch } = useResolvedService(token, args, { optional: false });
|
|
344
|
+
return serviceResult(state, refetch);
|
|
345
|
+
};
|
|
346
|
+
// src/service/use-suspense-service.mts
|
|
218
347
|
const cacheMap = /* @__PURE__ */ new WeakMap();
|
|
219
|
-
function
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
348
|
+
function getCache(container, token) {
|
|
349
|
+
let byToken = cacheMap.get(container);
|
|
350
|
+
if (!byToken) {
|
|
351
|
+
byToken = /* @__PURE__ */ new WeakMap();
|
|
352
|
+
cacheMap.set(container, byToken);
|
|
353
|
+
}
|
|
354
|
+
let cache = byToken.get(token);
|
|
224
355
|
if (!cache) {
|
|
225
356
|
cache = /* @__PURE__ */ new Map();
|
|
226
|
-
|
|
357
|
+
byToken.set(token, cache);
|
|
227
358
|
}
|
|
228
359
|
return cache;
|
|
229
360
|
}
|
|
230
361
|
/**
|
|
362
|
+
* The cache entry for `key`, created on first use. An instance the container
|
|
363
|
+
* already holds makes it resolved, so the first render does not suspend. The
|
|
364
|
+
* entry listens for the invalidation of that instance from the start: an
|
|
365
|
+
* effect would subscribe after the render, and miss one in between.
|
|
366
|
+
*/
|
|
367
|
+
function getEntry(cache, key, container, token, args) {
|
|
368
|
+
let entry = cache.get(key);
|
|
369
|
+
if (!entry) {
|
|
370
|
+
const syncInstance = container.peek(token, args);
|
|
371
|
+
entry = {
|
|
372
|
+
promise: null,
|
|
373
|
+
result: syncInstance !== null ? syncInstance : void 0,
|
|
374
|
+
error: void 0,
|
|
375
|
+
status: syncInstance !== null ? "resolved" : "pending",
|
|
376
|
+
version: 0,
|
|
377
|
+
subscribers: /* @__PURE__ */ new Set(),
|
|
378
|
+
unsubscribe: void 0,
|
|
379
|
+
eviction: void 0,
|
|
380
|
+
release: void 0,
|
|
381
|
+
renders: 0
|
|
382
|
+
};
|
|
383
|
+
cache.set(key, entry);
|
|
384
|
+
if (syncInstance !== null) setupInvalidationSubscription(entry, container, token, args);
|
|
385
|
+
}
|
|
386
|
+
return entry;
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
231
389
|
* Sets up invalidation subscription for a cache entry if not already subscribed.
|
|
232
390
|
* When the service is destroyed, clears the cache and notifies subscribers.
|
|
233
391
|
*/
|
|
234
|
-
function setupInvalidationSubscription(entry,
|
|
235
|
-
if (entry.unsubscribe
|
|
236
|
-
entry.unsubscribe =
|
|
392
|
+
function setupInvalidationSubscription(entry, container, token, args) {
|
|
393
|
+
if (entry.unsubscribe) return;
|
|
394
|
+
entry.unsubscribe = container.onInvalidate(token, args, () => {
|
|
237
395
|
entry.result = void 0;
|
|
238
396
|
entry.error = void 0;
|
|
239
397
|
entry.status = "pending";
|
|
@@ -241,109 +399,99 @@ function setupInvalidationSubscription(entry, rootContainer) {
|
|
|
241
399
|
entry.subscribers.forEach((callback) => callback());
|
|
242
400
|
});
|
|
243
401
|
}
|
|
244
|
-
function
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
402
|
+
function fetchService(entry, container, token, args) {
|
|
403
|
+
entry.status = "pending";
|
|
404
|
+
entry.version++;
|
|
405
|
+
entry.promise = container.get(token, args).then((instance) => {
|
|
406
|
+
entry.result = instance;
|
|
407
|
+
entry.status = "resolved";
|
|
408
|
+
setupInvalidationSubscription(entry, container, token, args);
|
|
409
|
+
entry.subscribers.forEach((callback) => callback());
|
|
410
|
+
return instance;
|
|
411
|
+
}).catch((error) => {
|
|
412
|
+
entry.error = error;
|
|
413
|
+
entry.status = "rejected";
|
|
414
|
+
throw error;
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
/**
|
|
418
|
+
* Drops a rejected entry two timer turns after the last render that threw its
|
|
419
|
+
* error. Every render until then throws the error again: React renders a
|
|
420
|
+
* failed component a second time before it shows the error boundary, and when
|
|
421
|
+
* the first of those renders used up its time slice, the second one runs in a
|
|
422
|
+
* later task. That task is queued before the second timer is, so it still
|
|
423
|
+
* finds the entry; with one turn it found the cache empty and resolved the
|
|
424
|
+
* service again. The next render after that, such as the one of an error
|
|
425
|
+
* boundary reset, resolves the service again.
|
|
426
|
+
*/
|
|
427
|
+
function evictAfterRender(cache, key, entry) {
|
|
428
|
+
clearTimeout(entry.eviction);
|
|
429
|
+
entry.eviction = setTimeout(() => {
|
|
430
|
+
entry.eviction = setTimeout(() => {
|
|
431
|
+
if (cache.get(key) === entry && entry.status === "rejected") {
|
|
432
|
+
cache.delete(key);
|
|
433
|
+
entry.unsubscribe?.();
|
|
261
434
|
}
|
|
262
|
-
},
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
currentEntry.error = error;
|
|
294
|
-
currentEntry.status = "rejected";
|
|
295
|
-
throw error;
|
|
296
|
-
});
|
|
297
|
-
return currentEntry.promise;
|
|
298
|
-
}, [
|
|
299
|
-
container,
|
|
300
|
-
rootContainer,
|
|
301
|
-
token,
|
|
302
|
-
args
|
|
303
|
-
]);
|
|
435
|
+
}, 0);
|
|
436
|
+
}, 0);
|
|
437
|
+
}
|
|
438
|
+
/**
|
|
439
|
+
* Drops a resolved entry, and its invalidation listener, one timer turn after
|
|
440
|
+
* its last subscriber left, unless a component subscribed or rendered with it
|
|
441
|
+
* in the meantime. A component that shows the service later reads the instance
|
|
442
|
+
* from the container again.
|
|
443
|
+
*/
|
|
444
|
+
function releaseWhenUnused(cache, key, entry) {
|
|
445
|
+
clearTimeout(entry.release);
|
|
446
|
+
const renders = entry.renders;
|
|
447
|
+
entry.release = setTimeout(() => {
|
|
448
|
+
if (cache.get(key) === entry && entry.status === "resolved" && entry.subscribers.size === 0 && entry.renders === renders) {
|
|
449
|
+
cache.delete(key);
|
|
450
|
+
entry.unsubscribe?.();
|
|
451
|
+
entry.unsubscribe = void 0;
|
|
452
|
+
}
|
|
453
|
+
}, 0);
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Hook that returns a service from the DI container and suspends while it is
|
|
457
|
+
* resolved. A failed resolution is thrown to the nearest error boundary.
|
|
458
|
+
* Resolves again, suspending, when the instance is invalidated.
|
|
459
|
+
*/
|
|
460
|
+
const useSuspenseService = function useSuspenseService(token, args) {
|
|
461
|
+
const container = useContainer();
|
|
462
|
+
const cache = getCache(container, token);
|
|
463
|
+
const cacheKey = getArgsKey(args);
|
|
464
|
+
const entry = getEntry(cache, cacheKey, container, token, args);
|
|
465
|
+
entry.renders++;
|
|
304
466
|
const subscribe = useCallback((callback) => {
|
|
305
467
|
entry.subscribers.add(callback);
|
|
306
468
|
return () => {
|
|
307
469
|
entry.subscribers.delete(callback);
|
|
470
|
+
if (entry.subscribers.size === 0) releaseWhenUnused(cache, cacheKey, entry);
|
|
308
471
|
};
|
|
309
|
-
}, [
|
|
472
|
+
}, [
|
|
473
|
+
cache,
|
|
474
|
+
cacheKey,
|
|
475
|
+
entry
|
|
476
|
+
]);
|
|
310
477
|
const getSnapshot = useCallback(() => {
|
|
311
478
|
return `${entry.status}:${entry.version}`;
|
|
312
479
|
}, [entry]);
|
|
313
480
|
useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
|
|
314
|
-
|
|
315
|
-
const currentEntry = entryRef.current;
|
|
316
|
-
if (currentEntry && currentEntry.status === "resolved" && currentEntry.instanceName && !currentEntry.unsubscribe) setupInvalidationSubscription(currentEntry, rootContainer);
|
|
317
|
-
}, [rootContainer, entry]);
|
|
318
|
-
if (entry.status === "pending" && !entry.promise) fetchService();
|
|
481
|
+
if (entry.status === "pending" && !entry.promise) fetchService(entry, container, token, args);
|
|
319
482
|
if (entry.status === "pending") throw entry.promise;
|
|
320
|
-
if (entry.status === "rejected")
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
//#endregion
|
|
325
|
-
//#region src/hooks/use-optional-service.mts
|
|
326
|
-
function optionalServiceReducer(state, action) {
|
|
327
|
-
switch (action.type) {
|
|
328
|
-
case "loading": return { status: "loading" };
|
|
329
|
-
case "success": return {
|
|
330
|
-
status: "success",
|
|
331
|
-
data: action.data
|
|
332
|
-
};
|
|
333
|
-
case "not-found": return { status: "not-found" };
|
|
334
|
-
case "error": return {
|
|
335
|
-
status: "error",
|
|
336
|
-
error: action.error
|
|
337
|
-
};
|
|
338
|
-
case "reset": return { status: "idle" };
|
|
339
|
-
default: return state;
|
|
483
|
+
if (entry.status === "rejected") {
|
|
484
|
+
evictAfterRender(cache, cacheKey, entry);
|
|
485
|
+
throw entry.error;
|
|
340
486
|
}
|
|
341
|
-
|
|
487
|
+
return entry.result;
|
|
488
|
+
};
|
|
489
|
+
// src/service/use-optional-service.mts
|
|
342
490
|
/**
|
|
343
491
|
* Hook to optionally load a service from the DI container.
|
|
344
492
|
*
|
|
345
|
-
* Unlike useService,
|
|
346
|
-
*
|
|
493
|
+
* Unlike useService, a token without a provider is not an error: the hook
|
|
494
|
+
* returns `isNotFound: true` instead.
|
|
347
495
|
*
|
|
348
496
|
* This is useful for:
|
|
349
497
|
* - Optional dependencies that may or may not be configured
|
|
@@ -364,103 +512,14 @@ function optionalServiceReducer(state, action) {
|
|
|
364
512
|
* }
|
|
365
513
|
* ```
|
|
366
514
|
*/
|
|
367
|
-
function useOptionalService(token, args) {
|
|
368
|
-
const
|
|
369
|
-
const rootContainer = useRootContainer();
|
|
370
|
-
const initialSyncInstanceRef = useRef(void 0);
|
|
371
|
-
const isFirstRenderRef = useRef(true);
|
|
372
|
-
if (isFirstRenderRef.current) {
|
|
373
|
-
try {
|
|
374
|
-
initialSyncInstanceRef.current = container.tryGetSync(token, args);
|
|
375
|
-
} catch {}
|
|
376
|
-
isFirstRenderRef.current = false;
|
|
377
|
-
}
|
|
378
|
-
const [state, dispatch] = useReducer(optionalServiceReducer, initialSyncInstanceRef.current ? {
|
|
379
|
-
status: "success",
|
|
380
|
-
data: initialSyncInstanceRef.current
|
|
381
|
-
} : { status: "idle" });
|
|
382
|
-
const instanceNameRef = useRef(null);
|
|
383
|
-
{
|
|
384
|
-
const argsRef = useRef(args);
|
|
385
|
-
useEffect(() => {
|
|
386
|
-
if (argsRef.current !== args) {
|
|
387
|
-
if (JSON.stringify(argsRef.current) === JSON.stringify(args)) console.warn(`useOptionalService called with args that look the same but are different instances: ${JSON.stringify(argsRef.current)} !== ${JSON.stringify(args)}!
|
|
388
|
-
This is likely because you are using a value that is not memoized.
|
|
389
|
-
Please use a memoized value or use a different approach to pass the args.
|
|
390
|
-
Example:
|
|
391
|
-
const args = useMemo(() => ({ userId: '123' }), [])
|
|
392
|
-
return useOptionalService(UserToken, args)`);
|
|
393
|
-
argsRef.current = args;
|
|
394
|
-
}
|
|
395
|
-
}, [args]);
|
|
396
|
-
}
|
|
397
|
-
const fetchService = useCallback(async () => {
|
|
398
|
-
dispatch({ type: "loading" });
|
|
399
|
-
try {
|
|
400
|
-
const instance = await container.get(token, args);
|
|
401
|
-
const instanceName = container.calculateInstanceName(token, args);
|
|
402
|
-
if (instanceName) instanceNameRef.current = instanceName;
|
|
403
|
-
dispatch({
|
|
404
|
-
type: "success",
|
|
405
|
-
data: instance
|
|
406
|
-
});
|
|
407
|
-
} catch (error) {
|
|
408
|
-
const err = error;
|
|
409
|
-
const errorMessage = err.message?.toLowerCase() ?? "";
|
|
410
|
-
if (errorMessage.includes("not found") || errorMessage.includes("not registered") || errorMessage.includes("no provider")) dispatch({ type: "not-found" });
|
|
411
|
-
else dispatch({
|
|
412
|
-
type: "error",
|
|
413
|
-
error: err
|
|
414
|
-
});
|
|
415
|
-
}
|
|
416
|
-
}, [
|
|
417
|
-
container,
|
|
418
|
-
token,
|
|
419
|
-
args
|
|
420
|
-
]);
|
|
421
|
-
useEffect(() => {
|
|
422
|
-
const eventBus = rootContainer.getEventBus();
|
|
423
|
-
let unsubscribe;
|
|
424
|
-
if (initialSyncInstanceRef.current) {
|
|
425
|
-
const instanceName = container.calculateInstanceName(token, args);
|
|
426
|
-
if (instanceName) {
|
|
427
|
-
instanceNameRef.current = instanceName;
|
|
428
|
-
unsubscribe = eventBus.on(instanceName, "destroy", () => {
|
|
429
|
-
fetchService();
|
|
430
|
-
});
|
|
431
|
-
}
|
|
432
|
-
} else {
|
|
433
|
-
fetchService().then(() => {
|
|
434
|
-
if (instanceNameRef.current) unsubscribe = eventBus.on(instanceNameRef.current, "destroy", () => {
|
|
435
|
-
fetchService();
|
|
436
|
-
});
|
|
437
|
-
});
|
|
438
|
-
return () => {
|
|
439
|
-
unsubscribe?.();
|
|
440
|
-
};
|
|
441
|
-
}
|
|
442
|
-
return () => {
|
|
443
|
-
unsubscribe?.();
|
|
444
|
-
};
|
|
445
|
-
}, [
|
|
446
|
-
fetchService,
|
|
447
|
-
rootContainer,
|
|
448
|
-
token,
|
|
449
|
-
args
|
|
450
|
-
]);
|
|
515
|
+
const useOptionalService = function useOptionalService(token, args) {
|
|
516
|
+
const { state, refetch } = useResolvedService(token, args, { optional: true });
|
|
451
517
|
return {
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
isLoading: state.status === "loading",
|
|
455
|
-
isSuccess: state.status === "success",
|
|
456
|
-
isNotFound: state.status === "not-found",
|
|
457
|
-
isError: state.status === "error",
|
|
458
|
-
refetch: fetchService
|
|
518
|
+
...serviceResult(state, refetch),
|
|
519
|
+
isNotFound: state.status === "not-found"
|
|
459
520
|
};
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
//#endregion
|
|
463
|
-
//#region src/hooks/use-invalidate.mts
|
|
521
|
+
};
|
|
522
|
+
// src/service/use-invalidate-instance.mts
|
|
464
523
|
/**
|
|
465
524
|
* Hook that returns a function to invalidate a service instance directly.
|
|
466
525
|
*
|
|
@@ -494,75 +553,6 @@ function useInvalidateInstance() {
|
|
|
494
553
|
await container.invalidate(instance);
|
|
495
554
|
}, [container]);
|
|
496
555
|
}
|
|
497
|
-
|
|
498
|
-
//#endregion
|
|
499
|
-
//#region src/hooks/use-scope.mts
|
|
500
|
-
/**
|
|
501
|
-
* Hook to get the current scope ID.
|
|
502
|
-
* Returns null if not inside a ScopeProvider.
|
|
503
|
-
*/
|
|
504
|
-
function useScope() {
|
|
505
|
-
return useContext(ScopedContainerContext)?.getRequestId() ?? null;
|
|
506
|
-
}
|
|
507
|
-
/**
|
|
508
|
-
* Hook to get the current scope ID, throwing if not inside a ScopeProvider.
|
|
509
|
-
* Use this when your component requires a scope to function correctly.
|
|
510
|
-
*/
|
|
511
|
-
function useScopeOrThrow() {
|
|
512
|
-
const scopeId = useScope();
|
|
513
|
-
if (scopeId === null) throw new Error("useScopeOrThrow must be used within a ScopeProvider. Wrap your component tree with <ScopeProvider> to create a request scope.");
|
|
514
|
-
return scopeId;
|
|
515
|
-
}
|
|
516
|
-
/**
|
|
517
|
-
* Hook to get the current ScopedContainer.
|
|
518
|
-
* Returns null if not inside a ScopeProvider.
|
|
519
|
-
*
|
|
520
|
-
* Use this to access scope metadata or other ScopedContainer methods.
|
|
521
|
-
*
|
|
522
|
-
* @example
|
|
523
|
-
* ```tsx
|
|
524
|
-
* function TableRow() {
|
|
525
|
-
* const scope = useScopedContainer()
|
|
526
|
-
* const rowData = scope?.getMetadata('rowData')
|
|
527
|
-
* // ...
|
|
528
|
-
* }
|
|
529
|
-
* ```
|
|
530
|
-
*/
|
|
531
|
-
function useScopedContainer() {
|
|
532
|
-
return useContext(ScopedContainerContext);
|
|
533
|
-
}
|
|
534
|
-
/**
|
|
535
|
-
* Hook to get the current ScopedContainer, throwing if not inside a ScopeProvider.
|
|
536
|
-
* Use this when your component requires a scope to function correctly.
|
|
537
|
-
*/
|
|
538
|
-
function useScopedContainerOrThrow() {
|
|
539
|
-
const scopedContainer = useScopedContainer();
|
|
540
|
-
if (scopedContainer === null) throw new Error("useScopedContainerOrThrow must be used within a ScopeProvider. Wrap your component tree with <ScopeProvider> to create a request scope.");
|
|
541
|
-
return scopedContainer;
|
|
542
|
-
}
|
|
543
|
-
/**
|
|
544
|
-
* Hook to get metadata from the current scope.
|
|
545
|
-
* Returns undefined if not inside a ScopeProvider or if the key doesn't exist.
|
|
546
|
-
*
|
|
547
|
-
* @example
|
|
548
|
-
* ```tsx
|
|
549
|
-
* // In parent component:
|
|
550
|
-
* <ScopeProvider metadata={{ userId: '123', theme: 'dark' }}>
|
|
551
|
-
* <ChildComponent />
|
|
552
|
-
* </ScopeProvider>
|
|
553
|
-
*
|
|
554
|
-
* // In child component:
|
|
555
|
-
* function ChildComponent() {
|
|
556
|
-
* const userId = useScopeMetadata<string>('userId')
|
|
557
|
-
* const theme = useScopeMetadata<'light' | 'dark'>('theme')
|
|
558
|
-
* // ...
|
|
559
|
-
* }
|
|
560
|
-
* ```
|
|
561
|
-
*/
|
|
562
|
-
function useScopeMetadata(key) {
|
|
563
|
-
return useContext(ScopedContainerContext)?.getMetadata(key);
|
|
564
|
-
}
|
|
565
|
-
|
|
566
|
-
//#endregion
|
|
567
556
|
export { ContainerContext, ContainerProvider, ScopeProvider, ScopedContainerContext, useContainer, useInvalidateInstance, useOptionalService, useRootContainer, useScope, useScopeMetadata, useScopeOrThrow, useScopedContainer, useScopedContainerOrThrow, useService, useSuspenseService };
|
|
557
|
+
|
|
568
558
|
//# sourceMappingURL=index.mjs.map
|