From e8fa6e7f39c9a215038fd75c4e2ddea5067deb72 Mon Sep 17 00:00:00 2001 From: krisbitney Date: Wed, 21 Sep 2022 15:37:30 +0500 Subject: [PATCH 01/25] Replaced thrown exceptions with Result types in core-js --- packages/js/core/src/__tests__/Plugin.spec.ts | 3 +- .../src/__tests__/apply-redirects.spec.ts | 42 +++++-- .../src/__tests__/get-implementations.spec.ts | 17 +-- .../js/core/src/__tests__/parse-query.spec.ts | 118 ++++++++++++------ .../js/core/src/algorithms/apply-redirects.ts | 14 ++- .../src/algorithms/get-implementations.ts | 27 +++- .../js/core/src/algorithms/parse-query.ts | 80 ++++++++---- .../js/core/src/interfaces/uri-resolver.ts | 8 +- packages/js/core/src/plugin/PluginWrapper.ts | 114 ++++++++--------- packages/js/core/src/types/Invoke.ts | 27 +--- packages/js/core/src/types/Plugin.ts | 16 ++- packages/js/core/src/types/Query.ts | 28 +---- packages/js/core/src/types/Subscription.ts | 6 +- packages/js/core/src/types/Uri.ts | 49 ++++---- packages/js/core/src/types/Wrapper.ts | 8 +- 15 files changed, 316 insertions(+), 241 deletions(-) diff --git a/packages/js/core/src/__tests__/Plugin.spec.ts b/packages/js/core/src/__tests__/Plugin.spec.ts index 119767b3f6..a7a965bf2f 100644 --- a/packages/js/core/src/__tests__/Plugin.spec.ts +++ b/packages/js/core/src/__tests__/Plugin.spec.ts @@ -2,6 +2,7 @@ import { Client, PluginModule } from ".."; +import { ResultOk } from "@polywrap/result"; class TestPluginModule extends PluginModule<{}> { testMethod(args: { value: number }, _client: Client): number { @@ -16,6 +17,6 @@ describe("Plugin", () => { expect(plugin).toBeTruthy(); expect ( await plugin._wrap_invoke("testMethod", { value: 5 }, {} as Client) - ).toBe(10); + ).toStrictEqual(ResultOk(10)); }); }); diff --git a/packages/js/core/src/__tests__/apply-redirects.spec.ts b/packages/js/core/src/__tests__/apply-redirects.spec.ts index c81ac071ea..b00dc8006f 100644 --- a/packages/js/core/src/__tests__/apply-redirects.spec.ts +++ b/packages/js/core/src/__tests__/apply-redirects.spec.ts @@ -9,13 +9,19 @@ describe("applyRedirects", () => { const uri1 = "wrap://ens/some-uri1.eth"; const uri2 = "wrap://ens/some-uri2.eth"; - const redirectedUri = applyRedirects(new Uri(uri1), [ + const redirectsResult = applyRedirects(new Uri(uri1), [ { from: new Uri(uri1), to: new Uri(uri2) } ]); - + + expect (redirectsResult.ok).toBeTruthy(); + if (!redirectsResult.ok) { + throw Error("This should never happen"); + } + + const redirectedUri = redirectsResult.value; expect(Uri.equals(redirectedUri, new Uri(uri2))).toBeTruthy(); }); @@ -24,7 +30,7 @@ describe("applyRedirects", () => { const uri2 = "wrap://ens/some-uri2.eth"; const uri3 = "wrap://ens/some-uri3.eth"; - const redirectedUri = applyRedirects(new Uri(uri1), [ + const redirectsResult = applyRedirects(new Uri(uri1), [ { from: new Uri(uri1), to: new Uri(uri2) @@ -34,20 +40,32 @@ describe("applyRedirects", () => { to: new Uri(uri3) } ]); - + + expect (redirectsResult.ok).toBeTruthy(); + if (!redirectsResult.ok) { + throw Error("This should never happen"); + } + + const redirectedUri = redirectsResult.value; expect(Uri.equals(redirectedUri, new Uri(uri2))).toBeTruthy(); }); it("can not redirect to self", () => { const uri = "wrap://ens/some-uri.eth"; - expect(() => { - applyRedirects(new Uri(uri), [ - { - from: new Uri(uri), - to: new Uri(uri) - } - ]); - }).toThrow(/Infinite loop while resolving URI/); + const redirectsResult = applyRedirects(new Uri(uri), [ + { + from: new Uri(uri), + to: new Uri(uri) + } + ]); + + expect(redirectsResult.ok).toBeFalsy(); + if (redirectsResult.ok) { + throw Error("This should never happen"); + } + + const err = redirectsResult.error?.message; + expect(err).toContain("Infinite loop while resolving URI"); }); }); diff --git a/packages/js/core/src/__tests__/get-implementations.spec.ts b/packages/js/core/src/__tests__/get-implementations.spec.ts index 330abed01c..470f37a8d0 100644 --- a/packages/js/core/src/__tests__/get-implementations.spec.ts +++ b/packages/js/core/src/__tests__/get-implementations.spec.ts @@ -4,6 +4,7 @@ import { UriRedirect, } from "../"; import { InterfaceImplementations } from "../types"; +import { ResultOk } from "@polywrap/result"; describe("getImplementations", () => { @@ -69,21 +70,21 @@ describe("getImplementations", () => { redirects ); - expect(getImplementationsResult1).toEqual([ + expect(getImplementationsResult1).toEqual(ResultOk([ new Uri(implementation1Uri), new Uri(implementation2Uri), new Uri(implementation3Uri) - ]); + ])); - expect(getImplementationsResult2).toEqual([ + expect(getImplementationsResult2).toEqual(ResultOk([ new Uri(implementation1Uri), new Uri(implementation2Uri), new Uri(implementation3Uri) - ]); + ])); - expect(getImplementationsResult3).toEqual([ + expect(getImplementationsResult3).toEqual(ResultOk([ new Uri(implementation3Uri) - ]); + ])); }); it("interface implementations are not redirected", () => { @@ -114,8 +115,8 @@ describe("getImplementations", () => { redirects ); - expect(getImplementationsResult).toEqual([ + expect(getImplementationsResult).toEqual(ResultOk([ new Uri(implementation1Uri) - ]); + ])); }); }); diff --git a/packages/js/core/src/__tests__/parse-query.spec.ts b/packages/js/core/src/__tests__/parse-query.spec.ts index b80bd41004..55506b17ff 100644 --- a/packages/js/core/src/__tests__/parse-query.spec.ts +++ b/packages/js/core/src/__tests__/parse-query.spec.ts @@ -1,4 +1,5 @@ import { createQueryDocument, parseQuery, QueryInvocations, Uri } from "../"; +import { ResultOk } from "@polywrap/result"; describe("parseQuery", () => { const dummy = new Uri("wrap://dumb/dummy"); @@ -59,7 +60,7 @@ describe("parseQuery", () => { } }; - expect(result).toMatchObject(expected); + expect(result).toMatchObject(ResultOk(expected)); }); it("works with multiple queries", () => { @@ -171,39 +172,63 @@ describe("parseQuery", () => { mutationAnotherMethod: method2.anotherMethod, }; - expect(result).toMatchObject(expected); + expect(result).toMatchObject(ResultOk(expected)); }); it("fails when given an empty document", () => { const doc = createQueryDocument("{ prop }"); // eslint-disable-next-line @typescript-eslint/no-explicit-any (doc.definitions as any) = []; - expect(() => parseQuery(dummy, doc)).toThrowError( - /Empty query document found/ - ); + const result = parseQuery(dummy, doc); + + expect (result.ok).toBeFalsy(); + if (result.ok) { + throw Error("This should never happen"); + } + + const error = result.error?.message; + expect(error).toContain("Empty query document found"); }); it("fails when a query operations isn't specified", () => { const doc = createQueryDocument("fragment Something on Type { something }"); - expect(() => parseQuery(dummy, doc)).toThrowError( - /Unrecognized root level definition type/ - ); + const result = parseQuery(dummy, doc); + + expect (result.ok).toBeFalsy(); + if (result.ok) { + throw Error("This should never happen"); + } + + const error = result.error?.message; + expect(error).toContain("Unrecognized root level definition type"); }); it("fails when method is missing", () => { const doc = createQueryDocument(`query { something }`); // eslint-disable-next-line @typescript-eslint/no-explicit-any (doc.definitions[0] as any).selectionSet.selections = []; - expect(() => parseQuery(dummy, doc)).toThrowError( - /Empty selection set found/ - ); + const result = parseQuery(dummy, doc); + + expect (result.ok).toBeFalsy(); + if (result.ok) { + throw Error("This should never happen"); + } + + const error = result.error?.message; + expect(error).toContain("Empty selection set found"); }); it("fails when a fragment spread is used within an operations", () => { const doc = createQueryDocument(`query { ...NamedFragment }`); - expect(() => parseQuery(dummy, doc)).toThrowError( - /Unsupported selection type found: FragmentSpread/ - ); + const result = parseQuery(dummy, doc); + + expect (result.ok).toBeFalsy(); + if (result.ok) { + throw Error("This should never happen"); + } + + const error = result.error?.message; + expect(error).toContain("Unsupported selection type found: FragmentSpread"); }); it("fails when variables were not specified", () => { @@ -214,10 +239,15 @@ describe("parseQuery", () => { ) } `); + const result = parseQuery(dummy, doc); + + expect (result.ok).toBeFalsy(); + if (result.ok) { + throw Error("This should never happen"); + } - expect(() => parseQuery(dummy, doc)).toThrowError( - /Variables were not specified/ - ); + const error = result.error?.message; + expect(error).toContain("Variables were not specified"); }); it("fails when variables is missing", () => { @@ -228,12 +258,15 @@ describe("parseQuery", () => { ) } `); + const result = parseQuery(dummy, doc, { arg2: "not arg1" }); - expect(() => - parseQuery(dummy, doc, { - arg2: "not arg1", - }) - ).toThrowError(/Missing variable/); + expect (result.ok).toBeFalsy(); + if (result.ok) { + throw Error("This should never happen"); + } + + const error = result.error?.message; + expect(error).toContain("Missing variable"); }); it("succeeds when variables is defined by falsy", () => { @@ -244,12 +277,8 @@ describe("parseQuery", () => { ) } `); - - expect(() => - parseQuery(dummy, doc, { - arg_1: 0, - }) - ).not.toThrowError(/Missing variable/); + const result = parseQuery(dummy, doc, { arg_1: 0 }); + expect (result.ok).toBeTruthy(); }); it("fails when duplicate args arguments are provided", () => { @@ -261,10 +290,15 @@ describe("parseQuery", () => { ) } `); + const result = parseQuery(dummy, doc); - expect(() => parseQuery(dummy, doc)).toThrowError( - /Duplicate arguments found/ - ); + expect (result.ok).toBeFalsy(); + if (result.ok) { + throw Error("This should never happen"); + } + + const error = result.error?.message; + expect(error).toContain("Duplicate arguments found"); }); it("fails when duplicate aliases found", () => { @@ -283,10 +317,15 @@ describe("parseQuery", () => { } } `); + const result = parseQuery(dummy, doc); + + expect (result.ok).toBeFalsy(); + if (result.ok) { + throw Error("This should never happen"); + } - expect(() => parseQuery(dummy, doc)).toThrowError( - /Duplicate query name found "alias"/ - ); + const error = result.error?.message; + expect(error).toContain(`Duplicate query name found "alias"`); }); it("fails when duplicate methods without alias found", () => { @@ -305,9 +344,14 @@ describe("parseQuery", () => { } } `); + const result = parseQuery(dummy, doc); + + expect (result.ok).toBeFalsy(); + if (result.ok) { + throw Error("This should never happen"); + } - expect(() => parseQuery(dummy, doc)).toThrowError( - /Duplicate query name found "method"/ - ); + const error = result.error?.message; + expect(error).toContain(`Duplicate query name found "method"`); }); }); diff --git a/packages/js/core/src/algorithms/apply-redirects.ts b/packages/js/core/src/algorithms/apply-redirects.ts index 0f684dc40c..fd1c60a3fe 100644 --- a/packages/js/core/src/algorithms/apply-redirects.ts +++ b/packages/js/core/src/algorithms/apply-redirects.ts @@ -1,26 +1,28 @@ import { Uri, UriRedirect } from "../types"; import { Tracer } from "@polywrap/tracing-js"; +import { Result, ResultErr, ResultOk } from "@polywrap/result"; export const applyRedirects = Tracer.traceFunc( "core: applyRedirects", - (uri: Uri, redirects: readonly UriRedirect[]): Uri => { + (uri: Uri, redirects: readonly UriRedirect[]): Result => { // Keep track of past redirects (from -> to) to find the final uri const redirectFromToMap: Record = {}; - const throwError = (message: string) => { - throw Error( + const createError = (message: string) => { + const error = Error( `${message}\nResolution Stack: ${JSON.stringify( redirectFromToMap, null, 2 )}` ); + return ResultErr(error); }; for (const redirect of redirects) { if (!redirect.from) { - throwError( + return createError( `Redirect missing the from property.\nEncountered while resolving ${uri.uri}` ); } @@ -42,10 +44,10 @@ export const applyRedirects = Tracer.traceFunc( finalUri = redirectFromToMap[finalUri.uri]; if (visitedUris[finalUri.uri]) { - throwError(`Infinite loop while resolving URI "${uri}".`); + return createError(`Infinite loop while resolving URI "${uri}".`); } } - return finalUri; + return ResultOk(finalUri); } ); diff --git a/packages/js/core/src/algorithms/get-implementations.ts b/packages/js/core/src/algorithms/get-implementations.ts index 799143f0a9..359313941c 100644 --- a/packages/js/core/src/algorithms/get-implementations.ts +++ b/packages/js/core/src/algorithms/get-implementations.ts @@ -2,6 +2,7 @@ import { Uri, UriRedirect, InterfaceImplementations } from "../types"; import { applyRedirects } from "./apply-redirects"; import { Tracer } from "@polywrap/tracing-js"; +import { Result, ResultOk } from "@polywrap/result"; export const getImplementations = Tracer.traceFunc( "core: getImplementations", @@ -9,7 +10,7 @@ export const getImplementations = Tracer.traceFunc( wrapperInterfaceUri: Uri, interfaces: readonly InterfaceImplementations[], redirects?: readonly UriRedirect[] - ): Uri[] => { + ): Result => { const result: Uri[] = []; const addUniqueResult = (uri: Uri) => { @@ -24,9 +25,19 @@ export const getImplementations = Tracer.traceFunc( wrapperInterfaceUri: Uri ) => { for (const interfaceImplementations of implementationsArray) { - const fullyResolvedUri = redirects - ? applyRedirects(interfaceImplementations.interface, redirects) - : interfaceImplementations.interface; + let fullyResolvedUri: Uri; + if (redirects) { + const redirectsResult = applyRedirects( + interfaceImplementations.interface, + redirects + ); + if (!redirectsResult.ok) { + continue; + } + fullyResolvedUri = redirectsResult.value; + } else { + fullyResolvedUri = interfaceImplementations.interface; + } if (Uri.equals(fullyResolvedUri, wrapperInterfaceUri)) { for (const implementation of interfaceImplementations.implementations) { @@ -39,11 +50,15 @@ export const getImplementations = Tracer.traceFunc( let finalUri = wrapperInterfaceUri; if (redirects) { - finalUri = applyRedirects(wrapperInterfaceUri, redirects); + const redirectsResult = applyRedirects(wrapperInterfaceUri, redirects); + if (!redirectsResult.ok) { + return redirectsResult; + } + finalUri = redirectsResult.value; } addAllImplementationsFromImplementationsArray(interfaces, finalUri); - return result; + return ResultOk(result); } ); diff --git a/packages/js/core/src/algorithms/parse-query.ts b/packages/js/core/src/algorithms/parse-query.ts index 8016e3c0ca..db52f75990 100644 --- a/packages/js/core/src/algorithms/parse-query.ts +++ b/packages/js/core/src/algorithms/parse-query.ts @@ -2,6 +2,7 @@ import { QueryInvocations, QueryDocument, Uri } from "../types"; import { SelectionSetNode, ValueNode } from "graphql"; import { Tracer } from "@polywrap/tracing-js"; +import { Result, ResultErr, ResultOk } from "@polywrap/result"; export const parseQuery = Tracer.traceFunc( "core: parseQuery", @@ -9,19 +10,20 @@ export const parseQuery = Tracer.traceFunc( uri: Uri, doc: QueryDocument, variables?: Record - ): QueryInvocations => { + ): Result, Error> => { if (doc.definitions.length === 0) { - throw Error("Empty query document found."); + return ResultErr(Error("Empty query document found.")); } const queryInvocations: QueryInvocations = {}; for (const def of doc.definitions) { if (def.kind !== "OperationDefinition") { - throw Error( + const error = Error( `Unrecognized root level definition type: ${def.kind}\n` + "Please use a 'query' or 'mutation' operations." ); + return ResultErr(error); } // Get the method name @@ -29,26 +31,29 @@ export const parseQuery = Tracer.traceFunc( const selections = selectionSet.selections; if (selections.length === 0) { - throw Error( + const error = Error( "Empty selection set found. Please include the name of a method you'd like to query." ); + return ResultErr(error); } for (const selection of selections) { if (selection.kind !== "Field") { - throw Error( + const error = Error( `Unsupported selection type found: ${selection.kind}\n` + "Please query a method." ); + return ResultErr(error); } const method = selection.name.value; const invocationName = selection.alias ? selection.alias.value : method; if (queryInvocations[invocationName]) { - throw Error( + const error = Error( `Duplicate query name found "${invocationName}". Please use GraphQL aliases that each have unique names.` ); + return ResultErr(error); } // Get all arguments @@ -60,10 +65,14 @@ export const parseQuery = Tracer.traceFunc( const name = arg.name.value; if (args[name]) { - throw Error(`Duplicate arguments found: ${name}`); + return ResultErr(Error(`Duplicate arguments found: ${name}`)); } - args[name] = extractValue(arg.value, variables); + const extractionResult = extractValue(arg.value, variables); + if (!extractionResult.ok) { + return extractionResult; + } + args[name] = extractionResult.value; } } @@ -75,88 +84,105 @@ export const parseQuery = Tracer.traceFunc( } } - return queryInvocations; + return ResultOk(queryInvocations); } ); const extractValue = Tracer.traceFunc( "core: extractValue", - (node: ValueNode, variables?: Record): unknown => { + ( + node: ValueNode, + variables?: Record + ): Result => { if (node.kind === "Variable") { // Get the argument's value from the variables object if (!variables) { - throw Error( + const error = Error( `Variables were not specified, tried to resolve variable from query. Name: ${node.name.value}\n` ); + return ResultErr(error); } if (variables[node.name.value] === undefined) { - throw Error(`Missing variable: ${node.name.value}`); + return ResultErr(Error(`Missing variable: ${node.name.value}`)); } - return variables[node.name.value]; + return ResultOk(variables[node.name.value]); } else if ( node.kind === "StringValue" || node.kind === "EnumValue" || node.kind === "BooleanValue" ) { - return node.value; + return ResultOk(node.value); } else if (node.kind === "IntValue") { - return Number.parseInt(node.value); + return ResultOk(Number.parseInt(node.value)); } else if (node.kind === "FloatValue") { - return Number.parseFloat(node.value); + return ResultOk(Number.parseFloat(node.value)); } else if (node.kind === "NullValue") { - return null; + return ResultOk(null); } else if (node.kind === "ListValue") { const length = node.values.length; const list = []; for (let i = 0; i < length; ++i) { - list.push(extractValue(node.values[i], variables)); + const extractionResult = extractValue(node.values[i], variables); + if (!extractionResult.ok) { + return extractionResult; + } + list.push(extractionResult.value); } - return list; + return ResultOk(list); } else if (node.kind === "ObjectValue") { const length = node.fields.length; const object: Record = {}; for (let i = 0; i < length; ++i) { const field = node.fields[i]; - object[field.name.value] = extractValue(field.value, variables); + const extractionResult = extractValue(field.value, variables); + if (!extractionResult.ok) { + return extractionResult; + } + object[field.name.value] = extractionResult.value; } - return object; + return ResultOk(object); } else { - throw Error(`Unsupported value node: ${node}`); + return ResultErr(Error(`Unsupported value node: ${node}`)); } } ); export const extractSelections = Tracer.traceFunc( "core: extractSelections", - (node: SelectionSetNode): Record => { + (node: SelectionSetNode): Result, Error> => { const result: Record = {}; for (const selection of node.selections) { if (selection.kind !== "Field") { - throw Error( + const error = Error( `Unsupported result selection type found: ${selection.kind}` ); + return ResultErr(error); } const name = selection.name.value; if (result[name]) { - throw Error(`Duplicate result selections found: ${name}`); + return ResultErr(Error(`Duplicate result selections found: ${name}`)); } if (selection.selectionSet) { - result[name] = extractSelections(selection.selectionSet); + const selectionsResult = extractSelections(selection.selectionSet); + if (!selectionsResult.ok) { + return selectionsResult; + } + result[name] = selectionsResult.value; } else { result[name] = true; } } - return result; + return ResultOk(result); } ); diff --git a/packages/js/core/src/interfaces/uri-resolver.ts b/packages/js/core/src/interfaces/uri-resolver.ts index 182e27efcc..1da5fbc3ab 100644 --- a/packages/js/core/src/interfaces/uri-resolver.ts +++ b/packages/js/core/src/interfaces/uri-resolver.ts @@ -1,7 +1,7 @@ -// TODO: https://github.com/polywrap/monorepo/issues/101 -import { Uri, Invoker, InvokeResult } from "../"; +import { Uri, Invoker } from "../"; import { Tracer } from "@polywrap/tracing-js"; +import { Result } from "@polywrap/result"; export interface MaybeUriOrManifest { uri?: string; @@ -15,7 +15,7 @@ export const module = { invoker: Invoker, wrapper: Uri, uri: Uri - ): Promise> => { + ): Promise> => { return invoker.invoke({ uri: wrapper.uri, method: `tryResolveUri`, @@ -32,7 +32,7 @@ export const module = { invoker: Invoker, wrapper: Uri, path: string - ): Promise> => { + ): Promise> => { return invoker.invoke({ uri: wrapper.uri, method: "getFile", diff --git a/packages/js/core/src/plugin/PluginWrapper.ts b/packages/js/core/src/plugin/PluginWrapper.ts index 13df1587ce..27465756a9 100644 --- a/packages/js/core/src/plugin/PluginWrapper.ts +++ b/packages/js/core/src/plugin/PluginWrapper.ts @@ -14,6 +14,7 @@ import { import { WrapManifest } from "@polywrap/wrap-manifest-types-js"; import { msgpackDecode } from "@polywrap/msgpack-js"; import { Tracer, TracingLevel } from "@polywrap/tracing-js"; +import { Result, ResultErr, ResultOk } from "@polywrap/result"; export class PluginWrapper implements Wrapper { private _instance: PluginModule | undefined; @@ -29,15 +30,14 @@ export class PluginWrapper implements Wrapper { public async getFile( _: GetFileOptions, _client: Client - ): Promise { - throw Error("client.getFile(...) is not implemented for Plugins."); + ): Promise> { + return ResultErr( + Error("client.getFile(...) is not implemented for Plugins.") + ); } @Tracer.traceMethod("PluginWrapper: getManifest") - public async getManifest( - _: GetManifestOptions, - _client: Client - ): Promise { + public getManifest(_: GetManifestOptions, _client: Client): WrapManifest { return this._plugin.manifest; } @@ -51,70 +51,66 @@ export class PluginWrapper implements Wrapper { `Plugin Wrapper invoked: ${options.uri.uri}, with method ${options.method}`, TracingLevel.High ); - try { - const { method } = options; - const args = options.args || {}; - const module = this._getInstance(); - - if (!module) { - throw new Error(`PluginWrapper: module "${module}" not found.`); - } - - if (!module.getMethod(method)) { - throw new Error(`PluginWrapper: method "${method}" not found.`); - } + const { method } = options; + const args = options.args || {}; + const module = this._getInstance(); - // Set the module's environment - await module.setEnv(options.env || {}); + if (!module) { + return { + data: ResultErr(Error(`PluginWrapper: module "${module}" not found.`)), + }; + } - let jsArgs: Record; + if (!module.getMethod(method)) { + return { + data: ResultErr(Error(`PluginWrapper: method "${method}" not found.`)), + }; + } - // If the args are a msgpack buffer, deserialize it - if (isBuffer(args)) { - const result = msgpackDecode(args); + // Set the module's environment + await module.setEnv(options.env || {}); - Tracer.addEvent("msgpack-decoded", result); + let jsArgs: Record; - if (typeof result !== "object") { - throw new Error( - `PluginWrapper: decoded MsgPack args did not result in an object.\nResult: ${result}` - ); - } + // If the args are a msgpack buffer, deserialize it + if (isBuffer(args)) { + const result = msgpackDecode(args); - jsArgs = result as Record; - } else { - jsArgs = args as Record; - } + Tracer.addEvent("msgpack-decoded", result); - // Invoke the function - try { - const result = await module._wrap_invoke(method, jsArgs, client); - - if (result !== undefined) { - const data = result as unknown; - - Tracer.addEvent("Result", data); - - return { - data: data, - encoded: false, - }; - } else { - return {}; - } - } catch (e) { - throw Error( - `PluginWrapper: invocation exception encountered.\n` + - `uri: ${options.uri}\nmodule: ${module}\n` + - `method: ${method}\n` + - `args: ${JSON.stringify(jsArgs, null, 2)}\n` + - `exception: ${e.message}` + if (typeof result !== "object") { + const msgPackException = Error( + `PluginWrapper: decoded MsgPack args did not result in an object.\nResult: ${result}` ); + return { data: ResultErr(msgPackException) }; } - } catch (error) { + + jsArgs = result as Record; + } else { + jsArgs = args as Record; + } + + // Invoke the function + const result = await module._wrap_invoke(method, jsArgs, client); + + if (result.ok) { + const data = result.value; + + Tracer.addEvent("Result", data); + return { - error, + data: ResultOk(data), + encoded: false, }; + } else { + const invocationException = Error( + `PluginWrapper: invocation exception encountered.\n` + + `uri: ${options.uri}\nmodule: ${module}\n` + + `method: ${method}\n` + + `args: ${JSON.stringify(jsArgs, null, 2)}\n` + + `exception: ${result.error?.message}` + ); + return { data: ResultErr(invocationException) }; } } diff --git a/packages/js/core/src/types/Invoke.ts b/packages/js/core/src/types/Invoke.ts index e1e6a61c2a..6d690595d5 100644 --- a/packages/js/core/src/types/Invoke.ts +++ b/packages/js/core/src/types/Invoke.ts @@ -1,6 +1,8 @@ import { ClientConfig, Uri, Wrapper } from "."; import { IUriResolutionContext } from "../uri-resolution"; +import { Result } from "@polywrap/result"; + /** Options required for an Wrapper invocation. */ export interface InvokeOptions< TUri extends Uri | string = string, @@ -36,24 +38,6 @@ export interface InvokeOptions< contextId?: string; } -/** - * Result of an Wrapper invocation. - * - * @template TData Type of the invoke result data. - */ -export interface InvokeResult { - /** - * Invoke result data. The type of this value is the return type - * of the method. If undefined, it means something went wrong. - * Errors should be populated with information as to what happened. - * Null is used to represent an intentionally null result. - */ - data?: TData; - - /** Errors encountered during the invocation. */ - error?: Error; -} - export interface InvokerOptions< TUri extends Uri | string = string, TClientConfig extends ClientConfig = ClientConfig @@ -64,13 +48,14 @@ export interface InvokerOptions< export interface Invoker { invokeWrapper( options: InvokerOptions & { wrapper: Wrapper } - ): Promise>; + ): Promise>; invoke( options: InvokerOptions - ): Promise>; + ): Promise>; } -export interface InvocableResult extends InvokeResult { +export interface InvocableResult { + data: Result; encoded?: boolean; } diff --git a/packages/js/core/src/types/Plugin.ts b/packages/js/core/src/types/Plugin.ts index 1251ffcd1d..9e7a8b5237 100644 --- a/packages/js/core/src/types/Plugin.ts +++ b/packages/js/core/src/types/Plugin.ts @@ -2,6 +2,7 @@ import { Client, MaybeAsync, executeMaybeAsyncFunction } from "."; import { WrapManifest } from "@polywrap/wrap-manifest-types-js"; +import { Result, ResultErr, ResultOk } from "@polywrap/result"; /** * Invocable plugin method. @@ -42,20 +43,27 @@ export abstract class PluginModule< public async _wrap_invoke< TArgs extends Record = Record, TResult = unknown - >(method: string, args: TArgs, client: Client): Promise { + >( + method: string, + args: TArgs, + client: Client + ): Promise> { const fn = this.getMethod(method); if (!fn) { - throw Error(`Plugin missing method "${method}"`); + return ResultErr(Error(`Plugin missing method "${method}"`)); } if (typeof fn !== "function") { - throw Error(`Plugin method "${method}" must be of type 'function'`); + return ResultErr( + Error(`Plugin method "${method}" must be of type 'function'`) + ); } - return await executeMaybeAsyncFunction( + const data = await executeMaybeAsyncFunction( fn.bind(this, args, client) ); + return ResultOk(data); } public getMethod< diff --git a/packages/js/core/src/types/Query.ts b/packages/js/core/src/types/Query.ts index 0cf4cfa9cb..3bde10e480 100644 --- a/packages/js/core/src/types/Query.ts +++ b/packages/js/core/src/types/Query.ts @@ -3,6 +3,7 @@ import { Uri, InvokeOptions, ClientConfig } from "./"; import { Tracer } from "@polywrap/tracing-js"; import { DocumentNode } from "graphql"; import gql from "graphql-tag"; +import { Result } from "@polywrap/result"; /** GraphQL QueryDocument */ export type QueryDocument = DocumentNode; @@ -46,31 +47,6 @@ export interface QueryOptions< contextId?: string; } -/** - * The result of an Wrapper query, which is the aggregate - * of one or more [[InvokeResult | invocation results]]. - * - * @template TData Type of the query result data. - */ -export interface QueryResult< - TData extends Record = Record -> { - /** - * Query result data. The type of this value is a named map, - * where the key is the method's name, and value is the [[InvokeResult]]'s data. - * This is done to allow for parallel invocations within a - * single query document. In case of method name collisions, - * a postfix of `_0` will be applied, where 0 will be incremented for - * each occurrence. If undefined, it means something went wrong. - * Errors should be populated with information as to what happened. - * Null is used to represent an intentionally null result. - */ - data?: TData; - - /** Errors encountered during the query. */ - errors?: Error[]; -} - export interface QueryInvocations { [methodOrAlias: string]: InvokeOptions; } @@ -83,5 +59,5 @@ export interface QueryHandler { TUri extends Uri | string = string >( options: QueryOptions - ): Promise>; + ): Promise>; } diff --git a/packages/js/core/src/types/Subscription.ts b/packages/js/core/src/types/Subscription.ts index bb2ee2b671..a0b1601794 100644 --- a/packages/js/core/src/types/Subscription.ts +++ b/packages/js/core/src/types/Subscription.ts @@ -1,6 +1,8 @@ import { Uri } from "./Uri"; import { ClientConfig } from "./Client"; -import { InvokeOptions, InvokeResult } from "./Invoke"; +import { InvokeOptions } from "./Invoke"; + +import { Result } from "@polywrap/result"; /** Defines the frequency of Wrapper invocations for an Wrapper subscription */ export interface SubscriptionFrequency { @@ -44,7 +46,7 @@ export interface Subscription { * Implementation of AsyncIterator protocol makes the Subscription an * AsyncIterable, allowing use in for await...of loops. */ - [Symbol.asyncIterator](): AsyncGenerator>; + [Symbol.asyncIterator](): AsyncGenerator>; } export interface SubscriptionHandler { diff --git a/packages/js/core/src/types/Uri.ts b/packages/js/core/src/types/Uri.ts index 7e215f2cbe..1a96031321 100644 --- a/packages/js/core/src/types/Uri.ts +++ b/packages/js/core/src/types/Uri.ts @@ -1,4 +1,5 @@ import { Tracer } from "@polywrap/tracing-js"; +import { Result, ResultErr, ResultOk } from "@polywrap/result"; /** URI configuration */ export interface UriConfig { @@ -36,7 +37,11 @@ export class Uri { } constructor(uri: string) { - this._config = Uri.parseUri(uri); + const result = Uri.parseUri(uri); + if (!result.ok) { + throw result.error; + } + this._config = result.value; } public static equals(a: Uri, b: Uri): boolean { @@ -48,17 +53,13 @@ export class Uri { } public static isValidUri(uri: string, parsed?: UriConfig): boolean { - try { - const result = Uri.parseUri(uri); - - if (parsed) { - parsed = Object.assign(parsed, result); - } + const result = Uri.parseUri(uri); - return true; - } catch (e) { - return false; + if (parsed && result.ok) { + Object.assign(parsed, result.value); } + + return result.ok; } public toString(): string { @@ -66,9 +67,9 @@ export class Uri { } @Tracer.traceMethod("Uri: parseUri") - public static parseUri(uri: string): UriConfig { + public static parseUri(uri: string): Result { if (!uri) { - throw Error("The provided URI is empty"); + return ResultErr(Error("The provided URI is empty")); } let processed = uri; @@ -86,10 +87,10 @@ export class Uri { processed = "wrap://" + processed; } - // If the wrap:// is not in the beginning, throw an error + // If the wrap:// is not in the beginning, return an error if (wrapSchemeIdx > -1 && wrapSchemeIdx !== 0) { - throw Error( - "The wrap:// scheme must be at the beginning of the URI string" + return ResultErr( + Error("The wrap:// scheme must be at the beginning of the URI string") ); } @@ -102,20 +103,22 @@ export class Uri { } if (!result || result.length !== 3) { - throw Error( - `URI is malformed, here are some examples of valid URIs:\n` + - `wrap://ipfs/QmHASH\n` + - `wrap://ens/domain.eth\n` + - `ens/domain.eth\n\n` + - `Invalid URI Received: ${uri}` + return ResultErr( + Error( + `URI is malformed, here are some examples of valid URIs:\n` + + `wrap://ipfs/QmHASH\n` + + `wrap://ens/domain.eth\n` + + `ens/domain.eth\n\n` + + `Invalid URI Received: ${uri}` + ) ); } - return { + return ResultOk({ uri: processed, authority: result[1], path: result[2], - }; + }); } @Tracer.traceMethod("Uri: from") diff --git a/packages/js/core/src/types/Wrapper.ts b/packages/js/core/src/types/Wrapper.ts index e11bf2397c..3f52f66f21 100644 --- a/packages/js/core/src/types/Wrapper.ts +++ b/packages/js/core/src/types/Wrapper.ts @@ -10,6 +10,7 @@ import { } from "."; import { WrapManifest } from "@polywrap/wrap-manifest-types-js"; +import { Result } from "@polywrap/result"; /** * The Wrapper definition, which can be used to spawn @@ -40,7 +41,7 @@ export interface Wrapper extends Invocable { getFile( options: GetFileOptions, client: Client - ): Promise; + ): Promise>; /** * Get a manifest from the Wrapper package. @@ -48,8 +49,5 @@ export interface Wrapper extends Invocable { * * @param client The client instance requesting the manifest. */ - getManifest( - options: GetManifestOptions, - client: Client - ): Promise; + getManifest(options: GetManifestOptions, client: Client): WrapManifest; } From feca06864838d708308bac073ca63b470d4072af Mon Sep 17 00:00:00 2001 From: krisbitney Date: Wed, 21 Sep 2022 16:22:45 +0500 Subject: [PATCH 02/25] Replaced thrown exceptions with Result types in wasm-js --- packages/js/wasm/src/IWasmPackage.ts | 3 +- packages/js/wasm/src/WasmPackage.ts | 9 ++- packages/js/wasm/src/WasmWrapper.ts | 89 +++++++++++++--------------- packages/js/wasm/src/imports.ts | 20 +++---- 4 files changed, 58 insertions(+), 63 deletions(-) diff --git a/packages/js/wasm/src/IWasmPackage.ts b/packages/js/wasm/src/IWasmPackage.ts index 656ff04006..d534f69b16 100644 --- a/packages/js/wasm/src/IWasmPackage.ts +++ b/packages/js/wasm/src/IWasmPackage.ts @@ -1,5 +1,6 @@ import { IWrapPackage } from "@polywrap/core-js"; +import { Result } from "@polywrap/result"; export interface IWasmPackage extends IWrapPackage { - getWasmModule(): Promise; + getWasmModule(): Promise>; } diff --git a/packages/js/wasm/src/WasmPackage.ts b/packages/js/wasm/src/WasmPackage.ts index e564546fa8..a785399905 100644 --- a/packages/js/wasm/src/WasmPackage.ts +++ b/packages/js/wasm/src/WasmPackage.ts @@ -9,6 +9,7 @@ import { WrapManifest, } from "@polywrap/wrap-manifest-types-js"; import { GetManifestOptions, Wrapper } from "@polywrap/core-js"; +import { Result, ResultErr, ResultOk } from "@polywrap/result"; export class WasmPackage implements IWasmPackage { protected constructor(private readonly fileReader: IFileReader) {} @@ -63,6 +64,7 @@ export class WasmPackage implements IWasmPackage { } } + // TODO: return Result async getManifest(options?: GetManifestOptions): Promise { const wrapManifest = await this.fileReader.readFile(WRAP_MANIFEST_PATH); @@ -73,16 +75,17 @@ export class WasmPackage implements IWasmPackage { return deserializeWrapManifest(wrapManifest, options); } - async getWasmModule(): Promise { + async getWasmModule(): Promise> { const wasmModule = await this.fileReader.readFile(WRAP_MODULE_PATH); if (!wasmModule) { - throw Error(`Wrapper does not contain a wasm module`); + return ResultErr(Error(`Wrapper does not contain a wasm module`)); } - return wasmModule; + return ResultOk(wasmModule); } + // TODO: return Result async createWrapper(options?: GetManifestOptions): Promise { const manifest = await this.getManifest(options); diff --git a/packages/js/wasm/src/WasmWrapper.ts b/packages/js/wasm/src/WasmWrapper.ts index 2619042663..2c88dfad1f 100644 --- a/packages/js/wasm/src/WasmWrapper.ts +++ b/packages/js/wasm/src/WasmWrapper.ts @@ -9,7 +9,6 @@ import { msgpackEncode } from "@polywrap/msgpack-js"; import { Tracer, TracingLevel } from "@polywrap/tracing-js"; import { AsyncWasmInstance } from "@polywrap/asyncify-js"; import { - InvokeResult, Wrapper, Uri, InvokeOptions, @@ -18,10 +17,7 @@ import { isBuffer, GetFileOptions, } from "@polywrap/core-js"; - -type InvokeResultOrError = - | { type: "InvokeResult"; invokeResult: Uint8Array } - | { type: "InvokeError"; invokeError: string }; +import { Result, ResultErr, ResultOk } from "@polywrap/result"; export interface State { method: string; @@ -40,7 +36,7 @@ export interface State { error?: string; args: unknown[]; }; - invokeResult: InvokeResult; + invokeResult?: Result; getImplementationsResult?: Uint8Array; env: Uint8Array; } @@ -65,14 +61,18 @@ export class WasmWrapper implements Wrapper { } @Tracer.traceMethod("WasmWrapper: getFile") - public async getFile(options: GetFileOptions): Promise { + public async getFile( + options: GetFileOptions + ): Promise> { const { path, encoding } = options; const data = await this._fileReader.readFile(path); // If nothing is returned, the file was not found if (!data) { - throw Error(`WasmWrapper: File was not found.\nSubpath: ${path}`); + return ResultErr( + Error(`WasmWrapper: File was not found.\nSubpath: ${path}`) + ); } if (encoding) { @@ -80,17 +80,18 @@ export class WasmWrapper implements Wrapper { const text = decoder.decode(data); if (!text) { - throw Error( + const error = Error( `WasmWrapper: Decoding the file's bytes array failed.\nBytes: ${data}` ); + return ResultErr(error); } - return text; + return ResultOk(text); } - return data; + return ResultOk(data); } @Tracer.traceMethod("WasmWrapper: getManifest") - public async getManifest(): Promise { + public getManifest(): WrapManifest { return this._manifest; } @@ -107,7 +108,11 @@ export class WasmWrapper implements Wrapper { try { const { method } = options; const args = options.args || {}; - const wasm = await this._getWasmModule(); + const wasmResult = await this._getWasmModule(); + if (!wasmResult.ok) { + return { data: wasmResult }; + } + const wasm = wasmResult.value; const state: State = { invoke: {}, @@ -117,7 +122,6 @@ export class WasmWrapper implements Wrapper { subinvokeImplementation: { args: [], }, - invokeResult: {} as InvokeResult, method, args: args ? isBuffer(args) @@ -128,7 +132,7 @@ export class WasmWrapper implements Wrapper { }; const abort = (message: string) => { - throw new Error( + throw Error( `WasmWrapper: Wasm module aborted execution.\nURI: ${options.uri.uri}\n` + `Method: ${method}\n` + `Args: ${JSON.stringify(args, null, 2)}\nMessage: ${message}.\n` @@ -157,30 +161,23 @@ export class WasmWrapper implements Wrapper { const invokeResult = this._processInvokeResult(state, result, abort); - switch (invokeResult.type) { - case "InvokeError": { - throw Error( - `WasmWrapper: invocation exception encountered.\n` + - `uri: ${options.uri.uri}\n` + - `method: ${method}\n` + - `args: ${JSON.stringify(args, null, 2)}\n` + - `exception: ${invokeResult.invokeError}` - ); - } - case "InvokeResult": { - return { - data: invokeResult.invokeResult, - encoded: true, - }; - } - default: { - throw Error(`WasmWrapper: Unknown state "${state}"`); - } + if (invokeResult.ok) { + return { + data: invokeResult, + encoded: true, + }; + } else { + const error = Error( + `WasmWrapper: invocation exception encountered.\n` + + `uri: ${options.uri.uri}\n` + + `method: ${method}\n` + + `args: ${JSON.stringify(args, null, 2)}\n` + + `exception: ${invokeResult.error?.message}` + ); + return { data: ResultErr(error) }; } } catch (error) { - return { - error, - }; + return { data: ResultErr(error) }; } } @@ -189,38 +186,32 @@ export class WasmWrapper implements Wrapper { state: State, result: boolean, abort: (message: string) => never - ): InvokeResultOrError { + ): Result { if (result) { if (!state.invoke.result) { abort("Invoke result is missing."); } - return { - type: "InvokeResult", - invokeResult: state.invoke.result, - }; + return ResultOk(state.invoke.result); } else { if (!state.invoke.error) { abort("Invoke error is missing."); } - return { - type: "InvokeError", - invokeError: state.invoke.error, - }; + return ResultErr(Error(state.invoke.error)); } } @Tracer.traceMethod("WasmWrapper: getWasmModule") - private async _getWasmModule(): Promise { + private async _getWasmModule(): Promise> { if (this._wasmModule === undefined) { this._wasmModule = await this._fileReader.readFile(WRAP_MODULE_PATH); if (!this._wasmModule) { - throw Error(`Wrapper does not contain a wasm module`); + return ResultErr(Error(`Wrapper does not contain a wasm module`)); } } - return this._wasmModule; + return ResultOk(this._wasmModule); } } diff --git a/packages/js/wasm/src/imports.ts b/packages/js/wasm/src/imports.ts index 1e1ee4cc81..903adbbf18 100644 --- a/packages/js/wasm/src/imports.ts +++ b/packages/js/wasm/src/imports.ts @@ -33,20 +33,20 @@ export const createImports = (config: { const method = readString(memory.buffer, methodPtr, methodLen); const args = readBytes(memory.buffer, argsPtr, argsLen); - const { data, error } = await client.invoke({ + const result = await client.invoke({ uri: uri, method: method, args: new Uint8Array(args), encodeResult: true, }); - if (!error) { - state.subinvoke.result = data; + if (result.ok) { + state.subinvoke.result = result.value; } else { - state.subinvoke.error = `${error.name}: ${error.message}`; + state.subinvoke.error = `${result.error?.name}: ${result.error?.message}`; } - return !error; + return result.ok; }, // Give WASM the size of the result __wrap_subinvoke_result_len: (): u32 => { @@ -99,20 +99,20 @@ export const createImports = (config: { state.subinvokeImplementation.args = [implUri, method, args]; - const { data, error } = await client.invoke({ + const result = await client.invoke({ uri: implUri, method: method, args: new Uint8Array(args), encodeResult: true, }); - if (!error) { - state.subinvokeImplementation.result = data; + if (result.ok) { + state.subinvokeImplementation.result = result.value; } else { - state.subinvokeImplementation.error = `${error.name}: ${error.message}`; + state.subinvokeImplementation.error = `${result.error?.name}: ${result.error?.message}`; } - return !error; + return result.ok; }, __wrap_subinvokeImplementation_result_len: (): u32 => { if (!state.subinvokeImplementation.result) { From 9472c7c6b05e97078014080914406e0b3f8a9961 Mon Sep 17 00:00:00 2001 From: krisbitney Date: Wed, 21 Sep 2022 17:05:36 +0500 Subject: [PATCH 03/25] Replaced thrown exceptions with Result types in uri resolvers and more wasm-js --- .../src/ExtendableUriResolver.ts | 25 +++++++++++++------ .../src/UriResolverExtensionFileReader.ts | 16 ++++-------- .../src/UriResolverWrapper.ts | 11 +++----- packages/js/wasm/src/IFileReader.ts | 4 ++- packages/js/wasm/src/InMemoryFileReader.ts | 22 ++++++++++------ packages/js/wasm/src/WasmPackage.ts | 13 +++++----- packages/js/wasm/src/WasmWrapper.ts | 12 ++++++--- 7 files changed, 58 insertions(+), 45 deletions(-) diff --git a/packages/js/uri-resolver-extensions/src/ExtendableUriResolver.ts b/packages/js/uri-resolver-extensions/src/ExtendableUriResolver.ts index 5e3820418d..a00f7cf01c 100644 --- a/packages/js/uri-resolver-extensions/src/ExtendableUriResolver.ts +++ b/packages/js/uri-resolver-extensions/src/ExtendableUriResolver.ts @@ -13,7 +13,10 @@ import { import { Result, ResultOk } from "@polywrap/result"; import { UriResolverAggregatorBase } from "@polywrap/uri-resolvers-js"; -export class ExtendableUriResolver extends UriResolverAggregatorBase { +export class ExtendableUriResolver extends UriResolverAggregatorBase< + Error, + Error +> { private readonly resolverName: string; constructor(resolverName?: string) { @@ -25,13 +28,19 @@ export class ExtendableUriResolver extends UriResolverAggregatorBase { uri: Uri, client: Client, resolutionContext: IUriResolutionContext - ): Promise[]>> { - const uriResolverImpls = getImplementations( + ): Promise[], Error>> { + const getImplementationsResult = getImplementations( coreInterfaceUris.uriResolver, client.getInterfaces({}), client.getRedirects({}) ); + if (!getImplementationsResult.ok) { + return getImplementationsResult; + } + + const uriResolverImpls = getImplementationsResult.value; + const resolvers: UriResolverWrapper[] = uriResolverImpls .filter((x) => !resolutionContext.isResolving(x)) .map((implementationUri) => new UriResolverWrapper(implementationUri)); @@ -43,12 +52,12 @@ export class ExtendableUriResolver extends UriResolverAggregatorBase { uri: Uri, client: Client, resolutionContext: IUriResolutionContext - ): Promise> { + ): Promise> { const result = await this.getUriResolvers(uri, client, resolutionContext); - const resolvers = (result as { - ok: true; - value: UriResolverWrapper[]; - }).value; + if (!result.ok) { + return UriResolutionResult.err(result.error); + } + const resolvers = result.value as UriResolverWrapper[]; if (resolvers.length === 0) { return UriResolutionResult.ok(uri); diff --git a/packages/js/uri-resolver-extensions/src/UriResolverExtensionFileReader.ts b/packages/js/uri-resolver-extensions/src/UriResolverExtensionFileReader.ts index 52431c219e..3bc713533e 100644 --- a/packages/js/uri-resolver-extensions/src/UriResolverExtensionFileReader.ts +++ b/packages/js/uri-resolver-extensions/src/UriResolverExtensionFileReader.ts @@ -2,12 +2,12 @@ import { Client, combinePaths, InvokeOptions, - InvokeResult, Uri, UriResolverInterface, Wrapper, } from "@polywrap/core-js"; import { IFileReader } from "@polywrap/wasm-js"; +import { Result } from "@polywrap/result"; export class UriResolverExtensionFileReader implements IFileReader { constructor( @@ -16,26 +16,20 @@ export class UriResolverExtensionFileReader implements IFileReader { private readonly client: Client ) {} - async readFile(filePath: string): Promise { - const { data, error } = await UriResolverInterface.module.getFile( + async readFile(filePath: string): Promise> { + return await UriResolverInterface.module.getFile( { invoke: ( options: InvokeOptions - ): Promise> => + ): Promise> => this.client.invoke(options), invokeWrapper: ( options: InvokeOptions & { wrapper: Wrapper } - ): Promise> => + ): Promise> => this.client.invokeWrapper(options), }, this.resolverExtensionUri, combinePaths(this.wrapperUri.path, filePath) ); - - if (error) { - throw error; - } - - return data; } } diff --git a/packages/js/uri-resolver-extensions/src/UriResolverWrapper.ts b/packages/js/uri-resolver-extensions/src/UriResolverWrapper.ts index 7dd4172a9b..d01aeb6a2e 100644 --- a/packages/js/uri-resolver-extensions/src/UriResolverWrapper.ts +++ b/packages/js/uri-resolver-extensions/src/UriResolverWrapper.ts @@ -10,7 +10,7 @@ import { UriPackageOrWrapper, getEnvFromUriHistory, } from "@polywrap/core-js"; -import { Result, ResultOk, ResultErr } from "@polywrap/result"; +import { Result, ResultOk } from "@polywrap/result"; import { WasmPackage } from "@polywrap/wasm-js"; import { ResolverWithHistory } from "@polywrap/uri-resolvers-js"; @@ -91,13 +91,10 @@ const tryResolveUriWithImplementation = async ( } ); - const { data, error } = invokeResult; - - const uriOrManifest = data as UriResolverInterface.MaybeUriOrManifest; - - if (error) { - return ResultErr(error); + if (!invokeResult.ok) { + return invokeResult; } + const uriOrManifest = invokeResult.value as UriResolverInterface.MaybeUriOrManifest; return ResultOk(uriOrManifest ?? undefined); }; diff --git a/packages/js/wasm/src/IFileReader.ts b/packages/js/wasm/src/IFileReader.ts index c93503f6f3..3d7f868337 100644 --- a/packages/js/wasm/src/IFileReader.ts +++ b/packages/js/wasm/src/IFileReader.ts @@ -1,3 +1,5 @@ +import { Result } from "@polywrap/result"; + export interface IFileReader { - readFile(filePath: string): Promise; + readFile(filePath: string): Promise>; } diff --git a/packages/js/wasm/src/InMemoryFileReader.ts b/packages/js/wasm/src/InMemoryFileReader.ts index ae23ae5c08..bc4b577e07 100644 --- a/packages/js/wasm/src/InMemoryFileReader.ts +++ b/packages/js/wasm/src/InMemoryFileReader.ts @@ -1,15 +1,17 @@ import { WRAP_MANIFEST_PATH, WRAP_MODULE_PATH } from "./constants"; import { IFileReader } from "./IFileReader"; +import { Result, ResultErr, ResultOk } from "@polywrap/result"; + export class InMemoryFileReader { static fromManifest( manifest: Uint8Array, baseFileReader: IFileReader ): IFileReader { return { - async readFile(filePath: string): Promise { + async readFile(filePath: string): Promise> { if (filePath === WRAP_MANIFEST_PATH) { - return manifest; + return ResultOk(manifest); } else { return baseFileReader.readFile(filePath); } @@ -22,9 +24,9 @@ export class InMemoryFileReader { baseFileReader: IFileReader ): IFileReader { return { - async readFile(filePath: string): Promise { + async readFile(filePath: string): Promise> { if (filePath === WRAP_MODULE_PATH) { - return wasmModule; + return ResultOk(wasmModule); } else { return baseFileReader.readFile(filePath); } @@ -37,15 +39,19 @@ export class InMemoryFileReader { baseFileReader?: IFileReader ): IFileReader { return { - async readFile(filePath: string): Promise { + async readFile(filePath: string): Promise> { if (filePath === WRAP_MANIFEST_PATH) { - return manifest; + return ResultOk(manifest); } else if (filePath === WRAP_MODULE_PATH) { - return wasmModule; + return ResultOk(wasmModule); } else if (baseFileReader) { return baseFileReader.readFile(filePath); } else { - return undefined; + const error = Error( + `Unable to read file at filepath ${filePath}.` + + `Expected '${WRAP_MANIFEST_PATH}' or '${WRAP_MODULE_PATH}'.` + ); + return ResultErr(error); } }, }; diff --git a/packages/js/wasm/src/WasmPackage.ts b/packages/js/wasm/src/WasmPackage.ts index a785399905..4429e1e373 100644 --- a/packages/js/wasm/src/WasmPackage.ts +++ b/packages/js/wasm/src/WasmPackage.ts @@ -9,7 +9,7 @@ import { WrapManifest, } from "@polywrap/wrap-manifest-types-js"; import { GetManifestOptions, Wrapper } from "@polywrap/core-js"; -import { Result, ResultErr, ResultOk } from "@polywrap/result"; +import { Result, ResultErr } from "@polywrap/result"; export class WasmPackage implements IWasmPackage { protected constructor(private readonly fileReader: IFileReader) {} @@ -66,23 +66,24 @@ export class WasmPackage implements IWasmPackage { // TODO: return Result async getManifest(options?: GetManifestOptions): Promise { - const wrapManifest = await this.fileReader.readFile(WRAP_MANIFEST_PATH); + const result = await this.fileReader.readFile(WRAP_MANIFEST_PATH); - if (!wrapManifest) { + if (!result.ok) { throw Error(`WRAP manifest not found`); } + const wrapManifest = result.value; return deserializeWrapManifest(wrapManifest, options); } async getWasmModule(): Promise> { - const wasmModule = await this.fileReader.readFile(WRAP_MODULE_PATH); + const result = await this.fileReader.readFile(WRAP_MODULE_PATH); - if (!wasmModule) { + if (!result.ok) { return ResultErr(Error(`Wrapper does not contain a wasm module`)); } - return ResultOk(wasmModule); + return result; } // TODO: return Result diff --git a/packages/js/wasm/src/WasmWrapper.ts b/packages/js/wasm/src/WasmWrapper.ts index 2c88dfad1f..789511d3dd 100644 --- a/packages/js/wasm/src/WasmWrapper.ts +++ b/packages/js/wasm/src/WasmWrapper.ts @@ -66,15 +66,17 @@ export class WasmWrapper implements Wrapper { ): Promise> { const { path, encoding } = options; - const data = await this._fileReader.readFile(path); + const dataResult = await this._fileReader.readFile(path); // If nothing is returned, the file was not found - if (!data) { + if (!dataResult.ok) { return ResultErr( Error(`WasmWrapper: File was not found.\nSubpath: ${path}`) ); } + const data = dataResult.value; + if (encoding) { const decoder = new TextDecoder(encoding); const text = decoder.decode(data); @@ -205,11 +207,13 @@ export class WasmWrapper implements Wrapper { @Tracer.traceMethod("WasmWrapper: getWasmModule") private async _getWasmModule(): Promise> { if (this._wasmModule === undefined) { - this._wasmModule = await this._fileReader.readFile(WRAP_MODULE_PATH); + const result = await this._fileReader.readFile(WRAP_MODULE_PATH); - if (!this._wasmModule) { + if (!result.ok) { return ResultErr(Error(`Wrapper does not contain a wasm module`)); } + + this._wasmModule = result.value; } return ResultOk(this._wasmModule); From 3025b889d32558479106fd30f6c89df58c1db0d7 Mon Sep 17 00:00:00 2001 From: krisbitney Date: Sat, 24 Sep 2022 17:32:21 +0500 Subject: [PATCH 04/25] Replaced thrown exceptions with Result types in client; tests failing --- packages/js/client/src/PolywrapClient.ts | 150 +++++---- .../src/__tests__/core/plugin-wrapper.spec.ts | 17 +- .../uri-resolution/uri-resolution.spec.ts | 2 +- .../src/__tests__/core/wasm-wrapper.spec.ts | 75 +++-- .../js/client/src/__tests__/e2e/env.spec.ts | 6 +- .../js/client/src/__tests__/e2e/test-cases.ts | 292 +++++++++--------- .../client/src/__tests__/e2e/wasm-as.spec.ts | 16 +- .../client/src/__tests__/utils/resultTypes.ts | 1 + packages/js/core/src/types/Client.ts | 7 +- packages/js/core/src/types/Query.ts | 28 +- packages/js/test-env/src/index.ts | 14 +- packages/js/wasm/src/imports.ts | 9 +- 12 files changed, 349 insertions(+), 268 deletions(-) create mode 100644 packages/js/client/src/__tests__/utils/resultTypes.ts diff --git a/packages/js/client/src/PolywrapClient.ts b/packages/js/client/src/PolywrapClient.ts index 991d7fbf5b..244f414643 100644 --- a/packages/js/client/src/PolywrapClient.ts +++ b/packages/js/client/src/PolywrapClient.ts @@ -12,11 +12,9 @@ import { GetRedirectsOptions, InterfaceImplementations, InvokeOptions, - InvokeResult, InvokerOptions, PluginRegistration, QueryOptions, - QueryResult, SubscribeOptions, Subscription, Uri, @@ -37,6 +35,7 @@ import { UriResolutionContext, getEnvFromUriHistory, PluginPackage, + QueryResult, } from "@polywrap/core-js"; import { buildCleanUriHistory, @@ -46,7 +45,7 @@ import { msgpackEncode, msgpackDecode } from "@polywrap/msgpack-js"; import { WrapManifest } from "@polywrap/wrap-manifest-types-js"; import { Tracer, TracerConfig, TracingLevel } from "@polywrap/tracing-js"; import { ClientConfigBuilder } from "@polywrap/client-config-builder-js"; -import { Result } from "@polywrap/result"; +import { Result, ResultErr, ResultOk } from "@polywrap/result"; export interface PolywrapClientConfig extends ClientConfig { @@ -177,18 +176,27 @@ export class PolywrapClient implements Client { public async getManifest( uri: TUri, options: GetManifestOptions = {} - ): Promise { - const wrapper = await this._loadWrapper(Uri.from(uri), undefined, options); + ): Promise> { + const load = await this._loadWrapper(Uri.from(uri), undefined, options); + if (!load.ok) { + return load; + } + const wrapper = load.value; const client = contextualizeClient(this, options.contextId); - return await wrapper.getManifest(options, client); + const manifest = wrapper.getManifest(options, client); + return ResultOk(manifest); } @Tracer.traceMethod("PolywrapClient: getFile") public async getFile( uri: TUri, options: GetFileOptions - ): Promise { - const wrapper = await this._loadWrapper(Uri.from(uri), undefined, options); + ): Promise> { + const load = await this._loadWrapper(Uri.from(uri), undefined, options); + if (!load.ok) { + return load; + } + const wrapper = load.value; const client = contextualizeClient(this, options.contextId); return await wrapper.getFile(options, client); } @@ -197,21 +205,25 @@ export class PolywrapClient implements Client { public getImplementations( uri: TUri, options: GetImplementationsOptions = {} - ): TUri[] { + ): Result { const isUriTypeString = typeof uri === "string"; const applyRedirects = !!options.applyRedirects; - return isUriTypeString - ? (getImplementations( - Uri.from(uri), - this.getInterfaces(options), - applyRedirects ? this.getRedirects(options) : undefined - ).map((x: Uri) => x.uri) as TUri[]) - : (getImplementations( - Uri.from(uri), - this.getInterfaces(options), - applyRedirects ? this.getRedirects(options) : undefined - ) as TUri[]); + const getImplResult = getImplementations( + Uri.from(uri), + this.getInterfaces(options), + applyRedirects ? this.getRedirects(options) : undefined + ); + + if (!getImplResult.ok) { + return getImplResult; + } + + const uris = isUriTypeString + ? (getImplResult.value.map((x: Uri) => x.uri) as TUri[]) + : (getImplResult.value as TUri[]); + + return ResultOk(uris); } @Tracer.traceMethod("PolywrapClient: query", TracingLevel.High) @@ -229,7 +241,7 @@ export class PolywrapClient implements Client { let result: QueryResult; - try { + err: try { const typedOptions: QueryOptions = { ...options, uri: Uri.from(options.uri), @@ -242,12 +254,17 @@ export class PolywrapClient implements Client { typeof query === "string" ? createQueryDocument(query) : query; // Parse the query to understand what's being invoked - const queryInvocations = parseQuery(uri, queryDocument, variables); + const parseResult = parseQuery(uri, queryDocument, variables); + if (!parseResult.ok) { + result = { errors: [parseResult.error as Error] }; + break err; + } + const queryInvocations = parseResult.value; // Execute all invocations in parallel const parallelInvocations: Promise<{ name: string; - result: InvokeResult; + result: Result; }>[] = []; for (const invocationName of Object.keys(queryInvocations)) { @@ -273,9 +290,10 @@ export class PolywrapClient implements Client { const errors: Error[] = []; for (const invocation of invocationResults) { - data[invocation.name] = invocation.result.data; - if (invocation.result.error) { - errors.push(invocation.result.error); + if (invocation.result.ok) { + data[invocation.name] = invocation.result.value; + } else { + errors.push(invocation.result.error as Error); } } @@ -303,15 +321,15 @@ export class PolywrapClient implements Client { TUri extends Uri | string = string >( options: InvokerOptions & { wrapper: Wrapper } - ): Promise> { + ): Promise> { const { contextId, shouldClearContext } = this._setContext( options.contextId, options.config ); - let error: Error | undefined; + let error: Error; - try { + invokeError: try { const typedOptions: InvokeOptions = { ...options, contextId: contextId, @@ -324,22 +342,21 @@ export class PolywrapClient implements Client { contextualizeClient(this, contextId) ); - if (invocableResult.data !== undefined) { - if (options.encodeResult && !invocableResult.encoded) { - return { - data: (msgpackEncode(invocableResult.data) as unknown) as TData, - }; - } else if (invocableResult.encoded && !options.encodeResult) { - return { - data: msgpackDecode(invocableResult.data as Uint8Array) as TData, - }; - } else { - return { - data: invocableResult.data as TData, - }; - } + if (!invocableResult.data.ok) { + error = invocableResult.data.error as Error; + break invokeError; + } + + const value = invocableResult.data.value; + + if (options.encodeResult && !invocableResult.encoded) { + const encoded = msgpackEncode(value); + return ResultOk((encoded as unknown) as TData); + } else if (invocableResult.encoded && !options.encodeResult) { + const decoded = msgpackDecode(value as Uint8Array); + return ResultOk(decoded as TData); } else { - error = invocableResult.error; + return ResultOk(value as TData); } } catch (e) { error = e; @@ -349,21 +366,21 @@ export class PolywrapClient implements Client { this._clearContext(contextId); } - return { error }; + return ResultErr(error); } @Tracer.traceMethod("PolywrapClient: invoke") public async invoke( options: InvokerOptions - ): Promise> { + ): Promise> { const { contextId, shouldClearContext } = this._setContext( options.contextId, options.config ); - let error: Error | undefined; + let error: Error; - try { + err: try { const typedOptions: InvokeOptions = { ...options, contextId: contextId, @@ -373,11 +390,16 @@ export class PolywrapClient implements Client { const resolutionContext = options.resolutionContext ?? new UriResolutionContext(); - const wrapper = await this._loadWrapper( + const loadWrapperResult = await this._loadWrapper( typedOptions.uri, resolutionContext, { contextId } ); + if (!loadWrapperResult.ok) { + error = loadWrapperResult.error as Error; + break err; + } + const wrapper = loadWrapperResult.value; const client = contextualizeClient(this, contextId); @@ -386,11 +408,15 @@ export class PolywrapClient implements Client { client ); - return await client.invokeWrapper({ + const invokeResult = await client.invokeWrapper({ env: env?.env, ...typedOptions, wrapper, }); + if (invokeResult.ok) { + return invokeResult; + } + error = invokeResult.error as Error; } catch (e) { error = e; } @@ -399,7 +425,7 @@ export class PolywrapClient implements Client { this._clearContext(contextId); } - return { error }; + return ResultErr(error); } @Tracer.traceMethod("PolywrapClient: subscribe") @@ -442,7 +468,7 @@ export class PolywrapClient implements Client { } subscription.isActive = false; }, - async *[Symbol.asyncIterator](): AsyncGenerator> { + async *[Symbol.asyncIterator](): AsyncGenerator> { let timeout: NodeJS.Timeout | undefined = undefined; subscription.isActive = true; @@ -468,7 +494,7 @@ export class PolywrapClient implements Client { break; } - const result: InvokeResult = await client.invoke({ + const result = await client.invoke({ uri: uri, method: method, args: args, @@ -625,7 +651,7 @@ export class PolywrapClient implements Client { uri: Uri, resolutionContext?: IUriResolutionContext, options?: Contextualized - ): Promise { + ): Promise> { Tracer.setAttribute("label", `Wrapper loaded: ${uri}`, TracingLevel.High); if (!resolutionContext) { @@ -639,27 +665,29 @@ export class PolywrapClient implements Client { }); if (!result.ok) { - if (result.error) { - throw result.error; + if (result.error && result.error instanceof Error) { + return result as Result; } else { - throw Error( + const error = Error( `Error resolving URI "${uri.uri}"\nResolution Stack: ${JSON.stringify( resolutionContext.getHistory(), null, 2 )}` ); + return ResultErr(error); } } const uriPackageOrWrapper = result.value; if (uriPackageOrWrapper.type === "uri") { - throw Error( + const error = Error( `Error resolving URI "${uri.uri}"\nURI not found ${ uriPackageOrWrapper.uri.uri }\nResolution Stack: ${JSON.stringify(history, null, 2)}` ); + return ResultErr(error); } let packageOrWrapper: IWrapPackage | Wrapper; @@ -672,7 +700,7 @@ export class PolywrapClient implements Client { const wrapper = await initWrapper(packageOrWrapper); - return wrapper; + return ResultOk(wrapper); } } @@ -693,12 +721,12 @@ const contextualizeClient = ( }, invokeWrapper: ( options: InvokeOptions & { wrapper: Wrapper } - ): Promise> => { + ): Promise> => { return client.invokeWrapper({ ...options, contextId }); }, invoke: ( options: InvokeOptions - ): Promise> => { + ): Promise> => { return client.invoke({ ...options, contextId }); }, subscribe: ( diff --git a/packages/js/client/src/__tests__/core/plugin-wrapper.spec.ts b/packages/js/client/src/__tests__/core/plugin-wrapper.spec.ts index ecdd6ef0fc..2aa251f09c 100644 --- a/packages/js/client/src/__tests__/core/plugin-wrapper.spec.ts +++ b/packages/js/client/src/__tests__/core/plugin-wrapper.spec.ts @@ -83,9 +83,9 @@ describe("plugin-wrapper", () => { method: "getMap", }); - expect(getResult.error).toBeFalsy(); - expect(getResult.data).toBeTruthy(); - expect(getResult.data).toMatchObject( + if (!getResult.ok) fail(getResult.error); + expect(getResult.value).toBeTruthy(); + expect(getResult.value).toMatchObject( new Map().set("a", 1).set("b", 2) ); @@ -97,9 +97,9 @@ describe("plugin-wrapper", () => { }, }); - expect(updateResult.error).toBeFalsy(); - expect(updateResult.data).toBeTruthy(); - expect(updateResult.data).toMatchObject( + if (!updateResult.ok) fail(updateResult.error); + expect(updateResult.value).toBeTruthy(); + expect(updateResult.value).toMatchObject( new Map().set("a", 1).set("b", 3).set("c", 5) ); }); @@ -202,7 +202,8 @@ describe("plugin-wrapper", () => { test("get manifest should fetch wrap manifest from plugin", async () => { const client = await getClient(); const manifest = await client.getManifest("ens/ipfs.polywrap.eth"); - expect(manifest.type).toEqual("plugin"); - expect(manifest.name).toEqual("Ipfs"); + if (!manifest.ok) fail(manifest.error); + expect(manifest.value.type).toEqual("plugin"); + expect(manifest.value.name).toEqual("Ipfs"); }); }); diff --git a/packages/js/client/src/__tests__/core/uri-resolution/uri-resolution.spec.ts b/packages/js/client/src/__tests__/core/uri-resolution/uri-resolution.spec.ts index 604184ba3f..cfb039a7e1 100644 --- a/packages/js/client/src/__tests__/core/uri-resolution/uri-resolution.spec.ts +++ b/packages/js/client/src/__tests__/core/uri-resolution/uri-resolution.spec.ts @@ -1,7 +1,7 @@ -import { Uri } from "../../../../"; import { buildWrapper } from "@polywrap/test-env-js"; import { GetPathToTestWrappers } from "@polywrap/test-cases"; import { + Uri, coreInterfaceUris, IUriResolutionStep, PluginModule, diff --git a/packages/js/client/src/__tests__/core/wasm-wrapper.spec.ts b/packages/js/client/src/__tests__/core/wasm-wrapper.spec.ts index d6a603cf83..98719aa545 100644 --- a/packages/js/client/src/__tests__/core/wasm-wrapper.spec.ts +++ b/packages/js/client/src/__tests__/core/wasm-wrapper.spec.ts @@ -6,6 +6,7 @@ import { Uri, PluginModule, Subscription } from "../.."; import { WrapManifest } from "@polywrap/wrap-manifest-types-js"; import { getClient } from "../utils/getClient"; import { makeMemoryStoragePlugin } from "../e2e/memory-storage"; +import { ErrResult } from "../utils/resultTypes"; jest.setTimeout(200000); @@ -46,10 +47,10 @@ describe("wasm-wrapper", () => { }, }); - expect(result.error).toBeFalsy(); - expect(result.data).toBeTruthy(); - expect(typeof result.data).toBe("string"); - expect(result.data).toEqual("test"); + if (!result.ok) fail(result.error); + expect(result.value).toBeTruthy(); + expect(typeof result.value).toBe("string"); + expect(result.value).toEqual("test"); }); test("can invoke with typed URI", async () => { @@ -62,10 +63,10 @@ describe("wasm-wrapper", () => { }, }); - expect(result.error).toBeFalsy(); - expect(result.data).toBeTruthy(); - expect(typeof result.data).toBe("string"); - expect(result.data).toEqual("test"); + if (!result.ok) fail(result.error); + expect(result.value).toBeTruthy(); + expect(typeof result.value).toBe("string"); + expect(result.value).toEqual("test"); }); test("invoke with decode defaulted to true works as expected", async () => { @@ -78,10 +79,10 @@ describe("wasm-wrapper", () => { }, }); - expect(result.error).toBeFalsy(); - expect(result.data).toBeTruthy(); - expect(typeof result.data).toBe("string"); - expect(result.data).toEqual("test"); + if (!result.ok) fail(result.error); + expect(result.value).toBeTruthy(); + expect(typeof result.value).toBe("string"); + expect(result.value).toEqual("test"); }); test("invoke with decode set to false works as expected", async () => { @@ -95,10 +96,10 @@ describe("wasm-wrapper", () => { encodeResult: true, }); - expect(result.error).toBeFalsy(); - expect(result.data).toBeTruthy(); - expect(result.data instanceof Uint8Array).toBeTruthy(); - expect(msgpackDecode(result.data as Uint8Array)).toEqual("test"); + if (!result.ok) fail(result.error); + expect(result.value).toBeTruthy(); + expect(result.value instanceof Uint8Array).toBeTruthy(); + expect(msgpackDecode(result.value as Uint8Array)).toEqual("test"); }); it("should invoke wrapper with custom redirects", async () => { @@ -125,8 +126,9 @@ describe("wasm-wrapper", () => { }, }); - expect(result.data).toBeTruthy(); - expect(result.data).toEqual("plugin response"); + if (!result.ok) fail(result.error); + expect(result.value).toBeTruthy(); + expect(result.value).toEqual("plugin response"); }); it("should allow query time redirects", async () => { @@ -157,8 +159,9 @@ describe("wasm-wrapper", () => { }, }); - expect(result.data).toBeTruthy(); - expect(result.data).toEqual("plugin response"); + if (!result.ok) fail(result.error); + expect(result.value).toBeTruthy(); + expect(result.value).toEqual("plugin response"); }); test("get file from wrapper", async () => { @@ -168,12 +171,14 @@ describe("wasm-wrapper", () => { await fs.promises.readFile(`${simpleWrapperPath}/build/wrap.info`) ); - const receivedManifest: Uint8Array = (await client.getFile( + const receivedManifestResult = await client.getFile( simpleWrapperUri, { path: "./wrap.info", } - )) as Uint8Array; + ); + if (!receivedManifestResult.ok) fail(receivedManifestResult.error); + const receivedManifest = receivedManifestResult.value as Uint8Array; expect(receivedManifest).toEqual(expectedManifest); @@ -181,12 +186,14 @@ describe("wasm-wrapper", () => { await fs.promises.readFile(`${simpleWrapperPath}/build/wrap.wasm`) ); - const receivedWasmModule: Uint8Array = (await client.getFile( + const receivedWasmModuleResult = await client.getFile( simpleWrapperUri, { path: "./wrap.wasm", } - )) as Uint8Array; + ); + if (!receivedWasmModuleResult.ok) fail(receivedWasmModuleResult.error); + const receivedWasmModule = receivedWasmModuleResult.value as Uint8Array; expect(receivedWasmModule).toEqual(expectedWasmModule); @@ -202,11 +209,12 @@ describe("wasm-wrapper", () => { ], }); - await expect(() => - pluginClient.getFile("ens/mock-plugin.eth", { - path: "./index.js", - }) - ).rejects.toThrow("client.getFile(...) is not implemented for Plugins."); + let pluginGetFileResult = await pluginClient.getFile("ens/mock-plugin.eth", { + path: "./index.js", + }); + + pluginGetFileResult = pluginGetFileResult as ErrResult; + expect(pluginGetFileResult.error).toContain("client.getFile(...) is not implemented for Plugins."); }); test("subscribe", async () => { @@ -243,8 +251,8 @@ describe("wasm-wrapper", () => { }); for await (let result of getSubscription) { - expect(result.error).toBeFalsy(); - const val = result.data; + if (!result.ok) fail(result.error); + const val = result.value; if (val !== undefined) { results.push(val); @@ -290,8 +298,9 @@ describe("wasm-wrapper", () => { new Promise(async () => { for await (let result of getSubscription) { - expect(result.error).toBeFalsy(); - const val = result.data; + if (!result.ok) fail(result.error); + const val = result.value; + if (val !== undefined) { results.push(val); if (val >= 2) { diff --git a/packages/js/client/src/__tests__/e2e/env.spec.ts b/packages/js/client/src/__tests__/e2e/env.spec.ts index dbb24a125a..b94e992049 100644 --- a/packages/js/client/src/__tests__/e2e/env.spec.ts +++ b/packages/js/client/src/__tests__/e2e/env.spec.ts @@ -48,9 +48,9 @@ describe("env", () => { method: "mockEnv", }); - expect(mockEnv.error).toBeFalsy(); - expect(mockEnv.data).toBeTruthy(); - expect(mockEnv.data).toMatchObject({ arg1: "10" }); + if (!mockEnv.ok) fail(mockEnv.error); + expect(mockEnv.value).toBeTruthy(); + expect(mockEnv.value).toMatchObject({ arg1: "10" }); }); }); }); diff --git a/packages/js/client/src/__tests__/e2e/test-cases.ts b/packages/js/client/src/__tests__/e2e/test-cases.ts index e3ac67c7ba..54de40c69d 100644 --- a/packages/js/client/src/__tests__/e2e/test-cases.ts +++ b/packages/js/client/src/__tests__/e2e/test-cases.ts @@ -1,5 +1,6 @@ import { PolywrapClient, Uri } from "../../"; import { BigNumber } from "bignumber.js"; +import { ErrResult } from "../utils/resultTypes"; export const runAsyncifyTest = async ( client: PolywrapClient, @@ -15,27 +16,27 @@ export const runAsyncifyTest = async ( const expected = Array.from(new Array(40), (_, index) => index.toString()); - expect(subsequentInvokes.error).toBeFalsy(); - expect(subsequentInvokes.data).toBeTruthy(); - expect(subsequentInvokes.data).toEqual(expected); + if (!subsequentInvokes.ok) fail(subsequentInvokes.error); + expect(subsequentInvokes.value).toBeTruthy(); + expect(subsequentInvokes.value).toEqual(expected); const localVarMethod = await client.invoke({ uri: wrapperUri, method: "localVarMethod", }); - expect(localVarMethod.error).toBeFalsy(); - expect(localVarMethod.data).toBeTruthy(); - expect(localVarMethod.data).toEqual(true); + if (!localVarMethod.ok) fail(localVarMethod.error); + expect(localVarMethod.value).toBeTruthy(); + expect(localVarMethod.value).toEqual(true); const globalVarMethod = await client.invoke({ uri: wrapperUri, method: "globalVarMethod", }); - expect(globalVarMethod.error).toBeFalsy(); - expect(globalVarMethod.data).toBeTruthy(); - expect(globalVarMethod.data).toEqual(true); + if (!globalVarMethod.ok) fail(globalVarMethod.error); + expect(globalVarMethod.value).toBeTruthy(); + expect(globalVarMethod.value).toEqual(true); const largeStr = new Array(10000).join("polywrap "); const setDataWithLargeArgs = await client.invoke({ @@ -46,9 +47,9 @@ export const runAsyncifyTest = async ( }, }); - expect(setDataWithLargeArgs.error).toBeFalsy(); - expect(setDataWithLargeArgs.data).toBeTruthy(); - expect(setDataWithLargeArgs.data).toEqual(largeStr); + if (!setDataWithLargeArgs.ok) fail(setDataWithLargeArgs.error); + expect(setDataWithLargeArgs.value).toBeTruthy(); + expect(setDataWithLargeArgs.value).toEqual(largeStr); const setDataWithManyArgs = await client.invoke({ uri: wrapperUri, @@ -69,9 +70,9 @@ export const runAsyncifyTest = async ( }, }); - expect(setDataWithManyArgs.error).toBeFalsy(); - expect(setDataWithManyArgs.data).toBeTruthy(); - expect(setDataWithManyArgs.data).toEqual( + if (!setDataWithManyArgs.ok) fail(setDataWithManyArgs.error); + expect(setDataWithManyArgs.value).toBeTruthy(); + expect(setDataWithManyArgs.value).toEqual( "polywrap apolywrap bpolywrap cpolywrap dpolywrap epolywrap fpolywrap gpolywrap hpolywrap ipolywrap jpolywrap kpolywrap l" ); @@ -111,9 +112,9 @@ export const runAsyncifyTest = async ( }, }); - expect(setDataWithManyStructuredArgs.error).toBeFalsy(); - expect(setDataWithManyStructuredArgs.data).toBeTruthy(); - expect(setDataWithManyStructuredArgs.data).toBe(true); + if (!setDataWithManyStructuredArgs.ok) fail(setDataWithManyStructuredArgs.error); + expect(setDataWithManyStructuredArgs.value).toBeTruthy(); + expect(setDataWithManyStructuredArgs.value).toBe(true); }; export const runBigIntTypeTest = async ( @@ -134,9 +135,9 @@ export const runBigIntTypeTest = async ( const result = BigInt("123456789123456789") * BigInt("987654321987654321"); - expect(response.error).toBeFalsy(); - expect(response.data).toBeTruthy(); - expect(response.data).toEqual(result.toString()); + if (!response.ok) fail(response.error); + expect(response.value).toBeTruthy(); + expect(response.value).toEqual(result.toString()); } { @@ -159,9 +160,9 @@ export const runBigIntTypeTest = async ( BigInt("987654321987654321") * BigInt("987654321987654321987654321987654321"); - expect(response.error).toBeFalsy(); - expect(response.data).toBeTruthy(); - expect(response.data).toEqual(result.toString()); + if (!response.ok) fail(response.error); + expect(response.value).toBeTruthy(); + expect(response.value).toEqual(result.toString()); } }; @@ -185,9 +186,9 @@ export const runBigNumberTypeTest = async ( const prop1 = new BigNumber("98.7654321987654321"); const result = arg1.times(prop1); - expect(response.error).toBeFalsy(); - expect(response.data).toBeTruthy(); - expect(response.data).toEqual(result.toFixed()); + if (!response.ok) fail(response.error); + expect(response.value).toBeTruthy(); + expect(response.value).toEqual(result.toFixed()); } { @@ -210,9 +211,9 @@ export const runBigNumberTypeTest = async ( const prop2 = new BigNumber("987.654321987654321987654321987654321"); const result = arg1.times(arg2).times(prop1).times(prop2); - expect(response.error).toBeFalsy(); - expect(response.data).toBeTruthy(); - expect(response.data).toEqual(result.toFixed()); + if (!response.ok) fail(response.error); + expect(response.value).toBeTruthy(); + expect(response.value).toEqual(result.toFixed()); } }; @@ -227,15 +228,15 @@ export const runBytesTypeTest = async (client: PolywrapClient, uri: string) => { }, }); - expect(response.error).toBeFalsy(); - expect(response.data).toBeTruthy(); - expect(response.data).toEqual( + if (!response.ok) fail(response.error); + expect(response.value).toBeTruthy(); + expect(response.value).toEqual( new TextEncoder().encode("Argument Value Sanity!") ); }; export const runEnumTypesTest = async (client: PolywrapClient, uri: string) => { - const method1a = await client.invoke({ + let method1a = await client.invoke({ uri, method: "method1", args: { @@ -243,8 +244,9 @@ export const runEnumTypesTest = async (client: PolywrapClient, uri: string) => { }, }); + method1a = method1a as ErrResult; expect(method1a.error).toBeTruthy(); - expect((method1a.error as Error).message).toMatch( + expect(method1a.error?.message).toMatch( /__wrap_abort: Invalid value for enum 'SanityEnum': 5/gm ); @@ -257,11 +259,11 @@ export const runEnumTypesTest = async (client: PolywrapClient, uri: string) => { }, }); - expect(method1b.error).toBeFalsy(); - expect(method1b.data).toBeTruthy(); - expect(method1b.data).toEqual(2); + if (!method1b.ok) fail(method1b.error); + expect(method1b.value).toBeTruthy(); + expect(method1b.value).toEqual(2); - const method1c = await client.invoke({ + let method1c = await client.invoke({ uri, method: "method1", args: { @@ -270,6 +272,7 @@ export const runEnumTypesTest = async (client: PolywrapClient, uri: string) => { }, }); + method1c = method1c as ErrResult; expect(method1c.error).toBeTruthy(); expect(method1c.error?.message).toMatch( /__wrap_abort: Invalid key for enum 'SanityEnum': INVALID/gm @@ -283,9 +286,9 @@ export const runEnumTypesTest = async (client: PolywrapClient, uri: string) => { }, }); - expect(method2a.error).toBeFalsy(); - expect(method2a.data).toBeTruthy(); - expect(method2a.data).toEqual([0, 0, 2]); + if (!method2a.ok) fail(method2a.error); + expect(method2a.value).toBeTruthy(); + expect(method2a.value).toEqual([0, 0, 2]); }; export const runImplementationsTest = async ( @@ -319,12 +322,13 @@ export const runImplementationsTest = async ( }), ]); - expect(results.filter((x) => x.error).length).toEqual(0); - expect(results[0].data).toEqual({ + const okResults = results.filter((x) => x.ok) as { ok: true, value: unknown }[]; + expect(okResults.length).toEqual(results.length); + expect(okResults[0].value).toEqual({ uint8: 1, str: "Test String 1", }); - expect(results[1].data).toBe("Test String 2"); + expect(okResults[1].value).toBe("Test String 2"); }; export const runGetImplementationsTest = async ( @@ -341,9 +345,9 @@ export const runGetImplementationsTest = async ( method: "moduleImplementations", }); - expect(result.error).toBeFalsy(); - expect(result.data).toBeTruthy(); - expect(result.data).toEqual([implUri.uri]); + if (!result.ok) fail(result.error); + expect(result.value).toBeTruthy(); + expect(result.value).toEqual([implUri.uri]); const moduleMethodResult = await client.invoke({ uri: aggregatorUri, @@ -354,63 +358,68 @@ export const runGetImplementationsTest = async ( }, }, }); - expect(moduleMethodResult.error).toBeFalsy(); - expect(moduleMethodResult.data).toEqual("Test String 2"); + if (!moduleMethodResult.ok) fail(moduleMethodResult.error); + expect(moduleMethodResult.value).toEqual("Test String 2"); }; export const runInvalidTypesTest = async ( client: PolywrapClient, uri: string ) => { - const invalidBoolIntSent = await client.invoke({ + let invalidBoolIntSent = await client.invoke({ uri, method: "boolMethod", args: { arg: 10, }, }); + invalidBoolIntSent = invalidBoolIntSent as { ok: false, error: Error }; expect(invalidBoolIntSent.error).toBeTruthy(); expect(invalidBoolIntSent.error?.message).toMatch( /Property must be of type 'bool'. Found 'int'./ ); - const invalidIntBoolSent = await client.invoke({ + let invalidIntBoolSent = await client.invoke({ uri, method: "intMethod", args: { arg: true, }, }); + invalidIntBoolSent = invalidIntBoolSent as ErrResult; expect(invalidIntBoolSent.error).toBeTruthy(); expect(invalidIntBoolSent.error?.message).toMatch( /Property must be of type 'int'. Found 'bool'./ ); - const invalidUIntArraySent = await client.invoke({ + let invalidUIntArraySent = await client.invoke({ uri, method: "uIntMethod", args: { arg: [10], }, }); + invalidUIntArraySent = invalidUIntArraySent as ErrResult; expect(invalidUIntArraySent.error).toBeTruthy(); expect(invalidUIntArraySent.error?.message).toMatch( /Property must be of type 'uint'. Found 'array'./ ); - const invalidBytesFloatSent = await client.invoke({ + let invalidBytesFloatSent = await client.invoke({ uri, method: "bytesMethod", args: { arg: 10.15, }, }); + + invalidBytesFloatSent = invalidBytesFloatSent as ErrResult; expect(invalidBytesFloatSent.error).toBeTruthy(); expect(invalidBytesFloatSent.error?.message).toMatch( /Property must be of type 'bytes'. Found 'float64'./ ); - const invalidArrayMapSent = await client.invoke({ + let invalidArrayMapSent = await client.invoke({ uri, method: "arrayMethod", args: { @@ -419,6 +428,8 @@ export const runInvalidTypesTest = async ( }, }, }); + + invalidArrayMapSent = invalidArrayMapSent as ErrResult; expect(invalidArrayMapSent.error).toBeTruthy(); expect(invalidArrayMapSent.error?.message).toMatch( /Property must be of type 'array'. Found 'map'./ @@ -428,7 +439,7 @@ export const runInvalidTypesTest = async ( export const runJsonTypeTest = async (client: PolywrapClient, uri: string, testReserved: boolean = false) => { type Json = string; const value = JSON.stringify({ foo: "bar", bar: "bar" }); - const parseResponse = await client.invoke<{ parse: Json }>({ + const parseResponse = await client.invoke({ uri, method: "parse", args: { @@ -436,14 +447,15 @@ export const runJsonTypeTest = async (client: PolywrapClient, uri: string, testR }, }); - expect(parseResponse.data).toEqual(value); + if (!parseResponse.ok) fail(parseResponse.error); + expect(parseResponse.value).toEqual(value); const values = [ JSON.stringify({ bar: "foo" }), JSON.stringify({ baz: "fuz" }), ]; - const stringifyResponse = await client.invoke<{ stringify: Json }>({ + const stringifyResponse = await client.invoke({ uri, method: "stringify", args: { @@ -451,16 +463,15 @@ export const runJsonTypeTest = async (client: PolywrapClient, uri: string, testR }, }); - expect(stringifyResponse.data).toEqual(values.join("")); + if(!stringifyResponse.ok) fail(stringifyResponse.error); + expect(stringifyResponse.value).toEqual(values.join("")); const object = { jsonA: JSON.stringify({ foo: "bar" }), jsonB: JSON.stringify({ fuz: "baz" }), }; - const stringifyObjectResponse = await client.invoke<{ - stringifyObject: string; - }>({ + const stringifyObjectResponse = await client.invoke({ uri, method: "stringifyObject", args: { @@ -468,7 +479,8 @@ export const runJsonTypeTest = async (client: PolywrapClient, uri: string, testR }, }); - expect(stringifyObjectResponse.data).toEqual(object.jsonA + object.jsonB); + if (!stringifyObjectResponse.ok) fail(stringifyObjectResponse.error); + expect(stringifyObjectResponse.value).toEqual(object.jsonA + object.jsonB); const json = { valueA: 5, @@ -476,16 +488,15 @@ export const runJsonTypeTest = async (client: PolywrapClient, uri: string, testR valueC: true, }; - const methodJSONResponse = await client.invoke<{ - methodJSON: Json; - }>({ + const methodJSONResponse = await client.invoke({ uri, method: "methodJSON", args: json, }); + if (!methodJSONResponse.ok) fail(methodJSONResponse.error); const methodJSONResult = JSON.stringify(json); - expect(methodJSONResponse.data).toEqual(methodJSONResult); + expect(methodJSONResponse.value).toEqual(methodJSONResult); if (testReserved) { const reserved = { const: "hello", if: true }; @@ -496,8 +507,9 @@ export const runJsonTypeTest = async (client: PolywrapClient, uri: string, testR json: JSON.stringify(reserved) }, }); - - expect(parseReservedResponse.data).toEqual(reserved); + + if (!parseReservedResponse.ok) fail(parseReservedResponse.error); + expect(parseReservedResponse.value).toEqual(reserved); const stringifyReservedResponse = await client.invoke({ uri, @@ -506,7 +518,9 @@ export const runJsonTypeTest = async (client: PolywrapClient, uri: string, testR reserved }, }); - expect(stringifyReservedResponse.data).toEqual(JSON.stringify(reserved)); + + if (!stringifyReservedResponse.ok) fail(stringifyReservedResponse.error); + expect(stringifyReservedResponse.value).toEqual(JSON.stringify(reserved)); } }; @@ -537,8 +551,9 @@ export const runLargeTypesTest = async ( }, }); - expect(largeTypesMethodCall.data).toBeTruthy(); - expect(largeTypesMethodCall.data).toEqual({ + if (!largeTypesMethodCall.ok) fail(largeTypesMethodCall.error); + expect(largeTypesMethodCall.value).toBeTruthy(); + expect(largeTypesMethodCall.value).toEqual({ largeStr: largeStr, largeBytes: largeBytes, largeStrArray: largeStrArray, @@ -550,7 +565,7 @@ export const runNumberTypesTest = async ( client: PolywrapClient, uri: string ) => { - const i8Underflow = await client.invoke({ + let i8Underflow = await client.invoke({ uri, method: "i8Method", args: { @@ -558,13 +573,14 @@ export const runNumberTypesTest = async ( second: 10, }, }); + + i8Underflow = i8Underflow as ErrResult; expect(i8Underflow.error).toBeTruthy(); expect(i8Underflow.error?.message).toMatch( /integer overflow: value = -129; bits = 8/ ); - expect(i8Underflow.data).toBeUndefined(); - const u8Overflow = await client.invoke({ + let u8Overflow = await client.invoke({ uri, method: "u8Method", args: { @@ -572,13 +588,13 @@ export const runNumberTypesTest = async ( second: 10, }, }); + u8Overflow = u8Overflow as ErrResult; expect(u8Overflow.error).toBeTruthy(); expect(u8Overflow.error?.message).toMatch( /unsigned integer overflow: value = 256; bits = 8/ ); - expect(u8Overflow.data).toBeUndefined(); - const i16Underflow = await client.invoke({ + let i16Underflow = await client.invoke({ uri, method: "i16Method", args: { @@ -586,13 +602,13 @@ export const runNumberTypesTest = async ( second: 10, }, }); + i16Underflow = i16Underflow as ErrResult; expect(i16Underflow.error).toBeTruthy(); expect(i16Underflow.error?.message).toMatch( /integer overflow: value = -32769; bits = 16/ ); - expect(i16Underflow.data).toBeUndefined(); - const u16Overflow = await client.invoke({ + let u16Overflow = await client.invoke({ uri, method: "u16Method", args: { @@ -600,13 +616,13 @@ export const runNumberTypesTest = async ( second: 10, }, }); + u16Overflow = u16Overflow as ErrResult; expect(u16Overflow.error).toBeTruthy(); expect(u16Overflow.error?.message).toMatch( /unsigned integer overflow: value = 65536; bits = 16/ ); - expect(u16Overflow.data).toBeUndefined(); - const i32Underflow = await client.invoke({ + let i32Underflow = await client.invoke({ uri, method: "i32Method", args: { @@ -614,13 +630,13 @@ export const runNumberTypesTest = async ( second: 10, }, }); + i32Underflow = i32Underflow as ErrResult; expect(i32Underflow.error).toBeTruthy(); expect(i32Underflow.error?.message).toMatch( /integer overflow: value = -2147483649; bits = 32/ ); - expect(i32Underflow.data).toBeUndefined(); - const u32Overflow = await client.invoke({ + let u32Overflow = await client.invoke({ uri, method: "u32Method", args: { @@ -628,11 +644,11 @@ export const runNumberTypesTest = async ( second: 10, }, }); + u32Overflow = u32Overflow as ErrResult; expect(u32Overflow.error).toBeTruthy(); expect(u32Overflow.error?.message).toMatch( /unsigned integer overflow: value = 4294967296; bits = 32/ ); - expect(u32Overflow.data).toBeUndefined(); }; export const runObjectTypesTest = async ( @@ -652,9 +668,9 @@ export const runObjectTypesTest = async ( }, }); - expect(method1a.error).toBeFalsy(); - expect(method1a.data).toBeTruthy(); - expect(method1a.data).toEqual([ + if (!method1a.ok) fail(method1a.error); + expect(method1a.value).toBeTruthy(); + expect(method1a.value).toEqual([ { prop: "arg1 prop", nested: { @@ -688,9 +704,9 @@ export const runObjectTypesTest = async ( }, }); - expect(method1b.error).toBeFalsy(); - expect(method1b.data).toBeTruthy(); - expect(method1b.data).toEqual([ + if (!method1b.ok) fail(method1b.error); + expect(method1b.value).toBeTruthy(); + expect(method1b.value).toEqual([ { prop: "arg1 prop", nested: { @@ -718,9 +734,9 @@ export const runObjectTypesTest = async ( }, }); - expect(method2a.error).toBeFalsy(); - expect(method2a.data).toBeTruthy(); - expect(method2a.data).toEqual({ + if (!method2a.ok) fail(method2a.error); + expect(method2a.value).toBeTruthy(); + expect(method2a.value).toEqual({ prop: "arg prop", nested: { prop: "arg nested prop", @@ -740,8 +756,8 @@ export const runObjectTypesTest = async ( }, }); - expect(method2b.error).toBeFalsy(); - expect(method2b.data).toEqual(null); + if (!method2b.ok) fail(method2b.error); + expect(method2b.value).toEqual(null); const method3 = await client.invoke({ uri, @@ -756,9 +772,9 @@ export const runObjectTypesTest = async ( }, }); - expect(method3.error).toBeFalsy(); - expect(method3.data).toBeTruthy(); - expect(method3.data).toEqual([ + if (!method3.ok) fail(method3.error); + expect(method3.value).toBeTruthy(); + expect(method3.value).toEqual([ null, { prop: "arg prop", @@ -778,9 +794,9 @@ export const runObjectTypesTest = async ( }, }); - expect(method5.error).toBeFalsy(); - expect(method5.data).toBeTruthy(); - expect(method5.data).toEqual({ + if (!method5.ok) fail(method5.error); + expect(method5.value).toBeTruthy(); + expect(method5.value).toEqual({ prop: "1234", nested: { prop: "nested prop", @@ -809,8 +825,8 @@ export const runMapTypeTest = async (client: PolywrapClient, uri: string) => { map: mapClass, }, }); - expect(returnMapResponse1.error).toBeUndefined(); - expect(returnMapResponse1.data).toEqual(mapClass); + if (!returnMapResponse1.ok) fail(returnMapResponse1.error); + expect(returnMapResponse1.value).toEqual(mapClass); const returnMapResponse2 = await client.invoke>({ uri, @@ -819,8 +835,8 @@ export const runMapTypeTest = async (client: PolywrapClient, uri: string) => { map: mapRecord, }, }); - expect(returnMapResponse2.error).toBeUndefined(); - expect(returnMapResponse2.data).toEqual(mapClass); + if (!returnMapResponse2.ok) fail(returnMapResponse2.error); + expect(returnMapResponse2.value).toEqual(mapClass); const getKeyResponse1 = await client.invoke({ uri, @@ -833,8 +849,8 @@ export const runMapTypeTest = async (client: PolywrapClient, uri: string) => { key: "Hello", }, }); - expect(getKeyResponse1.error).toBeUndefined(); - expect(getKeyResponse1.data).toEqual(mapClass.get("Hello")); + if (!getKeyResponse1.ok) fail(getKeyResponse1.error); + expect(getKeyResponse1.value).toEqual(mapClass.get("Hello")); const getKeyResponse2 = await client.invoke({ uri, @@ -847,8 +863,8 @@ export const runMapTypeTest = async (client: PolywrapClient, uri: string) => { key: "Heyo", }, }); - expect(getKeyResponse2.error).toBeUndefined(); - expect(getKeyResponse2.data).toEqual(mapRecord.Heyo); + if (!getKeyResponse2.ok) fail(getKeyResponse2.error); + expect(getKeyResponse2.value).toEqual(mapRecord.Heyo); const returnCustomMap = await client.invoke<{ map: Map; @@ -863,8 +879,8 @@ export const runMapTypeTest = async (client: PolywrapClient, uri: string) => { }, }, }); - expect(returnCustomMap.error).toBeUndefined(); - expect(returnCustomMap.data).toEqual({ + if (!returnCustomMap.ok) fail(returnCustomMap.error); + expect(returnCustomMap.value).toEqual({ map: mapClass, nestedMap: nestedMapClass, }); @@ -878,8 +894,8 @@ export const runMapTypeTest = async (client: PolywrapClient, uri: string) => { }, } ); - expect(returnNestedMap.error).toBeUndefined(); - expect(returnNestedMap.data).toEqual(nestedMapClass); + if (!returnNestedMap.ok) fail(returnNestedMap.error); + expect(returnNestedMap.value).toEqual(nestedMapClass); }; export const runSimpleStorageTest = async ( @@ -896,15 +912,11 @@ export const runSimpleStorageTest = async ( }, }); - expect(deploy.error).toBeFalsy(); - expect(deploy.data).toBeTruthy(); - expect(deploy.data?.indexOf("0x")).toBeGreaterThan(-1); - - if (!deploy.data) { - return; - } + if (!deploy.ok) fail(deploy.error); + expect(deploy.value).toBeTruthy(); + expect(deploy.value.indexOf("0x")).toBeGreaterThan(-1); - const address = deploy.data; + const address = deploy.value; const set = await client.invoke({ uri: wrapperUri, method: "setData", @@ -917,9 +929,9 @@ export const runSimpleStorageTest = async ( }, }); - expect(set.error).toBeFalsy(); - expect(set.data).toBeTruthy(); - expect(set.data?.indexOf("0x")).toBeGreaterThan(-1); + if (!set.ok) fail(set.error); + expect(set.value).toBeTruthy(); + expect(set.value?.indexOf("0x")).toBeGreaterThan(-1); const getDataResult = await client.invoke({ uri: wrapperUri, @@ -932,8 +944,8 @@ export const runSimpleStorageTest = async ( }, }); - expect(getDataResult.error).toBeFalsy(); - expect(getDataResult.data).toEqual(55); + if (!getDataResult.ok) fail(getDataResult.error); + expect(getDataResult.value).toEqual(55); }; export const runSimpleEnvTest = async ( @@ -947,13 +959,13 @@ export const runSimpleEnvTest = async ( arg: "string", }, }); - expect(getEnvResult.error).toBeFalsy(); - expect(getEnvResult.data).toEqual({ + if (!getEnvResult.ok) fail(getEnvResult.error); + expect(getEnvResult.value).toEqual({ str: "module string", requiredInt: 1, }); - const getEnvNotSetResult = await client.invoke({ + let getEnvNotSetResult = await client.invoke({ uri: wrapperUri, method: "getEnv", args: { @@ -968,11 +980,11 @@ export const runSimpleEnvTest = async ( ], }, }); - expect(getEnvNotSetResult.data).toBeUndefined(); + getEnvNotSetResult = getEnvNotSetResult as ErrResult; expect(getEnvNotSetResult.error).toBeTruthy(); expect(getEnvNotSetResult.error?.message).toContain("requiredInt: Int"); - const envIncorrectResult = await client.invoke({ + let envIncorrectResult = await client.invoke({ uri: wrapperUri, method: "getEnv", args: { @@ -991,7 +1003,7 @@ export const runSimpleEnvTest = async ( }, }); - expect(envIncorrectResult.data).toBeUndefined(); + envIncorrectResult = envIncorrectResult as ErrResult; expect(envIncorrectResult.error).toBeTruthy(); expect(envIncorrectResult.error?.message).toContain( "Property must be of type 'int'. Found 'string'." @@ -1009,8 +1021,8 @@ export const runComplexEnvs = async ( arg: "string", }, }); - expect(methodRequireEnvResult.error).toBeFalsy(); - expect(methodRequireEnvResult.data).toEqual({ + if (!methodRequireEnvResult.ok) fail(methodRequireEnvResult.error); + expect(methodRequireEnvResult.value).toEqual({ str: "string", optFilledStr: "optional string", optStr: null, @@ -1034,8 +1046,8 @@ export const runComplexEnvs = async ( arg: "string", }, }); - expect(subinvokeEnvMethodResult.error).toBeFalsy(); - expect(subinvokeEnvMethodResult.data).toEqual({ + if (!subinvokeEnvMethodResult.ok) fail(subinvokeEnvMethodResult.error); + expect(subinvokeEnvMethodResult.value).toEqual({ local: { str: "string", optFilledStr: "optional string", @@ -1065,8 +1077,8 @@ export const runComplexEnvs = async ( arg: "string", }, }); - expect(methodRequireEnvModuleTimeResult.error).toBeFalsy(); - expect(methodRequireEnvModuleTimeResult.data).toEqual({ + if (!methodRequireEnvModuleTimeResult.ok) fail(methodRequireEnvModuleTimeResult.error); + expect(methodRequireEnvModuleTimeResult.value).toEqual({ str: "string", optFilledStr: "optional string", optStr: null, @@ -1108,8 +1120,8 @@ export const runComplexEnvs = async ( ], }, }); - expect(mockUpdatedEnvResult.error).toBeFalsy(); - expect(mockUpdatedEnvResult.data).toEqual({ + if (!mockUpdatedEnvResult.ok) fail(mockUpdatedEnvResult.error); + expect(mockUpdatedEnvResult.value).toEqual({ str: "another string", optFilledStr: "optional string", optStr: null, diff --git a/packages/js/client/src/__tests__/e2e/wasm-as.spec.ts b/packages/js/client/src/__tests__/e2e/wasm-as.spec.ts index 07bb69bf68..c4eed72b45 100644 --- a/packages/js/client/src/__tests__/e2e/wasm-as.spec.ts +++ b/packages/js/client/src/__tests__/e2e/wasm-as.spec.ts @@ -93,7 +93,7 @@ describe("wasm-as test cases", () => { await buildWrapper(wrapperPath); const ensUri = wrapperUri; - const query = await client.invoke({ + const result = await client.invoke({ uri: ensUri, method: "if", args: { @@ -103,9 +103,9 @@ describe("wasm-as test cases", () => { }, }); - expect(query.error).toBeFalsy(); - expect(query.data).toBeTruthy(); - expect(query.data).toMatchObject({ + if (!result.ok) fail(result.error); + expect(result.value).toBeTruthy(); + expect(result.value).toMatchObject({ else: "successfully used reserved keyword", }); }); @@ -195,7 +195,7 @@ describe("wasm-as test cases", () => { await buildWrapper(wrapperPath); - const query = await client.invoke({ + const result = await client.invoke({ uri: wrapperUri, method: "moduleMethod", args: { @@ -206,9 +206,9 @@ describe("wasm-as test cases", () => { }, }); - expect(query.error).toBeFalsy(); - expect(query.data).toBeTruthy(); - expect(query.data).toEqual({ + if (!result.ok) fail(result.error); + expect(result.value).toBeTruthy(); + expect(result.value).toEqual({ uint8: 1, str: "Test String 1", }); diff --git a/packages/js/client/src/__tests__/utils/resultTypes.ts b/packages/js/client/src/__tests__/utils/resultTypes.ts new file mode 100644 index 0000000000..17a02d06d4 --- /dev/null +++ b/packages/js/client/src/__tests__/utils/resultTypes.ts @@ -0,0 +1 @@ +export type ErrResult = { ok: false; error: E | undefined }; \ No newline at end of file diff --git a/packages/js/core/src/types/Client.ts b/packages/js/core/src/types/Client.ts index dee80eea28..a0c3122c02 100644 --- a/packages/js/core/src/types/Client.ts +++ b/packages/js/core/src/types/Client.ts @@ -13,6 +13,7 @@ import { IUriResolver } from "../uri-resolution"; import { UriResolverHandler } from "./UriResolver"; import { WrapManifest } from "@polywrap/wrap-manifest-types-js"; +import { Result } from "@polywrap/result"; export interface ClientConfig { redirects: UriRedirect[]; @@ -81,15 +82,15 @@ export interface Client getManifest( uri: TUri, options: GetManifestOptions - ): Promise; + ): Promise>; getFile( uri: TUri, options: GetFileOptions - ): Promise; + ): Promise>; getImplementations( uri: TUri, options: GetImplementationsOptions - ): TUri[]; + ): Result; } diff --git a/packages/js/core/src/types/Query.ts b/packages/js/core/src/types/Query.ts index 3bde10e480..0cf4cfa9cb 100644 --- a/packages/js/core/src/types/Query.ts +++ b/packages/js/core/src/types/Query.ts @@ -3,7 +3,6 @@ import { Uri, InvokeOptions, ClientConfig } from "./"; import { Tracer } from "@polywrap/tracing-js"; import { DocumentNode } from "graphql"; import gql from "graphql-tag"; -import { Result } from "@polywrap/result"; /** GraphQL QueryDocument */ export type QueryDocument = DocumentNode; @@ -47,6 +46,31 @@ export interface QueryOptions< contextId?: string; } +/** + * The result of an Wrapper query, which is the aggregate + * of one or more [[InvokeResult | invocation results]]. + * + * @template TData Type of the query result data. + */ +export interface QueryResult< + TData extends Record = Record +> { + /** + * Query result data. The type of this value is a named map, + * where the key is the method's name, and value is the [[InvokeResult]]'s data. + * This is done to allow for parallel invocations within a + * single query document. In case of method name collisions, + * a postfix of `_0` will be applied, where 0 will be incremented for + * each occurrence. If undefined, it means something went wrong. + * Errors should be populated with information as to what happened. + * Null is used to represent an intentionally null result. + */ + data?: TData; + + /** Errors encountered during the query. */ + errors?: Error[]; +} + export interface QueryInvocations { [methodOrAlias: string]: InvokeOptions; } @@ -59,5 +83,5 @@ export interface QueryHandler { TUri extends Uri | string = string >( options: QueryOptions - ): Promise>; + ): Promise>; } diff --git a/packages/js/test-env/src/index.ts b/packages/js/test-env/src/index.ts index b4ba6325ae..d16d5f4dd3 100644 --- a/packages/js/test-env/src/index.ts +++ b/packages/js/test-env/src/index.ts @@ -280,7 +280,7 @@ export async function buildAndDeployWrapper({ ], }); - const { data: signerAddress } = await client.invoke({ + const signerAddress = await client.invoke({ method: "getSignerAddress", uri: ethereumPluginUri, args: { @@ -290,16 +290,16 @@ export async function buildAndDeployWrapper({ }, }); - if (!signerAddress) { + if (!signerAddress.ok) { throw new Error("Could not get signer"); } - const { data: registerData, error } = await client.invoke<{ hash: string }>({ + const registerData = await client.invoke<{ hash: string }>({ method: "registerDomainAndSubdomainsRecursively", uri: ensWrapperUri, args: { domain: wrapperEns, - owner: signerAddress, + owner: signerAddress.value, resolverAddress: ensAddresses.resolverAddress, ttl: "0", registrarAddress: ensAddresses.registrarAddress, @@ -310,10 +310,10 @@ export async function buildAndDeployWrapper({ }, }); - if (!registerData) { + if (!registerData.ok) { throw new Error( `Could not register domain '${wrapperEns}'` + - (error ? `\nError: ${error.message}` : "") + (registerData.error ? `\nError: ${registerData.error.message}` : "") ); } @@ -321,7 +321,7 @@ export async function buildAndDeployWrapper({ method: "awaitTransaction", uri: ethereumPluginUri, args: { - txHash: registerData.hash, + txHash: registerData.value.hash, confirmations: 1, timeout: 15000, connection: { diff --git a/packages/js/wasm/src/imports.ts b/packages/js/wasm/src/imports.ts index 903adbbf18..0ec6338fe2 100644 --- a/packages/js/wasm/src/imports.ts +++ b/packages/js/wasm/src/imports.ts @@ -176,8 +176,13 @@ export const createImports = (config: { __wrap_getImplementations: (uriPtr: u32, uriLen: u32): boolean => { const uri = readString(memory.buffer, uriPtr, uriLen); const result = client.getImplementations(uri, {}); - state.getImplementationsResult = msgpackEncode(result); - return result.length > 0; + if (!result.ok) { + abort(result.error?.message as string); + return false; + } + const implementations = result.value; + state.getImplementationsResult = msgpackEncode(implementations); + return implementations.length > 0; }, __wrap_getImplementations_result_len: (): u32 => { if (!state.getImplementationsResult) { From 2343be35228096f39776c862e32a1c3176b0c0bd Mon Sep 17 00:00:00 2001 From: krisbitney Date: Sat, 24 Sep 2022 20:07:55 +0500 Subject: [PATCH 05/25] Updated schema-bind with Result type --- packages/js/core/src/index.ts | 1 + .../app/templates/types-ts.mustache | 4 +- .../plugin/templates/types-ts.mustache | 8 +-- .../cases/bind/sanity/output/app-ts/types.ts | 6 +- .../bind/sanity/output/plugin-ts/types.ts | 8 +-- .../codegen/001-sanity/expected/wrap/types.ts | 58 +++++++++---------- .../002-single-module/expected/wrap/types.ts | 58 +++++++++---------- .../codegen/003-env/expected/wrap/types.ts | 2 +- .../expected/wrap/types.ts | 2 +- .../005-custom-config/expected/wrap/types.ts | 54 ++++++++--------- .../expected/wrap/types.ts | 52 ++++++++--------- 11 files changed, 127 insertions(+), 126 deletions(-) diff --git a/packages/js/core/src/index.ts b/packages/js/core/src/index.ts index a53b68cd72..7c455fb135 100644 --- a/packages/js/core/src/index.ts +++ b/packages/js/core/src/index.ts @@ -4,3 +4,4 @@ export * from "./interfaces"; export * from "./uri-resolution"; export * from "./utils"; export * from "./plugin"; +export { Result } from "@polywrap/result"; diff --git a/packages/schema/bind/src/bindings/typescript/app/templates/types-ts.mustache b/packages/schema/bind/src/bindings/typescript/app/templates/types-ts.mustache index f02416fdc8..b57c90cfb5 100644 --- a/packages/schema/bind/src/bindings/typescript/app/templates/types-ts.mustache +++ b/packages/schema/bind/src/bindings/typescript/app/templates/types-ts.mustache @@ -4,7 +4,7 @@ import * as Types from "./"; // @ts-ignore import { Client, - InvokeResult + Result } from "@polywrap/core-js"; export type UInt = number; @@ -102,7 +102,7 @@ export const {{type}} = { args: {{parent.type}}_Args_{{name}}, client: Client, uri: string = "{{parent.uri}}" - ): Promise> => { + ): Promise> => { return client.invoke<{{#return}}{{#toTypescript}}{{toGraphQLType}}{{/toTypescript}}{{/return}}>({ uri, method: "{{name}}", diff --git a/packages/schema/bind/src/bindings/typescript/plugin/templates/types-ts.mustache b/packages/schema/bind/src/bindings/typescript/plugin/templates/types-ts.mustache index 50875ebe45..6e5817f97d 100644 --- a/packages/schema/bind/src/bindings/typescript/plugin/templates/types-ts.mustache +++ b/packages/schema/bind/src/bindings/typescript/plugin/templates/types-ts.mustache @@ -7,7 +7,7 @@ import * as Types from "./"; // @ts-ignore import { Client, - InvokeResult + Result } from "@polywrap/core-js"; export type UInt = number; @@ -112,7 +112,7 @@ export const {{type}} = { {{name}}: async ( args: {{parent.type}}_Args_{{name}}, client: Client - ): Promise> => { + ): Promise> => { return client.invoke<{{#return}}{{#toTypescript}}{{toGraphQLType}}{{/toTypescript}}{{/return}}>({ uri: "{{parent.uri}}", method: "{{name}}", @@ -137,7 +137,7 @@ export class {{#detectKeyword}}{{type}}{{/detectKeyword}} { public async {{name}} ( args: {{parent.type}}_Args_{{name}}, client: Client - ): Promise> { + ): Promise> { return client.invoke<{{#return}}{{#toTypescript}}{{toGraphQLType}}{{/toTypescript}}{{/return}}>({ uri: this.uri, method: "{{name}}", @@ -162,7 +162,7 @@ export class {{#detectKeyword}}{{namespace}}{{/detectKeyword}} { {{#capabilities}} {{#getImplementations}} {{#enabled}} - public static getImplementations(client: Client): string[] { + public static getImplementations(client: Client): Result { return client.getImplementations(this.uri, {}); } {{/enabled}} diff --git a/packages/test-cases/cases/bind/sanity/output/app-ts/types.ts b/packages/test-cases/cases/bind/sanity/output/app-ts/types.ts index 7e05acf86d..bc57effe7a 100644 --- a/packages/test-cases/cases/bind/sanity/output/app-ts/types.ts +++ b/packages/test-cases/cases/bind/sanity/output/app-ts/types.ts @@ -4,7 +4,7 @@ import * as Types from "./"; // @ts-ignore import { Client, - InvokeResult + Result } from "@polywrap/core-js"; export type UInt = number; @@ -170,7 +170,7 @@ export const TestImport_Module = { args: TestImport_Module_Args_importedMethod, client: Client, uri: string = "testimport.uri.eth" - ): Promise> => { + ): Promise> => { return client.invoke({ uri, method: "importedMethod", @@ -182,7 +182,7 @@ export const TestImport_Module = { args: TestImport_Module_Args_anotherMethod, client: Client, uri: string = "testimport.uri.eth" - ): Promise> => { + ): Promise> => { return client.invoke({ uri, method: "anotherMethod", diff --git a/packages/test-cases/cases/bind/sanity/output/plugin-ts/types.ts b/packages/test-cases/cases/bind/sanity/output/plugin-ts/types.ts index 9b0cddff40..15ce85dae1 100644 --- a/packages/test-cases/cases/bind/sanity/output/plugin-ts/types.ts +++ b/packages/test-cases/cases/bind/sanity/output/plugin-ts/types.ts @@ -7,7 +7,7 @@ import * as Types from "./"; // @ts-ignore import { Client, - InvokeResult + Result } from "@polywrap/core-js"; export type UInt = number; @@ -187,7 +187,7 @@ export class TestImport_Module { public async importedMethod ( args: TestImport_Module_Args_importedMethod, client: Client - ): Promise> { + ): Promise> { return client.invoke({ uri: this.uri, method: "importedMethod", @@ -198,7 +198,7 @@ export class TestImport_Module { public async anotherMethod ( args: TestImport_Module_Args_anotherMethod, client: Client - ): Promise> { + ): Promise> { return client.invoke({ uri: this.uri, method: "anotherMethod", @@ -212,7 +212,7 @@ export class TestImport_Module { export class TestImport { static uri: string = "testimport.uri.eth"; - public static getImplementations(client: Client): string[] { + public static getImplementations(client: Client): Result { return client.getImplementations(this.uri, {}); } } diff --git a/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/wrap/types.ts index 3172a4e4b0..6c3d27e56c 100644 --- a/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/wrap/types.ts +++ b/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/wrap/types.ts @@ -7,7 +7,7 @@ import * as Types from "./"; // @ts-ignore import { Client, - InvokeResult + Result } from "@polywrap/core-js"; export type UInt = number; @@ -347,7 +347,7 @@ export const Ethereum_Module = { callContractView: async ( args: Ethereum_Module_Args_callContractView, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractView", @@ -358,7 +358,7 @@ export const Ethereum_Module = { callContractStatic: async ( args: Ethereum_Module_Args_callContractStatic, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractStatic", @@ -369,7 +369,7 @@ export const Ethereum_Module = { getBalance: async ( args: Ethereum_Module_Args_getBalance, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getBalance", @@ -380,7 +380,7 @@ export const Ethereum_Module = { encodeParams: async ( args: Ethereum_Module_Args_encodeParams, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "encodeParams", @@ -391,7 +391,7 @@ export const Ethereum_Module = { encodeFunction: async ( args: Ethereum_Module_Args_encodeFunction, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "encodeFunction", @@ -402,7 +402,7 @@ export const Ethereum_Module = { solidityPack: async ( args: Ethereum_Module_Args_solidityPack, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "solidityPack", @@ -413,7 +413,7 @@ export const Ethereum_Module = { solidityKeccak256: async ( args: Ethereum_Module_Args_solidityKeccak256, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "solidityKeccak256", @@ -424,7 +424,7 @@ export const Ethereum_Module = { soliditySha256: async ( args: Ethereum_Module_Args_soliditySha256, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "soliditySha256", @@ -435,7 +435,7 @@ export const Ethereum_Module = { getSignerAddress: async ( args: Ethereum_Module_Args_getSignerAddress, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getSignerAddress", @@ -446,7 +446,7 @@ export const Ethereum_Module = { getSignerBalance: async ( args: Ethereum_Module_Args_getSignerBalance, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getSignerBalance", @@ -457,7 +457,7 @@ export const Ethereum_Module = { getSignerTransactionCount: async ( args: Ethereum_Module_Args_getSignerTransactionCount, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getSignerTransactionCount", @@ -468,7 +468,7 @@ export const Ethereum_Module = { getGasPrice: async ( args: Ethereum_Module_Args_getGasPrice, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getGasPrice", @@ -479,7 +479,7 @@ export const Ethereum_Module = { estimateTransactionGas: async ( args: Ethereum_Module_Args_estimateTransactionGas, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "estimateTransactionGas", @@ -490,7 +490,7 @@ export const Ethereum_Module = { estimateContractCallGas: async ( args: Ethereum_Module_Args_estimateContractCallGas, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "estimateContractCallGas", @@ -501,7 +501,7 @@ export const Ethereum_Module = { checkAddress: async ( args: Ethereum_Module_Args_checkAddress, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "checkAddress", @@ -512,7 +512,7 @@ export const Ethereum_Module = { toWei: async ( args: Ethereum_Module_Args_toWei, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "toWei", @@ -523,7 +523,7 @@ export const Ethereum_Module = { toEth: async ( args: Ethereum_Module_Args_toEth, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "toEth", @@ -534,7 +534,7 @@ export const Ethereum_Module = { awaitTransaction: async ( args: Ethereum_Module_Args_awaitTransaction, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "awaitTransaction", @@ -545,7 +545,7 @@ export const Ethereum_Module = { waitForEvent: async ( args: Ethereum_Module_Args_waitForEvent, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "waitForEvent", @@ -556,7 +556,7 @@ export const Ethereum_Module = { getNetwork: async ( args: Ethereum_Module_Args_getNetwork, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getNetwork", @@ -567,7 +567,7 @@ export const Ethereum_Module = { requestAccounts: async ( args: Ethereum_Module_Args_requestAccounts, client: Client - ): Promise>> => { + ): Promise, Error>> => { return client.invoke>({ uri: "ens/ethereum.polywrap.eth", method: "requestAccounts", @@ -578,7 +578,7 @@ export const Ethereum_Module = { callContractMethod: async ( args: Ethereum_Module_Args_callContractMethod, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractMethod", @@ -589,7 +589,7 @@ export const Ethereum_Module = { callContractMethodAndWait: async ( args: Ethereum_Module_Args_callContractMethodAndWait, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractMethodAndWait", @@ -600,7 +600,7 @@ export const Ethereum_Module = { sendTransaction: async ( args: Ethereum_Module_Args_sendTransaction, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "sendTransaction", @@ -611,7 +611,7 @@ export const Ethereum_Module = { sendTransactionAndWait: async ( args: Ethereum_Module_Args_sendTransactionAndWait, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "sendTransactionAndWait", @@ -622,7 +622,7 @@ export const Ethereum_Module = { deployContract: async ( args: Ethereum_Module_Args_deployContract, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "deployContract", @@ -633,7 +633,7 @@ export const Ethereum_Module = { signMessage: async ( args: Ethereum_Module_Args_signMessage, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "signMessage", @@ -644,7 +644,7 @@ export const Ethereum_Module = { sendRPC: async ( args: Ethereum_Module_Args_sendRPC, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "sendRPC", diff --git a/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/types.ts index 3172a4e4b0..de183960bc 100644 --- a/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/types.ts +++ b/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/types.ts @@ -7,7 +7,7 @@ import * as Types from "./"; // @ts-ignore import { Client, - InvokeResult + Result } from "@polywrap/core-js"; export type UInt = number; @@ -347,7 +347,7 @@ export const Ethereum_Module = { callContractView: async ( args: Ethereum_Module_Args_callContractView, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractView", @@ -358,7 +358,7 @@ export const Ethereum_Module = { callContractStatic: async ( args: Ethereum_Module_Args_callContractStatic, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractStatic", @@ -369,7 +369,7 @@ export const Ethereum_Module = { getBalance: async ( args: Ethereum_Module_Args_getBalance, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getBalance", @@ -380,7 +380,7 @@ export const Ethereum_Module = { encodeParams: async ( args: Ethereum_Module_Args_encodeParams, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "encodeParams", @@ -391,7 +391,7 @@ export const Ethereum_Module = { encodeFunction: async ( args: Ethereum_Module_Args_encodeFunction, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "encodeFunction", @@ -402,7 +402,7 @@ export const Ethereum_Module = { solidityPack: async ( args: Ethereum_Module_Args_solidityPack, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "solidityPack", @@ -413,7 +413,7 @@ export const Ethereum_Module = { solidityKeccak256: async ( args: Ethereum_Module_Args_solidityKeccak256, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "solidityKeccak256", @@ -424,7 +424,7 @@ export const Ethereum_Module = { soliditySha256: async ( args: Ethereum_Module_Args_soliditySha256, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "soliditySha256", @@ -435,7 +435,7 @@ export const Ethereum_Module = { getSignerAddress: async ( args: Ethereum_Module_Args_getSignerAddress, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getSignerAddress", @@ -446,7 +446,7 @@ export const Ethereum_Module = { getSignerBalance: async ( args: Ethereum_Module_Args_getSignerBalance, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getSignerBalance", @@ -457,7 +457,7 @@ export const Ethereum_Module = { getSignerTransactionCount: async ( args: Ethereum_Module_Args_getSignerTransactionCount, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getSignerTransactionCount", @@ -468,7 +468,7 @@ export const Ethereum_Module = { getGasPrice: async ( args: Ethereum_Module_Args_getGasPrice, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getGasPrice", @@ -479,7 +479,7 @@ export const Ethereum_Module = { estimateTransactionGas: async ( args: Ethereum_Module_Args_estimateTransactionGas, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "estimateTransactionGas", @@ -490,7 +490,7 @@ export const Ethereum_Module = { estimateContractCallGas: async ( args: Ethereum_Module_Args_estimateContractCallGas, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "estimateContractCallGas", @@ -501,7 +501,7 @@ export const Ethereum_Module = { checkAddress: async ( args: Ethereum_Module_Args_checkAddress, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "checkAddress", @@ -512,7 +512,7 @@ export const Ethereum_Module = { toWei: async ( args: Ethereum_Module_Args_toWei, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "toWei", @@ -523,7 +523,7 @@ export const Ethereum_Module = { toEth: async ( args: Ethereum_Module_Args_toEth, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "toEth", @@ -534,7 +534,7 @@ export const Ethereum_Module = { awaitTransaction: async ( args: Ethereum_Module_Args_awaitTransaction, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "awaitTransaction", @@ -545,7 +545,7 @@ export const Ethereum_Module = { waitForEvent: async ( args: Ethereum_Module_Args_waitForEvent, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "waitForEvent", @@ -556,7 +556,7 @@ export const Ethereum_Module = { getNetwork: async ( args: Ethereum_Module_Args_getNetwork, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getNetwork", @@ -567,7 +567,7 @@ export const Ethereum_Module = { requestAccounts: async ( args: Ethereum_Module_Args_requestAccounts, client: Client - ): Promise>> => { + ): Promise, Error>> => { return client.invoke>({ uri: "ens/ethereum.polywrap.eth", method: "requestAccounts", @@ -578,7 +578,7 @@ export const Ethereum_Module = { callContractMethod: async ( args: Ethereum_Module_Args_callContractMethod, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractMethod", @@ -589,7 +589,7 @@ export const Ethereum_Module = { callContractMethodAndWait: async ( args: Ethereum_Module_Args_callContractMethodAndWait, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractMethodAndWait", @@ -600,7 +600,7 @@ export const Ethereum_Module = { sendTransaction: async ( args: Ethereum_Module_Args_sendTransaction, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "sendTransaction", @@ -611,7 +611,7 @@ export const Ethereum_Module = { sendTransactionAndWait: async ( args: Ethereum_Module_Args_sendTransactionAndWait, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "sendTransactionAndWait", @@ -622,7 +622,7 @@ export const Ethereum_Module = { deployContract: async ( args: Ethereum_Module_Args_deployContract, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "deployContract", @@ -633,7 +633,7 @@ export const Ethereum_Module = { signMessage: async ( args: Ethereum_Module_Args_signMessage, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "signMessage", @@ -644,7 +644,7 @@ export const Ethereum_Module = { sendRPC: async ( args: Ethereum_Module_Args_sendRPC, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "sendRPC", diff --git a/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/wrap/types.ts index 6dbf11884a..3d6d6f6713 100644 --- a/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/wrap/types.ts +++ b/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/wrap/types.ts @@ -7,7 +7,7 @@ import * as Types from "./"; // @ts-ignore import { Client, - InvokeResult + Result } from "@polywrap/core-js"; export type UInt = number; diff --git a/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/wrap/types.ts index fee545ff08..8701cb2b8d 100644 --- a/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/wrap/types.ts +++ b/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/wrap/types.ts @@ -7,7 +7,7 @@ import * as Types from "./"; // @ts-ignore import { Client, - InvokeResult + Result } from "@polywrap/core-js"; export type UInt = number; diff --git a/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/types.ts index 3172a4e4b0..faaf617500 100644 --- a/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/types.ts +++ b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/types.ts @@ -7,7 +7,7 @@ import * as Types from "./"; // @ts-ignore import { Client, - InvokeResult + Result } from "@polywrap/core-js"; export type UInt = number; @@ -347,7 +347,7 @@ export const Ethereum_Module = { callContractView: async ( args: Ethereum_Module_Args_callContractView, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractView", @@ -358,7 +358,7 @@ export const Ethereum_Module = { callContractStatic: async ( args: Ethereum_Module_Args_callContractStatic, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractStatic", @@ -369,7 +369,7 @@ export const Ethereum_Module = { getBalance: async ( args: Ethereum_Module_Args_getBalance, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getBalance", @@ -380,7 +380,7 @@ export const Ethereum_Module = { encodeParams: async ( args: Ethereum_Module_Args_encodeParams, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "encodeParams", @@ -391,7 +391,7 @@ export const Ethereum_Module = { encodeFunction: async ( args: Ethereum_Module_Args_encodeFunction, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "encodeFunction", @@ -402,7 +402,7 @@ export const Ethereum_Module = { solidityPack: async ( args: Ethereum_Module_Args_solidityPack, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "solidityPack", @@ -413,7 +413,7 @@ export const Ethereum_Module = { solidityKeccak256: async ( args: Ethereum_Module_Args_solidityKeccak256, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "solidityKeccak256", @@ -424,7 +424,7 @@ export const Ethereum_Module = { soliditySha256: async ( args: Ethereum_Module_Args_soliditySha256, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "soliditySha256", @@ -435,7 +435,7 @@ export const Ethereum_Module = { getSignerAddress: async ( args: Ethereum_Module_Args_getSignerAddress, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getSignerAddress", @@ -446,7 +446,7 @@ export const Ethereum_Module = { getSignerBalance: async ( args: Ethereum_Module_Args_getSignerBalance, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getSignerBalance", @@ -457,7 +457,7 @@ export const Ethereum_Module = { getSignerTransactionCount: async ( args: Ethereum_Module_Args_getSignerTransactionCount, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getSignerTransactionCount", @@ -468,7 +468,7 @@ export const Ethereum_Module = { getGasPrice: async ( args: Ethereum_Module_Args_getGasPrice, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getGasPrice", @@ -479,7 +479,7 @@ export const Ethereum_Module = { estimateTransactionGas: async ( args: Ethereum_Module_Args_estimateTransactionGas, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "estimateTransactionGas", @@ -490,7 +490,7 @@ export const Ethereum_Module = { estimateContractCallGas: async ( args: Ethereum_Module_Args_estimateContractCallGas, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "estimateContractCallGas", @@ -501,7 +501,7 @@ export const Ethereum_Module = { checkAddress: async ( args: Ethereum_Module_Args_checkAddress, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "checkAddress", @@ -512,7 +512,7 @@ export const Ethereum_Module = { toWei: async ( args: Ethereum_Module_Args_toWei, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "toWei", @@ -523,7 +523,7 @@ export const Ethereum_Module = { toEth: async ( args: Ethereum_Module_Args_toEth, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "toEth", @@ -534,7 +534,7 @@ export const Ethereum_Module = { awaitTransaction: async ( args: Ethereum_Module_Args_awaitTransaction, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "awaitTransaction", @@ -545,7 +545,7 @@ export const Ethereum_Module = { waitForEvent: async ( args: Ethereum_Module_Args_waitForEvent, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "waitForEvent", @@ -556,7 +556,7 @@ export const Ethereum_Module = { getNetwork: async ( args: Ethereum_Module_Args_getNetwork, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getNetwork", @@ -578,7 +578,7 @@ export const Ethereum_Module = { callContractMethod: async ( args: Ethereum_Module_Args_callContractMethod, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractMethod", @@ -589,7 +589,7 @@ export const Ethereum_Module = { callContractMethodAndWait: async ( args: Ethereum_Module_Args_callContractMethodAndWait, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractMethodAndWait", @@ -600,7 +600,7 @@ export const Ethereum_Module = { sendTransaction: async ( args: Ethereum_Module_Args_sendTransaction, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "sendTransaction", @@ -611,7 +611,7 @@ export const Ethereum_Module = { sendTransactionAndWait: async ( args: Ethereum_Module_Args_sendTransactionAndWait, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "sendTransactionAndWait", @@ -622,7 +622,7 @@ export const Ethereum_Module = { deployContract: async ( args: Ethereum_Module_Args_deployContract, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "deployContract", @@ -633,7 +633,7 @@ export const Ethereum_Module = { signMessage: async ( args: Ethereum_Module_Args_signMessage, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "signMessage", diff --git a/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/types.ts index 3172a4e4b0..4286dc22f0 100644 --- a/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/types.ts +++ b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/types.ts @@ -347,7 +347,7 @@ export const Ethereum_Module = { callContractView: async ( args: Ethereum_Module_Args_callContractView, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractView", @@ -358,7 +358,7 @@ export const Ethereum_Module = { callContractStatic: async ( args: Ethereum_Module_Args_callContractStatic, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractStatic", @@ -369,7 +369,7 @@ export const Ethereum_Module = { getBalance: async ( args: Ethereum_Module_Args_getBalance, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getBalance", @@ -380,7 +380,7 @@ export const Ethereum_Module = { encodeParams: async ( args: Ethereum_Module_Args_encodeParams, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "encodeParams", @@ -391,7 +391,7 @@ export const Ethereum_Module = { encodeFunction: async ( args: Ethereum_Module_Args_encodeFunction, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "encodeFunction", @@ -402,7 +402,7 @@ export const Ethereum_Module = { solidityPack: async ( args: Ethereum_Module_Args_solidityPack, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "solidityPack", @@ -413,7 +413,7 @@ export const Ethereum_Module = { solidityKeccak256: async ( args: Ethereum_Module_Args_solidityKeccak256, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "solidityKeccak256", @@ -424,7 +424,7 @@ export const Ethereum_Module = { soliditySha256: async ( args: Ethereum_Module_Args_soliditySha256, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "soliditySha256", @@ -435,7 +435,7 @@ export const Ethereum_Module = { getSignerAddress: async ( args: Ethereum_Module_Args_getSignerAddress, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getSignerAddress", @@ -446,7 +446,7 @@ export const Ethereum_Module = { getSignerBalance: async ( args: Ethereum_Module_Args_getSignerBalance, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getSignerBalance", @@ -457,7 +457,7 @@ export const Ethereum_Module = { getSignerTransactionCount: async ( args: Ethereum_Module_Args_getSignerTransactionCount, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getSignerTransactionCount", @@ -468,7 +468,7 @@ export const Ethereum_Module = { getGasPrice: async ( args: Ethereum_Module_Args_getGasPrice, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getGasPrice", @@ -479,7 +479,7 @@ export const Ethereum_Module = { estimateTransactionGas: async ( args: Ethereum_Module_Args_estimateTransactionGas, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "estimateTransactionGas", @@ -490,7 +490,7 @@ export const Ethereum_Module = { estimateContractCallGas: async ( args: Ethereum_Module_Args_estimateContractCallGas, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "estimateContractCallGas", @@ -501,7 +501,7 @@ export const Ethereum_Module = { checkAddress: async ( args: Ethereum_Module_Args_checkAddress, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "checkAddress", @@ -512,7 +512,7 @@ export const Ethereum_Module = { toWei: async ( args: Ethereum_Module_Args_toWei, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "toWei", @@ -523,7 +523,7 @@ export const Ethereum_Module = { toEth: async ( args: Ethereum_Module_Args_toEth, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "toEth", @@ -534,7 +534,7 @@ export const Ethereum_Module = { awaitTransaction: async ( args: Ethereum_Module_Args_awaitTransaction, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "awaitTransaction", @@ -545,7 +545,7 @@ export const Ethereum_Module = { waitForEvent: async ( args: Ethereum_Module_Args_waitForEvent, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "waitForEvent", @@ -556,7 +556,7 @@ export const Ethereum_Module = { getNetwork: async ( args: Ethereum_Module_Args_getNetwork, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getNetwork", @@ -578,7 +578,7 @@ export const Ethereum_Module = { callContractMethod: async ( args: Ethereum_Module_Args_callContractMethod, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractMethod", @@ -589,7 +589,7 @@ export const Ethereum_Module = { callContractMethodAndWait: async ( args: Ethereum_Module_Args_callContractMethodAndWait, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractMethodAndWait", @@ -600,7 +600,7 @@ export const Ethereum_Module = { sendTransaction: async ( args: Ethereum_Module_Args_sendTransaction, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "sendTransaction", @@ -611,7 +611,7 @@ export const Ethereum_Module = { sendTransactionAndWait: async ( args: Ethereum_Module_Args_sendTransactionAndWait, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "sendTransactionAndWait", @@ -622,7 +622,7 @@ export const Ethereum_Module = { deployContract: async ( args: Ethereum_Module_Args_deployContract, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "deployContract", @@ -633,7 +633,7 @@ export const Ethereum_Module = { signMessage: async ( args: Ethereum_Module_Args_signMessage, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "signMessage", From ffac94531c148c696de818e68fd1292aa2ebebf3 Mon Sep 17 00:00:00 2001 From: krisbitney Date: Sat, 24 Sep 2022 20:58:55 +0500 Subject: [PATCH 06/25] Updated cli with Result type --- packages/cli/src/lib/SchemaComposer.ts | 11 +++-- .../ens-recursive-name-register/index.ts | 42 +++++++++---------- .../lib/defaults/deploy-modules/ens/index.ts | 16 +++---- packages/cli/src/lib/workflow/JobRunner.ts | 6 +-- packages/cli/src/lib/workflow/types.ts | 6 ++- .../js/plugins/ipfs/src/__tests__/e2e.spec.ts | 6 +-- .../ipfs-resolver/src/__tests__/e2e.spec.ts | 6 +-- 7 files changed, 46 insertions(+), 47 deletions(-) diff --git a/packages/cli/src/lib/SchemaComposer.ts b/packages/cli/src/lib/SchemaComposer.ts index c0742f0f2b..269536ac4f 100644 --- a/packages/cli/src/lib/SchemaComposer.ts +++ b/packages/cli/src/lib/SchemaComposer.ts @@ -127,13 +127,12 @@ export class SchemaComposer { } } - try { - const manifest = await this._client.getManifest(new Uri(uri)); - return manifest.abi; - } catch (e) { - gluegun.print.error(e); - throw e; + const manifest = await this._client.getManifest(new Uri(uri)); + if (!manifest.ok) { + gluegun.print.error(manifest.error); + throw manifest.error; } + return manifest.value.abi; } private async _loadGraphqlAbi( diff --git a/packages/cli/src/lib/defaults/deploy-modules/ens-recursive-name-register/index.ts b/packages/cli/src/lib/defaults/deploy-modules/ens-recursive-name-register/index.ts index 83ae04f700..bc34d6dd1a 100644 --- a/packages/cli/src/lib/defaults/deploy-modules/ens-recursive-name-register/index.ts +++ b/packages/cli/src/lib/defaults/deploy-modules/ens-recursive-name-register/index.ts @@ -1,6 +1,6 @@ /* eslint-disable @typescript-eslint/no-require-imports */ /* eslint-disable @typescript-eslint/no-var-requires */ -import { Deployer } from "../../../deploy/deployer"; +import { Deployer } from "../../../deploy"; import { Wallet } from "@ethersproject/wallet"; import { JsonRpcProvider } from "@ethersproject/providers"; @@ -76,7 +76,7 @@ class ENSRecursiveNameRegisterPublisher implements Deployer { ], }); - const { data: signerAddress } = await client.invoke({ + const signerAddress = await client.invoke({ method: "getSignerAddress", uri: ethereumPluginUri, args: { @@ -86,32 +86,30 @@ class ENSRecursiveNameRegisterPublisher implements Deployer { }, }); - if (!signerAddress) { + if (!signerAddress.ok) { throw new Error("Could not get signer"); } - const { data: registerData, error } = await client.invoke<{ hash: string }>( - { - method: "registerDomainAndSubdomainsRecursively", - uri: ensWrapperUri, - args: { - domain: ensDomain, - owner: signerAddress, - resolverAddress: config.ensResolverAddress, - ttl: "0", - registrarAddress: config.ensRegistrarAddress, - registryAddress: config.ensRegistryAddress, - connection: { - networkNameOrChainId: network, - }, + const registerData = await client.invoke<{ hash: string }>({ + method: "registerDomainAndSubdomainsRecursively", + uri: ensWrapperUri, + args: { + domain: ensDomain, + owner: signerAddress.value, + resolverAddress: config.ensResolverAddress, + ttl: "0", + registrarAddress: config.ensRegistrarAddress, + registryAddress: config.ensRegistryAddress, + connection: { + networkNameOrChainId: network, }, - } - ); + }, + }); - if (!registerData) { + if (!registerData.ok) { throw new Error( `Could not register domain '${ensDomain}'` + - (error ? `\nError: ${error.message}` : "") + (registerData.error ? `\nError: ${registerData.error.message}` : "") ); } @@ -119,7 +117,7 @@ class ENSRecursiveNameRegisterPublisher implements Deployer { method: "awaitTransaction", uri: ethereumPluginUri, args: { - txHash: registerData.hash, + txHash: registerData.value.hash, confirmations: 1, timeout: 15000, connection: { diff --git a/packages/cli/src/lib/defaults/deploy-modules/ens/index.ts b/packages/cli/src/lib/defaults/deploy-modules/ens/index.ts index 6710597bd6..8d4453e6e2 100644 --- a/packages/cli/src/lib/defaults/deploy-modules/ens/index.ts +++ b/packages/cli/src/lib/defaults/deploy-modules/ens/index.ts @@ -1,6 +1,6 @@ /* eslint-disable @typescript-eslint/no-require-imports */ /* eslint-disable @typescript-eslint/no-var-requires */ -import { Deployer } from "../../../deploy/deployer"; +import { Deployer } from "../../../deploy"; import { Wallet } from "@ethersproject/wallet"; import { JsonRpcProvider } from "@ethersproject/providers"; @@ -77,7 +77,7 @@ class ENSPublisher implements Deployer { ], }); - const { data: resolver } = await client.invoke({ + const resolver = await client.invoke({ method: "getResolver", uri: ensWrapperUri, args: { @@ -89,30 +89,30 @@ class ENSPublisher implements Deployer { }, }); - if (!resolver) { + if (!resolver.ok) { throw new Error(`Could not get resolver for '${config.domainName}'`); } - if (resolver === "0x0000000000000000000000000000000000000000") { + if (resolver.value === "0x0000000000000000000000000000000000000000") { throw new Error(`Resolver not set for '${config.domainName}'`); } const hash = "0x" + contentHash.fromIpfs(cid); - const { data: setContenthashData } = await client.invoke<{ hash: string }>({ + const setContenthashData = await client.invoke<{ hash: string }>({ method: "setContentHash", uri: ensWrapperUri, args: { domain: config.domainName, cid: hash, - resolverAddress: resolver, + resolverAddress: resolver.value, connection: { networkNameOrChainId: network, }, }, }); - if (!setContenthashData) { + if (!setContenthashData.ok) { throw new Error(`Could not set contentHash for '${config.domainName}'`); } @@ -120,7 +120,7 @@ class ENSPublisher implements Deployer { method: "awaitTransaction", uri: ethereumPluginUri, args: { - txHash: setContenthashData.hash, + txHash: setContenthashData.value.hash, confirmations: 1, timeout: 15000, connection: { diff --git a/packages/cli/src/lib/workflow/JobRunner.ts b/packages/cli/src/lib/workflow/JobRunner.ts index 0540403dbe..ea358fc29d 100644 --- a/packages/cli/src/lib/workflow/JobRunner.ts +++ b/packages/cli/src/lib/workflow/JobRunner.ts @@ -183,10 +183,10 @@ export class JobRunner { args: args, }); - if (invokeResult.error) { - return { ...invokeResult, status: JobStatus.FAILED }; + if (!invokeResult.ok) { + return { error: invokeResult.error, status: JobStatus.FAILED }; } else { - return { ...invokeResult, status: JobStatus.SUCCEED }; + return { data: invokeResult.value, status: JobStatus.SUCCEED }; } } diff --git a/packages/cli/src/lib/workflow/types.ts b/packages/cli/src/lib/workflow/types.ts index 5437a7fcdd..cce561c138 100644 --- a/packages/cli/src/lib/workflow/types.ts +++ b/packages/cli/src/lib/workflow/types.ts @@ -1,4 +1,4 @@ -import { ClientConfig, InvokeResult, Uri } from "@polywrap/core-js"; +import { ClientConfig, Uri } from "@polywrap/core-js"; export interface Step { uri: string | Uri; @@ -15,7 +15,9 @@ export enum JobStatus { SKIPPED = "SKIPPED", } -export interface JobResult extends InvokeResult { +export interface JobResult { + data?: TData; + error?: Error; status: JobStatus; } diff --git a/packages/js/plugins/ipfs/src/__tests__/e2e.spec.ts b/packages/js/plugins/ipfs/src/__tests__/e2e.spec.ts index 8cbb88e4f5..5180894138 100644 --- a/packages/js/plugins/ipfs/src/__tests__/e2e.spec.ts +++ b/packages/js/plugins/ipfs/src/__tests__/e2e.spec.ts @@ -1,4 +1,4 @@ -import { InvokeResult } from "@polywrap/core-js"; +import { Result } from "@polywrap/core-js"; import { PolywrapClient } from "@polywrap/client-js"; import { initTestEnvironment, @@ -98,8 +98,8 @@ describe("IPFS Plugin", () => { it("Should timeout within a specified amount of time - env and options", async () => { const createRacePromise = ( timeout: number - ): Promise> => { - return new Promise>((resolve) => + ): Promise> => { + return new Promise>((resolve) => setTimeout(() => { resolve({ data: Uint8Array.from([1, 2, 3, 4]), diff --git a/packages/js/plugins/uri-resolvers/ipfs-resolver/src/__tests__/e2e.spec.ts b/packages/js/plugins/uri-resolvers/ipfs-resolver/src/__tests__/e2e.spec.ts index 60f9b95659..8d84538e01 100644 --- a/packages/js/plugins/uri-resolvers/ipfs-resolver/src/__tests__/e2e.spec.ts +++ b/packages/js/plugins/uri-resolvers/ipfs-resolver/src/__tests__/e2e.spec.ts @@ -11,7 +11,7 @@ import { ipfsResolverPlugin } from ".."; import { ipfsPlugin } from "@polywrap/ipfs-plugin-js"; import { IpfsClient } from "./helpers/IpfsClient"; import { createIpfsClient } from "./helpers/createIpfsClient"; -import { InvokeResult } from "@polywrap/core-js"; +import { Result } from "@polywrap/core-js"; jest.setTimeout(300000); @@ -89,8 +89,8 @@ describe("IPFS Plugin", () => { const createRacePromise = ( timeout: number - ): Promise> => { - return new Promise>((resolve) => + ): Promise> => { + return new Promise>((resolve) => setTimeout(() => { resolve({ data: Uint8Array.from([1, 2, 3, 4]), From f5517ba0d60b62e8391f91dd2f7420cad93e7128 Mon Sep 17 00:00:00 2001 From: krisbitney Date: Sun, 25 Sep 2022 08:27:19 +0500 Subject: [PATCH 07/25] monorepo building with Result type (untested) --- .../plugins/ipfs/src/utils/exec/abortable.ts | 2 +- .../uri-resolvers/ens-resolver/src/index.ts | 16 +++++++-------- .../file-system-resolver/src/index.ts | 12 +++++++---- .../uri-resolvers/http-resolver/src/index.ts | 10 ++++++++-- .../uri-resolvers/ipfs-resolver/src/index.ts | 18 ++++++++--------- packages/js/react/src/invoke.tsx | 20 +++++++++++-------- 6 files changed, 46 insertions(+), 32 deletions(-) diff --git a/packages/js/plugins/ipfs/src/utils/exec/abortable.ts b/packages/js/plugins/ipfs/src/utils/exec/abortable.ts index 47d276c310..b578ed5a5c 100644 --- a/packages/js/plugins/ipfs/src/utils/exec/abortable.ts +++ b/packages/js/plugins/ipfs/src/utils/exec/abortable.ts @@ -77,7 +77,7 @@ export const execAbortable = ( provider, abort: () => { controller.abort(); - timer && clearTimeout(); + timer && clearTimeout(timer); }, }; }; diff --git a/packages/js/plugins/uri-resolvers/ens-resolver/src/index.ts b/packages/js/plugins/uri-resolvers/ens-resolver/src/index.ts index 17dcc81de5..ea337a5b90 100644 --- a/packages/js/plugins/uri-resolvers/ens-resolver/src/index.ts +++ b/packages/js/plugins/uri-resolvers/ens-resolver/src/index.ts @@ -111,7 +111,7 @@ export class EnsResolverPlugin extends Module { args: string[], networkNameOrChainId?: string ): Promise => { - const { data, error } = await Ethereum_Module.callContractView( + const result = await Ethereum_Module.callContractView( { address, method, @@ -125,22 +125,22 @@ export class EnsResolverPlugin extends Module { client ); - if (error) { - throw error; + if (!result.ok) { + throw result.error; } - if (data) { - if (typeof data !== "string") { + if (result.value) { + if (typeof result.value !== "string") { throw Error( - `Malformed data returned from Ethereum.callContractView: ${data}` + `Malformed data returned from Ethereum.callContractView: ${result.value}` ); } - return data; + return result.value; } throw Error( - `Ethereum.callContractView returned nothing.\nData: ${data}\nError: ${error}` + `Ethereum.callContractView returned nothing.\nData: \nError: ` ); }; diff --git a/packages/js/plugins/uri-resolvers/file-system-resolver/src/index.ts b/packages/js/plugins/uri-resolvers/file-system-resolver/src/index.ts index 9638d5dbe9..80ad27882c 100644 --- a/packages/js/plugins/uri-resolvers/file-system-resolver/src/index.ts +++ b/packages/js/plugins/uri-resolvers/file-system-resolver/src/index.ts @@ -33,16 +33,17 @@ export class FileSystemResolverPlugin extends Module { _client ); - if (manifestExistsResult.data) { + if (manifestExistsResult.ok && manifestExistsResult.value) { try { const manifestResult = await FileSystem_Module.readFile( { path: manifestPath }, _client ); - if (manifestResult.error) { + if (!manifestResult.ok) { console.warn(manifestResult.error); + return { uri: null, manifest: undefined }; } - manifest = manifestResult.data; + manifest = manifestResult.value; } catch (e) { // TODO: logging } @@ -57,8 +58,11 @@ export class FileSystemResolverPlugin extends Module { { path: args.path }, _client ); + if (!fileResult.ok) { + return null; + } - return fileResult.data ?? null; + return fileResult.value; } catch (e) { return null; } diff --git a/packages/js/plugins/uri-resolvers/http-resolver/src/index.ts b/packages/js/plugins/uri-resolvers/http-resolver/src/index.ts index edccc857a5..9dc0003e72 100644 --- a/packages/js/plugins/uri-resolvers/http-resolver/src/index.ts +++ b/packages/js/plugins/uri-resolvers/http-resolver/src/index.ts @@ -37,7 +37,10 @@ export class HttpResolverPlugin extends Module { _client ); - const result = manifestResult.data; + if (!manifestResult.ok) { + return { uri: null, manifest: null }; + } + const result = manifestResult.value; if (result && result.body) { manifest = Buffer.from(result.body, "base64"); @@ -65,7 +68,10 @@ export class HttpResolverPlugin extends Module { client ); - const result = resolveResult.data; + if (!resolveResult.ok) { + return null; + } + const result = resolveResult.value; if (!result || !result.body) { return null; diff --git a/packages/js/plugins/uri-resolvers/ipfs-resolver/src/index.ts b/packages/js/plugins/uri-resolvers/ipfs-resolver/src/index.ts index 5daa7bf78d..477121e61a 100644 --- a/packages/js/plugins/uri-resolvers/ipfs-resolver/src/index.ts +++ b/packages/js/plugins/uri-resolvers/ipfs-resolver/src/index.ts @@ -47,10 +47,8 @@ export class IpfsResolverPlugin extends Module { _client ); - if (manifestResult.data) { - manifest = Buffer.from(manifestResult.data); - } else { - throw new Error(); + if (manifestResult.ok) { + manifest = Buffer.from(manifestResult.value); } } catch (e) { // TODO: logging @@ -79,13 +77,11 @@ export class IpfsResolverPlugin extends Module { client ); - const result = resolveResult.data; - - if (!result) { + if (!resolveResult.ok || !resolveResult.value) { return null; } - provider = result.provider; + provider = resolveResult.value.provider; } const catResult = await Ipfs_Module.cat( @@ -100,7 +96,11 @@ export class IpfsResolverPlugin extends Module { client ); - return catResult.data ?? null; + if (!catResult.ok) { + return null; + } + + return catResult.value; } catch (e) { return null; } diff --git a/packages/js/react/src/invoke.tsx b/packages/js/react/src/invoke.tsx index 3b11f1509c..e5f756d2d4 100644 --- a/packages/js/react/src/invoke.tsx +++ b/packages/js/react/src/invoke.tsx @@ -3,13 +3,13 @@ import { useStateReducer } from "./state"; import { InvokeOptions, - InvokeResult, + Result, isBuffer } from "@polywrap/core-js"; -export interface UsePolywrapInvokeState< - TData = unknown -> extends InvokeResult { +export interface UsePolywrapInvokeState { + data?: TData; + error?: Error loading: boolean; } @@ -32,7 +32,7 @@ export interface UsePolywrapInvoke< > extends UsePolywrapInvokeState { execute: ( args?: Record | Uint8Array - ) => Promise>; + ) => Promise>; } export function usePolywrapInvoke< @@ -48,15 +48,19 @@ export function usePolywrapInvoke< const execute = async (args?: Record | Uint8Array) => { dispatch({ loading: true }); - const { data, error } = await client.invoke({ + const result = await client.invoke({ ...props, args: isBuffer(args) ? args : { ...props.args, ...args, }, }); - dispatch({ data, error, loading: false }); - return { data, error }; + if (result.ok) { + dispatch({ data: result.value, loading: false }); + } else { + dispatch({ error: result.error, loading: false }); + } + return result; }; return { From 54f8a961617e56397c42e2e589c20a16c12fc5cb Mon Sep 17 00:00:00 2001 From: krisbitney Date: Sun, 25 Sep 2022 09:33:33 +0500 Subject: [PATCH 08/25] client tests passing --- .../__tests__/core/interface-impls.spec.ts | 30 ++++++++++++------- .../src/__tests__/core/wasm-wrapper.spec.ts | 2 +- .../js/client/src/__tests__/e2e/test-cases.ts | 10 ++++--- 3 files changed, 27 insertions(+), 15 deletions(-) diff --git a/packages/js/client/src/__tests__/core/interface-impls.spec.ts b/packages/js/client/src/__tests__/core/interface-impls.spec.ts index 080728d408..4ef005e719 100644 --- a/packages/js/client/src/__tests__/core/interface-impls.spec.ts +++ b/packages/js/client/src/__tests__/core/interface-impls.spec.ts @@ -38,7 +38,8 @@ describe("interface-impls", () => { const implementations = client.getImplementations(interfaceUri); - expect(implementations).toEqual([implementation1Uri, implementation2Uri]); + if (!implementations.ok) fail(implementations.error); + expect(implementations.value).toEqual([implementation1Uri, implementation2Uri]); }); it("should get all implementations of interface", async () => { @@ -101,19 +102,22 @@ describe("interface-impls", () => { applyRedirects: true, }); - expect(implementations1).toEqual([ + if (!implementations1.ok) fail(implementations1.error); + expect(implementations1.value).toEqual([ implementation1Uri, implementation2Uri, implementation3Uri, ]); - expect(implementations2).toEqual([ + if (!implementations2.ok) fail(implementations2.error); + expect(implementations2.value).toEqual([ implementation1Uri, implementation2Uri, implementation3Uri, ]); - expect(implementations3).toEqual([implementation3Uri, implementation4Uri]); + if (!implementations3.ok) fail(implementations3.error); + expect(implementations3.value).toEqual([implementation3Uri, implementation4Uri]); }); it("should not register plugins with an interface uri (without default plugins)", () => { @@ -291,7 +295,8 @@ describe("interface-impls", () => { { applyRedirects: true } ); - expect(getImplementationsResult).toEqual([new Uri(implementation2Uri)]); + if (!getImplementationsResult.ok) fail(getImplementationsResult.error); + expect(getImplementationsResult.value).toEqual([new Uri(implementation2Uri)]); }); test("get implementations - return implementations for plugins which don't have interface stated in manifest", () => { @@ -323,7 +328,8 @@ describe("interface-impls", () => { { applyRedirects: true } ); - expect(getImplementationsResult).toEqual([ + if (!getImplementationsResult.ok) fail(getImplementationsResult.error); + expect(getImplementationsResult.value).toEqual([ new Uri(implementation1Uri), new Uri(implementation2Uri), ]); @@ -356,20 +362,24 @@ describe("interface-impls", () => { }); let result = client.getImplementations(oldInterfaceUri); - expect(result).toEqual([implementation1Uri]); + if (!result.ok) fail(result.error); + expect(result.value).toEqual([implementation1Uri]); result = client.getImplementations(oldInterfaceUri, { applyRedirects: true, }); - expect(result).toEqual([implementation1Uri, implementation2Uri]); + if (!result.ok) fail(result.error); + expect(result.value).toEqual([implementation1Uri, implementation2Uri]); let result2 = client.getImplementations(new Uri(oldInterfaceUri)); - expect(result2).toEqual([new Uri(implementation1Uri)]); + if (!result2.ok) fail(result2.error); + expect(result2.value).toEqual([new Uri(implementation1Uri)]); result2 = client.getImplementations(new Uri(oldInterfaceUri), { applyRedirects: true, }); - expect(result2).toEqual([ + if (!result2.ok) fail(result2.error); + expect(result2.value).toEqual([ new Uri(implementation1Uri), new Uri(implementation2Uri), ]); diff --git a/packages/js/client/src/__tests__/core/wasm-wrapper.spec.ts b/packages/js/client/src/__tests__/core/wasm-wrapper.spec.ts index 98719aa545..d229313286 100644 --- a/packages/js/client/src/__tests__/core/wasm-wrapper.spec.ts +++ b/packages/js/client/src/__tests__/core/wasm-wrapper.spec.ts @@ -214,7 +214,7 @@ describe("wasm-wrapper", () => { }); pluginGetFileResult = pluginGetFileResult as ErrResult; - expect(pluginGetFileResult.error).toContain("client.getFile(...) is not implemented for Plugins."); + expect(pluginGetFileResult.error?.message).toContain("client.getFile(...) is not implemented for Plugins."); }); test("subscribe", async () => { diff --git a/packages/js/client/src/__tests__/e2e/test-cases.ts b/packages/js/client/src/__tests__/e2e/test-cases.ts index 54de40c69d..cc708f6eb8 100644 --- a/packages/js/client/src/__tests__/e2e/test-cases.ts +++ b/packages/js/client/src/__tests__/e2e/test-cases.ts @@ -296,9 +296,9 @@ export const runImplementationsTest = async ( interfaceUri: string, implementationUri: string ) => { - expect(client.getImplementations(interfaceUri)).toEqual([ - new Uri(implementationUri).uri, - ]); + const implResult = client.getImplementations(interfaceUri); + if (!implResult.ok) fail(implResult.error); + expect(implResult.value).toEqual([new Uri(implementationUri).uri]); const results = await Promise.all([ client.invoke({ @@ -338,7 +338,9 @@ export const runGetImplementationsTest = async ( implementationUri: string ) => { let implUri = new Uri(implementationUri); - expect(client.getImplementations(interfaceUri)).toEqual([implUri.uri]); + const implResult = client.getImplementations(interfaceUri); + if (!implResult.ok) fail(implResult.error); + expect(implResult.value).toEqual([implUri.uri]); const result = await client.invoke({ uri: aggregatorUri, From 4537d0e3861106922b7726e9d983e8251efdee85 Mon Sep 17 00:00:00 2001 From: krisbitney Date: Mon, 26 Sep 2022 08:30:08 +0500 Subject: [PATCH 09/25] plugin tests passing --- .../ethereum/src/__tests__/e2e.spec.ts | 250 +++++++++--------- .../file-system/src/__tests__/e2e.spec.ts | 48 ++-- .../http/src/__tests__/e2e/e2e.spec.ts | 82 +++--- .../src/__tests__/e2e/integration.spec.ts | 14 +- .../js/plugins/ipfs/src/__tests__/e2e.spec.ts | 48 ++-- .../logger/src/__tests__/e2e/e2e.spec.ts | 6 +- .../src/__tests__/e2e.spec.ts | 15 +- .../ipfs-resolver/src/__tests__/e2e.spec.ts | 28 +- .../plugins/ws/src/__tests__/e2e/e2e.spec.ts | 105 +++++--- .../ws/src/__tests__/e2e/integration.spec.ts | 3 +- 10 files changed, 320 insertions(+), 279 deletions(-) diff --git a/packages/js/plugins/ethereum/src/__tests__/e2e.spec.ts b/packages/js/plugins/ethereum/src/__tests__/e2e.spec.ts index 9c9d079d04..b101c9aa9e 100644 --- a/packages/js/plugins/ethereum/src/__tests__/e2e.spec.ts +++ b/packages/js/plugins/ethereum/src/__tests__/e2e.spec.ts @@ -113,9 +113,9 @@ describe("Ethereum Plugin", () => { }, }); - expect(response.error).toBeUndefined(); - expect(response.data).toBeDefined(); - expect(response.data).toBe("0x0000000000000000000000000000000000000000"); + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); + expect(response.value).toBe("0x0000000000000000000000000000000000000000"); }); it("callContractStatic (no error)", async () => { @@ -136,9 +136,9 @@ describe("Ethereum Plugin", () => { }, }); - expect(response.error).toBeUndefined(); - expect(response.data?.error).toBeFalsy(); - expect(response.data?.result).toBe(""); + if (!response.ok) fail(response.error); + expect(response.value?.error).toBeFalsy(); + expect(response.value?.result).toBe(""); }); it("callContractStatic (expecting error)", async () => { @@ -159,10 +159,9 @@ describe("Ethereum Plugin", () => { }, }); - expect(response.error).toBeUndefined(); - expect(response.data).toBeDefined(); - expect(response.data?.error).toBeTruthy(); - expect(response.data?.result).toContain( + if (!response.ok) fail(response.error); + expect(response.value?.error).toBeTruthy(); + expect(response.value?.result).toContain( "missing revert data in call exception" ); }); @@ -172,17 +171,18 @@ describe("Ethereum Plugin", () => { uri, method: "getSignerAddress", }); + if (!signerAddressQuery.ok) fail(signerAddressQuery.error); const response = await client.invoke({ uri, method: "getBalance", args: { - address: signerAddressQuery.data, + address: signerAddressQuery.value, }, }); - expect(response.error).toBeUndefined(); - expect(response.data).toBeDefined(); + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); }); it("encodeParams", async () => { @@ -195,7 +195,8 @@ describe("Ethereum Plugin", () => { }, }); - expect(response.data).toBe( + if (!response.ok) fail(response.error); + expect(response.value).toBe( "0x000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000" ); @@ -214,7 +215,7 @@ describe("Ethereum Plugin", () => { }, }); - expect(acceptsTupleArg.error).toBeUndefined(); + if (!acceptsTupleArg.ok) fail(acceptsTupleArg.error); }); it("encodeFunction", async () => { @@ -227,8 +228,8 @@ describe("Ethereum Plugin", () => { }, }); - expect(response.error).toBeUndefined(); - expect(response.data).toBe( + if (!response.ok) fail(response.error); + expect(response.value).toBe( "0x46d4adf20000000000000000000000000000000000000000000000000000000000000064" ); @@ -241,7 +242,7 @@ describe("Ethereum Plugin", () => { }, }); - expect(acceptsArrayArg.error).toBeUndefined(); + if (!acceptsArrayArg.ok) fail(acceptsArrayArg.error); }); it("solidityPack", async () => { @@ -268,9 +269,9 @@ describe("Ethereum Plugin", () => { }, }); - expect(result.error).toBeFalsy(); - expect(result.data).toBeTruthy(); - expect(result.data).toBe( + if (!result.ok) fail(result.error); + expect(result.value).toBeTruthy(); + expect(result.value).toBe( "0x0000000000000000000000000000000000000001000bb80000000000000000000000000000000000000002000bb8c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" ); }); @@ -299,9 +300,9 @@ describe("Ethereum Plugin", () => { }, }); - expect(result.error).toBeFalsy(); - expect(result.data).toBeTruthy(); - expect(result.data).toBe( + if (!result.ok) fail(result.error); + expect(result.value).toBeTruthy(); + expect(result.value).toBe( "0x5dd4ee83f9bab0157f0e929b6dddd106fd7de6e5089f0f05c2c0b861e3807588" ); }); @@ -330,9 +331,9 @@ describe("Ethereum Plugin", () => { }, }); - expect(result.error).toBeFalsy(); - expect(result.data).toBeTruthy(); - expect(result.data).toBe( + if (!result.ok) fail(result.error); + expect(result.value).toBeTruthy(); + expect(result.value).toBe( "0x8652504faf6e0d175e62c1d9c7e10d636d5ab8f153ec3257dab1726639058d27" ); }); @@ -343,9 +344,9 @@ describe("Ethereum Plugin", () => { method: "getSignerAddress", }); - expect(response.error).toBeUndefined(); - expect(response.data).toBeDefined(); - expect(response.data?.startsWith("0x")).toBe(true); + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); + expect(response.value?.startsWith("0x")).toBe(true); }); it("getSignerBalance", async () => { @@ -354,8 +355,8 @@ describe("Ethereum Plugin", () => { method: "getSignerBalance", }); - expect(response.error).toBeUndefined(); - expect(response.data).toBeDefined(); + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); }); it("getSignerTransactionCount", async () => { @@ -364,9 +365,9 @@ describe("Ethereum Plugin", () => { method: "getSignerTransactionCount", }); - expect(response.error).toBeUndefined(); - expect(response.data).toBeDefined(); - expect(Number(response.data)).toBeTruthy(); + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); + expect(Number(response.value)).toBeTruthy(); }); it("getGasPrice", async () => { @@ -375,9 +376,9 @@ describe("Ethereum Plugin", () => { method: "getGasPrice", }); - expect(response.error).toBeUndefined(); - expect(response.data).toBeDefined(); - expect(Number(response.data)).toBeTruthy(); + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); + expect(Number(response.value)).toBeTruthy(); }); it("estimateTransactionGas", async () => { @@ -393,9 +394,9 @@ describe("Ethereum Plugin", () => { }, }); - expect(response.error).toBeUndefined(); - expect(response.data).toBeDefined(); - const num = ethers.BigNumber.from(response.data); + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); + const num = ethers.BigNumber.from(response.value); expect(num.gt(0)).toBeTruthy(); }); @@ -411,9 +412,9 @@ describe("Ethereum Plugin", () => { }, }); - expect(response.data).toBeDefined(); - expect(response.error).toBeUndefined(); - const num = ethers.BigNumber.from(response.data); + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); + const num = ethers.BigNumber.from(response.value); expect(num.gt(0)).toBeTruthy(); }); @@ -426,9 +427,9 @@ describe("Ethereum Plugin", () => { }, }); - expect(response.error).toBeUndefined(); - expect(response.data).toBeDefined(); - expect(response.data).toEqual(true); + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); + expect(response.value).toEqual(true); }); it("toWei", async () => { @@ -440,9 +441,9 @@ describe("Ethereum Plugin", () => { }, }); - expect(response.error).toBeUndefined(); - expect(response.data).toBeDefined(); - expect(response.data).toEqual("20000000000000000000"); + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); + expect(response.value).toEqual("20000000000000000000"); }); it("toEth", async () => { @@ -454,9 +455,9 @@ describe("Ethereum Plugin", () => { }, }); - expect(response.error).toBeUndefined(); - expect(response.data).toBeDefined(); - expect(response.data).toEqual("20.0"); + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); + expect(response.value).toEqual("20.0"); }); it("awaitTransaction", async () => { @@ -472,9 +473,9 @@ describe("Ethereum Plugin", () => { }, }); - expect(response.error).toBeUndefined(); - expect(response.data?.hash).toBeTruthy(); - const txHash = response.data?.hash as string; + if (!response.ok) fail(response.error); + expect(response.value?.hash).toBeTruthy(); + const txHash = response.value?.hash as string; const awaitResponse = await client.invoke({ uri, @@ -486,9 +487,9 @@ describe("Ethereum Plugin", () => { }, }); - expect(awaitResponse.error).toBeUndefined(); - expect(awaitResponse.data).toBeDefined(); - expect(awaitResponse.data?.transactionHash).toBeDefined(); + if (!awaitResponse.ok) fail(awaitResponse.error); + expect(awaitResponse.value).toBeDefined(); + expect(awaitResponse.value.transactionHash).toBeDefined(); }); it("waitForEvent (NameTransfer)", async () => { @@ -497,8 +498,7 @@ describe("Ethereum Plugin", () => { const domain = "testwhatever10.eth"; const newOwner = "0xFFcf8FDEE72ac11b5c542428B35EEF5769C409f0"; - const listenerPromise = client - .invoke({ + const listenerPromise = client.invoke({ uri, method: "waitForEvent", args: { @@ -508,11 +508,15 @@ describe("Ethereum Plugin", () => { timeout: 20000, }, }) - .then((result: { data: Schema.EventNotification }) => { - expect(typeof result.data?.data === "string").toBe(true); - expect(typeof result.data?.address === "string").toBe(true); - expect(result.data?.log).toBeDefined(); - expect(typeof result.data?.log.transactionHash === "string").toBe( + .then((result) => { + if (result.ok) return result.value + else fail(result.error) + }) + .then((result: Schema.EventNotification) => { + expect(typeof result.data === "string").toBe(true); + expect(typeof result.address === "string").toBe(true); + expect(result.log).toBeDefined(); + expect(typeof result.log.transactionHash === "string").toBe( true ); }); @@ -556,15 +560,17 @@ describe("Ethereum Plugin", () => { timeout: 20000, }, }) - .then((result: { data: Schema.EventNotification }) => { - expect(typeof result.data?.data === "string").toBe(true); - expect(typeof result.data?.address === "string").toBe(true); - expect(result.data?.log).toBeDefined(); - expect(typeof result.data?.log.transactionHash === "string").toBe( + .then((result) => { + if (result.ok) return result.value + else fail(result.error) + }) + .then((result: Schema.EventNotification) => { + expect(typeof result.data === "string").toBe(true); + expect(typeof result.address === "string").toBe(true); + expect(result.log).toBeDefined(); + expect(typeof result.log.transactionHash === "string").toBe( true ); - - return; }); await client.invoke({ @@ -601,11 +607,11 @@ describe("Ethereum Plugin", () => { } }); - expect(mainnetNetwork.data).toBeTruthy(); - expect(mainnetNetwork.error).toBeFalsy(); - expect(mainnetNetwork.data?.chainId).toBe("1"); - expect(mainnetNetwork.data?.name).toBe("homestead"); - expect(mainnetNetwork.data?.ensAddress).toBe( + if (!mainnetNetwork.ok) fail(mainnetNetwork.error); + expect(mainnetNetwork.value).toBeTruthy(); + expect(mainnetNetwork.value?.chainId).toBe("1"); + expect(mainnetNetwork.value?.name).toBe("homestead"); + expect(mainnetNetwork.value?.ensAddress).toBe( "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e" ); }); @@ -619,12 +625,12 @@ describe("Ethereum Plugin", () => { } } }); - - expect(polygonNetwork.data).toBeTruthy(); - expect(polygonNetwork.error).toBeFalsy(); - expect(polygonNetwork.data?.chainId).toBe("137"); - expect(polygonNetwork.data?.name).toBe("matic"); - expect(polygonNetwork.data?.ensAddress).toBeFalsy(); + + if (!polygonNetwork.ok) fail(polygonNetwork.error); + expect(polygonNetwork.value).toBeTruthy(); + expect(polygonNetwork.value?.chainId).toBe("137"); + expect(polygonNetwork.value?.name).toBe("matic"); + expect(polygonNetwork.value?.ensAddress).toBeFalsy(); }); it("getNetwork - mainnet with env", async () => { @@ -645,11 +651,11 @@ describe("Ethereum Plugin", () => { }, }); - expect(mainnetNetwork.data).toBeTruthy(); - expect(mainnetNetwork.error).toBeFalsy(); - expect(mainnetNetwork.data?.chainId).toBe("1"); - expect(mainnetNetwork.data?.name).toBe("homestead"); - expect(mainnetNetwork.data?.ensAddress).toBe( + if (!mainnetNetwork.ok) fail(mainnetNetwork.error); + expect(mainnetNetwork.value).toBeTruthy(); + expect(mainnetNetwork.value?.chainId).toBe("1"); + expect(mainnetNetwork.value?.name).toBe("homestead"); + expect(mainnetNetwork.value?.ensAddress).toBe( "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e" ); }); @@ -672,25 +678,21 @@ describe("Ethereum Plugin", () => { }, }); - expect(polygonNetwork.data).toBeTruthy(); - expect(polygonNetwork.error).toBeFalsy(); - expect(polygonNetwork.data?.chainId).toBe("137"); - expect(polygonNetwork.data?.name).toBe("matic"); + if (!polygonNetwork.ok) fail(polygonNetwork.error); + expect(polygonNetwork.value).toBeTruthy(); + expect(polygonNetwork.value?.chainId).toBe("137"); + expect(polygonNetwork.value?.name).toBe("matic"); }); it("requestAccounts", async () => { - const { error } = await client.invoke({ + let result = await client.invoke({ uri, method: "requestAccounts", }) - + result = result as { ok: false; error: Error | undefined }; // eth_requestAccounts is not supported by Ganache // this RPC error indicates that the method call was attempted - expect(error?.message.indexOf("Method eth_requestAccounts not supported")).toBeGreaterThanOrEqual(0); - - // expect(error).toBeFalsy(); - // expect(data).toBeTruthy(); - // expect(data?.length).toBeGreaterThan(0); + expect(result.error?.message.indexOf("Method eth_requestAccounts not supported")).toBeGreaterThanOrEqual(0); }); }); @@ -713,8 +715,8 @@ describe("Ethereum Plugin", () => { } }); - expect(response.error).toBeUndefined(); - expect(response.data).toBeDefined(); + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); }); it("callContractMethodAndWait", async () => { @@ -735,8 +737,8 @@ describe("Ethereum Plugin", () => { } }); - expect(response.error).toBeUndefined(); - expect(response.data).toBeDefined(); + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); }); it("sendTransaction", async () => { @@ -748,9 +750,9 @@ describe("Ethereum Plugin", () => { } }); - expect(response.error).toBeUndefined(); - expect(response.data).toBeDefined(); - expect(response.data?.hash).toBeDefined(); + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); + expect(response.value?.hash).toBeDefined(); }); it("sendTransactionAndWait", async () => { @@ -762,10 +764,10 @@ describe("Ethereum Plugin", () => { } }); - expect(response.error).toBeUndefined(); - expect(response.data).toBeDefined(); + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); expect( - response.data?.transactionHash + response.value?.transactionHash ).toBeDefined(); }); @@ -779,9 +781,9 @@ describe("Ethereum Plugin", () => { } }); - expect(response.error).toBeUndefined(); - expect(response.data).toBeDefined(); - expect(response.data).toContain("0x"); + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); + expect(response.value).toContain("0x"); }); it("signMessage", async () => { @@ -793,8 +795,8 @@ describe("Ethereum Plugin", () => { } }); - expect(response.error).toBeUndefined(); - expect(response.data).toBe( + if (!response.ok) fail(response.error); + expect(response.value).toBe( "0xa4708243bf782c6769ed04d83e7192dbcf4fc131aa54fde9d889d8633ae39dab03d7babd2392982dff6bc20177f7d887e27e50848c851320ee89c6c63d18ca761c" ); }); @@ -808,8 +810,8 @@ describe("Ethereum Plugin", () => { } }); - expect(res.error).toBeUndefined(); - expect(res.data).toBeDefined(); + if (!res.ok) fail(res.error); + expect(res.value).toBeDefined(); }); }); @@ -824,11 +826,11 @@ describe("Ethereum Plugin", () => { } }); - expect(response1.error).toBeUndefined(); - expect(response1.data).toBeDefined(); - expect(response1.data).toContain("0x"); + if (!response1.ok) fail(response1.error); + expect(response1.value).toBeDefined(); + expect(response1.value).toContain("0x"); - const address = response1.data as string; + const address = response1.value; const structArg = JSON.stringify({ str: "foo bar", unsigned256: 123456, @@ -845,10 +847,10 @@ describe("Ethereum Plugin", () => { } }); - expect(response2.error).toBeUndefined(); - expect(response2.data).toBeDefined(); + if (!response2.ok) fail(response2.error); + expect(response2.value).toBeDefined(); expect( - response2.data?.transactionHash + response2.value?.transactionHash ).toBeDefined(); }); }); diff --git a/packages/js/plugins/file-system/src/__tests__/e2e.spec.ts b/packages/js/plugins/file-system/src/__tests__/e2e.spec.ts index d7547c07a7..f86ff77a17 100644 --- a/packages/js/plugins/file-system/src/__tests__/e2e.spec.ts +++ b/packages/js/plugins/file-system/src/__tests__/e2e.spec.ts @@ -48,21 +48,22 @@ describe("FileSystem plugin", () => { { path: sampleFilePath }, client ); - - expect(result.error).toBeFalsy(); - expect(result.data).toEqual(new Uint8Array(expectedContents)); + + if (!result.ok) fail(result.error); + expect(result.value).toEqual(new Uint8Array(expectedContents)); }); it("should fail reading a nonexistent file", async () => { const nonExistentFilePath = path.resolve(__dirname, "nonexistent.txt"); - const result = await FileSystem_Module.readFile( + let result = await FileSystem_Module.readFile( { path: nonExistentFilePath }, client ); - expect(result.data).toBeFalsy(); + result = result as { ok: false, error: Error | undefined }; expect(result.error).toBeTruthy(); + expect(result.ok).toBeFalsy(); }); it("should read a UTF8-encoded file as a string", async () => { @@ -77,8 +78,8 @@ describe("FileSystem plugin", () => { client ); - expect(result.error).toBeFalsy(); - expect(result.data).toBe(expectedContents); + if (!result.ok) fail(result.error); + expect(result.value).toBe(expectedContents); }); it("should read a file using supported encodings as a string", async () => { @@ -100,13 +101,13 @@ describe("FileSystem plugin", () => { client ); - expect(result.error).toBeFalsy(); + if (!result.ok) fail(result.error); const expectedContents = await fs.promises.readFile(sampleFilePath, { encoding: fileSystemEncodingToBufferEncoding(encoding), }); - expect(result.data).toBe(expectedContents); + expect(result.value).toBe(expectedContents); } }); @@ -116,8 +117,8 @@ describe("FileSystem plugin", () => { client ); - expect(result_fileExists.error).toBeFalsy(); - expect(result_fileExists.data).toBe(true); + if (!result_fileExists.ok) fail(result_fileExists.error); + expect(result_fileExists.value).toBe(true); const nonExistentFilePath = path.resolve( __dirname, @@ -129,8 +130,8 @@ describe("FileSystem plugin", () => { client ); - expect(result_fileMissing.error).toBeFalsy(); - expect(result_fileMissing.data).toBe(false); + if (!result_fileMissing.ok) fail(result_fileMissing.error); + expect(result_fileMissing.value).toBe(false); }); it("should write byte data to a file", async () => { @@ -145,8 +146,8 @@ describe("FileSystem plugin", () => { await fs.promises.readFile(tempFilePath) ); - expect(result.error).toBeFalsy(); - expect(result.data).toBe(true); + if (!result.ok) fail(result.error); + expect(result.value).toBe(true); expect(expectedFileContents).toEqual(bytes); }); @@ -157,8 +158,8 @@ describe("FileSystem plugin", () => { const result = await FileSystem_Module.rm({ path: tempFilePath }, client); - expect(result.error).toBeFalsy(); - expect(result.data).toBe(true); + if (!result.ok) fail(result.error); + expect(result.value).toBe(true); const fileExists = fs.existsSync(tempFilePath); @@ -179,8 +180,8 @@ describe("FileSystem plugin", () => { client ); - expect(result.error).toBeFalsy(); - expect(result.data).toBe(true); + if (!result.ok) fail(result.error); + expect(result.value).toBe(true); const fileExists = fs.existsSync(fileInDirPath); @@ -190,7 +191,8 @@ describe("FileSystem plugin", () => { it("should create a directory", async () => { const result = await FileSystem_Module.mkdir({ path: tempDirPath }, client); - expect(result.data).toBe(true); + if (!result.ok) fail(result.error); + expect(result.value).toBe(true); let directoryExists = fs.existsSync(tempDirPath); @@ -205,7 +207,8 @@ describe("FileSystem plugin", () => { client ); - expect(result.data).toBe(true); + if (!result.ok) fail(result.error); + expect(result.value).toBe(true); let directoryExists = fs.existsSync(dirInDirPath); @@ -217,7 +220,8 @@ describe("FileSystem plugin", () => { const result = await FileSystem_Module.rmdir({ path: tempDirPath }, client); - expect(result.data).toBe(true); + if (!result.ok) fail(result.error); + expect(result.value).toBe(true); const directoryExists = fs.existsSync(tempDirPath); diff --git a/packages/js/plugins/http/src/__tests__/e2e/e2e.spec.ts b/packages/js/plugins/http/src/__tests__/e2e/e2e.spec.ts index f0b6fee523..4b1b896d5d 100644 --- a/packages/js/plugins/http/src/__tests__/e2e/e2e.spec.ts +++ b/packages/js/plugins/http/src/__tests__/e2e/e2e.spec.ts @@ -42,12 +42,12 @@ describe("e2e tests for HttpPlugin", () => { }, }, }); - - expect(response.error).toBeUndefined(); - expect(response.data).toBeDefined(); - expect(response.data?.status).toBe(200); - expect(response.data?.body).toBe('{data: "test-response"}'); - expect(response.data?.headers?.size).toEqual(2); // default reply headers + + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); + expect(response.value?.status).toBe(200); + expect(response.value?.body).toBe('{data: "test-response"}'); + expect(response.value?.headers?.size).toEqual(2); // default reply headers }); test("successful request with response type as BINARY", async () => { @@ -67,13 +67,13 @@ describe("e2e tests for HttpPlugin", () => { }, }); - expect(response.error).toBeUndefined(); - expect(response.data).toBeDefined(); - expect(response.data?.status).toBe(200); - expect(response.data?.body).toBe( + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); + expect(response.value?.status).toBe(200); + expect(response.value?.body).toBe( Buffer.from('{data: "test-response"}').toString("base64") ); - expect(response.data?.headers?.size).toEqual(2); // default reply headers + expect(response.value?.headers?.size).toEqual(2); // default reply headers }); test("successful request with query params and request headers", async () => { @@ -100,11 +100,11 @@ describe("e2e tests for HttpPlugin", () => { }, }); - expect(response.error).toBeUndefined(); - expect(response.data).toBeDefined(); - expect(response.data?.status).toBe(200); - expect(response.data?.body).toBe('{data: "test-response"}'); - expect(response.data?.headers).toEqual( + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); + expect(response.value?.status).toBe(200); + expect(response.value?.body).toBe('{data: "test-response"}'); + expect(response.value?.headers).toEqual( new Map([ ["x-response-header", "resp-foo"], ["access-control-allow-origin", "*"], @@ -119,7 +119,7 @@ describe("e2e tests for HttpPlugin", () => { .get("/api") .reply(404); - const response = await polywrapClient.invoke({ + let response = await polywrapClient.invoke({ uri: "wrap://ens/http.polywrap.eth", method: "get", args: { @@ -130,8 +130,9 @@ describe("e2e tests for HttpPlugin", () => { }, }); - expect(response.data).toBeUndefined(); + response = response as { ok: false, error: Error | undefined }; expect(response.error).toBeDefined(); + expect(response.ok).toBeFalsy(); }); }); @@ -165,11 +166,11 @@ describe("e2e tests for HttpPlugin", () => { }, }); - expect(response.error).toBeUndefined(); - expect(response.data).toBeDefined(); - expect(response.data?.status).toBe(200); - expect(response.data?.body).toBe(resPayloadStringfified); - expect(response.data?.headers?.size).toEqual(2); // default reply headers + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); + expect(response.value?.status).toBe(200); + expect(response.value?.body).toBe(resPayloadStringfified); + expect(response.value?.headers?.size).toEqual(2); // default reply headers }); test("successful request with response type as TEXT", async () => { @@ -190,11 +191,11 @@ describe("e2e tests for HttpPlugin", () => { }, }); - expect(response.error).toBeUndefined(); - expect(response.data).toBeDefined(); - expect(response.data?.status).toBe(200); - expect(response.data?.body).toBe('{data: "test-response"}'); - expect(response.data?.headers?.size).toEqual(2); // default reply headers + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); + expect(response.value?.status).toBe(200); + expect(response.value?.body).toBe('{data: "test-response"}'); + expect(response.value?.headers?.size).toEqual(2); // default reply headers }); test("successful request with response type as BINARY", async () => { @@ -215,13 +216,13 @@ describe("e2e tests for HttpPlugin", () => { }, }); - expect(response.error).toBeUndefined(); - expect(response.data).toBeDefined(); - expect(response.data?.status).toBe(200); - expect(response.data?.body).toBe( + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); + expect(response.value?.status).toBe(200); + expect(response.value?.body).toBe( Buffer.from('{data: "test-response"}').toString("base64") ); - expect(response.data?.headers?.size).toEqual(2); // default reply headers + expect(response.value?.headers?.size).toEqual(2); // default reply headers }); test("successful request with query params and request headers", async () => { @@ -249,11 +250,11 @@ describe("e2e tests for HttpPlugin", () => { }, }); - expect(response.data).toBeDefined(); - expect(response.error).toBeUndefined(); - expect(response.data?.status).toBe(200); - expect(response.data?.body).toBe('{data: "test-response"}'); - expect(response.data?.headers).toEqual( + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); + expect(response.value?.status).toBe(200); + expect(response.value?.body).toBe('{data: "test-response"}'); + expect(response.value?.headers).toEqual( new Map([ ["x-response-header", "resp-foo"], ["access-control-allow-origin", "*"], @@ -268,7 +269,7 @@ describe("e2e tests for HttpPlugin", () => { .post("/api") .reply(404); - const response = await polywrapClient.invoke({ + let response = await polywrapClient.invoke({ uri: "wrap://ens/http.polywrap.eth", method: "post", args: { @@ -279,8 +280,9 @@ describe("e2e tests for HttpPlugin", () => { }, }); - expect(response.data).toBeUndefined(); + response = response as { ok: false, error: Error | undefined }; expect(response.error).toBeDefined(); + expect(response.ok).toBeFalsy(); }); }); }); diff --git a/packages/js/plugins/http/src/__tests__/e2e/integration.spec.ts b/packages/js/plugins/http/src/__tests__/e2e/integration.spec.ts index 29f79215f2..3cdbfbf1cb 100644 --- a/packages/js/plugins/http/src/__tests__/e2e/integration.spec.ts +++ b/packages/js/plugins/http/src/__tests__/e2e/integration.spec.ts @@ -56,9 +56,9 @@ describe("e2e tests for HttpPlugin", () => { }, }); - expect(response.error).toBeUndefined(); - expect(response.data).toBeDefined(); - expect(response.data?.status).toBe(200); + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); + expect(response.value?.status).toBe(200); }); it("post", async () => { @@ -86,10 +86,10 @@ describe("e2e tests for HttpPlugin", () => { }, }); - expect(response.error).toBeFalsy(); - expect(response.data).toBeTruthy(); - expect(response.data?.status).toBe(200); - expect(response.data?.body).toBeTruthy(); + if (!response.ok) fail(response.error); + expect(response.value).toBeTruthy(); + expect(response.value?.status).toBe(200); + expect(response.value?.body).toBeTruthy(); }); }); }); diff --git a/packages/js/plugins/ipfs/src/__tests__/e2e.spec.ts b/packages/js/plugins/ipfs/src/__tests__/e2e.spec.ts index 5180894138..cd5640549d 100644 --- a/packages/js/plugins/ipfs/src/__tests__/e2e.spec.ts +++ b/packages/js/plugins/ipfs/src/__tests__/e2e.spec.ts @@ -9,6 +9,7 @@ import { import { ipfsPlugin } from ".."; import { IpfsClient, IpfsFileInfo } from "../utils/IpfsClient"; import { Ipfs_Module } from "../wrap"; +import { ResultOk } from "@polywrap/result"; const createIpfsClient = require("@dorgjelli-test/ipfs-http-client-lite"); @@ -58,10 +59,10 @@ describe("IPFS Plugin", () => { { cid: sampleFileIpfsInfo.hash.toString() }, client ); + + if (!result.ok) fail(result.error); - expect(result.error).toBeFalsy(); - - expect(result.data).toEqual(sampleFileBuffer); + expect(result.value).toEqual(sampleFileBuffer); }); it("Should resolve a file successfully", async () => { @@ -72,9 +73,9 @@ describe("IPFS Plugin", () => { client ); - expect(result.error).toBeFalsy(); + if (!result.ok) fail(result.error); - expect(result.data).toEqual({ + expect(result.value).toEqual({ cid: `/ipfs/${sampleFileIpfsInfo.hash.toString()}`, provider: providers.ipfs, }); @@ -86,11 +87,11 @@ describe("IPFS Plugin", () => { let result = await Ipfs_Module.addFile({ data: contentsBuffer }, client); - expect(result.error).toBeFalsy(); + if (!result.ok) fail(result.error); - expect(result.data).toBeTruthy(); + expect(result.value).toBeTruthy(); - const addedFileBuffer = await ipfs.cat(result.data as string); + const addedFileBuffer = await ipfs.cat(result.value as string); expect(contentsBuffer).toEqual(addedFileBuffer); }); @@ -101,10 +102,9 @@ describe("IPFS Plugin", () => { ): Promise> => { return new Promise>((resolve) => setTimeout(() => { - resolve({ - data: Uint8Array.from([1, 2, 3, 4]), - error: undefined, - }); + resolve( + ResultOk(Uint8Array.from([1, 2, 3, 4])) + ); }, timeout) ); }; @@ -133,10 +133,10 @@ describe("IPFS Plugin", () => { let racePromise = createRacePromise(1100); - const result = await Promise.race([catPromise, racePromise]); + let result = await Promise.race([catPromise, racePromise]); expect(result).toBeTruthy(); - expect(result.data).toBeFalsy(); + result = result as { ok: false; error: Error | undefined }; expect(result.error).toBeTruthy(); expect(result.error?.stack).toMatch("Timeout has been reached"); expect(result.error?.stack).toMatch("Timeout: 1000"); @@ -151,13 +151,13 @@ describe("IPFS Plugin", () => { racePromise = createRacePromise(600); - const resultForOverride = await Promise.race([ + let resultForOverride = await Promise.race([ catPromiseWithTimeoutOverride, racePromise, ]); expect(resultForOverride).toBeTruthy(); - expect(resultForOverride.data).toBeFalsy(); + resultForOverride = resultForOverride as { ok: false; error: Error | undefined }; expect(resultForOverride.error).toBeTruthy(); expect(resultForOverride.error?.stack).toMatch("Timeout has been reached"); expect(resultForOverride.error?.stack).toMatch("Timeout: 500"); @@ -189,8 +189,8 @@ describe("IPFS Plugin", () => { clientWithBadProvider ); - expect(catResult.error).toBeFalsy(); - expect(catResult.data).toEqual(sampleFileBuffer); + if (!catResult.ok) fail(catResult.error); + expect(catResult.value).toEqual(sampleFileBuffer); const resolveResult = await Ipfs_Module.resolve( { @@ -200,8 +200,8 @@ describe("IPFS Plugin", () => { clientWithBadProvider ); - expect(resolveResult.error).toBeFalsy(); - expect(resolveResult.data).toEqual({ + if (!resolveResult.ok) fail(resolveResult.error); + expect(resolveResult.value).toEqual({ cid: `/ipfs/${sampleFileIpfsInfo.hash.toString()}`, provider: providers.ipfs, }); @@ -236,8 +236,8 @@ describe("IPFS Plugin", () => { clientWithBadProvider ); - expect(catResult.error).toBeFalsy(); - expect(catResult.data).toEqual(sampleFileBuffer); + if (!catResult.ok) fail(catResult.error); + expect(catResult.value).toEqual(sampleFileBuffer); const resolveResult = await Ipfs_Module.resolve( { @@ -250,8 +250,8 @@ describe("IPFS Plugin", () => { clientWithBadProvider ); - expect(resolveResult.error).toBeFalsy(); - expect(resolveResult.data).toEqual({ + if (!resolveResult.ok) fail(resolveResult.error); + expect(resolveResult.value).toEqual({ cid: `/ipfs/${sampleFileIpfsInfo.hash.toString()}`, provider: providers.ipfs, }); diff --git a/packages/js/plugins/logger/src/__tests__/e2e/e2e.spec.ts b/packages/js/plugins/logger/src/__tests__/e2e/e2e.spec.ts index 90aaf76cad..889e5e9b06 100644 --- a/packages/js/plugins/logger/src/__tests__/e2e/e2e.spec.ts +++ b/packages/js/plugins/logger/src/__tests__/e2e/e2e.spec.ts @@ -13,8 +13,8 @@ describe("log method", () => { }, }); - expect(response.error).toBeUndefined(); - expect(response.data).toBeDefined(); - expect(response.data).toBe(true); + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); + expect(response.value).toBe(true); }); }); diff --git a/packages/js/plugins/uri-resolvers/file-system-resolver/src/__tests__/e2e.spec.ts b/packages/js/plugins/uri-resolvers/file-system-resolver/src/__tests__/e2e.spec.ts index 98cf2150d0..87eef4dfda 100644 --- a/packages/js/plugins/uri-resolvers/file-system-resolver/src/__tests__/e2e.spec.ts +++ b/packages/js/plugins/uri-resolvers/file-system-resolver/src/__tests__/e2e.spec.ts @@ -95,25 +95,26 @@ describe("Filesystem plugin", () => { }, }); - expect(deploy.error).toBeFalsy(); - expect(deploy.data).toBeTruthy(); - expect(deploy.data?.indexOf("0x")).toBeGreaterThan(-1); + if (!deploy.ok) fail(deploy.error); + expect(deploy.value).toBeTruthy(); + expect(deploy.value.indexOf("0x")).toBeGreaterThan(-1); // get the manifest const manifest = await client.getManifest(fsUri); - expect(manifest).toBeTruthy(); - expect(manifest.version).toBe("0.1"); - expect(manifest.type).toEqual("wasm"); + if (!manifest.ok) fail(manifest.error); + expect(manifest.value.version).toBe("0.1"); + expect(manifest.value.type).toEqual("wasm"); // get a file const file = await client.getFile(fsUri, { path: "wrap.info", }); + if (!file.ok) fail(file.error); const expectedFile = await fs.promises.readFile(`${fsPath}/wrap.info`); const expectedInfo = Uint8Array.from(expectedFile); - expect(file).toStrictEqual(expectedInfo); + expect(file.value).toStrictEqual(expectedInfo); }); }); diff --git a/packages/js/plugins/uri-resolvers/ipfs-resolver/src/__tests__/e2e.spec.ts b/packages/js/plugins/uri-resolvers/ipfs-resolver/src/__tests__/e2e.spec.ts index 8d84538e01..d99a560248 100644 --- a/packages/js/plugins/uri-resolvers/ipfs-resolver/src/__tests__/e2e.spec.ts +++ b/packages/js/plugins/uri-resolvers/ipfs-resolver/src/__tests__/e2e.spec.ts @@ -12,6 +12,7 @@ import { ipfsPlugin } from "@polywrap/ipfs-plugin-js"; import { IpfsClient } from "./helpers/IpfsClient"; import { createIpfsClient } from "./helpers/createIpfsClient"; import { Result } from "@polywrap/core-js"; +import { ResultOk } from "@polywrap/result"; jest.setTimeout(300000); @@ -92,10 +93,7 @@ describe("IPFS Plugin", () => { ): Promise> => { return new Promise>((resolve) => setTimeout(() => { - resolve({ - data: Uint8Array.from([1, 2, 3, 4]), - error: undefined, - }); + resolve(ResultOk(Uint8Array.from([1, 2, 3, 4]))); }, timeout) ); }; @@ -128,8 +126,15 @@ describe("IPFS Plugin", () => { slowerRacePromise, ]); - expect(fasterRaceResult.data).toStrictEqual((await fasterRacePromise).data); - expect(slowerRaceResult.data).toStrictEqual((await getFilePromise).data); + if (!fasterRaceResult.ok) fail(fasterRaceResult.error); + const expectedFasterResult = await fasterRacePromise; + if (!expectedFasterResult.ok) fail(expectedFasterResult.error) + expect(fasterRaceResult.value).toStrictEqual(expectedFasterResult.value); + + if (!slowerRaceResult.ok) fail(slowerRaceResult.error); + const expectedSlowerResult = await getFilePromise; + if (!expectedSlowerResult.ok) fail(expectedSlowerResult.error); + expect(slowerRaceResult.value).toStrictEqual(expectedSlowerResult.value); }; const timeout = 1000; @@ -187,8 +192,15 @@ describe("IPFS Plugin", () => { slowerRacePromise, ]); - expect(fasterRaceResult.data).toStrictEqual((await fasterRacePromise).data); - expect(slowerRaceResult.data).toStrictEqual((await getFilePromise).data); + if (!fasterRaceResult.ok) fail(fasterRaceResult.error); + const expectedFasterResult = await fasterRacePromise; + if (!expectedFasterResult.ok) fail(expectedFasterResult.error) + expect(fasterRaceResult.value).toStrictEqual(expectedFasterResult.value); + + if (!slowerRaceResult.ok) fail(slowerRaceResult.error); + const expectedSlowerResult = await getFilePromise; + if (!expectedSlowerResult.ok) fail(expectedSlowerResult.error); + expect(slowerRaceResult.value).toStrictEqual(expectedSlowerResult.value); }; const timeout = 1000; diff --git a/packages/js/plugins/ws/src/__tests__/e2e/e2e.spec.ts b/packages/js/plugins/ws/src/__tests__/e2e/e2e.spec.ts index df8e969fd9..f3c3c00140 100644 --- a/packages/js/plugins/ws/src/__tests__/e2e/e2e.spec.ts +++ b/packages/js/plugins/ws/src/__tests__/e2e/e2e.spec.ts @@ -75,19 +75,20 @@ describe("WebSocket plugin", () => { }); it("should close a websocket connection", async () => { - const { data: id } = await polywrapClient.invoke({ + const result = await polywrapClient.invoke({ uri: "wrap://ens/ws.polywrap.eth", method: "open", args: { url: "ws://localhost:1234" } }) + if (!result.ok) fail(result.error); await polywrapClient.invoke({ uri: "wrap://ens/ws.polywrap.eth", method: "close", args: { - id + id: result.value } }) @@ -106,19 +107,20 @@ describe("WebSocket plugin", () => { it("should send a message to the server", async () => { - const { data: id } = await polywrapClient.invoke({ + const result = await polywrapClient.invoke({ uri: "wrap://ens/ws.polywrap.eth", method: "open", args: { url: "ws://localhost:1234" } }) + if (!result.ok) fail(result.error); await polywrapClient.invoke({ uri: "wrap://ens/ws.polywrap.eth", method: "send", args: { - id, + id: result.value, message: "test" } }) @@ -175,19 +177,20 @@ describe("WebSocket plugin", () => { it("should pass messages to a callback", async () => { - const { data: id } = await polywrapClient.invoke({ + const result = await polywrapClient.invoke({ uri: "wrap://ens/ws.polywrap.eth", method: "open", args: { url: "ws://localhost:1234" } }) + if (!result.ok) fail(result.error); await polywrapClient.invoke({ uri: "wrap://ens/ws.polywrap.eth", method: "addCallback", args: { - id, + id: result.value, callback: { uri: "wrap://ens/stub.polywrap.eth", method: "callback" @@ -201,19 +204,20 @@ describe("WebSocket plugin", () => { }); it("should remove callback", async () => { - const { data: id } = await polywrapClient.invoke({ + const result = await polywrapClient.invoke({ uri: "wrap://ens/ws.polywrap.eth", method: "open", args: { url: "ws://localhost:1234" } }) + if (!result.ok) fail(result.error); await polywrapClient.invoke({ uri: "wrap://ens/ws.polywrap.eth", method: "addCallback", args: { - id, + id: result.value, callback: { uri: "wrap://ens/stub.polywrap.eth", method: "callback" @@ -226,7 +230,7 @@ describe("WebSocket plugin", () => { uri: "wrap://ens/ws.polywrap.eth", method: "removeCallback", args: { - id, + id: result.value, callback: { uri: "wrap://ens/stub.polywrap.eth", method: "callback" @@ -253,19 +257,20 @@ describe("WebSocket plugin", () => { it("should receive a message", async () => { - const { data: id } = await polywrapClient.invoke({ + const result = await polywrapClient.invoke({ uri: "wrap://ens/ws.polywrap.eth", method: "open", args: { url: "ws://localhost:1234" } }) + if (!result.ok) fail(result.error); await polywrapClient.invoke({ uri: "wrap://ens/ws.polywrap.eth", method: "addCache", args: { - id + id: result.value } }) @@ -275,28 +280,30 @@ describe("WebSocket plugin", () => { uri: "wrap://ens/ws.polywrap.eth", method: "receive", args: { - id + id: result.value } }) + if (!response.ok) fail(response.error); - let data = response?.data?.map((msg) => msg.data) + let data = response.value.map((msg) => msg.data) expect(data).toEqual(["1", "2"]); }); it("should remove cache callback", async () => { - const { data: id } = await polywrapClient.invoke({ + const result = await polywrapClient.invoke({ uri: "wrap://ens/ws.polywrap.eth", method: "open", args: { url: "ws://localhost:1234" } }) + if (!result.ok) fail(result.error); await polywrapClient.invoke({ uri: "wrap://ens/ws.polywrap.eth", method: "addCache", args: { - id + id: result.value } }) @@ -305,7 +312,7 @@ describe("WebSocket plugin", () => { uri: "wrap://ens/ws.polywrap.eth", method: "removeCache", args: { - id + id: result.value } }) resolve() @@ -317,28 +324,30 @@ describe("WebSocket plugin", () => { uri: "wrap://ens/ws.polywrap.eth", method: "receive", args: { - id + id: result.value } }) - let data = response?.data?.map((msg) => msg.data) + if (!response.ok) fail(response.error); + let data = response.value.map((msg) => msg.data) expect(data).toEqual(["1", "2"]); }); it("should receive messages when a timeout is reached", async () => { - const { data: id } = await polywrapClient.invoke({ + const result = await polywrapClient.invoke({ uri: "wrap://ens/ws.polywrap.eth", method: "open", args: { url: "ws://localhost:1234" } }) + if (!result.ok) fail(result.error); await polywrapClient.invoke({ uri: "wrap://ens/ws.polywrap.eth", method: "addCache", args: { - id + id: result.value } }) @@ -346,30 +355,31 @@ describe("WebSocket plugin", () => { uri: "wrap://ens/ws.polywrap.eth", method: "receive", args: { - id, + id: result.value, timeout: 250 } }) - - let data = response?.data?.map((msg) => msg.data) + if (!response.ok) fail(response.error); + let data = response.value.map((msg) => msg.data) expect(data).toEqual(["1", "2"]); }); it("should receive messages when min is reached", async () => { - const { data: id } = await polywrapClient.invoke({ + const result = await polywrapClient.invoke({ uri: "wrap://ens/ws.polywrap.eth", method: "open", args: { url: "ws://localhost:1234" } }) + if (!result.ok) fail(result.error); await polywrapClient.invoke({ uri: "wrap://ens/ws.polywrap.eth", method: "addCache", args: { - id + id: result.value } }) @@ -377,29 +387,31 @@ describe("WebSocket plugin", () => { uri: "wrap://ens/ws.polywrap.eth", method: "receive", args: { - id, + id: result.value, min: 2 } }) - let data = response?.data?.map((msg) => msg.data) + if (!response.ok) fail(response.error); + let data = response.value.map((msg) => msg.data) expect(data).toEqual(["1", "2"]); }); it("should reach timeout before min", async () => { - const { data: id } = await polywrapClient.invoke({ + const result = await polywrapClient.invoke({ uri: "wrap://ens/ws.polywrap.eth", method: "open", args: { url: "ws://localhost:1234" } }) + if (!result.ok) fail(result.error); await polywrapClient.invoke({ uri: "wrap://ens/ws.polywrap.eth", method: "addCache", args: { - id + id: result.value } }) @@ -407,30 +419,32 @@ describe("WebSocket plugin", () => { uri: "wrap://ens/ws.polywrap.eth", method: "receive", args: { - id, + id: result.value, timeout: 110, min: 2 } }) - let data = response?.data?.map((msg) => msg.data) + if (!response.ok) fail(response.error); + let data = response.value.map((msg) => msg.data) expect(data).toEqual(["1"]); }); it("should reach min before timeout", async () => { - const { data: id } = await polywrapClient.invoke({ + const result = await polywrapClient.invoke({ uri: "wrap://ens/ws.polywrap.eth", method: "open", args: { url: "ws://localhost:1234" } }) + if (!result.ok) fail(result.error); await polywrapClient.invoke({ uri: "wrap://ens/ws.polywrap.eth", method: "addCache", args: { - id + id: result.value } }) @@ -438,31 +452,33 @@ describe("WebSocket plugin", () => { uri: "wrap://ens/ws.polywrap.eth", method: "receive", args: { - id, + id: result.value, timeout: 300, min: 1 } }) - let data = response?.data?.map((msg) => msg.data) + if (!response.ok) fail(response.error); + let data = response.value.map((msg) => msg.data) expect(data).toEqual(["1"]); }); it("should receive messages in batches", async () => { - const { data: id } = await polywrapClient.invoke({ + const result = await polywrapClient.invoke({ uri: "wrap://ens/ws.polywrap.eth", method: "open", args: { url: "ws://localhost:1234" } }) + if (!result.ok) fail(result.error); await polywrapClient.invoke({ uri: "wrap://ens/ws.polywrap.eth", method: "addCache", args: { - id + id: result.value } }) @@ -472,7 +488,7 @@ describe("WebSocket plugin", () => { uri: "wrap://ens/ws.polywrap.eth", method: "receive", args: { - id + id: result.value } }) @@ -482,7 +498,7 @@ describe("WebSocket plugin", () => { uri: "wrap://ens/ws.polywrap.eth", method: "receive", args: { - id + id: result.value } }) @@ -492,17 +508,20 @@ describe("WebSocket plugin", () => { uri: "wrap://ens/ws.polywrap.eth", method: "receive", args: { - id + id: result.value } }) - let data1 = response1?.data?.map((msg) => msg.data) + if (!response1.ok) fail(response1.error); + let data1 = response1.value.map((msg) => msg.data) expect(data1).toEqual(["1", "2"]); - let data2 = response2?.data?.map((msg) => msg.data) + if (!response2.ok) fail(response2.error); + let data2 = response2.value.map((msg) => msg.data) expect(data2).toEqual(["3"]); - let data3 = response3?.data?.map((msg) => msg.data) + if (!response3.ok) fail(response3.error); + let data3 = response3.value.map((msg) => msg.data) expect(data3).toEqual([]); }); }); diff --git a/packages/js/plugins/ws/src/__tests__/e2e/integration.spec.ts b/packages/js/plugins/ws/src/__tests__/e2e/integration.spec.ts index 4578dddeda..d1efdcca64 100644 --- a/packages/js/plugins/ws/src/__tests__/e2e/integration.spec.ts +++ b/packages/js/plugins/ws/src/__tests__/e2e/integration.spec.ts @@ -170,8 +170,9 @@ describe("e2e tests for WsPlugin", () => { timeout: 20 } }); + if (!response.ok) fail(response.error); - expect(response.data).toEqual(["1","2"]) + expect(response.value).toEqual(["1","2"]) clearTimeout(t1) clearTimeout(t2) From 095b9c7974a32b8f5f32b89af6e220b8302cdfae Mon Sep 17 00:00:00 2001 From: krisbitney Date: Mon, 26 Sep 2022 09:20:48 +0500 Subject: [PATCH 10/25] cli tests passing --- packages/js/client/src/PolywrapClient.ts | 2 ++ .../plugin/codegen/002-single-module/expected/wrap/types.ts | 2 +- .../plugin/codegen/005-custom-config/expected/wrap/types.ts | 4 ++-- .../codegen/006-custom-manifest-file/expected/wrap/types.ts | 6 +++--- 4 files changed, 8 insertions(+), 6 deletions(-) diff --git a/packages/js/client/src/PolywrapClient.ts b/packages/js/client/src/PolywrapClient.ts index 244f414643..3d9b6fc7db 100644 --- a/packages/js/client/src/PolywrapClient.ts +++ b/packages/js/client/src/PolywrapClient.ts @@ -667,6 +667,8 @@ export class PolywrapClient implements Client { if (!result.ok) { if (result.error && result.error instanceof Error) { return result as Result; + } else if (result.error && typeof result.error === "string") { + return ResultErr(Error(result.error)); } else { const error = Error( `Error resolving URI "${uri.uri}"\nResolution Stack: ${JSON.stringify( diff --git a/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/types.ts index de183960bc..6c3d27e56c 100644 --- a/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/types.ts +++ b/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/types.ts @@ -358,7 +358,7 @@ export const Ethereum_Module = { callContractStatic: async ( args: Ethereum_Module_Args_callContractStatic, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractStatic", diff --git a/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/types.ts index faaf617500..6c3d27e56c 100644 --- a/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/types.ts +++ b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/types.ts @@ -567,7 +567,7 @@ export const Ethereum_Module = { requestAccounts: async ( args: Ethereum_Module_Args_requestAccounts, client: Client - ): Promise>> => { + ): Promise, Error>> => { return client.invoke>({ uri: "ens/ethereum.polywrap.eth", method: "requestAccounts", @@ -644,7 +644,7 @@ export const Ethereum_Module = { sendRPC: async ( args: Ethereum_Module_Args_sendRPC, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "sendRPC", diff --git a/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/types.ts index 4286dc22f0..6c3d27e56c 100644 --- a/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/types.ts +++ b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/types.ts @@ -7,7 +7,7 @@ import * as Types from "./"; // @ts-ignore import { Client, - InvokeResult + Result } from "@polywrap/core-js"; export type UInt = number; @@ -567,7 +567,7 @@ export const Ethereum_Module = { requestAccounts: async ( args: Ethereum_Module_Args_requestAccounts, client: Client - ): Promise>> => { + ): Promise, Error>> => { return client.invoke>({ uri: "ens/ethereum.polywrap.eth", method: "requestAccounts", @@ -644,7 +644,7 @@ export const Ethereum_Module = { sendRPC: async ( args: Ethereum_Module_Args_sendRPC, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "sendRPC", From ca102821837155a6b78d6c3b7b5b230295e9ece9 Mon Sep 17 00:00:00 2001 From: krisbitney Date: Mon, 26 Sep 2022 10:20:51 +0500 Subject: [PATCH 11/25] fix for Result type in some Ethereum plugin tests --- .../ethereum/src/__tests__/e2e.spec.ts | 45 ++++++++++++------- 1 file changed, 28 insertions(+), 17 deletions(-) diff --git a/packages/js/plugins/ethereum/src/__tests__/e2e.spec.ts b/packages/js/plugins/ethereum/src/__tests__/e2e.spec.ts index a01edfe0f0..538e2a23e2 100644 --- a/packages/js/plugins/ethereum/src/__tests__/e2e.spec.ts +++ b/packages/js/plugins/ethereum/src/__tests__/e2e.spec.ts @@ -140,9 +140,9 @@ describe("Ethereum Plugin", () => { }, }); - expect(response.error).toBeUndefined(); - expect(response.data).toBeDefined(); - const num = ethers.BigNumber.from(response.data); + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); + const num = ethers.BigNumber.from(response.value); expect(num.eq("100")).toBeTruthy(); }); @@ -160,9 +160,9 @@ describe("Ethereum Plugin", () => { }, }); - expect(response.error).toBeUndefined(); - expect(response.data).toBeDefined(); - const num = ethers.BigNumber.from(response.data); + if (!response.ok) fail(response.error); + expect(response.value).toBeDefined(); + const num = ethers.BigNumber.from(response.value); expect(num.eq("100")).toBeTruthy(); }); @@ -181,10 +181,12 @@ describe("Ethereum Plugin", () => { }, }); - if (!response.data) { + if (!response.ok) fail(response.error); + + if (!response.value) { throw new Error('Empty data on view call, expecting JSON'); } - const result = JSON.parse(response.data); + const result = JSON.parse(response.value); expect(result.length).toEqual(2); expect(result[0]).toEqual("100"); @@ -206,10 +208,12 @@ describe("Ethereum Plugin", () => { }, }); - if (!response.data) { + if (!response.ok) fail(response.error); + + if (!response.value) { throw new Error('Empty data on view call, expecting JSON'); } - const result = JSON.parse(response.data); + const result = JSON.parse(response.value); expect(result.length).toEqual(2); expect(result[0]).toEqual("100"); @@ -231,10 +235,12 @@ describe("Ethereum Plugin", () => { }, }); - if (!response.data) { + if (!response.ok) fail(response.error); + + if (!response.value) { throw new Error('Empty data on view call, expecting JSON'); } - const result = JSON.parse(response.data); + const result = JSON.parse(response.value); expect(result.length).toEqual(2); expect(result[0]).toEqual("100"); @@ -254,7 +260,8 @@ describe("Ethereum Plugin", () => { }, }); - expect(response.data).toEqual('[]'); + if (!response.ok) fail(response.error); + expect(response.value).toEqual('[]'); }); it("callContractView (struct array single element)", async () => { @@ -271,10 +278,12 @@ describe("Ethereum Plugin", () => { }, }); - if (!response.data) { + if (!response.ok) fail(response.error); + + if (!response.value) { throw new Error('Empty data on view call, expecting JSON'); } - const result = JSON.parse(response.data); + const result = JSON.parse(response.value); expect(result.length).toEqual(1); expect(result[0].to).toEqual(queueAddress); @@ -296,10 +305,12 @@ describe("Ethereum Plugin", () => { }, }); - if (!response.data) { + if (!response.ok) fail(response.error); + + if (!response.value) { throw new Error('Empty data on view call, expecting JSON'); } - const result = JSON.parse(response.data); + const result = JSON.parse(response.value); expect(result.length).toEqual(2); expect(result[0].to).toEqual(queueAddress); From fa6c52dbe18c9ff225582113210652f655481017 Mon Sep 17 00:00:00 2001 From: dOrgJelli Date: Mon, 26 Sep 2022 12:03:08 +0200 Subject: [PATCH 12/25] fix: link schema packages to dep cli --- package.json | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 735b03424e..9d4570cd43 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,7 @@ "clean": "npx rimraf ./**/node_modules ./**/yarn.lock ./**/build ./**/coverage ./**/.polywrap", "dependencies:install": "cd dependencies && yarn", "preinstall": "yarn dependencies:install", - "build": "yarn build:core && yarn build:interfaces && yarn build:plugins && yarn build:resolver:plugins && yarn build:config && yarn build:client && yarn build:test-env && yarn build:cli", + "build": "yarn build:core && yarn link:schema && yarn build:interfaces && yarn build:plugins && yarn build:resolver:plugins && yarn build:config && yarn build:client && yarn build:test-env && yarn build:cli", "build:core": "lerna run build --no-private --ignore @polywrap/*-plugin-js --ignore @polywrap/client-config-builder-js --ignore polywrap --ignore @polywrap/client-js --ignore @polywrap/react --ignore @polywrap/test-env-js --ignore @polywrap/*-interface", "build:interfaces": "lerna run build --scope @polywrap/*-interface", "build:plugins": "lerna run build --scope @polywrap/*-plugin-js --ignore @polywrap/*-resolver-plugin-js", @@ -38,9 +38,10 @@ "link:manifests": "yarn link:manifests:polywrap && yarn link:manifests:wrap", "link:manifests:polywrap": "cd packages/js/manifests/polywrap && (yarn unlink || true) && yarn link && cd ../../../../dependencies && yarn link @polywrap/polywrap-manifest-types-js && cd ../", "link:manifests:wrap": "cd packages/js/manifests/wrap && (yarn unlink || true) && yarn link && cd ../../../../dependencies && yarn link @polywrap/wrap-manifest-types-js && cd ../", - "link:schema": "yarn link:schema:parse && yarn link:schema:compose", + "link:schema": "yarn link:schema:parse && yarn link:schema:compose && yarn link:schema:bind", "link:schema:parse": "cd packages/schema/parse && (yarn unlink || true) && yarn link && cd ../../../dependencies && yarn link @polywrap/schema-parse && cd ../", "link:schema:compose": "cd packages/schema/compose && (yarn unlink || true) && yarn link && cd ../../../dependencies && yarn link @polywrap/schema-compose && cd ../", + "link:schema:bind": "cd packages/schema/bind && (yarn unlink || true) && yarn link && cd ../../../dependencies && yarn link @polywrap/schema-bind && cd ../", "lint": "lerna run lint", "lint:fix": "lerna run lint -- --fix", "lint:ci": "yarn lint", From c20c6dea1fe5468cdc7927f8c4f849d801a96b7f Mon Sep 17 00:00:00 2001 From: dOrgJelli Date: Mon, 26 Sep 2022 21:58:05 +0200 Subject: [PATCH 13/25] chore: use InvokeResult instead of Result --- packages/js/core/src/types/Invoke.ts | 16 +++-- .../app/templates/types-ts.mustache | 4 +- .../plugin/templates/types-ts.mustache | 7 ++- .../codegen/001-sanity/expected/wrap/types.ts | 59 ++++++++++--------- .../002-single-module/expected/wrap/types.ts | 59 ++++++++++--------- .../codegen/003-env/expected/wrap/types.ts | 3 +- .../expected/wrap/types.ts | 3 +- .../005-custom-config/expected/wrap/types.ts | 59 ++++++++++--------- .../expected/wrap/types.ts | 59 ++++++++++--------- 9 files changed, 141 insertions(+), 128 deletions(-) diff --git a/packages/js/core/src/types/Invoke.ts b/packages/js/core/src/types/Invoke.ts index 6d690595d5..7a352de06b 100644 --- a/packages/js/core/src/types/Invoke.ts +++ b/packages/js/core/src/types/Invoke.ts @@ -38,6 +38,13 @@ export interface InvokeOptions< contextId?: string; } +/** + * Result of an Wrapper invocation. + * + * @template TData Type of the invoke result data. + */ +export type InvokeResult = Result; + export interface InvokerOptions< TUri extends Uri | string = string, TClientConfig extends ClientConfig = ClientConfig @@ -48,16 +55,15 @@ export interface InvokerOptions< export interface Invoker { invokeWrapper( options: InvokerOptions & { wrapper: Wrapper } - ): Promise>; + ): Promise>; invoke( options: InvokerOptions - ): Promise>; + ): Promise>; } -export interface InvocableResult { - data: Result; +export type InvocableResult = InvokeResult & { encoded?: boolean; -} +}; export interface Invocable { invoke( diff --git a/packages/schema/bind/src/bindings/typescript/app/templates/types-ts.mustache b/packages/schema/bind/src/bindings/typescript/app/templates/types-ts.mustache index b57c90cfb5..f02416fdc8 100644 --- a/packages/schema/bind/src/bindings/typescript/app/templates/types-ts.mustache +++ b/packages/schema/bind/src/bindings/typescript/app/templates/types-ts.mustache @@ -4,7 +4,7 @@ import * as Types from "./"; // @ts-ignore import { Client, - Result + InvokeResult } from "@polywrap/core-js"; export type UInt = number; @@ -102,7 +102,7 @@ export const {{type}} = { args: {{parent.type}}_Args_{{name}}, client: Client, uri: string = "{{parent.uri}}" - ): Promise> => { + ): Promise> => { return client.invoke<{{#return}}{{#toTypescript}}{{toGraphQLType}}{{/toTypescript}}{{/return}}>({ uri, method: "{{name}}", diff --git a/packages/schema/bind/src/bindings/typescript/plugin/templates/types-ts.mustache b/packages/schema/bind/src/bindings/typescript/plugin/templates/types-ts.mustache index 6e5817f97d..4dd80956b5 100644 --- a/packages/schema/bind/src/bindings/typescript/plugin/templates/types-ts.mustache +++ b/packages/schema/bind/src/bindings/typescript/plugin/templates/types-ts.mustache @@ -7,7 +7,8 @@ import * as Types from "./"; // @ts-ignore import { Client, - Result + Result, + InvokeResult } from "@polywrap/core-js"; export type UInt = number; @@ -112,7 +113,7 @@ export const {{type}} = { {{name}}: async ( args: {{parent.type}}_Args_{{name}}, client: Client - ): Promise> => { + ): Promise> => { return client.invoke<{{#return}}{{#toTypescript}}{{toGraphQLType}}{{/toTypescript}}{{/return}}>({ uri: "{{parent.uri}}", method: "{{name}}", @@ -137,7 +138,7 @@ export class {{#detectKeyword}}{{type}}{{/detectKeyword}} { public async {{name}} ( args: {{parent.type}}_Args_{{name}}, client: Client - ): Promise> { + ): Promise> { return client.invoke<{{#return}}{{#toTypescript}}{{toGraphQLType}}{{/toTypescript}}{{/return}}>({ uri: this.uri, method: "{{name}}", diff --git a/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/wrap/types.ts index 6c3d27e56c..67a72fe7d4 100644 --- a/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/wrap/types.ts +++ b/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/wrap/types.ts @@ -7,7 +7,8 @@ import * as Types from "./"; // @ts-ignore import { Client, - Result + Result, + InvokeResult } from "@polywrap/core-js"; export type UInt = number; @@ -347,7 +348,7 @@ export const Ethereum_Module = { callContractView: async ( args: Ethereum_Module_Args_callContractView, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractView", @@ -358,7 +359,7 @@ export const Ethereum_Module = { callContractStatic: async ( args: Ethereum_Module_Args_callContractStatic, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractStatic", @@ -369,7 +370,7 @@ export const Ethereum_Module = { getBalance: async ( args: Ethereum_Module_Args_getBalance, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getBalance", @@ -380,7 +381,7 @@ export const Ethereum_Module = { encodeParams: async ( args: Ethereum_Module_Args_encodeParams, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "encodeParams", @@ -391,7 +392,7 @@ export const Ethereum_Module = { encodeFunction: async ( args: Ethereum_Module_Args_encodeFunction, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "encodeFunction", @@ -402,7 +403,7 @@ export const Ethereum_Module = { solidityPack: async ( args: Ethereum_Module_Args_solidityPack, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "solidityPack", @@ -413,7 +414,7 @@ export const Ethereum_Module = { solidityKeccak256: async ( args: Ethereum_Module_Args_solidityKeccak256, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "solidityKeccak256", @@ -424,7 +425,7 @@ export const Ethereum_Module = { soliditySha256: async ( args: Ethereum_Module_Args_soliditySha256, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "soliditySha256", @@ -435,7 +436,7 @@ export const Ethereum_Module = { getSignerAddress: async ( args: Ethereum_Module_Args_getSignerAddress, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getSignerAddress", @@ -446,7 +447,7 @@ export const Ethereum_Module = { getSignerBalance: async ( args: Ethereum_Module_Args_getSignerBalance, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getSignerBalance", @@ -457,7 +458,7 @@ export const Ethereum_Module = { getSignerTransactionCount: async ( args: Ethereum_Module_Args_getSignerTransactionCount, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getSignerTransactionCount", @@ -468,7 +469,7 @@ export const Ethereum_Module = { getGasPrice: async ( args: Ethereum_Module_Args_getGasPrice, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getGasPrice", @@ -479,7 +480,7 @@ export const Ethereum_Module = { estimateTransactionGas: async ( args: Ethereum_Module_Args_estimateTransactionGas, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "estimateTransactionGas", @@ -490,7 +491,7 @@ export const Ethereum_Module = { estimateContractCallGas: async ( args: Ethereum_Module_Args_estimateContractCallGas, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "estimateContractCallGas", @@ -501,7 +502,7 @@ export const Ethereum_Module = { checkAddress: async ( args: Ethereum_Module_Args_checkAddress, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "checkAddress", @@ -512,7 +513,7 @@ export const Ethereum_Module = { toWei: async ( args: Ethereum_Module_Args_toWei, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "toWei", @@ -523,7 +524,7 @@ export const Ethereum_Module = { toEth: async ( args: Ethereum_Module_Args_toEth, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "toEth", @@ -534,7 +535,7 @@ export const Ethereum_Module = { awaitTransaction: async ( args: Ethereum_Module_Args_awaitTransaction, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "awaitTransaction", @@ -545,7 +546,7 @@ export const Ethereum_Module = { waitForEvent: async ( args: Ethereum_Module_Args_waitForEvent, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "waitForEvent", @@ -556,7 +557,7 @@ export const Ethereum_Module = { getNetwork: async ( args: Ethereum_Module_Args_getNetwork, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getNetwork", @@ -567,7 +568,7 @@ export const Ethereum_Module = { requestAccounts: async ( args: Ethereum_Module_Args_requestAccounts, client: Client - ): Promise, Error>> => { + ): Promise>> => { return client.invoke>({ uri: "ens/ethereum.polywrap.eth", method: "requestAccounts", @@ -578,7 +579,7 @@ export const Ethereum_Module = { callContractMethod: async ( args: Ethereum_Module_Args_callContractMethod, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractMethod", @@ -589,7 +590,7 @@ export const Ethereum_Module = { callContractMethodAndWait: async ( args: Ethereum_Module_Args_callContractMethodAndWait, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractMethodAndWait", @@ -600,7 +601,7 @@ export const Ethereum_Module = { sendTransaction: async ( args: Ethereum_Module_Args_sendTransaction, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "sendTransaction", @@ -611,7 +612,7 @@ export const Ethereum_Module = { sendTransactionAndWait: async ( args: Ethereum_Module_Args_sendTransactionAndWait, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "sendTransactionAndWait", @@ -622,7 +623,7 @@ export const Ethereum_Module = { deployContract: async ( args: Ethereum_Module_Args_deployContract, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "deployContract", @@ -633,7 +634,7 @@ export const Ethereum_Module = { signMessage: async ( args: Ethereum_Module_Args_signMessage, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "signMessage", @@ -644,7 +645,7 @@ export const Ethereum_Module = { sendRPC: async ( args: Ethereum_Module_Args_sendRPC, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "sendRPC", diff --git a/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/types.ts index 6c3d27e56c..67a72fe7d4 100644 --- a/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/types.ts +++ b/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/types.ts @@ -7,7 +7,8 @@ import * as Types from "./"; // @ts-ignore import { Client, - Result + Result, + InvokeResult } from "@polywrap/core-js"; export type UInt = number; @@ -347,7 +348,7 @@ export const Ethereum_Module = { callContractView: async ( args: Ethereum_Module_Args_callContractView, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractView", @@ -358,7 +359,7 @@ export const Ethereum_Module = { callContractStatic: async ( args: Ethereum_Module_Args_callContractStatic, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractStatic", @@ -369,7 +370,7 @@ export const Ethereum_Module = { getBalance: async ( args: Ethereum_Module_Args_getBalance, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getBalance", @@ -380,7 +381,7 @@ export const Ethereum_Module = { encodeParams: async ( args: Ethereum_Module_Args_encodeParams, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "encodeParams", @@ -391,7 +392,7 @@ export const Ethereum_Module = { encodeFunction: async ( args: Ethereum_Module_Args_encodeFunction, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "encodeFunction", @@ -402,7 +403,7 @@ export const Ethereum_Module = { solidityPack: async ( args: Ethereum_Module_Args_solidityPack, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "solidityPack", @@ -413,7 +414,7 @@ export const Ethereum_Module = { solidityKeccak256: async ( args: Ethereum_Module_Args_solidityKeccak256, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "solidityKeccak256", @@ -424,7 +425,7 @@ export const Ethereum_Module = { soliditySha256: async ( args: Ethereum_Module_Args_soliditySha256, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "soliditySha256", @@ -435,7 +436,7 @@ export const Ethereum_Module = { getSignerAddress: async ( args: Ethereum_Module_Args_getSignerAddress, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getSignerAddress", @@ -446,7 +447,7 @@ export const Ethereum_Module = { getSignerBalance: async ( args: Ethereum_Module_Args_getSignerBalance, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getSignerBalance", @@ -457,7 +458,7 @@ export const Ethereum_Module = { getSignerTransactionCount: async ( args: Ethereum_Module_Args_getSignerTransactionCount, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getSignerTransactionCount", @@ -468,7 +469,7 @@ export const Ethereum_Module = { getGasPrice: async ( args: Ethereum_Module_Args_getGasPrice, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getGasPrice", @@ -479,7 +480,7 @@ export const Ethereum_Module = { estimateTransactionGas: async ( args: Ethereum_Module_Args_estimateTransactionGas, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "estimateTransactionGas", @@ -490,7 +491,7 @@ export const Ethereum_Module = { estimateContractCallGas: async ( args: Ethereum_Module_Args_estimateContractCallGas, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "estimateContractCallGas", @@ -501,7 +502,7 @@ export const Ethereum_Module = { checkAddress: async ( args: Ethereum_Module_Args_checkAddress, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "checkAddress", @@ -512,7 +513,7 @@ export const Ethereum_Module = { toWei: async ( args: Ethereum_Module_Args_toWei, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "toWei", @@ -523,7 +524,7 @@ export const Ethereum_Module = { toEth: async ( args: Ethereum_Module_Args_toEth, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "toEth", @@ -534,7 +535,7 @@ export const Ethereum_Module = { awaitTransaction: async ( args: Ethereum_Module_Args_awaitTransaction, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "awaitTransaction", @@ -545,7 +546,7 @@ export const Ethereum_Module = { waitForEvent: async ( args: Ethereum_Module_Args_waitForEvent, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "waitForEvent", @@ -556,7 +557,7 @@ export const Ethereum_Module = { getNetwork: async ( args: Ethereum_Module_Args_getNetwork, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getNetwork", @@ -567,7 +568,7 @@ export const Ethereum_Module = { requestAccounts: async ( args: Ethereum_Module_Args_requestAccounts, client: Client - ): Promise, Error>> => { + ): Promise>> => { return client.invoke>({ uri: "ens/ethereum.polywrap.eth", method: "requestAccounts", @@ -578,7 +579,7 @@ export const Ethereum_Module = { callContractMethod: async ( args: Ethereum_Module_Args_callContractMethod, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractMethod", @@ -589,7 +590,7 @@ export const Ethereum_Module = { callContractMethodAndWait: async ( args: Ethereum_Module_Args_callContractMethodAndWait, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractMethodAndWait", @@ -600,7 +601,7 @@ export const Ethereum_Module = { sendTransaction: async ( args: Ethereum_Module_Args_sendTransaction, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "sendTransaction", @@ -611,7 +612,7 @@ export const Ethereum_Module = { sendTransactionAndWait: async ( args: Ethereum_Module_Args_sendTransactionAndWait, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "sendTransactionAndWait", @@ -622,7 +623,7 @@ export const Ethereum_Module = { deployContract: async ( args: Ethereum_Module_Args_deployContract, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "deployContract", @@ -633,7 +634,7 @@ export const Ethereum_Module = { signMessage: async ( args: Ethereum_Module_Args_signMessage, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "signMessage", @@ -644,7 +645,7 @@ export const Ethereum_Module = { sendRPC: async ( args: Ethereum_Module_Args_sendRPC, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "sendRPC", diff --git a/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/wrap/types.ts index 3d6d6f6713..b069eec20f 100644 --- a/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/wrap/types.ts +++ b/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/wrap/types.ts @@ -7,7 +7,8 @@ import * as Types from "./"; // @ts-ignore import { Client, - Result + Result, + InvokeResult } from "@polywrap/core-js"; export type UInt = number; diff --git a/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/wrap/types.ts index 8701cb2b8d..b6564471ee 100644 --- a/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/wrap/types.ts +++ b/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/wrap/types.ts @@ -7,7 +7,8 @@ import * as Types from "./"; // @ts-ignore import { Client, - Result + Result, + InvokeResult } from "@polywrap/core-js"; export type UInt = number; diff --git a/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/types.ts index 6c3d27e56c..67a72fe7d4 100644 --- a/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/types.ts +++ b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/types.ts @@ -7,7 +7,8 @@ import * as Types from "./"; // @ts-ignore import { Client, - Result + Result, + InvokeResult } from "@polywrap/core-js"; export type UInt = number; @@ -347,7 +348,7 @@ export const Ethereum_Module = { callContractView: async ( args: Ethereum_Module_Args_callContractView, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractView", @@ -358,7 +359,7 @@ export const Ethereum_Module = { callContractStatic: async ( args: Ethereum_Module_Args_callContractStatic, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractStatic", @@ -369,7 +370,7 @@ export const Ethereum_Module = { getBalance: async ( args: Ethereum_Module_Args_getBalance, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getBalance", @@ -380,7 +381,7 @@ export const Ethereum_Module = { encodeParams: async ( args: Ethereum_Module_Args_encodeParams, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "encodeParams", @@ -391,7 +392,7 @@ export const Ethereum_Module = { encodeFunction: async ( args: Ethereum_Module_Args_encodeFunction, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "encodeFunction", @@ -402,7 +403,7 @@ export const Ethereum_Module = { solidityPack: async ( args: Ethereum_Module_Args_solidityPack, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "solidityPack", @@ -413,7 +414,7 @@ export const Ethereum_Module = { solidityKeccak256: async ( args: Ethereum_Module_Args_solidityKeccak256, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "solidityKeccak256", @@ -424,7 +425,7 @@ export const Ethereum_Module = { soliditySha256: async ( args: Ethereum_Module_Args_soliditySha256, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "soliditySha256", @@ -435,7 +436,7 @@ export const Ethereum_Module = { getSignerAddress: async ( args: Ethereum_Module_Args_getSignerAddress, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getSignerAddress", @@ -446,7 +447,7 @@ export const Ethereum_Module = { getSignerBalance: async ( args: Ethereum_Module_Args_getSignerBalance, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getSignerBalance", @@ -457,7 +458,7 @@ export const Ethereum_Module = { getSignerTransactionCount: async ( args: Ethereum_Module_Args_getSignerTransactionCount, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getSignerTransactionCount", @@ -468,7 +469,7 @@ export const Ethereum_Module = { getGasPrice: async ( args: Ethereum_Module_Args_getGasPrice, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getGasPrice", @@ -479,7 +480,7 @@ export const Ethereum_Module = { estimateTransactionGas: async ( args: Ethereum_Module_Args_estimateTransactionGas, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "estimateTransactionGas", @@ -490,7 +491,7 @@ export const Ethereum_Module = { estimateContractCallGas: async ( args: Ethereum_Module_Args_estimateContractCallGas, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "estimateContractCallGas", @@ -501,7 +502,7 @@ export const Ethereum_Module = { checkAddress: async ( args: Ethereum_Module_Args_checkAddress, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "checkAddress", @@ -512,7 +513,7 @@ export const Ethereum_Module = { toWei: async ( args: Ethereum_Module_Args_toWei, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "toWei", @@ -523,7 +524,7 @@ export const Ethereum_Module = { toEth: async ( args: Ethereum_Module_Args_toEth, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "toEth", @@ -534,7 +535,7 @@ export const Ethereum_Module = { awaitTransaction: async ( args: Ethereum_Module_Args_awaitTransaction, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "awaitTransaction", @@ -545,7 +546,7 @@ export const Ethereum_Module = { waitForEvent: async ( args: Ethereum_Module_Args_waitForEvent, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "waitForEvent", @@ -556,7 +557,7 @@ export const Ethereum_Module = { getNetwork: async ( args: Ethereum_Module_Args_getNetwork, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getNetwork", @@ -567,7 +568,7 @@ export const Ethereum_Module = { requestAccounts: async ( args: Ethereum_Module_Args_requestAccounts, client: Client - ): Promise, Error>> => { + ): Promise>> => { return client.invoke>({ uri: "ens/ethereum.polywrap.eth", method: "requestAccounts", @@ -578,7 +579,7 @@ export const Ethereum_Module = { callContractMethod: async ( args: Ethereum_Module_Args_callContractMethod, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractMethod", @@ -589,7 +590,7 @@ export const Ethereum_Module = { callContractMethodAndWait: async ( args: Ethereum_Module_Args_callContractMethodAndWait, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractMethodAndWait", @@ -600,7 +601,7 @@ export const Ethereum_Module = { sendTransaction: async ( args: Ethereum_Module_Args_sendTransaction, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "sendTransaction", @@ -611,7 +612,7 @@ export const Ethereum_Module = { sendTransactionAndWait: async ( args: Ethereum_Module_Args_sendTransactionAndWait, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "sendTransactionAndWait", @@ -622,7 +623,7 @@ export const Ethereum_Module = { deployContract: async ( args: Ethereum_Module_Args_deployContract, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "deployContract", @@ -633,7 +634,7 @@ export const Ethereum_Module = { signMessage: async ( args: Ethereum_Module_Args_signMessage, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "signMessage", @@ -644,7 +645,7 @@ export const Ethereum_Module = { sendRPC: async ( args: Ethereum_Module_Args_sendRPC, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "sendRPC", diff --git a/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/types.ts index 6c3d27e56c..67a72fe7d4 100644 --- a/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/types.ts +++ b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/types.ts @@ -7,7 +7,8 @@ import * as Types from "./"; // @ts-ignore import { Client, - Result + Result, + InvokeResult } from "@polywrap/core-js"; export type UInt = number; @@ -347,7 +348,7 @@ export const Ethereum_Module = { callContractView: async ( args: Ethereum_Module_Args_callContractView, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractView", @@ -358,7 +359,7 @@ export const Ethereum_Module = { callContractStatic: async ( args: Ethereum_Module_Args_callContractStatic, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractStatic", @@ -369,7 +370,7 @@ export const Ethereum_Module = { getBalance: async ( args: Ethereum_Module_Args_getBalance, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getBalance", @@ -380,7 +381,7 @@ export const Ethereum_Module = { encodeParams: async ( args: Ethereum_Module_Args_encodeParams, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "encodeParams", @@ -391,7 +392,7 @@ export const Ethereum_Module = { encodeFunction: async ( args: Ethereum_Module_Args_encodeFunction, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "encodeFunction", @@ -402,7 +403,7 @@ export const Ethereum_Module = { solidityPack: async ( args: Ethereum_Module_Args_solidityPack, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "solidityPack", @@ -413,7 +414,7 @@ export const Ethereum_Module = { solidityKeccak256: async ( args: Ethereum_Module_Args_solidityKeccak256, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "solidityKeccak256", @@ -424,7 +425,7 @@ export const Ethereum_Module = { soliditySha256: async ( args: Ethereum_Module_Args_soliditySha256, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "soliditySha256", @@ -435,7 +436,7 @@ export const Ethereum_Module = { getSignerAddress: async ( args: Ethereum_Module_Args_getSignerAddress, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getSignerAddress", @@ -446,7 +447,7 @@ export const Ethereum_Module = { getSignerBalance: async ( args: Ethereum_Module_Args_getSignerBalance, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getSignerBalance", @@ -457,7 +458,7 @@ export const Ethereum_Module = { getSignerTransactionCount: async ( args: Ethereum_Module_Args_getSignerTransactionCount, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getSignerTransactionCount", @@ -468,7 +469,7 @@ export const Ethereum_Module = { getGasPrice: async ( args: Ethereum_Module_Args_getGasPrice, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getGasPrice", @@ -479,7 +480,7 @@ export const Ethereum_Module = { estimateTransactionGas: async ( args: Ethereum_Module_Args_estimateTransactionGas, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "estimateTransactionGas", @@ -490,7 +491,7 @@ export const Ethereum_Module = { estimateContractCallGas: async ( args: Ethereum_Module_Args_estimateContractCallGas, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "estimateContractCallGas", @@ -501,7 +502,7 @@ export const Ethereum_Module = { checkAddress: async ( args: Ethereum_Module_Args_checkAddress, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "checkAddress", @@ -512,7 +513,7 @@ export const Ethereum_Module = { toWei: async ( args: Ethereum_Module_Args_toWei, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "toWei", @@ -523,7 +524,7 @@ export const Ethereum_Module = { toEth: async ( args: Ethereum_Module_Args_toEth, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "toEth", @@ -534,7 +535,7 @@ export const Ethereum_Module = { awaitTransaction: async ( args: Ethereum_Module_Args_awaitTransaction, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "awaitTransaction", @@ -545,7 +546,7 @@ export const Ethereum_Module = { waitForEvent: async ( args: Ethereum_Module_Args_waitForEvent, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "waitForEvent", @@ -556,7 +557,7 @@ export const Ethereum_Module = { getNetwork: async ( args: Ethereum_Module_Args_getNetwork, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "getNetwork", @@ -567,7 +568,7 @@ export const Ethereum_Module = { requestAccounts: async ( args: Ethereum_Module_Args_requestAccounts, client: Client - ): Promise, Error>> => { + ): Promise>> => { return client.invoke>({ uri: "ens/ethereum.polywrap.eth", method: "requestAccounts", @@ -578,7 +579,7 @@ export const Ethereum_Module = { callContractMethod: async ( args: Ethereum_Module_Args_callContractMethod, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractMethod", @@ -589,7 +590,7 @@ export const Ethereum_Module = { callContractMethodAndWait: async ( args: Ethereum_Module_Args_callContractMethodAndWait, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "callContractMethodAndWait", @@ -600,7 +601,7 @@ export const Ethereum_Module = { sendTransaction: async ( args: Ethereum_Module_Args_sendTransaction, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "sendTransaction", @@ -611,7 +612,7 @@ export const Ethereum_Module = { sendTransactionAndWait: async ( args: Ethereum_Module_Args_sendTransactionAndWait, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "sendTransactionAndWait", @@ -622,7 +623,7 @@ export const Ethereum_Module = { deployContract: async ( args: Ethereum_Module_Args_deployContract, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "deployContract", @@ -633,7 +634,7 @@ export const Ethereum_Module = { signMessage: async ( args: Ethereum_Module_Args_signMessage, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "signMessage", @@ -644,7 +645,7 @@ export const Ethereum_Module = { sendRPC: async ( args: Ethereum_Module_Args_sendRPC, client: Client - ): Promise> => { + ): Promise> => { return client.invoke({ uri: "ens/ethereum.polywrap.eth", method: "sendRPC", From 84d029ef5557cd84d761fea46e2bae17f1eed82a Mon Sep 17 00:00:00 2001 From: dOrgJelli Date: Mon, 26 Sep 2022 22:11:07 +0200 Subject: [PATCH 14/25] chore: use InvokeResult --- packages/js/client/src/PolywrapClient.ts | 19 ++++++++++--------- .../cases/bind/sanity/output/app-ts/types.ts | 7 ++++--- .../bind/sanity/output/plugin-ts/types.ts | 7 ++++--- 3 files changed, 18 insertions(+), 15 deletions(-) diff --git a/packages/js/client/src/PolywrapClient.ts b/packages/js/client/src/PolywrapClient.ts index 3d9b6fc7db..a705332186 100644 --- a/packages/js/client/src/PolywrapClient.ts +++ b/packages/js/client/src/PolywrapClient.ts @@ -36,6 +36,7 @@ import { getEnvFromUriHistory, PluginPackage, QueryResult, + InvokeResult } from "@polywrap/core-js"; import { buildCleanUriHistory, @@ -264,7 +265,7 @@ export class PolywrapClient implements Client { // Execute all invocations in parallel const parallelInvocations: Promise<{ name: string; - result: Result; + result: InvokeResult; }>[] = []; for (const invocationName of Object.keys(queryInvocations)) { @@ -321,7 +322,7 @@ export class PolywrapClient implements Client { TUri extends Uri | string = string >( options: InvokerOptions & { wrapper: Wrapper } - ): Promise> { + ): Promise> { const { contextId, shouldClearContext } = this._setContext( options.contextId, options.config @@ -342,12 +343,12 @@ export class PolywrapClient implements Client { contextualizeClient(this, contextId) ); - if (!invocableResult.data.ok) { - error = invocableResult.data.error as Error; + if (!invocableResult.ok) { + error = invocableResult.error as Error; break invokeError; } - const value = invocableResult.data.value; + const value = invocableResult.value; if (options.encodeResult && !invocableResult.encoded) { const encoded = msgpackEncode(value); @@ -372,7 +373,7 @@ export class PolywrapClient implements Client { @Tracer.traceMethod("PolywrapClient: invoke") public async invoke( options: InvokerOptions - ): Promise> { + ): Promise> { const { contextId, shouldClearContext } = this._setContext( options.contextId, options.config @@ -468,7 +469,7 @@ export class PolywrapClient implements Client { } subscription.isActive = false; }, - async *[Symbol.asyncIterator](): AsyncGenerator> { + async *[Symbol.asyncIterator](): AsyncGenerator> { let timeout: NodeJS.Timeout | undefined = undefined; subscription.isActive = true; @@ -723,12 +724,12 @@ const contextualizeClient = ( }, invokeWrapper: ( options: InvokeOptions & { wrapper: Wrapper } - ): Promise> => { + ): Promise> => { return client.invokeWrapper({ ...options, contextId }); }, invoke: ( options: InvokeOptions - ): Promise> => { + ): Promise> => { return client.invoke({ ...options, contextId }); }, subscribe: ( diff --git a/packages/test-cases/cases/bind/sanity/output/app-ts/types.ts b/packages/test-cases/cases/bind/sanity/output/app-ts/types.ts index bc57effe7a..df9b1f60e8 100644 --- a/packages/test-cases/cases/bind/sanity/output/app-ts/types.ts +++ b/packages/test-cases/cases/bind/sanity/output/app-ts/types.ts @@ -4,7 +4,8 @@ import * as Types from "./"; // @ts-ignore import { Client, - Result + Result, + InvokeResult } from "@polywrap/core-js"; export type UInt = number; @@ -170,7 +171,7 @@ export const TestImport_Module = { args: TestImport_Module_Args_importedMethod, client: Client, uri: string = "testimport.uri.eth" - ): Promise> => { + ): Promise> => { return client.invoke({ uri, method: "importedMethod", @@ -182,7 +183,7 @@ export const TestImport_Module = { args: TestImport_Module_Args_anotherMethod, client: Client, uri: string = "testimport.uri.eth" - ): Promise> => { + ): Promise> => { return client.invoke({ uri, method: "anotherMethod", diff --git a/packages/test-cases/cases/bind/sanity/output/plugin-ts/types.ts b/packages/test-cases/cases/bind/sanity/output/plugin-ts/types.ts index 15ce85dae1..bea42392d8 100644 --- a/packages/test-cases/cases/bind/sanity/output/plugin-ts/types.ts +++ b/packages/test-cases/cases/bind/sanity/output/plugin-ts/types.ts @@ -7,7 +7,8 @@ import * as Types from "./"; // @ts-ignore import { Client, - Result + Result, + InvokeResult } from "@polywrap/core-js"; export type UInt = number; @@ -187,7 +188,7 @@ export class TestImport_Module { public async importedMethod ( args: TestImport_Module_Args_importedMethod, client: Client - ): Promise> { + ): Promise> { return client.invoke({ uri: this.uri, method: "importedMethod", @@ -198,7 +199,7 @@ export class TestImport_Module { public async anotherMethod ( args: TestImport_Module_Args_anotherMethod, client: Client - ): Promise> { + ): Promise> { return client.invoke({ uri: this.uri, method: "anotherMethod", From fde86ec1338148fdc2fcf02d61250bd420ff0b22 Mon Sep 17 00:00:00 2001 From: dOrgJelli Date: Mon, 26 Sep 2022 22:24:14 +0200 Subject: [PATCH 15/25] chore: fix build --- packages/js/core/src/plugin/PluginWrapper.ts | 14 +++++--------- packages/js/wasm/src/WasmWrapper.ts | 8 ++++---- .../typescript/plugin/templates/types-ts.mustache | 2 +- .../cases/bind/sanity/output/app-ts/types.ts | 1 - .../codegen/001-sanity/expected/wrap/types.ts | 1 - .../002-single-module/expected/wrap/types.ts | 1 - .../plugin/codegen/003-env/expected/wrap/types.ts | 1 - .../004-env-sanitization/expected/wrap/types.ts | 1 - .../005-custom-config/expected/wrap/types.ts | 1 - .../expected/wrap/types.ts | 1 - 10 files changed, 10 insertions(+), 21 deletions(-) diff --git a/packages/js/core/src/plugin/PluginWrapper.ts b/packages/js/core/src/plugin/PluginWrapper.ts index 27465756a9..b5733c21fe 100644 --- a/packages/js/core/src/plugin/PluginWrapper.ts +++ b/packages/js/core/src/plugin/PluginWrapper.ts @@ -56,15 +56,11 @@ export class PluginWrapper implements Wrapper { const module = this._getInstance(); if (!module) { - return { - data: ResultErr(Error(`PluginWrapper: module "${module}" not found.`)), - }; + return ResultErr(Error(`PluginWrapper: module "${module}" not found.`)); } if (!module.getMethod(method)) { - return { - data: ResultErr(Error(`PluginWrapper: method "${method}" not found.`)), - }; + return ResultErr(Error(`PluginWrapper: method "${method}" not found.`)); } // Set the module's environment @@ -82,7 +78,7 @@ export class PluginWrapper implements Wrapper { const msgPackException = Error( `PluginWrapper: decoded MsgPack args did not result in an object.\nResult: ${result}` ); - return { data: ResultErr(msgPackException) }; + return ResultErr(msgPackException); } jsArgs = result as Record; @@ -99,7 +95,7 @@ export class PluginWrapper implements Wrapper { Tracer.addEvent("Result", data); return { - data: ResultOk(data), + ...ResultOk(data), encoded: false, }; } else { @@ -110,7 +106,7 @@ export class PluginWrapper implements Wrapper { `args: ${JSON.stringify(jsArgs, null, 2)}\n` + `exception: ${result.error?.message}` ); - return { data: ResultErr(invocationException) }; + return ResultErr(invocationException); } } diff --git a/packages/js/wasm/src/WasmWrapper.ts b/packages/js/wasm/src/WasmWrapper.ts index 789511d3dd..91469f1494 100644 --- a/packages/js/wasm/src/WasmWrapper.ts +++ b/packages/js/wasm/src/WasmWrapper.ts @@ -112,7 +112,7 @@ export class WasmWrapper implements Wrapper { const args = options.args || {}; const wasmResult = await this._getWasmModule(); if (!wasmResult.ok) { - return { data: wasmResult }; + return wasmResult; } const wasm = wasmResult.value; @@ -165,7 +165,7 @@ export class WasmWrapper implements Wrapper { if (invokeResult.ok) { return { - data: invokeResult, + ...invokeResult, encoded: true, }; } else { @@ -176,10 +176,10 @@ export class WasmWrapper implements Wrapper { `args: ${JSON.stringify(args, null, 2)}\n` + `exception: ${invokeResult.error?.message}` ); - return { data: ResultErr(error) }; + return ResultErr(error); } } catch (error) { - return { data: ResultErr(error) }; + return ResultErr(error); } } diff --git a/packages/schema/bind/src/bindings/typescript/plugin/templates/types-ts.mustache b/packages/schema/bind/src/bindings/typescript/plugin/templates/types-ts.mustache index 4dd80956b5..9ff37d8c11 100644 --- a/packages/schema/bind/src/bindings/typescript/plugin/templates/types-ts.mustache +++ b/packages/schema/bind/src/bindings/typescript/plugin/templates/types-ts.mustache @@ -7,7 +7,7 @@ import * as Types from "./"; // @ts-ignore import { Client, - Result, + {{#interfaceTypes.length}}Result,{{/interfaceTypes.length}} InvokeResult } from "@polywrap/core-js"; diff --git a/packages/test-cases/cases/bind/sanity/output/app-ts/types.ts b/packages/test-cases/cases/bind/sanity/output/app-ts/types.ts index df9b1f60e8..7e05acf86d 100644 --- a/packages/test-cases/cases/bind/sanity/output/app-ts/types.ts +++ b/packages/test-cases/cases/bind/sanity/output/app-ts/types.ts @@ -4,7 +4,6 @@ import * as Types from "./"; // @ts-ignore import { Client, - Result, InvokeResult } from "@polywrap/core-js"; diff --git a/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/wrap/types.ts index 67a72fe7d4..3172a4e4b0 100644 --- a/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/wrap/types.ts +++ b/packages/test-cases/cases/cli/plugin/codegen/001-sanity/expected/wrap/types.ts @@ -7,7 +7,6 @@ import * as Types from "./"; // @ts-ignore import { Client, - Result, InvokeResult } from "@polywrap/core-js"; diff --git a/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/types.ts index 67a72fe7d4..3172a4e4b0 100644 --- a/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/types.ts +++ b/packages/test-cases/cases/cli/plugin/codegen/002-single-module/expected/wrap/types.ts @@ -7,7 +7,6 @@ import * as Types from "./"; // @ts-ignore import { Client, - Result, InvokeResult } from "@polywrap/core-js"; diff --git a/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/wrap/types.ts index b069eec20f..6dbf11884a 100644 --- a/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/wrap/types.ts +++ b/packages/test-cases/cases/cli/plugin/codegen/003-env/expected/wrap/types.ts @@ -7,7 +7,6 @@ import * as Types from "./"; // @ts-ignore import { Client, - Result, InvokeResult } from "@polywrap/core-js"; diff --git a/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/wrap/types.ts index b6564471ee..fee545ff08 100644 --- a/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/wrap/types.ts +++ b/packages/test-cases/cases/cli/plugin/codegen/004-env-sanitization/expected/wrap/types.ts @@ -7,7 +7,6 @@ import * as Types from "./"; // @ts-ignore import { Client, - Result, InvokeResult } from "@polywrap/core-js"; diff --git a/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/types.ts index 67a72fe7d4..3172a4e4b0 100644 --- a/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/types.ts +++ b/packages/test-cases/cases/cli/plugin/codegen/005-custom-config/expected/wrap/types.ts @@ -7,7 +7,6 @@ import * as Types from "./"; // @ts-ignore import { Client, - Result, InvokeResult } from "@polywrap/core-js"; diff --git a/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/types.ts b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/types.ts index 67a72fe7d4..3172a4e4b0 100644 --- a/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/types.ts +++ b/packages/test-cases/cases/cli/plugin/codegen/006-custom-manifest-file/expected/wrap/types.ts @@ -7,7 +7,6 @@ import * as Types from "./"; // @ts-ignore import { Client, - Result, InvokeResult } from "@polywrap/core-js"; From 6ab5736defad8f8b82db082fb7e3deb8c92142ec Mon Sep 17 00:00:00 2001 From: dOrgJelli Date: Mon, 26 Sep 2022 22:42:49 +0200 Subject: [PATCH 16/25] chore: lint fix --- packages/js/client/src/PolywrapClient.ts | 2 +- .../assemblyscript/polywrap.wasm-linked.build.yaml | 11 +++++++++++ .../wasm/assemblyscript/polywrap.wasm-linked.yaml | 9 +++++++++ 3 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 packages/templates/wasm/assemblyscript/polywrap.wasm-linked.build.yaml create mode 100644 packages/templates/wasm/assemblyscript/polywrap.wasm-linked.yaml diff --git a/packages/js/client/src/PolywrapClient.ts b/packages/js/client/src/PolywrapClient.ts index cda8fbf76a..47964b1435 100644 --- a/packages/js/client/src/PolywrapClient.ts +++ b/packages/js/client/src/PolywrapClient.ts @@ -28,7 +28,7 @@ import { getEnvFromUriHistory, PluginPackage, QueryResult, - InvokeResult + InvokeResult, } from "@polywrap/core-js"; import { buildCleanUriHistory, diff --git a/packages/templates/wasm/assemblyscript/polywrap.wasm-linked.build.yaml b/packages/templates/wasm/assemblyscript/polywrap.wasm-linked.build.yaml new file mode 100644 index 0000000000..959488ab0c --- /dev/null +++ b/packages/templates/wasm/assemblyscript/polywrap.wasm-linked.build.yaml @@ -0,0 +1,11 @@ +format: 0.1.0 +docker: + name: template-wasm-as +config: + node_version: "16.13.0" + include: + - ./package.json + - ./src +linked_packages: + - name: "@polywrap/wasm-as" + path: ../../../wasm/as diff --git a/packages/templates/wasm/assemblyscript/polywrap.wasm-linked.yaml b/packages/templates/wasm/assemblyscript/polywrap.wasm-linked.yaml new file mode 100644 index 0000000000..294a567ae7 --- /dev/null +++ b/packages/templates/wasm/assemblyscript/polywrap.wasm-linked.yaml @@ -0,0 +1,9 @@ +format: 0.2.0 +project: + name: template-wasm-as + type: wasm/assemblyscript +source: + module: ./src/index.ts + schema: ./src/schema.graphql +extensions: + build: ./polywrap.wasm-linked.build.yaml From ae28dc15c8669766eed225f595ee2fe2ab4b94bc Mon Sep 17 00:00:00 2001 From: dOrgJelli Date: Mon, 26 Sep 2022 23:07:11 +0200 Subject: [PATCH 17/25] chore: fix plugin codegen --- .../bindings/typescript/plugin/templates/types-ts.mustache | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/schema/bind/src/bindings/typescript/plugin/templates/types-ts.mustache b/packages/schema/bind/src/bindings/typescript/plugin/templates/types-ts.mustache index 9ff37d8c11..fe7452afe4 100644 --- a/packages/schema/bind/src/bindings/typescript/plugin/templates/types-ts.mustache +++ b/packages/schema/bind/src/bindings/typescript/plugin/templates/types-ts.mustache @@ -6,8 +6,8 @@ import * as Types from "./"; // @ts-ignore import { - Client, - {{#interfaceTypes.length}}Result,{{/interfaceTypes.length}} + Client,{{#interfaceTypes.length}} + Result,{{/interfaceTypes.length}} InvokeResult } from "@polywrap/core-js"; From 4ef83b3a824686915129b20c5831b6b4191f1c2d Mon Sep 17 00:00:00 2001 From: Jure Bogunovic Date: Tue, 27 Sep 2022 14:20:29 +0200 Subject: [PATCH 18/25] refactored use of result in client, made loadWrapper public --- packages/js/client/src/PolywrapClient.ts | 124 ++++++++++----------- packages/js/client/src/UriResolverError.ts | 19 ++++ yarn.lock | 10 +- 3 files changed, 81 insertions(+), 72 deletions(-) create mode 100644 packages/js/client/src/UriResolverError.ts diff --git a/packages/js/client/src/PolywrapClient.ts b/packages/js/client/src/PolywrapClient.ts index 47964b1435..8fb5e3f3fa 100644 --- a/packages/js/client/src/PolywrapClient.ts +++ b/packages/js/client/src/PolywrapClient.ts @@ -20,25 +20,23 @@ import { TryResolveUriOptions, IUriResolver, GetManifestOptions, - initWrapper, - IWrapPackage, IUriResolutionContext, UriPackageOrWrapper, UriResolutionContext, getEnvFromUriHistory, PluginPackage, QueryResult, - InvokeResult, } from "@polywrap/core-js"; import { buildCleanUriHistory, IWrapperCache, } from "@polywrap/uri-resolvers-js"; import { msgpackEncode, msgpackDecode } from "@polywrap/msgpack-js"; -import { WrapManifest } from "@polywrap/wrap-manifest-types-js"; +import { DeserializeManifestOptions, WrapManifest } from "@polywrap/wrap-manifest-types-js"; import { Tracer, TracerConfig, TracingLevel } from "@polywrap/tracing-js"; import { ClientConfigBuilder } from "@polywrap/client-config-builder-js"; import { Result, ResultErr, ResultOk } from "@polywrap/result"; +import { UriResolverError } from "./UriResolverError"; export interface PolywrapClientConfig extends ClientConfig { @@ -160,7 +158,7 @@ export class PolywrapClient implements Client { uri: TUri, options: GetManifestOptions = {} ): Promise> { - const load = await this._loadWrapper(Uri.from(uri), undefined); + const load = await this.loadWrapper(Uri.from(uri), undefined); if (!load.ok) { return load; } @@ -174,7 +172,7 @@ export class PolywrapClient implements Client { uri: TUri, options: GetFileOptions ): Promise> { - const load = await this._loadWrapper(Uri.from(uri), undefined); + const load = await this.loadWrapper(Uri.from(uri), undefined); if (!load.ok) { return load; } @@ -291,10 +289,8 @@ export class PolywrapClient implements Client { TUri extends Uri | string = string >( options: InvokerOptions & { wrapper: Wrapper } - ): Promise> { - let error: Error; - - invokeError: try { + ): Promise> { + try { const typedOptions: InvokeOptions = { ...options, uri: Uri.from(options.uri), @@ -304,8 +300,7 @@ export class PolywrapClient implements Client { const invocableResult = await wrapper.invoke(typedOptions, this); if (!invocableResult.ok) { - error = invocableResult.error as Error; - break invokeError; + return ResultErr(invocableResult.error); } const value = invocableResult.value; @@ -319,20 +314,16 @@ export class PolywrapClient implements Client { } else { return ResultOk(value as TData); } - } catch (e) { - error = e; + } catch (error) { + return ResultErr(error); } - - return ResultErr(error); } @Tracer.traceMethod("PolywrapClient: invoke") public async invoke( options: InvokerOptions ): Promise> { - let error: Error; - - err: try { + try { const typedOptions: InvokeOptions = { ...options, uri: Uri.from(options.uri), @@ -341,13 +332,12 @@ export class PolywrapClient implements Client { const resolutionContext = options.resolutionContext ?? new UriResolutionContext(); - const loadWrapperResult = await this._loadWrapper( + const loadWrapperResult = await this.loadWrapper( typedOptions.uri, resolutionContext ); if (!loadWrapperResult.ok) { - error = loadWrapperResult.error as Error; - break err; + return ResultErr(loadWrapperResult.error); } const wrapper = loadWrapperResult.value; @@ -361,15 +351,15 @@ export class PolywrapClient implements Client { ...typedOptions, wrapper, }); - if (invokeResult.ok) { - return invokeResult; + + if (!invokeResult.ok) { + return ResultErr(invokeResult.error); } - error = invokeResult.error as Error; - } catch (e) { - error = e; - } - return ResultErr(error); + return invokeResult; + } catch (error) { + return ResultErr(error); + } } @Tracer.traceMethod("PolywrapClient: subscribe") @@ -479,27 +469,11 @@ export class PolywrapClient implements Client { return response; } - @Tracer.traceMethod("PolywrapClient: validateConfig") - private _validateConfig(): void { - // Require plugins to use non-interface URIs - const pluginUris = this.getPlugins().map((x) => x.uri.uri); - const interfaceUris = this.getInterfaces().map((x) => x.interface.uri); - - const pluginsWithInterfaceUris = pluginUris.filter((plugin) => - interfaceUris.includes(plugin) - ); - - if (pluginsWithInterfaceUris.length) { - throw Error( - `Plugins can't use interfaces for their URI. Invalid plugins: ${pluginsWithInterfaceUris}` - ); - } - } - - @Tracer.traceMethod("PolywrapClient: _loadWrapper", TracingLevel.High) - private async _loadWrapper( + @Tracer.traceMethod("PolywrapClient: loadWrapper", TracingLevel.High) + public async loadWrapper( uri: Uri, - resolutionContext?: IUriResolutionContext + resolutionContext?: IUriResolutionContext, + options?: DeserializeManifestOptions ): Promise> { Tracer.setAttribute("label", `Wrapper loaded: ${uri}`, TracingLevel.High); @@ -513,19 +487,20 @@ export class PolywrapClient implements Client { }); if (!result.ok) { - if (result.error && result.error instanceof Error) { - return result as Result; - } else if (result.error && typeof result.error === "string") { - return ResultErr(Error(result.error)); + if (result.error) { + return ResultErr(new UriResolverError(result.error, resolutionContext)); } else { - const error = Error( - `Error resolving URI "${uri.uri}"\nResolution Stack: ${JSON.stringify( - resolutionContext.getHistory(), - null, - 2 - )}` + return ResultErr( + Error( + `Error resolving URI "${ + uri.uri + }"\nResolution Stack: ${JSON.stringify( + buildCleanUriHistory(resolutionContext.getHistory()), + null, + 2 + )}` + ) ); - return ResultErr(error); } } @@ -535,21 +510,36 @@ export class PolywrapClient implements Client { const error = Error( `Error resolving URI "${uri.uri}"\nURI not found ${ uriPackageOrWrapper.uri.uri - }\nResolution Stack: ${JSON.stringify(history, null, 2)}` + }\nResolution Stack: ${JSON.stringify( + buildCleanUriHistory(resolutionContext.getHistory()), + null, + 2 + )}` ); return ResultErr(error); } - let packageOrWrapper: IWrapPackage | Wrapper; - if (uriPackageOrWrapper.type === "package") { - packageOrWrapper = uriPackageOrWrapper.package; + return ResultOk(await uriPackageOrWrapper.package.createWrapper(options)); } else { - packageOrWrapper = uriPackageOrWrapper.wrapper; + return ResultOk(uriPackageOrWrapper.wrapper); } + } + + @Tracer.traceMethod("PolywrapClient: validateConfig") + private _validateConfig(): void { + // Require plugins to use non-interface URIs + const pluginUris = this.getPlugins().map((x) => x.uri.uri); + const interfaceUris = this.getInterfaces().map((x) => x.interface.uri); - const wrapper = await initWrapper(packageOrWrapper); + const pluginsWithInterfaceUris = pluginUris.filter((plugin) => + interfaceUris.includes(plugin) + ); - return ResultOk(wrapper); + if (pluginsWithInterfaceUris.length) { + throw Error( + `Plugins can't use interfaces for their URI. Invalid plugins: ${pluginsWithInterfaceUris}` + ); + } } } diff --git a/packages/js/client/src/UriResolverError.ts b/packages/js/client/src/UriResolverError.ts new file mode 100644 index 0000000000..5b41a2cacf --- /dev/null +++ b/packages/js/client/src/UriResolverError.ts @@ -0,0 +1,19 @@ +import { IUriResolutionContext } from "@polywrap/core-js"; +import { buildCleanUriHistory } from "@polywrap/uri-resolvers-js"; + +export class UriResolverError< + TError extends unknown = undefined +> extends Error { + constructor( + public readonly resolverError: TError, + resolutionContext: IUriResolutionContext + ) { + super( + `An internal resolver error occurred while resolving a URI.\nResolution Stack: ${JSON.stringify( + buildCleanUriHistory(resolutionContext.getHistory()), + null, + 2 + )}` + ); + } +} diff --git a/yarn.lock b/yarn.lock index 46bf424f1b..c53372ae26 100644 --- a/yarn.lock +++ b/yarn.lock @@ -17672,16 +17672,16 @@ utils-merge@1.0.1: resolved "https://registry.yarnpkg.com/utils-merge/-/utils-merge-1.0.1.tgz#9f95710f50a267947b2ccc124741c1028427e713" integrity sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA== -uuid@8.3.2, uuid@^8.3.0: - version "8.3.2" - resolved "https://registry.yarnpkg.com/uuid/-/uuid-8.3.2.tgz#80d5b5ced271bb9af6c445f21a1a04c606cefbe2" - integrity sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg== - uuid@^3.0.1, uuid@^3.3.2: version "3.4.0" resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.4.0.tgz#b23e4358afa8a202fe7a100af1f5f883f02007ee" integrity sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A== +uuid@^8.3.0: + version "8.3.2" + resolved "https://registry.yarnpkg.com/uuid/-/uuid-8.3.2.tgz#80d5b5ced271bb9af6c445f21a1a04c606cefbe2" + integrity sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg== + v8-compile-cache-lib@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz#6336e8d71965cb3d35a1bbb7868445a7c05264bf" From 18a2e4fe9f5cb271263619a8786996e789370208 Mon Sep 17 00:00:00 2001 From: Jure Bogunovic Date: Tue, 27 Sep 2022 15:23:03 +0200 Subject: [PATCH 19/25] using result for wrap packages --- packages/js/core/src/plugin/PluginWrapPackage.ts | 9 +++++---- packages/js/core/src/types/IWrapPackage.ts | 9 +++++++-- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/packages/js/core/src/plugin/PluginWrapPackage.ts b/packages/js/core/src/plugin/PluginWrapPackage.ts index 8928129e72..1172843cc6 100644 --- a/packages/js/core/src/plugin/PluginWrapPackage.ts +++ b/packages/js/core/src/plugin/PluginWrapPackage.ts @@ -2,6 +2,7 @@ import { IWrapPackage, PluginPackage, Uri, Wrapper } from "../types"; import { PluginWrapper } from "./PluginWrapper"; import { WrapManifest } from "@polywrap/wrap-manifest-types-js"; +import { Result, ResultOk } from "@polywrap/result"; // TODO: this is a temporary solution until we refactor the plugin package to be an IWrapPackage export class PluginWrapPackage implements IWrapPackage { @@ -10,11 +11,11 @@ export class PluginWrapPackage implements IWrapPackage { private readonly pluginPackage: PluginPackage ) {} - async getManifest(): Promise { - return this.pluginPackage.manifest; + async getManifest(): Promise> { + return ResultOk(this.pluginPackage.manifest); } - async createWrapper(): Promise { - return new PluginWrapper(this.pluginPackage); + async createWrapper(): Promise> { + return ResultOk(new PluginWrapper(this.pluginPackage)); } } diff --git a/packages/js/core/src/types/IWrapPackage.ts b/packages/js/core/src/types/IWrapPackage.ts index ce30d97c0f..9afe7fc5aa 100644 --- a/packages/js/core/src/types/IWrapPackage.ts +++ b/packages/js/core/src/types/IWrapPackage.ts @@ -4,8 +4,13 @@ import { DeserializeManifestOptions, WrapManifest, } from "@polywrap/wrap-manifest-types-js"; +import { Result } from "@polywrap/result"; export interface IWrapPackage { - getManifest(options?: GetManifestOptions): Promise; - createWrapper(options?: DeserializeManifestOptions): Promise; + getManifest( + options?: GetManifestOptions + ): Promise>; + createWrapper( + options?: DeserializeManifestOptions + ): Promise>; } From bdbcba5a86746de8ecf303d03119226254ba5589 Mon Sep 17 00:00:00 2001 From: Jure Bogunovic Date: Tue, 27 Sep 2022 15:23:40 +0200 Subject: [PATCH 20/25] removed initWrapper --- packages/js/core/src/utils/index.ts | 1 - packages/js/core/src/utils/initWrapper.ts | 13 ---------- .../src/ResolverExtensionLoader.ts | 25 +++++++------------ 3 files changed, 9 insertions(+), 30 deletions(-) delete mode 100644 packages/js/core/src/utils/initWrapper.ts diff --git a/packages/js/core/src/utils/index.ts b/packages/js/core/src/utils/index.ts index b9e83c77c7..1b9aa94c7d 100644 --- a/packages/js/core/src/utils/index.ts +++ b/packages/js/core/src/utils/index.ts @@ -1,5 +1,4 @@ export * from "./Queue"; export * from "./combinePaths"; export * from "./getEnvFromUriHistory"; -export * from "./initWrapper"; export * from "./is-buffer"; diff --git a/packages/js/core/src/utils/initWrapper.ts b/packages/js/core/src/utils/initWrapper.ts deleted file mode 100644 index 2f6d57be13..0000000000 --- a/packages/js/core/src/utils/initWrapper.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { IWrapPackage, Wrapper } from ".."; - -export const initWrapper = async ( - packageOrWrapper: IWrapPackage | Wrapper -): Promise => { - const wrapPackage = packageOrWrapper as Partial; - - if (wrapPackage.createWrapper) { - return await wrapPackage.createWrapper(); - } else { - return packageOrWrapper as Wrapper; - } -}; diff --git a/packages/js/uri-resolver-extensions/src/ResolverExtensionLoader.ts b/packages/js/uri-resolver-extensions/src/ResolverExtensionLoader.ts index e0dfc64503..efc2c12d6e 100644 --- a/packages/js/uri-resolver-extensions/src/ResolverExtensionLoader.ts +++ b/packages/js/uri-resolver-extensions/src/ResolverExtensionLoader.ts @@ -1,11 +1,4 @@ -import { - Uri, - Client, - IWrapPackage, - Wrapper, - initWrapper, - IUriResolutionContext, -} from "@polywrap/core-js"; +import { Uri, Client, Wrapper, IUriResolutionContext } from "@polywrap/core-js"; import { Result, ResultErr, ResultOk } from "@polywrap/result"; export const loadResolverExtension = async ( @@ -33,15 +26,15 @@ export const loadResolverExtension = async ( ); } - let wrapperOrPackage: IWrapPackage | Wrapper; - if (uriPackageOrWrapper.type === "package") { - wrapperOrPackage = uriPackageOrWrapper.package; - } else { - wrapperOrPackage = uriPackageOrWrapper.wrapper; - } + const result = await uriPackageOrWrapper.package.createWrapper(); - const wrapper = await initWrapper(wrapperOrPackage); + if (!result.ok) { + return result; + } - return ResultOk(wrapper); + return ResultOk(result.value); + } else { + return ResultOk(uriPackageOrWrapper.wrapper); + } }; From a72d200e77fc48dda916c796ecab5ded3685b1b1 Mon Sep 17 00:00:00 2001 From: Jure Bogunovic Date: Tue, 27 Sep 2022 15:24:05 +0200 Subject: [PATCH 21/25] result fixes --- packages/js/client/src/PolywrapClient.ts | 14 +++++++---- .../cache/PackageToWrapperCacheResolver.ts | 15 ++++++++---- packages/js/wasm/src/InMemoryFileReader.ts | 6 +---- packages/js/wasm/src/WasmPackage.ts | 23 ++++++++++++------- 4 files changed, 36 insertions(+), 22 deletions(-) diff --git a/packages/js/client/src/PolywrapClient.ts b/packages/js/client/src/PolywrapClient.ts index 8fb5e3f3fa..363b4a315b 100644 --- a/packages/js/client/src/PolywrapClient.ts +++ b/packages/js/client/src/PolywrapClient.ts @@ -236,7 +236,7 @@ export class PolywrapClient implements Client { // Execute all invocations in parallel const parallelInvocations: Promise<{ name: string; - result: InvokeResult; + result: Result; }>[] = []; for (const invocationName of Object.keys(queryInvocations)) { @@ -322,7 +322,7 @@ export class PolywrapClient implements Client { @Tracer.traceMethod("PolywrapClient: invoke") public async invoke( options: InvokerOptions - ): Promise> { + ): Promise> { try { const typedOptions: InvokeOptions = { ...options, @@ -394,7 +394,7 @@ export class PolywrapClient implements Client { stop(): void { subscription.isActive = false; }, - async *[Symbol.asyncIterator](): AsyncGenerator> { + async *[Symbol.asyncIterator](): AsyncGenerator> { let timeout: NodeJS.Timeout | undefined = undefined; subscription.isActive = true; @@ -520,7 +520,13 @@ export class PolywrapClient implements Client { } if (uriPackageOrWrapper.type === "package") { - return ResultOk(await uriPackageOrWrapper.package.createWrapper(options)); + const result = await uriPackageOrWrapper.package.createWrapper(); + + if (!result.ok) { + return result; + } + + return ResultOk(result.value); } else { return ResultOk(uriPackageOrWrapper.wrapper); } diff --git a/packages/js/uri-resolvers/src/cache/PackageToWrapperCacheResolver.ts b/packages/js/uri-resolvers/src/cache/PackageToWrapperCacheResolver.ts index 0d4711801c..7dde779423 100644 --- a/packages/js/uri-resolvers/src/cache/PackageToWrapperCacheResolver.ts +++ b/packages/js/uri-resolvers/src/cache/PackageToWrapperCacheResolver.ts @@ -15,10 +15,9 @@ import { import { DeserializeManifestOptions } from "@polywrap/wrap-manifest-types-js"; import { Result } from "@polywrap/result"; -export class PackageToWrapperCacheResolver - implements IUriResolver { +export class PackageToWrapperCacheResolver implements IUriResolver { name: string; - resolverToCache: IUriResolver; + resolverToCache: IUriResolver; constructor( private cache: IWrapperCache, @@ -39,7 +38,7 @@ export class PackageToWrapperCacheResolver uri: Uri, client: Client, resolutionContext: IUriResolutionContext - ): Promise> { + ): Promise> { const wrapper = await executeMaybeAsyncFunction( this.cache.get.bind(this.cache, uri) ); @@ -68,10 +67,16 @@ export class PackageToWrapperCacheResolver const wrapPackage = result.value.package; const resolutionPath: Uri[] = subContext.getResolutionPath(); - const wrapper = await wrapPackage.createWrapper({ + const createResult = await wrapPackage.createWrapper({ noValidate: this.options?.deserializeManifestOptions?.noValidate, }); + if (!createResult.ok) { + return createResult; + } + + const wrapper = createResult.value; + for (const uri of resolutionPath) { await executeMaybeAsyncFunction( this.cache.set.bind(this.cache, uri, wrapper) diff --git a/packages/js/wasm/src/InMemoryFileReader.ts b/packages/js/wasm/src/InMemoryFileReader.ts index bc4b577e07..1546db06ea 100644 --- a/packages/js/wasm/src/InMemoryFileReader.ts +++ b/packages/js/wasm/src/InMemoryFileReader.ts @@ -47,11 +47,7 @@ export class InMemoryFileReader { } else if (baseFileReader) { return baseFileReader.readFile(filePath); } else { - const error = Error( - `Unable to read file at filepath ${filePath}.` + - `Expected '${WRAP_MANIFEST_PATH}' or '${WRAP_MODULE_PATH}'.` - ); - return ResultErr(error); + return ResultErr(Error(`File not found at ${filePath}.`)); } }, }; diff --git a/packages/js/wasm/src/WasmPackage.ts b/packages/js/wasm/src/WasmPackage.ts index 4429e1e373..2f390a1811 100644 --- a/packages/js/wasm/src/WasmPackage.ts +++ b/packages/js/wasm/src/WasmPackage.ts @@ -9,7 +9,7 @@ import { WrapManifest, } from "@polywrap/wrap-manifest-types-js"; import { GetManifestOptions, Wrapper } from "@polywrap/core-js"; -import { Result, ResultErr } from "@polywrap/result"; +import { Result, ResultErr, ResultOk } from "@polywrap/result"; export class WasmPackage implements IWasmPackage { protected constructor(private readonly fileReader: IFileReader) {} @@ -65,15 +65,17 @@ export class WasmPackage implements IWasmPackage { } // TODO: return Result - async getManifest(options?: GetManifestOptions): Promise { + async getManifest( + options?: GetManifestOptions + ): Promise> { const result = await this.fileReader.readFile(WRAP_MANIFEST_PATH); if (!result.ok) { - throw Error(`WRAP manifest not found`); + return result; } const wrapManifest = result.value; - return deserializeWrapManifest(wrapManifest, options); + return ResultOk(await deserializeWrapManifest(wrapManifest, options)); } async getWasmModule(): Promise> { @@ -86,10 +88,15 @@ export class WasmPackage implements IWasmPackage { return result; } - // TODO: return Result - async createWrapper(options?: GetManifestOptions): Promise { - const manifest = await this.getManifest(options); + async createWrapper( + options?: GetManifestOptions + ): Promise> { + const result = await this.getManifest(options); + + if (!result.ok) { + return result; + } - return new WasmWrapper(manifest, this.fileReader); + return ResultOk(new WasmWrapper(result.value, this.fileReader)); } } From 5bff6c2c93bfcedeb395588e5e024cdd8a5dcb99 Mon Sep 17 00:00:00 2001 From: Jure Bogunovic Date: Tue, 27 Sep 2022 15:39:34 +0200 Subject: [PATCH 22/25] using InvokeResult instead of Result --- packages/js/client/src/PolywrapClient.ts | 12 ++++++++---- packages/js/react/src/invoke.tsx | 13 ++++--------- .../src/UriResolverExtensionFileReader.ts | 5 +++-- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/packages/js/client/src/PolywrapClient.ts b/packages/js/client/src/PolywrapClient.ts index 363b4a315b..25229c5f5d 100644 --- a/packages/js/client/src/PolywrapClient.ts +++ b/packages/js/client/src/PolywrapClient.ts @@ -26,13 +26,17 @@ import { getEnvFromUriHistory, PluginPackage, QueryResult, + InvokeResult, } from "@polywrap/core-js"; import { buildCleanUriHistory, IWrapperCache, } from "@polywrap/uri-resolvers-js"; import { msgpackEncode, msgpackDecode } from "@polywrap/msgpack-js"; -import { DeserializeManifestOptions, WrapManifest } from "@polywrap/wrap-manifest-types-js"; +import { + DeserializeManifestOptions, + WrapManifest, +} from "@polywrap/wrap-manifest-types-js"; import { Tracer, TracerConfig, TracingLevel } from "@polywrap/tracing-js"; import { ClientConfigBuilder } from "@polywrap/client-config-builder-js"; import { Result, ResultErr, ResultOk } from "@polywrap/result"; @@ -289,7 +293,7 @@ export class PolywrapClient implements Client { TUri extends Uri | string = string >( options: InvokerOptions & { wrapper: Wrapper } - ): Promise> { + ): Promise> { try { const typedOptions: InvokeOptions = { ...options, @@ -322,7 +326,7 @@ export class PolywrapClient implements Client { @Tracer.traceMethod("PolywrapClient: invoke") public async invoke( options: InvokerOptions - ): Promise> { + ): Promise> { try { const typedOptions: InvokeOptions = { ...options, @@ -394,7 +398,7 @@ export class PolywrapClient implements Client { stop(): void { subscription.isActive = false; }, - async *[Symbol.asyncIterator](): AsyncGenerator> { + async *[Symbol.asyncIterator](): AsyncGenerator> { let timeout: NodeJS.Timeout | undefined = undefined; subscription.isActive = true; diff --git a/packages/js/react/src/invoke.tsx b/packages/js/react/src/invoke.tsx index e5f756d2d4..7b75ccf4b0 100644 --- a/packages/js/react/src/invoke.tsx +++ b/packages/js/react/src/invoke.tsx @@ -1,11 +1,7 @@ import { usePolywrapClient } from "./client"; import { useStateReducer } from "./state"; -import { - InvokeOptions, - Result, - isBuffer -} from "@polywrap/core-js"; +import { InvokeOptions, isBuffer, InvokeResult } from "@polywrap/core-js"; export interface UsePolywrapInvokeState { data?: TData; @@ -27,12 +23,11 @@ export interface UsePolywrapInvokeProps extends InvokeOptions { Note that the initial values passed into the usePolywrapInvoke hook will be ignored when an Uint8Array is passed into execute(...). */ -export interface UsePolywrapInvoke< - TData = unknown -> extends UsePolywrapInvokeState { +export interface UsePolywrapInvoke + extends UsePolywrapInvokeState { execute: ( args?: Record | Uint8Array - ) => Promise>; + ) => Promise>; } export function usePolywrapInvoke< diff --git a/packages/js/uri-resolver-extensions/src/UriResolverExtensionFileReader.ts b/packages/js/uri-resolver-extensions/src/UriResolverExtensionFileReader.ts index 3bc713533e..646149caf3 100644 --- a/packages/js/uri-resolver-extensions/src/UriResolverExtensionFileReader.ts +++ b/packages/js/uri-resolver-extensions/src/UriResolverExtensionFileReader.ts @@ -2,6 +2,7 @@ import { Client, combinePaths, InvokeOptions, + InvokeResult, Uri, UriResolverInterface, Wrapper, @@ -21,11 +22,11 @@ export class UriResolverExtensionFileReader implements IFileReader { { invoke: ( options: InvokeOptions - ): Promise> => + ): Promise> => this.client.invoke(options), invokeWrapper: ( options: InvokeOptions & { wrapper: Wrapper } - ): Promise> => + ): Promise> => this.client.invokeWrapper(options), }, this.resolverExtensionUri, From fb618da29163b1eace5cf0b8b92fcc534476fad0 Mon Sep 17 00:00:00 2001 From: Jure Bogunovic Date: Tue, 27 Sep 2022 15:42:18 +0200 Subject: [PATCH 23/25] using InvokeResult instead of Result --- packages/js/client/src/PolywrapClient.ts | 2 +- packages/js/core/src/algorithms/parse-query.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/js/client/src/PolywrapClient.ts b/packages/js/client/src/PolywrapClient.ts index 25229c5f5d..663e59529f 100644 --- a/packages/js/client/src/PolywrapClient.ts +++ b/packages/js/client/src/PolywrapClient.ts @@ -240,7 +240,7 @@ export class PolywrapClient implements Client { // Execute all invocations in parallel const parallelInvocations: Promise<{ name: string; - result: Result; + result: InvokeResult; }>[] = []; for (const invocationName of Object.keys(queryInvocations)) { diff --git a/packages/js/core/src/algorithms/parse-query.ts b/packages/js/core/src/algorithms/parse-query.ts index db52f75990..671bd50749 100644 --- a/packages/js/core/src/algorithms/parse-query.ts +++ b/packages/js/core/src/algorithms/parse-query.ts @@ -1,4 +1,4 @@ -import { QueryInvocations, QueryDocument, Uri } from "../types"; +import { QueryInvocations, QueryDocument, Uri, InvokeResult } from "../types"; import { SelectionSetNode, ValueNode } from "graphql"; import { Tracer } from "@polywrap/tracing-js"; @@ -93,7 +93,7 @@ const extractValue = Tracer.traceFunc( ( node: ValueNode, variables?: Record - ): Result => { + ): InvokeResult => { if (node.kind === "Variable") { // Get the argument's value from the variables object if (!variables) { From 303ea6b35922a5e282826ef9b113dc2c98f0ce2b Mon Sep 17 00:00:00 2001 From: Jure Bogunovic Date: Tue, 27 Sep 2022 15:47:30 +0200 Subject: [PATCH 24/25] passing options to createWrapper --- packages/js/client/src/PolywrapClient.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/js/client/src/PolywrapClient.ts b/packages/js/client/src/PolywrapClient.ts index 663e59529f..d11d970abb 100644 --- a/packages/js/client/src/PolywrapClient.ts +++ b/packages/js/client/src/PolywrapClient.ts @@ -1,3 +1,5 @@ +import { UriResolverError } from "./UriResolverError"; + import { Wrapper, Client, @@ -40,7 +42,6 @@ import { import { Tracer, TracerConfig, TracingLevel } from "@polywrap/tracing-js"; import { ClientConfigBuilder } from "@polywrap/client-config-builder-js"; import { Result, ResultErr, ResultOk } from "@polywrap/result"; -import { UriResolverError } from "./UriResolverError"; export interface PolywrapClientConfig extends ClientConfig { @@ -524,7 +525,7 @@ export class PolywrapClient implements Client { } if (uriPackageOrWrapper.type === "package") { - const result = await uriPackageOrWrapper.package.createWrapper(); + const result = await uriPackageOrWrapper.package.createWrapper(options); if (!result.ok) { return result; From f0be41ea0e190d2bd0d2d2d5c3c93ea091a56661 Mon Sep 17 00:00:00 2001 From: dOrgJelli Date: Tue, 27 Sep 2022 16:04:14 +0200 Subject: [PATCH 25/25] chore: remove needless InvokeResult --- packages/js/core/src/algorithms/parse-query.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/js/core/src/algorithms/parse-query.ts b/packages/js/core/src/algorithms/parse-query.ts index 671bd50749..db52f75990 100644 --- a/packages/js/core/src/algorithms/parse-query.ts +++ b/packages/js/core/src/algorithms/parse-query.ts @@ -1,4 +1,4 @@ -import { QueryInvocations, QueryDocument, Uri, InvokeResult } from "../types"; +import { QueryInvocations, QueryDocument, Uri } from "../types"; import { SelectionSetNode, ValueNode } from "graphql"; import { Tracer } from "@polywrap/tracing-js"; @@ -93,7 +93,7 @@ const extractValue = Tracer.traceFunc( ( node: ValueNode, variables?: Record - ): InvokeResult => { + ): Result => { if (node.kind === "Variable") { // Get the argument's value from the variables object if (!variables) {