sparkwire 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.
@@ -0,0 +1,253 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * sparkwire: copy Spark UI components into your project as source you own.
4
+ *
5
+ * npx sparkwire init create sparkwire.json
6
+ * npx sparkwire add switch menu add components (and what they need)
7
+ * npx sparkwire list show available components
8
+ *
9
+ * Options: --dir <path> --registry <url-or-folder> --overwrite --dry-run
10
+ * --no-install --cwd <path> --yes
11
+ */
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import { spawnSync } from 'node:child_process';
15
+
16
+ const DEFAULT_REGISTRY = 'https://raw.githubusercontent.com/phoenix-am/spark-ui/master/registry/r/{name}.json';
17
+ const TARGET_PREFIX = 'components/spark-ui';
18
+ const CONFIG = 'sparkwire.json';
19
+
20
+ const c = {
21
+ bold: (s) => `\x1b[1m${s}\x1b[22m`,
22
+ dim: (s) => `\x1b[2m${s}\x1b[22m`,
23
+ yellow: (s) => `\x1b[33m${s}\x1b[39m`,
24
+ green: (s) => `\x1b[32m${s}\x1b[39m`,
25
+ red: (s) => `\x1b[31m${s}\x1b[39m`,
26
+ };
27
+ const fail = (msg) => {
28
+ console.error(`${c.red('✖')} ${msg}`);
29
+ process.exit(1);
30
+ };
31
+
32
+ /* ---------------------------------------------------------------- args */
33
+
34
+ function parseArgs(argv) {
35
+ const args = { _: [], install: true };
36
+ for (let i = 0; i < argv.length; i++) {
37
+ const a = argv[i];
38
+ if (a === '--no-install') args.install = false;
39
+ else if (a === '--overwrite' || a === '-o') args.overwrite = true;
40
+ else if (a === '--dry-run') args.dryRun = true;
41
+ else if (a === '--yes' || a === '-y') args.yes = true;
42
+ else if (a === '--help' || a === '-h') args.help = true;
43
+ else if (a === '--version' || a === '-v') args.version = true;
44
+ else if (['--dir', '--registry', '--cwd'].includes(a)) args[a.slice(2)] = argv[++i];
45
+ else if (a.startsWith('--') && a.includes('=')) {
46
+ const [k, v] = a.slice(2).split('=');
47
+ args[k] = v;
48
+ } else args._.push(a);
49
+ }
50
+ return args;
51
+ }
52
+
53
+ /* -------------------------------------------------------------- config */
54
+
55
+ function readConfig(cwd) {
56
+ const file = path.join(cwd, CONFIG);
57
+ return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : null;
58
+ }
59
+
60
+ function defaultDir(cwd) {
61
+ return fs.existsSync(path.join(cwd, 'src')) ? 'src/components/spark-ui' : 'components/spark-ui';
62
+ }
63
+
64
+ function settings(args) {
65
+ const cwd = path.resolve(args.cwd ?? process.cwd());
66
+ const config = readConfig(cwd) ?? {};
67
+ return {
68
+ cwd,
69
+ dir: args.dir ?? config.dir ?? defaultDir(cwd),
70
+ registry: args.registry ?? process.env.SPARKWIRE_REGISTRY ?? config.registry ?? DEFAULT_REGISTRY,
71
+ };
72
+ }
73
+
74
+ /* ------------------------------------------------------------ registry */
75
+
76
+ /** A registry is a URL template with {name}, or a local folder holding r/<name>.json. */
77
+ function itemLocation(registry, name) {
78
+ if (/^https?:\/\//.test(registry)) return registry.includes('{name}') ? registry.replace('{name}', name) : `${registry.replace(/\/$/, '')}/r/${name}.json`;
79
+ const base = path.resolve(registry);
80
+ const inR = path.join(base, 'r', `${name}.json`);
81
+ return fs.existsSync(inR) ? inR : path.join(base, `${name}.json`);
82
+ }
83
+
84
+ function indexLocation(registry) {
85
+ if (/^https?:\/\//.test(registry)) return registry.includes('{name}') ? registry.replace(/r\/\{name\}\.json$/, 'registry.json').replace('{name}.json', 'registry.json') : `${registry.replace(/\/$/, '')}/registry.json`;
86
+ return path.join(path.resolve(registry), 'registry.json');
87
+ }
88
+
89
+ async function load(location) {
90
+ if (/^https?:\/\//.test(location)) {
91
+ const res = await fetch(location);
92
+ if (!res.ok) throw new Error(`${res.status} ${res.statusText} for ${location}`);
93
+ return res.json();
94
+ }
95
+ if (!fs.existsSync(location)) throw new Error(`not found: ${location}`);
96
+ return JSON.parse(fs.readFileSync(location, 'utf8'));
97
+ }
98
+
99
+ const bare = (dep) => dep.replace(/^@sparkwire\//, '');
100
+
101
+ /** Load items and everything they depend on, dependencies first. */
102
+ async function resolve(names, registry) {
103
+ const seen = new Map();
104
+ const order = [];
105
+ async function visit(name, from) {
106
+ if (seen.has(name)) return;
107
+ seen.set(name, null);
108
+ let item;
109
+ try {
110
+ item = await load(itemLocation(registry, name));
111
+ } catch (e) {
112
+ fail(`Unknown component "${name}"${from ? ` (needed by ${from})` : ''}: ${e.message}\n Run ${c.bold('npx sparkwire list')} to see what's available.`);
113
+ }
114
+ for (const dep of item.registryDependencies ?? []) await visit(bare(dep), name);
115
+ seen.set(name, item);
116
+ order.push(item);
117
+ }
118
+ for (const n of names) await visit(n);
119
+ return order;
120
+ }
121
+
122
+ /* ------------------------------------------------------------- install */
123
+
124
+ function packageManager(cwd) {
125
+ const has = (f) => fs.existsSync(path.join(cwd, f));
126
+ if (has('pnpm-lock.yaml')) return 'pnpm';
127
+ if (has('yarn.lock')) return 'yarn';
128
+ if (has('bun.lockb') || has('bun.lock')) return 'bun';
129
+ return 'npm';
130
+ }
131
+
132
+ function missingDeps(cwd, deps) {
133
+ let pkg = {};
134
+ try {
135
+ pkg = JSON.parse(fs.readFileSync(path.join(cwd, 'package.json'), 'utf8'));
136
+ } catch {
137
+ /* no package.json: install everything */
138
+ }
139
+ const have = { ...pkg.dependencies, ...pkg.devDependencies, ...pkg.peerDependencies };
140
+ return deps.filter((d) => {
141
+ const name = d.startsWith('@') ? '@' + d.slice(1).split('@')[0] : d.split('@')[0];
142
+ return !have[name];
143
+ });
144
+ }
145
+
146
+ function install(cwd, deps) {
147
+ const pm = packageManager(cwd);
148
+ const cmd = pm === 'npm' ? ['install', ...deps] : ['add', ...deps];
149
+ console.log(`${c.dim('$')} ${pm} ${cmd.join(' ')}`);
150
+ const r = spawnSync(pm, cmd, { cwd, stdio: 'inherit', shell: process.platform === 'win32' });
151
+ if (r.status !== 0) fail(`${pm} failed. Install these yourself: ${deps.join(' ')}`);
152
+ }
153
+
154
+ /* ------------------------------------------------------------ commands */
155
+
156
+ async function add(args) {
157
+ const names = args._.slice(1).map((n) => n.replace(/^@sparkwire\//, '').toLowerCase());
158
+ if (!names.length) fail(`Name at least one component, e.g. ${c.bold('npx sparkwire add switch')}`);
159
+ const { cwd, dir, registry } = settings(args);
160
+ const items = await resolve(names, registry);
161
+
162
+ const written = [];
163
+ const skipped = [];
164
+ for (const item of items) {
165
+ for (const file of item.files ?? []) {
166
+ const rel = (file.target ?? file.path).replace(new RegExp(`^${TARGET_PREFIX}`), dir);
167
+ const dest = path.join(cwd, rel);
168
+ if (fs.existsSync(dest) && !args.overwrite) {
169
+ if (fs.readFileSync(dest, 'utf8') !== file.content) skipped.push(rel);
170
+ continue;
171
+ }
172
+ if (!args.dryRun) {
173
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
174
+ fs.writeFileSync(dest, file.content);
175
+ }
176
+ written.push(rel);
177
+ }
178
+ }
179
+
180
+ const deps = [...new Set(items.flatMap((i) => i.dependencies ?? []))];
181
+ const toInstall = missingDeps(cwd, deps);
182
+
183
+ console.log(`\n${c.yellow('⚡')} ${c.bold(args.dryRun ? 'Would add' : 'Added')} ${items.map((i) => i.name).join(', ')}`);
184
+ for (const f of written) console.log(` ${c.green('+')} ${f}`);
185
+ if (skipped.length) {
186
+ console.log(`\n${c.bold('Kept your changes')} in ${skipped.length} file(s) (use --overwrite to replace):`);
187
+ for (const f of skipped) console.log(` ${c.dim('=')} ${f}`);
188
+ }
189
+ if (toInstall.length) {
190
+ if (args.dryRun || !args.install) console.log(`\n${c.bold('Install:')} ${toInstall.join(' ')}`);
191
+ else install(cwd, toInstall);
192
+ }
193
+
194
+ const cssPath = `${dir}/styles.css`;
195
+ if (written.includes(cssPath) || items.some((i) => i.name === 'styles')) {
196
+ console.log(`\n${c.bold('One-time setup:')} import the styles once, e.g. in your root layout:`);
197
+ console.log(` import '${path.relative(cwd, path.join(cwd, cssPath)).startsWith('src/') ? '@/' + cssPath.replace(/^src\//, '') : './' + cssPath}';`);
198
+ }
199
+ const first = items.find((i) => names.includes(i.name));
200
+ // Folder of the item's first file, relative to the install dir (e.g. Button, blocks/Dashboard).
201
+ const folder = first?.files?.[0]?.target?.split('/').slice(2, -1).join('/');
202
+ if (folder) console.log(`\n${c.bold('Use it:')} import { ... } from '${dir.replace(/^src\//, '@/')}/${folder}';\n`);
203
+ }
204
+
205
+ async function list(args) {
206
+ const { registry } = settings(args);
207
+ let index;
208
+ try {
209
+ index = await load(indexLocation(registry));
210
+ } catch (e) {
211
+ fail(`Could not read the registry index: ${e.message}`);
212
+ }
213
+ const internal = new Set(['utils', 'styles']);
214
+ const width = Math.max(...index.items.map((i) => i.name.length));
215
+ console.log(`\n${c.yellow('⚡')} ${c.bold('Spark UI components')} ${c.dim(`(${registry.includes('{name}') ? new URL(registry).host : registry})`)}\n`);
216
+ for (const i of index.items.filter((x) => !internal.has(x.name))) console.log(` ${i.name.padEnd(width)} ${c.dim(i.description)}`);
217
+ console.log(`\nAdd one: ${c.bold('npx sparkwire add <name>')}\n`);
218
+ }
219
+
220
+ function init(args) {
221
+ const { cwd, dir, registry } = settings(args);
222
+ const file = path.join(cwd, CONFIG);
223
+ if (fs.existsSync(file) && !args.overwrite) fail(`${CONFIG} already exists (use --overwrite to replace it).`);
224
+ const config = { $schema: 'https://raw.githubusercontent.com/phoenix-am/spark-ui/master/registry/sparkwire.schema.json', dir };
225
+ if (registry !== DEFAULT_REGISTRY) config.registry = registry;
226
+ if (!args.dryRun) fs.writeFileSync(file, JSON.stringify(config, null, 2) + '\n');
227
+ console.log(`${c.green('✔')} ${args.dryRun ? 'Would write' : 'Wrote'} ${CONFIG}: components go to ${c.bold(dir)}`);
228
+ }
229
+
230
+ const HELP = `
231
+ ${c.yellow('⚡')} ${c.bold('sparkwire')}: add Spark UI components to your project as source you own.
232
+
233
+ ${c.bold('npx sparkwire init')} create sparkwire.json (where components go)
234
+ ${c.bold('npx sparkwire add')} <names...> copy components and what they need
235
+ ${c.bold('npx sparkwire list')} show available components
236
+
237
+ Options
238
+ --dir <path> folder for components (default: src/components/spark-ui or components/spark-ui)
239
+ --registry <url> registry URL template with {name}, or a local folder
240
+ --overwrite, -o replace files you have changed
241
+ --dry-run show what would happen, change nothing
242
+ --no-install don't install npm dependencies
243
+ --cwd <path> run in another folder
244
+ `;
245
+
246
+ const args = parseArgs(process.argv.slice(2));
247
+ const cmd = args._[0];
248
+ if (args.version) console.log('0.1.0');
249
+ else if (args.help || !cmd) console.log(HELP);
250
+ else if (cmd === 'add') await add(args);
251
+ else if (cmd === 'list' || cmd === 'ls') await list(args);
252
+ else if (cmd === 'init') init(args);
253
+ else fail(`Unknown command "${cmd}". Run npx sparkwire --help.`);
package/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
2
  "name": "sparkwire",
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": "Add Spark UI (Live Wire) components to your project as source you own: npx sparkwire add switch",
5
+ "type": "module",
6
+ "bin": {
7
+ "sparkwire": "./bin/sparkwire.mjs"
8
+ },
9
+ "files": [
10
+ "bin"
11
+ ],
12
+ "engines": {
13
+ "node": ">=18"
14
+ },
15
+ "keywords": [
16
+ "react",
17
+ "components",
18
+ "ui",
19
+ "spark-ui",
20
+ "sparkwire",
21
+ "cli",
22
+ "registry"
23
+ ],
24
+ "license": "MIT",
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/phoenix-am/spark-ui.git",
28
+ "directory": "packages/cli"
29
+ },
30
+ "homepage": "https://github.com/phoenix-am/spark-ui#readme",
31
+ "publishConfig": {
32
+ "provenance": true
33
+ }
34
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.