@typewirets/react 0.1.0 → 0.2.0-rc.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.
@@ -9,88 +9,383 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _ReactResolutionContext_resolutionContext, _ReactResolutionContext_resolutions, _ReactResolutionContext_resolutionErrors;
12
+ var _ReactResolutionContext_instances, _ReactResolutionContext_resolutionContext, _ReactResolutionContext_resolutionErrors, _ReactResolutionContext_generation, _ReactResolutionContext_allClearedAt, _ReactResolutionContext_clearedAt, _ReactResolutionContext_clearedSince;
13
13
  import { jsx as _jsx } from "react/jsx-runtime";
14
+ /**
15
+ * TypeWire React Integration
16
+ *
17
+ * Provides React bindings for TypeWire dependency injection, enabling
18
+ * context-based dependency resolution within React component trees.
19
+ *
20
+ * Key exports:
21
+ * - {@link ReactResolutionContext} — Wraps a `ResolutionContext` with error caching, so a failed resolution doesn't loop under Suspense
22
+ * - {@link ContainerContext} — React Context holding the active resolution context
23
+ * - {@link useContainer} — Hook to access the current resolution context
24
+ * - {@link useTypeWire} — Hook to resolve a TypeWire with React Suspense support
25
+ * - {@link usePreload} — Hook that suspends a subtree once until a set of wires is created
26
+ * - {@link ResolutionContextProvider} — Component that provides a resolution context to the tree
27
+ *
28
+ * @packageDocumentation
29
+ */
14
30
  import * as React from "react";
15
31
  import { TypeWireError, TypeWireContainer, } from "@typewirets/core";
