juas.dev 1.0.0 → 1.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,164 @@
1
+ // ============================================================
2
+ // credentials.js — Secure local credential storage (~/.juas)
3
+ // ============================================================
4
+ import fs from "fs";
5
+ import fsp from "fs/promises";
6
+ import os from "os";
7
+ import path from "path";
8
+
9
+ export const DEFAULT_CLI_BASE_URL = "https://juas.dev";
10
+
11
+ /**
12
+ * Resolves the directory where CLI credentials are persisted.
13
+ * Supports JUAS_HOME override for isolated environments and automated tests.
14
+ */
15
+ export function getCredentialsDir() {
16
+ const override = process.env.JUAS_HOME?.trim();
17
+ if (override) {
18
+ return path.resolve(override);
19
+ }
20
+ return path.join(os.homedir(), ".juas");
21
+ }
22
+
23
+ export function getCredentialsPath() {
24
+ return path.join(getCredentialsDir(), "credentials.json");
25
+ }
26
+
27
+ /**
28
+ * Validates and normalizes the Juas.dev base URL.
29
+ * Rejects unencrypted remote HTTP URLs to prevent credential leakage over plaintext networks.
30
+ */
31
+ export function validateCliBaseUrl(rawUrl) {
32
+ const candidate = (rawUrl || DEFAULT_CLI_BASE_URL).trim().replace(/\/+$/, "");
33
+ let parsed;
34
+ try {
35
+ parsed = new URL(candidate);
36
+ } catch {
37
+ throw new Error(`Invalid Juas CLI URL: "${candidate}"`);
38
+ }
39
+
40
+ const isLocalhost =
41
+ parsed.hostname === "127.0.0.1" || parsed.hostname === "localhost" || parsed.hostname === "::1";
42
+
43
+ if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && isLocalhost)) {
44
+ throw new Error(
45
+ `Insecure CLI endpoint "${candidate}". Use HTTPS or a local loopback URL.`
46
+ );
47
+ }
48
+
49
+ return parsed.origin;
50
+ }
51
+
52
+ export function getCliBaseUrl(explicitUrl) {
53
+ return validateCliBaseUrl(explicitUrl || process.env.JUAS_CLI_URL || DEFAULT_CLI_BASE_URL);
54
+ }
55
+
56
+ /**
57
+ * Reads saved CLI credentials from disk, returning null if absent or malformed.
58
+ */
59
+ export function readCredentials() {
60
+ const credPath = getCredentialsPath();
61
+ try {
62
+ if (!fs.existsSync(credPath)) return null;
63
+ const raw = JSON.parse(fs.readFileSync(credPath, "utf-8"));
64
+ if (!raw || typeof raw !== "object" || typeof raw.token !== "string" || !raw.token.trim()) {
65
+ return null;
66
+ }
67
+ return {
68
+ ...raw,
69
+ token: raw.token.trim(),
70
+ };
71
+ } catch {
72
+ return null;
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Persists CLI credentials with restrictive permissions (0700 dir / 0600 file on POSIX).
78
+ */
79
+ export async function writeCredentials(payload) {
80
+ if (!payload || typeof payload.token !== "string" || !payload.token.trim()) {
81
+ throw new Error("Cannot persist empty CLI credentials.");
82
+ }
83
+
84
+ const dir = getCredentialsDir();
85
+ const credPath = getCredentialsPath();
86
+
87
+ await fsp.mkdir(dir, { recursive: true, mode: 0o700 });
88
+ if (process.platform !== "win32") {
89
+ await fsp.chmod(dir, 0o700).catch(() => undefined);
90
+ }
91
+
92
+ const record = {
93
+ token: payload.token.trim(),
94
+ baseUrl: payload.baseUrl || DEFAULT_CLI_BASE_URL,
95
+ user: payload.user || null,
96
+ subscription: payload.subscription || null,
97
+ savedAt: payload.savedAt || new Date().toISOString(),
98
+ };
99
+
100
+ await fsp.writeFile(credPath, JSON.stringify(record, null, 2) + "\n", {
101
+ encoding: "utf-8",
102
+ mode: 0o600,
103
+ });
104
+ if (process.platform !== "win32") {
105
+ await fsp.chmod(credPath, 0o600).catch(() => undefined);
106
+ }
107
+
108
+ return credPath;
109
+ }
110
+
111
+ /**
112
+ * Removes saved local credentials if present. Returns true if a file was deleted.
113
+ */
114
+ export async function clearCredentials() {
115
+ const credPath = getCredentialsPath();
116
+ try {
117
+ await fsp.unlink(credPath);
118
+ return true;
119
+ } catch (err) {
120
+ if (err && typeof err === "object" && err.code === "ENOENT") {
121
+ return false;
122
+ }
123
+ throw err;
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Resolves the active CLI bearer token following standard precedence:
129
+ * 1. Explicit `--token` flag
130
+ * 2. `JUAS_API_TOKEN` environment variable
131
+ * 3. `~/.juas/credentials.json`
132
+ */
133
+ export function getActiveToken(explicitToken) {
134
+ const flagToken = typeof explicitToken === "string" ? explicitToken.trim() : "";
135
+ if (flagToken) {
136
+ return { token: flagToken, source: "flag", baseUrl: getCliBaseUrl() };
137
+ }
138
+
139
+ const envToken = process.env.JUAS_API_TOKEN?.trim() || "";
140
+ if (envToken) {
141
+ return { token: envToken, source: "env", baseUrl: getCliBaseUrl() };
142
+ }
143
+
144
+ const saved = readCredentials();
145
+ if (saved?.token) {
146
+ return {
147
+ token: saved.token,
148
+ source: "file",
149
+ baseUrl: saved.baseUrl ? validateCliBaseUrl(saved.baseUrl) : getCliBaseUrl(),
150
+ saved,
151
+ };
152
+ }
153
+
154
+ return { token: null, source: null, baseUrl: getCliBaseUrl() };
155
+ }
156
+
157
+ /**
158
+ * Returns a redacted preview of a CLI key suitable for terminal output.
159
+ */
160
+ export function maskToken(token) {
161
+ if (!token || typeof token !== "string") return "(none)";
162
+ if (token.length <= 16) return "••••••••";
163
+ return `${token.slice(0, 12)}••••••••${token.slice(-4)}`;
164
+ }
@@ -0,0 +1,55 @@
1
+ // ============================================================
2
+ // deps.js — detect the user's package manager & install deps
3
+ // ============================================================
4
+ import { execSync, spawnSync } from "child_process";
5
+ import fs from "fs-extra";
6
+ import path from "path";
7
+
8
+ /** Detect which package manager is in use. */
9
+ export function detectPackageManager(cwd = process.cwd()) {
10
+ if (fs.existsSync(path.join(cwd, "pnpm-lock.yaml"))) return "pnpm";
11
+ if (fs.existsSync(path.join(cwd, "yarn.lock"))) return "yarn";
12
+ if (fs.existsSync(path.join(cwd, "bun.lockb"))) return "bun";
13
+ return "npm";
14
+ }
15
+
16
+ /**
17
+ * Install an array of npm packages using the detected package manager.
18
+ * @param {string[]} packages - e.g. ["framer-motion", "clsx"]
19
+ * @param {string} cwd - project root
20
+ */
21
+ export function installDependencies(packages, cwd = process.cwd()) {
22
+ if (!packages.length) return;
23
+ const pm = detectPackageManager(cwd);
24
+
25
+ const installCmd = {
26
+ npm: `npm install ${packages.join(" ")}`,
27
+ pnpm: `pnpm add ${packages.join(" ")}`,
28
+ yarn: `yarn add ${packages.join(" ")}`,
29
+ bun: `bun add ${packages.join(" ")}`,
30
+ }[pm];
31
+
32
+ execSync(installCmd, { cwd, stdio: "inherit" });
33
+ }
34
+
35
+ /**
36
+ * Check whether the user already has a package installed.
37
+ */
38
+ export function isPackageInstalled(pkg, cwd = process.cwd()) {
39
+ const pkgJsonPath = path.join(cwd, "package.json");
40
+ if (!fs.existsSync(pkgJsonPath)) return false;
41
+ const pkgJson = fs.readJsonSync(pkgJsonPath);
42
+ const allDeps = {
43
+ ...(pkgJson.dependencies ?? {}),
44
+ ...(pkgJson.devDependencies ?? {}),
45
+ ...(pkgJson.peerDependencies ?? {}),
46
+ };
47
+ return pkg in allDeps;
48
+ }
49
+
50
+ /**
51
+ * Filter out already-installed packages.
52
+ */
53
+ export function getMissingPackages(packages, cwd = process.cwd()) {
54
+ return packages.filter((p) => !isPackageInstalled(p, cwd));
55
+ }
@@ -0,0 +1,22 @@
1
+ // ============================================================
2
+ // logger.js — colourful terminal output helpers
3
+ // ============================================================
4
+ import pc from "picocolors";
5
+
6
+ export const logger = {
7
+ info: (...args) => console.log(pc.cyan(" ●"), ...args),
8
+ success: (...args) => console.log(pc.green(" ✔"), ...args),
9
+ warn: (...args) => console.log(pc.yellow(" ⚠"), ...args),
10
+ error: (...args) => console.error(pc.red(" ✖"), ...args),
11
+ label: (label, value) => console.log(` ${pc.bold(label + ":")} ${value}`),
12
+ divider: () => console.log(pc.dim(" " + "─".repeat(52))),
13
+ blank: () => console.log(),
14
+
15
+ banner() {
16
+ console.log();
17
+ console.log(pc.bold(pc.magenta(" ┌──────────────────────────────────────┐")));
18
+ console.log(pc.bold(pc.magenta(" │ juas.dev CLI ⚡ │")));
19
+ console.log(pc.bold(pc.magenta(" └──────────────────────────────────────┘")));
20
+ console.log();
21
+ },
22
+ };
@@ -0,0 +1,81 @@
1
+ // ============================================================
2
+ // supabase.js — lightweight REST client for the CLI
3
+ // Uses the PUBLIC anon key — safe to ship in the npm package
4
+ // ============================================================
5
+
6
+ export const SUPABASE_URL = "https://jznmqsiueeauoulgvzww.supabase.co";
7
+ export const SUPABASE_ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imp6bm1xc2l1ZWVhdW91bGd2end3Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODE1MTA0MjIsImV4cCI6MjA5NzA4NjQyMn0.KG54rFl_jT0ofhQ9KuYGEQYNC8_kZD0KxoCpmXWz1pU";
8
+
9
+ /**
10
+ * Thin fetch wrapper around the Supabase REST API.
11
+ */
12
+ export async function supabaseGet(table, params = {}) {
13
+ const url = new URL(`${SUPABASE_URL}/rest/v1/${table}`);
14
+ Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));
15
+
16
+ const res = await fetch(url.toString(), {
17
+ headers: {
18
+ apikey: SUPABASE_ANON_KEY,
19
+ Authorization: `Bearer ${SUPABASE_ANON_KEY}`,
20
+ "Content-Type": "application/json",
21
+ },
22
+ });
23
+
24
+ if (!res.ok) {
25
+ const txt = await res.text();
26
+ throw new Error(`Supabase error ${res.status}: ${txt}`);
27
+ }
28
+
29
+ return res.json();
30
+ }
31
+
32
+ /**
33
+ * Fetch a single component + its latest version code by slug.
34
+ */
35
+ export async function fetchComponentBySlug(slug) {
36
+ const components = await supabaseGet("components", {
37
+ slug: `eq.${slug}`,
38
+ status: "in.(published,featured)",
39
+ select: "id,name,slug,description,category,tags,tech_stack,framework,latest_version,pricing_tier,project_files",
40
+ limit: "1",
41
+ });
42
+
43
+ if (!components.length) return null;
44
+ const component = components[0];
45
+
46
+ const versions = await supabaseGet("component_versions", {
47
+ component_id: `eq.${component.id}`,
48
+ version: `eq.${component.latest_version}`,
49
+ select: "id,version,code_tsx,code_css,dependencies,readme",
50
+ limit: "1",
51
+ });
52
+
53
+ return { component, version: versions[0] ?? null };
54
+ }
55
+
56
+ /**
57
+ * List all published components.
58
+ */
59
+ export async function listComponents({ category } = {}) {
60
+ const params = {
61
+ status: "in.(published,featured)",
62
+ select: "id,name,slug,description,category,tags,tech_stack,latest_version",
63
+ order: "name.asc",
64
+ limit: "200",
65
+ };
66
+ if (category) params.category = `eq.${category}`;
67
+ return supabaseGet("components", params);
68
+ }
69
+
70
+ /**
71
+ * Search components by name or description.
72
+ */
73
+ export async function searchComponents(query) {
74
+ return supabaseGet("components", {
75
+ status: "in.(published,featured)",
76
+ or: `name.ilike.*${query}*,description.ilike.*${query}*`,
77
+ select: "id,name,slug,description,category,tags,latest_version",
78
+ order: "name.asc",
79
+ limit: "50",
80
+ });
81
+ }
package/index.js DELETED
@@ -1,123 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- import { Command } from 'commander';
4
- import prompts from 'prompts';
5
- import pc from 'picocolors';
6
- import ora from 'ora';
7
- import fs from 'fs/promises';
8
- import path from 'path';
9
- import { createClient } from '@supabase/supabase-js';
10
-
11
- // Hardcoded for CLI public access
12
- const SUPABASE_URL = "https://jznmqsiueeauoulgvzww.supabase.co";
13
- const SUPABASE_ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imp6bm1xc2l1ZWVhdW91bGd2end3Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODE1MTA0MjIsImV4cCI6MjA5NzA4NjQyMn0.KG54rFl_jT0ofhQ9KuYGEQYNC8_kZD0KxoCpmXWz1pU";
14
-
15
- const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
16
- const program = new Command();
17
-
18
- program
19
- .name('dhil-ui')
20
- .description('Add ultra-premium React components to your project')
21
- .version('1.0.0');
22
-
23
- // --- INIT COMMAND ---
24
- program
25
- .command('init')
26
- .description('Initialize your project and choose your components directory')
27
- .action(async () => {
28
- console.log(pc.bold(pc.red('Welcome to dhil.dev CLI\n')));
29
-
30
- const response = await prompts({
31
- type: 'text',
32
- name: 'componentsDir',
33
- message: 'Where is your components directory?',
34
- initial: 'components/ui'
35
- });
36
-
37
- if (!response.componentsDir) {
38
- console.log(pc.red('Operation cancelled.'));
39
- process.exit(1);
40
- }
41
-
42
- const config = {
43
- componentsDir: response.componentsDir
44
- };
45
-
46
- await fs.writeFile(
47
- path.join(process.cwd(), 'components.json'),
48
- JSON.stringify(config, null, 2)
49
- );
50
-
51
- console.log(pc.green(`\n✔ Configuration saved to components.json`));
52
- console.log(`\nYou can now run ${pc.cyan('npx dhil-ui add <component>')} to start building.`);
53
- });
54
-
55
- // --- ADD COMMAND ---
56
- program
57
- .command('add <componentId>')
58
- .description('Add a component to your project')
59
- .action(async (componentId) => {
60
- const spinner = ora(`Fetching ${componentId}...`).start();
61
-
62
- try {
63
- // 1. Fetch from Supabase
64
- const { data: component, error } = await supabase
65
- .from('components')
66
- .select(`
67
- id, name, tech_stack,
68
- component_versions (
69
- code_tsx, dependencies
70
- )
71
- `)
72
- .eq('id', componentId)
73
- .single();
74
-
75
- if (error || !component) {
76
- throw new Error(`Component not found or API error: ${error?.message || ''}`);
77
- }
78
-
79
- const version = component.component_versions[0];
80
- if (!version || !version.code_tsx) {
81
- throw new Error('No source code available for this component.');
82
- }
83
-
84
- spinner.text = `Installing ${component.name}...`;
85
-
86
- // 2. Determine target directory
87
- let targetDir = 'components/ui';
88
- try {
89
- const configRaw = await fs.readFile(path.join(process.cwd(), 'components.json'), 'utf-8');
90
- const config = JSON.parse(configRaw);
91
- if (config.componentsDir) {
92
- targetDir = config.componentsDir;
93
- }
94
- } catch (err) {
95
- // Default to components/ui if no config
96
- }
97
-
98
- // Ensure directory exists
99
- const absoluteTargetDir = path.join(process.cwd(), targetDir);
100
- await fs.mkdir(absoluteTargetDir, { recursive: true });
101
-
102
- // 3. Write File
103
- // Format filename (e.g. "Colorful 3D Text" -> "Colorful3DText.tsx")
104
- const fileName = component.name.replace(/[^a-zA-Z0-9]/g, '') + '.tsx';
105
- const filePath = path.join(absoluteTargetDir, fileName);
106
-
107
- await fs.writeFile(filePath, version.code_tsx);
108
-
109
- spinner.succeed(pc.green(`Added ${pc.bold(component.name)} to ${targetDir}/${fileName}`));
110
-
111
- // 4. Check dependencies
112
- if (version.dependencies && version.dependencies.length > 0) {
113
- console.log(pc.yellow(`\n⚠ Please ensure you have the following dependencies installed:`));
114
- console.log(pc.cyan(` npm install ${version.dependencies.join(' ')}`));
115
- }
116
-
117
- } catch (err) {
118
- spinner.fail(pc.red(err.message));
119
- process.exit(1);
120
- }
121
- });
122
-
123
- program.parse();