@thallylabs/mcp 0.7.1 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.js +67 -918
  2. package/dist/tools.js +67 -918
  3. package/package.json +2 -1
package/dist/index.js CHANGED
@@ -536,867 +536,15 @@ async function handleUpdatePage(input) {
536
536
 
537
537
  // src/tools/migrate-docs.ts
538
538
  import { z as z6 } from "zod";
539
-
540
- // src/lib/migrate/index.ts
541
- import { mkdirSync as mkdirSync3, copyFileSync, writeFileSync as writeFileSync5, existsSync as existsSync6, mkdtempSync, rmSync } from "fs";
542
- import { join as join7, dirname as dirname2, resolve as resolve2 } from "path";
543
- import { tmpdir } from "os";
544
- import { execSync as execSync3 } from "child_process";
545
- import pLimit from "p-limit";
546
-
547
- // src/lib/migrate/github.ts
548
- import { execSync as execSync2 } from "child_process";
549
- import { readdirSync as readdirSync2, statSync } from "fs";
550
- import { join as join5, relative, extname, basename } from "path";
551
- var OPENAPI_FILENAMES = [
552
- "openapi.json",
553
- "openapi.yaml",
554
- "openapi.yml",
555
- "swagger.json",
556
- "swagger.yaml",
557
- "swagger.yml"
558
- ];
559
- function detectOpenApiSpec(cloneDir) {
560
- return findOpenApiSpec(cloneDir, 0);
561
- }
562
- function findOpenApiSpec(dir, depth) {
563
- if (depth > 3) return null;
564
- let entries;
565
- try {
566
- entries = readdirSync2(dir);
567
- } catch {
568
- return null;
569
- }
570
- for (const filename of OPENAPI_FILENAMES) {
571
- if (entries.includes(filename)) {
572
- return { absPath: join5(dir, filename), filename };
573
- }
574
- }
575
- for (const entry of entries) {
576
- if (entry.startsWith(".") || entry === "node_modules") continue;
577
- const fullPath = join5(dir, entry);
578
- try {
579
- if (statSync(fullPath).isDirectory()) {
580
- const found = findOpenApiSpec(fullPath, depth + 1);
581
- if (found) return found;
582
- }
583
- } catch {
584
- }
585
- }
586
- return null;
587
- }
588
- function parseGitHubUrl(rawUrl) {
589
- let url;
590
- try {
591
- url = new URL(rawUrl);
592
- } catch {
593
- throw new Error(`Invalid URL: ${rawUrl}`);
594
- }
595
- if (url.hostname !== "github.com") {
596
- throw new Error(`URL must be a github.com URL, got: ${url.hostname}`);
597
- }
598
- const parts = url.pathname.replace(/^\//, "").split("/");
599
- if (parts.length < 2 || !parts[0] || !parts[1]) {
600
- throw new Error(`GitHub URL must include owner and repo: ${rawUrl}`);
601
- }
602
- const owner = parts[0];
603
- const repo = parts[1];
604
- let branch = "HEAD";
605
- let docsDir = "";
606
- if (parts.length >= 4 && parts[2] === "tree") {
607
- branch = parts[3];
608
- if (parts.length > 4) {
609
- docsDir = parts.slice(4).join("/");
610
- }
611
- }
612
- const cloneUrl = `https://github.com/${owner}/${repo}.git`;
613
- return { owner, repo, branch, docsDir, cloneUrl };
614
- }
615
- async function cloneRepo(source, targetDir) {
616
- const parts = ["git", "clone", "--depth", "1"];
617
- if (source.branch !== "HEAD") {
618
- parts.push("--branch", source.branch);
619
- }
620
- parts.push(source.cloneUrl, targetDir);
621
- const cmd = parts.join(" ");
622
- try {
623
- execSync2(cmd, { stdio: "pipe" });
624
- } catch (err) {
625
- const stderr = err.stderr?.toString().trim() ?? "";
626
- const msg = stderr || (err instanceof Error ? err.message : String(err));
627
- throw new Error(`Failed to clone ${source.cloneUrl}: ${msg}`);
628
- }
629
- }
630
- var MD_EXTENSIONS = /* @__PURE__ */ new Set([".md", ".mdx"]);
631
- var ALL_DOC_EXTENSIONS = /* @__PURE__ */ new Set([".md", ".mdx", ".rst", ".txt"]);
632
- function hasMdFiles(dir) {
633
- let entries;
634
- try {
635
- entries = readdirSync2(dir);
636
- } catch {
637
- return false;
638
- }
639
- for (const entry of entries) {
640
- const fullPath = join5(dir, entry);
641
- try {
642
- const stat = statSync(fullPath);
643
- if (stat.isDirectory()) {
644
- if (hasMdFiles(fullPath)) return true;
645
- } else if (MD_EXTENSIONS.has(extname(entry).toLowerCase())) {
646
- return true;
647
- }
648
- } catch {
649
- }
650
- }
651
- return false;
652
- }
653
- function detectDocsDir(cloneDir) {
654
- const candidates = [
655
- "docs",
656
- "documentation",
657
- "content",
658
- "pages",
659
- "src/content",
660
- "src/pages",
661
- "guide",
662
- "guides",
663
- ""
664
- ];
665
- for (const candidate of candidates) {
666
- const fullPath = candidate ? join5(cloneDir, candidate) : cloneDir;
667
- try {
668
- const stat = statSync(fullPath);
669
- if (stat.isDirectory() && hasMdFiles(fullPath)) {
670
- return candidate;
671
- }
672
- } catch {
673
- }
674
- }
675
- return "";
676
- }
677
- function slugifySegment(seg) {
678
- return seg.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
679
- }
680
- function derivePageId(relPath) {
681
- const normalized = relPath.replace(/\\/g, "/");
682
- const parts = normalized.split("/");
683
- const filename = parts[parts.length - 1];
684
- const dirs = parts.slice(0, -1);
685
- const base = basename(filename, extname(filename));
686
- if (dirs.length === 0 && base.toLowerCase() === "readme") {
687
- return "introduction";
688
- }
689
- if (base.toLowerCase() === "index") {
690
- if (dirs.length === 0) return "introduction";
691
- return dirs.map(slugifySegment).join("/");
692
- }
693
- return [...dirs, base].map(slugifySegment).join("/");
694
- }
695
- function scanDir(dir, baseDir, primaryOnly, results) {
696
- let entries;
697
- try {
698
- entries = readdirSync2(dir);
699
- } catch {
700
- return;
701
- }
702
- for (const entry of entries) {
703
- if (entry.startsWith("_") || entry.startsWith(".") || entry === "node_modules") continue;
704
- const fullPath = join5(dir, entry);
705
- let stat;
706
- try {
707
- stat = statSync(fullPath);
708
- } catch {
709
- continue;
710
- }
711
- if (stat.isDirectory()) {
712
- scanDir(fullPath, baseDir, primaryOnly, results);
713
- } else {
714
- const ext = extname(entry).toLowerCase();
715
- const validExt = primaryOnly ? MD_EXTENSIONS.has(ext) : ALL_DOC_EXTENSIONS.has(ext);
716
- if (!validExt) continue;
717
- const relPath = relative(baseDir, fullPath);
718
- const pageId = derivePageId(relPath);
719
- results.push({ absPath: fullPath, relPath, pageId, ext });
720
- }
721
- }
722
- }
723
- function findDocFiles(cloneDir, docsDir) {
724
- const baseDir = docsDir ? join5(cloneDir, docsDir) : cloneDir;
725
- const primaryResults = [];
726
- scanDir(baseDir, baseDir, true, primaryResults);
727
- if (primaryResults.length > 0) return primaryResults;
728
- const allResults = [];
729
- scanDir(baseDir, baseDir, false, allResults);
730
- return allResults;
731
- }
732
-
733
- // src/lib/migrate/importer.ts
734
- import { readFileSync as readFileSync4 } from "fs";
735
- import { basename as basename2, extname as extname2 } from "path";
736
- import matter2 from "gray-matter";
737
- import Anthropic from "@anthropic-ai/sdk";
738
- function titleFromFilename(relPath) {
739
- const filename = relPath.replace(/\\/g, "/").split("/").pop() ?? relPath;
740
- const base = basename2(filename, extname2(filename));
741
- return base.split(/[-_]/).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
742
- }
743
- function extractFirstParagraph(content) {
744
- for (const line of content.split("\n")) {
745
- const trimmed = line.trim();
746
- if (!trimmed) continue;
747
- if (trimmed.startsWith("#")) continue;
748
- if (trimmed.startsWith("```") || trimmed.startsWith(":::") || trimmed.startsWith("<")) continue;
749
- if (trimmed.startsWith("import ") || trimmed.startsWith("export ")) continue;
750
- return trimmed.slice(0, 200);
751
- }
752
- return "";
753
- }
754
- function normalizeComponents(body) {
755
- let result = body;
756
- const importedComponents = /* @__PURE__ */ new Set();
757
- result = result.replace(
758
- /^import\s+(\w+|\{[^}]+\})\s+from\s+['"][^'"]+['"]\s*;?\s*$/gm,
759
- (_, imported) => {
760
- const name = imported.trim();
761
- if (/^[A-Z]\w*$/.test(name)) importedComponents.add(name);
762
- return "";
763
- }
764
- );
765
- for (const name of importedComponents) {
766
- result = result.replace(
767
- new RegExp(`<${name}(?:\\s[^>]*)?\\/>`, "gm"),
768
- `{/* <${name} /> \u2014 imported snippet component */}`
769
- );
770
- result = result.replace(
771
- new RegExp(`<${name}(?:\\s[^>]*)?>([\\s\\S]*?)<\\/${name}>`, "g"),
772
- `{/* <${name}> \u2014 imported snippet component */}`
773
- );
774
- }
775
- result = result.replace(/<!--([\s\S]*?)-->/g, (_, inner) => `{/*${inner}*/}`);
776
- result = result.replace(/<Tip>([\s\S]*?)<\/Tip>/g, (_, c) => `<Note>${c}</Note>`);
777
- result = result.replace(/<Check>([\s\S]*?)<\/Check>/g, (_, c) => `<Note>${c}</Note>`);
778
- result = result.replace(/<Danger>([\s\S]*?)<\/Danger>/g, (_, c) => `<Error>${c}</Error>`);
779
- result = result.replace(/<Callout(?:\s[^>]*)?>([\s\S]*?)<\/Callout>/g, (_, c) => `<Note>${c}</Note>`);
780
- result = result.replace(/:::(\w+)(?:\s+[^\n]*)?\n([\s\S]*?):::/g, (_, type, content) => {
781
- const tag = mapAdmonitionToThallyTag(type.toLowerCase());
782
- return `<${tag}>
783
- ${content.trim()}
784
- </${tag}>`;
785
- });
786
- result = result.replace(
787
- /\{%\s*hint\s+style="(\w+)"\s*%\}([\s\S]*?)\{%\s*endhint\s*%\}/g,
788
- (_, style, content) => {
789
- const tag = mapGitBookStyleToThallyTag(style.toLowerCase());
790
- return `<${tag}>
791
- ${content.trim()}
792
- </${tag}>`;
793
- }
794
- );
795
- result = result.replace(/<AccordionGroup[^>]*>\n?([\s\S]*?)\n?<\/AccordionGroup>/g, (_, inner) => inner.trim());
796
- result = result.replace(/<Expandable(\s[^>]*)?>/g, (_, attrs = "") => {
797
- const title = attrs.match(/title="([^"]*)"/)?.[1] ?? "Details";
798
- return `<Accordion title="${title}">`;
799
- });
800
- result = result.replace(/<\/Expandable>/g, "</Accordion>");
801
- result = result.replace(/<Latex>([\s\S]*?)<\/Latex>/g, (_, inner) => `\`${inner.trim()}\``);
802
- result = result.replace(/<(?:ResponseField|ParamField)([^>]*)>/g, (_, attrs) => {
803
- const name = attrs.match(/name="([^"]*)"/)?.[1] ?? "";
804
- const type = attrs.match(/type="([^"]*)"/)?.[1] ?? "";
805
- const required = /\brequired\b/.test(attrs);
806
- const def = attrs.match(/default="([^"]*)"/)?.[1];
807
- const deprecated = /\bdeprecated\b/.test(attrs);
808
- const meta = [
809
- type && `\`${type}\``,
810
- required && "*(required)*",
811
- deprecated && "*(deprecated)*",
812
- def !== void 0 && `*(default: \`${def}\`)*`
813
- ].filter(Boolean).join(" ");
814
- return `
815
- **\`${name}\`** ${meta}
816
-
817
- `;
818
- });
819
- result = result.replace(/<\/(?:ResponseField|ParamField)>/g, "\n");
820
- result = result.replace(/<RequestExample[^>]*>/g, "<CodeGroup>");
821
- result = result.replace(/<\/RequestExample>/g, "</CodeGroup>");
822
- result = result.replace(/<ResponseExample[^>]*>/g, "<CodeGroup>");
823
- result = result.replace(/<\/ResponseExample>/g, "</CodeGroup>");
824
- result = result.replace(/<Panel[^>]*>([\s\S]*?)<\/Panel>/g, (_, inner) => inner.trim());
825
- result = result.replace(/<Badge[^>]*>([\s\S]*?)<\/Badge>/g, (_, inner) => `**${inner.trim()}**`);
826
- result = result.replace(/<Tile(\s[^>]*)?>/g, (_, attrs = "") => `<Card${attrs}>`);
827
- result = result.replace(/<\/Tile>/g, "</Card>");
828
- result = result.replace(/<View(\s[^>]*)?>/g, (_, attrs = "") => {
829
- const title = attrs.match(/title="([^"]*)"/)?.[1] ?? "View";
830
- return `<Tab title="${title}">`;
831
- });
832
- result = result.replace(/<\/View>/g, "</Tab>");
833
- result = result.replace(/<Update(\s[^>]*)?>/g, (_, attrs = "") => {
834
- const label = attrs.match(/label="([^"]*)"/)?.[1] ?? "";
835
- const desc = attrs.match(/description="([^"]*)"/)?.[1] ?? "";
836
- return `## ${label}${desc ? `
837
-
838
- *${desc}*` : ""}
839
-
840
- `;
841
- });
842
- result = result.replace(/<\/Update>/g, "\n");
843
- result = result.replace(/<Prompt[^>]*>([\s\S]*?)<\/Prompt>/g, (_, inner) => {
844
- return `\`\`\`text
845
- ${inner.trim()}
846
- \`\`\``;
847
- });
848
- result = result.replace(/<Tree[^>]*>/g, "```\n");
849
- result = result.replace(/<\/Tree>/g, "\n```");
850
- result = result.replace(/<Tree\.Folder[^>]*name="([^"]*)"[^>]*>/g, (_, name) => `\u{1F4C1} ${name}/
851
- `);
852
- result = result.replace(/<\/Tree\.Folder>/g, "");
853
- result = result.replace(new RegExp('<Tree\\.File[^>]*name="([^"]*)"[^>]*/>', "g"), (_, name) => ` ${name}
854
- `);
855
- result = result.replace(/<Color[^>]*>/g, "| Name | Value |\n|---|---|\n");
856
- result = result.replace(/<\/Color>/g, "");
857
- result = result.replace(/<Color\.Row[^>]*title="([^"]*)"[^>]*>/g, (_, title) => `**${title}**
858
- `);
859
- result = result.replace(/<\/Color\.Row>/g, "");
860
- result = result.replace(
861
- /<Color\.Item[^>]*name="([^"]*)"[^>]*value="([^"]*)"[^>]*\/>/g,
862
- (_, name, value) => `| ${name} | \`${value}\` |
863
- `
864
- );
865
- result = result.replace(/<Banner[^>]*>([\s\S]*?)<\/Banner>/g, "");
866
- result = result.replace(/<Banner[^>]*\/>/g, "");
867
- return result;
868
- }
869
- function mapAdmonitionToThallyTag(type) {
870
- if (type === "warning" || type === "caution") return "Warning";
871
- if (type === "danger") return "Error";
872
- if (type === "info") return "Info";
873
- return "Note";
874
- }
875
- function mapGitBookStyleToThallyTag(style) {
876
- if (style === "warning") return "Warning";
877
- if (style === "danger") return "Error";
878
- if (style === "success") return "Note";
879
- return "Info";
880
- }
881
- var RST_SYSTEM_PROMPT = `You are a documentation converter. Convert the given file content to clean MDX.
882
- Respond with ONLY valid JSON \u2014 no prose, no markdown fences:
883
- {
884
- "frontmatter": { "title": "string", "description": "string", "keywords": ["..."] },
885
- "body": "string \u2014 full MDX body"
886
- }
887
- Rules: preserve code blocks with language hints; convert tables to Markdown; convert callout
888
- boxes to <Note> or <Warning>; preserve heading hierarchy; do not include page title as a heading.`;
889
- function parseClaudeResponse(text) {
890
- try {
891
- return JSON.parse(text);
892
- } catch {
893
- const stripped = text.replace(/^```(?:json)?\s*/m, "").replace(/\s*```\s*$/m, "").trim();
894
- return JSON.parse(stripped);
895
- }
896
- }
897
- async function importFile(file, apiKey) {
898
- const ext = file.ext.toLowerCase();
899
- if (ext === ".md" || ext === ".mdx") {
900
- const raw = readFileSync4(file.absPath, "utf8");
901
- const parsed = matter2(raw);
902
- const fmTitle = parsed.data.title ?? "";
903
- const fmDesc = parsed.data.description ?? "";
904
- const fmKeywords = parsed.data.keywords;
905
- const title = fmTitle || titleFromFilename(file.relPath);
906
- const description = fmDesc || extractFirstParagraph(parsed.content);
907
- const keywords = Array.isArray(fmKeywords) ? fmKeywords : [];
908
- const openapi = parsed.data.openapi;
909
- const body = normalizeComponents(parsed.content);
910
- if (openapi && !body.trim()) return null;
911
- return { pageId: file.pageId, frontmatter: { title, description, keywords }, body };
912
- }
913
- if (!apiKey) {
914
- throw new Error(`Skipping non-Markdown file (no API key): ${file.relPath}`);
915
- }
916
- const content = readFileSync4(file.absPath, "utf8");
917
- const client = new Anthropic({ apiKey });
918
- const message = await client.messages.create({
919
- model: "claude-sonnet-4-6",
920
- max_tokens: 4096,
921
- system: RST_SYSTEM_PROMPT,
922
- messages: [
923
- {
924
- role: "user",
925
- content: `Convert this documentation file to MDX.
926
-
927
- File: ${file.relPath}
928
-
929
- Content:
930
- ${content.slice(0, 8e4)}`
931
- }
932
- ]
933
- });
934
- const responseText = message.content.filter((block) => block.type === "text").map((block) => block.text).join("");
935
- const claudeResult = parseClaudeResponse(responseText);
936
- return {
937
- pageId: file.pageId,
938
- frontmatter: claudeResult.frontmatter,
939
- body: claudeResult.body
940
- };
941
- }
942
-
943
- // src/lib/migrate/nav-builder.ts
944
- import { existsSync as existsSync5, readFileSync as readFileSync5 } from "fs";
945
- import { join as join6 } from "path";
946
- function titleCase(str) {
947
- return str.split("-").map((word) => {
948
- if (word.toLowerCase() === "api") return "API";
949
- if (word.toLowerCase() === "sdk") return "SDK";
950
- if (word.toLowerCase() === "cli") return "CLI";
951
- if (word.toLowerCase() === "ui") return "UI";
952
- if (word.toLowerCase() === "faq") return "FAQ";
953
- return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
954
- }).join(" ");
955
- }
956
- function buildNavStructure(pages) {
957
- const seen = /* @__PURE__ */ new Set();
958
- const ordered = [];
959
- for (const p of pages) {
960
- if (!seen.has(p.pageId)) {
961
- seen.add(p.pageId);
962
- ordered.push(p.pageId);
963
- }
964
- }
965
- const depth1Segments = /* @__PURE__ */ new Set();
966
- for (const id of ordered) {
967
- const parts = id.split("/");
968
- if (parts.length > 1) {
969
- depth1Segments.add(parts[0]);
970
- }
971
- }
972
- const rootOnlyPages = ordered.filter((id) => !id.includes("/"));
973
- const useSingleTab = depth1Segments.size === 0 || depth1Segments.size === 1 && rootOnlyPages.length === 0;
974
- let tabs;
975
- if (useSingleTab) {
976
- const groups = buildGroups(ordered, null);
977
- tabs = [{ tab: "Overview", groups }];
978
- } else {
979
- tabs = [];
980
- if (rootOnlyPages.length > 0) {
981
- const groups = buildGroups(rootOnlyPages, null);
982
- tabs.push({ tab: "Overview", groups });
983
- }
984
- for (const seg of depth1Segments) {
985
- const tabPages = ordered.filter((id) => id.startsWith(seg + "/") || id === seg);
986
- const groups = buildGroups(tabPages, seg);
987
- tabs.push({ tab: titleCase(seg), groups });
988
- }
989
- }
990
- tabs.push({ tab: "Changelog", href: "/changelog" });
991
- return { tabs };
992
- }
993
- function buildGroups(pageIds, tabSegment) {
994
- const groupMap = /* @__PURE__ */ new Map();
995
- for (const id of pageIds) {
996
- let groupName;
997
- if (tabSegment === null) {
998
- groupName = "Overview";
999
- } else {
1000
- const rel = id.startsWith(tabSegment + "/") ? id.slice(tabSegment.length + 1) : id;
1001
- const relParts = rel.split("/");
1002
- groupName = relParts.length === 1 ? titleCase(tabSegment) : titleCase(relParts[0]);
1003
- }
1004
- if (!groupMap.has(groupName)) groupMap.set(groupName, []);
1005
- groupMap.get(groupName).push(id);
1006
- }
1007
- const groups = [];
1008
- for (const [groupName, groupPages] of groupMap) {
1009
- const sorted = [...groupPages];
1010
- const introIdx = sorted.indexOf("introduction");
1011
- if (introIdx > 0) {
1012
- sorted.splice(introIdx, 1);
1013
- sorted.unshift("introduction");
1014
- }
1015
- groups.push({ group: groupName, pages: sorted });
1016
- }
1017
- return groups;
1018
- }
1019
- function detectPlatform(cloneDir) {
1020
- if (existsSync5(join6(cloneDir, "mint.json"))) return "mintlify";
1021
- if (existsSync5(join6(cloneDir, "docs.json"))) {
1022
- try {
1023
- const parsed = JSON.parse(readFileSync5(join6(cloneDir, "docs.json"), "utf8"));
1024
- if (Array.isArray(parsed.tabs)) return "thally";
1025
- const schema = parsed.$schema;
1026
- if (schema?.includes("mintlify") || "navigation" in parsed) return "mintlify";
1027
- } catch {
1028
- }
1029
- }
1030
- if (existsSync5(join6(cloneDir, "docusaurus.config.js")) || existsSync5(join6(cloneDir, "docusaurus.config.ts")) || existsSync5(join6(cloneDir, "docusaurus.config.mjs"))) return "docusaurus";
1031
- if (existsSync5(join6(cloneDir, "SUMMARY.md"))) return "gitbook";
1032
- if (existsSync5(join6(cloneDir, ".vitepress"))) return "vitepress";
1033
- if (existsSync5(join6(cloneDir, "astro.config.mjs")) || existsSync5(join6(cloneDir, "astro.config.ts"))) return "starlight";
1034
- if (existsSync5(join6(cloneDir, "_meta.json")) || existsSync5(join6(cloneDir, "pages", "_meta.json"))) return "nextra";
1035
- return "unknown";
1036
- }
1037
- function slugify2(s) {
1038
- return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
1039
- }
1040
- function normalizePageRef(ref, docsDir) {
1041
- let r = ref;
1042
- if (docsDir && r.startsWith(docsDir + "/")) r = r.slice(docsDir.length + 1);
1043
- r = r.replace(/\.(mdx?|rst|txt)$/, "");
1044
- const parts = r.split("/");
1045
- const last = parts[parts.length - 1].toLowerCase();
1046
- if (last === "index" || last === "readme") {
1047
- return parts.length === 1 ? "introduction" : parts.slice(0, -1).map(slugify2).join("/");
1048
- }
1049
- return parts.map(slugify2).join("/");
1050
- }
1051
- function convertMintTabs(tabs, docsDir) {
1052
- if (tabs.length === 0) return null;
1053
- function convertPageRef(page) {
1054
- if (typeof page === "string") return normalizePageRef(page, docsDir);
1055
- if (page !== null && typeof page === "object" && "group" in page && "pages" in page) {
1056
- const p = page;
1057
- return {
1058
- group: String(p.group),
1059
- pages: (p.pages ?? []).map(convertPageRef)
1060
- };
1061
- }
1062
- return String(page);
1063
- }
1064
- const resultTabs = tabs.map((item) => {
1065
- if (item.href) return { tab: String(item.tab), href: String(item.href) };
1066
- const groups = (item.groups ?? []).map((g) => ({
1067
- group: String(g.group),
1068
- pages: (g.pages ?? []).map(convertPageRef)
1069
- }));
1070
- return { tab: String(item.tab), groups };
1071
- });
1072
- if (!resultTabs.some((t) => t.tab === "Changelog")) {
1073
- resultTabs.push({ tab: "Changelog", href: "/changelog" });
1074
- }
1075
- return { tabs: resultTabs };
1076
- }
1077
- function parseMintConfig(config, docsDir) {
1078
- const nav = config.navigation;
1079
- if (nav && typeof nav === "object" && !Array.isArray(nav)) {
1080
- const v3Tabs = nav.tabs;
1081
- if (Array.isArray(v3Tabs) && v3Tabs.length > 0) return convertMintTabs(v3Tabs, docsDir);
1082
- }
1083
- if (!Array.isArray(nav) || nav.length === 0) return null;
1084
- if ("tab" in nav[0]) return convertMintTabs(nav, docsDir);
1085
- function convertPageRef(page) {
1086
- if (typeof page === "string") return normalizePageRef(page, docsDir);
1087
- if (page !== null && typeof page === "object" && "group" in page && "pages" in page) {
1088
- const p = page;
1089
- return { group: String(p.group), pages: (p.pages ?? []).map(convertPageRef) };
1090
- }
1091
- return String(page);
1092
- }
1093
- const groups = nav.map((item) => ({
1094
- group: String(item.group ?? ""),
1095
- pages: (item.pages ?? []).map(convertPageRef)
1096
- }));
1097
- return { tabs: [{ tab: "Docs", groups }, { tab: "Changelog", href: "/changelog" }] };
1098
- }
1099
- function parseGitBookSummary(cloneDir, docsDir) {
1100
- const candidates = [join6(cloneDir, "SUMMARY.md")];
1101
- if (docsDir) candidates.push(join6(cloneDir, docsDir, "SUMMARY.md"));
1102
- let raw = "";
1103
- for (const p of candidates) {
1104
- if (existsSync5(p)) {
1105
- raw = readFileSync5(p, "utf8");
1106
- break;
1107
- }
1108
- }
1109
- if (!raw) return null;
1110
- const groups = [];
1111
- let currentGroupName = "Overview";
1112
- let currentPages = [];
1113
- for (const line of raw.split("\n")) {
1114
- const groupMatch = line.match(/^##\s+(.+)/);
1115
- if (groupMatch) {
1116
- if (currentPages.length > 0) groups.push({ group: currentGroupName, pages: currentPages });
1117
- currentGroupName = groupMatch[1].trim();
1118
- currentPages = [];
1119
- continue;
1120
- }
1121
- const pageMatch = line.match(/^\*\s+\[.+?\]\((.+?)\)/);
1122
- if (pageMatch) {
1123
- const ref = pageMatch[1].trim();
1124
- if (ref.startsWith("http")) continue;
1125
- currentPages.push(normalizePageRef(ref, docsDir));
1126
- }
1127
- }
1128
- if (currentPages.length > 0) groups.push({ group: currentGroupName, pages: currentPages });
1129
- if (groups.length === 0) return null;
1130
- return { tabs: [{ tab: "Docs", groups }, { tab: "Changelog", href: "/changelog" }] };
1131
- }
1132
- function parseNextraMeta(cloneDir, docsDir) {
1133
- const baseDir = docsDir ? join6(cloneDir, docsDir) : cloneDir;
1134
- const metaPath = join6(baseDir, "_meta.json");
1135
- if (!existsSync5(metaPath)) return null;
1136
- try {
1137
- const meta = JSON.parse(readFileSync5(metaPath, "utf8"));
1138
- const pages = [];
1139
- for (const [key, value] of Object.entries(meta)) {
1140
- if (typeof value === "object" && value !== null) {
1141
- const v = value;
1142
- if (v.type === "separator" || v.type === "menu") continue;
1143
- }
1144
- pages.push(key === "index" ? "introduction" : slugify2(key));
1145
- }
1146
- if (pages.length === 0) return null;
1147
- return {
1148
- tabs: [
1149
- { tab: "Docs", groups: [{ group: "Overview", pages }] },
1150
- { tab: "Changelog", href: "/changelog" }
1151
- ]
1152
- };
1153
- } catch {
1154
- return null;
1155
- }
1156
- }
1157
- var PLATFORM_LABELS = {
1158
- mintlify: "Mintlify",
1159
- docusaurus: "Docusaurus",
1160
- gitbook: "GitBook",
1161
- nextra: "Nextra",
1162
- vitepress: "VitePress",
1163
- starlight: "Starlight (Astro)",
1164
- thally: "Thally",
1165
- unknown: "unknown"
1166
- };
1167
- function detectNavFromConfig(cloneDir, docsDir, platform) {
1168
- const detected = platform ?? detectPlatform(cloneDir);
1169
- const label = PLATFORM_LABELS[detected];
1170
- switch (detected) {
1171
- case "thally": {
1172
- try {
1173
- const parsed = JSON.parse(
1174
- readFileSync5(join6(cloneDir, "docs.json"), "utf8")
1175
- );
1176
- console.log(` \u{1F4CB} Detected ${label} \u2014 using docs.json navigation as-is`);
1177
- return parsed;
1178
- } catch {
1179
- return null;
1180
- }
1181
- }
1182
- case "mintlify": {
1183
- for (const file of ["docs.json", "mint.json"]) {
1184
- const p = join6(cloneDir, file);
1185
- if (!existsSync5(p)) continue;
1186
- try {
1187
- const config = JSON.parse(readFileSync5(p, "utf8"));
1188
- const nav = parseMintConfig(config, docsDir);
1189
- if (nav) {
1190
- console.log(` \u{1F4CB} Detected ${label} (${file}) \u2014 converting navigation`);
1191
- return nav;
1192
- }
1193
- } catch {
1194
- }
1195
- }
1196
- return null;
1197
- }
1198
- case "gitbook": {
1199
- const nav = parseGitBookSummary(cloneDir, docsDir);
1200
- if (nav) console.log(` \u{1F4CB} Detected ${label} (SUMMARY.md) \u2014 converting navigation`);
1201
- return nav;
1202
- }
1203
- case "nextra": {
1204
- const nav = parseNextraMeta(cloneDir, docsDir);
1205
- if (nav) console.log(` \u{1F4CB} Detected ${label} (_meta.json) \u2014 converting navigation`);
1206
- return nav;
1207
- }
1208
- case "docusaurus":
1209
- case "vitepress":
1210
- case "starlight":
1211
- console.log(` \u{1F4CB} Detected ${label} \u2014 nav config is JavaScript, using directory structure`);
1212
- return null;
1213
- default:
1214
- return null;
1215
- }
1216
- }
1217
-
1218
- // src/lib/migrate/index.ts
1219
- function mergeDocsJson(existing, incoming) {
1220
- const existingTabNames = new Set(existing.tabs.map((t) => t.tab));
1221
- const merged = { tabs: [...existing.tabs.filter((t) => t.tab !== "Changelog")] };
1222
- if (existing.ai || incoming.ai) {
1223
- merged.ai = { ...incoming.ai, ...existing.ai };
1224
- }
1225
- for (const tab of incoming.tabs) {
1226
- if (tab.tab === "Changelog") continue;
1227
- if (existingTabNames.has(tab.tab)) {
1228
- const existingTab = merged.tabs.find((t) => t.tab === tab.tab);
1229
- if (existingTab.groups && tab.groups) {
1230
- const existingGroupNames = new Set(existingTab.groups.map((g) => g.group));
1231
- for (const group of tab.groups) {
1232
- if (existingGroupNames.has(group.group)) {
1233
- const eg = existingTab.groups.find((g) => g.group === group.group);
1234
- const existingPageSet = new Set(eg.pages.map((p) => typeof p === "string" ? p : p.group));
1235
- for (const page of group.pages) {
1236
- const key = typeof page === "string" ? page : page.group;
1237
- if (!existingPageSet.has(key)) eg.pages.push(page);
1238
- }
1239
- } else {
1240
- existingTab.groups.push(group);
1241
- }
1242
- }
1243
- } else if (tab.groups) {
1244
- existingTab.groups = tab.groups;
1245
- }
1246
- } else {
1247
- merged.tabs.push(tab);
1248
- }
1249
- }
1250
- merged.tabs.push({ tab: "Changelog", href: "/changelog" });
1251
- return merged;
1252
- }
1253
- function injectApiTab(config, specFilename) {
1254
- const apiTab = { tab: "API Reference", api: { source: `/${specFilename}` } };
1255
- const tabs = config.tabs.filter((t) => {
1256
- if (t.tab.toLowerCase().includes("api")) return false;
1257
- return true;
1258
- });
1259
- const changelogIdx = tabs.findIndex((t) => t.tab === "Changelog");
1260
- if (changelogIdx >= 0) {
1261
- tabs.splice(changelogIdx, 0, apiTab);
1262
- } else {
1263
- tabs.push(apiTab);
1264
- }
1265
- return { ...config, tabs };
1266
- }
1267
- function installDeps2(targetDir) {
1268
- execSync3("npm install", { cwd: targetDir, stdio: "inherit" });
1269
- }
1270
- function initGit2(targetDir) {
1271
- try {
1272
- execSync3("git init", { cwd: targetDir, stdio: "inherit" });
1273
- execSync3("git add -A", { cwd: targetDir, stdio: "inherit" });
1274
- execSync3('git commit -m "Initial commit from create-thally-docs"', { cwd: targetDir, stdio: "inherit" });
1275
- } catch {
1276
- }
1277
- }
1278
- async function migrateDocs(opts) {
1279
- const { sourceUrl, projectDir: rawProjectDir, into, apiKey, projectName } = opts;
1280
- const projectDir = resolve2(rawProjectDir);
1281
- const source = parseGitHubUrl(sourceUrl);
1282
- if (opts.branch) source.branch = opts.branch;
1283
- if (!into) {
1284
- console.log(` \u{1F3D7} Scaffolding new project at ${projectDir}...`);
1285
- await scaffold({
1286
- projectDir,
1287
- projectName: projectName ?? "My Docs",
1288
- description: `Documentation migrated from ${source.owner}/${source.repo}`,
1289
- brandPreset: "primary",
1290
- repoUrl: `https://github.com/${source.owner}/${source.repo}`,
1291
- doInstall: false
1292
- });
1293
- } else {
1294
- if (!existsSync6(projectDir)) {
1295
- throw new Error(`Project directory "${projectDir}" does not exist.`);
1296
- }
1297
- }
1298
- const tmpBase = mkdtempSync(join7(tmpdir(), "thally-migrate-"));
1299
- const cloneDir = join7(tmpBase, "repo");
1300
- console.log(` \u{1F4E6} Cloning ${source.owner}/${source.repo}...`);
1301
- try {
1302
- await cloneRepo(source, cloneDir);
1303
- const docsDir = opts.docsDir ?? (source.docsDir || detectDocsDir(cloneDir));
1304
- const docFiles = findDocFiles(cloneDir, docsDir);
1305
- const docsDirLabel = docsDir ? `${docsDir}/` : "repo root";
1306
- console.log(` \u{1F4C4} Found ${docFiles.length} files in ${docsDirLabel}`);
1307
- if (docFiles.length === 0) {
1308
- console.warn(" \u26A0 No doc files found. Check the URL and try again.");
1309
- return { pagesWritten: 0, projectDir };
1310
- }
1311
- const platform = detectPlatform(cloneDir);
1312
- const detectedNav = detectNavFromConfig(cloneDir, docsDir, platform);
1313
- const openApiSpec = detectOpenApiSpec(cloneDir);
1314
- if (openApiSpec) {
1315
- console.log(` \u{1F50C} Found OpenAPI spec: ${openApiSpec.filename}`);
1316
- }
1317
- const limit = pLimit(5);
1318
- let doneCount = 0;
1319
- const imported = (await Promise.all(
1320
- docFiles.map(
1321
- (file) => limit(async () => {
1322
- try {
1323
- const result = await importFile(file, apiKey);
1324
- doneCount++;
1325
- if (result) {
1326
- console.log(` [${doneCount}/${docFiles.length}] ${result.pageId}`);
1327
- } else {
1328
- console.log(` [${doneCount}/${docFiles.length}] ${file.pageId} (openapi \u2014 wired via spec)`);
1329
- }
1330
- return result;
1331
- } catch (err) {
1332
- const msg = err instanceof Error ? err.message : String(err);
1333
- if (msg.includes("no API key")) {
1334
- console.warn(` \u26A0 ${msg}`);
1335
- } else {
1336
- console.warn(` \u26A0 Skipping ${file.relPath}: ${msg}`);
1337
- }
1338
- doneCount++;
1339
- return null;
1340
- }
1341
- })
1342
- )
1343
- )).filter(Boolean);
1344
- const pageIdSeen = /* @__PURE__ */ new Set();
1345
- const deduped = imported.filter((p) => {
1346
- if (pageIdSeen.has(p.pageId)) return false;
1347
- pageIdSeen.add(p.pageId);
1348
- return true;
1349
- });
1350
- const contentDir = join7(projectDir, "src", "content");
1351
- let pagesWritten = 0;
1352
- for (const page of deduped) {
1353
- const filePath = join7(contentDir, `${page.pageId}.mdx`);
1354
- mkdirSync3(dirname2(filePath), { recursive: true });
1355
- const mdx = [
1356
- "---",
1357
- `title: "${page.frontmatter.title.replace(/"/g, '\\"')}"`,
1358
- `description: "${page.frontmatter.description.replace(/"/g, '\\"')}"`,
1359
- page.frontmatter.keywords.length > 0 ? `keywords: [${page.frontmatter.keywords.map((k) => `"${k.replace(/"/g, '\\"')}"`).join(", ")}]` : null,
1360
- "---",
1361
- "",
1362
- page.body
1363
- ].filter((line) => line !== null).join("\n");
1364
- writeFileSync5(filePath, mdx, "utf8");
1365
- pagesWritten++;
1366
- }
1367
- let finalNav = detectedNav ?? buildNavStructure(deduped);
1368
- if (openApiSpec) {
1369
- const publicDir = join7(projectDir, "public");
1370
- mkdirSync3(publicDir, { recursive: true });
1371
- copyFileSync(openApiSpec.absPath, join7(publicDir, openApiSpec.filename));
1372
- console.log(` \u{1F4CB} Copied ${openApiSpec.filename} \u2192 public/${openApiSpec.filename}`);
1373
- finalNav = injectApiTab(finalNav, openApiSpec.filename);
1374
- }
1375
- if (into && existsSync6(join7(projectDir, "docs.json"))) {
1376
- const existing = readDocsJson(projectDir);
1377
- const merged = mergeDocsJson(existing, finalNav);
1378
- writeDocsJson(projectDir, merged);
1379
- } else {
1380
- writeDocsJson(projectDir, finalNav);
1381
- }
1382
- if (!into) {
1383
- installDeps2(projectDir);
1384
- initGit2(projectDir);
1385
- }
1386
- return { pagesWritten, projectDir };
1387
- } finally {
1388
- rmSync(tmpBase, { recursive: true, force: true });
1389
- }
1390
- }
1391
-
1392
- // src/tools/migrate-docs.ts
539
+ import { migrateDocs } from "create-thally-docs/migrate";
1393
540
  var migrateDocsSchema = z6.object({
1394
- sourceUrl: z6.string().describe("GitHub URL of the docs repo to migrate"),
541
+ sourceUrl: z6.string().describe("GitHub repository URL or public documentation URL to migrate"),
1395
542
  projectDir: z6.string().describe("Path for new project or existing project dir"),
1396
543
  into: z6.boolean().optional().default(false).describe("Migrate into existing project instead of scaffolding"),
1397
544
  branch: z6.string().optional().describe("Git branch (default: auto-detect)"),
1398
545
  docsDir: z6.string().optional().describe("Docs subdirectory in repo (default: auto-detect)"),
1399
- apiKey: z6.string().optional().describe("Anthropic API key for non-Markdown file conversion")
546
+ apiKey: z6.string().optional().describe("Anthropic API key for non-Markdown file conversion"),
547
+ maxPages: z6.number().int().min(1).max(1e3).optional().describe("Maximum public URL pages to import")
1400
548
  });
