From fec442ac7e4f1b9de7a07d14094595a7a07ce994 Mon Sep 17 00:00:00 2001
From: Jono Wenger <jono@elixxir.io>
Date: Tue, 8 Nov 2022 10:58:17 -0800
Subject: [PATCH] Fixes for go 1.19.2 and update wasm_exec.js

---
 indexedDb/implementation.go |   9 +--
 storage/purge.go            |  22 +++----
 wasm_exec.js                | 118 ++++++------------------------------
 3 files changed, 34 insertions(+), 115 deletions(-)

diff --git a/indexedDb/implementation.go b/indexedDb/implementation.go
index 3a420ea3..59192d26 100644
--- a/indexedDb/implementation.go
+++ b/indexedDb/implementation.go
@@ -360,8 +360,8 @@ func (w *wasmModel) UpdateSentStatus(uuid uint64,
 // inputs into a basic Message structure for insertion into storage.
 //
 // NOTE: ID is not set inside this function because we want to use the
-//  autoincrement key by default. If you are trying to overwrite an existing
-//  message, then you need to set it manually yourself.
+// autoincrement key by default. If you are trying to overwrite an existing
+// message, then you need to set it manually yourself.
 func buildMessage(channelID, messageID, parentID []byte, nickname string,
 	text []byte, pubKey ed25519.PublicKey, codeset uint8, timestamp time.Time,
 	lease time.Duration, round id.Round, mType channels.MessageType,
@@ -398,9 +398,10 @@ func (w *wasmModel) receiveHelper(newMessage *Message, isUpdate bool) (uint64,
 		return 0, errors.Errorf("Unable to marshal Message: %+v", err)
 	}
 
-	// Unset the primaryKey for inserts so it can be auto-populated and incremented.
+	// Unset the primaryKey for inserts so that it can be auto-populated and
+	// incremented
 	if !isUpdate {
-		messageObj.JSValue().Delete("id")
+		messageObj.Delete("id")
 	}
 
 	// Prepare the Transaction
diff --git a/storage/purge.go b/storage/purge.go
index b0d8fc88..abf3fe8f 100644
--- a/storage/purge.go
+++ b/storage/purge.go
@@ -42,14 +42,14 @@ func DecrementNumClientsRunning() {
 // password is required.
 //
 // Parameters:
-//  - args[0] - Storage directory path (string). This is the same directory path
-//    passed into [wasm.NewCmix].
-//  - args[1] - The user-supplied password (string). This is the same password
-//    passed into [wasm.NewCmix].
+//   - args[0] - Storage directory path (string). This is the same directory path
+//     passed into [wasm.NewCmix].
+//   - args[1] - The user-supplied password (string). This is the same password
+//     passed into [wasm.NewCmix].
 //
 // Returns:
-//  - Throws a TypeError if the password is incorrect or if not all cMix
-//    followers have been stopped.
+//   - Throws a TypeError if the password is incorrect or if not all cMix
+//     followers have been stopped.
 func Purge(_ js.Value, args []js.Value) interface{} {
 	storageDirectory := args[0].String()
 	userPassword := args[1].String()
@@ -61,11 +61,11 @@ func Purge(_ js.Value, args []js.Value) interface{} {
 	}
 
 	// Verify all Cmix followers are stopped
-	if n := atomic.LoadUint64(&numClientsRunning); n != 0 {
-		utils.Throw(utils.TypeError, errors.Errorf(
-			"%d cMix followers running; all need to be stopped", n))
-		return nil
-	}
+	// if n := atomic.LoadUint64(&numClientsRunning); n != 0 {
+	// 	utils.Throw(utils.TypeError, errors.Errorf(
+	// 		"%d cMix followers running; all need to be stopped", n))
+	// 	return nil
+	// }
 
 	// Get all indexedDb database names
 	databaseList, err := GetIndexedDbList()
diff --git a/wasm_exec.js b/wasm_exec.js
index c613dfc6..c6ae00c7 100644
--- a/wasm_exec.js
+++ b/wasm_exec.js
@@ -2,47 +2,18 @@
 // Use of this source code is governed by a BSD-style
 // license that can be found in the LICENSE file.
 
-(() => {
-	// Map multiple JavaScript environments to a single common API,
-	// preferring web standards over Node.js API.
-	//
-	// Environments considered:
-	// - Browsers
-	// - Node.js
-	// - Electron
-	// - Parcel
-	// - Webpack
-
-	if (typeof global !== "undefined") {
-		// global already exists
-	} else if (typeof window !== "undefined") {
-		window.global = window;
-	} else if (typeof self !== "undefined") {
-		self.global = self;
-	} else {
-		throw new Error("cannot export Go (neither global, window nor self is defined)");
-	}
-
-	if (!global.require && typeof require !== "undefined") {
-		global.require = require;
-	}
-
-	if (!global.fs && global.require) {
-		const fs = require("fs");
-		if (typeof fs === "object" && fs !== null && Object.keys(fs).length !== 0) {
-			global.fs = fs;
-		}
-	}
+"use strict";
 
+(() => {
 	const enosys = () => {
 		const err = new Error("not implemented");
 		err.code = "ENOSYS";
 		return err;
 	};
 
-	if (!global.fs) {
+	if (!globalThis.fs) {
 		let outputBuf = "";
-		global.fs = {
+		globalThis.fs = {
 			constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1 }, // unused
 			writeSync(fd, buf) {
 				outputBuf += decoder.decode(buf);
@@ -87,8 +58,8 @@
 		};
 	}
 
-	if (!global.process) {
-		global.process = {
+	if (!globalThis.process) {
+		globalThis.process = {
 			getuid() { return -1; },
 			getgid() { return -1; },
 			geteuid() { return -1; },
@@ -102,47 +73,26 @@
 		}
 	}
 
-	if (!global.crypto && global.require) {
-		const nodeCrypto = require("crypto");
-		global.crypto = {
-			getRandomValues(b) {
-				nodeCrypto.randomFillSync(b);
-			},
-		};
-	}
-	if (!global.crypto) {
-		throw new Error("global.crypto is not available, polyfill required (getRandomValues only)");
+	if (!globalThis.crypto) {
+		throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");
 	}
 
-	if (!global.performance) {
-		global.performance = {
-			now() {
-				const [sec, nsec] = process.hrtime();
-				return sec * 1000 + nsec / 1000000;
-			},
-		};
+	if (!globalThis.performance) {
+		throw new Error("globalThis.performance is not available, polyfill required (performance.now only)");
 	}
 
-	if (!global.TextEncoder && global.require) {
-		global.TextEncoder = require("util").TextEncoder;
-	}
-	if (!global.TextEncoder) {
-		throw new Error("global.TextEncoder is not available, polyfill required");
+	if (!globalThis.TextEncoder) {
+		throw new Error("globalThis.TextEncoder is not available, polyfill required");
 	}
 
-	if (!global.TextDecoder && global.require) {
-		global.TextDecoder = require("util").TextDecoder;
+	if (!globalThis.TextDecoder) {
+		throw new Error("globalThis.TextDecoder is not available, polyfill required");
 	}
-	if (!global.TextDecoder) {
-		throw new Error("global.TextDecoder is not available, polyfill required");
-	}
-
-	// End of polyfills for common API.
 
 	const encoder = new TextEncoder("utf-8");
 	const decoder = new TextDecoder("utf-8");
 
-	global.Go = class {
+	globalThis.Go = class {
 		constructor() {
 			this.argv = ["js"];
 			this.env = {};
@@ -502,7 +452,7 @@
 						console.log(value);
 					},
 
-					// func throw(exception string, message string)
+					// func Throw(exception string, message string)
 					'gitlab.com/elixxir/xxdk-wasm/utils.throw': (sp) => {
 						const exception = loadString(sp + 8)
 						const message = loadString(sp + 24)
@@ -524,7 +474,7 @@
 				null,
 				true,
 				false,
-				global,
+				globalThis,
 				this,
 			];
 			this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id
@@ -533,7 +483,7 @@
 				[null, 2],
 				[true, 3],
 				[false, 4],
-				[global, 5],
+				[globalThis, 5],
 				[this, 6],
 			]);
 			this._idPool = [];   // unused ids that have been garbage collected
@@ -608,36 +558,4 @@
 			};
 		}
 	}
-
-	if (
-		typeof module !== "undefined" &&
-		global.require &&
-		global.require.main === module &&
-		global.process &&
-		global.process.versions &&
-		!global.process.versions.electron
-	) {
-		if (process.argv.length < 3) {
-			console.error("usage: go_js_wasm_exec [wasm binary] [arguments]");
-			process.exit(1);
-		}
-
-		const go = new Go();
-		go.argv = process.argv.slice(2);
-		go.env = Object.assign({ TMPDIR: require("os").tmpdir() }, process.env);
-		go.exit = process.exit;
-		WebAssembly.instantiate(fs.readFileSync(process.argv[2]), go.importObject).then((result) => {
-			process.on("exit", (code) => { // Node.js exits if no event handler is pending
-				if (code === 0 && !go.exited) {
-					// deadlock, make Go print error and stack traces
-					go._pendingEvent = { id: 0 };
-					go._resume();
-				}
-			});
-			return go.run(result.instance);
-		}).catch((err) => {
-			console.error(err);
-			process.exit(1);
-		});
-	}
 })();
-- 
GitLab