import { ak as join, ay as dirname, p as networkFetch, h as getDefaultNetworkController } from "./fetch-virtual-server-BZi6n2Qk.js";
const DEFAULT_CLOUDFLARE_API_BASE_URL = "https://api.cloudflare.com/client/v4";
const DEFAULT_CLOUDFLARE_AUTH_URL = "https://dash.cloudflare.com/oauth2/auth";
const DEFAULT_CLOUDFLARE_TOKEN_URL = "https://dash.cloudflare.com/oauth2/token";
const DEFAULT_CLOUDFLARE_REVOKE_URL = "https://dash.cloudflare.com/oauth2/revoke";
const DEFAULT_WRANGLER_CLIENT_ID = "54d11594-84e4-41aa-b438-e81b8fa78ee7";
const DEFAULT_WRANGLER_CALLBACK_HOST = "localhost";
const DEFAULT_WRANGLER_CALLBACK_PORT = 8976;
const WRANGLER_CALLBACK_PATH = "/oauth/callback";
const WRANGLER_CALLBACK_URL = `http://${DEFAULT_WRANGLER_CALLBACK_HOST}:${DEFAULT_WRANGLER_CALLBACK_PORT}${WRANGLER_CALLBACK_PATH}`;
const WRANGLER_LEGACY_AUTH_CONFIG_PATH = "/home/user/.wrangler/config/default.toml";
const WRANGLER_AUTH_CONFIG_PATH = "/home/user/.config/.wrangler/config/default.toml";
const DEFAULT_WRANGLER_OAUTH_SCOPES = [
  "account:read",
  "user:read",
  "workers:write",
  "workers_kv:write",
  "workers_routes:write",
  "workers_scripts:write",
  "workers_tail:read",
  "d1:write",
  "pages:write",
  "zone:read",
  "ssl_certs:write",
  "ai:write",
  "ai-search:write",
  "ai-search:run",
  "queues:write",
  "pipelines:write",
  "secrets_store:write",
  "artifacts:write",
  "flagship:write",
  "containers:write",
  "cloudchamber:write",
  "connectivity:admin",
  "email_routing:write",
  "email_sending:write",
  "browser:write"
];
let preparedCloudflareAuthPopup = null;
function withDefaultController() {
  return getDefaultNetworkController();
}
function isRecord(value) {
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function coerceString(value) {
  return typeof value === "string" && value.trim() ? value.trim() : null;
}
function ensureParentDir(vfs, filePath) {
  const parent = dirname(filePath);
  if (!vfs.existsSync(parent)) {
    vfs.mkdirSync(parent, { recursive: true });
  }
}
function parseTomlString(value) {
  const trimmed = value.trim();
  if (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'")) {
    if (trimmed.startsWith('"')) {
      try {
        return JSON.parse(trimmed);
      } catch {
        return trimmed.slice(1, -1);
      }
    }
    return trimmed.slice(1, -1).replace(/''/g, "'");
  }
  return trimmed;
}
function splitTomlArrayItems(rawValue) {
  const trimmed = rawValue.trim();
  if (!trimmed.startsWith("[") || !trimmed.endsWith("]")) {
    return [];
  }
  const items = [];
  let current = "";
  let quote = null;
  let escaped = false;
  for (const char of trimmed.slice(1, -1)) {
    if (quote) {
      current += char;
      if (escaped) {
        escaped = false;
        continue;
      }
      if (char === "\\") {
        escaped = true;
        continue;
      }
      if (char === quote) {
        quote = null;
      }
      continue;
    }
    if (char === '"' || char === "'") {
      quote = char;
      current += char;
      continue;
    }
    if (char === ",") {
      if (current.trim()) {
        items.push(current.trim());
      }
      current = "";
      continue;
    }
    current += char;
  }
  if (current.trim()) {
    items.push(current.trim());
  }
  return items;
}
function readTomlKey(rawText, key) {
  const matcher = new RegExp(`^${key}\\s*=\\s*(.+?)\\s*$`, "m");
  const match = rawText.match(matcher);
  if (!match) {
    return null;
  }
  return match[1] ?? null;
}
function getWranglerAuthCandidatePaths() {
  return [WRANGLER_LEGACY_AUTH_CONFIG_PATH, WRANGLER_AUTH_CONFIG_PATH];
}
function getPendingAuthCandidatePaths() {
  return [
    join(dirname(WRANGLER_LEGACY_AUTH_CONFIG_PATH), "pending-login.json"),
    join(dirname(WRANGLER_AUTH_CONFIG_PATH), "pending-login.json")
  ];
}
function readRawTextFile(vfs, filePath) {
  if (!vfs.existsSync(filePath)) {
    return "";
  }
  try {
    return String(vfs.readFileSync(filePath, "utf8"));
  } catch {
    return "";
  }
}
function writePendingAuthStateFile(vfs, state, filePath) {
  ensureParentDir(vfs, filePath);
  vfs.writeFileSync(filePath, JSON.stringify(state, null, 2));
}
function readPendingAuthStateFile(vfs, filePath) {
  if (!vfs.existsSync(filePath)) {
    return null;
  }
  try {
    const parsed = JSON.parse(vfs.readFileSync(filePath, "utf8"));
    if (!isRecord(parsed)) {
      return null;
    }
    const state = coerceString(parsed.state);
    const codeVerifier = coerceString(parsed.codeVerifier);
    const clientId = coerceString(parsed.clientId);
    const redirectUri = coerceString(parsed.redirectUri);
    const authUrl = coerceString(parsed.authUrl);
    const tokenUrl = coerceString(parsed.tokenUrl);
    const createdAt = typeof parsed.createdAt === "number" && Number.isFinite(parsed.createdAt) ? parsed.createdAt : Date.now();
    const scopes = Array.isArray(parsed.scopes) ? parsed.scopes.map((scope) => coerceString(scope)).filter(Boolean) : [];
    if (!state || !codeVerifier || !clientId || !redirectUri || !authUrl || !tokenUrl) {
      return null;
    }
    return {
      state,
      codeVerifier,
      clientId,
      redirectUri,
      authUrl,
      tokenUrl,
      createdAt,
      scopes
    };
  } catch {
    return null;
  }
}
function getCloudflareHeaders(auth, headers) {
  const next = new Headers(headers);
  if ("apiToken" in auth) {
    next.set("authorization", `Bearer ${auth.apiToken.trim()}`);
  } else {
    next.set("x-auth-key", auth.apiKey.trim());
    next.set("x-auth-email", auth.email.trim());
  }
  return next;
}
function createCloudflareApiError(fallbackMessage, error) {
  var _a;
  const message = ((_a = error == null ? void 0 : error.message) == null ? void 0 : _a.trim()) || fallbackMessage;
  const next = new Error(message);
  if (typeof (error == null ? void 0 : error.code) === "number") {
    next.code = error.code;
  }
  return next;
}
async function cloudflareFetch(url, init = {}) {
  return networkFetch(url, init, withDefaultController());
}
async function readCloudflareEnvelopeError(response, fallbackMessage) {
  try {
    const contentType = response.headers.get("content-type") ?? "";
    if (contentType.includes("application/json")) {
      const parsed = await response.json();
      if (isRecord(parsed)) {
        const envelope = parsed;
        const firstError = Array.isArray(envelope.errors) ? envelope.errors[0] : null;
        if (firstError) {
          return createCloudflareApiError(fallbackMessage, firstError);
        }
        if (typeof parsed.message === "string" && parsed.message.trim()) {
          return createCloudflareApiError(`${fallbackMessage}: ${parsed.message.trim()}`);
        }
      }
    } else {
      const text = (await response.text()).trim();
      if (text) {
        return createCloudflareApiError(`${fallbackMessage}: ${text}`);
      }
    }
  } catch {
  }
  return createCloudflareApiError(`${fallbackMessage}: ${response.status} ${response.statusText}`);
}
async function cloudflareApiFetchResult(apiBaseUrl, pathname, auth) {
  var _a;
  const response = await cloudflareFetch(
    `${normalizeCloudflareApiBaseUrl(apiBaseUrl)}${pathname.startsWith("/") ? pathname : `/${pathname}`}`,
    {
      headers: getCloudflareHeaders(auth)
    }
  );
  const contentType = response.headers.get("content-type") ?? "";
  const parsed = contentType.includes("application/json") ? await response.json() : null;
  if (!response.ok) {
    throw await readCloudflareEnvelopeError(response, `${pathname} failed`);
  }
  if (!parsed || parsed.success === false || parsed.result === void 0) {
    throw createCloudflareApiError(
      `${pathname} returned an invalid response`,
      (_a = parsed == null ? void 0 : parsed.errors) == null ? void 0 : _a[0]
    );
  }
  return parsed.result;
}
function encodeBase64Url(bytes) {
  const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
  let binary = "";
  for (const byte of view) {
    binary += String.fromCharCode(byte);
  }
  return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
}
function randomToken(length = 64) {
  const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
  const bytes = crypto.getRandomValues(new Uint8Array(length));
  let output = "";
  for (const byte of bytes) {
    output += alphabet[byte % alphabet.length];
  }
  return output;
}
function normalizeCloudflareApiBaseUrl(value) {
  const trimmed = value == null ? void 0 : value.trim();
  if (!trimmed) {
    return DEFAULT_CLOUDFLARE_API_BASE_URL;
  }
  return trimmed.replace(/\/+$/, "") || DEFAULT_CLOUDFLARE_API_BASE_URL;
}
function normalizeCloudflareAuthUrl(value) {
  const trimmed = value == null ? void 0 : value.trim();
  if (!trimmed) {
    return DEFAULT_CLOUDFLARE_AUTH_URL;
  }
  return trimmed.replace(/\/+$/, "") || DEFAULT_CLOUDFLARE_AUTH_URL;
}
function normalizeCloudflareTokenUrl(value) {
  const trimmed = value == null ? void 0 : value.trim();
  if (!trimmed) {
    return DEFAULT_CLOUDFLARE_TOKEN_URL;
  }
  return trimmed.replace(/\/+$/, "") || DEFAULT_CLOUDFLARE_TOKEN_URL;
}
function normalizeCloudflareRevokeUrl(value) {
  const trimmed = value == null ? void 0 : value.trim();
  if (!trimmed) {
    return DEFAULT_CLOUDFLARE_REVOKE_URL;
  }
  return trimmed.replace(/\/+$/, "") || DEFAULT_CLOUDFLARE_REVOKE_URL;
}
function readWranglerAuthConfig(vfs) {
  for (const filePath of getWranglerAuthCandidatePaths()) {
    if (!vfs.existsSync(filePath)) {
      continue;
    }
    const rawText = readRawTextFile(vfs, filePath);
    const accessToken = coerceString(parseTomlString(readTomlKey(rawText, "oauth_token") ?? ""));
    const refreshToken = coerceString(parseTomlString(readTomlKey(rawText, "refresh_token") ?? ""));
    const expirationTime = coerceString(parseTomlString(readTomlKey(rawText, "expiration_time") ?? ""));
    const scopesRaw = readTomlKey(rawText, "scopes");
    const scopes = scopesRaw ? splitTomlArrayItems(scopesRaw).map(parseTomlString).map((scope) => scope.trim()).filter(Boolean) : [];
    return {
      accessToken,
      refreshToken,
      expirationTime,
      scopes,
      path: filePath,
      rawText
    };
  }
  return {
    accessToken: null,
    refreshToken: null,
    expirationTime: null,
    scopes: [],
    path: null,
    rawText: ""
  };
}
function getPreferredWranglerAuthConfigPath(vfs) {
  if (vfs.existsSync(WRANGLER_LEGACY_AUTH_CONFIG_PATH)) {
    return WRANGLER_LEGACY_AUTH_CONFIG_PATH;
  }
  return WRANGLER_AUTH_CONFIG_PATH;
}
function getPreferredWranglerPendingAuthPath(vfs) {
  return join(
    dirname(getPreferredWranglerAuthConfigPath(vfs)),
    "pending-login.json"
  );
}
function writeWranglerAuthConfig(vfs, input) {
  var _a, _b;
  const filePath = getPreferredWranglerAuthConfigPath(vfs);
  const lines = [
    `oauth_token = ${JSON.stringify(input.accessToken.trim())}`,
    ((_a = input.refreshToken) == null ? void 0 : _a.trim()) ? `refresh_token = ${JSON.stringify(input.refreshToken.trim())}` : null,
    ((_b = input.expirationTime) == null ? void 0 : _b.trim()) ? `expiration_time = ${JSON.stringify(input.expirationTime.trim())}` : null,
    `scopes = ${JSON.stringify([...input.scopes ?? []])}`,
    ""
  ].filter((line) => line !== null);
  ensureParentDir(vfs, filePath);
  vfs.writeFileSync(filePath, lines.join("\n"));
}
function deleteWranglerAuthConfig(vfs) {
  let removed = false;
  for (const filePath of getWranglerAuthCandidatePaths()) {
    if (!vfs.existsSync(filePath)) {
      continue;
    }
    try {
      vfs.unlinkSync(filePath);
      removed = true;
    } catch {
    }
  }
  return removed;
}
function writePendingWranglerAuthState(vfs, state) {
  writePendingAuthStateFile(vfs, state, getPreferredWranglerPendingAuthPath(vfs));
}
function readPendingWranglerAuthState(vfs) {
  for (const filePath of getPendingAuthCandidatePaths()) {
    const state = readPendingAuthStateFile(vfs, filePath);
    if (state) {
      return state;
    }
  }
  return null;
}
function deletePendingWranglerAuthState(vfs) {
  let removed = false;
  for (const filePath of getPendingAuthCandidatePaths()) {
    if (!vfs.existsSync(filePath)) {
      continue;
    }
    try {
      vfs.unlinkSync(filePath);
      removed = true;
    } catch {
    }
  }
  return removed;
}
function cancelPreparedCloudflareAuthPopup() {
  if (!preparedCloudflareAuthPopup) {
    return;
  }
  try {
    preparedCloudflareAuthPopup.close();
  } catch {
  }
  preparedCloudflareAuthPopup = null;
}
function openCloudflareAuthWindow(url) {
  var _a, _b;
  const popup = preparedCloudflareAuthPopup;
  preparedCloudflareAuthPopup = null;
  if (popup && !popup.closed) {
    try {
      popup.location.href = url;
      (_a = popup.focus) == null ? void 0 : _a.call(popup);
      return;
    } catch {
      try {
        popup.close();
      } catch {
      }
    }
  }
  try {
    (_b = window.open) == null ? void 0 : _b.call(window, url, "_blank");
  } catch {
  }
}
async function createWranglerPkcePair() {
  const codeVerifier = randomToken(96);
  const digest = await crypto.subtle.digest(
    "SHA-256",
    new TextEncoder().encode(codeVerifier)
  );
  return {
    codeVerifier,
    codeChallenge: encodeBase64Url(digest),
    state: randomToken(48)
  };
}
function buildWranglerAuthorizationUrl(input) {
  const scopes = Array.from(/* @__PURE__ */ new Set([...input.scopes, "offline_access"]));
  const search = new URLSearchParams({
    response_type: "code",
    client_id: input.clientId.trim(),
    redirect_uri: WRANGLER_CALLBACK_URL,
    scope: scopes.join(" "),
    state: input.state.trim(),
    code_challenge: input.codeChallenge.trim(),
    code_challenge_method: "S256"
  });
  return `${normalizeCloudflareAuthUrl(input.authUrl)}?${search.toString()}`;
}
async function exchangeWranglerAuthorizationCode(input) {
  var _a;
  const body = new URLSearchParams({
    grant_type: "authorization_code",
    code: input.code.trim(),
    redirect_uri: ((_a = input.redirectUri) == null ? void 0 : _a.trim()) || WRANGLER_CALLBACK_URL,
    client_id: input.clientId.trim(),
    code_verifier: input.codeVerifier.trim()
  });
  const response = await cloudflareFetch(normalizeCloudflareTokenUrl(input.tokenUrl), {
    method: "POST",
    headers: {
      "content-type": "application/x-www-form-urlencoded"
    },
    body: body.toString()
  });
  const parsed = await response.json();
  if (!response.ok || typeof parsed.error === "string") {
    throw createCloudflareApiError(
      "Cloudflare OAuth code exchange failed",
      {
        message: coerceString(parsed.error_description) || coerceString(parsed.error) || void 0
      }
    );
  }
  const accessToken = coerceString(parsed.access_token);
  if (!accessToken) {
    throw new Error("Cloudflare did not return an access token.");
  }
  const expiresIn = typeof parsed.expires_in === "number" && Number.isFinite(parsed.expires_in) ? parsed.expires_in : null;
  const expirationTime = expiresIn !== null ? new Date(Date.now() + expiresIn * 1e3).toISOString() : null;
  return {
    accessToken,
    refreshToken: coerceString(parsed.refresh_token),
    expirationTime,
    scopes: typeof parsed.scope === "string" ? parsed.scope.split(/\s+/).map((scope) => scope.trim()).filter(Boolean) : []
  };
}
async function refreshWranglerAccessToken(input) {
  const body = new URLSearchParams({
    grant_type: "refresh_token",
    refresh_token: input.refreshToken.trim(),
    client_id: input.clientId.trim()
  });
  const response = await cloudflareFetch(normalizeCloudflareTokenUrl(input.tokenUrl), {
    method: "POST",
    headers: {
      "content-type": "application/x-www-form-urlencoded"
    },
    body: body.toString()
  });
  const parsed = await response.json();
  if (!response.ok || typeof parsed.error === "string") {
    throw createCloudflareApiError(
      "Cloudflare OAuth refresh failed",
      {
        message: coerceString(parsed.error_description) || coerceString(parsed.error) || void 0
      }
    );
  }
  const accessToken = coerceString(parsed.access_token);
  if (!accessToken) {
    throw new Error("Cloudflare did not return a refreshed access token.");
  }
  const expiresIn = typeof parsed.expires_in === "number" && Number.isFinite(parsed.expires_in) ? parsed.expires_in : null;
  const expirationTime = expiresIn !== null ? new Date(Date.now() + expiresIn * 1e3).toISOString() : null;
  return {
    accessToken,
    refreshToken: coerceString(parsed.refresh_token) || input.refreshToken.trim(),
    expirationTime,
    scopes: typeof parsed.scope === "string" ? parsed.scope.split(/\s+/).map((scope) => scope.trim()).filter(Boolean) : []
  };
}
async function revokeWranglerRefreshToken(input) {
  const body = new URLSearchParams({
    client_id: input.clientId.trim(),
    token_type_hint: "refresh_token",
    token: input.refreshToken.trim()
  });
  await cloudflareFetch(normalizeCloudflareRevokeUrl(input.revokeUrl), {
    method: "POST",
    headers: {
      "content-type": "application/x-www-form-urlencoded"
    },
    body: body.toString()
  }).catch(() => {
  });
}
async function fetchCloudflareCurrentUser(apiBaseUrl, auth) {
  const result = await cloudflareApiFetchResult(
    apiBaseUrl,
    "/user",
    auth
  );
  const firstName = coerceString(result.first_name);
  const lastName = coerceString(result.last_name);
  const name = [firstName, lastName].filter(Boolean).join(" ").trim() || null;
  return {
    id: coerceString(result.id),
    email: coerceString(result.email),
    name
  };
}
async function fetchCloudflareAccounts(apiBaseUrl, auth) {
  const result = await cloudflareApiFetchResult(
    apiBaseUrl,
    "/accounts",
    auth
  );
  return result.map((account) => ({
    id: coerceString(account.id) || "",
    name: coerceString(account.name) || ""
  })).filter((account) => account.id);
}
async function verifyCloudflareUserApiToken(apiBaseUrl, apiToken) {
  const result = await cloudflareApiFetchResult(
    apiBaseUrl,
    "/user/tokens/verify",
    { apiToken }
  );
  return {
    id: coerceString(result.id),
    status: coerceString(result.status),
    expiresOn: coerceString(result.expires_on),
    notBefore: coerceString(result.not_before)
  };
}
function isWranglerAccessTokenExpired(config) {
  if (!config.accessToken) {
    return true;
  }
  if (!config.expirationTime) {
    return false;
  }
  const expiration = Date.parse(config.expirationTime);
  if (Number.isNaN(expiration)) {
    return false;
  }
  return Date.now() >= expiration;
}
const WRANGLER_VERSION = "4.83.0";
const WRANGLER_DESKTOP_AUTH_TIMEOUT_MS = 18e4;
const DESKTOP_OAUTH_LOOPBACK_BRIDGE_KEY = Symbol.for(
  "almostnode.desktopOAuthLoopback"
);
const DESKTOP_CLOUDFLARE_SUCCESS_HTML = `<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Cloudflare authentication complete</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style>
      body {
        margin: 0;
        min-height: 100vh;
        display: grid;
        place-items: center;
        background: #0f172a;
        color: #e2e8f0;
        font: 16px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
      }
      main {
        max-width: 32rem;
        padding: 2rem;
        text-align: center;
      }
      h1 {
        margin: 0 0 0.75rem;
        font-size: 1.5rem;
      }
      p {
        margin: 0;
        color: #cbd5e1;
      }
    </style>
  </head>
  <body>
    <main>
      <h1>Cloudflare authentication complete</h1>
      <p>You can close this window and return to almostnode.</p>
    </main>
  </body>
</html>`;
function ok(stdout) {
  return { stdout, stderr: "", exitCode: 0 };
}
function err(stderr, exitCode = 1) {
  return { stdout: "", stderr, exitCode };
}
function envToRecord(env) {
  if (!env) {
    return {};
  }
  if (env instanceof Map) {
    return Object.fromEntries(env);
  }
  return env;
}
function signalAborted(signal) {
  return (signal == null ? void 0 : signal.aborted) === true;
}
function abortResult() {
  return err("wrangler: command aborted\n", 130);
}
function formatErrorMessage(error) {
  return error instanceof Error ? error.message : String(error);
}
function parseBooleanFlagValue(value) {
  const trimmed = value.trim().toLowerCase();
  if (trimmed === "true" || trimmed === "1" || trimmed === "yes") {
    return true;
  }
  if (trimmed === "false" || trimmed === "0" || trimmed === "no") {
    return false;
  }
  return null;
}
function parsePortValue(value) {
  if (!value) {
    return null;
  }
  const parsed = Number(value);
  if (!Number.isInteger(parsed) || parsed <= 0 || parsed > 65535) {
    return null;
  }
  return parsed;
}
function getDesktopOAuthLoopbackBridge() {
  const candidate = globalThis[DESKTOP_OAUTH_LOOPBACK_BRIDGE_KEY];
  if (!candidate) {
    return null;
  }
  if (typeof candidate.createSession !== "function" || typeof candidate.openExternal !== "function" || typeof candidate.waitForCallback !== "function") {
    return null;
  }
  return candidate;
}
async function persistKeychainState(keychain) {
  await (keychain == null ? void 0 : keychain.persistCurrentState().catch(() => {
  }));
}
function parseCommonFlags(args, ctx) {
  var _a, _b, _c;
  const env = envToRecord(ctx.env);
  const scopes = [...DEFAULT_WRANGLER_OAUTH_SCOPES];
  let apiUrl = normalizeCloudflareApiBaseUrl(
    env.CLOUDFLARE_API_BASE_URL || DEFAULT_CLOUDFLARE_API_BASE_URL
  );
  let authUrl = normalizeCloudflareAuthUrl(
    env.CLOUDFLARE_AUTH_URL || env.WRANGLER_AUTH_URL || DEFAULT_CLOUDFLARE_AUTH_URL
  );
  let tokenUrl = normalizeCloudflareTokenUrl(
    env.CLOUDFLARE_TOKEN_URL || env.WRANGLER_TOKEN_URL || DEFAULT_CLOUDFLARE_TOKEN_URL
  );
  let revokeUrl = normalizeCloudflareRevokeUrl(
    env.CLOUDFLARE_REVOKE_URL || env.WRANGLER_REVOKE_URL || DEFAULT_CLOUDFLARE_REVOKE_URL
  );
  let clientId = ((_a = env.CLOUDFLARE_OAUTH_CLIENT_ID) == null ? void 0 : _a.trim()) || ((_b = env.WRANGLER_CLIENT_ID) == null ? void 0 : _b.trim()) || DEFAULT_WRANGLER_CLIENT_ID;
  let callbackHost = ((_c = env.WRANGLER_CALLBACK_HOST) == null ? void 0 : _c.trim()) || DEFAULT_WRANGLER_CALLBACK_HOST;
  let callbackPort = parsePortValue(env.WRANGLER_CALLBACK_PORT) ?? DEFAULT_WRANGLER_CALLBACK_PORT;
  let browser = true;
  let scopesList = false;
  const rest = [];
  for (let index = 0; index < args.length; index += 1) {
    const arg = args[index];
    const next = args[index + 1];
    if (arg === "--api-url") {
      if (!next) return { apiUrl, authUrl, tokenUrl, revokeUrl, clientId, callbackHost, callbackPort, browser, scopesList, scopes, rest: [], error: "missing value for --api-url" };
      apiUrl = normalizeCloudflareApiBaseUrl(next);
      index += 1;
      continue;
    }
    if (arg.startsWith("--api-url=")) {
      apiUrl = normalizeCloudflareApiBaseUrl(arg.slice("--api-url=".length));
      continue;
    }
    if (arg === "--auth-url") {
      if (!next) return { apiUrl, authUrl, tokenUrl, revokeUrl, clientId, callbackHost, callbackPort, browser, scopesList, scopes, rest: [], error: "missing value for --auth-url" };
      authUrl = normalizeCloudflareAuthUrl(next);
      index += 1;
      continue;
    }
    if (arg.startsWith("--auth-url=")) {
      authUrl = normalizeCloudflareAuthUrl(arg.slice("--auth-url=".length));
      continue;
    }
    if (arg === "--token-url") {
      if (!next) return { apiUrl, authUrl, tokenUrl, revokeUrl, clientId, callbackHost, callbackPort, browser, scopesList, scopes, rest: [], error: "missing value for --token-url" };
      tokenUrl = normalizeCloudflareTokenUrl(next);
      index += 1;
      continue;
    }
    if (arg.startsWith("--token-url=")) {
      tokenUrl = normalizeCloudflareTokenUrl(arg.slice("--token-url=".length));
      continue;
    }
    if (arg === "--revoke-url") {
      if (!next) return { apiUrl, authUrl, tokenUrl, revokeUrl, clientId, callbackHost, callbackPort, browser, scopesList, scopes, rest: [], error: "missing value for --revoke-url" };
      revokeUrl = normalizeCloudflareRevokeUrl(next);
      index += 1;
      continue;
    }
    if (arg.startsWith("--revoke-url=")) {
      revokeUrl = normalizeCloudflareRevokeUrl(arg.slice("--revoke-url=".length));
      continue;
    }
    if (arg === "--client-id") {
      if (!next) return { apiUrl, authUrl, tokenUrl, revokeUrl, clientId, callbackHost, callbackPort, browser, scopesList, scopes, rest: [], error: "missing value for --client-id" };
      clientId = next.trim() || clientId;
      index += 1;
      continue;
    }
    if (arg.startsWith("--client-id=")) {
      clientId = arg.slice("--client-id=".length).trim() || clientId;
      continue;
    }
    if (arg === "--callback-host") {
      if (!next) return { apiUrl, authUrl, tokenUrl, revokeUrl, clientId, callbackHost, callbackPort, browser, scopesList, scopes, rest: [], error: "missing value for --callback-host" };
      callbackHost = next.trim() || callbackHost;
      index += 1;
      continue;
    }
    if (arg.startsWith("--callback-host=")) {
      callbackHost = arg.slice("--callback-host=".length).trim() || callbackHost;
      continue;
    }
    if (arg === "--callback-port") {
      const parsed = parsePortValue(next);
      if (parsed == null) return { apiUrl, authUrl, tokenUrl, revokeUrl, clientId, callbackHost, callbackPort, browser, scopesList, scopes, rest: [], error: "invalid --callback-port value" };
      callbackPort = parsed;
      index += 1;
      continue;
    }
    if (arg.startsWith("--callback-port=")) {
      const parsed = parsePortValue(arg.slice("--callback-port=".length));
      if (parsed == null) return { apiUrl, authUrl, tokenUrl, revokeUrl, clientId, callbackHost, callbackPort, browser, scopesList, scopes, rest: [], error: "invalid --callback-port value" };
      callbackPort = parsed;
      continue;
    }
    if (arg === "--browser") {
      if (next && !next.startsWith("-")) {
        const parsed = parseBooleanFlagValue(next);
        if (parsed == null) {
          return { apiUrl, authUrl, tokenUrl, revokeUrl, clientId, callbackHost, callbackPort, browser, scopesList, scopes, rest: [], error: "invalid value for --browser" };
        }
        browser = parsed;
        index += 1;
      } else {
        browser = true;
      }
      continue;
    }
    if (arg === "--no-browser") {
      browser = false;
      continue;
    }
    if (arg.startsWith("--browser=")) {
      const parsed = parseBooleanFlagValue(arg.slice("--browser=".length));
      if (parsed == null) {
        return { apiUrl, authUrl, tokenUrl, revokeUrl, clientId, callbackHost, callbackPort, browser, scopesList, scopes, rest: [], error: "invalid value for --browser" };
      }
      browser = parsed;
      continue;
    }
    if (arg === "--scopes-list") {
      scopesList = true;
      continue;
    }
    if (arg === "--scopes") {
      if (!next) return { apiUrl, authUrl, tokenUrl, revokeUrl, clientId, callbackHost, callbackPort, browser, scopesList, scopes, rest: [], error: "missing value for --scopes" };
      scopes.splice(0, scopes.length, ...next.split(/\s+/).map((value) => value.trim()).filter(Boolean));
      index += 1;
      continue;
    }
    if (arg.startsWith("--scopes=")) {
      scopes.splice(0, scopes.length, ...arg.slice("--scopes=".length).split(/\s+/).map((value) => value.trim()).filter(Boolean));
      continue;
    }
    rest.push(...args.slice(index));
    break;
  }
  return {
    apiUrl,
    authUrl,
    tokenUrl,
    revokeUrl,
    clientId,
    callbackHost,
    callbackPort,
    browser,
    scopesList,
    scopes,
    rest
  };
}
function getAuthFromEnv(ctx) {
  var _a, _b, _c;
  const env = envToRecord(ctx.env);
  const apiKey = (_a = env.CLOUDFLARE_API_KEY) == null ? void 0 : _a.trim();
  const email = (_b = env.CLOUDFLARE_EMAIL) == null ? void 0 : _b.trim();
  const apiToken = (_c = env.CLOUDFLARE_API_TOKEN) == null ? void 0 : _c.trim();
  if (apiKey && email) {
    return {
      type: "api_key",
      apiKey,
      email
    };
  }
  if (apiToken) {
    return {
      type: "api_token",
      token: apiToken
    };
  }
  return null;
}
function parseCallbackUrl(rawInput, expectedState) {
  const trimmed = rawInput.trim();
  let parsed;
  try {
    parsed = new URL(trimmed);
  } catch {
    if (trimmed.startsWith("/")) {
      parsed = new URL(trimmed, WRANGLER_CALLBACK_URL);
    } else if (trimmed.startsWith("?")) {
      parsed = new URL(`${WRANGLER_CALLBACK_URL}${trimmed}`);
    } else {
      throw new Error("Expected a full callback URL such as http://localhost:8976/oauth/callback?code=...");
    }
  }
  const returnedState = parsed.searchParams.get("state");
  if (!returnedState) {
    throw new Error("The pasted callback URL did not include a state parameter.");
  }
  if (returnedState !== expectedState) {
    throw new Error("The pasted callback URL did not match this Wrangler login request.");
  }
  const errorValue = parsed.searchParams.get("error");
  if (errorValue) {
    const description = parsed.searchParams.get("error_description");
    throw new Error(description || errorValue);
  }
  const code = parsed.searchParams.get("code");
  if (!code) {
    throw new Error("The pasted callback URL did not include an authorization code.");
  }
  return parsed;
}
function buildHelpText() {
  return 'wrangler - Cloudflare auth and local dev integration for almostnode\n\nSupported commands:\n  login                        Start the browser-based Cloudflare OAuth flow\n  login complete <url>         Finish a pending login with the localhost callback URL\n  logout                       Remove the saved Cloudflare auth state\n  whoami [--json]              Show the current Cloudflare identity\n  dev [entry]                  Run a local Workers-style dev server\n  pages dev [dir]              Run a local Pages-style static dev server\n  auth token [--json]          Print the current auth token details\n  auth whoami [--json]         Alias for `wrangler whoami`\n  auth login                   Alias for `wrangler login`\n  auth logout                  Alias for `wrangler logout`\n  auth complete <url>          Alias for `wrangler login complete`\n\nCommon flags:\n      --api-url <url>          Override the Cloudflare API base URL\n      --auth-url <url>         Override the Cloudflare OAuth authorization URL\n      --token-url <url>        Override the Cloudflare OAuth token URL\n      --revoke-url <url>       Override the Cloudflare OAuth revoke URL\n      --client-id <id>         Override the Wrangler OAuth client id\n      --browser[=bool]         Control whether login opens a browser window\n      --callback-host <host>   Listener host for advanced/manual login flows\n      --callback-port <port>   Listener port for advanced/manual login flows\n      --scopes "<list>"        Override the OAuth scopes requested during login\n';
}
function formatScopesList(scopes) {
  return `Available Wrangler OAuth scopes:
${scopes.map((scope) => `- ${scope}`).join("\n")}
`;
}
async function resolveStoredOauthAuth(vfs, options, keychain) {
  const config = readWranglerAuthConfig(vfs);
  if (!config.accessToken && !config.refreshToken) {
    return null;
  }
  if (config.accessToken && !isWranglerAccessTokenExpired(config)) {
    return {
      type: "oauth",
      token: config.accessToken,
      refreshToken: config.refreshToken,
      expirationTime: config.expirationTime,
      scopes: [...config.scopes]
    };
  }
  if (!config.refreshToken) {
    throw new Error("Stored Cloudflare OAuth credentials have expired. Run `wrangler login` again.");
  }
  const refreshed = await refreshWranglerAccessToken({
    clientId: options.clientId,
    refreshToken: config.refreshToken,
    tokenUrl: options.tokenUrl
  });
  const scopes = refreshed.scopes.length > 0 ? refreshed.scopes : config.scopes;
  writeWranglerAuthConfig(vfs, {
    accessToken: refreshed.accessToken,
    refreshToken: refreshed.refreshToken,
    expirationTime: refreshed.expirationTime,
    scopes
  });
  await persistKeychainState(keychain);
  return {
    type: "oauth",
    token: refreshed.accessToken,
    refreshToken: refreshed.refreshToken,
    expirationTime: refreshed.expirationTime,
    scopes
  };
}
async function resolveAuthSource(vfs, ctx, options, keychain) {
  return getAuthFromEnv(ctx) || resolveStoredOauthAuth(vfs, options, keychain);
}
async function resolveWhoami(vfs, ctx, options, keychain) {
  const auth = await resolveAuthSource(vfs, ctx, options, keychain);
  if (!auth) {
    return null;
  }
  if (auth.type === "api_key") {
    const accounts2 = await fetchCloudflareAccounts(options.apiUrl, {
      apiKey: auth.apiKey,
      email: auth.email
    });
    return {
      loggedIn: true,
      authType: "Global API Key",
      email: auth.email,
      accounts: accounts2,
      tokenPermissions: null
    };
  }
  if (auth.type === "api_token") {
    let authType = "User API Token";
    try {
      await verifyCloudflareUserApiToken(options.apiUrl, auth.token);
    } catch (error) {
      const code = error && typeof error === "object" && "code" in error ? error.code : null;
      if (code === 1e4) {
        authType = "Account API Token";
      } else {
        throw error;
      }
    }
    let email = null;
    try {
      email = (await fetchCloudflareCurrentUser(options.apiUrl, {
        apiToken: auth.token
      })).email;
    } catch (error) {
      const code = error && typeof error === "object" && "code" in error ? error.code : null;
      if (code !== 9109) {
        throw error;
      }
    }
    const accounts2 = await fetchCloudflareAccounts(options.apiUrl, {
      apiToken: auth.token
    });
    return {
      loggedIn: true,
      authType,
      email,
      accounts: accounts2,
      tokenPermissions: null
    };
  }
  const user = await fetchCloudflareCurrentUser(options.apiUrl, {
    apiToken: auth.token
  });
  const accounts = await fetchCloudflareAccounts(options.apiUrl, {
    apiToken: auth.token
  });
  return {
    loggedIn: true,
    authType: "OAuth Token",
    email: user.email,
    accounts,
    tokenPermissions: auth.scopes.length > 0 ? [...auth.scopes] : null
  };
}
function formatWhoamiText(result) {
  var _a;
  const lines = [];
  if (result.authType === "Account API Token" && ((_a = result.accounts[0]) == null ? void 0 : _a.name)) {
    lines.push(
      `You are logged in with an ${result.authType}, associated with the account ${result.accounts[0].name}.`
    );
  } else if (result.email) {
    lines.push(
      `You are logged in with an ${result.authType}, associated with the email ${result.email}.`
    );
  } else {
    lines.push(`You are logged in with an ${result.authType}.`);
  }
  if (result.accounts.length > 0) {
    lines.push("");
    lines.push("Accounts:");
    for (const account of result.accounts) {
      lines.push(`- ${account.name || "(unnamed)"} (${account.id})`);
    }
  }
  if (result.tokenPermissions && result.tokenPermissions.length > 0) {
    lines.push("");
    lines.push("Token Permissions:");
    for (const permission of result.tokenPermissions) {
      lines.push(`- ${permission}`);
    }
  }
  return `${lines.join("\n")}
`;
}
function formatLoginInstructions(authUrl) {
  return `Open this URL in your browser to authorize Wrangler:
${authUrl}

Cloudflare will redirect to ${WRANGLER_CALLBACK_URL}.
If that page fails to load, copy the full callback URL from the browser address bar and run:
  wrangler login complete "<callback-url>"
`;
}
function formatLoginSuccessMessage(email) {
  return email ? `Authentication complete.
Logged in to Cloudflare as ${email}
` : "Authentication complete.\nLogged in to Cloudflare.\n";
}
async function completePendingWranglerLogin(vfs, options, callbackUrlInput, keychain) {
  const pending = readPendingWranglerAuthState(vfs);
  if (!pending) {
    throw new Error(
      "No pending Wrangler browser login was found. Run `wrangler login` to start a new login flow."
    );
  }
  const callbackUrl = parseCallbackUrl(callbackUrlInput, pending.state);
  const exchange = await exchangeWranglerAuthorizationCode({
    clientId: pending.clientId || options.clientId,
    code: callbackUrl.searchParams.get("code") || "",
    codeVerifier: pending.codeVerifier,
    redirectUri: pending.redirectUri || WRANGLER_CALLBACK_URL,
    tokenUrl: pending.tokenUrl || options.tokenUrl
  });
  writeWranglerAuthConfig(vfs, {
    accessToken: exchange.accessToken,
    refreshToken: exchange.refreshToken,
    expirationTime: exchange.expirationTime,
    scopes: exchange.scopes.length > 0 ? exchange.scopes : pending.scopes
  });
  deletePendingWranglerAuthState(vfs);
  await persistKeychainState(keychain);
  let email = null;
  try {
    email = (await fetchCloudflareCurrentUser(options.apiUrl, {
      apiToken: exchange.accessToken
    })).email;
  } catch {
  }
  return { email };
}
async function runLoginCommand(args, ctx, vfs, keychain) {
  const resolved = parseCommonFlags(args, ctx);
  if (resolved.error) {
    cancelPreparedCloudflareAuthPopup();
    return err(`wrangler login: ${resolved.error}
`);
  }
  if (resolved.scopesList) {
    return ok(formatScopesList(resolved.scopes));
  }
  const envAuth = getAuthFromEnv(ctx);
  if ((envAuth == null ? void 0 : envAuth.type) === "api_token") {
    cancelPreparedCloudflareAuthPopup();
    return ok(
      "Using CLOUDFLARE_API_TOKEN from the environment. Unset it to log in via OAuth.\n"
    );
  }
  if ((envAuth == null ? void 0 : envAuth.type) === "api_key") {
    cancelPreparedCloudflareAuthPopup();
    return ok(
      "Using CLOUDFLARE_API_KEY and CLOUDFLARE_EMAIL from the environment. Unset them to log in via OAuth.\n"
    );
  }
  try {
    const existing = await resolveStoredOauthAuth(vfs, resolved, keychain);
    if (existing) {
      const identity = await resolveWhoami(vfs, ctx, resolved, keychain).catch(() => null);
      return ok(
        (identity == null ? void 0 : identity.email) ? `Already logged in to Cloudflare as ${identity.email}
  To re-authenticate, run: wrangler logout && wrangler login
` : "Already logged in to Cloudflare.\n  To re-authenticate, run: wrangler logout && wrangler login\n"
      );
    }
  } catch (error) {
    deleteWranglerAuthConfig(vfs);
    deletePendingWranglerAuthState(vfs);
    await persistKeychainState(keychain);
    return err(`wrangler login: ${formatErrorMessage(error)}
`);
  }
  const { codeVerifier, codeChallenge, state } = await createWranglerPkcePair();
  const authUrl = buildWranglerAuthorizationUrl({
    authUrl: resolved.authUrl,
    clientId: resolved.clientId,
    codeChallenge,
    scopes: resolved.scopes,
    state
  });
  writePendingWranglerAuthState(vfs, {
    authUrl: resolved.authUrl,
    clientId: resolved.clientId,
    codeVerifier,
    createdAt: Date.now(),
    redirectUri: WRANGLER_CALLBACK_URL,
    scopes: resolved.scopes,
    state,
    tokenUrl: resolved.tokenUrl
  });
  await persistKeychainState(keychain);
  const desktopLoopbackBridge = getDesktopOAuthLoopbackBridge();
  const canAutoCaptureDesktopCallback = resolved.browser && resolved.callbackPort === DEFAULT_WRANGLER_CALLBACK_PORT && (resolved.callbackHost === "localhost" || resolved.callbackHost === "127.0.0.1") && desktopLoopbackBridge;
  if (canAutoCaptureDesktopCallback && desktopLoopbackBridge) {
    let sessionId = null;
    try {
      const session = await desktopLoopbackBridge.createSession({
        callbackPath: WRANGLER_CALLBACK_PATH,
        preferredPort: DEFAULT_WRANGLER_CALLBACK_PORT
      });
      sessionId = session.sessionId;
      await desktopLoopbackBridge.openExternal({
        sessionId,
        url: authUrl
      });
      const { callbackUrl } = await desktopLoopbackBridge.waitForCallback({
        sessionId,
        timeoutMs: WRANGLER_DESKTOP_AUTH_TIMEOUT_MS,
        successHtml: DESKTOP_CLOUDFLARE_SUCCESS_HTML
      });
      const completed = await completePendingWranglerLogin(
        vfs,
        resolved,
        callbackUrl,
        keychain
      );
      return ok(formatLoginSuccessMessage(completed.email));
    } catch (error) {
      if (signalAborted(ctx.signal)) {
        return abortResult();
      }
      return err(
        `Cloudflare login failed: ${formatErrorMessage(error)}
` + formatLoginInstructions(authUrl)
      );
    }
  }
  if (!resolved.browser) {
    return ok(formatLoginInstructions(authUrl));
  }
  if (typeof window === "undefined") {
    return err(
      "wrangler login requires a browser environment. Re-run with `--browser=false` to print the login URL.\n"
    );
  }
  openCloudflareAuthWindow(authUrl);
  try {
    if (typeof window.alert === "function") {
      window.alert(
        `Finish the Cloudflare login in the browser tab that just opened.

Cloudflare will redirect to ${WRANGLER_CALLBACK_URL}.
When that page fails to load, copy the full callback URL from the browser address bar and paste it into the next prompt.

If the browser tab did not open, open this URL manually:
${authUrl}`
      );
    }
  } catch {
  }
  if (typeof window.prompt !== "function") {
    return ok(formatLoginInstructions(authUrl));
  }
  const pastedCallback = window.prompt(
    "Paste the full Cloudflare callback URL from the browser address bar after login completes:",
    ""
  );
  if (!(pastedCallback == null ? void 0 : pastedCallback.trim())) {
    return ok(formatLoginInstructions(authUrl));
  }
  try {
    const completed = await completePendingWranglerLogin(
      vfs,
      resolved,
      pastedCallback,
      keychain
    );
    return ok(formatLoginSuccessMessage(completed.email));
  } catch (error) {
    return err(`Cloudflare login failed: ${formatErrorMessage(error)}
`);
  }
}
async function runCompleteCommand(args, ctx, vfs, keychain) {
  var _a, _b;
  const resolved = parseCommonFlags(args, ctx);
  if (resolved.error) {
    return err(`wrangler login complete: ${resolved.error}
`);
  }
  const callbackUrl = ((_a = resolved.rest[0]) == null ? void 0 : _a.trim()) || (typeof window !== "undefined" && typeof window.prompt === "function" ? (_b = window.prompt(
    "Paste the full Cloudflare callback URL from the browser address bar after login completes:",
    ""
  )) == null ? void 0 : _b.trim() : "");
  if (!callbackUrl) {
    return err("wrangler login complete: missing callback URL\n");
  }
  try {
    const completed = await completePendingWranglerLogin(
      vfs,
      resolved,
      callbackUrl,
      keychain
    );
    return ok(formatLoginSuccessMessage(completed.email));
  } catch (error) {
    return err(`wrangler login complete: ${formatErrorMessage(error)}
`);
  }
}
async function runLogoutCommand(args, ctx, vfs, keychain) {
  const resolved = parseCommonFlags(args, ctx);
  if (resolved.error) {
    return err(`wrangler logout: ${resolved.error}
`);
  }
  const envAuth = getAuthFromEnv(ctx);
  const config = readWranglerAuthConfig(vfs);
  if (config.refreshToken) {
    await revokeWranglerRefreshToken({
      clientId: resolved.clientId,
      refreshToken: config.refreshToken,
      revokeUrl: resolved.revokeUrl
    });
  }
  const removed = deleteWranglerAuthConfig(vfs);
  const removedPending = deletePendingWranglerAuthState(vfs);
  if (removed || removedPending) {
    await persistKeychainState(keychain);
  }
  if ((envAuth == null ? void 0 : envAuth.type) === "api_token") {
    return ok(
      removed || removedPending ? "Removed saved Cloudflare login state. CLOUDFLARE_API_TOKEN is still set in the environment.\n" : "CLOUDFLARE_API_TOKEN is still set in the environment. Unset it to log out completely.\n"
    );
  }
  if ((envAuth == null ? void 0 : envAuth.type) === "api_key") {
    return ok(
      removed || removedPending ? "Removed saved Cloudflare login state. CLOUDFLARE_API_KEY and CLOUDFLARE_EMAIL are still set in the environment.\n" : "CLOUDFLARE_API_KEY and CLOUDFLARE_EMAIL are still set in the environment. Unset them to log out completely.\n"
    );
  }
  if (removed || removedPending) {
    return ok("Successfully logged out.\n");
  }
  return ok("Not logged in, exiting...\n");
}
async function runWhoamiCommand(args, ctx, vfs, keychain) {
  const resolved = parseCommonFlags(args, ctx);
  if (resolved.error) {
    return err(`wrangler whoami: ${resolved.error}
`);
  }
  let json = false;
  for (const arg of resolved.rest) {
    if (arg === "--json") {
      json = true;
      continue;
    }
    return err(`wrangler whoami: unknown argument '${arg}'
`);
  }
  try {
    const whoami = await resolveWhoami(vfs, ctx, resolved, keychain);
    if (!whoami) {
      if (json) {
        return { stdout: `${JSON.stringify({ loggedIn: false }, null, 2)}
`, stderr: "", exitCode: 1 };
      }
      return err("You are not authenticated. Please run `wrangler login`.\n");
    }
    if (json) {
      return ok(`${JSON.stringify(whoami, null, 2)}
`);
    }
    return ok(formatWhoamiText(whoami));
  } catch (error) {
    return err(`wrangler whoami: ${formatErrorMessage(error)}
`);
  }
}
async function runTokenCommand(args, ctx, vfs, keychain) {
  const resolved = parseCommonFlags(args, ctx);
  if (resolved.error) {
    return err(`wrangler auth token: ${resolved.error}
`);
  }
  let json = false;
  for (const arg of resolved.rest) {
    if (arg === "--json") {
      json = true;
      continue;
    }
    return err(`wrangler auth token: unknown argument '${arg}'
`);
  }
  try {
    const auth = await resolveAuthSource(vfs, ctx, resolved, keychain);
    if (!auth) {
      return err("Not logged in. Please run `wrangler login` to authenticate.\n");
    }
    if (auth.type === "api_key") {
      const payload2 = {
        type: "api_key",
        key: auth.apiKey,
        email: auth.email
      };
      if (json) {
        return ok(`${JSON.stringify(payload2, null, 2)}
`);
      }
      return err(
        "Cannot output a single token when using CLOUDFLARE_API_KEY and CLOUDFLARE_EMAIL.\nUse --json to get both key and email, or use CLOUDFLARE_API_TOKEN instead.\n"
      );
    }
    const payload = auth.type === "api_token" ? { type: "api_token", token: auth.token } : { type: "oauth", token: auth.token };
    if (json) {
      return ok(`${JSON.stringify(payload, null, 2)}
`);
    }
    return ok(`${payload.token}
`);
  } catch (error) {
    return err(`wrangler auth token: ${formatErrorMessage(error)}
`);
  }
}
async function runWranglerCommand(args, ctx, vfs, keychain) {
  if (signalAborted(ctx.signal)) {
    return abortResult();
  }
  const firstArg = args[0];
  if (!firstArg || firstArg === "help" || firstArg === "--help" || firstArg === "-h") {
    return ok(buildHelpText());
  }
  if (firstArg === "--version" || firstArg === "-v" || firstArg === "version") {
    return ok(`${WRANGLER_VERSION}
`);
  }
  if (firstArg === "login") {
    if (args[1] === "complete") {
      return runCompleteCommand(args.slice(2), ctx, vfs, keychain);
    }
    return runLoginCommand(args.slice(1), ctx, vfs, keychain);
  }
  if (firstArg === "logout") {
    return runLogoutCommand(args.slice(1), ctx, vfs, keychain);
  }
  if (firstArg === "whoami") {
    return runWhoamiCommand(args.slice(1), ctx, vfs, keychain);
  }
  if (firstArg === "auth") {
    const authCommand = args[1];
    if (!authCommand || authCommand === "help" || authCommand === "--help" || authCommand === "-h") {
      return ok(buildHelpText());
    }
    if (authCommand === "token") {
      return runTokenCommand(args.slice(2), ctx, vfs, keychain);
    }
    if (authCommand === "whoami") {
      return runWhoamiCommand(args.slice(2), ctx, vfs, keychain);
    }
    if (authCommand === "login") {
      return runLoginCommand(args.slice(2), ctx, vfs, keychain);
    }
    if (authCommand === "logout") {
      return runLogoutCommand(args.slice(2), ctx, vfs, keychain);
    }
    if (authCommand === "complete") {
      return runCompleteCommand(args.slice(2), ctx, vfs, keychain);
    }
    return err(`wrangler auth: unsupported subcommand '${authCommand}'
`);
  }
  if (firstArg === "dev" || firstArg === "pages") {
    return err(
      `wrangler ${args.join(" ")} is handled by the builtin dev-server integration and should not be delegated here.
`
    );
  }
  return err(`wrangler: unsupported command '${args.join(" ")}'
`);
}
export {
  runWranglerCommand
};
//# sourceMappingURL=wrangler-command-BADosYet.js.map
