'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var fse = require('fs-extra');
var prettier = require('prettier');
var EventEmitter = require('events');
var uuid = require('uuid');
var dirTree = require('directory-tree');

var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __esm = (fn, res) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));

// ../../node_modules/.pnpm/tsup@6.5.0_typescript@4.9.4/node_modules/tsup/assets/cjs_shims.js
var init_cjs_shims = __esm({
  "../../node_modules/.pnpm/tsup@6.5.0_typescript@4.9.4/node_modules/tsup/assets/cjs_shims.js"() {
  }
});

// ../../node_modules/.pnpm/path-browserify@1.0.1/node_modules/path-browserify/index.js
var require_path_browserify = __commonJS({
  "../../node_modules/.pnpm/path-browserify@1.0.1/node_modules/path-browserify/index.js"(exports, module) {
    init_cjs_shims();
    function assertPath(path) {
      if (typeof path !== "string") {
        throw new TypeError("Path must be a string. Received " + JSON.stringify(path));
      }
    }
    function normalizeStringPosix(path, allowAboveRoot) {
      var res = "";
      var lastSegmentLength = 0;
      var lastSlash = -1;
      var dots = 0;
      var code;
      for (var i = 0; i <= path.length; ++i) {
        if (i < path.length)
          code = path.charCodeAt(i);
        else if (code === 47)
          break;
        else
          code = 47;
        if (code === 47) {
          if (lastSlash === i - 1 || dots === 1) ; else if (lastSlash !== i - 1 && dots === 2) {
            if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 || res.charCodeAt(res.length - 2) !== 46) {
              if (res.length > 2) {
                var lastSlashIndex = res.lastIndexOf("/");
                if (lastSlashIndex !== res.length - 1) {
                  if (lastSlashIndex === -1) {
                    res = "";
                    lastSegmentLength = 0;
                  } else {
                    res = res.slice(0, lastSlashIndex);
                    lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
                  }
                  lastSlash = i;
                  dots = 0;
                  continue;
                }
              } else if (res.length === 2 || res.length === 1) {
                res = "";
                lastSegmentLength = 0;
                lastSlash = i;
                dots = 0;
                continue;
              }
            }
            if (allowAboveRoot) {
              if (res.length > 0)
                res += "/..";
              else
                res = "..";
              lastSegmentLength = 2;
            }
          } else {
            if (res.length > 0)
              res += "/" + path.slice(lastSlash + 1, i);
            else
              res = path.slice(lastSlash + 1, i);
            lastSegmentLength = i - lastSlash - 1;
          }
          lastSlash = i;
          dots = 0;
        } else if (code === 46 && dots !== -1) {
          ++dots;
        } else {
          dots = -1;
        }
      }
      return res;
    }
    function _format(sep, pathObject) {
      var dir = pathObject.dir || pathObject.root;
      var base = pathObject.base || (pathObject.name || "") + (pathObject.ext || "");
      if (!dir) {
        return base;
      }
      if (dir === pathObject.root) {
        return dir + base;
      }
      return dir + sep + base;
    }
    var posix = {
      resolve: function resolve() {
        var resolvedPath = "";
        var resolvedAbsolute = false;
        var cwd;
        for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
          var path;
          if (i >= 0)
            path = arguments[i];
          else {
            if (cwd === void 0)
              cwd = process.cwd();
            path = cwd;
          }
          assertPath(path);
          if (path.length === 0) {
            continue;
          }
          resolvedPath = path + "/" + resolvedPath;
          resolvedAbsolute = path.charCodeAt(0) === 47;
        }
        resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);
        if (resolvedAbsolute) {
          if (resolvedPath.length > 0)
            return "/" + resolvedPath;
          else
            return "/";
        } else if (resolvedPath.length > 0) {
          return resolvedPath;
        } else {
          return ".";
        }
      },
      normalize: function normalize(path) {
        assertPath(path);
        if (path.length === 0)
          return ".";
        var isAbsolute = path.charCodeAt(0) === 47;
        var trailingSeparator = path.charCodeAt(path.length - 1) === 47;
        path = normalizeStringPosix(path, !isAbsolute);
        if (path.length === 0 && !isAbsolute)
          path = ".";
        if (path.length > 0 && trailingSeparator)
          path += "/";
        if (isAbsolute)
          return "/" + path;
        return path;
      },
      isAbsolute: function isAbsolute(path) {
        assertPath(path);
        return path.length > 0 && path.charCodeAt(0) === 47;
      },
      join: function join() {
        if (arguments.length === 0)
          return ".";
        var joined;
        for (var i = 0; i < arguments.length; ++i) {
          var arg = arguments[i];
          assertPath(arg);
          if (arg.length > 0) {
            if (joined === void 0)
              joined = arg;
            else
              joined += "/" + arg;
          }
        }
        if (joined === void 0)
          return ".";
        return posix.normalize(joined);
      },
      relative: function relative(from, to) {
        assertPath(from);
        assertPath(to);
        if (from === to)
          return "";
        from = posix.resolve(from);
        to = posix.resolve(to);
        if (from === to)
          return "";
        var fromStart = 1;
        for (; fromStart < from.length; ++fromStart) {
          if (from.charCodeAt(fromStart) !== 47)
            break;
        }
        var fromEnd = from.length;
        var fromLen = fromEnd - fromStart;
        var toStart = 1;
        for (; toStart < to.length; ++toStart) {
          if (to.charCodeAt(toStart) !== 47)
            break;
        }
        var toEnd = to.length;
        var toLen = toEnd - toStart;
        var length = fromLen < toLen ? fromLen : toLen;
        var lastCommonSep = -1;
        var i = 0;
        for (; i <= length; ++i) {
          if (i === length) {
            if (toLen > length) {
              if (to.charCodeAt(toStart + i) === 47) {
                return to.slice(toStart + i + 1);
              } else if (i === 0) {
                return to.slice(toStart + i);
              }
            } else if (fromLen > length) {
              if (from.charCodeAt(fromStart + i) === 47) {
                lastCommonSep = i;
              } else if (i === 0) {
                lastCommonSep = 0;
              }
            }
            break;
          }
          var fromCode = from.charCodeAt(fromStart + i);
          var toCode = to.charCodeAt(toStart + i);
          if (fromCode !== toCode)
            break;
          else if (fromCode === 47)
            lastCommonSep = i;
        }
        var out = "";
        for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
          if (i === fromEnd || from.charCodeAt(i) === 47) {
            if (out.length === 0)
              out += "..";
            else
              out += "/..";
          }
        }
        if (out.length > 0)
          return out + to.slice(toStart + lastCommonSep);
        else {
          toStart += lastCommonSep;
          if (to.charCodeAt(toStart) === 47)
            ++toStart;
          return to.slice(toStart);
        }
      },
      _makeLong: function _makeLong(path) {
        return path;
      },
      dirname: function dirname(path) {
        assertPath(path);
        if (path.length === 0)
          return ".";
        var code = path.charCodeAt(0);
        var hasRoot = code === 47;
        var end = -1;
        var matchedSlash = true;
        for (var i = path.length - 1; i >= 1; --i) {
          code = path.charCodeAt(i);
          if (code === 47) {
            if (!matchedSlash) {
              end = i;
              break;
            }
          } else {
            matchedSlash = false;
          }
        }
        if (end === -1)
          return hasRoot ? "/" : ".";
        if (hasRoot && end === 1)
          return "//";
        return path.slice(0, end);
      },
      basename: function basename(path, ext) {
        if (ext !== void 0 && typeof ext !== "string")
          throw new TypeError('"ext" argument must be a string');
        assertPath(path);
        var start = 0;
        var end = -1;
        var matchedSlash = true;
        var i;
        if (ext !== void 0 && ext.length > 0 && ext.length <= path.length) {
          if (ext.length === path.length && ext === path)
            return "";
          var extIdx = ext.length - 1;
          var firstNonSlashEnd = -1;
          for (i = path.length - 1; i >= 0; --i) {
            var code = path.charCodeAt(i);
            if (code === 47) {
              if (!matchedSlash) {
                start = i + 1;
                break;
              }
            } else {
              if (firstNonSlashEnd === -1) {
                matchedSlash = false;
                firstNonSlashEnd = i + 1;
              }
              if (extIdx >= 0) {
                if (code === ext.charCodeAt(extIdx)) {
                  if (--extIdx === -1) {
                    end = i;
                  }
                } else {
                  extIdx = -1;
                  end = firstNonSlashEnd;
                }
              }
            }
          }
          if (start === end)
            end = firstNonSlashEnd;
          else if (end === -1)
            end = path.length;
          return path.slice(start, end);
        } else {
          for (i = path.length - 1; i >= 0; --i) {
            if (path.charCodeAt(i) === 47) {
              if (!matchedSlash) {
                start = i + 1;
                break;
              }
            } else if (end === -1) {
              matchedSlash = false;
              end = i + 1;
            }
          }
          if (end === -1)
            return "";
          return path.slice(start, end);
        }
      },
      extname: function extname(path) {
        assertPath(path);
        var startDot = -1;
        var startPart = 0;
        var end = -1;
        var matchedSlash = true;
        var preDotState = 0;
        for (var i = path.length - 1; i >= 0; --i) {
          var code = path.charCodeAt(i);
          if (code === 47) {
            if (!matchedSlash) {
              startPart = i + 1;
              break;
            }
            continue;
          }
          if (end === -1) {
            matchedSlash = false;
            end = i + 1;
          }
          if (code === 46) {
            if (startDot === -1)
              startDot = i;
            else if (preDotState !== 1)
              preDotState = 1;
          } else if (startDot !== -1) {
            preDotState = -1;
          }
        }
        if (startDot === -1 || end === -1 || preDotState === 0 || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
          return "";
        }
        return path.slice(startDot, end);
      },
      format: function format2(pathObject) {
        if (pathObject === null || typeof pathObject !== "object") {
          throw new TypeError('The "pathObject" argument must be of type Object. Received type ' + typeof pathObject);
        }
        return _format("/", pathObject);
      },
      parse: function parse(path) {
        assertPath(path);
        var ret = { root: "", dir: "", base: "", ext: "", name: "" };
        if (path.length === 0)
          return ret;
        var code = path.charCodeAt(0);
        var isAbsolute = code === 47;
        var start;
        if (isAbsolute) {
          ret.root = "/";
          start = 1;
        } else {
          start = 0;
        }
        var startDot = -1;
        var startPart = 0;
        var end = -1;
        var matchedSlash = true;
        var i = path.length - 1;
        var preDotState = 0;
        for (; i >= start; --i) {
          code = path.charCodeAt(i);
          if (code === 47) {
            if (!matchedSlash) {
              startPart = i + 1;
              break;
            }
            continue;
          }
          if (end === -1) {
            matchedSlash = false;
            end = i + 1;
          }
          if (code === 46) {
            if (startDot === -1)
              startDot = i;
            else if (preDotState !== 1)
              preDotState = 1;
          } else if (startDot !== -1) {
            preDotState = -1;
          }
        }
        if (startDot === -1 || end === -1 || preDotState === 0 || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
          if (end !== -1) {
            if (startPart === 0 && isAbsolute)
              ret.base = ret.name = path.slice(1, end);
            else
              ret.base = ret.name = path.slice(startPart, end);
          }
        } else {
          if (startPart === 0 && isAbsolute) {
            ret.name = path.slice(1, startDot);
            ret.base = path.slice(1, end);
          } else {
            ret.name = path.slice(startPart, startDot);
            ret.base = path.slice(startPart, end);
          }
          ret.ext = path.slice(startDot, end);
        }
        if (startPart > 0)
          ret.dir = path.slice(0, startPart - 1);
        else if (isAbsolute)
          ret.dir = "/";
        return ret;
      },
      sep: "/",
      delimiter: ":",
      win32: null,
      posix: null
    };
    posix.posix = posix;
    module.exports = posix;
  }
});

