[WASM] Converted mono-config.js to mono-config.json (#53606)
authorDaniel Genkin <genkind@gmail.com>
Mon, 21 Jun 2021 14:10:58 +0000 (10:10 -0400)
committerGitHub <noreply@github.com>
Mon, 21 Jun 2021 14:10:58 +0000 (11:10 -0300)
* converted mono-config.js to mono-config.json

* Fixed test

* fixed handling of case where Module isn't defined

* Fixed remaining failing tests

* Replaced alerts with console.log to fix Helix test

* replaced all vars with consts

* use fetch

* clean syntax

* prevent timeouts when the mono-config file fails to load

* Moved config file loading to preInit

* Fixed tests

* Adjusted file linking

* removed the unnecessary js_support.js

* cleaned up function

* updated samples

* removed lingering pre-js flag

* Fixed trimming tests

* addressed PR comments

* removed useless function

19 files changed:
src/mono/sample/mbr/browser/index.html
src/mono/sample/mbr/browser/runtime.js
src/mono/sample/wasm/browser-bench/index.html
src/mono/sample/wasm/browser-bench/runtime.js
src/mono/sample/wasm/browser-profile/index.html
src/mono/sample/wasm/browser-profile/runtime.js
src/mono/sample/wasm/browser/index.html
src/mono/sample/wasm/browser/runtime.js
src/mono/wasm/build/WasmApp.targets
src/mono/wasm/debugger/tests/debugger-test/debugger-driver.html
src/mono/wasm/debugger/tests/debugger-test/runtime-debugger.js
src/mono/wasm/runtime-test.js
src/mono/wasm/runtime/library_mono.js
src/tasks/WasmAppBuilder/WasmAppBuilder.cs
src/tests/BuildWasmApps/Wasm.Build.Tests/BuildTestBase.cs
src/tests/FunctionalTests/WebAssembly/Browser/AOT/index.html
src/tests/FunctionalTests/WebAssembly/Browser/AOT/runtime.js
src/tests/FunctionalTests/WebAssembly/Browser/NormalInterp/index.html
src/tests/FunctionalTests/WebAssembly/Browser/NormalInterp/runtime.js

index 472cf5f..eb19b7b 100644 (file)
@@ -29,7 +29,6 @@
         },
       };
     </script>
-    <script type="text/javascript" src="mono-config.js"></script>
     <script type="text/javascript" src="runtime.js"></script>
 
     <script defer src="dotnet.js"></script>
