import {
  analyzeTemplate,
  applyMigration,
  baseTemplateName,
  buildAuthoringReference,
  canEdit,
  contentTypeFor,
  createDiagnosticRegistry,
  deriveFields,
  hasRole,
  isVersionedTemplateName,
  loadComponents,
  loadTemplate,
  pendingMigrations,
  renderReferenceMarkdown,
  validateSite,
  workingStoreRoundTripDiagnostic
} from "./chunk-CBLBQP27.js";

// ../editor-api/src/scaffold.ts
var HOME_HTML = `<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>{title}</title>
    <link rel="stylesheet" href="/styles.css" />
  </head>
  <body>
    <main>
      <h1>{title}</h1>
      <div class="prose" data-type="richtext">{body}</div>
    </main>
  </body>
</html>
`;
var HOME_JSON = `${JSON.stringify(
  {
    template: "home",
    title: "Welcome",
    isPublished: true,
    fields: {
      body: "<p>This is your starter home page. Edit it in the nanoesis editor and click Publish to update your site.</p>"
    }
  },
  null,
  2
)}
`;
var STYLES_CSS = `:root {
  --ink: #1a1a2e;
  --muted: #555;
  --accent: #4f46e5;
  --max: 42rem;
  font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
  line-height: 1.6;
  color: var(--ink);
}

body {
  margin: 0;
}

main {
  max-width: var(--max);
  margin-inline: auto;
  padding: 1.5rem 1.25rem;
}

h1 {
  font-size: 2.25rem;
  letter-spacing: -0.01em;
  margin: 0 0 1rem;
}

.prose {
  font-size: 1.05rem;
}

a {
  color: var(--accent);
}
`;
var SCAFFOLD_FILES = {
  "templates/home.html": HOME_HTML,
  "public/styles.css": STYLES_CSS,
  "content/index.json": HOME_JSON
};

