@vercel/geistdocs 2.0.2 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/cli/index.js +1 -1
  2. package/dist/components/link.d.ts +5 -0
  3. package/dist/components/link.d.ts.map +1 -0
  4. package/dist/components/link.js +4 -0
  5. package/dist/internal/docs-link-class-name.d.ts +2 -0
  6. package/dist/internal/docs-link-class-name.d.ts.map +1 -0
  7. package/dist/internal/docs-link-class-name.js +3 -0
  8. package/dist/internal/page-tree-visibility.d.ts +4 -0
  9. package/dist/internal/page-tree-visibility.d.ts.map +1 -0
  10. package/dist/internal/page-tree-visibility.js +42 -0
  11. package/dist/page-visibility.d.ts +7 -0
  12. package/dist/page-visibility.d.ts.map +1 -1
  13. package/dist/pages/docs.d.ts +25 -21
  14. package/dist/pages/docs.d.ts.map +1 -1
  15. package/dist/pages/docs.js +53 -17
  16. package/dist/proxy.d.ts +4 -1
  17. package/dist/proxy.d.ts.map +1 -1
  18. package/dist/proxy.js +42 -12
  19. package/dist/routes/chat.d.ts +4 -1
  20. package/dist/routes/chat.d.ts.map +1 -1
  21. package/dist/routes/chat.js +58 -25
  22. package/dist/routes/llms.d.ts +14 -10
  23. package/dist/routes/llms.d.ts.map +1 -1
  24. package/dist/routes/llms.js +50 -8
  25. package/dist/routes/search-export.d.ts +3 -1
  26. package/dist/routes/search-export.d.ts.map +1 -1
  27. package/dist/routes/search-export.js +4 -3
  28. package/dist/routes/search.d.ts +3 -1
  29. package/dist/routes/search.d.ts.map +1 -1
  30. package/dist/routes/search.js +4 -3
  31. package/dist/routes/sitemap.d.ts +3 -2
  32. package/dist/routes/sitemap.d.ts.map +1 -1
  33. package/dist/routes/sitemap.js +7 -4
  34. package/dist/source.d.ts +1 -0
  35. package/dist/source.d.ts.map +1 -1
  36. package/docs/agents.md +1 -1
  37. package/docs/llms.txt +114 -3
  38. package/docs/manifest.json +1 -1
  39. package/docs/pages/configuration.md +53 -0
  40. package/docs/pages/getting-started.md +8 -0
  41. package/docs/pages/llms-txt.md +2 -0
  42. package/docs/pages/md.md +4 -0
  43. package/docs/pages/packages.md +6 -2
  44. package/docs/pages/proxy.md +14 -0
  45. package/docs/pages/syntax.md +26 -0
  46. package/package.json +5 -1
  47. package/template/AGENTS.md +2 -1
  48. package/template/app/styles/geistdocs.css +2 -2
  49. package/template/content/docs/configuration.mdx +53 -0
  50. package/template/content/docs/getting-started.mdx +9 -0
  51. package/template/content/docs/llms-txt.mdx +2 -0
  52. package/template/content/docs/md.mdx +4 -0
  53. package/template/content/docs/packages.mdx +6 -2
  54. package/template/content/docs/proxy.mdx +14 -0
  55. package/template/content/docs/syntax.mdx +26 -0
  56. package/template/package.json +1 -1
