"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const debug_1 = require("debug");
const debug = debug_1.default('axm:profiling');
const metricConfig_1 = require("../utils/metricConfig");
const serviceManager_1 = require("../serviceManager");
class ProfilingHeap {
    constructor() {
        this.defaultConf = {
            samplingInterval: 32768
        };
        this.inspectorService = serviceManager_1.ServiceManager.get('inspector');
    }
    init(config) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            config = metricConfig_1.default.getConfig(config, this.defaultConf);
            this.config = config;
            this.inspectorService.createSession();
            this.inspectorService.connect();
            return this.inspectorService.post('HeapProfiler.enable');
        });
    }
    destroy() {
        this.inspectorService.disconnect();
    }
    start() {
        return this.inspectorService.post('HeapProfiler.startSampling', {
            samplingInterval: this.config.samplingInterval
        });
    }
    stop() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return this.getProfileInfo();
        });
    }
    takeSnapshot() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            const chunks = [];
            this.inspectorService.on('HeapProfiler.addHeapSnapshotChunk', (data) => {
                chunks.push(data.params.chunk);
            });
            yield this.inspectorService.post('HeapProfiler.takeHeapSnapshot', {
                reportProgress: false
            });
            return chunks.join('');
        });
    }
    getProfileInfo() {
        return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
            let data;
            try {
                data = yield this.inspectorService.post('HeapProfiler.stopSampling');
            }
            catch (err) {
                debug('Heap profiling stopped !');
                return reject(err);
            }
            resolve(JSON.stringify(data.profile));
        }));
    }
}
exports.default = ProfilingHeap;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicHJvZmlsaW5nSGVhcC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9wcm9maWxpbmcvcHJvZmlsaW5nSGVhcC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7QUFBQSxpQ0FBeUI7QU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