// src/index.ts
init_cjs_shims();

// src/build.ts
init_cjs_shims();

// src/managers/pluginManager/PluginManager.ts
init_cjs_shims();

// src/plugin.ts
init_cjs_shims();
var import_path2 = __toESM(require_path_browserify());

// src/utils/isPromise.ts
init_cjs_shims();
var isPromise = (result) => {
  return typeof result?.then === "function";
};

// src/utils/write.ts
init_cjs_shims();

// src/utils/format.ts
init_cjs_shims();
var formatOptions = {
  tabWidth: 2,
  printWidth: 160,
  parser: "typescript",
  singleQuote: true,
  semi: false,
  bracketSameLine: false,
  endOfLine: "auto"
};
var format = (text) => {
  return prettier.format(text, formatOptions);
};

// src/utils/write.ts
var write = async (data, path, options = { format: false }) => {
  const formattedData = options.format ? format(data) : data;
  try {
    await fse.stat(path);
    const oldContent = await fse.readFile(path, { encoding: "utf-8" });
    if (oldContent?.toString() === formattedData) {
      return;
    }
  } catch (_err) {
    return fse.outputFile(path, formattedData, { encoding: "utf-8" });
  }
  return fse.outputFile(path, formattedData, { encoding: "utf-8" });
};
var clean = async (path) => {
  return fse.remove(path);
};

