Skip to content

Commit

Permalink
Update ESLint rules and fix console errors
Browse files Browse the repository at this point in the history
  • Loading branch information
b3hr4d committed Feb 17, 2024
1 parent 06122bb commit 42290fa
Show file tree
Hide file tree
Showing 7 changed files with 58 additions and 61 deletions.
5 changes: 4 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
"prettier"
],
"rules": {
"typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-unused-vars": [
"error",
{ "argsIgnorePattern": "^_" }
],
"no-console": 1,
"prettier/prettier": 2
},
Expand Down
34 changes: 19 additions & 15 deletions packages/store/src/actor/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Actor } from "@dfinity/agent"
import { createStoreWithOptionalDevtools } from "../helper"
import type { ActorSubclass, HttpAgent } from "@dfinity/agent"
import type { HttpAgent } from "@dfinity/agent"
import type {
CanisterId,
ExtractActorMethodArgs,
Expand All @@ -9,16 +9,16 @@ import type {
ActorStore,
ActorMethodStates,
ActorManagerOptions,
DefaultActorType,
FunctionName,
ExtractedService,
BaseActor,
} from "./types"
import { IDL } from "@dfinity/candid"
import type { AgentManager, UpdateAgentOptions } from "../agent"

export * from "./types"

export class ActorManager<A extends ActorSubclass<any> = DefaultActorType> {
export class ActorManager<A = BaseActor> {
private actor: null | A = null
private idlFactory: IDL.InterfaceFactory

Expand Down Expand Up @@ -67,7 +67,7 @@ export class ActorManager<A extends ActorSubclass<any> = DefaultActorType> {

// Initialize stores
this.actorStore = createStoreWithOptionalDevtools(
{ ...this.DEFAULT_ACTOR_STATE },
this.DEFAULT_ACTOR_STATE,
{ withDevtools, store: `actor-${String(canisterId)}` }
)

Expand All @@ -81,19 +81,22 @@ export class ActorManager<A extends ActorSubclass<any> = DefaultActorType> {
}

public extractService(): ExtractedService<A> {
return this.idlFactory({ IDL })._fields.reduce(
(acc, [functionName, type]) => {
acc[functionName as FunctionName<A>] = (extractorClass, data) => {
return type.accept(extractorClass, data || functionName)
}

return acc
},
{} as ExtractedService<A>
)
return this.idlFactory({ IDL })._fields.reduce((acc, service) => {
const functionName = service[0] as keyof A
const type = service[1]

const visit = ((extractorClass, data) => {
return type.accept(extractorClass, data || functionName)
}) as ExtractedService<A>[typeof functionName]

acc[functionName] = visit

return acc
}, {} as ExtractedService<A>)
}

private initializeActor = (agent: HttpAgent) => {
// eslint-disable-next-line no-console
console.info(
`Initializing actor ${this.canisterId} on ${
agent.isLocal() ? "local" : "ic"
Expand Down Expand Up @@ -127,6 +130,7 @@ export class ActorManager<A extends ActorSubclass<any> = DefaultActorType> {
initialized: true,
})
} catch (error) {
// eslint-disable-next-line no-console
console.error("Error in initializeActor:", error)
this.updateState({ error: error as Error, initializing: false })
}
Expand Down Expand Up @@ -170,7 +174,7 @@ export class ActorManager<A extends ActorSubclass<any> = DefaultActorType> {
}
}

const emptyVisitor = new Proxy({} as ExtractedService<any>, {
const emptyVisitor = new Proxy({} as ExtractedService<never>, {
get: function (_, prop) {
throw new Error(
`Cannot visit function "${String(
Expand Down
48 changes: 22 additions & 26 deletions packages/store/src/actor/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,16 @@ import type { StoreApi } from "zustand"
import type { AgentManager } from "../agent"
import type { ActorMethod, ActorSubclass, Principal } from "../types"

export type FunctionName<A = DefaultActorType> = keyof A & string

export type FunctionType = "query" | "update"

export interface DefaultActorType {
[key: string]: ActorMethod<any, any>
[key: string]: ActorMethod
}

// Type for identifying a canister
export type BaseActor<T = DefaultActorType> = ActorSubclass<T>

export type FunctionName<A = BaseActor> = keyof A & string

export type FunctionType = "query" | "update"

export type CanisterId = string | Principal

export interface ActorManagerOptions {
Expand All @@ -23,33 +24,31 @@ export interface ActorManagerOptions {
initializeOnCreate?: boolean
}

export type ExtractVisitorType<T> = T extends IDL.Visitor<infer U, infer V>
? { data: U; return: V }
export type ExtractVisitorType<V> = V extends IDL.Visitor<infer D, infer R>
? { data: D; returnType: R }
: never

export type ExtractedService<
A = DefaultActorType,
M extends FunctionName<A> = FunctionName<A>
> = {
[K in M]: <V extends IDL.Visitor<any, any>>(
export type ExtractedService<A = BaseActor, M extends keyof A = keyof A> = {
[K in M]: <V extends IDL.Visitor<unknown, unknown>>(
extractorClass: V,
data?: ExtractVisitorType<V>["data"]
) => ReturnType<V["visitFunc"]>
}

// Utility types for extracting method arguments and return types
export type ExtractActorMethodArgs<T> = T extends ActorMethod<infer A>
? A
// Extracts the argument types of an ActorMethod
export type ExtractActorMethodArgs<T> = T extends ActorMethod<infer Args>
? Args
: never

// Extracts the return type of an ActorMethod
export type ExtractActorMethodReturnType<T> = T extends ActorMethod<
any,
infer R
unknown[],
infer Ret
>
? R
? Ret
: never

export interface ActorMethodState<A, M extends FunctionName<A>> {
export interface ActorMethodState<A, M extends keyof A> {
[key: string]: {
data: ExtractActorMethodReturnType<A[M]> | undefined
loading: boolean
Expand All @@ -58,7 +57,7 @@ export interface ActorMethodState<A, M extends FunctionName<A>> {
}

export type ActorMethodStates<A> = {
[M in FunctionName<A>]: ActorMethodState<A, M>
[M in keyof A]: ActorMethodState<A, M>
}

// State structure for an actor in a ReActor
Expand All @@ -69,13 +68,10 @@ export type ActorState<A> = {
methodState: ActorMethodStates<A>
}

export type ActorStore<A extends ActorSubclass<any> = DefaultActorType> =
StoreApi<ActorState<A>>
export type ActorStore<A = BaseActor> = StoreApi<ActorState<A>>

// Function type for directly calling a method on an actor
export type CallActorMethod<A = Record<string, ActorMethod>> = <
M extends FunctionName<A>
>(
export type CallActorMethod<A = BaseActor> = <M extends keyof A>(
functionName: M,
...args: ExtractActorMethodArgs<A[M]>
) => Promise<ExtractActorMethodReturnType<A[M]>>
4 changes: 1 addition & 3 deletions packages/store/src/agent/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ export class AgentManager {
this.updateState({ initialized: true, initializing: false })
} catch (error) {
this.updateState({ error: error as Error, initializing: false })
console.error("Error fetching root key:", error)
}
}
}
Expand Down Expand Up @@ -105,6 +104,7 @@ export class AgentManager {
try {
const { AuthClient } = await import("@dfinity/auth-client").catch(
(error) => {
// eslint-disable-next-line no-console
console.error("Failed to import @dfinity/auth-client:", error)
throw new Error(
"Authentication failed: @dfinity/auth-client package is missing."
Expand All @@ -130,8 +130,6 @@ export class AgentManager {
return identity
} catch (error) {
this.updateState({ error: error as Error, authenticating: false })

console.error("Error in authenticate:", error)
throw error
}
}
Expand Down
14 changes: 7 additions & 7 deletions packages/store/src/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ import { hash } from "@dfinity/agent"
import { toHexString } from "@dfinity/candid"
import { devtools } from "zustand/middleware"
import { createStore } from "zustand/vanilla"
import type { ActorSubclass } from "./types"
import { BaseActor } from "./actor"

interface StoreOptions {
withDevtools?: boolean
store: string
}

export function createStoreWithOptionalDevtools(
initialState: any,
export function createStoreWithOptionalDevtools<T>(
initialState: T,
options: StoreOptions
) {
if (options.withDevtools) {
Expand All @@ -25,15 +25,15 @@ export function createStoreWithOptionalDevtools(
}
}

export function jsonToString(json: any) {
export function jsonToString(json: never) {
return JSON.stringify(
json,
(_, value) => (typeof value === "bigint" ? `BigInt(${value})` : value),
2
)
}

export const generateRequestHash = (args?: any[]) => {
export const generateRequestHash = (args?: unknown[]) => {
const serializedArgs = args
?.map((arg) => {
if (typeof arg === "bigint") {
Expand All @@ -47,12 +47,12 @@ export const generateRequestHash = (args?: any[]) => {
return stringToHash(serializedArgs ?? "")
}

export const generateHash = (field?: any) => {
export const generateHash = (field?: never) => {
const serializedArgs = JSON.stringify(field)
return stringToHash(serializedArgs ?? "")
}

export const generateActorHash = (actor: ActorSubclass<any>) => {
export const generateActorHash = (actor: BaseActor) => {
const serializedArgs = JSON.stringify(actor)
return stringToHash(serializedArgs ?? "")
}
Expand Down
12 changes: 4 additions & 8 deletions packages/store/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { ActorManagerOptions, DefaultActorType } from "./actor/types"
import type { ActorManagerOptions, BaseActor } from "./actor/types"
import type { AgentManagerOptions } from "./agent/types"

import { ActorManager } from "./actor"
import { AgentManager } from "./agent"
import { ActorSubclass, CreateReActorOptions } from "./types"
import { CreateReActorOptions } from "./types"
import { CandidAdapter, CandidAdapterOptions } from "./tools"

export * from "./helper"
Expand Down Expand Up @@ -36,9 +36,7 @@ export const createAgentManager = (
* @category Main
* @includeExample ./packages/store/README.md:91-106
*/
export const createActorManager = <
A extends ActorSubclass<any> = DefaultActorType
>(
export const createActorManager = <A = BaseActor>(
options: ActorManagerOptions
): ActorManager<A> => {
return new ActorManager<A>(options)
Expand All @@ -52,9 +50,7 @@ export const createActorManager = <
* @category Main
* @includeExample ./packages/store/README.md:32-45
*/
export const createReActorStore = <
A extends ActorSubclass<any> = DefaultActorType
>(
export const createReActorStore = <A = BaseActor>(
options: CreateReActorOptions
): ActorManager<A> => {
const {
Expand Down
2 changes: 1 addition & 1 deletion packages/store/src/tools/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@ export interface CandidAdapterOptions {

export interface CandidDefenition {
idlFactory: IDL.InterfaceFactory
init: ({ IDL }: { IDL: any }) => never[]
init: ({ idl }: { idl: typeof IDL }) => never[]
}

0 comments on commit 42290fa

Please sign in to comment.