1401
549
  async function handleMigrateDocs(input) {
1402
550
  const apiKey = input.apiKey ?? process.env.ANTHROPIC_API_KEY;
@@ -1407,6 +555,7 @@ async function handleMigrateDocs(input) {
1407
555
  apiKey,
1408
556
  branch: input.branch,
1409
557
  docsDir: input.docsDir,
558
+ maxPages: input.maxPages,
1410
559
  yes: true
1411
560
  });
1412
561
  return `Migration complete! ${result.pagesWritten} pages written to ${result.projectDir}/src/content/`;
@@ -1414,9 +563,9 @@ async function handleMigrateDocs(input) {
1414
563
 
1415
564
  // src/tools/search-docs.ts
1416
565
  import { z as z7 } from "zod";
1417
- import { readdirSync as readdirSync3, statSync as statSync2, readFileSync as readFileSync7, existsSync as existsSync7 } from "fs";
1418
- import { join as join8, relative as relative2, extname as extname3 } from "path";
1419
- import matter3 from "gray-matter";
566
+ import { readdirSync as readdirSync2, statSync, readFileSync as readFileSync4, existsSync as existsSync4 } from "fs";
567
+ import { join as join5, relative, extname } from "path";
568
+ import matter2 from "gray-matter";
1420
569
  var searchDocsSchema = z7.object({
1421
570
  projectDir: z7.string().describe("Path to the Thally project root"),
1422
571
  query: z7.string().describe("Search query"),
@@ -1425,17 +574,17 @@ var searchDocsSchema = z7.object({
1425
574
  function scanMdxFiles(dir, results) {
1426
575
  let entries;
1427
576
  try {
1428
- entries = readdirSync3(dir);
577
+ entries = readdirSync2(dir);
1429
578
  } catch {
1430
579
  return;
1431
580
  }
1432
581
  for (const entry of entries) {
1433
- const fullPath = join8(dir, entry);
582
+ const fullPath = join5(dir, entry);
1434
583
  try {
1435
- const stat = statSync2(fullPath);
584
+ const stat = statSync(fullPath);
1436
585
  if (stat.isDirectory()) {
1437
586
  scanMdxFiles(fullPath, results);
1438
- } else if (extname3(entry).toLowerCase() === ".mdx") {
587
+ } else if (extname(entry).toLowerCase() === ".mdx") {
1439
588
  results.push(fullPath);
1440
589
  }
1441
590
  } catch {
@@ -1448,15 +597,15 @@ function scoreFiles(files, contentDir, query) {
1448
597
  for (const filePath of files) {
1449
598
  let raw;
1450
599
  try {
1451
- raw = readFileSync7(filePath, "utf8");
600
+ raw = readFileSync4(filePath, "utf8");
1452
601
  } catch {
1453
602
  continue;
1454
603
  }
1455
- const { data, content } = matter3(raw);
604
+ const { data, content } = matter2(raw);
1456
605
  const title = data.title ?? "";
1457
606
  const description = data.description ?? "";
1458
607
  const keywords = data.keywords ?? [];
1459
- const pageId = relative2(contentDir, filePath).replace(/\.mdx$/, "").replace(/\\/g, "/");
608
+ const pageId = relative(contentDir, filePath).replace(/\.mdx$/, "").replace(/\\/g, "/");
1460
609
  let score = 0;
1461
610
  for (const term of terms) {
1462
611
  if (title.toLowerCase().includes(term)) score += 3;
@@ -1473,8 +622,8 @@ function scoreFiles(files, contentDir, query) {
1473
622
  }
1474
623
  async function handleSearchDocs(input) {
1475
624
  const { projectDir, query, limit = 5 } = input;
1476
- const contentDir = join8(projectDir, "src", "content");
1477
- if (!existsSync7(contentDir)) {
625
+ const contentDir = join5(projectDir, "src", "content");
626
+ if (!existsSync4(contentDir)) {
1478
627
  throw new Error(`Content directory not found: ${contentDir}`);
1479
628
  }
1480
629
  const files = [];
@@ -1569,23 +718,23 @@ async function handleAgentReadiness(input) {
1569
718
 
1570
719
  // src/tools/read-page.ts
1571
720
  import { z as z10 } from "zod";
1572
- import { existsSync as existsSync8, readFileSync as readFileSync8 } from "fs";
1573
- import { join as join9 } from "path";
1574
- import matter4 from "gray-matter";
721
+ import { existsSync as existsSync5, readFileSync as readFileSync5 } from "fs";
722
+ import { join as join6 } from "path";
723
+ import matter3 from "gray-matter";
1575
724
  var readPageSchema = z10.object({
1576
725
  projectDir: z10.string().describe("Path to the Thally project root"),
1577
726
  pageId: z10.string().describe('Page ID, e.g. "guides/authentication"')
1578
727
  });
1579
728
  async function handleReadPage(input) {
1580
729
  const { projectDir, pageId } = input;
1581
- const contentDir = join9(projectDir, "src", "content");
730
+ const contentDir = join6(projectDir, "src", "content");
1582
731
  const candidates = [
1583
- join9(contentDir, `${pageId}.mdx`),
1584
- join9(contentDir, `${pageId}/index.mdx`)
732
+ join6(contentDir, `${pageId}.mdx`),
733
+ join6(contentDir, `${pageId}/index.mdx`)
1585
734
  ];
1586
735
  let filePath = null;
1587
736
  for (const c of candidates) {
1588
- if (existsSync8(c)) {
737
+ if (existsSync5(c)) {
1589
738
  filePath = c;
1590
739
  break;
1591
740
  }
@@ -1593,8 +742,8 @@ async function handleReadPage(input) {
1593
742
  if (!filePath) {
1594
743
  throw new Error(`Page not found: "${pageId}". No file at src/content/${pageId}.mdx`);
1595
744
  }
1596
- const raw = readFileSync8(filePath, "utf8");
1597
- const { data, content } = matter4(raw);
745
+ const raw = readFileSync5(filePath, "utf8");
746
+ const { data, content } = matter3(raw);
1598
747
  const title = data.title ?? pageId;
1599
748
  const description = data.description ?? "";
1600
749
  const lines = [`# ${title}`, `*${pageId}*`, ""];
@@ -1608,9 +757,9 @@ async function handleReadPage(input) {
1608
757
 
1609
758
  // src/tools/get-context.ts
1610
759
  import { z as z11 } from "zod";
1611
- import { existsSync as existsSync9, readFileSync as readFileSync9 } from "fs";
1612
- import { join as join10 } from "path";
1613
- import matter5 from "gray-matter";
760
+ import { existsSync as existsSync6, readFileSync as readFileSync6 } from "fs";
761
+ import { join as join7 } from "path";
762
+ import matter4 from "gray-matter";
1614
763
  var getContextSchema = z11.object({
1615
764
  projectDir: z11.string().describe("Path to the Thally project root"),
1616
765
  topic: z11.string().describe("Topic or question to find relevant docs for"),
@@ -1618,8 +767,8 @@ var getContextSchema = z11.object({
1618
767
  });
1619
768
  async function handleGetContext(input) {
1620
769
  const { projectDir, topic, maxTokens = 4e3 } = input;
1621
- const contentDir = join10(projectDir, "src", "content");
1622
- if (!existsSync9(contentDir)) {
770
+ const contentDir = join7(projectDir, "src", "content");
771
+ if (!existsSync6(contentDir)) {
1623
772
  throw new Error(`Content directory not found: ${contentDir}`);
1624
773
  }
1625
774
  const files = [];
@@ -1633,14 +782,14 @@ async function handleGetContext(input) {
1633
782
  const sections = [];
1634
783
  for (const result of scored) {
1635
784
  const candidates = [
1636
- join10(contentDir, `${result.pageId}.mdx`),
1637
- join10(contentDir, `${result.pageId}/index.mdx`)
785
+ join7(contentDir, `${result.pageId}.mdx`),
786
+ join7(contentDir, `${result.pageId}/index.mdx`)
1638
787
  ];
1639
788
  let content = "";
1640
789
  for (const c of candidates) {
1641
- if (existsSync9(c)) {
1642
- const raw = readFileSync9(c, "utf8");
1643
- const { content: body } = matter5(raw);
790
+ if (existsSync6(c)) {
791
+ const raw = readFileSync6(c, "utf8");
792
+ const { content: body } = matter4(raw);
1644
793
  content = body.trim();
1645
794
  break;
1646
795
  }
@@ -1664,9 +813,9 @@ async function handleGetContext(input) {
1664
813
 
1665
814
  // src/tools/lint-project.ts
1666
815
  import { z as z12 } from "zod";
1667
- import { existsSync as existsSync10, readFileSync as readFileSync10 } from "fs";
1668
- import { join as join11 } from "path";
1669
- import matter6 from "gray-matter";
816
+ import { existsSync as existsSync7, readFileSync as readFileSync7 } from "fs";
817
+ import { join as join8 } from "path";
818
+ import matter5 from "gray-matter";
1670
819
  var lintProjectSchema = z12.object({
1671
820
  projectDir: z12.string().describe("Path to the Thally project root"),
1672
821
  fix: z12.boolean().optional().default(false).describe("Auto-fix issues where possible (adds orphan pages to nav)")
@@ -1697,9 +846,9 @@ function addOrphanToNav(projectDir, pageId) {
1697
846
  }
1698
847
  async function handleLintProject(input) {
1699
848
  const { projectDir, fix = false } = input;
1700
- const contentDir = join11(projectDir, "src", "content");
849
+ const contentDir = join8(projectDir, "src", "content");
1701
850
  const issues = [];
1702
- if (!existsSync10(join11(projectDir, "docs.json"))) {
851
+ if (!existsSync7(join8(projectDir, "docs.json"))) {
1703
852
  throw new Error(`Not a Thally project: docs.json not found in ${projectDir}`);
1704
853
  }
1705
854
  const config = readDocsJson(projectDir);
@@ -1718,10 +867,10 @@ async function handleLintProject(input) {
1718
867
  }
1719
868
  for (const pageId of navPageIds) {
1720
869
  const candidates = [
1721
- join11(contentDir, `${pageId}.mdx`),
1722
- join11(contentDir, `${pageId}/index.mdx`)
870
+ join8(contentDir, `${pageId}.mdx`),
871
+ join8(contentDir, `${pageId}/index.mdx`)
1723
872
  ];
1724
- if (!candidates.some((c) => existsSync10(c))) {
873
+ if (!candidates.some((c) => existsSync7(c))) {
1725
874
  issues.push({
1726
875
  severity: "error",
1727
876
  message: `"${pageId}" is in docs.json but has no MDX file`,
@@ -1730,7 +879,7 @@ async function handleLintProject(input) {
1730
879
  }
1731
880
  }
1732
881
  const allFiles = [];
1733
- if (existsSync10(contentDir)) {
882
+ if (existsSync7(contentDir)) {
1734
883
  scanMdxFiles(contentDir, allFiles);
1735
884
  }
1736
885
  const fixedOrphans = [];
@@ -1748,8 +897,8 @@ async function handleLintProject(input) {
1748
897
  let data = {};
1749
898
  let content = "";
1750
899
  try {
1751
- const raw = readFileSync10(filePath, "utf8");
1752
- const parsed = matter6(raw);
900
+ const raw = readFileSync7(filePath, "utf8");
901
+ const parsed = matter5(raw);
1753
902
  data = parsed.data;
1754
903
  content = parsed.content;
1755
904
  } catch {
@@ -1805,11 +954,11 @@ async function handleLintProject(input) {
1805
954
 
1806
955
  // src/tools/translate-docs.ts
1807
956
  import { z as z13 } from "zod";
1808
- import { readFileSync as readFileSync11, writeFileSync as writeFileSync7, existsSync as existsSync11, mkdirSync as mkdirSync4 } from "fs";
1809
- import { join as join12, dirname as dirname3 } from "path";
1810
- import matter7 from "gray-matter";
1811
- import Anthropic2 from "@anthropic-ai/sdk";
1812
- import pLimit2 from "p-limit";
957
+ import { readFileSync as readFileSync8, writeFileSync as writeFileSync6, existsSync as existsSync8, mkdirSync as mkdirSync3 } from "fs";
958
+ import { join as join9, dirname as dirname2 } from "path";
959
+ import matter6 from "gray-matter";
960
+ import Anthropic from "@anthropic-ai/sdk";
961
+ import pLimit from "p-limit";
1813
962
  var translateDocsSchema = z13.object({
1814
963
  projectDir: z13.string().describe("Path to the Thally project directory"),
1815
964
  locale: z13.string().describe('Target locale code, e.g. "es", "fr"'),
@@ -1819,8 +968,8 @@ var translateDocsSchema = z13.object({
1819
968
  model: z13.string().optional().default("claude-sonnet-4-6").describe("Claude model to use for translation")
1820
969
  });
1821
970
  function readDocsJson2(projectDir) {
1822
- const docsPath = join12(projectDir, "docs.json");
1823
- const raw = readFileSync11(docsPath, "utf8");
971
+ const docsPath = join9(projectDir, "docs.json");
972
+ const raw = readFileSync8(docsPath, "utf8");
1824
973
  return JSON.parse(raw);
1825
974
  }
1826
975
  function collectPageIds(pages) {
@@ -1862,12 +1011,12 @@ function getAllPageIds(config) {
1862
1011
  return { ids, hrefOnlyPages };
1863
1012
  }
1864
1013
  function findSourceFile(projectDir, pageId) {
1865
- const contentRoot = join12(projectDir, "src", "content");
1014
+ const contentRoot = join9(projectDir, "src", "content");
1866
1015
  const candidates = [
1867
- join12(contentRoot, `${pageId}.mdx`),
1868
- join12(contentRoot, `${pageId}/index.mdx`)
1016
+ join9(contentRoot, `${pageId}.mdx`),
1017
+ join9(contentRoot, `${pageId}/index.mdx`)
1869
1018
  ];
1870
- return candidates.find((p) => existsSync11(p)) ?? null;
1019
+ return candidates.find((p) => existsSync8(p)) ?? null;
1871
1020
  }
1872
1021
  var TRANSLATION_SYSTEM_PROMPT = `You are a professional documentation translator. You will receive an MDX documentation file and translate it into the target language.
1873
1022
 
@@ -1919,7 +1068,7 @@ async function handleTranslateDocs(input) {
1919
1068
  }
1920
1069
  const { ids: allPageIds, hrefOnlyPages } = getAllPageIds(config);
1921
1070
  const targetPageIds = pages ?? allPageIds;
1922
- const contentRoot = join12(projectDir, "src", "content");
1071
+ const contentRoot = join9(projectDir, "src", "content");
1923
1072
  const toTranslate = [];
1924
1073
  const skipped = [];
1925
1074
  for (const pageId of targetPageIds) {
@@ -1929,8 +1078,8 @@ async function handleTranslateDocs(input) {
1929
1078
  continue;
1930
1079
  }
1931
1080
  const relativeFromContent = sourceFile.slice(contentRoot.length + 1);
1932
- const targetFile = join12(contentRoot, locale, relativeFromContent);
1933
- if (existsSync11(targetFile) && !force) {
1081
+ const targetFile = join9(contentRoot, locale, relativeFromContent);
1082
+ if (existsSync8(targetFile) && !force) {
1934
1083
  skipped.push(`${pageId} (already translated)`);
1935
1084
  continue;
1936
1085
  }
@@ -1939,21 +1088,21 @@ async function handleTranslateDocs(input) {
1939
1088
  if (toTranslate.length === 0) {
1940
1089
  return `Nothing to translate. ${skipped.length} page(s) skipped.`;
1941
1090
  }
1942
- const client = new Anthropic2({ apiKey });
1943
- const limit = pLimit2(3);
1091
+ const client = new Anthropic({ apiKey });
1092
+ const limit = pLimit(3);
1944
1093
  const results = [];
1945
1094
  await Promise.all(
1946
1095
  toTranslate.map(
1947
1096
  ({ pageId, sourceFile, targetFile }) => limit(async () => {
1948
1097
  try {
1949
- const sourceContent = readFileSync11(sourceFile, "utf8");
1950
- const parsed = matter7(sourceContent);
1098
+ const sourceContent = readFileSync8(sourceFile, "utf8");
1099
+ const parsed = matter6(sourceContent);
1951
1100
  if (!parsed.data.title) {
1952
1101
  console.warn(`[translate] ${pageId}: missing title in frontmatter`);
1953
1102
  }
1954
1103
  const translated = await translatePage(sourceContent, targetLocale.label, locale, model, client);
1955
- mkdirSync4(dirname3(targetFile), { recursive: true });
1956
- writeFileSync7(targetFile, translated + "\n", "utf8");
1104
+ mkdirSync3(dirname2(targetFile), { recursive: true });
1105
+ writeFileSync6(targetFile, translated + "\n", "utf8");
1957
1106
  results.push({ pageId, success: true });
1958
1107
  } catch (err) {
1959
1108
  const msg = err instanceof Error ? err.message : String(err);