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 __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 script_instruction_exports = {};
__export(script_instruction_exports, {
  ScriptInstruction: () => ScriptInstruction
});
module.exports = __toCommonJS(script_instruction_exports);
var import_node_crypto = __toESM(require("node:crypto"));
var import_node_vm = require("node:vm");
var import_core = require("@babel/core");
var import_dayjs = __toESM(require("dayjs"));
var import_jsonata = __toESM(require("jsonata"));
var import_lodash = __toESM(require("lodash"));
var import_qrcode = __toESM(require("qrcode"));
var import__ = require("../..");
var import_get_remote_code_fetcher = require("../../utils/get-remote-code-fetcher");
class ScriptInstruction extends import__.Instruction {
  async run(node, input, processor) {
    const {
      sourceArray,
      type,
      code = "",
      model,
      codeSource = "local",
      codeType,
      codeUrl,
      codeBranch = "main",
      codeAuthType,
      codeAuthToken,
      codeAuthUsername
    } = node.config;
    let actualCode = code;
    if (codeSource === "remote" && codeUrl && codeType) {
      try {
        const app = processor.options.plugin.app;
        const remoteCodeFetcher = (0, import_get_remote_code_fetcher.getRemoteCodeFetcher)(app);
        if (remoteCodeFetcher) {
          const codeCache = node.config.codeCache;
          if (codeCache == null ? void 0 : codeCache.content) {
            app.logger.info(`[Workflow Node ${node.id}] Using cached remote code from database`);
            actualCode = codeCache.content;
          } else {
            app.logger.info(
              `[Workflow Node ${node.id}] No cache found, fetching remote code from ${codeUrl} (type: ${codeType}, branch: ${codeBranch || "main"})`
            );
            actualCode = await remoteCodeFetcher.fetchCode(
              codeUrl,
              codeType,
              codeBranch || "main",
              // 使用配置的分支，默认为 'main'
              void 0,
              // codePath - 使用默认值
              codeAuthType,
              codeAuthToken,
              codeAuthUsername
            );
            const nodeRepo = app.db.getRepository("flow_nodes");
            await nodeRepo.update({
              filterByTk: node.id,
              values: {
                config: {
                  ...node.config,
                  codeCache: {
                    content: actualCode,
                    timestamp: Date.now()
                    // 保留 timestamp 用于记录，但不用于验证
                  }
                }
              }
            });
            app.logger.info(`[Workflow Node ${node.id}] Remote code fetched and cached successfully`);
          }
        } else {
          const codeCache = node.config.codeCache;
          if (codeCache == null ? void 0 : codeCache.content) {
            app.logger.info(`[Workflow Node ${node.id}] Using cached remote code from database (fallback mode)`);
            actualCode = codeCache.content;
          } else {
            const http = require("node:http");
            const https = require("node:https");
            const { URL } = require("node:url");
            const urlObj = new URL(codeUrl);
            const client = urlObj.protocol === "https:" ? https : http;
            app.logger.info(
              `[Workflow Node ${node.id}] No cache found, fetching remote code via HTTP (type: ${codeType}, branch: ${codeBranch || "main"})`
            );
            actualCode = await new Promise((resolve, reject) => {
              const headers = {
                "User-Agent": "TegoWorkflow/1.0"
              };
              if (codeAuthType === "token" && codeAuthToken) {
                headers["Authorization"] = `Bearer ${codeAuthToken}`;
              } else if (codeAuthType === "basic" && codeAuthUsername && codeAuthToken) {
                const credentials = Buffer.from(`${codeAuthUsername}:${codeAuthToken}`).toString("base64");
                headers["Authorization"] = `Basic ${credentials}`;
              }
              const request = client.get(
                {
                  hostname: urlObj.hostname,
                  port: urlObj.port || (urlObj.protocol === "https:" ? 443 : 80),
                  path: urlObj.pathname + urlObj.search,
                  headers,
                  timeout: 1e4
                },
                (res) => {
                  if (res.statusCode !== 200) {
                    reject(new Error(`Failed to fetch: HTTP ${res.statusCode}`));
                    return;
                  }
                  let data2 = "";
                  res.on("data", (chunk) => {
                    data2 += chunk;
                  });
                  res.on("end", () => {
                    resolve(data2);
                  });
                }
              );
              request.on("error", reject);
              request.on("timeout", () => {
                request.destroy();
                reject(new Error("Request timeout"));
              });
            });
            const nodeRepo = app.db.getRepository("flow_nodes");
            await nodeRepo.update({
              filterByTk: node.id,
              values: {
                config: {
                  ...node.config,
                  codeCache: {
                    content: actualCode,
                    timestamp: Date.now()
                    // 保留 timestamp 用于记录，但不用于验证
                  }
                }
              }
            });
            app.logger.info(`[Workflow Node ${node.id}] Remote code fetched and cached successfully (fallback mode)`);
          }
        }
      } catch (error) {
        const app = processor.options.plugin.app;
        app.logger.error("Failed to fetch remote code for script node", {
          error: error instanceof Error ? error.message : String(error),
          nodeId: node.id,
          codeUrl
        });
        const codeCache = node.config.codeCache;
        if (codeCache == null ? void 0 : codeCache.content) {
          app.logger.warn(`[Workflow Node ${node.id}] Remote fetch failed, using cached code as fallback`);
          actualCode = codeCache.content;
        } else if (!code) {
          throw new Error(`Failed to fetch remote code: ${error instanceof Error ? error.message : String(error)}`);
        } else {
          app.logger.warn(`[Workflow Node ${node.id}] Remote code fetch failed, falling back to local code`);
          actualCode = code;
        }
      }
    }
    let data = {};
    switch (sourceArray.length) {
      case 0: {
        data = {};
        break;
      }
      case 1: {
        const keyName = sourceArray[0]["keyName"];
        const sourcePath = sourceArray[0]["sourcePath"];
        const rawData = processor.getParsedValue(sourcePath, node.id);
        if (keyName) {
          data = {
            [keyName]: rawData
          };
        } else {
          data = rawData;
        }
        break;
      }
      default: {
        data = sourceArray.reduce(
          (cookedData, { keyName, sourcePath }) => ({
            ...cookedData,
            [keyName]: processor.getParsedValue(sourcePath, node.id)
          }),
          {}
        );
      }
    }
    try {
      let result = {};
      switch (type) {
        case "jsonata":
          result = await convertByJSONata(actualCode, data);
          break;
        case "js":
          result = await convertByJsCode(actualCode, data);
          break;
        case "ts":
          result = await convertByTsCode(actualCode, data, processor);
          break;
        default:
      }
      if (typeof result === "object" && result && (model == null ? void 0 : model.length)) {
        if (Array.isArray(result)) {
          result = result.map((item) => mapModel(item, model));
        } else {
          result = mapModel(result, model);
        }
      }
      return {
        result,
        status: import__.JOB_STATUS.RESOLVED
      };
    } catch (err) {
      return {
        result: err.toString(),
        status: import__.JOB_STATUS.ERROR
      };
    }
  }
}
async function convertByJSONata(code, data) {
  const engine = (expression, data2) => (0, import_jsonata.default)(expression).evaluate(data2);
  const result = await engine(code, data);
  return result;
}
async function convertByJsCode(code, data) {
  const ctx = {
    data,
    body: {}
  };
  await evalSimulate(code, {
    ctx,
    lib: {
      log: console.log,
      JSON,
      qrcode: import_qrcode.default,
      crypto: import_node_crypto.default,
      jsonata: import_jsonata.default,
      dayjs: import_dayjs.default
    }
  });
  return ctx.body;
}
async function convertByTsCode(code, data, processor) {
  const options = processor.options;
  const app = processor.options.plugin.app;
  const compiledCode = (0, import_core.transform)(code, {
    sourceType: "module",
    filename: "a.tsx",
    presets: [
      [
        require("@babel/preset-env"),
        {
          modules: "commonjs",
          targets: {
            node: "current"
          }
        }
      ],
      require("@babel/preset-react"),
      require("@babel/preset-typescript")
    ]
  }).code;
  const script = new import_node_vm.Script(compiledCode);
  const defaultFunction = async (event, context) => {
    return {};
  };
  const contextRequire = function(moduleName) {
    if (moduleName === "@tachybase/utils/client") {
      return require.call(this, "@tachybase/utils");
    }
    if (moduleName === "@tachybase/module-pdf/client") {
      return require.call(this, "@tachybase/module-pdf");
    }
    if (moduleName === "@react-pdf/renderer") {
      return require.call(this, "@tachybase/module-pdf");
    }
    if (app.modules[moduleName]) {
      return app.modules[moduleName];
    }
    return require.call(this, moduleName);
  };
  Object.assign(contextRequire, require);
  const sandbox = {
    module: {},
    exports: { default: defaultFunction },
    require: contextRequire,
    console
  };
  (0, import_node_vm.createContext)(sandbox);
  try {
    script.runInContext(sandbox);
  } catch (error) {
    app.logger.error("Cloud Component ", { error });
  }
  const func = sandbox.exports.default;
  const result = await func(data || {}, {
    ...options
  });
  return result;
}
function mapModel(data, model) {
  if (typeof data !== "object" || data === null) {
    throw new Error("Invalid data: data should be a non-null object");
  }
  const result = model.reduce((acc, { path, alias }) => {
    const key = alias ?? path.replace(/\./g, "_");
    const value = import_lodash.default.get(data, path);
    acc[key] = value;
    return acc;
  }, {});
  return result;
}
async function evalSimulate(jsCode, { ctx, lib }) {
  const AsyncFunction = async function() {
  }.constructor;
  return await new AsyncFunction("$root", `with($root) { ${jsCode}; }`)({
    ctx,
    // 允许用户覆盖，这个时候可以使用 _ctx
    __ctx: ctx,
    lib
  });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  ScriptInstruction
});
