openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
75 lines (74 loc) • 2.63 kB
JavaScript
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
//#region src/plugin-sdk/feature-contract.ts
/** Browser-safe typed operations over the existing plugin session-action transport. */
function defineFeatureContract(e) {
if (!e.pluginId.trim() || Object.keys(e.operations).length > 64 || Object.keys(e.events).length > 64) throw new Error("Feature contracts require a plugin id and at most 64 operations and events");
for (const t of Object.keys(e.operations)) if (!/^[a-z][a-z0-9._-]{0,127}$/u.test(t)) throw new Error(`Invalid feature operation id: ${t}`);
for (const t of Object.keys(e.events)) if (!/^[a-z][a-z0-9_-]{0,127}$/u.test(t)) throw new Error(`Invalid feature event id: ${t}`);
return e;
}
function createFeatureClient(e, t) {
if (t.pluginId !== e.pluginId) throw new Error("Feature contract must belong to the active browser plugin");
const invoke = async (n, r, i = {}) => {
t.signal.throwIfAborted();
const a = await t.request("plugins.sessionAction", {
pluginId: e.pluginId,
actionId: n,
payload: r,
...i
});
t.signal.throwIfAborted();
if (!isRecord(a) || a.ok !== true) throw new Error(isRecord(a) && typeof a.error === "string" ? a.error : "Feature operation returned an invalid response");
return a.result;
};
const on = (n, r) => t.onEvent(`plugin.${e.pluginId}.${n}`, (e) => r(e));
const watch = (n, r, i) => {
if (e.operations[n]?.kind !== "query") throw new Error("Only feature queries can be watched");
let a = false;
let o = 0;
let s = false;
let c = t.connection.connected;
const refresh = () => {
o += 1;
if (a || !t.connection.connected || s) return;
s = true;
queueMicrotask(() => {
s = false;
if (a || !t.connection.connected) return;
const e = o;
invoke(n, r, {
sessionKey: i.sessionKey,
agentId: i.agentId
}).then((n) => {
if (!a && e === o && t.connection.connected) i.onChange(n);
}, (n) => {
if (!a && e === o && t.connection.connected) i.onError(n instanceof Error ? n : new Error(String(n)));
});
});
};
const l = i.events.map((e) => on(e, refresh));
l.push(t.subscribe(() => {
if (c !== t.connection.connected) {
c = t.connection.connected;
refresh();
}
}));
const dispose = () => {
a = true;
o += 1;
for (const e of l) e();
t.signal.removeEventListener("abort", dispose);
};
t.signal.addEventListener("abort", dispose, { once: true });
if (t.signal.aborted) dispose();
else refresh();
return dispose;
};
return {
invoke,
on,
watch
};
}
//#endregion
export { defineFeatureContract as n, createFeatureClient as t };