var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
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 __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/leading/hooks.ts
import { AsyncSeriesHook, AsyncSeriesWaterfallHook } from "tapable";
import { generateHooksAccess } from "@diplodoc/cli/lib/utils";
function hooks(name) {
  return {
    Plugins: new AsyncSeriesWaterfallHook(["plugins"], `${name}.Plugins`),
    Loaded: new AsyncSeriesHook(
      ["leading", "meta", "path"],
      `${name}.Loaded`
    ),
    Resolved: new AsyncSeriesHook(
      ["leading", "meta", "path"],
      `${name}.Resolved`
    ),
    Dump: new AsyncSeriesHook(["vfile"], `${name}.Dump`)
  };
}
var [getHooks, withHooks] = generateHooksAccess("Leading", hooks);

// src/core/leading/LeadingService.ts
import { dirname, join } from "node:path";
import { dump, load } from "js-yaml";
import {
  Buckets,
  Defer,
  Graph,
  VFile,
  all,
  bounded,
  fullPath,
  langFromPath,
  normalizePath,
  walkLinks as walkLinks2
} from "@diplodoc/cli/lib/utils";

// src/core/leading/loader.ts
import { get, set } from "lodash";
import { evaluate, liquidJson, liquidSnippet } from "@diplodoc/liquid";
import { bucket, filterBlocksByConditions, parseLocalUrl, rebasePath, walkLinks } from "@diplodoc/cli/lib/utils";
var LoaderAPI = class {
  constructor(proxy = {}) {
    this.deps = proxy.deps || bucket();
    this.assets = proxy.assets || bucket();
    this.meta = proxy.meta || bucket();
  }
};
async function loader(yaml) {
  yaml = resolveConditions.call(this, yaml);
  yaml = resolveFields.call(this, yaml);
  yaml = mangleFrontMatter.call(this, yaml);
  yaml = templateFields.call(this, yaml);
  for (const plugin of this.plugins) {
    yaml = await plugin.call(this, yaml);
  }
  yaml = resolveAssets.call(this, yaml);
  this.api.deps.set([]);
  return yaml;
}
function resolveConditions(yaml) {
  const { skipMissingVars = false } = this.options;
  const vars = this.vars || {};
  yaml = filterBlocksByConditions(yaml, vars, skipMissingVars);
  return yaml;
}
function resolveFields(yaml) {
  for (const field of ["title", "nav.title", "meta.title", "meta.description"]) {
    const value = get(yaml, field);
    if (value) {
      set(yaml, field, toText(getFirstValuable(value, this.vars)));
    }
  }
  if (yaml.description) {
    yaml.description = toTextArray(getAllValuable(yaml.description, this.vars));
  }
  yaml.links = getAllValuable(yaml.links || [], this.vars);
  return yaml;
}
function mangleFrontMatter(yaml) {
  const { vars, options } = this;
  const { disableLiquid } = options;
  if (!yaml.meta) {
    this.api.meta.set({});
    return yaml;
  }
  const frontmatter = yaml.meta;
  yaml.meta = void 0;
  if (disableLiquid) {
    this.api.meta.set(frontmatter);
  } else {
    this.api.meta.set(liquidJson.call(this, frontmatter, vars));
  }
  return yaml;
}
function templateFields(yaml) {
  const { conditions, substitutions } = this.settings;
  const interpolate = (value) => {
    if (typeof value !== "string") {
      return value;
    }
    return liquidSnippet.call(this, value, this.vars);
  };
  if (!conditions && !substitutions) {
    return yaml;
  }
  for (const field of ["title", "description", "nav.title"]) {
    const value = get(yaml, field);
    if (Array.isArray(value)) {
      set(yaml, field, value.map(interpolate));
    } else if (typeof value === "string") {
      set(yaml, field, interpolate(value));
    }
  }
  for (const link of yaml.links) {
    for (const field of ["title", "description"]) {
      const value = get(link, field);
      if (typeof value === "string") {
        set(link, field, interpolate(value));
      }
    }
  }
  return yaml;
}
function resolveAssets(yaml) {
  const assets = [];
  yaml = walkLinks(yaml, (link) => {
    const asset = parseLocalUrl(link);
    if (asset) {
      try {
        asset.path = rebasePath(
          this.path,
          decodeURIComponent(asset.path)
        );
        assets.push(asset);
      } catch {
      }
    }
    return link;
  });
  this.api.assets.set(assets);
  return yaml;
}
function getAllValuable(items, vars) {
  const result = [];
  for (const item of normalizeItems(items, vars)) {
    if (typeof item === "string") {
      result.push(item);
    } else if (item.when !== false) {
      delete item.when;
      result.push(item);
    }
  }
  return result;
}
function getFirstValuable(items, vars) {
  for (const item of normalizeItems(items, vars)) {
    if (typeof item === "string") {
      return item;
    } else if (item.when !== false) {
      delete item.when;
      return item;
    }
  }
  return void 0;
}
function normalizeItems(items, vars) {
  if (!Array.isArray(items)) {
    items = [items];
  }
  return items.map((item) => {
    if (typeof item === "string") {
      return item;
    }
    if (typeof item.when === "string") {
      item.when = Boolean(evaluate(item.when, vars));
    }
    return item;
  });
}
function toText(item) {
  if (!item) {
    return void 0;
  }
  if (typeof item === "string") {
    return item;
  }
  if (Array.isArray(item.text)) {
    return item.text[0];
  } else {
    return item.text;
  }
}
function toTextArray(items) {
  const result = [];
  for (const item of items) {
    if (typeof item === "string") {
      result.push(item);
    } else if (typeof item.text === "string") {
      result.push(item.text);
    } else if (Array.isArray(item.text)) {
      result.push(...item.text);
    }
  }
  return result;
}

