From 7a32ddc45ceda2148b3cbe203157abe1c348ca59 Mon Sep 17 00:00:00 2001 From: Alberto Ricart Date: Thu, 14 Jul 2022 13:28:28 -0500 Subject: [PATCH] adding a shim --- bin/tweetnacl-esm.ts | 18 ++++++++++++++++++ modules/esm/nacl.d.ts | 17 +++++++++++++++++ modules/esm/nacl.js | 17 +++++++++++++++++ 3 files changed, 52 insertions(+) diff --git a/bin/tweetnacl-esm.ts b/bin/tweetnacl-esm.ts index dd8d7d1..c894a3e 100644 --- a/bin/tweetnacl-esm.ts +++ b/bin/tweetnacl-esm.ts @@ -7,6 +7,24 @@ async function copyFromModulesDir(from: string, tail = ""): Promise { const head =`// this source from node_modules/tweetnacl@${version}/${from}\n // deno-lint-ignore-file // deno-fmt-ignore-file + +// added by nkeys.js +// shim for crypto.randomBytes on nodejs when using the esm module of the nkeys.js library +if (!globalThis.crypto) { + console.log("shimming crypto.randomBytes") + if (typeof module !== "undefined") { + globalThis.crypto = require("crypto"); + console.log("shimmed with node crypto"); + } else { + globalThis.crypto = { + randomBytes: (a) => { + for (let i = 0; i < a.length; i++) { + a[i] = Math.floor(256 * Math.random()); + } + }, + }; + } +} `; let src = await Deno.readTextFile( diff --git a/modules/esm/nacl.d.ts b/modules/esm/nacl.d.ts index b9ce633..74a6c15 100644 --- a/modules/esm/nacl.d.ts +++ b/modules/esm/nacl.d.ts @@ -2,6 +2,23 @@ // deno-lint-ignore-file // deno-fmt-ignore-file + +// added by nkeys.js +// shim for crypto.randomBytes on nodejs when using the esm module of the nkeys.js library +if (!globalThis.crypto) { + console.log("shimming crypto.randomBytes") + if (typeof module !== "undefined") { + globalThis.crypto = require("crypto"); + } else { + globalThis.crypto = { + randomBytes: (a) => { + for (let i = 0; i < a.length; i++) { + a[i] = Math.floor(256 * Math.random()); + } + }, + }; + } +} // Type definitions for TweetNaCl.js export as namespace nacl; diff --git a/modules/esm/nacl.js b/modules/esm/nacl.js index f24f5d9..9c9aa51 100644 --- a/modules/esm/nacl.js +++ b/modules/esm/nacl.js @@ -2,6 +2,23 @@ // deno-lint-ignore-file // deno-fmt-ignore-file + +// added by nkeys.js +// shim for crypto.randomBytes on nodejs when using the esm module of the nkeys.js library +if (!globalThis.crypto) { + console.log("shimming crypto.randomBytes") + if (typeof module !== "undefined") { + globalThis.crypto = require("crypto"); + } else { + globalThis.crypto = { + randomBytes: (a) => { + for (let i = 0; i < a.length; i++) { + a[i] = Math.floor(256 * Math.random()); + } + }, + }; + } +} (function(nacl) { 'use strict';