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 __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : 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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __decoratorStart = (base) => [, , , __create((base == null ? void 0 : 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);
var cloud_libraries_service_exports = {};
__export(cloud_libraries_service_exports, {
  CloudLibrariesService: () => CloudLibrariesService
});
module.exports = __toCommonJS(cloud_libraries_service_exports);
var import_node_vm = require("node:vm");
var import_server = require("@tego/server");
var babelParser = __toESM(require("@babel/parser"));
var import_traverse = __toESM(require("@babel/traverse"));
var import_topo = __toESM(require("@hapi/topo"));
var import_module_mapping = require("../config/module-mapping");
var import_cloud_compiler = require("./cloud-compiler");
var import_remote_code_fetcher = require("./remote-code-fetcher");
var _remoteCodeFetcher_dec, _compiler_dec, _logger_dec, _app_dec, _db_dec, _CloudLibrariesService_decorators, _init;
_CloudLibrariesService_decorators = [(0, import_server.Service)()], _db_dec = [(0, import_server.Db)()], _app_dec = [(0, import_server.App)()], _logger_dec = [(0, import_server.InjectLog)()], _compiler_dec = [(0, import_server.Inject)(() => import_cloud_compiler.CloudCompiler)], _remoteCodeFetcher_dec = [(0, import_server.Inject)(() => import_remote_code_fetcher.RemoteCodeFetcher)];
class CloudLibrariesService {
  constructor() {
    this.db = __runInitializers(_init, 8, this), __runInitializers(_init, 11, this);
    this.app = __runInitializers(_init, 12, this), __runInitializers(_init, 15, this);
    this.logger = __runInitializers(_init, 16, this), __runInitializers(_init, 19, this);
    this.compiler = __runInitializers(_init, 20, this), __runInitializers(_init, 23, this);
    this.remoteCodeFetcher = __runInitializers(_init, 24, this), __runInitializers(_init, 27, this);
  }
  async compileLibraries() {
    const libRepo = this.app.db.getRepository("cloudLibraries");
    const libs = await libRepo.find({
      filter: {
        enabled: true
      }
    });
    const repo = this.app.db.getRepository("effectLibraries");
    for (const lib of libs) {
      const {
        name,
        code: debugCode,
        codeSource = "local",
        codeType,
        codeUrl,
        codeBranch = "main",
        codePath,
        codeCache,
        module: module2,
        isClient,
        isServer,
        serverPlugin,
        clientPlugin,
        enabled,
        version,
        component,
        versions
      } = lib;
      let code;
      if (codeSource === "remote" && codeUrl && codeType) {
        try {
          if (codeCache == null ? void 0 : codeCache.content) {
            this.logger.info(`[${module2}] Using cached remote code from database`);
            code = codeCache.content;
          } else {
            const { codeAuthType, codeAuthToken, codeAuthUsername } = lib;
            this.logger.info(
              `[${module2}] No cache found, fetching remote code from ${codeUrl} (type: ${codeType}, branch: ${codeBranch || "main"})`
            );
            this.logger.info(
              `[${module2}] Auth config: type=${codeAuthType || "none"}, hasToken=${!!codeAuthToken}, hasUsername=${!!codeAuthUsername}`
            );
            code = await this.remoteCodeFetcher.fetchCode(
              codeUrl,
              codeType,
              codeBranch,
              codePath,
              codeAuthType,
              codeAuthToken,
              codeAuthUsername
            );
            const libRepo2 = this.app.db.getRepository("cloudLibraries");
            await libRepo2.update({
              filterByTk: lib.id,
              values: {
                codeCache: {
                  content: code,
                  timestamp: Date.now()
                  // 保留 timestamp 用于记录，但不用于验证
                }
              }
            });
            this.logger.info(`[${module2}] Remote code fetched and cached successfully`);
          }
        } catch (error) {
          this.logger.error(`[${module2}] Failed to fetch remote code`, {
            error: error instanceof Error ? error.message : String(error)
          });
          if (codeCache == null ? void 0 : codeCache.content) {
            this.logger.warn(`[${module2}] Remote fetch failed, using cached code as fallback`);
            code = codeCache.content;
          } else {
            this.logger.warn(`[${module2}] Remote code fetch failed, falling back to local code`);
            code = debugCode;
            if (version && version !== "debug") {
              code = versions[Number[version]].code;
            }
          }
        }
      } else {
        code = debugCode;
        if (version && version !== "debug") {
          code = versions[Number[version]].code;
        }
        this.logger.debug(`[${module2}] Using local code (source: ${codeSource || "local"})`);
      }
      const clientCode = this.compiler.toAmd(code);
      const serverCode = this.compiler.toCjs(code);
      repo.updateOrCreate({
        filterKeys: ["module"],
        values: {
          name,
          module: module2,
          enabled,
          server: serverCode,
          client: clientCode,
          isClient,
          isServer,
          serverPlugin,
          clientPlugin,
          component
        }
      });
    }
  }
  async loadServerLibraries() {
    this.logger.info(`load cloudLibrarie: start`);
    const repo = this.app.db.getRepository("effectLibraries");
    const cloudLibraries = await repo.find({
      filter: {
        enabled: true,
        isServer: true
      }
    });
    const sorter = new import_topo.default.Sorter();
    for (const cloudLibrary of cloudLibraries) {
      const ast = babelParser.parse(cloudLibrary.server, {
        sourceType: "script"
        // CommonJS 使用 script 模式
      });
      const dependencies = [];
      (0, import_traverse.default)(ast, {
        CallExpression(path) {
          const callee = path.get("callee");
          if (callee.isIdentifier({ name: "require" })) {
            const args = path.get("arguments");
            if (args.length > 0 && args[0].isStringLiteral()) {
              dependencies.push(args[0].node.value);
            }
          }
        }
      });
      sorter.add(cloudLibrary, {
        after: dependencies,
        group: cloudLibrary.module
      });
    }
    const EXECUTION_TIMEOUT = 3e4;
    for (const cloudLibrary of sorter.nodes) {
      this.logger.info(`Loading cloud library: ${cloudLibrary.module}`);
      const compiledCode = cloudLibrary.server;
      try {
        const script = new import_node_vm.Script(compiledCode);
        const defaultFunction = async (event, context) => {
          return {};
        };
        const that = this;
        const moduleMappings = (0, import_module_mapping.getModuleMappings)();
        const contextRequire = function(moduleName) {
          if (that.app.modules[moduleName]) {
            return that.app.modules[moduleName];
          }
          const resolvedModuleName = (0, import_module_mapping.resolveModuleName)(moduleName, moduleMappings);
          try {
            return require.call(this, resolvedModuleName);
          } catch (error) {
            if (resolvedModuleName !== moduleName) {
              try {
                return require.call(this, moduleName);
              } catch (originalError) {
                that.logger.warn(`Module not found: ${moduleName} (mapped to ${resolvedModuleName})`, {
                  module: cloudLibrary.module,
                  originalError: originalError instanceof Error ? originalError.message : String(originalError),
                  mappedError: error instanceof Error ? error.message : String(error)
                });
                return {};
              }
            } else {
              that.logger.warn(`Module not found: ${moduleName}`, {
                module: cloudLibrary.module,
                meta: error instanceof Error ? error.message : String(error)
              });
              return {};
            }
          }
        };
        Object.assign(contextRequire, require);
        const safeConsole = {
          log: console.log.bind(console),
          info: console.info.bind(console),
          warn: console.warn.bind(console),
          error: console.error.bind(console)
          // 禁止使用 console.clear 和 console.trace 等可能影响调试的操作
        };
        const sandbox = {
          module: {},
          exports: { default: defaultFunction },
          require: contextRequire,
          console: safeConsole,
          // 禁止访问全局对象
          global: void 0,
          process: void 0,
          Buffer: void 0,
          // 禁止使用 eval 和 Function 构造函数
          eval: void 0,
          Function: void 0
        };
        (0, import_node_vm.createContext)(sandbox);
        const startTime = Date.now();
        script.runInContext(sandbox);
        const executionTime = Date.now() - startTime;
        if (executionTime > EXECUTION_TIMEOUT) {
          this.logger.warn(
            `Cloud library ${cloudLibrary.module} execution took ${executionTime}ms, exceeding timeout threshold`
          );
        } else {
          this.logger.debug(`Cloud library ${cloudLibrary.module} executed in ${executionTime}ms`);
        }
        this.app.modules[cloudLibrary.module] = sandbox.exports;
        this.logger.info(`Successfully loaded cloud library: ${cloudLibrary.module}`);
      } catch (error) {
        this.logger.error(`Failed to load cloud library: ${cloudLibrary.module}`, {
          error: error instanceof Error ? error.message : String(error),
          stack: error instanceof Error ? error.stack : void 0
        });
      }
    }
  }
  async load() {
    this.app.acl.allow("effectLibraries", "list", "public");
    this.app.on("afterStart", async () => {
      await this.compileLibraries();
      await this.loadServerLibraries();
    });
    this.app.acl.addFixedParams("cloudLibraries", "destroy", () => {
      return {
        filter: {
          enabled: false
        }
      };
    });
    this.app.acl.registerSnippet({
      name: "pm.business-components.cloud-component",
      actions: ["cloudLibraries:*"]
    });
  }
}
_init = __decoratorStart(null);
__decorateElement(_init, 5, "db", _db_dec, CloudLibrariesService);
__decorateElement(_init, 5, "app", _app_dec, CloudLibrariesService);
__decorateElement(_init, 5, "logger", _logger_dec, CloudLibrariesService);
__decorateElement(_init, 5, "compiler", _compiler_dec, CloudLibrariesService);
__decorateElement(_init, 5, "remoteCodeFetcher", _remoteCodeFetcher_dec, CloudLibrariesService);
CloudLibrariesService = __decorateElement(_init, 0, "CloudLibrariesService", _CloudLibrariesService_decorators, CloudLibrariesService);
__runInitializers(_init, 1, CloudLibrariesService);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  CloudLibrariesService
});
