@ic-reactor/react 0.5.5 → 1.0.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.
@@ -0,0 +1,16 @@
1
+ import React from "react";
2
+ import { ActorUseMethodCallArg, ActorUseQueryArgs, ActorUseUpdateArgs } from "../../types";
3
+ import { CreateActorOptions, ActorContextType, ActorProviderProps } from "./types";
4
+ export * from "./types";
5
+ export declare const createReActorContext: <Actor extends unknown>({ canisterId: defaultCanisterId, ...defaultConfig }?: Partial<CreateActorOptions>) => {
6
+ ActorContext: React.Context<ActorContextType | null>;
7
+ ActorProvider: React.FC<ActorProviderProps>;
8
+ useActorContext: <A extends unknown = Actor>() => ActorContextType<A>;
9
+ useActorState: () => import("../../types").UseActorStoreReturn<Actor>;
10
+ useQueryCall: <M extends keyof Actor & string>(args: ActorUseQueryArgs<Actor, M>) => import("../../types").ActorCallReturn<Actor, M>;
11
+ useUpdateCall: <M_1 extends keyof Actor & string>(args: ActorUseUpdateArgs<Actor, M_1>) => import("../../types").ActorCallReturn<Actor, M_1>;
12
+ useMethodCall: <M_2 extends keyof Actor & string>(args: ActorUseMethodCallArg<Actor, M_2>) => import("../../types").ActorUseMethodCallReturn<Actor, M_2, true>;
13
+ useVisitMethod: (functionName: keyof Actor & string) => import("@ic-reactor/core").VisitService<Actor>[keyof Actor & string];
14
+ initialize: () => Promise<void>;
15
+ };
16
+ export declare const ActorContext: React.Context<ActorContextType | null>, ActorProvider: React.FC<ActorProviderProps>, useActorContext: <A extends unknown = unknown>() => ActorContextType<A>, useActorState: () => import("../../types").UseActorStoreReturn<unknown>, useQueryCall: <M extends never>(args: ActorUseQueryArgs<unknown, M>) => import("../../types").ActorCallReturn<unknown, M>, useUpdateCall: <M extends never>(args: ActorUseUpdateArgs<unknown, M>) => import("../../types").ActorCallReturn<unknown, M>, useMethodCall: <M extends never>(args: ActorUseMethodCallArg<unknown, M>) => import("../../types").ActorUseMethodCallReturn<unknown, M, true>, useVisitMethod: (functionName: never) => never;
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
26
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
27
+ };
28
+ var __rest = (this && this.__rest) || function (s, e) {
29
+ var t = {};
30
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
31
+ t[p] = s[p];
32
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
33
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
34
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
35
+ t[p[i]] = s[p[i]];
36
+ }
37
+ return t;
38
+ };
39
+ var _a;
40
+ Object.defineProperty(exports, "__esModule", { value: true });
41
+ exports.useVisitMethod = exports.useMethodCall = exports.useUpdateCall = exports.useQueryCall = exports.useActorState = exports.useActorContext = exports.ActorProvider = exports.ActorContext = exports.createReActorContext = void 0;
42
+ /* eslint-disable @typescript-eslint/no-explicit-any */
43
+ const react_1 = __importStar(require("react"));
44
+ const actor_1 = require("../../hooks/actor");
45
+ const useActor_1 = require("../../hooks/useActor");
46
+ __exportStar(require("./types"), exports);
47
+ const createReActorContext = (_a = {}) => {
48
+ var { canisterId: defaultCanisterId } = _a, defaultConfig = __rest(_a, ["canisterId"]);
49
+ const ActorContext = (0, react_1.createContext)(null);
50
+ const ActorProvider = (_a) => {
51
+ var { children, canisterId = defaultCanisterId, loadingComponent = react_1.default.createElement("div", null, "Fetching canister...") } = _a, restConfig = __rest(_a, ["children", "canisterId", "loadingComponent"]);
52
+ if (!canisterId) {
53
+ throw new Error("canisterId is required");
54
+ }
55
+ const config = (0, react_1.useMemo)(() => (Object.assign(Object.assign({}, defaultConfig), restConfig)), [defaultConfig, restConfig]);
56
+ const { actorManager, fetchError, fetching } = (0, useActor_1.useActor)(Object.assign({ canisterId }, config));
57
+ const hooks = (0, react_1.useMemo)(() => {
58
+ if (actorManager) {
59
+ return (0, actor_1.getActorHooks)(actorManager);
60
+ }
61
+ return null;
62
+ }, [actorManager === null || actorManager === void 0 ? void 0 : actorManager.canisterId]);
63
+ return (react_1.default.createElement(ActorContext.Provider, { value: hooks }, fetching || hooks === null ? fetchError !== null && fetchError !== void 0 ? fetchError : loadingComponent : children));
64
+ };
65
+ ActorProvider.displayName = "ActorProvider";
66
+ const useActorContext = () => {
67
+ const context = (0, react_1.useContext)(ActorContext);
68
+ if (!context) {
69
+ throw new Error("useActor must be used within a ActorProvider");
70
+ }
71
+ return context;
72
+ };
73
+ const initialize = () => useActorContext().initialize();
74
+ const useActorState = () => useActorContext().useActorState();
75
+ const useQueryCall = (args) => useActorContext().useQueryCall(args);
76
+ const useUpdateCall = (args) => useActorContext().useUpdateCall(args);
77
+ const useMethodCall = (args) => useActorContext().useMethodCall(args);
78
+ const useVisitMethod = (functionName) => useActorContext().useVisitMethod(functionName);
79
+ return {
80
+ ActorContext,
81
+ ActorProvider,
82
+ useActorContext,
83
+ useActorState,
84
+ useQueryCall,
85
+ useUpdateCall,
86
+ useMethodCall,
87
+ useVisitMethod,
88
+ initialize,
89
+ };
90
+ };
91
+ exports.createReActorContext = createReActorContext;
92
+ _a = (0, exports.createReActorContext)(), exports.ActorContext = _a.ActorContext, exports.ActorProvider = _a.ActorProvider, exports.useActorContext = _a.useActorContext, exports.useActorState = _a.useActorState, exports.useQueryCall = _a.useQueryCall, exports.useUpdateCall = _a.useUpdateCall, exports.useMethodCall = _a.useMethodCall, exports.useVisitMethod = _a.useVisitMethod;
@@ -0,0 +1,29 @@
1
+ /// <reference types="react" />
2
+ import { IDL } from "@dfinity/candid";
3
+ import { ActorManagerOptions, BaseActor } from "@ic-reactor/core";
4
+ import { AgentContextType } from "../agent";
5
+ import { ActorHooks } from "../../types";
6
+ export type ActorContextType<Actor = BaseActor, F extends boolean = true> = ActorHooks<Actor, F> & {
7
+ ActorContext: React.Context<ActorContextType<Actor, F> | null>;
8
+ useActorContext: <A = Actor>() => ActorContextType<A>;
9
+ ActorProvider: React.FC<ActorProviderProps>;
10
+ };
11
+ export type CreateReActorContext = {
12
+ <A = BaseActor>(options?: Partial<CreateActorOptions> & {
13
+ withVisitor: true;
14
+ }): ActorContextType<A, true>;
15
+ <A = BaseActor>(options?: Partial<CreateActorOptions> & {
16
+ withVisitor?: false | undefined;
17
+ }): ActorContextType<A, false>;
18
+ };
19
+ export interface CreateActorOptions extends Omit<ActorManagerOptions, "idlFactory" | "agentManager" | "canisterId"> {
20
+ didjsId?: string;
21
+ canisterId?: string;
22
+ agentContext?: AgentContextType;
23
+ idlFactory?: IDL.InterfaceFactory;
24
+ loadingComponent?: React.ReactNode;
25
+ }
26
+ export interface ActorProviderProps extends CreateActorOptions {
27
+ children?: React.ReactNode | undefined;
28
+ loadingComponent?: React.ReactNode;
29
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,4 @@
1
+ import { AgentManager, HttpAgent } from "@ic-reactor/core";
2
+ import { AgentContextType } from "./types";
3
+ export declare const useAgentManager: (agentContext?: AgentContextType) => AgentManager;
4
+ export declare const useAgentContext: (agentContext?: AgentContextType) => HttpAgent | undefined;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useAgentContext = exports.useAgentManager = void 0;
4
+ const react_1 = require("react");
5
+ const _1 = require(".");
6
+ const useAgentManager = (agentContext) => {
7
+ const context = (0, _1.useAgentManagerContext)(agentContext);
8
+ return context.agentManager;
9
+ };
10
+ exports.useAgentManager = useAgentManager;
11
+ const useAgentContext = (agentContext) => {
12
+ const agentManager = (0, exports.useAgentManager)(agentContext);
13
+ const [agent, setAgent] = (0, react_1.useState)(agentManager.getAgent());
14
+ (0, react_1.useEffect)(() => agentManager.subscribeAgent(setAgent), []);
15
+ return agent;
16
+ };
17
+ exports.useAgentContext = useAgentContext;
@@ -0,0 +1,10 @@
1
+ import React from "react";
2
+ import { AgentManagerOptions } from "@ic-reactor/core";
3
+ import { AgentContextValue, AgentContextType, AgentProviderProps } from "./types";
4
+ export * from "./types";
5
+ export * from "./hooks";
6
+ export declare const AgentManagerContext: React.Context<AgentContextValue | null>;
7
+ export declare const useAgentManagerContext: (agentContext?: AgentContextType) => AgentContextValue;
8
+ export declare const createAgentContext: (config: AgentManagerOptions) => AgentContextValue;
9
+ declare const AgentProvider: React.FC<AgentProviderProps>;
10
+ export { AgentProvider };
@@ -22,6 +22,9 @@ var __importStar = (this && this.__importStar) || function (mod) {
22
22
  __setModuleDefault(result, mod);
23
23
  return result;
24
24
  };
25
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
26
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
27
+ };
25
28
  var __rest = (this && this.__rest) || function (s, e) {
26
29
  var t = {};
27
30
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
@@ -34,40 +37,33 @@ var __rest = (this && this.__rest) || function (s, e) {
34
37
  return t;
35
38
  };
36
39
  Object.defineProperty(exports, "__esModule", { value: true });
37
- exports.AgentProvider = exports.createAgentContext = exports.useAgentManager = exports.useAgent = exports.AgentContext = void 0;
40
+ exports.AgentProvider = exports.createAgentContext = exports.useAgentManagerContext = exports.AgentManagerContext = void 0;
38
41
  const react_1 = __importStar(require("react"));
39
- const store_1 = require("@ic-reactor/store");
40
- const auth_1 = require("../hooks/auth");
41
- exports.AgentContext = (0, react_1.createContext)(null);
42
- const useAgent = (agentContext) => {
43
- const context = (0, react_1.useContext)(agentContext || exports.AgentContext);
42
+ const core_1 = require("@ic-reactor/core");
43
+ const agent_1 = require("../../hooks/agent");
44
+ const auth_1 = require("../../hooks/auth");
45
+ __exportStar(require("./types"), exports);
46
+ __exportStar(require("./hooks"), exports);
47
+ exports.AgentManagerContext = (0, react_1.createContext)(null);
48
+ const useAgentManagerContext = (agentContext) => {
49
+ const context = (0, react_1.useContext)(agentContext || exports.AgentManagerContext);
44
50
  if (!context) {
45
- throw new Error("useAgent must be used within a AgentProvider");
51
+ throw new Error("Agent context must be used within a AgentProvider");
46
52
  }
47
53
  return context;
48
54
  };
49
- exports.useAgent = useAgent;
50
- const useAgentManager = (agentContext) => {
51
- const context = (0, react_1.useContext)(agentContext || exports.AgentContext);
52
- if (!context) {
53
- throw new Error("useAgentManager must be used within a AgentProvider");
54
- }
55
- return context.agentManager;
56
- };
57
- exports.useAgentManager = useAgentManager;
55
+ exports.useAgentManagerContext = useAgentManagerContext;
58
56
  const createAgentContext = (config) => {
59
- const agentManager = (0, store_1.createAgentManager)(config);
60
- const hooks = (0, auth_1.getAuthHooks)(agentManager);
61
- return Object.assign(Object.assign({}, hooks), { agentManager });
57
+ const agentManager = (0, core_1.createAgentManager)(config);
58
+ const agenthooks = (0, agent_1.getAgentHooks)(agentManager);
59
+ const authHooks = (0, auth_1.getAuthHooks)(agentManager);
60
+ return Object.assign(Object.assign(Object.assign({}, agenthooks), authHooks), { agentManager });
62
61
  };
63
62
  exports.createAgentContext = createAgentContext;
64
63
  const AgentProvider = (_a) => {
65
64
  var { children } = _a, config = __rest(_a, ["children"]);
66
- const value = (0, react_1.useMemo)(() => {
67
- const agentManager = config.agentManager || (0, store_1.createAgentManager)(config);
68
- const hooks = (0, auth_1.getAuthHooks)(agentManager);
69
- return Object.assign(Object.assign({}, hooks), { agentManager });
70
- }, [config]);
71
- return react_1.default.createElement(exports.AgentContext.Provider, { value: value }, children);
65
+ const value = (0, react_1.useMemo)(() => (0, exports.createAgentContext)(config), [config]);
66
+ return (react_1.default.createElement(exports.AgentManagerContext.Provider, { value: value }, children));
72
67
  };
73
68
  exports.AgentProvider = AgentProvider;
69
+ AgentProvider.displayName = "AgentProvider";
@@ -0,0 +1,11 @@
1
+ import React, { PropsWithChildren } from "react";
2
+ import { AgentManager, AgentManagerOptions } from "@ic-reactor/core";
3
+ import { getAuthHooks } from "../../hooks/auth";
4
+ import { getAgentHooks } from "../../hooks/agent";
5
+ export type AgentContextValue = ReturnType<typeof getAuthHooks> & ReturnType<typeof getAgentHooks> & {
6
+ agentManager: AgentManager;
7
+ };
8
+ export type AgentContextType = React.Context<AgentContextValue | null>;
9
+ export interface AgentProviderProps extends PropsWithChildren, AgentManagerOptions {
10
+ agentManager?: AgentManager;
11
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ export * from "./actor";
2
+ export * from "./agent";
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./actor"), exports);
18
+ __exportStar(require("./agent"), exports);
@@ -1,3 +1,3 @@
1
- import type { ActorManager } from "@ic-reactor/store";
2
- import type { ActorHooks } from "../types";
3
- export declare const getActorHooks: <A extends unknown>({ initialize, serviceFields, withServiceFields, canisterId, actorStore, callMethod, }: ActorManager<A>) => ActorHooks<A, boolean>;
1
+ import { ActorHooks } from "../types";
2
+ import { ActorManager } from "@ic-reactor/core";
3
+ export declare const getActorHooks: <A>({ initialize, canisterId, actorStore, callMethod, visitFunction, }: ActorManager<A>) => ActorHooks<A, true>;
@@ -21,43 +21,31 @@ var __rest = (this && this.__rest) || function (s, e) {
21
21
  };
22
22
  Object.defineProperty(exports, "__esModule", { value: true });
23
23
  exports.getActorHooks = void 0;
24
+ /* eslint-disable no-console */
24
25
  const react_1 = require("react");
25
26
  const zustand_1 = require("zustand");
26
- const getActorHooks = ({ initialize, serviceFields, withServiceFields, canisterId, actorStore, callMethod, }) => {
27
- const useActorStore = () => {
27
+ const DEFAULT_STATE = {
28
+ data: undefined,
29
+ error: undefined,
30
+ loading: false,
31
+ };
32
+ const getActorHooks = ({ initialize, canisterId, actorStore, callMethod, visitFunction, }) => {
33
+ const useActorState = () => {
28
34
  const actorState = (0, zustand_1.useStore)(actorStore, (state) => state);
29
35
  return Object.assign(Object.assign({}, actorState), { canisterId });
30
36
  };
31
- const useServiceFields = () => {
32
- if (!withServiceFields || !serviceFields) {
33
- throw new Error("Service fields not initialized. Pass `withServiceFields` to initialize service fields.");
34
- }
35
- return serviceFields;
36
- };
37
- const useMethods = () => {
38
- const serviceFields = useServiceFields();
39
- return (0, react_1.useMemo)(() => {
40
- return Object.values(serviceFields.methods);
41
- }, [serviceFields]);
37
+ const useVisitFunction = () => {
38
+ return visitFunction;
42
39
  };
43
- const useMethodFields = () => {
44
- const serviceFields = useServiceFields();
40
+ const useVisitMethod = (functionName) => {
41
+ const serviceFields = useVisitFunction();
45
42
  return (0, react_1.useMemo)(() => {
46
- return Object.values(serviceFields.methodFields);
47
- }, [serviceFields]);
48
- };
49
- const useMethodField = (functionName) => {
50
- const serviceMethod = useServiceFields();
51
- return (0, react_1.useMemo)(() => {
52
- return serviceMethod.methodFields[functionName];
53
- }, [functionName, serviceMethod]);
43
+ return serviceFields[functionName];
44
+ }, [functionName, serviceFields]);
54
45
  };
55
46
  const useReActorCall = ({ onError, onSuccess, onLoading, args = [], functionName, throwOnError = false, }) => {
56
- const [state, setState] = (0, react_1.useState)({
57
- data: undefined,
58
- error: undefined,
59
- loading: false,
60
- });
47
+ const [state, setState] = (0, react_1.useState)(DEFAULT_STATE);
48
+ const reset = (0, react_1.useCallback)(() => setState(DEFAULT_STATE), []);
61
49
  const call = (0, react_1.useCallback)((eventOrReplaceArgs) => __awaiter(void 0, void 0, void 0, function* () {
62
50
  onLoading === null || onLoading === void 0 ? void 0 : onLoading(true);
63
51
  onError === null || onError === void 0 ? void 0 : onError(undefined);
@@ -83,15 +71,12 @@ const getActorHooks = ({ initialize, serviceFields, withServiceFields, canisterI
83
71
  throw error;
84
72
  }
85
73
  }), [args, functionName, onError, onSuccess, onLoading]);
86
- const field = (0, react_1.useMemo)(() => {
87
- return serviceFields === null || serviceFields === void 0 ? void 0 : serviceFields.methodFields[functionName];
88
- }, [functionName]);
89
- return Object.assign({ call, field }, state);
74
+ return Object.assign({ call, reset }, state);
90
75
  };
91
76
  const useQueryCall = (_a) => {
92
- var { refetchOnMount = false, refetchInterval = false } = _a, rest = __rest(_a, ["refetchOnMount", "refetchInterval"]);
77
+ var { refetchOnMount = true, refetchInterval = false } = _a, rest = __rest(_a, ["refetchOnMount", "refetchInterval"]);
93
78
  const _b = useReActorCall(rest), { call } = _b, state = __rest(_b, ["call"]);
94
- let intervalId = (0, react_1.useRef)(undefined);
79
+ const intervalId = (0, react_1.useRef)(undefined);
95
80
  (0, react_1.useEffect)(() => {
96
81
  // Auto-refresh logic
97
82
  if (refetchInterval) {
@@ -112,27 +97,17 @@ const getActorHooks = ({ initialize, serviceFields, withServiceFields, canisterI
112
97
  const useUpdateCall = (args) => {
113
98
  return useReActorCall(args);
114
99
  };
115
- const useMethodCall = (_a) => {
116
- var { type } = _a, rest = __rest(_a, ["type"]);
117
- switch (type) {
118
- case "query":
119
- return useQueryCall(rest);
120
- case "update":
121
- return useUpdateCall(rest);
122
- default:
123
- throw new Error(`Invalid type: ${type}`);
124
- }
100
+ const useMethodCall = (args) => {
101
+ const visit = visitFunction[args.functionName];
102
+ return Object.assign({ visit }, useReActorCall(args));
125
103
  };
126
104
  return {
127
105
  initialize,
128
106
  useQueryCall,
129
107
  useUpdateCall,
108
+ useVisitMethod,
109
+ useActorState,
130
110
  useMethodCall,
131
- useActorStore,
132
- useMethods,
133
- useMethodField,
134
- useMethodFields,
135
- useServiceFields,
136
111
  };
137
112
  };
138
113
  exports.getActorHooks = getActorHooks;
@@ -0,0 +1,6 @@
1
+ import type { AgentManager, HttpAgent } from "@ic-reactor/core";
2
+ export type AgentHooks = ReturnType<typeof getAgentHooks>;
3
+ export declare const getAgentHooks: (agentManager: AgentManager) => {
4
+ useAgent: () => HttpAgent | undefined;
5
+ useAgentState: () => import("@ic-reactor/core").AgentState;
6
+ };
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getAgentHooks = void 0;
4
+ const react_1 = require("react");
5
+ const zustand_1 = require("zustand");
6
+ const getAgentHooks = (agentManager) => {
7
+ const { agentStore, getAgent } = agentManager;
8
+ const useAgentState = () => {
9
+ return (0, zustand_1.useStore)(agentStore, (state) => state);
10
+ };
11
+ const useAgent = () => {
12
+ const [agent, setAgent] = (0, react_1.useState)(getAgent());
13
+ (0, react_1.useEffect)(() => agentManager.subscribeAgent(setAgent), []);
14
+ return agent;
15
+ };
16
+ return {
17
+ useAgent,
18
+ useAgentState,
19
+ };
20
+ };
21
+ exports.getAgentHooks = getAgentHooks;
@@ -1,11 +1,10 @@
1
1
  import type { AuthClientLoginOptions } from "@dfinity/auth-client";
2
- import type { AgentManager, Identity, Principal } from "@ic-reactor/store";
2
+ import type { AgentManager, Identity, Principal } from "@ic-reactor/core";
3
3
  import { AuthArgs } from "../types";
4
4
  export type AuthHooks = ReturnType<typeof getAuthHooks>;
5
5
  export declare const getAuthHooks: (agentManager: AgentManager) => {
6
6
  useUserPrincipal: () => Principal | undefined;
7
- useAgentManager: () => AgentManager;
8
- useAuthStore: () => import("@ic-reactor/store").AgentAuthState;
7
+ useAuthStore: () => import("@ic-reactor/core").AuthState;
9
8
  useAuthClient: ({ onAuthentication, onAuthenticationSuccess, onAuthenticationFailure, onLogin, onLoginSuccess, onLoginError, onLoggedOut, }?: AuthArgs) => {
10
9
  authClient: import("@dfinity/auth-client").AuthClient | null;
11
10
  authenticated: boolean;
@@ -14,9 +14,6 @@ const react_1 = require("react");
14
14
  const zustand_1 = require("zustand");
15
15
  const getAuthHooks = (agentManager) => {
16
16
  const { authenticate: authenticator, authStore, isLocalEnv } = agentManager;
17
- const useAgentManager = () => {
18
- return agentManager;
19
- };
20
17
  const useAuthStore = () => {
21
18
  const authState = (0, zustand_1.useStore)(authStore, (state) => state);
22
19
  return authState;
@@ -30,17 +27,17 @@ const getAuthHooks = (agentManager) => {
30
27
  const [loginError, setLoginError] = (0, react_1.useState)(null);
31
28
  const { authClient, authenticated, authenticating, identity } = useAuthStore();
32
29
  const authenticate = (0, react_1.useCallback)(() => __awaiter(void 0, void 0, void 0, function* () {
33
- const authenticatePromise = new Promise((resolve, reject) => __awaiter(void 0, void 0, void 0, function* () {
34
- try {
35
- const identity = yield authenticator();
30
+ const authenticatePromise = new Promise((resolve, reject) => {
31
+ authenticator()
32
+ .then((identity) => {
36
33
  onAuthenticationSuccess === null || onAuthenticationSuccess === void 0 ? void 0 : onAuthenticationSuccess(identity);
37
34
  resolve(identity);
38
- }
39
- catch (e) {
35
+ })
36
+ .catch((e) => {
40
37
  onAuthenticationFailure === null || onAuthenticationFailure === void 0 ? void 0 : onAuthenticationFailure(e);
41
38
  reject(e);
42
- }
43
- }));
39
+ });
40
+ });
44
41
  onAuthentication === null || onAuthentication === void 0 ? void 0 : onAuthentication(() => authenticatePromise);
45
42
  return authenticatePromise;
46
43
  }), [
@@ -52,21 +49,28 @@ const getAuthHooks = (agentManager) => {
52
49
  const login = (0, react_1.useCallback)((options) => __awaiter(void 0, void 0, void 0, function* () {
53
50
  setLoginLoading(true);
54
51
  setLoginError(null);
55
- const loginPromise = new Promise((resolve, reject) => __awaiter(void 0, void 0, void 0, function* () {
52
+ const loginPromise = new Promise((resolve, reject) => {
56
53
  try {
57
54
  if (!authClient) {
58
55
  throw new Error("Auth client not initialized");
59
56
  }
60
- yield authClient.login(Object.assign(Object.assign({ identityProvider: isLocalEnv
57
+ authClient.login(Object.assign(Object.assign({ identityProvider: isLocalEnv
61
58
  ? "https://identity.ic0.app/#authorize"
62
- : "http://rdmx6-jaaaa-aaaaa-aaadq-cai.localhost:4943/#authorize" }, options), { onSuccess: () => __awaiter(void 0, void 0, void 0, function* () {
63
- var _a;
64
- const identity = yield authenticate();
65
- const principal = identity.getPrincipal();
66
- (_a = options === null || options === void 0 ? void 0 : options.onSuccess) === null || _a === void 0 ? void 0 : _a.call(options);
67
- onLoginSuccess === null || onLoginSuccess === void 0 ? void 0 : onLoginSuccess(principal);
68
- resolve(principal);
69
- }), onError: (e) => {
59
+ : "http://rdmx6-jaaaa-aaaaa-aaadq-cai.localhost:4943/#authorize" }, options), { onSuccess: () => {
60
+ authenticate()
61
+ .then((identity) => {
62
+ var _a;
63
+ const principal = identity.getPrincipal();
64
+ (_a = options === null || options === void 0 ? void 0 : options.onSuccess) === null || _a === void 0 ? void 0 : _a.call(options);
65
+ onLoginSuccess === null || onLoginSuccess === void 0 ? void 0 : onLoginSuccess(principal);
66
+ resolve(principal);
67
+ })
68
+ .catch((e) => {
69
+ setLoginError(e);
70
+ onLoginError === null || onLoginError === void 0 ? void 0 : onLoginError(e);
71
+ reject(e);
72
+ });
73
+ }, onError: (e) => {
70
74
  var _a;
71
75
  (_a = options === null || options === void 0 ? void 0 : options.onError) === null || _a === void 0 ? void 0 : _a.call(options, e);
72
76
  const error = new Error("Login failed: " + e);
@@ -83,7 +87,7 @@ const getAuthHooks = (agentManager) => {
83
87
  finally {
84
88
  setLoginLoading(false);
85
89
  }
86
- }));
90
+ });
87
91
  onLogin === null || onLogin === void 0 ? void 0 : onLogin(() => loginPromise);
88
92
  }), [
89
93
  authClient,
@@ -120,7 +124,6 @@ const getAuthHooks = (agentManager) => {
120
124
  };
121
125
  return {
122
126
  useUserPrincipal,
123
- useAgentManager,
124
127
  useAuthStore,
125
128
  useAuthClient,
126
129
  };
@@ -0,0 +1,5 @@
1
+ export * from "./useActor";
2
+ export * from "./useCandid";
3
+ export * from "./agent";
4
+ export * from "./actor";
5
+ export * from "./auth";
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./useActor"), exports);
18
+ __exportStar(require("./useCandid"), exports);
19
+ __exportStar(require("./agent"), exports);
20
+ __exportStar(require("./actor"), exports);
21
+ __exportStar(require("./auth"), exports);
@@ -0,0 +1,15 @@
1
+ import { ActorManagerOptions, BaseActor, IDL } from "@ic-reactor/core";
2
+ import { AgentContextType } from "../context/agent";
3
+ interface DynamicActorArgs extends Omit<ActorManagerOptions, "idlFactory" | "agentManager" | "canisterId"> {
4
+ canisterId: string;
5
+ idlFactory?: IDL.InterfaceFactory;
6
+ agentContext?: AgentContextType;
7
+ didjsCanisterId?: string;
8
+ }
9
+ export declare const useActor: <A = BaseActor>({ canisterId, agentContext, idlFactory: maybeIdlFactory, didjsCanisterId, ...config }: DynamicActorArgs) => {
10
+ fetchCandid: () => Promise<import("@ic-reactor/core").CandidDefenition | undefined>;
11
+ fetching: boolean;
12
+ fetchError: string | null;
13
+ actorManager: import("@ic-reactor/core").ActorManager<A> | null;
14
+ };
15
+ export {};
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ var __rest = (this && this.__rest) || function (s, e) {
3
+ var t = {};
4
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
+ t[p] = s[p];
6
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
+ t[p[i]] = s[p[i]];
10
+ }
11
+ return t;
12
+ };
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.useActor = void 0;
15
+ const core_1 = require("@ic-reactor/core");
16
+ const react_1 = require("react");
17
+ const agent_1 = require("../context/agent");
18
+ const useCandid_1 = require("./useCandid");
19
+ const useActor = (_a) => {
20
+ var { canisterId, agentContext, idlFactory: maybeIdlFactory, didjsCanisterId } = _a, config = __rest(_a, ["canisterId", "agentContext", "idlFactory", "didjsCanisterId"]);
21
+ const agentManager = (0, agent_1.useAgentManager)(agentContext);
22
+ const _b = (0, useCandid_1.useCandid)({
23
+ canisterId,
24
+ didjsCanisterId,
25
+ idlFactory: maybeIdlFactory,
26
+ }), { candid: { idlFactory } } = _b, rest = __rest(_b, ["candid"]);
27
+ const actorManager = (0, react_1.useMemo)(() => {
28
+ if (!idlFactory) {
29
+ return null;
30
+ }
31
+ else {
32
+ const manager = (0, core_1.createReActorStore)({
33
+ agentManager,
34
+ idlFactory,
35
+ canisterId,
36
+ withDevtools: config.withDevtools,
37
+ });
38
+ return manager;
39
+ }
40
+ }, [idlFactory]);
41
+ return Object.assign({ actorManager }, rest);
42
+ };
43
+ exports.useActor = useActor;
@@ -0,0 +1,18 @@
1
+ import type { IDL } from "@dfinity/candid";
2
+ interface UseIDLFactoryArgs {
3
+ canisterId: string;
4
+ didjsCanisterId?: string;
5
+ idlFactory?: IDL.InterfaceFactory;
6
+ }
7
+ export declare const useCandid: ({ canisterId, didjsCanisterId, idlFactory, }: UseIDLFactoryArgs) => {
8
+ fetchCandid: () => Promise<import("@ic-reactor/core").CandidDefenition | undefined>;
9
+ candid: {
10
+ idlFactory?: IDL.InterfaceFactory | undefined;
11
+ init: ({ idl }: {
12
+ idl: typeof IDL;
13
+ }) => never[];
14
+ };
15
+ fetching: boolean;
16
+ fetchError: string | null;
17
+ };
18
+ export {};
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.useCandid = void 0;
13
+ const react_1 = require("react");
14
+ const core_1 = require("@ic-reactor/core");
15
+ const agent_1 = require("../context/agent");
16
+ const DEFAULT_STATE = {
17
+ candid: { idlFactory: undefined, init: () => [] },
18
+ fetching: false,
19
+ fetchError: null,
20
+ };
21
+ const useCandid = ({ canisterId, didjsCanisterId, idlFactory, }) => {
22
+ const [{ candid, fetchError, fetching }, setCandid] = (0, react_1.useState)(Object.assign(Object.assign({}, DEFAULT_STATE), { candid: {
23
+ idlFactory,
24
+ init: () => [],
25
+ } }));
26
+ const agent = (0, agent_1.useAgentContext)();
27
+ const fetchCandid = (0, react_1.useCallback)(() => __awaiter(void 0, void 0, void 0, function* () {
28
+ if (!canisterId || !agent)
29
+ return;
30
+ setCandid((prevState) => (Object.assign(Object.assign({}, prevState), { candid: DEFAULT_STATE.candid, fetching: true, fetchError: null })));
31
+ try {
32
+ const candidManager = (0, core_1.createCandidAdapter)({ agent, didjsCanisterId });
33
+ const fetchedCandid = yield candidManager.getCandidDefinition(canisterId);
34
+ setCandid({
35
+ candid: fetchedCandid,
36
+ fetching: false,
37
+ fetchError: null,
38
+ });
39
+ return fetchedCandid;
40
+ }
41
+ catch (err) {
42
+ // eslint-disable-next-line no-console
43
+ console.error(err);
44
+ setCandid((prevState) => (Object.assign(Object.assign({}, prevState), { fetchError: `Error fetching canister ${canisterId}`, fetching: false })));
45
+ }
46
+ }), [canisterId, didjsCanisterId, agent]);
47
+ (0, react_1.useEffect)(() => {
48
+ if (!fetching && !idlFactory) {
49
+ fetchCandid();
50
+ }
51
+ }, [fetchCandid]);
52
+ return { fetchCandid, candid, fetching, fetchError };
53
+ };
54
+ exports.useCandid = useCandid;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,31 @@
1
- import { CreateReActor } from "./types";
2
- export * from "@ic-reactor/store";
1
+ import { CreateReActorOptions, BaseActor } from "@ic-reactor/core";
2
+ export { createReActor as createReActorCore } from "@ic-reactor/core";
3
+ export * from "@ic-reactor/core";
3
4
  export * from "./context/agent";
4
5
  export * from "./context/actor";
5
- export declare const createReActor: CreateReActor;
6
+ export * from "./hooks";
7
+ export declare const createReActor: <A = BaseActor>({ isLocalEnv, withVisitor, withProcessEnv, ...options }: CreateReActorOptions) => {
8
+ useUserPrincipal: () => import("@dfinity/principal").Principal | undefined;
9
+ useAuthStore: () => import("@ic-reactor/core").AuthState;
10
+ useAuthClient: ({ onAuthentication, onAuthenticationSuccess, onAuthenticationFailure, onLogin, onLoginSuccess, onLoginError, onLoggedOut, }?: import("./types").AuthArgs) => {
11
+ authClient: import("@dfinity/auth-client").AuthClient | null;
12
+ authenticated: boolean;
13
+ authenticating: boolean;
14
+ identity: import("@ic-reactor/core").Identity | null;
15
+ login: (options?: import("@dfinity/auth-client").AuthClientLoginOptions | undefined) => Promise<void>;
16
+ logout: (options?: {
17
+ returnTo?: string | undefined;
18
+ } | undefined) => Promise<void>;
19
+ authenticate: () => Promise<import("@ic-reactor/core").Identity>;
20
+ loginLoading: boolean;
21
+ loginError: Error | null;
22
+ };
23
+ initialize: () => Promise<void>;
24
+ useActorState: () => import("./types").UseActorStoreReturn<A>;
25
+ useQueryCall: import("./types").ActorQueryCall<A>;
26
+ useUpdateCall: import("./types").ActorUpdateCall<A>;
27
+ useMethodCall: <M extends import("@ic-reactor/core").FunctionName<A>>(args: import("./types").ActorUseMethodCallArg<A, M>) => import("./types").ActorUseMethodCallReturn<A, M, true>;
28
+ useVisitMethod: <M_1 extends import("@ic-reactor/core").FunctionName<A>>(functionName: M_1) => import("@ic-reactor/core").VisitService<A>[M_1];
29
+ getAgent: () => import("@ic-reactor/core").HttpAgent;
30
+ getVisitFunction: () => import("@ic-reactor/core").VisitService<A>;
31
+ };
package/dist/index.js CHANGED
@@ -25,32 +25,39 @@ var __rest = (this && this.__rest) || function (s, e) {
25
25
  return t;
26
26
  };
27
27
  Object.defineProperty(exports, "__esModule", { value: true });
28
- exports.createReActor = void 0;
29
- const store_1 = require("@ic-reactor/store");
28
+ exports.createReActor = exports.createReActorCore = void 0;
29
+ const core_1 = require("@ic-reactor/core");
30
30
  const actor_1 = require("./hooks/actor");
31
31
  const auth_1 = require("./hooks/auth");
32
- __exportStar(require("@ic-reactor/store"), exports);
32
+ var core_2 = require("@ic-reactor/core");
33
+ Object.defineProperty(exports, "createReActorCore", { enumerable: true, get: function () { return core_2.createReActor; } });
34
+ __exportStar(require("@ic-reactor/core"), exports);
33
35
  __exportStar(require("./context/agent"), exports);
34
36
  __exportStar(require("./context/actor"), exports);
37
+ __exportStar(require("./hooks"), exports);
35
38
  const createReActor = (_a) => {
36
- var { isLocalEnv, withServiceFields } = _a, options = __rest(_a, ["isLocalEnv", "withServiceFields"]);
39
+ var { isLocalEnv, withVisitor, withProcessEnv } = _a, options = __rest(_a, ["isLocalEnv", "withVisitor", "withProcessEnv"]);
37
40
  isLocalEnv =
38
41
  isLocalEnv ||
39
- (typeof process !== "undefined" &&
40
- (process.env.DFX_NETWORK === "local" ||
41
- process.env.NODE_ENV === "development"));
42
- const actorManager = (0, store_1.createReActorStore)(Object.assign({ isLocalEnv,
43
- withServiceFields }, options));
44
- const getServiceFields = () => {
45
- if (!withServiceFields || !actorManager.serviceFields) {
46
- throw new Error("Service fields not initialized. Pass `withServiceFields` to initialize service fields.");
42
+ (withProcessEnv
43
+ ? typeof process !== "undefined" &&
44
+ (process.env.DFX_NETWORK === "local" ||
45
+ process.env.NODE_ENV === "development")
46
+ : false);
47
+ const actorManager = (0, core_1.createReActorStore)(Object.assign({ isLocalEnv,
48
+ withVisitor }, options));
49
+ const getVisitFunction = () => {
50
+ if (!withVisitor) {
51
+ throw new Error("Service fields not initialized. Pass `withVisitor` to initialize service fields.");
47
52
  }
48
- return actorManager.serviceFields;
53
+ return actorManager.visitFunction;
49
54
  };
50
55
  const getAgent = () => {
51
56
  return actorManager.agentManager.getAgent();
52
57
  };
58
+ const actorHooks = (0, actor_1.getActorHooks)(actorManager);
59
+ const authHooks = (0, auth_1.getAuthHooks)(actorManager.agentManager);
53
60
  return Object.assign(Object.assign({ getAgent,
54
- getServiceFields }, (0, actor_1.getActorHooks)(actorManager)), (0, auth_1.getAuthHooks)(actorManager.agentManager));
61
+ getVisitFunction }, actorHooks), authHooks);
55
62
  };
56
63
  exports.createReActor = createReActor;
package/dist/types.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  /// <reference types="react" />
2
- import type { ActorState, ActorSubclass, CanisterId, CreateReActorOptions, ExtractActorMethodArgs, ExtractActorMethodReturnType, ExtractedFunction, ExtractedService, HttpAgent, Identity, Principal, ServiceMethodType, ServiceMethodTypeAndName } from "@ic-reactor/store";
2
+ import type { ActorState, CanisterId, CreateReActorOptions, ActorMethodArgs, ActorMethodReturnType, HttpAgent, Identity, Principal, FunctionName, VisitService } from "@ic-reactor/core";
3
3
  import type { AuthHooks } from "./hooks/auth";
4
+ import { AgentHooks } from "./hooks/agent";
4
5
  export type AuthArgs = {
5
6
  onAuthentication?: (promise: () => Promise<Identity>) => void;
6
7
  onAuthenticationSuccess?: (identity: Identity) => void;
@@ -10,70 +11,63 @@ export type AuthArgs = {
10
11
  onLogin?: (promise: () => Promise<Principal>) => void;
11
12
  onLoggedOut?: () => void;
12
13
  };
13
- export type ActorCallArgs<A, M extends keyof A> = {
14
- functionName: M & string;
15
- args?: ExtractActorMethodArgs<A[M]>;
14
+ export type ActorCallArgs<A, M extends FunctionName<A>> = {
15
+ functionName: M;
16
+ args?: ActorMethodArgs<A[M]>;
16
17
  onLoading?: (loading: boolean) => void;
17
18
  onError?: (error: Error | undefined) => void;
18
- onSuccess?: (data: ExtractActorMethodReturnType<A[M]> | undefined) => void;
19
+ onSuccess?: (data: ActorMethodReturnType<A[M]> | undefined) => void;
19
20
  throwOnError?: boolean;
20
21
  };
21
- export type ActorHookState<A, M extends keyof A> = {
22
- data: ExtractActorMethodReturnType<A[M]> | undefined;
22
+ export type ActorHookState<A, M extends FunctionName<A>> = {
23
+ data: ActorMethodReturnType<A[M]> | undefined;
23
24
  error: Error | undefined;
24
25
  loading: boolean;
25
26
  };
26
- export interface ActorUseQueryArgs<A, M extends keyof A> extends ActorCallArgs<A, M> {
27
+ export interface ActorUseQueryArgs<A, M extends FunctionName<A>> extends ActorCallArgs<A, M> {
27
28
  refetchOnMount?: boolean;
28
29
  refetchInterval?: number | false;
29
30
  }
30
- export interface ActorUseQueryReturn<A, M extends keyof A, W extends boolean = false> {
31
- call: (eventOrReplaceArgs?: React.MouseEvent | ExtractActorMethodArgs<A[M]>) => Promise<unknown>;
32
- field: W extends true ? ExtractedFunction<A> : undefined;
33
- data: unknown;
34
- error: Error | undefined;
35
- loading: boolean;
31
+ export interface ActorUseUpdateArgs<A, M extends FunctionName<A>> extends ActorCallArgs<A, M> {
36
32
  }
37
- export interface ActorUseUpdateArgs<A, M extends keyof A> extends ActorCallArgs<A, M> {
38
- }
39
- export interface ActorUseUpdateReturn<A, M extends keyof A, W extends boolean = false> {
40
- call: (eventOrReplaceArgs?: React.MouseEvent | ExtractActorMethodArgs<A[M]>) => Promise<unknown>;
41
- field: W extends true ? ExtractedFunction<A> : undefined;
42
- data: unknown;
33
+ export type ActorCallReturn<A, M extends FunctionName<A>> = ActorHookState<A, M> & {
34
+ reset: () => void;
35
+ call: (eventOrReplaceArgs?: React.MouseEvent | ActorMethodArgs<A[M]>) => Promise<ActorMethodReturnType<A[M]> | undefined>;
36
+ };
37
+ export type ActorCall<A> = <M extends FunctionName<A>>(args: ActorCallArgs<A, M>) => ActorCallReturn<A, M>;
38
+ export type ActorQueryCall<A> = <M extends FunctionName<A>>(args: ActorUseQueryArgs<A, M>) => ActorCallReturn<A, M>;
39
+ export type ActorUpdateCall<A> = <M extends FunctionName<A>>(args: ActorUseUpdateArgs<A, M>) => ActorCallReturn<A, M>;
40
+ export type ActorMethodCall<A, M extends FunctionName<A>> = (args: ActorUseMethodCallArg<A, M>) => ActorUseMethodCallReturn<A, M>;
41
+ export interface ActorUseMethodCallReturn<A, M extends FunctionName<A>, F extends boolean = false> extends ActorCallReturn<A, M> {
42
+ visit: F extends true ? VisitService<A>[M] : undefined;
43
+ reset: () => void;
43
44
  error: Error | undefined;
44
45
  loading: boolean;
45
46
  }
46
- export type ActorUseMethodArg<A, T extends ServiceMethodType> = T extends "query" ? ActorUseQueryArgs<A, keyof A> : ActorUseUpdateArgs<A, keyof A>;
47
- export type ActorHooksWithField<A> = ActorDefaultHooks<A, true> & ActorFieldHooks<A>;
48
- export type ActorHooksWithoutField<A> = ActorDefaultHooks<A, false>;
49
- export type ActorHooks<A, W extends boolean | undefined = undefined> = W extends true ? ActorHooksWithField<A> : W extends false ? ActorHooksWithoutField<A> : ActorHooksWithField<A> | ActorHooksWithoutField<A>;
47
+ export type ActorUseMethodCallArg<A, M extends FunctionName<A>> = ActorCallArgs<A, M>;
48
+ export type ActorHooks<A, F extends boolean = false> = ActorDefaultHooks<A, F> & (F extends true ? ActorFieldHooks<A> : object);
50
49
  export interface ActorFieldHooks<A> {
51
- useServiceFields: () => ExtractedService<A>;
52
- useMethodFields: () => ExtractedFunction<A>[];
53
- useMethodField: (functionName: keyof A & string) => ExtractedFunction<A>;
54
- useMethods: () => ServiceMethodTypeAndName<A>[];
50
+ useVisitMethod: <M extends FunctionName<A>>(functionName: M) => VisitService<A>[M];
55
51
  }
56
52
  export type UseActorStoreReturn<A> = ActorState<A> & {
57
53
  canisterId: CanisterId;
58
54
  };
59
- export interface ActorDefaultHooks<A, W extends boolean = false> {
55
+ export interface ActorDefaultHooks<A, F extends boolean> {
60
56
  initialize: () => Promise<void>;
61
- useActorStore: () => UseActorStoreReturn<A>;
62
- useQueryCall: <M extends keyof A>(args: ActorUseQueryArgs<A, M>) => ActorUseQueryReturn<A, M, W>;
63
- useUpdateCall: <M extends keyof A>(args: ActorUseUpdateArgs<A, M>) => ActorUseUpdateReturn<A, M, W>;
64
- useMethodCall: <M extends keyof A, T extends ServiceMethodType>(args: ActorUseMethodArg<A, T> & {
65
- type: T;
66
- }) => T extends "query" ? ActorUseQueryReturn<A, M, W> : ActorUseUpdateReturn<A, M, W>;
57
+ useActorState: () => UseActorStoreReturn<A>;
58
+ useQueryCall: ActorQueryCall<A>;
59
+ useUpdateCall: ActorUpdateCall<A>;
60
+ useMethodCall: <M extends FunctionName<A>>(args: ActorUseMethodCallArg<A, M>) => ActorUseMethodCallReturn<A, M, F>;
67
61
  }
68
62
  export type GetFunctions<A> = {
69
63
  getAgent: () => HttpAgent;
70
- getServiceFields: () => ExtractedService<A>;
64
+ getVisitFunction: () => VisitService<A>;
71
65
  };
72
66
  export type CreateReActor = {
73
- <A extends ActorSubclass<any>>(options: CreateReActorOptions & {
74
- withServiceFields: true;
75
- }): GetFunctions<A> & ActorHooksWithField<A> & AuthHooks;
76
- <A extends ActorSubclass<any>>(options: CreateReActorOptions & {
77
- withServiceFields?: false | undefined;
78
- }): GetFunctions<A> & ActorHooksWithoutField<A> & AuthHooks;
67
+ <A>(options: CreateReActorOptions & {
68
+ withVisitor: true;
69
+ }): GetFunctions<A> & ActorHooks<A, true> & AuthHooks & AgentHooks;
70
+ <A>(options: CreateReActorOptions & {
71
+ withVisitor?: false | undefined;
72
+ }): GetFunctions<A> & ActorHooks<A, false> & AuthHooks & AgentHooks;
79
73
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ic-reactor/react",
3
- "version": "0.5.5",
4
- "description": "A React library for interacting with Dfinity actors",
3
+ "version": "1.0.0",
4
+ "description": "A React library for interacting with Internet Computer canisters",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "files": [
@@ -35,18 +35,18 @@
35
35
  "node": ">=10"
36
36
  },
37
37
  "dependencies": {
38
- "@ic-reactor/store": "^0.5.3",
38
+ "@ic-reactor/core": "^1.0.0",
39
39
  "zustand-utils": "^1.3"
40
40
  },
41
41
  "peerDependencies": {
42
- "@dfinity/agent": "^0.20",
43
- "@dfinity/auth-client": "^0.20",
44
- "@dfinity/candid": "0.20",
45
- "@dfinity/identity": "^0.20",
46
- "@dfinity/principal": "^0.20",
42
+ "@dfinity/agent": "^1.0",
43
+ "@dfinity/auth-client": "^1.0",
44
+ "@dfinity/candid": "1.0",
45
+ "@dfinity/identity": "^1.0",
46
+ "@dfinity/principal": "^1.0",
47
47
  "@peculiar/webcrypto": "1.4",
48
48
  "react": ">=16.8",
49
- "zustand": "4.4"
49
+ "zustand": "4.5"
50
50
  },
51
- "gitHead": "3f3c31450f315083c0aa18978a7ec876333037c2"
51
+ "gitHead": "ca9e2f3438a4566c26d5ce56b0f0b953aa93df53"
52
52
  }
@@ -1,16 +0,0 @@
1
- import React, { PropsWithChildren } from "react";
2
- import { IDL } from "@dfinity/candid";
3
- import { ActorSubclass, ActorManagerOptions } from "@ic-reactor/store";
4
- import { AgentContextType } from "./agent";
5
- import { ActorHooksWithField } from "../types";
6
- export type ActorContextType<A = ActorSubclass<any>> = ActorHooksWithField<A>;
7
- export declare const ActorContext: React.Context<ActorContextType<any> | null>;
8
- type UseActorType = <A = ActorSubclass<any>>() => ActorContextType<A>;
9
- export declare const useActor: UseActorType;
10
- interface ActorProviderProps extends PropsWithChildren, Omit<ActorManagerOptions, "idlFactory" | "agentManager"> {
11
- agentContext?: AgentContextType;
12
- idlFactory?: IDL.InterfaceFactory;
13
- loadingComponent?: React.ReactNode;
14
- }
15
- export declare const ActorProvider: React.FC<ActorProviderProps>;
16
- export {};
@@ -1,125 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
- var __rest = (this && this.__rest) || function (s, e) {
35
- var t = {};
36
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
37
- t[p] = s[p];
38
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
39
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
40
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
41
- t[p[i]] = s[p[i]];
42
- }
43
- return t;
44
- };
45
- Object.defineProperty(exports, "__esModule", { value: true });
46
- exports.ActorProvider = exports.useActor = exports.ActorContext = void 0;
47
- const react_1 = __importStar(require("react"));
48
- const index_1 = require("../index");
49
- const store_1 = require("@ic-reactor/store");
50
- const agent_1 = require("./agent");
51
- exports.ActorContext = (0, react_1.createContext)(null);
52
- const useActor = () => {
53
- const context = (0, react_1.useContext)(exports.ActorContext);
54
- if (!context) {
55
- throw new Error("useActor must be used within a ActorProvider");
56
- }
57
- return context;
58
- };
59
- exports.useActor = useActor;
60
- const ActorProvider = (_a) => {
61
- var { children, canisterId, agentContext, loadingComponent = react_1.default.createElement("div", null, "Loading..."), withServiceFields = false } = _a, config = __rest(_a, ["children", "canisterId", "agentContext", "loadingComponent", "withServiceFields"]);
62
- const agentManager = (0, agent_1.useAgentManager)(agentContext);
63
- const [didJs, setDidJS] = (0, react_1.useState)();
64
- const [fetching, setFetching] = (0, react_1.useState)(false);
65
- const fetchDidJs = (0, react_1.useCallback)(() => __awaiter(void 0, void 0, void 0, function* () {
66
- if (!canisterId) {
67
- throw new Error("canisterId is required");
68
- }
69
- if (fetching) {
70
- return;
71
- }
72
- setFetching(true);
73
- const agent = agentManager.getAgent();
74
- (0, store_1.getDidJsFromMetadata)(agent, canisterId).then((idlFactory) => __awaiter(void 0, void 0, void 0, function* () {
75
- if (!idlFactory) {
76
- try {
77
- idlFactory = yield (0, store_1.getDidJsFromTmpHack)(agent, canisterId);
78
- }
79
- catch (err) {
80
- if (/no query method/.test(err)) {
81
- console.warn(err);
82
- idlFactory = undefined;
83
- }
84
- else {
85
- throw err;
86
- }
87
- }
88
- if (!idlFactory) {
89
- console.warn("No query method found for canister", canisterId);
90
- }
91
- }
92
- setDidJS(idlFactory);
93
- setFetching(false);
94
- }));
95
- }), [canisterId, agentManager]);
96
- (0, react_1.useEffect)(() => {
97
- const { idlFactory } = config;
98
- if (idlFactory) {
99
- setDidJS({ idlFactory });
100
- return;
101
- }
102
- console.log("idlFactory not provided, fetching from canister...");
103
- fetchDidJs();
104
- }, [fetchDidJs, config.idlFactory]);
105
- const hooks = (0, react_1.useMemo)(() => {
106
- if (!didJs) {
107
- return null;
108
- }
109
- try {
110
- return (0, index_1.createReActor)({
111
- idlFactory: didJs.idlFactory,
112
- agentManager,
113
- canisterId,
114
- withDevtools: config.withDevtools,
115
- withServiceFields: withServiceFields,
116
- });
117
- }
118
- catch (err) {
119
- console.error(err);
120
- return null;
121
- }
122
- }, [canisterId, agentManager, didJs]);
123
- return (react_1.default.createElement(exports.ActorContext.Provider, { value: hooks }, fetching || hooks === null ? loadingComponent : children));
124
- };
125
- exports.ActorProvider = ActorProvider;
@@ -1,16 +0,0 @@
1
- import React, { PropsWithChildren } from "react";
2
- import { AgentManager, AgentManagerOptions } from "@ic-reactor/store";
3
- import { getAuthHooks } from "../hooks/auth";
4
- export type AgentContextValue = ReturnType<typeof getAuthHooks> & {
5
- agentManager: AgentManager;
6
- };
7
- export type AgentContextType = React.Context<AgentContextValue | null>;
8
- export declare const AgentContext: React.Context<AgentContextValue | null>;
9
- export declare const useAgent: (agentContext?: AgentContextType) => AgentContextValue;
10
- export declare const useAgentManager: (agentContext?: AgentContextType) => AgentManager;
11
- export declare const createAgentContext: (config: AgentManagerOptions) => AgentContextValue;
12
- interface AgentProviderProps extends PropsWithChildren, AgentManagerOptions {
13
- agentManager?: AgentManager;
14
- }
15
- export declare const AgentProvider: React.FC<AgentProviderProps>;
16
- export {};