@ic-reactor/core 0.5.3 → 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,187 @@
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
19
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
20
+ };
21
+ var __importStar = (this && this.__importStar) || function (mod) {
22
+ if (mod && mod.__esModule) return mod;
23
+ var result = {};
24
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
25
+ __setModuleDefault(result, mod);
26
+ return result;
27
+ };
28
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
29
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
30
+ return new (P || (P = Promise))(function (resolve, reject) {
31
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
32
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
33
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
34
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
35
+ });
36
+ };
37
+ var __rest = (this && this.__rest) || function (s, e) {
38
+ var t = {};
39
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
40
+ t[p] = s[p];
41
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
42
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
43
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
44
+ t[p[i]] = s[p[i]];
45
+ }
46
+ return t;
47
+ };
48
+ Object.defineProperty(exports, "__esModule", { value: true });
49
+ exports.AgentManager = exports.LOCAL_HOST_NETWORK_URI = exports.IC_HOST_NETWORK_URI = void 0;
50
+ const agent_1 = require("@dfinity/agent");
51
+ const helper_1 = require("../tools/helper");
52
+ __exportStar(require("./types"), exports);
53
+ exports.IC_HOST_NETWORK_URI = "https://ic0.app";
54
+ exports.LOCAL_HOST_NETWORK_URI = "http://127.0.0.1:4943";
55
+ class AgentManager {
56
+ constructor(options) {
57
+ this._subscribers = [];
58
+ this.initialAgentState = {
59
+ initialized: false,
60
+ initializing: false,
61
+ error: undefined,
62
+ };
63
+ this.initialAuthState = {
64
+ identity: null,
65
+ authClient: null,
66
+ authenticating: false,
67
+ authenticated: false,
68
+ error: undefined,
69
+ };
70
+ this.updateAgentState = (newState) => {
71
+ this.agentStore.setState((state) => (Object.assign(Object.assign({}, state), newState)));
72
+ };
73
+ this.updateAuthState = (newState) => {
74
+ this.authStore.setState((state) => (Object.assign(Object.assign({}, state), newState)));
75
+ };
76
+ this.initializeAgent = () => __awaiter(this, void 0, void 0, function* () {
77
+ this.updateAgentState({ initializing: true });
78
+ if (this.isLocalEnv) {
79
+ try {
80
+ yield this._agent.fetchRootKey();
81
+ this.updateAgentState({ initialized: true, initializing: false });
82
+ }
83
+ catch (error) {
84
+ this.updateAgentState({ error: error, initializing: false });
85
+ }
86
+ }
87
+ });
88
+ this.subscribeAgent = (callback) => {
89
+ this._subscribers.push(callback);
90
+ return () => this.unsubscribeAgent(callback);
91
+ };
92
+ this.unsubscribeAgent = (callback) => {
93
+ this._subscribers = this._subscribers.filter((sub) => sub !== callback);
94
+ };
95
+ this.notifySubscribers = () => {
96
+ this._subscribers.forEach((callback) => callback(this._agent));
97
+ };
98
+ this.updateAgent = (options) => __awaiter(this, void 0, void 0, function* () {
99
+ const { agent } = options || {};
100
+ if (agent) {
101
+ this._agent = agent;
102
+ }
103
+ else if (options) {
104
+ this._agent = new agent_1.HttpAgent(options);
105
+ this.isLocalEnv = this._agent.isLocal();
106
+ yield this.initializeAgent();
107
+ }
108
+ this.notifySubscribers();
109
+ });
110
+ this.authenticate = () => __awaiter(this, void 0, void 0, function* () {
111
+ this.updateAuthState({ authenticating: true });
112
+ try {
113
+ const { AuthClient } = yield Promise.resolve().then(() => __importStar(require("@dfinity/auth-client"))).catch((error) => {
114
+ // eslint-disable-next-line no-console
115
+ console.error("Failed to import @dfinity/auth-client:", error);
116
+ throw new Error("Authentication failed: @dfinity/auth-client package is missing.");
117
+ });
118
+ const authClient = yield AuthClient.create();
119
+ const authenticated = yield authClient.isAuthenticated();
120
+ const identity = authClient.getIdentity();
121
+ this._agent.replaceIdentity(identity);
122
+ this.notifySubscribers();
123
+ this.updateAuthState({
124
+ authClient,
125
+ authenticated,
126
+ identity,
127
+ authenticating: false,
128
+ });
129
+ return identity;
130
+ }
131
+ catch (error) {
132
+ this.updateAuthState({ error: error, authenticating: false });
133
+ throw error;
134
+ }
135
+ });
136
+ // agent store
137
+ this.getAgent = () => {
138
+ return this._agent;
139
+ };
140
+ this.getAgentStore = () => {
141
+ return this.agentStore;
142
+ };
143
+ this.getAgentState = () => {
144
+ return this.agentStore.getState();
145
+ };
146
+ this.subscribeAgentState = (listener) => {
147
+ return this.agentStore.subscribe(listener);
148
+ };
149
+ // auth store
150
+ this.getAuthState = () => {
151
+ return this.authStore.getState();
152
+ };
153
+ this.subscribeAuthState = (listener) => {
154
+ return this.authStore.subscribe(listener);
155
+ };
156
+ this.getAuthClient = () => {
157
+ return this.authStore.getState().authClient;
158
+ };
159
+ this.getIdentity = () => {
160
+ return this.authStore.getState().identity;
161
+ };
162
+ this.getPrincipal = () => {
163
+ const identity = this.authStore.getState().identity;
164
+ return identity ? identity.getPrincipal() : null;
165
+ };
166
+ const _a = options || {}, { withDevtools, port = 4943, isLocalEnv, host: optionHost } = _a, agentOptions = __rest(_a, ["withDevtools", "port", "isLocalEnv", "host"]);
167
+ const host = isLocalEnv
168
+ ? `http://127.0.0.1:${port}`
169
+ : optionHost
170
+ ? optionHost.includes("localhost")
171
+ ? optionHost.replace("localhost", "127.0.0.1")
172
+ : optionHost
173
+ : exports.IC_HOST_NETWORK_URI;
174
+ this.agentStore = (0, helper_1.createStoreWithOptionalDevtools)(this.initialAgentState, {
175
+ withDevtools,
176
+ store: "agent",
177
+ });
178
+ this.authStore = (0, helper_1.createStoreWithOptionalDevtools)(this.initialAuthState, {
179
+ withDevtools,
180
+ store: "auth",
181
+ });
182
+ this._agent = new agent_1.HttpAgent(Object.assign(Object.assign({}, agentOptions), { host }));
183
+ this.isLocalEnv = this._agent.isLocal();
184
+ this.initializeAgent();
185
+ }
186
+ }
187
+ exports.AgentManager = AgentManager;
@@ -0,0 +1,26 @@
1
+ import type { HttpAgent, HttpAgentOptions, Identity } from "@dfinity/agent";
2
+ import type { AuthClient } from "@dfinity/auth-client";
3
+ import type { StoreApi } from "zustand";
4
+ export { HttpAgentOptions, AuthClient, Identity };
5
+ export interface AgentManagerOptions extends HttpAgentOptions {
6
+ port?: number;
7
+ isLocalEnv?: boolean;
8
+ withDevtools?: boolean;
9
+ }
10
+ export interface AgentState {
11
+ initialized: boolean;
12
+ initializing: boolean;
13
+ error: Error | undefined;
14
+ }
15
+ export interface AuthState {
16
+ identity: Identity | null;
17
+ authClient: AuthClient | null;
18
+ authenticating: boolean;
19
+ authenticated: boolean;
20
+ error: Error | undefined;
21
+ }
22
+ export interface UpdateAgentOptions extends HttpAgentOptions {
23
+ agent?: HttpAgent;
24
+ }
25
+ export type AgentStore = StoreApi<AgentState>;
26
+ export type AuthStore = StoreApi<AuthState>;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/dist/index.d.ts CHANGED
@@ -1,20 +1,56 @@
1
- import type { CreateReActorOptions } from "@ic-reactor/store";
2
- import { ActorQuery, ActorUpdate } from "./types";
3
- export declare const createReActor: <A extends unknown>(options: CreateReActorOptions) => {
4
- canisterId: import("@ic-reactor/store").CanisterId;
5
- withServiceFields: boolean;
6
- serviceFields?: import("@ic-reactor/store").ExtractedService<A> | undefined;
7
- unsubscribeActor: () => void;
8
- initialize: (options?: import("@ic-reactor/store").UpdateAgentOptions | undefined) => Promise<void>;
9
- updateMethodState: (newState: Partial<import("@ic-reactor/store").ActorMethodStates<A>>) => void;
10
- isLocalEnv: boolean;
11
- subscribeAgent: (callback: (agent: import("@ic-reactor/store").HttpAgent) => void) => () => void;
12
- unsubscribeAgent: (callback: (agent: import("@ic-reactor/store").HttpAgent) => void) => void;
13
- updateAgent: (options?: import("@ic-reactor/store").UpdateAgentOptions | undefined) => Promise<void>;
14
- authenticate: () => Promise<import("@ic-reactor/store").Identity>;
15
- getAgent: () => import("@ic-reactor/store").HttpAgent;
16
- actorStore: import("@ic-reactor/store").ActorStore<A>;
17
- authStore: import("@ic-reactor/store").AgentAuthStore;
18
- queryCall: ActorQuery<A>;
19
- updateCall: ActorUpdate<A>;
20
- };
1
+ import type { ActorManagerOptions, BaseActor } from "./actor/types";
2
+ import type { AgentManagerOptions } from "./agent/types";
3
+ import { ActorManager } from "./actor";
4
+ import { AgentManager } from "./agent";
5
+ import type { ActorCoreActions, CreateReActorOptions, CreateReActorStoreOptions } from "./types";
6
+ import { CandidAdapter, CandidAdapterOptions } from "./tools";
7
+ export * from "./types";
8
+ export * from "./actor";
9
+ export * from "./agent";
10
+ export * from "./tools";
11
+ /**
12
+ * Create a new actor manager with the given options.
13
+ * Its create a new agent manager if not provided.
14
+ *
15
+ * @category Main
16
+ * @includeExample ./packages/core/README.md:30-91
17
+ */
18
+ export declare const createReActor: <A = BaseActor>({ isLocalEnv, withProcessEnv, ...options }: CreateReActorOptions) => ActorCoreActions<A>;
19
+ /**
20
+ * Create a new actor manager with the given options.
21
+ * Its create a new agent manager if not provided.
22
+ * It also creates a new actor manager with the given options.
23
+ *
24
+ * @category Main
25
+ * @includeExample ./packages/core/README.md:32-45
26
+ */
27
+ export declare const createReActorStore: <A = BaseActor>(options: CreateReActorStoreOptions) => ActorManager<A>;
28
+ /**
29
+ * Agent manager handles the lifecycle of the `@dfinity/agent`.
30
+ * It is responsible for creating agent and managing the agent's state.
31
+ * You can use it to subscribe to the agent changes.
32
+ * login and logout to the internet identity.
33
+ *
34
+ * @category Main
35
+ * @includeExample ./packages/core/README.md:55-86
36
+ */
37
+ export declare const createAgentManager: (options?: AgentManagerOptions) => AgentManager;
38
+ /**
39
+ * Actor manager handles the lifecycle of the actors.
40
+ * It is responsible for creating and managing the actors.
41
+ * You can use it to call and visit the actor's methods.
42
+ * It also provides a way to interact with the actor's state.
43
+ *
44
+ * @category Main
45
+ * @includeExample ./packages/core/README.md:94-109
46
+ */
47
+ export declare const createActorManager: <A = BaseActor>(options: ActorManagerOptions) => ActorManager<A>;
48
+ /**
49
+ * The `CandidAdapter` class is used to interact with a canister and retrieve its Candid interface definition.
50
+ * It provides methods to fetch the Candid definition either from the canister's metadata or by using a temporary hack method.
51
+ * If both methods fail, it throws an error.
52
+ *
53
+ * @category Main
54
+ * @includeExample ./packages/core/README.md:164-205
55
+ */
56
+ export declare const createCandidAdapter: (options: CandidAdapterOptions) => CandidAdapter;
package/dist/index.js CHANGED
@@ -1,4 +1,18 @@
1
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
+ };
2
16
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
17
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
18
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -20,36 +34,40 @@ var __rest = (this && this.__rest) || function (s, e) {
20
34
  return t;
21
35
  };
