"use strict";
/*
 * Tencent is pleased to support the open source community by making
 * Hippy available.
 *
 * Copyright (C) 2017-2019 THL A29 Limited, a Tencent company.
 * All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.tdfHeapMiddleWareManager = void 0;
const tslib_1 = require("tslib");
const fs_1 = tslib_1.__importDefault(require("fs"));
const path_1 = tslib_1.__importDefault(require("path"));
const enum_tdf_mapping_1 = require("@hippy/devtools-protocol/dist/types/enum-tdf-mapping");
const config_1 = require("@debug-server-next/config");
const log_1 = require("@debug-server-next/utils/log");
const log = new log_1.Logger('tdf-heap-middleware');
/**
 * TODO save heap data to local, doesn't support remote debug
 */
exports.tdfHeapMiddleWareManager = {
    downwardMiddleWareListMap: {
        [enum_tdf_mapping_1.TdfCommand.TDFMemoryGetHeapMeta]: async ({ msg, sendToDevtools }) => {
            var _a;
            try {
                const commandRes = msg;
                const { cachePath } = config_1.config;
                const fpath = path_1.default.join(cachePath, `${commandRes.id}.json`);
                await fs_1.default.promises.writeFile(fpath, JSON.stringify(commandRes));
                return sendToDevtools(commandRes);
            }
            catch (e) {
                log.error('write heap failed! %s', (_a = e) === null || _a === void 0 ? void 0 : _a.stack);
                return Promise.reject(e);
            }
        },
    },
    upwardMiddleWareListMap: {
        [enum_tdf_mapping_1.TdfCommand.TDFMemoryFetchHeapCache]: async ({ msg, sendToDevtools }) => {
            var _a;
            try {
                const req = msg;
                const { cachePath } = config_1.config;
                const fpath = path_1.default.join(cachePath, `${req.params.id}.json`);
                const cacheMsgStr = await fs_1.default.promises.readFile(fpath, 'utf8');
                const cacheMsg = JSON.parse(cacheMsgStr);
                return sendToDevtools({
                    id: req.id,
                    method: req.method,
                    result: cacheMsg.result,
                });
            }
            catch (e) {
                log.error('write heap failed! %s', (_a = e) === null || _a === void 0 ? void 0 : _a.stack);
                return Promise.reject(e);
            }
        },
    },
};
