/* Tiny CEP helper -- talks to ExtendScript + Node without the full CSInterface
 * library. Works in the CEP panel context (window.__adobe_cep__). */
var CEP = (function () {
    function evalScript(script, cb) {
        if (window.__adobe_cep__ && window.__adobe_cep__.evalScript) {
            window.__adobe_cep__.evalScript(script, function (res) { if (cb) { cb(res); } });
        } else if (cb) {
            cb('{"ok":false,"errors":["Not running inside Premiere (no CEP host)."]}');
        }
    }
    function nodeRequire(mod) {
        if (typeof require === "function") { return require(mod); }
        if (window.cep_node && window.cep_node.require) { return window.cep_node.require(mod); }
        throw new Error("Node.js is not enabled in this panel.");
    }
    // safely JSON-encode a string for embedding in an evalScript call.
    // v1.03: also escape U+2028/U+2029 — JSON.stringify leaves them raw, but they
    // are LINE TERMINATORS inside an ExtendScript string literal, so a speaker or
    // track name containing one produced a syntax error ("Bad response from
    // Premiere") instead of a working call.
    function q(s) {
        return JSON.stringify(String(s))
            .replace(/\u2028/g, "\\u2028")
            .replace(/\u2029/g, "\\u2029");
    }
    // Open a URL in the user's default browser (for sign-in). Prefer the CEP
    // host API; fall back to the OS opener via Node.
    // v1.10 hardening: only ever open HTTPS URLs, reject shell metacharacters,
    // and use execFile with an ARGUMENT ARRAY (never string interpolation into a
    // shell). URLs can arrive from server responses; a compromised/MITM'd reply
    // must not become local code execution.
    function safeURL(url) {
        url = String(url || "");
        if (!/^https:\/\//i.test(url)) { return ""; }
        if (/["'`\\\s<>{}$]/.test(url)) { return ""; }
        return url;
    }
    function openURL(url) {
        var u = safeURL(url);
        if (!u) { return false; }
        try {
            if (window.cep && window.cep.util && window.cep.util.openURLInDefaultBrowser) {
                window.cep.util.openURLInDefaultBrowser(u); return true;
            }
        } catch (e) {}
        try {
            var cp = nodeRequire("child_process");
            if (typeof process !== "undefined" && process.platform === "win32") {
                // `start` is a cmd builtin, so cmd is required — but the URL rides
                // as a discrete argv entry, not inside an interpolated string.
                cp.execFile("cmd", ["/c", "start", "", u]);
            } else {
                cp.execFile("open", [u]);
            }
            return true;
        } catch (e2) {}
        return false;
    }
    return { evalScript: evalScript, require: nodeRequire, q: q, openURL: openURL,
             _safeURL: safeURL };
})();
