dreamteamer 0.46.1 → 0.48.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/src/testing.js ADDED
@@ -0,0 +1,86 @@
1
+ // `dreamteamer/testing` — what a module's own test suite needs to test itself on the real engine,
2
+ // with nothing but `node --test` and this import (cr-dt-007, G2). Every helper spawns the engine the
3
+ // way a consumer runs it: `init` in a fresh folder, `dt install` of the module packed with `npm pack`
4
+ // (so the package's `files` list is what is tested), then `dt` verbs. Nothing imports src/ by path, and
5
+ // the engine is THIS file's package — never a `dreamteamer` that happens to be on PATH.
6
+ //
7
+ // createWorkspace({ engine? }) a fresh, committed workspace on the engine (DT_ENGINE_DIR wins when set)
8
+ // pack(moduleDir) the tarball npm would publish
9
+ // install(ws, spec, opts?) `dt install` of a name, a tarball, or a folder (packed first)
10
+ // run(ws, args, opts?) the CLI in the workspace — { status, stdout, stderr }; status null on timeout
11
+ // engineMeets(range) does the running engine satisfy a semver range
12
+ //
13
+ // Synchronous throughout, so a test reads top to bottom. Temp folders are removed at exit unless
14
+ // DT_KEEP_FIXTURES is set. Policy (D64): on 0.x a breaking change to this export lands in a minor,
15
+ // announced one release ahead in UPDATING.md.
16
+ import fs from 'node:fs';
17
+ import os from 'node:os';
18
+ import path from 'node:path';
19
+ import { spawnSync } from 'node:child_process';
20
+ import { fileURLToPath } from 'node:url';
21
+ import { satisfies } from './semver.js';
22
+ import { resolveNpm, childEnv } from './checkout.js';
23
+ import { engineRun, freshWorkspace } from './check-alone.js';
24
+
25
+ /** The engine running this file: its package root. */
26
+ export const ENGINE = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
27
+ const VERSION = JSON.parse(fs.readFileSync(path.join(ENGINE, 'package.json'), 'utf8')).version;
28
+
29
+ const made = [];
30
+ let hooked = false;
31
+ function tempDir(prefix) {
32
+ const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), `dreamteamer-testing-${prefix}-`)));
33
+ made.push(dir);
34
+ if (!hooked) {
35
+ hooked = true;
36
+ process.on('exit', () => { if (!process.env.DT_KEEP_FIXTURES) for (const d of made) fs.rmSync(d, { recursive: true, force: true }); });
37
+ }
38
+ return dir;
39
+ }
40
+
41
+ /** The CLI of the workspace's engine, in the workspace. */
42
+ export function run(ws, args, opts = {}) {
43
+ return engineRun(ws.engine, ws.root, args, { timeoutMs: 60_000, ...opts });
44
+ }
45
+
46
+ /**
47
+ * A fresh workspace made by the engine's own `init`: the engine declared as a `file:` dependency and
48
+ * linked before init, so init finds it present and asks no registry; git-initialised and committed.
49
+ * `engine` (a package root) wins, then `DT_ENGINE_DIR`, then the engine running this file.
50
+ */
51
+ export function createWorkspace({ engine } = {}) {
52
+ const eng = engine ?? (process.env.DT_ENGINE_DIR ? path.resolve(process.env.DT_ENGINE_DIR) : ENGINE);
53
+ const root = tempDir('ws');
54
+ const ws = { root, engine: eng, dt: (args, opts) => run(ws, args, opts) };
55
+ freshWorkspace(root, eng);
56
+ return ws;
57
+ }
58
+
59
+ /** `npm pack` of a module folder into a temp folder; the tarball's path. */
60
+ export function pack(moduleDir) {
61
+ const npm = resolveNpm();
62
+ if (!npm) throw new Error('no npm beside this node or on PATH — pack needs it');
63
+ const dest = tempDir('pack');
64
+ const r = spawnSync(npm, ['pack', '--silent', '--pack-destination', dest], { cwd: path.resolve(moduleDir), encoding: 'utf8', timeout: 120_000, env: childEnv() });
65
+ if (r.status !== 0) throw new Error(`npm pack failed in ${moduleDir} (exit ${r.status}):\n${r.stderr}${r.stdout}`);
66
+ const tgz = fs.readdirSync(dest).filter((f) => f.endsWith('.tgz'));
67
+ if (tgz.length !== 1) throw new Error(`npm pack left ${tgz.length} tarballs in ${dest}`);
68
+ return path.join(dest, tgz[0]);
69
+ }
70
+
71
+ /** `dt install` of a name, a tarball path, or a module folder (packed first, so its `files` list is
72
+ * what is installed). Never throws on the engine's exit: 3 (an input still needed) is a result. */
73
+ export function install(ws, spec, opts = {}) {
74
+ const isFolder = !spec.endsWith('.tgz') && fs.existsSync(spec) && fs.statSync(spec).isDirectory();
75
+ const target = isFolder ? pack(spec) : spec;
76
+ return run(ws, ['install', target, '--no-input'], { timeoutMs: 300_000, ...opts });
77
+ }
78
+
79
+ /** Does the running engine (or DT_ENGINE_DIR's) satisfy `range`? */
80
+ export function engineMeets(range) {
81
+ let version = VERSION;
82
+ if (process.env.DT_ENGINE_DIR) {
83
+ try { version = JSON.parse(fs.readFileSync(path.join(path.resolve(process.env.DT_ENGINE_DIR), 'package.json'), 'utf8')).version; } catch { /* the running engine's */ }
84
+ }
85
+ return satisfies(version, range) === true;
86
+ }
package/src/update.js ADDED
@@ -0,0 +1,89 @@
1
+ // `dt update <name>[@<version>] | --engine` — move ONE pin forward on purpose: an npm module to the
2
+ // latest release within its ranges (or to the named version), or the engine itself. Re-pinned
3
+ // exactly, closure-checked exactly as `dt install` checks it, compiled, committed with install's
4
+ // pathspec. A downgrade needs `--allow downgrade`; a development link is skipped and named. Nothing
5
+ // here runs on its own, and `dt update` with no target keeps its meaning: git modules fast-forward.
6
+ // A module update is install's steps 2–6 on the whole resolved closure, so a version that adds a
7
+ // dependency brings it in and a version that adds a setup unit runs its safe part.
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { spawnSync, execFileSync } from 'node:child_process';
11
+ import { resolveNpm, childEnv } from './checkout.js';
12
+ import { readSpecManifest, resolveClosure, installedModules, compareVersions, InstallRefusal, npmFloor, npmAndCompile, setupAndCommit, printUnitResults } from './install-modules.js';
13
+ import { EXIT } from './setup.js';
14
+
15
+ const gitOk = (root, args) => { try { execFileSync('git', args, { cwd: root, stdio: 'ignore' }); return true; } catch { return false; } };
16
+
17
+ /**
18
+ * `updateModules(ws, { name, version, engine, allow, from }, { open, npm, log })` → exit code.
19
+ * `name` is a package name (with `version` the exact version asked for, or null for latest);
20
+ * `engine: true` targets `dreamteamer` itself.
21
+ */
22
+ export async function updateModules(ws, { name = null, version = null, engine = false, allow = new Set(), from = null, noCommit = false } = {}, { open, npm = resolveNpm(), log = console.log, processEnv = process.env } = {}) {
23
+ if (typeof open !== 'function') throw new Error('updateModules: opts.open is required');
24
+ const floor = npmFloor(npm);
25
+ if (floor) { console.error(`✖ ${floor}`); return EXIT.failed; }
26
+ const target = engine ? 'dreamteamer' : name;
27
+ const installed = installedModules(ws);
28
+ const here = engine
29
+ ? (() => { try { return { name: 'dreamteamer', version: JSON.parse(fs.readFileSync(path.join(ws.root, 'node_modules', 'dreamteamer', 'package.json'), 'utf8')).version, linked: fs.lstatSync(path.join(ws.root, 'node_modules', 'dreamteamer')).isSymbolicLink() }; } catch { return null; } })()
30
+ : installed.get(target);
31
+ if (!here) { console.error(`✖ ${target} is not installed — dt install ${target}`); return EXIT.failed; }
32
+ if (here.linked) { log(`— ${target}: a development link — skipped (not pinned; remove the link to pin a version)`); return EXIT.done; }
33
+ let entry;
34
+ try { entry = readSpecManifest(version ? `${target}@${version}` : target, { from, npm, cwd: ws.root }); } catch (e) { if (e instanceof InstallRefusal) { console.error(`✖ ${e.message}`); return EXIT.failed; } throw e; }
35
+ const next = entry.manifest.version;
36
+ if (next === here.version) { log(`✔ ${target} is already ${next} — nothing to do`); return EXIT.done; }
37
+ if (compareVersions(next, here.version) < 0 && !allow.has('downgrade')) { console.error(`✖ ${target} ${here.version} → ${next} is a downgrade — say so: dt update ${target}@${next} --allow downgrade`); return EXIT.failed; }
38
+ const subject = `dreamteamer: update ${target} ${here.version} → ${next}`;
39
+ if (engine) {
40
+ // the engine itself: npm, then compile with the NEW engine — this process is the old one
41
+ log(`▶ update: ${target} ${here.version} → ${next}`);
42
+ const r = spawnSync(npm, ['install', '--save-exact', '--no-audit', '--no-fund', entry.spec], { cwd: ws.root, stdio: 'inherit', env: childEnv(), timeout: 600_000 });
43
+ if (r.status !== 0) { console.error(`✖ npm exited ${r.status ?? r.error?.message} — run the same command again to resume`); return EXIT.failed; }
44
+ let got = null;
45
+ try { got = JSON.parse(fs.readFileSync(path.join(ws.root, 'node_modules', 'dreamteamer', 'package.json'), 'utf8')).version; } catch { /* missing */ }
46
+ if (got !== next) { console.error(`✖ npm exited 0, but node_modules/dreamteamer is ${got ?? 'missing'}, not ${next}`); return EXIT.failed; }
47
+ const c = spawnSync(process.execPath, [path.join(ws.root, 'node_modules', 'dreamteamer', 'bin', 'dreamteamer.js'), 'compile'], { cwd: ws.root, stdio: 'inherit', env: childEnv(), timeout: 600_000 });
48
+ if (c.status !== 0) { console.error(`✖ compile with dreamteamer ${next} exited ${c.status} — the pin moved; fix what it reports, then dt compile`); return EXIT.failed; }
49
+ let committed = null;
50
+ if (!noCommit && gitOk(ws.root, ['rev-parse', '--git-dir'])) {
51
+ const paths = ['package.json', 'package-lock.json', '.env.example'].filter((rel) => fs.existsSync(path.join(ws.root, rel)));
52
+ if (gitOk(ws.root, ['add', '--', ...paths]) && gitOk(ws.root, ['commit', '--quiet', '-m', subject, '--', ...paths])) committed = paths;
53
+ }
54
+ log(`✔ ${target} ${here.version} → ${next} — compiled${committed ? `, committed (${committed.join(', ')})` : ', not committed'}`);
55
+ return EXIT.done;
56
+ }
57
+ // a module: install one pin later — the closure check exactly as install step 1 (with the target
58
+ // itself out of the installed map, so "installed at another version" does not refuse the very move
59
+ // being asked for), then install's steps 2–6 on the WHOLE resolved list: a version that adds a
60
+ // dreamteamer.dependencies entry brings the dependency in, compiled and committed with it, and a
61
+ // version that adds a setup unit runs its safe part
62
+ const others = new Map([...installed].filter(([n]) => n !== target));
63
+ let plan;
64
+ try { plan = resolveClosure([entry.spec], { installed: others, from, npm, cwd: ws.root }); } catch (e) { if (e instanceof InstallRefusal) { console.error(`✖ ${e.message}`); return EXIT.failed; } throw e; }
65
+ const names = plan.list.map((e) => e.manifest.name);
66
+ const extra = names.filter((n) => n !== target);
67
+ log(`▶ update: ${target} ${here.version} → ${next}${extra.length ? ` — with ${extra.join(', ')}` : ''}`);
68
+ const step = await npmAndCompile(ws, plan.list, { npm, open, log, what: 'update' });
69
+ if (step.code !== undefined) return step.code;
70
+ const out = await setupAndCommit(ws, step.fresh, names, { subject, processEnv, noCommit });
71
+ log(`✔ ${target} ${here.version} → ${next}${extra.length ? ` (with ${extra.join(', ')})` : ''} — compiled${out.committed ? `, committed (${out.committed.join(', ')})` : ', not committed'}`);
72
+ printUnitResults(out.results, out.ignored, log);
73
+ return out.code;
74
+ }
75
+
76
+ /** The `dt update` argv: a target (`name`, `name@version`), `--engine`, `--allow downgrade`, `--from <dir>`, `--no-commit`. */
77
+ export function parseUpdateArgs(argv) {
78
+ const out = { name: null, version: null, engine: argv.includes('--engine'), allow: new Set(), from: null, noCommit: argv.includes('--no-commit') };
79
+ for (let i = 0; i < argv.length; i++) {
80
+ const a = argv[i];
81
+ if (a === '--allow') { const k = argv[++i]; if (k !== 'downgrade') throw new Error(`dt update --allow takes downgrade (got ${JSON.stringify(k)})`); out.allow.add(k); }
82
+ else if (a === '--from') out.from = argv[++i] ?? null;
83
+ else if (!a.startsWith('--') && !['--allow', '--from'].includes(argv[i - 1])) {
84
+ const at = a.startsWith('@') ? a.indexOf('@', 1) : a.indexOf('@');
85
+ if (at > 0) { out.name = a.slice(0, at); out.version = a.slice(at + 1); } else out.name = a;
86
+ }
87
+ }
88
+ return out;
89
+ }