"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.peel = exports.peel_ = void 0;
// ets_tracing: off
const Tp = __importStar(require("../../Collections/Immutable/Tuple"));
const Function_1 = require("../../Function");
const T = __importStar(require("../_internal/effect"));
const M = __importStar(require("../_internal/managed"));
const SK = __importStar(require("../Sink"));
const concat_1 = require("./concat");
const fromChunk_1 = require("./fromChunk");
const repeatEffectChunkOption_1 = require("./repeatEffectChunkOption");
const run_1 = require("./run");
/**
 * Peels off enough material from the stream to construct a `Z` using the
 * provided `Sink` and then returns both the `Z` and the rest of the
 * `Stream` in a managed resource. Like all `Managed` values, the provided
 * stream is valid only within the scope of `Managed`.
 */
function peel_(self, sink) {
    return M.chain_(self.proc, (pull) => {
        const stream = (0, repeatEffectChunkOption_1.repeatEffectChunkOption)(pull);
        const s = SK.exposeLeftover(sink);
        return (M.map_(T.toManaged((0, run_1.run)(s)(stream)), (e) => Tp.tuple(e.get(0), (0, concat_1.concat_)((0, fromChunk_1.fromChunk)(e.get(1)), stream))));
    });
}
exports.peel_ = peel_;
/**
 * Peels off enough material from the stream to construct a `Z` using the
 * provided `Sink` and then returns both the `Z` and the rest of the
 * `Stream` in a managed resource. Like all `Managed` values, the provided
 * stream is valid only within the scope of `Managed`.
 */
function peel(sink) {
    return (self) => peel_(self, sink);
}
exports.peel = peel;
//# sourceMappingURL=peel.js.map