docs-cache 0.2.0 → 0.3.1
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 +56 -38
- package/dist/chunks/add.mjs +1 -1
- package/dist/chunks/clean-git-cache.mjs +2 -0
- package/dist/chunks/clean.mjs +1 -1
- package/dist/chunks/init.mjs +1 -1
- package/dist/chunks/prune.mjs +1 -1
- package/dist/chunks/remove.mjs +1 -1
- package/dist/chunks/status.mjs +1 -1
- package/dist/chunks/sync.mjs +8 -8
- package/dist/chunks/verify.mjs +1 -1
- package/dist/cli.mjs +22 -19
- package/dist/shared/docs-cache.BWEcxcrg.mjs +3 -0
- package/dist/shared/{docs-cache.CLG_Tn1G.mjs → docs-cache.C96VehGu.mjs} +2 -2
- package/dist/shared/docs-cache.DDgb7yxQ.mjs +6 -0
- package/dist/shared/docs-cache.kK1DPQIQ.mjs +2 -0
- package/package.json +1 -1
- package/dist/shared/docs-cache.CIYNztql.mjs +0 -3
- package/dist/shared/docs-cache.D-Yt8qB9.mjs +0 -6
package/README.md
CHANGED
|
@@ -19,7 +19,7 @@ Documentation is cached in a gitignored location, exposed to agent and tool targ
|
|
|
19
19
|
- **Fast**: Local cache avoids network roundtrips after sync.
|
|
20
20
|
- **Flexible**: Cache full repos or just the subdirectories you need.
|
|
21
21
|
|
|
22
|
-
> **Note**: Sources are downloaded to a local cache. If you provide a `targetDir`, `docs-cache` creates a symlink or copy from the cache to that target directory.
|
|
22
|
+
> **Note**: Sources are downloaded to a local cache. If you provide a `targetDir`, `docs-cache` creates a symlink or copy from the cache to that target directory.
|
|
23
23
|
|
|
24
24
|
## Usage
|
|
25
25
|
|
|
@@ -73,42 +73,60 @@ npx docs-cache clean
|
|
|
73
73
|
|
|
74
74
|
### Options
|
|
75
75
|
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
|
79
|
-
|
|
|
80
|
-
| `
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
- `
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
76
|
+
**Top-level**
|
|
77
|
+
|
|
78
|
+
| Field | Details | Required |
|
|
79
|
+
| ---------- | -------------------------------------- | -------- |
|
|
80
|
+
| `cacheDir` | Directory for cache. Default: `.docs`. | Optional |
|
|
81
|
+
| `sources` | List of repositories to sync. | Required |
|
|
82
|
+
| `defaults` | Default settings for all sources. | Optional |
|
|
83
|
+
|
|
84
|
+
<details>
|
|
85
|
+
<summary>Show default and source options</summary>
|
|
86
|
+
|
|
87
|
+
### Default options
|
|
88
|
+
|
|
89
|
+
All fields in `defaults` apply to all sources unless overridden per-source.
|
|
90
|
+
|
|
91
|
+
| Field | Details |
|
|
92
|
+
| ------------ | --------------------------------------------------------------------------------------------------------- |
|
|
93
|
+
| `ref` | Branch, tag, or commit. Default: `"HEAD"`. |
|
|
94
|
+
| `mode` | Cache mode. Default: `"materialize"`. |
|
|
95
|
+
| `include` | Glob patterns to copy. Default: `["**/*.{md,mdx,markdown,mkd,txt,rst,adoc,asciidoc}"]`. |
|
|
96
|
+
| `targetMode` | How to link or copy from the cache to the destination. Default: `"symlink"` on Unix, `"copy"` on Windows. |
|
|
97
|
+
| `depth` | Git clone depth. Default: `1`. |
|
|
98
|
+
| `required` | Whether missing sources should fail. Default: `true`. |
|
|
99
|
+
| `maxBytes` | Maximum total bytes to materialize. Default: `200000000` (200 MB). |
|
|
100
|
+
| `maxFiles` | Maximum total files to materialize. |
|
|
101
|
+
| `allowHosts` | Allowed Git hosts. Default: `["github.com", "gitlab.com"]`. |
|
|
102
|
+
| `toc` | Generate per-source `TOC.md`. Default: `true`. Supports `true`, `false`, or a format (`"tree"`, `"compressed"`). |
|
|
103
|
+
|
|
104
|
+
### Source options
|
|
105
|
+
|
|
106
|
+
#### Required
|
|
107
|
+
|
|
108
|
+
| Field | Details |
|
|
109
|
+
| ------ | --------------------------------- |
|
|
110
|
+
| `repo` | Git URL. |
|
|
111
|
+
| `id` | Unique identifier for the source. |
|
|
112
|
+
|
|
113
|
+
#### Optional
|
|
114
|
+
|
|
115
|
+
| Field | Details |
|
|
116
|
+
| ------------ | ---------------------------------------------------------------- |
|
|
117
|
+
| `ref` | Branch, tag, or commit. |
|
|
118
|
+
| `include` | Glob patterns to copy. |
|
|
119
|
+
| `exclude` | Glob patterns to skip. |
|
|
120
|
+
| `targetDir` | Path where files should be symlinked/copied to, outside `.docs`. |
|
|
121
|
+
| `targetMode` | How to link or copy from the cache to the destination. |
|
|
122
|
+
| `required` | Whether missing sources should fail. |
|
|
123
|
+
| `maxBytes` | Maximum total bytes to materialize. |
|
|
124
|
+
| `maxFiles` | Maximum total files to materialize. |
|
|
125
|
+
| `toc` | Generate per-source `TOC.md`. Supports `true`, `false`, or a format (`"tree"`, `"compressed"`). |
|
|
126
|
+
|
|
127
|
+
> **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`. Git operation timeout is configured via the `--timeout-ms` CLI flag, not as a per-source configuration option.
|
|
128
|
+
|
|
129
|
+
</details>
|
|
112
130
|
|
|
113
131
|
## NPM Integration
|
|
114
132
|
|
|
@@ -117,7 +135,7 @@ Use `postinstall` to ensure documentation is available locally immediately after
|
|
|
117
135
|
```json
|
|
118
136
|
{
|
|
119
137
|
"scripts": {
|
|
120
|
-
"postinstall": "npx docs-cache sync"
|
|
138
|
+
"postinstall": "npx docs-cache sync --prune"
|
|
121
139
|
}
|
|
122
140
|
}
|
|
123
141
|
```
|
package/dist/chunks/add.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
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.
|
|
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.BWEcxcrg.mjs";import{e as N}from"../shared/docs-cache.C96VehGu.mjs";import{r as O}from"../shared/docs-cache.DDgb7yxQ.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
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
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{rm as n,readdir as o,stat as m}from"node:fs/promises";import u from"node:path";import{r as f,e as w}from"../shared/docs-cache.kK1DPQIQ.mjs";import"node:os";const c=async t=>{try{const e=await o(t,{withFileTypes:!0});let r=0;for(const a of e){const i=u.join(t,a.name);if(a.isDirectory())r+=await c(i);else{const s=await m(i);r+=s.size}}return r}catch{return 0}},h=async t=>{try{return(await o(t)).length}catch{return 0}},p=async()=>{const t=f();if(!await w(t))return{removed:!1,cacheDir:t};const e=await h(t),r=await c(t);return await n(t,{recursive:!0,force:!0}),{removed:!0,cacheDir:t,repoCount:e,bytesFreed:r}};export{p as cleanGitCache};
|
|
2
|
+
//# sourceMappingURL=clean-git-cache.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.BWEcxcrg.mjs";import{b as n}from"../shared/docs-cache.DDgb7yxQ.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 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.
|
|
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.BWEcxcrg.mjs";import{g as H,e as k}from"../shared/docs-cache.C96VehGu.mjs";import"zod";import"../shared/docs-cache.DDgb7yxQ.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
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.BWEcxcrg.mjs";import{b as v}from"../shared/docs-cache.DDgb7yxQ.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 F,w as I,r as P}from"../shared/docs-cache.
|
|
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.BWEcxcrg.mjs";import{r as O}from"../shared/docs-cache.DDgb7yxQ.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
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,
|
|
1
|
+
import{access as E}from"node:fs/promises";import a from"picocolors";import{u as o,a as u,b as w,g as D}from"../shared/docs-cache.DDgb7yxQ.mjs";import{l as v,b as x}from"../shared/docs-cache.BWEcxcrg.mjs";import{resolveLockPath as C,readLock as P}from"../lock.mjs";import"node:process";import"cac";import"node:path";import"zod";const h=async r=>{try{return await E(r),!0}catch{return!1}},L=async r=>{const{config:i,resolvedPath:t,sources:n}=await v(r.configPath),s=w(t,i.cacheDir??x,r.cacheDirOverride),l=await h(s),c=C(t),e=await h(c);let d=!1,f=null;if(e)try{f=await P(c),d=!0}catch{d=!1}const g=await Promise.all(n.map(async m=>{const p=D(s,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:s,cacheDirExists:l,lockPath:c,lockExists:e,lockValid:d,sources:g}},b=r=>{const i=o.path(r.cacheDir),t=r.cacheDirExists?a.green("present"):a.red("missing"),n=r.lockExists?r.lockValid?a.green("valid"):a.red("invalid"):a.yellow("missing");if(o.header("Cache",`${i} (${t})`),o.header("Lock",`docs.lock (${n})`),r.sources.length===0){o.line(),o.line(`${u.warn} No sources configured.`);return}o.line();for(const s of r.sources){const l=s.docsExists?u.success:u.error,c=s.lockEntry?a.green("locked"):a.yellow("new"),e=o.hash(s.lockEntry?.resolvedCommit);o.item(l,s.id.padEnd(20),`${c.padEnd(10)} ${e}`)}};export{L as getStatus,b as printStatus};
|
|
2
2
|
//# sourceMappingURL=status.mjs.map
|
package/dist/chunks/sync.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{createHash as
|
|
2
|
-
`).filter(Boolean);return
|
|
3
|
-
|
|
4
|
-
`)}throw
|
|
5
|
-
`;o.update(
|
|
6
|
-
`)}await
|
|
7
|
-
`)},
|
|
8
|
-
`))if(o.trim()){const i=JSON.parse(o);i.path&&s.push(i.path)}return s}catch{return[]}},
|
|
1
|
+
import{createHash as A,randomBytes as ve}from"node:crypto";import{mkdtemp as B,rm as O,mkdir as R,readFile as j,writeFile as V,access as N,rename as U,open as z,lstat as De,symlink as $e,cp as Ce}from"node:fs/promises";import w from"node:path";import x from"picocolors";import{g as Pe,t as Y,r as G,D as xe,u as C,a as M,b as Me}from"../shared/docs-cache.DDgb7yxQ.mjs";import{a as W,l as Ee,D as Te,b as Oe}from"../shared/docs-cache.BWEcxcrg.mjs";import{execFile as Q}from"node:child_process";import ke,{tmpdir as Z}from"node:os";import{pathToFileURL as Fe}from"node:url";import{promisify as ee}from"node:util";import{e as be,r as te}from"../shared/docs-cache.kK1DPQIQ.mjs";import{writeLock as Re,resolveLockPath as Ie,readLock as je}from"../lock.mjs";import{M as J,v as re}from"./verify.mjs";import{createWriteStream as oe,createReadStream as _e,constants as se}from"node:fs";import{pipeline as Le}from"node:stream/promises";import ie from"fast-glob";const Ae=/^(https?:\/\/)([^@]+)@/i,_=e=>e.replace(Ae,"$1***@"),Ne=ee(Q),He=3e4,Be=new Set(["file:","ftp:","data:","javascript:"]),Ue=e=>{try{const r=new URL(e);if(Be.has(r.protocol))throw new Error(`Blocked protocol '${r.protocol}' in repo URL '${_(e)}'.`)}catch(r){if(r instanceof TypeError)return;throw r}},ze=e=>{if(Ue(e),e.startsWith("git@")){const r=e.indexOf("@"),t=e.indexOf(":",r+1);return t===-1?null:e.slice(r+1,t)||null}try{const r=new URL(e);return r.protocol!=="https:"&&r.protocol!=="ssh:"?null:r.hostname||null}catch{return null}},ae=(e,r)=>{const t=ze(e);if(!t)throw new Error(`Unsupported repo URL '${_(e)}'. Use HTTPS or SSH.`);const s=t.toLowerCase();if(!r.map(o=>o.toLowerCase()).includes(s))throw new Error(`Host '${t}' is not in allowHosts for '${_(e)}'.`)},ne=e=>{const r=e.trim().split(`
|
|
2
|
+
`).filter(Boolean);return r.length===0?null:r[0].split(/\s+/)[0]||null},Ye=async e=>{ae(e.repo,e.allowHosts);const{stdout:r}=await Ne("git",["ls-remote",e.repo,e.ref],{timeout:e.timeoutMs??He,maxBuffer:1024*1024}),t=ne(r);if(!t)throw new Error(`Unable to resolve ref '${e.ref}' for ${_(e.repo)}.`);return{repo:e.repo,ref:e.ref,resolvedCommit:t}},ce=ee(Q),le=12e4,Ge=3,We=100,T=async(e,r)=>{const t=["-c","core.hooksPath=/dev/null","-c","submodule.recurse=false","-c","protocol.ext.allow=never"];r?.allowFileProtocol?t.push("-c","protocol.file.allow=always"):t.push("-c","protocol.file.allow=never"),await ce("git",[...t,...e],{cwd:r?.cwd,timeout:r?.timeoutMs??le,maxBuffer:10*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"}}})},k=async(e,r=Ge)=>{for(let t=0;t<=r;t+=1)try{await O(e,{recursive:!0,force:!0});return}catch(s){const o=s.code;if(o!=="ENOTEMPTY"&&o!=="EBUSY"&&o!=="EPERM"||t===r)throw s;await new Promise(i=>setTimeout(i,We*(t+1)))}},Je=e=>A("sha256").update(e).digest("hex").substring(0,16),Xe=e=>{const r=Je(e);return w.join(te(),r)},qe=async e=>{try{return await T(["rev-parse","--git-dir"],{cwd:e}),!0}catch{return!1}},ue=async e=>{try{const r=w.join(e,".git","config"),t=(await j(r,"utf8")).toLowerCase();return t.includes("partialclone")||t.includes("promisor")||t.includes("partialclonefilter")}catch{return!1}},Ke=async(e,r,t,s)=>{const o=w.join(t,"archive.tar");await T(["archive","--remote",e,"--format=tar","--output",o,r],{timeoutMs:s}),await ce("tar",["-xf",o,"-C",t],{timeout:s??le,maxBuffer:1024*1024}),await O(o,{force:!0})},fe=e=>{if(!e||e.length===0)return!1;for(const r of e)if(!r||r.includes("**"))return!1;return!0},me=e=>{if(!e)return[];const r=e.map(t=>{const s=t.replace(/\\/g,"/"),o=s.indexOf("*");return(o===-1?s:s.slice(0,o)).replace(/\/+$|\/$/,"")});return Array.from(new Set(r.filter(t=>t.length>0)))},X=async(e,r)=>{const t=/^[0-9a-f]{7,40}$/i.test(e.ref),s=fe(e.include),o=["clone","--no-checkout","--depth",String(e.depth),"--recurse-submodules=no","--no-tags"];if(s&&o.push("--sparse"),t||(o.push("--single-branch"),e.ref!=="HEAD"&&o.push("--branch",e.ref)),o.push(e.repo,r),await T(o,{timeoutMs:e.timeoutMs}),s){const i=me(e.include);i.length>0&&await T(["-C",r,"sparse-checkout","set",...i],{timeoutMs:e.timeoutMs})}await T(["-C",r,"checkout","--quiet","--detach",e.resolvedCommit],{timeoutMs:e.timeoutMs})},Ve=async(e,r)=>{const t=Xe(e.repo),s=await be(t),o=/^[0-9a-f]{7,40}$/i.test(e.ref),i=fe(e.include),c=te();if(await R(c,{recursive:!0}),s&&await qe(t))if(await ue(t))await k(t),await X(e,t);else try{const u=["fetch","origin"];if(o)u.push("--depth",String(e.depth));else{const D=e.ref==="HEAD"?"HEAD":`${e.ref}:refs/remotes/origin/${e.ref}`;u.push(D,"--depth",String(e.depth))}await T(["-C",t,...u],{timeoutMs:e.timeoutMs})}catch{await k(t),await X(e,t)}else s&&await k(t),await X(e,t);await R(r,{recursive:!0});const a=["clone","--no-checkout","--depth",String(e.depth),"--recurse-submodules=no","--no-tags"];await ue(t)&&a.splice(2,0,"--filter=blob:none"),i&&a.push("--sparse"),o||(a.push("--single-branch"),e.ref!=="HEAD"&&a.push("--branch",e.ref));const n=Fe(t).href;if(a.push(n,r),await T(a,{timeoutMs:e.timeoutMs,allowFileProtocol:!0}),i){const u=me(e.include);u.length>0&&await T(["-C",r,"sparse-checkout","set",...u],{timeoutMs:e.timeoutMs,allowFileProtocol:!0})}await T(["-C",r,"checkout","--quiet","--detach",e.resolvedCommit],{timeoutMs:e.timeoutMs,allowFileProtocol:!0})},Qe=async e=>{const r=await B(w.join(Z(),`docs-cache-${e.sourceId}-`));try{return await Ke(e.repo,e.resolvedCommit,r,e.timeoutMs),r}catch(t){throw await k(r),t}},Ze=async e=>{W(e.sourceId,"sourceId");try{const r=await Qe(e);return{repoDir:r,cleanup:async()=>{await k(r)}}}catch{const r=await B(w.join(Z(),`docs-cache-${e.sourceId}-`));try{return await Ve(e,r),{repoDir:r,cleanup:async()=>{await k(r)}}}catch(t){throw await k(r),t}}},H=e=>Y(e),q=Number(process.env.DOCS_CACHE_STREAM_THRESHOLD_MB??"2"),et=Number.isFinite(q)&&q>0?Math.floor(q*1024*1024):1024*1024,tt=(e,r)=>{const t=w.resolve(e);if(!w.resolve(r).startsWith(t+w.sep))throw new Error(`Path traversal detected: ${r}`)},de=async e=>{try{return await z(e,se.O_RDONLY|se.O_NOFOLLOW)}catch(r){const t=r.code;if(t==="ELOOP")return null;if(t==="EINVAL"||t==="ENOSYS"||t==="ENOTSUP")return(await De(e)).isSymbolicLink()?null:await z(e,"r");throw r}},rt=async(e,r=5e3)=>{const t=Date.now();for(;Date.now()-t<r;)try{const s=await z(e,"wx");return{release:async()=>{await s.close(),await O(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}.`)},ot=async e=>{W(e.sourceId,"sourceId");const r=Pe(e.cacheDir,e.sourceId);await R(e.cacheDir,{recursive:!0});const t=await B(w.join(e.cacheDir,`.tmp-${e.sourceId}-`));let s=null;const o=async()=>{const i=s;!i||i.closed||i.destroyed||await new Promise(c=>{const a=()=>{i.off("close",n),i.off("error",u),c()},n=()=>a(),u=()=>a();i.once("close",n),i.once("error",u);try{i.end()}catch{a()}})};try{const i=(await ie(e.include,{cwd:e.repoDir,ignore:[".git/**",...e.exclude??[]],dot:!0,onlyFiles:!0,followSymbolicLinks:!1})).map(f=>({relativePath:f,normalized:H(f)})).sort((f,h)=>f.normalized.localeCompare(h.normalized)),c=new Set;for(const{relativePath:f}of i)c.add(w.dirname(f));await Promise.all(Array.from(c,f=>R(w.join(t,f),{recursive:!0})));let a=0,n=0;const u=Math.max(1,Math.min(i.length,Math.max(8,Math.min(128,ke.cpus().length*8)))),D=w.join(t,J),g=oe(D,{encoding:"utf8"});s=g;const $=A("sha256"),S=async f=>new Promise((h,m)=>{const p=l=>{g.off("drain",d),m(l)},d=()=>{g.off("error",p),h()};g.once("error",p),g.write(f)?(g.off("error",p),h()):g.once("drain",d)});for(let f=0;f<i.length;f+=u){const h=i.slice(f,f+u),m=await Promise.all(h.map(async p=>{const d=w.join(e.repoDir,p.relativePath),l=await de(d);if(!l)return null;try{const P=await l.stat();if(!P.isFile())return null;const E=w.join(t,p.relativePath);if(tt(t,E),P.size>=et){const I=_e(d,{fd:l.fd,autoClose:!1}),F=oe(E);await Le(I,F)}else{const I=await l.readFile();await V(E,I)}return{path:p.normalized,size:P.size}}finally{await l.close()}}));for(const p of m){if(!p)continue;if(e.maxFiles!==void 0&&n+1>e.maxFiles)throw new Error(`Materialized content exceeds maxFiles (${e.maxFiles}).`);if(a+=p.size,a>e.maxBytes)throw new Error(`Materialized content exceeds maxBytes (${e.maxBytes}).`);const d=`${JSON.stringify(p)}
|
|
3
|
+
`;$.update(d),await S(d),n+=1}}await new Promise((f,h)=>{g.end(()=>f()),g.once("error",h)});const y=$.digest("hex"),v=async f=>{try{return await N(f),!0}catch{return!1}};return await(async(f,h)=>{const m=await rt(`${h}.lock`);try{const p=await v(h),d=`${h}.bak-${ve(8).toString("hex")}`;p&&await U(h,d);try{await U(f,h)}catch(l){if(p)try{await U(d,h)}catch(P){const E=P instanceof Error?P.message:String(P);process.stderr.write(`Warning: Failed to restore backup: ${E}
|
|
4
|
+
`)}throw l}p&&await O(d,{recursive:!0,force:!0})}finally{await m.release()}})(t,r.sourceDir),{bytes:a,fileCount:n,manifestSha256:y}}catch(i){try{await o()}catch{}throw await O(t,{recursive:!0,force:!0}),i}},st=async e=>{W(e.sourceId,"sourceId");const r=await ie(e.include,{cwd:e.repoDir,ignore:[".git/**",...e.exclude??[]],dot:!0,onlyFiles:!0,followSymbolicLinks:!1});r.sort((i,c)=>H(i).localeCompare(H(c)));let t=0,s=0;const o=A("sha256");for(const i of r){const c=H(i),a=w.join(e.repoDir,i),n=await de(a);if(n)try{const u=await n.stat();if(!u.isFile())continue;if(e.maxFiles!==void 0&&s+1>e.maxFiles)throw new Error(`Materialized content exceeds maxFiles (${e.maxFiles}).`);if(t+=u.size,t>e.maxBytes)throw new Error(`Materialized content exceeds maxBytes (${e.maxBytes}).`);const D=`${JSON.stringify({path:c,size:u.size})}
|
|
5
|
+
`;o.update(D),s+=1}finally{await n.close()}}return{bytes:t,fileCount:s,manifestSha256:o.digest("hex")}},it=async(e,r)=>{await r.rm(e,{recursive:!0,force:!0})},K=async e=>{const r=e.deps??{cp:Ce,mkdir:R,rm:O,symlink:$e,stderr:process.stderr},t=w.dirname(e.targetDir);await r.mkdir(t,{recursive:!0}),await it(e.targetDir,r);const s=process.platform==="win32"?"copy":"symlink";if((e.mode??s)==="copy"){await r.cp(e.sourceDir,e.targetDir,{recursive:!0});return}const o=process.platform==="win32"?"junction":"dir";try{await r.symlink(e.sourceDir,e.targetDir,o)}catch(i){const c=i.code;if(c&&new Set(["EPERM","EACCES","ENOTSUP","EINVAL"]).has(c)){if(e.explicitTargetMode){const a=i instanceof Error?i.message:String(i);r.stderr.write(`Warning: Failed to create symlink at ${e.targetDir}. Falling back to copy. ${a}
|
|
6
|
+
`)}await r.cp(e.sourceDir,e.targetDir,{recursive:!0});return}throw i}},at=e=>{const r={dirs:new Map,files:[]};for(const t of e){const s=t.split("/").filter(Boolean);if(s.length===0)continue;let o=r;for(const c of s.slice(0,-1)){let a=o.dirs.get(c);a||(a={dirs:new Map,files:[]},o.dirs.set(c,a)),o=a}const i=s[s.length-1];o.files.push({name:i,path:t})}return r},he=(e,r,t)=>{const s=" ".repeat(r),o=Array.from(e.dirs.keys()).sort(),i=[...e.files].sort((c,a)=>c.name.localeCompare(a.name));for(const c of o){t.push(`${s}- ${c}/`);const a=e.dirs.get(c);a&&he(a,r+1,t)}for(const c of i)t.push(`${s}- [${c.name}](./${c.path})`)},nt=(e,r,t)=>{const s=[...e].sort((a,n)=>a.localeCompare(n)),o=new Map;for(const a of s){const n=a.lastIndexOf("/"),u=n===-1?"":a.substring(0,n),D=n===-1?a:a.substring(n+1),g=o.get(u);g?g.push(D):o.set(u,[D])}const i=Array.from(o.keys()).sort(),c=[];c.push(`[${t}]`);for(const a of i){const n=o.get(a);if(!n)continue;const u=n.join(",");a===""?c.push(`root:{${u}}`):c.push(`${a}:{${u}}`)}r.push(c.join("|"))},ct=(e,r="compressed")=>{const t=[];if(r==="tree"){t.push(`# ${e.id} - Documentation`),t.push(""),t.push("## Files"),t.push("");const s=at(e.files);he(s,0,t)}else{const s=`${e.id} Docs Index`;nt(e.files,t,s)}return t.push(""),t.join(`
|
|
7
|
+
`)},lt=async e=>{const r=w.join(e,".manifest.jsonl");try{const t=await j(r,"utf8"),s=[];for(const o of t.split(`
|
|
8
|
+
`))if(o.trim()){const i=JSON.parse(o);i.path&&s.push(i.path)}return s}catch{return[]}},ut=async e=>{const r=new Map(e.sources.map(s=>[s.id,s])),t=new Map((e.results??[]).map(s=>[s.id,s]));for(const[s,o]of Object.entries(e.lock.sources)){const i=r.get(s);i?.targetDir&&Y(G(e.configPath,i.targetDir));const c=w.join(e.cacheDir,s);try{await N(c)}catch{continue}const a=await lt(c),n={id:s,repo:o.repo,ref:o.ref,resolvedCommit:o.resolvedCommit,fileCount:o.fileCount,cachePath:Y(w.join(e.cacheDir,s)),files:a},u=i?.toc,D=u!==!1;let g="compressed";typeof u=="string"&&(g=u);const $=w.join(c,xe);if(D){if(t.get(s)?.status==="up-to-date")try{await N($);continue}catch{}const S=ct(n,g);await V($,S,"utf8")}else try{await O($,{force:!0})}catch{}}},ft=e=>{if(e<1024)return`${e} B`;const r=["KB","MB","GB","TB"];let t=e,s=-1;for(;t>=1024&&s<r.length-1;)t/=1024,s+=1;return`${t.toFixed(1)} ${r[s]}`},L=async e=>{try{return await N(e),!0}catch{return!1}},pe=async(e,r)=>{const t=w.join(e,r);return await L(t)?await L(w.join(t,J)):!1},we=e=>{if(!e||e.length===0)return[];const r=e.map(t=>t.trim()).filter(t=>t.length>0);return Array.from(new Set(r)).sort()},mt=e=>{const r={include:we(e.include),exclude:we(e.exclude)},t=A("sha256");return t.update(JSON.stringify(r)),t.digest("hex")},ge=async(e,r={})=>{const{config:t,resolvedPath:s,sources:o}=await Ee(e.configPath),i=t.defaults??Te.defaults,c=Me(s,t.cacheDir??Oe,e.cacheDirOverride),a=Ie(s),n=await L(a);let u=null;n&&(u=await je(a));const D=r.resolveRemoteCommit??Ye,g=e.sourceFilter?.length?o.filter(S=>e.sourceFilter?.includes(S.id)):o,$=await Promise.all(g.map(async S=>{const y=u?.sources?.[S.id],v=S.include??i.include,f=S.exclude,h=mt({include:v,exclude:f});if(e.offline){const l=await pe(c,S.id);return{id:S.id,repo:y?.repo??S.repo,ref:y?.ref??S.ref??i.ref,resolvedCommit:y?.resolvedCommit??"offline",lockCommit:y?.resolvedCommit??null,lockRulesSha256:y?.rulesSha256,status:y&&l?"up-to-date":"missing",bytes:y?.bytes,fileCount:y?.fileCount,manifestSha256:y?.manifestSha256,rulesSha256:h}}const m=await D({repo:S.repo,ref:S.ref,allowHosts:i.allowHosts,timeoutMs:e.timeoutMs}),p=y?.resolvedCommit===m.resolvedCommit&&y?.rulesSha256===h,d=y?p?"up-to-date":"changed":"missing";return{id:S.id,repo:m.repo,ref:m.ref,resolvedCommit:m.resolvedCommit,lockCommit:y?.resolvedCommit??null,lockRulesSha256:y?.rulesSha256,status:d,bytes:y?.bytes,fileCount:y?.fileCount,manifestSha256:y?.manifestSha256,rulesSha256:h}}));return{config:t,configPath:s,cacheDir:c,lockPath:a,lockExists:n,lockData:u,results:$,sources:g,defaults:i}},dt=async()=>{const e=w.resolve(process.cwd(),"package.json");try{const r=await j(e,"utf8"),t=JSON.parse(r.toString());return typeof t.version=="string"?t.version:"0.0.0"}catch{}try{const r=await j(new URL("../package.json",import.meta.url),"utf8"),t=JSON.parse(r.toString());return typeof t.version=="string"?t.version:"0.0.0"}catch{}try{const r=await j(new URL("../../package.json",import.meta.url),"utf8"),t=JSON.parse(r.toString());return typeof t.version=="string"?t.version:"0.0.0"}catch{return"0.0.0"}},ht=async(e,r)=>{const t=await dt(),s=new Date().toISOString(),o={...r?.sources??{}};for(const i of e.results){const c=o[i.id];o[i.id]={repo:i.repo,ref:i.ref,resolvedCommit:i.resolvedCommit,bytes:i.bytes??c?.bytes??0,fileCount:i.fileCount??c?.fileCount??0,manifestSha256:i.manifestSha256??c?.manifestSha256??i.resolvedCommit,rulesSha256:i.rulesSha256??c?.rulesSha256,updatedAt:s}}return{version:1,generatedAt:s,toolVersion:t,sources:o}},ye=async(e,r={})=>{const t=process.hrtime.bigint();let s=0;const o=await ge(e,r);await R(o.cacheDir,{recursive:!0});const i=o.lockData,c=o.results.filter(n=>{const u=o.sources.find(D=>D.id===n.id);return n.status==="missing"&&(u?.required??!0)});if(e.failOnMiss&&c.length>0)throw new Error(`Missing required source(s): ${c.map(n=>n.id).join(", ")}.`);if(!e.lockOnly){const n=o.defaults,u=r.fetchSource??Ze,D=r.materializeSource??ot,g=new Map,$=async(v,f)=>{const h=v?.length?o.results.filter(m=>v.includes(m.id)):o.results;return(await Promise.all(h.map(async m=>{const p=o.sources.find(l=>l.id===m.id);if(!p)return null;if(f)return{result:m,source:p};let d=g.get(m.id);return d===void 0&&(d=await pe(o.cacheDir,m.id),g.set(m.id,d)),m.status!=="up-to-date"||!d?{result:m,source:p}:null}))).filter(Boolean)},S=async()=>{await Promise.all(o.sources.map(async v=>{if(!v.targetDir)return;const f=G(o.configPath,v.targetDir);await L(f)||await K({sourceDir:w.join(o.cacheDir,v.id),targetDir:f,mode:v.targetMode??n.targetMode,explicitTargetMode:v.targetMode!==void 0})}))},y=async v=>{const f=e.concurrency??4;let h=0;const m=async()=>{const p=v[h];if(!p||!p.source)return;h+=1;const{result:d,source:l}=p,P=o.lockData?.sources?.[l.id];e.json||C.step("Fetching",l.id);const E=await u({sourceId:l.id,repo:l.repo,ref:l.ref,resolvedCommit:d.resolvedCommit,cacheDir:o.cacheDir,depth:l.depth??n.depth,include:l.include??n.include,timeoutMs:e.timeoutMs});try{const I=w.join(o.cacheDir,l.id,J);if(d.status!=="up-to-date"&&P?.manifestSha256&&await L(I)){const b=await st({sourceId:l.id,repoDir:E.repoDir,cacheDir:o.cacheDir,include:l.include??n.include,exclude:l.exclude,maxBytes:l.maxBytes??n.maxBytes,maxFiles:l.maxFiles??n.maxFiles});if(b.manifestSha256===P.manifestSha256){d.bytes=b.bytes,d.fileCount=b.fileCount,d.manifestSha256=b.manifestSha256,d.status="up-to-date",e.json||C.item(M.success,l.id,"no content changes"),await m();return}}const F=await D({sourceId:l.id,repoDir:E.repoDir,cacheDir:o.cacheDir,include:l.include??n.include,exclude:l.exclude,maxBytes:l.maxBytes??n.maxBytes,maxFiles:l.maxFiles??n.maxFiles});if(l.targetDir){const b=G(o.configPath,l.targetDir);await K({sourceDir:w.join(o.cacheDir,l.id),targetDir:b,mode:l.targetMode??n.targetMode,explicitTargetMode:l.targetMode!==void 0})}d.bytes=F.bytes,d.fileCount=F.fileCount,d.manifestSha256=F.manifestSha256,e.json||C.item(M.success,l.id,`synced ${F.fileCount} files`)}finally{await E.cleanup()}await m()};await Promise.all(Array.from({length:Math.min(f,v.length)},m))};if(e.offline)await S();else{const v=await $();await y(v),await S()}if(!e.offline){const v=(await re({configPath:o.configPath,cacheDirOverride:o.cacheDir})).results.filter(f=>!f.ok);if(v.length>0){const f=await $(v.map(m=>m.id),!0);f.length>0&&(await y(f),await S());const h=(await re({configPath:o.configPath,cacheDirOverride:o.cacheDir})).results.filter(m=>!m.ok);if(h.length>0&&(s+=1,!e.json)){const m=h.map(p=>`${p.id} (${p.issues.join("; ")})`).join(", ");C.line(`${M.warn} Verify failed for ${h.length} source(s): ${m}`)}}}}const a=await ht(o,i);if(await Re(o.lockPath,a),!e.json){const n=Number(process.hrtime.bigint()-t)/1e6,u=o.results.reduce((g,$)=>g+($.bytes??0),0),D=o.results.reduce((g,$)=>g+($.fileCount??0),0);C.line(`${M.info} Completed in ${n.toFixed(0)}ms \xB7 ${ft(u)} \xB7 ${D} files${s?` \xB7 ${s} warning${s===1?"":"s"}`:""}`)}return await ut({cacheDir:o.cacheDir,configPath:o.configPath,lock:a,sources:o.sources,results:o.results}),o.lockExists=!0,o},Se=e=>{const r={upToDate:e.results.filter(t=>t.status==="up-to-date").length,changed:e.results.filter(t=>t.status==="changed").length,missing:e.results.filter(t=>t.status==="missing").length};if(e.results.length===0){C.line(`${M.info} No sources to sync.`);return}C.line(`${M.info} ${e.results.length} sources (${r.upToDate} up-to-date, ${r.changed} changed, ${r.missing} missing)`);for(const t of e.results){const s=C.hash(t.resolvedCommit),o=C.hash(t.lockCommit),i=!!t.lockRulesSha256&&!!t.rulesSha256&&t.lockRulesSha256!==t.rulesSha256;if(t.status==="up-to-date"){C.item(M.success,t.id,`${x.dim("up-to-date")} ${x.gray(s)}`);continue}if(t.status==="changed"){if(t.lockCommit===t.resolvedCommit&&i){C.item(M.warn,t.id,`${x.dim("rules changed")} ${x.gray(s)}`);continue}C.item(M.warn,t.id,`${x.dim("changed")} ${x.gray(o)} ${x.dim("->")} ${x.gray(s)}`);continue}C.item(M.warn,t.id,`${x.dim("missing")} ${x.gray(s)}`)}},pt={__proto__:null,getSyncPlan:ge,printSyncPlan:Se,runSync:ye};export{K as a,Se as b,ye as c,ae as e,ne as p,_ as r,pt as s};
|
|
9
9
|
//# sourceMappingURL=sync.mjs.map
|
package/dist/chunks/verify.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{stat as
|
|
1
|
+
import{stat as $,access as N}from"node:fs/promises";import h from"node:path";import{b as v,r as k,u as l,a as m}from"../shared/docs-cache.DDgb7yxQ.mjs";import{l as O,b as T}from"../shared/docs-cache.BWEcxcrg.mjs";import{createReadStream as _}from"node:fs";import C from"node:readline";const p=".manifest.jsonl",I=async function*(s){const o=h.join(s,p),a=_(o,{encoding:"utf8"}),t=C.createInterface({input:a,crlfDelay:1/0});try{for await(const u of t){const f=u.trim();f&&(yield JSON.parse(f))}}finally{t.close(),a.destroy()}},j=async s=>{try{return await N(s),!0}catch{return!1}},w=async s=>{const{config:o,resolvedPath:a,sources:t}=await O(s.configPath),u=v(a,o.cacheDir??T,s.cacheDirOverride),f=async(r,n)=>{if(!await j(r))return{ok:!1,issues:[n==="source"?"missing source directory":"missing target directory"]};try{let e=0,i=0;for await(const g of I(r)){const E=h.join(r,g.path);try{(await $(E)).size!==g.size&&(i+=1)}catch(y){const d=y.code;if(d==="ENOENT"||d==="ENOTDIR"){e+=1;continue}throw y}}const c=[];return e>0&&c.push(n==="source"?`missing files: ${e}`:`target missing files: ${e}`),i>0&&c.push(n==="source"?`size mismatch: ${i}`:`target size mismatch: ${i}`),{ok:c.length===0,issues:c}}catch(e){const i=e.code;if(i==="ENOENT"||i==="ENOTDIR")return{ok:!1,issues:[n==="source"?"missing manifest":"missing target manifest"]};throw e}},D=await Promise.all(t.map(async r=>{const n=h.join(u,r.id),e=[...(await f(n,"source")).issues];if(r.targetDir&&r.targetMode==="copy"){const i=k(a,r.targetDir),c=await f(i,"target");e.push(...c.issues)}return{id:r.id,ok:e.length===0,issues:e}}));return{cacheDir:u,results:D}},M=s=>{const o=s.results.filter(t=>t.ok).length,a=s.results.length-o;if(s.results.length===0){l.line(`${m.warn} No sources to verify.`);return}l.line(`${m.info} Verified ${s.results.length} sources (${o} ok, ${a} failed)`);for(const t of s.results)t.ok?l.item(m.success,t.id):l.item(m.warn,t.id,t.issues.join(", "))},z={__proto__:null,printVerify:M,verifyCache:w};export{p as M,z as a,w as v};
|
|
2
2
|
//# sourceMappingURL=verify.mjs.map
|
package/dist/cli.mjs
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
|
-
import
|
|
1
|
+
import y from"node:path";import s from"node:process";import g from"picocolors";import{p as O,s as $,E as f,a as l,u as r}from"./shared/docs-cache.DDgb7yxQ.mjs";import"cac";const u="docs-cache",D=`
|
|
2
2
|
Usage: ${u} <command> [options]
|
|
3
3
|
|
|
4
4
|
Commands:
|
|
5
|
-
add
|
|
6
|
-
remove
|
|
7
|
-
sync
|
|
8
|
-
status
|
|
9
|
-
clean
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
5
|
+
add Add sources to the config (supports github:org/repo#ref)
|
|
6
|
+
remove Remove sources from the config and targets
|
|
7
|
+
sync Synchronize cache with config
|
|
8
|
+
status Show cache status
|
|
9
|
+
clean Remove project cache
|
|
10
|
+
clean-cache Clear global git cache
|
|
11
|
+
prune Remove unused data
|
|
12
|
+
verify Validate cache integrity
|
|
13
|
+
init Create a new config interactively
|
|
13
14
|
|
|
14
15
|
Global options:
|
|
15
16
|
--source <repo> (add only)
|
|
@@ -23,14 +24,16 @@ Global options:
|
|
|
23
24
|
--concurrency <n>
|
|
24
25
|
--json
|
|
25
26
|
--timeout-ms <n>
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
`)
|
|
29
|
-
`);else{
|
|
30
|
-
`):
|
|
31
|
-
`):
|
|
32
|
-
`):
|
|
33
|
-
`):
|
|
34
|
-
`):
|
|
35
|
-
`):(
|
|
27
|
+
--silent
|
|
28
|
+
`,p=()=>{s.stdout.write(D.trimStart())},m=n=>{s.stderr.write(`${l.error} ${n}
|
|
29
|
+
`)},S=n=>{const t=n.findIndex(e=>!e.startsWith("-")),h=t===-1?[]:n.slice(t+1),d=[];let a=-1;const i=new Set(["--config","--cache-dir","--concurrency","--timeout-ms"]);for(let e=0;e<h.length;e+=1){const o=h[e];if(o==="--source"){const c=h[e+1];if(!c||c.startsWith("-"))throw new Error("--source expects a value.");d.push({repo:c}),a=d.length-1,e+=1;continue}if(o==="--target"||o==="--target-dir"){const c=h[e+1];if(!c||c.startsWith("-"))throw new Error("--target expects a value.");if(a===-1)throw new Error("--target must follow a --source entry.");d[a].targetDir=c,e+=1;continue}if(i.has(o)){e+=1;continue}o.startsWith("--")||(d.push({repo:o}),a=d.length-1)}return d},P=async(n,t,h,d)=>{if(n==="add"){const{addSources:a}=await import("./chunks/add.mjs"),{runSync:i}=await import("./chunks/sync.mjs").then(function(c){return c.s}),e=S(d);if(e.length===0)throw new Error("Usage: docs-cache add [--source <repo> --target <dir>] <repo...>");const o=await a({configPath:t.config,entries:e});if(t.offline?t.json||r.line(`${l.warn} Offline: skipped sync`):await i({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)s.stdout.write(`${JSON.stringify(o,null,2)}
|
|
30
|
+
`);else{for(const c of o.sources){const v=c.repo.replace(/^https?:\/\//,"").replace(/\.git$/,""),j=c.targetDir?` ${g.dim("->")} ${g.magenta(c.targetDir)}`:"";r.item(l.success,c.id,`${g.blue(v)}${j}`)}o.skipped?.length&&r.line(`${l.warn} Skipped ${o.skipped.length} existing source${o.skipped.length===1?"":"s"}: ${o.skipped.join(", ")}`),r.line(`${l.info} Updated ${g.gray(y.relative(s.cwd(),o.configPath)||"docs.config.json")}`),o.gitignoreUpdated&&o.gitignorePath&&r.line(`${l.info} Updated ${g.gray(r.path(o.gitignorePath))}`)}return}if(n==="remove"){const{removeSources:a}=await import("./chunks/remove.mjs"),{pruneCache:i}=await import("./chunks/prune.mjs");if(h.length===0)throw new Error("Usage: docs-cache remove <id...>");const e=await a({configPath:t.config,ids:h});if(t.json)s.stdout.write(`${JSON.stringify(e,null,2)}
|
|
31
|
+
`);else{if(e.removed.length>0&&r.line(`${l.success} Removed ${e.removed.length} source${e.removed.length===1?"":"s"}: ${e.removed.join(", ")}`),e.missing.length>0&&r.line(`${l.warn} Missing ${e.missing.length} source${e.missing.length===1?"":"s"}: ${e.missing.join(", ")}`),e.targetsRemoved.length>0){const o=e.targetsRemoved.map(c=>`${c.id} -> ${r.path(c.targetDir)}`).join(", ");r.line(`${l.success} Removed ${e.targetsRemoved.length} target${e.targetsRemoved.length===1?"":"s"}: ${o}`)}r.line(`${l.info} Updated ${g.gray(y.relative(s.cwd(),e.configPath)||"docs.config.json")}`)}t.prune&&await i({configPath:t.config,cacheDirOverride:t.cacheDir,json:t.json});return}if(n==="status"){const{getStatus:a,printStatus:i}=await import("./chunks/status.mjs"),e=await a({configPath:t.config,cacheDirOverride:t.cacheDir,json:t.json});t.json?s.stdout.write(`${JSON.stringify(e,null,2)}
|
|
32
|
+
`):i(e);return}if(n==="clean"){const{cleanCache:a}=await import("./chunks/clean.mjs"),i=await a({configPath:t.config,cacheDirOverride:t.cacheDir,json:t.json});t.json?s.stdout.write(`${JSON.stringify(i,null,2)}
|
|
33
|
+
`):i.removed?r.line(`${l.success} Removed cache at ${r.path(i.cacheDir)}`):r.line(`${l.info} Cache already missing at ${r.path(i.cacheDir)}`);return}if(n==="clean-cache"){const{cleanGitCache:a}=await import("./chunks/clean-git-cache.mjs"),i=await a();if(t.json)s.stdout.write(`${JSON.stringify(i,null,2)}
|
|
34
|
+
`);else if(i.removed){const e=i.bytesFreed!==void 0?`${(i.bytesFreed/1024/1024).toFixed(2)} MB`:"unknown size",o=i.repoCount!==void 0?` (${i.repoCount} cached repositor${i.repoCount===1?"y":"ies"})`:"";r.line(`${l.success} Cleared global git cache${o}: ${e} freed`),r.line(`${l.info} Cache location: ${r.path(i.cacheDir)}`)}else r.line(`${l.info} Global git cache already empty at ${r.path(i.cacheDir)}`);return}if(n==="prune"){const{pruneCache:a}=await import("./chunks/prune.mjs"),i=await a({configPath:t.config,cacheDirOverride:t.cacheDir,json:t.json});t.json?s.stdout.write(`${JSON.stringify(i,null,2)}
|
|
35
|
+
`):i.removed.length===0?r.line(`${l.info} No cache entries to prune.`):r.line(`${l.success} Pruned ${i.removed.length} cache entr${i.removed.length===1?"y":"ies"}: ${i.removed.join(", ")}`);return}if(n==="sync"){const{printSyncPlan:a,runSync:i}=await import("./chunks/sync.mjs").then(function(o){return o.s}),e=await i({configPath:t.config,cacheDirOverride:t.cacheDir,json:t.json,lockOnly:t.lockOnly,offline:t.offline,failOnMiss:t.failOnMiss,timeoutMs:t.timeoutMs});t.json?s.stdout.write(`${JSON.stringify(e,null,2)}
|
|
36
|
+
`):a(e);return}if(n==="verify"){const{printVerify:a,verifyCache:i}=await import("./chunks/verify.mjs").then(function(o){return o.a}),e=await i({configPath:t.config,cacheDirOverride:t.cacheDir,json:t.json});t.json?s.stdout.write(`${JSON.stringify(e,null,2)}
|
|
37
|
+
`):a(e),e.results.some(o=>!o.ok)&&s.exit(f.FatalError);return}if(n==="init"){const{initConfig:a}=await import("./chunks/init.mjs");if(t.config)throw new Error("Init does not accept --config. Use the project root.");const i=await a({cacheDirOverride:t.cacheDir,json:t.json});t.json?s.stdout.write(`${JSON.stringify(i,null,2)}
|
|
38
|
+
`):(r.line(`${l.success} Wrote ${g.gray(r.path(i.configPath))}`),i.gitignoreUpdated&&i.gitignorePath&&r.line(`${l.info} Updated ${g.gray(r.path(i.gitignorePath))}`));return}r.line(`${u} ${n}: not implemented yet.`)};async function C(){try{s.on("uncaughtException",w),s.on("unhandledRejection",w);const n=O(),t=n.rawArgs;$(n.options.silent),n.help&&(p(),s.exit(f.Success)),n.command||(p(),s.exit(f.InvalidArgument)),n.command!=="add"&&n.command!=="remove"&&n.positionals.length>0&&(m(`${u}: unexpected arguments.`),p(),s.exit(f.InvalidArgument)),n.command!=="add"&&n.options.targetDir&&(m(`${u}: --target-dir is only valid for add.`),p(),s.exit(f.InvalidArgument)),await P(n.command,n.options,n.positionals,n.rawArgs)}catch(n){w(n)}}function w(n){const t=n.message||String(n);m(t),s.exit(f.FatalError)}export{u as CLI_NAME,C as main};
|
|
36
39
|
//# sourceMappingURL=cli.mjs.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{writeFile as I,readFile as T,access as z}from"node:fs/promises";import h from"node:path";import{z as i}from"zod";import{r as L}from"./docs-cache.DDgb7yxQ.mjs";const b=i.enum(["symlink","copy"]),M=i.enum(["materialize"]),D=i.enum(["tree","compressed"]),U=i.object({type:i.enum(["commit","manifest"]),value:i.string().nullable()}).strict(),_=i.object({ref:i.string().min(1),mode:M,include:i.array(i.string().min(1)).min(1),targetMode:b.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.union([i.boolean(),D]).optional()}).strict(),P=i.object({id:i.string().min(1),repo:i.string().min(1),targetDir:i.string().min(1).optional(),targetMode:b.optional(),ref:i.string().min(1).optional(),mode:M.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:U.optional(),toc:i.union([i.boolean(),D]).optional()}).strict(),J=i.object({$schema:i.string().min(1).optional(),cacheDir:i.string().min(1).optional(),targetMode:b.optional(),defaults:_.partial().optional(),sources:i.array(P)}).strict(),R=/^[a-zA-Z0-9_-]+$/,G=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(!R.test(e))throw new Error(`${t} must contain only alphanumeric characters, hyphens, and underscores.`);if(G.has(e.toUpperCase()))throw new Error(`${t} uses reserved name '${e}'.`);return e},j="docs.config.json",v=".docs",A="package.json",V=process.platform==="win32"?"copy":"symlink",g={cacheDir:v,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"],toc:!0},sources:[]},X=(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 n=t[o];if(Array.isArray(d)&&Array.isArray(n)){X(d,n)||(r[o]=d);continue}if(S(d)&&S(n)){const c=C(d,n);Object.keys(c).length>0&&(r[o]=c);continue}d!==n&&(r[o]=d)}return r},Z=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},k=(e,t)=>{if(typeof e!="boolean")throw new Error(`${t} must be a boolean.`);return e},K=(e,t)=>{if(typeof e!="number"||Number.isNaN(e))throw new Error(`${t} must be a number.`);return e},f=(e,t)=>{const r=K(e,t);if(r<1)throw new Error(`${t} must be greater than zero.`);return r},y=(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},q=(e,t)=>{const r=l(e,t);if(r!=="symlink"&&r!=="copy")throw new Error(`${t} must be "symlink" or "copy".`);return r},B=(e,t)=>{if(e!=="materialize")throw new Error(`${t} must be "materialize".`);return e},Q=(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}},N=e=>{if(!p(e))throw new Error("Config must be a JSON object.");const t=J.safeParse(e);if(!t.success){const s=t.error.issues.map(a=>`${a.path.join(".")||"config"} ${a.message}`).join("; ");throw new Error(`Config does not match schema: ${s}.`)}const r=e.cacheDir?l(e.cacheDir,"cacheDir"):v,o=e.defaults,d=e.targetMode!==void 0?q(e.targetMode,"targetMode"):void 0,n=g.defaults;let c=n;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"):n.ref,mode:o.mode!==void 0?B(o.mode,"defaults.mode"):n.mode,include:o.include!==void 0?y(o.include,"defaults.include"):n.include,targetMode:o.targetMode!==void 0?q(o.targetMode,"defaults.targetMode"):d??n.targetMode,depth:o.depth!==void 0?f(o.depth,"defaults.depth"):n.depth,required:o.required!==void 0?k(o.required,"defaults.required"):n.required,maxBytes:o.maxBytes!==void 0?f(o.maxBytes,"defaults.maxBytes"):n.maxBytes,maxFiles:o.maxFiles!==void 0?f(o.maxFiles,"defaults.maxFiles"):n.maxFiles,allowHosts:o.allowHosts!==void 0?y(o.allowHosts,"defaults.allowHosts"):n.allowHosts,toc:o.toc!==void 0?o.toc:n.toc}}else d!==void 0&&(c={...n,targetMode:d});if(!Array.isArray(e.sources))throw new Error("sources must be an array.");const m=e.sources.map((s,a)=>{if(!p(s))throw new Error(`sources[${a}] must be an object.`);const u={id:F(s.id,`sources[${a}].id`),repo:l(s.repo,`sources[${a}].repo`)};if(s.targetDir!==void 0&&(u.targetDir=l(s.targetDir,`sources[${a}].targetDir`)),s.targetMode!==void 0){const $=l(s.targetMode,`sources[${a}].targetMode`);if($!=="symlink"&&$!=="copy")throw new Error(`sources[${a}].targetMode must be "symlink" or "copy".`);u.targetMode=$}return s.ref!==void 0&&(u.ref=l(s.ref,`sources[${a}].ref`)),s.mode!==void 0&&(u.mode=B(s.mode,`sources[${a}].mode`)),s.depth!==void 0&&(u.depth=f(s.depth,`sources[${a}].depth`)),s.include!==void 0&&(u.include=y(s.include,`sources[${a}].include`)),s.exclude!==void 0&&(u.exclude=y(s.exclude,`sources[${a}].exclude`)),s.required!==void 0&&(u.required=k(s.required,`sources[${a}].required`)),s.maxBytes!==void 0&&(u.maxBytes=f(s.maxBytes,`sources[${a}].maxBytes`)),s.maxFiles!==void 0&&(u.maxFiles=f(s.maxFiles,`sources[${a}].maxFiles`)),s.integrity!==void 0&&(u.integrity=Q(s.integrity,`sources[${a}].integrity`)),s.toc!==void 0&&(u.toc=s.toc),u}),E=new Set,w=[];for(const s of m)E.has(s.id)&&w.push(s.id),E.add(s.id);if(w.length>0)throw new Error(`Duplicate source IDs found: ${w.join(", ")}. Each source must have a unique ID.`);return{cacheDir:r,targetMode:d,defaults:c,sources:m}},W=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}))},O=e=>e?h.resolve(e):h.resolve(process.cwd(),j),Y=()=>h.resolve(process.cwd(),A),H=async e=>{try{return await z(e),!0}catch{return!1}},x=async(e,t)=>{let r;try{r=await T(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 n=N(d);for(const c of n.sources)c.targetDir&&L(e,c.targetDir);return{config:n,resolvedPath:e,sources:W(n)}},ee=async(e,t)=>{const r=`${JSON.stringify(t,null,2)}
|
|
2
|
+
`;await I(e,r,"utf8")},te=async e=>{const t=O(e),r=h.basename(t)===A;if(e)return x(t,r?"package":"config");if(await H(t))return x(t,"config");const o=Y();if(await H(o))try{return await x(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,v as b,j as c,te as l,O as r,Z as s,N as v,ee as w};
|
|
3
|
+
//# sourceMappingURL=docs-cache.BWEcxcrg.mjs.map
|
|
@@ -1,5 +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.
|
|
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.DDgb7yxQ.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
2
|
`)?"":`
|
|
3
3
|
`,s=`${e}${i}${t.entry}
|
|
4
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.
|
|
5
|
+
//# sourceMappingURL=docs-cache.C96VehGu.mjs.map
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import p from"node:process";import d from"cac";import i from"node:path";import s from"picocolors";var a=(o=>(o[o.Success=0]="Success",o[o.FatalError=1]="FatalError",o[o.InvalidArgument=9]="InvalidArgument",o))(a||{});const m=["add","remove","sync","status","clean","clean-cache","prune","verify","init"],h=(o=p.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").option("--silent","Suppress non-error output").help();const e=r.parse(o,{run:!1}),t=e.args[0];if(t&&!m.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,silent:!!e.options.silent};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 l=o.slice(2);return{command:t??null,options:n,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),p.exit(a.InvalidArgument)}},f="TOC.md",u=o=>o.replace(/\\/g,"/"),g=(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(u(n).split("/").filter(Boolean).includes(".git"))throw new Error("targetDir cannot be within .git directory.");return t},y=(o,r,e)=>{if(e)return i.resolve(e);const t=i.dirname(o);return i.resolve(t,r)},w=(o,r)=>{i.join(o,"repos");const e=i.join(o,r);return{cacheDir:o,sourceDir:e}},v={error:s.red("\u2716"),success:s.green("\u2714"),info:s.blue("\u2139"),warn:s.yellow("\u26A0")};let c=!1;const b=o=>{c=o},E={path:o=>{const r=i.relative(process.cwd(),o),e=r.length<o.length?r:o;return u(e)},hash:o=>o?o.slice(0,7):"-",pad:(o,r)=>o.padEnd(r),line:(o="")=>{c||process.stdout.write(`${o}
|
|
2
|
+
`)},header:(o,r)=>{c||process.stdout.write(`${s.blue("\u2139")} ${o.padEnd(10)} ${r}
|
|
3
|
+
`)},item:(o,r,e)=>{if(c)return;const t=s.bold(r),n=e?s.gray(e):"";process.stdout.write(` ${o} ${t} ${n}
|
|
4
|
+
`)},step:(o,r,e)=>{if(c)return;const t=s.cyan("\u2192");process.stdout.write(` ${t} ${o} ${s.bold(r)}${e?` ${s.dim(e)}`:""}
|
|
5
|
+
`)}};export{f as D,a as E,v as a,y as b,w as g,h as p,g as r,b as s,u as t,E as u};
|
|
6
|
+
//# sourceMappingURL=docs-cache.DDgb7yxQ.mjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{access as s}from"node:fs/promises";import{homedir as a}from"node:os";import e from"node:path";const c=()=>{const r=a();switch(process.platform){case"darwin":return e.join(r,"Library","Caches");case"win32":return process.env.LOCALAPPDATA||e.join(r,"AppData","Local");default:return process.env.XDG_CACHE_HOME||e.join(r,".cache")}},t=()=>process.env.DOCS_CACHE_GIT_DIR||e.join(c(),"docs-cache-git"),o=async r=>{try{return await s(r),!0}catch{return!1}};export{o as e,t as r};
|
|
2
|
+
//# sourceMappingURL=docs-cache.kK1DPQIQ.mjs.map
|
package/package.json
CHANGED
|
@@ -1,3 +0,0 @@
|
|
|
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
|
|
@@ -1,6 +0,0 @@
|
|
|
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
|