export type SendQueue = Readonly<{
  enqueue: (fn: () => Promise<void>) => Promise<void>
  serializeReceive: (fn: () => Promise<void>) => Promise<void>
}>

export function createSendQueue(): SendQueue {
  let queue: Promise<void> = Promise.resolve()

  const enqueue = (fn: () => Promise<void>): Promise<void> => {
    queue = queue.then(fn, fn)
    return queue
  }

  const serializeReceive = async (fn: () => Promise<void>): Promise<void> => {
    await enqueue(fn)
  }

  return { enqueue, serializeReceive }
}
