"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 __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 NodeJsEnvironment_exports = {};
__export(NodeJsEnvironment_exports, {
  NodeJsEnvironment: () => NodeJsEnvironment,
  getDefaults: () => getDefaults,
  loadConfigFile: () => loadConfigFile
});
module.exports = __toCommonJS(NodeJsEnvironment_exports);
var import_config = require("#config.js");
var import_NodeJsCrypto = require("#crypto/NodeJsCrypto.js");
var import_NodeJsHttpEndpoint = require("#net/NodeJsHttpEndpoint.js");
var import_FileStorageDriver = require("#storage/fs/FileStorageDriver.js");
var import_general = require("@matter/general");
var import_runtimeChecks = require("#util/runtimeChecks.js");
var import_node_fs = require("node:fs");
var import_promises = require("node:fs/promises");
var import_node_path = require("node:path");
var import_NodeJsFilesystem = require("../fs/NodeJsFilesystem.js");
var import_NodeJsNetwork = require("../net/NodeJsNetwork.js");
var import_ProcessManager = require("./ProcessManager.js");
/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
function NodeJsEnvironment() {
  const env = new import_general.Environment("default");
  loadVariables(env);
  configureCrypto(env);
  configureRuntime(env);
  configureStorage(env);
  configureNetwork(env);
  configureFilesystem(env);
  if (!env.vars.has("logger.format") && import_general.Logger.format === import_general.LogFormat.PLAIN && process.stdin?.isTTY) {
    env.vars.set("logger.format", import_general.LogFormat.ANSI);
  }
  import_general.ServiceBundle.default.deploy(env);
  import_config.config.isInitialized = true;
  return env;
}
function loadVariables(env) {
  const vars = env.vars;
  vars.addConfigStyle(getDefaults(vars));
  if (import_config.config.loadProcessEnv) {
    vars.addUnixEnvStyle(process.env);
  }
  if (import_config.config.loadProcessArgv) {
    vars.addArgvStyle(process.argv);
  }
  const { configPath, configVars } = loadConfigFile(vars);
  if (import_config.config.loadConfigFile) {
    vars.addConfigStyle(configVars);
  }
  if (import_config.config.loadProcessEnv) {
    vars.addUnixEnvStyle(process.env);
  }
  if (import_config.config.loadProcessArgv) {
    vars.addArgvStyle(process.argv);
  }
  vars.persistConfigValue = async (name, value) => {
    if (value === void 0) {
      delete configVars[name];
    }
    configVars[name] = value;
    await (0, import_promises.writeFile)(configPath, JSON.stringify(configVars, void 0, 4));
  };
}
function rootDirOf(env) {
  return env.vars.get("path.root", ".");
}
function configureCrypto(env) {
  import_general.Boot.init(() => {
    if (env.vars.boolean("nodejs.crypto")) {
      let crypto;
      if (!(0, import_runtimeChecks.isBunjs)()) {
        crypto = new import_NodeJsCrypto.NodeJsCrypto();
      } else {
        crypto = new import_general.StandardCrypto(global.crypto);
      }
      env.set(import_general.Entropy, crypto);
      env.set(import_general.Crypto, crypto);
      return;
    }
    if (import_general.Environment.default.has(import_general.Entropy)) {
      env.set(import_general.Entropy, import_general.Environment.default.get(import_general.Entropy));
    }
    if (import_general.Environment.default.has(import_general.Crypto)) {
      env.set(import_general.Crypto, import_general.Environment.default.get(import_general.Crypto));
    }
  });
}
function configureNetwork(env) {
  import_general.Boot.init(() => {
    if (env.vars.boolean("nodejs.network")) {
      env.set(import_general.Network, new import_NodeJsNetwork.NodeJsNetwork());
      env.set(import_general.HttpEndpointFactory, new import_NodeJsHttpEndpoint.NodeJsHttpEndpoint.Factory());
      return;
    }
    if (import_general.Environment.default.has(import_general.Network)) {
      env.set(import_general.Network, import_general.Environment.default.get(import_general.Network));
    }
    if (import_general.Environment.default.has(import_general.HttpEndpointFactory)) {
      env.set(import_general.HttpEndpointFactory, import_general.Environment.default.get(import_general.HttpEndpointFactory));
    }
  });
}
function configureRuntime(env) {
  const processManager = new import_ProcessManager.ProcessManager(env);
  env.set(import_ProcessManager.ProcessManager, processManager);
}
function configureStorage(env) {
  import_general.Boot.init(() => {
    if (env.vars.boolean("nodejs.storage")) {
      const service = env.get(import_general.StorageService);
      service.registerDriver(import_general.MemoryStorageDriver);
      service.registerDriver(import_general.WalStorageDriver);
      service.registerDriver(import_FileStorageDriver.FileStorageDriver);
      service.registerDriver({
        id: "sqlite",
        async create(namespace) {
          const { SqliteStorageDriver } = await import("#storage/sqlite/index.js");
          return SqliteStorageDriver.create(namespace);
        }
      });
      service.defaultDriver = "file";
      let storageDriver = env.vars.string("storage.driver");
      if (storageDriver && storageDriver.length > 0) {
        service.configuredDriver = storageDriver;
      }
      return;
    }
    if (import_general.Environment.default.has(import_general.StorageService)) {
      env.set(import_general.StorageService, import_general.Environment.default.get(import_general.StorageService));
    }
  });
}
function configureFilesystem(env) {
  import_general.Boot.init(() => {
    if (env.vars.boolean("nodejs.filesystem")) {
      env.set(import_general.Filesystem, new import_NodeJsFilesystem.NodeJsFilesystem(() => env.vars.get("storage.path", rootDirOf(env))));
      return;
    }
    if (import_general.Environment.default.has(import_general.Filesystem)) {
      env.set(import_general.Filesystem, import_general.Environment.default.get(import_general.Filesystem));
    }
  });
}
function loadConfigFile(vars) {
  const configPath = vars.get("path.config", "config.json");
  if (!(0, import_node_fs.existsSync)(configPath)) {
    return { configPath, configVars: {} };
  }
  let configJson;
  try {
    configJson = (0, import_node_fs.readFileSync)(configPath).toString();
  } catch (e) {
    throw new import_general.ImplementationError(`Error reading configuration file ${configPath}: ${(0, import_general.asError)(e).message}`);
  }
  let configVars;
  try {
    configVars = JSON.parse(configJson);
  } catch (e) {
    throw new import_general.ImplementationError(`Error parsing configuration file ${configPath}: ${(0, import_general.asError)(e).message}`);
  }
  return { configPath, configVars };
}
function getDefaultRoot(envName) {
  if (import_config.config.defaultStoragePath !== void 0) {
    return import_config.config.defaultStoragePath;
  }
  let matterDir;
  if (process.platform === "win32") {
    matterDir = (0, import_node_path.resolve)(process.env.APPDATA ?? ".", "matter");
  } else {
    matterDir = (0, import_node_path.resolve)(process.env.HOME ?? ".", ".matter");
  }
  if (envName !== "default") {
    matterDir = `${matterDir}-${envName}`;
  }
  return matterDir;
}
function getDefaults(vars) {
  const envName = vars.get("environment", import_config.config.defaultEnvironmentName);
  const rootPath = vars.get("path.root", getDefaultRoot(envName));
  const configPath = (0, import_node_path.resolve)(rootPath, vars.get("path.config", import_config.config.defaultConfigFilePath));
  return {
    environment: envName,
    path: {
      root: rootPath,
      config: configPath
    },
    runtime: {
      signals: import_config.config.trapProcessSignals,
      exitcode: import_config.config.setProcessExitCodeOnError,
      unhandlederrors: import_config.config.trapUnhandledErrors
    },
    nodejs: {
      crypto: import_config.config.installCrypto,
      filesystem: import_config.config.installFilesystem,
      network: import_config.config.installNetwork,
      storage: import_config.config.initializeStorage
    },
    storage: {
      driver: import_config.config.storageDriver
    }
  };
}
//# sourceMappingURL=NodeJsEnvironment.js.map