// src/utils/cache.ts
init_cjs_shims();
function createPluginCache(cache) {
  return {
    delete(id) {
      return delete cache[id];
    },
    get(id) {
      const item = cache[id];
      if (!item)
        return;
      item[0] = 0;
      return item[1];
    },
    has(id) {
      const item = cache[id];
      if (!item)
        return false;
      item[0] = 0;
      return true;
    },
    set(id, value) {
      cache[id] = [0, value];
    }
  };
}

// src/utils/read.ts
init_cjs_shims();
var import_path = __toESM(require_path_browserify());
var getRelativePath = (root, file) => {
  if (!root || !file) {
    throw new Error("Root and file should be filled in when retrieving the relativePath");
  }
  const newPath = import_path.default.relative(root, file).replace("../", "").replace(".ts", "").trimEnd();
  return `./${newPath}`;
};
var getPathMode = (path) => {
  if (!path) {
    return void 0;
  }
  return import_path.default.extname(path) ? "file" : "directory";
};
var read = async (path, encoding = "utf8") => {
  try {
    return fse.readFile(path, encoding);
  } catch (err) {
    console.error(err);
    throw err;
  }
};

// src/plugin.ts
function createPlugin(factory) {
  return (options) => {
    const plugin = factory(options);
    if (Array.isArray(plugin)) {
      throw new Error("Not implemented");
    }
    if (!plugin.transform) {
      plugin.transform = function transform(code) {
        return code;
      };
    }
    return plugin;
  };
}
var name = "core";
var isEmittedFile = (result) => {
  return !!result.id;
};
var definePlugin = createPlugin((options) => {
  const { fileManager, resolveId, load } = options;
  const api = {
    get config() {
      return options.config;
    },
    fileManager,
    async addFile(file, options2) {
      if (isEmittedFile(file)) {
        const resolvedId = await resolveId({ fileName: file.id, directory: file.importer, options: file.options });
        const path = resolvedId || file.importer || file.id;
        return fileManager.add({
          path,
          fileName: file.name || file.id,
          source: file.source || ""
        });
      }
      if (options2?.root) ;
      return fileManager.addOrAppend(file);
    },
    resolveId,
    load,
    cache: createPluginCache(/* @__PURE__ */ Object.create(null))
  };
  return {
    name,
    api,
    resolveId(fileName, directory) {
      if (!directory) {
        return null;
      }
      return import_path2.default.resolve(directory, fileName);
    }
  };
});

