openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
107 lines (106 loc) • 2.14 kB
JavaScript
import { R as resolveTimerTimeoutMs } from "./number-coercion-D6u-4YD8.mjs";
//#region src/channels/draft-stream-loop.ts
function createDraftStreamLoop(e) {
const t = resolveTimerTimeoutMs(e.throttleMs, 0, 0);
const n = e.emptyValue ?? "";
const r = e.isEmpty ?? ((e) => typeof e === "string" && e.trim().length === 0);
const hasPendingValue = (e) => typeof e === "string" ? e.length > 0 : !r(e);
let i = 0;
let a = n;
let o;
let s;
const clearTimer = () => {
clearTimeout(s);
s = void 0;
};
const retainUnsentValue = (t, n) => {
if (!hasPendingValue(a)) a = t;
else if (n && e.coalesceInFlight) schedule();
};
const flush = async (t = false) => {
clearTimer();
while (!e.isStopped()) {
if (o) {
await o;
if (t && e.coalesceInFlight) return;
continue;
}
const s = a;
if (r(s)) {
a = n;
return;
}
a = n;
let c;
try {
o = Promise.resolve(e.sendOrEditStreamMessage(s)).finally(() => {
o = void 0;
});
c = await o;
} catch (e) {
retainUnsentValue(s, t);
throw e;
}
if (c === false) {
retainUnsentValue(s, t);
return;
}
i = Date.now();
if (!hasPendingValue(a)) return;
if (t && e.coalesceInFlight) {
schedule();
return;
}
}
};
const startBackgroundFlush = () => {
flush(true).catch((t) => {
e.onBackgroundFlushError?.(t);
});
};
const schedule = () => {
if (s) return;
const e = Math.max(0, t - (Date.now() - i));
s = setTimeout(() => {
startBackgroundFlush();
}, e);
};
return {
update: (n) => {
if (e.isStopped()) return;
a = n;
if (o) {
if (!e.coalesceInFlight) schedule();
return;
}
if (!s && Date.now() - i >= t) {
startBackgroundFlush();
return;
}
schedule();
},
flush: () => flush(),
stop: () => {
a = n;
clearTimer();
},
resetPending: () => {
a = n;
},
resetThrottleWindow: () => {
i = 0;
clearTimer();
},
waitForInFlight: async () => {
if (o) await o;
},
takePending: () => {
const e = a;
a = n;
clearTimer();
return e;
}
};
}
//#endregion
export { createDraftStreamLoop as t };