@ductape/cli 0.5.8 → 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 +25 -0
- package/dist/commands/ui.d.ts +58 -0
- package/dist/commands/ui.js +359 -0
- package/dist/index.js +92 -2
- 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,64 @@
|
|
|
1
|
+
import { DuctapeOperationError } from '../operation-error.js';
|
|
2
|
+
import { getProduct, getProductAppAction } from '../platform-api.js';
|
|
3
|
+
const tagsOf = (value) => Array.isArray(value) ? value.map((item) => (item && typeof item === 'object' ? String(item.tag ?? '') : String(item))).filter(Boolean) : undefined;
|
|
4
|
+
export function platformLookup(ctx, product, env) {
|
|
5
|
+
return {
|
|
6
|
+
async action(app, action) {
|
|
7
|
+
try {
|
|
8
|
+
await getProductAppAction(ctx, product, app, action, env);
|
|
9
|
+
return { ok: true };
|
|
10
|
+
}
|
|
11
|
+
catch (error) {
|
|
12
|
+
// The action-contract route answers 400 with its reason when the action is not there; anything else is a failure to ask.
|
|
13
|
+
if (error instanceof DuctapeOperationError && error.details.httpStatus === 400)
|
|
14
|
+
return { ok: false, reason: error.message };
|
|
15
|
+
if (error instanceof Error && /Environment-bound action contract is unavailable/.test(error.message))
|
|
16
|
+
return { ok: false, reason: error.message };
|
|
17
|
+
throw error;
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
async inventory() {
|
|
21
|
+
const raw = (await getProduct(ctx, { tag: product }));
|
|
22
|
+
if (!raw || typeof raw !== 'object')
|
|
23
|
+
throw new Error(`Product "${product}" could not be read`);
|
|
24
|
+
const product_ = (raw.data && typeof raw.data === 'object' ? raw.data : raw);
|
|
25
|
+
return {
|
|
26
|
+
envs: (tagsOf(product_.envs?.map((e) => ({ tag: e?.slug }))) ?? []),
|
|
27
|
+
features: tagsOf(product_.features),
|
|
28
|
+
sessions: tagsOf(product_.sessions),
|
|
29
|
+
};
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
export async function checkRequirements(lookup, env, pieces) {
|
|
34
|
+
const inventory = await lookup.inventory();
|
|
35
|
+
const envKnown = inventory.envs.includes(env);
|
|
36
|
+
const results = [];
|
|
37
|
+
const actionCache = new Map();
|
|
38
|
+
for (const piece of pieces) {
|
|
39
|
+
for (const { app, action } of piece.requires?.actions ?? []) {
|
|
40
|
+
const key = `${app}/${action}`;
|
|
41
|
+
if (!actionCache.has(key)) {
|
|
42
|
+
try {
|
|
43
|
+
actionCache.set(key, envKnown ? await lookup.action(app, action) : { ok: false, reason: `The product has no environment "${env}"` });
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
actionCache.set(key, { error: error instanceof Error ? error.message : String(error) });
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
const found = actionCache.get(key);
|
|
50
|
+
results.push('error' in found
|
|
51
|
+
? { piece: piece.name, kind: 'action', ref: key, status: 'unknown', detail: `Could not check: ${found.error}` }
|
|
52
|
+
: found.ok ? { piece: piece.name, kind: 'action', ref: key, status: 'ok' } : { piece: piece.name, kind: 'action', ref: key, status: 'missing', detail: found.reason });
|
|
53
|
+
}
|
|
54
|
+
for (const kind of ['feature', 'session']) {
|
|
55
|
+
const have = kind === 'feature' ? inventory.features : inventory.sessions;
|
|
56
|
+
for (const tag of (kind === 'feature' ? piece.requires?.features : piece.requires?.sessions) ?? []) {
|
|
57
|
+
results.push(have === undefined
|
|
58
|
+
? { piece: piece.name, kind, ref: tag, status: 'unknown', detail: `The product's ${kind}s could not be read` }
|
|
59
|
+
: have.includes(tag) ? { piece: piece.name, kind, ref: tag, status: 'ok' } : { piece: piece.name, kind, ref: tag, status: 'missing', detail: `The product has no ${kind} "${tag}"` });
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return { ok: results.every((r) => r.status === 'ok'), envKnown, results };
|
|
64
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { type IUiDiagnostic, type IUiManifest } from './manifest.js';
|
|
2
|
+
import { type IUiPack } from './pack.js';
|
|
3
|
+
/**
|
|
4
|
+
* Adding UI pieces to an application: their verified source is written into ductape/ui/installed/<name>/, pinned in
|
|
5
|
+
* ductape/ui.lock.json, and made importable as #ui/<name> through package.json "imports". Builds read only those files, so
|
|
6
|
+
* they never contact Ductape; `verify` proves the files are still exactly what the lockfile pinned.
|
|
7
|
+
*/
|
|
8
|
+
export declare const LOCKFILE: string;
|
|
9
|
+
export declare const LOCKFILE_VERSION = 1;
|
|
10
|
+
export declare const IMPORT_PREFIX = "#ui/";
|
|
11
|
+
export interface ILockEntry {
|
|
12
|
+
version: string;
|
|
13
|
+
framework: string;
|
|
14
|
+
integrity: string;
|
|
15
|
+
entry: string;
|
|
16
|
+
/** Added by name, rather than only because another piece uses it. */
|
|
17
|
+
direct: boolean;
|
|
18
|
+
uses?: Record<string, string>;
|
|
19
|
+
}
|
|
20
|
+
export interface ILockfile {
|
|
21
|
+
lockfileVersion: number;
|
|
22
|
+
pieces: Record<string, ILockEntry>;
|
|
23
|
+
}
|
|
24
|
+
/** Where artifacts come from. The registry client is one; tests can pass another. */
|
|
25
|
+
export interface IPackSource {
|
|
26
|
+
fetchPack(name: string, version: string, expectedIntegrity?: string): Promise<{
|
|
27
|
+
pack: IUiPack;
|
|
28
|
+
deprecation?: {
|
|
29
|
+
reason?: string;
|
|
30
|
+
replacement?: string;
|
|
31
|
+
};
|
|
32
|
+
}>;
|
|
33
|
+
}
|
|
34
|
+
export declare const installedRoot: (projectRoot: string) => string;
|
|
35
|
+
export declare const importTarget: (name: string, entry: string) => string;
|
|
36
|
+
export declare function readLockfile(projectRoot: string): ILockfile;
|
|
37
|
+
/** Sorted keys, so the file only changes when what it pins changes. */
|
|
38
|
+
export declare function writeLockfile(projectRoot: string, lock: ILockfile): void;
|
|
39
|
+
/** Which installed pieces use `name`. */
|
|
40
|
+
export declare const dependentsOf: (lock: ILockfile, name: string) => string[];
|
|
41
|
+
/** Drops pieces that were only there because something used them and nothing does any more. */
|
|
42
|
+
export declare function pruneOrphans(lock: ILockfile): string[];
|
|
43
|
+
export interface IPeerProblem {
|
|
44
|
+
severity: 'error' | 'warning';
|
|
45
|
+
code: 'UI_PEER_MISSING' | 'UI_PEER_NOT_INSTALLED' | 'UI_PEER_VERSION' | 'UI_PEER_RANGE_UNKNOWN';
|
|
46
|
+
package: string;
|
|
47
|
+
range: string;
|
|
48
|
+
installed?: string;
|
|
49
|
+
requiredBy: string[];
|
|
50
|
+
message: string;
|
|
51
|
+
}
|
|
52
|
+
/** The installed version of a package, looking in node_modules from the project up, as Node resolves it. */
|
|
53
|
+
export declare function installedVersion(projectRoot: string, pkg: string): string | undefined;
|
|
54
|
+
export declare function installCommand(projectRoot: string, specs: string[]): string;
|
|
55
|
+
/** Checks every piece's peerDependencies against the application's package.json and node_modules. */
|
|
56
|
+
export declare function checkPeers(projectRoot: string, manifests: IUiManifest[]): IPeerProblem[];
|
|
57
|
+
export interface IPlan {
|
|
58
|
+
lock: ILockfile;
|
|
59
|
+
/** Artifacts to write, by name. Pieces in the lock but not here are already on disk as pinned. */
|
|
60
|
+
write: Map<string, IUiPack>;
|
|
61
|
+
removed: string[];
|
|
62
|
+
warnings: string[];
|
|
63
|
+
}
|
|
64
|
+
export declare function planAdd(source: IPackSource, current: ILockfile, name: string, version?: string): Promise<IPlan>;
|
|
65
|
+
export declare function planUpdate(source: IPackSource, current: ILockfile, name: string, version?: string): Promise<IPlan & {
|
|
66
|
+
from: string;
|
|
67
|
+
to: string;
|
|
68
|
+
}>;
|
|
69
|
+
export declare function planRemove(current: ILockfile, name: string): IPlan;
|
|
70
|
+
/** Makes the files, the lockfile and package.json match the plan. New folders are written beside the old ones first. */
|
|
71
|
+
export declare function applyPlan(projectRoot: string, plan: IPlan): void;
|
|
72
|
+
/** Sets package.json "imports" so #ui/<name> names each installed piece's entry. Other imports are left exactly as they are. */
|
|
73
|
+
export declare function syncImports(projectRoot: string, lock: ILockfile): boolean;
|
|
74
|
+
/**
|
|
75
|
+
* Offline. Every pinned piece must be on disk exactly as pinned (no file changed, added or removed), package.json must import
|
|
76
|
+
* it, and nothing unpinned may sit in the installed folder. Peer packages are checked too unless `peers` is false.
|
|
77
|
+
*/
|
|
78
|
+
export declare function verifyInstalled(projectRoot: string, opts?: {
|
|
79
|
+
peers?: boolean;
|
|
80
|
+
}): {
|
|
81
|
+
ok: boolean;
|
|
82
|
+
diagnostics: IUiDiagnostic[];
|
|
83
|
+
checked: string[];
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* Puts back every pinned piece that is missing or changed, fetching exactly the pinned artifact. With `offline`, nothing is
|
|
87
|
+
* fetched and anything that would need fetching is an error.
|
|
88
|
+
*/
|
|
89
|
+
export declare function planInstall(projectRoot: string, source: (() => IPackSource) | undefined): Promise<{
|
|
90
|
+
plan: IPlan;
|
|
91
|
+
restored: string[];
|
|
92
|
+
}>;
|
|
@@ -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
|
+
};
|