"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (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 __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 __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const node_fs_1 = __importDefault(require("node:fs"));
const node_os_1 = __importDefault(require("node:os"));
const node_path_1 = __importDefault(require("node:path"));
const bind_decorator_1 = __importDefault(require("bind-decorator"));
const json_stable_stringify_without_jsonify_1 = __importDefault(require("json-stable-stringify-without-jsonify"));
const data_1 = __importDefault(require("../util/data"));
const logger_1 = __importDefault(require("../util/logger"));
const settings = __importStar(require("../util/settings"));
const utils_1 = __importDefault(require("../util/utils"));
const extension_1 = __importDefault(require("./extension"));
const SUPPORTED_OPERATIONS = ["save", "remove"];
const TMP_PREFIX = ".tmp-ed42d4f2-";
class ExternalJSExtension extends extension_1.default {
    folderName;
    mqttTopic;
    requestRegex;
    basePath;
    nodeModulesSymlinked = false;
    constructor(zigbee, mqtt, state, publishEntityState, eventBus, enableDisableExtension, restartCallback, addExtension, mqttTopic, folderName) {
        super(zigbee, mqtt, state, publishEntityState, eventBus, enableDisableExtension, restartCallback, addExtension);
        this.folderName = folderName;
        this.mqttTopic = mqttTopic;
        this.requestRegex = new RegExp(`${settings.get().mqtt.base_topic}/bridge/request/${mqttTopic}/(save|remove)`);
        this.basePath = data_1.default.joinPath(folderName);
    }
    /**
     * In case the external JS is not in the Z2M install dir (e.g. when `ZIGBEE2MQTT_DATA` is used), the external
     * JS cannot import from `node_modules`.
     * To workaround this create a symlink to `node_modules` in the external JS dir.
     * https://nodejs.org/api/esm.html#no-node_path
     */
    symlinkNodeModulesIfNecessary() {
        if (!this.nodeModulesSymlinked) {
            this.nodeModulesSymlinked = true;
            const nodeModulesPath = node_path_1.default.join(__dirname, "..", "..", "node_modules");
            const z2mDirNormalized = `${node_path_1.default.resolve(node_path_1.default.join(nodeModulesPath, ".."))}${node_path_1.default.sep}`;
            const basePathNormalized = `${node_path_1.default.resolve(this.basePath)}${node_path_1.default.sep}`;
            const basePathInZ2mDir = basePathNormalized.startsWith(z2mDirNormalized);
            if (!basePathInZ2mDir) {
                logger_1.default.debug(`External JS folder '${this.folderName}' is outside the Z2M install dir, creating a symlink to 'node_modules'`);
                const nodeModulesSymlink = node_path_1.default.join(this.basePath, "node_modules");
                /* v8 ignore start */
                if (node_fs_1.default.existsSync(nodeModulesSymlink)) {
                    node_fs_1.default.unlinkSync(nodeModulesSymlink);
                }
                /* v8 ignore stop */
                // Type `junction` is required on Windows.
                // https://github.com/nodejs/node/issues/18518#issuecomment-513866491
                node_fs_1.default.symlinkSync(nodeModulesPath, nodeModulesSymlink, /* v8 ignore next */ node_os_1.default.platform() === "win32" ? "junction" : "dir");
            }
        }
    }
    async start() {
        await super.start();
        this.eventBus.onMQTTMessage(this, this.onMQTTMessage);
        await this.loadFiles();
        await this.publishExternalJS();
    }
    async stop() {
        await super.stop();
        // ensure "node_modules" is never followed & included in 3rd-party backup systems
        const nodeModulesSymlink = node_path_1.default.join(this.basePath, "node_modules");
        if (node_fs_1.default.existsSync(nodeModulesSymlink)) {
            node_fs_1.default.unlinkSync(nodeModulesSymlink);
        }
    }
    getFilePath(name, mkBasePath = false) {
        if (mkBasePath && !node_fs_1.default.existsSync(this.basePath)) {
            node_fs_1.default.mkdirSync(this.basePath, { recursive: true });
        }
        return node_path_1.default.join(this.basePath, name);
    }
    getFileCode(name) {
        return node_fs_1.default.readFileSync(this.getFilePath(name), "utf8");
    }
    *getFiles() {
        if (node_fs_1.default.existsSync(this.basePath)) {
            for (const fileName of node_fs_1.default.readdirSync(this.basePath)) {
                if (!fileName.startsWith(TMP_PREFIX) && (fileName.endsWith(".js") || fileName.endsWith(".cjs") || fileName.endsWith(".mjs"))) {
                    yield { name: fileName, code: this.getFileCode(fileName) };
                }
            }
        }
    }
    async onMQTTMessage(data) {
        const match = data.topic.match(this.requestRegex);
        if (match && SUPPORTED_OPERATIONS.includes(match[1].toLowerCase())) {
            const message = utils_1.default.parseJSON(data.message, data.message);
            try {
                let response;
                if (match[1].toLowerCase() === "save") {
                    response = await this.save(message);
                }
                else {
                    response = await this.remove(message);
                }
                await this.mqtt.publish(`bridge/response/${this.mqttTopic}/${match[1]}`, (0, json_stable_stringify_without_jsonify_1.default)(response));
            }
            catch (error) {
                logger_1.default.error(`Request '${data.topic}' failed with error: '${error.message}'`);
                const response = utils_1.default.getResponse(message, {}, `${error.message}`);
                await this.mqtt.publish(`bridge/response/${this.mqttTopic}/${match[1]}`, (0, json_stable_stringify_without_jsonify_1.default)(response));
            }
        }
    }
    async remove(message) {
        if (!message.name) {
            return utils_1.default.getResponse(message, {}, "Invalid payload");
        }
        const { name } = message;
        const toBeRemoved = this.getFilePath(name);
        if (node_fs_1.default.existsSync(toBeRemoved)) {
            const mod = await this.importFile(toBeRemoved);
            await this.removeJS(name, mod.default);
            node_fs_1.default.rmSync(toBeRemoved, { force: true });
            logger_1.default.info(`${name} (${toBeRemoved}) removed.`);
            await this.publishExternalJS();
            return utils_1.default.getResponse(message, {});
        }
        return utils_1.default.getResponse(message, {}, `${name} (${toBeRemoved}) doesn't exists`);
    }
    async save(message) {
        if (!message.name || !message.code) {
            return utils_1.default.getResponse(message, {}, "Invalid payload");
        }
        const { name, code } = message;
        if (!name.endsWith(".mjs") && !name.endsWith(".js") && !name.endsWith(".cjs")) {
            return utils_1.default.getResponse(message, {}, "JavaScript file must have '.mjs', '.js' or '.cjs' extension");
        }
        const filePath = this.getFilePath(name, true);
        try {
            node_fs_1.default.writeFileSync(filePath, code, "utf8");
            this.symlinkNodeModulesIfNecessary();
            const mod = await this.importFile(filePath);
            await this.loadJS(name, mod.default, name);
            logger_1.default.info(`${name} loaded. Contents written to '${filePath}'.`);
            await this.publishExternalJS();
            return utils_1.default.getResponse(message, {});
        }
        catch (error) {
            return utils_1.default.getResponse(message, {}, `${name} contains invalid code: ${error.message}`);
        }
    }
    async loadFiles() {
        for (const extension of this.getFiles()) {
            this.symlinkNodeModulesIfNecessary();
            const filePath = this.getFilePath(extension.name);
            try {
                const mod = await this.importFile(filePath);
                await this.loadJS(extension.name, mod.default);
            }
            catch (error) {
                logger_1.default.error(`Invalid external ${this.mqttTopic} '${extension.name}' was ignored and renamed to prevent interference with Zigbee2MQTT. (${error.message})`);
                // biome-ignore lint/style/noNonNullAssertion: always Error
                logger_1.default.debug(error.stack);
                // change ext so Z2M doesn't try to load it again and again
                node_fs_1.default.renameSync(filePath, `${filePath}.invalid`);
            }
        }
    }
    async publishExternalJS() {
        await this.mqtt.publish(`bridge/${this.mqttTopic}s`, (0, json_stable_stringify_without_jsonify_1.default)(Array.from(this.getFiles())), {
            clientOptions: { retain: true },
            skipLog: true,
        });
    }
    // biome-ignore lint/suspicious/noExplicitAny: dynamic module
    async importFile(file) {
        const ext = node_path_1.default.extname(file);
        // Create the file in a temp path to bypass node module cache when importing multiple times.
        const tmpFile = node_path_1.default.join(this.basePath, `${TMP_PREFIX}${node_path_1.default.basename(file, ext)}-${crypto.randomUUID()}${ext}`);
        node_fs_1.default.copyFileSync(file, tmpFile);
        try {
            // Do `replaceAll("\\", "/")` to prevent issues on Windows
            /* v8 ignore next */
            const mod = await import(node_os_1.default.platform() === "win32" ? `file:///${tmpFile.replaceAll("\\", "/")}` : tmpFile);
            return mod;
        }
        finally {
            node_fs_1.default.rmSync(tmpFile);
        }
    }
}
exports.default = ExternalJSExtension;
__decorate([
    bind_decorator_1.default
], ExternalJSExtension.prototype, "onMQTTMessage", null);
__decorate([
    bind_decorator_1.default
], ExternalJSExtension.prototype, "remove", null);
__decorate([
    bind_decorator_1.default
], ExternalJSExtension.prototype, "save", null);
//# sourceMappingURL=data:application/json;base64, 