"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : /* @__PURE__ */ Symbol.for("Symbol." + name);
var __typeError = (msg) => {
  throw TypeError(msg);
};
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol("metadata")] ?? null)];
var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
var __runInitializers = (array, flags, self, value) => {
  for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value);
  return value;
};
var __decorateElement = (array, flags, name, decorators, target, extra) => {
  var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
  var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
  var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
  var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() {
    return __privateGet(this, extra);
  }, set [name](x) {
    return __privateSet(this, extra, x);
  } }, name));
  k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
  for (var i = decorators.length - 1; i >= 0; i--) {
    ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
    if (k) {
      ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x };
      if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
      if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
    }
    it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1;
    if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
    else if (typeof it !== "object" || it === null) __typeError("Object expected");
    else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
  }
  return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
};
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);

// src/core/template/index.ts
var index_exports = {};
__export(index_exports, {
  Template: () => Template
});
module.exports = __toCommonJS(index_exports);

// src/core/template/template.ts
var import_lodash = require("lodash");
var import_ts_dedent = require("ts-dedent");
var import_csp_header = require("csp-header");
var import_utils = require("@diplodoc/cli/lib/utils");

// src/core/template/utils.ts
function getFaviconType(faviconSrc) {
  if (!faviconSrc) {
    return void 0;
  }
  const cleanSrc = faviconSrc.split(/[?#]/)[0];
  const ext = cleanSrc.split(".").pop()?.toLowerCase();
  switch (ext) {
    case "svg":
      return "image/svg+xml";
    case "png":
      return "image/png";
    case "ico":
      return "image/x-icon";
    case "jpg":
    case "jpeg":
      return "image/jpeg";
    default:
      return void 0;
  }
}
function compareAlternates(a, b) {
  if (a.href < b.href) {
    return -1;
  }
  if (a.href > b.href) {
    return 1;
  }
  return 0;
}

// src/core/template/template.ts
var RTL_LANGS = [
  "ar",
  "arc",
  "ckb",
  "dv",
  "fa",
  "ha",
  "he",
  "khw",
  "ks",
  "ps",
  "sd",
  "ur",
  "uz_AF",
  "yi"
];
var _addAlternates_dec, _setCanonical_dec, _setFaviconSrc_dec, _addCsp_dec, _setCspDisabled_dec, _addBodyClass_dec, _addBody_dec, _addScript_dec, _addStyle_dec, _addMeta_dec, _setTitle_dec, _init;
_setTitle_dec = [import_utils.bounded], _addMeta_dec = [import_utils.bounded], _addStyle_dec = [import_utils.bounded], _addScript_dec = [import_utils.bounded], _addBody_dec = [import_utils.bounded], _addBodyClass_dec = [import_utils.bounded], _setCspDisabled_dec = [import_utils.bounded], _addCsp_dec = [import_utils.bounded], _setFaviconSrc_dec = [import_utils.bounded], _setCanonical_dec = [import_utils.bounded], _addAlternates_dec = [import_utils.bounded];
var Template = class {
  /**
   * Creates a new Template instance.
   *
   * @param path - Relative path of the page (will be normalized)
   * @param lang - Language code for the page
   * @param signs - Optional array of symbols for template identification/classification
   */
  constructor(path, lang, signs = []) {
    __runInitializers(_init, 5, this);
    /** Normalized path of the page (used for calculating base href) */
    this.path = void 0;
    /** Language code for the page (e.g., 'en', 'ru', 'ar') */
    this.lang = void 0;
    this.signs = [];
    this.title = "";
    this.csp = {};
    this.cspDisabled = false;
    this.meta = [];
    this.styles = [];
    this.scripts = [];
    this.body = [];
    this.bodyClass = ["g-root", "g-root_theme_light"];
    this.faviconSrc = "";
    this.canonical = "";
    this.alternates = [];
    this.path = (0, import_utils.normalizePath)(path);
    this.lang = lang;
    this.signs = signs;
  }
  /** Whether the template's language is right-to-left (RTL) */
  get isRTL() {
    return RTL_LANGS.includes(this.lang);
  }
  /**
   * Checks if the template has a specific sign.
   *
   * @param sign - Symbol to check
   * @returns `true` if template has the sign
   */
  is(sign) {
    return this.signs.includes(sign);
  }
  /**
   * Escapes HTML entities in a string.
   *
   * @param string - String to escape
   * @returns Escaped string with HTML entities
   */
  escape(string) {
    return string.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  }
  /**
   * Unescapes HTML entities in a string.
   *
   * IMPORTANT: This method should be serializable.
   *
   * @param string - String with HTML entities
   * @returns Unescaped string
   */
  unescape(string) {
    return string.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
  }
  setTitle(title) {
    this.title = title;
    return this;
  }
  addMeta(props) {
    this.meta.push(props);
    return this;
  }
  addStyle(style2, options = {}) {
    if (typeof options === "number") {
      options = {};
    }
    options = {
      position: "leading" /* Leading */,
      inline: false,
      attrs: {},
      ...options
    };
    this.styles.push({
      ...options,
      value: style2
    });
    return this;
  }
  addScript(script2, options = {}) {
    if (typeof options === "number") {
      options = {};
    }
    options = {
      position: "trailing" /* Trailing */,
      inline: false,
      attrs: {},
      ...options
    };
    this.scripts.push({
      ...options,
      value: script2
    });
    return this;
  }
  addBody(body) {
    this.body.push(body);
    return this;
  }
  addBodyClass(...classes) {
    this.bodyClass.push(...classes);
    return this;
  }
  setCspDisabled(disabled) {
    this.cspDisabled = disabled;
    return this;
  }
  addCsp(rules) {
    if (this.cspDisabled) {
      return;
    }
    for (const [key, records] of Object.entries(rules)) {
      this.csp[key] = this.csp[key] || [];
      this.csp[key].push(...records);
    }
  }
  setFaviconSrc(faviconSrc) {
    this.faviconSrc = faviconSrc;
    return this;
  }
  setCanonical(canonical) {
    this.canonical = canonical;
    return this;
  }
  addAlternates(alternates) {
    this.alternates = (0, import_lodash.uniqBy)(this.alternates.concat(alternates), (0, import_utils.get)("href"));
    return this;
  }
  /**
   * Generates the final HTML string from the template.
   *
   * Calculates base href, formats all metadata, styles, scripts, and body content
   * into a complete HTML document. Automatically handles RTL languages and CSP nonces.
   *
   * @returns Complete HTML document as string
   */
  dump() {
    const { lang, title, styles, scripts, body, bodyClass, faviconSrc, canonical, alternates } = this;
    const base = (0, import_utils.getDepthPath)((0, import_utils.getDepth)(this.path) - 1);
    const faviconType = getFaviconType(faviconSrc);
    return import_ts_dedent.dedent`
            <!DOCTYPE html>
            <html lang="${lang}" dir="${this.isRTL ? "rtl" : "ltr"}">
                <head>
                    <meta charset="utf-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <base href="${base}" />
                    <title>${title}</title>
                    ${canonical ? `<link rel="canonical" href="${canonical}">` : ""}
                    ${Object.values(alternates).sort(compareAlternates).map(alternate).join("\n")}
                    ${this.meta.map(meta).join("\n")}
                    ${csp(this.csp)}
                    <style type="text/css">html, body {min-height:100vh; height:100vh;}</style>
                    ${faviconSrc && `<link rel="icon" type="${faviconType}" href="${faviconSrc}">`}
                    ${leading(scripts).map(script(this.csp)).join("\n")}
                    ${leading(styles).map(style(this.csp)).join("\n")}
                </head>
                <body class="${bodyClass.join(" ")}">
                    ${body.join("\n") || `<div id="root"></div>`}
                    ${state(scripts).map(script(this.csp)).join("\n")}
                    ${trailing(scripts).map(script(this.csp)).join("\n")}
                    ${trailing(styles).map(style(this.csp)).join("\n")}
                </body>
            </html>
        `;
  }
};
_init = __decoratorStart(null);
__decorateElement(_init, 1, "setTitle", _setTitle_dec, Template);
__decorateElement(_init, 1, "addMeta", _addMeta_dec, Template);
__decorateElement(_init, 1, "addStyle", _addStyle_dec, Template);
__decorateElement(_init, 1, "addScript", _addScript_dec, Template);
__decorateElement(_init, 1, "addBody", _addBody_dec, Template);
__decorateElement(_init, 1, "addBodyClass", _addBodyClass_dec, Template);
__decorateElement(_init, 1, "setCspDisabled", _setCspDisabled_dec, Template);
__decorateElement(_init, 1, "addCsp", _addCsp_dec, Template);
__decorateElement(_init, 1, "setFaviconSrc", _setFaviconSrc_dec, Template);
__decorateElement(_init, 1, "setCanonical", _setCanonical_dec, Template);
__decorateElement(_init, 1, "addAlternates", _addAlternates_dec, Template);
__decoratorMetadata(_init, Template);
function leading(array) {
  return array.filter(({ position }) => position === "leading");
}
function state(array) {
  return array.filter(({ position }) => position === "state");
}
function trailing(array) {
  return array.filter(({ position }) => position === "trailing");
}
function meta(record) {
  return `<meta ${attributes(record)}>`;
}
function alternate({ href, hreflang }) {
  return `<link ${attributes({ rel: "alternate", href, hreflang })} />`;
}
function csp(directives) {
  if (!directives || !Object.keys(directives).length) {
    return "";
  }
  return meta({
    "http-equiv": "Content-Security-Policy",
    content: (0, import_csp_header.getCSP)({ directives })
  });
}
function style(csp2) {
  return function({ value, inline, attrs }) {
    if (inline) {
      return import_ts_dedent.dedent`
                <style ${attributes({ ...attrs, nonce: nonce(csp2, "style-src") })}>
                    ${value}
                </style>
            `;
    }
    return `<link ${attributes({
      ...attrs,
      type: "text/css",
      rel: "stylesheet",
      href: value,
      nonce: nonce(csp2, "style-src")
    })}/>`;
  };
}
function script(csp2) {
  return function({ value, inline, attrs }) {
    if (inline) {
      return import_ts_dedent.dedent`
                <script ${attributes({
        type: "application/javascript",
        ...attrs,
        nonce: nonce(csp2, "script-src")
      })}>
                    ${value}
                </script>
            `;
    }
    return `<script ${attributes({
      type: "application/javascript",
      defer: "",
      ...attrs,
      src: value,
      nonce: nonce(csp2, "script-src")
    })}></script>`;
  };
}
function nonce(csp2, scope) {
  if (!csp2 || !csp2[scope]) {
    return;
  }
  const rule = csp2[scope].find((rule2) => rule2.match(/^nonce/));
  if (!rule) {
    return;
  }
  return rule.match(/(?<=nonce=).*/g)[0];
}
function attributes(attrs) {
  return Object.keys(attrs).reduce((acc, key) => {
    const value = attrs[key];
    if (value === "") {
      acc += ` ${key}`;
    } else if (value !== void 0) {
      acc += ` ${key}="${value}"`;
    }
    return acc;
  }, "").trim();
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  Template
});
//# sourceMappingURL=index.js.map
