@fragments-sdk/cli 0.13.1 → 0.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +11 -1
- package/dist/bin.js.map +1 -1
- package/dist/init-cloud-REQ3XLHO.js +279 -0
- package/dist/init-cloud-REQ3XLHO.js.map +1 -0
- package/package.json +5 -4
- package/src/bin.ts +17 -0
- package/src/commands/init-cloud.ts +354 -0
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
import { createRequire as __banner_createRequire } from 'module'; const require = __banner_createRequire(import.meta.url);
|
|
2
|
+
import "./chunk-D2CDBRNU.js";
|
|
3
|
+
import {
|
|
4
|
+
BRAND
|
|
5
|
+
} from "./chunk-I34BC3CU.js";
|
|
6
|
+
import "./chunk-Z7EY4VHE.js";
|
|
7
|
+
|
|
8
|
+
// src/commands/init-cloud.ts
|
|
9
|
+
import { createServer } from "http";
|
|
10
|
+
import { randomBytes } from "crypto";
|
|
11
|
+
import { execSync, exec } from "child_process";
|
|
12
|
+
import { readFileSync, writeFileSync, existsSync, appendFileSync } from "fs";
|
|
13
|
+
import { resolve, join } from "path";
|
|
14
|
+
import { platform } from "os";
|
|
15
|
+
import pc from "picocolors";
|
|
16
|
+
function detectPackageManager() {
|
|
17
|
+
let dir = process.cwd();
|
|
18
|
+
const root = resolve("/");
|
|
19
|
+
while (dir !== root) {
|
|
20
|
+
if (existsSync(join(dir, "bun.lockb")) || existsSync(join(dir, "bun.lock"))) return "bun";
|
|
21
|
+
if (existsSync(join(dir, "pnpm-lock.yaml"))) return "pnpm";
|
|
22
|
+
if (existsSync(join(dir, "yarn.lock"))) return "yarn";
|
|
23
|
+
const parent = resolve(dir, "..");
|
|
24
|
+
if (parent === dir) break;
|
|
25
|
+
dir = parent;
|
|
26
|
+
}
|
|
27
|
+
return "npm";
|
|
28
|
+
}
|
|
29
|
+
function detectFramework() {
|
|
30
|
+
try {
|
|
31
|
+
const pkg = JSON.parse(readFileSync(resolve("package.json"), "utf-8"));
|
|
32
|
+
const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
33
|
+
if (allDeps["next"]) return "Next.js";
|
|
34
|
+
if (allDeps["nuxt"]) return "Nuxt";
|
|
35
|
+
if (allDeps["@sveltejs/kit"]) return "SvelteKit";
|
|
36
|
+
if (allDeps["svelte"]) return "Svelte";
|
|
37
|
+
if (allDeps["vue"]) return "Vue";
|
|
38
|
+
if (allDeps["astro"]) return "Astro";
|
|
39
|
+
if (allDeps["react"]) return "React";
|
|
40
|
+
return "Unknown";
|
|
41
|
+
} catch {
|
|
42
|
+
return "Unknown";
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function inferInputGlob(framework) {
|
|
46
|
+
switch (framework) {
|
|
47
|
+
case "Next.js":
|
|
48
|
+
return ["./app/**/*.{tsx,jsx}", "./components/**/*.{tsx,jsx}"];
|
|
49
|
+
case "Nuxt":
|
|
50
|
+
case "Vue":
|
|
51
|
+
return ["./**/*.vue"];
|
|
52
|
+
case "SvelteKit":
|
|
53
|
+
case "Svelte":
|
|
54
|
+
return ["./src/**/*.svelte"];
|
|
55
|
+
case "Astro":
|
|
56
|
+
return ["./src/**/*.{astro,tsx,jsx}"];
|
|
57
|
+
default:
|
|
58
|
+
return "./src/**/*.{tsx,jsx}";
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function openBrowser(url) {
|
|
62
|
+
const os = platform();
|
|
63
|
+
const cmd = os === "darwin" ? "open" : os === "win32" ? 'start ""' : "xdg-open";
|
|
64
|
+
exec(`${cmd} "${url}"`);
|
|
65
|
+
}
|
|
66
|
+
function installCommand(pm) {
|
|
67
|
+
switch (pm) {
|
|
68
|
+
case "pnpm":
|
|
69
|
+
return "pnpm add";
|
|
70
|
+
case "yarn":
|
|
71
|
+
return "yarn add";
|
|
72
|
+
case "bun":
|
|
73
|
+
return "bun add";
|
|
74
|
+
default:
|
|
75
|
+
return "npm install";
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
function isMonorepoWorkspaceDep() {
|
|
79
|
+
try {
|
|
80
|
+
const pkg = JSON.parse(readFileSync(resolve("package.json"), "utf-8"));
|
|
81
|
+
const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
82
|
+
return allDeps["@fragments-sdk/govern"]?.startsWith("workspace:") || allDeps["@fragments-sdk/cli"]?.startsWith("workspace:");
|
|
83
|
+
} catch {
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
function waitForAuth(cloudUrl, port, timeoutMs) {
|
|
88
|
+
const nonce = randomBytes(16).toString("hex");
|
|
89
|
+
return new Promise((resolve2, reject) => {
|
|
90
|
+
const timeout = setTimeout(() => {
|
|
91
|
+
server.close();
|
|
92
|
+
reject(new Error("Authentication timed out. Please try again."));
|
|
93
|
+
}, timeoutMs);
|
|
94
|
+
const server = createServer((req, res) => {
|
|
95
|
+
const url = new URL(req.url, `http://localhost:${port}`);
|
|
96
|
+
if (url.pathname === "/callback") {
|
|
97
|
+
const key = url.searchParams.get("key");
|
|
98
|
+
const org = url.searchParams.get("org");
|
|
99
|
+
const returnedNonce = url.searchParams.get("nonce");
|
|
100
|
+
if (returnedNonce !== nonce) {
|
|
101
|
+
res.writeHead(400, { "Content-Type": "text/plain" });
|
|
102
|
+
res.end("Nonce mismatch \u2014 please try again.");
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
if (!key) {
|
|
106
|
+
res.writeHead(400, { "Content-Type": "text/plain" });
|
|
107
|
+
res.end("Missing API key in callback.");
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
res.writeHead(200, { "Content-Type": "text/html" });
|
|
111
|
+
res.end(`<!DOCTYPE html>
|
|
112
|
+
<html><head><title>Fragments CLI</title>
|
|
113
|
+
<style>body{font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;background:#0a0a0f;color:#e5e5e5}
|
|
114
|
+
.box{text-align:center;padding:48px}.check{font-size:48px;margin-bottom:16px}p{color:#888;margin-top:8px}</style>
|
|
115
|
+
</head><body><div class="box"><div class="check">✓</div><h2>CLI Authorized</h2><p>You can close this tab and return to your terminal.</p></div>
|
|
116
|
+
<script>setTimeout(()=>window.close(),3000)</script>
|
|
117
|
+
</body></html>`);
|
|
118
|
+
clearTimeout(timeout);
|
|
119
|
+
server.close();
|
|
120
|
+
resolve2({ apiKey: key, orgName: org ?? "your organization" });
|
|
121
|
+
} else {
|
|
122
|
+
res.writeHead(404);
|
|
123
|
+
res.end();
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
server.on("error", (err) => {
|
|
127
|
+
if (err.code === "EADDRINUSE") {
|
|
128
|
+
clearTimeout(timeout);
|
|
129
|
+
reject(new Error(`Port ${port} is in use. Try: fragments init --cloud --port ${port + 1}`));
|
|
130
|
+
} else {
|
|
131
|
+
clearTimeout(timeout);
|
|
132
|
+
reject(err);
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
server.listen(port, "127.0.0.1", () => {
|
|
136
|
+
const authUrl = `${cloudUrl}/cli-auth?port=${port}&nonce=${nonce}`;
|
|
137
|
+
openBrowser(authUrl);
|
|
138
|
+
});
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
function saveApiKey(apiKey, cloudUrl) {
|
|
142
|
+
const envPath = resolve(".env");
|
|
143
|
+
const entry = `FRAGMENTS_API_KEY=${apiKey}`;
|
|
144
|
+
if (existsSync(envPath)) {
|
|
145
|
+
const content = readFileSync(envPath, "utf-8");
|
|
146
|
+
if (content.includes("FRAGMENTS_API_KEY=")) {
|
|
147
|
+
const updated = content.replace(/^FRAGMENTS_API_KEY=.*$/m, entry);
|
|
148
|
+
writeFileSync(envPath, updated, "utf-8");
|
|
149
|
+
} else {
|
|
150
|
+
appendFileSync(envPath, `
|
|
151
|
+
${entry}
|
|
152
|
+
`, "utf-8");
|
|
153
|
+
}
|
|
154
|
+
} else {
|
|
155
|
+
writeFileSync(envPath, `${entry}
|
|
156
|
+
`, "utf-8");
|
|
157
|
+
}
|
|
158
|
+
if (cloudUrl !== "https://app.usefragments.com") {
|
|
159
|
+
const content = readFileSync(envPath, "utf-8");
|
|
160
|
+
if (!content.includes("FRAGMENTS_URL=")) {
|
|
161
|
+
appendFileSync(envPath, `FRAGMENTS_URL=${cloudUrl}
|
|
162
|
+
`, "utf-8");
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
const gitignorePath = resolve(".gitignore");
|
|
166
|
+
if (existsSync(gitignorePath)) {
|
|
167
|
+
const gitignore = readFileSync(gitignorePath, "utf-8");
|
|
168
|
+
if (!gitignore.split("\n").some((line) => line.trim() === ".env")) {
|
|
169
|
+
appendFileSync(gitignorePath, "\n.env\n", "utf-8");
|
|
170
|
+
}
|
|
171
|
+
} else {
|
|
172
|
+
writeFileSync(gitignorePath, ".env\n", "utf-8");
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
function writeGovernConfig(input) {
|
|
176
|
+
const configPath = resolve(BRAND.configFile);
|
|
177
|
+
if (existsSync(configPath)) return;
|
|
178
|
+
const inputStr = Array.isArray(input) ? `[${input.map((p) => `'${p}'`).join(", ")}]` : `'${input}'`;
|
|
179
|
+
const template = `import { defineConfig } from '@fragments-sdk/govern';
|
|
180
|
+
|
|
181
|
+
export default defineConfig({
|
|
182
|
+
cloud: true,
|
|
183
|
+
checks: ['accessibility', 'consistency', 'responsive'],
|
|
184
|
+
input: ${inputStr},
|
|
185
|
+
});
|
|
186
|
+
`;
|
|
187
|
+
writeFileSync(configPath, template, "utf-8");
|
|
188
|
+
}
|
|
189
|
+
async function initCloud(options = {}) {
|
|
190
|
+
const cloudUrl = options.url ?? process.env.FRAGMENTS_URL ?? "https://app.usefragments.com";
|
|
191
|
+
const port = options.port ?? 9876;
|
|
192
|
+
const timeoutMs = options.timeout ?? 12e4;
|
|
193
|
+
console.log(pc.bold(`
|
|
194
|
+
${BRAND.name}
|
|
195
|
+
`));
|
|
196
|
+
if (!options.authOnly) {
|
|
197
|
+
if (!existsSync(resolve("package.json"))) {
|
|
198
|
+
console.log(pc.red(" No package.json found. Run this from a project directory.\n"));
|
|
199
|
+
process.exit(1);
|
|
200
|
+
}
|
|
201
|
+
const pm2 = detectPackageManager();
|
|
202
|
+
const framework2 = detectFramework();
|
|
203
|
+
console.log(pc.dim(` Project: ${framework2}`));
|
|
204
|
+
console.log(pc.dim(` Package manager: ${pm2}
|
|
205
|
+
`));
|
|
206
|
+
}
|
|
207
|
+
console.log(pc.dim(" Opening browser to sign in...\n"));
|
|
208
|
+
let auth;
|
|
209
|
+
try {
|
|
210
|
+
auth = await waitForAuth(cloudUrl, port, timeoutMs);
|
|
211
|
+
} catch (err) {
|
|
212
|
+
console.log(pc.red(`
|
|
213
|
+
${err instanceof Error ? err.message : "Auth failed"}
|
|
214
|
+
`));
|
|
215
|
+
process.exit(1);
|
|
216
|
+
}
|
|
217
|
+
console.log(pc.green(` \u2713 Authenticated \u2014 ${auth.orgName}
|
|
218
|
+
`));
|
|
219
|
+
saveApiKey(auth.apiKey, cloudUrl);
|
|
220
|
+
console.log(pc.green(" \u2713 API key saved to .env"));
|
|
221
|
+
if (options.authOnly) {
|
|
222
|
+
console.log(pc.green("\n \u2713 All set!\n"));
|
|
223
|
+
console.log(pc.dim(` Dashboard: ${cloudUrl}
|
|
224
|
+
`));
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
const pm = detectPackageManager();
|
|
228
|
+
if (!isMonorepoWorkspaceDep()) {
|
|
229
|
+
const deps = "@fragments-sdk/govern @fragments-sdk/cli";
|
|
230
|
+
console.log(pc.dim(`
|
|
231
|
+
Installing ${deps}...`));
|
|
232
|
+
try {
|
|
233
|
+
execSync(`${installCommand(pm)} ${deps}`, {
|
|
234
|
+
stdio: "pipe",
|
|
235
|
+
cwd: process.cwd()
|
|
236
|
+
});
|
|
237
|
+
console.log(pc.green(" \u2713 Dependencies installed"));
|
|
238
|
+
} catch (err) {
|
|
239
|
+
console.log(pc.yellow(" \u26A0 Install failed \u2014 you may need to install manually:"));
|
|
240
|
+
console.log(pc.dim(` ${installCommand(pm)} ${deps}
|
|
241
|
+
`));
|
|
242
|
+
}
|
|
243
|
+
} else {
|
|
244
|
+
console.log(pc.dim("\n Workspace deps detected \u2014 skipping install"));
|
|
245
|
+
}
|
|
246
|
+
const framework = detectFramework();
|
|
247
|
+
const input = inferInputGlob(framework);
|
|
248
|
+
const configPath = resolve(BRAND.configFile);
|
|
249
|
+
if (existsSync(configPath)) {
|
|
250
|
+
console.log(pc.dim(` Config already exists: ${BRAND.configFile}`));
|
|
251
|
+
} else {
|
|
252
|
+
writeGovernConfig(input);
|
|
253
|
+
console.log(pc.green(` \u2713 Created ${BRAND.configFile}`));
|
|
254
|
+
}
|
|
255
|
+
if (!options.skipCheck) {
|
|
256
|
+
console.log(pc.dim("\n Running first governance check...\n"));
|
|
257
|
+
try {
|
|
258
|
+
const output = execSync("npx fragments govern check --cloud", {
|
|
259
|
+
stdio: "pipe",
|
|
260
|
+
cwd: process.cwd(),
|
|
261
|
+
env: { ...process.env, FRAGMENTS_API_KEY: auth.apiKey }
|
|
262
|
+
});
|
|
263
|
+
console.log(output.toString());
|
|
264
|
+
} catch (err) {
|
|
265
|
+
if (err.stdout) {
|
|
266
|
+
console.log(err.stdout.toString());
|
|
267
|
+
}
|
|
268
|
+
console.log(pc.dim(" (check completed with violations \u2014 see dashboard for details)"));
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
console.log(pc.green("\n \u2713 All set!") + " Your project is connected to Fragments Cloud.\n");
|
|
272
|
+
console.log(pc.dim(` Dashboard: ${cloudUrl}`));
|
|
273
|
+
console.log(pc.dim(" Run checks: fragments govern check --cloud"));
|
|
274
|
+
console.log(pc.dim(" View config: fragments.config.ts\n"));
|
|
275
|
+
}
|
|
276
|
+
export {
|
|
277
|
+
initCloud
|
|
278
|
+
};
|
|
279
|
+
//# sourceMappingURL=init-cloud-REQ3XLHO.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/init-cloud.ts"],"sourcesContent":["/**\n * fragments init --cloud\n *\n * Zero-config cloud setup: opens browser for auth, receives API key\n * via localhost callback, detects project, installs deps, creates config,\n * runs first check.\n */\n\nimport { createServer, type IncomingMessage, type ServerResponse } from 'node:http';\nimport { randomBytes } from 'node:crypto';\nimport { execSync, exec } from 'node:child_process';\nimport { readFileSync, writeFileSync, existsSync, appendFileSync } from 'node:fs';\nimport { resolve, join } from 'node:path';\nimport { platform } from 'node:os';\nimport pc from 'picocolors';\nimport { BRAND } from '../core/index.js';\n\n// ─── Types ──────────────────────────────────────────────────────────────────\n\ninterface AuthResult {\n apiKey: string;\n orgName: string;\n}\n\nexport interface InitCloudOptions {\n /** Cloud dashboard URL */\n url?: string;\n /** Port for localhost callback server */\n port?: number;\n /** Timeout in ms for auth */\n timeout?: number;\n /** Skip project detection and setup */\n authOnly?: boolean;\n /** Skip the first governance check */\n skipCheck?: boolean;\n}\n\n// ─── Utilities ──────────────────────────────────────────────────────────────\n\nfunction detectPackageManager(): 'pnpm' | 'yarn' | 'bun' | 'npm' {\n // Check current dir and parent dirs (for monorepos)\n let dir = process.cwd();\n const root = resolve('/');\n while (dir !== root) {\n if (existsSync(join(dir, 'bun.lockb')) || existsSync(join(dir, 'bun.lock'))) return 'bun';\n if (existsSync(join(dir, 'pnpm-lock.yaml'))) return 'pnpm';\n if (existsSync(join(dir, 'yarn.lock'))) return 'yarn';\n const parent = resolve(dir, '..');\n if (parent === dir) break;\n dir = parent;\n }\n return 'npm';\n}\n\nfunction detectFramework(): string {\n try {\n const pkg = JSON.parse(readFileSync(resolve('package.json'), 'utf-8'));\n const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };\n\n if (allDeps['next']) return 'Next.js';\n if (allDeps['nuxt']) return 'Nuxt';\n if (allDeps['@sveltejs/kit']) return 'SvelteKit';\n if (allDeps['svelte']) return 'Svelte';\n if (allDeps['vue']) return 'Vue';\n if (allDeps['astro']) return 'Astro';\n if (allDeps['react']) return 'React';\n return 'Unknown';\n } catch {\n return 'Unknown';\n }\n}\n\nfunction inferInputGlob(framework: string): string | string[] {\n switch (framework) {\n case 'Next.js':\n return ['./app/**/*.{tsx,jsx}', './components/**/*.{tsx,jsx}'];\n case 'Nuxt':\n case 'Vue':\n return ['./**/*.vue'];\n case 'SvelteKit':\n case 'Svelte':\n return ['./src/**/*.svelte'];\n case 'Astro':\n return ['./src/**/*.{astro,tsx,jsx}'];\n default:\n return './src/**/*.{tsx,jsx}';\n }\n}\n\nfunction openBrowser(url: string): void {\n const os = platform();\n const cmd =\n os === 'darwin' ? 'open' :\n os === 'win32' ? 'start \"\"' :\n 'xdg-open';\n\n exec(`${cmd} \"${url}\"`);\n}\n\nfunction installCommand(pm: string): string {\n switch (pm) {\n case 'pnpm': return 'pnpm add';\n case 'yarn': return 'yarn add';\n case 'bun': return 'bun add';\n default: return 'npm install';\n }\n}\n\nfunction isMonorepoWorkspaceDep(): boolean {\n try {\n const pkg = JSON.parse(readFileSync(resolve('package.json'), 'utf-8'));\n const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };\n return (\n allDeps['@fragments-sdk/govern']?.startsWith('workspace:') ||\n allDeps['@fragments-sdk/cli']?.startsWith('workspace:')\n );\n } catch {\n return false;\n }\n}\n\n// ─── Localhost Auth Server ──────────────────────────────────────────────────\n\nfunction waitForAuth(\n cloudUrl: string,\n port: number,\n timeoutMs: number,\n): Promise<AuthResult> {\n const nonce = randomBytes(16).toString('hex');\n\n return new Promise<AuthResult>((resolve, reject) => {\n const timeout = setTimeout(() => {\n server.close();\n reject(new Error('Authentication timed out. Please try again.'));\n }, timeoutMs);\n\n const server = createServer((req: IncomingMessage, res: ServerResponse) => {\n const url = new URL(req.url!, `http://localhost:${port}`);\n\n if (url.pathname === '/callback') {\n const key = url.searchParams.get('key');\n const org = url.searchParams.get('org');\n const returnedNonce = url.searchParams.get('nonce');\n\n if (returnedNonce !== nonce) {\n res.writeHead(400, { 'Content-Type': 'text/plain' });\n res.end('Nonce mismatch — please try again.');\n return;\n }\n\n if (!key) {\n res.writeHead(400, { 'Content-Type': 'text/plain' });\n res.end('Missing API key in callback.');\n return;\n }\n\n // Show \"you can close this tab\" page\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(`<!DOCTYPE html>\n<html><head><title>Fragments CLI</title>\n<style>body{font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;background:#0a0a0f;color:#e5e5e5}\n.box{text-align:center;padding:48px}.check{font-size:48px;margin-bottom:16px}p{color:#888;margin-top:8px}</style>\n</head><body><div class=\"box\"><div class=\"check\">✓</div><h2>CLI Authorized</h2><p>You can close this tab and return to your terminal.</p></div>\n<script>setTimeout(()=>window.close(),3000)</script>\n</body></html>`);\n\n clearTimeout(timeout);\n server.close();\n resolve({ apiKey: key, orgName: org ?? 'your organization' });\n } else {\n res.writeHead(404);\n res.end();\n }\n });\n\n server.on('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EADDRINUSE') {\n clearTimeout(timeout);\n reject(new Error(`Port ${port} is in use. Try: fragments init --cloud --port ${port + 1}`));\n } else {\n clearTimeout(timeout);\n reject(err);\n }\n });\n\n server.listen(port, '127.0.0.1', () => {\n const authUrl = `${cloudUrl}/cli-auth?port=${port}&nonce=${nonce}`;\n openBrowser(authUrl);\n });\n });\n}\n\n// ─── Save to .env ───────────────────────────────────────────────────────────\n\nfunction saveApiKey(apiKey: string, cloudUrl: string): void {\n const envPath = resolve('.env');\n const entry = `FRAGMENTS_API_KEY=${apiKey}`;\n\n if (existsSync(envPath)) {\n const content = readFileSync(envPath, 'utf-8');\n if (content.includes('FRAGMENTS_API_KEY=')) {\n const updated = content.replace(/^FRAGMENTS_API_KEY=.*$/m, entry);\n writeFileSync(envPath, updated, 'utf-8');\n } else {\n appendFileSync(envPath, `\\n${entry}\\n`, 'utf-8');\n }\n } else {\n writeFileSync(envPath, `${entry}\\n`, 'utf-8');\n }\n\n // Add FRAGMENTS_URL if non-default\n if (cloudUrl !== 'https://app.usefragments.com') {\n const content = readFileSync(envPath, 'utf-8');\n if (!content.includes('FRAGMENTS_URL=')) {\n appendFileSync(envPath, `FRAGMENTS_URL=${cloudUrl}\\n`, 'utf-8');\n }\n }\n\n // Ensure .env is in .gitignore\n const gitignorePath = resolve('.gitignore');\n if (existsSync(gitignorePath)) {\n const gitignore = readFileSync(gitignorePath, 'utf-8');\n if (!gitignore.split('\\n').some((line) => line.trim() === '.env')) {\n appendFileSync(gitignorePath, '\\n.env\\n', 'utf-8');\n }\n } else {\n writeFileSync(gitignorePath, '.env\\n', 'utf-8');\n }\n}\n\n// ─── Write governance config ────────────────────────────────────────────────\n\nfunction writeGovernConfig(input: string | string[]): void {\n const configPath = resolve(BRAND.configFile);\n if (existsSync(configPath)) return; // Don't overwrite\n\n const inputStr = Array.isArray(input)\n ? `[${input.map((p) => `'${p}'`).join(', ')}]`\n : `'${input}'`;\n\n const template = `import { defineConfig } from '@fragments-sdk/govern';\n\nexport default defineConfig({\n cloud: true,\n checks: ['accessibility', 'consistency', 'responsive'],\n input: ${inputStr},\n});\n`;\n\n writeFileSync(configPath, template, 'utf-8');\n}\n\n// ─── Main ───────────────────────────────────────────────────────────────────\n\nexport async function initCloud(options: InitCloudOptions = {}): Promise<void> {\n const cloudUrl = options.url ?? process.env.FRAGMENTS_URL ?? 'https://app.usefragments.com';\n const port = options.port ?? 9876;\n const timeoutMs = options.timeout ?? 120_000;\n\n console.log(pc.bold(`\\n ${BRAND.name}\\n`));\n\n // ── 1. Detect project ─────────────────────────────────────────────\n if (!options.authOnly) {\n if (!existsSync(resolve('package.json'))) {\n console.log(pc.red(' No package.json found. Run this from a project directory.\\n'));\n process.exit(1);\n }\n\n const pm = detectPackageManager();\n const framework = detectFramework();\n console.log(pc.dim(` Project: ${framework}`));\n console.log(pc.dim(` Package manager: ${pm}\\n`));\n }\n\n // ── 2. Authenticate ───────────────────────────────────────────────\n console.log(pc.dim(' Opening browser to sign in...\\n'));\n\n let auth: AuthResult;\n try {\n auth = await waitForAuth(cloudUrl, port, timeoutMs);\n } catch (err) {\n console.log(pc.red(`\\n ${err instanceof Error ? err.message : 'Auth failed'}\\n`));\n process.exit(1);\n }\n\n console.log(pc.green(` ✓ Authenticated — ${auth.orgName}\\n`));\n\n // ── 3. Save API key ──────────────────────────────────────────────\n saveApiKey(auth.apiKey, cloudUrl);\n console.log(pc.green(' ✓ API key saved to .env'));\n\n if (options.authOnly) {\n console.log(pc.green('\\n ✓ All set!\\n'));\n console.log(pc.dim(` Dashboard: ${cloudUrl}\\n`));\n return;\n }\n\n // ── 4. Install dependencies ───────────────────────────────────────\n const pm = detectPackageManager();\n\n if (!isMonorepoWorkspaceDep()) {\n const deps = '@fragments-sdk/govern @fragments-sdk/cli';\n console.log(pc.dim(`\\n Installing ${deps}...`));\n try {\n execSync(`${installCommand(pm)} ${deps}`, {\n stdio: 'pipe',\n cwd: process.cwd(),\n });\n console.log(pc.green(' ✓ Dependencies installed'));\n } catch (err) {\n console.log(pc.yellow(' ⚠ Install failed — you may need to install manually:'));\n console.log(pc.dim(` ${installCommand(pm)} ${deps}\\n`));\n }\n } else {\n console.log(pc.dim('\\n Workspace deps detected — skipping install'));\n }\n\n // ── 5. Create governance config ───────────────────────────────────\n const framework = detectFramework();\n const input = inferInputGlob(framework);\n const configPath = resolve(BRAND.configFile);\n\n if (existsSync(configPath)) {\n console.log(pc.dim(` Config already exists: ${BRAND.configFile}`));\n } else {\n writeGovernConfig(input);\n console.log(pc.green(` ✓ Created ${BRAND.configFile}`));\n }\n\n // ── 6. Run first check ────────────────────────────────────────────\n if (!options.skipCheck) {\n console.log(pc.dim('\\n Running first governance check...\\n'));\n try {\n const output = execSync('npx fragments govern check --cloud', {\n stdio: 'pipe',\n cwd: process.cwd(),\n env: { ...process.env, FRAGMENTS_API_KEY: auth.apiKey },\n });\n console.log(output.toString());\n } catch (err: any) {\n // Check may \"fail\" with violations — that's OK\n if (err.stdout) {\n console.log(err.stdout.toString());\n }\n console.log(pc.dim(' (check completed with violations — see dashboard for details)'));\n }\n }\n\n // ── 7. Done ───────────────────────────────────────────────────────\n console.log(pc.green('\\n ✓ All set!') + ' Your project is connected to Fragments Cloud.\\n');\n console.log(pc.dim(` Dashboard: ${cloudUrl}`));\n console.log(pc.dim(' Run checks: fragments govern check --cloud'));\n console.log(pc.dim(' View config: fragments.config.ts\\n'));\n}\n"],"mappings":";;;;;;;;AAQA,SAAS,oBAA+D;AACxE,SAAS,mBAAmB;AAC5B,SAAS,UAAU,YAAY;AAC/B,SAAS,cAAc,eAAe,YAAY,sBAAsB;AACxE,SAAS,SAAS,YAAY;AAC9B,SAAS,gBAAgB;AACzB,OAAO,QAAQ;AAyBf,SAAS,uBAAwD;AAE/D,MAAI,MAAM,QAAQ,IAAI;AACtB,QAAM,OAAO,QAAQ,GAAG;AACxB,SAAO,QAAQ,MAAM;AACnB,QAAI,WAAW,KAAK,KAAK,WAAW,CAAC,KAAK,WAAW,KAAK,KAAK,UAAU,CAAC,EAAG,QAAO;AACpF,QAAI,WAAW,KAAK,KAAK,gBAAgB,CAAC,EAAG,QAAO;AACpD,QAAI,WAAW,KAAK,KAAK,WAAW,CAAC,EAAG,QAAO;AAC/C,UAAM,SAAS,QAAQ,KAAK,IAAI;AAChC,QAAI,WAAW,IAAK;AACpB,UAAM;AAAA,EACR;AACA,SAAO;AACT;AAEA,SAAS,kBAA0B;AACjC,MAAI;AACF,UAAM,MAAM,KAAK,MAAM,aAAa,QAAQ,cAAc,GAAG,OAAO,CAAC;AACrE,UAAM,UAAU,EAAE,GAAG,IAAI,cAAc,GAAG,IAAI,gBAAgB;AAE9D,QAAI,QAAQ,MAAM,EAAG,QAAO;AAC5B,QAAI,QAAQ,MAAM,EAAG,QAAO;AAC5B,QAAI,QAAQ,eAAe,EAAG,QAAO;AACrC,QAAI,QAAQ,QAAQ,EAAG,QAAO;AAC9B,QAAI,QAAQ,KAAK,EAAG,QAAO;AAC3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O,SAAS,CAAC;AAAA,MACnC;AACA,cAAQ,IAAI,GAAG,IAAI,sEAAiE,CAAC;AAAA,IACvF;AAAA,EACF;AAGA,UAAQ,IAAI,GAAG,MAAM,qBAAgB,IAAI,kDAAkD;AAC3F,UAAQ,IAAI,GAAG,IAAI,gBAAgB,QAAQ,EAAE,CAAC;AAC9C,UAAQ,IAAI,GAAG,IAAI,8CAA8C,CAAC;AAClE,UAAQ,IAAI,GAAG,IAAI,sCAAsC,CAAC;AAC5D;","names":["resolve","pm","framework"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fragments-sdk/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.1",
|
|
4
4
|
"license": "FSL-1.1-MIT",
|
|
5
5
|
"description": "CLI, MCP server, and dev tools for Fragments design system",
|
|
6
6
|
"author": "Conan McNicholl",
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
},
|
|
12
12
|
"type": "module",
|
|
13
13
|
"bin": {
|
|
14
|
+
"cli": "./dist/bin.js",
|
|
14
15
|
"fragments": "./dist/bin.js",
|
|
15
16
|
"fragments-sdk": "./dist/bin.js",
|
|
16
17
|
"fragments-mcp": "./dist/mcp-bin.js"
|
|
@@ -80,11 +81,11 @@
|
|
|
80
81
|
"vite": "^6.0.0",
|
|
81
82
|
"vite-plugin-svgr": "^4.5.0",
|
|
82
83
|
"zod": "^3.24.1",
|
|
83
|
-
"@fragments-sdk/context": "0.5.1",
|
|
84
84
|
"@fragments-sdk/core": "1.0.1",
|
|
85
85
|
"@fragments-sdk/govern": "^0.2.1",
|
|
86
|
-
"@fragments-sdk/
|
|
87
|
-
"@fragments-sdk/
|
|
86
|
+
"@fragments-sdk/webmcp": "2.0.1",
|
|
87
|
+
"@fragments-sdk/context": "0.5.1",
|
|
88
|
+
"@fragments-sdk/viewer": "0.2.5"
|
|
88
89
|
},
|
|
89
90
|
"devDependencies": {
|
|
90
91
|
"@types/babel__generator": "^7.6.8",
|
package/src/bin.ts
CHANGED
|
@@ -828,6 +828,11 @@ program
|
|
|
828
828
|
.description('Initialize fragments in a project (zero-config by default)')
|
|
829
829
|
.option('--force', 'Overwrite existing config')
|
|
830
830
|
.option('-y, --yes', 'Non-interactive mode (now the default)')
|
|
831
|
+
.option('--cloud', 'Set up Fragments Cloud governance (zero-config browser auth)')
|
|
832
|
+
.option('--cloud-url <url>', 'Cloud dashboard URL (default: https://app.usefragments.com)')
|
|
833
|
+
.option('--port <port>', 'Localhost port for auth callback (default: 9876)')
|
|
834
|
+
.option('--auth-only', 'Only authenticate, skip project setup')
|
|
835
|
+
.option('--skip-check', 'Skip running the first governance check')
|
|
831
836
|
.option('--configure', 'Interactive mode for theme seeds, snapshots, etc.')
|
|
832
837
|
.option('--scan <path>', 'Scan a TypeScript component directory and generate fragment files')
|
|
833
838
|
.option('--enrich', 'Use AI to fill knowledge fields during --scan (requires API key)')
|
|
@@ -837,6 +842,18 @@ program
|
|
|
837
842
|
.option('--model <model>', 'Override AI model for enrichment')
|
|
838
843
|
.action(async (options) => {
|
|
839
844
|
try {
|
|
845
|
+
// Cloud init — separate flow
|
|
846
|
+
if (options.cloud) {
|
|
847
|
+
const { initCloud } = await import('./commands/init-cloud.js');
|
|
848
|
+
await initCloud({
|
|
849
|
+
url: options.cloudUrl,
|
|
850
|
+
port: options.port ? Number(options.port) : undefined,
|
|
851
|
+
authOnly: options.authOnly,
|
|
852
|
+
skipCheck: options.skipCheck,
|
|
853
|
+
});
|
|
854
|
+
return;
|
|
855
|
+
}
|
|
856
|
+
|
|
840
857
|
const { init } = await import('./commands/init.js');
|
|
841
858
|
const result = await init({
|
|
842
859
|
projectRoot: process.cwd(),
|