hostBridgeBootstrapJs function
Builds the bootstrap installed into the JS engine.
sendInvoke is a JS expression evaluating to a function, called with the
payload JSON string to ship a hostInvoke message to the host. It is
parenthesised at the call site: a bare function (p) {...} in statement
position parses as a declaration and is rejected for having no name.
Everything else is identical across platforms.
Implementation
String hostBridgeBootstrapJs(String sendInvoke) =>
'''
(function() {
if (globalThis.__hostBridgeReady) return;
globalThis.__hostBridgeReady = true;
globalThis.__hostPending = {};
globalThis.__hostNextUuid = 0;
globalThis.host = {};
globalThis.__hostResolve = function(uuid, jsonResult) {
var p = globalThis.__hostPending[uuid];
if (!p) return;
delete globalThis.__hostPending[uuid];
var v;
try { v = JSON.parse(jsonResult); } catch (e) { v = null; }
p.resolve(v);
};
globalThis.__hostReject = function(uuid, message) {
var p = globalThis.__hostPending[uuid];
if (!p) return;
delete globalThis.__hostPending[uuid];
p.reject(new Error(message));
};
globalThis.__hostCall = function(atom, verb, args) {
var uuid = '_h' + (++globalThis.__hostNextUuid);
return new Promise(function(resolve, reject) {
globalThis.__hostPending[uuid] = { resolve: resolve, reject: reject };
($sendInvoke)(
JSON.stringify({ uuid: uuid, atom: atom, verb: verb, args: args || [] }),
);
});
};
})();
''';