// src/managers/fileManager/FileManager.ts
init_cjs_shims();

// src/managers/fileManager/events.ts
init_cjs_shims();
var keys = {
  getFileKey: () => `file`,
  getStatusChangeKey: () => `status-change`,
  getStatusChangeByIdKey: (id) => `${id}-status-change`,
  getSuccessKey: () => `success`,
  getRemoveKey: (id) => `${id}remove`
};
var getFileManagerEvents = (emitter) => {
  return {
    emitFile: (id, file) => {
      emitter.emit(keys.getFileKey(), id, file);
    },
    emitStatusChange: (file) => {
      emitter.emit(keys.getStatusChangeKey(), file);
    },
    emitStatusChangeById: (id, status) => {
      emitter.emit(keys.getStatusChangeByIdKey(id), status);
    },
    emitSuccess: () => {
      emitter.emit(keys.getSuccessKey());
    },
    emitRemove: (id, file) => {
      emitter.emit(keys.getRemoveKey(id), file);
    },
    onAdd: (callback) => {
      emitter.on(keys.getFileKey(), callback);
      return () => emitter.removeListener(keys.getFileKey(), callback);
    },
    onStatusChange: (callback) => {
      emitter.on(keys.getStatusChangeKey(), callback);
      return () => emitter.removeListener(keys.getStatusChangeKey(), callback);
    },
    onStatusChangeById: (id, callback) => {
      emitter.on(keys.getStatusChangeByIdKey(id), callback);
      return () => emitter.removeListener(keys.getStatusChangeByIdKey(id), callback);
    },
    onSuccess: (callback) => {
      emitter.on(keys.getSuccessKey(), callback);
      return () => emitter.removeListener(keys.getSuccessKey(), callback);
    },
    onRemove: (id, callback) => {
      emitter.on(keys.getRemoveKey(id), callback);
      return () => emitter.removeListener(keys.getRemoveKey(id), callback);
    }
  };
};