// ../editor-api/src/api.ts
var MAX_LOGO_BYTES = 1024 * 1024;
function requiredWriteRole(path) {
  const top = path.split("/")[0];
  if (top === "content") return "author";
  if (top === "templates" || top === "components" || top === "public") return "developer";
  return "admin";
}
function denyWrite(principal, path) {
  if (hasRole(principal, requiredWriteRole(path))) return null;
  return json(403, { ok: false, error: "your role cannot modify this path" });
}
function json(status, data) {
  return {
    status,
    headers: { "content-type": "application/json" },
    body: JSON.stringify(data)
  };
}
function methodNotAllowed() {
  return json(405, { ok: false, error: "POST only" });
}
function withDefaultHeaders(response) {
  const headers = { ...response.headers ?? {} };
  if (headers["cache-control"] === void 0) {
    headers["cache-control"] = "no-store";
    if (headers["vary"] === void 0) headers["vary"] = "Authorization";
  }
  return { ...response, headers };
}
var BEARER_PREFIX = /^Bearer\s+/i;
function bearerToken(getHeader) {
  const raw = getHeader("authorization") ?? getHeader("Authorization");
  if (raw === void 0) return void 0;
  const match = BEARER_PREFIX.exec(raw);
  return match ? raw.slice(match[0].length).trim() : void 0;
}
async function parseJsonBody(req) {
  const bytes = await req.body();
  if (bytes.byteLength === 0) return null;
  try {
    return JSON.parse(new TextDecoder().decode(bytes));
  } catch {
    return null;
  }
}
function isLoginRequest(value) {
  return typeof value === "object" && value !== null && typeof value["username"] === "string" && typeof value["password"] === "string";
}
function isChangePasswordRequest(value) {
  return typeof value === "object" && value !== null && typeof value["currentPassword"] === "string" && typeof value["newPassword"] === "string";
}
async function handleAuthRoute(deps, req) {
  const endpoints = deps.authEndpoints;
  if (endpoints === void 0) return void 0;
  switch (req.path) {
    case "/api/auth/state":
      return json(200, await endpoints.state());
    case "/api/login": {
      if (req.method !== "POST") return methodNotAllowed();
      const body = await parseJsonBody(req);
      if (!isLoginRequest(body)) {
        return json(400, { ok: false, error: "JSON body with username + password required" });
      }
      const result = await endpoints.login(body);
      if (result.ok) {
        return json(200, {
          ok: true,
          token: result.value.token,
          principal: result.value.principal,
          firstRunBootstrap: result.value.firstRunBootstrap
        });
      }
      return json(result.status, { ok: false, error: result.error });
    }
    case "/api/refresh": {
      if (req.method !== "POST") return methodNotAllowed();
      const token = bearerToken(req.getHeader);
      if (token === void 0) return json(401, { ok: false, error: "no token" });
      const result = await endpoints.refresh(token);
      if (result.ok) {
        return json(200, {
          ok: true,
          token: result.value.token,
          principal: result.value.principal
        });
      }
      return json(result.status, { ok: false, error: result.error });
    }
    case "/api/logout": {
      if (req.method !== "POST") return methodNotAllowed();
      const token = bearerToken(req.getHeader);
      await endpoints.logout(token ?? "");
      return json(200, { ok: true });
    }
    default:
      return void 0;
  }
}
function isObject(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
function fromAuthResult(result) {
  return result.ok ? json(200, result.value) : json(result.status, { ok: false, error: result.error });
}
async function handleUserAdminRoute(deps, req, caller) {
  const userAdmin = deps.userAdmin;
  if (userAdmin === void 0) {
    return json(404, { ok: false, error: "user management is not available on this host" });
  }
  if (!hasRole(caller, "admin")) {
    return json(403, { ok: false, error: "admin role required" });
  }
  const segments = req.path.slice("/api/users".length).split("/").filter((s) => s !== "");
  if (segments.length === 0) {
    if (req.method === "GET") return fromAuthResult(await userAdmin.listUsers());
    if (req.method === "POST") {
      const body = await parseJsonBody(req);
      if (!isObject(body)) return json(400, { ok: false, error: "JSON body required" });
      return fromAuthResult(await userAdmin.createUser(body));
    }
    return json(405, { ok: false, error: "method not allowed" });
  }
  const targetId = segments[0];
  if (segments.length === 2 && segments[1] === "password") {
    if (req.method !== "POST") return json(405, { ok: false, error: "method not allowed" });
    const body = await parseJsonBody(req);
    if (!isObject(body)) return json(400, { ok: false, error: "JSON body required" });
    return fromAuthResult(
      await userAdmin.resetPassword(targetId, body)
    );
  }
  if (segments.length === 1) {
    if (req.method === "PATCH") {
      const body = await parseJsonBody(req);
      if (!isObject(body)) return json(400, { ok: false, error: "JSON body required" });
      return fromAuthResult(
        await userAdmin.updateUser(caller.userId, targetId, body)
      );
    }
    if (req.method === "DELETE") {
      return fromAuthResult(await userAdmin.deleteUser(caller.userId, targetId));
    }
    return json(405, { ok: false, error: "method not allowed" });
  }
  return json(404, { ok: false, error: `Unknown API route: ${req.path}` });
}
async function handleDiagnosticsRoute(deps, req, caller) {
  const registry = deps.diagnostics;
  if (registry === void 0) {
    return json(404, { ok: false, error: "diagnostics are not available on this host" });
  }
  if (!hasRole(caller, "admin")) {
    return json(403, { ok: false, error: "admin role required" });
  }
  if (req.path === "/api/admin/diagnostics") {
    if (req.method !== "GET") return json(405, { ok: false, error: "method not allowed" });
    const findings = await registry.runAll({ store: deps.store });
    return json(200, { findings });
  }
  if (req.method !== "POST") return json(405, { ok: false, error: "method not allowed" });
  const body = await parseJsonBody(req);
  if (!isObject(body) || typeof body["id"] !== "string") {
    return json(400, { ok: false, error: "JSON body with repair id required" });
  }
  try {
    const findings = await registry.runRepair(body["id"], { store: deps.store });
    return json(200, { findings });
  } catch (error) {
    return json(400, { ok: false, error: error instanceof Error ? error.message : String(error) });
  }
}
async function handleMigrationsRoute(deps, req, caller) {
  if (req.path === "/api/migrations") {
    if (req.method !== "GET") return json(405, { ok: false, error: "method not allowed" });
    const result = await pendingMigrations(deps.store);
    return json(200, {
      items: result.items,
      byTemplate: Object.fromEntries(result.byTemplate)
    });
  }
  if (req.path === "/api/migrations/preview") {
    if (req.method !== "GET") return json(405, { ok: false, error: "method not allowed" });
    const itemPath2 = req.query.get("path") ?? "";
    if (itemPath2 === "") return json(400, { ok: false, error: "path query param required" });
    return previewMigration(deps, itemPath2);
  }
  if (req.method !== "POST") return json(405, { ok: false, error: "method not allowed" });
  void caller;
  const body = await parseJsonBody(req);
  if (!isObject(body) || typeof body["path"] !== "string" || !isObject(body["resolution"])) {
    return json(400, { ok: false, error: "JSON body { path, resolution } required" });
  }
  const itemPath = body["path"];
  const denied = denyWrite(caller, itemPath);
  if (denied) return denied;
  try {
    await applyMigration(deps.store, itemPath, normalizeResolution(body["resolution"]));
    const refreshed = await pendingMigrations(deps.store);
    return json(200, {
      ok: true,
      items: refreshed.items,
      byTemplate: Object.fromEntries(refreshed.byTemplate)
    });
  } catch (error) {
    return json(400, { ok: false, error: error instanceof Error ? error.message : String(error) });
  }
}
async function previewMigration(deps, itemPath) {
  let itemJson;
  try {
    itemJson = JSON.parse(await deps.store.readText(itemPath));
  } catch {
    return json(404, { ok: false, error: "item not found" });
  }
  const tplName = typeof itemJson["template"] === "string" ? itemJson["template"] : "";
  if (tplName === "") return json(400, { ok: false, error: "item has no template binding" });
  const baseTpl = tplName.replace(/@v\d+$/, "");
  const components = await loadComponents(deps.store).catch(() => /* @__PURE__ */ new Map());
  const currentHtml = await safeReadTemplate(deps.store, baseTpl);
  const currentFields = currentHtml === null ? [] : deriveFields(currentHtml, components).map((f) => f.name);
  let leftTpl = null;
  let leftHtml = null;
  if (tplName !== baseTpl) {
    leftTpl = tplName;
    leftHtml = await safeReadTemplate(deps.store, tplName);
  } else {
    const { bestFitSnapshot: pickBestFit } = await import("./index.js");
    const itemFields2 = Object.keys(
      typeof itemJson["fields"] === "object" && itemJson["fields"] !== null ? itemJson["fields"] : {}
    );
    const best = await pickBestFit(deps.store, baseTpl, itemFields2);
    if (best !== null) {
      leftTpl = best;
      leftHtml = await safeReadTemplate(deps.store, best);
    }
  }
  const measureTpl = tplName === baseTpl ? baseTpl : tplName;
  const measureHtml = tplName === baseTpl ? currentHtml : leftHtml;
  const measureFields = measureHtml === null ? [] : deriveFields(measureHtml, components).map((f) => f.name);
  const itemFields = typeof itemJson["fields"] === "object" && itemJson["fields"] !== null ? itemJson["fields"] : {};
  const orphans = Object.keys(itemFields).filter((name) => !measureFields.includes(name)).map((name) => ({ name, value: itemFields[name] }));
  void measureTpl;
  return json(200, {
    left: leftHtml === null ? null : { template: leftTpl, html: leftHtml },
    right: { template: baseTpl, html: currentHtml ?? "" },
    orphans,
    missing: [],
    currentTemplateFields: currentFields
  });
}
async function safeReadTemplate(store, name) {
  try {
    return await store.readText(`templates/${name}.html`);
  } catch {
    return null;
  }
}
function normalizeResolution(raw) {
  const drop = Array.isArray(raw["drop"]) ? raw["drop"].filter((v) => typeof v === "string") : [];
  const keep = Array.isArray(raw["keep"]) ? raw["keep"].filter((v) => typeof v === "string") : [];
  const rename2 = {};
  if (isObject(raw["rename"])) {
    for (const [from, to] of Object.entries(raw["rename"])) {
      if (typeof to === "string") rename2[from] = to;
    }
  }
  const fill = {};
  if (isObject(raw["fill"])) {
    for (const [name, value] of Object.entries(raw["fill"])) {
      if (typeof value === "string") fill[name] = value;
    }
  }
  return { drop, rename: rename2, keep, fill };
}
async function handleStampRoute(deps, req, caller) {
  if (req.method !== "POST") return json(405, { ok: false, error: "method not allowed" });
  if (!hasRole(caller, "developer")) {
    return json(403, { ok: false, error: "developer role required" });
  }
  const body = await parseJsonBody(req);
  if (!isObject(body) || typeof body["name"] !== "string" || body["kind"] !== "template" && body["kind"] !== "component") {
    return json(400, {
      ok: false,
      error: 'JSON body { name, kind: "template" | "component" } required'
    });
  }
  try {
    const record = await deps.store.stamp(body["name"], body["kind"]);
    return json(200, record);
  } catch (error) {
    return json(400, { ok: false, error: error instanceof Error ? error.message : String(error) });
  }
}
async function handleBrandingRoute(deps, req) {
  if (req.path !== "/api/branding" && req.path !== "/api/branding/logo") return void 0;
  const store = deps.branding;
  if (req.method === "GET") {
    if (req.path === "/api/branding") {
      if (store === void 0) return json(200, { name: null, logoUrl: null });
      const state = await store.get();
      const logoUrl = state.logo === null ? null : `/api/branding/logo?v=${state.logo.updatedAt}`;
      return json(200, { name: state.name, logoUrl });
    }
    const logo = store === void 0 ? null : await store.getLogo();
    if (logo === null) return { status: 404, body: "" };
    return {
      status: 200,
      headers: { "content-type": logo.contentType, "cache-control": "public, max-age=31536000" },
      body: logo.bytes
    };
  }
  if (store === void 0) {
    return json(404, { ok: false, error: "branding is not available on this host" });
  }
  if (!hasRole(await deps.identity.authenticate(req.getHeader), "admin")) {
    return json(403, { ok: false, error: "admin role required" });
  }
  if (req.path === "/api/branding") {
    if (req.method !== "PUT") return json(405, { ok: false, error: "method not allowed" });
    const body = await parseJsonBody(req);
    if (!isObject(body)) return json(400, { ok: false, error: "JSON body required" });
    const raw = body["name"];
    const name = typeof raw === "string" && raw.trim() !== "" ? raw.trim() : null;
    await store.setName(name);
    return json(200, { ok: true });
  }
  if (req.method === "POST") {
    const contentType = req.getHeader("content-type") ?? "";
    if (!contentType.startsWith("image/")) {
      return json(415, { ok: false, error: "logo must be an image" });
    }
    const bytes = await req.body();
    if (bytes.byteLength === 0) return json(400, { ok: false, error: "empty body" });
    if (bytes.byteLength > MAX_LOGO_BYTES) return json(413, { ok: false, error: "logo too large" });
    await store.setLogo(bytes, contentType);
    return json(200, { ok: true });
  }
  if (req.method === "DELETE") {
    await store.clearLogo();
    return json(200, { ok: true });
  }
  return json(405, { ok: false, error: "method not allowed" });
}
async function handleApi(deps, req) {
  return withDefaultHeaders(await dispatchApi(deps, req));
}
async function dispatchApi(deps, req) {
  const authResponse = await handleAuthRoute(deps, req);
  if (authResponse !== void 0) return authResponse;
  const brandingResponse = await handleBrandingRoute(deps, req);
  if (brandingResponse !== void 0) return brandingResponse;
  const principal = await deps.identity.authenticate(req.getHeader);
  if (!canEdit(principal)) {
    return json(401, { ok: false, error: "Unauthorized" });
  }
  if (req.path === "/api/users" || req.path.startsWith("/api/users/")) {
    return handleUserAdminRoute(deps, req, principal);
  }
  if (req.path === "/api/admin/diagnostics" || req.path === "/api/admin/diagnostics/repair") {
    return handleDiagnosticsRoute(deps, req, principal);
  }
  if (req.path === "/api/migrations" || req.path === "/api/migrations/preview" || req.path === "/api/migrations/apply") {
    return handleMigrationsRoute(deps, req, principal);
  }
  if (req.path === "/api/templates/stamp") {
    return handleStampRoute(deps, req, principal);
  }
  const get = (key) => req.query.get(key) ?? "";
  switch (req.path) {
    case "/api/list": {
      try {
        return json(200, await deps.store.list(get("dir")));
      } catch {
        return json(200, []);
      }
    }
    case "/api/read": {
      const path = get("path");
      try {
        const bytes = await deps.store.readBytes(path);
        return { status: 200, headers: { "content-type": contentTypeFor(path) }, body: bytes };
      } catch {
        return { status: 404, body: "" };
      }
    }
    case "/api/exists":
      return json(200, { exists: await deps.store.exists(get("path")) });
    case "/api/validate":
      return json(200, await validateSite(deps.store));
    case "/api/authors":
      return json(200, deps.authors ? await deps.authors() : []);
    case "/api/template-fields": {
      try {
        const [template, components] = await Promise.all([
          loadTemplate(deps.store, get("name")),
          loadComponents(deps.store)
        ]);
        return json(200, deriveFields(template, components));
      } catch {
        return { status: 404, body: "" };
      }
    }
    case "/api/write": {
      if (req.method !== "POST") return methodNotAllowed();
      const denied = denyWrite(principal, get("path"));
      if (denied) return denied;
      try {
        const result = await deps.store.write(get("path"), await req.body());
        return json(200, {
          ok: true,
          ...result.stamped !== void 0 && { stamped: result.stamped },
          ...result.stampIncomplete === true && { stampIncomplete: true },
          ...result.schemaDelta !== void 0 && { schemaDelta: result.schemaDelta },
          ...result.parseDiagnostics !== void 0 && {
            parseDiagnostics: result.parseDiagnostics
          }
        });
      } catch (error) {
        return json(500, { ok: false, error: String(error) });
      }
    }
    case "/api/delete": {
      if (req.method !== "POST") return methodNotAllowed();
      const denied = denyWrite(principal, get("path"));
      if (denied) return denied;
      try {
        await deps.store.delete(get("path"));
        return json(200, { ok: true });
      } catch (error) {
        return json(500, { ok: false, error: String(error) });
      }
    }
    case "/api/rename": {
      if (req.method !== "POST") return methodNotAllowed();
      const denied = denyWrite(principal, get("from")) ?? denyWrite(principal, get("to"));
      if (denied) return denied;
      const result = await deps.store.rename(get("from"), get("to"));
      if (result.ok) return json(200, { ok: true });
      const status = result.reason === "exists" ? 409 : 404;
      return json(status, { ok: false, error: result.reason });
    }
    case "/api/publish": {
      if (req.method !== "POST") return methodNotAllowed();
      const result = await deps.publish();
      if (result.ok) {
        return json(200, {
          ok: true,
          written: result.written.length,
          ...result.summary !== void 0 && { summary: result.summary }
        });
      }
      return json(422, {
        ok: false,
        errors: result.validation.errors.map((e) => e.message),
        ...result.summary !== void 0 && { summary: result.summary }
      });
    }
    case "/api/scaffold": {
      if (req.method !== "POST") return methodNotAllowed();
      if (!hasRole(principal, "admin")) {
        return json(403, { ok: false, error: "admin role required" });
      }
      if ((await deps.store.list("content")).length > 0) {
        return json(409, { ok: false, error: "site already has content" });
      }
      const created = [];
      const skipped = [];
      for (const [path, content] of Object.entries(SCAFFOLD_FILES)) {
        if (await deps.store.exists(path)) {
          skipped.push(path);
          continue;
        }
        await deps.store.write(path, new TextEncoder().encode(content));
        created.push(path);
      }
      return json(200, { ok: true, created, skipped });
    }
    case "/api/reconcile": {
      if (req.method !== "POST") return methodNotAllowed();
      if (deps.reconcile === void 0) {
        return json(404, { ok: false, error: "reconcile is not available on this host" });
      }
      const result = await deps.reconcile();
      return json(200, {
        ok: true,
        added: result.added.length,
        removed: result.removed.length,
        total: result.index.keys.length
      });
    }
    case "/api/me/password": {
      if (req.method !== "POST") return methodNotAllowed();
      if (deps.authEndpoints === void 0) {
        return json(404, { ok: false, error: "no credential provider configured" });
      }
      const body = await parseJsonBody(req);
      if (!isChangePasswordRequest(body)) {
        return json(400, {
          ok: false,
          error: "JSON body with currentPassword + newPassword required"
        });
      }
      const result = await deps.authEndpoints.changePassword(principal.userId, body);
      if (result.ok) return json(200, { ok: true, token: result.value.token });
      return json(result.status, { ok: false, error: result.error });
    }
    case "/api/me/token": {
      const endpoints = deps.authEndpoints;
      if (req.method === "POST") {
        if (endpoints?.createToken === void 0) {
          return json(404, { ok: false, error: "tokens are not available on this host" });
        }
        const result = await endpoints.createToken(principal.userId);
        return result.ok ? json(200, { ok: true, token: result.value.token, expiresAt: result.value.expiresAt }) : json(result.status, { ok: false, error: result.error });
      }
      if (req.method === "DELETE") {
        if (endpoints?.revokeTokens === void 0) {
          return json(404, { ok: false, error: "token revocation is not available" });
        }
        const result = await endpoints.revokeTokens(principal.userId);
        return result.ok ? json(200, { ok: true }) : json(result.status, { ok: false, error: result.error });
      }
      return json(405, { ok: false, error: "method not allowed" });
    }
    default:
      return json(404, { ok: false, error: `Unknown API route: ${req.path}` });
  }
}

// ../editor-api/src/authors.ts
function displayNameOf(user) {
  const explicit = user.displayName?.trim();
  return explicit !== void 0 && explicit !== "" ? explicit : user.username;
}
function authorOptions(users) {
  return users.map((user) => ({ name: displayNameOf(user), user: user.username })).sort((a, b) => a.name.localeCompare(b.name));
}
function authorDirectory(users) {
  const byUser = new Map(users.map((user) => [user.username, displayNameOf(user)]));
  return (user) => {
    const displayName = byUser.get(user);
    return displayName === void 0 ? void 0 : { displayName };
  };
}

// ../editor-api/src/mcp.ts
function str(args, key) {
  const value = args[key];
  return typeof value === "string" ? value : "";
}
function request(method, path, query, bodyText, token) {
  const body = bodyText === void 0 ? new Uint8Array() : new TextEncoder().encode(bodyText);
  return {
    method,
    path,
    query: new URLSearchParams(query),
    getHeader: (name) => name.toLowerCase() === "authorization" && token !== void 0 ? `Bearer ${token}` : void 0,
    body: async () => body
  };
}
var pathArg = {
  type: "string",
  description: 'Site-relative path with forward slashes, e.g. "content/blog/post.json".'
};
var TOOL_SPECS = [
  {
    name: "list_dir",
    description: "List the immediate children (files and folders) of a site directory. Use '' or omit for the site root; the top-level folders are content/ (pages), templates/, components/, and public/.",
    inputSchema: {
      type: "object",
      properties: {
        path: { type: "string", description: "Directory path, '' for the site root." }
      },
      additionalProperties: false
    },
    toRequest: (args, token) => request("GET", "/api/list", { dir: str(args, "path") }, void 0, token)
  },
  {
    name: "read_file",
    description: "Read a file's text contents (content JSON, a template/component's HTML, CSS, etc.). Reports an error if the file does not exist.",
    inputSchema: {
      type: "object",
      properties: { path: pathArg },
      required: ["path"],
      additionalProperties: false
    },
    toRequest: (args, token) => request("GET", "/api/read", { path: str(args, "path") }, void 0, token)
  },
  {
    name: "describe_template",
    description: "List the fields a template defines (name, type, label, whether required, length limits), so you know what a page using it needs. Pass the template name without its path or extension, e.g. 'article' for templates/article.html.",
    inputSchema: {
      type: "object",
      properties: {
        name: {
          type: "string",
          description: 'Template name without path or extension, e.g. "article".'
        }
      },
      required: ["name"],
      additionalProperties: false
    },
    toRequest: (args, token) => request("GET", "/api/template-fields", { name: str(args, "name") }, void 0, token)
  },
  {
    name: "write_file",
    description: "Create or overwrite a text file. content/ requires the author role; templates/, components/, and public/ require the developer role. Read the nanoesis://reference resource first for the authoring syntax. For template/component paths the response includes `schemaDelta` (added/removed/typeChanged fields) \u2014 if `typeChanged` contains `destructive: true` or `removed` is non-empty, an auto-stamp has been written and authored content may need migration, so surface to the user before further edits. For content/*.json writes the response may include `parseDiagnostics.unknownTopLevelKeys` \u2014 top-level keys the parser dropped because they are not system keys; content values belong under `fields` (system keys are case-sensitive: `isPublished`, not `IsPublished`). See the reference's 'Authoring guardrails for LLMs' section for the common pitfalls (notably: `data-*` annotations bind to the element, not the token inside it \u2014 moving a token out of its annotated container silently strips them).",
    inputSchema: {
      type: "object",
      properties: {
        path: pathArg,
        contents: { type: "string", description: "The full new text contents of the file." }
      },
      required: ["path", "contents"],
      additionalProperties: false
    },
    toRequest: (args, token) => request("POST", "/api/write", { path: str(args, "path") }, str(args, "contents"), token)
  },
  {
    name: "delete_path",
    description: "Delete a file or a whole folder subtree. Same role rules as write_file. Deleting a path that does not exist is a no-op.",
    inputSchema: {
      type: "object",
      properties: { path: pathArg },
      required: ["path"],
      additionalProperties: false
    },
    toRequest: (args, token) => request("POST", "/api/delete", { path: str(args, "path") }, void 0, token)
  },
  {
    name: "rename_path",
    description: "Move or rename a file or folder subtree. Refuses to overwrite an existing destination. Requires write rights at both the source and the destination. Renaming a template also requires updating every content item bound to the old name (the validation gate will catch unbound items on publish, but `list_pending_migrations` is the cheaper check).",
    inputSchema: {
      type: "object",
      properties: {
        from: { type: "string", description: "The current path." },
        to: { type: "string", description: "The new path." }
      },
      required: ["from", "to"],
      additionalProperties: false
    },
    toRequest: (args, token) => request(
      "POST",
      "/api/rename",
      { from: str(args, "from"), to: str(args, "to") },
      void 0,
      token
    )
  },
  {
    name: "validate",
    description: "Run the validation gate over the whole site and return its diagnostics, without publishing. Use it to check your work: errors would block a publish, warnings (e.g. length constraints) only inform.",
    inputSchema: { type: "object", properties: {}, additionalProperties: false },
    toRequest: (_args, token) => request("GET", "/api/validate", {}, void 0, token)
  },
  {
    name: "publish",
    description: "Compile and publish the whole site. Runs the validation gate first; if anything would break, it reports the problems and writes nothing.",
    inputSchema: { type: "object", properties: {}, additionalProperties: false },
    toRequest: (_args, token) => request("POST", "/api/publish", {}, void 0, token)
  },
  {
    name: "list_pending_migrations",
    description: "List content items whose JSON fields don't match their bound template's schema (orphan fields or missing required fields). Use this after a destructive template edit (you'll see a `stamped` record on write_file) to see what needs migrating, or any time to check site-wide drift.",
    inputSchema: { type: "object", properties: {}, additionalProperties: false },
    toRequest: (_args, token) => request("GET", "/api/migrations", {}, void 0, token)
  },
  {
    name: "preview_migration",
    description: 'For one content item, return the current template HTML, the best-fit snapshot HTML (the "before"), the list of orphan fields with their values, and the names of fields the current template defines. Use this to plan how to migrate (drop, rename, or keep each orphan).',
    inputSchema: {
      type: "object",
      properties: { path: pathArg },
      required: ["path"],
      additionalProperties: false
    },
    toRequest: (args, token) => request("GET", "/api/migrations/preview", { path: str(args, "path") }, void 0, token)
  },
  {
    name: "apply_migration",
    description: "Resolve a content item's schema drift in one go. `resolution` is a JSON object: `drop` (array of orphan field names to delete), `rename` (object mapping orphan field name \u2192 current template field name to copy the value into), `keep` (array of orphan field names to leave untouched), and `fill` (object mapping current template field name \u2192 value, for missing required fields). Returns the refreshed pending list.",
    inputSchema: {
      type: "object",
      properties: {
        path: pathArg,
        resolution: {
          type: "string",
          description: 'A JSON object encoded as a string: { "drop": string[], "rename": { from: to }, "keep": string[], "fill": { name: value } }.'
        }
      },
      required: ["path", "resolution"],
      additionalProperties: false
    },
    toRequest: (args, token) => request(
      "POST",
      "/api/migrations/apply",
      {},
      JSON.stringify({
        path: str(args, "path"),
        resolution: parseResolutionArg(str(args, "resolution"))
      }),
      token
    )
  }
];
function parseResolutionArg(raw) {
  if (raw === "") return {};
  try {
    return JSON.parse(raw);
  } catch {
    return {};
  }
}
var MCP_TOOLS = TOOL_SPECS.map(
  ({ name, description, inputSchema }) => ({ name, description, inputSchema })
);
function toResult(response) {
  const text = typeof response.body === "string" ? response.body : response.body === void 0 ? "" : new TextDecoder().decode(response.body);
  return { text, isError: response.status >= 400 };
}
async function callMcpTool(deps, name, args = {}, options = {}) {
  const spec = TOOL_SPECS.find((tool) => tool.name === name);
  if (spec === void 0) return { text: `Unknown tool: ${name}`, isError: true };
  return toResult(await handleApi(deps, spec.toRequest(args, options.token)));
}
var REFERENCE_URI = "nanoesis://reference";
var MCP_RESOURCES = [
  {
    uri: REFERENCE_URI,
    name: "nanoesis authoring reference",
    description: "The generated reference for nanoesis templates and content: tokens, field types, annotations, loops, components, and the document shell. Read this before writing templates or content.",
    mimeType: "text/markdown"
  }
];
function readMcpResource(uri) {
  if (uri === REFERENCE_URI) {
    return { text: renderReferenceMarkdown(buildAuthoringReference()), mimeType: "text/markdown" };
  }
  return void 0;
}

// ../editor-api/src/diagnose.ts
function buildDefaultDiagnostics() {
  const registry = createDiagnosticRegistry();
  registry.add(workingStoreRoundTripDiagnostic);
  registry.add(homeTemplateMissingDiagnostic);
  registry.add(noPublishedContentDiagnostic);
  registry.add(templateSnapshotIntegrityDiagnostic);
  registry.add(templateSuffixConflictDiagnostic);
  registry.add(pendingMigrationsDiagnostic);
  registry.addRepair(recreateHomeTemplateRepair);
  registry.addRepair(rebindItemToCurrentRepair);
  registry.addRepair(copySnapshotToCurrentRepair);
  return registry;
}
var HOME_PATH = "templates/home.html";
var homeTemplateMissingDiagnostic = {
  id: "content.home-template",
  async run({ store }) {
    if (await store.exists(HOME_PATH)) return [];
    return [
      {
        id: "content.home-template.missing",
        source: "content",
        severity: "error",
        title: "Home template is missing",
        detail: `The locked path ${HOME_PATH} does not exist. Without it, the editor cannot render the home page and publishing will fail to compile the index. Recreate it from the bundled scaffold to restore the working state.`,
        repair: { id: "content.home-template.recreate", label: "Recreate home template" }
      }
    ];
  }
};
var recreateHomeTemplateRepair = {
  id: "content.home-template.recreate",
  async run({ store }) {
    if (await store.exists(HOME_PATH)) return;
    const bytes = new TextEncoder().encode(SCAFFOLD_FILES[HOME_PATH]);
    await store.write(HOME_PATH, bytes);
  }
};
var noPublishedContentDiagnostic = {
  id: "content.no-published-content",
  async run({ store }) {
    const published = await anyPublishedContentItem(store);
    if (published) return [];
    return [
      {
        id: "content.no-published-content",
        source: "content",
        severity: "warning",
        title: "Nothing is published",
        detail: "No content item has isPublished: true, so a publish would produce no pages. Open a content item and toggle Published, then publish again."
      }
    ];
  }
};
var templateSnapshotIntegrityDiagnostic = {
  id: "templates.snapshot-integrity",
  async run({ store }) {
    const findings = [];
    const components = await loadComponents(store).catch(() => /* @__PURE__ */ new Map());
    const items = await collectContentItems(store);
    const snapshotCache = /* @__PURE__ */ new Map();
    for (const item of items) {
      if (!isVersionedTemplateName(item.template)) continue;
      const kind = "template";
      const path = `${kind === "template" ? "templates" : "components"}/${item.template}.html`;
      let state = snapshotCache.get(path);
      if (state === void 0) {
        state = await classifySnapshot(store, path, components);
        snapshotCache.set(path, state);
      }
      if (state === "ok") continue;
      const isMissing = state === "missing";
      findings.push({
        id: `templates.${isMissing ? "missing" : "corrupt"}-snapshot:${item.path}`,
        source: "templates",
        severity: "error",
        title: isMissing ? `Pinned snapshot missing: ${path}` : `Pinned snapshot will not parse: ${path}`,
        detail: isMissing ? `${item.path} pins to ${item.template}, but ${path} does not exist. Restore the snapshot from git/backup, or rebind this item to the current template (its fields will need migration after).` : `${item.path} pins to ${item.template}, but ${path} cannot be parsed as a template. Restore valid bytes from git/backup, or rebind this item to the current template.`,
        repair: {
          id: "templates.rebind-item-to-current",
          label: "Rebind item to current template",
          args: { itemPath: item.path }
        }
      });
    }
    return findings;
  }
};
var rebindItemToCurrentRepair = {
  id: "templates.rebind-item-to-current",
  async run({ store }, args) {
    const itemPath = args["itemPath"];
    if (typeof itemPath !== "string" || itemPath === "") {
      throw new Error("rebind-item-to-current: missing itemPath arg");
    }
    const text = await store.readText(itemPath);
    const data = JSON.parse(text);
    if (typeof data !== "object" || data === null) {
      throw new Error(`rebind-item-to-current: ${itemPath} is not a JSON object`);
    }
    const obj = data;
    if (typeof obj.template !== "string" || !isVersionedTemplateName(obj.template)) {
      return;
    }
    obj.template = baseTemplateName(obj.template);
    const next = `${JSON.stringify(obj, null, 2)}
`;
    await store.write(itemPath, new TextEncoder().encode(next));
  }
};
var templateSuffixConflictDiagnostic = {
  id: "templates.suffix-conflict",
  async run({ store }) {
    const findings = [];
    for (const dir of ["templates", "components"]) {
      let entries;
      try {
        entries = await store.list(dir);
      } catch {
        continue;
      }
      const seenBases = /* @__PURE__ */ new Set();
      const snapshots = [];
      for (const entry of entries) {
        if (entry.kind !== "file" || !entry.name.endsWith(".html")) continue;
        const stem = entry.name.slice(0, -".html".length);
        if (isVersionedTemplateName(stem)) {
          snapshots.push({ base: baseTemplateName(stem), snapshotPath: `${dir}/${entry.name}` });
        } else {
          seenBases.add(stem);
        }
      }
      for (const snap of snapshots) {
        if (seenBases.has(snap.base)) continue;
        const currentPath = `${dir}/${snap.base}.html`;
        findings.push({
          id: `templates.suffix-conflict:${snap.snapshotPath}`,
          source: "templates",
          severity: "warning",
          title: `Snapshot has no current sibling: ${snap.snapshotPath}`,
          detail: `${snap.snapshotPath} exists but ${currentPath} does not. Promote the snapshot to current with "Copy snapshot to current", or rename the snapshot off the @v<N> suffix if it was named this way by mistake.`,
          repair: {
            id: "templates.copy-snapshot-to-current",
            label: "Copy snapshot to current",
            args: { snapshotPath: snap.snapshotPath, currentPath }
          }
        });
      }
    }
    return findings;
  }
};
var copySnapshotToCurrentRepair = {
  id: "templates.copy-snapshot-to-current",
  async run({ store }, args) {
    const snapshotPath = args["snapshotPath"];
    const currentPath = args["currentPath"];
    if (typeof snapshotPath !== "string" || typeof currentPath !== "string") {
      throw new Error("copy-snapshot-to-current: missing snapshotPath or currentPath args");
    }
    if (await store.exists(currentPath)) return;
    const bytes = await store.readBytes(snapshotPath);
    await store.write(currentPath, bytes);
  }
};
var pendingMigrationsDiagnostic = {
  id: "content.pending-migrations",
  async run({ store }) {
    const components = await loadComponents(store).catch(() => /* @__PURE__ */ new Map());
    const items = await collectContentItems(store);
    const templateFieldCache = /* @__PURE__ */ new Map();
    let pendingCount = 0;
    for (const item of items) {
      if (isVersionedTemplateName(item.template)) continue;
      let expected = templateFieldCache.get(item.template);
      if (expected === void 0) {
        const path = `templates/${item.template}.html`;
        try {
          const html = await store.readText(path);
          expected = new Set(deriveFields(html, components).map((f) => f.name));
        } catch {
          expected = /* @__PURE__ */ new Set();
        }
        templateFieldCache.set(item.template, expected);
      }
      const orphans = Object.keys(item.fields).filter((k) => !expected.has(k));
      if (orphans.length > 0) pendingCount += 1;
    }
    if (pendingCount === 0) return [];
    return [
      {
        id: "content.pending-migrations",
        source: "content",
        severity: "warning",
        title: `${pendingCount} item${pendingCount === 1 ? "" : "s"} pending migration`,
        detail: `${pendingCount} content item${pendingCount === 1 ? "" : "s"} ${pendingCount === 1 ? "has" : "have"} fields not rendered by ${pendingCount === 1 ? "its" : "their"} current template. The Migrations workspace (shipping in Phase 2 of versioning) will resolve these; for now, edit the item JSON to drop or rename the orphan fields. The site continues to publish \u2014 drift is a soft warning, not a publish blocker.`
      }
    ];
  }
};
async function collectContentItems(store, dir = "content") {
  const out = [];
  let entries;
  try {
    entries = await store.list(dir);
  } catch {
    return out;
  }
  for (const entry of entries) {
    const path = dir === "" ? entry.name : `${dir}/${entry.name}`;
    if (entry.kind === "dir") {
      out.push(...await collectContentItems(store, path));
      continue;
    }
    if (!entry.name.endsWith(".json") || entry.name.startsWith("_")) continue;
    let data;
    try {
      data = JSON.parse(await store.readText(path));
    } catch {
      continue;
    }
    if (typeof data !== "object" || data === null) continue;
    const obj = data;
    const template = obj["template"];
    if (typeof template !== "string") continue;
    const fields = obj["fields"];
    out.push({
      path,
      template,
      fields: typeof fields === "object" && fields !== null ? fields : {}
    });
  }
  return out;
}
async function classifySnapshot(store, path, components) {
  if (!await store.exists(path)) return "missing";
  try {
    const html = await store.readText(path);
    if (html.trim() === "") return "corrupt";
    analyzeTemplate(html, components);
    return "ok";
  } catch {
    return "corrupt";
  }
}
async function anyPublishedContentItem(store, dir = "content") {
  let entries;
  try {
    entries = await store.list(dir);
  } catch {
    return false;
  }
  for (const entry of entries) {
    const path = dir === "" ? entry.name : `${dir}/${entry.name}`;
    if (entry.kind === "dir") {
      if (await anyPublishedContentItem(store, path)) return true;
      continue;
    }
    if (!entry.name.endsWith(".json")) continue;
    try {
      const text = await store.readText(path);
      const data = JSON.parse(text);
      if (typeof data === "object" && data !== null && data.isPublished === true) {
        return true;
      }
    } catch {
    }
  }
  return false;
}

// ../editor-api/src/branding.ts
import { mkdir, readFile, rename, rm, writeFile } from "fs/promises";
import { dirname, join } from "path";
var EMPTY = { name: null, logo: null };
var InMemoryBrandingStore = class {
  constructor(now = Date.now) {
    this.now = now;
  }
  now;
  name = null;
  logo = null;
  logoUpdatedAt = 0;
  async get() {
    return {
      name: this.name,
      logo: this.logo === null ? null : { contentType: this.logo.contentType, updatedAt: this.logoUpdatedAt }
    };
  }
  async getLogo() {
    return this.logo;
  }
  async setName(name) {
    this.name = name;
  }
  async setLogo(bytes, contentType) {
    this.logo = { bytes, contentType };
    this.logoUpdatedAt = this.now();
  }
  async clearLogo() {
    this.logo = null;
  }
};
var FileBrandingStore = class {
  constructor(metaPath, now = Date.now) {
    this.metaPath = metaPath;
    this.now = now;
    this.logoPath = join(dirname(metaPath), "branding-logo");
  }
  metaPath;
  now;
  logoPath;
  async loadMeta() {
    try {
      const raw = await readFile(this.metaPath, "utf8");
      const text = raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw;
      const parsed = JSON.parse(text);
      return {
        name: typeof parsed.name === "string" ? parsed.name : null,
        logo: parsed.logo && typeof parsed.logo.contentType === "string" ? {
          contentType: parsed.logo.contentType,
          updatedAt: Number(parsed.logo.updatedAt) || 0
        } : null
      };
    } catch (error) {
      if (error.code === "ENOENT") return EMPTY;
      throw error;
    }
  }
  async saveMeta(state) {
    await mkdir(dirname(this.metaPath), { recursive: true });
    const tmp = `${this.metaPath}.tmp`;
    await writeFile(tmp, JSON.stringify(state, null, 2), "utf8");
    await rename(tmp, this.metaPath);
  }
  async get() {
    return this.loadMeta();
  }
  async getLogo() {
    const meta = await this.loadMeta();
    if (meta.logo === null) return null;
    try {
      const bytes = await readFile(this.logoPath);
      return { bytes: new Uint8Array(bytes), contentType: meta.logo.contentType };
    } catch (error) {
      if (error.code === "ENOENT") return null;
      throw error;
    }
  }
  async setName(name) {
    const meta = await this.loadMeta();
    await this.saveMeta({ name, logo: meta.logo });
  }
  async setLogo(bytes, contentType) {
    const meta = await this.loadMeta();
    await mkdir(dirname(this.logoPath), { recursive: true });
    const tmp = `${this.logoPath}.tmp`;
    await writeFile(tmp, bytes);
    await rename(tmp, this.logoPath);
    await this.saveMeta({ name: meta.name, logo: { contentType, updatedAt: this.now() } });
  }
  async clearLogo() {
    const meta = await this.loadMeta();
    await rm(this.logoPath, { force: true });
    await this.saveMeta({ name: meta.name, logo: null });
  }
};

export {
  SCAFFOLD_FILES,
  handleApi,
  authorOptions,
  authorDirectory,
  MCP_TOOLS,
  callMcpTool,
  MCP_RESOURCES,
  readMcpResource,
  buildDefaultDiagnostics,
  homeTemplateMissingDiagnostic,
  recreateHomeTemplateRepair,
  noPublishedContentDiagnostic,
  templateSnapshotIntegrityDiagnostic,
  rebindItemToCurrentRepair,
  templateSuffixConflictDiagnostic,
  copySnapshotToCurrentRepair,
  pendingMigrationsDiagnostic,
  InMemoryBrandingStore,
  FileBrandingStore
};
