@vercel/geistdocs 2.6.0 → 2.7.0

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 (91) hide show
  1. package/dist/cli/index.js +1 -1
  2. package/dist/internal/github-button.d.ts.map +1 -1
  3. package/dist/internal/github-button.js +2 -1
  4. package/dist/internal/mdx-to-markdown.d.ts.map +1 -1
  5. package/dist/internal/mdx-to-markdown.js +465 -27
  6. package/dist/providers/public/components/badge.d.ts +13 -6
  7. package/dist/providers/public/components/badge.d.ts.map +1 -1
  8. package/dist/providers/public/components/badge.js +54 -9
  9. package/dist/providers/public/components/code-block-server.d.ts.map +1 -1
  10. package/dist/providers/public/components/code-block-server.js +13 -3
  11. package/dist/providers/public/components/filename-icon.d.ts +3 -0
  12. package/dist/providers/public/components/filename-icon.d.ts.map +1 -0
  13. package/dist/providers/public/components/filename-icon.js +13 -0
  14. package/dist/providers/public/components/input.d.ts +27 -0
  15. package/dist/providers/public/components/input.d.ts.map +1 -0
  16. package/dist/providers/public/components/input.js +27 -0
  17. package/dist/providers/public/components/theme-switcher.d.ts +5 -1
  18. package/dist/providers/public/components/theme-switcher.d.ts.map +1 -1
  19. package/dist/providers/public/components/theme-switcher.js +7 -3
  20. package/dist/providers/public/components/toggle.d.ts +26 -0
  21. package/dist/providers/public/components/toggle.d.ts.map +1 -0
  22. package/dist/providers/public/components/toggle.js +53 -0
  23. package/dist/providers/public/components/tooltip.d.ts +33 -7
  24. package/dist/providers/public/components/tooltip.d.ts.map +1 -1
  25. package/dist/providers/public/components/tooltip.js +19 -1
  26. package/dist/providers/public-assets/icons.d.ts +1 -0
  27. package/dist/providers/public-assets/icons.d.ts.map +1 -1
  28. package/dist/providers/public-assets/icons.js +1 -0
  29. package/docs/agents.md +25 -2
  30. package/docs/llms.txt +975 -14
  31. package/docs/manifest.json +211 -4
  32. package/docs/pages/components/badge.md +30 -0
  33. package/docs/pages/components/button.md +28 -0
  34. package/docs/pages/components/callout.md +28 -0
  35. package/docs/pages/components/code-block-tabs.md +49 -0
  36. package/docs/pages/components/code-block.md +26 -0
  37. package/docs/pages/components/collapsible.md +38 -0
  38. package/docs/pages/components/command-prompt.md +59 -0
  39. package/docs/pages/components/copy-prompt.md +25 -0
  40. package/docs/pages/components/details.md +37 -0
  41. package/docs/pages/components/dropdown-menu.md +43 -0
  42. package/docs/pages/components/image.md +36 -0
  43. package/docs/pages/components/index.md +49 -0
  44. package/docs/pages/components/input.md +35 -0
  45. package/docs/pages/components/link.md +28 -0
  46. package/docs/pages/components/mermaid.md +29 -0
  47. package/docs/pages/components/navigation-menu.md +50 -0
  48. package/docs/pages/components/popover.md +38 -0
  49. package/docs/pages/components/scroll-area.md +40 -0
  50. package/docs/pages/components/tabs.md +47 -0
  51. package/docs/pages/components/theme-switcher.md +32 -0
  52. package/docs/pages/components/toggle.md +37 -0
  53. package/docs/pages/components/tooltip.md +36 -0
  54. package/docs/pages/components/video.md +26 -0
  55. package/docs/pages/index.md +1 -1
  56. package/docs/pages/migration.md +4 -4
  57. package/docs/pages/syntax.md +7 -7
  58. package/docs/sitemap.md +24 -1
  59. package/package.json +29 -1
  60. package/public-foundation.css +1 -1
  61. package/template/components/geistdocs/toggle-demo.tsx +14 -0
  62. package/template/content/docs/components/badge.mdx +26 -0
  63. package/template/content/docs/components/button.mdx +24 -0
  64. package/template/content/docs/components/callout.mdx +24 -0
  65. package/template/content/docs/components/code-block-tabs.mdx +45 -0
  66. package/template/content/docs/components/code-block.mdx +22 -0
  67. package/template/content/docs/components/collapsible.mdx +34 -0
  68. package/template/content/docs/components/command-prompt.mdx +55 -0
  69. package/template/content/docs/components/copy-prompt.mdx +23 -0
  70. package/template/content/docs/components/details.mdx +33 -0
  71. package/template/content/docs/components/dropdown-menu.mdx +39 -0
  72. package/template/content/docs/components/image.mdx +32 -0
  73. package/template/content/docs/components/index.mdx +45 -0
  74. package/template/content/docs/components/input.mdx +31 -0
  75. package/template/content/docs/components/link.mdx +24 -0
  76. package/template/content/docs/components/mermaid.mdx +25 -0
  77. package/template/content/docs/components/meta.json +25 -1
  78. package/template/content/docs/components/navigation-menu.mdx +46 -0
  79. package/template/content/docs/components/popover.mdx +34 -0
  80. package/template/content/docs/components/scroll-area.mdx +36 -0
  81. package/template/content/docs/components/tabs.mdx +43 -0
  82. package/template/content/docs/components/theme-switcher.mdx +28 -0
  83. package/template/content/docs/components/toggle.mdx +33 -0
  84. package/template/content/docs/components/tooltip.mdx +32 -0
  85. package/template/content/docs/components/video.mdx +22 -0
  86. package/template/content/docs/index.mdx +1 -1
  87. package/template/content/docs/meta.json +1 -1
  88. package/template/content/docs/migration.mdx +4 -4
  89. package/template/content/docs/syntax.cn.mdx +3 -3
  90. package/template/content/docs/syntax.mdx +7 -7
  91. package/template/package.json +1 -1
