@vercel/geistdocs 2.10.0 → 2.12.0-canary.edf0ffd

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.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});
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.12.0-canary.edf0ffd","-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":"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,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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;AAwoDD;;;;;;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"}
@@ -936,9 +936,8 @@ const replaceComponent = (node) => {
936
936
  if ((node.name === "CopyPrompt" || node.name === "Prompt") && text) {
937
937
  return [paragraph(text)];
938
938
  }
939
- // Presentation-only components (including CodeBlockTabs and CodeBlockTab)
940
- // should not leak into agent-readable Markdown. Their meaningful children
941
- // remain in document order, so every tab's fenced code is written out.
939
+ // Presentation-only components should not leak into agent-readable
940
+ // Markdown. Their meaningful children remain in document order.
942
941
  return node.children ?? [];
943
942
  };
944
943
  const isJsxElement = (node) => node.type === "mdxJsxFlowElement" || node.type === "mdxJsxTextElement";
@@ -1007,6 +1006,48 @@ const tabsNodes = (node) => {
1007
1006
  ];
1008
1007
  });
1009
1008
  };
1009
+ const nodeText = (node) => typeof node.value === "string"
1010
+ ? node.value
1011
+ : (node.children ?? []).map(nodeText).join("");
1012
+ // Fumadocs groups fences that share a `tab=` meta into `CodeBlockTabs` (or an
1013
+ // author writes `CompactCodeBlockTabs`), with the tab names in
1014
+ // `CodeBlockTabsTrigger` elements. Dropping the triggers left
1015
+ // unlabelled, near-identical fences (`pnpm add`, `npm install`, …), so each
1016
+ // panel keeps its trigger's label, or its `value`, in bold before its code.
1017
+ // A lone tab has nothing to tell apart, so its code stays bare.
1018
+ const codeBlockTabsNodes = (node) => {
1019
+ const panelCount = (node.children ?? []).filter((child) => isJsxElement(child) && child.name === "CodeBlockTab").length;
1020
+ // Triggers written on adjacent lines parse as inline elements inside a
1021
+ // paragraph, so search the whole list rather than its direct children.
1022
+ const labels = new Map();
1023
+ const collectLabels = (current) => {
1024
+ if (isJsxElement(current) && current.name === "CodeBlockTabsTrigger") {
1025
+ const value = getAttribute(current, "value");
1026
+ const label = nodeText(current).trim();
1027
+ if (value && label) {
1028
+ labels.set(value, label);
1029
+ }
1030
+ return;
1031
+ }
1032
+ for (const child of current.children ?? []) {
1033
+ if (!isJsxElement(child) || child.name !== "CodeBlockTab") {
1034
+ collectLabels(child);
1035
+ }
1036
+ }
1037
+ };
1038
+ collectLabels(node);
1039
+ return (node.children ?? []).flatMap((child) => {
1040
+ if (!isJsxElement(child) || child.name !== "CodeBlockTab") {
1041
+ return cleanNode(child);
1042
+ }
1043
+ const value = getAttribute(child, "value");
1044
+ const label = value ? (labels.get(value) ?? value) : undefined;
1045
+ const content = (child.children ?? []).flatMap(cleanNode);
1046
+ return label && panelCount > 1
1047
+ ? [strongParagraph(label), ...content]
1048
+ : content;
1049
+ });
1050
+ };
1010
1051
  // Steps exist in two shapes: the `Steps`/`Step` components authored in MDX and
1011
1052
  // the `div.fd-steps`/`div.fd-step` output that remarkSteps emits for numbered
1012
1053
  // headings. Both flatten to their content with the step number restored on
