aibridgejs: Cross-Context Bridge
aibridgejs solves this problem: each host runtime communicates in its own way, but you do not want platform details such as postMessage and flutter_inappwebview.callHandler scattered through your business logic. It provides a stable call / on / emit API, and the differences between hosts are encapsulated by adapters.
Install
Section titled “Install”npm install aibridgejsSubpath Exports
Section titled “Subpath Exports”| Subpath | Contents |
|---|---|
aibridgejs |
Core: createBridge, types, error classes |
aibridgejs/mock |
createMockAdapter: loopback, suited to development and unit tests |
aibridgejs/iframe |
createIframeAdapter: origin-verified postMessage |
aibridgejs/flutter |
createFlutterAdapter: Flutter InAppWebView JS handler |
aibridgejs/detect |
detectBridgeAdapter: picks an adapter automatically from host globals |
Quick Start (mock adapter, suited to development)
Section titled “Quick Start (mock adapter, suited to development)”import { createBridge } from "aibridgejs";import { createMockAdapter } from "aibridgejs/mock";
const bridge = createBridge({ adapter: createMockAdapter() });await bridge.ready();
// The mock loops the event back to this listener.const off = bridge.on("player.ready", (payload) => { console.log("player.ready", payload);});await bridge.emit("player.ready", { playerId: "p1" });
off();bridge.dispose();Switching to the iframe Adapter
Section titled “Switching to the iframe Adapter”import { createBridge } from "aibridgejs";import { createIframeAdapter } from "aibridgejs/iframe";
const target = iframe.contentWindow!;const adapter = createIframeAdapter(window, { targetOrigin: "https://game.example.com", // Must be an exact origin; "*", a path or a trailing slash throws BridgeError postTarget: target, expectedSource: target,});
const bridge = createBridge({ adapter });await bridge.ready();Automatic Adapter Detection
Section titled “Automatic Adapter Detection”import { createBridge } from "aibridgejs";import { detectBridgeAdapter } from "aibridgejs/detect";
// Checks flutter → iframe → mock in order; inside an iframe, iframe.targetOrigin is requiredconst adapter = detectBridgeAdapter(window, { iframe: { targetOrigin: "https://host.example.com" },});const bridge = createBridge({ adapter });Protocol Structure
Section titled “Protocol Structure”Every envelope carries a string id used to match requests and responses. This supports multiple concurrent call()s, each matched by its id on return. A call() or emit() issued before the bridge is ready is held back by a gating mechanism and sent in call order once it is ready, regardless of which options each carries.
reset, dispose and Errors
Section titled “reset, dispose and Errors”bridge.reset()rejects pendingcall()s and in-flightemit()s withBridgeResetError, then waits foradapter.ready()again. Registeredon()listeners and adapter subscriptions are kept, so do not register them again after a reset.bridge.dispose()is a permanent teardown: in-flightcall()s andemit()s reject withBridgeDisposedError, and all listeners are removed.- An
emit()withoutsignal/timeoutMshas no time limit, but is reclaimed byreset()/dispose(). Code that awaits it must handle both errors; for fire-and-forget, writebridge.emit(...).catch(() => {}). - Misuse throws
BridgeErrorbefore any side effect, with the message prefixaibridgejs:: missing options, an adapter missingready/post/subscribe/dispose, a listener that is not a function, a host missingaddEventListener/removeEventListener, or an iframetargetOriginthat is not an exact origin. Check withinstanceof BridgeErrorand do not match on the full message. - A custom adapter must implement the four methods
ready,post,subscribeanddispose(leave an empty implementation for any you do not need). The signal passed toready()is scoped to each readiness round; bothreset()anddispose()abort it, and the adapter should remove its own listeners on abort.
Common Pairings
Section titled “Common Pairings”- With
aiecsjs: serialise the world snapshot withaiecsjs/serializeand send it through the bridge to another window or a Flutter shell - With
aifsmjs: a machine definition is plain JSON, so it can be sent through the bridge and used to create a runtime on the other side - Hybrid apps: in Flutter + WebView scenarios, use it to call native features (camera, saving files, notifications)