package/dist/cli/index.js CHANGED
@@ -4,4 +4,4 @@ import{program as A}from"commander";import{access as Xe,copyFile as Ke,readdir a
4
4
  `);throw new AggregateError(s,`Mixedbread search sync did not complete:
5
5
  ${a}`)}return r},Mt=async({client:e,file:t,pollIntervalMs:n,pollTimeoutMs:r,sleep:s})=>{let i=t,o=Date.now()+r;for(;i.status==="pending"||i.status==="in_progress";){if(Date.now()>=o)throw new Error(`Mixedbread timed out while indexing file ${t.id}.`);await s(n),i=await e.retrieveStoreFile(t.id)}if(i.status!=="completed")throw new Error(`Mixedbread failed to index file ${t.id} (${i.status}).`);return i},Rt=async({client:e,desired:t,pollIntervalMs:n,pollTimeoutMs:r,sleep:s})=>{let i=await e.uploadFile({content:t.document.content,filename:`${L(t.document.id).slice(0,32)}.md`}),o;try{o=await e.createStoreFile({externalId:t.externalId,fileId:i,metadata:{...t.metadata,[g.rawFileId]:i}})}catch(a){try{await e.deleteFile(i)}catch(d){throw new AggregateError([a,d],`Mixedbread failed to attach and clean up raw file ${i}.`)}throw a}return Mt({client:e,file:o,pollIntervalMs:n,pollTimeoutMs:r,sleep:s})},Te=async({client:e,concurrency:t=Et,manifest:n,pollIntervalMs:r=St,pollTimeoutMs:s=bt,revision:i,revisionAncestors:o=[],revisionTimestamp:a,sleep:d=At})=>{let c=be(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=>Pt(p,u,i,o,a)),m=new Map(l.map(p=>[p.document.id,p])),h=(await xe(e)).flatMap(p=>{let y=q(p.metadata);return y?.siteId===u?[{file:p,metadata:y}]:[]}),x=new Map,v=new Set;for(let p of h){W(p.metadata,i,a)&&v.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)||v.has(p.document.id)));await Ee(_,t,p=>Rt({client:e,desired:p,pollIntervalMs:r,pollTimeoutMs:s,sleep:d}));let E=(await xe(e)).flatMap(p=>{let y=q(p.metadata);return y?.siteId===u?[{file:p,metadata:y}]:[]}),D=new Set(E.filter(({metadata:p})=>W(p,i,a)).map(({metadata:p})=>p.documentId)),ie=new Set;for(let p of l){if(D.has(p.document.id))continue;let ae=E.filter(({file:B,metadata:k})=>B.status==="completed"&&k.documentId===p.document.id&&k.contentHash===p.hash).sort((B,k)=>B.file.id.localeCompare(k.file.id))[0];ae&&ie.add(ae.file.id)}let oe=E.filter(({file:p,metadata:y})=>p.status!=="pending"&&p.status!=="in_progress"&&!W(y,i,a)&&vt({currentRevision:i,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 kt=50,Ct=e=>`vercel integration add mixedbread --name docs-${e||"your-site-id"} --environment production`,Ie=(e,t)=>Ft("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim(),Ot=e=>{let t=process.env.VERCEL_GIT_COMMIT_SHA?.trim(),n=[];try{n=Ie(e,["rev-list",`--max-count=${kt+1}`,t||"HEAD"]).split(`
6
6
  `).filter(Boolean)}catch{n=[]}let r=t||n[0],s;for(let i of Array.from(new Set([r,"HEAD"].filter(Boolean))))try{let o=Number(Ie(e,["show","-s","--format=%ct",i]));if(Number.isFinite(o)){s=o;break}}catch{}return{revision:r,revisionAncestors:n.filter(i=>i!==r),revisionTimestamp:s}},Pe=async({allowNonProduction:e=!1,dir:t=".next"}={})=>{let n=process.cwd();Dt.loadEnvConfig(n,!1);let r=process.env.MXBAI_API_KEY?.trim(),s=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!=!!s)throw new Error("Mixedbread is partially configured. Set both MXBAI_API_KEY and MXBAI_STORE_ID.");let i;try{i=await _e({cwd:n,outputDirectory:t})}catch(a){if(!(r||s)){console.log("Geistdocs search sync skipped: no Mixedbread credentials or static search export were found.");return}throw a}if(i.provider!=="mixedbread"){console.log("Geistdocs search sync skipped: Ask AI uses local retrieval.");return}if(!(r&&s))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:",Ct(i.siteId)].join(`
7
- `));let o=await Te({client:he({apiBaseUrl:process.env.MXBAI_BASE_URL,apiKey:r,storeId:s}),manifest:i,...Ot(n)});console.log(`Geistdocs search sync complete: ${o.uploaded} uploaded, ${o.deleted} deleted, ${o.skipped} unchanged.`)};import{readFileSync as $t,writeFileSync as Nt}from"fs";import{mkdir as Ut,readFile as Z,writeFile as Lt}from"fs/promises";import{dirname as Gt,extname as jt,relative as Re,resolve as j}from"path";import{intro as Vt,isCancel as Bt,log as I,multiselect as Jt,outro as G,spinner as Ht}from"@clack/prompts";import{glob as Xt}from"glob";import{Node as F,Project as Kt,SyntaxKind as Yt}from"ts-morph";var qt="geistdocs.tsx",zt="content/docs/**/*.mdx",ee=".translation-cache.json",Q=8,ve=()=>({version:1,entries:{}}),Wt=async e=>{let t=await Z(e),{createHash:n}=await import("crypto");return n("sha256").update(t).digest("hex")},Qt=e=>{let t=j(process.cwd(),e);return $t(t,"utf8")},Ae=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):[],Zt=e=>{try{let t=new Kt({compilerOptions:{allowJs:!0,jsx:4,module:99,target:10},skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!0}),n=Qt(e),i=t.createSourceFile(e,n,{overwrite:!0}).getVariableDeclarations().find(a=>a.getName()==="translations")?.getInitializer();if(!i)return[];if(F.isObjectLiteralExpression(i))return Ae(i);let o=i.getFirstDescendantByKind(Yt.ObjectLiteralExpression);return o?Ae(o):[]}catch(t){let n=t instanceof Error?t.message:`${t}`;return I.warn(`Failed to read locales from ${e}: ${n}`),[]}},en=async()=>{let e=await Jt({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 Bt(e)&&(G("Translation cancelled"),process.exit(0)),e},tn=async e=>(await Xt(e,{cwd:process.cwd(),absolute:!0,nodir:!0})).sort(),nn=async()=>{let e=j(process.cwd(),ee);try{let t=await Z(e,"utf8"),n=JSON.parse(t);return n.version!==1||!n.entries?ve():{version:1,entries:n.entries}}catch{return ve()}},Me=e=>{let t=j(process.cwd(),ee),n=JSON.stringify(e,null,2);Nt(t,n,"utf8")},rn=async e=>{let t=await Promise.all(e.map(async n=>[n,await Wt(n)]));return Object.fromEntries(t)},sn=(e,t)=>{let n=jt(e);return`${e.slice(0,-n.length)}.${t}${n}`},Fe=(e,t)=>`${Re(process.cwd(),e)}::${t}`,on=(e,t,n,r,s=!1)=>{let i=[],o=0;for(let a of t){let d=n[a];for(let c of e){let u=sn(a,c),l=Fe(a,c),m=r.entries[l];if(!s&&m?.hash===d){o+=1;continue}i.push({locale:c,sourceFile:a,sourceHash:d,targetFile:u})}}return{tasks:i,skippedCount:o}},an=async e=>{await Ut(Gt(e),{recursive:!0})},cn=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 i=await r.text();throw new Error(`API request failed (${r.status}): ${i}`)}let s=await r.json();if(!s.translation)throw new Error("API response did not include a translation");return s.translation},dn=async(e,t,n)=>{let r=await Z(e.sourceFile,"utf8"),s=await cn(t,r,e.locale);await an(e.targetFile),await Lt(e.targetFile,s,"utf8"),n.entries[Fe(e.sourceFile,e.locale)]={hash:e.sourceHash,updatedAt:new Date().toISOString()}},De=async(e,t)=>{Vt("Translate MDX content");let n=e??zt,r=t.url||process.env.GEISTDOCS_TRANSLATE_URL||"https://geistdocs.com/translate",s=Zt(t.config??qt),i=await tn(n);i.length===0&&(I.error(`No MDX files found matching pattern: ${n}`),G("Translation cancelled"),process.exit(1)),I.info(`Found ${i.length} MDX file(s) matching pattern`),s.length===0&&(s=await en());let o=j(process.cwd(),ee),a=await nn();await Me(a),I.info(`Using cache: ${o}`);let d=await rn(i),{tasks:c,skippedCount:u}=on(s,i,d,a,t.force);if(c.length===0){I.success("All translations are up to date!"),G(`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=Ht();m.start("Translating content...");let f=0;for(let h of l)await Promise.all(h.map(async x=>{await dn(x,r,a),f+=1,m.message(`Translated ${f}/${c.length}: ${Re(process.cwd(),x.targetFile)}`)})),await Me(a);m.stop("Translation complete!"),G(`Created/updated ${c.length} file(s)`)};import{access as ln,copyFile as pn,mkdir as $e,rm as re}from"fs/promises";import{dirname as un,join as P}from"path";import{intro as gn,log as w,outro as V,spinner as Ne}from"@clack/prompts";import{glob as mn}from"glob";var fn=["**/*"],hn=["content/docs/**"],te=".geistdocs-tmp",wn=async(e,t)=>{let n=P(e,t);await re(n,{recursive:!0,force:!0}),await $e(n,{recursive:!0})},ne=async e=>await re(e,{recursive:!0,force:!0}),ke=async(e,t,n)=>(await mn(e,{cwd:n,nodir:!0,dot:!0,ignore:[".git/**",...t]})).sort(),yn=async e=>{try{return await ln(e),!0}catch{return!1}},xn=async(e,t,n)=>{let r=P(t,e),s=P(n,e);return await yn(r)?(await pn(r,s),{success:!0}):{success:!1,error:`Source file not found: ${r}`}},En=async(e,t)=>{let n=P(t,e);return await re(n,{force:!0}),{success:!0}},Ce=20,Oe=async(e,t,n)=>{let r=[];for(let s=0;s<e.length;s+=n){let i=e.slice(s,s+n),o=await Promise.all(i.map(t));r.push(...o)}return r},Sn=async(e,t,n,r,s)=>{let i={success:[],deleted:[],failed:[]},o=[...new Set(e.map(d=>un(P(r,d))))];s.message(`Creating ${o.length} directories...`),await Promise.all(o.map(d=>$e(d,{recursive:!0}))),s.message(`Updating ${e.length} files...`);let a=await Oe(e,async d=>{let c=await xn(d,n,r);return{file:d,...c}},Ce);for(let{file:d,success:c,error:u}of a)c?i.success.push(d):i.failed.push({file:d,error:u??"Unknown error"});if(t.length>0){s.message(`Deleting ${t.length} files...`);let d=await Oe(t,async c=>{try{return await En(c,r),{file:c,success:!0}}catch(u){let l=u instanceof Error?u.message:`${u}`;return{file:c,success:!1,error:l}}},Ce);for(let c of d)c.success?i.deleted.push(c.file):i.failed.push({file:c.file,error:c.error})}return i},bn=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}`)}},_n=e=>e.includes("canary")?"canary":"latest",Tn=async e=>{let t=await fetch(`https://registry.npmjs.org/${encodeURIComponent(b)}`);if(!t.ok)throw new Error(`Failed to resolve ${b}@${e}`);let r=(await t.json())["dist-tags"]?.[e];if(!r)throw new Error(`Could not find dist-tag ${e} for ${b}`);return r},In=async e=>{let t=await M(e),n=J(t,b);if(!n)return{currentVersion:n,nextVersion:void 0,updated:!1};let r=_n(n),s=await Tn(r);return n===s?{currentVersion:n,nextVersion:s,updateTag:r,updated:!1}:($(t,b,s),await O(e,t),{currentVersion:n,nextVersion:s,updateTag:r,updated:!0})},Pn=async(e,t,n)=>{let r=await M(e);if(!le(r,b))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:s,nextVersion:i,updateTag:o,updated:a}=await In(e);if(!a)return w.success(s?`@vercel/geistdocs is already at ${i} (${o}).`:"No package version update was needed."),V("Package-based site is already up to date."),!0;w.info(`Bumping ${b} from ${s} to ${i} (${o})`);let d=Ne();return d.start("Installing updated package version..."),await T("pnpm",["install"],{cwd:e}),d.stop("Package update complete!"),V("Please review and test the upgraded package version."),!0},vn=async(e,t,n,r,s)=>{let i=P(e,te),o=Ne(),a=s?.sync?i:t;o.start("Preparing template snapshot..."),s?.sync&&(await wn(e,te),await N(i)),o.message("Scanning for files...");let d=await ke(n,r,a),c=[];if(s?.sync){o.message("Comparing with local files...");let l=await ke(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."),s?.sync&&await ne(i),V("Update cancelled.");return}w.info(`Patterns: ${n.length}`),w.info(`Files to update: ${d.length}`),s?.sync&&w.info(`Files to delete: ${c.length}`),o.start("Updating files...");let u=await Sn(d,c,a,e,o);s?.sync&&(o.message("Cleaning up..."),await ne(i)),o.stop("Update complete!"),bn(u),V("Please review and test the changes carefully.")},Ue=async(e,t)=>{let n=process.cwd(),r=H(),s=e&&e.length>0?e:fn,i=e&&e.length>0?[]:hn;try{if(gn("Let's update your Geistdocs project!"),await Pn(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 vn(n,r,s,i,t)}catch(o){let a=o instanceof Error?o.message:`${o}`;try{await ne(P(n,te))}catch{}w.error(`Failed to update project: ${a}`),process.exit(1)}};A.name("geistdocs").description("CLI for Geistdocs projects").version("2.0.2","-v, --version","Output the current version");A.command("init").description("Initialize a new Geistdocs project").option("--name <name>","Name of the project").option("--disable-git","Disable git initialization").action(fe);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(De);var An=A.command("search").description("Manage the external search index used by Ask AI");An.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 Te({client:he({apiBaseUrl:process.env.MXBAI_BASE_URL,apiKey:r,storeId:s}),manifest:i,...Ot(n)});console.log(`Geistdocs search sync complete: ${o.uploaded} uploaded, ${o.deleted} deleted, ${o.skipped} unchanged.`)};import{readFileSync as $t,writeFileSync as Nt}from"fs";import{mkdir as Ut,readFile as Z,writeFile as Lt}from"fs/promises";import{dirname as Gt,extname as jt,relative as Re,resolve as j}from"path";import{intro as Vt,isCancel as Bt,log as I,multiselect as Jt,outro as G,spinner as Ht}from"@clack/prompts";import{glob as Xt}from"glob";import{Node as F,Project as Kt,SyntaxKind as Yt}from"ts-morph";var qt="geistdocs.tsx",zt="content/docs/**/*.mdx",ee=".translation-cache.json",Q=8,ve=()=>({version:1,entries:{}}),Wt=async e=>{let t=await Z(e),{createHash:n}=await import("crypto");return n("sha256").update(t).digest("hex")},Qt=e=>{let t=j(process.cwd(),e);return $t(t,"utf8")},Ae=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):[],Zt=e=>{try{let t=new Kt({compilerOptions:{allowJs:!0,jsx:4,module:99,target:10},skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!0}),n=Qt(e),i=t.createSourceFile(e,n,{overwrite:!0}).getVariableDeclarations().find(a=>a.getName()==="translations")?.getInitializer();if(!i)return[];if(F.isObjectLiteralExpression(i))return Ae(i);let o=i.getFirstDescendantByKind(Yt.ObjectLiteralExpression);return o?Ae(o):[]}catch(t){let n=t instanceof Error?t.message:`${t}`;return I.warn(`Failed to read locales from ${e}: ${n}`),[]}},en=async()=>{let e=await Jt({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 Bt(e)&&(G("Translation cancelled"),process.exit(0)),e},tn=async e=>(await Xt(e,{cwd:process.cwd(),absolute:!0,nodir:!0})).sort(),nn=async()=>{let e=j(process.cwd(),ee);try{let t=await Z(e,"utf8"),n=JSON.parse(t);return n.version!==1||!n.entries?ve():{version:1,entries:n.entries}}catch{return ve()}},Me=e=>{let t=j(process.cwd(),ee),n=JSON.stringify(e,null,2);Nt(t,n,"utf8")},rn=async e=>{let t=await Promise.all(e.map(async n=>[n,await Wt(n)]));return Object.fromEntries(t)},sn=(e,t)=>{let n=jt(e);return`${e.slice(0,-n.length)}.${t}${n}`},Fe=(e,t)=>`${Re(process.cwd(),e)}::${t}`,on=(e,t,n,r,s=!1)=>{let i=[],o=0;for(let a of t){let d=n[a];for(let c of e){let u=sn(a,c),l=Fe(a,c),m=r.entries[l];if(!s&&m?.hash===d){o+=1;continue}i.push({locale:c,sourceFile:a,sourceHash:d,targetFile:u})}}return{tasks:i,skippedCount:o}},an=async e=>{await Ut(Gt(e),{recursive:!0})},cn=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 i=await r.text();throw new Error(`API request failed (${r.status}): ${i}`)}let s=await r.json();if(!s.translation)throw new Error("API response did not include a translation");return s.translation},dn=async(e,t,n)=>{let r=await Z(e.sourceFile,"utf8"),s=await cn(t,r,e.locale);await an(e.targetFile),await Lt(e.targetFile,s,"utf8"),n.entries[Fe(e.sourceFile,e.locale)]={hash:e.sourceHash,updatedAt:new Date().toISOString()}},De=async(e,t)=>{Vt("Translate MDX content");let n=e??zt,r=t.url||process.env.GEISTDOCS_TRANSLATE_URL||"https://geistdocs.com/translate",s=Zt(t.config??qt),i=await tn(n);i.length===0&&(I.error(`No MDX files found matching pattern: ${n}`),G("Translation cancelled"),process.exit(1)),I.info(`Found ${i.length} MDX file(s) matching pattern`),s.length===0&&(s=await en());let o=j(process.cwd(),ee),a=await nn();await Me(a),I.info(`Using cache: ${o}`);let d=await rn(i),{tasks:c,skippedCount:u}=on(s,i,d,a,t.force);if(c.length===0){I.success("All translations are up to date!"),G(`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=Ht();m.start("Translating content...");let f=0;for(let h of l)await Promise.all(h.map(async x=>{await dn(x,r,a),f+=1,m.message(`Translated ${f}/${c.length}: ${Re(process.cwd(),x.targetFile)}`)})),await Me(a);m.stop("Translation complete!"),G(`Created/updated ${c.length} file(s)`)};import{access as ln,copyFile as pn,mkdir as $e,rm as re}from"fs/promises";import{dirname as un,join as P}from"path";import{intro as gn,log as w,outro as V,spinner as Ne}from"@clack/prompts";import{glob as mn}from"glob";var fn=["**/*"],hn=["content/docs/**"],te=".geistdocs-tmp",wn=async(e,t)=>{let n=P(e,t);await re(n,{recursive:!0,force:!0}),await $e(n,{recursive:!0})},ne=async e=>await re(e,{recursive:!0,force:!0}),ke=async(e,t,n)=>(await mn(e,{cwd:n,nodir:!0,dot:!0,ignore:[".git/**",...t]})).sort(),yn=async e=>{try{return await ln(e),!0}catch{return!1}},xn=async(e,t,n)=>{let r=P(t,e),s=P(n,e);return await yn(r)?(await pn(r,s),{success:!0}):{success:!1,error:`Source file not found: ${r}`}},En=async(e,t)=>{let n=P(t,e);return await re(n,{force:!0}),{success:!0}},Ce=20,Oe=async(e,t,n)=>{let r=[];for(let s=0;s<e.length;s+=n){let i=e.slice(s,s+n),o=await Promise.all(i.map(t));r.push(...o)}return r},Sn=async(e,t,n,r,s)=>{let i={success:[],deleted:[],failed:[]},o=[...new Set(e.map(d=>un(P(r,d))))];s.message(`Creating ${o.length} directories...`),await Promise.all(o.map(d=>$e(d,{recursive:!0}))),s.message(`Updating ${e.length} files...`);let a=await Oe(e,async d=>{let c=await xn(d,n,r);return{file:d,...c}},Ce);for(let{file:d,success:c,error:u}of a)c?i.success.push(d):i.failed.push({file:d,error:u??"Unknown error"});if(t.length>0){s.message(`Deleting ${t.length} files...`);let d=await Oe(t,async c=>{try{return await En(c,r),{file:c,success:!0}}catch(u){let l=u instanceof Error?u.message:`${u}`;return{file:c,success:!1,error:l}}},Ce);for(let c of d)c.success?i.deleted.push(c.file):i.failed.push({file:c.file,error:c.error})}return i},bn=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}`)}},_n=e=>e.includes("canary")?"canary":"latest",Tn=async e=>{let t=await fetch(`https://registry.npmjs.org/${encodeURIComponent(b)}`);if(!t.ok)throw new Error(`Failed to resolve ${b}@${e}`);let r=(await t.json())["dist-tags"]?.[e];if(!r)throw new Error(`Could not find dist-tag ${e} for ${b}`);return r},In=async e=>{let t=await M(e),n=J(t,b);if(!n)return{currentVersion:n,nextVersion:void 0,updated:!1};let r=_n(n),s=await Tn(r);return n===s?{currentVersion:n,nextVersion:s,updateTag:r,updated:!1}:($(t,b,s),await O(e,t),{currentVersion:n,nextVersion:s,updateTag:r,updated:!0})},Pn=async(e,t,n)=>{let r=await M(e);if(!le(r,b))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:s,nextVersion:i,updateTag:o,updated:a}=await In(e);if(!a)return w.success(s?`@vercel/geistdocs is already at ${i} (${o}).`:"No package version update was needed."),V("Package-based site is already up to date."),!0;w.info(`Bumping ${b} from ${s} to ${i} (${o})`);let d=Ne();return d.start("Installing updated package version..."),await T("pnpm",["install"],{cwd:e}),d.stop("Package update complete!"),V("Please review and test the upgraded package version."),!0},vn=async(e,t,n,r,s)=>{let i=P(e,te),o=Ne(),a=s?.sync?i:t;o.start("Preparing template snapshot..."),s?.sync&&(await wn(e,te),await N(i)),o.message("Scanning for files...");let d=await ke(n,r,a),c=[];if(s?.sync){o.message("Comparing with local files...");let l=await ke(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."),s?.sync&&await ne(i),V("Update cancelled.");return}w.info(`Patterns: ${n.length}`),w.info(`Files to update: ${d.length}`),s?.sync&&w.info(`Files to delete: ${c.length}`),o.start("Updating files...");let u=await Sn(d,c,a,e,o);s?.sync&&(o.message("Cleaning up..."),await ne(i)),o.stop("Update complete!"),bn(u),V("Please review and test the changes carefully.")},Ue=async(e,t)=>{let n=process.cwd(),r=H(),s=e&&e.length>0?e:fn,i=e&&e.length>0?[]:hn;try{if(gn("Let's update your Geistdocs project!"),await Pn(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 vn(n,r,s,i,t)}catch(o){let a=o instanceof Error?o.message:`${o}`;try{await ne(P(n,te))}catch{}w.error(`Failed to update project: ${a}`),process.exit(1)}};A.name("geistdocs").description("CLI for Geistdocs projects").version("2.2.0","-v, --version","Output the current version");A.command("init").description("Initialize a new Geistdocs project").option("--name <name>","Name of the project").option("--disable-git","Disable git initialization").action(fe);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(De);var An=A.command("search").description("Manage the external search index used by Ask AI");An.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,5 @@
1
+ import type { ComponentProps } from "react";
2
+ export type NativeDocsLinkProps = ComponentProps<"a">;
3
+ /** A styled anchor for links that must use browser-native navigation. */
4
+ export declare const NativeDocsLink: ({ className, ...props }: NativeDocsLinkProps) => import("react/jsx-runtime").JSX.Element;
5
+ //# sourceMappingURL=link.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"link.d.ts","sourceRoot":"","sources":["../../src/components/link.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,OAAO,CAAC;AAG5C,MAAM,MAAM,mBAAmB,GAAG,cAAc,CAAC,GAAG,CAAC,CAAC;AAEtD,yEAAyE;AACzE,eAAO,MAAM,cAAc,GAAI,yBAG5B,mBAAmB,4CAErB,CAAC"}
@@ -0,0 +1,4 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { getDocsLinkClassName } from "../internal/docs-link-class-name.js";
3
+ /** A styled anchor for links that must use browser-native navigation. */
4
+ export const NativeDocsLink = ({ className, ...props }) => (_jsx("a", { ...props, className: getDocsLinkClassName(className) }));
@@ -0,0 +1,2 @@
1
+ export declare const getDocsLinkClassName: (className?: string) => string;
2
+ //# sourceMappingURL=docs-link-class-name.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"docs-link-class-name.d.ts","sourceRoot":"","sources":["../../src/internal/docs-link-class-name.ts"],"names":[],"mappings":"AAKA,eAAO,MAAM,oBAAoB,GAAI,YAAY,MAAM,WAClB,CAAC"}
@@ -0,0 +1,3 @@
1
+ import { cn } from "#geistdocs-ui/utils";
2
+ const DOCS_LINK_CLASS_NAME = "font-normal text-gray-1000! underline decoration-1 decoration-gray-700 underline-offset-4 hover:text-gray-1000! hover:decoration-gray-1000 hover:opacity-100!";
3
+ export const getDocsLinkClassName = (className) => cn(DOCS_LINK_CLASS_NAME, className);
@@ -0,0 +1,4 @@
1
+ import type { Root } from "fumadocs-core/page-tree";
2
+ /** Removes hidden pages without mutating Fumadocs' shared page tree. */
3
+ export declare const filterPageTree: (tree: Root, hiddenUrls: ReadonlySet<string>) => Root;
4
+ //# sourceMappingURL=page-tree-visibility.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"page-tree-visibility.d.ts","sourceRoot":"","sources":["../../src/internal/page-tree-visibility.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAgB,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAiDlE,wEAAwE;AACxE,eAAO,MAAM,cAAc,GACzB,MAAM,IAAI,EACV,YAAY,WAAW,CAAC,MAAM,CAAC,KAC9B,IASD,CAAC"}
@@ -0,0 +1,42 @@
1
+ const filterNodes = (nodes, hiddenUrls) => {
2
+ const filtered = [];
3
+ let pendingSeparator;
4
+ for (const node of nodes) {
5
+ if (node.type === "separator") {
6
+ pendingSeparator = node;
7
+ continue;
8
+ }
9
+ const visible = filterNode(node, hiddenUrls);
10
+ if (!visible) {
11
+ continue;
12
+ }
13
+ if (pendingSeparator) {
14
+ filtered.push(pendingSeparator);
15
+ pendingSeparator = undefined;
16
+ }
17
+ filtered.push(visible);
18
+ }
19
+ return filtered;
20
+ };
21
+ const filterNode = (node, hiddenUrls) => {
22
+ if (node.type === "page") {
23
+ return hiddenUrls.has(node.url) ? null : node;
24
+ }
25
+ const children = filterNodes(node.children, hiddenUrls);
26
+ const index = node.index && !hiddenUrls.has(node.index.url) ? node.index : undefined;
27
+ if (!(index || children.length > 0)) {
28
+ return null;
29
+ }
30
+ return { ...node, children, index };
31
+ };
32
+ /** Removes hidden pages without mutating Fumadocs' shared page tree. */
33
+ export const filterPageTree = (tree, hiddenUrls) => ({
34
+ ...tree,
35
+ children: filterNodes(tree.children, hiddenUrls),
36
+ fallback: tree.fallback
37
+ ? {
38
+ ...tree.fallback,
39
+ children: filterNodes(tree.fallback.children, hiddenUrls),
40
+ }
41
+ : undefined,
42
+ });
@@ -1,5 +1,12 @@
1
1
  import type { Metadata } from "next";
