docs-cache 0.1.3 → 0.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.
- package/README.md +29 -13
- package/dist/chunks/add.mjs +2 -2
- package/dist/chunks/clean.mjs +1 -1
- package/dist/chunks/init.mjs +2 -2
- package/dist/chunks/prune.mjs +1 -1
- package/dist/chunks/remove.mjs +2 -2
- package/dist/chunks/status.mjs +1 -1
- package/dist/chunks/sync.mjs +8 -7
- package/dist/chunks/verify.mjs +1 -1
- package/dist/cli.mjs +11 -11
- package/dist/shared/docs-cache.CIYNztql.mjs +3 -0
- package/dist/shared/docs-cache.CLG_Tn1G.mjs +5 -0
- package/dist/shared/docs-cache.D-Yt8qB9.mjs +6 -0
- package/package.json +1 -1
- package/dist/shared/docs-cache.D4Fth4X8.mjs +0 -3
- package/dist/shared/docs-cache.D9_kM5zq.mjs +0 -6
package/README.md
CHANGED
|
@@ -73,24 +73,40 @@ npx docs-cache clean
|
|
|
73
73
|
|
|
74
74
|
### Options
|
|
75
75
|
|
|
76
|
-
| Field | Type | Description
|
|
77
|
-
| ---------- | ------- |
|
|
78
|
-
| `cacheDir` | string | Directory for cache, defaults to `.docs`
|
|
79
|
-
| `
|
|
80
|
-
| `
|
|
81
|
-
|
|
76
|
+
| Field | Type | Description |
|
|
77
|
+
| ---------- | ------- | ---------------------------------------------------- |
|
|
78
|
+
| `cacheDir` | string | Directory for cache, defaults to `.docs` |
|
|
79
|
+
| `sources` | array | List of repositories to sync |
|
|
80
|
+
| `defaults` | object | Default settings for all sources |
|
|
81
|
+
|
|
82
|
+
**Default Options:**
|
|
83
|
+
|
|
84
|
+
All fields in `defaults` apply to all sources unless overridden per-source:
|
|
85
|
+
|
|
86
|
+
- `ref`: Branch, tag, or commit (default: `"HEAD"`)
|
|
87
|
+
- `mode`: Cache mode (default: `"materialize"`)
|
|
88
|
+
- `include`: Glob patterns to copy (default: `["**/*.{md,mdx,markdown,mkd,txt,rst,adoc,asciidoc}"]`)
|
|
89
|
+
- `targetMode`: `"symlink"` or `"copy"` (default: `"symlink"` on Unix, `"copy"` on Windows)
|
|
90
|
+
- `depth`: Git clone depth (default: `1`)
|
|
91
|
+
- `required`: Whether missing sources should fail (default: `true`)
|
|
92
|
+
- `maxBytes`: Maximum total bytes to materialize (default: `200000000`)
|
|
93
|
+
- `maxFiles`: Maximum total files to materialize (optional)
|
|
94
|
+
- `allowHosts`: Allowed Git hosts (default: `["github.com", "gitlab.com"]`)
|
|
95
|
+
- `toc`: Generate per-source `TOC.md` listing all documentation files (default: `true`)
|
|
82
96
|
|
|
83
97
|
**Source Options:**
|
|
84
98
|
|
|
85
|
-
- `repo`: Git URL
|
|
86
|
-
- `
|
|
87
|
-
- `
|
|
99
|
+
- `repo`: Git URL (required)
|
|
100
|
+
- `id`: Unique identifier for the source (required)
|
|
101
|
+
- `ref`: Branch, tag, or commit (overrides default)
|
|
102
|
+
- `include`: Glob patterns to copy (overrides default)
|
|
88
103
|
- `exclude`: Glob patterns to skip
|
|
89
104
|
- `targetDir`: Optional path where files should be symlinked/copied to, outside `.docs`
|
|
90
|
-
- `targetMode`:
|
|
91
|
-
- `required`: Whether missing sources should fail
|
|
92
|
-
- `maxBytes`: Maximum total bytes to materialize
|
|
93
|
-
- `maxFiles`: Maximum total files to materialize
|
|
105
|
+
- `targetMode`: `"symlink"` or `"copy"` (overrides default)
|
|
106
|
+
- `required`: Whether missing sources should fail (overrides default)
|
|
107
|
+
- `maxBytes`: Maximum total bytes to materialize (overrides default)
|
|
108
|
+
- `maxFiles`: Maximum total files to materialize (overrides default)
|
|
109
|
+
- `toc`: Generate per-source `TOC.md` listing all documentation files (overrides default)
|
|
94
110
|
|
|
95
111
|
> **Note**: Sources are always downloaded to `.docs/<id>/`. If you provide a `targetDir`, `docs-cache` will create a symlink or copy pointing from the cache to that target directory. The target should be outside `.docs`.
|
|
96
112
|
|
package/dist/chunks/add.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{readFile as
|
|
2
|
-
`,"utf8")}else await
|
|
1
|
+
import{readFile as D,writeFile as k,access as E}from"node:fs/promises";import l from"node:path";import{v,D as P,a as A,s as F,w as I,b as U,r as S}from"../shared/docs-cache.CIYNztql.mjs";import{e as N}from"../shared/docs-cache.CLG_Tn1G.mjs";import{r as O}from"../shared/docs-cache.D-Yt8qB9.mjs";import{r as x}from"../shared/docs-cache.BSvQNKuf.mjs";import"zod";import"node:process";import"cac";import"picocolors";const u=async o=>{try{return await E(o),!0}catch{return!1}},y="package.json",C=async o=>{const i=await D(o,"utf8"),e=JSON.parse(i),a=e["docs-cache"];return a?{parsed:e,config:v(a)}:{parsed:e,config:null}},J=async o=>{if(o){const a=S(o);return{resolvedPath:a,mode:l.basename(a)===y?"package":"config"}}const i=S();if(await u(i))return{resolvedPath:i,mode:"config"};const e=l.resolve(process.cwd(),y);return await u(e)&&(await C(e)).config?{resolvedPath:e,mode:"package"}:{resolvedPath:i,mode:"config"}},T=async o=>{const i=await J(o.configPath),e=i.resolvedPath;let a=P,t=null,g=null,f=!1;if(await u(e))if(i.mode==="package"){const r=await C(e);g=r.parsed,t=r.config,a=t??P,f=!!t}else{const r=await D(e,"utf8");t=JSON.parse(r.toString()),a=v(t),f=!0}const b="https://raw.githubusercontent.com/fbosch/docs-cache/main/docs.config.schema.json",p=new Set(a.sources.map(r=>r.id)),m=[],d=o.entries.map(r=>{const n=x(r.repo),w=r.id||n.inferredId;if(!w)throw new Error("Unable to infer id. Provide an explicit id.");const c=A(w,"source id");return p.has(c)?(m.push(c),null):(p.add(c),r.targetDir&&O(e,r.targetDir),{id:c,repo:n.repoUrl,...r.targetDir?{targetDir:r.targetDir}:{},...n.ref?{ref:n.ref}:{}})}).filter(Boolean);if(d.length===0)throw new Error("All sources already exist in config.");const s={$schema:b,sources:[...a.sources,...d]};if(t?.cacheDir&&(s.cacheDir=t.cacheDir),t?.defaults&&(s.defaults=t.defaults),i.mode==="package"){const r=g??{};r["docs-cache"]=F(s),await k(e,`${JSON.stringify(r,null,2)}
|
|
2
|
+
`,"utf8")}else await I(e,s);const h=f?null:await N(l.dirname(e),t?.cacheDir??U);return{configPath:e,sources:d,skipped:m,created:!0,gitignoreUpdated:h?.updated??!1,gitignorePath:h?.gitignorePath??null}};export{T as addSources};
|
|
3
3
|
//# sourceMappingURL=add.mjs.map
|
package/dist/chunks/clean.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{rm as o,access as i}from"node:fs/promises";import{l as s,b as m}from"../shared/docs-cache.
|
|
1
|
+
import{rm as o,access as i}from"node:fs/promises";import{l as s,b as m}from"../shared/docs-cache.CIYNztql.mjs";import{a as n}from"../shared/docs-cache.D-Yt8qB9.mjs";import"node:path";import"zod";import"node:process";import"cac";import"picocolors";const f=async r=>{try{return await i(r),!0}catch{return!1}},p=async r=>{const{config:t,resolvedPath:c}=await s(r.configPath),a=n(c,t.cacheDir??m,r.cacheDirOverride),e=await f(a);return e&&await o(a,{recursive:!0,force:!0}),{cacheDir:a,removed:e}};export{p as cleanCache};
|
|
2
2
|
//# sourceMappingURL=clean.mjs.map
|
package/dist/chunks/init.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{readFile as
|
|
2
|
-
`,"utf8"),{configPath:
|
|
1
|
+
import{readFile as C,writeFile as N,access as S}from"node:fs/promises";import c from"node:path";import{confirm as V,isCancel as G,select as J,text as U}from"@clack/prompts";import{c as _,b as r,s as L,w as T}from"../shared/docs-cache.CIYNztql.mjs";import{g as H,e as k}from"../shared/docs-cache.CLG_Tn1G.mjs";import"zod";import"../shared/docs-cache.D-Yt8qB9.mjs";import"node:process";import"cac";import"picocolors";const h=async n=>{try{return await S(n),!0}catch{return!1}},M=async(n,s={})=>{const y=s.confirm??V,l=s.isCancel??G,x=s.select??J,F=s.text??U,f=n.cwd??process.cwd(),d=c.resolve(f,_),i=c.resolve(f,"package.json"),g=[];if(await h(d)&&g.push(d),await h(i)){const e=await C(i,"utf8");JSON.parse(e)["docs-cache"]&&g.push(i)}if(g.length>0)throw new Error(`Config already exists at ${g.join(", ")}. Init aborted.`);let b=!1;if(await h(i)){const e=await C(i,"utf8");if(!JSON.parse(e)["docs-cache"]){const o=await x({message:"Config location",options:[{value:"config",label:"docs.config.json"},{value:"package",label:"package.json"}],initialValue:"config"});if(l(o))throw new Error("Init cancelled.");b=o==="package"}}const $=b?i:d,v=n.cacheDirOverride??r,u=await F({message:"Cache directory",initialValue:v});if(l(u))throw new Error("Init cancelled.");const A=u||r,D=await y({message:"Generate TOC.md (table of contents with links to all documentation)",initialValue:!0});if(l(D))throw new Error("Init cancelled.");const I=await H(f,A);let P=!1;if(I.entry&&!I.hasEntry){const e=await y({message:"Add cache directory to .gitignore",initialValue:!0});if(l(e))throw new Error("Init cancelled.");P=e}const a={configPath:$,cacheDir:u,toc:D,gitignore:P},t=c.resolve(f,a.configPath);if(c.basename(t)==="package.json"){const e=await C(t,"utf8"),o=JSON.parse(e);if(o["docs-cache"])throw new Error(`docs-cache config already exists in ${t}.`);const p={$schema:"https://raw.githubusercontent.com/fbosch/docs-cache/main/docs.config.schema.json",sources:[]},E=a.cacheDir||r;E!==r&&(p.cacheDir=E),a.toc||(p.defaults={toc:!1}),o["docs-cache"]=L(p),await N(t,`${JSON.stringify(o,null,2)}
|
|
2
|
+
`,"utf8");const O=a.gitignore?await k(c.dirname(t),E):null;return{configPath:t,created:!0,gitignoreUpdated:O?.updated??!1,gitignorePath:O?.gitignorePath??null}}if(await h(t))throw new Error(`Config already exists at ${t}.`);const w={$schema:"https://raw.githubusercontent.com/fbosch/docs-cache/main/docs.config.schema.json",sources:[]},m=a.cacheDir||r;m!==r&&(w.cacheDir=m),a.toc||(w.defaults={toc:!1}),await T(t,w);const j=a.gitignore?await k(c.dirname(t),m):null;return{configPath:t,created:!0,gitignoreUpdated:j?.updated??!1,gitignorePath:j?.gitignorePath??null}};export{M as initConfig};
|
|
3
3
|
//# sourceMappingURL=init.mjs.map
|
package/dist/chunks/prune.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readdir as p,rm as f,access as h}from"node:fs/promises";import u from"node:path";import{l as d,b as D}from"../shared/docs-cache.
|
|
1
|
+
import{readdir as p,rm as f,access as h}from"node:fs/promises";import u from"node:path";import{l as d,b as D}from"../shared/docs-cache.CIYNztql.mjs";import{a as v}from"../shared/docs-cache.D-Yt8qB9.mjs";import"zod";import"node:process";import"cac";import"picocolors";const w=async t=>{try{return await h(t),!0}catch{return!1}},l=async t=>{const{config:c,resolvedPath:s,sources:a}=await d(t.configPath),e=v(s,c.cacheDir??D,t.cacheDirOverride);if(!await w(e))return{cacheDir:e,removed:[],kept:a.map(r=>r.id)};const n=new Set(a.map(r=>r.id)),m=await p(e,{withFileTypes:!0}),o=[];for(const r of m){if(!r.isDirectory())continue;const i=r.name;n.has(i)||i.startsWith(".tmp-")||(await f(u.join(e,i),{recursive:!0,force:!0}),o.push(i))}return{cacheDir:e,removed:o,kept:a.map(r=>r.id)}};export{l as pruneCache};
|
|
2
2
|
//# sourceMappingURL=prune.mjs.map
|
package/dist/chunks/remove.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{readFile as w,writeFile as N,rm as $,access as k}from"node:fs/promises";import v from"node:path";import{v as D,D as E,s as
|
|
2
|
-
`,"utf8")}else await
|
|
1
|
+
import{readFile as w,writeFile as N,rm as $,access as k}from"node:fs/promises";import v from"node:path";import{v as D,D as E,s as F,w as I,r as P}from"../shared/docs-cache.CIYNztql.mjs";import{r as O}from"../shared/docs-cache.D-Yt8qB9.mjs";import{r as U}from"../shared/docs-cache.BSvQNKuf.mjs";import"zod";import"node:process";import"cac";import"picocolors";const f=async a=>{try{return await k(a),!0}catch{return!1}},y="package.json",S=async a=>{const s=await w(a,"utf8"),o=JSON.parse(s),r=o["docs-cache"];return r?{parsed:o,config:D(r)}:{parsed:o,config:null}},b=async a=>{if(a){const r=P(a);return{resolvedPath:r,mode:v.basename(r)===y?"package":"config"}}const s=P();if(await f(s))return{resolvedPath:s,mode:"config"};const o=v.resolve(process.cwd(),y);return await f(o)&&(await S(o)).config?{resolvedPath:o,mode:"package"}:{resolvedPath:s,mode:"config"}},J=async a=>{if(a.ids.length===0)throw new Error("No sources specified to remove.");const s=await b(a.configPath),o=s.resolvedPath;let r=E,t=null,d=null;if(await f(o))if(s.mode==="package"){const e=await S(o);if(d=e.parsed,t=e.config,!t)throw new Error(`Missing docs-cache config in ${o}.`);r=t}else{const e=await w(o,"utf8");t=JSON.parse(e.toString()),r=D(t)}else throw new Error(`Config not found at ${o}.`);const u=new Map(r.sources.map(e=>[e.id,e])),g=new Map(r.sources.map(e=>[e.repo,e])),n=new Set,l=[];for(const e of a.ids){if(u.has(e)){n.add(e);continue}const i=U(e);if(i.repoUrl&&g.has(i.repoUrl)){const p=g.get(i.repoUrl);p&&n.add(p.id);continue}if(i.inferredId&&u.has(i.inferredId)){n.add(i.inferredId);continue}l.push(e)}const C=r.sources.filter(e=>!n.has(e.id)),h=r.sources.filter(e=>n.has(e.id)).map(e=>e.id),M=r.sources.filter(e=>n.has(e.id));if(h.length===0)throw new Error("No matching sources found to remove.");const c={$schema:t?.$schema??"https://raw.githubusercontent.com/fbosch/docs-cache/main/docs.config.schema.json",sources:C};if(t?.cacheDir&&(c.cacheDir=t.cacheDir),t?.defaults&&(c.defaults=t.defaults),t?.targetMode&&(c.targetMode=t.targetMode),s.mode==="package"){const e=d??{};e["docs-cache"]=F(c),await N(o,`${JSON.stringify(e,null,2)}
|
|
2
|
+
`,"utf8")}else await I(o,c);const m=[];for(const e of M){if(!e.targetDir)continue;const i=O(o,e.targetDir);await $(i,{recursive:!0,force:!0}),m.push({id:e.id,targetDir:i})}return{configPath:o,removed:h,missing:l,targetsRemoved:m}};export{J as removeSources};
|
|
3
3
|
//# sourceMappingURL=remove.mjs.map
|
package/dist/chunks/status.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{access as E}from"node:fs/promises";import a from"picocolors";import{u as o,s as u,a as w,g as D}from"../shared/docs-cache.
|
|
1
|
+
import{access as E}from"node:fs/promises";import a from"picocolors";import{u as o,s as u,a as w,g as D}from"../shared/docs-cache.D-Yt8qB9.mjs";import{l as v,b as x}from"../shared/docs-cache.CIYNztql.mjs";import{resolveLockPath as C,readLock as P}from"../lock.mjs";import"node:process";import"cac";import"node:path";import"zod";const h=async s=>{try{return await E(s),!0}catch{return!1}},$=async s=>{const{config:e,resolvedPath:t,sources:n}=await v(s.configPath),r=w(t,e.cacheDir??x,s.cacheDirOverride),l=await h(r),c=C(t),i=await h(c);let d=!1,f=null;if(i)try{f=await P(c),d=!0}catch{d=!1}const g=await Promise.all(n.map(async m=>{const p=D(r,m.id),k=await h(p.sourceDir),y=f?.sources?.[m.id]??null;return{id:m.id,docsPath:p.sourceDir,docsExists:k,lockEntry:y}}));return{configPath:t,cacheDir:r,cacheDirExists:l,lockPath:c,lockExists:i,lockValid:d,sources:g}},L=s=>{const e=o.path(s.cacheDir),t=s.cacheDirExists?a.green("present"):a.red("missing"),n=s.lockExists?s.lockValid?a.green("valid"):a.red("invalid"):a.yellow("missing");if(o.header("Cache",`${e} (${t})`),o.header("Lock",`docs.lock (${n})`),s.sources.length===0){o.line(),o.line(`${u.warn} No sources configured.`);return}o.line();for(const r of s.sources){const l=r.docsExists?u.success:u.error,c=r.lockEntry?a.green("locked"):a.yellow("new"),i=o.hash(r.lockEntry?.resolvedCommit);o.item(l,r.id.padEnd(20),`${c.padEnd(10)} ${i}`)}};export{$ as getStatus,L as printStatus};
|
|
2
2
|
//# sourceMappingURL=status.mjs.map
|
package/dist/chunks/sync.mjs
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import{createHash as
|
|
2
|
-
`).filter(Boolean);return
|
|
3
|
-
`;
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
`)}
|
|
1
|
+
import{createHash as N,randomBytes as he}from"node:crypto";import{rm as M,mkdtemp as A,mkdir as b,writeFile as X,access as _,rename as B,open as H,lstat as pe,symlink as we,cp as ge,readFile as j}from"node:fs/promises";import h from"node:path";import E from"picocolors";import{g as ye,t as U,r as z,D as Se,u as C,s as O,a as De}from"../shared/docs-cache.D-Yt8qB9.mjs";import{a as G,l as ve,D as $e,b as Ce}from"../shared/docs-cache.CIYNztql.mjs";import{execFile as K}from"node:child_process";import xe,{tmpdir as q}from"node:os";import{promisify as V}from"node:util";import{writeLock as Pe,resolveLockPath as Me,readLock as Ee}from"../lock.mjs";import{M as Y,v as Z}from"./verify.mjs";import{createWriteStream as Q,createReadStream as Oe,constants as ee}from"node:fs";import{pipeline as Te}from"node:stream/promises";import te from"fast-glob";const ke=/^(https?:\/\/)([^@]+)@/i,R=e=>e.replace(ke,"$1***@"),Fe=V(K),Re=3e4,Ie=new Set(["file:","ftp:","data:","javascript:"]),be=e=>{try{const t=new URL(e);if(Ie.has(t.protocol))throw new Error(`Blocked protocol '${t.protocol}' in repo URL '${R(e)}'.`)}catch(t){if(t instanceof TypeError)return;throw t}},_e=e=>{if(be(e),e.startsWith("git@")){const t=e.indexOf("@"),r=e.indexOf(":",t+1);return r===-1?null:e.slice(t+1,r)||null}try{const t=new URL(e);return t.protocol!=="https:"&&t.protocol!=="ssh:"?null:t.hostname||null}catch{return null}},re=(e,t)=>{const r=_e(e);if(!r)throw new Error(`Unsupported repo URL '${R(e)}'. Use HTTPS or SSH.`);const s=r.toLowerCase();if(!t.map(o=>o.toLowerCase()).includes(s))throw new Error(`Host '${r}' is not in allowHosts for '${R(e)}'.`)},oe=e=>{const t=e.trim().split(`
|
|
2
|
+
`).filter(Boolean);return t.length===0?null:t[0].split(/\s+/)[0]||null},je=async e=>{re(e.repo,e.allowHosts);const{stdout:t}=await Fe("git",["ls-remote",e.repo,e.ref],{timeout:e.timeoutMs??Re,maxBuffer:1024*1024}),r=oe(t);if(!r)throw new Error(`Unable to resolve ref '${e.ref}' for ${R(e.repo)}.`);return{repo:e.repo,ref:e.ref,resolvedCommit:r}},se=V(K),ie=3e4,L=async(e,t)=>{await se("git",["-c","core.hooksPath=/dev/null","-c","submodule.recurse=false","-c","protocol.file.allow=never","-c","protocol.ext.allow=never",...e],{cwd:t?.cwd,timeout:t?.timeoutMs??ie,maxBuffer:1024*1024,env:{PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER,USERPROFILE:process.env.USERPROFILE,TMPDIR:process.env.TMPDIR,TMP:process.env.TMP,TEMP:process.env.TEMP,SYSTEMROOT:process.env.SYSTEMROOT,WINDIR:process.env.WINDIR,SSH_AUTH_SOCK:process.env.SSH_AUTH_SOCK,SSH_AGENT_PID:process.env.SSH_AGENT_PID,HTTP_PROXY:process.env.HTTP_PROXY,HTTPS_PROXY:process.env.HTTPS_PROXY,NO_PROXY:process.env.NO_PROXY,GIT_TERMINAL_PROMPT:"0",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_NOGLOBAL:"1",...process.platform==="win32"?{}:{GIT_ASKPASS:"/bin/false"}}})},Le=async(e,t,r,s)=>{const o=h.join(r,"archive.tar");await L(["archive","--remote",e,"--format=tar","--output",o,t],{timeoutMs:s}),await se("tar",["-xf",o,"-C",r],{timeout:s??ie,maxBuffer:1024*1024}),await M(o,{force:!0})},Ne=e=>{if(!e||e.length===0)return!1;for(const t of e)if(!t||t.includes("**"))return!1;return!0},Ae=e=>{if(!e)return[];const t=e.map(r=>{const s=r.replace(/\\/g,"/"),o=s.indexOf("*");return(o===-1?s:s.slice(0,o)).replace(/\/+$|\/$/,"")});return Array.from(new Set(t.filter(r=>r.length>0)))},Be=async(e,t)=>{const r=/^[0-9a-f]{7,40}$/i.test(e.ref),s=Ne(e.include),o=["clone","--no-checkout","--filter=blob:none","--depth",String(e.depth),"--recurse-submodules=no","--no-tags"];if(s&&o.push("--sparse"),r||(o.push("--single-branch"),e.ref!=="HEAD"&&o.push("--branch",e.ref)),o.push(e.repo,t),await L(o,{timeoutMs:e.timeoutMs}),s){const i=Ae(e.include);i.length>0&&await L(["-C",t,"sparse-checkout","set",...i],{timeoutMs:e.timeoutMs})}await L(["-C",t,"checkout","--detach",e.resolvedCommit],{timeoutMs:e.timeoutMs})},He=async e=>{const t=await A(h.join(q(),`docs-cache-${e.sourceId}-`));try{return await Le(e.repo,e.resolvedCommit,t,e.timeoutMs),t}catch(r){throw await M(t,{recursive:!0,force:!0}),r}},Ue=async e=>{G(e.sourceId,"sourceId");try{const t=await He(e);return{repoDir:t,cleanup:async()=>{await M(t,{recursive:!0,force:!0})}}}catch{const t=await A(h.join(q(),`docs-cache-${e.sourceId}-`));try{return await Be(e,t),{repoDir:t,cleanup:async()=>{await M(t,{recursive:!0,force:!0})}}}catch(r){throw await M(t,{recursive:!0,force:!0}),r}}},F=e=>U(e),W=Number(process.env.DOCS_CACHE_STREAM_THRESHOLD_MB??"2"),ze=Number.isFinite(W)&&W>0?Math.floor(W*1024*1024):1024*1024,Ge=(e,t)=>{const r=h.resolve(e);if(!h.resolve(t).startsWith(r+h.sep))throw new Error(`Path traversal detected: ${t}`)},ae=async e=>{try{return await H(e,ee.O_RDONLY|ee.O_NOFOLLOW)}catch(t){const r=t.code;if(r==="ELOOP")return null;if(r==="EINVAL"||r==="ENOSYS"||r==="ENOTSUP")return(await pe(e)).isSymbolicLink()?null:await H(e,"r");throw t}},Ye=async(e,t=5e3)=>{const r=Date.now();for(;Date.now()-r<t;)try{const s=await H(e,"wx");return{release:async()=>{await s.close(),await M(e,{force:!0})}}}catch(s){if(s.code!=="EEXIST")throw s;await new Promise(o=>setTimeout(o,100))}throw new Error(`Failed to acquire lock for ${e}.`)},We=async e=>{G(e.sourceId,"sourceId");const t=ye(e.cacheDir,e.sourceId);await b(e.cacheDir,{recursive:!0});const r=await A(h.join(e.cacheDir,`.tmp-${e.sourceId}-`));let s=null;const o=async()=>{const i=s;!i||i.closed||i.destroyed||await new Promise(l=>{const f=()=>{i.off("close",u),i.off("error",w),l()},u=()=>f(),w=()=>f();i.once("close",u),i.once("error",w);try{i.end()}catch{f()}})};try{const i=await te(e.include,{cwd:e.repoDir,ignore:[".git/**",...e.exclude??[]],dot:!0,onlyFiles:!0,followSymbolicLinks:!1});i.sort((m,c)=>F(m).localeCompare(F(c)));const l=new Set;for(const m of i)l.add(h.dirname(m));await Promise.all(Array.from(l,m=>b(h.join(r,m),{recursive:!0})));let f=0,u=0;const w=Math.max(1,Math.min(i.length,Math.max(8,Math.min(128,xe.cpus().length*8)))),v=h.join(r,Y),p=Q(v,{encoding:"utf8"});s=p;const D=N("sha256"),y=async m=>new Promise((c,g)=>{const d=x=>{p.off("drain",a),g(x)},a=()=>{p.off("error",d),c()};p.once("error",d),p.write(m)?(p.off("error",d),c()):p.once("drain",a)});for(let m=0;m<i.length;m+=w){const c=i.slice(m,m+w),g=await Promise.all(c.map(async d=>{const a=F(d),x=h.join(e.repoDir,d),$=await ae(x);if(!$)return null;try{const k=await $.stat();if(!k.isFile())return null;const T=h.join(r,d);if(Ge(r,T),k.size>=ze){const P=Oe(x,{fd:$.fd,autoClose:!1}),de=Q(T);await Te(P,de)}else{const P=await $.readFile();await X(T,P)}return{path:a,size:k.size}}finally{await $.close()}}));for(const d of g){if(!d)continue;if(e.maxFiles!==void 0&&u+1>e.maxFiles)throw new Error(`Materialized content exceeds maxFiles (${e.maxFiles}).`);if(f+=d.size,f>e.maxBytes)throw new Error(`Materialized content exceeds maxBytes (${e.maxBytes}).`);const a=`${JSON.stringify(d)}
|
|
3
|
+
`;D.update(a),await y(a),u+=1}}await new Promise((m,c)=>{p.end(()=>m()),p.once("error",c)});const n=D.digest("hex"),S=async m=>{try{return await _(m),!0}catch{return!1}};return await(async(m,c)=>{const g=await Ye(`${c}.lock`);try{const d=await S(c),a=`${c}.bak-${he(8).toString("hex")}`;d&&await B(c,a);try{await B(m,c)}catch(x){if(d)try{await B(a,c)}catch($){const k=$ instanceof Error?$.message:String($);process.stderr.write(`Warning: Failed to restore backup: ${k}
|
|
4
|
+
`)}throw x}d&&await M(a,{recursive:!0,force:!0})}finally{await g.release()}})(r,t.sourceDir),{bytes:f,fileCount:u,manifestSha256:n}}catch(i){try{await o()}catch{}throw await M(r,{recursive:!0,force:!0}),i}},Je=async e=>{G(e.sourceId,"sourceId");const t=await te(e.include,{cwd:e.repoDir,ignore:[".git/**",...e.exclude??[]],dot:!0,onlyFiles:!0,followSymbolicLinks:!1});t.sort((i,l)=>F(i).localeCompare(F(l)));let r=0,s=0;const o=N("sha256");for(const i of t){const l=F(i),f=h.join(e.repoDir,i),u=await ae(f);if(u)try{const w=await u.stat();if(!w.isFile())continue;if(e.maxFiles!==void 0&&s+1>e.maxFiles)throw new Error(`Materialized content exceeds maxFiles (${e.maxFiles}).`);if(r+=w.size,r>e.maxBytes)throw new Error(`Materialized content exceeds maxBytes (${e.maxBytes}).`);const v=`${JSON.stringify({path:l,size:w.size})}
|
|
5
|
+
`;o.update(v),s+=1}finally{await u.close()}}return{bytes:r,fileCount:s,manifestSha256:o.digest("hex")}},Xe=async(e,t)=>{await t.rm(e,{recursive:!0,force:!0})},J=async e=>{const t=e.deps??{cp:ge,mkdir:b,rm:M,symlink:we,stderr:process.stderr},r=h.dirname(e.targetDir);await t.mkdir(r,{recursive:!0}),await Xe(e.targetDir,t);const s=process.platform==="win32"?"copy":"symlink";if((e.mode??s)==="copy"){await t.cp(e.sourceDir,e.targetDir,{recursive:!0});return}const o=process.platform==="win32"?"junction":"dir";try{await t.symlink(e.sourceDir,e.targetDir,o)}catch(i){const l=i.code;if(l&&new Set(["EPERM","EACCES","ENOTSUP","EINVAL"]).has(l)){if(e.explicitTargetMode){const f=i instanceof Error?i.message:String(i);t.stderr.write(`Warning: Failed to create symlink at ${e.targetDir}. Falling back to copy. ${f}
|
|
6
|
+
`)}await t.cp(e.sourceDir,e.targetDir,{recursive:!0});return}throw i}},Ke=e=>{const t={dirs:new Map,files:[]};for(const r of e){const s=r.split("/").filter(Boolean);if(s.length===0)continue;let o=t;for(const l of s.slice(0,-1)){let f=o.dirs.get(l);f||(f={dirs:new Map,files:[]},o.dirs.set(l,f)),o=f}const i=s[s.length-1];o.files.push({name:i,path:r})}return t},ne=(e,t,r)=>{const s=" ".repeat(t),o=Array.from(e.dirs.keys()).sort(),i=[...e.files].sort((l,f)=>l.name.localeCompare(f.name));for(const l of o){r.push(`${s}- ${l}/`);const f=e.dirs.get(l);f&&ne(f,t+1,r)}for(const l of i)r.push(`${s}- [${l.name}](./${l.path})`)},qe=e=>{const t=[];t.push("---"),t.push(`id: ${e.id}`),t.push(`repository: ${e.repo}`),t.push(`ref: ${e.ref}`),t.push(`commit: ${e.resolvedCommit}`),e.targetDir&&t.push(`targetDir: ${e.targetDir}`),t.push("---"),t.push(""),t.push(`# ${e.id} - Documentation`),t.push(""),t.push("## Files"),t.push("");const r=Ke(e.files);return ne(r,0,t),t.push(""),t.join(`
|
|
7
|
+
`)},Ve=async e=>{const t=h.join(e,".manifest.jsonl");try{const r=await j(t,"utf8"),s=[];for(const o of r.split(`
|
|
8
|
+
`))if(o.trim()){const i=JSON.parse(o);i.path&&s.push(i.path)}return s}catch{return[]}},Ze=async e=>{const t=new Map(e.sources.map(s=>[s.id,s])),r=new Map((e.results??[]).map(s=>[s.id,s]));for(const[s,o]of Object.entries(e.lock.sources)){const i=t.get(s),l=i?.targetDir?U(z(e.configPath,i.targetDir)):void 0,f=h.join(e.cacheDir,s);try{await _(f)}catch{continue}const u=await Ve(f),w={id:s,repo:o.repo,ref:o.ref,resolvedCommit:o.resolvedCommit,fileCount:o.fileCount,cachePath:U(h.join(e.cacheDir,s)),targetDir:l,files:u},v=i?.toc??!0,p=h.join(f,Se);if(v){if(r.get(s)?.status==="up-to-date")try{await _(p);continue}catch{}const D=qe(w);await X(p,D,"utf8")}else try{await M(p,{force:!0})}catch{}}},Qe=e=>{if(e<1024)return`${e} B`;const t=["KB","MB","GB","TB"];let r=e,s=-1;for(;r>=1024&&s<t.length-1;)r/=1024,s+=1;return`${r.toFixed(1)} ${t[s]}`},I=async e=>{try{return await _(e),!0}catch{return!1}},ce=async(e,t)=>{const r=h.join(e,t);return await I(r)?await I(h.join(r,Y)):!1},le=e=>{if(!e||e.length===0)return[];const t=e.map(r=>r.trim()).filter(r=>r.length>0);return Array.from(new Set(t)).sort()},et=e=>{const t={include:le(e.include),exclude:le(e.exclude)},r=N("sha256");return r.update(JSON.stringify(t)),r.digest("hex")},ue=async(e,t={})=>{const{config:r,resolvedPath:s,sources:o}=await ve(e.configPath),i=r.defaults??$e.defaults,l=De(s,r.cacheDir??Ce,e.cacheDirOverride),f=Me(s),u=await I(f);let w=null;u&&(w=await Ee(f));const v=t.resolveRemoteCommit??je,p=e.sourceFilter?.length?o.filter(y=>e.sourceFilter?.includes(y.id)):o,D=await Promise.all(p.map(async y=>{const n=w?.sources?.[y.id],S=y.include??i.include,m=y.exclude,c=et({include:S,exclude:m});if(e.offline){const x=await ce(l,y.id);return{id:y.id,repo:n?.repo??y.repo,ref:n?.ref??y.ref??i.ref,resolvedCommit:n?.resolvedCommit??"offline",lockCommit:n?.resolvedCommit??null,lockRulesSha256:n?.rulesSha256,status:n&&x?"up-to-date":"missing",bytes:n?.bytes,fileCount:n?.fileCount,manifestSha256:n?.manifestSha256,rulesSha256:c}}const g=await v({repo:y.repo,ref:y.ref,allowHosts:i.allowHosts,timeoutMs:e.timeoutMs}),d=n?.resolvedCommit===g.resolvedCommit&&n?.rulesSha256===c,a=n?d?"up-to-date":"changed":"missing";return{id:y.id,repo:g.repo,ref:g.ref,resolvedCommit:g.resolvedCommit,lockCommit:n?.resolvedCommit??null,lockRulesSha256:n?.rulesSha256,status:a,bytes:n?.bytes,fileCount:n?.fileCount,manifestSha256:n?.manifestSha256,rulesSha256:c}}));return{config:r,configPath:s,cacheDir:l,lockPath:f,lockExists:u,lockData:w,results:D,sources:p,defaults:i}},tt=async()=>{const e=h.resolve(process.cwd(),"package.json");try{const t=await j(e,"utf8"),r=JSON.parse(t.toString());return typeof r.version=="string"?r.version:"0.0.0"}catch{}try{const t=await j(new URL("../package.json",import.meta.url),"utf8"),r=JSON.parse(t.toString());return typeof r.version=="string"?r.version:"0.0.0"}catch{}try{const t=await j(new URL("../../package.json",import.meta.url),"utf8"),r=JSON.parse(t.toString());return typeof r.version=="string"?r.version:"0.0.0"}catch{return"0.0.0"}},rt=async(e,t)=>{const r=await tt(),s=new Date().toISOString(),o={...t?.sources??{}};for(const i of e.results){const l=o[i.id];o[i.id]={repo:i.repo,ref:i.ref,resolvedCommit:i.resolvedCommit,bytes:i.bytes??l?.bytes??0,fileCount:i.fileCount??l?.fileCount??0,manifestSha256:i.manifestSha256??l?.manifestSha256??i.resolvedCommit,rulesSha256:i.rulesSha256??l?.rulesSha256,updatedAt:s}}return{version:1,generatedAt:s,toolVersion:r,sources:o}},fe=async(e,t={})=>{const r=process.hrtime.bigint();let s=0;const o=await ue(e,t);await b(o.cacheDir,{recursive:!0});const i=o.lockData,l=o.results.filter(u=>{const w=o.sources.find(v=>v.id===u.id);return u.status==="missing"&&(w?.required??!0)});if(e.failOnMiss&&l.length>0)throw new Error(`Missing required source(s): ${l.map(u=>u.id).join(", ")}.`);if(!e.lockOnly){const u=o.defaults,w=t.fetchSource??Ue,v=t.materializeSource??We,p=async(n,S)=>{const m=n?.length?o.results.filter(c=>n.includes(c.id)):o.results;return(await Promise.all(m.map(async c=>{const g=o.sources.find(a=>a.id===c.id);if(!g)return null;const d=await ce(o.cacheDir,c.id);return S||c.status!=="up-to-date"||!d?{result:c,source:g}:null}))).filter(Boolean)},D=async()=>{await Promise.all(o.sources.map(async n=>{if(!n.targetDir)return;const S=z(o.configPath,n.targetDir);await I(S)||await J({sourceDir:h.join(o.cacheDir,n.id),targetDir:S,mode:n.targetMode??u.targetMode,explicitTargetMode:n.targetMode!==void 0})}))},y=async n=>{const S=e.concurrency??4;let m=0;const c=async()=>{const g=n[m];if(!g||!g.source)return;m+=1;const{result:d,source:a}=g,x=o.lockData?.sources?.[a.id];e.json||C.step("Fetching",a.id);const $=await w({sourceId:a.id,repo:a.repo,ref:a.ref,resolvedCommit:d.resolvedCommit,cacheDir:o.cacheDir,depth:a.depth??u.depth,include:a.include??u.include,timeoutMs:e.timeoutMs});try{const k=h.join(o.cacheDir,a.id,Y);if(d.status!=="up-to-date"&&x?.manifestSha256&&await I(k)){const P=await Je({sourceId:a.id,repoDir:$.repoDir,cacheDir:o.cacheDir,include:a.include??u.include,exclude:a.exclude,maxBytes:a.maxBytes??u.maxBytes,maxFiles:a.maxFiles??u.maxFiles});if(P.manifestSha256===x.manifestSha256){d.bytes=P.bytes,d.fileCount=P.fileCount,d.manifestSha256=P.manifestSha256,d.status="up-to-date",e.json||C.item(O.success,a.id,"no content changes"),await c();return}}const T=await v({sourceId:a.id,repoDir:$.repoDir,cacheDir:o.cacheDir,include:a.include??u.include,exclude:a.exclude,maxBytes:a.maxBytes??u.maxBytes,maxFiles:a.maxFiles??u.maxFiles});if(a.targetDir){const P=z(o.configPath,a.targetDir);await J({sourceDir:h.join(o.cacheDir,a.id),targetDir:P,mode:a.targetMode??u.targetMode,explicitTargetMode:a.targetMode!==void 0})}d.bytes=T.bytes,d.fileCount=T.fileCount,d.manifestSha256=T.manifestSha256,e.json||C.item(O.success,a.id,`synced ${T.fileCount} files`)}finally{await $.cleanup()}await c()};await Promise.all(Array.from({length:Math.min(S,n.length)},c))};if(e.offline)await D();else{const n=await p();await y(n),await D()}if(!e.offline){const n=(await Z({configPath:o.configPath,cacheDirOverride:o.cacheDir})).results.filter(S=>!S.ok);if(n.length>0){const S=await p(n.map(c=>c.id),!0);S.length>0&&(await y(S),await D());const m=(await Z({configPath:o.configPath,cacheDirOverride:o.cacheDir})).results.filter(c=>!c.ok);if(m.length>0&&(s+=1,!e.json)){const c=m.map(g=>`${g.id} (${g.issues.join("; ")})`).join(", ");C.line(`${O.warn} Verify failed for ${m.length} source(s): ${c}`)}}}}const f=await rt(o,i);if(await Pe(o.lockPath,f),!e.json){const u=Number(process.hrtime.bigint()-r)/1e6,w=o.results.reduce((p,D)=>p+(D.bytes??0),0),v=o.results.reduce((p,D)=>p+(D.fileCount??0),0);C.line(`${O.info} Completed in ${u.toFixed(0)}ms \xB7 ${Qe(w)} \xB7 ${v} files${s?` \xB7 ${s} warning${s===1?"":"s"}`:""}`)}return await Ze({cacheDir:o.cacheDir,configPath:o.configPath,lock:f,sources:o.sources,results:o.results}),o.lockExists=!0,o},me=e=>{const t={upToDate:e.results.filter(r=>r.status==="up-to-date").length,changed:e.results.filter(r=>r.status==="changed").length,missing:e.results.filter(r=>r.status==="missing").length};if(e.results.length===0){C.line(`${O.info} No sources to sync.`);return}C.line(`${O.info} ${e.results.length} sources (${t.upToDate} up-to-date, ${t.changed} changed, ${t.missing} missing)`);for(const r of e.results){const s=C.hash(r.resolvedCommit),o=C.hash(r.lockCommit),i=!!r.lockRulesSha256&&!!r.rulesSha256&&r.lockRulesSha256!==r.rulesSha256;if(r.status==="up-to-date"){C.item(O.success,r.id,`${E.dim("up-to-date")} ${E.gray(s)}`);continue}if(r.status==="changed"){if(r.lockCommit===r.resolvedCommit&&i){C.item(O.warn,r.id,`${E.dim("rules changed")} ${E.gray(s)}`);continue}C.item(O.warn,r.id,`${E.dim("changed")} ${E.gray(o)} ${E.dim("->")} ${E.gray(s)}`);continue}C.item(O.warn,r.id,`${E.dim("missing")} ${E.gray(s)}`)}},ot={__proto__:null,getSyncPlan:ue,printSyncPlan:me,runSync:fe};export{J as a,me as b,fe as c,re as e,oe as p,R as r,ot as s};
|
|
8
9
|
//# sourceMappingURL=sync.mjs.map
|
package/dist/chunks/verify.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{stat as v,access as k}from"node:fs/promises";import g from"node:path";import{a as _,r as C,u as l,s as m}from"../shared/docs-cache.
|
|
1
|
+
import{stat as v,access as k}from"node:fs/promises";import g from"node:path";import{a as _,r as C,u as l,s as m}from"../shared/docs-cache.D-Yt8qB9.mjs";import{l as E,b as j}from"../shared/docs-cache.CIYNztql.mjs";import{createReadStream as M}from"node:fs";import z from"node:readline";const d=".manifest.jsonl",A=async function*(s){const a=g.join(s,d),r=M(a,{encoding:"utf8"}),e=z.createInterface({input:r,crlfDelay:1/0});try{for await(const u of e){const f=u.trim();f&&(yield JSON.parse(f))}}finally{e.close(),r.destroy()}},p=async s=>{try{return await k(s),!0}catch{return!1}},w=async s=>{const{config:a,resolvedPath:r,sources:e}=await E(s.configPath),u=_(r,a.cacheDir??j,s.cacheDirOverride),f=async(i,o)=>{if(!await p(i))return{ok:!1,issues:[o==="source"?"missing source directory":"missing target directory"]};try{let t=0,n=0;for await(const h of A(i)){const y=g.join(i,h.path);if(!await p(y)){t+=1;continue}(await v(y)).size!==h.size&&(n+=1)}const c=[];return t>0&&c.push(o==="source"?`missing files: ${t}`:`target missing files: ${t}`),n>0&&c.push(o==="source"?`size mismatch: ${n}`:`target size mismatch: ${n}`),{ok:c.length===0,issues:c}}catch{return{ok:!1,issues:[o==="source"?"missing manifest":"missing target manifest"]}}},D=await Promise.all(e.map(async i=>{const o=g.join(u,i.id),t=[...(await f(o,"source")).issues];if(i.targetDir&&i.targetMode==="copy"){const n=C(r,i.targetDir),c=await f(n,"target");t.push(...c.issues)}return{id:i.id,ok:t.length===0,issues:t}}));return{cacheDir:u,results:D}},I=s=>{const a=s.results.filter(e=>e.ok).length,r=s.results.length-a;if(s.results.length===0){l.line(`${m.warn} No sources to verify.`);return}l.line(`${m.info} Verified ${s.results.length} sources (${a} ok, ${r} failed)`);for(const e of s.results)e.ok?l.item(m.success,e.id):l.item(m.warn,e.id,e.issues.join(", "))},N={__proto__:null,printVerify:I,verifyCache:w};export{d as M,N as a,w as v};
|
|
2
2
|
//# sourceMappingURL=verify.mjs.map
|
package/dist/cli.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import w from"node:path";import
|
|
1
|
+
import w from"node:path";import a from"node:process";import l from"picocolors";import{p as j,E as f,s as g,u as r}from"./shared/docs-cache.D-Yt8qB9.mjs";import"cac";const u="docs-cache",O=`
|
|
2
2
|
Usage: ${u} <command> [options]
|
|
3
3
|
|
|
4
4
|
Commands:
|
|
@@ -23,14 +23,14 @@ Global options:
|
|
|
23
23
|
--concurrency <n>
|
|
24
24
|
--json
|
|
25
25
|
--timeout-ms <n>
|
|
26
|
-
`,m=()=>{
|
|
27
|
-
`)},D=e=>{const t=e.findIndex(i=>!i.startsWith("-")),
|
|
28
|
-
`);else{for(const
|
|
29
|
-
`);else{if(i.removed.length>0&&
|
|
30
|
-
`):n(i);return}if(e==="clean"){const{cleanCache:
|
|
31
|
-
`):n.removed?
|
|
32
|
-
`):n.removed.length===0?
|
|
33
|
-
`):
|
|
34
|
-
`):
|
|
35
|
-
`):
|
|
26
|
+
`,m=()=>{a.stdout.write(O.trimStart())},p=e=>{a.stderr.write(`${g.error} ${e}
|
|
27
|
+
`)},D=e=>{const t=e.findIndex(i=>!i.startsWith("-")),h=t===-1?[]:e.slice(t+1),d=[];let s=-1;const n=new Set(["--config","--cache-dir","--concurrency","--timeout-ms"]);for(let i=0;i<h.length;i+=1){const o=h[i];if(o==="--source"){const c=h[i+1];if(!c||c.startsWith("-"))throw new Error("--source expects a value.");d.push({repo:c}),s=d.length-1,i+=1;continue}if(o==="--target"||o==="--target-dir"){const c=h[i+1];if(!c||c.startsWith("-"))throw new Error("--target expects a value.");if(s===-1)throw new Error("--target must follow a --source entry.");d[s].targetDir=c,i+=1;continue}if(n.has(o)){i+=1;continue}o.startsWith("--")||(d.push({repo:o}),s=d.length-1)}return d},S=async(e,t,h,d)=>{if(e==="add"){const{addSources:s}=await import("./chunks/add.mjs"),{runSync:n}=await import("./chunks/sync.mjs").then(function(c){return c.s}),i=D(d);if(i.length===0)throw new Error("Usage: docs-cache add [--source <repo> --target <dir>] <repo...>");const o=await s({configPath:t.config,entries:i});if(t.offline?t.json||r.line(`${g.warn} Offline: skipped sync`):await n({configPath:t.config,cacheDirOverride:t.cacheDir,json:t.json,lockOnly:t.lockOnly,offline:t.offline,failOnMiss:t.failOnMiss,sourceFilter:o.sources.map(c=>c.id),timeoutMs:t.timeoutMs}),t.json)a.stdout.write(`${JSON.stringify(o,null,2)}
|
|
28
|
+
`);else{for(const c of o.sources){const y=c.repo.replace(/^https?:\/\//,"").replace(/\.git$/,""),v=c.targetDir?` ${l.dim("->")} ${l.magenta(c.targetDir)}`:"";r.item(g.success,c.id,`${l.blue(y)}${v}`)}o.skipped?.length&&r.line(`${g.warn} Skipped ${o.skipped.length} existing source${o.skipped.length===1?"":"s"}: ${o.skipped.join(", ")}`),r.line(`${g.info} Updated ${l.gray(w.relative(a.cwd(),o.configPath)||"docs.config.json")}`),o.gitignoreUpdated&&o.gitignorePath&&r.line(`${g.info} Updated ${l.gray(r.path(o.gitignorePath))}`)}return}if(e==="remove"){const{removeSources:s}=await import("./chunks/remove.mjs"),{pruneCache:n}=await import("./chunks/prune.mjs");if(h.length===0)throw new Error("Usage: docs-cache remove <id...>");const i=await s({configPath:t.config,ids:h});if(t.json)a.stdout.write(`${JSON.stringify(i,null,2)}
|
|
29
|
+
`);else{if(i.removed.length>0&&r.line(`${g.success} Removed ${i.removed.length} source${i.removed.length===1?"":"s"}: ${i.removed.join(", ")}`),i.missing.length>0&&r.line(`${g.warn} Missing ${i.missing.length} source${i.missing.length===1?"":"s"}: ${i.missing.join(", ")}`),i.targetsRemoved.length>0){const o=i.targetsRemoved.map(c=>`${c.id} -> ${r.path(c.targetDir)}`).join(", ");r.line(`${g.success} Removed ${i.targetsRemoved.length} target${i.targetsRemoved.length===1?"":"s"}: ${o}`)}r.line(`${g.info} Updated ${l.gray(w.relative(a.cwd(),i.configPath)||"docs.config.json")}`)}t.prune&&await n({configPath:t.config,cacheDirOverride:t.cacheDir,json:t.json});return}if(e==="status"){const{getStatus:s,printStatus:n}=await import("./chunks/status.mjs"),i=await s({configPath:t.config,cacheDirOverride:t.cacheDir,json:t.json});t.json?a.stdout.write(`${JSON.stringify(i,null,2)}
|
|
30
|
+
`):n(i);return}if(e==="clean"){const{cleanCache:s}=await import("./chunks/clean.mjs"),n=await s({configPath:t.config,cacheDirOverride:t.cacheDir,json:t.json});t.json?a.stdout.write(`${JSON.stringify(n,null,2)}
|
|
31
|
+
`):n.removed?r.line(`${g.success} Removed cache at ${r.path(n.cacheDir)}`):r.line(`${g.info} Cache already missing at ${r.path(n.cacheDir)}`);return}if(e==="prune"){const{pruneCache:s}=await import("./chunks/prune.mjs"),n=await s({configPath:t.config,cacheDirOverride:t.cacheDir,json:t.json});t.json?a.stdout.write(`${JSON.stringify(n,null,2)}
|
|
32
|
+
`):n.removed.length===0?r.line(`${g.info} No cache entries to prune.`):r.line(`${g.success} Pruned ${n.removed.length} cache entr${n.removed.length===1?"y":"ies"}: ${n.removed.join(", ")}`);return}if(e==="sync"){const{printSyncPlan:s,runSync:n}=await import("./chunks/sync.mjs").then(function(o){return o.s}),i=await n({configPath:t.config,cacheDirOverride:t.cacheDir,json:t.json,lockOnly:t.lockOnly,offline:t.offline,failOnMiss:t.failOnMiss,timeoutMs:t.timeoutMs});t.json?a.stdout.write(`${JSON.stringify(i,null,2)}
|
|
33
|
+
`):s(i);return}if(e==="verify"){const{printVerify:s,verifyCache:n}=await import("./chunks/verify.mjs").then(function(o){return o.a}),i=await n({configPath:t.config,cacheDirOverride:t.cacheDir,json:t.json});t.json?a.stdout.write(`${JSON.stringify(i,null,2)}
|
|
34
|
+
`):s(i),i.results.some(o=>!o.ok)&&a.exit(f.FatalError);return}if(e==="init"){const{initConfig:s}=await import("./chunks/init.mjs");if(t.config)throw new Error("Init does not accept --config. Use the project root.");const n=await s({cacheDirOverride:t.cacheDir,json:t.json});t.json?a.stdout.write(`${JSON.stringify(n,null,2)}
|
|
35
|
+
`):(r.line(`${g.success} Wrote ${l.gray(r.path(n.configPath))}`),n.gitignoreUpdated&&n.gitignorePath&&r.line(`${g.info} Updated ${l.gray(r.path(n.gitignorePath))}`));return}r.line(`${u} ${e}: not implemented yet.`)};async function P(){try{a.on("uncaughtException",$),a.on("unhandledRejection",$);const e=j(),t=e.rawArgs;e.help&&(m(),a.exit(f.Success)),e.command||(m(),a.exit(f.InvalidArgument)),e.command!=="add"&&e.command!=="remove"&&e.positionals.length>0&&(p(`${u}: unexpected arguments.`),m(),a.exit(f.InvalidArgument)),e.command!=="add"&&e.options.targetDir&&(p(`${u}: --target-dir is only valid for add.`),m(),a.exit(f.InvalidArgument)),await S(e.command,e.options,e.positionals,e.rawArgs)}catch(e){$(e)}}function $(e){const t=e.message||String(e);p(t),a.exit(f.FatalError)}export{u as CLI_NAME,P as main};
|
|
36
36
|
//# sourceMappingURL=cli.mjs.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{writeFile as H,readFile as I,access as z}from"node:fs/promises";import h from"node:path";import{z as i}from"zod";import{r as T}from"./docs-cache.D-Yt8qB9.mjs";const v=i.enum(["symlink","copy"]),D=i.enum(["materialize"]),L=i.object({type:i.enum(["commit","manifest"]),value:i.string().nullable()}).strict(),U=i.object({ref:i.string().min(1),mode:D,include:i.array(i.string().min(1)).min(1),targetMode:v.optional(),depth:i.number().min(1),required:i.boolean(),maxBytes:i.number().min(1),maxFiles:i.number().min(1).optional(),allowHosts:i.array(i.string().min(1)).min(1),toc:i.boolean().optional()}).strict(),_=i.object({id:i.string().min(1),repo:i.string().min(1),targetDir:i.string().min(1).optional(),targetMode:v.optional(),ref:i.string().min(1).optional(),mode:D.optional(),depth:i.number().min(1).optional(),include:i.array(i.string().min(1)).optional(),exclude:i.array(i.string().min(1)).optional(),required:i.boolean().optional(),maxBytes:i.number().min(1).optional(),maxFiles:i.number().min(1).optional(),integrity:L.optional(),toc:i.boolean().optional()}).strict(),P=i.object({$schema:i.string().min(1).optional(),cacheDir:i.string().min(1).optional(),targetMode:v.optional(),defaults:U.partial().optional(),sources:i.array(_)}).strict(),J=/^[a-zA-Z0-9_-]+$/,R=new Set([".","..","CON","PRN","AUX","NUL","COM1","LPT1"]),F=(e,t)=>{if(typeof e!="string"||e.length===0)throw new Error(`${t} must be a non-empty string.`);if(e.length>200)throw new Error(`${t} exceeds maximum length of 200.`);if(!J.test(e))throw new Error(`${t} must contain only alphanumeric characters, hyphens, and underscores.`);if(R.has(e.toUpperCase()))throw new Error(`${t} uses reserved name '${e}'.`);return e},j="docs.config.json",x=".docs",A="package.json",G=process.platform==="win32"?"copy":"symlink",g={cacheDir:x,defaults:{ref:"HEAD",mode:"materialize",include:["**/*.{md,mdx,markdown,mkd,txt,rst,adoc,asciidoc}"],targetMode:G,depth:1,required:!0,maxBytes:2e8,allowHosts:["github.com","gitlab.com"],toc:!0},sources:[]},V=(e,t)=>!e||!t?e===t:e.length!==t.length?!1:e.every((r,o)=>r===t[o]),S=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),C=(e,t)=>{const r={};for(const[o,d]of Object.entries(e)){const a=t[o];if(Array.isArray(d)&&Array.isArray(a)){V(d,a)||(r[o]=d);continue}if(S(d)&&S(a)){const c=C(d,a);Object.keys(c).length>0&&(r[o]=c);continue}d!==a&&(r[o]=d)}return r},X=e=>{const t={...g,$schema:e.$schema,defaults:{...g.defaults,...e.targetMode?{targetMode:e.targetMode}:void 0}},r=C(e,t),o={$schema:r.$schema,cacheDir:r.cacheDir,targetMode:r.targetMode,defaults:r.defaults,sources:e.sources};return(!o.defaults||Object.keys(o.defaults).length===0)&&delete o.defaults,o},p=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),l=(e,t)=>{if(typeof e!="string"||e.length===0)throw new Error(`${t} must be a non-empty string.`);return e},y=(e,t)=>{if(typeof e!="boolean")throw new Error(`${t} must be a boolean.`);return e},Z=(e,t)=>{if(typeof e!="number"||Number.isNaN(e))throw new Error(`${t} must be a number.`);return e},f=(e,t)=>{const r=Z(e,t);if(r<1)throw new Error(`${t} must be greater than zero.`);return r},w=(e,t)=>{if(!Array.isArray(e)||e.length===0)throw new Error(`${t} must be a non-empty array of strings.`);for(const r of e)if(typeof r!="string"||r.length===0)throw new Error(`${t} must contain non-empty strings.`);return e},k=(e,t)=>{const r=l(e,t);if(r!=="symlink"&&r!=="copy")throw new Error(`${t} must be "symlink" or "copy".`);return r},q=(e,t)=>{if(e!=="materialize")throw new Error(`${t} must be "materialize".`);return e},K=(e,t)=>{if(!p(e))throw new Error(`${t} must be an object.`);const r=e.type;if(r!=="commit"&&r!=="manifest")throw new Error(`${t}.type must be "commit" or "manifest".`);const o=e.value;if(typeof o!="string"&&o!==null)throw new Error(`${t}.value must be a string or null.`);return{type:r,value:o}},B=e=>{if(!p(e))throw new Error("Config must be a JSON object.");const t=P.safeParse(e);if(!t.success){const s=t.error.issues.map(n=>`${n.path.join(".")||"config"} ${n.message}`).join("; ");throw new Error(`Config does not match schema: ${s}.`)}const r=e.cacheDir?l(e.cacheDir,"cacheDir"):x,o=e.defaults,d=e.targetMode!==void 0?k(e.targetMode,"targetMode"):void 0,a=g.defaults;let c=a;if(o!==void 0){if(!p(o))throw new Error("defaults must be an object.");c={ref:o.ref!==void 0?l(o.ref,"defaults.ref"):a.ref,mode:o.mode!==void 0?q(o.mode,"defaults.mode"):a.mode,include:o.include!==void 0?w(o.include,"defaults.include"):a.include,targetMode:o.targetMode!==void 0?k(o.targetMode,"defaults.targetMode"):d??a.targetMode,depth:o.depth!==void 0?f(o.depth,"defaults.depth"):a.depth,required:o.required!==void 0?y(o.required,"defaults.required"):a.required,maxBytes:o.maxBytes!==void 0?f(o.maxBytes,"defaults.maxBytes"):a.maxBytes,maxFiles:o.maxFiles!==void 0?f(o.maxFiles,"defaults.maxFiles"):a.maxFiles,allowHosts:o.allowHosts!==void 0?w(o.allowHosts,"defaults.allowHosts"):a.allowHosts,toc:o.toc!==void 0?y(o.toc,"defaults.toc"):a.toc}}else d!==void 0&&(c={...a,targetMode:d});if(!Array.isArray(e.sources))throw new Error("sources must be an array.");const m=e.sources.map((s,n)=>{if(!p(s))throw new Error(`sources[${n}] must be an object.`);const u={id:F(s.id,`sources[${n}].id`),repo:l(s.repo,`sources[${n}].repo`)};if(s.targetDir!==void 0&&(u.targetDir=l(s.targetDir,`sources[${n}].targetDir`)),s.targetMode!==void 0){const b=l(s.targetMode,`sources[${n}].targetMode`);if(b!=="symlink"&&b!=="copy")throw new Error(`sources[${n}].targetMode must be "symlink" or "copy".`);u.targetMode=b}return s.ref!==void 0&&(u.ref=l(s.ref,`sources[${n}].ref`)),s.mode!==void 0&&(u.mode=q(s.mode,`sources[${n}].mode`)),s.depth!==void 0&&(u.depth=f(s.depth,`sources[${n}].depth`)),s.include!==void 0&&(u.include=w(s.include,`sources[${n}].include`)),s.exclude!==void 0&&(u.exclude=w(s.exclude,`sources[${n}].exclude`)),s.required!==void 0&&(u.required=y(s.required,`sources[${n}].required`)),s.maxBytes!==void 0&&(u.maxBytes=f(s.maxBytes,`sources[${n}].maxBytes`)),s.maxFiles!==void 0&&(u.maxFiles=f(s.maxFiles,`sources[${n}].maxFiles`)),s.integrity!==void 0&&(u.integrity=K(s.integrity,`sources[${n}].integrity`)),s.toc!==void 0&&(u.toc=y(s.toc,`sources[${n}].toc`)),u}),M=new Set,$=[];for(const s of m)M.has(s.id)&&$.push(s.id),M.add(s.id);if($.length>0)throw new Error(`Duplicate source IDs found: ${$.join(", ")}. Each source must have a unique ID.`);return{cacheDir:r,targetMode:d,defaults:c,sources:m}},Q=e=>{const t=e.defaults??g.defaults;return e.sources.map(r=>({id:r.id,repo:r.repo,targetDir:r.targetDir,targetMode:r.targetMode??t.targetMode,ref:r.ref??t.ref,mode:r.mode??t.mode,depth:r.depth??t.depth,include:r.include??t.include,exclude:r.exclude,required:r.required??t.required,maxBytes:r.maxBytes??t.maxBytes,maxFiles:r.maxFiles??t.maxFiles,integrity:r.integrity,toc:r.toc??t.toc}))},N=e=>e?h.resolve(e):h.resolve(process.cwd(),j),W=()=>h.resolve(process.cwd(),A),O=async e=>{try{return await z(e),!0}catch{return!1}},E=async(e,t)=>{let r;try{r=await I(e,"utf8")}catch(c){const m=c instanceof Error?c.message:String(c);throw new Error(`Failed to read config at ${e}: ${m}`)}let o;try{o=JSON.parse(r)}catch(c){const m=c instanceof Error?c.message:String(c);throw new Error(`Invalid JSON in ${e}: ${m}`)}const d=t==="package"?o?.["docs-cache"]:o;if(t==="package"&&d===void 0)throw new Error(`Missing docs-cache config in ${e}.`);const a=B(d);for(const c of a.sources)c.targetDir&&T(e,c.targetDir);return{config:a,resolvedPath:e,sources:Q(a)}},Y=async(e,t)=>{const r=`${JSON.stringify(t,null,2)}
|
|
2
|
+
`;await H(e,r,"utf8")},ee=async e=>{const t=N(e),r=h.basename(t)===A;if(e)return E(t,r?"package":"config");if(await O(t))return E(t,"config");const o=W();if(await O(o))try{return await E(o,"package")}catch{}throw new Error(`No docs.config.json found at ${t} and no docs-cache config in ${o}.`)};export{g as D,F as a,x as b,j as c,ee as l,N as r,X as s,B as v,Y as w};
|
|
3
|
+
//# sourceMappingURL=docs-cache.CIYNztql.mjs.map
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{readFile as o,writeFile as f,access as P}from"node:fs/promises";import a from"node:path";import{t as p}from"./docs-cache.D-Yt8qB9.mjs";const g=async n=>{try{return await P(n),!0}catch{return!1}},l=n=>{const r=n.trim();if(!r||r.startsWith("#")||r.startsWith("!"))return"";let t=r.replace(/^\//,"");return t=t.replace(/^\.\//,""),t=t.replace(/\/+$/,""),p(t)},d=(n,r)=>{const t=a.isAbsolute(r)?a.resolve(r):a.resolve(n,r),e=a.relative(n,t);return e===".."||e.startsWith(`..${a.sep}`)||a.isAbsolute(e)?null:e.length===0?".":e},u=async(n,r)=>{const t=a.resolve(n,".gitignore"),e=d(n,r);if(!e)return{gitignorePath:t,entry:null,hasEntry:!1};const i=l(e);if(!i)return{gitignorePath:t,entry:null,hasEntry:!1};let s="";await g(t)&&(s=await o(t,"utf8"));const h=s.split(/\r?\n/),c=new Set(h.map(y=>l(y)).filter(Boolean));return{gitignorePath:t,entry:`${i}/`,hasEntry:c.has(i)}},w=async(n,r)=>{const t=await u(n,r);if(!t.entry)return{updated:!1,gitignorePath:t.gitignorePath,entry:null};if(t.hasEntry)return{updated:!1,gitignorePath:t.gitignorePath,entry:t.entry};let e="";await g(t.gitignorePath)&&(e=await o(t.gitignorePath,"utf8"));const i=e.length===0||e.endsWith(`
|
|
2
|
+
`)?"":`
|
|
3
|
+
`,s=`${e}${i}${t.entry}
|
|
4
|
+
`;return await f(t.gitignorePath,s,"utf8"),{updated:!0,gitignorePath:t.gitignorePath,entry:t.entry}};export{w as e,u as g};
|
|
5
|
+
//# sourceMappingURL=docs-cache.CLG_Tn1G.mjs.map
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import u from"node:process";import l from"cac";import i from"node:path";import s from"picocolors";var c=(o=>(o[o.Success=0]="Success",o[o.FatalError=1]="FatalError",o[o.InvalidArgument=9]="InvalidArgument",o))(c||{});const d=["add","remove","sync","status","clean","prune","verify","init"],m=(o=u.argv)=>{try{const r=l("docs-cache");r.option("--source <repo>","Source repo (add only)").option("--target <dir>","Target directory for source (add only)").option("--config <path>","Path to config file").option("--cache-dir <path>","Override cache directory").option("--offline","Disable network access").option("--fail-on-miss","Fail when required sources are missing").option("--lock-only","Update lock without materializing files").option("--prune","Prune cache on remove").option("--target-dir <path>","Target directory for add").option("--concurrency <n>","Concurrency limit").option("--json","Output JSON").option("--timeout-ms <n>","Network timeout in milliseconds").help();const e=r.parse(o,{run:!1}),t=e.args[0];if(t&&!d.includes(t))throw new Error(`Unknown command '${t}'.`);const n={config:e.options.config,cacheDir:e.options.cacheDir,offline:!!e.options.offline,failOnMiss:!!e.options.failOnMiss,lockOnly:!!e.options.lockOnly,prune:!!e.options.prune,targetDir:e.options.targetDir,concurrency:e.options.concurrency?Number(e.options.concurrency):void 0,json:!!e.options.json,timeoutMs:e.options.timeoutMs?Number(e.options.timeoutMs):void 0};if(n.concurrency!==void 0&&n.concurrency<1)throw new Error("--concurrency must be a positive number.");if(n.timeoutMs!==void 0&&n.timeoutMs<1)throw new Error("--timeout-ms must be a positive number.");const p=o.slice(2);return{command:t??null,options:n,positionals:e.args.slice(1),rawArgs:p,help:!!e.options.help}}catch(r){const e=r instanceof Error?r.message:String(r);console.error(e),u.exit(c.InvalidArgument)}},g="TOC.md",a=o=>o.replace(/\\/g,"/"),h=(o,r)=>{const e=i.dirname(i.resolve(o)),t=i.resolve(e,r),n=i.relative(e,t);if(n===".."||n.startsWith(`..${i.sep}`)||i.isAbsolute(n))throw new Error(`targetDir '${r}' escapes project directory. Must be within ${e}.`);if(a(n).split("/").filter(Boolean).includes(".git"))throw new Error("targetDir cannot be within .git directory.");return t},f=(o,r,e)=>{if(e)return i.resolve(e);const t=i.dirname(o);return i.resolve(t,r)},y=(o,r)=>{i.join(o,"repos");const e=i.join(o,r);return{cacheDir:o,sourceDir:e}},w={error:s.red("\u2716"),success:s.green("\u2714"),info:s.blue("\u2139"),warn:s.yellow("\u26A0")},v={path:o=>{const r=i.relative(process.cwd(),o),e=r.length<o.length?r:o;return a(e)},hash:o=>o?o.slice(0,7):"-",pad:(o,r)=>o.padEnd(r),line:(o="")=>process.stdout.write(`${o}
|
|
2
|
+
`),header:(o,r)=>{process.stdout.write(`${s.blue("\u2139")} ${o.padEnd(10)} ${r}
|
|
3
|
+
`)},item:(o,r,e)=>{const t=s.bold(r),n=e?s.gray(e):"";process.stdout.write(` ${o} ${t} ${n}
|
|
4
|
+
`)},step:(o,r,e)=>{const t=s.cyan("\u2192");process.stdout.write(` ${t} ${o} ${s.bold(r)}${e?` ${s.dim(e)}`:""}
|
|
5
|
+
`)}};export{g as D,c as E,f as a,y as g,m as p,h as r,w as s,a as t,v as u};
|
|
6
|
+
//# sourceMappingURL=docs-cache.D-Yt8qB9.mjs.map
|
package/package.json
CHANGED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{writeFile as I,readFile as z,access as T}from"node:fs/promises";import h from"node:path";import{z as o}from"zod";import{r as L}from"./docs-cache.D9_kM5zq.mjs";const $=o.enum(["symlink","copy"]),F=o.enum(["materialize"]),U=o.object({type:o.enum(["commit","manifest"]),value:o.string().nullable()}).strict(),_=o.object({ref:o.string().min(1),mode:F,include:o.array(o.string().min(1)).min(1),targetMode:$.optional(),depth:o.number().min(1),required:o.boolean(),maxBytes:o.number().min(1),maxFiles:o.number().min(1).optional(),allowHosts:o.array(o.string().min(1)).min(1)}).strict(),P=o.object({id:o.string().min(1),repo:o.string().min(1),targetDir:o.string().min(1).optional(),targetMode:$.optional(),ref:o.string().min(1).optional(),mode:F.optional(),depth:o.number().min(1).optional(),include:o.array(o.string().min(1)).optional(),exclude:o.array(o.string().min(1)).optional(),required:o.boolean().optional(),maxBytes:o.number().min(1).optional(),maxFiles:o.number().min(1).optional(),integrity:U.optional()}).strict(),J=o.object({$schema:o.string().min(1).optional(),cacheDir:o.string().min(1).optional(),targetMode:$.optional(),index:o.boolean().optional(),defaults:_.partial().optional(),sources:o.array(P)}).strict(),R=/^[a-zA-Z0-9_-]+$/,G=new Set([".","..","CON","PRN","AUX","NUL","COM1","LPT1"]),A=(e,r)=>{if(typeof e!="string"||e.length===0)throw new Error(`${r} must be a non-empty string.`);if(e.length>200)throw new Error(`${r} exceeds maximum length of 200.`);if(!R.test(e))throw new Error(`${r} must contain only alphanumeric characters, hyphens, and underscores.`);if(G.has(e.toUpperCase()))throw new Error(`${r} uses reserved name '${e}'.`);return e},j="docs.config.json",b=".docs",S="package.json",V=process.platform==="win32"?"copy":"symlink",f={cacheDir:b,index:!1,defaults:{ref:"HEAD",mode:"materialize",include:["**/*.{md,mdx,markdown,mkd,txt,rst,adoc,asciidoc}"],targetMode:V,depth:1,required:!0,maxBytes:2e8,allowHosts:["github.com","gitlab.com"]},sources:[]},X=(e,r)=>!e||!r?e===r:e.length!==r.length?!1:e.every((t,n)=>t===r[n]),C=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),k=(e,r)=>{const t={};for(const[n,s]of Object.entries(e)){const d=r[n];if(Array.isArray(s)&&Array.isArray(d)){X(s,d)||(t[n]=s);continue}if(C(s)&&C(d)){const a=k(s,d);Object.keys(a).length>0&&(t[n]=a);continue}s!==d&&(t[n]=s)}return t},Z=e=>{const r={...f,$schema:e.$schema,defaults:{...f.defaults,...e.targetMode?{targetMode:e.targetMode}:void 0}},t=k(e,r),n={$schema:t.$schema,cacheDir:t.cacheDir,index:t.index,targetMode:t.targetMode,defaults:t.defaults,sources:e.sources};return(!n.defaults||Object.keys(n.defaults).length===0)&&delete n.defaults,n},p=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),m=(e,r)=>{if(typeof e!="string"||e.length===0)throw new Error(`${r} must be a non-empty string.`);return e},v=(e,r)=>{if(typeof e!="boolean")throw new Error(`${r} must be a boolean.`);return e},K=(e,r)=>{if(typeof e!="number"||Number.isNaN(e))throw new Error(`${r} must be a number.`);return e},g=(e,r)=>{const t=K(e,r);if(t<1)throw new Error(`${r} must be greater than zero.`);return t},y=(e,r)=>{if(!Array.isArray(e)||e.length===0)throw new Error(`${r} must be a non-empty array of strings.`);for(const t of e)if(typeof t!="string"||t.length===0)throw new Error(`${r} must contain non-empty strings.`);return e},q=(e,r)=>{const t=m(e,r);if(t!=="symlink"&&t!=="copy")throw new Error(`${r} must be "symlink" or "copy".`);return t},B=(e,r)=>{if(e!=="materialize")throw new Error(`${r} must be "materialize".`);return e},Q=(e,r)=>{if(!p(e))throw new Error(`${r} must be an object.`);const t=e.type;if(t!=="commit"&&t!=="manifest")throw new Error(`${r}.type must be "commit" or "manifest".`);const n=e.value;if(typeof n!="string"&&n!==null)throw new Error(`${r}.value must be a string or null.`);return{type:t,value:n}},N=e=>{if(!p(e))throw new Error("Config must be a JSON object.");const r=J.safeParse(e);if(!r.success){const i=r.error.issues.map(c=>`${c.path.join(".")||"config"} ${c.message}`).join("; ");throw new Error(`Config does not match schema: ${i}.`)}const t=e.cacheDir?m(e.cacheDir,"cacheDir"):b,n=e.index!==void 0?v(e.index,"index"):f.index??!1,s=e.defaults,d=e.targetMode!==void 0?q(e.targetMode,"targetMode"):void 0,a=f.defaults;let l=a;if(s!==void 0){if(!p(s))throw new Error("defaults must be an object.");l={ref:s.ref!==void 0?m(s.ref,"defaults.ref"):a.ref,mode:s.mode!==void 0?B(s.mode,"defaults.mode"):a.mode,include:s.include!==void 0?y(s.include,"defaults.include"):a.include,targetMode:s.targetMode!==void 0?q(s.targetMode,"defaults.targetMode"):d??a.targetMode,depth:s.depth!==void 0?g(s.depth,"defaults.depth"):a.depth,required:s.required!==void 0?v(s.required,"defaults.required"):a.required,maxBytes:s.maxBytes!==void 0?g(s.maxBytes,"defaults.maxBytes"):a.maxBytes,maxFiles:s.maxFiles!==void 0?g(s.maxFiles,"defaults.maxFiles"):a.maxFiles,allowHosts:s.allowHosts!==void 0?y(s.allowHosts,"defaults.allowHosts"):a.allowHosts}}else d!==void 0&&(l={...a,targetMode:d});if(!Array.isArray(e.sources))throw new Error("sources must be an array.");const M=e.sources.map((i,c)=>{if(!p(i))throw new Error(`sources[${c}] must be an object.`);const u={id:A(i.id,`sources[${c}].id`),repo:m(i.repo,`sources[${c}].repo`)};if(i.targetDir!==void 0&&(u.targetDir=m(i.targetDir,`sources[${c}].targetDir`)),i.targetMode!==void 0){const x=m(i.targetMode,`sources[${c}].targetMode`);if(x!=="symlink"&&x!=="copy")throw new Error(`sources[${c}].targetMode must be "symlink" or "copy".`);u.targetMode=x}return i.ref!==void 0&&(u.ref=m(i.ref,`sources[${c}].ref`)),i.mode!==void 0&&(u.mode=B(i.mode,`sources[${c}].mode`)),i.depth!==void 0&&(u.depth=g(i.depth,`sources[${c}].depth`)),i.include!==void 0&&(u.include=y(i.include,`sources[${c}].include`)),i.exclude!==void 0&&(u.exclude=y(i.exclude,`sources[${c}].exclude`)),i.required!==void 0&&(u.required=v(i.required,`sources[${c}].required`)),i.maxBytes!==void 0&&(u.maxBytes=g(i.maxBytes,`sources[${c}].maxBytes`)),i.maxFiles!==void 0&&(u.maxFiles=g(i.maxFiles,`sources[${c}].maxFiles`)),i.integrity!==void 0&&(u.integrity=Q(i.integrity,`sources[${c}].integrity`)),u}),D=new Set,w=[];for(const i of M)D.has(i.id)&&w.push(i.id),D.add(i.id);if(w.length>0)throw new Error(`Duplicate source IDs found: ${w.join(", ")}. Each source must have a unique ID.`);return{cacheDir:t,targetMode:d,index:n,defaults:l,sources:M}},W=e=>{const r=e.defaults??f.defaults;return e.sources.map(t=>({id:t.id,repo:t.repo,targetDir:t.targetDir,targetMode:t.targetMode??r.targetMode,ref:t.ref??r.ref,mode:t.mode??r.mode,depth:t.depth??r.depth,include:t.include??r.include,exclude:t.exclude,required:t.required??r.required,maxBytes:t.maxBytes??r.maxBytes,maxFiles:t.maxFiles??r.maxFiles,integrity:t.integrity}))},O=e=>e?h.resolve(e):h.resolve(process.cwd(),j),Y=()=>h.resolve(process.cwd(),S),H=async e=>{try{return await T(e),!0}catch{return!1}},E=async(e,r)=>{let t;try{t=await z(e,"utf8")}catch(a){const l=a instanceof Error?a.message:String(a);throw new Error(`Failed to read config at ${e}: ${l}`)}let n;try{n=JSON.parse(t)}catch(a){const l=a instanceof Error?a.message:String(a);throw new Error(`Invalid JSON in ${e}: ${l}`)}const s=r==="package"?n?.["docs-cache"]:n;if(r==="package"&&s===void 0)throw new Error(`Missing docs-cache config in ${e}.`);const d=N(s);for(const a of d.sources)a.targetDir&&L(e,a.targetDir);return{config:d,resolvedPath:e,sources:W(d)}},ee=async(e,r)=>{const t=`${JSON.stringify(r,null,2)}
|
|
2
|
-
`;await I(e,t,"utf8")},re=async e=>{const r=O(e),t=h.basename(r)===S;if(e)return E(r,t?"package":"config");if(await H(r))return E(r,"config");const n=Y();if(await H(n))try{return await E(n,"package")}catch{}throw new Error(`No docs.config.json found at ${r} and no docs-cache config in ${n}.`)};export{f as D,A as a,b,j as c,re as l,O as r,Z as s,N as v,ee as w};
|
|
3
|
-
//# sourceMappingURL=docs-cache.D4Fth4X8.mjs.map
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import u from"node:process";import d from"cac";import n from"node:path";import s from"picocolors";var c=(o=>(o[o.Success=0]="Success",o[o.FatalError=1]="FatalError",o[o.InvalidArgument=9]="InvalidArgument",o))(c||{});const m=["add","remove","sync","status","clean","prune","verify","init"],h=(o=u.argv)=>{try{const r=d("docs-cache");r.option("--source <repo>","Source repo (add only)").option("--target <dir>","Target directory for source (add only)").option("--config <path>","Path to config file").option("--cache-dir <path>","Override cache directory").option("--offline","Disable network access").option("--fail-on-miss","Fail when required sources are missing").option("--lock-only","Update lock without materializing files").option("--prune","Prune cache on remove").option("--target-dir <path>","Target directory for add").option("--concurrency <n>","Concurrency limit").option("--json","Output JSON").option("--timeout-ms <n>","Network timeout in milliseconds").help();const e=r.parse(o,{run:!1}),t=e.args[0];if(t&&!m.includes(t))throw new Error(`Unknown command '${t}'.`);const i={config:e.options.config,cacheDir:e.options.cacheDir,offline:!!e.options.offline,failOnMiss:!!e.options.failOnMiss,lockOnly:!!e.options.lockOnly,prune:!!e.options.prune,targetDir:e.options.targetDir,concurrency:e.options.concurrency?Number(e.options.concurrency):void 0,json:!!e.options.json,timeoutMs:e.options.timeoutMs?Number(e.options.timeoutMs):void 0};if(i.concurrency!==void 0&&i.concurrency<1)throw new Error("--concurrency must be a positive number.");if(i.timeoutMs!==void 0&&i.timeoutMs<1)throw new Error("--timeout-ms must be a positive number.");const l=o.slice(2);return{command:t??null,options:i,positionals:e.args.slice(1),rawArgs:l,help:!!e.options.help}}catch(r){const e=r instanceof Error?r.message:String(r);console.error(e),u.exit(c.InvalidArgument)}},p="index.json",a=o=>o.replace(/\\/g,"/"),g=(o,r)=>{const e=n.dirname(n.resolve(o)),t=n.resolve(e,r),i=n.relative(e,t);if(i===".."||i.startsWith(`..${n.sep}`)||n.isAbsolute(i))throw new Error(`targetDir '${r}' escapes project directory. Must be within ${e}.`);if(a(i).split("/").filter(Boolean).includes(".git"))throw new Error("targetDir cannot be within .git directory.");return t},f=(o,r,e)=>{if(e)return n.resolve(e);const t=n.dirname(o);return n.resolve(t,r)},y=(o,r)=>{n.join(o,"repos");const e=n.join(o,r),t=n.join(o,p);return{cacheDir:o,sourceDir:e,indexPath:t}},w={error:s.red("\u2716"),success:s.green("\u2714"),info:s.blue("\u2139"),warn:s.yellow("\u26A0")},v={path:o=>{const r=n.relative(process.cwd(),o),e=r.length<o.length?r:o;return a(e)},hash:o=>o?o.slice(0,7):"-",pad:(o,r)=>o.padEnd(r),line:(o="")=>process.stdout.write(`${o}
|
|
2
|
-
`),header:(o,r)=>{process.stdout.write(`${s.blue("\u2139")} ${o.padEnd(10)} ${r}
|
|
3
|
-
`)},item:(o,r,e)=>{const t=s.bold(r),i=e?s.gray(e):"";process.stdout.write(` ${o} ${t} ${i}
|
|
4
|
-
`)},step:(o,r,e)=>{const t=s.cyan("\u2192");process.stdout.write(` ${t} ${o} ${s.bold(r)}${e?` ${s.dim(e)}`:""}
|
|
5
|
-
`)}};export{p as D,c as E,f as a,y as g,h as p,g as r,w as s,a as t,v as u};
|
|
6
|
-
//# sourceMappingURL=docs-cache.D9_kM5zq.mjs.map
|