// src/managers/fileManager/FileManager.ts
var FileManager = class {
  cache = /* @__PURE__ */ new Map();
  emitter = new EventEmitter();
  events = getFileManagerEvents(this.emitter);
  constructor() {
    this.events.onStatusChange(() => {
      if (this.getCountByStatus("removed") === this.cache.size) {
        this.events.emitSuccess();
      }
    });
  }
  getCache(id) {
    return this.cache.get(id);
  }
  getCacheByPath(path) {
    let cache;
    this.cache.forEach((item) => {
      if (item.file.path === path) {
        cache = item;
      }
    });
    return cache;
  }
  getCountByStatus(status) {
    let count = 0;
    this.cache.forEach((item) => {
      if (item.status === status) {
        count++;
      }
    });
    return count;
  }
  get files() {
    const files = [];
    this.cache.forEach((item) => {
      files.push(item.file);
    });
    return files;
  }
  add(file) {
    const cacheItem = { id: uuid.v4(), file, status: "new" };
    this.cache.set(cacheItem.id, cacheItem);
    this.events.emitFile(cacheItem.id, file);
    return new Promise((resolve) => {
      const unsubscribe = this.events.onRemove(cacheItem.id, (file2) => {
        resolve(file2);
        unsubscribe();
      });
    });
  }
  addOrAppend(file) {
    const previousCache = this.getCacheByPath(file.path);
    if (previousCache) {
      this.remove(previousCache.id);
      return this.add({
        ...file,
        source: `${previousCache.file.source}
${file.source}`
      });
    }
    return this.add(file);
  }
  setStatus(id, status) {
    const cacheItem = this.getCache(id);
    if (!cacheItem) {
      return;
    }
    cacheItem.status = status;
    this.cache.set(id, cacheItem);
    this.events.emitStatusChange(cacheItem.file);
    this.events.emitStatusChangeById(id, status);
  }
  get(id) {
    const cacheItem = this.getCache(id);
    return cacheItem?.file;
  }
  remove(id) {
    const cacheItem = this.getCache(id);
    if (!cacheItem) {
      return;
    }
    this.setStatus(id, "removed");
    this.events.emitRemove(id, cacheItem.file);
  }
  async write(...params) {
    return write(...params);
  }
  async read(...params) {
    return read(...params);
  }
};

// src/managers/fileManager/TreeNode.ts
init_cjs_shims();
var TreeNode = class {
  data;
  parent;
  children;
  constructor(data, parent) {
    this.data = data;
    this.parent = parent;
    return this;
  }
  addChild(data) {
    const child = new TreeNode(data, this);
    if (!this.children) {
      this.children = [];
    }
    this.children.push(child);
    return child;
  }
  find(data) {
    if (data === this.data) {
      return this;
    }
    if (this.children) {
      for (let i = 0, { length } = this.children, target = null; i < length; i++) {
        target = this.children[i].find(data);
        if (target) {
          return target;
        }
      }
    }
    return null;
  }
  leaves() {
    if (!this.children || this.children.length === 0) {
      return [this];
    }
    const leaves = [];
    if (this.children) {
      for (let i = 0, { length } = this.children; i < length; i++) {
        leaves.push.apply(leaves, this.children[i].leaves());
      }
    }
    return leaves;
  }
  root() {
    if (!this.parent) {
      return this;
    }
    return this.parent.root();
  }
  forEach(callback) {
    if (typeof callback !== "function") {
      throw new TypeError("forEach() callback must be a function");
    }
    callback(this);
    if (this.children) {
      for (let i = 0, { length } = this.children; i < length; i++) {
        this.children[i].forEach(callback);
      }
    }
    return this;
  }
  static build(path, options = {}) {
    const filteredTree = dirTree(path, { extensions: options?.extensions, exclude: options.exclude });
    if (!filteredTree) {
      return;
    }
    const treeNode = new TreeNode({ name: filteredTree.name, path: filteredTree.path, type: filteredTree.type });
    const recurse = (node, item) => {
      const subNode = node.addChild({ name: item.name, path: item.path, type: item.type });
      if (item.children?.length) {
        item.children?.forEach((child) => {
          recurse(subNode, child);
        });
      }
    };
    filteredTree.children?.forEach((child) => recurse(treeNode, child));
    return treeNode;
  }
};