// src/core/leading/LeadingService.ts
var _walkLinks_dec, _dump_dec, _load_dec, _init_dec, _LeadingService_decorators, _init;
_LeadingService_decorators = [withHooks], _init_dec = [bounded], _load_dec = [bounded], _dump_dec = [bounded], _walkLinks_dec = [bounded];
var LeadingService = class {
  constructor(run) {
    __runInitializers(_init, 5, this);
    this.name = "Leading";
    this.run = void 0;
    this.config = void 0;
    this.cache = {};
    this.plugins = [];
    this.pathToMeta = new Buckets();
    this.pathToDeps = new Buckets();
    this.pathToAssets = new Buckets();
    this.run = run;
    this.config = run.config;
  }
  get logger() {
    return this.run.logger;
  }
  async init() {
    this.plugins = await getHooks(this).Plugins.promise(this.plugins);
  }
  async load(path) {
    const file = normalizePath(path);
    if (file in this.cache) {
      return this.cache[file];
    }
    const defer = new Defer();
    this.cache[file] = defer.promise;
    try {
      const source = normalizePath(join(this.run.input, file));
      const raw = await this.run.read(source);
      const vars = this.run.vars.for(path);
      const yaml = load(raw || "{}");
      const context = this.loaderContext(file, raw, vars, this.proxy(file));
      const leading = await loader.call(context, yaml);
      const meta = this.pathToMeta.get(file);
      await getHooks(this).Loaded.promise(leading, meta, file);
      this.run.meta.addMetadata(path, vars.__metadata);
      this.run.meta.addSystemVars(path, vars.__system);
      this.run.meta.add(file, meta, true);
      this.run.meta.addResources(file, leading.meta);
      this.cache[file] = leading;
      defer.resolve(leading);
      await getHooks(this).Resolved.promise(leading, meta, file);
    } catch (error) {
      defer.reject(error);
    }
    return defer.promise;
  }
  async dump(path, leading) {
    const vfile = new VFile(path, leading || await this.load(path), dump);
    await getHooks(this).Dump.promise(vfile);
    return vfile;
  }
  walkLinks(leading, walker) {
    if (!leading) {
      return void 0;
    }
    return walkLinks2(leading, walker);
  }
  async deps(path) {
    const file = normalizePath(path);
    return this.pathToDeps.get(file);
  }
  async assets(path) {
    const file = normalizePath(path);
    return [...this.pathToAssets.get(file)];
  }
  async relations(path) {
    const file = normalizePath(path);
    const graph = new Graph();
    graph.addNode(file, { type: "entry" });
    await this.load(path);
    await all(
      (this.pathToDeps.get(file) || []).map(async (dep) => {
        graph.consume(await this.relations(dep.path));
        graph.setNodeData(dep.path, { type: "source" });
        graph.addDependency(path, dep.path);
      })
    );
    const meta = this.run.meta.get(path);
    const resources = [].concat(meta.script || [], meta.style || []);
    for (const resource of resources) {
      const file2 = normalizePath(join(dirname(path), resource));
      graph.addNode(file2);
      graph.setNodeData(file2, { type: "resource" });
      graph.addDependency(path, file2);
    }
    return graph;
  }
  release(path) {
    delete this.cache[path];
    this.pathToDeps.delete(path);
    this.pathToMeta.delete(path);
    this.pathToAssets.delete(path);
  }
  proxy(key) {
    return {
      deps: this.pathToDeps.bind(key),
      assets: this.pathToAssets.bind(key),
      meta: this.pathToMeta.bind(key)
    };
  }
  loaderContext(path, _raw, vars, api) {
    return {
      path,
      vars,
      lang: langFromPath(path, this.config),
      readFile: (path2) => {
        return this.run.read(join(this.run.input, path2));
      },
      emitFile: async (file, content) => {
        const rootPath = fullPath(file, path);
        await this.run.write(join(this.run.input, rootPath), content);
      },
      plugins: [...this.plugins],
      logger: this.logger,
      api: new LoaderAPI(api),
      options: {
        disableLiquid: !this.run.config.template.enabled,
        skipMissingVars: false
      },
      settings: {
        substitutions: this.config.template.features.substitutions,
        conditions: this.config.template.features.conditions
      }
    };
  }
};
_init = __decoratorStart(null);
__decorateElement(_init, 1, "init", _init_dec, LeadingService);
__decorateElement(_init, 1, "load", _load_dec, LeadingService);
__decorateElement(_init, 1, "dump", _dump_dec, LeadingService);
__decorateElement(_init, 1, "walkLinks", _walkLinks_dec, LeadingService);
LeadingService = __decorateElement(_init, 0, "LeadingService", _LeadingService_decorators, LeadingService);
__runInitializers(_init, 1, LeadingService);
export {
  LeadingService,
  getHooks
};
//# sourceMappingURL=index.mjs.map
