import { p as parseJsoncObject } from "./jsonc-COxDkWRr.js";
import { aD as normalize, ak as join, aE as isAbsolute, ay as dirname } from "./fetch-virtual-server-BZi6n2Qk.js";
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 coercePort(value) {
  if (typeof value === "number" && Number.isInteger(value) && value > 0 && value <= 65535) {
    return value;
  }
  if (typeof value === "string" && value.trim()) {
    const parsed = Number(value);
    if (Number.isInteger(parsed) && parsed > 0 && parsed <= 65535) {
      return parsed;
    }
  }
  return null;
}
function stripTomlComment(line) {
  let result = "";
  let quote = null;
  let escaped = false;
  for (const char of line) {
    if (quote) {
      result += char;
      if (escaped) {
        escaped = false;
        continue;
      }
      if (char === "\\" && quote === '"') {
        escaped = true;
        continue;
      }
      if (char === quote) {
        quote = null;
      }
      continue;
    }
    if (char === '"' || char === "'") {
      quote = char;
      result += char;
      continue;
    }
    if (char === "#") {
      break;
    }
    result += char;
  }
  return result.trim();
}
function parseTomlString(rawValue) {
  const trimmed = rawValue.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 values = [];
  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 === "\\" && quote === '"') {
        escaped = true;
        continue;
      }
      if (char === quote) {
        quote = null;
      }
      continue;
    }
    if (char === '"' || char === "'") {
      quote = char;
      current += char;
      continue;
    }
    if (char === ",") {
      if (current.trim()) {
        values.push(current.trim());
      }
      current = "";
      continue;
    }
    current += char;
  }
  if (current.trim()) {
    values.push(current.trim());
  }
  return values;
}
function parseTomlValue(rawValue) {
  const trimmed = rawValue.trim();
  if (!trimmed) {
    return "";
  }
  if (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'")) {
    return parseTomlString(trimmed);
  }
  if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
    return splitTomlArrayItems(trimmed).map(parseTomlValue);
  }
  if (trimmed === "true") {
    return true;
  }
  if (trimmed === "false") {
    return false;
  }
  if (/^-?\d+$/.test(trimmed)) {
    return Number(trimmed);
  }
  if (/^-?\d+\.\d+$/.test(trimmed)) {
    return Number(trimmed);
  }
  return trimmed;
}
function parseTomlObject(source) {
  const root = {};
  let currentSection = [];
  const ensureSection = (segments) => {
    let cursor = root;
    for (const segment of segments) {
      const next = isRecord(cursor[segment]) ? cursor[segment] : {};
      cursor[segment] = next;
      cursor = next;
    }
    return cursor;
  };
  for (const rawLine of source.split(/\r?\n/)) {
    const line = stripTomlComment(rawLine);
    if (!line) {
      continue;
    }
    if (line.startsWith("[") && line.endsWith("]")) {
      currentSection = line.slice(1, -1).split(".").map((segment) => parseTomlString(segment)).map((segment) => segment.trim()).filter(Boolean);
      continue;
    }
    const match = line.match(/^([A-Za-z0-9_-]+)\s*=\s*(.+)$/);
    if (!match) {
      continue;
    }
    const key = match[1];
    const value = parseTomlValue(match[2]);
    const target = ensureSection(currentSection);
    target[key] = value;
  }
  return root;
}
function readRawConfig(vfs, filePath) {
  if (!vfs.existsSync(filePath)) {
    return null;
  }
  try {
    return String(vfs.readFileSync(filePath, "utf8"));
  } catch {
    return null;
  }
}
function mapConfig(raw, configPath, format) {
  const dev = isRecord(raw.dev) ? raw.dev : {};
  const vars = isRecord(raw.vars) ? raw.vars : {};
  return {
    path: configPath,
    directory: dirname(configPath),
    format,
    name: coerceString(raw.name),
    main: coerceString(raw.main),
    pagesBuildOutputDir: coerceString(raw.pages_build_output_dir),
    vars: { ...vars },
    dev: {
      port: coercePort(dev.port),
      ip: coerceString(dev.ip),
      localProtocol: dev.local_protocol === "http" || dev.local_protocol === "https" ? dev.local_protocol : null
    }
  };
}
function readWranglerConfig(vfs, cwd) {
  const normalizedCwd = normalize(cwd || "/");
  const candidates = [
    {
      filePath: join(normalizedCwd, "wrangler.jsonc"),
      format: "jsonc",
      parse: (source) => parseJsoncObject(source)
    },
    {
      filePath: join(normalizedCwd, "wrangler.json"),
      format: "json",
      parse: (source) => {
        try {
          return JSON.parse(source);
        } catch {
          return null;
        }
      }
    },
    {
      filePath: join(normalizedCwd, "wrangler.toml"),
      format: "toml",
      parse: (source) => parseTomlObject(source)
    }
  ];
  for (const candidate of candidates) {
    const rawText = readRawConfig(vfs, candidate.filePath);
    if (rawText == null) {
      continue;
    }
    const parsed = candidate.parse(rawText);
    if (parsed) {
      return mapConfig(parsed, candidate.filePath, candidate.format);
    }
  }
  return {
    path: null,
    directory: normalizedCwd,
    format: null,
    name: null,
    main: null,
    pagesBuildOutputDir: null,
    vars: {},
    dev: {
      port: null,
      ip: null,
      localProtocol: null
    }
  };
}
function resolveWranglerPath(baseDir, candidate) {
  return isAbsolute(candidate) ? normalize(candidate) : normalize(join(baseDir, candidate));
}
function resolveWranglerWorkerEntry(vfs, cwd, config = readWranglerConfig(vfs, cwd), explicitEntry) {
  const explicit = explicitEntry == null ? void 0 : explicitEntry.trim();
  if (explicit) {
    return resolveWranglerPath(cwd, explicit);
  }
  if (config.main) {
    return resolveWranglerPath(config.directory, config.main);
  }
  const candidates = [
    "src/index.ts",
    "src/index.tsx",
    "src/index.js",
    "src/index.jsx",
    "index.ts",
    "index.js",
    "worker.ts",
    "worker.js"
  ];
  for (const candidate of candidates) {
    const resolved = resolveWranglerPath(cwd, candidate);
    if (vfs.existsSync(resolved)) {
      return resolved;
    }
  }
  return null;
}
function resolveWranglerPagesDirectory(vfs, cwd, config = readWranglerConfig(vfs, cwd), explicitDir) {
  const explicit = explicitDir == null ? void 0 : explicitDir.trim();
  if (explicit) {
    return resolveWranglerPath(cwd, explicit);
  }
  if (config.pagesBuildOutputDir) {
    return resolveWranglerPath(config.directory, config.pagesBuildOutputDir);
  }
  const fallbackDirs = ["dist", "build", "public"];
  for (const candidate of fallbackDirs) {
    const resolved = resolveWranglerPath(cwd, candidate);
    if (vfs.existsSync(resolved)) {
      return resolved;
    }
  }
  return null;
}
export {
  readWranglerConfig,
  resolveWranglerPagesDirectory,
  resolveWranglerPath,
  resolveWranglerWorkerEntry
};
//# sourceMappingURL=wrangler-config-DvOMiRnI.js.map
