From 0827303baec063a444abb996d14b60978e88dbc5 Mon Sep 17 00:00:00 2001 From: Alex Freska Date: Tue, 3 Dec 2024 13:06:24 -0500 Subject: [PATCH] refactor(sia_js): universal js sdk --- sia_js/example/nodejs/index.js | 2 +- sia_js/example/nodejs/package.json | 1 + sia_js/scripts/patch.mjs | 36 ++++++++++++++++++++++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 sia_js/scripts/patch.mjs diff --git a/sia_js/example/nodejs/index.js b/sia_js/example/nodejs/index.js index 89c3770..4383d34 100644 --- a/sia_js/example/nodejs/index.js +++ b/sia_js/example/nodejs/index.js @@ -1,4 +1,4 @@ -import { Seed, UnlockConditions } from "sia_js"; +import { Seed, UnlockConditions, Transaction } from "sia_js"; try { const s = Seed.generate(), diff --git a/sia_js/example/nodejs/package.json b/sia_js/example/nodejs/package.json index 80d59bb..e26642d 100644 --- a/sia_js/example/nodejs/package.json +++ b/sia_js/example/nodejs/package.json @@ -5,6 +5,7 @@ "author": "", "license": "MIT", "description": "", + "type":"module", "dependencies": { "sia_js": "file:../../pkg" } diff --git a/sia_js/scripts/patch.mjs b/sia_js/scripts/patch.mjs new file mode 100644 index 0000000..660ecc0 --- /dev/null +++ b/sia_js/scripts/patch.mjs @@ -0,0 +1,36 @@ +import fs from 'node:fs/promises'; + +const packageName = 'sia_js'; +const wasmFilename = 'sia_js_bg.wasm'; +const jsFilename = 'sia_js.js'; + +const rawWasmFile = await fs.readFile(`pkg/${wasmFilename}`); +const origJsFile = await fs.readFile(`pkg/${jsFilename}`, 'utf8'); + +const base64 = rawWasmFile.toString('base64'); + +// Remove NodeJS specific APIs and inline WASM. +const patchedJsFile = origJsFile + // TextEncoder and TextDecoder are globally available in NodeJS and browsers. + // inspect and inspect.custom are NodeJS specific APIs, replace with polyfill. + .replace('const { TextEncoder, TextDecoder, inspect } = require(`util`);',` +const inspect = (obj) => JSON.stringify(obj, null, 2); `) + .replace('[inspect.custom]', `[Symbol.for('nodejs.util.inspect.custom')]`) + // Inline WASM. + .replace(`const path = require('path').join(__dirname, '${wasmFilename}');`, '') + .replace(`const bytes = require('fs').readFileSync(path);`, ` +const wasmBase64 = '${base64}'; +const bytes = Uint8Array.from(atob(wasmBase64), c => c.charCodeAt(0));`); + +await fs.writeFile(`pkg/${jsFilename}`, patchedJsFile); + +// Remove WASM files. +await fs.unlink(`pkg/${wasmFilename}`); +await fs.unlink(`pkg/${wasmFilename}.d.ts`); + +// Remove WASM from .files section of package.json. +const pkgJsonFile = await fs.readFile('pkg/package.json', 'utf8'); +const pkgJson = JSON.parse(pkgJsonFile); +pkgJson.name = packageName; +pkgJson.files = pkgJson.files.filter(file => file !== wasmFilename); +await fs.writeFile('pkg/package.json', JSON.stringify(pkgJson, null, 2));