@vercel/geistdocs 2.9.8 → 2.10.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.
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.9.8","-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.10.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});
@@ -0,0 +1,29 @@
1
+ import type { ReactNode } from "react";
2
+ export interface TypeTableParameter {
3
+ description: ReactNode;
4
+ name: string;
5
+ }
6
+ export interface TypeTableNode {
7
+ default?: ReactNode;
8
+ deprecated?: boolean;
9
+ /** Additional description of the field. */
10
+ description?: ReactNode;
11
+ parameters?: TypeTableParameter[];
12
+ required?: boolean;
13
+ returns?: ReactNode;
14
+ /** The short type signature. */
15
+ type: ReactNode;
16
+ /** The full type signature. */
17
+ typeDescription?: ReactNode;
18
+ /** Optional link for the type. */
19
+ typeDescriptionLink?: string;
20
+ }
21
+ /**
22
+ * A table of props or fields, rendered as a Geist table with every value
23
+ * visible, so the page HTML carries the full reference. Accepts the same
24
+ * `type` object as the Fumadocs `TypeTable`.
25
+ */
26
+ export declare const TypeTable: ({ type, }: {
27
+ type: Record<string, TypeTableNode>;
28
+ }) => import("react/jsx-runtime").JSX.Element;
29
+ //# sourceMappingURL=type-table.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type-table.d.ts","sourceRoot":"","sources":["../../src/components/type-table.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAMvC,MAAM,WAAW,kBAAkB;IACjC,WAAW,EAAE,SAAS,CAAC;IACvB,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,aAAa;IAC5B,OAAO,CAAC,EAAE,SAAS,CAAC;IACpB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,2CAA2C;IAC3C,WAAW,CAAC,EAAE,SAAS,CAAC;IACxB,UAAU,CAAC,EAAE,kBAAkB,EAAE,CAAC;IAClC,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,OAAO,CAAC,EAAE,SAAS,CAAC;IACpB,gCAAgC;IAChC,IAAI,EAAE,SAAS,CAAC;IAChB,+BAA+B;IAC/B,eAAe,CAAC,EAAE,SAAS,CAAC;IAC5B,kCAAkC;IAClC,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAyDD;;;;GAIG;AACH,eAAO,MAAM,SAAS,GAAI,WAEvB;IACD,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;CACrC,4CA+CA,CAAC"}
@@ -0,0 +1,24 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { cn } from "#geistdocs-ui/utils";
3
+ import { getDocsLinkClassName } from "../internal/docs-link-class-name";
4
+ import { LocalizedLink } from "../internal/localized-link";
5
+ import { Table } from "./table";
6
+ // MDX passes types and defaults as strings; they read as code. Authors can
7
+ // still pass formatted React nodes, which render as given.
8
+ const asCode = (value) => typeof value === "string" ? _jsx("code", { children: value }) : value;
9
+ // App-local links follow the active language, as MDX links do.
10
+ const TypeLink = ({ children, href }) => href.startsWith("/") ? (_jsx(LocalizedLink, { className: getDocsLinkClassName(), href: href, children: children })) : (_jsx("a", { className: getDocsLinkClassName(), href: href, children: children }));
11
+ const Detail = ({ children, label, }) => (_jsxs("p", { className: "mt-2 mb-0 first:mt-0", children: [_jsxs("span", { className: "text-gray-900", children: [label, ": "] }), children] }));
12
+ const DescriptionCell = ({ item: { description, parameters = [], returns, typeDescription }, }) => (_jsxs("td", { children: [description ? _jsx("div", { className: "[&>p]:my-0", children: description }) : null, typeDescription ? (_jsx(Detail, { label: "Type", children: asCode(typeDescription) })) : null, parameters.length > 0 ? (_jsx(Detail, { label: "Parameters", children: parameters.map((parameter, index) => (_jsxs("span", { children: [index > 0 ? ", " : null, _jsx("code", { children: parameter.name }), parameter.description ? _jsxs(_Fragment, { children: [" (", parameter.description, ")"] }) : null] }, parameter.name))) })) : null, returns ? _jsx(Detail, { label: "Returns", children: asCode(returns) }) : null] }));
13
+ /**
14
+ * A table of props or fields, rendered as a Geist table with every value
15
+ * visible, so the page HTML carries the full reference. Accepts the same
16
+ * `type` object as the Fumadocs `TypeTable`.
17
+ */
18
+ export const TypeTable = ({ type, }) => {
19
+ const entries = Object.entries(type);
20
+ const hasDefaults = entries.some(([, item]) => item.default);
21
+ return (
22
+ // Descriptions wrap across lines, so every cell starts at the row's top.
23
+ _jsxs(Table, { className: "[&_tbody_td]:align-top", children: [_jsx("thead", { children: _jsxs("tr", { children: [_jsx("th", { children: "Prop" }), _jsx("th", { children: "Type" }), hasDefaults ? _jsx("th", { children: "Default" }) : null, _jsx("th", { children: "Description" })] }) }), _jsx("tbody", { children: entries.map(([name, item]) => (_jsxs("tr", { children: [_jsxs("td", { className: "whitespace-nowrap", children: [_jsxs("code", { className: cn(item.deprecated && "text-gray-900 line-through"), children: [name, item.required ? "" : "?"] }), item.deprecated ? (_jsx("span", { className: "ml-2 text-gray-900 text-xs", children: "Deprecated" })) : null] }), _jsx("td", { children: item.typeDescriptionLink ? (_jsx(TypeLink, { href: item.typeDescriptionLink, children: asCode(item.type) })) : (asCode(item.type)) }), hasDefaults ? (_jsx("td", { children: item.default ? asCode(item.default) : null })) : null, _jsx(DescriptionCell, { item: item })] }, name))) })] }));
24
+ };
package/dist/config.d.ts CHANGED
@@ -60,8 +60,9 @@ export interface GeistdocsFeatureConfig {
60
60
  }
