@mono-lit/utility 0.0.0-stage → 0.0.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/LICENSE.md +54 -0
- package/README.md +156 -2
- package/dist/app-roots-BJsIxzjk.d.ts +91 -0
- package/dist/app-roots-CvJnmXcs.js +128 -0
- package/dist/config-node-UzJrXg0Z.js +76 -0
- package/dist/config-node.d.ts +977 -0
- package/dist/config-node.js +7 -0
- package/dist/config.d.ts +2 -0
- package/dist/config.js +3 -0
- package/dist/create-config-D3m6xTaQ.d.ts +733 -0
- package/dist/create-config-DdL3Fh6T.js +357 -0
- package/dist/fetching.d.ts +239 -0
- package/dist/fetching.js +867 -0
- package/dist/generate-CJ7MtcDd.js +291 -0
- package/dist/index-C2hZeNkq.d.ts +365 -0
- package/dist/index-ClrZbU7n.d.ts +518 -0
- package/dist/index.d.ts +29 -0
- package/dist/index.js +939 -0
- package/dist/merge-file-C5nzi_MY.d.ts +122 -0
- package/dist/merge-file-CtyKTu5L.js +133 -0
- package/dist/mock-db-5mJTObSC.js +1282 -0
- package/dist/mock-db.d.ts +2 -0
- package/dist/mock-db.js +4 -0
- package/dist/mono-alias-DNDm-jB_.js +508 -0
- package/dist/mono-clone.mjs +958 -0
- package/dist/mono-db.d.ts +1 -0
- package/dist/mono-db.js +151 -0
- package/dist/mono-env.mjs +231 -0
- package/dist/mono-git.mjs +798 -0
- package/dist/mono-link-YlOQ2PVS.js +488 -0
- package/dist/mono-prepare.d.ts +1 -0
- package/dist/mono-prepare.js +27 -0
- package/dist/mono-skills.d.ts +1 -0
- package/dist/mono-skills.js +830 -0
- package/dist/mono-tsconfig-D2qRL9_R.js +204 -0
- package/dist/mono.mjs +34 -0
- package/dist/nuxt-layers-DP1m7f1-.js +176 -0
- package/dist/nuxt-layers.d.ts +34 -0
- package/dist/nuxt-layers.js +3 -0
- package/dist/nuxt-runtime.d.ts +18 -0
- package/dist/nuxt-runtime.js +102 -0
- package/dist/nuxt.d.ts +386 -0
- package/dist/nuxt.js +590 -0
- package/dist/runtime-C_IWNrAG.js +5817 -0
- package/dist/runtime.d.ts +2583 -0
- package/dist/runtime.js +4 -0
- package/dist/session-Bk985AIM.js +1721 -0
- package/dist/types-B6FdB7LJ.d.ts +57 -0
- package/dist/universal-B2eD9xho.d.ts +97 -0
- package/dist/universal-BNTo_83u.js +599 -0
- package/dist/virtual-mono-apps.d.ts +16 -0
- package/dist/vite.d.ts +940 -0
- package/dist/vite.js +1132 -0
- package/package.json +141 -3
|
@@ -0,0 +1,798 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Git transport for `mono sync`.
|
|
3
|
+
*
|
|
4
|
+
* `mono sync` historically reached GitHub only through a shared personal access
|
|
5
|
+
* token (REST `/repos/{o}/{r}/commits/{ref}` + an archive ZIP download), which
|
|
6
|
+
* burns REST rate limit for every app on every machine. Teammates who have been
|
|
7
|
+
* invited as collaborators can already reach those repos with their OWN machine
|
|
8
|
+
* credentials (Git Credential Manager / `gh auth`) over plain git transport,
|
|
9
|
+
* which has no REST rate limit at all. This module is the git half of that: a
|
|
10
|
+
* cheap access probe that doubles as the change-detection SHA, plus a shallow
|
|
11
|
+
* fetch to materialize the tree.
|
|
12
|
+
*
|
|
13
|
+
* Deliberately side-effect-free and importable so `tests/mono-git.test.ts` can
|
|
14
|
+
* cover it — `bin/mono-clone.mjs` is a top-level script that takes the lock and
|
|
15
|
+
* reads `mono.config.ts` at import time, so it cannot be unit tested. Every
|
|
16
|
+
* function that shells out accepts an injectable `run` for the same reason.
|
|
17
|
+
*
|
|
18
|
+
* HTTPS only, by design. If the machine's HTTPS git credentials do not reach the
|
|
19
|
+
* repo we fall straight back to the existing token behaviour rather than also
|
|
20
|
+
* probing `git@github.com` — see `probeGitAccess`.
|
|
21
|
+
*/
|
|
22
|
+
import fs from 'node:fs'
|
|
23
|
+
import os from 'node:os'
|
|
24
|
+
import path from 'node:path'
|
|
25
|
+
import { spawnSync } from 'node:child_process'
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Applied to EVERY git invocation. Each one is load-bearing:
|
|
29
|
+
*
|
|
30
|
+
* - `credential.interactive` / `credential.guiPrompt`: stop Git Credential
|
|
31
|
+
* Manager popping a GUI dialog. `GIT_TERMINAL_PROMPT=0` alone does NOT stop
|
|
32
|
+
* GCM — a probe with GCM active was measured hanging for >2 minutes on an
|
|
33
|
+
* invisible dialog. The env vars in `gitEnv()` and the `timeoutMs` in
|
|
34
|
+
* `runGit()` are the other two layers of that same defence.
|
|
35
|
+
* - `core.autocrlf=false` / `core.eol=lf`: Git for Windows defaults
|
|
36
|
+
* `autocrlf=true`, which would rewrite every LF to CRLF and make the git path
|
|
37
|
+
* produce a DIFFERENT tree than the ZIP path. Both transports must yield
|
|
38
|
+
* byte-identical files or the commit-sha cache silently lies.
|
|
39
|
+
* - `core.symlinks=false`: a GitHub archive ZIP cannot carry symlinks either;
|
|
40
|
+
* avoids "unable to create symlink" without Windows Developer Mode.
|
|
41
|
+
* - `submodule.recurse=false`: archives never contain submodules — parity.
|
|
42
|
+
* - `core.longpaths`: Windows paths over 260 chars.
|
|
43
|
+
* - `gc.auto=0`: the staging repo is deleted seconds later; never pay for gc.
|
|
44
|
+
*/
|
|
45
|
+
const BASE_ARGS = [
|
|
46
|
+
'-c', 'credential.interactive=false',
|
|
47
|
+
'-c', 'credential.guiPrompt=false',
|
|
48
|
+
'-c', 'core.longpaths=true',
|
|
49
|
+
'-c', 'core.autocrlf=false',
|
|
50
|
+
'-c', 'core.eol=lf',
|
|
51
|
+
'-c', 'core.symlinks=false',
|
|
52
|
+
'-c', 'submodule.recurse=false',
|
|
53
|
+
'-c', 'gc.auto=0',
|
|
54
|
+
'-c', 'advice.detachedHead=false',
|
|
55
|
+
'--no-pager',
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
/** Environment for every git child process. See BASE_ARGS for why. */
|
|
59
|
+
export function gitEnv(extra = {}) {
|
|
60
|
+
return {
|
|
61
|
+
...process.env,
|
|
62
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
63
|
+
GCM_INTERACTIVE: 'never',
|
|
64
|
+
// Pointer files, exactly like the ZIP path. Neither transport ships LFS content.
|
|
65
|
+
GIT_LFS_SKIP_SMUDGE: '1',
|
|
66
|
+
...extra,
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Run git. NEVER throws — returns a record for the caller to classify.
|
|
72
|
+
*
|
|
73
|
+
* `shell: false` is deliberate: the token path's `execSync('unzip -q "..."')` is
|
|
74
|
+
* a shell string, which is exactly the Windows quoting hazard not to repeat for
|
|
75
|
+
* paths like `C:\Program Files\...`.
|
|
76
|
+
*/
|
|
77
|
+
export function runGit(args, { cwd, timeoutMs = 20000, env } = {}) {
|
|
78
|
+
const res = spawnSync('git', [...BASE_ARGS, ...args], {
|
|
79
|
+
cwd,
|
|
80
|
+
env: gitEnv(env),
|
|
81
|
+
encoding: 'utf8',
|
|
82
|
+
shell: false,
|
|
83
|
+
windowsHide: true,
|
|
84
|
+
timeout: timeoutMs,
|
|
85
|
+
killSignal: 'SIGKILL',
|
|
86
|
+
maxBuffer: 32 * 1024 * 1024,
|
|
87
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
const timedOut = res.error?.code === 'ETIMEDOUT' || res.signal === 'SIGKILL'
|
|
91
|
+
|
|
92
|
+
return {
|
|
93
|
+
ok: res.status === 0 && !timedOut,
|
|
94
|
+
code: res.status,
|
|
95
|
+
signal: res.signal,
|
|
96
|
+
stdout: res.stdout || '',
|
|
97
|
+
stderr: res.stderr || '',
|
|
98
|
+
error: res.error, // ENOENT => git is not installed
|
|
99
|
+
timedOut,
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Order matters in `classifyGitFailure`: network is tested BEFORE auth, because a
|
|
104
|
+
// proxy or TLS failure can itself mention "403".
|
|
105
|
+
const RE_NETWORK = /Could not resolve host|Failed to connect|Connection (timed out|refused|reset)|Operation timed out|network is unreachable|unable to access '[^']*': (Proxy|SSL|OpenSSL|GnuTLS|Recv failure|send failure)|SSL certificate problem/i
|
|
106
|
+
const RE_NOTFOUND = /remote: Repository not found|repository '[^']*' not found|remote: Not Found/i
|
|
107
|
+
const RE_BADCRED = /Authentication failed|Invalid username or (password|token)|Support for password authentication|The requested URL returned error: 40[13]|403 Forbidden/i
|
|
108
|
+
const RE_NOCRED = /could not read (Username|Password)|unable to get (password|username) from user|terminal prompts disabled|no supported authentication methods/i
|
|
109
|
+
|
|
110
|
+
/** First `fatal:`/`error:`/`remote:` line of stderr, tag stripped. */
|
|
111
|
+
export function firstFatal(stderr) {
|
|
112
|
+
const lines = String(stderr).split('\n').map((s) => s.trim())
|
|
113
|
+
const line = lines.find((s) => /^(fatal|error|remote):/i.test(s)) || lines.find(Boolean) || ''
|
|
114
|
+
return line.replace(/^(fatal|error|remote):\s*/i, '')
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Turn a `runGit` result into an actionable cause.
|
|
119
|
+
*
|
|
120
|
+
* The `not-invited` vs `bad-credential` split is the point of this function:
|
|
121
|
+
* GitHub answers 404 ("Repository not found") for private repos you cannot see,
|
|
122
|
+
* but a STALE cached credential answers "Authentication failed". Telling that
|
|
123
|
+
* second user "you are not invited" would be actively misleading, and expired
|
|
124
|
+
* PATs sitting in Windows Credential Manager are common.
|
|
125
|
+
*
|
|
126
|
+
* @returns {{kind:'no-git'|'timeout'|'ref-missing'|'network'|'no-access'|'unknown',
|
|
127
|
+
* why?:'not-invited'|'bad-credential'|'no-credential', detail?:string}}
|
|
128
|
+
*/
|
|
129
|
+
export function classifyGitFailure(res) {
|
|
130
|
+
// Structural causes first — they carry no useful stderr.
|
|
131
|
+
if (res?.error?.code === 'ENOENT') return { kind: 'no-git' }
|
|
132
|
+
if (res?.timedOut) return { kind: 'timeout' }
|
|
133
|
+
|
|
134
|
+
const err = res?.stderr || ''
|
|
135
|
+
|
|
136
|
+
// `ls-remote --exit-code` exits 2 with no output when no ref matched.
|
|
137
|
+
if (res?.code === 2 && !err.trim()) return { kind: 'ref-missing' }
|
|
138
|
+
|
|
139
|
+
if (RE_NETWORK.test(err)) return { kind: 'network', detail: firstFatal(err) }
|
|
140
|
+
if (RE_NOTFOUND.test(err)) return { kind: 'no-access', why: 'not-invited', detail: firstFatal(err) }
|
|
141
|
+
if (RE_BADCRED.test(err)) return { kind: 'no-access', why: 'bad-credential', detail: firstFatal(err) }
|
|
142
|
+
if (RE_NOCRED.test(err)) return { kind: 'no-access', why: 'no-credential', detail: firstFatal(err) }
|
|
143
|
+
|
|
144
|
+
return { kind: 'unknown', detail: firstFatal(err) || `git exited ${res?.code}` }
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export const httpsRemote = (owner, repo) => `https://github.com/${owner}/${repo}.git`
|
|
148
|
+
|
|
149
|
+
export const isSha40 = (s) => /^[0-9a-f]{40}$/i.test(String(s))
|
|
150
|
+
/** 7..39 hex — resolvable by the REST API but NOT fetchable by git. */
|
|
151
|
+
export const isShortSha = (s) => /^[0-9a-f]{7,39}$/i.test(String(s))
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Refs to ask `ls-remote` about. `^{}` peels an annotated tag to its COMMIT,
|
|
155
|
+
* which is what REST `/commits/<ref>` returns — without it the SHA recorded in
|
|
156
|
+
* `.mono/apps-commit-cache.json` would differ between the two transports and
|
|
157
|
+
* every transport flip would force a redundant re-download.
|
|
158
|
+
*/
|
|
159
|
+
export function refPatterns(ref) {
|
|
160
|
+
return [`refs/heads/${ref}`, `refs/tags/${ref}`, `refs/tags/${ref}^{}`]
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Pick the SHA for `ref` out of `ls-remote` output. Branch beats tag. */
|
|
164
|
+
export function parseLsRemote(stdout, ref) {
|
|
165
|
+
const rows = String(stdout)
|
|
166
|
+
.split('\n')
|
|
167
|
+
.map((l) => l.trim())
|
|
168
|
+
.filter(Boolean)
|
|
169
|
+
.map((l) => {
|
|
170
|
+
const [sha, name] = l.split('\t')
|
|
171
|
+
return { sha, name }
|
|
172
|
+
})
|
|
173
|
+
|
|
174
|
+
const pick = (name) => rows.find((r) => r.name === name)?.sha || null
|
|
175
|
+
|
|
176
|
+
return (
|
|
177
|
+
pick(`refs/heads/${ref}`) ?? // branch
|
|
178
|
+
pick(`refs/tags/${ref}^{}`) ?? // annotated tag -> the commit it points at
|
|
179
|
+
pick(`refs/tags/${ref}`) ?? // lightweight tag
|
|
180
|
+
null
|
|
181
|
+
)
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Can this machine reach `owner/repo` with its own git credentials, and if so
|
|
186
|
+
* what is the head SHA of `ref`?
|
|
187
|
+
*
|
|
188
|
+
* ONE `ls-remote` answers both, so on the git path the REST call disappears
|
|
189
|
+
* entirely rather than merely being supplemented — which is the whole point of
|
|
190
|
+
* this change.
|
|
191
|
+
*
|
|
192
|
+
* @returns {{ok:true, sha:string, remoteUrl:string, viaSha?:boolean}
|
|
193
|
+
* | {ok:false, kind:string, why?:string, detail?:string, remoteUrl:string}}
|
|
194
|
+
*/
|
|
195
|
+
export function probeGitAccess({ owner, repo, ref, timeoutMs = 60000, run = runGit }) {
|
|
196
|
+
const remoteUrl = httpsRemote(owner, repo)
|
|
197
|
+
const res = run(['ls-remote', '--exit-code', remoteUrl, ...refPatterns(ref)], { timeoutMs })
|
|
198
|
+
|
|
199
|
+
if (res.ok) {
|
|
200
|
+
const sha = parseLsRemote(res.stdout, ref)
|
|
201
|
+
if (sha) return { ok: true, sha, remoteUrl }
|
|
202
|
+
// Exit 0 but nothing we recognise — treat as a missing ref.
|
|
203
|
+
return { ok: false, kind: 'ref-missing', remoteUrl }
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const cls = classifyGitFailure(res)
|
|
207
|
+
|
|
208
|
+
// Access is proven, the ref just isn't a branch or tag. A full 40-hex ref is a
|
|
209
|
+
// pinned commit: legitimate, and GitHub allows fetching an arbitrary SHA.
|
|
210
|
+
if (cls.kind === 'ref-missing' && isSha40(ref)) {
|
|
211
|
+
return { ok: true, sha: String(ref).toLowerCase(), remoteUrl, viaSha: true }
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
return { ...cls, ok: false, remoteUrl }
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Every legal split of a `/tree/<refAndDir>` URL remainder into ref + folder.
|
|
219
|
+
*
|
|
220
|
+
* A deep GitHub URL like `.../templates/tree/main/nuxt-remote` names the FOLDER
|
|
221
|
+
* `nuxt-remote` on branch `main` — not a branch called `main/nuxt-remote`. But
|
|
222
|
+
* the URL alone cannot tell that: `.../tree/release/v2` is a branch `release/v2`
|
|
223
|
+
* (no folder), while `.../tree/release/v2/app` could be branch `release` with
|
|
224
|
+
* folder `v2/app`. Only the remote knows. So we offer EVERY split, longest ref
|
|
225
|
+
* first, so a genuinely slashed branch keeps resolving exactly as it did before
|
|
226
|
+
* deep URLs existed, and the shorter splits are only consulted when the longer
|
|
227
|
+
* one turned out not to be a ref at all.
|
|
228
|
+
*
|
|
229
|
+
* Order is therefore load-bearing: candidate 0 is the pre-deep-URL behaviour.
|
|
230
|
+
*/
|
|
231
|
+
export function refDirCandidates(refAndDir) {
|
|
232
|
+
const segs = String(refAndDir).split('/').filter(Boolean)
|
|
233
|
+
const out = []
|
|
234
|
+
for (let i = segs.length; i >= 1; i--) {
|
|
235
|
+
out.push({ ref: segs.slice(0, i).join('/'), dir: segs.slice(i).join('/') })
|
|
236
|
+
}
|
|
237
|
+
return out
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Which candidate split of a deep URL is real? Probes longest-ref-first until
|
|
242
|
+
* one resolves; ONE extra `ls-remote` per candidate beyond the first, and only
|
|
243
|
+
* when the URL really is deep.
|
|
244
|
+
*
|
|
245
|
+
* A non-ref failure (no access, network) is the same for every candidate, so it
|
|
246
|
+
* is returned immediately rather than burning probes that cannot succeed.
|
|
247
|
+
*
|
|
248
|
+
* @returns {{ok:true, sha:string, remoteUrl:string, ref:string, dir:string, viaSha?:boolean}
|
|
249
|
+
* | {ok:false, kind:string, why?:string, detail?:string, tried?:string[]}}
|
|
250
|
+
* `tried` lists every ref asked about, for the all-missing error message.
|
|
251
|
+
*/
|
|
252
|
+
export function resolveRefDir({ owner, repo, refAndDir, timeoutMs = 60000, run = runGit }) {
|
|
253
|
+
const candidates = refDirCandidates(refAndDir)
|
|
254
|
+
|
|
255
|
+
for (const c of candidates) {
|
|
256
|
+
const probe = probeGitAccess({ owner, repo, ref: c.ref, timeoutMs, run })
|
|
257
|
+
if (probe.ok) return { ...probe, ref: c.ref, dir: c.dir }
|
|
258
|
+
if (probe.kind !== 'ref-missing') return probe
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
return { ok: false, kind: 'ref-missing', tried: candidates.map((c) => c.ref) }
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Which git method to materialize the tree with. Precedence: CLI > env > auto.
|
|
266
|
+
*
|
|
267
|
+
* `auto` = try `clone`, fall back to `init`+`fetch`. The escape hatch exists for
|
|
268
|
+
* locked-down corporate git setups where one of the two misbehaves; there is no
|
|
269
|
+
* reason to reach for it otherwise.
|
|
270
|
+
*
|
|
271
|
+
* @returns {'auto'|'clone'|'fetch'}
|
|
272
|
+
*/
|
|
273
|
+
export function resolveGitMethod({ env = process.env, argv = {} } = {}) {
|
|
274
|
+
const raw = String(argv.gitMethod || env.MONO_SYNC_GIT_METHOD || 'auto').toLowerCase()
|
|
275
|
+
return raw === 'clone' || raw === 'fetch' ? raw : 'auto'
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** `clone` refuses a non-empty target, and a failed attempt can leave debris. */
|
|
279
|
+
function resetDir(dir) {
|
|
280
|
+
fs.rmSync(dir, { recursive: true, force: true })
|
|
281
|
+
fs.mkdirSync(dir, { recursive: true })
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* One shallow `clone`. Measurably the fastest way to get a tree — see
|
|
286
|
+
* `materializeGitTree`. Handles a branch, a lightweight tag or an annotated tag
|
|
287
|
+
* via `--branch`, but NOT a raw commit SHA, which is why `fetchIntoDir` exists.
|
|
288
|
+
*/
|
|
289
|
+
function cloneIntoDir({ remoteUrl, ref, destDir, timeoutMs, run }) {
|
|
290
|
+
resetDir(destDir)
|
|
291
|
+
const r = run(
|
|
292
|
+
['clone', '--quiet', '--depth=1', '--no-tags', '--single-branch', '--branch', ref, remoteUrl, destDir],
|
|
293
|
+
{ timeoutMs },
|
|
294
|
+
)
|
|
295
|
+
return r.ok ? { ok: true } : { ok: false, detail: firstFatal(r.stderr) || r.error?.message || `exit ${r.code}` }
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* `init` + `remote add` + `fetch --depth=1 <want>` + `reset --hard`. Slower than
|
|
300
|
+
* `clone` (five git processes instead of one) but it is the only path that can
|
|
301
|
+
* take a raw 40-hex commit SHA as the want. `reset` rather than `checkout`
|
|
302
|
+
* because a fresh `init` leaves an unborn HEAD.
|
|
303
|
+
*/
|
|
304
|
+
function fetchIntoDir({ remoteUrl, ref, destDir, timeoutMs, run }) {
|
|
305
|
+
resetDir(destDir)
|
|
306
|
+
|
|
307
|
+
const step = (args, what) => {
|
|
308
|
+
const r = run(args, { cwd: destDir, timeoutMs })
|
|
309
|
+
return r.ok ? null : { ok: false, detail: `${what}: ${firstFatal(r.stderr) || r.error?.message || `exit ${r.code}`}` }
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
const want = isSha40(ref) ? String(ref).toLowerCase() : ref
|
|
313
|
+
|
|
314
|
+
return (
|
|
315
|
+
step(['init', '--quiet'], 'init') ??
|
|
316
|
+
step(['remote', 'add', 'origin', remoteUrl], 'remote add') ??
|
|
317
|
+
step(['fetch', '--quiet', '--depth=1', '--no-tags', '--no-recurse-submodules', 'origin', want], 'fetch') ??
|
|
318
|
+
step(['reset', '--quiet', '--hard', 'FETCH_HEAD'], 'checkout') ?? { ok: true }
|
|
319
|
+
)
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Populate `destDir` with the tree at `ref` (or a 40-hex SHA). No `unzip`, no
|
|
324
|
+
* tarball, no REST call.
|
|
325
|
+
*
|
|
326
|
+
* Tries `clone` first, then `init`+`fetch`. Both speak the identical wire
|
|
327
|
+
* protocol and fetch the identical pack — the gap is process spawns, which are
|
|
328
|
+
* expensive on Windows. Measured on this machine against a 1.8 MB / 55-file app
|
|
329
|
+
* repo, three runs each:
|
|
330
|
+
*
|
|
331
|
+
* clone --depth=1 3.7 / 3.8 / 3.8 s
|
|
332
|
+
* init + fetch + reset 7.0 / 7.1 / 7.2 s
|
|
333
|
+
* one bare git process ~0.44 s <- x5 for init/remote/fetch/reset/rev-parse
|
|
334
|
+
*
|
|
335
|
+
* So `clone` roughly halves it, and the four extra spawns account for nearly the
|
|
336
|
+
* whole difference. Keeping `fetch` as the fallback costs nothing when `clone`
|
|
337
|
+
* works and is REQUIRED anyway when `ref` is a pinned commit SHA, which
|
|
338
|
+
* `clone --branch` cannot express.
|
|
339
|
+
*
|
|
340
|
+
* A persistent local repo that `pull`s incrementally was measured too: 3.2 s,
|
|
341
|
+
* only ~0.6 s better than a cold clone, because these app repos are single-digit
|
|
342
|
+
* MB. That does not pay for keeping a live `.git` (and its shallow grafts, stale
|
|
343
|
+
* worktree metadata and corruption modes) between runs, so it is not built.
|
|
344
|
+
* (`git archive --remote` is not an option at all — GitHub disables
|
|
345
|
+
* `upload-archive`.)
|
|
346
|
+
*
|
|
347
|
+
* @returns {{sha: string, method: 'clone'|'fetch'}} `sha` is what actually
|
|
348
|
+
* landed. It may differ from the probe SHA if the branch advanced in between,
|
|
349
|
+
* and it is THIS one the commit cache must record.
|
|
350
|
+
*/
|
|
351
|
+
export function materializeGitTree({
|
|
352
|
+
remoteUrl,
|
|
353
|
+
ref,
|
|
354
|
+
sha,
|
|
355
|
+
destDir,
|
|
356
|
+
timeoutMs = 180000,
|
|
357
|
+
run = runGit,
|
|
358
|
+
method = 'auto',
|
|
359
|
+
}) {
|
|
360
|
+
// A raw commit SHA can only be a fetch `want`; `--branch` will not take one.
|
|
361
|
+
// That beats an explicit `method: 'clone'`, rather than failing an app that is
|
|
362
|
+
// legitimately pinned to a commit.
|
|
363
|
+
const order = isSha40(ref) ? ['fetch'] : method === 'auto' ? ['clone', 'fetch'] : [method]
|
|
364
|
+
|
|
365
|
+
const failures = []
|
|
366
|
+
let used = null
|
|
367
|
+
|
|
368
|
+
for (const attempt of order) {
|
|
369
|
+
const fn = attempt === 'clone' ? cloneIntoDir : fetchIntoDir
|
|
370
|
+
const res = fn({ remoteUrl, ref, destDir, timeoutMs, run })
|
|
371
|
+
if (res.ok) {
|
|
372
|
+
used = attempt
|
|
373
|
+
break
|
|
374
|
+
}
|
|
375
|
+
// `init+fetch` rather than `fetch`, because fetchIntoDir's detail already
|
|
376
|
+
// names which of its four steps broke — otherwise this reads "fetch failed:
|
|
377
|
+
// fetch: ...".
|
|
378
|
+
failures.push(`${attempt === 'clone' ? 'clone' : 'init+fetch'} failed: ${res.detail}`)
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
if (!used) {
|
|
382
|
+
fs.rmSync(destDir, { recursive: true, force: true })
|
|
383
|
+
throw new Error(`git could not materialize ${ref} (${failures.join('; ')})`)
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
const rev = run(['rev-parse', 'HEAD'], { cwd: destDir, timeoutMs: 15000 })
|
|
387
|
+
return { sha: rev.ok ? rev.stdout.trim() : sha, method: used }
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Move `repoDir/<dir>` to `destDir` — the folder-picking half of a deep-URL sync.
|
|
392
|
+
*
|
|
393
|
+
* Both dirs are staging dirs under `.mono/apps`, so the same volume: a rename,
|
|
394
|
+
* not a copy. A missing folder is a user error naming the URL's folder, not a
|
|
395
|
+
* git failure — the ref resolved fine, the path just isn't in the tree.
|
|
396
|
+
*/
|
|
397
|
+
export function pickSubtree(repoDir, dir, destDir) {
|
|
398
|
+
const sub = path.join(repoDir, ...String(dir).split('/').filter(Boolean))
|
|
399
|
+
|
|
400
|
+
let st = null
|
|
401
|
+
try { st = fs.statSync(sub) } catch { /* not there — reported below */ }
|
|
402
|
+
|
|
403
|
+
if (!st?.isDirectory()) {
|
|
404
|
+
throw new Error(`Folder "${dir}" not found in the repository (from the /tree/ URL).`)
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
fs.mkdirSync(path.dirname(destDir), { recursive: true })
|
|
408
|
+
fs.renameSync(sub, destDir)
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* Move a fully-built staging dir into place, keeping the old tree until the new
|
|
413
|
+
* one is committed.
|
|
414
|
+
*
|
|
415
|
+
* The previous code did `rmrf(outDir)` BEFORE downloading, so any failure left
|
|
416
|
+
* the app directory gone and the next `mono prepare` / dev server broken. Both
|
|
417
|
+
* transports now build into a stage and swap.
|
|
418
|
+
*/
|
|
419
|
+
/**
|
|
420
|
+
* EPERM/EBUSY: Windows, something holds a handle on the directory (editor,
|
|
421
|
+
* indexer, antivirus, dev server). EXDEV: different volume. ENOTEMPTY/EACCES:
|
|
422
|
+
* races. All mean "try the slower path", never "give up".
|
|
423
|
+
*/
|
|
424
|
+
const LOCKISH = ['EPERM', 'EBUSY', 'ENOTEMPTY', 'EXDEV', 'EACCES']
|
|
425
|
+
const isLockish = (e) => LOCKISH.includes(e?.code)
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* Refill `outDir` from `stageDir` without renaming or deleting `outDir` itself.
|
|
429
|
+
*
|
|
430
|
+
* On Windows a directory some process is watching cannot be RENAMED, but its
|
|
431
|
+
* contents can still be created, overwritten and deleted — measured on a
|
|
432
|
+
* developer machine where `rename` on every source directory failed while file
|
|
433
|
+
* writes and recursive subdirectory deletes both succeeded. When the swap cannot
|
|
434
|
+
* park the old tree, replacing the contents in place is the only move left.
|
|
435
|
+
*
|
|
436
|
+
* The cost is atomicity: for the duration of this call `outDir` is neither the
|
|
437
|
+
* old tree nor the new one. That beats the alternative, which was to abort and
|
|
438
|
+
* leave the app un-syncable on such a machine.
|
|
439
|
+
*/
|
|
440
|
+
function replaceContents(outDir, stageDir) {
|
|
441
|
+
fs.mkdirSync(outDir, { recursive: true })
|
|
442
|
+
for (const entry of fs.readdirSync(outDir)) {
|
|
443
|
+
fs.rmSync(path.join(outDir, entry), { recursive: true, force: true })
|
|
444
|
+
}
|
|
445
|
+
for (const entry of fs.readdirSync(stageDir)) {
|
|
446
|
+
fs.cpSync(path.join(stageDir, entry), path.join(outDir, entry), { recursive: true })
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
export function swapIntoPlace(stageDir, outDir) {
|
|
451
|
+
fs.mkdirSync(path.dirname(outDir), { recursive: true })
|
|
452
|
+
|
|
453
|
+
const backup = `${outDir}.old-${process.pid}-${Date.now().toString(36)}`
|
|
454
|
+
let parked = false
|
|
455
|
+
|
|
456
|
+
if (fs.existsSync(outDir)) {
|
|
457
|
+
try {
|
|
458
|
+
fs.renameSync(outDir, backup)
|
|
459
|
+
parked = true
|
|
460
|
+
} catch (e) {
|
|
461
|
+
// BOTH renames can fail this way and both must degrade — guarding only the
|
|
462
|
+
// second one (as this did) meant a machine that denies directory renames
|
|
463
|
+
// could clone an app once and then never update it: every later sync threw
|
|
464
|
+
// EPERM here, before any fallback ran.
|
|
465
|
+
if (!isLockish(e)) throw e
|
|
466
|
+
replaceContents(outDir, stageDir)
|
|
467
|
+
return
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
try {
|
|
472
|
+
fs.renameSync(stageDir, outDir)
|
|
473
|
+
} catch (e) {
|
|
474
|
+
if (!isLockish(e)) {
|
|
475
|
+
if (parked) {
|
|
476
|
+
try { fs.renameSync(backup, outDir) } catch { }
|
|
477
|
+
}
|
|
478
|
+
throw e
|
|
479
|
+
}
|
|
480
|
+
replaceContents(outDir, stageDir)
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
if (parked) fs.rmSync(backup, { recursive: true, force: true })
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/** Delete `.tmp-*` / `*.old-*` left behind by a crashed run. The `.mono/clone.lock` guarantees no live run owns them. */
|
|
487
|
+
export function sweepStrayStages(baseDir) {
|
|
488
|
+
let entries
|
|
489
|
+
try {
|
|
490
|
+
entries = fs.readdirSync(baseDir)
|
|
491
|
+
} catch {
|
|
492
|
+
return 0
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
let removed = 0
|
|
496
|
+
for (const name of entries) {
|
|
497
|
+
if (!isStageDebris(name)) continue
|
|
498
|
+
try {
|
|
499
|
+
fs.rmSync(path.join(baseDir, name), { recursive: true, force: true })
|
|
500
|
+
removed++
|
|
501
|
+
} catch { }
|
|
502
|
+
}
|
|
503
|
+
return removed
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/**
|
|
507
|
+
* Parse a GitHub app URL. Moved here from `bin/mono-clone.mjs` — one caller, and
|
|
508
|
+
* it gains test coverage for free.
|
|
509
|
+
*/
|
|
510
|
+
export function parseGithubUrl(input) {
|
|
511
|
+
let u
|
|
512
|
+
try {
|
|
513
|
+
u = new URL(String(input))
|
|
514
|
+
} catch {
|
|
515
|
+
throw new Error(`Invalid URL: ${input}`)
|
|
516
|
+
}
|
|
517
|
+
if (u.hostname !== 'github.com') {
|
|
518
|
+
throw new Error(`Only github.com URLs are supported: ${input}`)
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
const parts = u.pathname.replace(/^\/+|\/+$/g, '').split('/')
|
|
522
|
+
if (parts.length < 2) throw new Error(`Invalid GitHub url: ${input}`)
|
|
523
|
+
|
|
524
|
+
const owner = parts[0]
|
|
525
|
+
const repo = parts[1].replace(/\.git$/, '')
|
|
526
|
+
|
|
527
|
+
let ref = 'main'
|
|
528
|
+
if (parts[2] === 'tree' && parts.length >= 4) {
|
|
529
|
+
ref = parts.slice(3).join('/')
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
return { owner, repo, ref }
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* Which transport to use for an app. Precedence: CLI flag > env > per-app > auto.
|
|
537
|
+
*
|
|
538
|
+
* A global knob inside `mono.config.ts` would NOT work: `extractAppsArrayText`
|
|
539
|
+
* in mono-clone slices out only the `apps:` array, so a sibling top-level key is
|
|
540
|
+
* invisible to it. Hence the env var. The per-app key needs no parser change —
|
|
541
|
+
* `parseAppsArray` `Function()`-evals the whole app object literal.
|
|
542
|
+
*
|
|
543
|
+
* @returns {'auto'|'git'|'token'}
|
|
544
|
+
*/
|
|
545
|
+
export function resolveTransport({ app = {}, env = process.env, argv = {} } = {}) {
|
|
546
|
+
const raw = String(argv.transport || env.MONO_SYNC_TRANSPORT || app.transport || 'auto').toLowerCase()
|
|
547
|
+
return raw === 'git' || raw === 'token' ? raw : 'auto'
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/**
|
|
551
|
+
* Read a cached NEGATIVE access result, so a non-collaborator does not pay a
|
|
552
|
+
* failing probe on every single run. Positives are never cached — the same
|
|
553
|
+
* `ls-remote` is also our change-detection SHA, so skipping it would put the
|
|
554
|
+
* REST call back.
|
|
555
|
+
*/
|
|
556
|
+
export function accessCacheGet(cache, slug, { now = Date.now(), ttlMs } = {}) {
|
|
557
|
+
const entry = cache?.[slug]
|
|
558
|
+
if (!entry || entry.access !== 'none' || !Number.isFinite(entry.checkedAt)) return null
|
|
559
|
+
if (now - entry.checkedAt > ttlMs) return null
|
|
560
|
+
return entry
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
export function accessCacheSet(cache, slug, { why, detail, now = Date.now() } = {}) {
|
|
564
|
+
cache[slug] = { access: 'none', why, detail, checkedAt: now }
|
|
565
|
+
return cache
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/** Minimal argv reader for `--transport=<x>` / `--git-method=<x>` / `--recheck-access` / `--no-prune`. */
|
|
569
|
+
export function parseSyncArgv(argv = []) {
|
|
570
|
+
const out = {}
|
|
571
|
+
for (const raw of argv) {
|
|
572
|
+
const arg = String(raw)
|
|
573
|
+
if (arg === '--recheck-access') out.recheckAccess = true
|
|
574
|
+
else if (arg === '--no-prune') out.prune = false
|
|
575
|
+
else if (arg === '--prune') out.prune = true
|
|
576
|
+
else if (arg.startsWith('--transport=')) out.transport = arg.slice('--transport='.length)
|
|
577
|
+
else if (arg.startsWith('--git-method=')) out.gitMethod = arg.slice('--git-method='.length)
|
|
578
|
+
}
|
|
579
|
+
return out
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/** Human "5m ago" / "3h ago" for the cached-negative message. */
|
|
583
|
+
export function ago(ts, now = Date.now()) {
|
|
584
|
+
const mins = Math.max(0, Math.round((now - ts) / 60000))
|
|
585
|
+
return mins < 60 ? `${mins}m ago` : `${Math.round(mins / 60)}h ago`
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/** Unique-ish staging dir name, kept on the SAME volume as `outDir` so the swap can rename. */
|
|
589
|
+
export function stagePathFor(baseDir, name) {
|
|
590
|
+
return path.join(baseDir, `.tmp-${name}-${process.pid}-${Math.random().toString(36).slice(2, 8)}`)
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
// Re-exported for tests that want a temp root without importing `node:os`.
|
|
594
|
+
export const tmpRoot = () => os.tmpdir()
|
|
595
|
+
|
|
596
|
+
// --- pruning apps removed from mono.config -----------------------------------
|
|
597
|
+
//
|
|
598
|
+
// `mono sync` used to only ever ADD. Deleting an app from `mono.config.ts`'s
|
|
599
|
+
// `apps[]` left its clone on disk, and that clone is NOT inert: `monoAlias`,
|
|
600
|
+
// `monoEcosystem` and `monoMissingApps` all discover remotes by SCANNING the
|
|
601
|
+
// `.mono/apps/` directory listing, so a removed app kept producing `@<name>`
|
|
602
|
+
// aliases and kept contributing routes/layouts/stores — from a snapshot sync
|
|
603
|
+
// would never refresh again. These helpers are the delete half of that.
|
|
604
|
+
|
|
605
|
+
/** The one place clones live. Not per-app configurable: everything in `src/` (the vite `'/.mono/apps/'` markers, `MONO_APPS_DIR` in mono-tsconfig) hardcodes it. */
|
|
606
|
+
export const MONO_APPS_DIR = '.mono/apps'
|
|
607
|
+
|
|
608
|
+
/** Staging debris owned by `sweepStrayStages` — never an app, never pruned as one. */
|
|
609
|
+
const isStageDebris = (name) => /^\.tmp-/.test(name) || /\.old-\d+-[a-z0-9]+$/.test(name)
|
|
610
|
+
|
|
611
|
+
/**
|
|
612
|
+
* Directories under `appsDir` that no configured app owns.
|
|
613
|
+
*
|
|
614
|
+
* Keyed on the app NAME only. `parseGithubUrl` can throw on a malformed `url`,
|
|
615
|
+
* and a config typo must never be able to delete a tree — so the URL plays no
|
|
616
|
+
* part in deciding what survives here (it only prunes cache entries below).
|
|
617
|
+
*
|
|
618
|
+
* @param {string} appsDir absolute `.mono/apps`
|
|
619
|
+
* @param {Iterable<string>} keepNames configured `apps[].name`
|
|
620
|
+
* @returns {string[]} directory names to delete
|
|
621
|
+
*/
|
|
622
|
+
export function orphanAppDirs(appsDir, keepNames) {
|
|
623
|
+
let entries
|
|
624
|
+
try {
|
|
625
|
+
entries = fs.readdirSync(appsDir, { withFileTypes: true })
|
|
626
|
+
} catch {
|
|
627
|
+
return []
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
const keep = new Set(keepNames)
|
|
631
|
+
|
|
632
|
+
return entries
|
|
633
|
+
.filter((e) => e.isDirectory())
|
|
634
|
+
.map((e) => e.name)
|
|
635
|
+
.filter((name) => !keep.has(name) && !isStageDebris(name))
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
/**
|
|
639
|
+
* Assert a prune target really sits inside `.mono/apps`, and hand back the path.
|
|
640
|
+
*
|
|
641
|
+
* `orphanAppDirs` already decides WHAT to delete, and every app in `apps[]` —
|
|
642
|
+
* including one pointed at a local checkout by `path` — keeps its directory. So
|
|
643
|
+
* this is not the correctness guard; it is the one that survives a refactor.
|
|
644
|
+
*
|
|
645
|
+
* The history is the reason it exists. `MonoAppConfig.path` used to feed the
|
|
646
|
+
* clone destination, which fed this prune root, so a config typo could aim
|
|
647
|
+
* `rmrf` at any folder on the machine. `path` is now read-only — the directory
|
|
648
|
+
* an app is READ from, in every command — and never reaches here; but the blast
|
|
649
|
+
* radius should be bounded by something stronger than that remaining true.
|
|
650
|
+
*
|
|
651
|
+
* Rejects `..` traversal, an absolute path elsewhere, and the apps dir itself.
|
|
652
|
+
*
|
|
653
|
+
* @param {string} appsDir absolute `.mono/apps`
|
|
654
|
+
* @param {string} name directory name from {@link orphanAppDirs}
|
|
655
|
+
* @returns {string} absolute path safe to delete
|
|
656
|
+
* @throws if the target resolves outside `appsDir`
|
|
657
|
+
*/
|
|
658
|
+
export function appDirToPrune(appsDir, name) {
|
|
659
|
+
const root = path.resolve(appsDir)
|
|
660
|
+
const target = path.resolve(root, name)
|
|
661
|
+
const rel = path.relative(root, target)
|
|
662
|
+
|
|
663
|
+
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) {
|
|
664
|
+
throw new Error(
|
|
665
|
+
`[mono] refusing to prune '${name}': ${target} is not inside ${root}. ` +
|
|
666
|
+
'Only directories under .mono/apps are ever deleted.',
|
|
667
|
+
)
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
return target
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/** Commit-cache keys (`owner/repo@ref`) no configured app produces. */
|
|
674
|
+
export function staleCacheKeys(commitCache, keepKeys) {
|
|
675
|
+
const keep = new Set(keepKeys)
|
|
676
|
+
return Object.keys(commitCache ?? {}).filter((key) => !keep.has(key))
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
/** Access-cache keys (`owner/repo`) no configured app references. Access is repo-level, so this is keyed on the slug, not the ref. */
|
|
680
|
+
export function staleAccessKeys(accessCache, keepSlugs) {
|
|
681
|
+
const keep = new Set(keepSlugs)
|
|
682
|
+
return Object.keys(accessCache ?? {}).filter((slug) => !keep.has(slug))
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/**
|
|
686
|
+
* Drop `@<name>/*` + `@<name>-root/*` from the generated `.mono/tsconfig.json`.
|
|
687
|
+
*
|
|
688
|
+
* `mono prepare` rebuilds that file wholesale from the directory scan, so this
|
|
689
|
+
* only covers the window between `mono sync` and the next `mono prepare` — but
|
|
690
|
+
* in that window a stale mapping points TypeScript at a directory that no longer
|
|
691
|
+
* exists, which is worse than having no mapping at all.
|
|
692
|
+
*
|
|
693
|
+
* Plain JSON on purpose: the file is emitted by `pkg-types`' `writeTSConfig`, so
|
|
694
|
+
* it is never JSONC, and this `.mjs` cannot import `pkg-types`. A missing or
|
|
695
|
+
* malformed file is a silent no-op — `mono prepare` regenerates it either way.
|
|
696
|
+
*
|
|
697
|
+
* @returns {string[]} the path keys that were removed
|
|
698
|
+
*/
|
|
699
|
+
export function pruneMonoTsconfigPaths(monoTsconfigFile, removedNames, { rootSuffix = '-root' } = {}) {
|
|
700
|
+
let json
|
|
701
|
+
try {
|
|
702
|
+
json = JSON.parse(fs.readFileSync(monoTsconfigFile, 'utf8'))
|
|
703
|
+
} catch {
|
|
704
|
+
return []
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
const paths = json?.compilerOptions?.paths
|
|
708
|
+
if (!paths || typeof paths !== 'object') return []
|
|
709
|
+
|
|
710
|
+
const removed = []
|
|
711
|
+
for (const name of removedNames) {
|
|
712
|
+
for (const key of [`@${name}/*`, `@${name}${rootSuffix}/*`]) {
|
|
713
|
+
if (key in paths) {
|
|
714
|
+
delete paths[key]
|
|
715
|
+
removed.push(key)
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
if (!removed.length) return []
|
|
721
|
+
|
|
722
|
+
if (!Object.keys(paths).length) delete json.compilerOptions.paths
|
|
723
|
+
|
|
724
|
+
try {
|
|
725
|
+
fs.writeFileSync(monoTsconfigFile, `${JSON.stringify(json, null, 2)}\n`, 'utf8')
|
|
726
|
+
} catch {
|
|
727
|
+
return []
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
return removed
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* Whether to prune apps that left the config. Precedence: CLI > env > default on.
|
|
735
|
+
*
|
|
736
|
+
* The escape hatch exists for a host whose `.mono/apps/` holds a clone placed
|
|
737
|
+
* there by hand, or one federated only by a CLONED app's config (`mono sync`
|
|
738
|
+
* reads the ROOT config's `apps[]` and nothing else, so such a directory looks
|
|
739
|
+
* orphaned to it).
|
|
740
|
+
*/
|
|
741
|
+
export function resolvePrune({ env = process.env, argv = {} } = {}) {
|
|
742
|
+
if (argv.prune === false) return false
|
|
743
|
+
if (argv.prune === true) return true
|
|
744
|
+
const raw = env.MONO_SYNC_PRUNE
|
|
745
|
+
if (raw === undefined || raw === '') return true
|
|
746
|
+
return !/^(0|false|no|off)$/i.test(String(raw))
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
// --- app sources -------------------------------------------------------------
|
|
750
|
+
// An app comes from a clone (`url`) or is read in place (`path`, a sibling in a
|
|
751
|
+
// mono-lith). `mono sync` only has work for the first kind, and only falls back
|
|
752
|
+
// to the `url` when the `path` directory is absent (an app lifted out of the
|
|
753
|
+
// lith into a standalone checkout). Pure helpers; `isDir` is injectable for
|
|
754
|
+
// tests.
|
|
755
|
+
|
|
756
|
+
/**
|
|
757
|
+
* Why an `apps[]` entry is unusable, or `null` when it is fine.
|
|
758
|
+
*
|
|
759
|
+
* @param {any} app
|
|
760
|
+
* @returns {string | null}
|
|
761
|
+
*/
|
|
762
|
+
export function validateAppEntry(app) {
|
|
763
|
+
if (!app || typeof app !== 'object') return 'not an object'
|
|
764
|
+
if (typeof app.name !== 'string' || !app.name.trim()) return 'missing "name"'
|
|
765
|
+
const hasUrl = typeof app.url === 'string' && app.url.trim().length > 0
|
|
766
|
+
const hasPath = app.path != null
|
|
767
|
+
if (hasPath && (typeof app.path !== 'string' || !app.path.trim())) {
|
|
768
|
+
return '"path" must be a non-empty string'
|
|
769
|
+
}
|
|
770
|
+
if (!hasUrl && !hasPath) return 'needs at least one of "url" / "path"'
|
|
771
|
+
return null
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
/**
|
|
775
|
+
* Where `mono sync` should take this app from.
|
|
776
|
+
*
|
|
777
|
+
* - `{ kind: 'path', dir }` — `path` names an existing directory: nothing to clone.
|
|
778
|
+
* - `{ kind: 'clone' }` — no `path`: clone from `url` as always.
|
|
779
|
+
* - `{ kind: 'path-missing', dir }` — `path` declared but absent: clone from
|
|
780
|
+
* `url` if there is one, otherwise the caller fails the app.
|
|
781
|
+
*
|
|
782
|
+
* @param {{ path?: string }} app
|
|
783
|
+
* @param {{ cwd?: string, isDir?: (dir: string) => boolean }} [opts]
|
|
784
|
+
*/
|
|
785
|
+
export function resolveAppSource(app, { cwd = process.cwd(), isDir = isDirectory } = {}) {
|
|
786
|
+
const declared = typeof app?.path === 'string' ? app.path.trim() : ''
|
|
787
|
+
if (!declared) return { kind: 'clone' }
|
|
788
|
+
const dir = path.isAbsolute(declared) ? declared : path.resolve(cwd, declared)
|
|
789
|
+
return isDir(dir) ? { kind: 'path', dir } : { kind: 'path-missing', dir }
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
function isDirectory(dir) {
|
|
793
|
+
try {
|
|
794
|
+
return fs.statSync(dir).isDirectory()
|
|
795
|
+
} catch {
|
|
796
|
+
return false
|
|
797
|
+
}
|
|
798
|
+
}
|