32
+ /**
33
+ * A React-aware wrapper around {@link ResolutionContext} that caches resolution
34
+ * errors.
35
+ *
36
+ * When a component suspends on a resolution that then fails, React renders it
37
+ * again, and that render would start a new creation, suspend, fail and repeat
38
+ * forever. To stop that loop, the error from a failed `get` is cached, and
39
+ * later `get` and `getSync` calls for the same `TypeSymbol` throw it without
40
+ * calling the underlying context.
41
+ *
42
+ * A cached error lasts until {@link ReactResolutionContext.clearErrors} is
43
+ * called, even across `unbind` and a re-apply: this class only sees a
44
+ * `ResolutionContext`, so it cannot tell that a binding changed. To retry
45
+ * after replacing a binding, call `clearErrors` and then reset the error
46
+ * boundary that caught the error.
47
+ *
48
+ * Calls that run while a resolution is in flight are not deduplicated here.
49
+ * The underlying context must share one in-flight creation per singleton
50
+ * itself, or readers may get different instances. `TypeWireContainer` does,
51
+ * and never hands a creation started before `unbind` to new callers. So does
52
+ * the `@typewirets/inversify` adapter, because Inversify 7 shares concurrent
53
+ * singleton `getAsync` calls. A custom `ResolutionContext` must do the same.
54
+ *
55
+ * @example
56
+ * ```typescript
57
+ * const container = new TypeWireContainer();
58
+ * const context = new ReactResolutionContext(container);
59
+ * const value = await context.get(MySymbol);
60
+ *
61
+ * // After replacing the binding for MySymbol:
62
+ * context.clearErrors(MySymbol);
63
+ * ```
64
+ */
16
65
  export class ReactResolutionContext {
17
66
  constructor(resolutionContext) {
67
+ _ReactResolutionContext_instances.add(this);
68
+ /** The underlying resolution context that performs actual dependency resolution. */
18
69
  _ReactResolutionContext_resolutionContext.set(this, void 0);
19
- _ReactResolutionContext_resolutions.set(this, new Map());
70
+ /** Cached resolution errors, keyed by symbol, to fail fast on repeated access. */
20
71
  _ReactResolutionContext_resolutionErrors.set(this, new Map());
72
+ /** Counts `clearErrors` calls, so a `get` can tell if one ran while it waited. */
73
+ _ReactResolutionContext_generation.set(this, 0);
74
+ /** The generation of the last `clearErrors()` call that cleared every symbol. */
75
+ _ReactResolutionContext_allClearedAt.set(this, 0);
76
+ /** The generation of the last `clearErrors(typeSymbol)` call, per symbol. */
77
+ _ReactResolutionContext_clearedAt.set(this, new Map());
21
78
  __classPrivateFieldSet(this, _ReactResolutionContext_resolutionContext, resolutionContext, "f");
22
79
  }
80
+ /**
81
+ * Synchronously retrieves a resolved instance for the given type symbol.
82
+ *
83
+ * @template T The type of the resolved instance
84
+ * @param typeSymbol - The typed symbol identifying the dependency to resolve
85
+ * @returns The resolved instance
86
+ * @throws Re-throws the cached error if a previous async resolution for this symbol failed
87
+ * @throws Throws if the instance has not been resolved yet (see {@link ResolutionContext.getSync})
88
+ */
23
89
  getSync(typeSymbol) {
24
90
  if (__classPrivateFieldGet(this, _ReactResolutionContext_resolutionErrors, "f").has(typeSymbol.symbol)) {
25
91
  throw __classPrivateFieldGet(this, _ReactResolutionContext_resolutionErrors, "f").get(typeSymbol.symbol);
26
92
  }
27
93
  return __classPrivateFieldGet(this, _ReactResolutionContext_resolutionContext, "f").getSync(typeSymbol);
28
94
  }
95
+ /**
96
+ * Asynchronously resolves an instance for the given type symbol.
97
+ *
98
+ * If a previous resolution for this symbol failed, the cached error is
99
+ * thrown immediately. Otherwise the call goes to the underlying context,
100
+ * which joins a creation already in flight for a singleton.
101
+ *
102
+ * @template T The type of the resolved instance
103
+ * @param typeSymbol - The typed symbol identifying the dependency to resolve
104
+ * @returns A promise that resolves to the instance
105
+ * @throws Re-throws the cached error if a previous resolution for this symbol failed
106
+ */
29
107
  async get(typeSymbol) {
30
- if (__classPrivateFieldGet(this, _ReactResolutionContext_resolutionErrors, "f").has(typeSymbol.symbol)) {
31
- throw __classPrivateFieldGet(this, _ReactResolutionContext_resolutionErrors, "f").get(typeSymbol.symbol);
108
+ const symbol = typeSymbol.symbol;
109
+ if (__classPrivateFieldGet(this, _ReactResolutionContext_resolutionErrors, "f").has(symbol)) {
110
+ throw __classPrivateFieldGet(this, _ReactResolutionContext_resolutionErrors, "f").get(symbol);
32
111
  }
33
- const promise = __classPrivateFieldGet(this, _ReactResolutionContext_resolutions, "f").get(typeSymbol.symbol);
34
- if (promise) {
35
- return promise;
112
+ const startedAt = __classPrivateFieldGet(this, _ReactResolutionContext_generation, "f");
113
+ try {
114
+ return await __classPrivateFieldGet(this, _ReactResolutionContext_resolutionContext, "f").get(typeSymbol);
36
115
  }
37
- const newResolution = __classPrivateFieldGet(this, _ReactResolutionContext_resolutionContext, "f").get(typeSymbol);
38
- __classPrivateFieldGet(this, _ReactResolutionContext_resolutions, "f").set(typeSymbol.symbol, newResolution);
39
- return newResolution
40
- .catch((err) => {
41
- __classPrivateFieldGet(this, _ReactResolutionContext_resolutionErrors, "f").set(typeSymbol.symbol, err);
116
+ catch (err) {
117
+ // A failure that settles after `clearErrors` belongs to the attempt the
118
+ // caller just discarded: hand it to this caller, but don't cache it.
119
+ if (!__classPrivateFieldGet(this, _ReactResolutionContext_instances, "m", _ReactResolutionContext_clearedSince).call(this, symbol, startedAt)) {
120
+ __classPrivateFieldGet(this, _ReactResolutionContext_resolutionErrors, "f").set(symbol, err);
121
+ }
42
122
  throw err;
43
- })
44
- .finally(() => {
45
- __classPrivateFieldGet(this, _ReactResolutionContext_resolutions, "f").delete(typeSymbol.symbol);
46
- });
123
+ }
47
124
  }
125
+ /**
126
+ * Forgets cached resolution errors, so the next `get` or `getSync` asks the
127
+ * underlying context again.
128
+ *
129
+ * Call it after replacing a failed binding (`unbind`, then apply the wire
130
+ * again), then reset the error boundary that shows the error. A failure that
131
+ * was still in flight when you call this is not cached when it settles.
132
+ *
133
+ * @param typeSymbol - The symbol whose error to forget. Omit to forget all.
134
+ */
135
+ clearErrors(typeSymbol) {
136
+ __classPrivateFieldSet(this, _ReactResolutionContext_generation, __classPrivateFieldGet(this, _ReactResolutionContext_generation, "f") + 1, "f");
137
+ if (typeSymbol) {
138
+ __classPrivateFieldGet(this, _ReactResolutionContext_resolutionErrors, "f").delete(typeSymbol.symbol);
139
+ __classPrivateFieldGet(this, _ReactResolutionContext_clearedAt, "f").set(typeSymbol.symbol, __classPrivateFieldGet(this, _ReactResolutionContext_generation, "f"));
140
+ return;
141
+ }
142
+ __classPrivateFieldGet(this, _ReactResolutionContext_resolutionErrors, "f").clear();
143
+ __classPrivateFieldGet(this, _ReactResolutionContext_clearedAt, "f").clear();
144
+ __classPrivateFieldSet(this, _ReactResolutionContext_allClearedAt, __classPrivateFieldGet(this, _ReactResolutionContext_generation, "f"), "f");
145
+ }
146
+ }
147
+ _ReactResolutionContext_resolutionContext = new WeakMap(), _ReactResolutionContext_resolutionErrors = new WeakMap(), _ReactResolutionContext_generation = new WeakMap(), _ReactResolutionContext_allClearedAt = new WeakMap(), _ReactResolutionContext_clearedAt = new WeakMap(), _ReactResolutionContext_instances = new WeakSet(), _ReactResolutionContext_clearedSince = function _ReactResolutionContext_clearedSince(symbol, generation) {
148
+ const clearedAt = Math.max(__classPrivateFieldGet(this, _ReactResolutionContext_allClearedAt, "f"), __classPrivateFieldGet(this, _ReactResolutionContext_clearedAt, "f").get(symbol) ?? 0);
149
+ return clearedAt > generation;
150
+ };
151
+ /**
152
+ * The wrapper {@link ResolutionContextProvider} uses for each plain context, so
153
+ * every render and every mount of a provider for that context share one error
154
+ * cache and one context value.
155
+ */
156
+ const reactResolutionContexts = new WeakMap();
157
+ function reactResolutionContextFor(resolutionContext) {
158
+ if (resolutionContext instanceof ReactResolutionContext) {
159
+ return resolutionContext;
160
+ }
161
+ let wrapper = reactResolutionContexts.get(resolutionContext);
162
+ if (!wrapper) {
163
+ wrapper = new ReactResolutionContext(resolutionContext);
164
+ reactResolutionContexts.set(resolutionContext, wrapper);
165
+ }
166
+ return wrapper;
48
167
  }
49
- _ReactResolutionContext_resolutionContext = new WeakMap(), _ReactResolutionContext_resolutions = new WeakMap(), _ReactResolutionContext_resolutionErrors = new WeakMap();
168
+ /**
169
+ * React Context that holds the active {@link ResolutionContext} for the component tree.
170
+ *
171
+ * The default value is an empty {@link TypeWireContainer} wrapped in a
172
+ * {@link ReactResolutionContext}. In practice, you should provide your own
173
+ * container via {@link ResolutionContextProvider}.
174
+ */
50
175
  export const ContainerContext = React.createContext(new ReactResolutionContext(new TypeWireContainer()));
176
+ /**
177
+ * Hook to access the current {@link ResolutionContext} from the nearest
178
+ * {@link ResolutionContextProvider}.
179
+ *
180
+ * @returns The current resolution context
181
+ *
182
+ * @example
183
+ * ```tsx
184
+ * function MyComponent() {
185
+ * const container = useContainer();
186
+ * // Use container for manual resolution if needed
187
+ * }
188
+ * ```
189
+ */
51
190
  export function useContainer() {
52
191
  const container = React.useContext(ContainerContext);
53
192
  return container;
54
193
  }
55
- export function useTypeWire(typeWire) {
194
+ /** Error reason thrown by {@link useTypeWire} with `{ suspend: false }`. */
195
+ const ReasonNotPreloaded = "NotPreloaded";
196
+ const ScopeSingleton = "singleton";
197
+ /** Marks a state that has no value yet, so falsy values still count as values. */
198
+ const NotReady = Symbol("NotReady");
199
+ /**
200
+ * Reads a wire synchronously. Returns `NotReady` when the value isn't
201
+ * created yet and can be waited for; rethrows any other error.
202
+ */
203
+ function readSync(typeWire, container) {
204
+ try {
205
+ return typeWire.getInstanceSync(container);
206
+ }
207
+ catch (err) {
208
+ if (err instanceof TypeWireError && err.retriable) {
209
+ return NotReady;
210
+ }
211
+ throw err;
212
+ }
213
+ }
214
+ function notPreloaded(typeWire, cause) {
215
+ const name = typeWire.type.symbol.description ?? "(unnamed wire)";
216
+ const err = new TypeWireError(ReasonNotPreloaded, `${name} is not ready. It was rendered with { suspend: false } before it was created: preload it (container.preload or usePreload) before this component renders.`);
217
+ err.retriable = false;
218
+ Object.defineProperty(err, "cause", {
219
+ value: cause,
220
+ enumerable: false,
221
+ writable: true,
222
+ configurable: true,
223
+ });
224
+ return err;
225
+ }
226
+ /**
227
+ * Hook that resolves a {@link TypeWire} within the current container context,
228
+ * with React Suspense integration.
229
+ *
230
+ * Resolution behavior:
231
+ * 1. **Sync available** — If the wire can be resolved synchronously (e.g., a singleton
232
+ * that was already created or preloaded), the value is returned immediately,
233
+ * including falsy values such as `0`, `""`, `false` and `null`.
234
+ * 2. **Async pending** — If sync resolution fails with a retriable error, the hook
235
+ * starts an async resolution and throws the promise to trigger React Suspense.
236
+ * With `{ suspend: false }` it throws a `TypeWireError` with reason
237
+ * `NotPreloaded` instead.
238
+ * 3. **Error** — If sync resolution fails with a non-retriable error, it is re-thrown.
239
+ *
240
+ * To render without a fallback, preload the wires first, with
241
+ * `container.preload` before rendering or {@link usePreload} higher in the
242
+ * tree. A wire nobody preloaded suspends, so this hook must be used inside a
243
+ * `<Suspense>` boundary unless you pass `{ suspend: false }`.
244
+ *
245
+ * @template T The type of the resolved instance
246
+ * @param typeWire - The TypeWire to resolve
247
+ * @param opts - Optional settings; see {@link UseTypeWireOpts}
248
+ * @returns The resolved instance
249
+ * @throws The resolution promise when the value is not yet available (for Suspense)
250
+ * @throws {@link TypeWireError} with reason `NotPreloaded` when the value is not yet available and `suspend` is `false`
251
+ * @throws {@link TypeWireError} if synchronous resolution fails with a non-retriable error
252
+ *
253
+ * @example
254
+ * ```tsx
255
+ * function UserProfile() {
256
+ * const userService = useTypeWire(UserServiceWire);
257
+ * return <div>{userService.getName()}</div>;
258
+ * }
259
+ *
260
+ * // Preloaded before rendering: no fallback.
261
+ * await container.preload({ wires: [UserServiceWire] });
262
+ *
263
+ * // Or wrap in Suspense for wires that may not be ready yet.
264
+ * <Suspense fallback={<Loading />}>
265
+ * <UserProfile />
266
+ * </Suspense>
267
+ * ```
268
+ */
269
+ export function useTypeWire(typeWire, opts) {
56
270
  const container = useContainer();
57
- const [value, setValue] = React.useState(() => {
271
+ const suspend = opts?.suspend ?? true;
272
+ const [state, setState] = React.useState(() => ({ value: readSync(typeWire, container) }));
273
+ if (state.value === NotReady && !suspend) {
274
+ let cause;
58
275
  try {
59
- return typeWire.getInstanceSync(container);
276
+ typeWire.getInstanceSync(container);
60
277
  }
61
278
  catch (err) {
62
- if (err instanceof TypeWireError && err.retriable) {
63
- return null;
64
- }
65
- throw err;
279
+ cause = err;
66
280
  }
67
- });
281
+ throw notPreloaded(typeWire, cause);
282
+ }
68
283
  const promise = typeWire.getInstance(container);
69
284
  React.useEffect(() => {
70
- let mounted = false;
285
+ let mounted = true;
71
286
  promise
72
287
  .then((value) => {
73
288
  if (mounted) {
74
- console.log("we got the value", value);
75
- setValue(() => value);
289
+ // Keep the same state object for the same value, so React skips the
290
+ // re-render; a new object here would re-render, start a new
291
+ // `getInstance` and run this effect again, forever.
292
+ setState((prev) => (Object.is(prev.value, value) ? prev : { value }));
76
293
  }
77
294
  })
78
295
  .catch((err) => {
79
- console.error(err);
296
+ if (mounted) {
297
+ console.error(err);
298
+ }
80
299
  });
81
300
  return () => {
82
301
  mounted = false;
83
302
  };
84
303
  }, [promise]);
85
- if (value) {
86
- return value;
304
+ if (state.value !== NotReady) {
305
+ return state.value;
87
306
  }
88
307
  throw promise;
89
308
  }
309
+ /**
310
+ * Hook that suspends the calling component until every singleton in
311
+ * `opts.wires` is created, so components below it read them with
312
+ * {@link useTypeWire} without suspending.
313
+ *
314
+ * Use it where a part of the app starts (a route, a panel, a feature), under
315
+ * one `<Suspense>` boundary: the fallback shows once for the whole set, and
316
+ * the creations run in parallel. A creation that fails reaches the nearest
317
+ * error boundary.
318
+ *
319
+ * It works with any resolution context, including the Inversify adapter.
320
+ * Outside React, use `container.preload` instead.
321
+ *
322
+ * @param opts - The wires to preload; see {@link UsePreloadOpts}
323
+ * @throws A promise while any of the wires is still being created (for Suspense)
324
+ * @throws The creation's error, once one has failed
325
+ *
326
+ * @example
327
+ * ```tsx
328
+ * function ReportsRoute() {
329
+ * usePreload({ wires: [reportsServiceWire, chartsWire] });
330
+ * return <ReportsPage />;
331
+ * }
332
+ *
333
+ * <Suspense fallback={<Loading />}>
334
+ * <ReportsRoute />
335
+ * </Suspense>
336
+ * ```
337
+ */
338
+ export function usePreload(opts) {
339
+ const container = useContainer();
340
+ const pending = [];
341
+ for (const wire of opts.wires) {
342
+ if ((wire.scope ?? ScopeSingleton) !== ScopeSingleton) {
343
+ continue;
344
+ }
345
+ if (readSync(wire, container) === NotReady) {
346
+ pending.push(wire.getInstance(container));
347
+ }
348
+ }
349
+ if (pending.length > 0) {
350
+ throw Promise.all(pending);
351
+ }
352
+ }
353
+ /**
354
+ * React component that provides a {@link ResolutionContext} to the component tree.
355
+ *
356
+ * If the given `resolutionContext` is not already a {@link ReactResolutionContext},
357
+ * it is wrapped in one, so a failed resolution reaches an error boundary
358
+ * instead of retrying under Suspense. Each plain context gets one wrapper,
359
+ * reused on every render and every mount, so re-rendering the provider keeps
360
+ * cached errors and gives consumers the same context value.
361
+ *
362
+ * A cached error lasts until `clearErrors` is called, even after `unbind` and
363
+ * a re-apply. To be able to retry, create the {@link ReactResolutionContext}
364
+ * yourself, pass it here, and call its `clearErrors` after replacing the
365
+ * binding.
366
+ *
367
+ * The context must share one in-flight creation per singleton (as
368
+ * `TypeWireContainer` does); see {@link ReactResolutionContext}.
369
+ *
370
+ * @param props.resolutionContext - The resolution context to provide to descendants
371
+ * @param props.children - Child components that will have access to the context
372
+ *
373
+ * @example
374
+ * ```tsx
375
+ * async function main() {
376
+ * const container = new TypeWireContainer();
377
+ * await AppWireGroup.apply(container);
378
+ *
379
+ * createRoot(document.getElementById('root')!).render(
380
+ * <ResolutionContextProvider resolutionContext={container}>
381
+ * <App />
382
+ * </ResolutionContextProvider>
383
+ * );
384
+ * }
385
+ * ```
386
+ */
90
387
  export function ResolutionContextProvider(props) {
91
- const resolutionContext = props.resolutionContext instanceof ReactResolutionContext
92
- ? props.resolutionContext
93
- : new ReactResolutionContext(props.resolutionContext);
388
+ const resolutionContext = reactResolutionContextFor(props.resolutionContext);
94
389
  return (_jsx(ContainerContext, { value: resolutionContext, children: props.children }));
95
390
  }
96
391
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.tsx"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,EAIL,aAAa,EACb,iBAAiB,GAClB,MAAM,kBAAkB,CAAC;AAE1B,MAAM,OAAO,sBAAsB;IAKjC,YAAY,iBAAoC;QAJvC,4DAAsC;QACtC,8CAA8C,IAAI,GAAG,EAAE,EAAC;QACxD,mDAA0C,IAAI,GAAG,EAAE,EAAC;QAG3D,uBAAA,IAAI,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G;AACH,MAAM,UAAU,UAAU,CAAC,IAAoB;IAC7C,MAAM,SAAS,GAAG,YAAY,EAAE,CAAC;IACjC,MAAM,OAAO,GAAuB,EAAE,CAAC;IACvC,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;QAC9B,IAAI,CAAC,IAAI,CAAC,KAAK,IAAI,cAAc,CAAC,KAAK,cAAc,EAAE,CAAC;YACtD,SAAS;QACX,CAAC;QAED,IAAI,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC,KAAK,QAAQ,EAAE,CAAC;YAC3C,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC,CAAC;QAC5C,CAAC;IACH,CAAC;IAED,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACvB,MAAM,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAC7B,CAAC;AACH,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,MAAM,UAAU,yBAAyB,CAAC,KAGzC;IACC,MAAM,iBAAiB,GAAG,yBAAyB,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC;IAC7E,OAAO,CACL,KAAC,gBAAgB,IAAC,KAAK,EAAE,iBAAiB,YACvC,KAAK,CAAC,QAAQ,GACE,CACpB,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typewirets/react",
3
- "version": "0.1.0",
3
+ "version": "0.2.0-rc.1",
4
4
  "description": "React adapter for TypeWire dependency injection",
5
5
  "type": "module",
6
6
  "main": "dist/cjs/index.js",
@@ -15,12 +15,8 @@
15
15
  },
16
16
  "files": [
17
17
  "dist",
18
- "src/*.ts",
19
- "src/*.tsx",
20
- "!src/**/*.test.ts",
21
- "!src/**/*.test.tsx",
22
- "!src/**/__tests__/**",
23
18
  "README.md",
19
+ "CHANGELOG.md",
24
20
  "LICENSE"
25
21
  ],
26
22
  "keywords": [
@@ -55,8 +51,13 @@
55
51
  "zustand": "^5.0.3",
56
52
  "@typewirets/typescript-config": "0.0.0"
57
53
  },
54
+ "sideEffects": false,
55
+ "engines": {
56
+ "node": ">=22"
57
+ },
58
58
  "peerDependencies": {
59
- "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
59
+ "@types/react": "^16.8 || ^17.0 || ^18.0 || ^19.0",
60
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0"
60
61
  },
61
62
  "peerDependenciesMeta": {
62
63
  "@types/react": {
@@ -64,15 +65,15 @@
64
65
  }
65
66
  },
66
67
  "dependencies": {
67
- "@typewirets/core": "0.1.0"
68
+ "@typewirets/core": "0.2.0-rc.1"
68
69
  },
69
70
  "scripts": {
70
71
  "build": "pnpm clean && pnpm --filter '@typewirets/react' --parallel '/^build:.*/'",
71
- "build:cjs": "tsc --project tsconfig.build.json --outDir dist/cjs --module Commonjs --moduleResolution Node",
72
+ "build:cjs": "node ../../scripts/write-cjs-package-json.mjs && tsc --project tsconfig.build.json --outDir dist/cjs --module Commonjs --moduleResolution Node",
72
73
  "build:esm": "tsc --project tsconfig.build.json --outDir dist/esm --module ES2020 --moduleResolution Node",
73
74
  "build:types": "tsc --project tsconfig.build.json --outDir dist/types --declaration --declarationMap",
74
75
  "dev": "pnpm clean && pnpm --filter '@typewirets/react' --parallel '/^dev:.*/'",
75
- "dev:cjs": "tsc --watch --project tsconfig.build.json --outDir dist/cjs --module Commonjs --moduleResolution Node",
76
+ "dev:cjs": "node ../../scripts/write-cjs-package-json.mjs && tsc --watch --project tsconfig.build.json --outDir dist/cjs --module Commonjs --moduleResolution Node",
76
77
  "dev:esm": "tsc --watch --project tsconfig.build.json --outDir dist/esm --module ES2020 --moduleResolution Node",
77
78
  "dev:types": "tsc --watch --project tsconfig.build.json --outDir dist/types --declaration --declarationMap",
78
79
  "clean": "rimraf dist",
package/src/index.tsx DELETED
@@ -1,111 +0,0 @@
1
- import * as React from "react";
2
- import {
3
- type ResolutionContext,
4
- type TypeSymbol,
5
- type TypeWire,
6
- TypeWireError,
7
- TypeWireContainer,
8
- } from "@typewirets/core";
9
-
10
- export class ReactResolutionContext {
11
- readonly #resolutionContext: ResolutionContext;
12
- readonly #resolutions: Map<symbol, Promise<unknown>> = new Map();
13
- readonly #resolutionErrors: Map<symbol, unknown> = new Map();
14
-
15
- constructor(resolutionContext: ResolutionContext) {
16
- this.#resolutionContext = resolutionContext;
17
- }
18
-
19
- getSync<T>(typeSymbol: TypeSymbol<T>): T {
20
- if (this.#resolutionErrors.has(typeSymbol.symbol)) {
21
- throw this.#resolutionErrors.get(typeSymbol.symbol);
22
- }
23
- return this.#resolutionContext.getSync(typeSymbol);
24
- }
25
-
26
- async get<T>(typeSymbol: TypeSymbol<T>): Promise<T> {
27
- if (this.#resolutionErrors.has(typeSymbol.symbol)) {
28
- throw this.#resolutionErrors.get(typeSymbol.symbol);
29
- }
30
-
31
- const promise = this.#resolutions.get(typeSymbol.symbol) as Promise<T>;
32
- if (promise) {
33
- return promise;
34
- }
35
-
36
- const newResolution = this.#resolutionContext.get(typeSymbol);
37
- this.#resolutions.set(typeSymbol.symbol, newResolution);
38
- return newResolution
39
- .catch((err) => {
40
- this.#resolutionErrors.set(typeSymbol.symbol, err);
41
- throw err;
42
- })
43
- .finally(() => {
44
- this.#resolutions.delete(typeSymbol.symbol);
45
- });
46
- }
47
- }
48
-
49
- export const ContainerContext = React.createContext<ResolutionContext>(
50
- new ReactResolutionContext(new TypeWireContainer()),
51
- );
52
-
53
- export function useContainer() {
54
- const container = React.useContext(ContainerContext);
55
- return container;
56
- }
57
-
58
- export function useTypeWire<T>(typeWire: TypeWire<T>): T {
59
- const container = useContainer();
60
- const [value, setValue] = React.useState(() => {
61
- try {
62
- return typeWire.getInstanceSync(container);
63
- } catch (err: unknown) {
64
- if (err instanceof TypeWireError && err.retriable) {
65
- return null;
66
- }
67
-
68
- throw err;
69
- }
70
- });
71
-
72
- const promise = typeWire.getInstance(container);
73
- React.useEffect(() => {
74
- let mounted = false;
75
-
76
- promise
77
- .then((value) => {
78
- if (mounted) {
79
- console.log("we got the value", value);
80
- setValue(() => value);
81
- }
82
- })
83
- .catch((err) => {
84
- console.error(err);
85
- });
86
- return () => {
87
- mounted = false;
88
- };
89
- }, [promise]);
90
-
91
- if (value) {
92
- return value;
93
- }
94
-
95
- throw promise;
96
- }
97
-
98
- export function ResolutionContextProvider(props: {
99
- resolutionContext: ResolutionContext;
100
- children?: React.ReactNode;
101
- }) {
102
- const resolutionContext =
103
- props.resolutionContext instanceof ReactResolutionContext
104
- ? props.resolutionContext
105
- : new ReactResolutionContext(props.resolutionContext);
106
- return (
107
- <ContainerContext value={resolutionContext}>
108
- {props.children}
109
- </ContainerContext>
110
- );
111
- }