22
36
  Object.defineProperty(exports, "__esModule", { value: true });
23
- exports.createReActor = void 0;
24
- const store_1 = require("@ic-reactor/store");
25
- const createReActor = (options) => {
26
- const _a = (0, store_1.createReActorStore)(options), { agentManager, callMethod, actorStore } = _a, rest = __rest(_a, ["agentManager", "callMethod", "actorStore"]);
27
- const { authStore } = agentManager, agentRest = __rest(agentManager, ["authStore"]);
28
- const updateMethodState = (method, args = [], newState) => {
29
- const hash = (0, store_1.generateRequestHash)(args);
30
- actorStore.setState((state) => {
31
- if (!state.methodState) {
32
- console.error("Actor not initialized");
33
- return state;
34
- }
35
- if (!state.methodState[method]) {
36
- console.error(`Method ${String(method)} not found`);
37
- return state;
38
- }
39
- const currentMethodState = state.methodState[method][hash] || {
40
- loading: false,
41
- data: undefined,
42
- error: undefined,
43
- };
44
- return Object.assign(Object.assign({}, state), { methodState: Object.assign(Object.assign({}, state.methodState), { [method]: Object.assign(Object.assign({}, state.methodState[method]), { states: Object.assign(Object.assign({}, state.methodState[method].states), { [hash]: Object.assign(Object.assign({}, currentMethodState), newState) }) }) }) });
45
- });
46
- return hash;
47
- };
37
+ exports.createCandidAdapter = exports.createActorManager = exports.createAgentManager = exports.createReActorStore = exports.createReActor = void 0;
38
+ const actor_1 = require("./actor");
39
+ const agent_1 = require("./agent");
40
+ const tools_1 = require("./tools");
41
+ __exportStar(require("./types"), exports);
42
+ __exportStar(require("./actor"), exports);
43
+ __exportStar(require("./agent"), exports);
44
+ __exportStar(require("./tools"), exports);
45
+ /**
46
+ * Create a new actor manager with the given options.
47
+ * Its create a new agent manager if not provided.
48
+ *
49
+ * @category Main
50
+ * @includeExample ./packages/core/README.md:30-91
51
+ */
52
+ const createReActor = (_a) => {
53
+ var { isLocalEnv, withProcessEnv = false } = _a, options = __rest(_a, ["isLocalEnv", "withProcessEnv"]);
54
+ isLocalEnv =
55
+ isLocalEnv ||
56
+ (withProcessEnv
57
+ ? typeof process !== "undefined" &&
58
+ (process.env.DFX_NETWORK === "local" ||
59
+ process.env.NODE_ENV === "development")
60
+ : false);
61
+ const _b = (0, exports.createReActorStore)(Object.assign({ isLocalEnv }, options)), { subscribeActorState, updateMethodState, callMethod, getState, agentManager } = _b, rest = __rest(_b, ["subscribeActorState", "updateMethodState", "callMethod", "getState", "agentManager"]);
48
62
  const reActorMethod = (functionName, ...args) => {
63
+ const requestHash = (0, tools_1.generateRequestHash)(args);
64
+ const updateState = (newState = {}) => {
65
+ updateMethodState(functionName, requestHash, newState);
66
+ };
67
+ updateState();
49
68
  try {
50
- const requestHash = updateMethodState(functionName, args);
51
- const getState = (key) => {
52
- const state = actorStore.getState().methodState[functionName][requestHash];
69
+ const methodState = ((key) => {
70
+ const state = getState().methodState[functionName][requestHash];
53
71
  switch (key) {
54
72
  case "data":
55
73
  return state.data;
@@ -60,9 +78,9 @@ const createReActor = (options) => {
60
78
  default:
61
79
  return state;
62
80
  }
63
- };
81
+ });
64
82
  const subscribe = (callback) => {
65
- const unsubscribe = actorStore.subscribe((state) => {
83
+ const unsubscribe = subscribeActorState((state) => {
66
84
  const methodState = state.methodState[functionName];
67
85
  const methodStateHash = methodState[requestHash];
68
86
  if (methodStateHash) {
@@ -72,57 +90,138 @@ const createReActor = (options) => {
72
90
  return unsubscribe;
73
91
  };
74
92
  const call = (replaceArgs) => __awaiter(void 0, void 0, void 0, function* () {
75
- updateMethodState(functionName, args, {
93
+ updateState({
76
94
  loading: true,
77
95
  error: undefined,
78
96
  });
79
97
  try {
80
98
  const data = yield callMethod(functionName, ...(replaceArgs !== null && replaceArgs !== void 0 ? replaceArgs : args));
81
- updateMethodState(functionName, args, { data, loading: false });
99
+ updateState({ data, loading: false });
82
100
  return data;
83
101
  }
84
102
  catch (error) {
85
- updateMethodState(functionName, args, {
103
+ updateState({
86
104
  error: error,
87
105
  loading: false,
88
106
  });
89
- console.error(error);
107
+ throw error;
90
108
  }
91
109
  });
92
110
  return {
93
111
  requestHash,
94
112
  subscribe,
95
- getState,
113
+ getState: methodState,
96
114
  call,
97
115
  };
98
116
  }
99
117
  catch (error) {
100
- updateMethodState(functionName, args, {
118
+ updateState({
101
119
  error: error,
102
120
  loading: false,
103
121
  });
104
122
  throw error;
105
123
  }
106
124
  };
107
- const queryCall = ({ functionName, args = [], callOnMount = false, autoRefresh = false, refreshInterval = 5000, }) => {
125
+ const queryCall = ({ functionName, args = [], refetchOnMount = true, refetchInterval = false, }) => {
108
126
  let intervalId = null;
109
127
  const _a = reActorMethod(functionName, ...args), { call } = _a, rest = __rest(_a, ["call"]);
110
- if (autoRefresh) {
128
+ if (refetchInterval) {
111
129
  intervalId = setInterval(() => {
112
130
  call();
113
- }, refreshInterval);
131
+ }, refetchInterval);
114
132
  }
115
- let initialData = Promise.resolve();
116
- if (callOnMount)
117
- initialData = call();
118
- return Object.assign(Object.assign({}, rest), { call, initialData, intervalId });
133
+ let dataPromise = Promise.resolve();
134
+ if (refetchOnMount)
135
+ dataPromise = call();
136
+ return Object.assign(Object.assign({}, rest), { call, dataPromise, intervalId });
119
137
  };
120
138
  const updateCall = ({ functionName, args = [] }) => {
121
139
  return reActorMethod(functionName, ...args);
122
140
  };
123
- return Object.assign(Object.assign({ actorStore,
124
- authStore,
125
- queryCall,
126
- updateCall }, agentRest), rest);
141
+ const login = (options) => __awaiter(void 0, void 0, void 0, function* () {
142
+ const authClient = agentManager.getAuthClient();
143
+ if (!authClient) {
144
+ yield agentManager.authenticate();
145
+ }
146
+ yield authClient.login(Object.assign({ identityProvider: isLocalEnv
147
+ ? "https://identity.ic0.app/#authorize"
148
+ : "http://rdmx6-jaaaa-aaaaa-aaadq-cai.localhost:4943/#authorize" }, options));
149
+ });
150
+ const logout = (options) => __awaiter(void 0, void 0, void 0, function* () {
151
+ const authClient = agentManager.getAuthClient();
152
+ if (!authClient) {
153
+ throw new Error("Auth client not initialized");
154
+ }
155
+ yield authClient.logout(options);
156
+ yield agentManager.authenticate();
157
+ });
158
+ return Object.assign(Object.assign({ queryCall,
159
+ updateCall,
160
+ callMethod,
161
+ getState,
162
+ login,
163
+ logout,
164
+ subscribeActorState }, agentManager), rest);
127
165
  };
128
166
  exports.createReActor = createReActor;
167
+ /**
168
+ * Create a new actor manager with the given options.
169
+ * Its create a new agent manager if not provided.
170
+ * It also creates a new actor manager with the given options.
171
+ *
172
+ * @category Main
173
+ * @includeExample ./packages/core/README.md:32-45
174
+ */
175
+ const createReActorStore = (options) => {
176
+ const { idlFactory, canisterId, withDevtools = false, initializeOnCreate = true, withVisitor = false, agentManager: maybeAgentManager } = options, agentOptions = __rest(options, ["idlFactory", "canisterId", "withDevtools", "initializeOnCreate", "withVisitor", "agentManager"]);
177
+ const agentManager = maybeAgentManager ||
178
+ (0, exports.createAgentManager)(Object.assign({ withDevtools }, agentOptions));
179
+ const actorManager = (0, exports.createActorManager)({
180
+ idlFactory,
181
+ canisterId,
182
+ agentManager,
183
+ withVisitor,
184
+ withDevtools,
185
+ initializeOnCreate,
186
+ });
187
+ return actorManager;
188
+ };
189
+ exports.createReActorStore = createReActorStore;
190
+ /**
191
+ * Agent manager handles the lifecycle of the `@dfinity/agent`.
192
+ * It is responsible for creating agent and managing the agent's state.
193
+ * You can use it to subscribe to the agent changes.
194
+ * login and logout to the internet identity.
195
+ *
196
+ * @category Main
197
+ * @includeExample ./packages/core/README.md:55-86
198
+ */
199
+ const createAgentManager = (options) => {
200
+ return new agent_1.AgentManager(options);
201
+ };
202
+ exports.createAgentManager = createAgentManager;
203
+ /**
204
+ * Actor manager handles the lifecycle of the actors.
205
+ * It is responsible for creating and managing the actors.
206
+ * You can use it to call and visit the actor's methods.
207
+ * It also provides a way to interact with the actor's state.
208
+ *
209
+ * @category Main
210
+ * @includeExample ./packages/core/README.md:94-109
211
+ */
212
+ const createActorManager = (options) => {
213
+ return new actor_1.ActorManager(options);
214
+ };
215
+ exports.createActorManager = createActorManager;
216
+ /**
217
+ * The `CandidAdapter` class is used to interact with a canister and retrieve its Candid interface definition.
218
+ * It provides methods to fetch the Candid definition either from the canister's metadata or by using a temporary hack method.
219
+ * If both methods fail, it throws an error.
220
+ *
221
+ * @category Main
222
+ * @includeExample ./packages/core/README.md:164-205
223
+ */
224
+ const createCandidAdapter = (options) => {
225
+ return new tools_1.CandidAdapter(options);
226
+ };
227
+ exports.createCandidAdapter = createCandidAdapter;
@@ -0,0 +1,15 @@
1
+ import { HttpAgent } from "@dfinity/agent";
2
+ import { CanisterId } from "../actor";
3
+ import { CandidAdapterOptions, CandidDefenition } from "./types";
4
+ export declare const DEFAULT_LOCAL_DIDJS_ID = "bd3sg-teaaa-aaaaa-qaaba-cai";
5
+ export declare const DEFAULT_IC_DIDJS_ID = "a4gq6-oaaaa-aaaab-qaa4q-cai";
6
+ export declare class CandidAdapter {
7
+ agent: HttpAgent;
8
+ didjsCanisterId: string;
9
+ constructor({ agentManager, agent, didjsCanisterId }: CandidAdapterOptions);
10
+ private getDefaultDidJsId;
11
+ getCandidDefinition(canisterId: CanisterId): Promise<CandidDefenition>;
12
+ getFromMetadata(canisterId: CanisterId): Promise<CandidDefenition | undefined>;
13
+ getFromTmpHack(canisterId: CanisterId): Promise<CandidDefenition | undefined>;
14
+ didTojs(candidSource: string): Promise<CandidDefenition>;
15
+ }
@@ -0,0 +1,97 @@
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.CandidAdapter = exports.DEFAULT_IC_DIDJS_ID = exports.DEFAULT_LOCAL_DIDJS_ID = void 0;
13
+ const agent_1 = require("@dfinity/agent");
14
+ const principal_1 = require("@dfinity/principal");
15
+ exports.DEFAULT_LOCAL_DIDJS_ID = "bd3sg-teaaa-aaaaa-qaaba-cai";
16
+ exports.DEFAULT_IC_DIDJS_ID = "a4gq6-oaaaa-aaaab-qaa4q-cai";
17
+ class CandidAdapter {
18
+ constructor({ agentManager, agent, didjsCanisterId }) {
19
+ if (agent) {
20
+ this.agent = agent;
21
+ }
22
+ else if (agentManager) {
23
+ this.agent = agentManager.getAgent();
24
+ agentManager.subscribeAgent((agent) => {
25
+ this.agent = agent;
26
+ this.didjsCanisterId = didjsCanisterId || this.getDefaultDidJsId();
27
+ });
28
+ }
29
+ else {
30
+ throw new Error("No agent or agentManager provided");
31
+ }
32
+ this.didjsCanisterId = didjsCanisterId || this.getDefaultDidJsId();
33
+ }
34
+ getDefaultDidJsId() {
35
+ return this.agent.isLocal() ? exports.DEFAULT_LOCAL_DIDJS_ID : exports.DEFAULT_IC_DIDJS_ID;
36
+ }
37
+ getCandidDefinition(canisterId) {
38
+ return __awaiter(this, void 0, void 0, function* () {
39
+ // First attempt: Try getting Candid definition from metadata
40
+ const fromMetadata = yield this.getFromMetadata(canisterId);
41
+ if (fromMetadata)
42
+ return fromMetadata;
43
+ // Second attempt: Try the temporary hack method
44
+ const fromTmpHack = yield this.getFromTmpHack(canisterId);
45
+ if (fromTmpHack)
46
+ return fromTmpHack;
47
+ // If both attempts fail, throw an error
48
+ throw new Error("Failed to retrieve Candid definition by any method.");
49
+ });
50
+ }
51
+ getFromMetadata(canisterId) {
52
+ return __awaiter(this, void 0, void 0, function* () {
53
+ if (typeof canisterId === "string") {
54
+ canisterId = principal_1.Principal.fromText(canisterId);
55
+ }
56
+ const status = yield agent_1.CanisterStatus.request({
57
+ agent: this.agent,
58
+ canisterId,
59
+ paths: ["candid"],
60
+ });
61
+ const did = status.get("candid");
62
+ return did ? this.didTojs(did) : undefined;
63
+ });
64
+ }
65
+ getFromTmpHack(canisterId) {
66
+ return __awaiter(this, void 0, void 0, function* () {
67
+ const commonInterface = ({ IDL }) => IDL.Service({
68
+ __get_candid_interface_tmp_hack: IDL.Func([], [IDL.Text], ["query"]),
69
+ });
70
+ const actor = agent_1.Actor.createActor(commonInterface, {
71
+ agent: this.agent,
72
+ canisterId,
73
+ });
74
+ const data = (yield actor.__get_candid_interface_tmp_hack());
75
+ return data ? this.didTojs(data) : undefined;
76
+ });
77
+ }
78
+ didTojs(candidSource) {
79
+ return __awaiter(this, void 0, void 0, function* () {
80
+ const didjsInterface = ({ IDL }) => IDL.Service({
81
+ did_to_js: IDL.Func([IDL.Text], [IDL.Opt(IDL.Text)], ["query"]),
82
+ });
83
+ const didjs = agent_1.Actor.createActor(didjsInterface, {
84
+ agent: this.agent,
85
+ canisterId: this.didjsCanisterId,
86
+ });
87
+ const js = yield didjs.did_to_js(candidSource);
88
+ if (JSON.stringify(js) === JSON.stringify([])) {
89
+ throw new Error("Cannot fetch candid file");
90
+ }
91
+ const dataUri = "data:text/javascript;charset=utf-8," +
92
+ encodeURIComponent(js[0]);
93
+ return eval('import("' + dataUri + '")');
94
+ });
95
+ }
96
+ }
97
+ exports.CandidAdapter = CandidAdapter;