index 0856b8d..32918aa 100644 (file)
@@ -2,17 +2,29 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 
 var Module = { 
+    config: null,
+
+    preInit: async function() {
+        Module.config = await MONO.mono_wasm_load_config("./mono-config.json");
+    },
+
+    // Called when the runtime is initialized and wasm is ready
     onRuntimeInitialized: function () {
-        config.loaded_cb = function () {
+        if (!Module.config || Module.config.error) {
+            console.log("An error occured while loading the config file");
+            return;
+        }
+
+        Module.config.loaded_cb = function () {
             App.init ();
         };
-        config.environment_variables = {
+        Module.config.environment_variables = {
             "DOTNET_MODIFIABLE_ASSEMBLIES": "debug"
         };
-        config.fetch_file_cb = function (asset) {
+        Module.config.fetch_file_cb = function (asset) {
             return fetch (asset, { credentials: 'same-origin' });
         }
 
-        MONO.mono_load_runtime_and_bcl_args (config);
+        MONO.mono_load_runtime_and_bcl_args (Module.config);
     },
 };
index 8f77487..5c52719 100644 (file)
@@ -51,7 +51,6 @@
         }
       };
     </script>
-    <script type="text/javascript" src="mono-config.js"></script>
     <script type="text/javascript" src="runtime.js"></script>
 
     <script defer src="dotnet.js"></script>
index a39b0b9..60c383d 100644 (file)
@@ -1,9 +1,20 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
-
 var Module = { 
+    config: null,
+
+    preInit: async function() {
+        Module.config = await MONO.mono_wasm_load_config("./mono-config.json");
+    },
+
+    // Called when the runtime is initialized and wasm is ready
     onRuntimeInitialized: function () {
-        config.loaded_cb = function () {
+        if (!Module.config || Module.config.error) {
+            console.log("An error occured while loading the config file");
+            return;
+        }
+
+        Module.config.loaded_cb = function () {
             try {
                 App.init ();
             } catch (error) {
@@ -11,13 +22,21 @@ var Module = {
                 throw (error);
             }
         };
-        config.fetch_file_cb = function (asset) {
+        Module.config.fetch_file_cb = function (asset) {
             return fetch (asset, { credentials: 'same-origin' });
         }
 
+        if (Module.config.enable_profiler)
+        {
+            Module.config.aot_profiler_options = {
+                write_at:"Sample.Test::StopProfile",
+                send_to: "System.Runtime.InteropServices.JavaScript.Runtime::DumpAotProfileData"
+            }
+        }
+
         try
         {
-            MONO.mono_load_runtime_and_bcl_args (config);
+            MONO.mono_load_runtime_and_bcl_args (Module.config);
         } catch (error) {
             test_exit(1);
             throw(error);
index 50eb0ff..de4a559 100644 (file)
   <body>
     <h3 id="header">Wasm Browser Sample</h3>
     Result from Sample.Test.TestMeaning: <span id="out"></span>
-    <script type='text/javascript'>
-      var is_testing = false;
-      var onLoad = function() {
-        var url = new URL(decodeURI(window.location));
-        let args = url.searchParams.getAll('arg');
-        is_testing = args !== undefined && (args.find(arg => arg == '--testing') !== undefined);
-      };
 
-      var test_exit = function(exit_code)
-      {
-        if (!is_testing) {
-          console.log(`test_exit: ${exit_code}`);
-          return;
-        }
-
-        /* Set result in a tests_done element, to be read by xharness */
-        var tests_done_elem = document.createElement("label");
-        tests_done_elem.id = "tests_done";
-        tests_done_elem.innerHTML = exit_code.toString();
-        document.body.appendChild(tests_done_elem);
-
-        console.log(`WASM EXIT ${exit_code}`);
-      };
-
-      var App = {
-        init: function () {
-          var ret = BINDING.call_static_method("[Wasm.BrowserProfile.Sample] Sample.Test:TestMeaning", []);
-          document.getElementById("out").innerHTML = ret;
-          console.log ("ready");
-
-          if (is_testing)
-          {
-            console.debug(`ret: ${ret}`);
-            let exit_code = ret == 42 ? 0 : 1;
-            test_exit(exit_code);
-          }
-
-          if (config.enable_profiler) {
-            BINDING.call_static_method("[Wasm.BrowserProfile.Sample] Sample.Test:StopProfile", []);
-            saveProfile();
-          }
-        },
-      };
-
-      function saveProfile() {
-        var a = document.createElement('a');
-        var blob = new Blob([Module.aot_profile_data]);
-        a.href = URL.createObjectURL(blob);
-        a.download = "data.aotprofile";
-        // Append anchor to body.
-        document.body.appendChild(a);
-        a.click();
-
-        // Remove anchor from body
-        document.body.removeChild(a);
-      }
-
-    </script>
-    <script type="text/javascript" src="mono-config.js"></script>
     <script type="text/javascript" src="runtime.js"></script>
-
     <script defer src="dotnet.js"></script>
 
   </body>
index 1ce1c0b..2c83ff5 100644 (file)
@@ -1,22 +1,35 @@
 // Licensed to the .NET Foundation under one or more agreements.
 // The .NET Foundation licenses this file to you under the MIT license.
-var Module = {
+var Module = { 
+    is_testing: false,
+    config: null,
+
+    preInit: async function() {
+        Module.config = await MONO.mono_wasm_load_config("./mono-config.json");
+    },
+
+    // Called when the runtime is initialized and wasm is ready
     onRuntimeInitialized: function () {
-        config.loaded_cb = function () {
+        if (!Module.config || Module.config.error) {
+            console.log("An error occured while loading the config file");
+            return;
+        }
+
+        Module.config.loaded_cb = function () {
             try {
-                App.init ();
+                Module.init();
             } catch (error) {
-                test_exit(1);
+                Module.test_exit(1);
                 throw (error);
             }
         };
-        config.fetch_file_cb = function (asset) {
+        Module.config.fetch_file_cb = function (asset) {
             return fetch (asset, { credentials: 'same-origin' });
         }
 
-        if (config.enable_profiler)
+        if (Module.config.enable_profiler)
         {
-            config.aot_profiler_options = {
+            Module.config.aot_profiler_options = {
                 write_at:"Sample.Test::StopProfile",
                 send_to: "System.Runtime.InteropServices.JavaScript.Runtime::DumpAotProfileData"
             }
@@ -24,10 +37,63 @@ var Module = {
 
         try
         {
-            MONO.mono_load_runtime_and_bcl_args (config);
+            MONO.mono_load_runtime_and_bcl_args (Module.config);
         } catch (error) {
-            test_exit(1);
+            Module.test_exit(1);
             throw(error);
         }
+    },
+
+    init: function () {
+        console.log("not ready yet")
+        var ret = BINDING.call_static_method("[Wasm.BrowserProfile.Sample] Sample.Test:TestMeaning", []);
+        document.getElementById("out").innerHTML = ret;
+        console.log ("ready");
+
+        if (Module.is_testing)
+        {
+          console.debug(`ret: ${ret}`);
+          let exit_code = ret == 42 ? 0 : 1;
+          Module.test_exit(exit_code);
+        }
+
+        if (Module.config.enable_profiler) {
+          BINDING.call_static_method("[Wasm.BrowserProfile.Sample] Sample.Test:StopProfile", []);
+          Module.saveProfile();
+        }
+    },
+
+    onLoad: function() {
+        var url = new URL(decodeURI(window.location));
+        let args = url.searchParams.getAll('arg');
+        Module.is_testing = args !== undefined && (args.find(arg => arg == '--testing') !== undefined);
+    },
+  
+    test_exit: function(exit_code) {
+        if (!Module.is_testing) {
+            console.log(`test_exit: ${exit_code}`);
+            return;
+        }
+
+        /* Set result in a tests_done element, to be read by xharness */
+        var tests_done_elem = document.createElement("label");
+        tests_done_elem.id = "tests_done";
+        tests_done_elem.innerHTML = exit_code.toString();
+        document.body.appendChild(tests_done_elem);
+
+        console.log(`WASM EXIT ${exit_code}`);
+    },
+  
+    saveProfile: function () {
+        var a = document.createElement('a');
+        var blob = new Blob([Module.aot_profile_data]);
+        a.href = URL.createObjectURL(blob);
+        a.download = "data.aotprofile";
+        // Append anchor to body.
+        document.body.appendChild(a);
+        a.click();
+
+        // Remove anchor from body
+        document.body.removeChild(a);
     }
-};
\ No newline at end of file
+};
index bd8e501..5f170bb 100644 (file)
@@ -48,7 +48,6 @@
         },
       };
     </script>
-    <script type="text/javascript" src="mono-config.js"></script>
     <script type="text/javascript" src="runtime.js"></script>
 
     <script defer src="dotnet.js"></script>
index a39b0b9..e97feef 100644 (file)
@@ -2,8 +2,21 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 
 var Module = { 
+
+    config: null,
+
+    preInit: async function() {
+        Module.config = await MONO.mono_wasm_load_config("./mono-config.json");
+    },
+
+    // Called when the runtime is initialized and wasm is ready
     onRuntimeInitialized: function () {
-        config.loaded_cb = function () {
+        if (!Module.config || Module.config.error) {
+            console.log("No config found");
+            return;
+        }
+
+        Module.config.loaded_cb = function () {
             try {
                 App.init ();
             } catch (error) {
@@ -11,13 +24,13 @@ var Module = {
                 throw (error);
             }
         };
-        config.fetch_file_cb = function (asset) {
+        Module.config.fetch_file_cb = function (asset) {
             return fetch (asset, { credentials: 'same-origin' });
         }
 
         try
         {
-            MONO.mono_load_runtime_and_bcl_args (config);
+            MONO.mono_load_runtime_and_bcl_args (Module.config);
         } catch (error) {
             test_exit(1);
             throw(error);
index 2141cce..b886f32 100644 (file)
@@ -65,7 +65,7 @@
       - @(WasmFilesToIncludeInFileSystem) - Files to include in the vfs
       - @(WasmNativeAsset)        - Native files to be added to `NativeAssets` in the bundle.
 
-      - @(WasmExtraConfig)        - json elements to add to `mono-config.js`
+      - @(WasmExtraConfig)        - json elements to add to `mono-config.json`
                                     Eg. <WasmExtraConfig Include="enable_profiler" Value="true" />
 
                                     - Value attribute can have a number, bool, quoted string, or json string
index 87ba804..b1bfcd8 100644 (file)
@@ -83,7 +83,6 @@
                        return App.int_add (a, b);
                }
       </script>
-      <script type="text/javascript" src="mono-config.js"></script>
       <script type="text/javascript" src="runtime-debugger.js"></script>
       <script type="text/javascript" src="other.js"></script>
       <script async type="text/javascript" src="dotnet.js"></script>
index 4c641eb..360aa9b 100644 (file)
@@ -2,8 +2,20 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 
 var Module = { 
-       onRuntimeInitialized: function () {
-               config.loaded_cb = function () {
+    config: null,
+
+    preInit: async function() {
+        Module.config = await MONO.mono_wasm_load_config("./mono-config.json");
+    },
+
+    // Called when the runtime is initialized and wasm is ready
+    onRuntimeInitialized: function () {
+               if (!Module.config || Module.config.error) {
+            console.log("An error occured while loading the config file");
+            return;
+        }
+
+               Module.config.loaded_cb = function () {
                        App.init ();
                };
                // For custom logging patch the functions below
@@ -15,6 +27,6 @@ var Module = {
                MONO.mono_wasm_setenv ("MONO_LOG_LEVEL", "debug");
                MONO.mono_wasm_setenv ("MONO_LOG_MASK", "all");
                */
-               MONO.mono_load_runtime_and_bcl_args (config)
+               MONO.mono_load_runtime_and_bcl_args (Module.config)
        },
 };
index 74aa108..8b3395f 100644 (file)
@@ -204,14 +204,16 @@ function loadScript (url)
        }
 }
 
-loadScript ("mono-config.js");
-
 var Module = {
        mainScriptUrlOrBlob: "dotnet.js",
-
+       config: null,
        print,
        printErr,
 
+    preInit: async function() {
+        Module.config = await MONO.mono_wasm_load_config("./mono-config.json");
+    },
+
        onAbort: function(x) {
                print ("ABORT: " + x);
                var err = new Error();
@@ -230,7 +232,7 @@ var Module = {
                        Module.ccall ('mono_wasm_enable_on_demand_gc', 'void', ['number'], [0]);
                }
 
-               config.loaded_cb = function () {
+               Module.config.loaded_cb = function () {
                        let wds = FS.stat (working_dir);
                        if (wds === undefined || !FS.isDir (wds.mode)) {
                                fail_exec (`Could not find working directory ${working_dir}`);
@@ -240,13 +242,13 @@ var Module = {
                        FS.chdir (working_dir);
                        App.init ();
                };
-               config.fetch_file_cb = function (asset) {
+               Module.config.fetch_file_cb = function (asset) {
                        // console.log("fetch_file_cb('" + asset + "')");
                        // for testing purposes add BCL assets to VFS until we special case File.Open
                        // to identify when an assembly from the BCL is being open and resolve it correctly.
                        /*
                        var content = new Uint8Array (read (asset, 'binary'));
-                       var path = asset.substr(config.deploy_prefix.length);
+                       var path = asset.substr(Module.config.deploy_prefix.length);
                        writeContentToFile(content, path);
                        */
 
@@ -280,10 +282,9 @@ var Module = {
                        }
                };
 
-               MONO.mono_load_runtime_and_bcl_args (config);
+               MONO.mono_load_runtime_and_bcl_args (Module.config);
        },
 };
-
 loadScript ("dotnet.js");
 
 const IGNORE_PARAM_COUNT = -1;
index 1186660..36837f6 100644 (file)
@@ -86,6 +86,7 @@ var MonoSupportLib = {
                        module ["mono_wasm_new_root"] = MONO.mono_wasm_new_root.bind(MONO);
                        module ["mono_wasm_new_roots"] = MONO.mono_wasm_new_roots.bind(MONO);
                        module ["mono_wasm_release_roots"] = MONO.mono_wasm_release_roots.bind(MONO);
+                       module ["mono_wasm_load_config"] = MONO.mono_wasm_load_config.bind(MONO);
                },
 
                _base64Converter: {
@@ -2362,6 +2363,30 @@ var MonoSupportLib = {
 
                        console.debug('mono_wasm_debug_event_raised:aef14bca-5519-4dfe-b35a-f867abc123ae', JSON.stringify(event), JSON.stringify(args));
                },
+
+               /**
+                * Loads the mono config file (typically called mono-config.json)
+                *
+                * @param {string} configFilePath - relative path to the config file
+                * @throws Will throw an error if the config file loading fails
+                */
+               mono_wasm_load_config: async function (configFilePath) {                
+                       try {
+                               let config = null;
+                               // NOTE: when we add nodejs make sure to include the nodejs fetch package
+                               if (ENVIRONMENT_IS_WEB) {
+                                       const configRaw = await fetch(configFilePath);
+                                       config = await configRaw.json();
+                               }else if (ENVIRONMENT_IS_NODE) {
+                                       config = require(configFilePath);
+                               } else { // shell or worker
+                                       config = JSON.parse(read(configFilePath)); // read is a v8 debugger command
+                               }
+                               return config;
+                       } catch(e) {
+                               return {message: "failed to load config file", error: e};
+                       }
+               }
        },
 
        mono_wasm_add_typed_value: function (type, str_value, value) {
@@ -2549,7 +2574,7 @@ var MonoSupportLib = {
                        assembly_b64,
                        pdb_b64
                });
-       },
+       }
 };
 
 autoAddDeps(MonoSupportLib, '$MONO')
index 9ef7679..49d9844 100644 (file)
@@ -51,7 +51,7 @@ public class WasmAppBuilder : Task
     public ITaskItem[]? ExtraFilesToDeploy { get; set; }
 
     // <summary>
-    // Extra json elements to add to mono-config.js
+    // Extra json elements to add to mono-config.json
     //
     // Metadata:
     // - Value: can be a number, bool, quoted string, or json string
@@ -246,11 +246,11 @@ public class WasmAppBuilder : Task
             config.Extra[name] = valueObject;
         }
 
-        string monoConfigPath = Path.Combine(AppDir, "mono-config.js");
+        string monoConfigPath = Path.Combine(AppDir, "mono-config.json");
         using (var sw = File.CreateText(monoConfigPath))
         {
             var json = JsonSerializer.Serialize (config, new JsonSerializerOptions { WriteIndented = true });
-            sw.Write($"config = {json};");
+            sw.Write(json);
         }
         _fileWrites.Add(monoConfigPath);
 
index b5f1f7e..99e721d 100644 (file)
@@ -347,7 +347,7 @@ namespace Wasm.Build.Tests
                 "runtime.js",
                 "dotnet.timezones.blat",
                 "dotnet.wasm",
-                "mono-config.js",
+                "mono-config.json",
                 "dotnet.js",
                 "run-v8.sh"
             });
index efab9ac..642987d 100644 (file)
@@ -47,7 +47,6 @@
         },
       };
     </script>
-    <script type="text/javascript" src="mono-config.js"></script>
     <script type="text/javascript" src="runtime.js"></script>
 
     <script defer src="dotnet.js"></script>
index a39b0b9..65cba13 100644 (file)
@@ -2,8 +2,21 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 
 var Module = { 
+
+    config: null,
+
+    preInit: async function() {
+        Module.config = await MONO.mono_wasm_load_config("./mono-config.json");
+    },
+
     onRuntimeInitialized: function () {
-        config.loaded_cb = function () {
+        if (!Module.config || Module.config.error) {
+            console.log("No config found");
+            test_exit(1);
+            throw(Module.config.error);
+        }
+
+        Module.config.loaded_cb = function () {
             try {
                 App.init ();
             } catch (error) {
@@ -11,13 +24,13 @@ var Module = {
                 throw (error);
             }
         };
-        config.fetch_file_cb = function (asset) {
+        Module.config.fetch_file_cb = function (asset) {
             return fetch (asset, { credentials: 'same-origin' });
         }
 
         try
         {
-            MONO.mono_load_runtime_and_bcl_args (config);
+            MONO.mono_load_runtime_and_bcl_args (Module.config);
         } catch (error) {
             test_exit(1);
             throw(error);
index 03f6867..9de05f5 100644 (file)
@@ -47,7 +47,6 @@
         },
       };
     </script>
-    <script type="text/javascript" src="mono-config.js"></script>
     <script type="text/javascript" src="runtime.js"></script>
 
     <script defer src="dotnet.js"></script>
index a39b0b9..1a8abf5 100644 (file)
@@ -2,8 +2,21 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 
 var Module = { 
+
+    config: null,
+
+    preInit: async function() {
+        Module.config = await MONO.mono_wasm_load_config("./mono-config.json");
+    },
+
     onRuntimeInitialized: function () {
-        config.loaded_cb = function () {
+        if (!Module.config || Module.config.error) {
+            console.log("No config found");
+            test_exit(1);
+            throw(Module.config.error);
+        }
+        
+        Module.config.loaded_cb = function () {
             try {
                 App.init ();
             } catch (error) {
@@ -11,13 +24,13 @@ var Module = {
                 throw (error);
             }
         };
-        config.fetch_file_cb = function (asset) {
+        Module.config.fetch_file_cb = function (asset) {
             return fetch (asset, { credentials: 'same-origin' });
         }
 
         try
         {
-            MONO.mono_load_runtime_and_bcl_args (config);
+            MONO.mono_load_runtime_and_bcl_args (Module.config);
         } catch (error) {
             test_exit(1);
             throw(error);