Skip to content

Commit

Permalink
Updated main function to handle generics
Browse files Browse the repository at this point in the history
  • Loading branch information
uditdc committed Mar 20, 2024
1 parent 0415b79 commit 93e7c31
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 14 deletions.
9 changes: 6 additions & 3 deletions examples/stdin/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { InputProps, entryMain } from '@blockless/sdk-ts'
import { main, readInput } from '../../lib'
import { AbiCoder } from 'ethers'

interface Arguments {
n: number
v: string
}

entryMain(async (input: InputProps<Arguments>) => {
console.log('\n Example: Stdin')
main(async() => {
console.log('\nExample: Stdin')

// Read input arguments
const input = readInput<Arguments>()

if (Object.keys(input.args).length === 0) {
console.log('Missing args.')
Expand Down
5 changes: 1 addition & 4 deletions examples/stdin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,9 @@
"main": "index.ts",
"private": true,
"scripts": {
"build": "bls-sdk-ts build ./index.ts",
"build": "../../dist/bundler/index.js build ./index.ts",
"invoke": "echo '{ \"n\": 2, \"v\": \"abc\" }' | bls-runtime-deno build/index.wasm"
},
"devDependencies": {
"@blockless/sdk-ts": "file:../.."
},
"dependencies": {
"ethers": "^6.11.1"
}
Expand Down
27 changes: 21 additions & 6 deletions lib/entry.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,24 @@
import { InputProps, readInput, writeOutput } from './stdin'
import { writeOutput } from './stdin'

export async function entryMain<T>(
cb: (input: InputProps<T>) => Promise<object>
): Promise<void> {
const input = readInput<T>()
const result = await cb(input)
type EntryCallback<T extends object> = () => T
type EntryCallbackAsync<T extends object> = () => Promise<T>

export function main<T extends object>(cb: EntryCallback<T>): T
export async function main<T extends object>(cb: EntryCallbackAsync<T>): Promise<T>
export async function main<T extends object>(cb: EntryCallback<T> | EntryCallbackAsync<T>): Promise<T> {
if (isPromiseCallback(cb)) {
const result = await cb()
writeOutput(result)

return result
}

const result = cb()
writeOutput(result)

return result
}

function isPromiseCallback<T extends object>(cb: EntryCallback<T> | EntryCallbackAsync<T>): cb is EntryCallbackAsync<T> {
return typeof cb === 'function' && cb.length === 0;
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@blockless/sdk-ts",
"version": "1.0.0",
"version": "1.0.1",
"type": "module",
"module": "dist/lib/index.js",
"types": "dist/lib/index.d.ts",
Expand Down

0 comments on commit 93e7c31

Please sign in to comment.