atoms-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.
package/LICENSE ADDED
@@ -0,0 +1,24 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 thalavai-sankar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ Portions of this software are derived from Koala UI and other third-party
24
+ packages; their copyright and license notices are in THIRD_PARTY_NOTICES.md.
package/README.md CHANGED
@@ -1,3 +1,54 @@
1
- # Temporary Holding Version
1
+ # atoms-cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Copy editable Atoms design-system source into your project from the Atoms registry. You own the
4
+ files: edit them freely, and the CLI won't overwrite your changes unless you pass `--force`.
5
+
6
+ Needs Node 18.17 or later, a `package.json`, Tailwind CSS v4, React 19.2 or later, and a TypeScript
7
+ path alias for your source root (`"@/*": ["./src/*"]`, or `["./*"]` without a src folder).
8
+
9
+ ```sh
10
+ npx atoms-cli@latest init # detect the project, write atoms.json, add the foundation stylesheet
11
+ npx atoms-cli@latest list # see what the registry has
12
+ npx atoms-cli@latest add button # add Button and everything it needs
13
+ npx atoms-cli@latest add --all # add every item
14
+ ```
15
+
16
+ ## What init detects
17
+
18
+ - **Layout:** whether your code lives in `src/`.
19
+ - **Alias:** the tsconfig (or jsconfig) path that points at your source root, following `extends`,
20
+ `references` and `baseUrl`. Imports in the installed files are rewritten to it, so `@/lib/utils`
21
+ becomes `~/lib/utils` in a project that uses `~`.
22
+ - **Global stylesheet:** the one that imports Tailwind. The foundation stylesheet is imported right
23
+ after it.
24
+ - **Package manager:** npm, pnpm, yarn or bun, from `packageManager` or the lockfile.
25
+
26
+ All of it is saved in `atoms.json`, with the registry URL and a record of every file the CLI wrote.
27
+
28
+ ## How add works
29
+
30
+ 1. Resolves the items and their registry dependencies, dependencies first.
31
+ 2. Checks every downloaded file against its SHA-256 hash, and every item against the registry
32
+ index. Any mismatch stops the install before anything is written.
33
+ 3. Installs only the npm packages your `package.json` doesn't already list.
34
+ 4. Writes the files. A file that already exists and differs is kept and reported: edited by you,
35
+ written before atoms, or an older version.
36
+
37
+ **`--force` replaces locally edited registry files.** It overwrites every file that differs from the
38
+ registry, and your local changes to those files are lost. Run `--force --dry-run` first to see which
39
+ files it would replace.
40
+
41
+ ## Options
42
+
43
+ | Option | |
44
+ |---|---|
45
+ | `--cwd <path>` | Project folder (default: the current folder) |
46
+ | `--registry <url>` | Registry base URL (default: atoms.json, then https://atomsdesignsystem.vercel.app/r) |
47
+ | `--force` | Replace files that differ from the registry, including ones you edited |
48
+ | `--dry-run` | Show what would change without writing or installing anything |
49
+ | `--skip-install` | Don't run the package manager; print the command instead |
50
+ | `--verbose` | Show paths, dependencies and instructions |
51
+ | `-h, --help` | Show help |
52
+ | `-v, --version` | Show the version |
53
+
54
+ Exit code 0 means success; 1 means an error, reported on one line with a hint.
package/bin/atoms.mjs ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { main } from "../src/main.mjs"
3
+
4
+ process.exitCode = await main(process.argv.slice(2))
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "atoms-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Install editable Atoms design-system source into your project from the Atoms registry.",
5
+ "keywords": [
6
+ "atoms",
7
+ "design-system",
8
+ "components",
9
+ "registry",
10
+ "cli"
11
+ ],
12
+ "license": "MIT",
13
+ "homepage": "https://atomsdesignsystem.vercel.app",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/thalavai-sankar/atoms.git",
17
+ "directory": "packages/cli"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/thalavai-sankar/atoms/issues"
21
+ },
22
+ "type": "module",
23
+ "bin": {
24
+ "atoms": "bin/atoms.mjs"
25
+ },
26
+ "exports": {
27
+ ".": "./src/main.mjs",
28
+ "./package.json": "./package.json"
29
+ },
30
+ "files": [
31
+ "bin",
32
+ "src",
33
+ "README.md",
34
+ "LICENSE"
35
+ ],
36
+ "engines": {
37
+ "node": ">=18.17"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "scripts": {
43
+ "test": "vitest run --config vitest.config.mjs"
44
+ }
45
+ }
package/src/config.mjs ADDED
@@ -0,0 +1,46 @@
1
+ // atoms.json: the project's registry settings and a record of what the CLI installed. The record
2
+ // (`installed.<item>.files`) holds the hash each file had when it was written, which is how the
3
+ // CLI tells a file it wrote from one someone has since edited.
4
+
5
+ import fs from "node:fs"
6
+ import path from "node:path"
7
+
8
+ import { CliError } from "./errors.mjs"
9
+
10
+ export const CONFIG_FILE = "atoms.json"
11
+
12
+ export function configPath(cwd) {
13
+ return path.join(cwd, CONFIG_FILE)
14
+ }
15
+
16
+ export function readConfig(cwd, { required = true } = {}) {
17
+ const file = configPath(cwd)
18
+ if (!fs.existsSync(file)) {
19
+ if (!required) return null
20
+ throw new CliError(`No ${CONFIG_FILE} in ${cwd}.`, { hint: "Run `atoms init` first." })
21
+ }
22
+ let config
23
+ try {
24
+ config = JSON.parse(fs.readFileSync(file, "utf8"))
25
+ } catch (error) {
26
+ throw new CliError(`${CONFIG_FILE} is not valid JSON: ${error.message}`)
27
+ }
28
+ for (const key of ["registry", "alias", "stylesheet"]) {
29
+ if (typeof config[key] !== "string" || !config[key]) throw new CliError(`${CONFIG_FILE} has no "${key}".`, { hint: "Run `atoms init --force` to write it again." })
30
+ }
31
+ if (typeof config.srcDir !== "boolean") throw new CliError(`${CONFIG_FILE} has no "srcDir".`, { hint: "Run `atoms init --force` to write it again." })
32
+ config.installed ??= {}
33
+ return config
34
+ }
35
+
36
+ export function writeConfig(cwd, config) {
37
+ fs.writeFileSync(configPath(cwd), `${JSON.stringify(config, null, 2)}\n`)
38
+ }
39
+
40
+ /** The hash a target had when the CLI last wrote it, if it did. */
41
+ export function recordedHash(config, target) {
42
+ for (const entry of Object.values(config?.installed ?? {})) {
43
+ if (entry?.files?.[target]) return entry.files[target]
44
+ }
45
+ return null
46
+ }
package/src/errors.mjs ADDED
@@ -0,0 +1,9 @@
1
+ /** An error the CLI reports as one clear line (plus an optional hint), without a stack trace. */
2
+ export class CliError extends Error {
3
+ constructor(message, { hint, details } = {}) {
4
+ super(message)
5
+ this.name = "CliError"
6
+ this.hint = hint
7
+ this.details = details
8
+ }
9
+ }
@@ -0,0 +1,130 @@
1
+ // Plans and applies an install: which files to create, leave or replace, which npm packages are
2
+ // missing, and the foundation stylesheet's import in the app's global stylesheet.
3
+
4
+ import { spawn } from "node:child_process"
5
+ import fs from "node:fs"
6
+ import path from "node:path"
7
+
8
+ import { recordedHash } from "./config.mjs"
9
+ import { CliError } from "./errors.mjs"
10
+ import { declaredPackages } from "./project.mjs"
11
+ import { integrityOf } from "./registry.mjs"
12
+
13
+ const normalise = (content) => content.replace(/\r\n?/g, "\n")
14
+
15
+ /**
16
+ * One entry per file: `create` when it doesn't exist, `unchanged` when it already holds this content,
17
+ * `replace` when it differs and --force was passed, and `keep` when it differs without --force.
18
+ */
19
+ export function planFiles(cwd, items, config, { force }) {
20
+ const owners = new Map()
21
+ const files = []
22
+ for (const item of items) {
23
+ for (const file of item.files) {
24
+ if (owners.has(file.target)) {
25
+ throw new CliError(`"${item.name}" and "${owners.get(file.target)}" both write ${file.target}. Nothing was installed.`)
26
+ }
27
+ owners.set(file.target, item.name)
28
+ const absolute = path.join(cwd, file.target)
29
+ const entry = { item: item.name, target: file.target, absolute, content: file.content, integrity: file.integrity }
30
+ if (!fs.existsSync(absolute)) {
31
+ files.push({ ...entry, action: "create" })
32
+ continue
33
+ }
34
+ const current = normalise(fs.readFileSync(absolute, "utf8"))
35
+ if (current === normalise(file.content)) {
36
+ files.push({ ...entry, action: "unchanged" })
37
+ continue
38
+ }
39
+ const recorded = recordedHash(config, file.target)
40
+ const reason = !recorded
41
+ ? "not written by atoms"
42
+ : integrityOf(current) === recorded
43
+ ? "older version"
44
+ : "modified locally"
45
+ files.push({ ...entry, action: force ? "replace" : "keep", reason })
46
+ }
47
+ }
48
+ return files
49
+ }
50
+
51
+ export function applyFiles(files) {
52
+ for (const file of files) {
53
+ if (file.action !== "create" && file.action !== "replace") continue
54
+ fs.mkdirSync(path.dirname(file.absolute), { recursive: true })
55
+ fs.writeFileSync(file.absolute, file.content)
56
+ }
57
+ }
58
+
59
+ /** The npm packages the items use, the ones package.json lacks, and missing peers. */
60
+ export function planDependencies(pkg, items) {
61
+ const needed = new Map()
62
+ const peers = new Map()
63
+ for (const item of items) {
64
+ for (const [name, range] of Object.entries(item.dependencies ?? {})) needed.set(name, range)
65
+ for (const [name, range] of Object.entries(item.peerDependencies ?? {})) peers.set(name, range)
66
+ }
67
+ const declared = declaredPackages(pkg)
68
+ const missing = [...needed].filter(([name]) => !declared.has(name)).sort(([a], [b]) => a.localeCompare(b))
69
+ const missingPeers = [...peers].filter(([name]) => !declared.has(name)).sort(([a], [b]) => a.localeCompare(b))
70
+ return { needed, missing, missingPeers }
71
+ }
72
+
73
+ const TAILWIND_IMPORT = /@import\s+(?:url\()?["']tailwindcss["'][^;]*;/
74
+
75
+ /** The import line that brings the foundation stylesheet into the app's global stylesheet. */
76
+ export function planStylesheet(cwd, stylesheet, items) {
77
+ const foundationFiles = items.filter((item) => item.type === "foundation").flatMap((item) => item.files).filter((file) => file.target.endsWith(".css"))
78
+ if (!foundationFiles.length) return null
79
+ const sheetPath = path.join(cwd, stylesheet)
80
+ if (!fs.existsSync(sheetPath)) {
81
+ throw new CliError(`The stylesheet in atoms.json, ${stylesheet}, doesn't exist.`, { hint: "Run `atoms init --force` to detect it again." })
82
+ }
83
+ const original = fs.readFileSync(sheetPath, "utf8")
84
+ let content = original
85
+ const added = []
86
+ let missingTailwind = false
87
+ for (const file of foundationFiles) {
88
+ let specifier = path.posix.relative(path.posix.dirname(stylesheet), file.target)
89
+ if (!specifier.startsWith(".")) specifier = `./${specifier}`
90
+ const already = new RegExp(`@import\\s+(?:url\\()?["'](?:\\./)?${specifier.replace(/^\.\//, "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}["']`)
91
+ if (already.test(content)) continue
92
+ const line = `@import "${specifier}";`
93
+ const match = TAILWIND_IMPORT.exec(content)
94
+ if (match) {
95
+ const end = match.index + match[0].length
96
+ content = `${content.slice(0, end)}\n${line}${content.slice(end)}`
97
+ } else {
98
+ missingTailwind = true
99
+ content = `${line}\n${content}`
100
+ }
101
+ added.push(specifier)
102
+ }
103
+ return { path: stylesheet, absolute: sheetPath, changed: content !== original, content, added, missingTailwind }
104
+ }
105
+
106
+ /**
107
+ * Runs the package manager. On Windows npm, pnpm and yarn are .cmd shims that need a shell, so
108
+ * each argument is quoted (ranges hold `^`, which cmd.exe would otherwise eat). The command itself
109
+ * is quoted only when it has to be: a quoted `"npm"` makes npm.cmd look for itself in the current
110
+ * folder instead of its own.
111
+ */
112
+ export function runInstall({ command, args, cwd, onOutput }) {
113
+ return new Promise((resolve) => {
114
+ const windows = process.platform === "win32"
115
+ const shellCommand = /[\s"&|<>^()]/.test(command) ? `"${command}"` : command
116
+ const child = windows
117
+ ? spawn([shellCommand, ...args.map((arg) => `"${arg}"`)].join(" "), { cwd, shell: true, windowsHide: true })
118
+ : spawn(command, args, { cwd })
119
+ let output = ""
120
+ const collect = (chunk) => {
121
+ const text = chunk.toString()
122
+ output += text
123
+ onOutput?.(text)
124
+ }
125
+ child.stdout?.on("data", collect)
126
+ child.stderr?.on("data", collect)
127
+ child.on("error", (error) => resolve({ code: null, output: `${output}${error.message}`, error }))
128
+ child.on("close", (code) => resolve({ code, output }))
129
+ })
130
+ }
package/src/main.mjs ADDED
@@ -0,0 +1,331 @@
1
+ // atoms: installs editable Atoms source from the registry into a project.
2
+ //
3
+ // atoms init detect the project, write atoms.json, add the foundation stylesheet
4
+ // atoms list show the registry's items
5
+ // atoms add <item...> add items and everything they need
6
+ // atoms add --all add every item
7
+ //
8
+ // `main` takes its I/O as arguments so tests can run it in-process: the working directory,
9
+ // output streams, `fetch` and the package-manager runner.
10
+
11
+ import fs from "node:fs"
12
+ import path from "node:path"
13
+ import { parseArgs } from "node:util"
14
+
15
+ import { CONFIG_FILE, readConfig, writeConfig } from "./config.mjs"
16
+ import { CliError } from "./errors.mjs"
17
+ import { applyFiles, planDependencies, planFiles, planStylesheet, runInstall } from "./install.mjs"
18
+ import { detectAlias, detectPackageManager, detectStylesheet, installCommand, readPackageJson } from "./project.mjs"
19
+ import { DEFAULT_REGISTRY, createRegistry } from "./registry.mjs"
20
+
21
+ const VERSION = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version
22
+
23
+ const HELP = `Install editable Atoms design-system source into your project.
24
+
25
+ Usage
26
+ atoms init Detect the project, write ${CONFIG_FILE} and add the foundation stylesheet
27
+ atoms list List the registry's items
28
+ atoms add <item...> Add items and the registry items they depend on
29
+ atoms add --all Add every item
30
+
31
+ Options
32
+ --cwd <path> Project folder (default: the current folder)
33
+ --registry <url> Registry base URL (default: ${CONFIG_FILE}, then ${DEFAULT_REGISTRY})
34
+ --force Replace files that differ from the registry, including ones you edited
35
+ --dry-run Show what would change without writing or installing anything
36
+ --skip-install Don't run the package manager; print the command instead
37
+ --verbose Show paths, dependencies and instructions
38
+ -h, --help Show this help
39
+ -v, --version Show the version`
40
+
41
+ const PLURALS = { dependency: "dependencies" }
42
+ const plural = (count, word) => `${count} ${count === 1 ? word : PLURALS[word] ?? `${word}s`}`
43
+
44
+ function createReporter(io, verbose) {
45
+ const color = io.color
46
+ const paint = (code, text) => (color ? `\u001b[${code}m${text}\u001b[0m` : text)
47
+ const line = (stream, text) => stream.write(`${text}\n`)
48
+ return {
49
+ header: (text) => line(io.stdout, paint("1", text)),
50
+ ok: (text) => line(io.stdout, `${paint("32", "✓")} ${text}`),
51
+ plan: (text) => line(io.stdout, `${paint("36", "○")} ${text}`),
52
+ skip: (text) => line(io.stdout, `${paint("2", "–")} ${text}`),
53
+ warn: (text) => line(io.stdout, `${paint("33", "!")} ${text}`),
54
+ info: (text) => line(io.stdout, ` ${text}`),
55
+ detail: (text) => verbose && line(io.stdout, paint("2", ` ${text}`)),
56
+ section: (text) => verbose && line(io.stdout, ` ${paint("1", text)}`),
57
+ error: (error) => {
58
+ line(io.stderr, `${paint("31", "✗")} ${error.message}`)
59
+ if (error.hint) line(io.stderr, ` ${error.hint}`)
60
+ if (verbose && error.details) line(io.stderr, paint("2", error.details.trimEnd().split("\n").map((row) => ` ${row}`).join("\n")))
61
+ },
62
+ }
63
+ }
64
+
65
+ function parse(argv) {
66
+ try {
67
+ return parseArgs({
68
+ args: argv,
69
+ allowPositionals: true,
70
+ strict: true,
71
+ options: {
72
+ cwd: { type: "string" },
73
+ registry: { type: "string" },
74
+ force: { type: "boolean" },
75
+ "dry-run": { type: "boolean" },
76
+ "skip-install": { type: "boolean" },
77
+ verbose: { type: "boolean" },
78
+ all: { type: "boolean" },
79
+ help: { type: "boolean", short: "h" },
80
+ version: { type: "boolean", short: "v" },
81
+ },
82
+ })
83
+ } catch (error) {
84
+ throw new CliError(error.message.replace(/\. To specify.*$/s, "."), { hint: "Run `atoms --help` for the options." })
85
+ }
86
+ }
87
+
88
+ /** Resolves, plans and applies one install. Used by `init` (the foundations) and `add`. */
89
+ async function installItems({ cwd, pkg, config, registry, index, requested, flags, report, io, onCommit }) {
90
+ const dryRun = flags["dry-run"]
91
+ const items = await registry.resolve(requested, index)
92
+ const requestedSet = new Set(requested)
93
+ report.ok(`Resolved ${plural(items.length, "item")}`)
94
+ report.section("Items, in install order")
95
+ for (const item of items) report.detail(`${item.name} (${item.type}${requestedSet.has(item.name) ? "" : ", dependency"})`)
96
+
97
+ const files = planFiles(cwd, items, config, { force: flags.force })
98
+ const deps = planDependencies(pkg, items)
99
+ const sheet = planStylesheet(cwd, config.stylesheet, items)
100
+ const packageManager = detectPackageManager(cwd, pkg)
101
+ const specs = deps.missing.map(([name, range]) => `${name}@${range}`)
102
+ const install = installCommand(packageManager, specs)
103
+ const commandText = `${install.command} ${install.args.map((arg) => (/[\s^<>|&]/.test(arg) ? `"${arg}"` : arg)).join(" ")}`
104
+
105
+ report.section("npm dependencies")
106
+ for (const [name, range] of [...deps.needed].sort(([a], [b]) => a.localeCompare(b))) {
107
+ report.detail(`${name}@${range}${deps.missing.some(([missing]) => missing === name) ? " (missing)" : " (in package.json)"}`)
108
+ }
109
+ if (deps.missingPeers.length) {
110
+ report.warn(`Missing peer dependencies: ${deps.missingPeers.map(([name, range]) => `${name} ${range}`).join(", ")}. Install them yourself.`)
111
+ }
112
+
113
+ const count = (action) => files.filter((file) => file.action === action).length
114
+ const fileSummary = (verb) => {
115
+ const parts = [`${verb} ${plural(count("create"), "file")}`, `${count("unchanged")} unchanged`]
116
+ if (count("replace")) parts.push(`${count("replace")} replaced`)
117
+ return parts.join("; ")
118
+ }
119
+ const symbol = { create: "+", unchanged: "=", replace: "~", keep: "!" }
120
+ const listFiles = () => {
121
+ report.section("Files")
122
+ for (const file of files) report.detail(`${symbol[file.action]} ${file.target}${file.reason ? ` (${file.reason})` : ""}`)
123
+ }
124
+ const kept = files.filter((file) => file.action === "keep")
125
+ const reportKept = (verb) => {
126
+ if (!kept.length) return
127
+ report.warn(`${verb} ${plural(kept.length, "file")} that differ from the registry (use --force to replace)`)
128
+ for (const file of kept.slice(0, 10)) report.info(`${file.target} (${file.reason})`)
129
+ if (kept.length > 10) report.info(`…and ${kept.length - 10} more`)
130
+ }
131
+
132
+ if (dryRun) {
133
+ if (deps.missing.length) report.plan(`Would install ${plural(deps.missing.length, "dependency")}: ${commandText}`)
134
+ else report.plan("Would install 0 dependencies")
135
+ report.plan(fileSummary("Would create"))
136
+ listFiles()
137
+ reportKept("Would keep")
138
+ if (sheet?.changed) report.plan(`Would import ${sheet.added.join(", ")} in ${sheet.path}`)
139
+ showInstructions(items, report)
140
+ report.ok("Dry run complete: nothing was written or installed")
141
+ return
142
+ }
143
+
144
+ if (deps.missing.length && !flags["skip-install"]) {
145
+ report.detail(`$ ${commandText}`)
146
+ const result = await io.runInstall({ ...install, cwd, onOutput: flags.verbose ? (text) => io.stdout.write(text) : undefined })
147
+ if (result.code !== 0) {
148
+ const tail = (result.output ?? "").trim().split("\n").slice(-12).join("\n")
149
+ throw new CliError(
150
+ `Dependency installation failed: \`${commandText}\` ${result.code === null ? `could not start (${result.error?.message ?? "unknown error"})` : `exited with code ${result.code}`}. No files were written.`,
151
+ { hint: "Fix the package manager error and run the same command again, or pass --skip-install and install them yourself.", details: tail },
152
+ )
153
+ }
154
+ report.ok(`Installed ${plural(deps.missing.length, "dependency")}`)
155
+ } else if (deps.missing.length) {
156
+ report.skip(`Skipped installing ${plural(deps.missing.length, "dependency")} (--skip-install). Run:`)
157
+ report.info(commandText)
158
+ } else {
159
+ report.ok("Installed 0 dependencies")
160
+ }
161
+
162
+ applyFiles(files)
163
+ report.ok(fileSummary("Created"))
164
+ listFiles()
165
+ reportKept("Kept")
166
+ if (sheet?.changed) {
167
+ fs.writeFileSync(sheet.absolute, sheet.content)
168
+ report.ok(`Imported ${sheet.added.join(", ")} in ${sheet.path}`)
169
+ if (sheet.missingTailwind) report.warn(`${sheet.path} doesn't import Tailwind; add \`@import "tailwindcss";\` above the Atoms import.`)
170
+ }
171
+
172
+ for (const item of items) {
173
+ const previous = config.installed[item.name]?.files ?? {}
174
+ const recorded = {}
175
+ for (const file of files.filter((entry) => entry.item === item.name)) {
176
+ recorded[file.target] = file.action === "keep" ? previous[file.target] ?? null : file.integrity
177
+ if (recorded[file.target] === null) delete recorded[file.target]
178
+ }
179
+ config.installed[item.name] = { version: item.version, files: recorded }
180
+ }
181
+ config.installed = Object.fromEntries(Object.entries(config.installed).sort(([a], [b]) => a.localeCompare(b)))
182
+ writeConfig(cwd, config)
183
+ onCommit?.()
184
+ showInstructions(items, report)
185
+ report.ok("Installation complete")
186
+ }
187
+
188
+ // Steps every item shares; the rest are item-specific notes worth showing.
189
+ const GENERIC_STEP = /^(Install its registry dependencies|Install the npm packages|It needs |Write each file)/
190
+
191
+ function showInstructions(items, report) {
192
+ const notes = items.flatMap((item) => (item.install?.steps ?? []).filter((step) => !GENERIC_STEP.test(step)).map((step) => `${item.name}: ${step}`))
193
+ if (!notes.length) return
194
+ report.section("Instructions")
195
+ for (const note of notes) report.detail(note)
196
+ }
197
+
198
+ async function commandInit({ cwd, flags, report, io }) {
199
+ const pkg = readPackageJson(cwd)
200
+ let existing = null
201
+ try {
202
+ existing = readConfig(cwd, { required: false })
203
+ } catch (error) {
204
+ if (!flags.force) throw error
205
+ }
206
+ let config
207
+ let created = false
208
+ if (existing && !flags.force) {
209
+ config = existing
210
+ if (flags.registry) config.registry = flags.registry
211
+ } else {
212
+ const { alias, srcDir } = detectAlias(cwd)
213
+ const sheet = detectStylesheet(cwd, srcDir, [`${srcDir ? "src/" : ""}styles/atoms.css`])
214
+ config = {
215
+ registry: flags.registry ?? existing?.registry ?? DEFAULT_REGISTRY,
216
+ alias,
217
+ srcDir,
218
+ stylesheet: sheet.path,
219
+ installed: existing?.installed ?? {},
220
+ }
221
+ created = true
222
+ }
223
+ const registry = createRegistry({ url: config.registry, alias: config.alias, srcDir: config.srcDir, fetch: io.fetch })
224
+ config.registry = registry.base
225
+ const index = await registry.index()
226
+ report.header(index.title ?? "Atoms")
227
+ report.ok(`Detected ${config.srcDir ? "src/" : "root"} layout, alias ${config.alias}/, stylesheet ${config.stylesheet}${existing && !flags.force ? ` (from ${CONFIG_FILE})` : ""}`)
228
+ report.detail(`Project: ${cwd}`)
229
+ report.detail(`Registry: ${registry.base} (${index.name}@${index.version})`)
230
+ report.detail(`Package manager: ${detectPackageManager(cwd, pkg)}`)
231
+ const foundations = index.items.filter((item) => item.type === "foundation").map((item) => item.name)
232
+ await installItems({
233
+ cwd,
234
+ pkg,
235
+ config,
236
+ registry,
237
+ index,
238
+ requested: foundations,
239
+ flags,
240
+ report,
241
+ io,
242
+ onCommit: () => created && report.ok(`${existing ? "Rewrote" : "Created"} ${CONFIG_FILE}`),
243
+ })
244
+ if (flags["dry-run"] && created) report.plan(`Would ${existing ? "rewrite" : "create"} ${CONFIG_FILE}`)
245
+ }
246
+
247
+ async function commandAdd({ cwd, flags, positionals, report, io }) {
248
+ if (!flags.all && !positionals.length) throw new CliError("Name at least one item, or pass --all.", { hint: "Run `atoms list` to see every item." })
249
+ if (flags.all && positionals.length) throw new CliError("Pass item names or --all, not both.")
250
+ const pkg = readPackageJson(cwd)
251
+ const config = readConfig(cwd)
252
+ const registry = createRegistry({ url: flags.registry ?? config.registry, alias: config.alias, srcDir: config.srcDir, fetch: io.fetch })
253
+ const index = await registry.index()
254
+ report.header(index.title ?? "Atoms")
255
+ report.detail(`Project: ${cwd} (${config.srcDir ? "src/" : "root"} layout, alias ${config.alias}/)`)
256
+ report.detail(`Registry: ${registry.base} (${index.name}@${index.version})`)
257
+ const requested = flags.all ? index.items.map((item) => item.name) : [...new Set(positionals)]
258
+ await installItems({ cwd, pkg, config, registry, index, requested, flags, report, io })
259
+ }
260
+
261
+ async function commandList({ cwd, flags, report, io }) {
262
+ const config = readConfig(cwd, { required: false })
263
+ const registry = createRegistry({
264
+ url: flags.registry ?? config?.registry ?? DEFAULT_REGISTRY,
265
+ alias: config?.alias ?? "@",
266
+ srcDir: config?.srcDir ?? true,
267
+ fetch: io.fetch,
268
+ })
269
+ const index = await registry.index()
270
+ report.header(`${index.title ?? "Atoms"} ${index.version} · ${plural(index.items.length, "item")}`)
271
+ const width = Math.max(...index.items.map((item) => item.name.length)) + 2
272
+ for (const type of [...new Set(index.items.map((item) => item.type))]) {
273
+ const items = index.items.filter((item) => item.type === type)
274
+ io.stdout.write(`\n${type} (${items.length})\n`)
275
+ for (const item of items) {
276
+ const mark = config?.installed?.[item.name] ? "✓" : " "
277
+ io.stdout.write(`${mark} ${item.name.padEnd(width)}${item.title}\n`)
278
+ if (flags.verbose) {
279
+ io.stdout.write(` ${item.description}\n`)
280
+ if (item.registryDependencies.length) io.stdout.write(` needs: ${item.registryDependencies.join(", ")}\n`)
281
+ }
282
+ }
283
+ }
284
+ }
285
+
286
+ export async function main(argv, overrides = {}) {
287
+ const io = {
288
+ stdout: process.stdout,
289
+ stderr: process.stderr,
290
+ fetch: globalThis.fetch,
291
+ runInstall,
292
+ color: Boolean(process.stdout.isTTY) && !process.env.NO_COLOR,
293
+ cwd: process.cwd(),
294
+ ...overrides,
295
+ }
296
+ let report = createReporter(io, false)
297
+ try {
298
+ const { values: flags, positionals } = parse(argv)
299
+ report = createReporter(io, Boolean(flags.verbose))
300
+ const [command, ...rest] = positionals
301
+ if (flags.version) {
302
+ io.stdout.write(`${VERSION}\n`)
303
+ return 0
304
+ }
305
+ if (flags.help || !command) {
306
+ io.stdout.write(`${HELP}\n`)
307
+ return command || flags.help ? 0 : 1
308
+ }
309
+ const cwd = path.resolve(io.cwd, flags.cwd ?? ".")
310
+ if (!fs.existsSync(cwd) || !fs.statSync(cwd).isDirectory()) throw new CliError(`${cwd} is not a folder.`)
311
+ if (flags.all && command !== "add") throw new CliError("--all only works with `atoms add`.")
312
+ if (command === "init") {
313
+ if (rest.length) throw new CliError(`\`atoms init\` takes no item names (got ${rest.join(", ")}).`, { hint: "Run `atoms add <item>` after init." })
314
+ await commandInit({ cwd, flags, report, io })
315
+ } else if (command === "add") {
316
+ await commandAdd({ cwd, flags, positionals: rest, report, io })
317
+ } else if (command === "list") {
318
+ await commandList({ cwd, flags, report, io })
319
+ } else {
320
+ throw new CliError(`Unknown command "${command}".`, { hint: "Run `atoms --help` for the commands." })
321
+ }
322
+ return 0
323
+ } catch (error) {
324
+ if (error instanceof CliError) {
325
+ report.error(error)
326
+ return 1
327
+ }
328
+ report.error(new CliError(`Unexpected error: ${error?.message ?? error}`, { details: error?.stack }))
329
+ return 1
330
+ }
331
+ }
@@ -0,0 +1,202 @@
1
+ // Reads the consumer project: package.json, the src/ layout, the TypeScript import alias, the
2
+ // global stylesheet and the package manager. Everything here only reads.
3
+
4
+ import fs from "node:fs"
5
+ import path from "node:path"
6
+
7
+ import { CliError } from "./errors.mjs"
8
+
9
+ const toPosix = (value) => value.split(path.sep).join("/")
10
+
11
+ /** JSON with comments and trailing commas, as tsconfig.json allows. */
12
+ export function parseJsonc(text) {
13
+ let out = ""
14
+ let inString = false
15
+ for (let i = 0; i < text.length; i++) {
16
+ const char = text[i]
17
+ const next = text[i + 1]
18
+ if (inString) {
19
+ out += char
20
+ if (char === "\\") out += text[++i] ?? ""
21
+ else if (char === '"') inString = false
22
+ } else if (char === '"') {
23
+ inString = true
24
+ out += char
25
+ } else if (char === "/" && next === "/") {
26
+ while (i < text.length && text[i] !== "\n") i++
27
+ out += "\n"
28
+ } else if (char === "/" && next === "*") {
29
+ i += 2
30
+ while (i < text.length && !(text[i] === "*" && text[i + 1] === "/")) i++
31
+ i++
32
+ } else {
33
+ out += char
34
+ }
35
+ }
36
+ return JSON.parse(out.replace(/,(\s*[}\]])/g, "$1"))
37
+ }
38
+
39
+ export function readPackageJson(cwd) {
40
+ const file = path.join(cwd, "package.json")
41
+ if (!fs.existsSync(file)) {
42
+ throw new CliError(`No package.json in ${cwd}.`, { hint: "Run this in your project's root folder, or pass --cwd <path>." })
43
+ }
44
+ try {
45
+ return JSON.parse(fs.readFileSync(file, "utf8"))
46
+ } catch (error) {
47
+ throw new CliError(`package.json in ${cwd} is not valid JSON: ${error.message}`)
48
+ }
49
+ }
50
+
51
+ /** compilerOptions from a tsconfig, following relative `extends` (child options win). */
52
+ function readCompilerOptions(file, seen = new Set()) {
53
+ if (seen.has(file) || !fs.existsSync(file)) return null
54
+ seen.add(file)
55
+ let config
56
+ try {
57
+ config = parseJsonc(fs.readFileSync(file, "utf8"))
58
+ } catch (error) {
59
+ throw new CliError(`${path.basename(file)} could not be read: ${error.message}`)
60
+ }
61
+ const dir = path.dirname(file)
62
+ let inherited = {}
63
+ for (const parent of [config.extends].flat().filter((entry) => typeof entry === "string" && entry.startsWith("."))) {
64
+ const parentFile = path.resolve(dir, parent.endsWith(".json") ? parent : `${parent}.json`)
65
+ const parentOptions = readCompilerOptions(parentFile, seen)
66
+ if (parentOptions) inherited = { ...inherited, ...parentOptions.options, __dir: parentOptions.dir }
67
+ }
68
+ const own = config.compilerOptions ?? {}
69
+ const options = { ...inherited, ...own }
70
+ // `paths` and `baseUrl` resolve from the file that declares them.
71
+ const pathsDir = own.paths || own.baseUrl ? dir : inherited.__dir ?? dir
72
+ delete options.__dir
73
+ return { options, dir: pathsDir, references: config.references ?? [] }
74
+ }
75
+
76
+ /** Every tsconfig/jsconfig that may hold the paths, root files first, then their references. */
77
+ function configCandidates(cwd) {
78
+ const files = ["tsconfig.json", "tsconfig.app.json", "jsconfig.json"].map((name) => path.join(cwd, name))
79
+ const root = path.join(cwd, "tsconfig.json")
80
+ if (fs.existsSync(root)) {
81
+ try {
82
+ for (const reference of parseJsonc(fs.readFileSync(root, "utf8")).references ?? []) {
83
+ if (typeof reference?.path !== "string") continue
84
+ const target = path.resolve(cwd, reference.path)
85
+ files.push(target.endsWith(".json") ? target : path.join(target, "tsconfig.json"))
86
+ }
87
+ } catch {
88
+ // Reported when the file itself is read below.
89
+ }
90
+ }
91
+ return [...new Set(files)].filter((file) => fs.existsSync(file))
92
+ }
93
+
94
+ /** Whether the project keeps its code in src/. */
95
+ function looksLikeSrcLayout(cwd) {
96
+ const src = path.join(cwd, "src")
97
+ if (!fs.existsSync(src)) return false
98
+ return ["app", "pages", "components", "routes", "main.tsx", "main.ts", "main.jsx", "index.tsx", "index.ts", "App.tsx"].some((entry) =>
99
+ fs.existsSync(path.join(src, entry)),
100
+ )
101
+ }
102
+
103
+ /**
104
+ * The import alias that points at the project's source root (`@` for `"@/*": ["./src/*"]`), and
105
+ * whether that root is src/. The alias decides the layout when both an src/ and a root mapping exist.
106
+ */
107
+ export function detectAlias(cwd) {
108
+ const preferSrc = looksLikeSrcLayout(cwd)
109
+ const mappings = []
110
+ for (const file of configCandidates(cwd)) {
111
+ const result = readCompilerOptions(file)
112
+ const paths = result?.options.paths
113
+ if (!paths) continue
114
+ const base = path.resolve(result.dir, result.options.baseUrl ?? ".")
115
+ for (const [key, targets] of Object.entries(paths)) {
116
+ if (!key.endsWith("/*") || !Array.isArray(targets)) continue
117
+ for (const target of targets) {
118
+ if (typeof target !== "string" || !target.endsWith("/*")) continue
119
+ const resolved = path.resolve(base, target.slice(0, -2))
120
+ const srcDir = resolved === path.join(cwd, "src") ? true : resolved === cwd ? false : null
121
+ if (srcDir !== null) mappings.push({ alias: key.slice(0, -2), srcDir, file: toPosix(path.relative(cwd, file)) })
122
+ }
123
+ }
124
+ }
125
+ if (!mappings.length) {
126
+ const example = preferSrc ? `"@/*": ["./src/*"]` : `"@/*": ["./*"]`
127
+ throw new CliError("No TypeScript import alias points at your source root.", {
128
+ hint: `Add ${example} to compilerOptions.paths in tsconfig.json (or jsconfig.json), then run this again.`,
129
+ })
130
+ }
131
+ return mappings.find((mapping) => mapping.srcDir === preferSrc) ?? mappings[0]
132
+ }
133
+
134
+ const STYLESHEET_CANDIDATES = [
135
+ "app/globals.css",
136
+ "styles/globals.css",
137
+ "globals.css",
138
+ "index.css",
139
+ "styles/index.css",
140
+ "app.css",
141
+ "app/app.css",
142
+ "styles.css",
143
+ "main.css",
144
+ "styles/main.css",
145
+ ]
146
+ const TAILWIND_IMPORT = /@import\s+(?:url\()?["']tailwindcss["']/
147
+ const SKIP_DIRS = new Set(["node_modules", ".next", ".git", "dist", "build", "out", ".turbo", ".vercel", "coverage"])
148
+
149
+ function findCssFiles(dir, depth, found = []) {
150
+ if (depth < 0 || !fs.existsSync(dir)) return found
151
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
152
+ if (entry.isDirectory()) {
153
+ if (!SKIP_DIRS.has(entry.name) && !entry.name.startsWith(".")) findCssFiles(path.join(dir, entry.name), depth - 1, found)
154
+ } else if (entry.name.endsWith(".css")) {
155
+ found.push(path.join(dir, entry.name))
156
+ }
157
+ }
158
+ return found
159
+ }
160
+
161
+ /**
162
+ * The app's global stylesheet: the one that imports Tailwind, looked for in the usual places first
163
+ * and then anywhere in the source root. `exclude` is the foundation's own target.
164
+ */
165
+ export function detectStylesheet(cwd, srcDir, exclude = []) {
166
+ const root = srcDir ? path.join(cwd, "src") : cwd
167
+ const skip = new Set(exclude.map((file) => path.resolve(cwd, file)))
168
+ const known = STYLESHEET_CANDIDATES.map((file) => path.join(root, file)).filter((file) => fs.existsSync(file) && !skip.has(file))
169
+ const imports = (file) => TAILWIND_IMPORT.test(fs.readFileSync(file, "utf8"))
170
+ const pick =
171
+ known.find(imports) ??
172
+ findCssFiles(root, 4).filter((file) => !skip.has(file)).sort().find(imports) ??
173
+ known[0]
174
+ if (!pick) {
175
+ throw new CliError(`No global stylesheet found in ${srcDir ? "src/" : "the project root"}.`, {
176
+ hint: 'Create one that starts with `@import "tailwindcss";` and import it from your app, then run this again.',
177
+ })
178
+ }
179
+ return { path: toPosix(path.relative(cwd, pick)), importsTailwind: imports(pick) }
180
+ }
181
+
182
+ /** npm, pnpm, yarn or bun, from `packageManager` or the lockfile. */
183
+ export function detectPackageManager(cwd, pkg) {
184
+ const declared = typeof pkg.packageManager === "string" ? pkg.packageManager.split("@")[0] : null
185
+ if (["npm", "pnpm", "yarn", "bun"].includes(declared)) return declared
186
+ if (fs.existsSync(path.join(cwd, "pnpm-lock.yaml"))) return "pnpm"
187
+ if (fs.existsSync(path.join(cwd, "yarn.lock"))) return "yarn"
188
+ if (fs.existsSync(path.join(cwd, "bun.lockb")) || fs.existsSync(path.join(cwd, "bun.lock"))) return "bun"
189
+ return "npm"
190
+ }
191
+
192
+ export function installCommand(packageManager, specs) {
193
+ const verb = packageManager === "npm" ? "install" : "add"
194
+ return { command: packageManager, args: [verb, ...specs] }
195
+ }
196
+
197
+ /** Package names the project already declares, in any dependency field. */
198
+ export function declaredPackages(pkg) {
199
+ return new Set(
200
+ ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"].flatMap((field) => Object.keys(pkg[field] ?? {})),
201
+ )
202
+ }
@@ -0,0 +1,173 @@
1
+ // Talks to an Atoms registry: fetches the index and items for this project's layout, checks every
2
+ // hash, and orders the items so each one's registry dependencies come before it.
3
+
4
+ import { createHash } from "node:crypto"
5
+ import path from "node:path"
6
+
7
+ import { CliError } from "./errors.mjs"
8
+
9
+ export const DEFAULT_REGISTRY = "https://atomsdesignsystem.vercel.app/r"
10
+ const TIMEOUT_MS = 30_000
11
+ const CONCURRENCY = 8
12
+
13
+ export function integrityOf(content) {
14
+ return `sha256-${createHash("sha256").update(content, "utf8").digest("base64")}`
15
+ }
16
+
17
+ /** Same as the registry's: each target and its content hash, one per line, hashed together. */
18
+ export function itemIntegrity(files) {
19
+ return integrityOf(files.map((file) => `${file.target}\n${file.integrity}`).join("\n"))
20
+ }
21
+
22
+ export function normaliseRegistryUrl(url) {
23
+ let parsed
24
+ try {
25
+ parsed = new URL(url)
26
+ } catch {
27
+ throw new CliError(`"${url}" is not a registry URL.`, { hint: "Pass the registry's base, such as https://example.com/r." })
28
+ }
29
+ if (!["http:", "https:"].includes(parsed.protocol)) throw new CliError(`The registry must be http or https, not ${parsed.protocol}`)
30
+ return parsed.href.replace(/\/+$/, "")
31
+ }
32
+
33
+ function networkReason(error) {
34
+ const cause = error?.cause
35
+ if (error?.name === "TimeoutError" || error?.name === "AbortError") return `no answer within ${TIMEOUT_MS / 1000}s`
36
+ return cause?.code ?? cause?.message ?? error?.message ?? "unknown error"
37
+ }
38
+
39
+ /** A path inside the project, written with forward slashes, with no `..` and no drive or root. */
40
+ function assertSafeTarget(item, target) {
41
+ const bad =
42
+ typeof target !== "string" ||
43
+ !target ||
44
+ target.includes("\\") ||
45
+ target.includes("\0") ||
46
+ path.posix.isAbsolute(target) ||
47
+ /^[A-Za-z]:/.test(target) ||
48
+ target.split("/").some((segment) => segment === ".." || segment === "")
49
+ if (bad) throw new CliError(`The registry item "${item}" has an unsafe file path: ${JSON.stringify(target)}. Nothing was installed.`)
50
+ }
51
+
52
+ export function createRegistry({ url, alias, srcDir, fetch = globalThis.fetch }) {
53
+ const base = normaliseRegistryUrl(url)
54
+ const query = `?${new URLSearchParams({ alias, srcDir: String(srcDir) })}`
55
+
56
+ async function getJson(resource, { notFound } = {}) {
57
+ const href = `${base}/${resource}${query}`
58
+ let response
59
+ try {
60
+ response = await fetch(href, { signal: AbortSignal.timeout(TIMEOUT_MS), headers: { accept: "application/json" } })
61
+ } catch (error) {
62
+ throw new CliError(`Could not reach the registry at ${base} (${networkReason(error)}).`, {
63
+ hint: "Check your connection and the URL, or pass another with --registry <url>.",
64
+ })
65
+ }
66
+ if (response.status === 404 && notFound) throw notFound()
67
+ if (!response.ok) {
68
+ let detail = ""
69
+ try {
70
+ detail = (await response.json())?.error ?? ""
71
+ } catch {
72
+ // Not JSON; the status says enough.
73
+ }
74
+ throw new CliError(`The registry answered ${response.status} for ${resource}${detail ? `: ${detail}` : "."}`)
75
+ }
76
+ try {
77
+ return await response.json()
78
+ } catch {
79
+ throw new CliError(`The registry's answer for ${resource} is not valid JSON.`)
80
+ }
81
+ }
82
+
83
+ async function index() {
84
+ const data = await getJson("index.json", {
85
+ notFound: () => new CliError(`No registry index at ${base}/index.json.`, { hint: "Check the URL; it should end at the registry's base, such as …/r." }),
86
+ })
87
+ if (!data || typeof data.version !== "string" || !Array.isArray(data.items)) {
88
+ throw new CliError(`${base}/index.json is not an Atoms registry index.`)
89
+ }
90
+ if (data.options && (data.options.alias !== alias || data.options.srcDir !== srcDir)) {
91
+ throw new CliError(`The registry ignored this project's layout (alias ${alias}, ${srcDir ? "src/" : "no src/"}).`, {
92
+ hint: "It may be an older registry; update it or pass another with --registry.",
93
+ })
94
+ }
95
+ return data
96
+ }
97
+
98
+ /** Fetches one item and checks it against its own hashes and the index's. */
99
+ async function item(name, indexData) {
100
+ const data = await getJson(`${name}.json`, {
101
+ notFound: () => new CliError(`The registry lists "${name}" but has no ${name}.json.`),
102
+ })
103
+ const entry = indexData.items.find((candidate) => candidate.name === name)
104
+ const fail = (reason) =>
105
+ new CliError(`Integrity check failed for "${name}": ${reason}. Nothing was installed.`, {
106
+ hint: "The download doesn't match what the registry published. Try again; if it keeps failing, the registry or a proxy is serving altered files.",
107
+ })
108
+ if (data?.name !== name || !Array.isArray(data.files) || !data.files.length) throw fail("the response is not that item")
109
+ if (data.version !== indexData.version) throw fail(`it is version ${data.version}, the registry is ${indexData.version}`)
110
+ if (data.options && (data.options.alias !== alias || data.options.srcDir !== srcDir)) throw fail("it was rendered for another project layout")
111
+ for (const file of data.files) {
112
+ assertSafeTarget(name, file.target)
113
+ if (typeof file.content !== "string" || file.integrity !== integrityOf(file.content)) throw fail(`${file.target} does not match its hash`)
114
+ }
115
+ if (data.integrity !== itemIntegrity(data.files)) throw fail("its files do not match the item's hash")
116
+ if (entry?.integrity && entry.integrity !== data.integrity) throw fail("it does not match the hash in the registry index")
117
+ return data
118
+ }
119
+
120
+ /**
121
+ * The requested items and everything they need, dependencies first. Unknown names and
122
+ * dependencies the registry doesn't have are errors, reported before anything is fetched or written.
123
+ */
124
+ async function resolve(requested, indexData) {
125
+ const known = new Set(indexData.items.map((entry) => entry.name))
126
+ const unknown = requested.filter((name) => !known.has(name))
127
+ if (unknown.length) {
128
+ const suggestions = unknown.flatMap((name) => [...known].filter((candidate) => candidate.includes(name) || name.includes(candidate)).slice(0, 3))
129
+ throw new CliError(`Not in the registry: ${unknown.join(", ")}.`, {
130
+ hint: suggestions.length ? `Did you mean ${[...new Set(suggestions)].join(", ")}? Run \`atoms list\` to see every item.` : "Run `atoms list` to see every item.",
131
+ })
132
+ }
133
+ const fetched = new Map()
134
+ const fetchAll = async (names) => {
135
+ const queue = names.filter((name) => !fetched.has(name))
136
+ for (const name of queue) fetched.set(name, null)
137
+ const workers = Array.from({ length: Math.min(CONCURRENCY, queue.length) }, async () => {
138
+ while (queue.length) {
139
+ const name = queue.shift()
140
+ fetched.set(name, await item(name, indexData))
141
+ }
142
+ })
143
+ await Promise.all(workers)
144
+ }
145
+ await fetchAll(requested)
146
+ const order = []
147
+ const placed = new Set()
148
+ const needed = []
149
+ for (const name of requested) {
150
+ const closure = fetched.get(name).registryClosure ?? []
151
+ for (const dependency of closure) {
152
+ if (!known.has(dependency)) {
153
+ throw new CliError(`"${name}" needs "${dependency}", which the registry doesn't have.`, {
154
+ hint: "The registry is incomplete; report it to whoever publishes it.",
155
+ })
156
+ }
157
+ }
158
+ needed.push(...closure)
159
+ }
160
+ await fetchAll(needed)
161
+ for (const name of requested) {
162
+ for (const member of [...(fetched.get(name).registryClosure ?? []), name]) {
163
+ if (!placed.has(member)) {
164
+ placed.add(member)
165
+ order.push(fetched.get(member))
166
+ }
167
+ }
168
+ }
169
+ return order
170
+ }
171
+
172
+ return { base, index, item, resolve }
173
+ }