@@ -1051,6 +1092,10 @@ const cleanNode = (node) => {
1051
1092
  if (isJsxElement(node) && node.name === "Tabs") {
1052
1093
  return itemTabsNodes(node);
1053
1094
  }
1095
+ if (isJsxElement(node) &&
1096
+ (node.name === "CodeBlockTabs" || node.name === "CompactCodeBlockTabs")) {
1097
+ return codeBlockTabsNodes(node);
1098
+ }
1054
1099
  if (node.children) {
1055
1100
  node.children = node.children.flatMap(cleanNode);
1056
1101
  }
@@ -1,4 +1,4 @@
1
- import type { ReactNode } from "react";
1
+ import { type ReactNode } from "react";
2
2
  import type { GeistdocsNavbarBrand, GeistdocsNavbarOssProduct } from "../../config";
3
3
  export declare const DEFAULT_OSS_SECTION = "Open Source";
4
4
  export declare const DEFAULT_OSS_PRODUCTS: GeistdocsNavbarOssProduct[];
@@ -23,13 +23,19 @@ export declare function PanelLink({ active, product, }: {
23
23
  * reference, not the array.
24
24
  */
25
25
  export declare function resolveOssProducts(products: GeistdocsNavbarOssProduct[] | undefined, activeProduct: string | undefined): GeistdocsNavbarOssProduct[];
26
- interface NavbarLogoProps {
26
+ type NavbarLogoProps = {
27
27
  brand?: GeistdocsNavbarBrand;
28
28
  className?: string;
29
29
  href?: string;
30
+ } & ({
31
+ activeProduct?: string;
30
32
  logo: ReactNode;
31
- variant?: "oss" | "standard";
32
- }
33
+ ossProducts?: GeistdocsNavbarOssProduct[];
34
+ variant: "oss";
35
+ } | {
36
+ logo: ReactNode;
37
+ variant?: "standard";
38
+ });
33
39
  export declare function NavbarLogo({ brand, className, href, ...props }: NavbarLogoProps): import("react/jsx-runtime").JSX.Element;
34
40
  export {};
35
41
  //# sourceMappingURL=navbar-logo.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"navbar-logo.d.ts","sourceRoot":"","sources":["../../../src/internal/navbar/navbar-logo.tsx"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAIvC,OAAO,KAAK,EACV,oBAAoB,EACpB,yBAAyB,EAC1B,MAAM,cAAc,CAAC;AAKtB,eAAO,MAAM,mBAAmB,gBAAgB,CAAC;AAEjD,eAAO,MAAM,oBAAoB,EAAE,yBAAyB,EAuF3D,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,sBAAsB,gNAC4K,CAAC;AAEhN;;;GAGG;AACH,wBAAgB,SAAS,CAAC,EACxB,MAAM,EACN,OAAO,GACR,EAAE;IACD,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,OAAO,EAAE,IAAI,CAAC,yBAAyB,EAAE,UAAU,GAAG,MAAM,GAAG,OAAO,CAAC,CAAC;CACzE,2CA+BA;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAChC,QAAQ,EAAE,yBAAyB,EAAE,GAAG,SAAS,EACjD,aAAa,EAAE,MAAM,GAAG,SAAS,GAChC,yBAAyB,EAAE,CAI7B;AAED,UAAU,eAAe;IACvB,KAAK,CAAC,EAAE,oBAAoB,CAAC;IAC7B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,SAAS,CAAC;IAChB,OAAO,CAAC,EAAE,KAAK,GAAG,UAAU,CAAC;CAC9B;AAED,wBAAgB,UAAU,CAAC,EACzB,KAAK,EACL,SAAS,EACT,IAAU,EACV,GAAG,KAAK,EACT,EAAE,eAAe,2CAmBjB"}
1
+ {"version":3,"file":"navbar-logo.d.ts","sourceRoot":"","sources":["../../../src/internal/navbar/navbar-logo.tsx"],"names":[],"mappings":"AAKA,OAAO,EAAE,KAAK,SAAS,EAA+B,MAAM,OAAO,CAAC;AAIpE,OAAO,KAAK,EACV,oBAAoB,EACpB,yBAAyB,EAC1B,MAAM,cAAc,CAAC;AAWtB,eAAO,MAAM,mBAAmB,gBAAgB,CAAC;AAEjD,eAAO,MAAM,oBAAoB,EAAE,yBAAyB,EAuF3D,CAAC;AAqBF;;;GAGG;AACH,eAAO,MAAM,sBAAsB,gNAC4K,CAAC;AAEhN;;;GAGG;AACH,wBAAgB,SAAS,CAAC,EACxB,MAAM,EACN,OAAO,GACR,EAAE;IACD,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,OAAO,EAAE,IAAI,CAAC,yBAAyB,EAAE,UAAU,GAAG,MAAM,GAAG,OAAO,CAAC,CAAC;CACzE,2CA+BA;AAwCD;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAChC,QAAQ,EAAE,yBAAyB,EAAE,GAAG,SAAS,EACjD,aAAa,EAAE,MAAM,GAAG,SAAS,GAChC,yBAAyB,EAAE,CAI7B;AAED,KAAK,eAAe,GAAG;IACrB,KAAK,CAAC,EAAE,oBAAoB,CAAC;IAC7B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf,GAAG,CACA;IACE,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,IAAI,EAAE,SAAS,CAAC;IAChB,WAAW,CAAC,EAAE,yBAAyB,EAAE,CAAC;IAC1C,OAAO,EAAE,KAAK,CAAC;CAChB,GACD;IACE,IAAI,EAAE,SAAS,CAAC;IAChB,OAAO,CAAC,EAAE,UAAU,CAAC;CACtB,CACJ,CAAC;AAEF,wBAAgB,UAAU,CAAC,EACzB,KAAK,EACL,SAAS,EACT,IAAU,EACV,GAAG,KAAK,EACT,EAAE,eAAe,2CAiKjB"}
@@ -1,11 +1,14 @@
1
1
  "use client";
2
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
3
  import Link from "next/link";
4
+ import { usePathname, useRouter } from "next/navigation";
5
+ import { NavigationMenu as NavigationMenuPrimitive } from "radix-ui";
6
+ import { useEffect, useRef, useState } from "react";
4
7
  import { IconSlashForward } from "#geistdocs-assets/icons";
5
8
  import { LogoEveSvg } from "#geistdocs-assets/logos";
6
9
  import { cn } from "#geistdocs-ui/utils";
7
10
  import { LocalizedLink, useLocalizedHref } from "../localized-link";
8
- import { NavigationMenuLink } from "../ui/navigation-menu";
11
+ import { NavigationMenu, NavigationMenuItem, NavigationMenuLink, NavigationMenuList, NavigationMenuTrigger, } from "../ui/navigation-menu";
9
12
  import { NavbarBrand } from "./navbar-brand";
10
13
  export const DEFAULT_OSS_SECTION = "Open Source";
11
14
  export const DEFAULT_OSS_PRODUCTS = [
@@ -96,6 +99,20 @@ export const DEFAULT_OSS_PRODUCTS = [
96
99
  section: "Other",
97
100
  },
98
101
  ];
102
+ function groupOssProducts(products) {
103
+ const sections = [];
104
+ for (const product of products) {
105
+ const heading = product.section ?? DEFAULT_OSS_SECTION;
106
+ const existing = sections.find((section) => section.heading === heading);
107
+ if (existing) {
108
+ existing.items.push(product);
109
+ }
110
+ else {
111
+ sections.push({ heading, items: [product] });
112
+ }
113
+ }
114
+ return sections;
115
+ }
99
116
  /**
100
117
  * Full-bleed panel below the header used by navbar dropdowns. Rendered with
101
118
  * forceMount + hidden-when-closed so links stay in the server HTML.
@@ -110,6 +127,11 @@ export function PanelLink({ active, product, }) {
110
127
  const label = (_jsx("span", { className: "inline-flex items-baseline gap-1 rounded-sm text-gray-1000 text-label-20 group-focus-visible/osslink:ring-2 group-focus-visible/osslink:ring-blue-700 group-focus-visible/osslink:ring-offset-4 group-focus-visible/osslink:ring-offset-background-200", children: _jsx("span", { className: "decoration-1 underline-offset-[5px] group-hover/osslink:underline group-hover/osslink:decoration-gray-500 group-aria-[current=page]/osslink:underline group-aria-[current=page]/osslink:decoration-gray-500", children: product.label }) }));
111
128
  return (_jsx(NavigationMenuLink, { active: active, asChild: true, children: external ? (_jsx("a", { className: "group/osslink inline-flex w-full no-underline outline-none", href: product.href, rel: "noopener noreferrer", target: "_blank", children: label })) : (_jsx(LocalizedLink, { className: "group/osslink inline-flex w-full no-underline outline-none", href: product.href, children: label })) }));
112
129
  }
130
+ function OssFeaturedCard({ product }) {
131
+ const external = product.external ?? product.href.startsWith("http");
132
+ const card = (_jsxs("span", { className: "flex h-full w-[220px] flex-col gap-3 rounded-lg border border-gray-alpha-400 bg-background-100 p-4 no-underline transition-colors hover:border-gray-alpha-500", children: [_jsx("span", { className: "flex flex-1 items-center justify-center rounded-md bg-gray-100", children: product.logo }), product.description ? (_jsx("span", { className: "text-copy-14 text-gray-900", children: product.description })) : null] }));
133
+ return (_jsx(NavigationMenuLink, { asChild: true, children: external ? (_jsx("a", { className: "w-fit! rounded-lg no-underline outline-none focus-visible:ring-2 focus-visible:ring-blue-700 focus-visible:ring-offset-2 focus-visible:ring-offset-background-200", href: product.href, rel: "noopener noreferrer", target: "_blank", children: card })) : (_jsx(LocalizedLink, { className: "w-fit! rounded-lg no-underline outline-none focus-visible:ring-2 focus-visible:ring-blue-700 focus-visible:ring-offset-2 focus-visible:ring-offset-background-200", href: product.href, children: card })) }));
134
+ }
113
135
  /**
114
136
  * Resolve the mobile OSS product list (custom or default) and drop the active
115
137
  * product.
@@ -121,7 +143,53 @@ export function resolveOssProducts(products, activeProduct) {
121
143
  return (products ?? DEFAULT_OSS_PRODUCTS).filter((product) => product.id !== activeProduct && product.href !== activeProduct);
122
144
  }
123
145
  export function NavbarLogo({ brand, className, href = "/", ...props }) {
146
+ const isOss = props.variant === "oss";
147
+ const ossProducts = isOss
148
+ ? resolveOssProducts(props.ossProducts, props.activeProduct)
149
+ : [];
150
+ const featuredProducts = ossProducts.filter((product) => product.featured);
151
+ const ossSections = groupOssProducts(ossProducts.filter((product) => !product.featured));
152
+ const [navValue, setNavValue] = useState("");
153
+ const logoHoveredRef = useRef(false);
154
+ const suppressLogoHoverRef = useRef(false);
155
+ const pathname = usePathname();
156
+ const previousPathnameRef = useRef(pathname);
157
+ const router = useRouter();
124
158
  // Like every other navbar link, the wordmark keeps the active locale.
125
159
  const localizedHref = useLocalizedHref(href);
126
- return (_jsxs("span", { className: cn("flex items-center gap-2.5", className), children: [_jsx(NavbarBrand, { brand: brand, variant: props.variant }), _jsx("div", { className: "w-5 text-center text-gray-alpha-400 text-lg dark:text-gray-600", children: _jsx(IconSlashForward, { size: 20 }) }), _jsx(Link, { className: "flex items-center text-gray-1000", href: localizedHref, prefetch: true, children: props.logo })] }));
160
+ useEffect(() => {
161
+ if (isOss) {
162
+ router.prefetch(localizedHref);
163
+ }
164
+ }, [isOss, router, localizedHref]);
165
+ useEffect(() => {
166
+ if (pathname !== previousPathnameRef.current) {
167
+ logoHoveredRef.current = false;
168
+ setNavValue("");
169
+ previousPathnameRef.current = pathname;
170
+ }
171
+ }, [pathname]);
172
+ return (_jsxs("span", { className: cn("flex items-center gap-2.5", className), children: [_jsx(NavbarBrand, { brand: brand, variant: props.variant }), _jsx("div", { className: "w-5 text-center text-gray-alpha-400 text-lg dark:text-gray-600", children: _jsx(IconSlashForward, { size: 20 }) }), isOss ? (_jsxs(_Fragment, { children: [_jsx(Link, { className: "flex @min-[1024px]:hidden items-center text-gray-1000", href: localizedHref, prefetch: true, children: props.logo }), _jsxs("div", { className: "@min-[1024px]:contents hidden", children: [_jsx(NavigationMenu, { "aria-label": "Product navigation", delayDuration: 0, onValueChange: (value) => {
173
+ if (value && suppressLogoHoverRef.current) {
174
+ return;
175
+ }
176
+ if (value || !logoHoveredRef.current) {
177
+ setNavValue(value);
178
+ }
179
+ }, skipDelayDuration: 0, value: navValue, viewport: false, children: _jsx(NavigationMenuList, { className: "h-16 items-stretch", children: _jsxs(NavigationMenuItem, { className: "-mr-3 flex h-full items-center", onMouseLeave: () => {
180
+ suppressLogoHoverRef.current = false;
181
+ }, value: "oss-products", children: [_jsx(Link, { className: "relative flex h-full items-center text-gray-1000 outline-none before:absolute before:inset-x-0 before:top-1/2 before:h-9 before:-translate-y-1/2 before:rounded-md before:content-[''] focus-visible:before:ring-2 focus-visible:before:ring-blue-700 focus-visible:before:ring-inset", href: localizedHref, onClick: () => {
182
+ suppressLogoHoverRef.current = true;
183
+ if (pathname === localizedHref) {
184
+ logoHoveredRef.current = false;
185
+ setNavValue("");
186
+ }
187
+ }, onMouseEnter: () => {
188
+ logoHoveredRef.current = true;
189
+ if (!suppressLogoHoverRef.current) {
190
+ setNavValue("oss-products");
191
+ }
192
+ }, onMouseLeave: () => {
193
+ logoHoveredRef.current = false;
194
+ }, children: props.logo }), _jsx(NavigationMenuTrigger, { "aria-label": "Open product menu", className: "relative flex h-full w-10 items-center justify-center px-1 text-gray-1000 outline-none focus-visible:ring-2 focus-visible:ring-blue-700 focus-visible:ring-inset [&_svg]:top-0 [&_svg]:-translate-x-1.5" }), _jsx(NavigationMenuPrimitive.Content, { className: NAVBAR_PANEL_CLASSNAME, forceMount: true, children: _jsx("div", { className: "mx-auto w-full max-w-[1448px] px-2", children: _jsxs("div", { className: "flex flex-nowrap gap-x-10 pt-4 pb-6 pl-4", children: [featuredProducts.length > 0 ? (_jsxs("div", { className: "flex shrink-0 flex-col", children: [_jsx("p", { className: "text-gray-900 text-label-14", children: "Latest" }), _jsx("div", { className: "mt-[5px] flex flex-1 gap-x-10", children: featuredProducts.map((product) => (_jsx(OssFeaturedCard, { product: product }, product.href))) })] })) : null, ossSections.map((section) => (_jsxs("div", { className: "min-w-[180px] shrink-0", children: [_jsx("p", { className: "text-gray-900 text-label-14", children: section.heading }), _jsx("ul", { className: "mt-[5px] flex list-none flex-col", children: section.items.map((product) => (_jsx("li", { className: "flex", children: _jsx(PanelLink, { product: product }) }, product.href))) })] }, section.heading)))] }) }) })] }) }) }), _jsx("div", { "aria-hidden": "true", className: cn("pointer-events-none fixed inset-x-0 top-16 bottom-0 z-0 bg-background-200/60", navValue ? "opacity-100" : "opacity-0") })] })] })) : (_jsx(Link, { className: "flex items-center text-gray-1000", href: localizedHref, prefetch: true, children: props.logo }))] }));
127
195
  }
@@ -28,4 +28,29 @@ export declare const getSidebarSectionItems: (section: Folder | null) => Node[];
28
28
  export declare const getSidebarRootGroups: (nodes: Node[]) => SidebarRootGroup[];
29
29
  export declare const getInitialOpenFolderIds: (nodes: Node[], activeUrl: string | undefined, openFirstLevel?: boolean, scope?: string) => string[];
30
30
  export declare const getDescendantFolderIds: (folder: Folder, folderPath: number[], scope?: string) => string[];
31
+ /** A folder row as it stood when a press on its link began. */
32
+ export interface FolderLinkPress {
33
+ expanded: boolean;
34
+ selected: boolean;
35
+ }
36
+ /**
37
+ * What a click on a folder row's link should do to that folder.
38
+ *
39
+ * Judged from the row as it was when the press began, not when the click
40
+ * lands: sidebar links navigate on pointer down, so by the time the click
41
+ * arrives the route has usually changed, the row has become the current page,
42
+ * and the active branch has already been opened. Read at click time, a first
43
+ * click on a collapsed section would look like a click on the current row and
44
+ * close the section it just opened.
45
+ *
46
+ * - The current row toggles, so clicking it again collapses or expands it.
47
+ * - A collapsed row opens. Opening is idempotent, because the route change may
48
+ * have opened it first.
49
+ * - An expanded row that is not current stays as it is while its page loads.
50
+ */
51
+ export declare const getFolderLinkClickAction: ({ expanded, selected, }: FolderLinkPress) => "open" | "toggle" | null;
52
+ /** Open `id`, leaving the set untouched when it is already open. */
53
+ export declare const openFolderId: (opened: string[], id: string) => string[];
54
+ /** Open `id` if closed; otherwise close it along with every folder beneath it. */
55
+ export declare const toggleFolderId: (opened: string[], id: string, descendantIds: string[]) => string[];
31
56
  //# sourceMappingURL=sidebar-tree.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"sidebar-tree.d.ts","sourceRoot":"","sources":["../../src/internal/sidebar-tree.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAKvC,MAAM,MA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
136
  visit(folder.children, folderPath);
137
137
  return ids;
138
138
  };
139
+ /**
140
+ * What a click on a folder row's link should do to that folder.
141
+ *
142
+ * Judged from the row as it was when the press began, not when the click
143
+ * lands: sidebar links navigate on pointer down, so by the time the click
144
+ * arrives the route has usually changed, the row has become the current page,
145
+ * and the active branch has already been opened. Read at click time, a first
146
+ * click on a collapsed section would look like a click on the current row and
147
+ * close the section it just opened.
148
+ *
149
+ * - The current row toggles, so clicking it again collapses or expands it.
150
+ * - A collapsed row opens. Opening is idempotent, because the route change may
151
+ * have opened it first.
152
+ * - An expanded row that is not current stays as it is while its page loads.
153
+ */
154
+ export const getFolderLinkClickAction = ({ expanded, selected, }) => {
155
+ if (selected) {
156
+ return "toggle";
157
+ }
158
+ return expanded ? null : "open";
159
+ };
160
+ /** Open `id`, leaving the set untouched when it is already open. */
161
+ export const openFolderId = (opened, id) => opened.includes(id) ? opened : [...opened, id];
162
+ /** Open `id` if closed; otherwise close it along with every folder beneath it. */
163
+ export const toggleFolderId = (opened, id, descendantIds) => {
164
+ if (!opened.includes(id)) {
165
+ return [...opened, id];
166
+ }
167
+ const closing = new Set([id, ...descendantIds]);
168
+ return opened.filter((openId) => !closing.has(openId));
169
+ };
@@ -1 +1 @@
1
- {"version":3,"file":"sidebar.d.ts","sourceRoot":"","sources":["../../src/internal/sidebar.tsx"],"names":[],"mappings":"AAOA,OAAO,EAEL,KAAK,SAAS,EAQf,MAAM,OAAO,CAAC;AAgBf,OAAO,EAAE,KAAK,oBAAoB,EAAuB,MAAM,YAAY,CAAC;AA89B5E,eAAO,MAAM,gBAAgB,GAAI,6BAI9B;IACD,IAAI,CAAC,EAAE,oBAAoB,CAAC;IAC5B,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,GAAG,CAAC,EAAE,SAAS,CAAC;CACjB,4CAiEA,CAAC"}
1
+ {"version":3,"file":"sidebar.d.ts","sourceRoot":"","sources":["../../src/internal/sidebar.tsx"],"names":[],"mappings":"AAOA,OAAO,EAEL,KAAK,SAAS,EAQf,MAAM,OAAO,CAAC;AAgBf,OAAO,EAAE,KAAK,oBAAoB,EAAuB,MAAM,YAAY,CAAC;AAi/B5E,eAAO,MAAM,gBAAgB,GAAI,6BAI9B;IACD,IAAI,CAAC,EAAE,oBAAoB,CAAC;IAC5B,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,GAAG,CAAC,EAAE,SAAS,CAAC;CACjB,4CAiEA,CAAC"}
@@ -12,7 +12,7 @@ import { SearchButton } from "../controls";
12
12
  import { useGeistdocsSidebar } from "../sidebar";
13
13
  import { MouseDownNavigation } from "./mousedown-navigation";
14
14
  import { SIDEBAR_DESKTOP_MIN_WIDTH } from "./sidebar-responsive";
15
- import { findActiveRootSection, getDescendantFolderIds, getInitialOpenFolderIds, getSidebarBadgeTone, getSidebarItemBadge, getSidebarNodeId, getSidebarRootGroups, getSidebarSectionItems, hasSeparateRootDisclosure, isExternalSidebarItem, isExternalSidebarUrl, isSidebarItemCurrent, } from "./sidebar-tree";
15
+ import { findActiveRootSection, getDescendantFolderIds, getFolderLinkClickAction, getInitialOpenFolderIds, getSidebarBadgeTone, getSidebarItemBadge, getSidebarNodeId, getSidebarRootGroups, getSidebarSectionItems, hasSeparateRootDisclosure, isExternalSidebarItem, isExternalSidebarUrl, isSidebarItemCurrent, openFolderId, toggleFolderId, } from "./sidebar-tree";
16
16
  const UNSAFE_ID_CHARACTERS = /[^a-zA-Z0-9_-]/g;
17
17
  const collectPageUrls = (nodes) => {
18
18
  const urls = [];
@@ -119,18 +119,14 @@ const useOpenedFolders = (nodes, activeUrl, openFirstLevel, scope) => {
119
119
  const toggleFolder = (folder, path) => {
120
120
  const id = getSidebarNodeId(folder, path, scope);
121
121
  manualToggleRef.current = true;
122
- setOpened((current) => {
123
- if (!current.includes(id)) {
124
- return [...current, id];
125
- }
126
- const closing = new Set([
127
- id,
128
- ...getDescendantFolderIds(folder, path, scope),
129
- ]);
130
- return current.filter((openId) => !closing.has(openId));
131
- });
122
+ setOpened((current) => toggleFolderId(current, id, getDescendantFolderIds(folder, path, scope)));
123
+ };
124
+ const openFolder = (folder, path) => {
125
+ const id = getSidebarNodeId(folder, path, scope);
126
+ manualToggleRef.current = true;
127
+ setOpened((current) => openFolderId(current, id));
132
128
  };
133
- return { manualToggleRef, opened, toggleFolder };
129
+ return { manualToggleRef, openFolder, opened, toggleFolder };
134
130
  };
135
131
  const SidebarSeparatorRow = ({ depth, item, }) => (_jsxs("li", { className: cn("mt-4 flex items-center gap-2 px-2 pt-2 pb-1 font-medium text-gray-900 text-label-13 first:mt-0 [&_svg]:size-4", depth > 0 && "ml-3"), children: [item.icon ? _jsx("span", { className: "shrink-0", children: item.icon }) : null, _jsx("span", { className: "min-w-0 truncate", children: item.name })] }));
136
132
  const SidebarTreeItems = ({ depth, nodes, parentPath, state, }) => (_jsx(_Fragment, { children: nodes.map((node, index) => (_jsx(SidebarTreeNode, { depth: depth, node: node, path: [...parentPath, index], state: state }, getSidebarNodeId(node, [...parentPath, index], state.idScope)))) }));
@@ -148,6 +144,9 @@ const SidebarTrailingIcon = ({ children, className, }) => (_jsx("span", { classN
148
144
  const SidebarBadge = ({ label }) => label ? (_jsx("span", { className: cn("inline-flex h-6 max-w-24 shrink-0 items-center truncate rounded-full px-2 text-button-12", getSidebarBadgeTone(label)), children: label })) : null;
149
145
  const SidebarTreeNode = ({ depth, node, path, state, }) => {
150
146
  const nodeId = getSidebarNodeId(node, path, state.idScope);
147
+ // The row as it was when a press on its link began; see
148
+ // `getFolderLinkClickAction`.
149
+ const pressRef = useRef(null);
151
150
  if (node.type === "separator") {
152
151
  return _jsx(SidebarSeparatorRow, { depth: depth, item: node });
153
152
  }
@@ -167,14 +166,27 @@ const SidebarTreeNode = ({ depth, node, path, state, }) => {
167
166
  if (opensOutsideCurrentPage(event, item?.external, item?.url ?? "")) {
168
167
  return;
169
168
  }
170
- if (!(folder && hasChildren && (isSelected || !isExpanded))) {
169
+ const current = { expanded: isExpanded, selected: isSelected };
170
+ // A keyboard activation has no press (`detail` is 0), and a press that was
171
+ // dragged off the row left a stale one, so only a pointer click uses it.
172
+ const press = event.detail > 0 ? (pressRef.current ?? current) : current;
173
+ pressRef.current = null;
174
+ if (!(folder && hasChildren)) {
171
175
  return;
172
176
  }
173
- state.toggleFolder(folder, path);
177
+ const action = getFolderLinkClickAction(press);
178
+ if (action === "toggle") {
179
+ state.toggleFolder(folder, path);
180
+ }
181
+ else if (action === "open") {
182
+ state.openFolder(folder, path);
183
+ }
174
184
  };
175
185
  let primaryControl;
176
186
  if (item) {
177
- primaryControl = (_jsx(Link, { "aria-current": isSelected ? "page" : undefined, className: cn(rowClassName, "min-w-0 flex-1 no-underline outline-none focus-visible:shadow-[var(--ds-focus-ring)]"), external: item.external, href: item.url, onClick: handleLinkClick, prefetch: true, children: content }));
187
+ primaryControl = (_jsx(Link, { "aria-current": isSelected ? "page" : undefined, className: cn(rowClassName, "min-w-0 flex-1 no-underline outline-none focus-visible:shadow-[var(--ds-focus-ring)]"), external: item.external, href: item.url, onClick: handleLinkClick, onPointerDown: () => {
188
+ pressRef.current = { expanded: isExpanded, selected: isSelected };
189
+ }, prefetch: true, children: content }));
178
190
  }
179
191
  else if (folder && hasChildren) {
180
192
  primaryControl = (_jsxs("button", { "aria-controls": menuId, "aria-expanded": isExpanded, className: cn(rowClassName, "w-full min-w-0 flex-1 cursor-pointer border-0 bg-transparent text-left outline-none focus-visible:shadow-[var(--ds-focus-ring)]"), onClick: () => state.toggleFolder(folder, path), type: "button", children: [content, _jsx(SidebarTrailingIcon, { className: "-mr-1", children: _jsx(SidebarDisclosureIcon, { expanded: isExpanded }) })] }));
@@ -188,12 +200,13 @@ const SidebarTree = ({ activeUrl, idScope, nodes, onNavigate, openFirstLevel = f
188
200
  const generatedId = useId().replace(UNSAFE_ID_CHARACTERS, "");
189
201
  const resolvedIdScope = idScope ?? `sidebar-${generatedId}`;
190
202
  const listRef = useRef(null);
191
- const { manualToggleRef, opened, toggleFolder } = useOpenedFolders(nodes, activeUrl, openFirstLevel, resolvedIdScope);
203
+ const { manualToggleRef, openFolder, opened, toggleFolder } = useOpenedFolders(nodes, activeUrl, openFirstLevel, resolvedIdScope);
192
204
  const state = {
193
205
  activeUrl,
194
206
  idPrefix: `sidebar-${generatedId}`,
195
207
  idScope: resolvedIdScope,
196
208
  onNavigate,
209
+ openFolder,
197
210
  opened,
198
211
  toggleFolder,
199
212
  };
@@ -1 +1 @@
1
- {"version":3,"file":"navbar.d.ts","sourceRoot":"","sources":["../src/navbar.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAQhD,UAAU,WAAW;IACnB,MAAM,EAAE,IAAI,CACV,eAAe,EACb,QAAQ,GACR,MAAM,GACN,UAAU,GACV,KAAK,GACL,qBAAqB,GACrB,aAAa,GACb,cAAc,GACd,mBAAmB,GACnB,eAAe,CAClB,CAAC;CACH;AAKD,eAAO,MAAM,MAAM,GAAI,YAAY,WAAW,4CAmE7C,CAAC"}
1
+ {"version":3,"file":"navbar.d.ts","sourceRoot":"","sources":["../src/navbar.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAQhD,UAAU,WAAW;IACnB,MAAM,EAAE,IAAI,CACV,eAAe,EACb,QAAQ,GACR,MAAM,GACN,UAAU,GACV,KAAK,GACL,qBAAqB,GACrB,aAAa,GACb,cAAc,GACd,mBAAmB,GACnB,eAAe,CAClB,CAAC;CACH;AAKD,eAAO,MAAM,MAAM,GAAI,YAAY,WAAW,4CAqE7C,CAAC"}
package/dist/navbar.js CHANGED
@@ -16,5 +16,5 @@ export const Navbar = ({ config }) => {
16
16
  // The default product list lives in a "use client" module, so it is resolved
17
17
  // and filtered inside the mobile menu.
18
18
  const activeProduct = config.navbarActiveProduct;
19
- return (_jsx(NavbarShell, { children: _jsxs("div", { className: "@container mx-auto flex w-full max-w-[1448px] justify-between px-2", children: [_jsxs("div", { className: "flex select-none flex-row items-center", children: [isOss ? (_jsx(NavbarLogo, { brand: config.navbarBrand, className: "ml-4", href: config.logoHref, logo: config.logo, variant: "oss" })) : (_jsx(NavbarLogo, { brand: config.navbarBrand, className: "ml-4", href: config.logoHref, logo: config.logo, variant: "standard" })), _jsx(DesktopMenu, { className: "@min-[1024px]:flex hidden", items: nav })] }), _jsxs("div", { className: "mr-4 flex flex-row items-center justify-end gap-2", children: [_jsx(SearchButton, { className: "@min-[1024px]:flex hidden w-36" }), _jsx(AskAIButton, { className: "@min-[768px]:flex hidden shrink-0", size: "small", variant: "secondary" }), _jsx(AskAIButton, { className: "@min-[768px]:hidden", size: "small", variant: "secondary" }), showGithub ? (_jsx(GitHubButton, { className: "@min-[768px]:inline-flex hidden shrink-0", github: config.github })) : null, _jsx(MobileMenu, { activeProduct: activeProduct, githubUrl: githubUrl, nav: nav, ossProducts: config.navbarOssProducts, showOss: isOss })] })] }) }));
19
+ return (_jsx(NavbarShell, { children: _jsxs("div", { className: "@container mx-auto flex w-full max-w-[1448px] justify-between px-2", children: [_jsxs("div", { className: "flex select-none flex-row items-center", children: [isOss ? (_jsx(NavbarLogo, { activeProduct: activeProduct, brand: config.navbarBrand, className: "ml-4", href: config.logoHref, logo: config.logo, ossProducts: config.navbarOssProducts, variant: "oss" })) : (_jsx(NavbarLogo, { brand: config.navbarBrand, className: "ml-4", href: config.logoHref, logo: config.logo, variant: "standard" })), _jsx(DesktopMenu, { className: "@min-[1024px]:flex hidden", items: nav })] }), _jsxs("div", { className: "mr-4 flex flex-row items-center justify-end gap-2", children: [_jsx(SearchButton, { className: "@min-[1024px]:flex hidden w-36" }), _jsx(AskAIButton, { className: "@min-[768px]:flex hidden shrink-0", size: "small", variant: "secondary" }), _jsx(AskAIButton, { className: "@min-[768px]:hidden", size: "small", variant: "secondary" }), showGithub ? (_jsx(GitHubButton, { className: "@min-[768px]:inline-flex hidden shrink-0", github: config.github })) : null, _jsx(MobileMenu, { activeProduct: activeProduct, githubUrl: githubUrl, nav: nav, ossProducts: config.navbarOssProducts, showOss: isOss })] })] }) }));
20
20
  };
@@ -1,6 +1,7 @@
1
1
  import { type LanguageModel } from "ai";
2
2
  import { type GeistdocsConfig } from "../config";
3
3
  import { type ChatMixedbreadOptions } from "../internal/chat-retrieval";
4
+ import { type EveAgentClientContext } from "../internal/eve-agent";
4
5
  import { type GeistdocsPageFilter } from "../page-visibility";
5
6
  import type { GeistdocsSourceBundle } from "../source";
6
7
  type SourceBundle = GeistdocsSourceBundle;
@@ -22,16 +23,32 @@ interface ChatProxyConfig {
22
23
  * full, and no citations; every other message is forwarded as sent.
23
24
  */
24
25
  type ChatContextInjection = "auto" | "page-only";
26
+ /** The page the reader is viewing, as `eveAgent.clientContext` resolves it. */
27
+ interface ChatEveAgentCurrentPage {
28
+ title?: string;
29
+ url: string;
30
+ }
31
+ /** Builds eve's `clientContext` for one message from the reader's page. */
32
+ type ChatEveAgentClientContextFunction = (context: {
33
+ currentPage?: ChatEveAgentCurrentPage;
34
+ }) => EveAgentClientContext | Promise<EveAgentClientContext>;
25
35
  interface ChatEveAgentOptions {
26
36
  /**
27
- * Send eve's turn-scoped `clientContext: { currentPage: { url, title } }`
28
- * with every message, including the message that starts a replacement
29
- * session; prewarm requests carry no message, so they never send it.
30
- * `url` is the absolute public URL of `currentRoute`
31
- * (on `config.siteUrl`, or the request origin); `title` is included when
32
- * the route is a page Ask AI may see. @default false
37
+ * Send eve's turn-scoped `clientContext` with every message, including the
38
+ * message that starts a replacement session; prewarm requests carry no
39
+ * message, so they never send it.
40
+ *
41
+ * `true` sends `{ currentPage: { url, title } }`. `url` is the absolute
42
+ * public URL of `currentRoute` (on `config.siteUrl`, or the request
43
+ * origin); `title` is included when the route is a page Ask AI may see.
44
+ * Nothing is sent without a usable `currentRoute`.
45
+ *
46
+ * A function receives that `currentPage`, unset without a usable
47
+ * `currentRoute`, and returns the `clientContext` to send, so an agent can
48
+ * get its own fields with the page. It runs for every message and may be
49
+ * async. @default false
33
50
  */
34
- clientContext?: boolean;
51
+ clientContext?: boolean | ChatEveAgentClientContextFunction;
35
52
  /**
36
53
  * Extra headers for requests to the eve agent, replacing the default
37
54
  * `Authorization: Bearer <Vercel OIDC token>` when an `authorization`
@@ -1 +1 @@
1
- {"version":3,"file":"chat.d.ts","sourceRoot":"","sources":["../../src/routes/chat.ts"],"names":[],"mappings":"AACA,OAAO,EAIL,KAAK,aAAa,EAQnB,MAAM,IAAI,CAAC;AAGZ,OAAO,EAAE,KAAK,eAAe,EAAiB,MAAM,WAAW,CAAC;AAKhE,OAAO,EAEL,KAAK,qBAAqB,EAG3B,MAAM,4BAA4B,CAAC;AAyBpC,OAAO,EACL,KAAK,mBAAmB,EAEzB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,WAAW,CAAC;AAEvD,KAAK,YAAY,GAAG,qBAAqB,CAAC;AA4B1C;;;GAGG;AACH,KAAK,mBAAmB,GACpB,WAAW,GACX,CAAC,CAAC,OAAO,EAAE,OAAO,KAAK,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC;AAE/D,UAAU,eAAe;IACvB,OAAO,CAAC,EAAE,mBAAmB,CAAC;IAC9B,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;;;;;;GAOG;AACH,KAAK,oBAAoB,GAAG,MAAM,GAAG,WAAW,CAAC;AAEjD,UAAU,mBAAmB;IAC3B;;;;;;;OAOG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,mBAAmB,CAAC;IAC9B;;;;;;OAMG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;;OAKG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,qEAAqE;IACrE,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;;;;OAIG;IACH,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;CACzB;AAED,UAAU,iBAAiB;IACzB;;;OAGG;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,UAAU,GACV,iBAAiB,GACjB,QAAQ,GACR,SAAS,GACT,cAAc,CACjB,CAAC;IACF;;;;;OAKG;IACH,gBAAgB,CAAC,EAAE,oBAAoB,CAAC;IACxC;;;OAGG;IACH,QAAQ,CAAC,EAAE,mBAAmB,CAAC;IAC/B,4DAA4D;IAC5D,UAAU,CAAC,EAAE,mBAAmB,CAAC;IACjC;;;OAGG;IACH,MAAM,CAAC,EAAE,iBAAiB,CAAC;IAC3B;;;OAGG;IACH,UAAU,CAAC,EAAE,qBAAqB,CAAC;IACnC;;;;;;OAMG;IACH,KAAK,CAAC,EAAE,aAAa,CAAC;IACtB,KAAK,CAAC,EAAE,eAAe,CAAC;IACxB,MAAM,CAAC,EAAE,YAAY,CAAC;IACtB,OAAO,CAAC,EAAE,YAAY,EAAE,CAAC;CAC1B;AA0oDD,eAAO,MAAM,eAAe,GAAI,wGAW7B,sBAAsB;gBAqBE,OAAO;;CAiMjC,CAAC"}
@@ -345,11 +345,11 @@ const buildPageOnlyProxyMessages = (actualMessages, attachedDoc) => {
345
345
  ];
346
346
  };
347
347
  /**
348
- * eve `clientContext` naming the page the reader is viewing. Returns
348
+ * The page the reader is viewing, for eve `clientContext`. Returns
349
349
  * `undefined` without a usable `currentRoute`. The URL is built from the
350
350
  * route's path only, so a client cannot point it at another origin.
351
351
  */
352
- const getEveClientContext = ({ basePath, baseUrl, currentRoute, defaultLanguage, filterPage, languages, sources, }) => {
352
+ const getEveCurrentPage = ({ basePath, baseUrl, currentRoute, defaultLanguage, filterPage, languages, sources, }) => {
353
353
  if (typeof currentRoute !== "string" ||
354
354
  !currentRoute.trim() ||
355
355
  currentRoute.length > MAX_PAGE_CONTEXT_URL_CHARS) {
@@ -372,11 +372,9 @@ const getEveClientContext = ({ basePath, baseUrl, currentRoute, defaultLanguage,
372
372
  sources,
373
373
  });
374
374
  const title = page ? getPageData(page.page).title?.trim() : undefined;
375
- return {
376
- currentPage: title
377
- ? { url, title: title.slice(0, MAX_CLIENT_CONTEXT_TITLE_CHARS) }
378
- : { url },
379
- };
375
+ return title
376
+ ? { url, title: title.slice(0, MAX_CLIENT_CONTEXT_TITLE_CHARS) }
377
+ : { url };
380
378
  };
381
379
  const isFirstUserMessage = (messages) => messages.filter((message) => message.role === "user").length === 1;
382
380
  const buildProxyMessages = async ({ actualMessages, config, currentRoute, defaultLanguage, filterPage, languages, pageContext, routeSources, searchDocuments, }) => {
@@ -961,8 +959,8 @@ const createEveAgentResponse = async ({ actualMessages, agentUrl, config, contex
961
959
  const withPageContext = (message) => attachedDoc
962
960
  ? [createEvePageContextPart(attachedDoc), { type: "text", text: message }]
963
961
  : message;
964
- const clientContext = eveAgent?.clientContext
965
- ? getEveClientContext({
962
+ const currentPage = eveAgent?.clientContext
963
+ ? getEveCurrentPage({
966
964
  basePath: config.basePath,
967
965
  baseUrl,
968
966
  currentRoute,
@@ -972,6 +970,9 @@ const createEveAgentResponse = async ({ actualMessages, agentUrl, config, contex
972
970
  sources: routeSources,
973
971
  })
974
972
  : undefined;
973
+ const clientContext = typeof eveAgent?.clientContext === "function"
974
+ ? await eveAgent.clientContext({ currentPage })
975
+ : currentPage && { currentPage };
975
976
  const headers = await getEveAgentRequestHeaders({ eveAgent, req });
976
977
  let session;
977
978
  // The session must be settled before the response starts so the cookie
package/dist/source.d.ts CHANGED
@@ -62,6 +62,12 @@ export interface GeistdocsMarkdownOptions {
62
62
  remarkPlugins?: PluggableList;
63
63
  transform?: (markdown: string, context: GeistdocsMarkdownContext) => Promise<string> | string;
64
64
  }
65
+ export interface GeistdocsSlugsContext {
66
+ /** Content file path relative to the content directory, including any language suffix, such as `errors/NOT_FOUND.mdx` or `guide.cn.mdx`. */
67
+ path: string;
68
+ /** Default slugs derived from the path, without folder groups or a trailing `index`. */
69
+ slugs: string[];
70
+ }
65
71
  export interface CreateSourceOptions {
66
72
  baseUrl?: string;
67
73
  config: Pick<GeistdocsConfig, "agent" | "basePath" | "defaultLanguage" | "siteUrl" | "translations"> & Partial<Pick<GeistdocsConfig, "title">>;
@@ -69,6 +75,12 @@ export interface CreateSourceOptions {
69
75
  id?: string;
70
76
  label?: string;
71
77
  markdown?: GeistdocsMarkdownOptions;
78
+ /**
79
+ * Transform each page's URL slugs, for example to lowercase them. Returned
80
+ * slugs apply everywhere page URLs appear: routes, the page tree, Markdown
81
+ * routes, the sitemap, and `llms.txt`. Two pages may not share a URL.
82
+ */
83
+ slugs?: (context: GeistdocsSlugsContext) => string[];
72
84
  }
73
85
  export interface GeistdocsSourceDefinition extends Omit<CreateSourceOptions, "config"> {
74
86
  id: string;
@@ -88,7 +100,7 @@ export interface CreateVersionedSourcesOptions {
88
100
  current: string;
89
101
  versions: GeistdocsVersionedSourceDefinition[];
90
102
  }
91
- export declare const createSource: ({ docs, config, baseUrl, id, label, markdown, }: CreateSourceOptions) => {
103
+ export declare const createSource: ({ docs, config, baseUrl, id, label, markdown, slugs, }: CreateSourceOptions) => {
92
104
  baseUrl: string;
93
105
  routingConfig: {
94
106
  agent: import("./config.js").GeistdocsAgentReadinessConfig | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"source.d.ts","sourceRoot":"","sources":["../src/source.ts"],"names":[],"mappings":"AACA,OAAO,EACL,KAAK,aAAa,EAClB,MAAM,EAEP,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7C,OAAO,EACL,KAAK,eAAe,EACpB,KAAK,oBAAoB,EAG1B,MAAM,aAAa,CAAC;AACrB,OAAO,EAEL,KAAK,wBAAwB,EAC7B,KAAK,2BAA2B,EAChC,KAAK,iBAAiB,EACvB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,KAAK,qBAAqB,EAE3B,MAAM,6BAA6B,CAAC;AAErC,YAAY,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AAEzE,KAAK,aAAa,GAAG,UAAU,CAAC,OAAO,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;AA0FlD,MAAM,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;;;;;;;;;;;;;;;;;;;;;;;iCAtKF,aAAa;;;eAAe;;;;oCAcnB,aAAa;;;eAAe;;;;;;;;;;;;;;;;;;;6BAdrC,aAAa;;;WAAe;;;;gCAcnB,aAAa;;;WAAe;;;;;;;;;;;;;;;;;;6BAdrC,aAAa;;;WAAe;;;;gCAcnB,aAAa;;;WAAe;;;CA2LlE,CAAC;AAEF,MAAM,WAAW,0BAA0B;IACzC;;;OAGG;IACH,UAAU,CAAC,EAAE,CAAC,OAAO,EAAE;QAAE,IAAI,EAAE;YAAE,KAAK,EAAE,MAAM,EAAE,CAAC;YAAC,GAAG,EAAE,MAAM,CAAA;SAAE,CAAA;KAAE,KAAK,MAAM,CAAC;IAC7E,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,6EAA6E;IAC7E,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,OAAO,EAAE,qBAAqB,GAAG,qBAAqB,EAAE,CAAC;CAC1D;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,mBAAmB,GAAI,6CAKjC,0BAA0B,KAAG,MAAM,EAYrC,CAAC;AAEF,MAAM,WAAW,gCAAgC;IAC/C,UAAU,CAAC,EAAE,0BAA0B,CAAC,YAAY,CAAC,CAAC;IACtD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,IAAI,CAAC,UAAU,CAAC,OAAO,sBAAsB,CAAC,EAAE,KAAK,CAAC,CAAC;CAClE;AAED;;;;GAIG;AACH,eAAO,MAAM,yBAAyB,GAAI,iCAIvC,gCAAgC,KAAG,MAAM,CAAC,MAAM,EAAE,qBAAqB,CAiBvE,CAAC"}
package/dist/source.js CHANGED
@@ -57,6 +57,37 @@ const prefixMarkdownLinks = (markdown, basePath) => {
57
57
  ...prefixContentLinks(lines.slice(frontmatterEnd + 1), basePath),
58
58
  ].join("\n");
59
59
  };
60
+ const createSlugsPlugin = (transform) => {
61
+ // Each locale's storage inherits fallback pages from the default locale by
62
+ // reference, so transform every page object once.
63
+ const transformed = new WeakSet();
64
+ return {
65
+ name: "geistdocs:slugs",
66
+ // Runs after Fumadocs assigns the default slugs, so `index` pages and
67
+ // folder groups resolve before the transform sees them.
68
+ enforce: "post",
69
+ transformStorage({ storage }) {
70
+ const pathsByUrl = new Map();
71
+ for (const key of storage.getFiles()) {
72
+ const file = storage.read(key);
73
+ if (file?.format !== "page") {
74
+ continue;
75
+ }
76
+ if (!transformed.has(file)) {
77
+ // Storage keys drop the locale; `file.path` is the content file path.
78
+ file.slugs = transform({ path: file.path, slugs: [...file.slugs] });
79
+ transformed.add(file);
80
+ }
81
+ const url = file.slugs.join("/");
82
+ const existing = pathsByUrl.get(url);
83
+ if (existing) {
84
+ throw new Error(`Geistdocs slugs: ${existing} and ${file.path} both resolve to "/${url}".`);
85
+ }
86
+ pathsByUrl.set(url, file.path);
87
+ }
88
+ },
89
+ };
90
+ };
60
91
  const getLanguages = (config) => {
61
92
  const defaultLanguage = config.defaultLanguage ?? "en";
62
93
  const languages = Object.keys(config.translations ?? {});
@@ -118,7 +149,7 @@ const pageTreeTransformer = {
118
149
  };
119
150
  },
120
151
  };
121
- export const createSource = ({ docs, config, baseUrl = "/docs", id, label, markdown, }) => {
152
+ export const createSource = ({ docs, config, baseUrl = "/docs", id, label, markdown, slugs, }) => {
122
153
  const { defaultLanguage, languages } = getLanguages(config);
123
154
  const i18n = defineI18n({
124
155
  defaultLanguage,
@@ -131,6 +162,7 @@ export const createSource = ({ docs, config, baseUrl = "/docs", id, label, markd
131
162
  pageTree: {
132
163
  transformers: [pageTreeTransformer],
133
164
  },
165
+ plugins: slugs ? [createSlugsPlugin(slugs)] : undefined,
134
166
  source: docs.toFumadocsSource(),
135
167
  });
136
168
  const getPageImage = (page) => {
package/docs/agents.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Geistdocs Package Docs
2
2
 
3
- These docs are bundled with `@vercel/geistdocs` 2.10.0 so agents can understand the installed package without web access.
3
+ These docs are bundled with `@vercel/geistdocs` 2.12.0-canary.edf0ffd so agents can understand the installed package without web access.
4
4
  They are generated from `apps/template/content/docs` during the package build.
5
5
 
6
6
  ## How to use these files
package/docs/llms.txt CHANGED
@@ -1,6 +1,6 @@
1
1
  # Geistdocs Package Documentation
2
2
 
3
- These docs are bundled with `@vercel/geistdocs` 2.10.0.
3
+ These docs are bundled with `@vercel/geistdocs` 2.12.0-canary.edf0ffd.
4
4
  They describe how to build package-backed Geistdocs sites and how to use the package APIs from generated project adapters.
5
5
 
6
6
  ## Documentation Index
@@ -1402,6 +1402,20 @@ export default defineGeistdocsSourceConfig();
1402
1402
 
1403
1403
  To serve docs from the site root, use `route: "/"` in `content` and `baseUrl: "/"` in `createSource`. Root-mounted docs need explicit `markdownRoutes`; Geistdocs does not infer a broad `/*path` mapping because it can capture homepages and non-docs app routes.
1404
1404
 
1405
+ ## Page URLs
1406
+
1407
+ Page URLs come from content file paths. To change them without renaming files, pass `slugs` to `createSource`. It receives the file `path` and the default `slugs`, with folder groups and a trailing `index` already removed, and returns the slugs to use:
1408
+
1409
+ ```ts title="lib/geistdocs/source.ts"
1410
+ export const geistdocsSource = createSource({
1411
+ docs,
1412
+ config,
1413
+ slugs: ({ slugs }) => slugs.map((slug) => slug.toLowerCase()),
1414
+ });
1415
+ ```
1416
+
1417
+ With this transform, `errors/NOT_FOUND.mdx` is served at `/docs/errors/not_found`. The function runs once per content file: a translated file's `path` keeps its language suffix (`guide.cn.mdx`), and a page that falls back to the default language uses the default-language result. The new URLs apply to routes, the page tree, Markdown routes, the sitemap, and `llms.txt`. Geistdocs throws when two pages resolve to the same URL. Redirect links that use the old URLs, for example with a `before` hook in `createProxy`.
1418
+
1405
1419
  ## Next.js base paths
1406
1420
 
1407
1421
  When Next.js mounts the application below a path, set the same value in `next.config.ts` and Geistdocs config:
@@ -2147,6 +2161,9 @@ export const greeting: string = "Hello from TypeScript";
2147
2161
  export const greeting = "Hello from JavaScript";
2148
2162
  ```
2149
2163
 
2164
+ The page's Markdown export writes each tab's label in bold before its fence, so
2165
+ agents can tell the examples apart.
2166
+
2150
2167
  Wrap the same fences in `<CodeBlockTabs compact>` to move the selector into the
2151
2168
  code-block header:
2152
2169
 
@@ -4285,7 +4302,7 @@ The `eveAgent` option also accepts a `url` override for pointing staging deploym
4285
4302
  | `url` | `string` | `ai.eveAgent.url` | Agent base URL. Overrides `ai.eveAgent.url`; setting it here alone enables eve agent mode without exposing the URL in `geistdocs.tsx`. |
4286
4303
  | `headers` | `HeadersInit \| (request: Request) => HeadersInit \| Promise<HeadersInit>` | OIDC headers | Extra request headers. An `authorization` header replaces the OIDC bearer token. |
4287
4304
  | `secret` | `string` | `GEISTDOCS_CHAT_SECRET` | Secret that signs the eve session cookie, at least 32 bytes. |
4288
- | `clientContext` | `boolean` | `false` | Send the current page as eve `clientContext` with every message. |
4305
+ | `clientContext` | `boolean \| ({ currentPage }) => object \| Promise<object>` | `false` | Send the current page, or the object a function builds from it, as eve `clientContext` with every message. |
4289
4306
  | `visibleTools` | `string[]` | All tools | Tool names whose calls the chat shows. |
4290
4307
  | `toolCitations` | `boolean` | `true` | Forward tool outputs and show the URLs in them as source citations. |
4291
4308
 
@@ -4439,6 +4456,20 @@ The route derives `clientContext` from the `currentRoute` the Ask AI client alre
4439
4456
 
4440
4457
  The agent's eve version must accept `clientContext` on its session routes; eve 0.59 does. Prewarm requests never carry `clientContext`, because eve rejects it on a session created without a message.
4441
4458
 
4459
+ #### Build the client context yourself
4460
+
4461
+ Pass a function instead of `true` to choose what `clientContext` carries, such as fields your agent expects next to the page. It receives `{ currentPage }`, derived the same way and unset without a usable `currentRoute`, runs for every message, and may be async:
4462
+
4463
+ ```ts title="app/api/chat/route.ts"
4464
+ export const { POST, maxDuration } = createChatRoute({
4465
+ config,
4466
+ eveAgent: {
4467
+ clientContext: ({ currentPage }) => ({ surface: "docs", currentPage }),
4468
+ },
4469
+ sources: [geistdocsSource],
4470
+ });
4471
+ ```
4472
+
4442
4473
  ### Choose which agent tool calls the chat shows
4443
4474
 
4444
4475
  By default, the chat shows every eve tool call as an activity label, and URLs found in tool outputs become source citations. Two server-only `eveAgent` options change that:
@@ -467,5 +467,5 @@
467
467
  }
468
468
  ],
469
469
  "source": "apps/template/content/docs",
470
- "version": "2.10.0"
470
+ "version": "2.12.0-canary.edf0ffd"
471
471
  }
@@ -367,7 +367,7 @@ The `eveAgent` option also accepts a `url` override for pointing staging deploym
367
367
  | `url` | `string` | `ai.eveAgent.url` | Agent base URL. Overrides `ai.eveAgent.url`; setting it here alone enables eve agent mode without exposing the URL in `geistdocs.tsx`. |
368
368
  | `headers` | `HeadersInit \| (request: Request) => HeadersInit \| Promise<HeadersInit>` | OIDC headers | Extra request headers. An `authorization` header replaces the OIDC bearer token. |
369
369
  | `secret` | `string` | `GEISTDOCS_CHAT_SECRET` | Secret that signs the eve session cookie, at least 32 bytes. |
370
- | `clientContext` | `boolean` | `false` | Send the current page as eve `clientContext` with every message. |
370
+ | `clientContext` | `boolean \| ({ currentPage }) => object \| Promise<object>` | `false` | Send the current page, or the object a function builds from it, as eve `clientContext` with every message. |
371
371
  | `visibleTools` | `string[]` | All tools | Tool names whose calls the chat shows. |
372
372
  | `toolCitations` | `boolean` | `true` | Forward tool outputs and show the URLs in them as source citations. |
373
373
 
@@ -521,6 +521,20 @@ The route derives `clientContext` from the `currentRoute` the Ask AI client alre
521
521
 
522
522
  The agent's eve version must accept `clientContext` on its session routes; eve 0.59 does. Prewarm requests never carry `clientContext`, because eve rejects it on a session created without a message.
523
523
 
524
+ #### Build the client context yourself
525
+
526
+ Pass a function instead of `true` to choose what `clientContext` carries, such as fields your agent expects next to the page. It receives `{ currentPage }`, derived the same way and unset without a usable `currentRoute`, runs for every message, and may be async:
527
+
528
+ ```ts title="app/api/chat/route.ts"
529
+ export const { POST, maxDuration } = createChatRoute({
530
+ config,
531
+ eveAgent: {
532
+ clientContext: ({ currentPage }) => ({ surface: "docs", currentPage }),
533
+ },
534
+ sources: [geistdocsSource],
535
+ });
536
+ ```
537
+
524
538
  ### Choose which agent tool calls the chat shows
525
539
 
526
540
  By default, the chat shows every eve tool call as an activity label, and URLs found in tool outputs become source citations. Two server-only `eveAgent` options change that:
@@ -263,6 +263,20 @@ export default defineGeistdocsSourceConfig();
263
263
 
264
264
  To serve docs from the site root, use `route: "/"` in `content` and `baseUrl: "/"` in `createSource`. Root-mounted docs need explicit `markdownRoutes`; Geistdocs does not infer a broad `/*path` mapping because it can capture homepages and non-docs app routes.
265
265
 
266
+ ## Page URLs
267
+
268
+ Page URLs come from content file paths. To change them without renaming files, pass `slugs` to `createSource`. It receives the file `path` and the default `slugs`, with folder groups and a trailing `index` already removed, and returns the slugs to use:
269
+
270
+ ```ts title="lib/geistdocs/source.ts"
271
+ export const geistdocsSource = createSource({
272
+ docs,
273
+ config,
274
+ slugs: ({ slugs }) => slugs.map((slug) => slug.toLowerCase()),
275
+ });
276
+ ```
277
+
278
+ With this transform, `errors/NOT_FOUND.mdx` is served at `/docs/errors/not_found`. The function runs once per content file: a translated file's `path` keeps its language suffix (`guide.cn.mdx`), and a page that falls back to the default language uses the default-language result. The new URLs apply to routes, the page tree, Markdown routes, the sitemap, and `llms.txt`. Geistdocs throws when two pages resolve to the same URL. Redirect links that use the old URLs, for example with a `before` hook in `createProxy`.
279
+
266
280
  ## Next.js base paths
267
281
 
268
282
  When Next.js mounts the application below a path, set the same value in `next.config.ts` and Geistdocs config:
@@ -525,6 +525,9 @@ export const greeting: string = "Hello from TypeScript";
525
525
  export const greeting = "Hello from JavaScript";
526
526
  ```
527
527
 
528
+ The page's Markdown export writes each tab's label in bold before its fence, so
529
+ agents can tell the examples apart.
530
+
528
531
  Wrap the same fences in `<CodeBlockTabs compact>` to move the selector into the
529
532
  code-block header:
530
533
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@vercel/geistdocs",
3
3
  "description": "Runtime and CLI for Geistdocs projects.",
4
- "version": "2.10.0",
4
+ "version": "2.12.0-canary.edf0ffd",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
7
7
  "type": "git",
@@ -299,6 +299,10 @@
299
299
  "./theme.css": "./theme.css",
300
300
  "./package.json": "./package.json"
301
301
  },
302
+ "scripts": {
303
+ "build": "rm -rf dist docs template && node ./scripts/bundle-template.mjs && node ./scripts/bundle-docs.mjs && tsc -p tsconfig.runtime.json && tsup --config tsup.config.cli.ts",
304
+ "dev": "tsc -p tsconfig.runtime.json --watch --preserveWatchOutput"
305
+ },
302
306
  "dependencies": {
303
307
  "@ai-sdk/react": "^3.0.134",
304
308
  "@clack/prompts": "^0.11.0",
@@ -362,9 +366,5 @@
362
366
  "react-dom": "^19.2.3",
363
367
  "tsup": "^8.5.1",
364
368
  "typescript": "^5.9.3"
365
- },
366
- "scripts": {
367
- "build": "rm -rf dist docs template && node ./scripts/bundle-template.mjs && node ./scripts/bundle-docs.mjs && tsc -p tsconfig.runtime.json && tsup --config tsup.config.cli.ts",
368
- "dev": "tsc -p tsconfig.runtime.json --watch --preserveWatchOutput"
369
369
  }
370
- }
370
+ }
package/shared-theme.css CHANGED
@@ -121,7 +121,7 @@ button:not(:disabled, [aria-disabled="true"]) {
121
121
  }
122
122
 
123
123
  @media (width >= 80rem) {
124
- #nd-page {
124
+ #nd-page:not([data-full="true"]) {
125
125
  max-width: 780px;
126
126
  transform: translateX(-20px);
127
127
  }
@@ -410,6 +410,20 @@ eve 智能体模式会把附加的页面作为开头的文本部分发送(页
410
410
 
411
411
  路由根据 Ask AI 客户端已经发送的 `currentRoute` 生成 `clientContext`,客户端无需改动。`url` 是该路径(含 `basePath`)在 `siteUrl` 或请求来源上的绝对 URL,会忽略查询字符串、片段以及 `currentRoute` 中的任何来源。当路由是 Ask AI 可见的页面时,`title` 为页面标题(最多 256 个字符);否则 `currentPage` 只包含 `url`。没有 `currentRoute` 或其长度超过 2,048 个字符时,不发送 `clientContext`。发往会话 Cookie 中会话的后续消息,以及替换不再活动的会话时的第一条消息,也会携带 `clientContext`;预热请求从不携带 `clientContext`。
412
412
 
413
+ #### 自行构建客户端上下文
414
+
415
+ 传入函数而不是 `true`,即可决定 `clientContext` 的内容,例如智能体需要与页面一起接收的字段。该函数接收 `{ currentPage }`(生成方式相同,没有可用的 `currentRoute` 时未设置),每条消息都会调用一次,并且可以是异步函数:
416
+
417
+ ```ts title="app/api/chat/route.ts"
418
+ export const { POST, maxDuration } = createChatRoute({
419
+ config,
420
+ eveAgent: {
421
+ clientContext: ({ currentPage }) => ({ surface: "docs", currentPage }),
422
+ },
423
+ sources: [geistdocsSource],
424
+ });
425
+ ```
426
+
413
427
  ### 选择聊天中显示哪些智能体工具调用
414
428
 
415
429
  默认情况下,聊天会把每个 eve 工具调用显示为活动标签,并把工具输出中的 URL 显示为来源引用。仅在服务器端使用的 `eveAgent` 选项可以改变这一行为:
@@ -365,7 +365,7 @@ The `eveAgent` option also accepts a `url` override for pointing staging deploym
365
365
  | `url` | `string` | `ai.eveAgent.url` | Agent base URL. Overrides `ai.eveAgent.url`; setting it here alone enables eve agent mode without exposing the URL in `geistdocs.tsx`. |
366
366
  | `headers` | `HeadersInit \| (request: Request) => HeadersInit \| Promise<HeadersInit>` | OIDC headers | Extra request headers. An `authorization` header replaces the OIDC bearer token. |
367
367
  | `secret` | `string` | `GEISTDOCS_CHAT_SECRET` | Secret that signs the eve session cookie, at least 32 bytes. |
368
- | `clientContext` | `boolean` | `false` | Send the current page as eve `clientContext` with every message. |
368
+ | `clientContext` | `boolean \| ({ currentPage }) => object \| Promise<object>` | `false` | Send the current page, or the object a function builds from it, as eve `clientContext` with every message. |
369
369
  | `visibleTools` | `string[]` | All tools | Tool names whose calls the chat shows. |
370
370
  | `toolCitations` | `boolean` | `true` | Forward tool outputs and show the URLs in them as source citations. |
371
371
 
@@ -519,6 +519,20 @@ The route derives `clientContext` from the `currentRoute` the Ask AI client alre
519
519
 
520
520
  The agent's eve version must accept `clientContext` on its session routes; eve 0.59 does. Prewarm requests never carry `clientContext`, because eve rejects it on a session created without a message.
521
521
 
522
+ #### Build the client context yourself
523
+
524
+ Pass a function instead of `true` to choose what `clientContext` carries, such as fields your agent expects next to the page. It receives `{ currentPage }`, derived the same way and unset without a usable `currentRoute`, runs for every message, and may be async:
525
+
526
+ ```ts title="app/api/chat/route.ts"
527
+ export const { POST, maxDuration } = createChatRoute({
528
+ config,
529
+ eveAgent: {
530
+ clientContext: ({ currentPage }) => ({ surface: "docs", currentPage }),
531
+ },
532
+ sources: [geistdocsSource],
533
+ });
534
+ ```
535
+
522
536
  ### Choose which agent tool calls the chat shows
523
537
 
524
538
  By default, the chat shows every eve tool call as an activity label, and URLs found in tool outputs become source citations. Two server-only `eveAgent` options change that:
@@ -261,6 +261,20 @@ export default defineGeistdocsSourceConfig();
261
261
 
262
262
  To serve docs from the site root, use `route: "/"` in `content` and `baseUrl: "/"` in `createSource`. Root-mounted docs need explicit `markdownRoutes`; Geistdocs does not infer a broad `/*path` mapping because it can capture homepages and non-docs app routes.
263
263
 
264
+ ## Page URLs
265
+
266
+ Page URLs come from content file paths. To change them without renaming files, pass `slugs` to `createSource`. It receives the file `path` and the default `slugs`, with folder groups and a trailing `index` already removed, and returns the slugs to use:
267
+
268
+ ```ts title="lib/geistdocs/source.ts"
269
+ export const geistdocsSource = createSource({
270
+ docs,
271
+ config,
272
+ slugs: ({ slugs }) => slugs.map((slug) => slug.toLowerCase()),
273
+ });
274
+ ```
275
+
276
+ With this transform, `errors/NOT_FOUND.mdx` is served at `/docs/errors/not_found`. The function runs once per content file: a translated file's `path` keeps its language suffix (`guide.cn.mdx`), and a page that falls back to the default language uses the default-language result. The new URLs apply to routes, the page tree, Markdown routes, the sitemap, and `llms.txt`. Geistdocs throws when two pages resolve to the same URL. Redirect links that use the old URLs, for example with a `before` hook in `createProxy`.
277
+
264
278
  ## Next.js base paths
265
279
 
266
280
  When Next.js mounts the application below a path, set the same value in `next.config.ts` and Geistdocs config:
@@ -529,6 +529,9 @@ export const greeting: string = "Hello from TypeScript";
529
529
  export const greeting = "Hello from JavaScript";
530
530
  ```
531
531
 
532
+ The page's Markdown export writes each tab's label in bold before its fence, so
533
+ agents can tell the examples apart.
534
+
532
535
  Wrap the same fences in `<CodeBlockTabs compact>` to move the selector into the
533
536
  code-block header:
534
537
 
@@ -17,7 +17,7 @@
17
17
  "@streamdown/code": "^1.0.1",
18
18
  "@vercel/agent-readability": "^0.7.0",
19
19
  "@vercel/analytics": "^1.6.1",
20
- "@vercel/geistdocs": "2.10.0",
20
+ "@vercel/geistdocs": "2.12.0-canary.edf0ffd",
21
21
  "@vercel/speed-insights": "^1.3.1",
22
22
  "ai": "^6.0.132",
23
23
  "clsx": "^2.1.1",