"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const logger_1 = require("./logger");
exports.emptyBucket = (s3, Bucket) => tslib_1.__awaiter(this, void 0, void 0, function* () {
    const deleteObjects = (objects) => tslib_1.__awaiter(this, void 0, void 0, function* () {
        const Objects = objects.map(({ Key, VersionId }) => ({ Key, VersionId }));
        yield s3.deleteObjects({
            Bucket,
            Delete: { Objects }
        }).promise();
    });
    const run = () => tslib_1.__awaiter(this, void 0, void 0, function* () {
        let Versions;
        try {
            ({ Versions } = yield s3.listObjectVersions({ Bucket }).promise());
        }
        catch (err) {
            if (err.code === 'NoSuchBucket')
                return;
            throw err;
        }
        let count = 0;
        if (Versions.length > 0) {
            count += Versions.length;
            logger_1.logger.info(`Deleting from ${Bucket}: ${Versions.length} object versions`);
            yield deleteObjects(Versions);
        }
        const { DeleteMarkers } = yield s3.listObjectVersions({ Bucket }).promise();
        if (DeleteMarkers.length > 0) {
            count += DeleteMarkers.length;
            logger_1.logger.info(`Deleting from ${Bucket}: ${DeleteMarkers.length} object delete markers`);
            yield deleteObjects(DeleteMarkers);
        }
        const { Contents } = yield s3.listObjectsV2({ Bucket }).promise();
        if (Contents.length > 0) {
            count += Contents.length;
            logger_1.logger.info(`Deleting from ${Bucket}: ${Contents.length} objects`);
            yield deleteObjects(Contents);
        }
        return count;
    });
    let count;
    do {
        count = yield run();
    } while (count);
});
//# sourceMappingURL=empty-bucket.js.map