/**
 * 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 utils_exports = {};
__export(utils_exports, {
  cloudFilenameGetter: () => cloudFilenameGetter,
  diskFilenameGetter: () => diskFilenameGetter,
  encodeURL: () => encodeURL,
  ensureUrlEncoded: () => ensureUrlEncoded,
  getFileKey: () => getFileKey,
  getFilename: () => getFilename
});
module.exports = __toCommonJS(utils_exports);
var import_utils = require("@nocobase/utils");
var import_crypto = __toESM(require("crypto"));
var import_path = __toESM(require("path"));
var import_url_join = __toESM(require("url-join"));
function normalizeOriginalname(file) {
  const originalname = file == null ? void 0 : file.originalname;
  if (!originalname) {
    return "";
  }
  if (Buffer.isBuffer(originalname)) {
    return originalname.toString("utf8");
  }
  const decoded = Buffer.from(originalname, "binary").toString("utf8");
  if (decoded.includes("\uFFFD")) {
    return originalname;
  }
  return decoded;
}
function getFilename(req, file, cb) {
  const originalname = normalizeOriginalname(file);
  const baseName = import_path.default.basename(originalname.replace(/[<>?*|:"\\/]/g, "-"), import_path.default.extname(originalname));
  cb(null, `${baseName}-${(0, import_utils.uid)(6)}${import_path.default.extname(originalname)}`);
}
function getOriginalFilename(file) {
  const originalname = normalizeOriginalname(file);
  const extname = import_path.default.extname(originalname);
  const baseName = import_path.default.basename(originalname.replace(/[<>?*|:"\\/]/g, "-"), extname);
  return `${baseName}${extname}`;
}
const cloudFilenameGetter = (storage) => (req, file, cb) => {
  const renameMode = storage.renameMode;
  if (renameMode === "random") {
    import_crypto.default.randomBytes(16, function(err, raw) {
      if (err) {
        return cb(err);
      }
      const filename = `${raw.toString("hex")}${import_path.default.extname(normalizeOriginalname(file))}`;
      cb(null, `${storage.path ? `${storage.path.replace(/\/+$/, "")}/` : ""}${filename}`);
    });
    return;
  }
  if (renameMode === "none") {
    const filename = getOriginalFilename(file);
    cb(null, `${storage.path ? `${storage.path.replace(/\/+$/, "")}/` : ""}${filename}`);
    return;
  }
  getFilename(req, file, (err, filename) => {
    if (err) {
      return cb(err);
    }
    cb(null, `${storage.path ? `${storage.path.replace(/\/+$/, "")}/` : ""}${filename}`);
  });
};
const diskFilenameGetter = (storage) => (req, file, cb) => {
  const renameMode = storage.renameMode;
  if (renameMode === "random") {
    import_crypto.default.randomBytes(16, function(err, raw) {
      if (err) {
        return cb(err);
      }
      const filename = `${raw.toString("hex")}${import_path.default.extname(normalizeOriginalname(file))}`;
      cb(null, filename);
    });
    return;
  }
  if (renameMode === "none") {
    cb(null, getOriginalFilename(file));
    return;
  }
  getFilename(req, file, cb);
};
function getFileKey(record) {
  return (0, import_url_join.default)(record.path || "", record.filename).replace(/^\//, "");
}
function ensureUrlEncoded(value) {
  try {
    if (decodeURIComponent(value) !== value) {
      return value;
    }
  } catch (e) {
    return encodeURIComponent(value);
  }
  return encodeURIComponent(value);
}
function encodePathKeepSlash(path2) {
  return path2.split("/").map((segment) => ensureUrlEncoded(segment)).join("/");
}
function encodeURL(url) {
  try {
    const parsedUrl = new URL(url);
    parsedUrl.pathname = encodePathKeepSlash(parsedUrl.pathname);
    return parsedUrl.toString();
  } catch (error) {
    return url;
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  cloudFilenameGetter,
  diskFilenameGetter,
  encodeURL,
  ensureUrlEncoded,
  getFileKey,
  getFilename
});