// src/managers/pluginManager/PluginManager.ts
var hookNames = {
  validate: 1,
  buildStart: 1,
  resolveId: 1,
  load: 1,
  transform: 1,
  writeFile: 1,
  buildEnd: 1
};
var hooks = Object.keys(hookNames);
var PluginManager = class {
  plugins;
  fileManager;
  logger;
  config;
  core;
  constructor(config, options) {
    this.logger = options.logger;
    this.config = config;
    this.fileManager = new FileManager();
    this.core = definePlugin({
      config,
      fileManager: this.fileManager,
      load: this.load,
      resolveId: this.resolveId
    });
    this.plugins = [this.core, ...config.plugins || []];
  }
  resolveId = (params) => {
    if (params.pluginName) {
      return this.hookForPlugin(params.pluginName, "resolveId", [params.fileName, params.directory, params.options]);
    }
    return this.hookFirst("resolveId", [params.fileName, params.directory, params.options]);
  };
  load = async (id) => {
    return this.hookFirst("load", [id]);
  };
  hookForPlugin(pluginName, hookName, parameters, skipped) {
    let promise = Promise.resolve(null);
    for (const plugin of this.getSortedPlugins(hookName, pluginName)) {
      if (skipped && skipped.has(plugin))
        continue;
      promise = promise.then((result) => {
        if (result != null)
          return result;
        return this.run("hookFirst", hookName, parameters, plugin);
      });
    }
    return promise;
  }
  hookFirst(hookName, parameters, skipped) {
    let promise = Promise.resolve(null);
    for (const plugin of this.getSortedPlugins(hookName)) {
      if (skipped && skipped.has(plugin))
        continue;
      promise = promise.then((result) => {
        if (result != null)
          return result;
        return this.run("hookFirst", hookName, parameters, plugin);
      });
    }
    return promise;
  }
  async hookParallel(hookName, parameters) {
    const parallelPromises = [];
    for (const plugin of this.getSortedPlugins(hookName)) {
      if (plugin[hookName]?.sequential) {
        await Promise.all(parallelPromises);
        parallelPromises.length = 0;
        await this.run("hookParallel", hookName, parameters, plugin);
      } else {
        const promise = this.run("hookParallel", hookName, parameters, plugin);
        parallelPromises.push(promise);
      }
    }
    return Promise.all(parallelPromises);
  }
  hookReduceArg0(hookName, [argument0, ...rest], reduce) {
    let promise = Promise.resolve(argument0);
    for (const plugin of this.getSortedPlugins(hookName)) {
      promise = promise.then(
        (argument02) => this.run("hookReduceArg0", hookName, [argument02, ...rest], plugin).then(
          (result) => reduce.call(this.core.api, argument02, result, plugin)
        )
      );
    }
    return promise;
  }
  hookSeq(hookName, parameters) {
    let promise = Promise.resolve();
    for (const plugin of this.getSortedPlugins(hookName)) {
      promise = promise.then(() => this.run("hookSeq", hookName, parameters, plugin));
    }
    return promise.then(noReturn);
  }
  getSortedPlugins(hookName, pluginName) {
    const plugins = [...this.plugins];
    if (pluginName) {
      const pluginsByPluginName = plugins.filter((item) => item.name === pluginName && item[hookName]);
      if (pluginsByPluginName.length === 0) {
        if (this.config.logLevel === "warn" && this.logger?.spinner) {
          this.logger.spinner.info(`Plugin hook with ${hookName} not found for plugin ${pluginName}`);
        }
        return [this.core];
      }
      return pluginsByPluginName;
    }
    return plugins;
  }
  run(strategy, hookName, parameters, plugin) {
    const hook = plugin[hookName];
    return Promise.resolve().then(() => {
      if (typeof hook !== "function") {
        return hook;
      }
      if (this.config.logLevel === "info" && this.logger?.spinner) {
        this.logger.spinner.text = `[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} 
`;
      }
      const hookResult = hook.apply(this.core.api, parameters);
      if (!hookResult?.then) {
        if (this.config.logLevel === "info" && this.logger?.spinner) {
          this.logger.spinner.succeed(`[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} 
`);
        }
        return hookResult;
      }
      return Promise.resolve(hookResult).then((result) => {
        if (this.config.logLevel === "info" && this.logger?.spinner) {
          this.logger.spinner.succeed(`[${strategy}] ${hookName}: Excecuting task for plugin ${plugin.name} 
`);
        }
        return result;
      });
    }).catch((e) => this.catcher(e, plugin, hookName));
  }
  runSync(hookName, parameters, plugin) {
    const hook = plugin[hookName];
    try {
      return hook.apply(this.core.api, parameters);
    } catch (error) {
      return error;
    }
  }
  catcher(e, plugin, hookName) {
    const text = `${e.message} (plugin: ${plugin.name}, hook: ${hookName})
`;
    if (this.logger?.spinner) {
      this.logger.spinner.fail(text);
      throw e;
    }
  }
};
function noReturn() {
}

