/**
 * This file is part of the NocoBase (R) project.
 * Copyright (c) 2020-2024 NocoBase Co., Ltd.
 * Authors: NocoBase Team.
 *
 * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
 * For more information, please refer to: https://www.nocobase.com/agreement.
 */

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 document_loader_exports = {};
__export(document_loader_exports, {
  KimiDocumentLoader: () => KimiDocumentLoader
});
module.exports = __toCommonJS(document_loader_exports);
var import_promises = __toESM(require("node:fs/promises"));
var import_node_fs = require("node:fs");
var import_node_os = __toESM(require("node:os"));
var import_node_path = __toESM(require("node:path"));
var import_promises2 = require("node:stream/promises");
var import_documents = require("@langchain/core/documents");
var import_openai = require("@langchain/openai");
var import_utils = require("../../document-loader/utils");
class KimiDocumentLoader {
  constructor(fileManager, options) {
    this.fileManager = fileManager;
    this.options = options;
    this.client = this.createClient();
  }
  client;
  async load(file) {
    const text = await this.parseByApi(file);
    if (!text) {
      return [];
    }
    return [
      new import_documents.Document({
        pageContent: text,
        metadata: {
          source: file.filename,
          extname: (0, import_utils.resolveExtname)(file)
        }
      })
    ];
  }
  async parseByApi(sourceFile) {
    let uploadedFileId = "";
    const safeFilename = import_node_path.default.basename(sourceFile.filename || "document");
    const tempFilePath = import_node_path.default.join(import_node_os.default.tmpdir(), `${sourceFile.id ?? Date.now()}.${Date.now()}.${safeFilename}`);
    try {
      const { stream } = await this.fileManager.getFileStream(sourceFile);
      await (0, import_promises2.pipeline)(stream, (0, import_node_fs.createWriteStream)(tempFilePath));
      let uploaded;
      try {
        uploaded = await this.client.files.create({
          file: (0, import_node_fs.createReadStream)(tempFilePath),
          // @ts-ignore
          purpose: "file-extract"
        });
      } catch (error) {
        throw new Error(this.formatApiError(error, sourceFile, "upload"));
      }
      uploadedFileId = uploaded == null ? void 0 : uploaded.id;
      if (!uploadedFileId) {
        throw new Error("Kimi files.create response missing id");
      }
      let parsedResponse;
      try {
        parsedResponse = await this.client.files.content(uploadedFileId);
      } catch (error) {
        throw new Error(this.formatApiError(error, sourceFile, "extract"));
      }
      if (typeof (parsedResponse == null ? void 0 : parsedResponse.text) === "function") {
        return await parsedResponse.text();
      }
      return typeof parsedResponse === "string" ? parsedResponse : String(parsedResponse ?? "");
    } finally {
      await import_promises.default.rm(tempFilePath, { force: true });
      if (uploadedFileId) {
        await this.deleteRemoteFile(uploadedFileId);
      }
    }
  }
  async deleteRemoteFile(fileId) {
    try {
      await this.client.files.delete(fileId);
    } catch (error) {
    }
  }
  formatApiError(error, sourceFile, stage) {
    var _a, _b, _c, _d, _e, _f;
    const stageLabel = stage === "upload" ? "file upload" : "file extraction";
    const message = ((_a = error == null ? void 0 : error.error) == null ? void 0 : _a.message) ?? ((_d = (_c = (_b = error == null ? void 0 : error.response) == null ? void 0 : _b.data) == null ? void 0 : _c.error) == null ? void 0 : _d.message) ?? ((_f = (_e = error == null ? void 0 : error.response) == null ? void 0 : _e.data) == null ? void 0 : _f.message) ?? (error == null ? void 0 : error.message) ?? String(error);
    return `Kimi ${stageLabel} failed for "${sourceFile.filename}": ${message}`;
  }
  createClient() {
    const apiKey = this.options.apiKey;
    if (!apiKey) {
      throw new Error("Kimi provider apiKey is required for file parsing");
    }
    return new import_openai.OpenAIClient({
      apiKey,
      baseURL: this.options.baseURL ?? "https://api.moonshot.cn/v1"
    });
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  KimiDocumentLoader
});
