From a7f6af2cc6d7801bd079c8b4469ab1a13cd160d9 Mon Sep 17 00:00:00 2001 From: John Rees Date: Mon, 28 Jun 2021 21:31:41 +0100 Subject: [PATCH] ts: Import node modules if not browser (#436) --- ts/src/provider.ts | 5 ++++- ts/src/utils/common.ts | 6 ++++++ ts/src/workspace.ts | 14 ++++++-------- 3 files changed, 16 insertions(+), 9 deletions(-) create mode 100644 ts/src/utils/common.ts diff --git a/ts/src/provider.ts b/ts/src/provider.ts index c0aeda2a..a619e7a3 100644 --- a/ts/src/provider.ts +++ b/ts/src/provider.ts @@ -11,6 +11,7 @@ import { SimulatedTransactionResponse, Commitment, } from "@solana/web3.js"; +import { isBrowser } from "./utils/common"; /** * The network and wallet context used to send transactions paid for and signed @@ -54,12 +55,14 @@ export default class Provider { } /** - * Returns a `Provider` read from the `ANCHOR_PROVIDER_URL` envirnment + * Returns a `Provider` read from the `ANCHOR_PROVIDER_URL` environment * variable * * (This api is for Node only.) */ static env(): Provider { + if (isBrowser) return; + const process = require("process"); const url = process.env.ANCHOR_PROVIDER_URL; if (url === undefined) { diff --git a/ts/src/utils/common.ts b/ts/src/utils/common.ts new file mode 100644 index 00000000..59d3f3b3 --- /dev/null +++ b/ts/src/utils/common.ts @@ -0,0 +1,6 @@ +/** + * Returns true if being run inside a web browser, + * false if in a Node process or electron app. + */ +export const isBrowser = + typeof window !== "undefined" && !window.process?.hasOwnProperty("type"); diff --git a/ts/src/workspace.ts b/ts/src/workspace.ts index e4cc0e87..0e3f8eed 100644 --- a/ts/src/workspace.ts +++ b/ts/src/workspace.ts @@ -3,6 +3,7 @@ import * as toml from "toml"; import { PublicKey } from "@solana/web3.js"; import { Program } from "./program"; import { Idl } from "./idl"; +import { isBrowser } from "./utils/common"; let _populatedWorkspace = false; @@ -15,17 +16,14 @@ let _populatedWorkspace = false; */ const workspace = new Proxy({} as any, { get(workspaceCache: { [key: string]: Program }, programName: string) { - const fs = require("fs"); - const process = require("process"); - - if ( - typeof window !== "undefined" && - !window.process?.hasOwnProperty("type") - ) { - // Workspaces are available in electron, but not in the browser, yet. + if (isBrowser) { + console.log("Workspaces aren't available in the browser"); return undefined; } + const fs = require("fs"); + const process = require("process"); + if (!_populatedWorkspace) { const path = require("path");