dreamteamer 0.46.0 → 0.47.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +63 -6
- package/package.json +4 -3
- package/skills/using-dreamteamer/SKILL.md +6 -4
- package/skills/using-dreamteamer/references/extensions.md +8 -0
- package/skills/using-dreamteamer/references/getting-started.md +8 -8
- package/skills/using-dreamteamer/references/setup.md +120 -0
- package/src/checkout.js +260 -4
- package/src/cli.js +90 -18
- package/src/doctor.js +10 -0
- package/src/extensions.js +25 -6
- package/src/init.js +39 -14
- package/src/install-modules.js +382 -0
- package/src/setup-contract.js +72 -0
- package/src/setup.js +420 -0
- package/src/update.js +89 -0
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
// `dt install <spec…>` — bring a module into this workspace: resolve the closure and refuse early,
|
|
2
|
+
// npm install --save-exact, verify, compile (and restore on refusal), the safe part of the module's
|
|
3
|
+
// setup, one scoped commit. The engine names no module and resolves no version itself: npm resolves
|
|
4
|
+
// ranges, and the closure is the presence graph modules already declare (`dreamteamer.dependencies`,
|
|
5
|
+
// the key compile enforces for cross-module references). A folder of tarballs (`--from <dir>`) stands
|
|
6
|
+
// in for the registry — the offline form candidates and acceptance use.
|
|
7
|
+
//
|
|
8
|
+
// The other `install` forms — make THIS checkout ready, `--clone`, `repos/<id>`, `--hook` — stay in
|
|
9
|
+
// src/checkout.js and src/init.js; this file is only the spec form.
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import os from 'node:os';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import zlib from 'node:zlib';
|
|
14
|
+
import { spawnSync, execFileSync } from 'node:child_process';
|
|
15
|
+
import { satisfies } from './semver.js';
|
|
16
|
+
import { engineVersion } from './runtime.js';
|
|
17
|
+
import { parseEnvValues } from './env-vars.js';
|
|
18
|
+
import { compile, discoverModules, staleness } from './compile.js';
|
|
19
|
+
import { resolveNpm, childEnv } from './checkout.js';
|
|
20
|
+
import { units, runUnit, fillInputs, parseInputFlags, parseAllow, skippedUnits, fold, SetupUsage, EXIT, ttyIO, droppedKeys } from './setup.js';
|
|
21
|
+
|
|
22
|
+
const EXACT = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;
|
|
23
|
+
/** Numeric major.minor.patch order; a prerelease sorts below its release. */
|
|
24
|
+
export function compareVersions(a, b) {
|
|
25
|
+
const pa = String(a).split(/[-+]/)[0].split('.').map(Number), pb = String(b).split(/[-+]/)[0].split('.').map(Number);
|
|
26
|
+
for (let i = 0; i < 3; i++) if ((pa[i] ?? 0) !== (pb[i] ?? 0)) return (pa[i] ?? 0) - (pb[i] ?? 0);
|
|
27
|
+
return (a.includes('-') ? 0 : 1) - (b.includes('-') ? 0 : 1);
|
|
28
|
+
}
|
|
29
|
+
export const NPM_FLOOR = '>=7.0.0';
|
|
30
|
+
|
|
31
|
+
export class InstallRefusal extends Error { constructor(m) { super(m); this.code = EXIT.failed; } }
|
|
32
|
+
const refuse = (m) => new InstallRefusal(m);
|
|
33
|
+
|
|
34
|
+
// ---- reading manifests ----------------------------------------------------------------------------
|
|
35
|
+
|
|
36
|
+
/** `package/package.json` out of an npm tarball: gunzip, then walk the ustar headers (512-byte
|
|
37
|
+
* blocks; the size is octal at offset 124; a `./` prefix is tolerated). No dependency, no shell. */
|
|
38
|
+
export function readTarballManifest(file) {
|
|
39
|
+
const buf = zlib.gunzipSync(fs.readFileSync(file));
|
|
40
|
+
let at = 0;
|
|
41
|
+
while (at + 512 <= buf.length) {
|
|
42
|
+
const name = buf.toString('utf8', at, at + 100).replace(/\0.*$/s, '');
|
|
43
|
+
if (!name) break;
|
|
44
|
+
const size = parseInt(buf.toString('utf8', at + 124, at + 136).replace(/\0.*$/s, '').trim() || '0', 8);
|
|
45
|
+
const type = buf[at + 156];
|
|
46
|
+
const prefix = buf.toString('utf8', at + 345, at + 500).replace(/\0.*$/s, '');
|
|
47
|
+
const full = (prefix ? `${prefix}/${name}` : name).replace(/^\.\//, '');
|
|
48
|
+
if ((type === 48 || type === 0) && full === 'package/package.json') return JSON.parse(buf.toString('utf8', at + 512, at + 512 + size));
|
|
49
|
+
at += 512 + Math.ceil(size / 512) * 512;
|
|
50
|
+
}
|
|
51
|
+
throw refuse(`${file}: no package/package.json inside the tarball`);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Every tarball in a folder, indexed by package name, newest first (npm's own semver order via
|
|
55
|
+
* `satisfies`): file names are never parsed — `npm pack` writes `fix-a-1.0.0.tgz` for `@fix/a`. */
|
|
56
|
+
export function indexFolder(dir) {
|
|
57
|
+
const index = new Map();
|
|
58
|
+
if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) throw refuse(`--from ${dir}: not a folder`);
|
|
59
|
+
for (const f of fs.readdirSync(dir).filter((n) => n.endsWith('.tgz')).sort()) {
|
|
60
|
+
const file = path.join(dir, f);
|
|
61
|
+
let m;
|
|
62
|
+
try { m = readTarballManifest(file); } catch { continue; }
|
|
63
|
+
if (!m?.name || !m.version) continue;
|
|
64
|
+
(index.get(m.name) ?? index.set(m.name, []).get(m.name)).push({ version: m.version, file, manifest: m });
|
|
65
|
+
}
|
|
66
|
+
for (const list of index.values()) list.sort((a, b) => compareVersions(b.version, a.version));
|
|
67
|
+
return index;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const splitSpec = (spec) => {
|
|
71
|
+
const at = spec.startsWith('@') ? spec.indexOf('@', 1) : spec.indexOf('@');
|
|
72
|
+
return at > 0 ? { name: spec.slice(0, at), version: spec.slice(at + 1) } : { name: spec, version: null };
|
|
73
|
+
};
|
|
74
|
+
const isPathSpec = (spec, cwd) => (spec.startsWith('.') || path.isAbsolute(spec) || spec.startsWith('file:')) && fs.existsSync(path.resolve(cwd, spec.replace(/^file:/, '')));
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* One spec → its manifest and the spec npm will be handed. Kinds: `tarball` (a .tgz path, or a name
|
|
78
|
+
* resolved from `--from`), `folder` (a development link), `registry` (a name, read with one
|
|
79
|
+
* `npm view` — the only network call; `github:` and git URLs go the same way).
|
|
80
|
+
*/
|
|
81
|
+
export function readSpecManifest(spec, { from = null, index = null, npm = resolveNpm(), cwd = process.cwd() } = {}) {
|
|
82
|
+
if (isPathSpec(spec, cwd)) {
|
|
83
|
+
const abs = path.resolve(cwd, spec.replace(/^file:/, ''));
|
|
84
|
+
if (fs.statSync(abs).isDirectory()) {
|
|
85
|
+
const file = path.join(abs, 'package.json');
|
|
86
|
+
if (!fs.existsSync(file)) throw refuse(`${spec}: a folder with no package.json`);
|
|
87
|
+
return { kind: 'folder', spec: abs, manifest: JSON.parse(fs.readFileSync(file, 'utf8')) };
|
|
88
|
+
}
|
|
89
|
+
return { kind: 'tarball', spec: abs, manifest: readTarballManifest(abs) };
|
|
90
|
+
}
|
|
91
|
+
const { name, version } = splitSpec(spec);
|
|
92
|
+
if (from) {
|
|
93
|
+
const idx = index ?? indexFolder(from);
|
|
94
|
+
const candidates = idx.get(name) ?? [];
|
|
95
|
+
const pick = version ? candidates.find((c) => c.version === version) : candidates[0];
|
|
96
|
+
if (!pick) throw refuse(`no ${version ? `${name}@${version}` : name} in ${from}${candidates.length ? ` (it has ${candidates.map((c) => c.version).join(', ')})` : ''}`);
|
|
97
|
+
return { kind: 'tarball', spec: pick.file, manifest: pick.manifest };
|
|
98
|
+
}
|
|
99
|
+
if (!npm) throw refuse('cannot read the registry — node found, npm not on PATH');
|
|
100
|
+
const r = spawnSync(npm, ['view', spec, 'name', 'version', 'dreamteamer', 'peerDependencies', 'dependencies', '--json'], { encoding: 'utf8', cwd, env: childEnv(), timeout: 120_000 });
|
|
101
|
+
if (r.status !== 0) throw refuse(`npm view ${spec} failed${r.stderr ? ` — ${r.stderr.trim().split('\n').filter((l) => /E404|ETARGET|ENOTFOUND|EAI_AGAIN/.test(l))[0] ?? r.stderr.trim().split('\n')[0]}` : ''}`);
|
|
102
|
+
let out;
|
|
103
|
+
try { out = JSON.parse(r.stdout); } catch { throw refuse(`npm view ${spec}: unreadable answer`); }
|
|
104
|
+
const manifest = Array.isArray(out) ? out.at(-1) : out; // a range answers with every match; the last is the newest
|
|
105
|
+
if (!manifest?.name) throw refuse(`npm view ${spec}: no such package`);
|
|
106
|
+
return { kind: 'registry', spec: `${manifest.name}@${manifest.version}`, manifest };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// ---- the closure --------------------------------------------------------------------------------
|
|
110
|
+
|
|
111
|
+
/** The modules already here, by package name: version, whether it is a development link, its manifest. */
|
|
112
|
+
export function installedModules(ws) {
|
|
113
|
+
const out = new Map();
|
|
114
|
+
const { modules } = discoverModules(ws.root, ws.pkg);
|
|
115
|
+
for (const m of modules) {
|
|
116
|
+
let manifest = {};
|
|
117
|
+
try { manifest = JSON.parse(fs.readFileSync(path.join(m.root, 'package.json'), 'utf8')); } catch { /* a module with no manifest is not a package */ }
|
|
118
|
+
const name = manifest.name ?? m.name;
|
|
119
|
+
let linked = false;
|
|
120
|
+
try { linked = fs.lstatSync(path.join(ws.root, 'node_modules', name)).isSymbolicLink(); } catch { /* not under node_modules */ }
|
|
121
|
+
out.set(name, { name, version: manifest.version ?? null, linked, manifest, channel: m.channel });
|
|
122
|
+
}
|
|
123
|
+
return out;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Resolve the specs and the closure of their `dreamteamer.dependencies`, and refuse — before npm
|
|
128
|
+
* writes anything — a package that is not a module, an engine floor this engine does not meet, a
|
|
129
|
+
* ring, a version already installed differently, and `provides` conflicts in both directions.
|
|
130
|
+
* Returns the ordered install list (dependencies first) and the names already satisfied.
|
|
131
|
+
*/
|
|
132
|
+
export function resolveClosure(specs, { installed, from = null, npm = resolveNpm(), cwd = process.cwd(), engine = engineVersion() } = {}) {
|
|
133
|
+
const index = from ? indexFolder(from) : null;
|
|
134
|
+
const list = [];
|
|
135
|
+
const already = [];
|
|
136
|
+
const seen = new Map(); // name → entry
|
|
137
|
+
// a package an INSTALLED one already provides: present for the walk (never resolved again), and refused
|
|
138
|
+
// the moment it is asked for by name — before any of its dependencies are looked up anywhere
|
|
139
|
+
const providedBy = (name) => [...installed].find(([, i]) => (i.manifest?.dreamteamer?.provides ?? []).includes(name))?.[0] ?? null;
|
|
140
|
+
const judge = (entry, askedAs, stack = []) => {
|
|
141
|
+
const m = entry.manifest;
|
|
142
|
+
if (!m.dreamteamer || typeof m.dreamteamer !== 'object') throw refuse(`${m.name}@${m.version} is not a dreamteamer module (no dreamteamer key in its package.json)${stack.length ? ` — needed by ${stack.at(-1)}` : ''}`);
|
|
143
|
+
const provider = providedBy(m.name);
|
|
144
|
+
if (provider) throw refuse(`${provider} already provides ${m.name} — it is installed; nothing to add`);
|
|
145
|
+
const range = m.dreamteamer.engine;
|
|
146
|
+
if (range && satisfies(engine, range) === false) throw refuse(`${m.name}@${m.version} needs engine "${range}" — this is ${engine}; choose a version: dt install ${m.name}@<version>`);
|
|
147
|
+
const here = installed.get(m.name);
|
|
148
|
+
if (here?.linked) throw refuse(`${m.name} is a development link (not pinned) — remove the link to pin a version`);
|
|
149
|
+
if (here && here.version && here.version !== m.version && askedAs === 'spec') throw refuse(`${m.name} is installed at ${here.version}, not ${m.version} — move it on purpose: dt update ${m.name}@${m.version}`);
|
|
150
|
+
};
|
|
151
|
+
const walk = (spec, stack, askedAs) => {
|
|
152
|
+
// asked for by name and already provided: refuse by name, without reading any manifest
|
|
153
|
+
if (askedAs === 'spec' && !isPathSpec(spec, cwd)) { const p = providedBy(splitSpec(spec).name); if (p) throw refuse(`${p} already provides ${splitSpec(spec).name} — it is installed; nothing to add`); }
|
|
154
|
+
const entry = readSpecManifest(spec, { from, index, npm, cwd });
|
|
155
|
+
const name = entry.manifest.name;
|
|
156
|
+
if (stack.includes(name)) throw refuse(`ring in dreamteamer.dependencies: ${[...stack.slice(stack.indexOf(name)), name].join(' → ')}`);
|
|
157
|
+
if (seen.has(name)) {
|
|
158
|
+
// the same module asked for twice at different versions is a conflict, never a silent first-wins
|
|
159
|
+
const prev = seen.get(name).manifest.version;
|
|
160
|
+
if (askedAs === 'spec' && prev !== entry.manifest.version) throw refuse(`${name} is asked for at ${prev} and at ${entry.manifest.version} — one version per call`);
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
judge(entry, askedAs, stack);
|
|
164
|
+
const here = installed.get(name);
|
|
165
|
+
if (here && here.version === entry.manifest.version) { already.push(name); seen.set(name, entry); return; }
|
|
166
|
+
seen.set(name, entry);
|
|
167
|
+
for (const dep of entry.manifest.dreamteamer.dependencies ?? []) {
|
|
168
|
+
if ((installed.has(dep) || providedBy(dep)) && !stack.includes(dep)) continue; // present (or composed in): its own closure was judged when it came in
|
|
169
|
+
walk(dep, [...stack, name], 'dependency');
|
|
170
|
+
}
|
|
171
|
+
list.push(entry);
|
|
172
|
+
};
|
|
173
|
+
for (const s of specs) walk(s, [], 'spec');
|
|
174
|
+
// provides, both ways — against what is installed and within the call itself
|
|
175
|
+
const names = new Set(list.map((e) => e.manifest.name));
|
|
176
|
+
for (const e of list) {
|
|
177
|
+
const name = e.manifest.name;
|
|
178
|
+
for (const p of e.manifest.dreamteamer.provides ?? []) {
|
|
179
|
+
if (installed.has(p)) throw refuse(`${name} provides ${p}, which is installed — remove ${p} first (npm uninstall ${p}, then dt compile), or keep the small modules`);
|
|
180
|
+
if (names.has(p)) throw refuse(`${name} provides ${p} — install one or the other, not both in one call`);
|
|
181
|
+
}
|
|
182
|
+
for (const o of list) if (o !== e && (o.manifest.dreamteamer.provides ?? []).includes(name)) throw refuse(`${o.manifest.name} provides ${name} — install one or the other, not both in one call`);
|
|
183
|
+
}
|
|
184
|
+
return { list, already };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** The npm on PATH is at least NPM_FLOOR, or the refusal naming both. */
|
|
188
|
+
export function npmFloor(npm = resolveNpm()) {
|
|
189
|
+
if (!npm) return 'cannot install — node found, npm not on PATH';
|
|
190
|
+
const r = spawnSync(npm, ['--version'], { encoding: 'utf8', env: childEnv(), timeout: 30_000 });
|
|
191
|
+
const v = (r.stdout ?? '').trim();
|
|
192
|
+
if (r.status !== 0 || !EXACT.test(v)) return `cannot read npm's version (${r.stderr?.trim() || v || 'no output'})`;
|
|
193
|
+
return satisfies(v, NPM_FLOOR) === false ? `dt install needs npm >=${NPM_FLOOR.slice(2).replace(/\.0\.0$/, '')} (this is ${v}) — npm install -g npm` : null;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// ---- the verb -----------------------------------------------------------------------------------
|
|
197
|
+
|
|
198
|
+
const gitOk = (root, args) => { try { execFileSync('git', args, { cwd: root, stdio: 'ignore' }); return true; } catch { return false; } };
|
|
199
|
+
const gitIgnored = (root, rel) => gitOk(root, ['check-ignore', '-q', '--', rel]);
|
|
200
|
+
/** `git status --porcelain` of one path: '' when clean (modified AND untracked both count as dirty). */
|
|
201
|
+
const gitStatus = (root, rel) => { try { return execFileSync('git', ['status', '--porcelain', '--', rel], { cwd: root, encoding: 'utf8' }).trim(); } catch { return ''; } };
|
|
202
|
+
|
|
203
|
+
// ---- steps 2–4 and 5–6, shared with `dt update` (install one pin later) ----------------------------
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Steps 2–4: npm on the resolved list (the two files it rewrites copied aside), verify every package
|
|
207
|
+
* resolves at the version asked for, compile (a refusal restores the pre-image and prunes). Returns
|
|
208
|
+
* `{ fresh }`, or `{ code }`.
|
|
209
|
+
*/
|
|
210
|
+
export async function npmAndCompile(ws, list, { npm = resolveNpm(), open, json = false, log = console.log, hooks = {}, what = 'install' } = {}) {
|
|
211
|
+
const names = list.map((e) => e.manifest.name);
|
|
212
|
+
const pkgFile = path.join(ws.root, 'package.json'), lockFile = path.join(ws.root, 'package-lock.json');
|
|
213
|
+
const versionOf = (n) => { try { return JSON.parse(fs.readFileSync(path.join(ws.root, 'node_modules', n, 'package.json'), 'utf8')).version ?? null; } catch { return null; } };
|
|
214
|
+
// the pre-image: the two files npm rewrites, and the version each named package had (an update replaces one)
|
|
215
|
+
const before = { pkg: fs.readFileSync(pkgFile, 'utf8'), lock: fs.existsSync(lockFile) ? fs.readFileSync(lockFile, 'utf8') : null, versions: Object.fromEntries(names.map((n) => [n, versionOf(n)])) };
|
|
216
|
+
const args = ['install', '--save-exact', '--no-audit', '--no-fund', ...list.map((e) => e.spec)];
|
|
217
|
+
log(`▶ npm ${args.join(' ')}`);
|
|
218
|
+
const r = spawnSync(npm, args, { cwd: ws.root, stdio: json ? ['ignore', 2, 2] : 'inherit', env: childEnv(), timeout: 600_000 });
|
|
219
|
+
if (r.status !== 0) { console.error(`✖ npm exited ${r.status ?? r.error?.message} — package.json and package-lock.json may have changed; run the same command again to resume`); return { code: EXIT.failed }; }
|
|
220
|
+
if (hooks.afterNpm) hooks.afterNpm();
|
|
221
|
+
// 3. verify every package in the list resolves, at the version asked for (a folder link at whatever it holds)
|
|
222
|
+
const still = list.filter((e) => { const v = versionOf(e.manifest.name); return v === null || (e.kind !== 'folder' && v !== e.manifest.version); }).map((e) => e.manifest.name);
|
|
223
|
+
if (still.length) { console.error(`✖ npm exited 0, but ${still.join(', ')} still do${still.length === 1 ? 'es' : ''} not resolve in node_modules at the version asked for`); return { code: EXIT.failed }; }
|
|
224
|
+
// 4. compile — a refusal restores the pre-image and prunes
|
|
225
|
+
try {
|
|
226
|
+
const fresh = await open(ws.root);
|
|
227
|
+
const stdout = console.log;
|
|
228
|
+
if (json) console.log = console.error;
|
|
229
|
+
try { compile(fresh); } finally { console.log = stdout; }
|
|
230
|
+
return { fresh };
|
|
231
|
+
} catch (e) {
|
|
232
|
+
fs.writeFileSync(pkgFile, before.pkg);
|
|
233
|
+
if (before.lock !== null) fs.writeFileSync(lockFile, before.lock); else fs.rmSync(lockFile, { force: true });
|
|
234
|
+
// the packages this call added go, then npm prunes to the restored lockfile; an emptied scope folder goes too
|
|
235
|
+
for (const n of names) {
|
|
236
|
+
fs.rmSync(path.join(ws.root, 'node_modules', n), { recursive: true, force: true });
|
|
237
|
+
const scope = path.dirname(path.join(ws.root, 'node_modules', n));
|
|
238
|
+
try { if (n.startsWith('@') && fs.readdirSync(scope).length === 0) fs.rmdirSync(scope); } catch { /* not empty, or gone */ }
|
|
239
|
+
}
|
|
240
|
+
const back = spawnSync(npm, ['install', '--no-audit', '--no-fund'], { cwd: ws.root, stdio: 'ignore', env: childEnv(), timeout: 600_000 });
|
|
241
|
+
// the restore is checked, never assumed: npm's exit, and every package that had a version before the call is at it again
|
|
242
|
+
const notBack = names.filter((n) => before.versions[n] && versionOf(n) !== before.versions[n]);
|
|
243
|
+
if (back.status !== 0 || notBack.length) {
|
|
244
|
+
console.error(`✖ ${what} refused: ${e.message.split('\n')[0]}\n restore FAILED (npm exited ${back.status ?? back.error?.message})${notBack.length ? `: ${notBack.map((n) => `${n} is not back at ${before.versions[n]}`).join(', ')}` : ''} — package.json and package-lock.json were put back; node_modules was NOT: run npm install to bring it back`);
|
|
245
|
+
return { code: EXIT.failed };
|
|
246
|
+
}
|
|
247
|
+
console.error(`✖ ${what} refused: ${e.message.split('\n')[0]}\n package.json, package-lock.json and node_modules are as before the call`);
|
|
248
|
+
return { code: EXIT.failed };
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Steps 5–6: the safe part of the named packages' units (inputs filled leniently — npm has written,
|
|
254
|
+
* so a mistyped --input is a named warning, never an abort), then one scoped commit: the two files
|
|
255
|
+
* npm rewrites, .env.example if compile touched it, and every path an applied action reported that
|
|
256
|
+
* git does not ignore. Returns `{ code, results, committed, ignored }`.
|
|
257
|
+
*/
|
|
258
|
+
export async function setupAndCommit(ws, fresh, names, { subject, inputFlags = [], allow = new Set(), tty = false, noInput = true, io = null, processEnv = process.env, noCommit = false } = {}) {
|
|
259
|
+
const skipped = new Set(skippedUnits(fresh));
|
|
260
|
+
const fresh_units = units(fresh).filter((u) => names.includes(u.module) && !skipped.has(u.id));
|
|
261
|
+
let code = EXIT.done;
|
|
262
|
+
const results = [];
|
|
263
|
+
let ignored = [];
|
|
264
|
+
if (fresh_units.length) {
|
|
265
|
+
const term = tty && !noInput && !io ? ttyIO() : null;
|
|
266
|
+
try {
|
|
267
|
+
const filled = await fillInputs(fresh_units, { flags: inputFlags, env: { ...dotenv(fresh), ...processEnv }, tty, noInput, prompt: io?.prompt ?? term?.prompt ?? null, lenient: true });
|
|
268
|
+
ignored = filled.ignored;
|
|
269
|
+
for (const u of fresh_units) {
|
|
270
|
+
const res = await runUnit(fresh, u, { inputs: filled.inputs.get(u.id) ?? {}, allow, tty, ask: io?.ask ?? term?.ask ?? null, authorize: false, verify: false, processEnv, drop: droppedKeys(filled.problems, u.id) });
|
|
271
|
+
const problems = filled.problems.filter((m) => m.unit === u.id);
|
|
272
|
+
const missing = [...filled.missing.filter((m) => m.unit === u.id).map((m) => m.id), ...problems.filter((m) => m.required).map((m) => m.id)];
|
|
273
|
+
const f = fold(res.failed.length ? [...res.checks, ...res.failed.map((x) => ({ id: x.id, status: 'blocked', title: x.id, detail: x.message }))] : res.checks, {});
|
|
274
|
+
results.push({ id: u.id, module: u.module, ...f, applied: res.applied, pending: res.pending, failed: res.failed, problems, needs: [...new Set([...missing, ...res.needs])] });
|
|
275
|
+
if (missing.length) code = Math.max(code, EXIT.needsInput);
|
|
276
|
+
else if (res.failed.length && code === EXIT.done) code = EXIT.failed; // D57: a failed apply is a failure; the install itself stands and is committed
|
|
277
|
+
}
|
|
278
|
+
} finally { term?.close(); }
|
|
279
|
+
}
|
|
280
|
+
let committed = null;
|
|
281
|
+
if (!noCommit && gitOk(ws.root, ['rev-parse', '--git-dir'])) {
|
|
282
|
+
const changed = results.flatMap((r) => r.applied.flatMap((a) => a.changed ?? [])).map((p) => path.relative(ws.root, path.resolve(ws.root, p))).filter((rel) => rel && !rel.startsWith('..') && !path.isAbsolute(rel) && fs.existsSync(path.join(ws.root, rel)) && !gitIgnored(ws.root, rel));
|
|
283
|
+
const paths = [...new Set(['package.json', 'package-lock.json', '.env.example', ...changed])].filter((rel) => fs.existsSync(path.join(ws.root, rel)));
|
|
284
|
+
if (gitOk(ws.root, ['add', '--', ...paths]) && gitOk(ws.root, ['commit', '--quiet', '-m', subject, '--', ...paths])) committed = paths;
|
|
285
|
+
}
|
|
286
|
+
return { code, results, committed, ignored };
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** The unit lines a verb prints after setupAndCommit, one block per unit. */
|
|
290
|
+
export function printUnitResults(results, ignored, log) {
|
|
291
|
+
for (const text of ignored) log(`⚠ ${text} — ignored`);
|
|
292
|
+
for (const r of results) {
|
|
293
|
+
const verified = r.verified ? ` · verified ${r.verified}` : '';
|
|
294
|
+
log(`${r.state === 'ready' ? '✔' : r.state === 'blocked' ? '✖' : '—'} ${r.id}: ${r.state}${verified}${r.detail ? ` — ${r.detail}` : ''}`);
|
|
295
|
+
for (const a of r.applied) log(` ✔ ${a.id}${a.message ? ` — ${a.message}` : ''}`);
|
|
296
|
+
for (const f of r.failed) log(` ✖ ${f.id} — ${f.message}`);
|
|
297
|
+
for (const p of r.problems ?? []) log(` ✖ ${p.id} — ${p.reason}`);
|
|
298
|
+
for (const p of r.pending) log(` … ${p.id} (${p.why})${p.reason ? ` — ${p.reason}` : ''}`);
|
|
299
|
+
if (r.needs.length) log(` needs input: ${r.needs.join(', ')} — dt setup ${r.id} --input ${r.needs[0]}=<value>`);
|
|
300
|
+
if (ownerStepPending(r)) log(` the owner's step (opens a browser): dt setup ${r.id}${r.needs.map((n) => ` --input ${n}=<value>`).join('')} --authorize`);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
/** Whether a unit still has a step only the owner runs — a sign-in, a consent — pending. */
|
|
304
|
+
export const ownerStepPending = (r) => (r.pending ?? []).some((p) => p.runBy === 'owner' || (p.effects ?? []).some((e) => e.kind === 'account'));
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* `dt install <spec…> [--from <dir>] [--input k=v]… [--allow <kind>]… [--no-input] [--no-commit] [--json]`
|
|
308
|
+
* `hooks.afterNpm` is a test seam the CLI never sets (an interruption between npm and compile).
|
|
309
|
+
*/
|
|
310
|
+
export async function installModules(ws, argv, { open, npm = resolveNpm(), verify = null, hooks = {}, log: logOut = console.log, processEnv = process.env, tty = !!(process.stdin.isTTY && process.stdout.isTTY), io = null } = {}) {
|
|
311
|
+
if (typeof open !== 'function') throw new Error('installModules: opts.open (an extension-activating opener) is required');
|
|
312
|
+
const json = argv.includes('--json');
|
|
313
|
+
// with --json, stdout is the payload and nothing else: every line of chatter goes to stderr
|
|
314
|
+
const log = json ? console.error : logOut;
|
|
315
|
+
const noInput = json || argv.includes('--no-input');
|
|
316
|
+
const noCommit = argv.includes('--no-commit');
|
|
317
|
+
const fromAt = argv.indexOf('--from');
|
|
318
|
+
const from = fromAt > -1 ? path.resolve(ws.root, argv[fromAt + 1] ?? '') : null;
|
|
319
|
+
if (fromAt > -1 && !argv[fromAt + 1]) { console.error('✖ --from takes a folder of tarballs'); return EXIT.usage; }
|
|
320
|
+
const valueFlags = new Set(['--from', '--input', '--allow']);
|
|
321
|
+
const specs = argv.filter((a, i) => !a.startsWith('--') && !valueFlags.has(argv[i - 1]));
|
|
322
|
+
if (!specs.length) { console.error('✖ dt install takes one or more specs: a name, name@version, ./file.tgz, ./folder or a git URL'); return EXIT.usage; }
|
|
323
|
+
let allow, inputFlags;
|
|
324
|
+
try { allow = parseAllow(argv); inputFlags = parseInputFlags(argv); } catch (e) { if (e instanceof SetupUsage) { console.error(`✖ ${e.message}`); return EXIT.usage; } throw e; }
|
|
325
|
+
|
|
326
|
+
const floor = npmFloor(npm);
|
|
327
|
+
if (floor) { console.error(`✖ ${floor}`); return EXIT.failed; }
|
|
328
|
+
|
|
329
|
+
// 1. resolve and refuse early — nothing is written before step 2
|
|
330
|
+
const installed = installedModules(ws);
|
|
331
|
+
let plan;
|
|
332
|
+
try { plan = resolveClosure(specs, { installed, from, npm, cwd: ws.root }); } catch (e) { if (e instanceof InstallRefusal) { console.error(`✖ ${e.message}`); return EXIT.failed; } throw e; }
|
|
333
|
+
const setupOpts = { inputFlags, allow, tty, noInput, io, processEnv, noCommit };
|
|
334
|
+
if (!plan.list.length) {
|
|
335
|
+
// everything is here — but an earlier run cut off anywhere after npm (a kill, a Ctrl-D at a prompt,
|
|
336
|
+
// a refused input) may have left the runtime stale, npm's files uncommitted or the setup unrun;
|
|
337
|
+
// resuming means finishing those steps, never re-running npm. Clean, compiled and no inputs
|
|
338
|
+
// given is nothing to do; inputs given go to the installed units' setup.
|
|
339
|
+
const names = plan.already;
|
|
340
|
+
const s = staleness(ws.root);
|
|
341
|
+
const stale = !s.compiled || s.stale.length > 0;
|
|
342
|
+
const pending = ['package.json', 'package-lock.json', '.env.example'].filter((rel) => fs.existsSync(path.join(ws.root, rel)) && gitStatus(ws.root, rel) !== '');
|
|
343
|
+
if (!stale && !pending.length && !inputFlags.length) { log(`✔ already installed: ${names.join(', ')} — nothing to do`); return EXIT.done; }
|
|
344
|
+
let fresh;
|
|
345
|
+
try {
|
|
346
|
+
fresh = await open(ws.root);
|
|
347
|
+
if (stale) { const stdout = console.log; if (json) console.log = console.error; try { compile(fresh); } finally { console.log = stdout; } }
|
|
348
|
+
} catch (e) { console.error(`✖ compile: ${e.message.split('\n')[0]}`); return EXIT.failed; }
|
|
349
|
+
const out = await setupAndCommit(ws, fresh, names, { subject: `dreamteamer: install ${names.join(', ')}`, ...setupOpts });
|
|
350
|
+
const did = [stale ? 'the stale runtime was compiled' : null, out.committed ? `the pending changes were committed (${out.committed.join(', ')})` : null, out.results.length ? 'the setup ran' : null].filter(Boolean);
|
|
351
|
+
if (json) { logOut(JSON.stringify({ workspace: { root: ws.root }, installed: [], already: names, committed: out.committed, units: out.results }, null, 2)); return out.code; }
|
|
352
|
+
log(`✔ already installed: ${names.join(', ')} — ${did.join('; ') || 'nothing to do'}`);
|
|
353
|
+
printUnitResults(out.results, out.ignored, log);
|
|
354
|
+
return out.code;
|
|
355
|
+
}
|
|
356
|
+
const names = plan.list.map((e) => e.manifest.name);
|
|
357
|
+
log(`▶ install: ${plan.list.map((e) => `${e.manifest.name}@${e.manifest.version}${e.kind === 'folder' ? ' (linked)' : ''}`).join(', ')}${plan.already.length ? ` — already here: ${plan.already.join(', ')}` : ''}`);
|
|
358
|
+
|
|
359
|
+
// 2–4. npm, verify, compile (a refusal restores the pre-image)
|
|
360
|
+
const step = await npmAndCompile(ws, plan.list, { npm, open, json, log, hooks, what: 'install' });
|
|
361
|
+
if (step.code !== undefined) return step.code;
|
|
362
|
+
const fresh = step.fresh;
|
|
363
|
+
if (verify) {
|
|
364
|
+
const stdout = console.log;
|
|
365
|
+
if (json) console.log = console.error;
|
|
366
|
+
let bad;
|
|
367
|
+
try { bad = await verify(fresh); } finally { console.log = stdout; }
|
|
368
|
+
if (bad) log('⚠ check reported violations (above) — the install stands; fix the records, or the module\'s rules');
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// 5–6. the safe part of the new units' setup, one scoped commit
|
|
372
|
+
const out = await setupAndCommit(ws, fresh, names, { subject: `dreamteamer: install ${names.join(', ')}`, ...setupOpts });
|
|
373
|
+
if (json) { logOut(JSON.stringify({ workspace: { root: ws.root }, installed: names, already: plan.already, committed: out.committed, units: out.results }, null, 2)); return out.code; }
|
|
374
|
+
log(`✔ installed ${names.join(', ')} — compiled${out.committed ? `, committed (${out.committed.join(', ')})` : noCommit ? ', not committed (--no-commit)' : ', not committed (not a git repository)'}`);
|
|
375
|
+
printUnitResults(out.results, out.ignored, log);
|
|
376
|
+
return out.code;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const dotenv = (ws) => {
|
|
380
|
+
const file = path.join(ws.root, '.env');
|
|
381
|
+
return fs.existsSync(file) ? Object.fromEntries(parseEnvValues(fs.readFileSync(file, 'utf8'))) : {};
|
|
382
|
+
};
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// The `setup` contribution — extension API 1, setup version 1.
|
|
2
|
+
//
|
|
3
|
+
// A module that needs something from the person (a folder, a token, a download, a sign-in) declares
|
|
4
|
+
// HOW through a list of units, and the engine drives every unit the same way: `dt install` fills the
|
|
5
|
+
// unit's inputs and applies its safe actions, `dt setup` resumes and verifies, `dt status` folds its
|
|
6
|
+
// checks into one line. The engine never learns a module's name — a unit is addressed by its `id`,
|
|
7
|
+
// identical whether its module is installed alone or composed into a bigger package.
|
|
8
|
+
//
|
|
9
|
+
// setup: [{
|
|
10
|
+
// id: 'meetings', version: 1,
|
|
11
|
+
// inputs: [{ id, title?, env?, kind: 'string'|'path'|'rows'|'secret-path', required?, default?, prompt?, rows?: { columns } }],
|
|
12
|
+
// inspect(ctx) → { checks: [{ id, status, title, detail?, fix?, evidence? }] }
|
|
13
|
+
// plan(ctx, inputs) → { checks, actions: [{ id, title, effects: [{ kind, detail }], preview?, expect?, runBy?, kind? }], needs: [inputId] }
|
|
14
|
+
// apply(ctx, action, inputs) → { ok, changed: [paths], message? }
|
|
15
|
+
// }]
|
|
16
|
+
//
|
|
17
|
+
// This file is the validator and nothing else: pure, no fs, so the contract is testable without a
|
|
18
|
+
// workspace. `src/setup.js` runs the units.
|
|
19
|
+
export const SETUP_VERSION = 1;
|
|
20
|
+
export const INPUT_KINDS = ['string', 'path', 'rows', 'secret-path'];
|
|
21
|
+
export const CHECK_STATUSES = ['ready', 'configured', 'unverified', 'missing', 'blocked'];
|
|
22
|
+
export const EFFECT_KINDS = ['workspace-files', 'download', 'network', 'machine', 'account'];
|
|
23
|
+
|
|
24
|
+
const UNIT_ID = /^[a-z][a-z0-9-]*$/;
|
|
25
|
+
const INPUT_ID = /^[a-z][a-z0-9_]*$/;
|
|
26
|
+
const ENV_KEY = /^[A-Z][A-Z0-9_]*$/;
|
|
27
|
+
|
|
28
|
+
const kindOf = (v) => (Array.isArray(v) ? 'a list' : v === null ? 'null' : typeof v === 'object' ? 'an object' : typeof v);
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Validate one package's `setup` contribution. Returns the units with their defaults filled and the
|
|
32
|
+
* package name stamped as `module`, or the refusals — every one naming the unit and the field, so a
|
|
33
|
+
* module author reads the message and fixes the one line.
|
|
34
|
+
* `declared` is the package's `dreamteamer.env` and `dreamteamer.vars`: an input that names an env
|
|
35
|
+
* key must also be declared there, so a variable is declared in exactly one place.
|
|
36
|
+
*/
|
|
37
|
+
export function validateSetup(name, value, { env = [], vars = [] } = {}) {
|
|
38
|
+
if (value === undefined || value === null) return { units: [], errors: [] };
|
|
39
|
+
if (!Array.isArray(value)) return { units: [], errors: [`extension ${name}: setup must be a list of units (got ${kindOf(value)})`] };
|
|
40
|
+
const declared = new Set([...(env ?? []), ...(vars ?? [])]);
|
|
41
|
+
const errors = [];
|
|
42
|
+
const units = [];
|
|
43
|
+
const seen = new Set();
|
|
44
|
+
for (const u of value) {
|
|
45
|
+
if (!u || typeof u !== 'object' || Array.isArray(u)) { errors.push(`extension ${name}: a setup unit must be an object (got ${kindOf(u)})`); continue; }
|
|
46
|
+
if (typeof u.id !== 'string' || !UNIT_ID.test(u.id)) { errors.push(`extension ${name}: a setup unit id is a lowercase slug (got ${JSON.stringify(u.id)})`); continue; }
|
|
47
|
+
if (seen.has(u.id)) { errors.push(`extension ${name}: setup unit "${u.id}" is declared twice`); continue; }
|
|
48
|
+
seen.add(u.id);
|
|
49
|
+
if (u.version !== SETUP_VERSION) { errors.push(`unit ${u.id} declares setup version ${u.version}; this engine understands ${SETUP_VERSION} — update the engine or the module`); continue; }
|
|
50
|
+
let bad = false;
|
|
51
|
+
for (const f of ['inspect', 'plan', 'apply']) if (typeof u[f] !== 'function') { errors.push(`unit ${u.id}: ${f} must be a function`); bad = true; }
|
|
52
|
+
const inputs = [];
|
|
53
|
+
const rawInputs = u.inputs ?? [];
|
|
54
|
+
if (!Array.isArray(rawInputs)) { errors.push(`unit ${u.id}: inputs must be a list`); bad = true; }
|
|
55
|
+
else {
|
|
56
|
+
for (const i of rawInputs) {
|
|
57
|
+
if (!i || typeof i !== 'object') { errors.push(`unit ${u.id}: an input must be an object (got ${kindOf(i)})`); bad = true; continue; }
|
|
58
|
+
if (typeof i.id !== 'string' || !INPUT_ID.test(i.id)) { errors.push(`unit ${u.id}: an input id is a lowercase identifier (got ${JSON.stringify(i.id)})`); bad = true; continue; }
|
|
59
|
+
if (!INPUT_KINDS.includes(i.kind)) { errors.push(`unit ${u.id}: input ${i.id} has kind ${JSON.stringify(i.kind)} — one of ${INPUT_KINDS.join(', ')}`); bad = true; continue; }
|
|
60
|
+
if (i.env !== undefined) {
|
|
61
|
+
if (typeof i.env !== 'string' || !ENV_KEY.test(i.env)) { errors.push(`unit ${u.id}: input ${i.id} names env ${JSON.stringify(i.env)}, which is not an environment key`); bad = true; continue; }
|
|
62
|
+
if (!declared.has(i.env)) { errors.push(`unit ${u.id}: input ${i.id} names env ${i.env}, which the package does not declare in dreamteamer.env or vars`); bad = true; continue; }
|
|
63
|
+
}
|
|
64
|
+
if (i.kind === 'rows' && !(Array.isArray(i.rows?.columns) && i.rows.columns.length && i.rows.columns.every((c) => typeof c === 'string'))) { errors.push(`unit ${u.id}: input ${i.id} is rows and must declare rows.columns`); bad = true; continue; }
|
|
65
|
+
inputs.push({ id: i.id, kind: i.kind, env: i.env, required: i.required === true, title: i.title ?? i.id, default: i.default, prompt: i.prompt, rows: i.rows });
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (bad) continue;
|
|
69
|
+
units.push({ id: u.id, version: SETUP_VERSION, module: name, inputs, inspect: u.inspect, plan: u.plan, apply: u.apply });
|
|
70
|
+
}
|
|
71
|
+
return { units, errors };
|
|
72
|
+
}
|