61
61
  export interface GeistdocsEveAgentConfig {
62
62
  /**
63
- * Start an empty eve session when Ask AI loads so the first message can skip
64
- * workflow startup latency. Requires eve 0.59 or newer and the server-only
63
+ * Start an empty eve session when the reader starts typing a question in a
64
+ * new conversation, so the first message can skip workflow startup latency.
65
+ * Requires eve 0.59 or newer and the server-only
65
66
  * `GEISTDOCS_CHAT_SECRET` (without it, the chat route refuses prewarm
66
67
  * requests). @default false
67
68
  */
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAKvC,eAAO,MAAM,iBAAiB,GAAI,UAAU,MAAM,GAAG,SAAS,WAO7D,CAAC;AAEF,+EAA+E;AAC/E,eAAO,MAAM,aAAa,GAAI,MAAM,MAAM,EAAE,UAAU,MAAM,GAAG,SAAS,WAoBvE,CAAC;AAEF,qFAAqF;AACrF,eAAO,MAAM,aAAa,GAAI,MAAM,MAAM,EAAE,UAAU,MAAM,GAAG,SAAS,WAavE,CAAC;AAEF,4EAA4E;AAC5E,eAAO,MAAM,YAAY,GAAI,MAAM,MAAM,EAAE,UA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,SAAS,EAQf,MAAM,OAAO,CAAC;AAMf,OAAO,EAEL,KAAK,oBAAoB,EAE1B,MAAM,WAAW,CAAC;AAInB,KAAK,gBAAgB,GACjB;IAAE,MAAM,EAAE,SAAS,CAAA;CAAE,GACrB;IACE,KAAK,EAAE,KAAK,CAAC;IACb;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,IAAI,CAAC;IACnB,MAAM,EAAE,OAAO,CAAC;CACjB,GACD;IACE,mDAAmD;IACnD,iBAAiB,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IACvC,OAAO,EAAE,oBAAoB,CAAC;IAC9B,MAAM,EAAE,OAAO,CAAC;CACjB,CAAC;AAIN;;;GAGG;AACH,eAAO,MAAM,cAAc,wBAU1B,CAAC;AA8HF;;;;GAIG;AACH,eAAO,MAAM,4BAA4B,GAAI,eAE1C;IACD,QAAQ,EAAE,SAAS,CAAC;CACrB,4CAmCA,CAAC"}
1
+ {"version":3,"file":"session-provider.d.ts","sourceRoot":"","sources":["../../../src/internal/chat/session-provider.tsx"],"names":[],"mappings":"AAIA,OAAO,EAEL,KAAK,SAAS,EAQf,MAAM,OAAO,CAAC;AAMf,OAAO,EAEL,KAAK,oBAAoB,EAE1B,MAAM,WAAW,CAAC;AAInB,KAAK,gBAAgB,GACjB;IAAE,MAAM,EAAE,SAAS,CAAA;CAAE,GACrB;IACE,KAAK,EAAE,KAAK,CAAC;IACb;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,IAAI,CAAC;IACnB,MAAM,EAAE,OAAO,CAAC;CACjB,GACD;IACE,mDAAmD;IACnD,iBAAiB,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IACvC,OAAO,EAAE,oBAAoB,CAAC;IAC9B,MAAM,EAAE,OAAO,CAAC;CACjB,CAAC;AAIN;;;GAGG;AACH,eAAO,MAAM,cAAc,wBAU1B,CAAC;AAwHF;;;;GAIG;AACH,eAAO,MAAM,4BAA4B,GAAI,eAE1C;IACD,QAAQ,EAAE,SAAS,CAAC;CACrB,4CAmCA,CAAC"}
@@ -24,8 +24,8 @@ export const useChatSession = () => {
24
24
  };
25
25
  /**
26
26
  * Owns the one chat both shells render: restores the stored conversation,
27
- * saves it as it changes, clears it, and prewarms eve sessions. Runs once per
28
- * page however many shells are mounted.
27
+ * saves it as it changes, and clears it. Runs once per page however many
28
+ * shells are mounted.
29
29
  */
30
30
  const ChatSessionRoot = ({ api, children, }) => {
31
31
  const { historyRetentionMs, prewarmEveAgent, title } = useGeistdocsChatContext();
@@ -80,11 +80,6 @@ const ChatSessionRoot = ({ api, children, }) => {
80
80
  }, SAVE_DELAY_MS);
81
81
  }, [db, initialized, messages, persist]);
