Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

polymorphic with improved exports #6

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"ignorePaths": ["**/*.json", "**/*.css", "node_modules", "**/*.log", "lib", "dist"],
"useGitignore": true,
"language": "en",
"words": ["dataurl", "devpool", "outdir", "servedir"],
"words": ["dataurl", "devpool", "outdir", "servedir", "outfile", "ubiquitydao"],
"dictionaries": ["typescript", "node", "software-terms"],
"import": ["@cspell/dict-typescript/cspell-ext.json", "@cspell/dict-node/cspell-ext.json", "@cspell/dict-software-terms"],
"ignoreRegExpList": ["[0-9a-fA-F]{6}"],
Expand Down
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
tests/**/*.ts
29 changes: 29 additions & 0 deletions .github/workflows/publish-package.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
name: publish-package

on:
workflow_dispatch:
push:
branches:
- main

jobs:
release-please:
runs-on: ubuntu-latest
steps:
- uses: google-github-actions/release-please-action@v3
with:
release-type: node
package-name: "@keyrxng/rpc-handler"
default-branch: development
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "20.10.0"
registry-url: https://registry.npmjs.org/
- run: |
yarn install --immutable --immutable-cache --check-cache
yarn build
yarn pack
yarn publish --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_ACCESS_TOKEN }}
94 changes: 65 additions & 29 deletions build/esbuild-build.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import esbuild from "esbuild";
import chainlist from "../lib/chainlist/constants/extraRpcs";
import chainIDList from "../lib/chainlist/constants/chainIds.json";
import path from "path";
import * as fs from "fs";

