var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var asset_packs_exports = {};
__export(asset_packs_exports, {
  buildAssetPacksApiClientMethods: () => buildAssetPacksApiClientMethods
});
module.exports = __toCommonJS(asset_packs_exports);
var import_request = require("../core/request.js");
function buildPublicAssetPackPath(normalizeCreatorItemSlug, creatorUsername, packName, suffix = "") {
  const creator = normalizeCreatorItemSlug(creatorUsername, "creator");
  const name = normalizeCreatorItemSlug(packName, "name");
  return `/asset-packs/${encodeURIComponent(creator)}/${encodeURIComponent(name)}${suffix}`;
}
function appendNormalizedTagParams(params, tags) {
  if (!Array.isArray(tags)) {
    return;
  }
  for (const tag of tags) {
    if (typeof tag !== "string") {
      continue;
    }
    const normalized = tag.trim();
    if (normalized.length > 0) {
      params.append("tag", normalized);
    }
  }
}
function buildAssetPackVersionPath(normalizeCreatorItemSlug, normalizeSemverInput, creatorUsername, packName, version, suffix) {
  const creator = normalizeCreatorItemSlug(creatorUsername, "creator");
  const name = normalizeCreatorItemSlug(packName, "name");
  const normalizedVersion = normalizeSemverInput(version);
  return `/asset-packs/${encodeURIComponent(creator)}/${encodeURIComponent(name)}/versions/${encodeURIComponent(normalizedVersion)}${suffix}`;
}
async function buildAuthorizedHeaders(getClientHeaders, resolveToken) {
  const headers = new Headers();
  for (const [key, value] of Object.entries(getClientHeaders())) {
    headers.set(key, value);
  }
  const token = await resolveToken();
  if (token) {
    headers.set("authorization", `Bearer ${token}`);
  }
  return headers;
}
function buildAssetPackSessionAssetUploadForm(options) {
  if (!Array.isArray(options.files) || options.files.length === 0) {
    throw new Error("missing_asset_files");
  }
  const form = new FormData();
  for (const item of options.files) {
    if (!item) {
      throw new Error("missing_asset_upload_file");
    }
    const fieldName = typeof item.fieldName === "string" && item.fieldName.trim().length > 0 ? item.fieldName.trim() : "file";
    if (typeof item.filename === "string" && item.filename.trim().length > 0) {
      form.append(fieldName, item.file, item.filename.trim());
    } else {
      form.append(fieldName, item.file);
    }
  }
  return form;
}
function buildAssetPackSessionMediaUploadForm(options) {
  if (!options?.file) {
    throw new Error("missing_media_file");
  }
  const form = new FormData();
  if (typeof options.filename === "string" && options.filename.trim().length > 0) {
    form.append("file", options.file, options.filename.trim());
  } else {
    form.append("file", options.file);
  }
  return form;
}
async function fetchAssetPackRelatedRequest(request, handleApiError, normalizeCreatorItemSlug, creatorUsername, packName) {
  const response = await request({
    method: "GET",
    path: buildPublicAssetPackPath(normalizeCreatorItemSlug, creatorUsername, packName, "/related")
  });
  if (response.status !== 200) {
    handleApiError(response, "get_pack_related");
  }
  return response.body;
}
async function fetchAssetPackDetailRequest(request, handleApiError, creatorUsername, packName) {
  const response = await request({
    method: "GET",
    path: `/asset-packs/${encodeURIComponent(creatorUsername)}/${encodeURIComponent(packName)}`
  });
  if (response.status !== 200) {
    handleApiError(response, "fetch_asset_pack_by_slug");
  }
  if (!Array.isArray(response.body.assets)) {
    throw new Error("asset_pack_detail_assets_missing");
  }
  return response.body;
}
function buildAssetPacksApiClientMethods(input) {
  return {
    ...buildAssetPackUploadSessionMethods(input),
    ...buildAssetPackReadWriteMethods(input)
  };
}
function buildAssetPackUploadSessionMethods(input) {
  const { request, handleApiError, fetchImpl, includeBrowserCredentials, resolveBaseUrl, resolveUrl, parseResponseBody, resolveToken, getClientHeaders, buildCreatorAssetPackMutationPath, normalizeCreatorItemSlug } = input;
  return {
    async initializeAssetPackUpload(creatorUsername, name, requestBody) {
      const packName = typeof name === "string" ? name.trim() : "";
      if (!packName) {
        throw new Error("invalid_pack_name");
      }
      const response = await request({
        method: "POST",
        path: `${buildCreatorAssetPackMutationPath(creatorUsername, packName)}/upload-sessions`,
        body: requestBody
      });
      if (response.status !== 200 && response.status !== 201) {
        handleApiError(response, "initialize_asset_pack_upload");
      }
      return response.body;
    },
    async uploadAssetPackSessionAsset(creatorUsername, name, sessionId, uploadKey, options) {
      const packName = typeof name === "string" ? name.trim() : "";
      if (!packName) {
        throw new Error("invalid_pack_name");
      }
      const normalizedSessionId = typeof sessionId === "string" ? sessionId.trim() : "";
      const normalizedUploadKey = typeof uploadKey === "string" ? uploadKey.trim() : "";
      if (!normalizedSessionId) {
        throw new Error("invalid_pack_upload_session_id");
      }
      if (!normalizedUploadKey) {
        throw new Error("invalid_pack_upload_asset_key");
      }
      const form = buildAssetPackSessionAssetUploadForm(options);
      const base = resolveBaseUrl();
      const path = `${buildCreatorAssetPackMutationPath(creatorUsername, packName)}/upload-sessions/${encodeURIComponent(normalizedSessionId)}/assets/${encodeURIComponent(normalizedUploadKey)}`;
      const headers = await buildAuthorizedHeaders(getClientHeaders, resolveToken);
      const response = await fetchImpl(resolveUrl(base, path), {
        method: "POST",
        headers,
        body: form,
        ...(0, import_request.buildBrowserCredentialsInit)(includeBrowserCredentials)
      });
      const parsed = await parseResponseBody(response);
      const apiResponse = { status: response.status, body: parsed, headers: response.headers };
      if (response.status !== 200 && response.status !== 201) {
        handleApiError(apiResponse, "upload_asset_pack_session_asset");
      }
      return parsed;
    },
    async uploadAssetPackSessionMedia(creatorUsername, name, sessionId, mediaKey, options) {
      const packName = typeof name === "string" ? name.trim() : "";
      if (!packName) {
        throw new Error("invalid_pack_name");
      }
      const normalizedSessionId = typeof sessionId === "string" ? sessionId.trim() : "";
      const normalizedMediaKey = typeof mediaKey === "string" ? mediaKey.trim() : "";
      if (!normalizedSessionId) {
        throw new Error("invalid_pack_upload_session_id");
      }
      if (!normalizedMediaKey) {
        throw new Error("invalid_pack_upload_media_key");
      }
      const form = buildAssetPackSessionMediaUploadForm(options);
      const base = resolveBaseUrl();
      const path = `${buildCreatorAssetPackMutationPath(creatorUsername, packName)}/upload-sessions/${encodeURIComponent(normalizedSessionId)}/media/${encodeURIComponent(normalizedMediaKey)}`;
      const headers = await buildAuthorizedHeaders(getClientHeaders, resolveToken);
      const response = await fetchImpl(resolveUrl(base, path), {
        method: "POST",
        headers,
        body: form,
        ...(0, import_request.buildBrowserCredentialsInit)(includeBrowserCredentials)
      });
      const parsed = await parseResponseBody(response);
      const apiResponse = { status: response.status, body: parsed, headers: response.headers };
      if (response.status !== 200 && response.status !== 201) {
        handleApiError(apiResponse, "upload_asset_pack_session_media");
      }
      return parsed;
    },
    async finalizeAssetPackUpload(creatorUsername, name, sessionId) {
      const packName = typeof name === "string" ? name.trim() : "";
      if (!packName) {
        throw new Error("invalid_pack_name");
      }
      const normalizedSessionId = typeof sessionId === "string" ? sessionId.trim() : "";
      if (!normalizedSessionId) {
        throw new Error("invalid_pack_upload_session_id");
      }
      const response = await request({
        method: "POST",
        path: `${buildCreatorAssetPackMutationPath(creatorUsername, packName)}/upload-sessions/${encodeURIComponent(normalizedSessionId)}/finalize`
      });
      if (response.status !== 200 && response.status !== 201) {
        handleApiError(response, "finalize_asset_pack_upload");
      }
      return response.body;
    },
    async abortAssetPackUpload(creatorUsername, name, sessionId) {
      const packName = typeof name === "string" ? name.trim() : "";
      if (!packName) {
        throw new Error("invalid_pack_name");
      }
      const normalizedSessionId = typeof sessionId === "string" ? sessionId.trim() : "";
      if (!normalizedSessionId) {
        throw new Error("invalid_pack_upload_session_id");
      }
      const response = await request({
        method: "POST",
        path: `${buildCreatorAssetPackMutationPath(creatorUsername, packName)}/upload-sessions/${encodeURIComponent(normalizedSessionId)}/abort`
      });
      if (response.status !== 200) {
        handleApiError(response, "abort_asset_pack_upload");
      }
      return response.body;
    },
    async fetchAssetPackRelated(creatorUsername, packName) {
      return fetchAssetPackRelatedRequest(request, handleApiError, normalizeCreatorItemSlug, creatorUsername, packName);
    }
  };
}
function buildAssetPackReadWriteMethods(input) {
  const { request, handleApiError, fetchImpl, includeBrowserCredentials, resolveBaseUrl, resolveUrl, parseResponseBody, resolveToken, getClientHeaders, buildCreatorAssetPackMutationPath, normalizeCreatorItemSlug, normalizeSemverInput, parseContentDispositionFilename } = input;
  return {
    async listAssetPacks(options = {}) {
      const params = new URLSearchParams();
      if (typeof options.limit === "number") {
        params.set("limit", String(options.limit));
      }
      if (typeof options.offset === "number") {
        params.set("offset", String(options.offset));
      }
      if (typeof options.containsCategory === "string" && options.containsCategory.trim().length > 0) {
        params.set("containsCategory", options.containsCategory.trim());
      }
      if (typeof options.containsSubcategory === "string" && options.containsSubcategory.trim().length > 0) {
        params.set("containsSubcategory", options.containsSubcategory.trim());
      }
      appendNormalizedTagParams(params, options.tags);
      const query = params.toString();
      const path = `/asset-packs${query ? `?${query}` : ""}`;
      const response = await request({
        method: "GET",
        path
      });
      if (response.status !== 200) {
        handleApiError(response, "list_asset_packs");
      }
      return response.body;
    },
    async listAssetPacksForCreator(creatorUsername, options = {}) {
      const params = new URLSearchParams();
      if (typeof options.limit === "number") {
        params.set("limit", String(options.limit));
      }
      if (typeof options.offset === "number") {
        params.set("offset", String(options.offset));
      }
      if (typeof options.containsCategory === "string" && options.containsCategory.trim().length > 0) {
        params.set("containsCategory", options.containsCategory.trim());
      }
      if (typeof options.containsSubcategory === "string" && options.containsSubcategory.trim().length > 0) {
        params.set("containsSubcategory", options.containsSubcategory.trim());
      }
      appendNormalizedTagParams(params, options.tags);
      const query = params.toString();
      const path = `/creators/${encodeURIComponent(creatorUsername)}/asset-packs${query ? `?${query}` : ""}`;
      const response = await request({
        method: "GET",
        path
      });
      if (response.status !== 200) {
        handleApiError(response, "list_asset_packs_for_creator");
      }
      return response.body;
    },
    async fetchAssetPackBySlug(creatorUsername, packName) {
      return fetchAssetPackDetailRequest(request, handleApiError, creatorUsername, packName);
    },
    async fetchAssetPackDetailBySlug(creatorUsername, packName) {
      return fetchAssetPackDetailRequest(request, handleApiError, creatorUsername, packName);
    },
    async downloadAssetPackSource(creatorUsername, packName, version) {
      const creator = typeof creatorUsername === "string" ? creatorUsername.trim() : "";
      const name = typeof packName === "string" ? packName.trim() : "";
      if (!creator || !name) {
        throw new Error("invalid_pack_key");
      }
      const normalizedVersion = normalizeSemverInput(version);
      const path = buildAssetPackVersionPath(normalizeCreatorItemSlug, normalizeSemverInput, creator, name, normalizedVersion, "/source");
      const base = resolveBaseUrl();
      const headers = new Headers();
      for (const [key, value] of Object.entries(getClientHeaders())) {
        headers.set(key, value);
      }
      const token = await resolveToken();
      if (token) {
        headers.set("authorization", `Bearer ${token}`);
      }
      const response = await fetchImpl(resolveUrl(base, path), {
        method: "GET",
        headers,
        ...(0, import_request.buildBrowserCredentialsInit)(includeBrowserCredentials)
      });
      if (!response.ok) {
        const parsed = await parseResponseBody(response);
        handleApiError({ status: response.status, body: parsed, headers: response.headers }, "download_asset_pack_source");
      }
      const blob = await response.blob();
      const filename = parseContentDispositionFilename(response.headers.get("content-disposition")) ?? `${name}-${normalizedVersion}-source.zip`;
      const headerSize = response.headers.get("content-length");
      const parsedSize = headerSize ? Number.parseInt(headerSize, 10) : Number.NaN;
      const checksumHeader = response.headers.get("x-pack-source-checksum");
      return {
        blob,
        metadata: {
          filename,
          sizeBytes: Number.isFinite(parsedSize) && parsedSize >= 0 ? parsedSize : blob.size,
          checksum: checksumHeader ?? null
        }
      };
    },
    async downloadAssetPack(creatorUsername, packName, version) {
      const creator = typeof creatorUsername === "string" ? creatorUsername.trim() : "";
      const name = typeof packName === "string" ? packName.trim() : "";
      if (!creator || !name) {
        throw new Error("invalid_pack_key");
      }
      const normalizedVersion = normalizeSemverInput(version);
      const path = buildAssetPackVersionPath(normalizeCreatorItemSlug, normalizeSemverInput, creator, name, normalizedVersion, "/download");
      const base = resolveBaseUrl();
      const headers = new Headers();
      for (const [key, value] of Object.entries(getClientHeaders())) {
        headers.set(key, value);
      }
      const token = await resolveToken();
      if (token) {
        headers.set("authorization", `Bearer ${token}`);
      }
      const response = await fetchImpl(resolveUrl(base, path), {
        method: "GET",
        headers,
        ...(0, import_request.buildBrowserCredentialsInit)(includeBrowserCredentials)
      });
      if (!response.ok) {
        const parsed = await parseResponseBody(response);
        handleApiError({ status: response.status, body: parsed, headers: response.headers }, "download_asset_pack");
      }
      const blob = await response.blob();
      const filename = parseContentDispositionFilename(response.headers.get("content-disposition")) ?? `${name}-${normalizedVersion}.zip`;
      const headerSize = response.headers.get("content-length");
      const parsedSize = headerSize ? Number.parseInt(headerSize, 10) : Number.NaN;
      const checksumHeader = response.headers.get("x-pack-source-checksum");
      return {
        blob,
        metadata: {
          filename,
          sizeBytes: Number.isFinite(parsedSize) && parsedSize >= 0 ? parsedSize : blob.size,
          checksum: checksumHeader ?? null
        }
      };
    },
    async listAssetPackVersions(creatorUsername, packName, options = {}) {
      const params = new URLSearchParams();
      if (typeof options.limit === "number") {
        params.set("limit", String(options.limit));
      }
      if (typeof options.offset === "number") {
        params.set("offset", String(options.offset));
      }
      const query = params.toString();
      const path = `/asset-packs/${encodeURIComponent(creatorUsername)}/${encodeURIComponent(packName)}/versions${query ? `?${query}` : ""}`;
      const response = await request({
        method: "GET",
        path
      });
      if (response.status !== 200) {
        handleApiError(response, "list_asset_pack_versions");
      }
      return response.body;
    },
    async updateAssetPack(creatorUsername, name, requestBody) {
      const packName = typeof name === "string" ? name.trim() : "";
      if (!packName) {
        throw new Error("invalid_pack_name");
      }
      const response = await request({
        method: "PATCH",
        path: buildCreatorAssetPackMutationPath(creatorUsername, packName),
        body: requestBody
      });
      if (response.status !== 200) {
        handleApiError(response, "update_asset_pack");
      }
      return response.body;
    },
    async updateAssetPackVersion(creatorUsername, name, version, requestBody) {
      const packName = typeof name === "string" ? name.trim() : "";
      const versionValue = typeof version === "string" ? version.trim() : "";
      if (!packName) {
        throw new Error("invalid_pack_name");
      }
      if (!versionValue) {
        throw new Error("invalid_pack_version");
      }
      const response = await request({
        method: "PATCH",
        path: `${buildCreatorAssetPackMutationPath(creatorUsername, packName)}/versions/${encodeURIComponent(versionValue)}`,
        body: requestBody
      });
      if (response.status !== 200) {
        handleApiError(response, "update_asset_pack_version");
      }
      return response.body;
    },
    async deleteAssetPackVersion(creatorUsername, name, version) {
      const packName = typeof name === "string" ? name.trim() : "";
      const versionValue = typeof version === "string" ? version.trim() : "";
      if (!packName) {
        throw new Error("invalid_pack_name");
      }
      if (!versionValue) {
        throw new Error("invalid_pack_version");
      }
      const response = await request({
        method: "DELETE",
        path: `${buildCreatorAssetPackMutationPath(creatorUsername, packName)}/versions/${encodeURIComponent(versionValue)}`
      });
      if (response.status !== 200) {
        handleApiError(response, "delete_asset_pack_version");
      }
      return response.body;
    },
    async deleteAssetPack(creatorUsername, name) {
      const packName = typeof name === "string" ? name.trim() : "";
      if (!packName) {
        throw new Error("invalid_pack_name");
      }
      const response = await request({
        method: "DELETE",
        path: buildCreatorAssetPackMutationPath(creatorUsername, packName)
      });
      if (response.status !== 200) {
        handleApiError(response, "delete_asset_pack");
      }
      return response.body;
    }
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  buildAssetPacksApiClientMethods
});
