@usalyt/cli 0.0.0-stage → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/LICENSE +674 -0
- package/NOTICE +32 -0
- package/README.md +241 -2
- package/THIRD_PARTY_NOTICES.md +446 -0
- package/dist/index.d.mts +1 -0
- package/dist/index.mjs +653 -0
- package/package.json +46 -3
- package/src/commands/add.ts +199 -0
- package/src/commands/init.ts +103 -0
- package/src/commands/list.ts +54 -0
- package/src/index.ts +20 -0
- package/src/lib/config.ts +111 -0
- package/src/lib/imports.ts +92 -0
- package/src/lib/install.ts +225 -0
- package/src/lib/output.ts +7 -0
- package/src/lib/paths.ts +99 -0
- package/src/lib/registry.ts +120 -0
- package/tsdown.config.ts +9 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,653 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { defineCommand, runMain } from "citty";
|
|
4
|
+
import { spawnSync } from "node:child_process";
|
|
5
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { createInterface } from "node:readline/promises";
|
|
8
|
+
import pc from "picocolors";
|
|
9
|
+
import { fileURLToPath } from "node:url";
|
|
10
|
+
//#region src/lib/config.ts
|
|
11
|
+
const CONFIG_FILE = "usalyt.json";
|
|
12
|
+
var ConfigError = class extends Error {
|
|
13
|
+
constructor(message) {
|
|
14
|
+
super(message);
|
|
15
|
+
this.name = "ConfigError";
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Aliases are root-relative destinations. A leading `@/` or `~/` is accepted
|
|
20
|
+
* for readability and is equivalent to the consumer root. The CLI rejects
|
|
21
|
+
* absolute aliases and any alias that normalizes outside the root.
|
|
22
|
+
*/
|
|
23
|
+
function defaultConfig() {
|
|
24
|
+
return {
|
|
25
|
+
style: "default",
|
|
26
|
+
rsc: true,
|
|
27
|
+
tsx: true,
|
|
28
|
+
tailwind: {
|
|
29
|
+
config: "",
|
|
30
|
+
css: "src/styles/globals.css",
|
|
31
|
+
baseColor: "neutral"
|
|
32
|
+
},
|
|
33
|
+
aliases: {
|
|
34
|
+
components: "@/src/components/ui",
|
|
35
|
+
utils: "@/src/lib/utils"
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
function configPathFor(root) {
|
|
40
|
+
return path.join(root, CONFIG_FILE);
|
|
41
|
+
}
|
|
42
|
+
function isRecord$1(value) {
|
|
43
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
44
|
+
}
|
|
45
|
+
function requireAlias(aliases, key) {
|
|
46
|
+
const value = aliases[key];
|
|
47
|
+
if (typeof value !== "string" || value.trim() === "") throw new ConfigError(`${CONFIG_FILE} must define a non-empty "aliases.${key}" string.`);
|
|
48
|
+
return value;
|
|
49
|
+
}
|
|
50
|
+
/** Read `usalyt.json` from the consumer root, or return null when absent. */
|
|
51
|
+
function readConfig(root) {
|
|
52
|
+
const configPath = configPathFor(root);
|
|
53
|
+
if (!existsSync(configPath)) return null;
|
|
54
|
+
let parsed;
|
|
55
|
+
try {
|
|
56
|
+
parsed = JSON.parse(readFileSync(configPath, "utf8"));
|
|
57
|
+
} catch (error) {
|
|
58
|
+
throw new ConfigError(`${configPath} is not valid JSON: ${error.message}`);
|
|
59
|
+
}
|
|
60
|
+
if (!isRecord$1(parsed)) throw new ConfigError(`${configPath} must contain a JSON object.`);
|
|
61
|
+
if (!isRecord$1(parsed.aliases)) throw new ConfigError(`${configPath} must contain an "aliases" object.`);
|
|
62
|
+
const defaults = defaultConfig();
|
|
63
|
+
return {
|
|
64
|
+
style: typeof parsed.style === "string" ? parsed.style : defaults.style,
|
|
65
|
+
rsc: typeof parsed.rsc === "boolean" ? parsed.rsc : defaults.rsc,
|
|
66
|
+
tsx: typeof parsed.tsx === "boolean" ? parsed.tsx : defaults.tsx,
|
|
67
|
+
tailwind: isRecord$1(parsed.tailwind) ? {
|
|
68
|
+
config: typeof parsed.tailwind.config === "string" ? parsed.tailwind.config : defaults.tailwind.config,
|
|
69
|
+
css: typeof parsed.tailwind.css === "string" ? parsed.tailwind.css : defaults.tailwind.css,
|
|
70
|
+
baseColor: typeof parsed.tailwind.baseColor === "string" ? parsed.tailwind.baseColor : defaults.tailwind.baseColor
|
|
71
|
+
} : defaults.tailwind,
|
|
72
|
+
aliases: {
|
|
73
|
+
components: requireAlias(parsed.aliases, "components"),
|
|
74
|
+
utils: requireAlias(parsed.aliases, "utils")
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
function serializeConfig(config) {
|
|
79
|
+
return `${JSON.stringify(config, null, 2)}\n`;
|
|
80
|
+
}
|
|
81
|
+
//#endregion
|
|
82
|
+
//#region src/lib/imports.ts
|
|
83
|
+
const IMPORT_PATTERN = /(\bfrom\s*|\bimport\s*)(["'])([^"'\n]+)\2/g;
|
|
84
|
+
const SOURCE_EXTENSIONS = [
|
|
85
|
+
".tsx",
|
|
86
|
+
".ts",
|
|
87
|
+
".jsx",
|
|
88
|
+
".js",
|
|
89
|
+
".mts",
|
|
90
|
+
".cts",
|
|
91
|
+
".mjs",
|
|
92
|
+
".cjs"
|
|
93
|
+
];
|
|
94
|
+
function resolveSourceFile(sourcePath, specifier, knownSources) {
|
|
95
|
+
if (!specifier.startsWith(".")) return null;
|
|
96
|
+
const base = pathPosixNormalize(pathPosixJoin(pathPosixDirname(sourcePath), specifier));
|
|
97
|
+
const candidates = [base];
|
|
98
|
+
for (const extension of SOURCE_EXTENSIONS) candidates.push(`${base}${extension}`);
|
|
99
|
+
for (const extension of SOURCE_EXTENSIONS) candidates.push(`${base}/index${extension}`);
|
|
100
|
+
return candidates.find((candidate) => knownSources.has(candidate)) ?? null;
|
|
101
|
+
}
|
|
102
|
+
function pathPosixNormalize(value) {
|
|
103
|
+
return value.replace(/\\/g, "/").split("/").reduce((segments, segment) => {
|
|
104
|
+
if (segment === "" || segment === ".") return segments;
|
|
105
|
+
if (segment === ".." && segments.length > 0 && segments[segments.length - 1] !== "..") {
|
|
106
|
+
segments.pop();
|
|
107
|
+
return segments;
|
|
108
|
+
}
|
|
109
|
+
segments.push(segment);
|
|
110
|
+
return segments;
|
|
111
|
+
}, []).join("/");
|
|
112
|
+
}
|
|
113
|
+
function pathPosixJoin(...parts) {
|
|
114
|
+
return parts.filter((part) => part !== "").join("/");
|
|
115
|
+
}
|
|
116
|
+
function pathPosixDirname(value) {
|
|
117
|
+
const index = value.lastIndexOf("/");
|
|
118
|
+
return index === -1 ? "" : value.slice(0, index);
|
|
119
|
+
}
|
|
120
|
+
function toImportSpecifier(fromFile, toFile) {
|
|
121
|
+
let specifier = path.relative(path.dirname(fromFile), toFile).split(path.sep).join("/").replace(/\.(tsx?|jsx?|mts?|cts?|mjs?|cjs?)$/, "");
|
|
122
|
+
specifier = specifier.replace(/\/index$/, "");
|
|
123
|
+
if (!specifier.startsWith(".")) specifier = `./${specifier}`;
|
|
124
|
+
return specifier;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Rewrite registry-internal relative imports so references between installed
|
|
128
|
+
* files keep resolving at their configured destinations. Bare package imports
|
|
129
|
+
* are left untouched.
|
|
130
|
+
*/
|
|
131
|
+
function rewriteRelativeImports(options) {
|
|
132
|
+
const { content, sourcePath, destPath, sourceToDest } = options;
|
|
133
|
+
const knownSources = new Set(sourceToDest.keys());
|
|
134
|
+
return content.replace(IMPORT_PATTERN, (match, prefix, quote, specifier) => {
|
|
135
|
+
const resolved = resolveSourceFile(sourcePath, specifier, knownSources);
|
|
136
|
+
if (!resolved) return match;
|
|
137
|
+
const targetDest = sourceToDest.get(resolved);
|
|
138
|
+
if (!targetDest || targetDest === destPath) return match;
|
|
139
|
+
return `${prefix}${quote}${toImportSpecifier(destPath, targetDest)}${quote}`;
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
//#endregion
|
|
143
|
+
//#region src/lib/paths.ts
|
|
144
|
+
var UnsafePathError = class extends Error {
|
|
145
|
+
destination;
|
|
146
|
+
alias;
|
|
147
|
+
constructor(alias, destination, message) {
|
|
148
|
+
super(message);
|
|
149
|
+
this.name = "UnsafePathError";
|
|
150
|
+
this.alias = alias;
|
|
151
|
+
this.destination = destination;
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
const WINDOWS_ABSOLUTE = /^[A-Za-z]:[\\/]/;
|
|
155
|
+
/** Strip the `@/` or `~/` prefix and return the root-relative alias path. */
|
|
156
|
+
function aliasToRelativePath(alias, label) {
|
|
157
|
+
if (typeof alias !== "string" || alias.trim() === "") throw new UnsafePathError(alias, "", `The ${label} alias must be a non-empty string.`);
|
|
158
|
+
const original = alias.trim();
|
|
159
|
+
let value = original;
|
|
160
|
+
if (value.startsWith("@/") || value.startsWith("~/")) value = value.slice(2);
|
|
161
|
+
if (value.includes("\0")) throw new UnsafePathError(original, "", `The ${label} alias contains a null byte and cannot be used.`);
|
|
162
|
+
if (path.isAbsolute(value) || WINDOWS_ABSOLUTE.test(value)) throw new UnsafePathError(original, value, `The ${label} alias "${original}" is absolute. Aliases must resolve inside the consumer root.`);
|
|
163
|
+
return value === "" ? "." : value;
|
|
164
|
+
}
|
|
165
|
+
function isWithinRoot(root, destination) {
|
|
166
|
+
const relative = path.relative(root, destination);
|
|
167
|
+
return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Resolve an existing ancestor through `realpath` and append the missing
|
|
171
|
+
* segments, so a symlinked parent that points outside the root is detected
|
|
172
|
+
* before any directory or file is created.
|
|
173
|
+
*/
|
|
174
|
+
function realpathAllowMissing(target) {
|
|
175
|
+
let current = target;
|
|
176
|
+
const missing = [];
|
|
177
|
+
while (!existsSync(current)) {
|
|
178
|
+
const parent = path.dirname(current);
|
|
179
|
+
if (parent === current) break;
|
|
180
|
+
missing.unshift(path.basename(current));
|
|
181
|
+
current = parent;
|
|
182
|
+
}
|
|
183
|
+
const base = existsSync(current) ? realpathSync(current) : current;
|
|
184
|
+
return path.join(base, ...missing);
|
|
185
|
+
}
|
|
186
|
+
function assertWithinRoot(root, destination, label) {
|
|
187
|
+
if (!isWithinRoot(root, destination)) throw new UnsafePathError(label, destination, `The ${label} destination "${destination}" resolves outside the consumer root ${root}.`);
|
|
188
|
+
if (!isWithinRoot(realpathSync(root), realpathAllowMissing(destination))) throw new UnsafePathError(label, destination, `The ${label} destination "${destination}" resolves outside the consumer root ${root} through a symbolic link.`);
|
|
189
|
+
}
|
|
190
|
+
/** Resolve a configured alias against the consumer root and enforce containment. */
|
|
191
|
+
function resolveAliasWithinRoot(root, alias, label) {
|
|
192
|
+
const relative = aliasToRelativePath(alias, label);
|
|
193
|
+
const destination = path.resolve(root, relative);
|
|
194
|
+
assertWithinRoot(root, destination, label);
|
|
195
|
+
return destination;
|
|
196
|
+
}
|
|
197
|
+
//#endregion
|
|
198
|
+
//#region src/lib/install.ts
|
|
199
|
+
var UnknownItemsError = class extends Error {
|
|
200
|
+
names;
|
|
201
|
+
constructor(names) {
|
|
202
|
+
super(`unknown component(s): ${names.join(", ")}`);
|
|
203
|
+
this.name = "UnknownItemsError";
|
|
204
|
+
this.names = names;
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
var UnsupportedItemError = class extends Error {
|
|
208
|
+
constructor(message) {
|
|
209
|
+
super(message);
|
|
210
|
+
this.name = "UnsupportedItemError";
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
const SAFE_ITEM_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
214
|
+
const SAFE_FILE_BASENAME = /^[A-Za-z0-9._-]+$/;
|
|
215
|
+
const REWRITE_EXTENSIONS = /\.(tsx?|jsx?|mts?|cts?)$/;
|
|
216
|
+
function collectRegistryDependencies(targets, itemsByName) {
|
|
217
|
+
const planned = /* @__PURE__ */ new Set();
|
|
218
|
+
const ordered = [];
|
|
219
|
+
const visit = (name) => {
|
|
220
|
+
if (planned.has(name)) return;
|
|
221
|
+
const item = itemsByName.get(name);
|
|
222
|
+
if (!item) return;
|
|
223
|
+
planned.add(name);
|
|
224
|
+
for (const dependency of [...item.registryDependencies].sort()) visit(dependency);
|
|
225
|
+
ordered.push(name);
|
|
226
|
+
};
|
|
227
|
+
for (const target of targets) visit(target);
|
|
228
|
+
return ordered;
|
|
229
|
+
}
|
|
230
|
+
function relativeDisplayPath(root, destination) {
|
|
231
|
+
return path.relative(root, destination).split(path.sep).join("/");
|
|
232
|
+
}
|
|
233
|
+
function extensionOf(alias) {
|
|
234
|
+
return path.extname(alias);
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Build every destination and its rewritten content before touching the
|
|
238
|
+
* filesystem. Unknown items, unsafe destinations, directory collisions, and
|
|
239
|
+
* conflicts are all detected here so a rejected request writes nothing.
|
|
240
|
+
*/
|
|
241
|
+
function buildInstallPlan(options) {
|
|
242
|
+
const { registry, config, root, targets, overwrite } = options;
|
|
243
|
+
const itemsByName = new Map(registry.items.map((item) => [item.name, item]));
|
|
244
|
+
const unknown = targets.filter((target) => !itemsByName.has(target));
|
|
245
|
+
if (unknown.length > 0) throw new UnknownItemsError(unknown);
|
|
246
|
+
const plannedNames = collectRegistryDependencies(targets, itemsByName);
|
|
247
|
+
const componentsDir = resolveAliasWithinRoot(root, config.aliases.components, "components");
|
|
248
|
+
const utilsAlias = config.aliases.utils;
|
|
249
|
+
let utilsDestination = resolveAliasWithinRoot(root, utilsAlias, "utils");
|
|
250
|
+
if (extensionOf(utilsAlias) === "") {
|
|
251
|
+
utilsDestination = `${utilsDestination}.ts`;
|
|
252
|
+
assertWithinRoot(root, utilsDestination, "utils");
|
|
253
|
+
}
|
|
254
|
+
const sourceToDest = /* @__PURE__ */ new Map();
|
|
255
|
+
const destinationOwner = /* @__PURE__ */ new Map();
|
|
256
|
+
for (const name of plannedNames) {
|
|
257
|
+
const item = itemsByName.get(name);
|
|
258
|
+
if (!SAFE_ITEM_NAME.test(item.name)) throw new UnsupportedItemError(`Registry item "${item.name}" has an unsafe name and cannot be installed.`);
|
|
259
|
+
for (const file of item.files) {
|
|
260
|
+
const baseName = path.posix.basename(file.path);
|
|
261
|
+
if (!SAFE_FILE_BASENAME.test(baseName) || baseName === "." || baseName === "..") throw new UnsupportedItemError(`Registry item "${item.name}" contains an unsafe file path: ${file.path}`);
|
|
262
|
+
let destination;
|
|
263
|
+
if (file.path.startsWith("lib/")) {
|
|
264
|
+
if (item.name !== "utils") throw new UnsupportedItemError(`Registry item "${item.name}" targets the shared lib directory, which is reserved for the "utils" item.`);
|
|
265
|
+
destination = utilsDestination;
|
|
266
|
+
} else destination = path.join(componentsDir, item.name, baseName);
|
|
267
|
+
assertWithinRoot(root, destination, `"${item.name}"`);
|
|
268
|
+
const owner = destinationOwner.get(destination);
|
|
269
|
+
if (owner !== void 0 && owner !== file.path) throw new UnsupportedItemError(`Registry files "${owner}" and "${file.path}" resolve to the same destination: ${destination}`);
|
|
270
|
+
destinationOwner.set(destination, file.path);
|
|
271
|
+
sourceToDest.set(file.path, destination);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
const conflicts = [];
|
|
275
|
+
for (const destination of destinationOwner.keys()) {
|
|
276
|
+
let entry;
|
|
277
|
+
try {
|
|
278
|
+
entry = lstatSync(destination);
|
|
279
|
+
} catch {
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
if (entry.isSymbolicLink()) {
|
|
283
|
+
let realDestination;
|
|
284
|
+
try {
|
|
285
|
+
realDestination = realpathSync(destination);
|
|
286
|
+
} catch {
|
|
287
|
+
throw new UnsupportedItemError(`Cannot write "${destination}" because it is a symbolic link with a missing target.`);
|
|
288
|
+
}
|
|
289
|
+
if (!isWithinRoot(realpathSync(root), realDestination)) throw new UnsafePathError(destinationOwner.get(destination) ?? "destination", destination, `The destination "${destination}" resolves outside the consumer root ${root} through a symbolic link.`);
|
|
290
|
+
}
|
|
291
|
+
if (entry.isDirectory()) throw new UnsupportedItemError(`Cannot write "${destination}" because a directory already exists at that path.`);
|
|
292
|
+
if (!overwrite) conflicts.push(relativeDisplayPath(root, destination));
|
|
293
|
+
}
|
|
294
|
+
const writes = [];
|
|
295
|
+
for (const name of plannedNames) {
|
|
296
|
+
const item = itemsByName.get(name);
|
|
297
|
+
for (const file of item.files) {
|
|
298
|
+
const destination = sourceToDest.get(file.path);
|
|
299
|
+
const content = REWRITE_EXTENSIONS.test(file.path) ? rewriteRelativeImports({
|
|
300
|
+
content: file.content,
|
|
301
|
+
sourcePath: file.path,
|
|
302
|
+
destPath: destination,
|
|
303
|
+
sourceToDest
|
|
304
|
+
}) : file.content;
|
|
305
|
+
writes.push({
|
|
306
|
+
item: item.name,
|
|
307
|
+
destination,
|
|
308
|
+
relativeDestination: relativeDisplayPath(root, destination),
|
|
309
|
+
content
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
const dependencies = /* @__PURE__ */ new Set();
|
|
314
|
+
for (const name of plannedNames) {
|
|
315
|
+
const item = itemsByName.get(name);
|
|
316
|
+
for (const dependency of item.dependencies) dependencies.add(dependency);
|
|
317
|
+
}
|
|
318
|
+
return {
|
|
319
|
+
writes,
|
|
320
|
+
dependencies: [...dependencies].sort(),
|
|
321
|
+
conflicts: conflicts.sort()
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
//#endregion
|
|
325
|
+
//#region src/lib/output.ts
|
|
326
|
+
/** Print an actionable error to stderr and mark the process as failed. */
|
|
327
|
+
function printError(message) {
|
|
328
|
+
console.error(pc.red(`usalyt: ${message}`));
|
|
329
|
+
process.exitCode = 1;
|
|
330
|
+
}
|
|
331
|
+
//#endregion
|
|
332
|
+
//#region src/lib/registry.ts
|
|
333
|
+
var RegistryLoadError = class extends Error {
|
|
334
|
+
constructor(message) {
|
|
335
|
+
super(message);
|
|
336
|
+
this.name = "RegistryLoadError";
|
|
337
|
+
}
|
|
338
|
+
};
|
|
339
|
+
const require = createRequire(import.meta.url);
|
|
340
|
+
/**
|
|
341
|
+
* Resolve the registry through Node package resolution so the CLI works from
|
|
342
|
+
* any working directory once `@usalyt/registry` is installed. The relative
|
|
343
|
+
* candidates are a development-only fallback for the monorepo layout and are
|
|
344
|
+
* never based on the current working directory.
|
|
345
|
+
*/
|
|
346
|
+
function resolveRegistryPath() {
|
|
347
|
+
try {
|
|
348
|
+
return require.resolve("@usalyt/registry/registry.json");
|
|
349
|
+
} catch {
|
|
350
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
351
|
+
const candidates = [path.resolve(here, "../../registry/registry.json"), path.resolve(here, "../registry/registry.json")];
|
|
352
|
+
for (const candidate of candidates) if (existsSync(candidate)) return candidate;
|
|
353
|
+
throw new RegistryLoadError("Could not locate the packaged @usalyt/registry/registry.json. Reinstall @usalyt/cli so its @usalyt/registry dependency is present, then retry.");
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
function isRecord(value) {
|
|
357
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
358
|
+
}
|
|
359
|
+
function validateRegistry(value, registryPath) {
|
|
360
|
+
if (!isRecord(value)) throw new RegistryLoadError(`Registry at ${registryPath} is not a JSON object.`);
|
|
361
|
+
if (typeof value.name !== "string" || typeof value.version !== "string") throw new RegistryLoadError(`Registry at ${registryPath} is missing "name" or "version".`);
|
|
362
|
+
if (!Array.isArray(value.items) || value.items.length === 0) throw new RegistryLoadError(`Registry at ${registryPath} contains no items.`);
|
|
363
|
+
for (const item of value.items) {
|
|
364
|
+
if (!isRecord(item) || typeof item.name !== "string" || typeof item.type !== "string") throw new RegistryLoadError(`Registry at ${registryPath} contains an invalid item.`);
|
|
365
|
+
if (!Array.isArray(item.files) || item.files.length === 0) throw new RegistryLoadError(`Registry item "${item.name}" contains no files.`);
|
|
366
|
+
for (const file of item.files) if (!isRecord(file) || typeof file.path !== "string" || typeof file.content !== "string") throw new RegistryLoadError(`Registry item "${item.name}" contains an invalid file entry.`);
|
|
367
|
+
}
|
|
368
|
+
return value;
|
|
369
|
+
}
|
|
370
|
+
function loadRegistry() {
|
|
371
|
+
const registryPath = resolveRegistryPath();
|
|
372
|
+
let raw;
|
|
373
|
+
try {
|
|
374
|
+
raw = readFileSync(registryPath, "utf8");
|
|
375
|
+
} catch (error) {
|
|
376
|
+
throw new RegistryLoadError(`Could not read the packaged registry at ${registryPath}: ${error.message}`);
|
|
377
|
+
}
|
|
378
|
+
let parsed;
|
|
379
|
+
try {
|
|
380
|
+
parsed = JSON.parse(raw);
|
|
381
|
+
} catch (error) {
|
|
382
|
+
throw new RegistryLoadError(`The packaged registry at ${registryPath} is not valid JSON: ${error.message}`);
|
|
383
|
+
}
|
|
384
|
+
return {
|
|
385
|
+
registry: validateRegistry(parsed, registryPath),
|
|
386
|
+
registryPath
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
//#endregion
|
|
390
|
+
//#region src/commands/add.ts
|
|
391
|
+
function normalizePositionals(values) {
|
|
392
|
+
const names = values.map((value) => String(value)).flatMap((value) => value.split(/\s+/)).map((value) => value.trim()).filter(Boolean);
|
|
393
|
+
return [...new Set(names)];
|
|
394
|
+
}
|
|
395
|
+
async function confirmInstall(command) {
|
|
396
|
+
const rl = createInterface({
|
|
397
|
+
input: process.stdin,
|
|
398
|
+
output: process.stdout
|
|
399
|
+
});
|
|
400
|
+
try {
|
|
401
|
+
const answer = await rl.question(`Run "${command}" now? (y/N): `);
|
|
402
|
+
return /^y(es)?$/i.test(answer.trim());
|
|
403
|
+
} finally {
|
|
404
|
+
rl.close();
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
function runPnpmAdd(root, dependencies) {
|
|
408
|
+
const result = spawnSync("pnpm", ["add", ...dependencies], {
|
|
409
|
+
cwd: root,
|
|
410
|
+
stdio: "inherit"
|
|
411
|
+
});
|
|
412
|
+
if (result.error) {
|
|
413
|
+
printError(`could not run pnpm: ${result.error.message}`);
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
if (result.status !== 0) printError(`pnpm add exited with status ${String(result.status)}.`);
|
|
417
|
+
}
|
|
418
|
+
const addCommand = defineCommand({
|
|
419
|
+
meta: {
|
|
420
|
+
name: "add",
|
|
421
|
+
description: "Add registry components and their dependencies to your project"
|
|
422
|
+
},
|
|
423
|
+
args: {
|
|
424
|
+
components: {
|
|
425
|
+
type: "positional",
|
|
426
|
+
description: "Name of the component(s) to add",
|
|
427
|
+
required: false
|
|
428
|
+
},
|
|
429
|
+
all: {
|
|
430
|
+
type: "boolean",
|
|
431
|
+
description: "Add every item in the registry",
|
|
432
|
+
alias: "a"
|
|
433
|
+
},
|
|
434
|
+
yes: {
|
|
435
|
+
type: "boolean",
|
|
436
|
+
description: "Confirm dependency installation without prompting",
|
|
437
|
+
alias: "y"
|
|
438
|
+
},
|
|
439
|
+
overwrite: {
|
|
440
|
+
type: "boolean",
|
|
441
|
+
description: "Replace existing files",
|
|
442
|
+
alias: "o"
|
|
443
|
+
},
|
|
444
|
+
install: {
|
|
445
|
+
type: "boolean",
|
|
446
|
+
description: "Run the printed pnpm add command when consent is confirmed"
|
|
447
|
+
}
|
|
448
|
+
},
|
|
449
|
+
async run({ args }) {
|
|
450
|
+
const root = process.cwd();
|
|
451
|
+
let registry;
|
|
452
|
+
try {
|
|
453
|
+
({registry} = loadRegistry());
|
|
454
|
+
} catch (error) {
|
|
455
|
+
printError(error instanceof RegistryLoadError ? error.message : String(error));
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
458
|
+
const positionals = Array.isArray(args._) ? args._ : [];
|
|
459
|
+
const targets = args.all ? [...registry.items.map((item) => item.name)].sort() : normalizePositionals(positionals);
|
|
460
|
+
if (targets.length === 0) {
|
|
461
|
+
printError("no components specified. Pass one or more component names or --all.");
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
let config;
|
|
465
|
+
try {
|
|
466
|
+
config = readConfig(root) ?? defaultConfig();
|
|
467
|
+
} catch (error) {
|
|
468
|
+
printError(error.message);
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
let plan;
|
|
472
|
+
try {
|
|
473
|
+
plan = buildInstallPlan({
|
|
474
|
+
registry,
|
|
475
|
+
config,
|
|
476
|
+
root,
|
|
477
|
+
targets,
|
|
478
|
+
overwrite: Boolean(args.overwrite)
|
|
479
|
+
});
|
|
480
|
+
} catch (error) {
|
|
481
|
+
if (error instanceof UnknownItemsError) {
|
|
482
|
+
printError(`${error.message}.`);
|
|
483
|
+
console.error("Run \"usalyt list\" to see the available components.");
|
|
484
|
+
} else if (error instanceof UnsafePathError) printError(error.message);
|
|
485
|
+
else if (error instanceof UnsupportedItemError) printError(error.message);
|
|
486
|
+
else printError(error.message);
|
|
487
|
+
console.error("No files were written.");
|
|
488
|
+
return;
|
|
489
|
+
}
|
|
490
|
+
if (plan.conflicts.length > 0) {
|
|
491
|
+
printError("refusing to overwrite existing files without --overwrite:");
|
|
492
|
+
for (const conflict of plan.conflicts) console.error(` - ${conflict}`);
|
|
493
|
+
console.error("No files were written.");
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
try {
|
|
497
|
+
for (const write of plan.writes) {
|
|
498
|
+
mkdirSync(path.dirname(write.destination), { recursive: true });
|
|
499
|
+
writeFileSync(write.destination, write.content, "utf8");
|
|
500
|
+
}
|
|
501
|
+
} catch (error) {
|
|
502
|
+
printError(`could not write the planned files: ${error.message}. Some files may already have been written.`);
|
|
503
|
+
return;
|
|
504
|
+
}
|
|
505
|
+
const installedItems = new Set(plan.writes.map((write) => write.item)).size;
|
|
506
|
+
const dependencyCount = installedItems - targets.length;
|
|
507
|
+
console.log(`Installed ${installedItems} item(s) (${targets.length} requested, ${dependencyCount} registry dependencies):`);
|
|
508
|
+
for (const write of plan.writes) console.log(` + ${write.relativeDestination}`);
|
|
509
|
+
if (plan.dependencies.length === 0) {
|
|
510
|
+
console.log("No npm dependencies required.");
|
|
511
|
+
return;
|
|
512
|
+
}
|
|
513
|
+
const installCommand = `pnpm add ${plan.dependencies.join(" ")}`;
|
|
514
|
+
console.log(`Dependencies: ${installCommand}`);
|
|
515
|
+
if (!args.install) {
|
|
516
|
+
console.log("Dependencies were not installed. Run the command above, or pass --install --yes to execute it.");
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
if (!args.yes) {
|
|
520
|
+
if (process.stdin.isTTY && process.stdout.isTTY) if (await confirmInstall(installCommand)) runPnpmAdd(root, plan.dependencies);
|
|
521
|
+
else console.log("Dependencies were not installed.");
|
|
522
|
+
else console.log("Dependencies were not installed because consent was not confirmed. Pass --yes to execute the printed command.");
|
|
523
|
+
return;
|
|
524
|
+
}
|
|
525
|
+
runPnpmAdd(root, plan.dependencies);
|
|
526
|
+
}
|
|
527
|
+
});
|
|
528
|
+
//#endregion
|
|
529
|
+
//#region src/commands/init.ts
|
|
530
|
+
function aliasFromPath(value, stripExtension = false) {
|
|
531
|
+
const normalized = value.trim().replace(/\\/g, "/").replace(/^\.?\//, "");
|
|
532
|
+
return `@/${stripExtension ? normalized.replace(/\.(tsx?|jsx?)$/, "") : normalized}`;
|
|
533
|
+
}
|
|
534
|
+
async function promptForConfig(defaults) {
|
|
535
|
+
const rl = createInterface({
|
|
536
|
+
input: process.stdin,
|
|
537
|
+
output: process.stdout
|
|
538
|
+
});
|
|
539
|
+
try {
|
|
540
|
+
const defaultComponents = defaults.aliases.components.replace(/^@\//, "");
|
|
541
|
+
const defaultUtils = `${defaults.aliases.utils.replace(/^@\//, "")}.ts`;
|
|
542
|
+
const componentsAnswer = await rl.question(`Components directory (relative to the project root) [${defaultComponents}]: `);
|
|
543
|
+
const utilsAnswer = await rl.question(`Utils file (relative to the project root) [${defaultUtils}]: `);
|
|
544
|
+
const componentsPath = componentsAnswer.trim() || defaultComponents;
|
|
545
|
+
const utilsPath = utilsAnswer.trim() || defaultUtils;
|
|
546
|
+
return {
|
|
547
|
+
...defaults,
|
|
548
|
+
aliases: {
|
|
549
|
+
components: aliasFromPath(componentsPath),
|
|
550
|
+
utils: aliasFromPath(utilsPath, true)
|
|
551
|
+
}
|
|
552
|
+
};
|
|
553
|
+
} finally {
|
|
554
|
+
rl.close();
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
//#endregion
|
|
558
|
+
//#region src/index.ts
|
|
559
|
+
runMain(defineCommand({
|
|
560
|
+
meta: {
|
|
561
|
+
name: "usalyt",
|
|
562
|
+
version: "0.0.1",
|
|
563
|
+
description: "Usalyt component distribution CLI"
|
|
564
|
+
},
|
|
565
|
+
subCommands: {
|
|
566
|
+
init: defineCommand({
|
|
567
|
+
meta: {
|
|
568
|
+
name: "init",
|
|
569
|
+
description: "Create usalyt.json with the component and utility aliases"
|
|
570
|
+
},
|
|
571
|
+
args: {
|
|
572
|
+
yes: {
|
|
573
|
+
type: "boolean",
|
|
574
|
+
description: "Use the default aliases without prompting",
|
|
575
|
+
alias: "y"
|
|
576
|
+
},
|
|
577
|
+
overwrite: {
|
|
578
|
+
type: "boolean",
|
|
579
|
+
description: "Replace an existing usalyt.json",
|
|
580
|
+
alias: "o"
|
|
581
|
+
}
|
|
582
|
+
},
|
|
583
|
+
async run({ args }) {
|
|
584
|
+
const configPath = configPathFor(process.cwd());
|
|
585
|
+
if (existsSync(configPath) && !args.overwrite) {
|
|
586
|
+
printError(`${CONFIG_FILE} already exists at ${configPath}. Pass --overwrite to replace it.`);
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
try {
|
|
590
|
+
if (lstatSync(configPath).isSymbolicLink()) {
|
|
591
|
+
printError(`${CONFIG_FILE} at ${configPath} is a symbolic link. Remove the link and run init again.`);
|
|
592
|
+
return;
|
|
593
|
+
}
|
|
594
|
+
} catch {}
|
|
595
|
+
const defaults = defaultConfig();
|
|
596
|
+
const config = !args.yes && Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY) ? await promptForConfig(defaults) : defaults;
|
|
597
|
+
try {
|
|
598
|
+
writeFileSync(configPath, serializeConfig(config), "utf8");
|
|
599
|
+
} catch (error) {
|
|
600
|
+
printError(`could not write ${configPath}: ${error.message}`);
|
|
601
|
+
return;
|
|
602
|
+
}
|
|
603
|
+
console.log(`Created ${CONFIG_FILE} at ${configPath}`);
|
|
604
|
+
console.log(` components: ${config.aliases.components}`);
|
|
605
|
+
console.log(` utils: ${config.aliases.utils}`);
|
|
606
|
+
}
|
|
607
|
+
}),
|
|
608
|
+
add: addCommand,
|
|
609
|
+
list: defineCommand({
|
|
610
|
+
meta: {
|
|
611
|
+
name: "list",
|
|
612
|
+
description: "List the items in the packaged Usalyt registry"
|
|
613
|
+
},
|
|
614
|
+
args: { json: {
|
|
615
|
+
type: "boolean",
|
|
616
|
+
description: "Print machine-readable JSON"
|
|
617
|
+
} },
|
|
618
|
+
run({ args }) {
|
|
619
|
+
let registry;
|
|
620
|
+
try {
|
|
621
|
+
({registry} = loadRegistry());
|
|
622
|
+
} catch (error) {
|
|
623
|
+
printError(error.message);
|
|
624
|
+
return;
|
|
625
|
+
}
|
|
626
|
+
if (args.json) {
|
|
627
|
+
const payload = {
|
|
628
|
+
name: registry.name,
|
|
629
|
+
version: registry.version,
|
|
630
|
+
count: registry.items.length,
|
|
631
|
+
items: registry.items.map((item) => ({
|
|
632
|
+
name: item.name,
|
|
633
|
+
type: item.type,
|
|
634
|
+
title: item.title,
|
|
635
|
+
description: item.description,
|
|
636
|
+
license: item.license,
|
|
637
|
+
dependencies: item.dependencies,
|
|
638
|
+
registryDependencies: item.registryDependencies
|
|
639
|
+
}))
|
|
640
|
+
};
|
|
641
|
+
process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
|
|
642
|
+
return;
|
|
643
|
+
}
|
|
644
|
+
console.log(`${registry.name} registry ${registry.version}: ${registry.items.length} items`);
|
|
645
|
+
for (const item of registry.items) console.log(` ${pc.bold(item.name)} (${item.type}) - ${item.description}`);
|
|
646
|
+
console.log("");
|
|
647
|
+
console.log("Add components with: usalyt add <component>");
|
|
648
|
+
}
|
|
649
|
+
})
|
|
650
|
+
}
|
|
651
|
+
}));
|
|
652
|
+
//#endregion
|
|
653
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@usalyt/cli",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Usalyt component distribution CLI",
|
|
5
|
+
"bin": {
|
|
6
|
+
"usalyt": "./dist/index.mjs"
|
|
7
|
+
},
|
|
8
|
+
"type": "module",
|
|
9
|
+
"dependencies": {
|
|
10
|
+
"citty": "^0.2.2",
|
|
11
|
+
"picocolors": "^1.1.1",
|
|
12
|
+
"@usalyt/registry": "^0.0.1"
|
|
13
|
+
},
|
|
14
|
+
"devDependencies": {
|
|
15
|
+
"@types/node": "^26.1.1",
|
|
16
|
+
"tsdown": "^0.22.14",
|
|
17
|
+
"typescript": "^6.0.0"
|
|
18
|
+
},
|
|
19
|
+
"license": "GPL-3.0-only",
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "git+https://github.com/Usalyt/ui.git",
|
|
23
|
+
"directory": "usalyt/packages/cli"
|
|
24
|
+
},
|
|
25
|
+
"homepage": "https://github.com/Usalyt/ui",
|
|
26
|
+
"bugs": {
|
|
27
|
+
"url": "https://github.com/Usalyt/ui/issues"
|
|
28
|
+
},
|
|
29
|
+
"engines": {
|
|
30
|
+
"node": ">=20"
|
|
31
|
+
},
|
|
32
|
+
"publishConfig": {
|
|
33
|
+
"access": "public"
|
|
34
|
+
},
|
|
35
|
+
"files": [
|
|
36
|
+
"dist",
|
|
37
|
+
"src",
|
|
38
|
+
"tsdown.config.ts",
|
|
39
|
+
"README.md",
|
|
40
|
+
"LICENSE",
|
|
41
|
+
"NOTICE",
|
|
42
|
+
"THIRD_PARTY_NOTICES.md",
|
|
43
|
+
"CHANGELOG.md"
|
|
44
|
+
],
|
|
45
|
+
"scripts": {
|
|
46
|
+
"build": "tsdown",
|
|
47
|
+
"test": "pnpm build && node --test tests/cli.test.mjs"
|
|
48
|
+
}
|
|
6
49
|
}
|