const typescriptEntries = ["src/rpc-handler.ts", "src/constants.ts", "src/handler.ts", "src/services/rpc-service.ts", "src/services/storage-service.ts"];
const typescriptEntries = ["index.ts"];
export const entries = [...typescriptEntries];
const extraRpcs: Record<string, string[]> = {};
// this flattens all the rpcs into a single object, with key names that match the networkIds. The arrays are just of URLs per network ID.
Expand All @@ -17,44 +19,71 @@ Object.keys(chainlist).forEach((networkId) => {
export const esBuildContext: esbuild.BuildOptions = {
entryPoints: entries,
bundle: true,
minify: true,

outdir: "dist",
define: createEnvDefines({ extraRpcs, chainIDList }),
};

esbuild
.build({
...esBuildContext,
tsconfig: "tsconfig.node.json",
platform: "node",
outdir: "dist/cjs/src",
format: "cjs",
})
.then(() => {
console.log("Node.js esbuild complete");
})
.catch((err) => {
async function main() {
try {
await buildForEnvironments();
await buildIndex();
} catch (err) {
console.error(err);
process.exit(1);
});
}
}

esbuild
.build({
...esBuildContext,
tsconfig: "tsconfig.web.json",
platform: "browser",
outdir: "dist/esm/src",
format: "esm",
})
.then(() => {
console.log("Frontend esbuild complete");
})
.catch((err) => {
console.error(err);
process.exit(1);
main();

async function buildForEnvironments() {
ensureDistDir();

await esbuild
.build({
...esBuildContext,
tsconfig: "tsconfig.node.json",
platform: "node",
outdir: "dist/cjs",
format: "cjs",
})
.then(() => {
console.log("Node.js esbuild complete");
})
.catch((err) => {
console.error(err);
process.exit(1);
});

esbuild
.build({
...esBuildContext,
tsconfig: "tsconfig.web.json",
platform: "browser",
outdir: "dist/esm",
format: "esm",
})
.then(() => {
console.log("Frontend esbuild complete");
})
.catch((err) => {
console.error(err);
process.exit(1);
});
}

async function buildIndex() {
await esbuild.build({
entryPoints: ["index.ts"],
bundle: true,
format: "cjs",
outfile: "dist/index.js",
define: createEnvDefines({ extraRpcs, chainIDList }),
});

console.log("Index build complete.");
}

function createEnvDefines(generatedAtBuild: Record<string, unknown>): Record<string, string> {
const defines: Record<string, string> = {};

Expand All @@ -64,3 +93,10 @@ function createEnvDefines(generatedAtBuild: Record<string, unknown>): Record<str

return defines;
}

function ensureDistDir() {
const distPath = path.resolve(__dirname, "dist");
if (!fs.existsSync(distPath)) {
fs.mkdirSync(distPath, { recursive: true });
}
}
86 changes: 86 additions & 0 deletions build/tests-esbuild-build.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import esbuild from "esbuild";
import chainlist from "../lib/chainlist/constants/extraRpcs";
import chainIDList from "../lib/chainlist/constants/chainIds.json";
import path from "path";
import * as fs from "fs";

const typescriptEntries = ["tests/mocks/rpc-service.ts", "tests/mocks/rpc-handler.ts", "tests/mocks/constants.ts", "tests/mocks/handler.ts"];
export const entries = [...typescriptEntries];
const extraRpcs: Record<string, string[]> = {};
// this flattens all the rpcs into a single object, with key names that match the networkIds. The arrays are just of URLs per network ID.

Object.keys(chainlist).forEach((networkId) => {
const officialUrls = chainlist[networkId].rpcs.filter((rpc) => typeof rpc === "string");
const extraUrls: string[] = chainlist[networkId].rpcs.filter((rpc) => rpc.url !== undefined && rpc.tracking === "none").map((rpc) => rpc.url);

extraRpcs[networkId] = [...officialUrls, ...extraUrls].filter((rpc) => rpc.startsWith("https://"));
});

export const esBuildContext: esbuild.BuildOptions = {
entryPoints: entries,
bundle: true,

outdir: "dist",
define: createEnvDefines({ extraRpcs, chainIDList }),
};

async function main() {
try {
await buildForEnvironments();
await buildIndex();
} catch (err) {
console.error(err);
process.exit(1);
}
}

main();

async function buildForEnvironments() {
ensureDistDir();

await esbuild
.build({
...esBuildContext,
tsconfig: "tsconfig.tests.json",
platform: "node",
outdir: "dist/tests/mocks",
format: "cjs",
})
.then(() => {
console.log("Node.js esbuild complete");
})
.catch((err) => {
console.error(err);
process.exit(1);
});
}

async function buildIndex() {
await esbuild.build({
entryPoints: ["index.ts"],
bundle: true,
format: "cjs",
outfile: "dist/index.js",
define: createEnvDefines({ extraRpcs, chainIDList }),
});

console.log("Index build complete.");
}

function createEnvDefines(generatedAtBuild: Record<string, unknown>): Record<string, string> {
const defines: Record<string, string> = {};

Object.keys(generatedAtBuild).forEach((key) => {
defines[key] = JSON.stringify(generatedAtBuild[key]);
});

return defines;
}

function ensureDistDir() {
const distPath = path.resolve(__dirname, "dist");
if (!fs.existsSync(distPath)) {
fs.mkdirSync(distPath, { recursive: true });
}
}
77 changes: 77 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
export default async function getRPCHandler() {
let modulePath;
if (typeof window !== "undefined") {
modulePath = "./esm/index.js";
} else {
modulePath = "./cjs/index.js";
}

const { RPCHandler } = await import(modulePath);

return RPCHandler;
}

import {
ChainId,
ChainNames,
HandlerConstructorConfig,
HandlerInterface,
NativeToken,
NetworkCurrencies,
NetworkExplorers,
NetworkIds,
NetworkNames,
NetworkRPCs,
Token,
Tokens,
ValidBlockData,
} from "./types/handler";

import {
LOCAL_HOST,
chainIDList,
extraRpcs,
getNetworkName,
networkCurrencies,
networkExplorers,
networkIds,
networkNames,
networkRpcs,
nftAddress,
permit2Address,
tokens,
} from "./types/constants";

import { RPCHandler } from "./types/rpc-handler";

export {
LOCAL_HOST,
chainIDList,
extraRpcs,
getNetworkName,
networkCurrencies,
networkExplorers,
networkIds,
networkNames,
networkRpcs,
nftAddress,
permit2Address,
tokens,
};

export type {
ChainId,
ChainNames,
HandlerConstructorConfig,
HandlerInterface,
NativeToken,
NetworkCurrencies,
NetworkExplorers,
NetworkIds,
NetworkNames,
NetworkRPCs,
Token,
Tokens,
ValidBlockData,
};
export { RPCHandler };
21 changes: 11 additions & 10 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
"name": "@ubiquitydao/rpc-handler",
"version": "1.0.0",
"description": "Uses Chainlist's RPC collection racing them returning the lowest latency RPC",
"main": "dist/cjs/rpc-handler.js",
"module": "dist/esm/rpc-handler.js",
"types": "src/index.ts",
"main": "dist/cjs/index.js",
"module": "dist/esm/index.js",
"types": "dist/index.d.ts",
"author": "Ubiquity",
"license": "MIT",
"files": [
Expand All @@ -21,12 +21,12 @@
"knip": "knip",
"knip-ci": "knip --no-exit-code --reporter json",
"prepare": "husky install",
"build:cjs": "tsc --emitDeclarationOnly --outDir dist/cjs/src",
"build:esm": "tsc --emitDeclarationOnly --outDir dist/esm/src",
"build": "tsx build/esbuild-build.ts",
"postbuild": "yarn build:cjs && yarn build:esm",
"build:types": "tsc --emitDeclarationOnly --declaration --outDir dist && rm -rf dist/src",
"build:tests": "tsx build/tests-esbuild-build.ts && tsc --emitDeclarationOnly --declaration --project tsconfig.tests.json",
"build": "rm -rf dist && tsx build/esbuild-build.ts",
"postbuild": "yarn build:types",
"postinstall": "git submodule update --init --recursive",
"test": "jest"
"test": "rm -rf dist && yarn build:tests && jest"
},
"keywords": [
"typescript",
Expand All @@ -36,7 +36,8 @@
"open-source"
],
"dependencies": {
"@ethersproject/providers": "5.7.2"
"@ethersproject/providers": "5.7.2",
"axios": "^1.6.8"
},
"devDependencies": {
"@babel/core": "^7.24.0",
Expand Down Expand Up @@ -83,4 +84,4 @@
"@commitlint/config-conventional"
]
}
}
}
Loading
Loading