@vercel/geistdocs 1.0.3 → 1.0.5
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/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{program as
|
|
2
|
+
import{program as O}from"commander";import{copyFile as st,rm as ot}from"fs/promises";import{join as _}from"path";import{cancel as nt,intro as rt,isCancel as at,log as it,outro as ct,spinner as lt,text as pt}from"@clack/prompts";import{exec as tt}from"child_process";import{promisify as et}from"util";var A="https://github.com/vercel/geistdocs";var m={stdio:"ignore"};var j="geistdocs-update",p=et(tt);var gt="https://github.com/vercel/geistdocs.git",ft=async t=>{await p(`git clone --depth 1 --filter=blob:none --sparse ${gt} ${t}`,m),await p("git sparse-checkout set apps/template",{...m,cwd:t}),await p("mv apps/template/* apps/template/.[!.]* . 2>/dev/null || true",{...m,cwd:t,shell:"/bin/bash"}),await p("rm -rf apps .git",{...m,cwd:t})},dt=async()=>{await st(".env.example",".env.local")},mt=async()=>{await ot(_("content","docs"),{recursive:!0,force:!0})},ut=async()=>{await p("pnpm install",m)},ht=async()=>{await p("git init",m),await p("git add .",m),await p('git commit -m "\u2728 Initial commit"',m)},wt=async()=>{let t=await pt({message:"What is your project named?",placeholder:"my-app",validate(s){if(s.length===0)return"Please enter a project name."}});return at(t)&&(nt("Operation cancelled."),process.exit(0)),t.toString()},H=async t=>{try{rt("Let's start a Geistdocs project!");let s=process.cwd(),e=t.name||await wt(),o=lt(),r=_(s,e);o.start("Cloning template..."),await ft(e),o.message("Moving into project..."),process.chdir(r),o.message("Setting up environment variables..."),await dt(),o.message("Deleting demo content..."),await mt(),o.message("Installing dependencies..."),await ut(),t.disableGit||(o.message("Initializing Git repository..."),await ht()),o.stop("Project initialized successfully!"),ct("Run `pnpm dev` to start the development server.")}catch(s){let e=s instanceof Error?s.message:`Failed to initialize project: ${s}`;it.error(e),process.exit(1)}};import{createHash as yt}from"crypto";import{existsSync as Tt}from"fs";import{readFile as U,writeFile as J}from"fs/promises";import{dirname as $t,parse as N,resolve as C}from"path";import{intro as xt,isCancel as Pt,log as d,outro as P,spinner as bt,text as vt}from"@clack/prompts";import{glob as St}from"glob";import{Project as Ft,SyntaxKind as D}from"ts-morph";var k=10,Ct="content/docs/**/*.mdx",L=".translation-cache.json",Et=/\.[a-z]{2}\.mdx$/,jt=async t=>(await St(t,{cwd:process.cwd(),absolute:!0,nodir:!0})).filter(e=>e.endsWith(".mdx")).filter(e=>!Et.test(e)),Dt=t=>{let s=C(process.cwd(),t),r=new Ft({skipAddingFilesFromTsConfig:!0}).addSourceFileAtPath(s).getVariableDeclaration("translations");if(!r)throw new Error("Could not find translations export in config file");let a=r.getInitializer();if(!a||a.getKind()!==D.ObjectLiteralExpression)throw new Error("translations must be an object literal");let i=a.asKind(D.ObjectLiteralExpression);if(!i)throw new Error("Could not parse translations object");let g=i.getProperties().filter(l=>l.getKind()===D.PropertyAssignment).map(l=>l.asKind(D.PropertyAssignment)?.getName()).filter(l=>l!==void 0);if(g.length===0)throw new Error("No locales found in translations object");let[w,...y]=g;return y},Ot=t=>yt("sha256").update(t).digest("hex"),Rt=async()=>{let t=C(process.cwd(),L);if(!Tt(t))return{};try{let s=await U(t,"utf-8");return JSON.parse(s)}catch{return d.warn("Failed to load translation cache, starting fresh"),{}}},At=async t=>{let s=C(process.cwd(),L);await J(s,JSON.stringify(t,null,2),"utf-8")},kt=(t,s,e,o)=>{let r=t[s];if(!r)return!0;let a=r[e];return a?a.hash!==o:!0},Nt=async(t,s,e)=>{let o=await U(t,"utf-8"),r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:o,locales:s})}),a=await r.text();if(!r.ok){let i=`Translation failed with status ${r.status}`;try{let g=JSON.parse(a);i=g.error||g.message||i}catch{i=a||i}throw new Error(i)}try{return JSON.parse(a)}catch{throw new Error(`Failed to parse response: ${a.slice(0,200)}`)}},Ut=async(t,s,e,o)=>{let r=$t(t),{name:a,ext:i}=N(t);for(let[g,w]of Object.entries(s)){let y=C(r,`${a}.${g}${i}`);await J(y,w,"utf-8"),e[t]||(e[t]={}),e[t][g]={hash:o,translatedAt:new Date().toISOString()}}},K=async(t,s)=>{xt("Translate MDX content");let e=t??Ct,o=[],r=s.url||process.env.GEISTDOCS_TRANSLATE_URL||"https://geistdocs.com/translate",a=s.config??"geistdocs.tsx";if(a)try{o=Dt(a),d.info(`Loaded ${o.length} locale(s) from config: ${o.join(", ")}`)}catch(n){d.error(`Failed to load config: ${n instanceof Error?n.message:String(n)}`),P("Translation cancelled"),process.exit(1)}let i=await jt(e);if(i.length===0&&(d.error(`No MDX files found matching pattern: ${e}`),P("Translation cancelled"),process.exit(1)),d.info(`Found ${i.length} MDX file(s) matching pattern`),o.length===0){let n=await vt({message:"Enter target locales (comma-separated):",placeholder:"cn,fr,es",validate:c=>{if(!c)return"At least one locale is required"}});Pt(n)&&(P("Translation cancelled"),process.exit(0)),o=n.split(",").map(c=>c.trim())}let g=C(process.cwd(),L),w=await Rt();d.info(`Using cache: ${g}`);let y=new Map;for(let n of i){let c=await U(n,"utf-8");y.set(n,Ot(c))}let l=[],T=0;for(let n of o)for(let c of i){let x=y.get(c);if(!x)throw new Error(`Hash not found for file: ${c}`);s.force||kt(w,c,n,x)?l.push({filePath:c,locale:n,hash:x}):T+=1}if(l.length===0){d.success("All translations are up to date!"),P(`Skipped ${T} file(s) (unchanged)`);return}let b=new Map;for(let n of l)b.has(n.filePath)||b.set(n.filePath,[]),b.get(n.filePath)?.push(n);let z=Array.from(b.keys()),$=[];for(let n=0;n<z.length;n+=k)$.push(z.slice(n,n+k));d.info(`Processing ${l.length} file(s) (${i.length} \xD7 ${o.length} locales) in ${$.length} batch(es) of up to ${k}`),T>0&&d.info(`Skipped ${T} file(s) (unchanged)`);let v=bt();try{let n=new Map;v.start("Starting translation...");let c=0;for(let h=0;h<$.length;h++){let R=$[h];for(let f of R){let S=b.get(f);if(!S)throw new Error(`Tasks not found for file: ${f}`);let F=S.map(Y=>Y.locale),Q=S[0].hash;v.message(`Translating ${N(f).name} (${F.length} locales) - ${c}/${l.length} complete`);let M=await Nt(f,F,r);n.set(f,M),await Ut(f,M,w,Q),await At(w),c+=F.length}h<$.length-1&&(v.message(`Batch ${h+1}/${$.length} complete. Pausing...`),await new Promise(f=>setTimeout(f,1e3)))}v.stop("Translation complete!");let x=0;for(let[h,R]of n){let{name:f,ext:S}=N(h);for(let F of Object.keys(R))d.success(`Saved: ${f}.${F}${S}`),x+=1}let G=[`Translated ${x} file(s)`];T>0&&G.push(`Skipped ${T} unchanged`),P(G.join(" \u2022 "))}catch(n){let c=n instanceof Error?n.message:String(n);v.stop(`Translation failed: ${c}`),P("Exiting"),process.exit(1)}};import{copyFile as Lt,mkdir as B,rm as W}from"fs/promises";import{dirname as It,join as E}from"path";import{intro as zt,log as u,outro as X,spinner as Gt}from"@clack/prompts";import{glob as Mt}from"glob";var q="apps/template",V=["**/*","!content/docs/**"],_t=async t=>{let s=process.cwd(),e=E(s,t);await W(e,{recursive:!0,force:!0}),await B(e,{recursive:!0})},Ht=async t=>await p(`git clone --depth 1 ${A} ${t}`),I=async t=>await W(t,{recursive:!0,force:!0}),Jt=async(t,s)=>(await Mt(t,{cwd:s,nodir:!0,dot:!0,ignore:".git/**"})).sort(),Kt=async(t,s)=>{let e=process.cwd(),o=E(s,q,t),r=E(e,t);await B(It(r),{recursive:!0}),await Lt(o,r)},Xt=async(t,s,e)=>{let o={success:[],failed:[]};for(let r of t)try{e.message(`Updating ${r}...`),await Kt(r,s),o.success.push(r)}catch(a){let i=a instanceof Error?a.message:`${a}`;o.failed.push({file:r,error:i})}return o},Vt=t=>{if(t.success.length>0){u.success(`Successfully updated ${t.success.length} files:`);for(let s of t.success)u.info(` \u2713 ${s}`)}if(t.failed.length>0){u.warn(`Failed to update ${t.failed.length} files:`);for(let{file:s,error:e}of t.failed)u.error(` \u2717 ${s}: ${e}`)}},Z=async()=>{let t=process.cwd(),s=E(t,j);try{zt("Let's update your Geistdocs project!"),u.info(`Repository: ${A}`);let e=Gt();e.start("Creating temporary directory..."),await _t(j),e.message("Cloning repository..."),await Ht(j),e.message("Scanning for files...");let o=E(s,q),r=await Jt(V,o);if(e.stop(`Found ${r.length} files to update`),r.length===0){u.warn("No files matched the patterns. Nothing to update."),await I(s),X("Update cancelled.");return}u.info(`Patterns: ${V.length}`),u.info(`Files to update: ${r.length}`),e.start("Updating files...");let a=await Xt(r,s,e);e.message("Cleaning up..."),await I(s),e.stop("Update complete!"),Vt(a),X("Please review and test the changes carefully.")}catch(e){let o=e instanceof Error?e.message:`${e}`;try{await I(s)}catch{}u.error(`Failed to update project: ${o}`),process.exit(1)}};O.command("init").description("Initialize a new Geistdocs project").option("--name <name>","Name of the project").option("--disable-git","Disable git initialization").action(H);O.command("update").description("Update a Geistdocs project").action(Z);O.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(K);O.parse(process.argv);
|