'use strict';

var chunkKH6RQ4J5_js = require('./chunk-KH6RQ4J5.js');
var chunk6PRFP5EG_js = require('./chunk-6PRFP5EG.js');
var OSS = require('ali-oss');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var OSS__default = /*#__PURE__*/_interopDefault(OSS);

var logger = chunk6PRFP5EG_js.createLogger("AliyunOSSProvider");
var AliyunOSSProvider = class {
  constructor() {
    this.type = "aliyun-oss";
    this.config = null;
    this.client = null;
    this.isInitialized = false;
  }
  /**
   * 初始化存储提供者
   */
  async initialize(config) {
    return this.reinitialize(config);
  }
  /**
   * 重新初始化存储提供者（支持配置热更新）
   */
  async reinitialize(config) {
    if (config.type !== "aliyun-oss") {
      throw new chunkKH6RQ4J5_js.StorageProviderError("\u914D\u7F6E\u7C7B\u578B\u4E0D\u5339\u914D\uFF1A\u671F\u671B aliyun-oss");
    }
    const newConfig = config;
    const configChanged = !this.config || this.config.region !== newConfig.region || this.config.bucket !== newConfig.bucket || this.config.accessKeyId !== newConfig.accessKeyId || this.config.accessKeySecret !== newConfig.accessKeySecret || this.config.customDomain !== newConfig.customDomain || this.config.secure !== newConfig.secure || this.config.internal !== newConfig.internal;
    if (configChanged) {
      logger.info("\u{1F504} [AliyunOSSProvider] \u68C0\u6D4B\u5230\u914D\u7F6E\u53D8\u5316\uFF0C\u91CD\u65B0\u521D\u59CB\u5316OSS\u5BA2\u6237\u7AEF");
      logger.info(
        `\u2601\uFE0F [AliyunOSSProvider] \u65B0\u914D\u7F6E: bucket=${newConfig.bucket}, region=${newConfig.region}`
      );
    } else if (this.isInitialized) {
      logger.info("\u2139\uFE0F [AliyunOSSProvider] \u914D\u7F6E\u672A\u53D8\u5316\uFF0C\u8DF3\u8FC7\u91CD\u65B0\u521D\u59CB\u5316");
      return;
    }
    this.config = newConfig;
    logger.info(`\u2601\uFE0F [AliyunOSSProvider] ${this.isInitialized ? "\u91CD\u65B0" : ""}\u521D\u59CB\u5316\u963F\u91CC\u4E91OSS`);
    try {
      this.validateConfig();
      this.client = new OSS__default.default({
        region: this.config.region,
        bucket: this.config.bucket,
        accessKeyId: this.config.accessKeyId,
        accessKeySecret: this.config.accessKeySecret,
        secure: this.config.secure !== false,
        // 默认使用HTTPS
        internal: this.config.internal || false,
        // 默认使用公网
        timeout: 3e5,
        // 5分钟超时
        cname: !!this.config.customDomain,
        // 是否使用自定义域名
        endpoint: this.config.customDomain || void 0
      });
      await this.testConnection();
      this.isInitialized = true;
      logger.info(`\u2705 [AliyunOSSProvider] \u963F\u91CC\u4E91OSS${configChanged ? "\u91CD\u65B0" : ""}\u521D\u59CB\u5316\u5B8C\u6210`);
    } catch (error) {
      logger.error("\u274C [AliyunOSSProvider] \u963F\u91CC\u4E91OSS\u521D\u59CB\u5316\u5931\u8D25:", error);
      throw new chunkKH6RQ4J5_js.StorageProviderError(
        `\u963F\u91CC\u4E91OSS\u521D\u59CB\u5316\u5931\u8D25: ${error instanceof Error ? error.message : "\u672A\u77E5\u9519\u8BEF"}`
      );
    }
  }
  /**
   * 上传文件
   */
  async upload(fileInfo, filePath) {
    this.ensureInitialized();
    const startTime = Date.now();
    logger.info(`\u{1F4E4} [AliyunOSSProvider] \u5F00\u59CB\u4E0A\u4F20\u6587\u4EF6\u5230OSS: ${filePath}`);
    try {
      const buffer = Buffer.from(await fileInfo.file.arrayBuffer());
      const options = {
        headers: {
          "Content-Type": fileInfo.file.type || "application/octet-stream",
          "Content-Length": fileInfo.file.size.toString()
        },
        meta: {
          uid: 0,
          // 必需字段
          pid: 0,
          // 必需字段
          originalName: encodeURIComponent(fileInfo.file.name),
          moduleId: fileInfo.moduleId,
          businessId: fileInfo.businessId || "",
          uploadTime: (/* @__PURE__ */ new Date()).toISOString(),
          // 对元数据进行编码处理，避免中文字符问题
          ...this.encodeMetadata(fileInfo.metadata || {})
        }
      };
      let result;
      if (fileInfo.file.size > 100 * 1024 * 1024) {
        logger.info(
          `\u{1F4E6} [AliyunOSSProvider] \u4F7F\u7528\u5206\u7247\u4E0A\u4F20\u5927\u6587\u4EF6: ${filePath}, \u5927\u5C0F: ${fileInfo.file.size}`
        );
        result = await this.multipartUpload(filePath, buffer, options);
      } else {
        logger.info(
          `\u{1F4E4} [AliyunOSSProvider] \u4F7F\u7528\u666E\u901A\u4E0A\u4F20: ${filePath}, \u5927\u5C0F: ${fileInfo.file.size}`
        );
        result = await this.client.put(filePath, buffer, options);
      }
      const accessUrl = this.generateAccessUrl(filePath);
      const uploadTime = Date.now() - startTime;
      logger.info(`\u2705 [AliyunOSSProvider] \u6587\u4EF6\u4E0A\u4F20\u5B8C\u6210: ${filePath}, \u8017\u65F6: ${uploadTime}ms`);
      return {
        success: true,
        path: filePath,
        url: accessUrl,
        size: fileInfo.file.size,
        data: {
          etag: result.data ? JSON.stringify(result.data) : "",
          requestId: result.res?.rt || 0,
          uploadTime,
          ossUrl: result.url || result.name
        }
      };
    } catch (error) {
      logger.error(`\u274C [AliyunOSSProvider] \u6587\u4EF6\u4E0A\u4F20\u5931\u8D25: ${filePath}:`, error);
      return {
        success: false,
        error: this.formatOSSError(error)
      };
    }
  }
  /**
   * 下载文件
   */
  async download(filePath) {
    this.ensureInitialized();
    logger.info(`\u{1F4E5} [AliyunOSSProvider] \u5F00\u59CB\u4ECEOSS\u4E0B\u8F7D\u6587\u4EF6: ${filePath}`);
    try {
      const result = await this.client.get(filePath);
      if (!result.content || !Buffer.isBuffer(result.content)) {
        throw new chunkKH6RQ4J5_js.StorageProviderError("\u4E0B\u8F7D\u7684\u6587\u4EF6\u5185\u5BB9\u683C\u5F0F\u9519\u8BEF");
      }
      logger.info(
        `\u2705 [AliyunOSSProvider] \u6587\u4EF6\u4E0B\u8F7D\u5B8C\u6210: ${filePath}, \u5927\u5C0F: ${result.content.length}`
      );
      return result.content;
    } catch (error) {
      logger.error(`\u274C [AliyunOSSProvider] \u6587\u4EF6\u4E0B\u8F7D\u5931\u8D25: ${filePath}:`, error);
      if (this.isOSSError(error) && error.code === "NoSuchKey") {
        throw new chunkKH6RQ4J5_js.StorageProviderError(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${filePath}`);
      }
      throw new chunkKH6RQ4J5_js.StorageProviderError(`\u6587\u4EF6\u4E0B\u8F7D\u5931\u8D25: ${this.formatOSSError(error)}`);
    }
  }
  /**
   * 删除文件
   */
  async delete(filePath) {
    this.ensureInitialized();
    logger.info(`\u{1F5D1}\uFE0F [AliyunOSSProvider] \u5F00\u59CB\u4ECEOSS\u5220\u9664\u6587\u4EF6: ${filePath}`);
    try {
      const result = await this.client.delete(filePath);
      logger.info(`\u2705 [AliyunOSSProvider] \u6587\u4EF6\u5220\u9664\u5B8C\u6210: ${filePath}`);
      return {
        success: true,
        data: {
          requestId: result.res?.rt || 0,
          deletedPath: filePath
        }
      };
    } catch (error) {
      logger.error(`\u274C [AliyunOSSProvider] \u6587\u4EF6\u5220\u9664\u5931\u8D25: ${filePath}:`, error);
      if (this.isOSSError(error) && error.code === "NoSuchKey") {
        logger.warn(`\u26A0\uFE0F [AliyunOSSProvider] \u6587\u4EF6\u4E0D\u5B58\u5728: ${filePath}`);
        return {
          success: true,
          data: { reason: "file_not_exists" }
        };
      }
      return {
        success: false,
        error: this.formatOSSError(error)
      };
    }
  }
  /**
   * 获取文件信息
   */
  async getFileInfo(filePath) {
    this.ensureInitialized();
    try {
      const result = await this.client.head(filePath);
      return {
        success: true,
        size: parseInt(String(result.meta["content-length"] || "0")),
        data: {
          etag: result.meta.etag || "",
          lastModified: result.meta["last-modified"] || "",
          contentType: result.meta["content-type"],
          meta: result.meta,
          size: parseInt(String(result.meta["content-length"] || "0"))
        }
      };
    } catch (error) {
      if (this.isOSSError(error) && error.code === "NoSuchKey") {
        return {
          success: false,
          error: "\u6587\u4EF6\u4E0D\u5B58\u5728"
        };
      }
      return {
        success: false,
        error: this.formatOSSError(error)
      };
    }
  }
  /**
   * 生成访问URL
   */
  async getAccessUrl(filePath, expiresIn) {
    this.ensureInitialized();
    try {
      const isImage = /\.(jpg|jpeg|png|gif|webp|svg|bmp|ico)$/i.test(filePath);
      if (isImage) {
        return this.generateAccessUrl(filePath);
      } else {
        const expires = expiresIn || 3600;
        const signedUrl = this.client.signatureUrl(filePath, {
          expires,
          method: "GET"
        });
        return signedUrl;
      }
    } catch (error) {
      logger.error(`\u274C [AliyunOSSProvider] \u751F\u6210\u8BBF\u95EEURL\u5931\u8D25: ${filePath}:`, error);
      throw new chunkKH6RQ4J5_js.StorageProviderError(`\u751F\u6210\u8BBF\u95EEURL\u5931\u8D25: ${this.formatOSSError(error)}`);
    }
  }
  /**
   * 生成预签名上传URL
   */
  async getUploadUrl(filePath, expiresIn) {
    this.ensureInitialized();
    try {
      const expires = expiresIn || 3600;
      const signedUrl = this.client.signatureUrl(filePath, {
        expires,
        method: "PUT"
      });
      return signedUrl;
    } catch (error) {
      logger.error(`\u274C [AliyunOSSProvider] \u751F\u6210\u4E0A\u4F20URL\u5931\u8D25: ${filePath}:`, error);
      throw new chunkKH6RQ4J5_js.StorageProviderError(`\u751F\u6210\u4E0A\u4F20URL\u5931\u8D25: ${this.formatOSSError(error)}`);
    }
  }
  /**
   * 检查文件是否存在
   */
  async exists(filePath) {
    this.ensureInitialized();
    try {
      await this.client.head(filePath);
      return true;
    } catch (error) {
      if (this.isOSSError(error) && error.code === "NoSuchKey") {
        return false;
      }
      logger.warn(`\u26A0\uFE0F [AliyunOSSProvider] \u68C0\u67E5\u6587\u4EF6\u5B58\u5728\u6027\u65F6\u51FA\u9519: ${filePath}:`, error);
      return false;
    }
  }
  /**
   * 列出文件（详细信息）
   */
  async listFiles(prefix, delimiter = "/", maxKeys = 1e3) {
    this.ensureInitialized();
    try {
      const options = {
        prefix,
        delimiter,
        "max-keys": String(maxKeys)
      };
      const result = await this.client.list(options);
      const files = (result.objects || []).map((obj) => ({
        name: obj.name,
        url: this.generateAccessUrl(obj.name),
        size: obj.size,
        lastModified: obj.lastModified,
        etag: obj.etag,
        type: "file"
      }));
      const folders = result.prefixes || [];
      return {
        files,
        folders,
        nextMarker: result.nextMarker
      };
    } catch (error) {
      logger.error(`\u274C [AliyunOSSProvider] \u5217\u51FA\u6587\u4EF6\u5931\u8D25: ${prefix}:`, error);
      throw new chunkKH6RQ4J5_js.StorageProviderError(`\u5217\u51FA\u6587\u4EF6\u5931\u8D25: ${this.formatOSSError(error)}`);
    }
  }
  /**
   * 列出文件
   */
  async list(prefix, maxKeys) {
    this.ensureInitialized();
    try {
      const options = {
        prefix,
        "max-keys": String(maxKeys || 1e3)
      };
      const result = await this.client.list(options);
      return result.objects?.map((obj) => obj.name) || [];
    } catch (error) {
      logger.error(`\u274C [AliyunOSSProvider] \u5217\u51FA\u6587\u4EF6\u5931\u8D25: ${prefix}:`, error);
      return [];
    }
  }
  // ============= 私有方法 =============
  /**
   * 确保已初始化
   */
  ensureInitialized() {
    if (!this.isInitialized || !this.client || !this.config) {
      throw new chunkKH6RQ4J5_js.StorageProviderError("OSS\u5B58\u50A8\u63D0\u4F9B\u8005\u672A\u521D\u59CB\u5316");
    }
  }
  /**
   * 验证配置
   */
  validateConfig() {
    if (!this.config) {
      throw new chunkKH6RQ4J5_js.StorageProviderError("OSS\u914D\u7F6E\u4E3A\u7A7A");
    }
    const required = ["region", "bucket", "accessKeyId", "accessKeySecret"];
    const missing = required.filter((key) => !this.config[key]);
    if (missing.length > 0) {
      throw new chunkKH6RQ4J5_js.StorageProviderError(`OSS\u914D\u7F6E\u7F3A\u5C11\u5FC5\u9700\u9879: ${missing.join(", ")}`);
    }
  }
  /**
   * 测试连接
   */
  async testConnection() {
    try {
      await this.client.list({
        "max-keys": "1"
      });
      logger.info(`\u2705 [AliyunOSSProvider] OSS\u8FDE\u63A5\u6D4B\u8BD5\u6210\u529F`);
    } catch (error) {
      if (this.isOSSError(error)) {
        if (error.code === "NoSuchBucket") {
          throw new chunkKH6RQ4J5_js.StorageProviderError(`\u5B58\u50A8\u6876\u4E0D\u5B58\u5728: ${this.config.bucket}`);
        }
        if (error.code === "InvalidAccessKeyId") {
          throw new chunkKH6RQ4J5_js.StorageProviderError("Access Key ID \u65E0\u6548");
        }
        if (error.code === "SignatureDoesNotMatch") {
          throw new chunkKH6RQ4J5_js.StorageProviderError("Access Key Secret \u65E0\u6548");
        }
      }
      throw error;
    }
  }
  /**
   * 分片上传大文件
   */
  async multipartUpload(filePath, buffer, options) {
    logger.info(`\u{1F4E6} [AliyunOSSProvider] \u4F7F\u7528\u591A\u5206\u7247\u4E0A\u4F20`);
    const result = await this.client.multipartUpload(filePath, buffer, {
      partSize: 10 * 1024 * 1024,
      // 10MB per chunk
      parallel: 4,
      // 并发数
      progress: (p) => {
        if (p % 0.1 < 0.01) {
          logger.info(`\u{1F4E6} [AliyunOSSProvider] \u4E0A\u4F20\u8FDB\u5EA6: ${(p * 100).toFixed(1)}%`);
        }
      },
      meta: options.meta,
      headers: options.headers
    });
    return {
      name: result.name,
      url: result.name,
      // OSS返回的是object名称
      data: result.data,
      res: result.res
    };
  }
  /**
   * 生成公开访问URL
   */
  generateAccessUrl(filePath) {
    if (!this.config) {
      throw new chunkKH6RQ4J5_js.StorageProviderError("OSS\u914D\u7F6E\u4E3A\u7A7A");
    }
    const normalizedPath = filePath.startsWith("/") ? filePath.substring(1) : filePath;
    if (this.config.customDomain) {
      const protocol = this.config.secure !== false ? "https" : "http";
      const url = `${protocol}://${this.config.customDomain}/${normalizedPath}`;
      logger.info(`\u{1F517} [AliyunOSSProvider] \u4F7F\u7528\u81EA\u5B9A\u4E49\u57DF\u540D: ${url}`);
      return url;
    } else {
      const protocol = this.config.secure !== false ? "https" : "http";
      const url = `${protocol}://${this.config.bucket}.${this.config.region}.aliyuncs.com/${normalizedPath}`;
      logger.info(`\u{1F517} [AliyunOSSProvider] \u4F7F\u7528\u9ED8\u8BA4OSS\u57DF\u540D: ${url}`);
      return url;
    }
  }
  /**
   * 判断是否为OSS错误
   */
  isOSSError(error) {
    return error && typeof error.code === "string" && typeof error.name === "string";
  }
  /**
   * 格式化OSS错误信息
   */
  formatOSSError(error) {
    if (this.isOSSError(error)) {
      return `${error.code}: ${error.message}${error.requestId ? ` (RequestId: ${error.requestId})` : ""}`;
    }
    return error instanceof Error ? error.message : "\u672A\u77E5\u9519\u8BEF";
  }
  /**
   * 流式上传（可选实现）
   */
  async uploadStream(readableStream, filePath, contentType, contentLength) {
    this.ensureInitialized();
    const startTime = Date.now();
    logger.info(`\u{1F4E4} [AliyunOSSProvider] \u5F00\u59CB\u6D41\u5F0F\u4E0A\u4F20\u6587\u4EF6\u5230OSS: ${filePath}`);
    try {
      const options = {
        timeout: 3e5,
        mime: contentType || "application/octet-stream",
        meta: { uid: 0, pid: 0 },
        callback: { url: "", body: "" },
        headers: {}
      };
      if (contentLength) {
        options.headers["Content-Length"] = contentLength.toString();
      }
      const result = await this.client.putStream(filePath, readableStream, options);
      const accessUrl = this.generateAccessUrl(filePath);
      const uploadTime = Date.now() - startTime;
      logger.info(`\u2705 [AliyunOSSProvider] \u6D41\u5F0F\u4E0A\u4F20\u5B8C\u6210: ${filePath}, \u8017\u65F6: ${uploadTime}ms`);
      return {
        success: true,
        path: filePath,
        url: accessUrl,
        size: contentLength,
        data: {
          name: result.name,
          requestId: result.res?.rt || 0,
          uploadTime,
          ossUrl: result.url || result.name
        }
      };
    } catch (error) {
      logger.error(`\u274C [AliyunOSSProvider] \u6D41\u5F0F\u4E0A\u4F20\u5931\u8D25: ${filePath}:`, error);
      return {
        success: false,
        error: this.formatOSSError(error)
      };
    }
  }
  /**
   * 批量删除文件
   */
  async batchDelete(filePaths) {
    this.ensureInitialized();
    logger.info(`\u{1F5D1}\uFE0F [AliyunOSSProvider] \u5F00\u59CB\u6279\u91CF\u5220\u9664\u6587\u4EF6\uFF0C\u6570\u91CF: ${filePaths.length}`);
    try {
      const result = await this.client.deleteMulti(filePaths, {
        quiet: false
        // 返回删除结果
      });
      logger.info(`\u2705 [AliyunOSSProvider] \u6279\u91CF\u5220\u9664\u5B8C\u6210\uFF0C\u6210\u529F: ${result.deleted?.length || 0}`);
      return {
        success: true,
        data: {
          deleted: result.deleted,
          requestId: result.res?.rt || 0
        }
      };
    } catch (error) {
      logger.error(`\u274C [AliyunOSSProvider] \u6279\u91CF\u5220\u9664\u5931\u8D25:`, error);
      return {
        success: false,
        error: this.formatOSSError(error)
      };
    }
  }
  /**
   * 复制文件
   */
  async copy(sourcePath, targetPath) {
    this.ensureInitialized();
    logger.info(`\u{1F4CB} [AliyunOSSProvider] \u5F00\u59CB\u590D\u5236\u6587\u4EF6: ${sourcePath} -> ${targetPath}`);
    try {
      const result = await this.client.copy(targetPath, sourcePath);
      logger.info(`\u2705 [AliyunOSSProvider] \u6587\u4EF6\u590D\u5236\u5B8C\u6210: ${sourcePath} -> ${targetPath}`);
      return {
        success: true,
        data: {
          etag: result.data?.etag,
          lastModified: result.data?.lastModified,
          requestId: result.res?.rt || 0
        }
      };
    } catch (error) {
      logger.error(`\u274C [AliyunOSSProvider] \u6587\u4EF6\u590D\u5236\u5931\u8D25: ${sourcePath} -> ${targetPath}:`, error);
      return {
        success: false,
        error: this.formatOSSError(error)
      };
    }
  }
  /**
   * 编码元数据，避免中文字符在HTTP头部中的问题
   */
  encodeMetadata(metadata) {
    const encoded = {};
    for (const [key, value] of Object.entries(metadata)) {
      if (value !== null && value !== void 0) {
        const stringValue = String(value);
        encoded[key] = encodeURIComponent(stringValue);
      }
    }
    return encoded;
  }
};

exports.AliyunOSSProvider = AliyunOSSProvider;
//# sourceMappingURL=chunk-EXT3IKQA.js.map
//# sourceMappingURL=chunk-EXT3IKQA.js.map