import { pipe } from "../../Function"
import * as O from "../../Option"
import * as T from "../_internal/effect"
import * as M from "../_internal/managed"
import * as Ref from "../_internal/ref"
import * as Pull from "../Pull"
import { Stream } from "./definitions"
/**
 * Like `unfoldChunkM`, but allows the emission of values to end one step further than
 * the unfolding of the state. This is useful for embedding paginated APIs,
 * hence the name.
 */

export function paginateChunkM(s, f) {
  return new Stream(
    M.map_(
      M.bind_(M.do, "ref", () => T.toManaged(Ref.makeRef(O.some(s)))),
      ({ ref }) =>
        T.chain_(
          ref.get,
          O.fold(
            () => Pull.end,
            (s) =>
              T.foldM_(f(s), Pull.fail, ({ tuple: [as, s] }) => T.as_(ref.set(s), as))
          )
        )
    )
  )
}
//# sourceMappingURL=paginateChunkM.js.map
