jevhooks.git / plugin / hooks / bridge.ts
1// The only module that touches the compiled module's memory. wasm2js replaces
2// that buffer whenever memory grows, so a byte view kept across a call can
3// point at freed storage; nothing outside this file can hold one, and inside
4// it every view is taken from `memory.buffer` at the moment it is used.
5import { memory, alloc, dealloc, handle, out_len } from './jevhooks.js'
6
7const encoder = new TextEncoder()
8const decoder = new TextDecoder()
9
10/** What to do with a hook event (jevhooks-events' `Role`). */
11export type Role = 'decide' | 'observe' | 'ignore'
12
13/** As much of an event as routing needs. */
14export type Routed = { event: string; tool?: string; command?: string }
15
16/** Asks the Rust side what to do with an event. Synchronous and local. */
17export function route(routed: Routed): { role: Role; why: string } {
18  const input = encoder.encode(JSON.stringify(routed))
19  const ptr = alloc(input.length)
20  new Uint8Array(memory.buffer).set(input, ptr)
21  const out = handle(ptr, input.length)
22  const len = out_len()
23  const answer = JSON.parse(decoder.decode(new Uint8Array(memory.buffer, out, len)))
24  dealloc(ptr, input.length)
25  dealloc(out, len)
26  return answer
27}