"use strict";
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);

// src/profile.ts
var profile_exports = {};
__export(profile_exports, {
  resolveInvocationContext: () => resolveInvocationContext,
  resolveInvocationProfile: () => resolveInvocationProfile,
  resolveInvocationProfileName: () => resolveInvocationProfileName,
  resolvePosture: () => resolvePosture
});
module.exports = __toCommonJS(profile_exports);

// src/state.ts
var import_node_crypto = require("crypto");
var import_node_async_hooks = require("async_hooks");
var import_promises = require("fs/promises");
var import_node_os = require("os");
var import_node_path = require("path");
var DEFAULT_PROFILE = "default";
var invocationStateRoot = new import_node_async_hooks.AsyncLocalStorage();
function tinycloudHomePath() {
  const home = invocationStateRoot.getStore() ?? process.env.TC_HOME ?? process.env.HOME ?? process.env.USERPROFILE ?? (0, import_node_os.homedir)();
  return (0, import_node_path.join)(home, ".tinycloud");
}
function tinycloudConfigPath() {
  return (0, import_node_path.join)(tinycloudHomePath(), "config.json");
}
function profilesPath() {
  return (0, import_node_path.join)(tinycloudHomePath(), "profiles");
}
function profilePath(profile) {
  return (0, import_node_path.join)(profilesPath(), validateProfileName(profile));
}
function profileConfigPath(profile) {
  return (0, import_node_path.join)(profilePath(profile), "profile.json");
}
async function readJson(filePath) {
  try {
    return JSON.parse(await (0, import_promises.readFile)(filePath, "utf8"));
  } catch (error) {
    if (isErrno(error, "ENOENT")) return null;
    throw error;
  }
}
async function readProfile(profile) {
  return readJson(profileConfigPath(profile));
}
function validateProfileName(profile) {
  if (!profile || profile === "." || profile === ".." || profile.includes("/") || profile.includes("\\") || profile.includes("\0")) {
    throw new TypeError("Profile names must be non-empty path segments.");
  }
  return profile;
}
function isErrno(error, code) {
  return typeof error === "object" && error !== null && "code" in error && error.code === code;
}

// src/profile.ts
var DEFAULT_HOST = "https://node.tinycloud.xyz";
async function resolveInvocationContext(target = {}) {
  const resolved = await resolveInvocationProfile(target);
  return resolved.ok ? { ok: true, context: resolved.context } : resolved;
}
async function resolveInvocationProfile(target = {}) {
  const profile = await resolveProfileName(target);
  let storedProfile;
  try {
    storedProfile = await readProfile(profile);
  } catch {
    return profileNotFound(profile);
  }
  if (!isStoredProfile(storedProfile)) {
    return profileNotFound(profile);
  }
  if (target.privateKey === void 0 && !isCoherentProfile(storedProfile)) {
    return profileNotFound(profile);
  }
  const host = firstString(target.host, process.env.TC_HOST, storedProfile.host, DEFAULT_HOST);
  const posture = resolvePosture(storedProfile);
  return {
    ok: true,
    profile: storedProfile,
    context: {
      profile,
      host,
      posture,
      operatorType: isOperatorType(storedProfile.operatorType) ? storedProfile.operatorType : "human",
      principalDid: maybeDid(storedProfile.did),
      sessionDid: maybeDid(storedProfile.sessionDid),
      ownerDid: maybeDid(storedProfile.ownerDid),
      space: typeof storedProfile.spaceId === "string" ? storedProfile.spaceId : void 0
    }
  };
}
async function resolveInvocationProfileName(explicitProfile) {
  return resolveProfileName(
    explicitProfile === void 0 ? {} : { profile: explicitProfile }
  );
}
async function resolveProfileName(target) {
  if (typeof target.profile === "string") return target.profile;
  if (typeof process.env.TC_PROFILE === "string") return process.env.TC_PROFILE;
  try {
    const config = await readJson(tinycloudConfigPath());
    if (typeof config?.defaultProfile === "string") return config.defaultProfile;
  } catch {
  }
  return DEFAULT_PROFILE;
}
function resolvePosture(profile) {
  if (isPosture(profile.posture)) return profile.posture;
  if (profile.authMethod === "local") return "local-owner-key";
  return "owner-openkey";
}
function profileNotFound(profile) {
  return {
    ok: false,
    error: {
      code: "PROFILE_NOT_FOUND",
      message: `Profile "${profile}" is not available.`,
      retryable: false
    }
  };
}
function firstString(...values) {
  for (const value of values) {
    if (typeof value === "string" && value.length > 0) return value;
  }
  return DEFAULT_HOST;
}
function maybeDid(value) {
  if (typeof value !== "string" || value.length === 0) return void 0;
  const fragment = value.indexOf("#");
  return fragment === -1 ? value : value.slice(0, fragment);
}
function isPosture(value) {
  return value === "owner-openkey" || value === "delegate-session" || value === "local-owner-key" || value === "unauthenticated";
}
function isOperatorType(value) {
  return value === "human" || value === "agent";
}
function isStoredProfile(value) {
  return isRecord(value) && isNonEmptyString(value.name) && isNonEmptyString(value.host) && typeof value.chainId === "number" && Number.isFinite(value.chainId) && isNonEmptyString(value.spaceName) && isNonEmptyString(value.did) && isNonEmptyString(value.createdAt) && isOptionalNonEmptyString(value.sessionDid) && isOptionalNonEmptyString(value.ownerDid) && isOptionalNonEmptyString(value.spaceId) && isOptionalPosture(value.posture) && isOptionalOperatorType(value.operatorType) && isOptionalAuthMethod(value.authMethod) && isOptionalNonEmptyString(value.defaultSpace) && isOptionalNonEmptyString(value.privateKey) && isOptionalNonEmptyString(value.address) && isOptionalNonEmptyString(value.openkeyHost);
}
function isRecord(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isNonEmptyString(value) {
  return typeof value === "string" && value.length > 0;
}
function isOptionalNonEmptyString(value) {
  return value === void 0 || isNonEmptyString(value);
}
function isOptionalPosture(value) {
  return value === void 0 || isPosture(value);
}
function isOptionalOperatorType(value) {
  return value === void 0 || isOperatorType(value);
}
function isOptionalAuthMethod(value) {
  return value === void 0 || value === "openkey" || value === "local";
}
function isCoherentProfile(profile) {
  if (profile.authMethod === "local") {
    return profile.posture === void 0 || profile.posture === "local-owner-key";
  }
  if (profile.posture === "local-owner-key") {
    return profile.authMethod === "local";
  }
  return true;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  resolveInvocationContext,
  resolveInvocationProfile,
  resolveInvocationProfileName,
  resolvePosture
});
//# sourceMappingURL=profile.cjs.map