"use strict";
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 __name = (target, value) => __defProp(target, "name", { value, configurable: true });
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 UpdateConfig_exports = {};
__export(UpdateConfig_exports, {
  checkForConfigUpdates: () => checkForConfigUpdates,
  installConfigUpdate: () => installConfigUpdate
});
module.exports = __toCommonJS(UpdateConfig_exports);
var import_untar = require("@andrewbranch/untar.js");
var import_core = require("@zwave-js/core");
var import_shared = require("@zwave-js/shared");
var import_typeguards = require("alcalzone-shared/typeguards");
var import_pathe = __toESM(require("pathe"), 1);
var import_inc = __toESM(require("semver/functions/inc.js"), 1);
var import_valid = __toESM(require("semver/functions/valid.js"), 1);
var import_max_satisfying = __toESM(require("semver/ranges/max-satisfying.js"), 1);
async function checkForConfigUpdates(currentVersion) {
  const { default: ky } = await import("ky");
  let registry;
  try {
    registry = await ky.get("https://registry.npmjs.org/@zwave-js/config").json();
  } catch {
    throw new import_core.ZWaveError(`Could not check for config updates: Failed to download package information!`, import_core.ZWaveErrorCodes.Config_Update_RegistryError);
  }
  if (!(0, import_typeguards.isObject)(registry) || !(0, import_typeguards.isObject)(registry.versions)) {
    throw new import_core.ZWaveError(`Could not check for config updates: Downloaded package information does not contain version information!`, import_core.ZWaveErrorCodes.Config_Update_RegistryError);
  }
  const allVersions = Object.keys(registry.versions).filter((v) => !!(0, import_valid.default)(v)).filter((v) => /\-\d{8}$/.test(v));
  const updateRange = `>${currentVersion} <${(0, import_inc.default)(currentVersion, "patch")}`;
  const updateVersion = (0, import_max_satisfying.default)(allVersions, updateRange, {
    includePrerelease: true
  });
  if (updateVersion)
    return updateVersion;
}
__name(checkForConfigUpdates, "checkForConfigUpdates");
async function installConfigUpdate(fs, newVersion, external) {
  const { default: ky } = await import("ky");
  let registryInfo;
  try {
    registryInfo = await ky.get(`https://registry.npmjs.org/@zwave-js/config/${newVersion}`).json();
  } catch {
    throw new import_core.ZWaveError(`Config update failed: Could not fetch package info from npm registry!`, import_core.ZWaveErrorCodes.Config_Update_InstallFailed);
  }
  const url = registryInfo?.dist?.tarball;
  if (typeof url !== "string") {
    throw new import_core.ZWaveError(`Config update failed: Could not fetch package tarball URL from npm registry!`, import_core.ZWaveErrorCodes.Config_Update_InstallFailed);
  }
  let tarballData;
  try {
    tarballData = new Uint8Array(await ky.get(url).arrayBuffer());
  } catch (e) {
    throw new import_core.ZWaveError(`Config update failed: Could not download tarball. Reason: ${(0, import_shared.getErrorMessage)(e)}`, import_core.ZWaveErrorCodes.Config_Update_InstallFailed);
  }
  try {
    const tarFiles = (0, import_untar.untar)((0, import_core.gunzipSync)(tarballData));
    await fs.deleteDir(external.configDir);
    await fs.ensureDir(external.configDir);
    const prefix = "package/config/";
    for (const file of tarFiles) {
      if (!file.filename.startsWith(prefix) || !file.filename.endsWith(".json")) {
        continue;
      }
      const filename = file.filename.slice(prefix.length);
      const targetFileName = import_pathe.default.join(external.configDir, filename);
      const targetDirName = import_pathe.default.dirname(targetFileName);
      await fs.ensureDir(targetDirName);
      await fs.writeFile(targetFileName, file.fileData);
    }
    const externalVersionFilename = import_pathe.default.join(external.configDir, "version");
    await (0, import_shared.writeTextFile)(fs, externalVersionFilename, newVersion);
  } catch {
    throw new import_core.ZWaveError(`Config update failed: Could not extract tarball`, import_core.ZWaveErrorCodes.Config_Update_InstallFailed);
  }
}
__name(installConfigUpdate, "installConfigUpdate");
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  checkForConfigUpdates,
  installConfigUpdate
});
//# sourceMappingURL=UpdateConfig.js.map
