@ductape/cli 0.5.7 → 0.5.9
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 +43 -0
- package/dist/commands/troubleshoot.d.ts +2 -0
- package/dist/commands/troubleshoot.js +15 -0
- package/dist/commands/ui.d.ts +58 -0
- package/dist/commands/ui.js +359 -0
- package/dist/index.js +102 -2
- package/dist/lib/api-client.d.ts +3 -2
- package/dist/lib/api-client.js +6 -3
- package/dist/lib/troubleshoot/collect.d.ts +6 -0
- package/dist/lib/troubleshoot/collect.js +218 -0
- package/dist/lib/troubleshoot/report.d.ts +60 -0
- package/dist/lib/troubleshoot/report.js +98 -0
- package/dist/lib/ui/check.d.ts +38 -0
- package/dist/lib/ui/check.js +64 -0
- package/dist/lib/ui/consume.d.ts +92 -0
- package/dist/lib/ui/consume.js +392 -0
- package/dist/lib/ui/manifest.d.ts +53 -0
- package/dist/lib/ui/manifest.js +109 -0
- package/dist/lib/ui/pack.d.ts +39 -0
- package/dist/lib/ui/pack.js +96 -0
- package/dist/lib/ui/paths.d.ts +7 -0
- package/dist/lib/ui/paths.js +25 -0
- package/dist/lib/ui/registry.d.ts +84 -0
- package/dist/lib/ui/registry.js +78 -0
- package/dist/lib/ui/scaffold.d.ts +14 -0
- package/dist/lib/ui/scaffold.js +411 -0
- package/dist/lib/ui/semver.d.ts +11 -0
- package/dist/lib/ui/semver.js +115 -0
- package/dist/lib/ui/validate.d.ts +33 -0
- package/dist/lib/ui/validate.js +445 -0
- package/package.json +3 -2
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { frameworkFits, UI_MANIFEST_FILE, validateManifest } from './manifest.js';
|
|
4
|
+
import { buildPack } from './pack.js';
|
|
5
|
+
import { isSafeRelativePath, resolveInside } from './paths.js';
|
|
6
|
+
import { INSTALLED_DIR, UI_DIR } from './scaffold.js';
|
|
7
|
+
import { satisfies } from './semver.js';
|
|
8
|
+
/**
|
|
9
|
+
* Adding UI pieces to an application: their verified source is written into ductape/ui/installed/<name>/, pinned in
|
|
10
|
+
* ductape/ui.lock.json, and made importable as #ui/<name> through package.json "imports". Builds read only those files, so
|
|
11
|
+
* they never contact Ductape; `verify` proves the files are still exactly what the lockfile pinned.
|
|
12
|
+
*/
|
|
13
|
+
export const LOCKFILE = path.join('ductape', 'ui.lock.json');
|
|
14
|
+
export const LOCKFILE_VERSION = 1;
|
|
15
|
+
export const IMPORT_PREFIX = '#ui/';
|
|
16
|
+
export const installedRoot = (projectRoot) => path.join(projectRoot, UI_DIR, INSTALLED_DIR);
|
|
17
|
+
export const importTarget = (name, entry) => `./${[...UI_DIR.split(path.sep), INSTALLED_DIR, name, entry].join('/')}`;
|
|
18
|
+
// ---- lockfile -------------------------------------------------------------------------------------------------------
|
|
19
|
+
export function readLockfile(projectRoot) {
|
|
20
|
+
const file = path.join(projectRoot, LOCKFILE);
|
|
21
|
+
if (!fs.existsSync(file))
|
|
22
|
+
return { lockfileVersion: LOCKFILE_VERSION, pieces: {} };
|
|
23
|
+
const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
24
|
+
if (raw.lockfileVersion !== LOCKFILE_VERSION || !raw.pieces || typeof raw.pieces !== 'object') {
|
|
25
|
+
throw new Error(`${LOCKFILE} has lockfileVersion ${String(raw.lockfileVersion)}; this CLI reads version ${LOCKFILE_VERSION}`);
|
|
26
|
+
}
|
|
27
|
+
return raw;
|
|
28
|
+
}
|
|
29
|
+
/** Sorted keys, so the file only changes when what it pins changes. */
|
|
30
|
+
export function writeLockfile(projectRoot, lock) {
|
|
31
|
+
const pieces = {};
|
|
32
|
+
for (const name of Object.keys(lock.pieces).sort()) {
|
|
33
|
+
const e = lock.pieces[name];
|
|
34
|
+
pieces[name] = {
|
|
35
|
+
version: e.version, framework: e.framework, integrity: e.integrity, entry: e.entry, direct: e.direct,
|
|
36
|
+
...(e.uses && Object.keys(e.uses).length > 0 ? { uses: Object.fromEntries(Object.entries(e.uses).sort()) } : {}),
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
fs.mkdirSync(path.dirname(path.join(projectRoot, LOCKFILE)), { recursive: true });
|
|
40
|
+
fs.writeFileSync(path.join(projectRoot, LOCKFILE), `${JSON.stringify({ lockfileVersion: LOCKFILE_VERSION, pieces }, null, 2)}\n`);
|
|
41
|
+
}
|
|
42
|
+
const entryFor = (pack, direct) => ({
|
|
43
|
+
version: pack.manifest.version,
|
|
44
|
+
framework: pack.manifest.framework,
|
|
45
|
+
integrity: pack.integrity,
|
|
46
|
+
entry: pack.manifest.entry,
|
|
47
|
+
direct,
|
|
48
|
+
...(pack.manifest.uses ? { uses: { ...pack.manifest.uses } } : {}),
|
|
49
|
+
});
|
|
50
|
+
/** Which installed pieces use `name`. */
|
|
51
|
+
export const dependentsOf = (lock, name) => Object.entries(lock.pieces).filter(([, e]) => e.uses && name in e.uses).map(([n]) => n).sort();
|
|
52
|
+
/** Drops pieces that were only there because something used them and nothing does any more. */
|
|
53
|
+
export function pruneOrphans(lock) {
|
|
54
|
+
const removed = [];
|
|
55
|
+
let changed = true;
|
|
56
|
+
while (changed) {
|
|
57
|
+
changed = false;
|
|
58
|
+
for (const [name, entry] of Object.entries(lock.pieces)) {
|
|
59
|
+
if (!entry.direct && dependentsOf(lock, name).length === 0) {
|
|
60
|
+
delete lock.pieces[name];
|
|
61
|
+
removed.push(name);
|
|
62
|
+
changed = true;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return removed.sort();
|
|
67
|
+
}
|
|
68
|
+
function readJson(file) {
|
|
69
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
70
|
+
}
|
|
71
|
+
/** The installed version of a package, looking in node_modules from the project up, as Node resolves it. */
|
|
72
|
+
export function installedVersion(projectRoot, pkg) {
|
|
73
|
+
let dir = path.resolve(projectRoot);
|
|
74
|
+
while (true) {
|
|
75
|
+
const manifest = path.join(dir, 'node_modules', ...pkg.split('/'), 'package.json');
|
|
76
|
+
if (fs.existsSync(manifest))
|
|
77
|
+
return String(readJson(manifest).version ?? '');
|
|
78
|
+
const parent = path.dirname(dir);
|
|
79
|
+
if (parent === dir)
|
|
80
|
+
return undefined;
|
|
81
|
+
dir = parent;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
export function installCommand(projectRoot, specs) {
|
|
85
|
+
const quoted = specs.map((s) => (/[\s<>|^~*]/.test(s) ? `"${s}"` : s)).join(' ');
|
|
86
|
+
if (fs.existsSync(path.join(projectRoot, 'pnpm-lock.yaml')))
|
|
87
|
+
return `pnpm add ${quoted}`;
|
|
88
|
+
if (fs.existsSync(path.join(projectRoot, 'yarn.lock')))
|
|
89
|
+
return `yarn add ${quoted}`;
|
|
90
|
+
if (fs.existsSync(path.join(projectRoot, 'bun.lockb')) || fs.existsSync(path.join(projectRoot, 'bun.lock')))
|
|
91
|
+
return `bun add ${quoted}`;
|
|
92
|
+
return `npm install ${quoted}`;
|
|
93
|
+
}
|
|
94
|
+
/** Checks every piece's peerDependencies against the application's package.json and node_modules. */
|
|
95
|
+
export function checkPeers(projectRoot, manifests) {
|
|
96
|
+
const pkgJson = readJson(path.join(projectRoot, 'package.json'));
|
|
97
|
+
const declared = { ...pkgJson.peerDependencies, ...pkgJson.devDependencies, ...pkgJson.dependencies };
|
|
98
|
+
const wanted = new Map();
|
|
99
|
+
for (const m of manifests) {
|
|
100
|
+
for (const [pkg, range] of Object.entries(m.peerDependencies)) {
|
|
101
|
+
const ranges = wanted.get(pkg) ?? new Map();
|
|
102
|
+
ranges.set(range, [...(ranges.get(range) ?? []), m.name]);
|
|
103
|
+
wanted.set(pkg, ranges);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const problems = [];
|
|
107
|
+
for (const [pkg, ranges] of [...wanted].sort(([a], [b]) => a.localeCompare(b))) {
|
|
108
|
+
const installed = installedVersion(projectRoot, pkg);
|
|
109
|
+
for (const [range, requiredBy] of ranges) {
|
|
110
|
+
const base = { package: pkg, range, requiredBy, ...(installed ? { installed } : {}) };
|
|
111
|
+
if (!installed) {
|
|
112
|
+
problems.push(pkg in declared
|
|
113
|
+
? { ...base, severity: 'error', code: 'UI_PEER_NOT_INSTALLED', message: `${pkg} is in package.json but not installed; run your package manager's install` }
|
|
114
|
+
: { ...base, severity: 'error', code: 'UI_PEER_MISSING', message: `${pkg} ${range} is needed by ${requiredBy.join(', ')}: ${installCommand(projectRoot, [`${pkg}@${range}`])}` });
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
const ok = satisfies(installed, range);
|
|
118
|
+
if (ok === false)
|
|
119
|
+
problems.push({ ...base, severity: 'error', code: 'UI_PEER_VERSION', message: `${requiredBy.join(', ')} needs ${pkg} ${range}; ${installed} is installed` });
|
|
120
|
+
if (ok === undefined)
|
|
121
|
+
problems.push({ ...base, severity: 'warning', code: 'UI_PEER_RANGE_UNKNOWN', message: `Could not check ${pkg} ${installed} against "${range}"` });
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return problems;
|
|
125
|
+
}
|
|
126
|
+
const cloneLock = (lock) => JSON.parse(JSON.stringify(lock));
|
|
127
|
+
/**
|
|
128
|
+
* Brings `roots` (name and version or "latest") into a copy of the lock, with every piece they use at the exact version
|
|
129
|
+
* they name. One version of a piece per application: a different version already pinned is a conflict, not a choice.
|
|
130
|
+
*/
|
|
131
|
+
async function resolveInto(source, lock, roots, plan, framework) {
|
|
132
|
+
const queue = roots.map((r) => ({ ...r, direct: true }));
|
|
133
|
+
while (queue.length > 0) {
|
|
134
|
+
const item = queue.shift();
|
|
135
|
+
const pinned = lock.pieces[item.name];
|
|
136
|
+
if (pinned) {
|
|
137
|
+
if (item.version !== 'latest' && item.version !== pinned.version) {
|
|
138
|
+
const holders = [...dependentsOf(lock, item.name), ...(pinned.direct ? ['this application'] : [])];
|
|
139
|
+
throw new Error(`${item.by ?? 'This application'} needs ${item.name}@${item.version}, but ${item.name}@${pinned.version} is installed for ${holders.join(', ') || 'another piece'}. An application has one version of each piece.`);
|
|
140
|
+
}
|
|
141
|
+
// Already pinned at that version: on disk already (verify checks it) or being written by this plan.
|
|
142
|
+
if (item.direct)
|
|
143
|
+
pinned.direct = true;
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
const { pack, deprecation } = await source.fetchPack(item.name, item.version);
|
|
147
|
+
// Plain JavaScript pieces fit any application; framework pieces must match the application's other framework pieces.
|
|
148
|
+
const expected = framework ?? Object.values(lock.pieces).find((e) => e.framework !== 'javascript')?.framework;
|
|
149
|
+
if (expected && expected !== 'javascript' && !frameworkFits(expected, pack.manifest.framework)) {
|
|
150
|
+
throw new Error(`${item.name} is a ${pack.manifest.framework} piece; this application's pieces are ${expected}`);
|
|
151
|
+
}
|
|
152
|
+
if (deprecation)
|
|
153
|
+
plan.warnings.push(`${item.name}@${pack.manifest.version} is deprecated${deprecation.reason ? `: ${deprecation.reason}` : ''}${deprecation.replacement ? ` (use ${deprecation.replacement})` : ''}`);
|
|
154
|
+
lock.pieces[item.name] = entryFor(pack, item.direct);
|
|
155
|
+
plan.write.set(item.name, pack);
|
|
156
|
+
for (const [name, version] of Object.entries(pack.manifest.uses ?? {}))
|
|
157
|
+
queue.push({ name, version, direct: false, by: `${item.name}@${pack.manifest.version}` });
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
export async function planAdd(source, current, name, version = 'latest') {
|
|
161
|
+
const lock = cloneLock(current);
|
|
162
|
+
const plan = { lock, write: new Map(), removed: [], warnings: [] };
|
|
163
|
+
const pinned = lock.pieces[name];
|
|
164
|
+
if (pinned && version !== 'latest' && pinned.version !== version) {
|
|
165
|
+
throw new Error(`${name}@${pinned.version} is already installed; use \`ductape ui update ${name} --to ${version}\``);
|
|
166
|
+
}
|
|
167
|
+
await resolveInto(source, lock, [{ name, version: pinned && version === 'latest' ? pinned.version : version }], plan);
|
|
168
|
+
return plan;
|
|
169
|
+
}
|
|
170
|
+
export async function planUpdate(source, current, name, version = 'latest') {
|
|
171
|
+
const pinned = current.pieces[name];
|
|
172
|
+
if (!pinned)
|
|
173
|
+
throw new Error(`${name} is not installed; add it with \`ductape ui add ${name}\``);
|
|
174
|
+
const users = dependentsOf(current, name);
|
|
175
|
+
if (users.length > 0)
|
|
176
|
+
throw new Error(`${name}@${pinned.version} is pinned by ${users.join(', ')}; update ${users.length === 1 ? 'that piece' : 'those pieces'} instead`);
|
|
177
|
+
const target = await source.fetchPack(name, version);
|
|
178
|
+
if (target.pack.manifest.version === pinned.version) {
|
|
179
|
+
return { lock: cloneLock(current), write: new Map(), removed: [], warnings: [], from: pinned.version, to: pinned.version };
|
|
180
|
+
}
|
|
181
|
+
const lock = cloneLock(current);
|
|
182
|
+
delete lock.pieces[name];
|
|
183
|
+
const removed = pruneOrphans(lock);
|
|
184
|
+
const plan = { lock, write: new Map(), removed, warnings: [] };
|
|
185
|
+
await resolveInto(source, lock, [{ name, version: target.pack.manifest.version }], plan);
|
|
186
|
+
plan.lock.pieces[name].direct = true;
|
|
187
|
+
plan.removed = plan.removed.filter((r) => !(r in plan.lock.pieces));
|
|
188
|
+
return { ...plan, from: pinned.version, to: target.pack.manifest.version };
|
|
189
|
+
}
|
|
190
|
+
export function planRemove(current, name) {
|
|
191
|
+
if (!current.pieces[name])
|
|
192
|
+
throw new Error(`${name} is not installed`);
|
|
193
|
+
const users = dependentsOf(current, name);
|
|
194
|
+
if (users.length > 0)
|
|
195
|
+
throw new Error(`${name} is used by ${users.join(', ')}; remove ${users.length === 1 ? 'that piece' : 'those pieces'} first`);
|
|
196
|
+
const lock = cloneLock(current);
|
|
197
|
+
delete lock.pieces[name];
|
|
198
|
+
return { lock, write: new Map(), removed: [name, ...pruneOrphans(lock)].sort(), warnings: [] };
|
|
199
|
+
}
|
|
200
|
+
// ---- applying -------------------------------------------------------------------------------------------------------
|
|
201
|
+
/** Writes one artifact's files into a fresh folder, refusing any path that would leave it. */
|
|
202
|
+
function writePiece(dir, pack) {
|
|
203
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
204
|
+
for (const file of pack.files) {
|
|
205
|
+
const target = resolveInside(dir, file.path);
|
|
206
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
207
|
+
fs.writeFileSync(target, file.content, { flag: 'wx' });
|
|
208
|
+
}
|
|
209
|
+
fs.writeFileSync(path.join(dir, UI_MANIFEST_FILE), `${JSON.stringify(pack.manifest, null, 2)}\n`, { flag: 'wx' });
|
|
210
|
+
}
|
|
211
|
+
const INSTALLED_README = `# Installed UI pieces
|
|
212
|
+
|
|
213
|
+
Added with \`ductape ui add\` and pinned in ../../ui.lock.json. Do not edit these files: \`ductape ui verify\` fails when they
|
|
214
|
+
differ from the pinned artifacts. To change a piece, change it where it is written and publish a new version, then run
|
|
215
|
+
\`ductape ui update <name>\` here.
|
|
216
|
+
`;
|
|
217
|
+
/** Makes the files, the lockfile and package.json match the plan. New folders are written beside the old ones first. */
|
|
218
|
+
export function applyPlan(projectRoot, plan) {
|
|
219
|
+
const root = installedRoot(projectRoot);
|
|
220
|
+
fs.mkdirSync(root, { recursive: true });
|
|
221
|
+
for (const leftover of fs.readdirSync(root))
|
|
222
|
+
if (leftover.startsWith('.staging-'))
|
|
223
|
+
fs.rmSync(path.join(root, leftover), { recursive: true, force: true });
|
|
224
|
+
const staging = fs.mkdtempSync(path.join(root, '.staging-'));
|
|
225
|
+
try {
|
|
226
|
+
for (const [name, pack] of plan.write)
|
|
227
|
+
writePiece(path.join(staging, name), pack);
|
|
228
|
+
for (const name of [...plan.removed, ...plan.write.keys()]) {
|
|
229
|
+
const existing = resolveInside(root, name);
|
|
230
|
+
if (fs.existsSync(existing))
|
|
231
|
+
fs.rmSync(existing, { recursive: true, force: true });
|
|
232
|
+
}
|
|
233
|
+
for (const name of plan.write.keys())
|
|
234
|
+
fs.renameSync(path.join(staging, name), resolveInside(root, name));
|
|
235
|
+
}
|
|
236
|
+
finally {
|
|
237
|
+
fs.rmSync(staging, { recursive: true, force: true });
|
|
238
|
+
}
|
|
239
|
+
const readme = path.join(root, 'README.md');
|
|
240
|
+
if (!fs.existsSync(readme))
|
|
241
|
+
fs.writeFileSync(readme, INSTALLED_README);
|
|
242
|
+
writeLockfile(projectRoot, plan.lock);
|
|
243
|
+
syncImports(projectRoot, plan.lock);
|
|
244
|
+
}
|
|
245
|
+
/** Sets package.json "imports" so #ui/<name> names each installed piece's entry. Other imports are left exactly as they are. */
|
|
246
|
+
export function syncImports(projectRoot, lock) {
|
|
247
|
+
const file = path.join(projectRoot, 'package.json');
|
|
248
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
249
|
+
const pkg = JSON.parse(text);
|
|
250
|
+
const indent = /^(\s+)"/m.exec(text)?.[1] ?? ' ';
|
|
251
|
+
const current = (pkg.imports ?? {});
|
|
252
|
+
const next = {};
|
|
253
|
+
for (const [key, value] of Object.entries(current))
|
|
254
|
+
if (!key.startsWith(IMPORT_PREFIX))
|
|
255
|
+
next[key] = value;
|
|
256
|
+
for (const name of Object.keys(lock.pieces).sort())
|
|
257
|
+
next[`${IMPORT_PREFIX}${name}`] = importTarget(name, lock.pieces[name].entry);
|
|
258
|
+
if (JSON.stringify(current) === JSON.stringify(next))
|
|
259
|
+
return false;
|
|
260
|
+
if (Object.keys(next).length === 0)
|
|
261
|
+
delete pkg.imports;
|
|
262
|
+
else
|
|
263
|
+
pkg.imports = next;
|
|
264
|
+
fs.writeFileSync(file, `${JSON.stringify(pkg, null, indent)}${text.endsWith('\n') ? '\n' : ''}`);
|
|
265
|
+
return true;
|
|
266
|
+
}
|
|
267
|
+
// ---- verifying ------------------------------------------------------------------------------------------------------
|
|
268
|
+
function walkAll(dir, relative = '') {
|
|
269
|
+
const files = [];
|
|
270
|
+
const problems = [];
|
|
271
|
+
for (const entry of fs.readdirSync(path.join(dir, relative), { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) {
|
|
272
|
+
const rel = relative ? `${relative}/${entry.name}` : entry.name;
|
|
273
|
+
if (entry.isSymbolicLink())
|
|
274
|
+
problems.push(`${rel} is a link`);
|
|
275
|
+
else if (entry.isDirectory()) {
|
|
276
|
+
const inner = walkAll(dir, rel);
|
|
277
|
+
files.push(...inner.files);
|
|
278
|
+
problems.push(...inner.problems);
|
|
279
|
+
}
|
|
280
|
+
else if (entry.isFile()) {
|
|
281
|
+
if (!isSafeRelativePath(rel))
|
|
282
|
+
problems.push(`${rel} is not a file an artifact can contain`);
|
|
283
|
+
else
|
|
284
|
+
files.push({ path: rel, content: fs.readFileSync(path.join(dir, rel), 'utf8') });
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
return { files, problems };
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Offline. Every pinned piece must be on disk exactly as pinned (no file changed, added or removed), package.json must import
|
|
291
|
+
* it, and nothing unpinned may sit in the installed folder. Peer packages are checked too unless `peers` is false.
|
|
292
|
+
*/
|
|
293
|
+
export function verifyInstalled(projectRoot, opts = {}) {
|
|
294
|
+
const diagnostics = [];
|
|
295
|
+
const error = (code, message, file) => diagnostics.push({ severity: 'error', code, message, ...(file ? { file } : {}) });
|
|
296
|
+
let lock;
|
|
297
|
+
try {
|
|
298
|
+
lock = readLockfile(projectRoot);
|
|
299
|
+
}
|
|
300
|
+
catch (e) {
|
|
301
|
+
return { ok: false, diagnostics: [{ severity: 'error', code: 'UI_LOCK_INVALID', message: e.message }], checked: [] };
|
|
302
|
+
}
|
|
303
|
+
const root = installedRoot(projectRoot);
|
|
304
|
+
const manifests = [];
|
|
305
|
+
for (const [name, entry] of Object.entries(lock.pieces).sort()) {
|
|
306
|
+
const dir = path.join(root, name);
|
|
307
|
+
const where = `${UI_DIR.split(path.sep).join('/')}/${INSTALLED_DIR}/${name}`;
|
|
308
|
+
if (!fs.existsSync(dir)) {
|
|
309
|
+
error('UI_INSTALLED_MISSING', `${name}@${entry.version} is pinned but not on disk; run \`ductape ui install\``, where);
|
|
310
|
+
continue;
|
|
311
|
+
}
|
|
312
|
+
const manifestFile = path.join(dir, UI_MANIFEST_FILE);
|
|
313
|
+
if (!fs.existsSync(manifestFile)) {
|
|
314
|
+
error('UI_INSTALLED_MODIFIED', `${name} has no ${UI_MANIFEST_FILE}`, where);
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
let manifestRaw;
|
|
318
|
+
try {
|
|
319
|
+
manifestRaw = JSON.parse(fs.readFileSync(manifestFile, 'utf8'));
|
|
320
|
+
}
|
|
321
|
+
catch {
|
|
322
|
+
error('UI_INSTALLED_MODIFIED', `${name}/${UI_MANIFEST_FILE} is not valid JSON`, where);
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
const { manifest } = validateManifest(manifestRaw);
|
|
326
|
+
if (!manifest) {
|
|
327
|
+
error('UI_INSTALLED_MODIFIED', `${name}/${UI_MANIFEST_FILE} is not a valid manifest`, where);
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
const { files, problems } = walkAll(dir);
|
|
331
|
+
for (const problem of problems)
|
|
332
|
+
error('UI_INSTALLED_MODIFIED', problem, where);
|
|
333
|
+
const integrity = buildPack(manifest, files.filter((f) => f.path !== UI_MANIFEST_FILE)).integrity;
|
|
334
|
+
if (manifest.name !== name || manifest.version !== entry.version)
|
|
335
|
+
error('UI_INSTALLED_MODIFIED', `${where} holds ${manifest.name}@${manifest.version}, but ${name}@${entry.version} is pinned`, where);
|
|
336
|
+
else if (integrity !== entry.integrity)
|
|
337
|
+
error('UI_INSTALLED_MODIFIED', `${name}@${entry.version} differs from the pinned artifact (${entry.integrity}); run \`ductape ui install\` to restore it`, where);
|
|
338
|
+
manifests.push(manifest);
|
|
339
|
+
}
|
|
340
|
+
if (fs.existsSync(root)) {
|
|
341
|
+
for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
|
|
342
|
+
if (entry.name === 'README.md')
|
|
343
|
+
continue;
|
|
344
|
+
// A folder left by an install that was interrupted; the next install clears it.
|
|
345
|
+
if (entry.name.startsWith('.staging-'))
|
|
346
|
+
continue;
|
|
347
|
+
if (!(entry.name in lock.pieces))
|
|
348
|
+
error('UI_INSTALLED_UNPINNED', `${entry.name} is in the installed folder but not in ${LOCKFILE}`);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
const pkg = readJson(path.join(projectRoot, 'package.json'));
|
|
352
|
+
const imports = (pkg.imports ?? {});
|
|
353
|
+
for (const [name, entry] of Object.entries(lock.pieces)) {
|
|
354
|
+
if (imports[`${IMPORT_PREFIX}${name}`] !== importTarget(name, entry.entry))
|
|
355
|
+
error('UI_IMPORT_MAP', `package.json "imports" does not map ${IMPORT_PREFIX}${name} to ${importTarget(name, entry.entry)}; run \`ductape ui install\``, 'package.json');
|
|
356
|
+
}
|
|
357
|
+
for (const key of Object.keys(imports)) {
|
|
358
|
+
if (key.startsWith(IMPORT_PREFIX) && !(key.slice(IMPORT_PREFIX.length) in lock.pieces))
|
|
359
|
+
error('UI_IMPORT_MAP', `package.json imports ${key}, which is not pinned`, 'package.json');
|
|
360
|
+
}
|
|
361
|
+
if (opts.peers !== false) {
|
|
362
|
+
for (const p of checkPeers(projectRoot, manifests))
|
|
363
|
+
diagnostics.push({ severity: p.severity, code: p.code, message: p.message, file: 'package.json' });
|
|
364
|
+
}
|
|
365
|
+
return { ok: !diagnostics.some((d) => d.severity === 'error'), diagnostics, checked: Object.keys(lock.pieces).sort() };
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* Puts back every pinned piece that is missing or changed, fetching exactly the pinned artifact. With `offline`, nothing is
|
|
369
|
+
* fetched and anything that would need fetching is an error.
|
|
370
|
+
*/
|
|
371
|
+
export async function planInstall(projectRoot, source) {
|
|
372
|
+
const lock = readLockfile(projectRoot);
|
|
373
|
+
const plan = { lock, write: new Map(), removed: [], warnings: [] };
|
|
374
|
+
const { diagnostics } = verifyInstalled(projectRoot, { peers: false });
|
|
375
|
+
const broken = new Set();
|
|
376
|
+
for (const d of diagnostics) {
|
|
377
|
+
const name = d.file?.split('/').pop();
|
|
378
|
+
if ((d.code === 'UI_INSTALLED_MISSING' || d.code === 'UI_INSTALLED_MODIFIED') && name && name in lock.pieces)
|
|
379
|
+
broken.add(name);
|
|
380
|
+
if (d.code === 'UI_INSTALLED_UNPINNED')
|
|
381
|
+
plan.removed.push(d.message.split(' ')[0]);
|
|
382
|
+
}
|
|
383
|
+
if (broken.size > 0 && !source)
|
|
384
|
+
throw new Error(`These pieces need fetching, which --offline does not allow: ${[...broken].sort().join(', ')}`);
|
|
385
|
+
const registry = broken.size > 0 ? source() : undefined;
|
|
386
|
+
for (const name of [...broken].sort()) {
|
|
387
|
+
const entry = lock.pieces[name];
|
|
388
|
+
const { pack } = await registry.fetchPack(name, entry.version, entry.integrity);
|
|
389
|
+
plan.write.set(name, pack);
|
|
390
|
+
}
|
|
391
|
+
return { plan, restored: [...broken].sort() };
|
|
392
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The manifest of a Ductape UI piece: ui.json at the root of its directory. A UI piece is frontend source that a workspace
|
|
3
|
+
* publishes once and its applications add to their own repositories, where their own bundler compiles it.
|
|
4
|
+
*/
|
|
5
|
+
export declare const UI_MANIFEST_FILE = "ui.json";
|
|
6
|
+
/**
|
|
7
|
+
* Frameworks a UI piece can be written for. A "javascript" piece is plain DOM code (a mount function and a custom element) and
|
|
8
|
+
* can be used by an application of any framework.
|
|
9
|
+
*/
|
|
10
|
+
export declare const UI_FRAMEWORKS: readonly ["react", "vue", "javascript"];
|
|
11
|
+
export type UiFramework = (typeof UI_FRAMEWORKS)[number];
|
|
12
|
+
/** The package each framework needs in the consuming application. Plain JavaScript needs none. */
|
|
13
|
+
export declare const FRAMEWORK_PEER: Record<UiFramework, string | undefined>;
|
|
14
|
+
/** Whether a piece of framework `used` can be used by a piece or an application of framework `user`. */
|
|
15
|
+
export declare const frameworkFits: (user: string, used: string) => boolean;
|
|
16
|
+
export interface IUiActionRequirement {
|
|
17
|
+
app: string;
|
|
18
|
+
action: string;
|
|
19
|
+
}
|
|
20
|
+
/** What the consuming product must have for the piece to work. Checked online by `ductape ui check`, never during a build. */
|
|
21
|
+
export interface IUiRequirements {
|
|
22
|
+
actions?: IUiActionRequirement[];
|
|
23
|
+
features?: string[];
|
|
24
|
+
sessions?: string[];
|
|
25
|
+
}
|
|
26
|
+
export interface IUiManifest {
|
|
27
|
+
name: string;
|
|
28
|
+
/** Exact semantic version. Ranges are not allowed: a version names one immutable artifact. */
|
|
29
|
+
version: string;
|
|
30
|
+
framework: UiFramework;
|
|
31
|
+
/** Path of the module that is imported as #ui/<name>, relative to the piece's directory. */
|
|
32
|
+
entry: string;
|
|
33
|
+
description?: string;
|
|
34
|
+
/** npm packages the consuming application must already have installed, with the versions this piece supports. */
|
|
35
|
+
peerDependencies: Record<string, string>;
|
|
36
|
+
/** Other UI pieces this one imports as #ui/<name>, at exact versions. */
|
|
37
|
+
uses?: Record<string, string>;
|
|
38
|
+
requires?: IUiRequirements;
|
|
39
|
+
}
|
|
40
|
+
export interface IUiDiagnostic {
|
|
41
|
+
severity: 'error' | 'warning';
|
|
42
|
+
code: string;
|
|
43
|
+
message: string;
|
|
44
|
+
file?: string;
|
|
45
|
+
line?: number;
|
|
46
|
+
}
|
|
47
|
+
export declare const NAME_PATTERN: RegExp;
|
|
48
|
+
export declare const EXACT_VERSION: RegExp;
|
|
49
|
+
/** Checks the shape of a manifest. Returns the typed manifest only when there are no errors. */
|
|
50
|
+
export declare function validateManifest(raw: unknown): {
|
|
51
|
+
manifest?: IUiManifest;
|
|
52
|
+
diagnostics: IUiDiagnostic[];
|
|
53
|
+
};
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The manifest of a Ductape UI piece: ui.json at the root of its directory. A UI piece is frontend source that a workspace
|
|
3
|
+
* publishes once and its applications add to their own repositories, where their own bundler compiles it.
|
|
4
|
+
*/
|
|
5
|
+
export const UI_MANIFEST_FILE = 'ui.json';
|
|
6
|
+
/**
|
|
7
|
+
* Frameworks a UI piece can be written for. A "javascript" piece is plain DOM code (a mount function and a custom element) and
|
|
8
|
+
* can be used by an application of any framework.
|
|
9
|
+
*/
|
|
10
|
+
export const UI_FRAMEWORKS = ['react', 'vue', 'javascript'];
|
|
11
|
+
/** The package each framework needs in the consuming application. Plain JavaScript needs none. */
|
|
12
|
+
export const FRAMEWORK_PEER = { react: 'react', vue: 'vue', javascript: undefined };
|
|
13
|
+
/** Whether a piece of framework `used` can be used by a piece or an application of framework `user`. */
|
|
14
|
+
export const frameworkFits = (user, used) => used === user || used === 'javascript';
|
|
15
|
+
export const NAME_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
|
|
16
|
+
export const EXACT_VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
|
|
17
|
+
const TAG = /^[A-Za-z0-9][A-Za-z0-9_.:-]*$/;
|
|
18
|
+
const PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
|
|
19
|
+
const KNOWN_KEYS = new Set(['name', 'version', 'framework', 'entry', 'description', 'peerDependencies', 'uses', 'requires']);
|
|
20
|
+
const KNOWN_REQUIRES = new Set(['actions', 'features', 'sessions']);
|
|
21
|
+
const isRecord = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
|
|
22
|
+
const err = (code, message) => ({ severity: 'error', code, message, file: UI_MANIFEST_FILE });
|
|
23
|
+
/** Checks the shape of a manifest. Returns the typed manifest only when there are no errors. */
|
|
24
|
+
export function validateManifest(raw) {
|
|
25
|
+
const diagnostics = [];
|
|
26
|
+
if (!isRecord(raw))
|
|
27
|
+
return { diagnostics: [err('UI_MANIFEST_INVALID', 'ui.json must be a JSON object')] };
|
|
28
|
+
for (const key of Object.keys(raw)) {
|
|
29
|
+
if (!KNOWN_KEYS.has(key))
|
|
30
|
+
diagnostics.push(err('UI_MANIFEST_UNKNOWN_KEY', `Unknown field "${key}" in ui.json`));
|
|
31
|
+
}
|
|
32
|
+
if (typeof raw.name !== 'string' || !NAME_PATTERN.test(raw.name) || raw.name.length > 64) {
|
|
33
|
+
diagnostics.push(err('UI_MANIFEST_NAME', 'name must be lowercase words joined by hyphens, such as "order-table", at most 64 characters'));
|
|
34
|
+
}
|
|
35
|
+
if (typeof raw.version !== 'string' || !EXACT_VERSION.test(raw.version)) {
|
|
36
|
+
diagnostics.push(err('UI_MANIFEST_VERSION', 'version must be an exact semantic version such as "1.0.0"'));
|
|
37
|
+
}
|
|
38
|
+
if (typeof raw.framework !== 'string' || !UI_FRAMEWORKS.includes(raw.framework)) {
|
|
39
|
+
diagnostics.push(err('UI_MANIFEST_FRAMEWORK', `framework must be one of: ${UI_FRAMEWORKS.join(', ')}`));
|
|
40
|
+
}
|
|
41
|
+
if (typeof raw.entry !== 'string' || raw.entry.length === 0) {
|
|
42
|
+
diagnostics.push(err('UI_MANIFEST_ENTRY', 'entry must name the module to import, such as "index.tsx"'));
|
|
43
|
+
}
|
|
44
|
+
if (raw.description !== undefined && typeof raw.description !== 'string') {
|
|
45
|
+
diagnostics.push(err('UI_MANIFEST_DESCRIPTION', 'description must be a string'));
|
|
46
|
+
}
|
|
47
|
+
if (!isRecord(raw.peerDependencies)) {
|
|
48
|
+
diagnostics.push(err('UI_MANIFEST_PEERS', 'peerDependencies must be an object of package name to supported version range'));
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
for (const [pkg, range] of Object.entries(raw.peerDependencies)) {
|
|
52
|
+
if (!PACKAGE_NAME.test(pkg))
|
|
53
|
+
diagnostics.push(err('UI_MANIFEST_PEERS', `"${pkg}" is not a valid npm package name`));
|
|
54
|
+
if (typeof range !== 'string' || range.trim() === '')
|
|
55
|
+
diagnostics.push(err('UI_MANIFEST_PEERS', `peerDependencies["${pkg}"] must be a version range`));
|
|
56
|
+
}
|
|
57
|
+
const framework = raw.framework;
|
|
58
|
+
const needed = FRAMEWORK_PEER[framework];
|
|
59
|
+
if (needed && !(needed in raw.peerDependencies)) {
|
|
60
|
+
diagnostics.push(err('UI_MANIFEST_FRAMEWORK_PEER', `A ${framework} piece must list "${needed}" in peerDependencies`));
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (raw.uses !== undefined) {
|
|
64
|
+
if (!isRecord(raw.uses))
|
|
65
|
+
diagnostics.push(err('UI_MANIFEST_USES', 'uses must be an object of UI piece name to exact version'));
|
|
66
|
+
else {
|
|
67
|
+
for (const [name, version] of Object.entries(raw.uses)) {
|
|
68
|
+
if (!NAME_PATTERN.test(name))
|
|
69
|
+
diagnostics.push(err('UI_MANIFEST_USES', `uses: "${name}" is not a valid UI piece name`));
|
|
70
|
+
if (name === raw.name)
|
|
71
|
+
diagnostics.push(err('UI_MANIFEST_USES', 'A UI piece cannot use itself'));
|
|
72
|
+
if (typeof version !== 'string' || !EXACT_VERSION.test(version)) {
|
|
73
|
+
diagnostics.push(err('UI_MANIFEST_USES', `uses["${name}"] must be an exact version such as "1.0.0", not a range`));
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
if (raw.requires !== undefined) {
|
|
79
|
+
if (!isRecord(raw.requires))
|
|
80
|
+
diagnostics.push(err('UI_MANIFEST_REQUIRES', 'requires must be an object'));
|
|
81
|
+
else {
|
|
82
|
+
const requires = raw.requires;
|
|
83
|
+
for (const key of Object.keys(requires)) {
|
|
84
|
+
if (!KNOWN_REQUIRES.has(key))
|
|
85
|
+
diagnostics.push(err('UI_MANIFEST_REQUIRES', `Unknown requirement "${key}": use actions, features or sessions`));
|
|
86
|
+
}
|
|
87
|
+
if (requires.actions !== undefined) {
|
|
88
|
+
if (!Array.isArray(requires.actions))
|
|
89
|
+
diagnostics.push(err('UI_MANIFEST_REQUIRES', 'requires.actions must be a list of { "app", "action" }'));
|
|
90
|
+
else
|
|
91
|
+
requires.actions.forEach((item, index) => {
|
|
92
|
+
if (!isRecord(item) || typeof item.app !== 'string' || !TAG.test(item.app) || typeof item.action !== 'string' || !TAG.test(item.action)
|
|
93
|
+
|| Object.keys(item).some((k) => k !== 'app' && k !== 'action')) {
|
|
94
|
+
diagnostics.push(err('UI_MANIFEST_REQUIRES', `requires.actions[${index}] must be { "app": "<app tag>", "action": "<action tag>" }`));
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
for (const key of ['features', 'sessions']) {
|
|
99
|
+
const list = requires[key];
|
|
100
|
+
if (list === undefined)
|
|
101
|
+
continue;
|
|
102
|
+
if (!Array.isArray(list) || list.some((tag) => typeof tag !== 'string' || !TAG.test(tag))) {
|
|
103
|
+
diagnostics.push(err('UI_MANIFEST_REQUIRES', `requires.${key} must be a list of ${key === 'features' ? 'feature' : 'session'} tags`));
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return diagnostics.length === 0 ? { manifest: raw, diagnostics } : { diagnostics };
|
|
109
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { type IUiDiagnostic, type IUiManifest } from './manifest.js';
|
|
2
|
+
/**
|
|
3
|
+
* A packed UI piece: its manifest and the full text of each file, with a hash over all of it. JSON rather than a tar
|
|
4
|
+
* archive, so unpacking has no links, modes or archive tricks to defend against: only checked paths and text.
|
|
5
|
+
*/
|
|
6
|
+
export declare const UI_PACK_FORMAT = "ductape-ui/1";
|
|
7
|
+
export interface IUiPackFile {
|
|
8
|
+
path: string;
|
|
9
|
+
sha256: string;
|
|
10
|
+
bytes: number;
|
|
11
|
+
content: string;
|
|
12
|
+
}
|
|
13
|
+
export interface IUiPack {
|
|
14
|
+
format: typeof UI_PACK_FORMAT;
|
|
15
|
+
manifest: IUiManifest;
|
|
16
|
+
files: IUiPackFile[];
|
|
17
|
+
/** sha256 over the canonical form of the format, manifest and every file's path, hash and size. */
|
|
18
|
+
integrity: string;
|
|
19
|
+
}
|
|
20
|
+
export declare const MAX_FILES = 200;
|
|
21
|
+
export declare const MAX_FILE_BYTES: number;
|
|
22
|
+
export declare const MAX_TOTAL_BYTES: number;
|
|
23
|
+
/** JSON with object keys sorted at every level, so equal content always hashes equally. Same rule as Deploy release hashes. */
|
|
24
|
+
export declare function canonicalJson(value: unknown): string;
|
|
25
|
+
export declare const sha256Hex: (data: string | Buffer) => string;
|
|
26
|
+
export declare function computeIntegrity(manifest: IUiManifest, files: Array<Pick<IUiPackFile, 'path' | 'sha256' | 'bytes'>>): string;
|
|
27
|
+
/** Builds a pack from files that have already been read and validated. */
|
|
28
|
+
export declare function buildPack(manifest: IUiManifest, files: Array<{
|
|
29
|
+
path: string;
|
|
30
|
+
content: string;
|
|
31
|
+
}>): IUiPack;
|
|
32
|
+
/**
|
|
33
|
+
* Checks a pack that came from somewhere else (the registry, a cache, a file) before anything in it is used. When
|
|
34
|
+
* `expectedIntegrity` is given, as it is from a lockfile, the pack must be exactly that artifact.
|
|
35
|
+
*/
|
|
36
|
+
export declare function verifyPack(raw: unknown, expectedIntegrity?: string): {
|
|
37
|
+
pack?: IUiPack;
|
|
38
|
+
diagnostics: IUiDiagnostic[];
|
|
39
|
+
};
|