"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BlobService = exports.BlobEncoding = void 0;
const fs_1 = require("fs");
const inversify_1 = require("inversify");
const os_1 = __importDefault(require("os"));
const path_1 = __importDefault(require("path"));
const rimraf_1 = __importDefault(require("rimraf"));
const util_1 = __importDefault(require("util"));
const uuid_1 = require("uuid");
const config_js_1 = require("../../config.js");
const session_js_1 = require("../session.js");
const index_js_1 = require("../util/index.js");
const rimrafAsync = util_1.default.promisify(rimraf_1.default);
const BLOBS_DIR = (0, config_js_1.stringConfig)('BLOBS_DIR', path_1.default.resolve(os_1.default.tmpdir(), 'autopilot/blobs'));
var BlobEncoding;
(function (BlobEncoding) {
    BlobEncoding["BINARY"] = "binary";
    BlobEncoding["UTF8"] = "utf8";
    BlobEncoding["BASE64"] = "base64";
    BlobEncoding["HEX"] = "hex";
    BlobEncoding["ASCII"] = "ascii";
    BlobEncoding["UTF16LE"] = "utf16le";
    BlobEncoding["USC2"] = "usc2";
})(BlobEncoding = exports.BlobEncoding || (exports.BlobEncoding = {}));
let BlobService = class BlobService {
    constructor(config) {
        this.config = config;
        this.blobsMap = new Map();
    }
    async onSessionStart() {
        this.blobsMap.clear();
        await rimrafAsync(this.getBlobsPath());
        await fs_1.promises.mkdir(this.getBlobsPath(), { recursive: true });
    }
    getBlobsPath() {
        const blobsDir = this.config.get(BLOBS_DIR);
        return path_1.default.resolve(process.cwd(), blobsDir);
    }
    getBlob(blobId) {
        const blob = this.blobsMap.get(blobId);
        if (!blob) {
            throw (0, index_js_1.createError)({
                code: 'BlobNotfound',
                message: 'Blob not found by id',
                retry: true,
                details: { blobId },
            });
        }
        return blob;
    }
    async createBlob(filename, buffer) {
        const file = path_1.default.resolve(this.getBlobsPath(), filename);
        await fs_1.promises.writeFile(file, buffer);
        const blob = {
            blobId: 'blob:' + (0, uuid_1.v4)(),
            file,
            filename,
            length: buffer.length,
        };
        this.blobsMap.set(blob.blobId, blob);
        return blob;
    }
    async readBlob(blobId) {
        const blob = this.getBlob(blobId);
        const buffer = await fs_1.promises.readFile(blob.file);
        return buffer;
    }
    async copy(blob, filename) {
        const sanitizedFilename = filename.replace(/[^a-zA-Z0-9._-]/g, '_');
        const dstFile = path_1.default.join(this.getBlobsPath(), sanitizedFilename);
        await fs_1.promises.copyFile(blob.file, dstFile);
        return {
            blobId: blob.blobId,
            length: blob.length,
            file: dstFile,
            filename: sanitizedFilename,
        };
    }
};
BlobService = __decorate([
    (0, inversify_1.injectable)(),
    (0, session_js_1.SessionHandler)(),
    __param(0, (0, inversify_1.inject)(config_js_1.Configuration)),
    __metadata("design:paramtypes", [config_js_1.Configuration])
], BlobService);
exports.BlobService = BlobService;
//# sourceMappingURL=blob.js.map