From d4516a756c6fab4f824096debaf0198e38cea37f Mon Sep 17 00:00:00 2001
From: Kegan Dougal <kegan@matrix.org>
Date: Fri, 22 May 2020 11:06:59 +0100
Subject: [PATCH] Add IDBFS support

---
 Makefile                          |  5 +++--
 src/api.js                        | 11 ++++++++---
 src/exported_runtime_methods.json |  5 ++++-
 3 files changed, 15 insertions(+), 6 deletions(-)

diff --git a/Makefile b/Makefile
index 4031c258..9bd3f359 100644
--- a/Makefile
+++ b/Makefile
@@ -35,6 +35,8 @@ EMFLAGS = \
 	-s EXPORTED_FUNCTIONS=@src/exported_functions.json \
 	-s EXTRA_EXPORTED_RUNTIME_METHODS=@src/exported_runtime_methods.json \
 	-s SINGLE_FILE=0 \
+	-s FORCE_FILESYSTEM=1 \
+	-lidbfs.js \
 	-s NODEJS_CATCH_EXIT=0
 
 EMFLAGS_ASM = \
@@ -52,8 +54,7 @@ EMFLAGS_OPTIMIZED= \
 	-s INLINING_LIMIT=50 \
 	-O3 \
 	-flto \
-	--llvm-lto 1 \
-	--closure 1
+	--llvm-lto 1
 
 EMFLAGS_DEBUG = \
 	-s INLINING_LIMIT=10 \
diff --git a/src/api.js b/src/api.js
index 1484063d..993ab184 100644
--- a/src/api.js
+++ b/src/api.js
@@ -621,13 +621,18 @@ Module["onRuntimeInitialized"] = function onRuntimeInitialized() {
     * @memberof module:SqlJs
     * Open a new database either by creating a new one or opening an existing
     * one stored in the byte array passed in first argument
-    * @param {number[]} data An array of bytes representing
-    * an SQLite database file
+    * @param {number[]|string} data An array of bytes representing
+    * an SQLite database file. Alternatively, a file path representing the
+    * file to load if using IDBFS.
     */
     function Database(data) {
         this.filename = "dbfile_" + (0xffffffff * Math.random() >>> 0);
         if (data != null) {
-            FS.createDataFile("/", this.filename, data, true, true);
+            if (typeof data === "string") {
+                this.filename = data;
+            } else {
+                FS.createDataFile("/", this.filename, data, true, true);
+            }
         }
         this.handleError(sqlite3_open(this.filename, apiTemp));
         this.db = getValue(apiTemp, "i32");
diff --git a/src/exported_runtime_methods.json b/src/exported_runtime_methods.json
index 644fd3ea..aef61556 100644
--- a/src/exported_runtime_methods.json
+++ b/src/exported_runtime_methods.json
@@ -2,5 +2,8 @@
 "cwrap",
 "stackAlloc",
 "stackSave",
-"stackRestore"
+"stackRestore",
+"FS",
+"MEMFS",
+"IDBFS"
 ]