// src/managers/pluginManager/validate.ts
init_cjs_shims();
var ValidationPluginError = class extends Error {
};
var validatePlugins = (plugins, dependedPluginNames) => {
  let pluginNames = [];
  if (typeof dependedPluginNames === "string") {
    pluginNames = [dependedPluginNames];
  } else {
    pluginNames = dependedPluginNames;
  }
  pluginNames.forEach((pluginName) => {
    const exists = plugins.some((plugin) => plugin.name === pluginName);
    if (!exists) {
      throw new ValidationPluginError(`This plugin depends on the ${pluginName} plugin.`);
    }
  });
  return true;
};

// src/build.ts
async function transformReducer(_previousCode, result, _plugin) {
  if (result === null) {
    return null;
  }
  return result;
}
async function buildImplementation(options, done) {
  const { config, logger } = options;
  if (config.output.clean) {
    await clean(config.output.path);
  }
  const pluginManager = new PluginManager(config, { logger });
  const { plugins, fileManager } = pluginManager;
  try {
    await pluginManager.hookParallel("validate", [plugins]);
  } catch (e) {
    return;
  }
  fileManager.events.onSuccess(async () => {
    await pluginManager.hookParallel("buildEnd");
    setTimeout(() => {
      done({ fileManager });
    }, 1e3);
  });
  fileManager.events.onAdd(async (id, file) => {
    const { path } = file;
    let { source: code } = file;
    const loadedResult = await pluginManager.hookFirst("load", [path]);
    if (loadedResult) {
      code = loadedResult;
    }
    if (code) {
      const transformedCode = await pluginManager.hookReduceArg0("transform", [code, path], transformReducer);
      if (typeof config.input === "object") {
        await pluginManager.hookParallel("writeFile", [transformedCode, path]);
      }
      fileManager.setStatus(id, "success");
      fileManager.remove(id);
    }
  });
  await pluginManager.hookParallel("buildStart", [config]);
}
function build(options) {
  return new Promise((resolve, reject) => {
    try {
      buildImplementation(options, resolve);
    } catch (e) {
      reject(e);
    }
  });
}

// src/config.ts
init_cjs_shims();
var defineConfig = (options) => options;

// src/generators/SchemaGenerator.ts
init_cjs_shims();

// src/generators/Generator.ts
init_cjs_shims();
var Generator = class {
  _options = {};
  constructor(options = {}) {
    if (options) {
      this._options = {
        ...this._options,
        ...options
      };
    }
    return this;
  }
  get options() {
    return this._options;
  }
};

// src/generators/SchemaGenerator.ts
var SchemaGenerator = class extends Generator {
};

// src/index.ts
var src_default = build;

exports.FileManager = FileManager;
exports.Generator = Generator;
exports.PluginManager = PluginManager;
exports.SchemaGenerator = SchemaGenerator;
exports.TreeNode = TreeNode;
exports.ValidationPluginError = ValidationPluginError;
exports.build = build;
exports.clean = clean;
exports.createPlugin = createPlugin;
exports.createPluginCache = createPluginCache;
exports.default = src_default;
exports.defineConfig = defineConfig;
exports.format = format;
exports.getPathMode = getPathMode;
exports.getRelativePath = getRelativePath;
exports.hooks = hooks;
exports.isPromise = isPromise;
exports.read = read;
exports.validatePlugins = validatePlugins;
exports.write = write;
//# sourceMappingURL=out.js.map
//# sourceMappingURL=index.js.map