Skip to content
This repository was archived by the owner on Nov 9, 2026. It is now read-only.

Commit 980cfb0

Browse files
bghgaryCopilot
andauthored
Add host-controlled script loading for bundled imports (#259)
[Created by Copilot on behalf of @bghgary] ## Context Hosts that package JavaScript as resources need to load deferred bundles without enabling unrestricted file or network access. Resource delivery may be immediate or asynchronous. ## Compatibility The runtime API evaluates classic scripts and is independent of the bundler; it does not add native ECMAScript module loading. Source-level `import()` must be transformed by the bundler. See `Plugins/DynamicScriptLoader/README.md` for host integration and a Webpack 5 configuration example. Browser builds keep their normal chunk transport. The Webpack example is for packaged JavaScript chunks, not a development server or hot module replacement. --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent 21cb983 commit 980cfb0

9 files changed

Lines changed: 376 additions & 0 deletions

File tree

‎CMakeLists.txt‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,9 @@ option(JSRUNTIMEHOST_POLYFILL_PERFORMANCE "Include JsRuntimeHost Polyfill Perfor
103103
option(JSRUNTIMEHOST_POLYFILL_TEXTDECODER "Include JsRuntimeHost Polyfill TextDecoder." ON)
104104
option(JSRUNTIMEHOST_POLYFILL_TEXTENCODER "Include JsRuntimeHost Polyfill TextEncoder." ON)
105105

106+
# Plugins
107+
option(JSRUNTIMEHOST_PLUGIN_DYNAMICSCRIPTLOADER "Include JsRuntimeHost asynchronous resource script loader." ON)
108+
106109
# Compatibility with the previous AbortController option.
107110
if(DEFINED JSRUNTIMEHOST_POLYFILL_ABORT_CONTROLLER)
108111
set(JSRUNTIMEHOST_POLYFILL_ABORTCONTROLLER "${JSRUNTIMEHOST_POLYFILL_ABORT_CONTROLLER}")
@@ -369,6 +372,7 @@ endif()
369372

370373
add_subdirectory(Core)
371374
add_subdirectory(Polyfills)
375+
add_subdirectory(Plugins)
372376

373377
if(JSRUNTIMEHOST_TESTS AND NOT WINDOWS_STORE)
374378
add_subdirectory(Tests)

‎Plugins/CMakeLists.txt‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
if(JSRUNTIMEHOST_PLUGIN_DYNAMICSCRIPTLOADER)
2+
add_subdirectory(DynamicScriptLoader)
3+
endif()
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
set(SOURCES
2+
"Include/Babylon/Plugins/DynamicScriptLoader.h"
3+
"Source/DynamicScriptLoader.cpp")
4+
5+
add_library(DynamicScriptLoader ${SOURCES})
6+
warnings_as_errors(DynamicScriptLoader)
7+
8+
target_include_directories(DynamicScriptLoader PUBLIC "Include")
9+
10+
target_link_libraries(DynamicScriptLoader
11+
PUBLIC Foundation
12+
PUBLIC JsRuntime
13+
PUBLIC napi)
14+
15+
set_property(TARGET DynamicScriptLoader PROPERTY FOLDER Plugins)
16+
source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${SOURCES})
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#pragma once
2+
3+
#include <Babylon/Api.h>
4+
#include <napi/env.h>
5+
6+
#include <functional>
7+
#include <string>
8+
9+
namespace Babylon::Plugins::DynamicScriptLoader
10+
{
11+
// Return source as a JavaScript string or a Promise resolving to one.
12+
// Return null/undefined (or reject) when the resource is unavailable.
13+
// Called on the JavaScript thread; any asynchronous completion must also use
14+
// the runtime dispatcher before accessing Node-API values.
15+
using ResolverT = std::function<Napi::Value BABYLON_API (Napi::Env, const std::string&)>;
16+
17+
// Installs _native.loadScript(name): Promise<void>. The resolver alone determines
18+
// which resources can be loaded; no file or network fallback is provided.
19+
// The host must stop asynchronous producers before destroying the runtime.
20+
void BABYLON_API Initialize(Napi::Env env, ResolverT resolver);
21+
}
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
# Dynamic script loader
2+
3+
The optional C++ `DynamicScriptLoader` plugin installs `_native.loadScript(name)`, which returns a promise that settles after evaluating source in the current JavaScript context. The host supplies a resolver that returns either a JavaScript string or a promise of a string. Missing resources (null or undefined), rejected lookups, and evaluation errors reject the returned promise. No file or network loader is installed by JsRuntimeHost.
4+
5+
```cpp
6+
#include <Babylon/Plugins/DynamicScriptLoader.h>
7+
8+
Babylon::Plugins::DynamicScriptLoader::Initialize(env,
9+
[](Napi::Env env, const std::string& name) -> Napi::Value {
10+
auto source = FindPackagedScript(name);
11+
return source ? Napi::String::New(env, *source) : env.Null();
12+
});
13+
```
14+
15+
Initialize the plugin after `JsRuntime` and before evaluating the entry bundle. Link the `DynamicScriptLoader` target; `JSRUNTIMEHOST_PLUGIN_DYNAMICSCRIPTLOADER` controls whether it is built. It uses the existing `_native` object and does not install global `loadScript`, `importScripts`, or native `import()` syntax. Names must be nonempty strings without NUL characters; source containing NUL characters is rejected because the evaluation API accepts null-terminated strings. Empty source is allowed.
16+
17+
The resolver runs on the JavaScript thread. For asynchronous resolvers, return `Napi::Promise::Deferred::Promise()` and resolve it with source on a later JavaScript dispatch turn, or reject it with the lookup error. The host must stop asynchronous producers before destroying the runtime; it must not access Node-API values or dispatch through a destroyed runtime. The loader does not cache scripts or cancel host operations.
18+
19+
## Bundled imports
20+
21+
The runtime plugin is bundler-independent: it evaluates classic scripts, not untransformed ECMAScript modules. A bundler transforms source-level `import()` and manages exports, dependencies, caching, and concurrent imports. Its chunk transport must call `_native.loadScript` instead of a browser or filesystem loader.
22+
23+
### Webpack 5 example
24+
25+
The following `webpack.config.cjs` is an application-side example, not a separate JsRuntimeHost build package. It keeps Webpack's chunk registration and adds the host evaluation promise to the promises each import already waits for. JsRuntimeHost supplies `window` as an alias for the script global; no document is required.
26+
27+
```js
28+
module.exports = {
29+
entry: "./src/index.js",
30+
target: ["web", "es5"],
31+
mode: "production",
32+
devtool: false,
33+
output: {
34+
filename: "entry.js",
35+
chunkFilename: "[name].js",
36+
chunkFormat: "array-push",
37+
chunkLoading: "jsonp",
38+
globalObject: "window",
39+
publicPath: "",
40+
},
41+
plugins: [{
42+
apply(compiler) {
43+
const { RuntimeGlobals, RuntimeModule } = compiler.webpack;
44+
compiler.hooks.thisCompilation.tap("HostScriptLoading", compilation => {
45+
compilation.hooks.runtimeModule.tap("HostScriptLoading", module => {
46+
if (module.name === "load script") {
47+
module.generate = () => "";
48+
}
49+
});
50+
compilation.hooks.runtimeRequirementInTree.for(RuntimeGlobals.loadScript)
51+
.tap("HostScriptLoading", chunk => {
52+
const runtime = new RuntimeModule("host script loading", RuntimeModule.STAGE_ATTACH + 1);
53+
runtime.generate = () => `
54+
var loads = Object.create(null);
55+
${RuntimeGlobals.loadScript} = function(name, done) {
56+
var load = loads[name] = Promise.resolve().then(function() {
57+
return _native.loadScript(name);
58+
});
59+
load.then(function() {
60+
done({ type: "load", target: { src: name } });
61+
}, function() {
62+
done({ type: "error", target: { src: name } });
63+
});
64+
};
65+
var ensureChunk = ${RuntimeGlobals.ensureChunkHandlers}.j;
66+
${RuntimeGlobals.ensureChunkHandlers}.j = function(chunkId, promises) {
67+
ensureChunk(chunkId, promises);
68+
var load = loads[${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId)];
69+
if (load) {
70+
promises.push(load);
71+
}
72+
};`;
73+
compilation.addRuntimeModule(chunk, runtime);
74+
});
75+
});
76+
},
77+
}],
78+
};
79+
```
80+
81+
Initialize the runtime plugin before evaluating `entry.js`. Package every emitted JavaScript chunk under its emitted relative name; the host resolver decides which names are accepted. For browser builds, omit the example's plugin and use the normal browser output settings. Other bundlers need their own chunk-transport integration.
82+
83+
The import promise waits for both chunk registration and complete script evaluation. Lookup and evaluation failures reject it; successful evaluation without the expected registration rejects with Webpack's `ChunkLoadError`. Failed lookups can be retried. Evaluation failure after registration is not rolled back; discard the runtime if that failure leaves application state unusable.
84+
85+
This example uses classic JavaScript chunks only. Do not combine it with hot module replacement, a development server, browser prefetch/preload hints, CSS chunk loading, or native-module externals. The host must complete or reject each resource operation; no timeout is added. Select source transpilation appropriate for the engine: Webpack's `target` controls its generated runtime, not all syntax in application source.
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
#include <Babylon/Plugins/DynamicScriptLoader.h>
2+
#include <Babylon/JsRuntime.h>
3+
4+
#include <stdexcept>
5+
#include <utility>
6+
7+
namespace Babylon::Plugins::DynamicScriptLoader
8+
{
9+
namespace
10+
{
11+
Napi::Value LoadScript(const Napi::CallbackInfo& info, const ResolverT& resolver)
12+
{
13+
auto env = info.Env();
14+
const auto reject = [env](Napi::Value error) {
15+
const auto deferred = Napi::Promise::Deferred::New(env);
16+
deferred.Reject(error);
17+
return deferred.Promise();
18+
};
19+
if (info.Length() != 1 || !info[0].IsString())
20+
{
21+
return reject(Napi::TypeError::New(env, "loadScript expects one resource name").Value());
22+
}
23+
24+
const auto name = info[0].As<Napi::String>().Utf8Value();
25+
if (name.empty() || name.find('\0') != std::string::npos)
26+
{
27+
return reject(Napi::TypeError::New(env, "loadScript expects a nonempty resource name without NUL characters").Value());
28+
}
29+
try
30+
{
31+
auto source = resolver(env, name);
32+
if (env.IsExceptionPending())
33+
{
34+
throw env.GetAndClearPendingException();
35+
}
36+
auto promise = env.Global().Get("Promise").As<Napi::Function>();
37+
auto resolve = promise.Get("resolve").As<Napi::Function>();
38+
auto resolved = resolve.Call(promise, {source}).As<Napi::Promise>();
39+
auto evaluate = Napi::Function::New(env, [name](const Napi::CallbackInfo& callback) {
40+
if (!callback[0].IsString())
41+
{
42+
throw Napi::TypeError::New(callback.Env(), "Script source not found: " + name);
43+
}
44+
auto text = callback[0].As<Napi::String>().Utf8Value();
45+
// The engine-independent Eval API takes a null-terminated string.
46+
if (text.find('\0') != std::string::npos)
47+
{
48+
throw Napi::TypeError::New(callback.Env(), "Script source contains a NUL character: " + name);
49+
}
50+
Napi::Eval(callback.Env(), text.c_str(), name.c_str());
51+
});
52+
return resolved.Get("then").As<Napi::Function>().Call(resolved, {evaluate});
53+
}
54+
catch (const Napi::Error& error)
55+
{
56+
return reject(error.Value());
57+
}
58+
catch (const std::exception& error)
59+
{
60+
return reject(Napi::Error::New(env, error.what()).Value());
61+
}
62+
}
63+
}
64+
65+
void BABYLON_API Initialize(Napi::Env env, ResolverT resolver)
66+
{
67+
if (!resolver)
68+
{
69+
throw std::invalid_argument{"loadScript requires a resource resolver"};
70+
}
71+
72+
auto native = JsRuntime::NativeObject::GetFromJavaScript(env);
73+
if (native.Has("loadScript"))
74+
{
75+
throw Napi::Error::New(env, "_native.loadScript is already defined");
76+
}
77+
78+
native.Set("loadScript", Napi::Function::New(env, [resolver = std::move(resolver)](const Napi::CallbackInfo& info) {
79+
return LoadScript(info, resolver);
80+
}, "loadScript"));
81+
}
82+
}

‎Tests/UnitTests/CMakeLists.txt‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,10 @@ elseif(NAPI_JAVASCRIPT_ENGINE STREQUAL "JavaScriptCore")
7272
endif()
7373

7474
add_executable(UnitTests ${SOURCES} ${TEST_JAVASCRIPT} ${SCRIPTS} ${ASSETS})
75+
if(JSRUNTIMEHOST_PLUGIN_DYNAMICSCRIPTLOADER)
76+
target_sources(UnitTests PRIVATE "Source/Tests.DynamicScriptLoader.cpp")
77+
target_link_libraries(UnitTests PRIVATE DynamicScriptLoader)
78+
endif()
7579
if(NAPI_JAVASCRIPT_ENGINE STREQUAL "V8")
7680
target_sources(UnitTests PRIVATE "Source/Tests.V8ForegroundTaskRunner.cpp")
7781
target_link_libraries(UnitTests PRIVATE AppRuntimeInternal)

‎Tests/UnitTests/Source/Android/app/src/main/cpp/CMakeLists.txt‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,11 @@ add_library(UnitTestsJNI SHARED
2929
${UNIT_TESTS_DIR}/Source/Tests.StandardStreamLogger.cpp
3030
${UNIT_TESTS_DIR}/Source/Tests.TimeoutDispatcher.cpp)
3131

32+
if(JSRUNTIMEHOST_PLUGIN_DYNAMICSCRIPTLOADER)
33+
target_sources(UnitTestsJNI PRIVATE ${UNIT_TESTS_DIR}/Source/Tests.DynamicScriptLoader.cpp)
34+
target_link_libraries(UnitTestsJNI PRIVATE DynamicScriptLoader)
35+
endif()
36+
3237
if(NAPI_JAVASCRIPT_ENGINE STREQUAL "V8")
3338
target_sources(UnitTestsJNI PRIVATE ${UNIT_TESTS_DIR}/Source/Tests.V8ForegroundTaskRunner.cpp)
3439
target_link_libraries(UnitTestsJNI PRIVATE AppRuntimeInternal)

0 commit comments

Comments
 (0)