@erbium-app/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +76 -2
  2. package/dist/index.js +2017 -0
  3. package/package.json +50 -4
package/dist/index.js ADDED
@@ -0,0 +1,2017 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
5
+ import * as NodeServices from "@effect/platform-node/NodeServices";
6
+ import { Console, Effect } from "effect";
7
+ import { Argument, CliError, Command, Flag } from "effect/cli";
8
+ // package.json
9
+ var package_default = {
10
+ name: "@erbium-app/cli",
11
+ version: "0.1.0",
12
+ description: "Install, track, and update Erbium UI source files.",
13
+ keywords: [
14
+ "cli",
15
+ "components",
16
+ "design-system",
17
+ "react",
18
+ "registry",
19
+ "shadcn",
20
+ "ui"
21
+ ],
22
+ homepage: "https://ui.erbium.app/docs/cli",
23
+ bugs: {
24
+ url: "https://github.com/erbium-app/erbium-ui/issues"
25
+ },
26
+ license: "MIT",
27
+ repository: {
28
+ type: "git",
29
+ url: "git+https://github.com/erbium-app/erbium-ui.git",
30
+ directory: "packages/cli"
31
+ },
32
+ bin: {
33
+ erbium: "./dist/index.js"
34
+ },
35
+ files: [
36
+ "dist",
37
+ "README.md"
38
+ ],
39
+ type: "module",
40
+ publishConfig: {
41
+ access: "public"
42
+ },
43
+ scripts: {
44
+ build: "bun build src/index.ts --target node --packages external --outfile dist/index.js",
45
+ prepack: "bun run build",
46
+ test: "bun run build && node --test test/*.test.ts",
47
+ typecheck: "tsc --noEmit"
48
+ },
49
+ dependencies: {
50
+ "@effect/platform-node": "4.1.4",
51
+ effect: "4.1.4",
52
+ "get-tsconfig": "5.0.0-beta.6"
53
+ },
54
+ devDependencies: {
55
+ typescript: "catalog:"
56
+ },
57
+ engines: {
58
+ node: ">=22.18.0"
59
+ }
60
+ };
61
+
62
+ // src/discovery.ts
63
+ import * as Schema5 from "effect/Schema";
64
+
65
+ // src/project.ts
66
+ import { lstat, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
67
+ import path from "node:path";
68
+ import { randomUUID } from "node:crypto";
69
+ import { getTsconfig, resolvePathAlias } from "get-tsconfig";
70
+ import * as Schema2 from "effect/Schema";
71
+
72
+ // src/revision.ts
73
+ import { createHash } from "node:crypto";
74
+ import * as Schema from "effect/Schema";
75
+ var rev = Schema.String.check(Schema.isPattern(/^[a-f0-9]{64}$/u));
76
+ var file = Schema.Struct({
77
+ content: Schema.String,
78
+ path: Schema.String,
79
+ target: Schema.String,
80
+ type: Schema.String
81
+ });
82
+ var payload = Schema.Struct({
83
+ dependencies: Schema.optionalKey(Schema.Array(Schema.String)),
84
+ devDependencies: Schema.optionalKey(Schema.Array(Schema.String)),
85
+ files: Schema.optionalKey(Schema.Array(file)),
86
+ name: Schema.String,
87
+ registryDependencies: Schema.optionalKey(Schema.Array(Schema.String)),
88
+ type: Schema.String
89
+ });
90
+ var catalogItem = Schema.Struct({
91
+ title: Schema.optionalKey(Schema.String),
92
+ description: Schema.optionalKey(Schema.String),
93
+ keywords: Schema.optionalKey(Schema.Array(Schema.String))
94
+ });
95
+ var releaseHistory = Schema.Array(Schema.Struct({
96
+ commit: Schema.String,
97
+ date: Schema.String,
98
+ changes: Schema.Record(Schema.String, Schema.NullOr(rev))
99
+ }));
100
+ var manifest = Schema.Struct({
101
+ catalog: Schema.optionalKey(Schema.Record(Schema.String, catalogItem)),
102
+ version: Schema.Literal(1),
103
+ items: Schema.Record(Schema.String, rev)
104
+ });
105
+ var snapshot = Schema.Struct({ id: Schema.String, item: payload });
106
+ var hash = (content) => createHash("sha256").update(content).digest("hex");
107
+ var revision = (value) => hash(JSON.stringify({ id: value.id, item: Schema.decodeUnknownSync(payload)(value.item) }));
108
+ var payloadKeys = new Set([
109
+ "$schema",
110
+ "author",
111
+ "categories",
112
+ "description",
113
+ "docs",
114
+ "meta",
115
+ "keywords",
116
+ "title",
117
+ ...Object.keys(payload.fields)
118
+ ]);
119
+ var snapshotFor = (id, input) => {
120
+ const unsupported = Object.keys(input).filter((key) => !payloadKeys.has(key));
121
+ if (unsupported.length > 0) {
122
+ throw new Error(`Unsupported install fields in ${id}: ${unsupported.join(", ")}`);
123
+ }
124
+ return { id, item: Schema.decodeUnknownSync(payload)(input) };
125
+ };
126
+ var parseJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Json));
127
+
128
+ // src/project.ts
129
+ var digest = Schema2.String.check(Schema2.isPattern(/^[a-f0-9]{64}$/u));
130
+ var trackedItem = Schema2.Struct({
131
+ revision: digest,
132
+ files: Schema2.Record(Schema2.String, digest),
133
+ dependencies: Schema2.Array(Schema2.String),
134
+ devDependencies: Schema2.Array(Schema2.String),
135
+ registryDependencies: Schema2.Array(Schema2.String)
136
+ });
137
+ var lockSchema = Schema2.Struct({
138
+ version: Schema2.Literal(1),
139
+ items: Schema2.Record(Schema2.String, trackedItem),
140
+ aliases: Schema2.optionalKey(Schema2.Record(Schema2.String, Schema2.String))
141
+ });
142
+ var configSchema = Schema2.Struct({
143
+ aliases: Schema2.Record(Schema2.String, Schema2.String),
144
+ tsx: Schema2.optionalKey(Schema2.Boolean)
145
+ });
146
+ var aliasTarget = /^@(?<alias>ui|components|hooks|lib)\/(?<suffix>.+)$/u;
147
+ var canonicalImport = /(?<quote>["'])@\/registry\/erbium\/(?<group>ui|components|hooks|lib|blocks)\/(?<name>[^"'\n]+)\k<quote>/gu;
148
+ var leadingTrivia = /^(?:#![^\r\n]*)?(?:\s+|\/\/[^\r\n]*|\/\*[\s\S]*?\*\/)*/u;
149
+ var reservedTargets = new Set([
150
+ ".erbium",
151
+ "components.json",
152
+ "package.json",
153
+ "package-lock.json",
154
+ "bun.lock",
155
+ "bun.lockb",
156
+ "pnpm-lock.yaml",
157
+ "yarn.lock"
158
+ ]);
159
+ var lockPath = ".erbium/lock.json";
160
+ var errorCode = Schema2.decodeUnknownOption(Schema2.Struct({ code: Schema2.Literal("ENOENT") }));
161
+ var readText = async (file) => {
162
+ try {
163
+ return await readFile(file, "utf-8");
164
+ } catch (error) {
165
+ if (errorCode(error)._tag !== "Some") {
166
+ throw error;
167
+ }
168
+ return;
169
+ }
170
+ };
171
+ var safePath = async (root, target) => {
172
+ const segments = target.split("/");
173
+ if (path.isAbsolute(target) || target.includes("\\") || segments.some((part) => !part || part === ".." || part === "." || part.includes(":")) || segments[0] === ".git" || segments[0] === "node_modules") {
174
+ throw new Error(`Unsafe project path: ${target}`);
175
+ }
176
+ const prefixes = segments.map((_part, index) => path.join(root, ...segments.slice(0, index + 1)));
177
+ const entries = await Promise.all(prefixes.map(async (entry) => {
178
+ try {
179
+ return await lstat(entry);
180
+ } catch (error) {
181
+ if (errorCode(error)._tag !== "Some") {
182
+ throw error;
183
+ }
184
+ return null;
185
+ }
186
+ }));
187
+ if (entries.some((entry) => entry?.isSymbolicLink() === true)) {
188
+ throw new Error(`Refusing to write through a symbolic link: ${target}`);
189
+ }
190
+ return path.join(root, ...segments);
191
+ };
192
+ var atomicWrite = async (file, text) => {
193
+ await mkdir(path.dirname(file), { recursive: true });
194
+ const temporary = `${file}.${randomUUID()}.tmp`;
195
+ try {
196
+ await writeFile(temporary, text, { flag: "wx" });
197
+ await rename(temporary, file);
198
+ } finally {
199
+ await rm(temporary, { force: true });
200
+ }
201
+ };
202
+ var loadLock = async (root) => {
203
+ const text = await readText(await safePath(root, lockPath));
204
+ return text === undefined ? { version: 1, items: {} } : Schema2.decodeUnknownSync(lockSchema)(parseJson(text));
205
+ };
206
+ var projectConfig = async (root) => {
207
+ const text = await readText(path.join(root, "components.json"));
208
+ if (text === undefined) {
209
+ throw new Error("Set up components.json with shadcn init first.");
210
+ }
211
+ const config = Schema2.decodeUnknownSync(configSchema)(parseJson(text));
212
+ const { components } = config.aliases;
213
+ if (components === undefined || components.length === 0 || config.tsx === false) {
214
+ throw new Error("Erbium requires a TypeScript shadcn project with a components alias.");
215
+ }
216
+ const prefix = components.slice(0, components.lastIndexOf("/"));
217
+ const aliases = {
218
+ components,
219
+ ui: config.aliases.ui ?? `${components}/ui`,
220
+ hooks: config.aliases.hooks ?? `${prefix}/hooks`,
221
+ lib: config.aliases.lib ?? `${prefix}/lib`,
222
+ blocks: `${components}/blocks`
223
+ };
224
+ return { aliases, tsconfig: getTsconfig(root) };
225
+ };
226
+ var aliasName = Schema2.decodeUnknownSync(Schema2.Literals(["ui", "components", "hooks", "lib", "blocks"]));
227
+ var importAlias = (config, group) => config.aliases[aliasName(group)];
228
+ var planFiles = (root, config, snapshot) => (snapshot.item.files ?? []).map((file) => {
229
+ let target = file.target.slice(2);
230
+ if (!file.target.startsWith("~/")) {
231
+ const match = aliasTarget.exec(file.target);
232
+ const alias = match?.groups?.alias;
233
+ const suffix = match?.groups?.suffix;
234
+ const [absolute] = alias !== undefined && suffix !== undefined && config.tsconfig !== undefined ? resolvePathAlias(config.tsconfig, `${importAlias(config, alias)}/${suffix}`) : [];
235
+ if (absolute === undefined) {
236
+ throw new Error(`Cannot resolve ${file.target} for ${snapshot.id}. Check components.json and tsconfig.json.`);
237
+ }
238
+ target = path.relative(root, absolute).split(path.sep).join("/");
239
+ }
240
+ if (target.startsWith(".erbium/") || reservedTargets.has(target) || /(?:^|\/)\.env(?:\.|$)/u.test(target)) {
241
+ throw new Error(`Protected install target: ${target}`);
242
+ }
243
+ const content = /\.tsx?$/u.test(target) && file.type !== "registry:file" && file.type !== "registry:item" ? file.content.replace(leadingTrivia, "").replaceAll(canonicalImport, (_match, quote, group, name) => `${quote}${importAlias(config, group)}/${name}${quote}`) : file.content;
244
+ return { content, target };
245
+ });
246
+ var validateAliases = async (root) => {
247
+ const config = await projectConfig(root);
248
+ const aliases = {};
249
+ for (const [name, specifier] of Object.entries(config.aliases)) {
250
+ const [resolved] = config.tsconfig === undefined ? [] : resolvePathAlias(config.tsconfig, `${specifier}/erbium-target`);
251
+ if (resolved === undefined) {
252
+ throw new Error(`Alias ${specifier} does not resolve. Check components.json and tsconfig.json.`);
253
+ }
254
+ aliases[name] = path.relative(root, path.dirname(resolved)).split(path.sep).join("/") || ".";
255
+ }
256
+ return aliases;
257
+ };
258
+
259
+ // src/registry-config.ts
260
+ import path2 from "node:path";
261
+ import { parseEnv } from "node:util";
262
+ import * as Schema3 from "effect/Schema";
263
+ var configFile = "erbium.config.json";
264
+ var decodeConfig = Schema3.decodeUnknownSync(Schema3.Struct({
265
+ registry: Schema3.Union([
266
+ Schema3.String,
267
+ Schema3.Struct({
268
+ url: Schema3.String,
269
+ headers: Schema3.optionalKey(Schema3.Record(Schema3.String, Schema3.String))
270
+ })
271
+ ])
272
+ }));
273
+ var http = /^https?:\/\//iu;
274
+ var variable = /\$\{(?<key>[a-z_][a-z\d_]*)\}/giu;
275
+ var isString = Schema3.is(Schema3.String);
276
+ var defaultRegistry = "https://ui.erbium.app/r/erbium";
277
+ var resolveLocation = (root, location) => {
278
+ if (!http.test(location)) {
279
+ if (location.trim() === "" || location.includes("://")) {
280
+ throw new Error("Use a registry directory or an HTTP(S) URL.");
281
+ }
282
+ return path2.resolve(root, location);
283
+ }
284
+ const url = new URL(location);
285
+ if (url.username || url.password || url.search || url.hash) {
286
+ throw new Error("Registry URLs cannot contain credentials, query parameters, or fragments.");
287
+ }
288
+ return url.href.replace(/\/+$/u, "");
289
+ };
290
+ var validateHeaders = (location, headers) => {
291
+ if (Object.keys(headers).length === 0) {
292
+ return;
293
+ }
294
+ const url = http.test(location) ? new URL(location) : undefined;
295
+ if (url === undefined || url.protocol !== "https:" && !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)) {
296
+ throw new Error("Registry headers require HTTPS or a loopback HTTP URL.");
297
+ }
298
+ for (const [name, template] of Object.entries(headers)) {
299
+ if (!/^[!#$%&'*+.^_`|~\w-]+$/u.test(name) || [...template.matchAll(variable)].length === 0) {
300
+ throw new Error(`Use a valid header name and a value containing a \${VARIABLE} placeholder.`);
301
+ }
302
+ }
303
+ };
304
+ var loadConfig = async (root) => {
305
+ const content = await readText(await safePath(root, configFile));
306
+ if (content === undefined) {
307
+ return null;
308
+ }
309
+ const { registry } = decodeConfig(parseJson(content));
310
+ return isString(registry) ? { url: registry } : registry;
311
+ };
312
+ var saveRegistryConfig = async (root, location, headers) => {
313
+ const entries = headers.map((header) => {
314
+ const separator = header.indexOf(":");
315
+ if (separator < 1) {
316
+ throw new Error("Use --header 'Name: value' with an environment placeholder.");
317
+ }
318
+ return [header.slice(0, separator).trim(), header.slice(separator + 1).trim()];
319
+ });
320
+ const templates = Object.fromEntries(entries);
321
+ validateHeaders(resolveLocation(root, location), templates);
322
+ const registry = entries.length === 0 ? location : { url: location, headers: templates };
323
+ const file = await safePath(root, configFile);
324
+ const content = `${JSON.stringify({ registry }, null, 2)}
325
+ `;
326
+ if (await readText(file) === content) {
327
+ return [];
328
+ }
329
+ await atomicWrite(file, content);
330
+ return [configFile];
331
+ };
332
+ var hasRegistryConfig = async (root) => await loadConfig(root) !== null;
333
+ var registryRequest = async (root, override) => {
334
+ const config = await loadConfig(root);
335
+ const location = resolveLocation(root, override || (config?.url ?? defaultRegistry));
336
+ const templates = config?.headers !== undefined && location === resolveLocation(root, config.url) ? config.headers : {};
337
+ validateHeaders(location, templates);
338
+ if (!http.test(location)) {
339
+ return { location, headers: undefined };
340
+ }
341
+ const url = new URL(location);
342
+ const headers = new Headers;
343
+ if (Object.keys(templates).length > 0) {
344
+ const [env, local] = await Promise.all([".env", ".env.local"].map(async (file) => parseEnv(await readText(path2.join(root, file)) ?? "")));
345
+ const fileEnv = new Map(Object.entries({ ...env, ...local }));
346
+ for (const [name, template] of Object.entries(templates)) {
347
+ const value = template.replaceAll(variable, (_match, key) => {
348
+ const secret = process.env[key] ?? fileEnv.get(key);
349
+ if (secret === undefined || secret.length === 0) {
350
+ throw new Error(`Set ${key} to authenticate with the registry.`);
351
+ }
352
+ return secret;
353
+ });
354
+ try {
355
+ headers.set(name, value);
356
+ } catch {
357
+ throw new Error("Invalid value for an authenticated registry header.");
358
+ }
359
+ }
360
+ } else if (url.origin !== new URL(defaultRegistry).origin && (process.env.ERBIUM_REGISTRY_TOKEN ?? "") !== "") {
361
+ validateHeaders(location, { Authorization: `Bearer \${ERBIUM_REGISTRY_TOKEN}` });
362
+ try {
363
+ headers.set("Authorization", `Bearer ${process.env.ERBIUM_REGISTRY_TOKEN}`);
364
+ } catch {
365
+ throw new Error("Invalid ERBIUM_REGISTRY_TOKEN value.");
366
+ }
367
+ }
368
+ return { location, headers: [...headers].length === 0 ? undefined : headers };
369
+ };
370
+
371
+ // src/registry.ts
372
+ import { readFile as readFile2 } from "node:fs/promises";
373
+ import path3 from "node:path";
374
+ import * as Schema4 from "effect/Schema";
375
+ var itemId = /^@(?:erbium|erbium-examples)\/[a-z0-9][a-z0-9-]*$/u;
376
+ var normalizeItem = (value) => {
377
+ const id = value.includes("/") ? value : `@erbium/${value}`;
378
+ if (!itemId.test(id)) {
379
+ throw new Error(`Unsupported Erbium registry item: ${value}`);
380
+ }
381
+ return id;
382
+ };
383
+ var readRegistry = async ({ location, headers }, file) => {
384
+ if (!/^https?:\/\//u.test(location)) {
385
+ return parseJson(await readFile2(path3.join(location, file), "utf-8"));
386
+ }
387
+ const endpoint = new URL(`${location}/${file}`);
388
+ const options = { signal: AbortSignal.timeout(15000) };
389
+ if (headers !== undefined) {
390
+ options.headers = headers;
391
+ options.redirect = "error";
392
+ }
393
+ const response = await fetch(endpoint, options);
394
+ if (!response.ok) {
395
+ throw new Error(`Registry returned HTTP ${response.status} for ${file}.`);
396
+ }
397
+ return parseJson(await response.text());
398
+ };
399
+ var openRegistry = async (root, location) => {
400
+ const request = await registryRequest(root, location);
401
+ const { items, catalog = {} } = Schema4.decodeUnknownSync(manifest)(await readRegistry(request, "index.json"));
402
+ return {
403
+ items,
404
+ catalog,
405
+ async history() {
406
+ const releases = Schema4.decodeUnknownSync(releaseHistory)(await readRegistry(request, "history.json"));
407
+ const published = new Map;
408
+ return releases.toReversed().map(({ commit, date, changes }) => {
409
+ for (const [id, digest] of Object.entries(changes)) {
410
+ if (digest === null) {
411
+ published.delete(id);
412
+ } else {
413
+ published.set(id, digest);
414
+ }
415
+ }
416
+ return { commit, date, items: Object.fromEntries(published) };
417
+ }).toReversed();
418
+ },
419
+ async load(id, digest) {
420
+ const checked = Schema4.decodeUnknownSync(rev)(digest);
421
+ const raw = await readRegistry(request, `revisions/${checked}.json`);
422
+ const decoded = Schema4.decodeUnknownSync(snapshot)(raw);
423
+ const value = snapshotFor(decoded.id, decoded.item);
424
+ if (value.id !== id || value.item.name !== id.split("/")[1] || revision(value) !== digest) {
425
+ throw new Error(`Invalid revision for ${id}: ${digest}`);
426
+ }
427
+ return value;
428
+ }
429
+ };
430
+ };
431
+
432
+ // src/discovery.ts
433
+ var docsSite = "https://ui.erbium.app";
434
+ var configRecord = Schema5.decodeUnknownSync(Schema5.Record(Schema5.String, Schema5.Json));
435
+ var pageIndex = Schema5.decodeUnknownSync(Schema5.Struct({
436
+ pages: Schema5.Array(Schema5.Struct({
437
+ route: Schema5.String,
438
+ title: Schema5.String,
439
+ markdownUrl: Schema5.String
440
+ }))
441
+ }));
442
+ var skillPath = ".agents/skills/erbium-ui/SKILL.md";
443
+ var agentBlock = "<!-- erbium-ui:begin -->\nUse the local Erbium UI skill in `.agents/skills/erbium-ui/SKILL.md` for component discovery and managed installs.\n<!-- erbium-ui:end -->";
444
+ var fetchText = async (url) => {
445
+ const response = await fetch(url, { signal: AbortSignal.timeout(15000) });
446
+ if (!response.ok) {
447
+ throw new Error(`Documentation returned HTTP ${response.status} for ${url.pathname}.`);
448
+ }
449
+ return await response.text();
450
+ };
451
+ var initialize = async (root, agents, registry, headers) => {
452
+ await validateAliases(root);
453
+ const componentsPath = await safePath(root, "components.json");
454
+ const config = configRecord(parseJson(await readText(componentsPath) ?? "{}"));
455
+ const configured = configRecord(config.registries ?? {});
456
+ const lock = await safePath(root, lockPath);
457
+ await loadLock(root);
458
+ const defaults = {
459
+ "@erbium": `${docsSite}/r/ui/{name}.json`,
460
+ "@erbium-examples": `${docsSite}/r/examples/{name}.json`
461
+ };
462
+ if (headers.length > 0 && !registry) {
463
+ throw new Error("--header requires --registry.");
464
+ }
465
+ const changed = registry ? await saveRegistryConfig(root, registry, headers) : [];
466
+ if (Object.keys(defaults).some((namespace) => !Object.hasOwn(configured, namespace))) {
467
+ await atomicWrite(componentsPath, `${JSON.stringify({ ...config, registries: { ...defaults, ...configured } }, null, 2)}
468
+ `);
469
+ changed.push("components.json");
470
+ }
471
+ if (await readText(lock) === undefined) {
472
+ await atomicWrite(lock, `{ "version": 1, "items": {} }
473
+ `);
474
+ changed.push(lockPath);
475
+ }
476
+ if (agents) {
477
+ const skill = await safePath(root, skillPath);
478
+ const instructions = await safePath(root, "AGENTS.md");
479
+ const existing = await readText(instructions) ?? "";
480
+ if (await readText(skill) === undefined) {
481
+ await atomicWrite(skill, `---
482
+ name: erbium-ui
483
+ description: Find, install, and update Erbium UI source.
484
+ ---
485
+
486
+ Use \`erbium search\` and \`erbium docs\` before creating UI. Install with \`erbium add\`, or use shadcn and then \`erbium adopt\`. Commit the tracked source and its provenance. Review \`erbium diff\` before updating and run \`erbium check\` after editing.
487
+
488
+ Read ${docsSite}/docs/installation.md for setup.
489
+ `);
490
+ changed.push(skillPath);
491
+ }
492
+ if (!existing.includes("<!-- erbium-ui:begin -->")) {
493
+ const prefix = existing.length === 0 ? "" : `${existing.trimEnd()}
494
+
495
+ `;
496
+ await atomicWrite(instructions, `${prefix}${agentBlock}
497
+ `);
498
+ changed.push("AGENTS.md");
499
+ }
500
+ }
501
+ return changed;
502
+ };
503
+ var search = async (root, location, terms) => {
504
+ const registry = await openRegistry(root, location);
505
+ const words = terms.map((term) => term.toLowerCase());
506
+ const matches = Object.entries(registry.items).flatMap(([id, revision]) => {
507
+ const metadata = registry.catalog[id];
508
+ const name = id.split("/")[1] ?? id;
509
+ const title = metadata?.title?.toLowerCase() ?? "";
510
+ const content = [id, title, metadata?.description, ...metadata?.keywords ?? []].join(" ").toLowerCase();
511
+ if (!words.every((word) => content.includes(word))) {
512
+ return [];
513
+ }
514
+ let score = 0;
515
+ for (const word of words) {
516
+ if (word === id || word === name || word === title) {
517
+ score += 4;
518
+ } else {
519
+ score += name.includes(word) || title.includes(word) ? 2 : 1;
520
+ }
521
+ }
522
+ return [{ score, item: { id, revision, ...metadata } }];
523
+ });
524
+ return matches.toSorted((left, right) => right.score - left.score).map(({ item }) => item);
525
+ };
526
+ var registryDocumentation = async (cwd, location, topic) => {
527
+ const registry = await openRegistry(cwd, location);
528
+ const id = normalizeItem(topic);
529
+ const digest = registry.items[id];
530
+ if (digest === undefined) {
531
+ throw new Error(`No registry item found for ${id}. Use erbium search to discover items.`);
532
+ }
533
+ const { item } = await registry.load(id, digest);
534
+ const info = registry.catalog[id];
535
+ const dependencies = [
536
+ ...item.registryDependencies ?? [],
537
+ ...item.dependencies ?? [],
538
+ ...item.devDependencies ?? []
539
+ ];
540
+ const files = (item.files ?? []).map(({ target, content }) => {
541
+ let width = 3;
542
+ for (const [run] of content.matchAll(/`+/gu)) {
543
+ width = Math.max(width, run.length + 1);
544
+ }
545
+ const fence = "`".repeat(width);
546
+ return `## ${target}
547
+
548
+ ${fence}
549
+ ${content}
550
+ ${fence}`;
551
+ });
552
+ return [
553
+ `# ${info?.title ?? id}`,
554
+ info?.description,
555
+ `Revision: ${digest}`,
556
+ dependencies.length === 0 ? undefined : `Dependencies: ${dependencies.join(", ")}`,
557
+ ...files
558
+ ].filter(Boolean).join(`
559
+
560
+ `);
561
+ };
562
+ var documentation = async (topic, site) => {
563
+ const origin = new URL(site);
564
+ const index = pageIndex(parseJson(await fetchText(new URL("/api/docs.json", origin))));
565
+ const name = topic.split("/").at(-1);
566
+ const match = index.pages.find((page) => page.route === topic) ?? index.pages.find((page) => page.route.split("/").at(-1) === name);
567
+ if (match === undefined) {
568
+ throw new Error(`No documentation found for ${topic}. Use erbium search to discover items.`);
569
+ }
570
+ const url = new URL(new URL(match.markdownUrl, origin).pathname, origin);
571
+ return await fetchText(url);
572
+ };
573
+ var history = async (root, location, item) => {
574
+ const registry = await openRegistry(root, location);
575
+ const id = normalizeItem(item);
576
+ const current = registry.items[id];
577
+ const releases = await registry.history();
578
+ let previous;
579
+ const entries = releases.toReversed().flatMap(({ commit, date, items }) => {
580
+ const revision = items[id];
581
+ const changed = revision !== previous;
582
+ previous = revision;
583
+ return revision !== undefined && changed ? [{ id, revision, commit, date, current: revision === current }] : [];
584
+ }).toReversed();
585
+ if (current !== undefined && entries[0]?.revision !== current) {
586
+ return [{ id, revision: current, commit: null, date: null, current: true }, ...entries];
587
+ }
588
+ return entries;
589
+ };
590
+ var defaultDocs = new URL(defaultRegistry).origin;
591
+
592
+ // src/operations.ts
593
+ import { spawnSync } from "node:child_process";
594
+ import { mkdir as mkdir2, mkdtemp, realpath as realpath2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
595
+ import { tmpdir } from "node:os";
596
+ import path5 from "node:path";
597
+ import * as Schema6 from "effect/Schema";
598
+
599
+ // src/imports.ts
600
+ import { createRequire } from "node:module";
601
+ import { realpath, stat } from "node:fs/promises";
602
+ import path4 from "node:path";
603
+ import { resolvePathAlias as resolvePathAlias2 } from "get-tsconfig";
604
+ var sourceImport = /(?:^\s*(?:import|export)\b[^;]*?\bfrom\s*|\bimport\s*\(\s*|^\s*import\s*)(?<quote>["'])(?<source>[^"'\r\n]+)\k<quote>/gmu;
605
+ var extensions = [".ts", ".tsx", ".js", ".jsx", ".json", ".css"];
606
+ var importSpecifiers = (content) => [
607
+ ...new Set([...content.matchAll(sourceImport)].flatMap((match) => match.groups?.source ?? []))
608
+ ];
609
+ var resolveLocalImport = async (config, importer, specifier, resolvePackages = false) => {
610
+ const alias = config.tsconfig === undefined ? [] : resolvePathAlias2(config.tsconfig, specifier);
611
+ const candidates = specifier.startsWith(".") ? [path4.resolve(path4.dirname(importer), specifier)] : alias;
612
+ const paths = candidates.flatMap((candidate) => [
613
+ candidate,
614
+ ...extensions.map((extension) => candidate + extension),
615
+ ...extensions.map((extension) => path4.join(candidate, `index${extension}`)),
616
+ candidate.replace(/\.jsx?$/u, ".ts"),
617
+ candidate.replace(/\.jsx?$/u, ".tsx")
618
+ ]);
619
+ const existence = await Promise.all(paths.map(async (candidate) => {
620
+ const info = await stat(candidate).catch(() => null);
621
+ return info?.isFile() === true ? candidate : undefined;
622
+ }));
623
+ let target = existence.find((candidate) => candidate !== undefined);
624
+ if (target === undefined && resolvePackages && candidates.length === 0) {
625
+ try {
626
+ const resolved = createRequire(importer).resolve(specifier);
627
+ target = path4.isAbsolute(resolved) ? await realpath(resolved) : undefined;
628
+ } catch {
629
+ target = undefined;
630
+ }
631
+ }
632
+ return {
633
+ expectedLocal: candidates.length > 0 || Object.values(config.aliases ?? {}).some((prefix) => specifier === prefix || specifier.startsWith(`${prefix}/`)),
634
+ target
635
+ };
636
+ };
637
+
638
+ // src/operations.ts
639
+ var markers = /^(?:<{7} yours|>{7} upstream)(?:\r?$)/mu;
640
+ var packageName = /^(?<name>@[a-z\d][a-z\d._-]*\/[a-z\d][a-z\d._-]*|[a-z\d][a-z\d._-]*)(?:@(?<range>[^\s]+))?$/iu;
641
+ var packageManifest = Schema6.decodeUnknownSync(Schema6.Struct({
642
+ packageManager: Schema6.optionalKey(Schema6.String),
643
+ dependencies: Schema6.optionalKey(Schema6.Record(Schema6.String, Schema6.String)),
644
+ devDependencies: Schema6.optionalKey(Schema6.Record(Schema6.String, Schema6.String)),
645
+ peerDependencies: Schema6.optionalKey(Schema6.Record(Schema6.String, Schema6.String)),
646
+ optionalDependencies: Schema6.optionalKey(Schema6.Record(Schema6.String, Schema6.String))
647
+ }));
648
+ var journalSchema = Schema6.decodeUnknownSync(Schema6.Array(Schema6.Struct({
649
+ target: Schema6.String,
650
+ content: Schema6.String,
651
+ previous: Schema6.NullOr(Schema6.String)
652
+ })));
653
+ var basePath = (digest) => `.erbium/bases/${digest}.txt`;
654
+ var readBase = async (root, digest, target, local, recover) => {
655
+ if (local !== undefined && hash(local) === digest) {
656
+ return local;
657
+ }
658
+ const base = await readText(await safePath(root, basePath(digest)));
659
+ if (base !== undefined && hash(base) === digest) {
660
+ return base;
661
+ }
662
+ const history = spawnSync("git", ["log", "--format=%H", "--", target], {
663
+ cwd: root,
664
+ encoding: "utf-8"
665
+ });
666
+ const refs = [
667
+ `:./${target}`,
668
+ ...(history.stdout ?? "").split(`
669
+ `).filter(Boolean).map((commit) => `${commit}:./${target}`)
670
+ ];
671
+ for (const ref of refs) {
672
+ const candidate = spawnSync("git", ["show", ref], {
673
+ cwd: root,
674
+ encoding: "utf-8",
675
+ maxBuffer: 16 * 1024 * 1024
676
+ });
677
+ if (candidate.status === 0 && hash(candidate.stdout) === digest) {
678
+ return candidate.stdout;
679
+ }
680
+ }
681
+ const fromRegistry = await recover?.();
682
+ if (fromRegistry !== undefined && fromRegistry !== null && hash(fromRegistry) === digest) {
683
+ return fromRegistry;
684
+ }
685
+ throw new Error(`Missing or invalid baseline for ${target} (${digest}). Restore .erbium/bases from version control.`);
686
+ };
687
+ var readTracked = async (root, target) => await readText(await safePath(root, target));
688
+ var gitFile = async (mode, local, base, upstream) => {
689
+ const directory = await mkdtemp(path5.join(tmpdir(), "erbium-"));
690
+ try {
691
+ await Promise.all([
692
+ writeFile2(path5.join(directory, "local"), local),
693
+ writeFile2(path5.join(directory, "base"), base),
694
+ writeFile2(path5.join(directory, "upstream"), upstream)
695
+ ]);
696
+ const args = mode === "merge" ? [
697
+ "merge-file",
698
+ "-p",
699
+ "-L",
700
+ "yours",
701
+ "-L",
702
+ "base",
703
+ "-L",
704
+ "upstream",
705
+ "local",
706
+ "base",
707
+ "upstream"
708
+ ] : ["diff", "--no-index", "--no-color", "--", "base", "upstream"];
709
+ const result = spawnSync("git", args, {
710
+ cwd: directory,
711
+ encoding: "utf-8",
712
+ maxBuffer: 16 * 1024 * 1024
713
+ });
714
+ if (result.error !== undefined || result.status === null || result.status < 0 || result.status > (mode === "merge" ? 127 : 1)) {
715
+ throw new Error(`git ${args[0]} failed: ${result.error?.message ?? result.stderr}`);
716
+ }
717
+ return { content: result.stdout, conflict: mode === "merge" && result.status !== 0 };
718
+ } finally {
719
+ await rm2(directory, { force: true, recursive: true });
720
+ }
721
+ };
722
+ var selectItems = async (registry, names, installed) => {
723
+ const requested = new Set(names);
724
+ const pending = new Set;
725
+ const selected = new Map;
726
+ const visit = async (id) => {
727
+ if (selected.has(id) || Object.hasOwn(installed, id) && !requested.has(id)) {
728
+ return;
729
+ }
730
+ if (pending.has(id)) {
731
+ throw new Error(`Cyclic dependency at ${id}.`);
732
+ }
733
+ const digest = registry.items[id];
734
+ if (digest === undefined) {
735
+ throw new Error(`Item is missing from the registry: ${id}`);
736
+ }
737
+ pending.add(id);
738
+ const value = await registry.load(id, digest);
739
+ for (const dependency of value.item.registryDependencies ?? []) {
740
+ await visit(normalizeItem(dependency));
741
+ }
742
+ pending.delete(id);
743
+ selected.set(id, value);
744
+ };
745
+ for (const name of names) {
746
+ await visit(name);
747
+ }
748
+ return selected;
749
+ };
750
+ var snapshotBaselines = (root, config, registry, items) => {
751
+ const cache = new Map;
752
+ return async (id, target, digest) => {
753
+ const item = items[id];
754
+ if (item === undefined) {
755
+ return null;
756
+ }
757
+ let files = cache.get(id);
758
+ if (files === undefined) {
759
+ files = registry.load(id, item.revision).then((snapshot) => planFiles(root, config, snapshot)).catch(() => []);
760
+ cache.set(id, files);
761
+ }
762
+ const resolved = await files;
763
+ return resolved.find((file) => file.target === target && hash(file.content) === digest)?.content;
764
+ };
765
+ };
766
+ var plannedContent = async (mode, options, root, target, upstream, previous, recover) => {
767
+ const local = await readTracked(root, target);
768
+ if (mode === "adopt") {
769
+ if (local !== upstream) {
770
+ throw new Error(`Cannot adopt ${target}: it differs from the selected revision.`);
771
+ }
772
+ return { local, content: local };
773
+ }
774
+ if (options.overwrite === true) {
775
+ return { local, content: upstream };
776
+ }
777
+ if (local === undefined) {
778
+ if (previous !== undefined) {
779
+ throw new Error(`Tracked file is missing: ${target}. Restore it before updating.`);
780
+ }
781
+ return { local, content: upstream };
782
+ }
783
+ if (markers.test(local)) {
784
+ throw new Error(`Resolve the merge markers in ${target} first.`);
785
+ }
786
+ const localHash = hash(local);
787
+ const upstreamHash = hash(upstream);
788
+ if (previous !== undefined && (local === upstream || upstreamHash === previous)) {
789
+ return { local, content: local };
790
+ }
791
+ if (localHash === previous) {
792
+ return { local, content: upstream };
793
+ }
794
+ if (previous === undefined) {
795
+ throw new Error(`Unmanaged file already exists: ${target}. Adopt a matching install or move the file before adding.`);
796
+ }
797
+ const base = await readBase(root, previous, target, local, recover);
798
+ const merged = await gitFile("merge", local, base, upstream);
799
+ if (merged.conflict && options.conflictMarkers !== true) {
800
+ throw new Error(`Both sides edited the same lines in ${target}. Run erbium diff and erbium diff --local to review.`);
801
+ }
802
+ return { local, ...merged };
803
+ };
804
+ var packageSpecs = (specs) => specs.map((spec) => {
805
+ const match = packageName.exec(spec);
806
+ const name = match?.groups?.name;
807
+ const range = match?.groups?.range;
808
+ if (name === undefined || range !== undefined && !/^[~^*<>=|.\w+-]+$/u.test(range)) {
809
+ throw new Error(`Unsupported npm package specification: ${spec}`);
810
+ }
811
+ return { name, spec };
812
+ });
813
+ var packagePlan = async (root, items) => {
814
+ const text = await readText(path5.join(root, "package.json"));
815
+ if (text === undefined) {
816
+ throw new Error("Run Erbium in a project with package.json.");
817
+ }
818
+ const manifest = packageManifest(parseJson(text));
819
+ const declared = {
820
+ ...manifest.peerDependencies,
821
+ ...manifest.optionalDependencies,
822
+ ...manifest.devDependencies,
823
+ ...manifest.dependencies
824
+ };
825
+ const required = new Map;
826
+ for (const item of items) {
827
+ const entries = [
828
+ ...packageSpecs(item.devDependencies).map((entry) => ({ ...entry, dev: true })),
829
+ ...packageSpecs(item.dependencies).map((entry) => ({ ...entry, dev: false }))
830
+ ];
831
+ for (const { name, spec, dev } of entries) {
832
+ const previous = required.get(name);
833
+ if (previous !== undefined && previous.spec !== name && spec !== name && previous.spec !== spec) {
834
+ throw new Error(`Registry items require different ranges of ${name}: ${previous.spec}, ${spec}.`);
835
+ }
836
+ required.set(name, {
837
+ dev: dev && (previous?.dev ?? true),
838
+ spec: spec === name ? previous?.spec ?? spec : spec
839
+ });
840
+ }
841
+ }
842
+ const missing = [...required].filter(([name]) => !Object.hasOwn(declared, name));
843
+ const ranges = [...required].flatMap(([name, { spec }]) => {
844
+ const current = declared[name];
845
+ return current !== undefined && spec !== name && spec !== `${name}@${current}` ? [`${name} is declared as ${current}; the registry requests ${spec}.`] : [];
846
+ });
847
+ let manager = manifest.packageManager?.split("@")[0];
848
+ if (manager === undefined) {
849
+ const files = [
850
+ ["bun.lock", "bun"],
851
+ ["pnpm-lock.yaml", "pnpm"],
852
+ ["yarn.lock", "yarn"]
853
+ ];
854
+ const present = await Promise.all(files.map(async ([file, candidate]) => ({
855
+ candidate,
856
+ exists: await readText(path5.join(root, file)) !== undefined
857
+ })));
858
+ manager = present.find((file) => file.exists)?.candidate;
859
+ }
860
+ manager ??= "npm";
861
+ if (!["npm", "bun", "pnpm", "yarn"].includes(manager)) {
862
+ throw new Error(`Unsupported package manager: ${manager}`);
863
+ }
864
+ return {
865
+ manager,
866
+ ranges,
867
+ dependencies: missing.values().filter(([, entry]) => !entry.dev).map(([, entry]) => entry.spec).toArray(),
868
+ devDependencies: missing.values().filter(([, entry]) => entry.dev).map(([, entry]) => entry.spec).toArray()
869
+ };
870
+ };
871
+ var installPackages = (root, packages) => {
872
+ const { manager } = packages;
873
+ const install = (specs, dev) => {
874
+ if (specs.length === 0) {
875
+ return;
876
+ }
877
+ const args = [manager === "npm" ? "install" : "add", ...dev ? ["-D"] : [], "--", ...specs];
878
+ const result = spawnSync(manager, args, {
879
+ cwd: root,
880
+ encoding: "utf-8",
881
+ maxBuffer: 16 * 1024 * 1024
882
+ });
883
+ if (result.status !== 0 || result.error !== undefined) {
884
+ throw new Error(`${manager} failed to install ${specs.join(", ")}: ${result.error?.message ?? result.stderr}`);
885
+ }
886
+ };
887
+ install(packages.dependencies, false);
888
+ install(packages.devDependencies, true);
889
+ };
890
+ var finishJournal = async (root, journal) => {
891
+ const text = await readText(journal);
892
+ if (text === undefined) {
893
+ return;
894
+ }
895
+ const writes = journalSchema(parseJson(text));
896
+ const pending = await Promise.all(writes.map(async (write) => {
897
+ const absolute = await safePath(root, write.target);
898
+ const current = await readText(absolute);
899
+ if (current !== (write.previous ?? undefined) && current !== write.content) {
900
+ throw new Error(`Cannot resume interrupted update because ${write.target} changed.`);
901
+ }
902
+ return { absolute, ...write };
903
+ }));
904
+ for (const write of pending) {
905
+ await atomicWrite(write.absolute, write.content);
906
+ }
907
+ await rm2(journal);
908
+ };
909
+ var inspect = async (root, registry, installed, names) => {
910
+ const items = names.map((id) => {
911
+ const item = installed[id];
912
+ if (item === undefined) {
913
+ throw new Error(`${id} is not tracked.`);
914
+ }
915
+ return { id, item };
916
+ });
917
+ return await Promise.all(items.map(async ({ id, item }) => {
918
+ const files = await Promise.all(Object.entries(item.files).map(async ([target, digest]) => {
919
+ const local = await readTracked(root, target);
920
+ return {
921
+ target,
922
+ missing: local === undefined,
923
+ modified: local !== undefined && hash(local) !== digest,
924
+ conflict: local !== undefined && markers.test(local)
925
+ };
926
+ }));
927
+ const upstream = registry?.items[id];
928
+ return {
929
+ id,
930
+ revision: item.revision,
931
+ upstream,
932
+ updateAvailable: upstream !== undefined && upstream !== item.revision,
933
+ removed: registry !== undefined && upstream === undefined,
934
+ files
935
+ };
936
+ }));
937
+ };
938
+ var diffItem = async (root, registry, names, items) => {
939
+ const [id] = names;
940
+ const item = id === undefined ? undefined : items[id];
941
+ if (id === undefined || item === undefined || names.length !== 1) {
942
+ throw new Error("Provide one tracked item to diff.");
943
+ }
944
+ const upstream = registry?.items[id];
945
+ if (registry !== undefined && upstream === undefined) {
946
+ throw new Error(`${id} is missing from the registry.`);
947
+ }
948
+ const config = registry === undefined ? undefined : await projectConfig(root);
949
+ const recover = registry === undefined || config === undefined ? undefined : snapshotBaselines(root, config, registry, items);
950
+ const incoming = registry !== undefined && upstream !== undefined && config !== undefined ? planFiles(root, config, await registry.load(id, upstream)) : await Promise.all(Object.keys(item.files).map(async (target) => ({
951
+ target,
952
+ content: await readTracked(root, target)
953
+ })));
954
+ const targets = new Map(incoming.map((file) => [file.target, file.content]));
955
+ const files = [...new Set([...Object.keys(item.files), ...targets.keys()])];
956
+ return await Promise.all(files.map(async (target) => {
957
+ const previous = item.files[target];
958
+ const base = previous === undefined ? "" : await readBase(root, previous, target, await readTracked(root, target), async () => await recover?.(id, target, previous));
959
+ const content = targets.get(target) ?? "";
960
+ const result = await gitFile("diff", "", base, content);
961
+ return { target, diff: result.content };
962
+ }));
963
+ };
964
+ var fileOwners = (items) => {
965
+ const owners = new Map;
966
+ for (const [id, item] of Object.entries(items)) {
967
+ for (const [target, digest] of Object.entries(item.files)) {
968
+ const owner = owners.get(target);
969
+ if (owner !== undefined && owner.digest !== digest) {
970
+ throw new Error(`Different revisions claim ${target}: ${owner.items.join(", ")}, ${id}. Update the affected items together.`);
971
+ }
972
+ if (owner === undefined) {
973
+ owners.set(target, { digest, items: [id] });
974
+ } else {
975
+ owner.items.push(id);
976
+ }
977
+ }
978
+ }
979
+ return owners;
980
+ };
981
+ var planItems = (mode, root, config, items, selected) => {
982
+ const incoming = new Map;
983
+ const dropped = [];
984
+ const next = { ...items };
985
+ for (const [id, value] of selected) {
986
+ const previous = items[id];
987
+ const digest = revision(value);
988
+ if (mode === "adopt" && previous !== undefined && previous.revision !== digest) {
989
+ throw new Error(`${id} is already tracked. Use update.`);
990
+ }
991
+ const files = {};
992
+ for (const { target, content } of planFiles(root, config, value)) {
993
+ const shared = incoming.get(target);
994
+ if (shared !== undefined && shared.upstream !== content) {
995
+ throw new Error(`Registry items disagree on ${target}: ${shared.id}, ${id}.`);
996
+ }
997
+ incoming.set(target, { id, upstream: content });
998
+ files[target] = hash(content);
999
+ }
1000
+ dropped.push(...Object.keys(previous?.files ?? {}).filter((target) => !Object.hasOwn(files, target)));
1001
+ next[id] = {
1002
+ files,
1003
+ revision: digest,
1004
+ dependencies: value.item.dependencies ?? [],
1005
+ devDependencies: value.item.devDependencies ?? [],
1006
+ registryDependencies: value.item.registryDependencies ?? []
1007
+ };
1008
+ }
1009
+ return { incoming, dropped, items: next };
1010
+ };
1011
+ var planChanges = async (root, mode, options, registry, names) => {
1012
+ const lock = await loadLock(root);
1013
+ const items = { ...lock.items };
1014
+ const requested = names.length > 0 || mode !== "update" ? names : Object.keys(items).filter((id) => registry.items[id] !== undefined && registry.items[id] !== items[id]?.revision);
1015
+ if (mode === "update" && requested.some((id) => !Object.hasOwn(items, id))) {
1016
+ throw new Error("Update takes tracked items. Use add to install new items.");
1017
+ }
1018
+ const selected = await selectItems(registry, requested, items);
1019
+ const config = await projectConfig(root);
1020
+ const owners = fileOwners(items);
1021
+ const plan = planItems(mode, root, config, items, selected);
1022
+ const nextOwners = fileOwners(plan.items);
1023
+ const recover = snapshotBaselines(root, config, registry, items);
1024
+ const planned = await Promise.all([...plan.incoming].map(async ([target, { upstream }]) => {
1025
+ const owner = owners.get(target);
1026
+ const id = owner?.items[0];
1027
+ const recoverFile = owner === undefined || id === undefined ? undefined : async () => await recover(id, target, owner.digest);
1028
+ return {
1029
+ target,
1030
+ upstream,
1031
+ ...await plannedContent(mode, options, root, target, upstream, owner?.digest, recoverFile)
1032
+ };
1033
+ }));
1034
+ const bases = new Map(planned.map(({ upstream }) => [hash(upstream), upstream]));
1035
+ const writes = planned.flatMap(({ target, local, content }) => local === content ? [] : [{ target, previous: local, content }]);
1036
+ const dropped = [...new Set(plan.dropped)].filter((target) => !nextOwners.has(target));
1037
+ const conflicts = planned.flatMap(({ target, conflict }) => conflict === true ? [target] : []);
1038
+ return { items: plan.items, writes, bases, dropped, conflicts, selected: [...selected.keys()] };
1039
+ };
1040
+ var change = async (root, mode, options, registry, names) => {
1041
+ const { items, writes, bases, dropped, conflicts, selected } = await planChanges(root, mode, options, registry, names);
1042
+ const packages = await packagePlan(root, Object.values(items));
1043
+ if (mode === "adopt" && (packages.dependencies.length > 0 || packages.devDependencies.length > 0)) {
1044
+ throw new Error("Install the missing package dependencies before adopting these files.");
1045
+ }
1046
+ if (!options.dryRun && selected.length > 0) {
1047
+ const baselineWrites = await Promise.all([...bases].map(async ([digest, content]) => {
1048
+ const target = basePath(digest);
1049
+ const previous = await readTracked(root, target);
1050
+ return previous === content ? [] : [{ content, target, previous }];
1051
+ }));
1052
+ writes.unshift(...baselineWrites.flat());
1053
+ const previous = await readTracked(root, lockPath);
1054
+ writes.push({
1055
+ content: `${JSON.stringify({ version: 1, items, aliases: await validateAliases(root) }, null, 2)}
1056
+ `,
1057
+ previous,
1058
+ target: lockPath
1059
+ });
1060
+ if (mode !== "adopt" && options.skipInstall !== true) {
1061
+ installPackages(root, packages);
1062
+ }
1063
+ const journal = await safePath(root, ".erbium/pending.json");
1064
+ await atomicWrite(journal, JSON.stringify(writes.map((write) => ({ ...write, previous: write.previous ?? null }))));
1065
+ await finishJournal(root, journal);
1066
+ }
1067
+ return {
1068
+ items: selected,
1069
+ files: writes.values().map((write) => write.target).filter((target) => !target.startsWith(".erbium/")).toArray(),
1070
+ dropped,
1071
+ conflicts,
1072
+ packages,
1073
+ dryRun: options.dryRun,
1074
+ skipInstall: options.skipInstall ?? false
1075
+ };
1076
+ };
1077
+ var checkNames = ["config", "provenance", "dependencies", "imports"];
1078
+ var selectedChecks = (only) => {
1079
+ const valid = new Set(checkNames);
1080
+ const requested = only.length === 0 ? [...checkNames] : [...new Set(only.split(",").map((name) => name.trim()))];
1081
+ if (requested.some((name) => !valid.has(name))) {
1082
+ throw new Error(`Unknown check. Choose from ${checkNames.join(", ")}.`);
1083
+ }
1084
+ return checkNames.filter((name) => requested.includes(name));
1085
+ };
1086
+ var verifyProvenance = async (root, items) => {
1087
+ const owners = fileOwners(items);
1088
+ await Promise.all([...owners].map(async ([target, { digest }]) => {
1089
+ const local = await readTracked(root, target);
1090
+ if (local === undefined) {
1091
+ throw new Error(`Missing files: ${target}. Restore it before updating.`);
1092
+ }
1093
+ if (markers.test(local)) {
1094
+ throw new Error(`Unresolved merge conflict in ${target}.`);
1095
+ }
1096
+ await readBase(root, digest, target, local);
1097
+ }));
1098
+ };
1099
+ var verifyDependencies = async (root, items) => {
1100
+ for (const [id, item] of Object.entries(items)) {
1101
+ normalizeItem(id);
1102
+ for (const dependency of item.registryDependencies) {
1103
+ if (!Object.hasOwn(items, dependency)) {
1104
+ throw new Error(`${id} requires untracked registry item ${dependency}. Run erbium add ${dependency}.`);
1105
+ }
1106
+ }
1107
+ }
1108
+ const packages = await packagePlan(root, Object.values(items));
1109
+ const missing = [...packages.dependencies, ...packages.devDependencies];
1110
+ if (missing.length > 0) {
1111
+ throw new Error(`Missing package declarations: ${missing.join(", ")}.`);
1112
+ }
1113
+ return packages.ranges;
1114
+ };
1115
+ var verifyImports = async (root, items) => {
1116
+ const config = await projectConfig(root);
1117
+ const files = [...fileOwners(items).keys()].filter((target) => /\.[cm]?[jt]sx?$/u.test(target));
1118
+ const issues = await Promise.all(files.map(async (target) => {
1119
+ const file = await safePath(root, target);
1120
+ const text = await readText(file) ?? "";
1121
+ const imports = await Promise.all(importSpecifiers(text).map(async (specifier) => {
1122
+ const resolved = await resolveLocalImport(config, file, specifier);
1123
+ return resolved.expectedLocal && resolved.target === undefined ? [`${target} imports ${specifier}, which does not resolve.`] : [];
1124
+ }));
1125
+ return imports.flat();
1126
+ }));
1127
+ const broken = issues.flat();
1128
+ if (broken.length > 0) {
1129
+ throw new Error(broken.join(`
1130
+ `));
1131
+ }
1132
+ };
1133
+ var validateInstall = async (root, lock, steps) => {
1134
+ const { items } = lock;
1135
+ const checks = {
1136
+ config: async () => {
1137
+ const aliases = await validateAliases(root);
1138
+ if (lock.aliases !== undefined && Object.entries(lock.aliases).some(([name, value]) => aliases[name] !== value)) {
1139
+ throw new Error("Alias destinations changed since installation. Restore them or migrate the tracked paths.");
1140
+ }
1141
+ },
1142
+ provenance: async () => {
1143
+ await verifyProvenance(root, items);
1144
+ },
1145
+ dependencies: async () => await verifyDependencies(root, items),
1146
+ imports: async () => {
1147
+ await verifyImports(root, items);
1148
+ }
1149
+ };
1150
+ const results = await Promise.all(steps.map(async (step) => {
1151
+ try {
1152
+ const notes = await checks[step]();
1153
+ return { step, ok: true, notes: notes ?? [] };
1154
+ } catch (error) {
1155
+ return { step, ok: false, notes: [error instanceof Error ? error.message : String(error)] };
1156
+ }
1157
+ }));
1158
+ return { ok: results.every((result) => result.ok), steps: results };
1159
+ };
1160
+ var operationRegistry = async (mode, root, options) => {
1161
+ const registry = mode === "check" || mode === "diff" && options.local ? undefined : await openRegistry(root, options.registry);
1162
+ if (options.at === undefined || options.at.length === 0) {
1163
+ return registry;
1164
+ }
1165
+ if (mode !== "adopt" || registry === undefined) {
1166
+ throw new Error("--at is available for adopt.");
1167
+ }
1168
+ const releases = await registry.history();
1169
+ const { at } = options;
1170
+ const matching = releases.filter(({ commit }) => commit.startsWith(at));
1171
+ const [release] = matching;
1172
+ if (matching.length !== 1 || release === undefined) {
1173
+ throw new Error(`Expected one registry release matching ${at}. Run erbium history <item>.`);
1174
+ }
1175
+ return { ...registry, items: release.items };
1176
+ };
1177
+ var runOperation = async (mode, options) => {
1178
+ if (options.overwrite === true && options.conflictMarkers === true) {
1179
+ throw new Error("Choose either --overwrite or --conflict-markers.");
1180
+ }
1181
+ const root = await realpath2(options.cwd);
1182
+ const names = options.names.map(normalizeItem);
1183
+ const journal = await safePath(root, ".erbium/pending.json");
1184
+ const registry = await operationRegistry(mode, root, options);
1185
+ if (mode === "check" || mode === "status" || mode === "diff") {
1186
+ if (await readText(journal) !== undefined) {
1187
+ throw new Error("An update was interrupted. Rerun the write command to finish it.");
1188
+ }
1189
+ const lock = await loadLock(root);
1190
+ const { items } = lock;
1191
+ if (mode === "diff") {
1192
+ return await diffItem(root, registry, names, items);
1193
+ }
1194
+ const results = await inspect(root, registry, items, names.length > 0 ? names : Object.keys(items));
1195
+ if (mode === "check") {
1196
+ return {
1197
+ ...await validateInstall(root, lock, selectedChecks(options.only ?? "")),
1198
+ tracked: results
1199
+ };
1200
+ }
1201
+ return results;
1202
+ }
1203
+ if (registry === undefined) {
1204
+ throw new Error("Registry required.");
1205
+ }
1206
+ if (options.dryRun) {
1207
+ if (await readText(journal) !== undefined) {
1208
+ throw new Error("An update was interrupted. Rerun the write command to finish it.");
1209
+ }
1210
+ return await change(root, mode, options, registry, names);
1211
+ }
1212
+ const guard = await safePath(root, ".erbium/operation");
1213
+ await mkdir2(path5.dirname(guard), { recursive: true });
1214
+ try {
1215
+ await mkdir2(guard);
1216
+ } catch (error) {
1217
+ throw new Error("An Erbium operation is active. If it was interrupted, remove the empty .erbium/operation directory and rerun.", { cause: error });
1218
+ }
1219
+ try {
1220
+ await finishJournal(root, journal);
1221
+ return await change(root, mode, options, registry, names);
1222
+ } finally {
1223
+ await rm2(guard, { recursive: true });
1224
+ }
1225
+ };
1226
+
1227
+ // src/usage.ts
1228
+ import { execFileSync } from "node:child_process";
1229
+ import { mkdtemp as mkdtemp2, realpath as realpath3, rm as rm3 } from "node:fs/promises";
1230
+ import { tmpdir as tmpdir2 } from "node:os";
1231
+ import path6 from "node:path";
1232
+ import * as Schema7 from "effect/Schema";
1233
+ import { getTsconfig as getTsconfig2 } from "get-tsconfig";
1234
+ var trackedFiles = (root) => execFileSync("git", ["ls-files", "--cached", "--others", "--exclude-standard", "-z"], {
1235
+ cwd: root,
1236
+ encoding: "utf-8",
1237
+ maxBuffer: 16 * 1024 * 1024
1238
+ }).split("\x00").filter(Boolean);
1239
+ var importGraph = async (root, files) => {
1240
+ const cache = new Map;
1241
+ const sources = files.filter((file) => /\.[cm]?[jt]sx?$/u.test(file));
1242
+ const references = await Promise.all(sources.map(async (file) => {
1243
+ const absolute = await safePath(root, file);
1244
+ const text = await readText(absolute) ?? "";
1245
+ const tsconfig = getTsconfig2(path6.dirname(absolute), { cache });
1246
+ const resolutions = await Promise.all(importSpecifiers(text).map(async (specifier) => await resolveLocalImport({ tsconfig }, absolute, specifier, true)));
1247
+ return { file: absolute, targets: resolutions.flatMap(({ target }) => target ?? []) };
1248
+ }));
1249
+ const graph = new Map;
1250
+ for (const { file, targets } of references) {
1251
+ for (const target of targets) {
1252
+ const importers = graph.get(target) ?? new Set;
1253
+ importers.add(file);
1254
+ graph.set(target, importers);
1255
+ }
1256
+ }
1257
+ return graph;
1258
+ };
1259
+ var consumingFiles = (graph, targets) => {
1260
+ const direct = new Set(targets.flatMap((file) => [...graph.get(file) ?? []]));
1261
+ const all = new Set(direct);
1262
+ for (const file of all) {
1263
+ for (const importer of graph.get(file) ?? []) {
1264
+ all.add(importer);
1265
+ }
1266
+ }
1267
+ return { direct, all };
1268
+ };
1269
+ var scan = async (cwd, registry) => {
1270
+ const root = await realpath3(cwd);
1271
+ const files = [...new Set(trackedFiles(root))].toSorted();
1272
+ const locks = files.filter((file) => /(?:^|\/)\.erbium\/lock\.json$/u.test(file));
1273
+ const graph = await importGraph(root, files);
1274
+ const packages = files.values().filter((file) => path6.basename(file) === "package.json").map((file) => path6.dirname(file)).toArray().toSorted((left, right) => right.length - left.length);
1275
+ return await Promise.all(locks.map(async (lock) => {
1276
+ const directory = path6.dirname(path6.dirname(lock));
1277
+ const project = path6.resolve(root, directory);
1278
+ const { items } = await loadLock(project);
1279
+ const usageItems = await Promise.all(Object.entries(items).map(async ([id, item]) => {
1280
+ const states = await Promise.all(Object.entries(item.files).map(async ([target, digest]) => {
1281
+ const absolute = await safePath(project, target);
1282
+ const local = await readText(absolute);
1283
+ return { absolute, target, modified: local === undefined || hash(local) !== digest };
1284
+ }));
1285
+ const upstream = registry?.items[id] ?? null;
1286
+ const { direct, all } = consumingFiles(graph, states.map(({ absolute }) => absolute));
1287
+ const importedBy = [...direct].map((file) => path6.relative(root, file)).toSorted();
1288
+ const usedByProjects = [
1289
+ ...new Set([...all].map((file) => {
1290
+ const relative = path6.relative(root, file);
1291
+ return packages.find((entry) => entry === "." || relative.startsWith(`${entry}/`)) ?? ".";
1292
+ }))
1293
+ ].toSorted();
1294
+ return {
1295
+ id,
1296
+ revision: item.revision,
1297
+ upstream,
1298
+ updateAvailable: upstream !== null && upstream !== item.revision,
1299
+ modifiedFiles: states.flatMap(({ target, modified }) => modified ? [target] : []),
1300
+ importedBy,
1301
+ usedByProjects
1302
+ };
1303
+ }));
1304
+ return { project: directory, items: usageItems };
1305
+ }));
1306
+ };
1307
+ var scanRemote = async (root, registry, repo) => {
1308
+ const temporary = await mkdtemp2(path6.join(tmpdir2(), "erbium-usage-"));
1309
+ const checkout = path6.join(temporary, "checkout");
1310
+ try {
1311
+ execFileSync("git", ["-C", root, "clone", "--depth", "1", "--quiet", "--", repo, checkout], {
1312
+ cwd: root,
1313
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0" }
1314
+ });
1315
+ return await scan(checkout, registry);
1316
+ } finally {
1317
+ await rm3(temporary, { recursive: true, force: true });
1318
+ }
1319
+ };
1320
+ var githubRepos = (root, organization) => {
1321
+ if (!/^[a-z0-9][a-z0-9-]*$/iu.test(organization)) {
1322
+ throw new Error("Provide a GitHub organization name.");
1323
+ }
1324
+ const output = execFileSync("gh", [
1325
+ "api",
1326
+ "--hostname",
1327
+ "github.com",
1328
+ "--paginate",
1329
+ "--slurp",
1330
+ `orgs/${organization}/repos?per_page=100`
1331
+ ], { cwd: root, encoding: "utf-8", maxBuffer: 32 * 1024 * 1024 });
1332
+ const pages = Schema7.decodeUnknownSync(Schema7.Array(Schema7.Array(Schema7.Struct({
1333
+ full_name: Schema7.String,
1334
+ clone_url: Schema7.String
1335
+ }))))(parseJson(output));
1336
+ return pages.flat().toSorted((left, right) => left.full_name.localeCompare(right.full_name, "en"));
1337
+ };
1338
+ var usage = async (cwd, location, offline, repo, github) => {
1339
+ if (repo.length > 0 && github.length > 0) {
1340
+ throw new Error("Use either --repo or --github.");
1341
+ }
1342
+ const root = await realpath3(cwd);
1343
+ const registry = offline ? undefined : await openRegistry(root, location);
1344
+ if (repo.length === 0 && github.length === 0) {
1345
+ return await scan(root, registry);
1346
+ }
1347
+ if (repo.length > 0) {
1348
+ return await scanRemote(root, registry, repo);
1349
+ }
1350
+ const projects = [];
1351
+ for (const repository of githubRepos(root, github)) {
1352
+ const found = await scanRemote(root, registry, repository.clone_url);
1353
+ projects.push(...found.map((project) => ({
1354
+ ...project,
1355
+ project: project.project === "." ? repository.full_name : `${repository.full_name}/${project.project}`
1356
+ })));
1357
+ }
1358
+ return projects;
1359
+ };
1360
+
1361
+ // src/registry-tools.ts
1362
+ import { once } from "node:events";
1363
+ import { cp, mkdir as mkdir5, readFile as readFile4, realpath as realpath4, rm as rm4 } from "node:fs/promises";
1364
+ import { createServer } from "node:http";
1365
+ import path9 from "node:path";
1366
+ import * as Schema9 from "effect/Schema";
1367
+
1368
+ // src/publish.ts
1369
+ import { execFileSync as execFileSync2 } from "node:child_process";
1370
+ import { mkdir as mkdir3, readFile as readFile3, writeFile as writeFile3 } from "node:fs/promises";
1371
+ import path7 from "node:path";
1372
+ import { fileURLToPath } from "node:url";
1373
+ import * as Schema8 from "effect/Schema";
1374
+ var root = fileURLToPath(new URL("../../..", import.meta.url));
1375
+ var decodeCatalog = Schema8.decodeUnknownSync(Schema8.Struct({ items: Schema8.Array(Schema8.Record(Schema8.String, Schema8.Json)) }));
1376
+ var itemName = Schema8.decodeUnknownSync(Schema8.Struct({ name: Schema8.String }));
1377
+ var firstRegistryCommit = "886b33bb9fb8d66dfd5e6a9a2ffe687ac341b88a";
1378
+ var catalogs = [
1379
+ ["erbium", "packages/ui/public/r/registry.json"],
1380
+ ["erbium-examples", "packages/showcase/public/r/registry.json"]
1381
+ ];
1382
+ var gitAt = (cwd, args) => execFileSync2("git", args, { cwd, encoding: "utf-8", maxBuffer: 50 * 1024 * 1024 });
1383
+ var historyPaths = (directory, sources) => sources.map(([namespace, file]) => {
1384
+ const relative = path7.relative(directory, path7.resolve(directory, file));
1385
+ if (relative.startsWith(`..${path7.sep}`) || relative === ".." || relative === "") {
1386
+ throw new Error(`Catalog must be inside the Git checkout to publish history: ${file}`);
1387
+ }
1388
+ return [namespace, relative.split(path7.sep).join("/")];
1389
+ });
1390
+ var publishRevisions = async (output, history, sources = catalogs, checkout) => {
1391
+ const revisions = path7.join(output, "revisions");
1392
+ await mkdir3(revisions, { recursive: true });
1393
+ const written = new Set;
1394
+ const catalog = {};
1395
+ const metadata = Schema8.decodeUnknownSync(Schema8.Struct({
1396
+ title: Schema8.optionalKey(Schema8.String),
1397
+ description: Schema8.optionalKey(Schema8.String),
1398
+ keywords: Schema8.optionalKey(Schema8.Array(Schema8.String))
1399
+ }));
1400
+ const items = {};
1401
+ const collect = (namespace, text, current, releaseItems) => {
1402
+ const records = decodeCatalog(parseJson(text)).items;
1403
+ const snapshots = [];
1404
+ const seen = new Set;
1405
+ for (const record of records) {
1406
+ const id = normalizeItem(`@${namespace}/${itemName(record).name}`);
1407
+ if (seen.has(id)) {
1408
+ throw new Error(`Duplicate registry item ${id}.`);
1409
+ }
1410
+ seen.add(id);
1411
+ const value = snapshotFor(id, record);
1412
+ const digest = revision(value);
1413
+ if (current) {
1414
+ items[id] = digest;
1415
+ catalog[id] = metadata(record);
1416
+ }
1417
+ if (releaseItems !== undefined) {
1418
+ releaseItems[id] = digest;
1419
+ }
1420
+ if (!written.has(digest)) {
1421
+ written.add(digest);
1422
+ snapshots.push({ digest, value });
1423
+ }
1424
+ }
1425
+ return snapshots;
1426
+ };
1427
+ const directory = history && checkout !== undefined ? gitAt(checkout, ["rev-parse", "--show-toplevel"]).trim() : root;
1428
+ const git = (args) => gitAt(directory, args);
1429
+ const files = history ? historyPaths(directory, sources) : [];
1430
+ if (history && git(["rev-parse", "--is-shallow-repository"]).trim() !== "false") {
1431
+ throw new Error("Registry publishing requires full Git history. Use fetch-depth: 0.");
1432
+ }
1433
+ const current = await Promise.all(sources.map(async ([namespace, file]) => collect(namespace, await readFile3(path7.resolve(root, file), "utf-8"), true)));
1434
+ const commits = history ? git([
1435
+ "--literal-pathspecs",
1436
+ "log",
1437
+ "--first-parent",
1438
+ "--full-history",
1439
+ "--format=%H",
1440
+ ...checkout === undefined ? [`${firstRegistryCommit}..HEAD`] : ["HEAD"],
1441
+ "--",
1442
+ ...files.map(([, file]) => file)
1443
+ ]).trim().split(`
1444
+ `).filter(Boolean) : [];
1445
+ if (history && checkout === undefined) {
1446
+ commits.push(firstRegistryCommit);
1447
+ } else if (history && commits.length === 0) {
1448
+ throw new Error("No committed catalog history found. Commit the catalog before publishing history.");
1449
+ }
1450
+ const releases = commits.map((commit) => ({
1451
+ commit,
1452
+ date: git(["show", "-s", "--format=%cI", commit]).trim(),
1453
+ items: Object.fromEntries([])
1454
+ }));
1455
+ const previous = releases.flatMap((release) => files.flatMap(([namespace, file]) => git(["--literal-pathspecs", "ls-tree", release.commit, "--", file]).length === 0 ? [] : collect(namespace, git(["show", `${release.commit}:${file}`]), false, release.items)));
1456
+ await Promise.all([...current.flat(), ...previous].map(async ({ digest, value }) => {
1457
+ await writeFile3(path7.join(revisions, `${digest}.json`), `${JSON.stringify(value)}
1458
+ `, {
1459
+ flag: "wx"
1460
+ }).catch(async () => {
1461
+ const existing = await readFile3(path7.join(revisions, `${digest}.json`), "utf-8");
1462
+ if (existing !== `${JSON.stringify(value)}
1463
+ `) {
1464
+ throw new Error(`Published snapshot differs from revision ${digest}.`);
1465
+ }
1466
+ });
1467
+ }));
1468
+ let last = {};
1469
+ const changes = releases.toReversed().map(({ commit, date, items: published }) => {
1470
+ const ids = new Set([...Object.keys(last), ...Object.keys(published)]);
1471
+ const changed = Object.fromEntries([...ids].flatMap((id) => last[id] === published[id] ? [] : [[id, published[id] ?? null]]));
1472
+ last = published;
1473
+ return { commit, date, changes: changed };
1474
+ }).toReversed();
1475
+ await atomicWrite(path7.join(output, "history.json"), `${JSON.stringify(changes)}
1476
+ `);
1477
+ const ordered = Object.fromEntries(Object.entries(items).toSorted(([left], [right]) => left.localeCompare(right, "en")));
1478
+ await atomicWrite(path7.join(output, "index.json"), `${JSON.stringify({
1479
+ version: 1,
1480
+ items: ordered,
1481
+ catalog: Object.fromEntries(Object.keys(ordered).map((id) => [id, catalog[id]]))
1482
+ })}
1483
+ `);
1484
+ };
1485
+
1486
+ // src/registry-site.ts
1487
+ import { mkdir as mkdir4 } from "node:fs/promises";
1488
+ import path8 from "node:path";
1489
+ var html = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
1490
+ var page = (title, body) => `<!doctype html>
1491
+ <html lang="en">
1492
+ <meta charset="utf-8">
1493
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1494
+ <title>${html(title)}</title>
1495
+ <style>
1496
+ :root { color-scheme: light dark; }
1497
+ body { font: 1rem/1.6 system-ui, sans-serif; max-width: 72ch; margin: 2rem auto; padding: 0 1rem; overflow-wrap: anywhere; }
1498
+ pre { padding: 1rem; border: 1px solid; overflow: auto; }
1499
+ summary { cursor: pointer; }
1500
+ </style>
1501
+ <main>${body}</main>
1502
+ </html>
1503
+ `;
1504
+ var itemPage = (id) => `items/${id.slice(1)}.html`;
1505
+ var writeRegistrySite = async (output, location, artifacts) => {
1506
+ const registry = await openRegistry(output, location);
1507
+ const history = await registry.history();
1508
+ const releases = history.toReversed();
1509
+ const entries = Object.entries(registry.items);
1510
+ const summaries = entries.map(([id]) => {
1511
+ const info = registry.catalog[id];
1512
+ return { id, title: info?.title ?? id, description: info?.description ?? "" };
1513
+ });
1514
+ await Promise.all(summaries.map(async ({ id, title, description }) => {
1515
+ const digest = registry.items[id];
1516
+ if (digest === undefined) {
1517
+ throw new Error(`Missing current revision for ${id}.`);
1518
+ }
1519
+ const { item } = await registry.load(id, digest);
1520
+ const files = (item.files ?? []).map(({ target, content }) => `<details><summary><code>${html(target)}</code></summary><pre><code>${html(content)}</code></pre></details>`);
1521
+ let previous;
1522
+ const revisions = releases.flatMap(({ commit, date, items }) => {
1523
+ const next = items[id];
1524
+ const changed = next !== previous;
1525
+ previous = next;
1526
+ return changed && next !== undefined ? [
1527
+ `<li><a href="../../r/erbium/revisions/${next}.json">${html(date)} · ${html(commit.slice(0, 12))}</a></li>`
1528
+ ] : [];
1529
+ }).toReversed();
1530
+ const dependencyLinks = (item.registryDependencies ?? []).map((dependency) => `<li><code>${html(dependency)}</code></li>`);
1531
+ const name = id.split("/")[1] ?? id;
1532
+ const story = artifacts.previews?.get(name);
1533
+ const preview = story === undefined ? "" : `<p><a href="../../storybook/iframe.html?id=${encodeURIComponent(story)}&amp;viewMode=story">Open Storybook preview</a></p>`;
1534
+ const file = path8.join(output, itemPage(id));
1535
+ await mkdir4(path8.dirname(file), { recursive: true });
1536
+ await atomicWrite(file, page(title, `<p><a href="../../index.html">Registry</a></p>
1537
+ <h1>${html(title)}</h1><p>${html(description)}</p>
1538
+ <p><code>erbium add ${html(id)} --registry &lt;url&gt;/r/erbium</code></p>
1539
+ <p><a href="../../r/erbium/revisions/${digest}.json">Current snapshot</a></p>
1540
+ ${preview}
1541
+ ${dependencyLinks.length > 0 ? `<h2>Registry dependencies</h2><ul>${dependencyLinks.join("")}</ul>` : ""}
1542
+ ${files.length > 0 ? `<h2>Source</h2>${files.join(`
1543
+ `)}` : ""}
1544
+ ${revisions.length > 0 ? `<h2>Published revisions</h2><ol>${revisions.join("")}</ol>` : ""}`));
1545
+ }));
1546
+ await Promise.all([
1547
+ atomicWrite(path8.join(output, "index.html"), page("Erbium registry", `<h1>Erbium registry</h1>
1548
+ <p><a href="llms.txt">Agent index</a> · <a href="r/erbium/index.json">Registry index</a></p>
1549
+ ${artifacts.usage ? '<p><a href="usage.json">Usage report</a></p>' : ""}
1550
+ ${artifacts.verify ? '<p><a href="verify.json">Verification report</a></p>' : ""}
1551
+ <ul>${summaries.map(({ id, title }) => `<li><a href="${itemPage(id)}">${html(title)}</a> <code>${html(id)}</code></li>`).join(`
1552
+ `)}</ul>`)),
1553
+ atomicWrite(path8.join(output, "llms.txt"), `# Erbium registry
1554
+
1555
+ > Source, dependencies, and revisions for each installable item.
1556
+
1557
+ ## Items
1558
+
1559
+ ${summaries.map(({ id }) => `- [${id}](${itemPage(id)})`).join(`
1560
+ `)}
1561
+ `)
1562
+ ]);
1563
+ };
1564
+
1565
+ // src/registry-tools.ts
1566
+ var decodeCatalog2 = Schema9.decodeUnknownSync(Schema9.Struct({
1567
+ items: Schema9.Array(Schema9.Record(Schema9.String, Schema9.Json))
1568
+ }));
1569
+ var itemName2 = Schema9.decodeUnknownSync(Schema9.Struct({ name: Schema9.String }));
1570
+ var sourceFile = /\.[cm]?[jt]sx?$/u;
1571
+ var canonicalPrefix = "@/registry/erbium/";
1572
+ var moduleExtensions = [".ts", ".tsx", ".js", ".jsx", ".json", ".css"];
1573
+ var resolvesModule = (targets, target) => {
1574
+ const stem = target.replace(/\.jsx?$/u, "");
1575
+ return targets.has(target) || moduleExtensions.some((extension) => targets.has(stem + extension) || targets.has(`${target}/index${extension}`));
1576
+ };
1577
+ var validateImports = (id, files, targets) => {
1578
+ for (const file of files) {
1579
+ if (!sourceFile.test(file.target)) {
1580
+ continue;
1581
+ }
1582
+ for (const specifier of importSpecifiers(file.content)) {
1583
+ let target;
1584
+ if (specifier.startsWith(canonicalPrefix)) {
1585
+ const name = specifier.slice(canonicalPrefix.length);
1586
+ target = name.startsWith("blocks/") ? `@components/${name}` : `@${name}`;
1587
+ } else if (specifier.startsWith("./") || specifier.startsWith("../")) {
1588
+ target = path9.posix.join(path9.posix.dirname(file.target), specifier);
1589
+ } else {
1590
+ continue;
1591
+ }
1592
+ if (!resolvesModule(targets, target)) {
1593
+ throw new Error(`Unresolved registry import ${specifier} in ${id} (${file.target}). Declare the item that ships it as a registry dependency.`);
1594
+ }
1595
+ }
1596
+ }
1597
+ };
1598
+ var validateSnapshots = (items) => {
1599
+ const seen = new Set;
1600
+ for (const { id, item } of items) {
1601
+ if (seen.has(id)) {
1602
+ throw new Error(`Duplicate registry item ${id}.`);
1603
+ }
1604
+ seen.add(id);
1605
+ const targets = new Set;
1606
+ for (const { target } of item.files ?? []) {
1607
+ if (targets.has(target) || !/^(?:@(?:ui|components|hooks|lib)|~)\/.+/u.test(target) || /(?:^|\/)\.\.?(?:\/|$)|\\|\/\//u.test(target)) {
1608
+ throw new Error(`Invalid or duplicate target ${target} in ${id}.`);
1609
+ }
1610
+ targets.add(target);
1611
+ }
1612
+ }
1613
+ const byId = new Map(items.map(({ id, item }) => [id, item]));
1614
+ const visited = new Map;
1615
+ const active = new Set;
1616
+ const visit = (id) => {
1617
+ const cached = visited.get(id);
1618
+ if (cached !== undefined) {
1619
+ return cached;
1620
+ }
1621
+ if (active.has(id)) {
1622
+ throw new Error(`Registry dependency cycle at ${id}.`);
1623
+ }
1624
+ const item = byId.get(id);
1625
+ if (item === undefined) {
1626
+ throw new Error(`Missing registry dependency ${id}.`);
1627
+ }
1628
+ active.add(id);
1629
+ const files = item.files ?? [];
1630
+ const targets = new Set(files.map(({ target }) => target));
1631
+ for (const child of item.registryDependencies ?? []) {
1632
+ for (const target of visit(normalizeItem(child))) {
1633
+ targets.add(target);
1634
+ }
1635
+ }
1636
+ validateImports(id, files, targets);
1637
+ active.delete(id);
1638
+ visited.set(id, targets);
1639
+ return targets;
1640
+ };
1641
+ for (const id of byId.keys()) {
1642
+ visit(id);
1643
+ }
1644
+ return items.length;
1645
+ };
1646
+ var validateRegistry = async (cwd, location) => {
1647
+ const registry = await openRegistry(cwd, location);
1648
+ const entries = Object.entries(registry.items);
1649
+ const items = [];
1650
+ const batchSize = 16;
1651
+ for (let start = 0;start < entries.length; start += batchSize) {
1652
+ const batch = entries.slice(start, start + batchSize);
1653
+ const snapshots = await Promise.all(batch.map(async ([id, digest]) => await registry.load(normalizeItem(id), digest)));
1654
+ items.push(...snapshots);
1655
+ }
1656
+ return validateSnapshots(items);
1657
+ };
1658
+ var storyIndex = Schema9.decodeUnknownSync(Schema9.Struct({
1659
+ entries: Schema9.Record(Schema9.String, Schema9.Struct({
1660
+ id: Schema9.String,
1661
+ type: Schema9.String,
1662
+ importPath: Schema9.String,
1663
+ name: Schema9.String
1664
+ }))
1665
+ }));
1666
+ var usageReport = Schema9.decodeUnknownSync(Schema9.Array(Schema9.Struct({
1667
+ project: Schema9.String,
1668
+ items: Schema9.Array(Schema9.Struct({ id: Schema9.String }))
1669
+ })));
1670
+ var verificationReport = Schema9.decodeUnknownSync(Schema9.Struct({
1671
+ ok: Schema9.Boolean,
1672
+ steps: Schema9.Array(Schema9.Struct({
1673
+ step: Schema9.String,
1674
+ ok: Schema9.Boolean,
1675
+ notes: Schema9.Array(Schema9.String)
1676
+ }))
1677
+ }));
1678
+ var readReport = async (cwd, file, validate) => {
1679
+ if (!file) {
1680
+ return null;
1681
+ }
1682
+ const content = await readFile4(path9.resolve(cwd, file), "utf-8");
1683
+ validate(parseJson(content));
1684
+ return content;
1685
+ };
1686
+ var readStorybook = async (cwd, directory, output) => {
1687
+ if (!directory) {
1688
+ return null;
1689
+ }
1690
+ const source = await realpath4(path9.resolve(cwd, directory));
1691
+ const destination = path9.join(await realpath4(output).catch(() => output), "storybook");
1692
+ if (source === destination || source.startsWith(destination + path9.sep) || destination.startsWith(source + path9.sep)) {
1693
+ throw new Error("Keep the Storybook input and output directories separate.");
1694
+ }
1695
+ const [index] = await Promise.all([
1696
+ readFile4(path9.join(source, "index.json"), "utf-8"),
1697
+ readFile4(path9.join(source, "iframe.html"))
1698
+ ]);
1699
+ const { entries } = storyIndex(parseJson(index));
1700
+ const previews = new Map;
1701
+ for (const entry of Object.values(entries)) {
1702
+ const match = /(?:^|\/)(?<name>[a-z0-9-]+)\.stories\.[cm]?[jt]sx?$/u.exec(entry.importPath);
1703
+ const name = match?.groups?.name;
1704
+ if (entry.type === "story" && name !== undefined && (!previews.has(name) || entry.name === "Default")) {
1705
+ previews.set(name, entry.id);
1706
+ }
1707
+ }
1708
+ return { source, destination, previews };
1709
+ };
1710
+ var buildRegistry = async ({
1711
+ cwd,
1712
+ input,
1713
+ examples,
1714
+ out,
1715
+ history,
1716
+ noSite,
1717
+ storybook,
1718
+ usage,
1719
+ verify
1720
+ }) => {
1721
+ const output = path9.resolve(cwd, out);
1722
+ const sources = [["erbium", path9.resolve(cwd, input)]];
1723
+ if (examples.length > 0) {
1724
+ sources.push(["erbium-examples", path9.resolve(cwd, examples)]);
1725
+ }
1726
+ const catalogs = await Promise.all(sources.map(async ([namespace, file]) => {
1727
+ const text = await readFile4(file, "utf-8");
1728
+ const { items } = decodeCatalog2(parseJson(text));
1729
+ const records = items.map((item) => {
1730
+ const { name } = itemName2(item);
1731
+ const id = normalizeItem(`@${namespace}/${name}`);
1732
+ if (name === "registry") {
1733
+ throw new Error(`Registry item ${id} conflicts with the catalog filename.`);
1734
+ }
1735
+ return { name, item, snapshot: snapshotFor(id, item) };
1736
+ });
1737
+ return { namespace, text, records };
1738
+ }));
1739
+ const count = validateSnapshots(catalogs.flatMap(({ records }) => records.map(({ snapshot }) => snapshot)));
1740
+ const [stories, usageJson, verifyJson] = await Promise.all([
1741
+ readStorybook(cwd, noSite ? "" : storybook, output),
1742
+ readReport(cwd, noSite ? "" : usage, usageReport),
1743
+ readReport(cwd, noSite ? "" : verify, verificationReport)
1744
+ ]);
1745
+ const managed = path9.join(output, "r", "erbium");
1746
+ const historySources = history ? await Promise.all(sources.map(async ([namespace, file]) => [namespace, await realpath4(file)])) : sources;
1747
+ await publishRevisions(managed, history, historySources, cwd);
1748
+ await Promise.all(catalogs.map(async ({ namespace, text, records }) => {
1749
+ const target = path9.join(output, "r", namespace === "erbium" ? "ui" : "examples");
1750
+ await mkdir5(target, { recursive: true });
1751
+ await Promise.all(records.map(async ({ name, item }) => {
1752
+ await atomicWrite(path9.join(target, `${name}.json`), `${JSON.stringify({
1753
+ ...item,
1754
+ $schema: "https://ui.shadcn.com/schema/registry-item.json"
1755
+ })}
1756
+ `);
1757
+ }));
1758
+ await atomicWrite(path9.join(target, "registry.json"), text);
1759
+ }));
1760
+ await Promise.all([
1761
+ rm4(await safePath(output, "storybook"), { recursive: true, force: true }),
1762
+ rm4(await safePath(output, "usage.json"), { force: true }),
1763
+ rm4(await safePath(output, "verify.json"), { force: true }),
1764
+ ...noSite ? [
1765
+ rm4(await safePath(output, "index.html"), { force: true }),
1766
+ rm4(await safePath(output, "llms.txt"), { force: true }),
1767
+ rm4(await safePath(output, "items"), { recursive: true, force: true })
1768
+ ] : []
1769
+ ]);
1770
+ if (!noSite) {
1771
+ await Promise.all([
1772
+ stories === null ? undefined : cp(stories.source, stories.destination, { recursive: true }),
1773
+ usageJson === null ? undefined : atomicWrite(path9.join(output, "usage.json"), usageJson),
1774
+ verifyJson === null ? undefined : atomicWrite(path9.join(output, "verify.json"), verifyJson),
1775
+ writeRegistrySite(output, managed, {
1776
+ previews: stories?.previews,
1777
+ usage: usageJson !== null,
1778
+ verify: verifyJson !== null
1779
+ })
1780
+ ]);
1781
+ }
1782
+ return { output, count };
1783
+ };
1784
+ var routes = /^\/(?<file>index\.html|llms\.txt|usage\.json|verify\.json|storybook\/.+|items\/(?:erbium|erbium-examples)\/[a-z0-9-]+\.html|r\/(?:erbium\/(?:index\.json|history\.json|revisions\/[a-f0-9]{64}\.json)|(?:ui|examples)\/[a-z0-9-]+\.json))$/u;
1785
+ var contentTypes = new Map([
1786
+ [".html", "text/html; charset=utf-8"],
1787
+ [".txt", "text/plain; charset=utf-8"],
1788
+ [".json", "application/json; charset=utf-8"],
1789
+ [".css", "text/css; charset=utf-8"],
1790
+ [".js", "text/javascript; charset=utf-8"],
1791
+ [".mjs", "text/javascript; charset=utf-8"],
1792
+ [".svg", "image/svg+xml"],
1793
+ [".png", "image/png"],
1794
+ [".webp", "image/webp"],
1795
+ [".jpg", "image/jpeg"],
1796
+ [".jpeg", "image/jpeg"],
1797
+ [".gif", "image/gif"],
1798
+ [".woff", "font/woff"],
1799
+ [".woff2", "font/woff2"],
1800
+ [".wasm", "application/wasm"]
1801
+ ]);
1802
+ var serveRegistry = async (cwd, directory, port, signal) => {
1803
+ const root = path9.resolve(cwd, directory);
1804
+ const server = createServer((request, response) => {
1805
+ const [url = ""] = request.url?.split("?") ?? [];
1806
+ const route = url === "/" || url === "/storybook/" ? `${url}index.html` : url;
1807
+ let file;
1808
+ try {
1809
+ file = routes.exec(decodeURIComponent(route))?.groups?.file;
1810
+ } catch {
1811
+ response.writeHead(400).end();
1812
+ return;
1813
+ }
1814
+ if (file === undefined || request.method !== "GET" && request.method !== "HEAD") {
1815
+ response.writeHead(404).end();
1816
+ return;
1817
+ }
1818
+ const send = async () => {
1819
+ const content = await readFile4(await safePath(root, file));
1820
+ const type = contentTypes.get(path9.extname(file)) ?? "application/octet-stream";
1821
+ response.writeHead(200, { "Content-Type": type, "Content-Length": content.length }).end(request.method === "HEAD" ? undefined : content);
1822
+ };
1823
+ send().catch(() => {
1824
+ response.writeHead(404).end();
1825
+ });
1826
+ });
1827
+ signal.throwIfAborted();
1828
+ const closed = once(server, "close");
1829
+ server.listen({ port, host: "127.0.0.1", signal });
1830
+ await closed;
1831
+ };
1832
+
1833
+ // src/index.ts
1834
+ var cwd = Flag.String("cwd").pipe(Flag.withDescription("Run from this project directory (default: current directory)"), Flag.withDefault("."));
1835
+ var registry = Flag.String("registry").pipe(Flag.withDescription("Use this managed registry directory or URL for this command"), Flag.withDefault(""));
1836
+ var json = Flag.Boolean("json").pipe(Flag.withDescription("Print machine-readable JSON"), Flag.withDefault(false));
1837
+ var commands = {
1838
+ add: "Install components and track the source you received",
1839
+ adopt: "Track an existing shadcn install that matches the current revision",
1840
+ check: "Verify tracked files and package declarations offline",
1841
+ diff: "Compare the installed baseline with upstream or your local edits",
1842
+ status: "Show local changes and available revisions",
1843
+ update: "Merge registry changes into tracked source"
1844
+ };
1845
+ var reportLine = (entry) => {
1846
+ if ("diff" in entry) {
1847
+ return entry.diff.length === 0 ? [] : [`${entry.target}
1848
+ ${entry.diff}`];
1849
+ }
1850
+ const states = [
1851
+ ...entry.removed ? ["removed upstream"] : [],
1852
+ ...entry.updateAvailable ? ["update available"] : []
1853
+ ];
1854
+ const files = entry.files.flatMap((file) => {
1855
+ const conditions = [
1856
+ ...file.missing ? ["missing"] : [],
1857
+ ...file.conflict ? ["unresolved conflict"] : [],
1858
+ ...file.modified ? ["modified locally"] : []
1859
+ ];
1860
+ return conditions.length === 0 ? [] : [` ${file.target} ${conditions.join(", ")}`];
1861
+ });
1862
+ return [`${entry.id} ${states.length === 0 ? "current" : states.join(", ")}`, ...files];
1863
+ };
1864
+ var render = (result, jsonOutput) => {
1865
+ if (jsonOutput) {
1866
+ return JSON.stringify(result, null, 2);
1867
+ }
1868
+ if (Array.isArray(result)) {
1869
+ return result.length === 0 ? "No tracked items." : result.flatMap(reportLine).join(`
1870
+ `);
1871
+ }
1872
+ if ("steps" in result) {
1873
+ return result.steps.flatMap(({ step, ok, notes }) => [`${step}: ${ok ? "passed" : "failed"}`, ...notes]).join(`
1874
+ `);
1875
+ }
1876
+ const action = result.dryRun ? "Would track" : "Tracked";
1877
+ const change = result.dryRun ? "would change" : "changed";
1878
+ const summary = result.items.length > 0 ? `${action} ${result.items.length} items. ${result.files.length} source files ${change}.` : "No updates to apply.";
1879
+ const dropped = result.dropped.map((file) => `Kept ${file}. The item no longer ships it.`);
1880
+ const dependencies = [...result.packages.dependencies, ...result.packages.devDependencies];
1881
+ const packages = [];
1882
+ if (dependencies.length > 0 && (result.skipInstall || result.dryRun)) {
1883
+ const actionLabel = result.skipInstall ? "Install separately:" : "Would install";
1884
+ packages.push(`${actionLabel} ${dependencies.join(", ")}.`);
1885
+ }
1886
+ const conflicts = result.conflicts.map((file) => `${result.dryRun ? "Would write" : "Wrote"} conflict markers in ${file}.`);
1887
+ return [summary, ...conflicts, ...dropped, ...result.packages.ranges, ...packages].join(`
1888
+ `);
1889
+ };
1890
+ var visibleFlag = (visible, flag) => visible ? flag : Flag.withHidden(flag);
1891
+ var operation = (mode) => {
1892
+ const writes = mode === "add" || mode === "adopt" || mode === "update";
1893
+ const installs = mode === "add" || mode === "update";
1894
+ const item = Argument.String("item").pipe(Argument.withDescription("Erbium item name, such as button or @erbium-examples/button-demo"));
1895
+ const common = {
1896
+ cwd,
1897
+ registry: mode === "check" ? Flag.withHidden(registry) : registry,
1898
+ json,
1899
+ dryRun: visibleFlag(writes, Flag.Boolean("dry-run").pipe(Flag.withDescription("Plan file and dependency changes without applying them"), Flag.withDefault(false))),
1900
+ local: visibleFlag(mode === "diff", Flag.Boolean("local").pipe(Flag.withDescription("Compare the installed baseline with the local files offline"), Flag.withDefault(false))),
1901
+ at: visibleFlag(mode === "adopt", Flag.String("at").pipe(Flag.withDescription("Adopt from a published Git commit or unique commit prefix"), Flag.withDefault(""))),
1902
+ only: visibleFlag(mode === "check", Flag.String("only").pipe(Flag.withDescription("Run comma-separated checks: config, provenance, dependencies, imports"), Flag.withDefault(""))),
1903
+ names: mode === "diff" ? item.pipe(Argument.map((name) => [name])) : item.pipe(Argument.variadic({ min: mode === "add" || mode === "adopt" ? 1 : 0 }))
1904
+ };
1905
+ const config = installs ? {
1906
+ ...common,
1907
+ skipInstall: Flag.Boolean("skip-install").pipe(Flag.withDescription("Track source and report missing packages for separate installation"), Flag.withDefault(false)),
1908
+ overwrite: Flag.Boolean("overwrite").pipe(Flag.withDescription("Replace selected files with registry copies"), Flag.withDefault(false)),
1909
+ conflictMarkers: Flag.Boolean("conflict-markers").pipe(Flag.withDescription("Write overlapping edits with Git conflict markers"), Flag.withDefault(false))
1910
+ } : common;
1911
+ return Command.make(mode, config, (options) => Effect.gen(function* runCommand() {
1912
+ const result = yield* Effect.tryPromise({
1913
+ try: async () => await runOperation(mode, options),
1914
+ catch: (cause) => new CliError.UserError({ cause })
1915
+ });
1916
+ const output = render(result, options.json);
1917
+ if (output.length > 0) {
1918
+ yield* Console.log(output);
1919
+ }
1920
+ if ("ok" in result && !result.ok) {
1921
+ yield* new CliError.UserError({ cause: new Error("Erbium check failed.") });
1922
+ }
1923
+ })).pipe(Command.withDescription(commands[mode]));
1924
+ };
1925
+ var query = (work, args, print) => Effect.gen(function* runQuery() {
1926
+ const result = yield* Effect.tryPromise({
1927
+ try: async () => await work(...args),
1928
+ catch: (cause) => new CliError.UserError({ cause })
1929
+ });
1930
+ yield* Console.log(print(result));
1931
+ });
1932
+ var data = JSON.stringify;
1933
+ var init = Command.make("init", {
1934
+ cwd,
1935
+ registry: registry.pipe(Flag.withDescription("Save a managed registry directory or URL")),
1936
+ headers: Flag.String("header").pipe(Flag.withDescription(`Save a header template such as 'Authorization: Bearer \${TOKEN}'`), Flag.atLeast(0)),
1937
+ agents: Flag.Boolean("agents").pipe(Flag.withDescription("Write the Erbium skill and add it to AGENTS.md"), Flag.withDefault(false)),
1938
+ json
1939
+ }, (options) => query(initialize, [options.cwd, options.agents, options.registry, options.headers], (files) => options.json ? data(files) : files.join(`
1940
+ `) || "Erbium is configured.")).pipe(Command.withDescription("Configure the Erbium registries in a shadcn project"));
1941
+ var searchCommand = Command.make("search", {
1942
+ cwd,
1943
+ registry,
1944
+ json,
1945
+ terms: Argument.String("term").pipe(Argument.variadic())
1946
+ }, (options) => query(search, [options.cwd, options.registry, options.terms], (items) => options.json ? data(items) : items.map((item) => `${item.id} ${item.description?.split(`
1947
+ `)[0] ?? ""}`.trimEnd()).join(`
1948
+ `))).pipe(Command.withDescription("Find registry items by name and description"));
1949
+ var docs = Command.make("docs", {
1950
+ cwd,
1951
+ topic: Argument.String("topic").pipe(Argument.withDefault("installation")),
1952
+ site: Flag.String("site").pipe(Flag.withDescription("Read a guide from this docs site (public site by default)"), Flag.withDefault("")),
1953
+ registry
1954
+ }, (options) => query(async () => {
1955
+ if (options.registry || !options.site && await hasRegistryConfig(options.cwd)) {
1956
+ return await registryDocumentation(options.cwd, options.registry, options.topic);
1957
+ }
1958
+ return await documentation(options.topic, options.site || defaultDocs);
1959
+ }, [], (markdown) => markdown)).pipe(Command.withDescription("Read Erbium documentation as Markdown"));
1960
+ var historyCommand = Command.make("history", {
1961
+ cwd,
1962
+ registry,
1963
+ json,
1964
+ item: Argument.String("item")
1965
+ }, (options) => query(history, [options.cwd, options.registry, options.item], (releases) => options.json ? data(releases) : releases.map(({ revision, commit, date, current }) => `${revision} ${commit ?? ""} ${date ?? ""}${current ? " current" : ""}`).join(`
1966
+ `))).pipe(Command.withDescription("Show published revisions of an item"));
1967
+ var usageCommand = Command.make("usage", {
1968
+ cwd,
1969
+ registry,
1970
+ json,
1971
+ offline: Flag.Boolean("offline").pipe(Flag.withDescription("Skip registry lookups and report local usage"), Flag.withDefault(false)),
1972
+ repo: Flag.String("repo").pipe(Flag.withDescription("Scan a temporary checkout of this Git repository"), Flag.withDefault("")),
1973
+ github: Flag.String("github").pipe(Flag.withDescription("Scan repositories visible to the GitHub CLI in this organization"), Flag.withDefault(""))
1974
+ }, (options) => query(usage, [options.cwd, options.registry, options.offline, options.repo, options.github], (projects) => options.json ? data(projects) : projects.flatMap(({ project, items }) => items.map((item) => `${project} ${item.id} ${item.importedBy.length} importing files${item.updateAvailable ? " update available" : ""}`)).join(`
1975
+ `) || "No tracked projects.")).pipe(Command.withDescription("Show tracked items and their imports in a Git repository"));
1976
+ var registryCommands = Command.make("registry").pipe(Command.withDescription("Build, validate, and serve a versioned Erbium registry"), Command.withSubcommands([
1977
+ Command.make("build", {
1978
+ cwd,
1979
+ input: Argument.String("catalog").pipe(Argument.withDescription("Path to a shadcn catalog with inlined file contents")),
1980
+ examples: Flag.String("examples").pipe(Flag.withDescription("Include a second catalog for @erbium-examples items"), Flag.withDefault("")),
1981
+ storybook: Flag.String("storybook").pipe(Flag.withDescription("Include a static Storybook build for item previews"), Flag.withDefault("")),
1982
+ usage: Flag.String("usage").pipe(Flag.withDescription("Publish a report from erbium usage --json"), Flag.withDefault("")),
1983
+ verify: Flag.String("verify").pipe(Flag.withDescription("Publish a report from erbium check --json"), Flag.withDefault("")),
1984
+ noSite: Flag.Boolean("no-site").pipe(Flag.withDescription("Publish only the managed and shadcn registry files"), Flag.withDefault(false)),
1985
+ history: Flag.Boolean("history").pipe(Flag.withDescription("Publish revisions from the catalogs’ first-parent Git history"), Flag.withDefault(false)),
1986
+ out: Flag.String("out").pipe(Flag.withDescription("Write artifacts to this directory (default: dist/registry)"), Flag.withDefault("dist/registry"))
1987
+ }, (options) => query(buildRegistry, [options], ({ output, count }) => `Built ${count} items in ${output}.`)).pipe(Command.withDescription("Validate catalogs and write a static registry")),
1988
+ Command.make("validate", { cwd, registry }, (options) => query(validateRegistry, [options.cwd, options.registry], (count) => `Validated ${count} items.`)).pipe(Command.withDescription("Validate a managed registry’s revisions and imports")),
1989
+ Command.make("serve", {
1990
+ cwd,
1991
+ directory: Argument.String("directory").pipe(Argument.withDefault("dist/registry")),
1992
+ port: Flag.Int("port").pipe(Flag.withDescription("Listen on this loopback port (default: 4178)"), Flag.withDefault(4178))
1993
+ }, ({ cwd: root, directory, port }) => Effect.gen(function* serve() {
1994
+ yield* Console.log(`Serving registry on http://127.0.0.1:${port}/`);
1995
+ yield* Effect.tryPromise({
1996
+ try: async (signal) => {
1997
+ await serveRegistry(root, directory, port, signal);
1998
+ },
1999
+ catch: (cause) => new CliError.UserError({ cause })
2000
+ });
2001
+ })).pipe(Command.withDescription("Serve a built registry on loopback for local testing"))
2002
+ ]));
2003
+ var cli = Command.make("erbium").pipe(Command.withDescription("Manage source-owned Erbium UI components"), Command.withSubcommands([
2004
+ init,
2005
+ searchCommand,
2006
+ docs,
2007
+ historyCommand,
2008
+ usageCommand,
2009
+ registryCommands,
2010
+ operation("add"),
2011
+ operation("adopt"),
2012
+ operation("status"),
2013
+ operation("diff"),
2014
+ operation("update"),
2015
+ operation("check")
2016
+ ]));
2017
+ NodeRuntime.runMain(Command.run(cli, { version: package_default.version }).pipe(Effect.provide(NodeServices.layer)));