2
2
  import type { GeistdocsPageSurface } from "./config";
3
+ import type { GeistdocsSourceBundle, GeistdocsSourcePage } from "./source";
4
+ export interface GeistdocsPageFilterContext<Source = GeistdocsSourceBundle> {
5
+ lang: string;
6
+ source: Source;
7
+ }
8
+ /** Narrows a site's stable public documentation corpus. */
9
+ export type GeistdocsPageFilter<Page = GeistdocsSourcePage, Source = GeistdocsSourceBundle> = (page: Page, context: GeistdocsPageFilterContext<Source>) => boolean;
3
10
  export interface GeistdocsPageVisibilityData {
4
11
  canonical?: string;
5
12
  excludeFrom?: GeistdocsPageSurface[];
@@ -1 +1 @@
1
- {"version":3,"file":"page-visibility.d.ts","sourceRoot":"","sources":["../src/page-visibility.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAErD,MAAM,WAAW,2BAA2B;IAC1C,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,oBAAoB,EAAE,CAAC;IACrC,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;IACpB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;CACjB;AAED,UAAU,6BAA6B;IACrC,IAAI,EAAE,OAAO,CAAC;CACf;AAKD,eAAO,MAAM,eAAe,GAAI,MAAM,6BAA6B,YAGlE,CAAC;AAEF,eAAO,MAAM,uBAAuB,GAClC,MAAM,6BAA6B,EACnC,SAAS,oBAAoB,YAa9B,CAAC;AAEF,eAAO,MAAM,aAAa,GACxB,MAAM,6BAA6B,KAClC,QAAQ,CAAC,QAAQ,CAAC,GAAG,SASvB,CAAC"}
1
+ {"version":3,"file":"page-visibility.d.ts","sourceRoot":"","sources":["../src/page-visibility.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AACrD,OAAO,KAAK,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,UAAU,CAAC;AAE3E,MAAM,WAAW,0BAA0B,CAAC,MAAM,GAAG,qBAAqB;IACxE,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,2DAA2D;AAC3D,MAAM,MAAM,mBAAmB,CAC7B,IAAI,GAAG,mBAAmB,EAC1B,MAAM,GAAG,qBAAqB,IAC5B,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,0BAA0B,CAAC,MAAM,CAAC,KAAK,OAAO,CAAC;AAEzE,MAAM,WAAW,2BAA2B;IAC1C,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,oBAAoB,EAAE,CAAC;IACrC,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;IACpB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;CACjB;AAED,UAAU,6BAA6B;IACrC,IAAI,EAAE,OAAO,CAAC;CACf;AAKD,eAAO,MAAM,eAAe,GAAI,MAAM,6BAA6B,YAGlE,CAAC;AAEF,eAAO,MAAM,uBAAuB,GAClC,MAAM,6BAA6B,EACnC,SAAS,oBAAoB,YAa9B,CAAC;AAEF,eAAO,MAAM,aAAa,GACxB,MAAM,6BAA6B,KAClC,QAAQ,CAAC,QAAQ,CAAC,GAAG,SASvB,CAAC"}
@@ -1,7 +1,8 @@
1
1
  import { DocsPage as FumadocsDocsPage } from "fumadocs-ui/layouts/docs/page";
2
2
  import type { MDXComponents } from "mdx/types";
3
3
  import type { Metadata } from "next";
4
- import type { ComponentProps, ComponentType, ReactNode } from "react";
4
+ import { type ComponentProps, type ComponentType, type ReactNode } from "react";
5
+ import { NativeDocsLink } from "../components/link";
5
6
  import { type GeistdocsConfig } from "../config";
6
7
  import { type GeistdocsPageVisibilityData } from "../page-visibility";
7
8
  import type { GeistdocsSourceBundle } from "../source";
@@ -10,10 +11,15 @@ type GeistdocsPage = NonNullable<ReturnType<SourceBundle["source"]["getPage"]>>;
10
11
  type PageActionsBundle = ReturnType<typeof createPageActions>;
11
12
  type DocsPageLink = MDXComponents["a"];
12
13
  type TableOfContentOptions = NonNullable<ComponentProps<typeof FumadocsDocsPage>["tableOfContent"]>;
13
- interface DocsPageParams {
14
+ export interface DocsPageParams extends Record<string, string | string[] | undefined> {
14
15
  lang: string;
15
16
  slug?: string[];
16
17
  }
18
+ export interface DocsPageAccessContext<Params extends DocsPageParams = DocsPageParams> {
19
+ params: Params;
20
+ source: SourceBundle;
21
+ }
22
+ export type DocsPageAccessFilter<Params extends DocsPageParams = DocsPageParams> = (page: GeistdocsPage, context: DocsPageAccessContext<Params>) => boolean | Promise<boolean>;
17
23
  type DocsPageMdx = MDXComponents | ((context: {
18
24
  link: DocsPageLink;
19
25
  page: GeistdocsPage;
@@ -23,14 +29,14 @@ type OpenGraphImages = NonNullable<Metadata["openGraph"]>["images"];
23
29
  interface DocsPageOpenGraphOptions {
24
30
  images?: boolean | OpenGraphImages;
25
31
  }
26
- interface PageUrlContext {
32
+ interface PageUrlContext<Params extends DocsPageParams = DocsPageParams> {
27
33
  page: GeistdocsPage;
28
- params: DocsPageParams;
34
+ params: Params;
29
35
  }
30
- interface PublicPageUrlContext extends PageUrlContext {
36
+ interface PublicPageUrlContext<Params extends DocsPageParams = DocsPageParams> extends PageUrlContext<Params> {
31
37
  pageUrl: string;
32
38
  }
33
- interface MarkdownUrlContext extends PublicPageUrlContext {
39
+ interface MarkdownUrlContext<Params extends DocsPageParams = DocsPageParams> extends PublicPageUrlContext<Params> {
34
40
  publicPageUrl: string;
35
41
  }
36
42
  export interface ResolvePageMarkdownUrlOptions {
@@ -49,17 +55,19 @@ interface DocsPageData extends GeistdocsPageVisibilityData {
49
55
  title: string;
50
56
  toc: ComponentProps<typeof FumadocsDocsPage>["toc"];
51
57
  }
52
- interface CreateDocsPageOptions {
58
+ export interface CreateDocsPageOptions<Params extends DocsPageParams = DocsPageParams> {
59
+ /** Return false to make a page unavailable for the current route params. */
60
+ canViewPage?: DocsPageAccessFilter<Params>;
53
61
  config: Pick<GeistdocsConfig, "ai" | "basePath" | "feedback" | "github" | "pageActions" | "siteId" | "siteUrl">;
54
62
  filterStaticParams?: (params: DocsPageParams) => boolean;
55
- getMarkdownUrl?: (context: MarkdownUrlContext) => string;
56
- getPageUrl?: (context: PageUrlContext) => string;
57
- getPublicPageUrl?: (context: PublicPageUrlContext) => string;
63
+ getMarkdownUrl?: (context: MarkdownUrlContext<Params>) => string;
64
+ getPageUrl?: (context: PageUrlContext<Params>) => string;
65
+ getPublicPageUrl?: (context: PublicPageUrlContext<Params>) => string;
58
66
  mdx?: DocsPageMdx;
59
67
  metadata?: (context: {
60
68
  metadata: Metadata;
61
69
  page: GeistdocsPage;
62
- params: DocsPageParams;
70
+ params: Params;
63
71
  }) => Metadata | Promise<Metadata>;
64
72
  openGraph?: DocsPageOpenGraphOptions;
65
73
  pageActions?: PageActionsBundle;
@@ -73,6 +81,7 @@ interface CreateDocsPageOptions {
73
81
  }) => ReactNode;
74
82
  resolveLink?: (context: {
75
83
  link: DocsPageLink;
84
+ nativeLink: typeof NativeDocsLink;
76
85
  page: GeistdocsPage;
77
86
  source: SourceBundle;
78
87
  }) => DocsPageLink;
@@ -80,19 +89,14 @@ interface CreateDocsPageOptions {
80
89
  tableOfContent?: TableOfContentOptions;
81
90
  tableOfContentPopover?: ComponentProps<typeof FumadocsDocsPage>["tableOfContentPopover"];
82
91
  }
83
- export declare const createDocsPage: ({ config, source, mdx, pageActions, filterStaticParams, getMarkdownUrl, getPageUrl, getPublicPageUrl, metadata, openGraph, renderTop, resolveLink, tableOfContent, tableOfContentPopover, }: CreateDocsPageOptions) => {
84
- Page: ({ params, }: {
85
- params: Promise<{
86
- lang: string;
87
- slug?: string[];
88
- }>;
92
+ export declare const createDocsPage: <Params extends DocsPageParams = DocsPageParams>({ canViewPage, config, source, mdx, pageActions, filterStaticParams, getMarkdownUrl, getPageUrl, getPublicPageUrl, metadata, openGraph, renderTop, resolveLink, tableOfContent, tableOfContentPopover, }: CreateDocsPageOptions<Params>) => {
93
+ Page: ({ params }: {
94
+ params: Promise<Params>;
89
95
  }) => import("react/jsx-runtime").JSX.Element;
96
+ getPageTree: (params: Params) => Promise<import("fumadocs-core/page-tree").Root>;
90
97
  generateStaticParams: () => DocsPageParams[];
91
98
  generateMetadata: ({ params, }: {
92
- params: Promise<{
93
- lang: string;
94
- slug?: string[];
95
- }>;
99
+ params: Promise<Params>;
96
100
  }) => Promise<Metadata>;
97
101
  };
98
102
  export declare const createPageActions: ({ config, getExtraActions, }: import("../internal/page-actions").CreatePageActionsOptions) => {
@@ -1 +1 @@
1
- {"version":3,"file":"docs.d.ts","sourceRoot":"","sources":["../../src/pages/docs.tsx"],"names":[],"mappings":"AACA,OAAO,EAGL,QAAQ,IAAI,gBAAgB,EAE7B,MAAM,+BAA+B,CAAC;AAEvC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,MAAM,CAAC;AAErC,OAAO,KAAK,EAAE,cAAc,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAEtE,OAAO,EAAE,KAAK,eAAe,EAA+B,MAAM,WAAW,CAAC;AAc9E,OAAO,EACL,KAAK,2BAA2B,EAEjC,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,WAAW,CAAC;AAEvD,KAAK,YAAY,GAAG,qBAAqB,CAAC;AAC1C,KAAK,aAAa,GAAG,WAAW,CAAC,UAAU,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CA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qB,CAAC,MAAM,CAAC;uBAsOJ;QAAE,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,CAAA;KAAE;0BAtKlB,MAAM;;oCAoLtC;QACD,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;KACzB,KAAG,OAAO,CAAC,QAAQ,CAAC;CAqDtB,CAAC;AAEF,eAAO,MAAM,iBAAiB;;;CAA4B,CAAC"}
@@ -3,8 +3,11 @@ import Link from "fumadocs-core/link";
3
3
  import { DocsBody as FumadocsDocsBody, DocsDescription as FumadocsDocsDescription, DocsPage as FumadocsDocsPage, DocsTitle as FumadocsDocsTitle, } from "fumadocs-ui/layouts/docs/page";
4
4
  import { createRelativeLink } from "fumadocs-ui/mdx";
5
5
  import { notFound } from "next/navigation";
6
+ import { cache, } from "react";
6
7
  import { cn } from "#geistdocs-ui/utils";
8
+ import { NativeDocsLink } from "../components/link";
7
9
  import { getPublicPath, withBasePath } from "../config";
10
+ import { getDocsLinkClassName } from "../internal/docs-link-class-name";
8
11
  import { DocsPageErrorBoundary } from "../internal/docs-page-error-boundary";
9
12
  import { resolveDocumentTitle } from "../internal/document-title";
10
13
  import { resolveLinkHref, stripBasePathFromHref } from "../internal/link-href";
@@ -13,6 +16,7 @@ import { createPageActions as createInternalPageActions } from "../internal/page
13
16
  import { GeistdocsPageActions, GeistdocsTableOfContentsActions, } from "../internal/page-actions-client";
14
17
  import { PageBreadcrumb } from "../internal/page-breadcrumb";
15
18
  import { getPageFooterItems, PageFooter } from "../internal/page-footer";
19
+ import { filterPageTree } from "../internal/page-tree-visibility";
16
20
  import { GeistdocsTableOfContents } from "../internal/table-of-contents";
17
21
  import { createMdxComponents } from "../mdx";
18
22
  import { getPageRobots, } from "../page-visibility";
@@ -22,7 +26,7 @@ const renderPrefetchedDocsLink = (siteUrl, basePath, { children, className, href
22
26
  const linkHref = resolved.href === originalHref
23
27
  ? resolved.href
24
28
  : stripBasePathFromHref(resolved.href, basePath);
25
- return (_jsx(Link, { ...props, className: cn("font-normal text-gray-1000! underline decoration-1 decoration-gray-700 underline-offset-4 hover:text-gray-1000! hover:decoration-gray-1000 hover:opacity-100!", className), href: linkHref, prefetch: !resolved.external, rel: resolved.external ? rel : undefined, target: resolved.external ? target : undefined, children: children }));
29
+ return (_jsx(Link, { ...props, className: getDocsLinkClassName(className), href: linkHref, prefetch: !resolved.external, rel: resolved.external ? rel : undefined, target: resolved.external ? target : undefined, children: children }));
26
30
  };
27
31
  export const resolvePageMarkdownUrl = (options) => resolveInternalPageMarkdownUrl(options);
28
32
  const DocsTitle = ({ className, ...props }) => (_jsx(FumadocsDocsTitle, { className: cn("mb-4 text-balance", className), ...props }));
@@ -33,7 +37,10 @@ const TocFooterSlot = ({ children }) => children ? _jsx("div", { className: "mt-
33
37
  const hasTableOfContentsActions = (config, extraActions) => config.pageActions?.scrollTop !== false ||
34
38
  config.feedback?.enabled !== false ||
35
39
  extraActions.length > 0;
36
- export const createDocsPage = ({ config, source, mdx, pageActions = createInternalPageActions({ config }), filterStaticParams, getMarkdownUrl, getPageUrl, getPublicPageUrl, metadata, openGraph, renderTop, resolveLink, tableOfContent, tableOfContentPopover, }) => {
40
+ const serializeParams = (params) => JSON.stringify(Object.entries(params)
41
+ .filter(([, value]) => value !== undefined)
42
+ .sort(([left], [right]) => left.localeCompare(right)));
43
+ export const createDocsPage = ({ canViewPage, config, source, mdx, pageActions = createInternalPageActions({ config }), filterStaticParams, getMarkdownUrl, getPageUrl, getPublicPageUrl, metadata, openGraph, renderTop, resolveLink, tableOfContent, tableOfContentPopover, }) => {
37
44
  const DocsLink = renderPrefetchedDocsLink.bind(null, config.siteUrl, config.basePath);
38
45
  const resolvePageUrls = (page, params) => {
39
46
  const pageUrl = getPageUrl?.({ page, params }) ?? page.url;
@@ -48,22 +55,53 @@ export const createDocsPage = ({ config, source, mdx, pageActions = createIntern
48
55
  });
49
56
  return { markdownUrl, pageUrl, publicPageUrl };
50
57
  };
51
- const PageContent = async ({ params, }) => {
52
- const resolvedParams = await params;
53
- const { slug, lang } = resolvedParams;
54
- const page = source.source.getPage(slug, lang);
58
+ const getAccessState = cache(async (paramsKey) => {
59
+ const params = Object.fromEntries(JSON.parse(paramsKey));
60
+ const tree = source.source.getPageTree(params.lang);
61
+ if (!canViewPage) {
62
+ return { tree, visibleUrls: undefined };
63
+ }
64
+ const access = await Promise.all(source.source.getPages(params.lang).map(async (page) => ({
65
+ page,
66
+ visible: await canViewPage(page, { params, source }),
67
+ })));
68
+ const visibleUrls = new Set(access.filter(({ visible }) => visible).map(({ page }) => page.url));
69
+ const hiddenUrls = new Set(access.filter(({ visible }) => !visible).map(({ page }) => page.url));
70
+ return { tree: filterPageTree(tree, hiddenUrls), visibleUrls };
71
+ });
72
+ const getPage = async (params) => {
73
+ const page = source.source.getPage(params.slug, params.lang);
55
74
  if (!page) {
56
75
  notFound();
57
76
  }
77
+ if (canViewPage) {
78
+ const { visibleUrls } = await getAccessState(serializeParams(params));
79
+ if (!visibleUrls?.has(page.url)) {
80
+ notFound();
81
+ }
82
+ }
83
+ return page;
84
+ };
85
+ const getPageTree = async (params) => (await getAccessState(serializeParams(params))).tree;
86
+ const PageContent = async ({ params }) => {
87
+ const resolvedParams = await params;
88
+ const { lang } = resolvedParams;
89
+ const page = await getPage(resolvedParams);
90
+ const pageTree = await getPageTree(resolvedParams);
58
91
  const data = page.data;
59
92
  const MDX = data.body;
60
93
  const defaultLink = createRelativeLink(source.source, page, DocsLink);
61
94
  const link = resolveLink
62
- ? resolveLink({ link: defaultLink, page, source })
95
+ ? resolveLink({
96
+ link: defaultLink,
97
+ nativeLink: NativeDocsLink,
98
+ page,
99
+ source,
100
+ })
63
101
  : defaultLink;
64
102
  const resolvedMdx = typeof mdx === "function" ? mdx({ link, page, source }) : mdx;
65
103
  const { markdownUrl, pageUrl, publicPageUrl } = resolvePageUrls(page, resolvedParams);
66
- const footerItems = getPageFooterItems(source.source.getPageTree(lang), page.url);
104
+ const footerItems = getPageFooterItems(pageTree, page.url);
67
105
  const pagesByUrl = getPageUrl
68
106
  ? new Map(source.source.getPages(lang).map((entry) => [entry.url, entry]))
69
107
  : undefined;
@@ -79,7 +117,7 @@ export const createDocsPage = ({ config, source, mdx, pageActions = createIntern
79
117
  ...item,
80
118
  url: getPageUrl({
81
119
  page: itemPage,
82
- params: { lang, slug: itemPage.slugs },
120
+ params: { ...resolvedParams, slug: itemPage.slugs },
83
121
  }),
84
122
  };
85
123
  };
@@ -106,7 +144,7 @@ export const createDocsPage = ({ config, source, mdx, pageActions = createIntern
106
144
  const tocFooter = (_jsxs(_Fragment, { children: [hasTocLinks && hasTocActions ? (_jsx("div", { className: "mt-4 border-gray-alpha-400 border-t pt-4", children: _jsx("nav", { "aria-label": "Page actions", className: "flex min-w-0 flex-col gap-1", children: _jsx(GeistdocsTableOfContentsActions, { config: pageActions.config, extraActions: footerActions }) }) })) : null, _jsx(TocFooterSlot, { children: tableOfContent?.footer })] }));
107
145
  const tocComponent = tableOfContent?.component ?? (_jsx(GeistdocsTableOfContents, { footer: tocFooter, header: tableOfContent?.header, toc: data.toc ?? [] }));
108
146
  return (_jsxs(FumadocsDocsPage, { breadcrumb: {
109
- component: (_jsx(PageBreadcrumb, { tree: source.source.getPageTree(lang), url: page.url })),
147
+ component: _jsx(PageBreadcrumb, { tree: pageTree, url: page.url }),
110
148
  }, footer: { component: _jsx(PageFooter, { ...resolvedFooterItems }) }, full: data.full, tableOfContent: {
111
149
  enabled: true,
112
150
  single: true,
@@ -135,18 +173,15 @@ export const createDocsPage = ({ config, source, mdx, pageActions = createIntern
135
173
  ...resolvedMdx,
136
174
  } }) })] }));
137
175
  };
138
- const Page = ({ params, }) => (_jsx(DocsPageErrorBoundary, { children: _jsx(PageContent, { params: params }) }));
176
+ const Page = ({ params }) => (_jsx(DocsPageErrorBoundary, { children: _jsx(PageContent, { params: params }) }));
139
177
  const generateStaticParams = () => {
140
178
  const params = source.source.generateParams();
141
179
  return filterStaticParams ? params.filter(filterStaticParams) : params;
142
180
  };
143
181
  const generateMetadata = async ({ params, }) => {
144
182
  const resolvedParams = await params;
145
- const { slug, lang } = resolvedParams;
146
- const page = source.source.getPage(slug, lang);
147
- if (!page) {
148
- notFound();
149
- }
183
+ const page = await getPage(resolvedParams);
184
+ const pageTree = await getPageTree(resolvedParams);
150
185
  const data = page.data;
151
186
  const { markdownUrl, publicPageUrl } = resolvePageUrls(page, resolvedParams);
152
187
  const openGraphImages = openGraph?.images === true
@@ -163,7 +198,7 @@ export const createDocsPage = ({ config, source, mdx, pageActions = createIntern
163
198
  title: resolveDocumentTitle({
164
199
  pageTitle: data.title,
165
200
  pageUrl: page.url,
166
- tree: source.source.getPageTree(lang),
201
+ tree: pageTree,
167
202
  }),
168
203
  description: data.description,
169
204
  keywords: data.keywords,
@@ -186,6 +221,7 @@ export const createDocsPage = ({ config, source, mdx, pageActions = createIntern
186
221
  };
187
222
  return {
188
223
  Page,
224
+ getPageTree,
189
225
  generateStaticParams,
190
226
  generateMetadata,
191
227
  };
package/dist/proxy.d.ts CHANGED
@@ -17,6 +17,7 @@ export interface GeistdocsProxyContext {
17
17
  }
18
18
  type ProxyHookResult = Response | undefined | null;
19
19
  export type GeistdocsProxyHook = (context: GeistdocsProxyContext) => Promise<ProxyHookResult> | ProxyHookResult;
20
+ export type GeistdocsRewriteTransform = (pathname: `/${string}`, context: GeistdocsProxyContext) => Promise<`/${string}`> | `/${string}`;
20
21
  export interface GeistdocsMarkdownRoute {
21
22
  from: `/${string}`;
22
23
  to: `/${string}` | ((context: {
@@ -39,7 +40,9 @@ export interface CreateProxyOptions {
39
40
  }) => boolean);
40
41
  markdownRoutes?: GeistdocsMarkdownRoute[];
41
42
  trackMarkdownRequest?: (event: TrackMarkdownRequestEvent) => Promise<void> | void;
43
+ /** Transform Geistdocs' localized, app-local internal rewrite destination. */
44
+ transformRewrite?: GeistdocsRewriteTransform;
42
45
  }
43
- export declare const createProxy: ({ additionalMarkdownRoutes, after, before, config, markdownNotFound, markdownRoutes, trackMarkdownRequest, }: CreateProxyOptions) => (request: NextRequest, context: NextFetchEvent) => Promise<Response>;
46
+ export declare const createProxy: ({ additionalMarkdownRoutes, after, before, config, markdownNotFound, markdownRoutes, trackMarkdownRequest, transformRewrite, }: CreateProxyOptions) => (request: NextRequest, context: NextFetchEvent) => Promise<Response>;
44
47
  export {};
45
48
  //# sourceMappingURL=proxy.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"proxy.d.ts","sourceRoot":"","sources":["../src/proxy.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,KAAK,cAAc,EACnB,KAAK,WAAW,EAEjB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,KAAK,eAAe,EAGrB,MAAM,UAAU,CAAC;AASlB,MAAM,MAAM,eAAe,GACvB,UAAU,GACV,iBAAiB,GACjB,WAAW,GACX,IAAI,CAAC;AAET,MAAM,WAAW,yBAAyB;IACxC,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,eAAe,CAAC,EAAE,eAAe,CAAC;IAClC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,WAAW,CAAC,EAAE,QAAQ,GAAG,mBAAmB,GAAG,eAAe,CAAC;IAC/D,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;CAC1B;AAED,MAAM,WAAW,qBAAqB;IACpC,OAAO,EAAE,cAAc,CAAC;IACxB,eAAe,EAAE,MAAM,CAAC;IACxB,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,OAAO,EAAE,WAAW,CAAC;CACtB;AAED,KAAK,eAAe,GAAG,QAAQ,GAAG,SAAS,GAAG,IAAI,CAAC;AAEnD,MAAM,MAAM,kBAAkB,GAAG,CAC/B,OAAO,EAAE,qBAAqB,KAC3B,OAAO,CAAC,eAAe,CAAC,GAAG,eAAe,CAAC;AAEhD,MAAM,WAAW,sBAAsB;IACrC,IAAI,EAAE,IAAI,MAAM,EAAE,CAAC;IACnB,EAAE,EACE,IAAI,MAAM,EA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C;IAClD,MAAM,CAAC,EAAE,kBAAkB,GAAG,kBAAkB,EAAE,CAAC;IACnD,MAAM,EAAE,IAAI,CACV,eAAe,EACf,OAAO,GAAG,UAAU,GAAG,SAAS,GAAG,iBAAiB,GAAG,cAAc,CACtE,CAAC;IACF,sFAAsF;IACtF,gBAAgB,CAAC,EACb,OAAO,GACP,CAAC,CAAC,OAAO,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,KAAK,OAAO,CAAC,CAAC;IACnE,cAAc,CAAC,EAAE,sBAAsB,EAAE,CAAC;IAC1C,oBAAoB,CAAC,EAAE,CACrB,KAAK,EAAE,yBAAyB,KAC7B,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IAC1B,8EAA8E;IAC9E,gBAAgB,CAAC,EAAE,yBAAyB,CAAC;CAC9C;AAoKD,eAAO,MAAM,WAAW,GAAI,gIASzB,kBAAkB,MAsVL,SAAS,WAAW,EAAE,SAAS,cAAc,sBA0D5D,CAAC"}
package/dist/proxy.js CHANGED
@@ -121,7 +121,7 @@ const getLocalizedPathname = (pathname, languages, defaultLanguage) => {
121
121
  pathname: `/${segments.slice(1).join("/")}`,
122
122
  };
123
123
  };
124
- export const createProxy = ({ additionalMarkdownRoutes, after, before, config, markdownNotFound, markdownRoutes, trackMarkdownRequest, }) => {
124
+ export const createProxy = ({ additionalMarkdownRoutes, after, before, config, markdownNotFound, markdownRoutes, trackMarkdownRequest, transformRewrite, }) => {
125
125
  const agentEnabled = config.agent !== undefined && config.agent.enabled !== false;
126
126
  const contentRouteMappings = [
127
127
  ...(additionalMarkdownRoutes ?? []),
@@ -195,7 +195,10 @@ export const createProxy = ({ additionalMarkdownRoutes, after, before, config, m
195
195
  }
196
196
  return null;
197
197
  };
198
- const tryMarkdownRewrite = (request, context, pathname, language, options) => {
198
+ const resolveInternalPathname = async (pathname, proxyContext) => transformRewrite
199
+ ? transformRewrite(pathname, proxyContext)
200
+ : pathname;
201
+ const tryMarkdownRewrite = async (request, context, proxyContext, pathname, language, options) => {
199
202
  const result = resolveMarkdownRewrite(pathname, language);
200
203
  if (!result) {
201
204
  return null;
@@ -212,7 +215,7 @@ export const createProxy = ({ additionalMarkdownRoutes, after, before, config, m
212
215
  if (configuredBasePath) {
213
216
  rewriteUrl.basePath = configuredBasePath;
214
217
  }
215
- rewriteUrl.pathname = result;
218
+ rewriteUrl.pathname = await resolveInternalPathname(result, proxyContext);
216
219
  const response = NextResponse.rewrite(rewriteUrl);
217
220
  // The destination route adds a canonical only after it resolves a page.
218
221
  // The proxy cannot distinguish valid pages from smart not-found responses.
@@ -221,26 +224,26 @@ export const createProxy = ({ additionalMarkdownRoutes, after, before, config, m
221
224
  };
222
225
  const isMdExtensionRequest = (pathname, language) => (pathname.endsWith(".md") || pathname.endsWith(".mdx")) &&
223
226
  Boolean(resolveMarkdownRewrite(pathname.replace(MDX_EXTENSION_PATTERN, ""), language));
224
- const handleMarkdownExtensionRequest = (request, context, pathname, language, trackPath) => {
227
+ const handleMarkdownExtensionRequest = (request, context, proxyContext, pathname, language, trackPath) => {
225
228
  if (!isMdExtensionRequest(pathname, language)) {
226
229
  return null;
227
230
  }
228
- return tryMarkdownRewrite(request, context, pathname.replace(MDX_EXTENSION_PATTERN, ""), language, {
231
+ return tryMarkdownRewrite(request, context, proxyContext, pathname.replace(MDX_EXTENSION_PATTERN, ""), language, {
229
232
  requestType: "md-url",
230
233
  trackPath,
231
234
  });
232
235
  };
233
- const handleNegotiatedMarkdownRequest = (request, context, pathname, language, trackPath, decision) => {
236
+ const handleNegotiatedMarkdownRequest = (request, context, proxyContext, pathname, language, trackPath, decision) => {
234
237
  if (!decision.serve) {
235
238
  return null;
236
239
  }
237
- return tryMarkdownRewrite(request, context, pathname, language, {
240
+ return tryMarkdownRewrite(request, context, proxyContext, pathname, language, {
238
241
  requestType: decision.reason === "agent" ? "agent-rewrite" : "header-negotiated",
239
242
  detectionMethod: decision.reason === "agent" ? decision.detection.method : undefined,
240
243
  trackPath,
241
244
  });
242
245
  };
243
- const handleMarkdownNegotiation = (request, context, pathname) => {
246
+ const handleMarkdownNegotiation = async (request, context, proxyContext, pathname) => {
244
247
  if (!MARKDOWN_REQUEST_METHODS.has(request.method)) {
245
248
  return null;
246
249
  }
@@ -249,14 +252,14 @@ export const createProxy = ({ additionalMarkdownRoutes, after, before, config, m
249
252
  PACKAGE_ROUTE_PATHS.has(localized.pathname)) {
250
253
  return null;
251
254
  }
252
- const extensionResponse = handleMarkdownExtensionRequest(request, context, localized.pathname, localized.language, pathname);
255
+ const extensionResponse = await handleMarkdownExtensionRequest(request, context, proxyContext, localized.pathname, localized.language, pathname);
253
256
  if (extensionResponse) {
254
257
  return extensionResponse;
255
258
  }
256
259
  const markdownDecision = getMarkdownDecision(request);
257
260
  if (resolveMarkdownRewrite(localized.pathname, localized.language) &&
258
261
  !localized.pathname.includes("/llms.mdx/")) {
259
- const negotiatedResponse = handleNegotiatedMarkdownRequest(request, context, localized.pathname, localized.language, pathname, markdownDecision);
262
+ const negotiatedResponse = await handleNegotiatedMarkdownRequest(request, context, proxyContext, localized.pathname, localized.language, pathname, markdownDecision);
260
263
  if (negotiatedResponse) {
261
264
  return negotiatedResponse;
262
265
  }
@@ -277,6 +280,33 @@ export const createProxy = ({ additionalMarkdownRoutes, after, before, config, m
277
280
  }
278
281
  return response;
279
282
  };
283
+ const transformI18nResponse = async (response, request, proxyContext, pathname) => {
284
+ if (!transformRewrite || response.headers.has("location")) {
285
+ return response;
286
+ }
287
+ const rewrite = response.headers.get("x-middleware-rewrite");
288
+ let internalPathname = pathname;
289
+ let rewriteUrl = new URL(request.url);
290
+ if (rewrite) {
291
+ rewriteUrl = new URL(rewrite);
292
+ internalPathname = rewriteUrl.pathname;
293
+ }
294
+ if (configuredBasePath &&
295
+ (internalPathname === configuredBasePath ||
296
+ internalPathname.startsWith(`${configuredBasePath}/`))) {
297
+ internalPathname =
298
+ internalPathname.slice(configuredBasePath.length) || "/";
299
+ }
300
+ const transformed = await resolveInternalPathname(internalPathname, proxyContext);
301
+ rewriteUrl.pathname = getPublicPath(transformed, configuredBasePath);
302
+ const transformedResponse = NextResponse.rewrite(rewriteUrl);
303
+ for (const [key, value] of response.headers) {
304
+ if (key !== "x-middleware-next" && key !== "x-middleware-rewrite") {
305
+ transformedResponse.headers.set(key, value);
306
+ }
307
+ }
308
+ return transformedResponse;
309
+ };
280
310
  return async (request, context) => {
281
311
  const pathname = request.nextUrl.pathname;
282
312
  const proxyContext = {
@@ -298,7 +328,7 @@ export const createProxy = ({ additionalMarkdownRoutes, after, before, config, m
298
328
  acceptHeader: request.headers.get("accept"),
299
329
  });
300
330
  }
301
- const markdownResponse = handleMarkdownNegotiation(request, context, pathname);
331
+ const markdownResponse = await handleMarkdownNegotiation(request, context, proxyContext, pathname);
302
332
  if (markdownResponse) {
303
333
  return markdownResponse;
304
334
  }
@@ -306,7 +336,7 @@ export const createProxy = ({ additionalMarkdownRoutes, after, before, config, m
306
336
  if (afterResponse) {
307
337
  return afterResponse;
308
338
  }
309
- const response = await handleI18nRequest(request, context);
339
+ const response = await transformI18nResponse(await handleI18nRequest(request, context), request, proxyContext, pathname);
310
340
  if (MARKDOWN_REQUEST_METHODS.has(request.method) &&
311
341
  resolveMarkdownRewrite(localized.pathname, localized.language)) {
312
342
  applyMarkdownHeaders(response.headers);