82
82
  useEffect(() => () => clearTimeout(saveTimeoutRef.current), []);
83
- useEffect(() => {
84
- if (initialized && messages.length === 0) {
85
- session.prewarm();
86
- }
87
- }, [initialized, messages.length, session]);
88
83
  const clearConversation = useCallback(async () => {
89
84
  clearTimeout(saveTimeoutRef.current);
90
85
  saveTimeoutRef.current = undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"shell.d.ts","sourceRoot":"","sources":["../../../src/internal/chat/shell.tsx"],"names":[],"mappings":"AA6ZA,eAAO,MAAM,kBAAkB,sDAgE9B,CAAC"}
1
+ {"version":3,"file":"shell.d.ts","sourceRoot":"","sources":["../../../src/internal/chat/shell.tsx"],"names":[],"mappings":"AAsaA,eAAO,MAAM,kBAAkB,sDAgE9B,CAAC"}
@@ -73,6 +73,13 @@ const GeistdocsChatPanel = ({ clearConversation, expandable, session, textareaRe
73
73
  const { messages, sendMessage, setMessages, status, stop } = useChat({
74
74
  chat: session.chat,
75
75
  });
76
+ const hasDraft = prompt.trim().length > 0;
77
+ // Prewarm on the draft so session startup overlaps with typing.
78
+ useEffect(() => {
79
+ if (hasDraft && messages.length === 0) {
80
+ session.prewarm();
81
+ }
82
+ }, [hasDraft, messages.length, session]);
76
83
  const submitText = useChatCommands({
77
84
  clearConversation,
78
85
  commandState,
@@ -1 +1 @@
1
- {"version":3,"file":"localized-link.d.ts","sourceRoot":"","sources":["../../src/internal/localized-link.tsx"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,oBAAoB,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAI7D,UAAU,kBAAmB,SAAQ,oBAAoB,CAAC,iBAAiB,CAAC;IAC1E,QAAQ,EAAE,SAAS,CAAC;IACpB,IAAI,EAAE,MAAM,CAAC;CACd;AAED;;;GAGG;AACH,eAAO,MAAM,gBAAgB,GAAI,MAAM,MAAM,KAAG,MAM/C,CAAC;AAEF,eAAO,MAAM,aAAa,GAAI,oBAAoB,kBAAkB,4CAInE,CAAC"}
1
+ {"version":3,"file":"localized-link.d.ts","sourceRoot":"","sources":["../../src/internal/localized-link.tsx"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,oBAAoB,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAI7D,UAAU,kBAAmB,SAAQ,oBAAoB,CAAC,iBAAiB,CAAC;IAC1E,QAAQ,EAAE,SAAS,CAAC;IACpB,IAAI,EAAE,MAAM,CAAC;CACd;AAED;;;GAGG;AACH,eAAO,MAAM,gBAAgB,GAAI,MAAM,MAAM,KAAG,MAQ/C,CAAC;AAEF,eAAO,MAAM,aAAa,GAAI,oBAAoB,kBAAkB,4CAInE,CAAC"}
@@ -9,9 +9,11 @@ import { useGeistdocsConfig } from "./config-context";
9
9
  * `localizeHref` for the prefixing rules.
10
10
  */
11
11
  export const useLocalizedHref = (href) => {
12
+ // `useParams` returns null outside the App Router (for example, a server
13
+ // render with no route); the link then keeps the default language.
12
14
  const params = useParams();
13
15
  const { defaultLanguage = "en" } = useGeistdocsConfig();
14
- const language = typeof params.lang === "string" ? params.lang : undefined;
16
+ const language = typeof params?.lang === "string" ? params.lang : undefined;
15
17
  return localizeHref(href, language, defaultLanguage);
16
18
  };
17
19
  export const LocalizedLink = ({ href, ...props }) => {
@@ -1,9 +1,42 @@
1
1
  import { type PluggableList } from "unified";
2
+ /** A prop value the exporter can read without evaluating JavaScript. */
3
+ export type MarkdownPropValue = boolean | null | number | string | MarkdownPropValue[] | {
4
+ [key: string]: MarkdownPropValue;
5
+ };
6
+ /** One MDX element handed to a site's Markdown serializer. */
7
+ export interface MarkdownComponentElement {
8
+ /** Markdown converted from the element's children; empty when it has none. */
9
+ children: string;
10
+ /** Whether the element sits inside a paragraph rather than on its own lines. */
11
+ inline: boolean;
12
+ /** The component name as authored, such as `TSDoc` or `Docs.Callout`. */
13
+ name: string;
14
+ /**
15
+ * Props whose values are static literals: strings, numbers, booleans,
16
+ * `null`, and arrays or objects built only from those. Props that need
17
+ * JavaScript to evaluate (identifiers, calls, spreads) are left out.
18
+ */
19
+ props: Record<string, MarkdownPropValue>;
20
+ }
21
+ /**
22
+ * Return Markdown to write in place of the element (an empty string removes
23
+ * it), or `undefined` / `null` to keep the built-in conversion.
24
+ */
25
+ export type MarkdownComponentSerializer<Context = unknown> = (element: MarkdownComponentElement, context: Context) => string | null | undefined | Promise<string | null | undefined>;
26
+ export interface MdxToMarkdownOptions<Context = unknown> {
27
+ /** Markdown serializers for site components, keyed by component name. */
28
+ components?: Record<string, MarkdownComponentSerializer<Context>>;
29
+ /** Syntax plugins the site uses in `source.config.ts`, such as `remark-math`. */
30
+ remarkPlugins?: PluggableList;
31
+ }
2
32
  /**
3
33
  * Create a converter from authored MDX to component-free, agent-readable Markdown.
4
- * Pass the syntax plugins the site uses in `source.config.ts`, such as `remark-math`.
34
+ * Pass the syntax plugins the site uses in `source.config.ts`, such as
35
+ * `remark-math`, either directly or as `remarkPlugins` beside `components`,
36
+ * the Markdown serializers for site components. The converter passes its
37
+ * second argument to each serializer as context.
5
38
  */
6
- export declare const createMdxToMarkdown: (remarkPlugins?: PluggableList) => (source: string) => Promise<string>;
39
+ export declare const createMdxToMarkdown: <Context = undefined>(options?: PluggableList | MdxToMarkdownOptions<Context>) => (source: string, context?: Context) => Promise<string>;
7
40
  /** Convert authored MDX into component-free, agent-readable Markdown. */
8
- export declare const mdxToMarkdown: (source: string) => Promise<string>;
41
+ export declare const mdxToMarkdown: (source: string, context?: undefined) => Promise<string>;
9
42
  //# sourceMappingURL=mdx-to-markdown.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"mdx-to-markdown.d.ts","sourceRoot":"","sources":["../../src/internal/mdx-to-markdown.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,KAAK,aAAa,EAAW,MAAM,SAAS,CAAC;AA43CtD;;;GAGG;AACH,eAAO,MAAM,mBAAmB,GAAI,gBAAgB,aAAa,MAGjD,QAAQ,MAAM,oBAe7B,CAAC;AAEF,yEAAyE;AACzE,eAAO,MAAM,aAAa,WAlBF,MAAM,oBAkBoB,CAAC"}
1
+ {"version":3,"file":"mdx-to-markdown.d.ts","sourceRoot":"","sources":["../../src/internal/mdx-to-markdown.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,KAAK,aAAa,EAA2B,MAAM,SAAS,CAAC;AAkCtE,wEAAwE;AACxE,MAAM,MAAM,iBAAiB,GACzB,OAAO,GACP,IAAI,GACJ,MAAM,GACN,MAAM,GACN,iBAAiB,EAAE,GACnB;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,iBAAiB,CAAA;CAAE,CAAC;AAEzC,8DAA8D;AAC9D,MAAM,WAAW,wBAAwB;IACvC,8EAA8E;IAC9E,QAAQ,EAAE,MAAM,CAAC;IACjB,gFAAgF;IAChF,MAAM,EAAE,OAAO,CAAC;IAChB,yEAAyE;IACzE,IAAI,EAAE,MAAM,CAAC;IACb;;;;OAIG;IACH,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAC;CAC1C;AAED;;;GAGG;AACH,MAAM,MAAM,2BAA2B,CAAC,OAAO,GAAG,OAAO,IAAI,CAC3D,OAAO,EAAE,wBAAwB,EACjC,OAAO,EAAE,OAAO,KACb,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC,CAAC;AAEpE,MAAM,WAAW,oBAAoB,CAAC,OAAO,GAAG,OAAO;IACrD,yEAAyE;IACzE,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,2BAA2B,CAAC,OAAO,CAAC,CAAC,CAAC;IAClE,iFAAiF;IACjF,aAAa,CAAC,EAAE,aAAa,CAAC;CAC/B;AAklDD;;;;;;GAMG;AACH,eAAO,MAAM,mBAAmB,GAAI,OAAO,GAAG,SAAS,EACrD,UAAU,aAAa,GAAG,oBAAoB,CAAC,OAAO,CAAC,MAUzC,QAAQ,MAAM,EAAE,UAAU,OAAO,oBAgBhD,CAAC;AAEF,yEAAyE;AACzE,eAAO,MAAM,aAAa,WAnBF,MAAM,yCAmBoB,CAAC"}
@@ -40,6 +40,18 @@ function expressionString(node) {
40
40
  }
41
41
  return undefined;
42
42
  }
43
+ // Types are usually one string. Generated OpenAPI 3.1 references write a
44
+ // union as an array of strings (`["string", "null"]`), shown as `string | null`.
45
+ // An array with any non-literal member is unknown, so no partial union is shown.
46
+ const expressionType = (node) => {
47
+ if (node?.type !== "ArrayExpression") {
48
+ return expressionString(node);
49
+ }
50
+ const members = (node.elements ?? []).map((element) => element ? expressionString(element) : undefined);
51
+ return members.length > 0 && members.every(Boolean)
52
+ ? members.join(" | ")
53
+ : undefined;
54
+ };
43
55
  const expressionBoolean = (node) => node?.type === "Literal" && typeof node.value === "boolean"
44
56
  ? node.value
45
57
  : undefined;
@@ -305,7 +317,7 @@ const typeTableNodes = (node) => {
305
317
  }
306
318
  const name = propertyName(property);
307
319
  const value = property.value;
308
- const type = expressionString(objectProperty(value, "type"));
320
+ const type = expressionType(objectProperty(value, "type"));
309
321
  const description = expressionString(objectProperty(value, "description"));
310
322
  return name && (type || description)
311
323
  ? [
@@ -410,7 +422,7 @@ const describedLabel = (label, description) => {
410
422
  // The page shows the type name over its parameters but not the description,
411
423
  // so the export does the same.
412
424
  const parameterGroupItems = (group) => {
413
- const type = expressionString(objectProperty(group, "type"));
425
+ const type = expressionType(objectProperty(group, "type"));
414
426
  const nested = parameterItems(objectElements(objectProperty(group, "parameters")));
415
427
  if (!type) {
416
428
  return nested;
@@ -422,7 +434,7 @@ const parameterGroupItems = (group) => {
422
434
  function parameterItems(entries) {
423
435
  return entries.flatMap((entry) => {
424
436
  const name = expressionString(objectProperty(entry, "name"));
425
- const type = expressionString(objectProperty(entry, "type"));
437
+ const type = expressionType(objectProperty(entry, "type"));
426
438
  const description = expressionString(objectProperty(entry, "description"));
427
439
  const optional = objectProperty(entry, "isOptional");
428
440
  const nested = objectElements(objectProperty(entry, "properties")).flatMap(parameterGroupItems);
@@ -495,7 +507,7 @@ const apiVariantItems = (entry) => objectElements(objectProperty(entry, "variant
495
507
  function apiParameterItems(entries) {
496
508
  return entries.flatMap((entry) => {
497
509
  const name = expressionString(objectProperty(entry, "name"));
498
- const type = expressionString(objectProperty(entry, "type"));
510
+ const type = expressionType(objectProperty(entry, "type"));
499
511
  const description = expressionString(objectProperty(entry, "description"));
500
512
  const required = expressionBoolean(objectProperty(entry, "required"));
501
513
  const deprecated = expressionBoolean(objectProperty(entry, "deprecated"));
@@ -793,8 +805,10 @@ const endpointDisplayNodes = (node) => {
793
805
  const fullPath = path
794
806
  ? `${versionPrefix ?? (VERSIONED_PATH.test(path) ? "" : "/v1")}${path}`
795
807
  : undefined;
796
- const label = method?.toUpperCase() === "DELETE" ? "DEL" : method?.toUpperCase();
797
- return method && path ? [heading([inlineCode(`${label}${fullPath}`)])] : [];
808
+ // The page badge abbreviates DELETE to DEL; agents need the HTTP method.
809
+ return method && path
810
+ ? [heading([inlineCode(`${method.toUpperCase()} ${fullPath}`)])]
811
+ : [];
798
812
  };
799
813
  const themeAwareImageNodes = (node) => {
800
814
  const light = getAttributeExpression(node, "light");
@@ -1061,16 +1075,196 @@ const cleanNode = (node) => {
1061
1075
  const cleanChildren = (parent) => {
1062
1076
  parent.children = (parent.children ?? []).flatMap(cleanNode);
1063
1077
  };
1064
- const cleanMdx = () => (tree) => {
1065
- cleanChildren(tree);
1078
+ const UNKNOWN_VALUE = Symbol("unknown");
1079
+ // Evaluate only literal JavaScript. Anything that needs scope or execution
1080
+ // (identifiers, calls, spreads, interpolated templates) is unknown, and an
1081
+ // array or object that contains an unknown part is unknown as a whole so a
1082
+ // serializer never sees a partial shape.
1083
+ const staticArray = (node) => {
1084
+ const values = [];
1085
+ for (const element of node.elements ?? []) {
1086
+ const value = element ? staticValue(element) : UNKNOWN_VALUE;
1087
+ if (value === UNKNOWN_VALUE) {
1088
+ return UNKNOWN_VALUE;
1089
+ }
1090
+ values.push(value);
1091
+ }
1092
+ return values;
1093
+ };
1094
+ const staticObject = (node) => {
1095
+ const entries = [];
1096
+ for (const property of node.properties ?? []) {
1097
+ if (property.type !== "Property" || property.computed) {
1098
+ return UNKNOWN_VALUE;
1099
+ }
1100
+ const key = propertyName(property);
1101
+ const value = staticValue(property.value);
1102
+ if (key === undefined || value === UNKNOWN_VALUE) {
1103
+ return UNKNOWN_VALUE;
1104
+ }
1105
+ entries.push([key, value]);
1106
+ }
1107
+ // fromEntries defines own properties, so a `__proto__` key stays data.
1108
+ return Object.fromEntries(entries);
1109
+ };
1110
+ function staticValue(node) {
1111
+ if (!node) {
1112
+ return UNKNOWN_VALUE;
1113
+ }
1114
+ if (node.type === "Literal") {
1115
+ const { value } = node;
1116
+ return value === null ||
1117
+ typeof value === "boolean" ||
1118
+ typeof value === "number" ||
1119
+ typeof value === "string"
1120
+ ? value
1121
+ : UNKNOWN_VALUE;
1122
+ }
1123
+ if (node.type === "TemplateLiteral") {
1124
+ return expressionString(node) ?? UNKNOWN_VALUE;
1125
+ }
1126
+ if (node.type === "ArrayExpression") {
1127
+ return staticArray(node);
1128
+ }
1129
+ if (node.type === "ObjectExpression") {
1130
+ return staticObject(node);
1131
+ }
1132
+ if (node.type === "UnaryExpression" &&
1133
+ node.operator === "-" &&
1134
+ node.argument?.type === "Literal" &&
1135
+ typeof node.argument.value === "number") {
1136
+ return -node.argument.value;
1137
+ }
1138
+ return UNKNOWN_VALUE;
1139
+ }
1140
+ const attributeValue = (value) => {
1141
+ // A bare attribute (`<Badge new />`) is `true`, as in JSX.
1142
+ if (value === null || value === undefined) {
1143
+ return true;
1144
+ }
1145
+ if (typeof value === "string") {
1146
+ return value;
1147
+ }
1148
+ const statement = value.data?.estree?.body[0];
1149
+ return statement?.type === "ExpressionStatement"
1150
+ ? staticValue(statement.expression)
1151
+ : UNKNOWN_VALUE;
1152
+ };
1153
+ // JSX applies props left to right: a later attribute replaces an earlier one,
1154
+ // and a spread can replace any prop before it, so those are no longer known.
1155
+ const staticProps = (node) => {
1156
+ const props = new Map();
1157
+ for (const attribute of node.attributes ?? []) {
1158
+ if (attribute.type === "mdxJsxExpressionAttribute") {
1159
+ props.clear();
1160
+ continue;
1161
+ }
1162
+ if (attribute.type !== "mdxJsxAttribute" || !attribute.name) {
1163
+ continue;
1164
+ }
1165
+ const value = attributeValue(attribute.value);
1166
+ if (value === UNKNOWN_VALUE) {
1167
+ props.delete(attribute.name);
1168
+ }
1169
+ else {
1170
+ props.set(attribute.name, value);
1171
+ }
1172
+ }
1173
+ return Object.fromEntries(props);
1174
+ };
1175
+ const serializerFor = (node, components) => isJsxElement(node) && node.name && Object.hasOwn(components, node.name)
1176
+ ? components[node.name]
1177
+ : undefined;
1178
+ const childrenMarkdown = (node, state) => {
1179
+ // Convert a copy: when the serializer defers to the built-in conversion,
1180
+ // the original children must still be intact for it.
1181
+ const children = structuredClone(node.children ?? []).flatMap(cleanNode);
1182
+ const blocks = node.type === "mdxJsxTextElement"
1183
+ ? [{ children, type: "paragraph" }]
1184
+ : blockChildren({ children, type: node.type }, true);
1185
+ return state.stringify(blocks).trim();
1186
+ };
1187
+ const serializeElement = async (node, serializer, state) => {
1188
+ const name = node.name ?? "";
1189
+ const inline = node.type === "mdxJsxTextElement";
1190
+ let markdown;
1191
+ try {
1192
+ markdown = await serializer({
1193
+ children: childrenMarkdown(node, state),
1194
+ inline,
1195
+ name,
1196
+ props: staticProps(node),
1197
+ }, state.context);
1198
+ }
1199
+ catch (error) {
1200
+ throw new Error(`The Markdown serializer for <${name}> failed.`, {
1201
+ cause: error,
1202
+ });
1203
+ }
1204
+ if (markdown === null || markdown === undefined) {
1205
+ return undefined;
1206
+ }
1207
+ const nodes = state.parseMarkdown(markdown);
1208
+ // Inline output stays in its sentence when it is a single paragraph.
1209
+ if (inline && nodes.length === 1 && nodes[0].type === "paragraph") {
1210
+ return nodes[0].children ?? [];
1211
+ }
1212
+ return nodes;
1066
1213
  };
1067
- const createProcessor = (remarkPlugins = []) => unified()
1214
+ // Innermost elements first, so a serializer's `children` already contains
1215
+ // the output of serializers registered for the components nested inside it.
1216
+ const serializeComponents = async (parent, state) => {
1217
+ if (!parent.children) {
1218
+ return;
1219
+ }
1220
+ const children = [];
1221
+ for (const child of parent.children) {
1222
+ await serializeComponents(child, state);
1223
+ const serializer = serializerFor(child, state.components);
1224
+ const replacement = serializer
1225
+ ? await serializeElement(child, serializer, state)
1226
+ : undefined;
1227
+ if (replacement) {
1228
+ children.push(...replacement);
1229
+ }
1230
+ else {
1231
+ children.push(child);
1232
+ }
1233
+ }
1234
+ parent.children = children;
1235
+ };
1236
+ function cleanMdx(options) {
1237
+ const components = options.components ?? {};
1238
+ if (Object.keys(components).length === 0) {
1239
+ return (tree) => {
1240
+ cleanChildren(tree);
1241
+ };
1242
+ }
1243
+ const fragmentParser = unified()
1244
+ .use(remarkParse)
1245
+ .use(remarkGfm)
1246
+ .use(options.remarkPlugins);
1247
+ return async (tree, file) => {
1248
+ await serializeComponents(tree, {
1249
+ components,
1250
+ context: file.data.geistdocsMarkdownContext,
1251
+ parseMarkdown: (markdown) => fragmentParser.runSync(fragmentParser.parse(markdown))
1252
+ .children,
1253
+ stringify: (nodes) => String(this.stringify({
1254
+ children: nodes,
1255
+ type: "root",
1256
+ })),
1257
+ });
1258
+ cleanChildren(tree);
1259
+ };
1260
+ }
1261
+ const createProcessor = (remarkPlugins = [], components) => unified()
1068
1262
  .use(remarkParse)
1069
1263
  .use(remarkGfm)
1070
1264
  .use(remarkPlugins)
1071
1265
  .use(remarkMdx)
1072
1266
  .use(remarkFrontmatter, ["yaml"])
1073
- .use(cleanMdx)
1267
+ .use(cleanMdx, { components, remarkPlugins })
1074
1268
  .use(remarkStringify, {
1075
1269
  bullet: "-",
1076
1270
  fences: true,
@@ -1129,15 +1323,22 @@ const escapeOffendingText = (source, error) => {
1129
1323
  const MAX_ESCAPES = 100;
1130
1324
  /**
1131
1325
  * Create a converter from authored MDX to component-free, agent-readable Markdown.
1132
- * Pass the syntax plugins the site uses in `source.config.ts`, such as `remark-math`.
1326
+ * Pass the syntax plugins the site uses in `source.config.ts`, such as
1327
+ * `remark-math`, either directly or as `remarkPlugins` beside `components`,
1328
+ * the Markdown serializers for site components. The converter passes its
1329
+ * second argument to each serializer as context.
1133
1330
  */
1134
- export const createMdxToMarkdown = (remarkPlugins) => {
1135
- const processor = createProcessor(remarkPlugins);
1136
- return async (source) => {
1331
+ export const createMdxToMarkdown = (options) => {
1332
+ const { components, remarkPlugins } = Array.isArray(options)
1333
+ ? { components: undefined, remarkPlugins: options }
1334
+ : (options ?? {});
1335
+ const processor = createProcessor(remarkPlugins, components);
1336
+ return async (source, context) => {
1137
1337
  let input = source;
1138
1338
  for (let attempt = 0; attempt <= MAX_ESCAPES; attempt += 1) {
1139
1339
  try {
1140
- return String(await processor.process(input)).trim();
1340
+ const data = { geistdocsMarkdownContext: context };
1341
+ return String(await processor.process({ data, value: input })).trim();
1141
1342
  }
1142
1343
  catch (error) {
1143
1344
  const escaped = escapeOffendingText(input, error);
package/dist/mdx.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"mdx.d.ts","sourceRoot":"","sources":["../src/mdx.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AA8B/C,OAAO,EAGL,KAAK,4BAA4B,IAAI,mBAAmB,EAGzD,MA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D,CAAC;AAEnE,eAAO,MAAM,2BAA2B,GACtC,GAAG,eAAe,KAAK,CAAC,sBAAsB,GAAG,SAAS,CAAC,KAC1D,sBACkD,CAAC"}
package/dist/mdx.js CHANGED
@@ -1,5 +1,4 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
- import { TypeTable } from "fumadocs-ui/components/type-table";
3
2
  import defaultMdxComponents from "fumadocs-ui/mdx";
4
3
  import Link from "next/link";
5
4
  import { Tabs } from "#geistdocs-ui/components/tabs";
@@ -17,6 +16,7 @@ import { Mermaid } from "./components/mermaid";
17
16
  import { Step, Steps } from "./components/steps";
18
17
  import { Table } from "./components/table";
19
18
  import { TabContent, TabsWithChildren } from "./components/tabs-with-children";
19
+ import { TypeTable } from "./components/type-table";
20
20
  import { Video } from "./components/video";
21
21
  import { LocalizedLink } from "./internal/localized-link";
22
22
  import { geistdocsFrontmatterSchema as frontmatterSchema, geistdocsMetaSchema as metaSchema, geistShikiTheme as shikiTheme, defineGeistdocsSourceConfig as sourceConfig, } from "./source-config";