package/dist/cli/index.js CHANGED
@@ -4,4 +4,4 @@ import{Option as Rn,program as A}from"commander";import{access as Ke,copyFile as
4
4
  `);throw new AggregateError(i,`Mixedbread search sync did not complete:
5
5
  ${a}`)}return r},Ft=async({client:e,file:t,pollIntervalMs:n,pollTimeoutMs:r,sleep:i})=>{let s=t,o=Date.now()+r;for(;s.status==="pending"||s.status==="in_progress";){if(Date.now()>=o)throw new Error(`Mixedbread timed out while indexing file ${t.id}.`);await i(n),s=await e.retrieveStoreFile(t.id)}if(s.status!=="completed")throw new Error(`Mixedbread failed to index file ${t.id} (${s.status}).`);return s},Dt=async({client:e,desired:t,pollIntervalMs:n,pollTimeoutMs:r,sleep:i})=>{let s=await e.uploadFile({content:t.document.content,filename:`${U(t.document.id).slice(0,32)}.md`}),o;try{o=await e.createStoreFile({externalId:t.externalId,fileId:s,metadata:{...t.metadata,[g.rawFileId]:s}})}catch(a){try{await e.deleteFile(s)}catch(d){throw new AggregateError([a,d],`Mixedbread failed to attach and clean up raw file ${s}.`)}throw a}return Ft({client:e,file:o,pollIntervalMs:n,pollTimeoutMs:r,sleep:i})},Ie=async({client:e,concurrency:t=St,manifest:n,pollIntervalMs:r=_t,pollTimeoutMs:i=Tt,revision:s,revisionAncestors:o=[],revisionTimestamp:a,sleep:d=Rt})=>{let c=_e(n);if(c.provider!=="mixedbread")return{deleted:0,skipped:c.documents.length,uploaded:0};let u=c.siteId?.trim();if(!u)throw new Error("Mixedbread retrieval requires a non-empty siteId in geistdocs.tsx.");if(c.documents.length===0)throw new Error("The Geistdocs search export is empty. Refusing to remove indexed documents.");let l=c.documents.map(p=>At(p,u,s,o,a)),m=new Map(l.map(p=>[p.document.id,p])),h=(await be(e)).flatMap(p=>{let y=q(p.metadata);return y?.siteId===u?[{file:p,metadata:y}]:[]}),x=new Map,P=new Set;for(let p of h){W(p.metadata,s,a)&&P.add(p.metadata.documentId);let y=m.get(p.metadata.documentId);y&&p.metadata.contentHash===y.hash&&p.file.status==="completed"&&!x.has(p.metadata.documentId)&&x.set(p.metadata.documentId,p)}let _=l.filter(p=>!(x.has(p.document.id)||P.has(p.document.id)));await Ee(_,t,p=>Dt({client:e,desired:p,pollIntervalMs:r,pollTimeoutMs:i,sleep:d}));let b=(await be(e)).flatMap(p=>{let y=q(p.metadata);return y?.siteId===u?[{file:p,metadata:y}]:[]}),D=new Set(b.filter(({metadata:p})=>W(p,s,a)).map(({metadata:p})=>p.documentId)),ie=new Set;for(let p of l){if(D.has(p.document.id))continue;let ae=b.filter(({file:V,metadata:k})=>V.status==="completed"&&k.documentId===p.document.id&&k.contentHash===p.hash).sort((V,k)=>V.file.id.localeCompare(k.file.id))[0];ae&&ie.add(ae.file.id)}let oe=b.filter(({file:p,metadata:y})=>p.status!=="pending"&&p.status!=="in_progress"&&!W(y,s,a)&&Mt({currentRevision:s,currentRevisionAncestors:o,currentRevisionTimestamp:a,desired:m.get(y.documentId),metadata:y})&&!ie.has(p.id));return await Ee(oe,t,async({file:p,metadata:y})=>{await e.deleteFile(y.rawFileId??p.id),await e.deleteStoreFile(p.id)}),{deleted:oe.length,skipped:l.length-_.length,uploaded:_.length}};var Ot=50,$t=e=>`vercel integration add mixedbread --name docs-${e||"your-site-id"} --environment production`,ve=(e,t)=>kt("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),Nt=e=>{let t=process.env.VERCEL_GIT_COMMIT_SHA?.trim(),n=[];try{n=ve(e,["rev-list",`--max-count=${Ot+1}`,t||"HEAD"]).split(`
6
6
  `).filter(Boolean)}catch{n=[]}let r=t||n[0],i;for(let s of Array.from(new Set([r,"HEAD"].filter(Boolean))))try{let o=Number(ve(e,["show","-s","--format=%ct",s]));if(Number.isFinite(o)){i=o;break}}catch{}return{revision:r,revisionAncestors:n.filter(s=>s!==r),revisionTimestamp:i}},Pe=async({allowNonProduction:e=!1,dir:t=".next"}={})=>{let n=process.cwd();Ct.loadEnvConfig(n,!1);let r=process.env.MXBAI_API_KEY?.trim(),i=process.env.MXBAI_STORE_ID?.trim();if(process.env.VERCEL_ENV!=="production"&&!e){console.log("Geistdocs search sync skipped: this is not a production Vercel build.");return}if(!!r!=!!i)throw new Error("Mixedbread is partially configured. Set both MXBAI_API_KEY and MXBAI_STORE_ID.");let s;try{s=await Te({cwd:n,outputDirectory:t})}catch(a){if(!(r||i)){console.log("Geistdocs search sync skipped: no Mixedbread credentials or static search export were found.");return}throw a}if(s.provider!=="mixedbread"){console.log("Geistdocs search sync skipped: Ask AI uses local retrieval.");return}if(!(r&&i))throw new Error(["Mixedbread retrieval is enabled, but MXBAI_API_KEY or MXBAI_STORE_ID is missing.","From the root of this site's repository, linked to the correct Vercel project, run:",$t(s.siteId)].join(`
7
- `));let o=await Ie({client:we({apiBaseUrl:process.env.MXBAI_BASE_URL,apiKey:r,storeId:i}),manifest:s,...Nt(n)});console.log(`Geistdocs search sync complete: ${o.uploaded} uploaded, ${o.deleted} deleted, ${o.skipped} unchanged.`)};import{readFileSync as Gt,writeFileSync as Ut}from"fs";import{mkdir as Lt,readFile as Z,writeFile as jt}from"fs/promises";import{dirname as Bt,extname as Vt,relative as Fe,resolve as j}from"path";import{intro as Jt,isCancel as Ht,log as I,multiselect as Xt,outro as L,spinner as Kt}from"@clack/prompts";import{glob as Yt}from"glob";import{Node as F,Project as qt,SyntaxKind as zt}from"ts-morph";var Wt="geistdocs.tsx",Qt="content/docs/**/*.mdx",ee=".translation-cache.json",Q=8,Ae=()=>({version:1,entries:{}}),Zt=async e=>{let t=await Z(e),{createHash:n}=await import("crypto");return n("sha256").update(t).digest("hex")},en=e=>{let t=j(process.cwd(),e);return Gt(t,"utf8")},Me=e=>F.isObjectLiteralExpression(e)?e.getProperties().flatMap(t=>{if(F.isPropertyAssignment(t)){let n=t.getNameNode();if(F.isIdentifier(n)||F.isStringLiteral(n))return[n.getText().replaceAll(/['"]/g,"")]}return[]}).filter(Boolean):[],tn=e=>{try{let t=new qt({compilerOptions:{allowJs:!0,jsx:4,module:99,target:10},skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!0}),n=en(e),s=t.createSourceFile(e,n,{overwrite:!0}).getVariableDeclarations().find(a=>a.getName()==="translations")?.getInitializer();if(!s)return[];if(F.isObjectLiteralExpression(s))return Me(s);let o=s.getFirstDescendantByKind(zt.ObjectLiteralExpression);return o?Me(o):[]}catch(t){let n=t instanceof Error?t.message:`${t}`;return I.warn(`Failed to read locales from ${e}: ${n}`),[]}},nn=async()=>{let e=await Xt({message:"Which locales should be translated?",options:[{value:"cn",label:"Chinese (cn)"},{value:"jp",label:"Japanese (jp)"},{value:"es",label:"Spanish (es)"},{value:"fr",label:"French (fr)"},{value:"de",label:"German (de)"}],required:!0});return Ht(e)&&(L("Translation cancelled"),process.exit(0)),e},rn=async e=>(await Yt(e,{cwd:process.cwd(),absolute:!0,nodir:!0})).sort(),sn=async()=>{let e=j(process.cwd(),ee);try{let t=await Z(e,"utf8"),n=JSON.parse(t);return n.version!==1||!n.entries?Ae():{version:1,entries:n.entries}}catch{return Ae()}},Re=e=>{let t=j(process.cwd(),ee),n=JSON.stringify(e,null,2);Ut(t,n,"utf8")},on=async e=>{let t=await Promise.all(e.map(async n=>[n,await Zt(n)]));return Object.fromEntries(t)},an=(e,t)=>{let n=Vt(e);return`${e.slice(0,-n.length)}.${t}${n}`},De=(e,t)=>`${Fe(process.cwd(),e)}::${t}`,cn=(e,t,n,r,i=!1)=>{let s=[],o=0;for(let a of t){let d=n[a];for(let c of e){let u=an(a,c),l=De(a,c),m=r.entries[l];if(!i&&m?.hash===d){o+=1;continue}s.push({locale:c,sourceFile:a,sourceHash:d,targetFile:u})}}return{tasks:s,skippedCount:o}},dn=async e=>{await Lt(Bt(e),{recursive:!0})},ln=async(e,t,n)=>{let r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:t,locale:n})});if(!r.ok){let s=await r.text();throw new Error(`API request failed (${r.status}): ${s}`)}let i=await r.json();if(!i.translation)throw new Error("API response did not include a translation");return i.translation},pn=async(e,t,n)=>{let r=await Z(e.sourceFile,"utf8"),i=await ln(t,r,e.locale);await dn(e.targetFile),await jt(e.targetFile,i,"utf8"),n.entries[De(e.sourceFile,e.locale)]={hash:e.sourceHash,updatedAt:new Date().toISOString()}},ke=async(e,t)=>{Jt("Translate MDX content");let n=e??Qt,r=t.url||process.env.GEISTDOCS_TRANSLATE_URL||"https://geistdocs.com/translate",i=tn(t.config??Wt),s=await rn(n);s.length===0&&(I.error(`No MDX files found matching pattern: ${n}`),L("Translation cancelled"),process.exit(1)),I.info(`Found ${s.length} MDX file(s) matching pattern`),i.length===0&&(i=await nn());let o=j(process.cwd(),ee),a=await sn();await Re(a),I.info(`Using cache: ${o}`);let d=await on(s),{tasks:c,skippedCount:u}=cn(i,s,d,a,t.force);if(c.length===0){I.success("All translations are up to date!"),L(`Skipped ${u} file(s) (unchanged)`);return}let l=[];for(let h=0;h<c.length;h+=Q)l.push(c.slice(h,h+Q));I.info(`Processing ${c.length} translation(s) in ${l.length} batch(es) of up to ${Q}`),u>0&&I.info(`Skipped ${u} translation(s) (unchanged)`);let m=Kt();m.start("Translating content...");let f=0;for(let h of l)await Promise.all(h.map(async x=>{await pn(x,r,a),f+=1,m.message(`Translated ${f}/${c.length}: ${Fe(process.cwd(),x.targetFile)}`)})),await Re(a);m.stop("Translation complete!"),L(`Created/updated ${c.length} file(s)`)};import{access as un,copyFile as gn,mkdir as Ne,rm as re}from"fs/promises";import{dirname as mn,join as v}from"path";import{intro as fn,log as w,outro as B,spinner as Ge}from"@clack/prompts";import{glob as hn}from"glob";var wn=["**/*"],yn=["content/docs/**"],te=".geistdocs-tmp",xn=async(e,t)=>{let n=v(e,t);await re(n,{recursive:!0,force:!0}),await Ne(n,{recursive:!0})},ne=async e=>await re(e,{recursive:!0,force:!0}),Ce=async(e,t,n)=>(await hn(e,{cwd:n,nodir:!0,dot:!0,ignore:[".git/**",...t]})).sort(),bn=async e=>{try{return await un(e),!0}catch{return!1}},En=async(e,t,n)=>{let r=v(t,e),i=v(n,e);return await bn(r)?(await gn(r,i),{success:!0}):{success:!1,error:`Source file not found: ${r}`}},Sn=async(e,t)=>{let n=v(t,e);return await re(n,{force:!0}),{success:!0}},Oe=20,$e=async(e,t,n)=>{let r=[];for(let i=0;i<e.length;i+=n){let s=e.slice(i,i+n),o=await Promise.all(s.map(t));r.push(...o)}return r},_n=async(e,t,n,r,i)=>{let s={success:[],deleted:[],failed:[]},o=[...new Set(e.map(d=>mn(v(r,d))))];i.message(`Creating ${o.length} directories...`),await Promise.all(o.map(d=>Ne(d,{recursive:!0}))),i.message(`Updating ${e.length} files...`);let a=await $e(e,async d=>{let c=await En(d,n,r);return{file:d,...c}},Oe);for(let{file:d,success:c,error:u}of a)c?s.success.push(d):s.failed.push({file:d,error:u??"Unknown error"});if(t.length>0){i.message(`Deleting ${t.length} files...`);let d=await $e(t,async c=>{try{return await Sn(c,r),{file:c,success:!0}}catch(u){let l=u instanceof Error?u.message:`${u}`;return{file:c,success:!1,error:l}}},Oe);for(let c of d)c.success?s.deleted.push(c.file):s.failed.push({file:c.file,error:c.error})}return s},Tn=e=>{if(e.success.length>0){w.success(`Successfully updated ${e.success.length} files:`);for(let t of e.success)w.info(` \u2713 ${t}`)}if(e.deleted.length>0){w.success(`Deleted ${e.deleted.length} files:`);for(let t of e.deleted)w.info(` \u{1F5D1} ${t}`)}if(e.failed.length>0){w.warn(`Failed to update ${e.failed.length} files:`);for(let{file:t,error:n}of e.failed)w.error(` \u2717 ${t}: ${n}`)}},In=e=>e.includes("canary")?"canary":"latest",vn=async e=>{let t=await fetch(`https://registry.npmjs.org/${encodeURIComponent(S)}`);if(!t.ok)throw new Error(`Failed to resolve ${S}@${e}`);let r=(await t.json())["dist-tags"]?.[e];if(!r)throw new Error(`Could not find dist-tag ${e} for ${S}`);return r},Pn=async e=>{let t=await M(e),n=J(t,S);if(!n)return{currentVersion:n,nextVersion:void 0,updated:!1};let r=In(n),i=await vn(r);return n===i?{currentVersion:n,nextVersion:i,updateTag:r,updated:!1}:($(t,S,i),await O(e,t),{currentVersion:n,nextVersion:i,updateTag:r,updated:!0})},An=async(e,t,n)=>{let r=await M(e);if(!le(r,S))return!1;t&&t.length>0&&w.warn("Ignoring file patterns for a package-based site. This update will bump the package version instead."),n?.sync&&w.warn("Ignoring --sync for a package-based site. Runtime updates now come from the package version.");let{currentVersion:i,nextVersion:s,updateTag:o,updated:a}=await Pn(e);if(!a)return w.success(i?`@vercel/geistdocs is already at ${s} (${o}).`:"No package version update was needed."),B("Package-based site is already up to date."),!0;w.info(`Bumping ${S} from ${i} to ${s} (${o})`);let d=Ge();return d.start("Installing updated package version..."),await T("pnpm",["install"],{cwd:e}),d.stop("Package update complete!"),B("Please review and test the upgraded package version."),!0},Mn=async(e,t,n,r,i)=>{let s=v(e,te),o=Ge(),a=i?.sync?s:t;o.start("Preparing template snapshot..."),i?.sync&&(await xn(e,te),await N(s)),o.message("Scanning for files...");let d=await Ce(n,r,a),c=[];if(i?.sync){o.message("Comparing with local files...");let l=await Ce(n,r,e),m=new Set(d);c=l.filter(f=>!m.has(f))}if(o.stop(`Found ${d.length} files to update`),d.length===0&&c.length===0){w.warn("No files matched the patterns. Nothing to update."),i?.sync&&await ne(s),B("Update cancelled.");return}w.info(`Patterns: ${n.length}`),w.info(`Files to update: ${d.length}`),i?.sync&&w.info(`Files to delete: ${c.length}`),o.start("Updating files...");let u=await _n(d,c,a,e,o);i?.sync&&(o.message("Cleaning up..."),await ne(s)),o.stop("Update complete!"),Tn(u),B("Please review and test the changes carefully.")},Ue=async(e,t)=>{let n=process.cwd(),r=H(),i=e&&e.length>0?e:wn,s=e&&e.length>0?[]:yn;try{if(fn("Let's update your Geistdocs project!"),await An(n,e,t))return;w.info("Template source: bundled package snapshot"),e&&e.length>0&&w.info(`Updating specific files: ${e.join(", ")}`),t?.sync&&w.info("Sync mode enabled: will delete files removed from template"),await Mn(n,r,i,s,t)}catch(o){let a=o instanceof Error?o.message:`${o}`;try{await ne(v(n,te))}catch{}w.error(`Failed to update project: ${a}`),process.exit(1)}};A.name("geistdocs").description("CLI for Geistdocs projects").version("2.6.0","-v, --version","Output the current version");A.command("init").description("Initialize a new Geistdocs project").option("--name <name>","Name of the project").addOption(new Rn("--brand <brand>","Navbar brand").choices(["vercel","labs"]).default("vercel")).option("--disable-git","Disable git initialization").action(he);A.command("update [files...]").description("Update a Geistdocs project (optionally specify files/patterns to update)").option("--sync","Delete local files that no longer exist in the template").action(Ue);A.command("translate [pattern]").description("Translate MDX file(s) to one or more locales (default: content/docs/**/*.mdx)").option("--config <path>","Path to config file to load locales from (defaults to geistdocs.tsx)").option("--url <url>","Custom translation API URL (defaults to GEISTDOCS_TRANSLATE_URL or https://geistdocs.com/translate)").option("--force","Force re-translation of all files, ignoring cache").action(ke);var Fn=A.command("search").description("Manage the external search index used by Ask AI");Fn.command("sync").description("Sync the latest static docs export to Mixedbread").option("--dir <path>","Next.js output directory",".next").option("--allow-non-production","Run outside a production Vercel build").action(Pe);await A.parseAsync(process.argv).catch(e=>{console.error(e instanceof Error?e.message:e),process.exitCode=1});
7
+ `));let o=await Ie({client:we({apiBaseUrl:process.env.MXBAI_BASE_URL,apiKey:r,storeId:i}),manifest:s,...Nt(n)});console.log(`Geistdocs search sync complete: ${o.uploaded} uploaded, ${o.deleted} deleted, ${o.skipped} unchanged.`)};import{readFileSync as Gt,writeFileSync as Ut}from"fs";import{mkdir as Lt,readFile as Z,writeFile as jt}from"fs/promises";import{dirname as Bt,extname as Vt,relative as Fe,resolve as j}from"path";import{intro as Jt,isCancel as Ht,log as I,multiselect as Xt,outro as L,spinner as Kt}from"@clack/prompts";import{glob as Yt}from"glob";import{Node as F,Project as qt,SyntaxKind as zt}from"ts-morph";var Wt="geistdocs.tsx",Qt="content/docs/**/*.mdx",ee=".translation-cache.json",Q=8,Ae=()=>({version:1,entries:{}}),Zt=async e=>{let t=await Z(e),{createHash:n}=await import("crypto");return n("sha256").update(t).digest("hex")},en=e=>{let t=j(process.cwd(),e);return Gt(t,"utf8")},Me=e=>F.isObjectLiteralExpression(e)?e.getProperties().flatMap(t=>{if(F.isPropertyAssignment(t)){let n=t.getNameNode();if(F.isIdentifier(n)||F.isStringLiteral(n))return[n.getText().replaceAll(/['"]/g,"")]}return[]}).filter(Boolean):[],tn=e=>{try{let t=new qt({compilerOptions:{allowJs:!0,jsx:4,module:99,target:10},skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!0}),n=en(e),s=t.createSourceFile(e,n,{overwrite:!0}).getVariableDeclarations().find(a=>a.getName()==="translations")?.getInitializer();if(!s)return[];if(F.isObjectLiteralExpression(s))return Me(s);let o=s.getFirstDescendantByKind(zt.ObjectLiteralExpression);return o?Me(o):[]}catch(t){let n=t instanceof Error?t.message:`${t}`;return I.warn(`Failed to read locales from ${e}: ${n}`),[]}},nn=async()=>{let e=await Xt({message:"Which locales should be translated?",options:[{value:"cn",label:"Chinese (cn)"},{value:"jp",label:"Japanese (jp)"},{value:"es",label:"Spanish (es)"},{value:"fr",label:"French (fr)"},{value:"de",label:"German (de)"}],required:!0});return Ht(e)&&(L("Translation cancelled"),process.exit(0)),e},rn=async e=>(await Yt(e,{cwd:process.cwd(),absolute:!0,nodir:!0})).sort(),sn=async()=>{let e=j(process.cwd(),ee);try{let t=await Z(e,"utf8"),n=JSON.parse(t);return n.version!==1||!n.entries?Ae():{version:1,entries:n.entries}}catch{return Ae()}},Re=e=>{let t=j(process.cwd(),ee),n=JSON.stringify(e,null,2);Ut(t,n,"utf8")},on=async e=>{let t=await Promise.all(e.map(async n=>[n,await Zt(n)]));return Object.fromEntries(t)},an=(e,t)=>{let n=Vt(e);return`${e.slice(0,-n.length)}.${t}${n}`},De=(e,t)=>`${Fe(process.cwd(),e)}::${t}`,cn=(e,t,n,r,i=!1)=>{let s=[],o=0;for(let a of t){let d=n[a];for(let c of e){let u=an(a,c),l=De(a,c),m=r.entries[l];if(!i&&m?.hash===d){o+=1;continue}s.push({locale:c,sourceFile:a,sourceHash:d,targetFile:u})}}return{tasks:s,skippedCount:o}},dn=async e=>{await Lt(Bt(e),{recursive:!0})},ln=async(e,t,n)=>{let r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:t,locale:n})});if(!r.ok){let s=await r.text();throw new Error(`API request failed (${r.status}): ${s}`)}let i=await r.json();if(!i.translation)throw new Error("API response did not include a translation");return i.translation},pn=async(e,t,n)=>{let r=await Z(e.sourceFile,"utf8"),i=await ln(t,r,e.locale);await dn(e.targetFile),await jt(e.targetFile,i,"utf8"),n.entries[De(e.sourceFile,e.locale)]={hash:e.sourceHash,updatedAt:new Date().toISOString()}},ke=async(e,t)=>{Jt("Translate MDX content");let n=e??Qt,r=t.url||process.env.GEISTDOCS_TRANSLATE_URL||"https://geistdocs.com/translate",i=tn(t.config??Wt),s=await rn(n);s.length===0&&(I.error(`No MDX files found matching pattern: ${n}`),L("Translation cancelled"),process.exit(1)),I.info(`Found ${s.length} MDX file(s) matching pattern`),i.length===0&&(i=await nn());let o=j(process.cwd(),ee),a=await sn();await Re(a),I.info(`Using cache: ${o}`);let d=await on(s),{tasks:c,skippedCount:u}=cn(i,s,d,a,t.force);if(c.length===0){I.success("All translations are up to date!"),L(`Skipped ${u} file(s) (unchanged)`);return}let l=[];for(let h=0;h<c.length;h+=Q)l.push(c.slice(h,h+Q));I.info(`Processing ${c.length} translation(s) in ${l.length} batch(es) of up to ${Q}`),u>0&&I.info(`Skipped ${u} translation(s) (unchanged)`);let m=Kt();m.start("Translating content...");let f=0;for(let h of l)await Promise.all(h.map(async x=>{await pn(x,r,a),f+=1,m.message(`Translated ${f}/${c.length}: ${Fe(process.cwd(),x.targetFile)}`)})),await Re(a);m.stop("Translation complete!"),L(`Created/updated ${c.length} file(s)`)};import{access as un,copyFile as gn,mkdir as Ne,rm as re}from"fs/promises";import{dirname as mn,join as v}from"path";import{intro as fn,log as w,outro as B,spinner as Ge}from"@clack/prompts";import{glob as hn}from"glob";var wn=["**/*"],yn=["content/docs/**"],te=".geistdocs-tmp",xn=async(e,t)=>{let n=v(e,t);await re(n,{recursive:!0,force:!0}),await Ne(n,{recursive:!0})},ne=async e=>await re(e,{recursive:!0,force:!0}),Ce=async(e,t,n)=>(await hn(e,{cwd:n,nodir:!0,dot:!0,ignore:[".git/**",...t]})).sort(),bn=async e=>{try{return await un(e),!0}catch{return!1}},En=async(e,t,n)=>{let r=v(t,e),i=v(n,e);return await bn(r)?(await gn(r,i),{success:!0}):{success:!1,error:`Source file not found: ${r}`}},Sn=async(e,t)=>{let n=v(t,e);return await re(n,{force:!0}),{success:!0}},Oe=20,$e=async(e,t,n)=>{let r=[];for(let i=0;i<e.length;i+=n){let s=e.slice(i,i+n),o=await Promise.all(s.map(t));r.push(...o)}return r},_n=async(e,t,n,r,i)=>{let s={success:[],deleted:[],failed:[]},o=[...new Set(e.map(d=>mn(v(r,d))))];i.message(`Creating ${o.length} directories...`),await Promise.all(o.map(d=>Ne(d,{recursive:!0}))),i.message(`Updating ${e.length} files...`);let a=await $e(e,async d=>{let c=await En(d,n,r);return{file:d,...c}},Oe);for(let{file:d,success:c,error:u}of a)c?s.success.push(d):s.failed.push({file:d,error:u??"Unknown error"});if(t.length>0){i.message(`Deleting ${t.length} files...`);let d=await $e(t,async c=>{try{return await Sn(c,r),{file:c,success:!0}}catch(u){let l=u instanceof Error?u.message:`${u}`;return{file:c,success:!1,error:l}}},Oe);for(let c of d)c.success?s.deleted.push(c.file):s.failed.push({file:c.file,error:c.error})}return s},Tn=e=>{if(e.success.length>0){w.success(`Successfully updated ${e.success.length} files:`);for(let t of e.success)w.info(` \u2713 ${t}`)}if(e.deleted.length>0){w.success(`Deleted ${e.deleted.length} files:`);for(let t of e.deleted)w.info(` \u{1F5D1} ${t}`)}if(e.failed.length>0){w.warn(`Failed to update ${e.failed.length} files:`);for(let{file:t,error:n}of e.failed)w.error(` \u2717 ${t}: ${n}`)}},In=e=>e.includes("canary")?"canary":"latest",vn=async e=>{let t=await fetch(`https://registry.npmjs.org/${encodeURIComponent(S)}`);if(!t.ok)throw new Error(`Failed to resolve ${S}@${e}`);let r=(await t.json())["dist-tags"]?.[e];if(!r)throw new Error(`Could not find dist-tag ${e} for ${S}`);return r},Pn=async e=>{let t=await M(e),n=J(t,S);if(!n)return{currentVersion:n,nextVersion:void 0,updated:!1};let r=In(n),i=await vn(r);return n===i?{currentVersion:n,nextVersion:i,updateTag:r,updated:!1}:($(t,S,i),await O(e,t),{currentVersion:n,nextVersion:i,updateTag:r,updated:!0})},An=async(e,t,n)=>{let r=await M(e);if(!le(r,S))return!1;t&&t.length>0&&w.warn("Ignoring file patterns for a package-based site. This update will bump the package version instead."),n?.sync&&w.warn("Ignoring --sync for a package-based site. Runtime updates now come from the package version.");let{currentVersion:i,nextVersion:s,updateTag:o,updated:a}=await Pn(e);if(!a)return w.success(i?`@vercel/geistdocs is already at ${s} (${o}).`:"No package version update was needed."),B("Package-based site is already up to date."),!0;w.info(`Bumping ${S} from ${i} to ${s} (${o})`);let d=Ge();return d.start("Installing updated package version..."),await T("pnpm",["install"],{cwd:e}),d.stop("Package update complete!"),B("Please review and test the upgraded package version."),!0},Mn=async(e,t,n,r,i)=>{let s=v(e,te),o=Ge(),a=i?.sync?s:t;o.start("Preparing template snapshot..."),i?.sync&&(await xn(e,te),await N(s)),o.message("Scanning for files...");let d=await Ce(n,r,a),c=[];if(i?.sync){o.message("Comparing with local files...");let l=await Ce(n,r,e),m=new Set(d);c=l.filter(f=>!m.has(f))}if(o.stop(`Found ${d.length} files to update`),d.length===0&&c.length===0){w.warn("No files matched the patterns. Nothing to update."),i?.sync&&await ne(s),B("Update cancelled.");return}w.info(`Patterns: ${n.length}`),w.info(`Files to update: ${d.length}`),i?.sync&&w.info(`Files to delete: ${c.length}`),o.start("Updating files...");let u=await _n(d,c,a,e,o);i?.sync&&(o.message("Cleaning up..."),await ne(s)),o.stop("Update complete!"),Tn(u),B("Please review and test the changes carefully.")},Ue=async(e,t)=>{let n=process.cwd(),r=H(),i=e&&e.length>0?e:wn,s=e&&e.length>0?[]:yn;try{if(fn("Let's update your Geistdocs project!"),await An(n,e,t))return;w.info("Template source: bundled package snapshot"),e&&e.length>0&&w.info(`Updating specific files: ${e.join(", ")}`),t?.sync&&w.info("Sync mode enabled: will delete files removed from template"),await Mn(n,r,i,s,t)}catch(o){let a=o instanceof Error?o.message:`${o}`;try{await ne(v(n,te))}catch{}w.error(`Failed to update project: ${a}`),process.exit(1)}};A.name("geistdocs").description("CLI for Geistdocs projects").version("2.7.0","-v, --version","Output the current version");A.command("init").description("Initialize a new Geistdocs project").option("--name <name>","Name of the project").addOption(new Rn("--brand <brand>","Navbar brand").choices(["vercel","labs"]).default("vercel")).option("--disable-git","Disable git initialization").action(he);A.command("update [files...]").description("Update a Geistdocs project (optionally specify files/patterns to update)").option("--sync","Delete local files that no longer exist in the template").action(Ue);A.command("translate [pattern]").description("Translate MDX file(s) to one or more locales (default: content/docs/**/*.mdx)").option("--config <path>","Path to config file to load locales from (defaults to geistdocs.tsx)").option("--url <url>","Custom translation API URL (defaults to GEISTDOCS_TRANSLATE_URL or https://geistdocs.com/translate)").option("--force","Force re-translation of all files, ignoring cache").action(ke);var Fn=A.command("search").description("Manage the external search index used by Ask AI");Fn.command("sync").description("Sync the latest static docs export to Mixedbread").option("--dir <path>","Next.js output directory",".next").option("--allow-non-production","Run outside a production Vercel build").action(Pe);await A.parseAsync(process.argv).catch(e=>{console.error(e instanceof Error?e.message:e),process.exitCode=1});
@@ -1 +1 @@
1
- {"version":3,"file":"github-button.d.ts","sourceRoot":"","sources":["../../src/internal/github-button.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,WAAW,CAAC;AAEvD,UAAU,iBAAiB;IACzB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,qBAAqB,CAAC;CAChC;AAED,eAAO,MAAM,gBAAgB,GAC3B,SAAS,qBAAqB,KAC7B,MAAM,GAAG,IAGF,CAAC;AAEX,eAAO,MAAM,YAAY,GAAI,uBAAuB,iBAAiB,mDAuBpE,CAAC"}
1
+ {"version":3,"file":"github-button.d.ts","sourceRoot":"","sources":["../../src/internal/github-button.tsx"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,WAAW,CAAC;AAEvD,UAAU,iBAAiB;IACzB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,qBAAqB,CAAC;CAChC;AAED,eAAO,MAAM,gBAAgB,GAC3B,SAAS,qBAAqB,KAC7B,MAAM,GAAG,IAGF,CAAC;AAEX,eAAO,MAAM,YAAY,GAAI,uBAAuB,iBAAiB,mDAuBpE,CAAC"}
@@ -1,6 +1,7 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { LogoIconGithub } from "#geistdocs-assets/logos";
3
3
  import { Button } from "#geistdocs-ui/components/button";
4
+ import { cn } from "#geistdocs-ui/utils";
4
5
  export const getGithubRepoUrl = (github) => github?.owner && github.repo
5
6
  ? `https://github.com/${github.owner}/${github.repo}`
6
7
  : null;
@@ -9,5 +10,5 @@ export const GitHubButton = ({ className, github }) => {
9
10
  if (!url) {
10
11
  return null;
11
12
  }
12
- return (_jsx(Button, { "aria-label": "GitHub repository", Component: "a", className: className, href: url, rel: "noopener", shape: "square", size: "small", svgOnly: true, target: "_blank", type: "unstyled", children: _jsx(LogoIconGithub, { size: 16 }) }));
13
+ return (_jsx(Button, { "aria-label": "GitHub repository", Component: "a", className: cn("size-8 items-center justify-center", className), href: url, rel: "noopener", shape: "square", size: "small", svgOnly: true, target: "_blank", type: "unstyled", children: _jsx(LogoIconGithub, { size: 16 }) }));
13
14
  };
@@ -1 +1 @@
1
- {"version":3,"file":"mdx-to-markdown.d.ts","sourceRoot":"","sources":["../../src/internal/mdx-to-markdown.ts"],"names":[],"mappings":"AAkYA,yEAAyE;AACzE,eAAO,MAAM,aAAa,GAAU,QAAQ,MAAM,oBAcjD,CAAC"}
1
+ {"version":3,"file":"mdx-to-markdown.d.ts","sourceRoot":"","sources":["../../src/internal/mdx-to-markdown.ts"],"names":[],"mappings":"AA43BA,yEAAyE;AACzE,eAAO,MAAM,aAAa,GAAU,QAAQ,MAAM,oBAcjD,CAAC"}
@@ -4,8 +4,42 @@ import remarkMdx from "remark-mdx";
4
4
  import remarkParse from "remark-parse";
5
5
  import remarkStringify from "remark-stringify";
6
6
  import { unified } from "unified";
7
+ const LEADING_WHITESPACE = /^\s+/;
8
+ const TRAILING_WHITESPACE = /\s+$/;
9
+ const WHITESPACE = /\s+/;
10
+ // JSX applies props left to right, so a repeated attribute or a later spread
11
+ // wins at runtime. Read the last literal and distrust it when a spread follows.
12
+ const findAttribute = (node, name) => {
13
+ const attributes = node.attributes ?? [];
14
+ let index = -1;
15
+ for (let position = attributes.length - 1; position >= 0; position -= 1) {
16
+ const entry = attributes[position];
17
+ if (entry.type === "mdxJsxAttribute" && entry.name === name) {
18
+ index = position;
19
+ break;
20
+ }
21
+ }
22
+ if (index < 0 ||
23
+ attributes
24
+ .slice(index + 1)
25
+ .some((entry) => entry.type === "mdxJsxExpressionAttribute")) {
26
+ return undefined;
27
+ }
28
+ return attributes[index];
29
+ };
30
+ function expressionString(node) {
31
+ if (node?.type === "Literal" && typeof node.value === "string") {
32
+ return node.value;
33
+ }
34
+ if (node?.type === "TemplateLiteral" &&
35
+ node.expressions?.length === 0 &&
36
+ node.quasis?.length === 1) {
37
+ return node.quasis[0].value?.cooked ?? node.quasis[0].value?.raw;
38
+ }
39
+ return undefined;
40
+ }
7
41
  const getAttribute = (node, name) => {
8
- const attribute = node.attributes?.find((entry) => entry.type === "mdxJsxAttribute" && entry.name === name);
42
+ const attribute = findAttribute(node, name);
9
43
  if (!attribute) {
10
44
  return undefined;
11
45
  }
@@ -16,14 +50,127 @@ const getAttribute = (node, name) => {
16
50
  const expression = statement?.type === "ExpressionStatement"
17
51
  ? statement.expression
18
52
  : undefined;
19
- return expression?.type === "Literal" && typeof expression.value === "string"
20
- ? expression.value
53
+ return expressionString(expression);
54
+ };
55
+ const getAttributeExpression = (node, name) => {
56
+ const value = findAttribute(node, name)?.value;
57
+ if (!value || typeof value === "string") {
58
+ return undefined;
59
+ }
60
+ const statement = value.data?.estree?.body[0];
61
+ return statement?.type === "ExpressionStatement"
62
+ ? statement.expression
21
63
  : undefined;
22
64
  };
65
+ const propertyName = (node) => {
66
+ if (node.key?.type === "Identifier") {
67
+ return node.key.name;
68
+ }
69
+ return expressionString(node.key);
70
+ };
71
+ const objectProperty = (node, name) => {
72
+ if (node?.type !== "ObjectExpression") {
73
+ return undefined;
74
+ }
75
+ const properties = node.properties ?? [];
76
+ let index = -1;
77
+ for (let position = properties.length - 1; position >= 0; position -= 1) {
78
+ const property = properties[position];
79
+ if (property.type === "Property" &&
80
+ !property.computed &&
81
+ propertyName(property) === name) {
82
+ index = position;
83
+ break;
84
+ }
85
+ }
86
+ if (index < 0 ||
87
+ properties
88
+ .slice(index + 1)
89
+ .some((property) => property.type === "SpreadElement")) {
90
+ return undefined;
91
+ }
92
+ return properties[index].value;
93
+ };
23
94
  const paragraph = (value) => ({
24
95
  children: [{ type: "text", value }],
25
96
  type: "paragraph",
26
97
  });
98
+ const inlineCode = (value) => ({
99
+ type: "inlineCode",
100
+ value,
101
+ });
102
+ const heading = (children, depth = 4) => ({
103
+ children,
104
+ depth,
105
+ type: "heading",
106
+ });
107
+ const BLOCK_NODE_TYPES = new Set([
108
+ "blockquote",
109
+ "code",
110
+ "heading",
111
+ "html",
112
+ "list",
113
+ "paragraph",
114
+ "table",
115
+ "thematicBreak",
116
+ ]);
117
+ const phrasingChildren = (node) => {
118
+ const children = [];
119
+ for (const child of node.children ?? []) {
120
+ if (child.type === "paragraph") {
121
+ const paragraphChildren = child.children ?? [];
122
+ if (children.length > 0 && paragraphChildren.length > 0) {
123
+ children.push({ type: "text", value: " " });
124
+ }
125
+ children.push(...paragraphChildren);
126
+ }
127
+ else if (BLOCK_NODE_TYPES.has(child.type)) {
128
+ return undefined;
129
+ }
130
+ else {
131
+ children.push(child);
132
+ }
133
+ }
134
+ return children;
135
+ };
136
+ const blockChildren = (node, force = false) => {
137
+ const children = node.children ?? [];
138
+ if (!force && node.type !== "mdxJsxFlowElement") {
139
+ return children;
140
+ }
141
+ const blocks = [];
142
+ let phrasing = [];
143
+ const flush = () => {
144
+ const children = phrasing.map((child, index) => {
145
+ if (child.type !== "text" || !child.value) {
146
+ return child;
147
+ }
148
+ let value = child.value;
149
+ if (index === 0) {
150
+ value = value.replace(LEADING_WHITESPACE, "");
151
+ }
152
+ if (index === phrasing.length - 1) {
153
+ value = value.replace(TRAILING_WHITESPACE, "");
154
+ }
155
+ return { ...child, value };
156
+ });
157
+ if (children.some((child) => child.type !== "text" || child.value)) {
158
+ blocks.push({ children, type: "paragraph" });
159
+ }
160
+ phrasing = [];
161
+ };
162
+ for (const child of children) {
163
+ if (BLOCK_NODE_TYPES.has(child.type)) {
164
+ flush();
165
+ blocks.push(child);
166
+ }
167
+ else {
168
+ phrasing.push(child);
169
+ }
170
+ }
171
+ flush();
172
+ return blocks;
173
+ };
27
174
  const OMITTED_NODE_TYPES = new Set([
28
175
  "mdxFlowExpression",
29
176
  "mdxTextExpression",
@@ -44,12 +191,283 @@ const imageNodes = (node) => {
44
191
  type: "paragraph",
45
192
  });
46
193
  }
194
+ else if (alt) {
195
+ nodes.push({
196
+ children: [
197
+ {
198
+ children: [{ type: "text", value: "Image:" }],
199
+ type: "strong",
200
+ },
201
+ { type: "text", value: ` ${alt}` },
202
+ ],
203
+ type: "paragraph",
204
+ });
205
+ }
47
206
  const caption = getAttribute(node, "caption");
48
207
  if (caption) {
49
208
  nodes.push(paragraph(caption));
50
209
  }
51
210
  return nodes;
52
211
  };
212
+ const cardNodes = (node) => {
213
+ const title = getAttribute(node, "title");
214
+ const href = getAttribute(node, "href");
215
+ const description = getAttribute(node, "description");
216
+ const nodes = [];
217
+ if (title) {
218
+ const titleNode = { type: "text", value: title };
219
+ nodes.push(heading([
220
+ href ? { children: [titleNode], type: "link", url: href } : titleNode,
221
+ ]));
222
+ }
223
+ if (description) {
224
+ nodes.push(paragraph(description));
225
+ }
226
+ nodes.push(...blockChildren(node, true));
227
+ return nodes;
228
+ };
229
+ const linkNodes = (node) => {
230
+ const href = getAttribute(node, "href");
231
+ if (!href) {
232
+ return node.children ?? [];
233
+ }
234
+ const children = phrasingChildren(node);
235
+ if (!children) {
236
+ return blockChildren(node, true);
237
+ }
238
+ if (children.length === 0) {
239
+ const label = getAttribute(node, "title") ?? getAttribute(node, "label") ?? href;
240
+ children.push({ type: "text", value: label });
241
+ }
242
+ const link = { children, type: "link", url: href };
243
+ return node.type === "mdxJsxFlowElement"
244
+ ? [{ children: [link], type: "paragraph" }]
245
+ : [link];
246
+ };
247
+ const labelledContentNodes = (node, attributes) => {
248
+ const label = attributes
249
+ .map((attribute) => getAttribute(node, attribute))
250
+ .find(Boolean);
251
+ return [
252
+ ...(label ? [heading([{ type: "text", value: label }])] : []),
253
+ ...blockChildren(node, true),
254
+ ];
255
+ };
256
+ const summaryNodes = (node) => {
257
+ const children = phrasingChildren(node);
258
+ if (!children) {
259
+ return blockChildren(node, true);
260
+ }
261
+ return children.length === 0
262
+ ? []
263
+ : [
264
+ {
265
+ children: [{ children, type: "strong" }],
266
+ type: "paragraph",
267
+ },
268
+ ];
269
+ };
270
+ const typeTableNodes = (node) => {
271
+ const definition = getAttributeExpression(node, "type");
272
+ if (definition?.type !== "ObjectExpression") {
273
+ return [];
274
+ }
275
+ const properties = definition.properties ?? [];
276
+ const rows = properties.flatMap((property, index) => {
277
+ if (property.type !== "Property" ||
278
+ property.computed ||
279
+ properties
280
+ .slice(index + 1)
281
+ .some((entry) => entry.type === "SpreadElement")) {
282
+ return [];
283
+ }
284
+ const name = propertyName(property);
285
+ const value = property.value;
286
+ const type = expressionString(objectProperty(value, "type"));
287
+ const description = expressionString(objectProperty(value, "description"));
288
+ return name && (type || description)
289
+ ? [
290
+ {
291
+ children: [
292
+ {
293
+ children: [inlineCode(name)],
294
+ type: "tableCell",
295
+ },
296
+ {
297
+ children: type ? [inlineCode(type)] : [],
298
+ type: "tableCell",
299
+ },
300
+ {
301
+ children: description
302
+ ? [{ type: "text", value: description }]
303
+ : [],
304
+ type: "tableCell",
305
+ },
306
+ ],
307
+ type: "tableRow",
308
+ },
309
+ ]
310
+ : [];
311
+ });
312
+ if (rows.length === 0) {
313
+ return [];
314
+ }
315
+ return [
316
+ {
317
+ children: [
318
+ {
319
+ children: ["Property", "Type", "Description"].map((value) => ({
320
+ children: [{ type: "text", value }],
321
+ type: "tableCell",
322
+ })),
323
+ type: "tableRow",
324
+ },
325
+ ...rows,
326
+ ],
327
+ type: "table",
328
+ },
329
+ ];
330
+ };
331
+ const mermaidNodes = (node) => {
332
+ const chart = getAttribute(node, "chart");
333
+ return chart ? [{ lang: "mermaid", type: "code", value: chart }] : [];
334
+ };
335
+ const fileTreeItems = (node) => {
336
+ if (node.name !== "File" && node.name !== "Folder") {
337
+ return [];
338
+ }
339
+ const descendants = (node.children ?? []).flatMap(fileTreeItems);
340
+ const name = getAttribute(node, "name");
341
+ if (!name) {
342
+ return descendants;
343
+ }
344
+ return [
345
+ {
346
+ children: [
347
+ {
348
+ children: [inlineCode(`${name}${node.name === "Folder" ? "/" : ""}`)],
349
+ type: "paragraph",
350
+ },
351
+ ...(descendants.length > 0
352
+ ? [
353
+ {
354
+ children: descendants,
355
+ ordered: false,
356
+ spread: false,
357
+ type: "list",
358
+ },
359
+ ]
360
+ : []),
361
+ ],
362
+ spread: false,
363
+ type: "listItem",
364
+ },
365
+ ];
366
+ };
367
+ const filesNodes = (node) => {
368
+ const items = (node.children ?? []).flatMap(fileTreeItems);
369
+ return items.length > 0
370
+ ? [{ children: items, ordered: false, spread: false, type: "list" }]
371
+ : [];
372
+ };
373
+ const packageNodes = (node) => {
374
+ const packageValue = getAttribute(node, "package") ?? getAttribute(node, "packages");
375
+ const packageExpression = getAttributeExpression(node, "packages");
376
+ const packages = packageValue
377
+ ? packageValue.split(WHITESPACE).filter(Boolean)
378
+ : (packageExpression?.elements ?? [])
379
+ .map((entry) => expressionString(entry ?? undefined))
380
+ .filter((entry) => Boolean(entry));
381
+ if (packages.length === 0) {
382
+ return [];
383
+ }
384
+ return [
385
+ {
386
+ children: [
387
+ {
388
+ children: [{ type: "text", value: "Packages:" }],
389
+ type: "strong",
390
+ },
391
+ { type: "text", value: " " },
392
+ ...packages.flatMap((entry, index) => [
393
+ ...(index > 0 ? [{ type: "text", value: ", " }] : []),
394
+ inlineCode(entry),
395
+ ]),
396
+ ],
397
+ type: "paragraph",
398
+ },
399
+ ];
400
+ };
401
+ const videoNodes = (node) => {
402
+ const url = getAttribute(node, "src") ?? getAttribute(node, "url");
403
+ if (!url) {
404
+ return [];
405
+ }
406
+ const label = getAttribute(node, "title") ?? "Video";
407
+ return [
408
+ {
409
+ children: [
410
+ {
411
+ children: [{ type: "text", value: label }],
412
+ type: "link",
413
+ url,
414
+ },
415
+ ],
416
+ type: "paragraph",
417
+ },
418
+ ];
419
+ };
420
+ const apiOperationNodes = (node) => {
421
+ const operations = getAttributeExpression(node, "operations");
422
+ if (operations?.type !== "ArrayExpression") {
423
+ return [];
424
+ }
425
+ return (operations.elements ?? []).flatMap((operation) => {
426
+ const method = expressionString(objectProperty(operation ?? undefined, "method"));
427
+ const path = expressionString(objectProperty(operation ?? undefined, "path"));
428
+ return method && path
429
+ ? [heading([inlineCode(`${method.toUpperCase()} ${path}`)])]
430
+ : [];
431
+ });
432
+ };
433
+ const endpointNodes = (node) => {
434
+ const method = getAttribute(node, "method");
435
+ const path = getAttribute(node, "path");
436
+ return method && path
437
+ ? [heading([inlineCode(`${method.toUpperCase()} ${path}`)])]
438
+ : [];
439
+ };
440
+ const themeAwareImageNodes = (node) => {
441
+ const light = getAttributeExpression(node, "light");
442
+ const dark = getAttributeExpression(node, "dark");
443
+ const source = expressionString(objectProperty(light, "src")) ??
444
+ expressionString(objectProperty(dark, "src"));
445
+ const alt = expressionString(objectProperty(light, "alt")) ??
446
+ expressionString(objectProperty(dark, "alt")) ??
447
+ "";
448
+ if (source) {
449
+ return [
450
+ {
451
+ children: [{ alt, type: "image", url: source }],
452
+ type: "paragraph",
453
+ },
454
+ ];
455
+ }
456
+ return alt
457
+ ? [
458
+ {
459
+ children: [
460
+ {
461
+ children: [{ type: "text", value: "Image:" }],
462
+ type: "strong",
463
+ },
464
+ { type: "text", value: ` ${alt}` },
465
+ ],
466
+ type: "paragraph",
467
+ },
468
+ ]
469
+ : [];
470
+ };
53
471
  const calloutNode = (node) => {
54
472
  const title = getAttribute(node, "title");
55
473
  const heading = title
@@ -66,7 +484,7 @@ const calloutNode = (node) => {
66
484
  ]
67
485
  : [];
68
486
  return {
69
- children: [...heading, ...(node.children ?? [])],
487
+ children: [...heading, ...blockChildren(node, true)],
70
488
  type: "blockquote",
71
489
  };
72
490
  };
@@ -93,21 +511,40 @@ const buttonNodes = (node) => {
93
511
  ? [{ children: [link], type: "paragraph" }]
94
512
  : [link];
95
513
  };
514
+ const COMPONENT_REPLACERS = {
515
+ Accordion: (node) => labelledContentNodes(node, ["title"]),
516
+ APIPage: apiOperationNodes,
517
+ APISignature: endpointNodes,
518
+ Button: buttonNodes,
519
+ Callout: (node) => [calloutNode(node)],
520
+ Card: cardNodes,
521
+ Details: (node) => blockChildren(node, true),
522
+ EndpointDisplay: endpointNodes,
523
+ Image: imageNodes,
524
+ InstallPackages: packageNodes,
525
+ LearnMore: linkNodes,
526
+ Link: linkNodes,
527
+ MDXImage: imageNodes,
528
+ Mermaid: mermaidNodes,
529
+ PackageInstall: packageNodes,
530
+ PropertiesTable: typeTableNodes,
531
+ Summary: summaryNodes,
532
+ Tab: (node) => labelledContentNodes(node, ["title", "label", "value"]),
533
+ ThemeAwareImage: themeAwareImageNodes,
534
+ TypeTable: typeTableNodes,
535
+ Video: videoNodes,
536
+ };
96
537
  const replaceComponent = (node) => {
97
- if (OMITTED_COMPONENTS.has(node.name ?? "")) {
538
+ const name = node.name ?? "";
539
+ if (OMITTED_COMPONENTS.has(name)) {
98
540
  return [];
99
541
  }
100
- if (node.name === "Check" || node.name === "Cross") {
101
- return [{ type: "text", value: node.name === "Check" ? "✓" : "✗" }];
102
- }
103
- if (node.name === "Image") {
104
- return imageNodes(node);
542
+ if (name === "Check" || name === "Cross") {
543
+ return [{ type: "text", value: name === "Check" ? "✓" : "✗" }];
105
544
  }
106
- if (node.name === "Callout") {
107
- return [calloutNode(node)];
108
- }
109
- if (node.name === "Button") {
110
- return buttonNodes(node);
545
+ const replacer = COMPONENT_REPLACERS[name];
546
+ if (replacer) {
547
+ return replacer(node);
111
548
  }
112
549
  const text = getAttribute(node, "text");
113
550
  if ((node.name === "CopyPrompt" || node.name === "Prompt") && text) {
@@ -119,22 +556,13 @@ const replaceComponent = (node) => {
119
556
  return node.children ?? [];
120
557
  };
121
558
  const isJsxElement = (node) => node.type === "mdxJsxFlowElement" || node.type === "mdxJsxTextElement";
122
- const getAttributeExpression = (node, name) => {
123
- const value = node.attributes?.find((entry) => entry.type === "mdxJsxAttribute" && entry.name === name)?.value;
124
- if (!value || typeof value === "string") {
125
- return undefined;
126
- }
127
- const statement = value.data?.estree?.body[0];
128
- return statement?.type === "ExpressionStatement"
129
- ? statement.expression
130
- : undefined;
131
- };
132
559
  const tabsNodes = (node) => {
133
560
  const expression = getAttributeExpression(node, "tabs");
561
+ const elements = expression?.elements ?? [];
134
562
  // Read literals without evaluating MDX. A spread makes label positions unknown.
135
563
  const labels = expression?.type === "ArrayExpression" &&
136
- !expression.elements.some((element) => element?.type === "SpreadElement")
137
- ? expression.elements.map((element) => element?.type === "Literal" && typeof element.value === "string"
564
+ !elements.some((element) => element?.type === "SpreadElement")
565
+ ? elements.map((element) => element?.type === "Literal" && typeof element.value === "string"
138
566
  ? element.value
139
567
  : undefined)
140
568
  : [];
@@ -198,12 +626,22 @@ const cleanNode = (node) => {
198
626
  if (isStepsNode(node)) {
199
627
  return stepsNodes(node);
200
628
  }
629
+ if (isJsxElement(node) && node.name === "Files") {
630
+ return filesNodes(node);
631
+ }
201
632
  if (isJsxElement(node) && node.name === "TabsWithChildren") {
202
633
  return tabsNodes(node);
203
634
  }
204
635
  if (node.children) {
205
636
  node.children = node.children.flatMap(cleanNode);
206
637
  }
638
+ // Inline JSX can expand into block Markdown (for example an Accordion title
639
+ // becomes a heading). Lift those blocks out of the containing paragraph so
640
+ // remark-stringify does not concatenate structurally invalid children.
641
+ if (node.type === "paragraph" &&
642
+ node.children?.some((child) => BLOCK_NODE_TYPES.has(child.type))) {
643
+ return blockChildren(node, true);
644
+ }
207
645
  if (!isJsxElement(node)) {
208
646
  return [node];
209
647
  }