slapify 0.0.14 โ†’ 0.0.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +342 -258
  2. package/dist/ai/interpreter.d.ts +13 -0
  3. package/dist/ai/interpreter.js +1 -293
  4. package/dist/browser/agent.js +1 -485
  5. package/dist/cli.js +1 -1315
  6. package/dist/config/loader.js +1 -305
  7. package/dist/index.d.ts +2 -0
  8. package/dist/index.js +1 -260
  9. package/dist/parser/flow.js +1 -117
  10. package/dist/perf/audit.d.ts +215 -0
  11. package/dist/perf/audit.js +1 -0
  12. package/dist/report/generator.d.ts +1 -0
  13. package/dist/report/generator.js +1 -549
  14. package/dist/runner/index.d.ts +14 -1
  15. package/dist/runner/index.js +1 -584
  16. package/dist/task/index.d.ts +5 -0
  17. package/dist/task/index.js +1 -0
  18. package/dist/task/report.d.ts +9 -0
  19. package/dist/task/report.js +1 -0
  20. package/dist/task/runner.d.ts +3 -0
  21. package/dist/task/runner.js +1 -0
  22. package/dist/task/session.d.ts +18 -0
  23. package/dist/task/session.js +1 -0
  24. package/dist/task/tools.d.ts +253 -0
  25. package/dist/task/tools.js +1 -0
  26. package/dist/task/types.d.ts +153 -0
  27. package/dist/task/types.js +1 -0
  28. package/dist/types.d.ts +2 -0
  29. package/dist/types.js +1 -2
  30. package/package.json +25 -15
  31. package/dist/ai/interpreter.d.ts.map +0 -1
  32. package/dist/ai/interpreter.js.map +0 -1
  33. package/dist/browser/agent.d.ts.map +0 -1
  34. package/dist/browser/agent.js.map +0 -1
  35. package/dist/cli.d.ts.map +0 -1
  36. package/dist/cli.js.map +0 -1
  37. package/dist/config/loader.d.ts.map +0 -1
  38. package/dist/config/loader.js.map +0 -1
  39. package/dist/index.d.ts.map +0 -1
  40. package/dist/index.js.map +0 -1
  41. package/dist/parser/flow.d.ts.map +0 -1
  42. package/dist/parser/flow.js.map +0 -1
  43. package/dist/report/generator.d.ts.map +0 -1
  44. package/dist/report/generator.js.map +0 -1
  45. package/dist/runner/index.d.ts.map +0 -1
  46. package/dist/runner/index.js.map +0 -1
  47. package/dist/types.d.ts.map +0 -1
  48. package/dist/types.js.map +0 -1
package/dist/cli.js CHANGED
@@ -1,1316 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import { Command } from "commander";
3
- import chalk from "chalk";
4
- import ora from "ora";
5
- import path from "path";
6
- import fs from "fs";
7
- import dotenv from "dotenv";
8
- import { loadConfig, loadCredentials, getConfigDir, } from "./config/loader.js";
9
- import { parseFlowFile, findFlowFiles, validateFlowFile, getFlowSummary, } from "./parser/flow.js";
10
- import { TestRunner } from "./runner/index.js";
11
- import { ReportGenerator } from "./report/generator.js";
12
- import { BrowserAgent } from "./browser/agent.js";
13
- import { generateText } from "ai";
14
- import { createAnthropic } from "@ai-sdk/anthropic";
15
- import { createOpenAI } from "@ai-sdk/openai";
16
- import { createGoogleGenerativeAI } from "@ai-sdk/google";
17
- import { createMistral } from "@ai-sdk/mistral";
18
- import { createGroq } from "@ai-sdk/groq";
19
- import yaml from "yaml";
20
- // Load environment variables
21
- dotenv.config();
22
- /**
23
- * Get AI model based on config
24
- */
25
- function getModelFromConfig(llmConfig) {
26
- switch (llmConfig.provider) {
27
- case "anthropic": {
28
- const anthropic = createAnthropic({ apiKey: llmConfig.api_key });
29
- return anthropic(llmConfig.model);
30
- }
31
- case "openai": {
32
- const openai = createOpenAI({ apiKey: llmConfig.api_key });
33
- return openai(llmConfig.model);
34
- }
35
- case "google": {
36
- const google = createGoogleGenerativeAI({ apiKey: llmConfig.api_key });
37
- return google(llmConfig.model);
38
- }
39
- case "mistral": {
40
- const mistral = createMistral({ apiKey: llmConfig.api_key });
41
- return mistral(llmConfig.model);
42
- }
43
- case "groq": {
44
- const groq = createGroq({ apiKey: llmConfig.api_key });
45
- return groq(llmConfig.model);
46
- }
47
- case "ollama": {
48
- const ollama = createOpenAI({
49
- apiKey: "ollama",
50
- baseURL: llmConfig.base_url || "http://localhost:11434/v1",
51
- });
52
- return ollama(llmConfig.model);
53
- }
54
- default:
55
- throw new Error(`Unsupported provider: ${llmConfig.provider}`);
56
- }
57
- }
58
- const program = new Command();
59
- program
60
- .name("slapify")
61
- .description("AI-powered test automation using natural language flow files")
62
- .version("0.1.0");
63
- // Init command
64
- program
65
- .command("init")
66
- .description("Initialize Slapify in the current directory")
67
- .option("-y, --yes", "Skip prompts and use defaults")
68
- .action(async (options) => {
69
- const readline = await import("readline");
70
- // Check if already initialized
71
- if (fs.existsSync(".slapify")) {
72
- console.log(chalk.yellow("Slapify is already initialized in this directory."));
73
- console.log(chalk.gray("Delete .slapify folder to reinitialize."));
74
- return;
75
- }
76
- console.log(chalk.blue.bold("\n๐Ÿ–๏ธ Welcome to Slapify!\n"));
77
- console.log(chalk.gray("AI-powered E2E testing that slaps - by slaps.dev\n"));
78
- // Import the new functions
79
- const { findSystemBrowsers, initConfig: doInit } = await import("./config/loader.js");
80
- let provider = "anthropic";
81
- let model;
82
- let browserPath;
83
- let useSystemBrowser;
84
- const providerInfo = {
85
- anthropic: {
86
- name: "Anthropic (Claude)",
87
- envVar: "ANTHROPIC_API_KEY",
88
- defaultModel: "claude-haiku-4-5-20251001",
89
- models: [
90
- {
91
- id: "claude-haiku-4-5-20251001",
92
- name: "Haiku 4.5 - fast & cheap ($1/5M tokens)",
93
- recommended: true,
94
- },
95
- {
96
- id: "claude-sonnet-4-20250514",
97
- name: "Sonnet 4 - more capable ($3/15M tokens)",
98
- },
99
- { id: "custom", name: "Enter custom model ID" },
100
- ],
101
- },
102
- openai: {
103
- name: "OpenAI",
104
- envVar: "OPENAI_API_KEY",
105
- defaultModel: "gpt-4o-mini",
106
- models: [
107
- {
108
- id: "gpt-4o-mini",
109
- name: "GPT-4o Mini - fast & cheap ($0.15/0.6M tokens)",
110
- recommended: true,
111
- },
112
- { id: "gpt-4.1-mini", name: "GPT-4.1 Mini - newer" },
113
- { id: "gpt-4o", name: "GPT-4o - more capable ($2.5/10M tokens)" },
114
- { id: "custom", name: "Enter custom model ID" },
115
- ],
116
- },
117
- google: {
118
- name: "Google (Gemini)",
119
- envVar: "GOOGLE_API_KEY",
120
- defaultModel: "gemini-2.0-flash",
121
- models: [
122
- {
123
- id: "gemini-2.0-flash",
124
- name: "Gemini 2.0 Flash - fastest & cheapest",
125
- recommended: true,
126
- },
127
- { id: "gemini-1.5-flash", name: "Gemini 1.5 Flash - stable" },
128
- { id: "gemini-1.5-pro", name: "Gemini 1.5 Pro - more capable" },
129
- { id: "custom", name: "Enter custom model ID" },
130
- ],
131
- },
132
- mistral: {
133
- name: "Mistral",
134
- envVar: "MISTRAL_API_KEY",
135
- askModel: true,
136
- defaultModel: "mistral-small-latest",
137
- },
138
- groq: {
139
- name: "Groq (Fast inference)",
140
- envVar: "GROQ_API_KEY",
141
- askModel: true,
142
- defaultModel: "llama-3.3-70b-versatile",
143
- },
144
- ollama: {
145
- name: "Ollama (Local)",
146
- envVar: "",
147
- askModel: true,
148
- defaultModel: "llama3",
149
- },
150
- };
151
- if (options.yes) {
152
- // Use defaults
153
- console.log(chalk.gray("Using default settings...\n"));
154
- }
155
- else {
156
- const rl = readline.createInterface({
157
- input: process.stdin,
158
- output: process.stdout,
159
- });
160
- const question = (prompt) => new Promise((resolve) => rl.question(prompt, resolve));
161
- // Step 1: LLM Provider
162
- console.log(chalk.cyan("1. Choose your LLM provider:\n"));
163
- console.log(" 1) Anthropic (Claude) " + chalk.green("- recommended"));
164
- console.log(" 2) OpenAI (GPT-4)");
165
- console.log(" 3) Google (Gemini)");
166
- console.log(" 4) Mistral");
167
- console.log(" 5) Groq " + chalk.gray("- fast & free tier"));
168
- console.log(" 6) Ollama " + chalk.gray("- local, no API key"));
169
- console.log("");
170
- const providerChoice = await question(chalk.white(" Select [1]: "));
171
- const providerMap = {
172
- "1": "anthropic",
173
- "2": "openai",
174
- "3": "google",
175
- "4": "mistral",
176
- "5": "groq",
177
- "6": "ollama",
178
- };
179
- provider = providerMap[providerChoice] || "anthropic";
180
- const info = providerInfo[provider];
181
- console.log(chalk.green(` โœ“ Using ${info.name}\n`));
182
- // Step 1b: Model Selection
183
- if (info.models && info.models.length > 0) {
184
- console.log(chalk.cyan(" Choose model:\n"));
185
- info.models.forEach((m, i) => {
186
- const rec = m.recommended ? chalk.green(" โ† recommended") : "";
187
- console.log(` ${i + 1}) ${m.name}${rec}`);
188
- });
189
- console.log("");
190
- const modelChoice = await question(chalk.white(" Select [1]: "));
191
- const modelIdx = parseInt(modelChoice) - 1 || 0;
192
- const selectedModel = info.models[modelIdx];
193
- if (selectedModel?.id === "custom") {
194
- const customModel = await question(chalk.white(" Enter model ID: "));
195
- model = customModel.trim() || info.defaultModel;
196
- }
197
- else {
198
- model = selectedModel?.id || info.defaultModel;
199
- }
200
- console.log(chalk.green(` โœ“ Using model: ${model}\n`));
201
- }
202
- else if (info.askModel) {
203
- // For Mistral, Groq, Ollama - ask for model ID directly
204
- console.log(chalk.gray(` Enter model ID (default: ${info.defaultModel})`));
205
- if (provider === "ollama") {
206
- console.log(chalk.gray(" Common models: llama3, mistral, codellama, phi3"));
207
- }
208
- else if (provider === "groq") {
209
- console.log(chalk.gray(" Common models: llama-3.3-70b-versatile, mixtral-8x7b-32768"));
210
- }
211
- else if (provider === "mistral") {
212
- console.log(chalk.gray(" Common models: mistral-small-latest, mistral-large-latest"));
213
- }
214
- console.log("");
215
- const modelInput = await question(chalk.white(` Model [${info.defaultModel}]: `));
216
- model = modelInput.trim() || info.defaultModel;
217
- console.log(chalk.green(` โœ“ Using model: ${model}\n`));
218
- if (provider === "ollama") {
219
- console.log(chalk.gray(" Make sure Ollama is running: ollama serve"));
220
- console.log("");
221
- }
222
- }
223
- // Step 2: API Key Verification (skip for Ollama)
224
- if (provider !== "ollama") {
225
- console.log(chalk.cyan("2. API Key verification:\n"));
226
- const envVar = info.envVar;
227
- let apiKey = process.env[envVar];
228
- if (apiKey) {
229
- console.log(chalk.gray(` Found ${envVar} in environment`));
230
- }
231
- else {
232
- console.log(chalk.yellow(` ${envVar} not found in environment`));
233
- console.log(chalk.gray(" You can set it now or add it to your shell config later.\n"));
234
- const keyInput = await question(chalk.white(` Enter API key (or press Enter to skip): `));
235
- if (keyInput.trim()) {
236
- apiKey = keyInput.trim();
237
- }
238
- }
239
- // API key verification loop
240
- let verified = false;
241
- while (!verified) {
242
- if (apiKey) {
243
- const verifyChoice = await question(chalk.white(" Verify API key with test call? (Y/n): "));
244
- if (verifyChoice.toLowerCase() !== "n") {
245
- // Close readline temporarily - ora spinner can interfere with readline
246
- rl.pause();
247
- const verifySpinner = ora(" Verifying API key...").start();
248
- try {
249
- // Make a minimal test call
250
- const testConfig = {
251
- provider,
252
- model: model || info.defaultModel || "test",
253
- api_key: apiKey,
254
- };
255
- const testModel = getModelFromConfig(testConfig);
256
- const response = await generateText({
257
- model: testModel,
258
- prompt: "Reply with only the word 'pong'",
259
- maxTokens: 10,
260
- });
261
- if (response.text.toLowerCase().includes("pong")) {
262
- verifySpinner.succeed(chalk.green("API key verified! โœ“"));
263
- }
264
- else {
265
- verifySpinner.succeed(chalk.green("API key works! (got response)"));
266
- }
267
- verified = true;
268
- }
269
- catch (error) {
270
- verifySpinner.fail(chalk.red("API key verification failed"));
271
- console.log(chalk.red(` Error: ${error.message}\n`));
272
- }
273
- // Resume readline after spinner is done
274
- rl.resume();
275
- if (!verified) {
276
- const retryChoice = await question(chalk.white(" Try a different API key? (Y/n): "));
277
- if (retryChoice.toLowerCase() === "n") {
278
- console.log(chalk.yellow(` Remember to set ${envVar} correctly before running tests.`));
279
- break;
280
- }
281
- const newKey = await question(chalk.white(` Enter API key: `));
282
- if (newKey.trim()) {
283
- apiKey = newKey.trim();
284
- }
285
- else {
286
- console.log(chalk.yellow(" No key entered, skipping.\n"));
287
- break;
288
- }
289
- }
290
- }
291
- else {
292
- console.log(chalk.gray(" Skipping verification\n"));
293
- break;
294
- }
295
- }
296
- else {
297
- console.log(chalk.yellow(`\n Remember to set ${envVar} before running tests.`));
298
- break;
299
- }
300
- }
301
- console.log("");
302
- }
303
- // Step 3: Browser Setup
304
- console.log(chalk.cyan(`${provider === "ollama" ? "2" : "3"}. Browser setup:\n`));
305
- const systemBrowsers = findSystemBrowsers();
306
- if (systemBrowsers.length > 0) {
307
- console.log(" Found browsers on your system:");
308
- systemBrowsers.forEach((b, i) => {
309
- console.log(chalk.gray(` ${i + 1}) ${b.name}`));
310
- });
311
- console.log(chalk.gray(` ${systemBrowsers.length + 1}) Download Chromium (~170MB)`));
312
- console.log(chalk.gray(` ${systemBrowsers.length + 2}) Enter custom path`));
313
- console.log("");
314
- const browserChoice = await question(chalk.white(` Select [1]: `));
315
- const choiceNum = parseInt(browserChoice) || 1;
316
- if (choiceNum <= systemBrowsers.length) {
317
- browserPath = systemBrowsers[choiceNum - 1].path;
318
- useSystemBrowser = true;
319
- console.log(chalk.green(` โœ“ Using ${systemBrowsers[choiceNum - 1].name}\n`));
320
- }
321
- else if (choiceNum === systemBrowsers.length + 2) {
322
- const customPath = await question(chalk.white(" Enter browser path: "));
323
- if (customPath.trim()) {
324
- browserPath = customPath.trim();
325
- useSystemBrowser = true;
326
- console.log(chalk.green(` โœ“ Using custom browser\n`));
327
- }
328
- }
329
- else {
330
- useSystemBrowser = false;
331
- console.log(chalk.green(" โœ“ Will download Chromium on first run\n"));
332
- }
333
- }
334
- else {
335
- console.log(" No browsers found. Options:");
336
- console.log(chalk.gray(" 1) Download Chromium automatically (~170MB)"));
337
- console.log(chalk.gray(" 2) Enter custom browser path"));
338
- console.log("");
339
- const browserChoice = await question(chalk.white(" Select [1]: "));
340
- if (browserChoice === "2") {
341
- const customPath = await question(chalk.white(" Enter browser path: "));
342
- if (customPath.trim()) {
343
- browserPath = customPath.trim();
344
- useSystemBrowser = true;
345
- console.log(chalk.green(" โœ“ Using custom browser\n"));
346
- }
347
- }
348
- else {
349
- useSystemBrowser = false;
350
- console.log(chalk.green(" โœ“ Will download Chromium on first run\n"));
351
- }
352
- }
353
- rl.close();
354
- }
355
- // Initialize
356
- const spinner = ora("Creating configuration...").start();
357
- try {
358
- doInit(process.cwd(), {
359
- provider,
360
- model,
361
- browserPath,
362
- useSystemBrowser,
363
- });
364
- spinner.succeed("Slapify initialized!");
365
- console.log("");
366
- console.log(chalk.green("Created:"));
367
- console.log(" ๐Ÿ“ .slapify/config.yaml - Configuration");
368
- console.log(" ๐Ÿ” .slapify/credentials.yaml - Credentials (gitignored)");
369
- console.log(" ๐Ÿ“ tests/example.flow - Sample test");
370
- console.log("");
371
- const info = providerInfo[provider];
372
- console.log(chalk.yellow("Next steps:"));
373
- console.log("");
374
- if (provider === "ollama") {
375
- console.log(chalk.white(` 1. Make sure Ollama is running:`));
376
- console.log(chalk.cyan(` ollama serve`));
377
- console.log(chalk.cyan(` ollama pull llama3`));
378
- }
379
- else {
380
- console.log(chalk.white(` 1. Set your API key:`));
381
- console.log(chalk.cyan(` export ${info.envVar}=your-key-here`));
382
- }
383
- console.log("");
384
- console.log(chalk.white(` 2. Run the example test:`));
385
- console.log(chalk.cyan(` slapify run tests/example.flow`));
386
- console.log("");
387
- console.log(chalk.white(` 3. Create your own tests:`));
388
- console.log(chalk.cyan(` slapify create my-first-test`));
389
- console.log(chalk.cyan(` slapify generate "test login for myapp.com"`));
390
- console.log("");
391
- console.log(chalk.gray(" Config can be modified anytime in .slapify/config.yaml"));
392
- console.log("");
393
- }
394
- catch (error) {
395
- spinner.fail(error.message);
396
- process.exit(1);
397
- }
398
- });
399
- // Install command (for agent-browser)
400
- program
401
- .command("install")
402
- .description("Install browser dependencies")
403
- .action(() => {
404
- const spinner = ora("Checking agent-browser...").start();
405
- if (BrowserAgent.isInstalled()) {
406
- spinner.succeed("agent-browser is already installed");
407
- }
408
- else {
409
- spinner.text = "Installing agent-browser...";
410
- try {
411
- BrowserAgent.install();
412
- spinner.succeed("Browser dependencies installed!");
413
- }
414
- catch (error) {
415
- spinner.fail(`Installation failed: ${error.message}`);
416
- process.exit(1);
417
- }
418
- }
419
- });
420
- // Run command
421
- program
422
- .command("run [files...]")
423
- .description("Run flow test files")
424
- .option("--headed", "Run browser in headed mode (visible)")
425
- .option("--report [format]", "Generate report folder (html, markdown, json)")
426
- .option("--output <dir>", "Output directory for reports", "./test-reports")
427
- .option("--credentials <profile>", "Default credentials profile to use")
428
- .option("-p, --parallel", "Run tests in parallel")
429
- .option("-w, --workers <n>", "Number of parallel workers (default: 4)", "4")
430
- .action(async (files, options) => {
431
- try {
432
- // Load configuration
433
- const configDir = getConfigDir();
434
- if (!configDir) {
435
- console.log(chalk.red('No .slapify directory found. Run "slapify init" first.'));
436
- process.exit(1);
437
- }
438
- const config = loadConfig(configDir);
439
- const credentials = loadCredentials(configDir);
440
- // Apply CLI options
441
- if (options.headed) {
442
- config.browser = { ...config.browser, headless: false };
443
- }
444
- // Only enable screenshots if report is requested
445
- const generateReport = options.report !== undefined;
446
- config.report = {
447
- ...config.report,
448
- format: typeof options.report === "string" ? options.report : "html",
449
- output_dir: options.output,
450
- screenshots: generateReport, // Only take screenshots for reports
451
- };
452
- // Find flow files
453
- let flowFiles = [];
454
- if (files.length === 0) {
455
- // Run all flow files in tests directory
456
- const testsDir = path.join(process.cwd(), "tests");
457
- if (fs.existsSync(testsDir)) {
458
- flowFiles = await findFlowFiles(testsDir);
459
- }
460
- }
461
- else {
462
- for (const file of files) {
463
- if (fs.statSync(file).isDirectory()) {
464
- const found = await findFlowFiles(file);
465
- flowFiles.push(...found);
466
- }
467
- else {
468
- flowFiles.push(file);
469
- }
470
- }
471
- }
472
- if (flowFiles.length === 0) {
473
- console.log(chalk.yellow("No .flow files found to run."));
474
- process.exit(0);
475
- }
476
- const reporter = new ReportGenerator(config.report);
477
- const results = [];
478
- const isParallel = options.parallel && flowFiles.length > 1;
479
- const workers = parseInt(options.workers) || 4;
480
- if (isParallel) {
481
- // Parallel execution
482
- console.log(chalk.blue.bold(`\nโ”โ”โ” Running ${flowFiles.length} tests in parallel (${workers} workers) โ”โ”โ”\n`));
483
- const pending = [...flowFiles];
484
- const running = new Map();
485
- const testStatus = new Map();
486
- // Initialize status
487
- for (const file of flowFiles) {
488
- const name = path.basename(file, ".flow");
489
- testStatus.set(name, chalk.gray("โณ pending"));
490
- }
491
- const printStatus = () => {
492
- // Clear and reprint status
493
- process.stdout.write("\x1B[" + flowFiles.length + "A"); // Move cursor up
494
- for (const file of flowFiles) {
495
- const name = path.basename(file, ".flow");
496
- const status = testStatus.get(name) || "";
497
- process.stdout.write("\x1B[2K"); // Clear line
498
- console.log(` ${name}: ${status}`);
499
- }
500
- };
501
- // Print initial status
502
- for (const file of flowFiles) {
503
- const name = path.basename(file, ".flow");
504
- console.log(` ${name}: ${testStatus.get(name)}`);
505
- }
506
- const runTest = async (file) => {
507
- const flow = parseFlowFile(file);
508
- const name = flow.name;
509
- testStatus.set(name, chalk.cyan("โ–ถ running..."));
510
- printStatus();
511
- try {
512
- const runner = new TestRunner(config, credentials);
513
- const result = await runner.runFlow(flow);
514
- results.push(result);
515
- if (result.status === "passed") {
516
- testStatus.set(name, chalk.green(`โœ“ passed (${result.passedSteps}/${result.totalSteps} steps, ${(result.duration / 1000).toFixed(1)}s)`));
517
- }
518
- else {
519
- testStatus.set(name, chalk.red(`โœ— failed (${result.failedSteps} failed, ${result.passedSteps} passed)`));
520
- }
521
- }
522
- catch (error) {
523
- testStatus.set(name, chalk.red(`โœ— error: ${error.message}`));
524
- }
525
- printStatus();
526
- };
527
- // Process with worker limit
528
- while (pending.length > 0 || running.size > 0) {
529
- // Start new tasks up to worker limit
530
- while (pending.length > 0 && running.size < workers) {
531
- const file = pending.shift();
532
- const promise = runTest(file).then(() => {
533
- running.delete(file);
534
- });
535
- running.set(file, promise);
536
- }
537
- // Wait for at least one to complete
538
- if (running.size > 0) {
539
- await Promise.race(running.values());
540
- }
541
- }
542
- console.log(""); // Extra newline after parallel run
543
- }
544
- else {
545
- // Sequential execution
546
- for (const file of flowFiles) {
547
- const flow = parseFlowFile(file);
548
- const summary = getFlowSummary(flow);
549
- // Print test header
550
- console.log("");
551
- console.log(chalk.blue.bold(`โ”โ”โ” ${flow.name} โ”โ”โ”`));
552
- console.log(chalk.gray(` ${summary.totalSteps} steps (${summary.requiredSteps} required, ${summary.optionalSteps} optional)`));
553
- console.log("");
554
- try {
555
- const runner = new TestRunner(config, credentials);
556
- const result = await runner.runFlow(flow, (stepResult) => {
557
- // Real-time step output
558
- const step = stepResult.step;
559
- const statusIcon = stepResult.status === "passed"
560
- ? chalk.green("โœ“")
561
- : stepResult.status === "failed"
562
- ? chalk.red("โœ—")
563
- : chalk.yellow("โŠ˜");
564
- const optionalTag = step.optional
565
- ? chalk.gray(" [optional]")
566
- : "";
567
- const retriedTag = stepResult.retried
568
- ? chalk.yellow(" [retried]")
569
- : "";
570
- const duration = chalk.gray(`(${(stepResult.duration / 1000).toFixed(1)}s)`);
571
- console.log(` ${statusIcon} ${step.text}${optionalTag}${retriedTag} ${duration}`);
572
- // Show error inline if failed
573
- if (stepResult.status === "failed" && stepResult.error) {
574
- console.log(chalk.red(` โ””โ”€ ${stepResult.error}`));
575
- }
576
- // Show assumptions if any
577
- if (stepResult.assumptions && stepResult.assumptions.length > 0) {
578
- for (const assumption of stepResult.assumptions) {
579
- console.log(chalk.gray(` โ””โ”€ ๐Ÿ’ก ${assumption}`));
580
- }
581
- }
582
- });
583
- results.push(result);
584
- // Print test summary
585
- console.log("");
586
- if (result.status === "passed") {
587
- console.log(chalk.green.bold(` โœ“ PASSED`) +
588
- chalk.gray(` (${result.passedSteps}/${result.totalSteps} steps in ${(result.duration / 1000).toFixed(1)}s)`));
589
- }
590
- else {
591
- console.log(chalk.red.bold(` โœ— FAILED`) +
592
- chalk.gray(` (${result.failedSteps} failed, ${result.passedSteps} passed)`));
593
- }
594
- // Auto-handled info
595
- if (result.autoHandled.length > 0) {
596
- console.log(chalk.gray(` โ„น Auto-handled: ${result.autoHandled.join(", ")}`));
597
- }
598
- }
599
- catch (error) {
600
- console.log(chalk.red(` โœ— ERROR: ${error.message}`));
601
- }
602
- }
603
- }
604
- // Final summary
605
- console.log("");
606
- console.log(chalk.blue.bold("โ”โ”โ” Summary โ”โ”โ”"));
607
- const passed = results.filter((r) => r.status === "passed").length;
608
- const failed = results.filter((r) => r.status === "failed").length;
609
- const totalSteps = results.reduce((sum, r) => sum + r.totalSteps, 0);
610
- const passedSteps = results.reduce((sum, r) => sum + r.passedSteps, 0);
611
- console.log(chalk.gray(` ${results.length} test file(s), ${totalSteps} total steps`));
612
- if (failed === 0) {
613
- console.log(chalk.green.bold(` โœ“ All ${passed} test(s) passed! (${passedSteps}/${totalSteps} steps)`));
614
- }
615
- else {
616
- console.log(chalk.red.bold(` โœ— ${failed}/${results.length} test(s) failed`));
617
- }
618
- // Generate suite report if requested and multiple files
619
- if (generateReport && results.length > 0) {
620
- let reportPath;
621
- if (results.length === 1) {
622
- reportPath = reporter.saveAsFolder(results[0]);
623
- }
624
- else {
625
- reportPath = reporter.saveSuiteAsFolder(results);
626
- }
627
- console.log(chalk.cyan(`\n ๐Ÿ“„ Report: ${reportPath}`));
628
- }
629
- console.log("");
630
- if (failed > 0) {
631
- process.exit(1);
632
- }
633
- }
634
- catch (error) {
635
- console.error(chalk.red(`Error: ${error.message}`));
636
- process.exit(1);
637
- }
638
- });
639
- // Create command
640
- program
641
- .command("create <name>")
642
- .description("Create a new flow file")
643
- .option("-d, --dir <directory>", "Directory to create flow in", "tests")
644
- .action(async (name, options) => {
645
- const readline = await import("readline");
646
- // Ensure directory exists
647
- const dir = options.dir;
648
- if (!fs.existsSync(dir)) {
649
- fs.mkdirSync(dir, { recursive: true });
650
- }
651
- // Generate filename
652
- const filename = name.endsWith(".flow") ? name : `${name}.flow`;
653
- const filepath = path.join(dir, filename);
654
- if (fs.existsSync(filepath)) {
655
- console.log(chalk.red(`File already exists: ${filepath}`));
656
- process.exit(1);
657
- }
658
- console.log(chalk.blue(`\nCreating: ${filepath}`));
659
- console.log(chalk.gray("Enter your test steps (one per line). Empty line to finish.\n"));
660
- const rl = readline.createInterface({
661
- input: process.stdin,
662
- output: process.stdout,
663
- });
664
- const lines = [`# ${name}`, ""];
665
- let lineNum = 1;
666
- const askLine = () => {
667
- return new Promise((resolve) => {
668
- rl.question(chalk.cyan(`${lineNum}. `), (answer) => {
669
- resolve(answer);
670
- });
671
- });
672
- };
673
- while (true) {
674
- const line = await askLine();
675
- if (line === "") {
676
- break;
677
- }
678
- lines.push(line);
679
- lineNum++;
680
- }
681
- rl.close();
682
- if (lines.length <= 2) {
683
- console.log(chalk.yellow("\nNo steps entered. File not created."));
684
- return;
685
- }
686
- // Write file
687
- fs.writeFileSync(filepath, lines.join("\n") + "\n");
688
- console.log(chalk.green(`\nโœ“ Created: ${filepath}`));
689
- console.log(chalk.gray(` ${lineNum - 1} steps`));
690
- console.log(chalk.gray(`\nRun with: slapify run ${filepath}`));
691
- });
692
- // Generate command - AI-powered flow generation
693
- program
694
- .command("generate <prompt>")
695
- .alias("gen")
696
- .description("Generate a flow file from a natural language prompt")
697
- .option("-d, --dir <directory>", "Directory to save flow", "tests")
698
- .option("--headed", "Show browser while analyzing")
699
- .action(async (prompt, options) => {
700
- const configDir = getConfigDir();
701
- if (!configDir) {
702
- console.log(chalk.red('No .slapify directory found. Run "slapify init" first.'));
703
- process.exit(1);
704
- }
705
- const config = loadConfig(configDir);
706
- const readline = await import("readline");
707
- console.log(chalk.blue("\n๐Ÿค– AI Flow Generator\n"));
708
- // Step 1: Extract URL from prompt using AI
709
- let spinner = ora("Analyzing prompt...").start();
710
- const urlResponse = await generateText({
711
- model: getModelFromConfig(config.llm),
712
- prompt: `Extract the URL from this test request. If there's no URL mentioned, respond with "NO_URL".
713
-
714
- Request: "${prompt}"
715
-
716
- Respond with ONLY the URL (e.g., https://example.com) or "NO_URL". Nothing else.`,
717
- maxTokens: 100,
718
- });
719
- let url = urlResponse.text.trim();
720
- spinner.stop();
721
- // Step 2: If no URL, ask user
722
- if (url === "NO_URL" || !url.startsWith("http")) {
723
- const rl = readline.createInterface({
724
- input: process.stdin,
725
- output: process.stdout,
726
- });
727
- url = await new Promise((resolve) => {
728
- rl.question(chalk.cyan("Enter the URL to test: "), (answer) => {
729
- rl.close();
730
- resolve(answer.trim());
731
- });
732
- });
733
- if (!url) {
734
- console.log(chalk.red("No URL provided. Aborting."));
735
- process.exit(1);
736
- }
737
- }
738
- console.log(chalk.gray(`URL: ${url}\n`));
739
- // Step 3: Open browser and get page snapshot
740
- spinner = ora("Opening browser and analyzing page...").start();
741
- const browser = new BrowserAgent({
742
- ...config.browser,
743
- headless: !options.headed,
744
- });
745
- try {
746
- await browser.navigate(url);
747
- await browser.wait(2000); // Wait for page to load
748
- const snapshot = await browser.snapshot(true);
749
- const pageTitle = await browser.getTitle();
750
- spinner.succeed("Page analyzed");
751
- // Step 4: Generate test steps using AI
752
- spinner = ora("Generating test steps...").start();
753
- const generationResponse = await generateText({
754
- model: getModelFromConfig(config.llm),
755
- system: `You are a test automation expert. Generate clear, actionable test steps for a .flow file.
756
-
757
- Rules:
758
- - Each step should be a single action or verification
759
- - Use natural language that describes WHAT to do, not HOW
760
- - Include [Optional] prefix for steps that might not always apply (popups, banners)
761
- - Include verification steps to confirm actions worked
762
- - Use "If X appears, do Y" for conditional handling
763
- - Keep steps concise but clear
764
- - Start with navigation to the URL
765
- - Generate a suitable filename (lowercase, hyphenated, no extension)
766
-
767
- Output format:
768
- FILENAME: suggested-name
769
- STEPS:
770
- Go to <url>
771
- Step 2 here
772
- Step 3 here
773
- ...`,
774
- prompt: `Generate test steps for this request:
775
-
776
- "${prompt}"
777
-
778
- Target URL: ${url}
779
- Page Title: ${pageTitle}
780
-
781
- Current page structure:
782
- ${snapshot}
783
-
784
- Generate practical test steps that accomplish the user's goal.`,
785
- maxTokens: 1500,
786
- });
787
- spinner.succeed("Test steps generated");
788
- // Parse the response
789
- const responseText = generationResponse.text;
790
- const filenameMatch = responseText.match(/FILENAME:\s*(.+)/i);
791
- const stepsMatch = responseText.match(/STEPS:\s*([\s\S]+)/i);
792
- let filename = filenameMatch
793
- ? filenameMatch[1]
794
- .trim()
795
- .replace(/[^a-z0-9-]/gi, "-")
796
- .toLowerCase()
797
- : "generated-test";
798
- if (!filename.endsWith(".flow")) {
799
- filename += ".flow";
800
- }
801
- const steps = stepsMatch
802
- ? stepsMatch[1].trim()
803
- : responseText.replace(/FILENAME:.+/i, "").trim();
804
- // Close browser
805
- await browser.close();
806
- // Step 5: Show generated steps and confirm
807
- console.log(chalk.blue("\nโ”โ”โ” Generated Flow โ”โ”โ”\n"));
808
- console.log(chalk.white(steps));
809
- console.log(chalk.blue("\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\n"));
810
- const rl = readline.createInterface({
811
- input: process.stdin,
812
- output: process.stdout,
813
- });
814
- const confirm = await new Promise((resolve) => {
815
- rl.question(chalk.cyan(`Save as ${options.dir}/${filename}? (Y/n/edit): `), (answer) => {
816
- rl.close();
817
- resolve(answer.trim().toLowerCase());
818
- });
819
- });
820
- if (confirm === "n" || confirm === "no") {
821
- console.log(chalk.yellow("Cancelled."));
822
- return;
823
- }
824
- if (confirm === "e" || confirm === "edit") {
825
- // Let user edit the filename
826
- const rl2 = readline.createInterface({
827
- input: process.stdin,
828
- output: process.stdout,
829
- });
830
- filename = await new Promise((resolve) => {
831
- rl2.question(chalk.cyan("Filename: "), (answer) => {
832
- rl2.close();
833
- const name = answer.trim() || filename;
834
- resolve(name.endsWith(".flow") ? name : name + ".flow");
835
- });
836
- });
837
- }
838
- // Step 6: Save the file
839
- const dir = options.dir;
840
- if (!fs.existsSync(dir)) {
841
- fs.mkdirSync(dir, { recursive: true });
842
- }
843
- const filepath = path.join(dir, filename);
844
- const content = `# ${filename
845
- .replace(".flow", "")
846
- .replace(/-/g, " ")}\n# Generated from: ${prompt}\n\n${steps}\n`;
847
- fs.writeFileSync(filepath, content);
848
- console.log(chalk.green(`\nโœ“ Saved: ${filepath}`));
849
- console.log(chalk.gray(`\nRun with: slapify run ${filepath}`));
850
- }
851
- catch (error) {
852
- spinner.fail("Error");
853
- await browser.close();
854
- console.error(chalk.red(`Error: ${error.message}`));
855
- process.exit(1);
856
- }
857
- });
858
- // Fix command - analyze and fix failing tests
859
- program
860
- .command("fix <file>")
861
- .description("Analyze a failing test and suggest/apply fixes")
862
- .option("--auto", "Automatically apply suggested fixes without confirmation")
863
- .option("--headed", "Run browser in headed mode for debugging")
864
- .action(async (file, options) => {
865
- const configDir = getConfigDir();
866
- if (!configDir) {
867
- console.log(chalk.red('No .slapify directory found. Run "slapify init" first.'));
868
- process.exit(1);
869
- }
870
- if (!fs.existsSync(file)) {
871
- console.log(chalk.red(`File not found: ${file}`));
872
- process.exit(1);
873
- }
874
- const config = loadConfig(configDir);
875
- const credentials = loadCredentials(configDir);
876
- if (options.headed) {
877
- config.browser = { ...config.browser, headless: false };
878
- }
879
- // Enable screenshots for diagnosis
880
- config.report = { ...config.report, screenshots: true };
881
- const readline = await import("readline");
882
- let spinner = ora("Running test to identify failures...").start();
883
- try {
884
- // Step 1: Run the test to see what fails
885
- const flow = parseFlowFile(file);
886
- const runner = new TestRunner(config, credentials);
887
- const failedSteps = [];
888
- const result = await runner.runFlow(flow, (stepResult) => {
889
- if (stepResult.status === "failed" && stepResult.error) {
890
- failedSteps.push({
891
- step: stepResult.step.text,
892
- error: stepResult.error,
893
- line: stepResult.step.line,
894
- screenshot: stepResult.screenshot,
895
- });
896
- }
897
- });
898
- if (result.status === "passed") {
899
- spinner.succeed("Test passed! No fixes needed.");
900
- return;
901
- }
902
- spinner.info(`Found ${failedSteps.length} failing step(s)`);
903
- if (failedSteps.length === 0) {
904
- console.log(chalk.yellow("No specific step failures to fix."));
905
- return;
906
- }
907
- // Step 2: Read the original flow file
908
- const originalContent = fs.readFileSync(file, "utf-8");
909
- const lines = originalContent.split("\n");
910
- // Step 3: Use AI to analyze and suggest fixes
911
- spinner = ora("Analyzing failures and generating fixes...").start();
912
- const failureDetails = failedSteps
913
- .map((f) => `Line ${f.line}: "${f.step}"\n Error: ${f.error}`)
914
- .join("\n\n");
915
- const analysisResponse = await generateText({
916
- model: getModelFromConfig(config.llm),
917
- system: `You are a test automation expert. Analyze failing test steps and suggest fixes.
918
-
919
- Original flow file:
920
- \`\`\`
921
- ${originalContent}
922
- \`\`\`
923
-
924
- Failing steps:
925
- ${failureDetails}
926
-
927
- Based on the errors, suggest fixes for the flow file. Common issues and fixes:
928
- 1. Element not found โ†’ Try more descriptive text, add wait, or make step optional
929
- 2. Timeout โ†’ Add explicit wait or increase timeout
930
- 3. Navigation error โ†’ Add wait after navigation, or split into smaller steps
931
- 4. Element obscured โ†’ Add step to close popup/modal first
932
- 5. Stale element โ†’ Add wait for page to stabilize
933
-
934
- Respond with JSON:
935
- {
936
- "analysis": "Brief explanation of what's wrong",
937
- "fixes": [
938
- {
939
- "line": 5,
940
- "original": "Click the submit button",
941
- "fixed": "Click the Submit button",
942
- "reason": "Button text is capitalized"
943
- }
944
- ],
945
- "additions": [
946
- {
947
- "afterLine": 4,
948
- "step": "[Optional] Wait for page to load",
949
- "reason": "Page might still be loading"
950
- }
951
- ]
952
- }`,
953
- prompt: "Analyze the failures and suggest specific fixes.",
954
- maxTokens: 1500,
955
- });
956
- spinner.succeed("Analysis complete");
957
- // Parse the response
958
- const jsonMatch = analysisResponse.text.match(/\{[\s\S]*\}/);
959
- if (!jsonMatch) {
960
- console.log(chalk.red("Could not parse AI response"));
961
- return;
962
- }
963
- const suggestions = JSON.parse(jsonMatch[0]);
964
- // Step 4: Display suggestions
965
- console.log(chalk.blue("\nโ”โ”โ” Analysis โ”โ”โ”\n"));
966
- console.log(chalk.white(suggestions.analysis));
967
- if (suggestions.fixes?.length > 0 || suggestions.additions?.length > 0) {
968
- console.log(chalk.blue("\nโ”โ”โ” Suggested Fixes โ”โ”โ”\n"));
969
- if (suggestions.fixes?.length > 0) {
970
- for (const fix of suggestions.fixes) {
971
- console.log(chalk.yellow(`Line ${fix.line}:`));
972
- console.log(chalk.red(` - ${fix.original}`));
973
- console.log(chalk.green(` + ${fix.fixed}`));
974
- console.log(chalk.gray(` Reason: ${fix.reason}\n`));
975
- }
976
- }
977
- if (suggestions.additions?.length > 0) {
978
- console.log(chalk.yellow("New steps to add:"));
979
- for (const add of suggestions.additions) {
980
- console.log(chalk.green(` + After line ${add.afterLine}: ${add.step}`));
981
- console.log(chalk.gray(` Reason: ${add.reason}\n`));
982
- }
983
- }
984
- // Step 5: Apply fixes
985
- let shouldApply = options.auto;
986
- if (!shouldApply) {
987
- const rl = readline.createInterface({
988
- input: process.stdin,
989
- output: process.stdout,
990
- });
991
- const answer = await new Promise((resolve) => {
992
- rl.question(chalk.cyan("Apply these fixes? (y/N): "), (answer) => {
993
- rl.close();
994
- resolve(answer.trim().toLowerCase());
995
- });
996
- });
997
- shouldApply = answer === "y" || answer === "yes";
998
- }
999
- if (shouldApply) {
1000
- // Apply fixes to lines
1001
- let newLines = [...lines];
1002
- const lineOffsets = new Map(); // Track line number changes
1003
- // Apply modifications first
1004
- if (suggestions.fixes) {
1005
- for (const fix of suggestions.fixes) {
1006
- const lineIdx = fix.line - 1;
1007
- if (lineIdx >= 0 && lineIdx < newLines.length) {
1008
- newLines[lineIdx] = fix.fixed;
1009
- }
1010
- }
1011
- }
1012
- // Apply additions (in reverse order to maintain line numbers)
1013
- if (suggestions.additions) {
1014
- const sortedAdditions = [...suggestions.additions].sort((a, b) => b.afterLine - a.afterLine);
1015
- for (const add of sortedAdditions) {
1016
- const afterIdx = add.afterLine;
1017
- newLines.splice(afterIdx, 0, add.step);
1018
- }
1019
- }
1020
- // Write the fixed file
1021
- const newContent = newLines.join("\n");
1022
- // Backup original
1023
- const backupPath = file + ".backup";
1024
- fs.writeFileSync(backupPath, originalContent);
1025
- // Write fixed version
1026
- fs.writeFileSync(file, newContent);
1027
- console.log(chalk.green(`\nโœ“ Fixes applied to ${file}`));
1028
- console.log(chalk.gray(` Backup saved to ${backupPath}`));
1029
- console.log(chalk.gray(`\nRun again with: slapify run ${file}`));
1030
- }
1031
- else {
1032
- console.log(chalk.yellow("No changes made."));
1033
- }
1034
- }
1035
- else {
1036
- console.log(chalk.yellow("\nNo automatic fixes suggested."));
1037
- console.log(chalk.gray("The failures may require manual investigation."));
1038
- }
1039
- }
1040
- catch (error) {
1041
- spinner.fail("Error");
1042
- console.error(chalk.red(`Error: ${error.message}`));
1043
- process.exit(1);
1044
- }
1045
- });
1046
- // Validate command
1047
- program
1048
- .command("validate [files...]")
1049
- .description("Validate flow files for syntax issues")
1050
- .action(async (files) => {
1051
- let flowFiles = [];
1052
- if (files.length === 0) {
1053
- const testsDir = path.join(process.cwd(), "tests");
1054
- if (fs.existsSync(testsDir)) {
1055
- flowFiles = await findFlowFiles(testsDir);
1056
- }
1057
- }
1058
- else {
1059
- flowFiles = files;
1060
- }
1061
- if (flowFiles.length === 0) {
1062
- console.log(chalk.yellow("No .flow files found."));
1063
- return;
1064
- }
1065
- let hasWarnings = false;
1066
- for (const file of flowFiles) {
1067
- try {
1068
- const flow = parseFlowFile(file);
1069
- const warnings = validateFlowFile(flow);
1070
- const summary = getFlowSummary(flow);
1071
- if (warnings.length > 0) {
1072
- hasWarnings = true;
1073
- console.log(chalk.yellow(`โš ๏ธ ${file}`));
1074
- for (const warning of warnings) {
1075
- console.log(chalk.yellow(` ${warning}`));
1076
- }
1077
- }
1078
- else {
1079
- console.log(chalk.green(`โœ… ${file}`));
1080
- console.log(chalk.gray(` ${summary.totalSteps} steps (${summary.requiredSteps} required, ${summary.optionalSteps} optional)`));
1081
- }
1082
- }
1083
- catch (error) {
1084
- console.log(chalk.red(`โŒ ${file}`));
1085
- console.log(chalk.red(` ${error.message}`));
1086
- hasWarnings = true;
1087
- }
1088
- }
1089
- if (hasWarnings) {
1090
- process.exit(1);
1091
- }
1092
- });
1093
- // List command
1094
- program
1095
- .command("list")
1096
- .description("List all flow files")
1097
- .action(async () => {
1098
- const testsDir = path.join(process.cwd(), "tests");
1099
- if (!fs.existsSync(testsDir)) {
1100
- console.log(chalk.yellow("No tests directory found."));
1101
- return;
1102
- }
1103
- const flowFiles = await findFlowFiles(testsDir);
1104
- if (flowFiles.length === 0) {
1105
- console.log(chalk.yellow("No .flow files found."));
1106
- return;
1107
- }
1108
- console.log(chalk.blue(`\nFound ${flowFiles.length} flow file(s):\n`));
1109
- for (const file of flowFiles) {
1110
- const flow = parseFlowFile(file);
1111
- const summary = getFlowSummary(flow);
1112
- const relativePath = path.relative(process.cwd(), file);
1113
- console.log(` ${chalk.white(relativePath)}`);
1114
- console.log(chalk.gray(` ${summary.totalSteps} steps (${summary.requiredSteps} required, ${summary.optionalSteps} optional)`));
1115
- }
1116
- console.log("");
1117
- });
1118
- // Credentials command
1119
- program
1120
- .command("credentials")
1121
- .description("List configured credential profiles")
1122
- .action(() => {
1123
- const configDir = getConfigDir();
1124
- if (!configDir) {
1125
- console.log(chalk.red('No .slapify directory found. Run "slapify init" first.'));
1126
- process.exit(1);
1127
- }
1128
- const credentials = loadCredentials(configDir);
1129
- const profiles = Object.keys(credentials.profiles);
1130
- if (profiles.length === 0) {
1131
- console.log(chalk.yellow("No credential profiles configured."));
1132
- console.log(chalk.gray("Edit .slapify/credentials.yaml to add profiles."));
1133
- return;
1134
- }
1135
- console.log(chalk.blue(`\nConfigured credential profiles:\n`));
1136
- for (const name of profiles) {
1137
- const profile = credentials.profiles[name];
1138
- console.log(` ${chalk.white(name)} (${profile.type})`);
1139
- if (profile.username) {
1140
- console.log(chalk.gray(` username: ${profile.username}`));
1141
- }
1142
- if (profile.email) {
1143
- console.log(chalk.gray(` email: ${profile.email}`));
1144
- }
1145
- if (profile.totp_secret) {
1146
- console.log(chalk.gray(` 2FA: TOTP configured`));
1147
- }
1148
- if (profile.fixed_otp) {
1149
- console.log(chalk.gray(` 2FA: Fixed OTP configured`));
1150
- }
1151
- }
1152
- console.log("");
1153
- });
1154
- // Fix credentials YAML (localStorage/sessionStorage saved as JSON strings)
1155
- function normalizeStorage(v) {
1156
- if (typeof v === "string") {
1157
- try {
1158
- v = JSON.parse(v);
1159
- }
1160
- catch {
1161
- return {};
1162
- }
1163
- }
1164
- if (!v || typeof v !== "object" || Array.isArray(v))
1165
- return {};
1166
- const out = {};
1167
- for (const [k, val] of Object.entries(v)) {
1168
- out[String(k)] = typeof val === "string" ? val : JSON.stringify(val);
1169
- }
1170
- return out;
1171
- }
1172
- function fixCredentialsFile(filePath, dryRun) {
1173
- const resolved = path.resolve(filePath);
1174
- if (!fs.existsSync(resolved)) {
1175
- console.log(chalk.yellow(` Skip (not found): ${resolved}`));
1176
- return false;
1177
- }
1178
- const content = fs.readFileSync(resolved, "utf-8");
1179
- let data;
1180
- try {
1181
- data = yaml.parse(content);
1182
- }
1183
- catch (e) {
1184
- console.log(chalk.red(` Invalid YAML: ${resolved}`));
1185
- console.log(chalk.gray(` ${e.message}`));
1186
- return false;
1187
- }
1188
- if (!data || !data.profiles || typeof data.profiles !== "object") {
1189
- console.log(chalk.yellow(` No profiles in: ${resolved}`));
1190
- return false;
1191
- }
1192
- let changed = false;
1193
- for (const [name, profile] of Object.entries(data.profiles)) {
1194
- if (profile.type !== "inject")
1195
- continue;
1196
- const needLocal = typeof profile.localStorage === "string" ||
1197
- (profile.localStorage &&
1198
- (Array.isArray(profile.localStorage) ||
1199
- typeof profile.localStorage !== "object"));
1200
- const needSession = typeof profile.sessionStorage === "string" ||
1201
- (profile.sessionStorage &&
1202
- (Array.isArray(profile.sessionStorage) ||
1203
- typeof profile.sessionStorage !== "object"));
1204
- if (!needLocal && !needSession)
1205
- continue;
1206
- data.profiles[name] = {
1207
- ...profile,
1208
- ...(needLocal && {
1209
- localStorage: normalizeStorage(profile.localStorage),
1210
- }),
1211
- ...(needSession && {
1212
- sessionStorage: normalizeStorage(profile.sessionStorage),
1213
- }),
1214
- };
1215
- changed = true;
1216
- }
1217
- if (!changed) {
1218
- console.log(chalk.gray(` No changes needed: ${resolved}`));
1219
- return false;
1220
- }
1221
- if (dryRun) {
1222
- console.log(chalk.cyan(` Would fix: ${resolved}`));
1223
- return true;
1224
- }
1225
- const backupPath = resolved + ".backup";
1226
- fs.copyFileSync(resolved, backupPath);
1227
- fs.writeFileSync(resolved, yaml.stringify(data, { indent: 2, lineWidth: 0 }));
1228
- console.log(chalk.green(` Fixed: ${resolved}`));
1229
- console.log(chalk.gray(` Backup: ${backupPath}`));
1230
- return true;
1231
- }
1232
- program
1233
- .command("fix-credentials [files...]")
1234
- .description("Fix credential YAML files where localStorage/sessionStorage were saved as JSON strings")
1235
- .option("--dry-run", "Only print what would be fixed")
1236
- .action((files, options) => {
1237
- const toFix = [];
1238
- if (files && files.length > 0) {
1239
- toFix.push(...files.map((f) => path.resolve(f)));
1240
- }
1241
- else {
1242
- const cwd = process.cwd();
1243
- toFix.push(path.join(cwd, "temp_credentials.yaml"));
1244
- const configDir = getConfigDir();
1245
- if (configDir) {
1246
- toFix.push(path.join(configDir, "credentials.yaml"));
1247
- }
1248
- }
1249
- console.log(chalk.blue("\n๐Ÿ”ง Fix credential YAML files\n"));
1250
- if (options.dryRun) {
1251
- console.log(chalk.gray(" (dry run โ€“ no files will be modified)\n"));
1252
- }
1253
- let fixed = 0;
1254
- for (const f of toFix) {
1255
- if (fixCredentialsFile(f, !!options.dryRun))
1256
- fixed++;
1257
- }
1258
- if (fixed === 0 && toFix.length > 0) {
1259
- console.log(chalk.gray("\n No files needed fixing."));
1260
- }
1261
- console.log("");
1262
- });
1263
- // Interactive mode
1264
- program
1265
- .command("interactive [url]")
1266
- .alias("i")
1267
- .description("Run steps interactively")
1268
- .option("--headed", "Run browser in headed mode")
1269
- .action(async (url, options) => {
1270
- console.log(chalk.blue("\n๐Ÿงช Slapify Interactive Mode"));
1271
- console.log(chalk.gray('Type test steps and press Enter to execute. Type "exit" to quit.\n'));
1272
- const configDir = getConfigDir();
1273
- if (!configDir) {
1274
- console.log(chalk.red('No .slapify directory found. Run "slapify init" first.'));
1275
- process.exit(1);
1276
- }
1277
- const config = loadConfig(configDir);
1278
- const credentials = loadCredentials(configDir);
1279
- if (options.headed) {
1280
- config.browser = { ...config.browser, headless: false };
1281
- }
1282
- const runner = new TestRunner(config, credentials);
1283
- if (url) {
1284
- console.log(chalk.gray(`Navigating to ${url}...`));
1285
- // Would navigate here
1286
- }
1287
- // Simple readline interface
1288
- const readline = await import("readline");
1289
- const rl = readline.createInterface({
1290
- input: process.stdin,
1291
- output: process.stdout,
1292
- });
1293
- const prompt = () => {
1294
- rl.question(chalk.cyan("> "), async (input) => {
1295
- const trimmed = input.trim();
1296
- if (trimmed.toLowerCase() === "exit" ||
1297
- trimmed.toLowerCase() === "quit") {
1298
- console.log(chalk.gray("\nGoodbye!"));
1299
- rl.close();
1300
- process.exit(0);
1301
- }
1302
- if (!trimmed) {
1303
- prompt();
1304
- return;
1305
- }
1306
- // Execute the step
1307
- console.log(chalk.gray(`Executing: ${trimmed}`));
1308
- // Would execute step here
1309
- console.log(chalk.green("โœ“ Done"));
1310
- prompt();
1311
- });
1312
- };
1313
- prompt();
1314
- });
1315
- program.parse();
1316
- //# sourceMappingURL=cli.js.map
2
+ import{Command as e}from"commander";import o from"chalk";import s from"ora";import n from"path";import t from"fs";import l from"dotenv";import{loadConfig as r,loadCredentials as a,getConfigDir as i}from"./config/loader.js";import{parseFlowFile as c,findFlowFiles as d,validateFlowFile as g,getFlowSummary as p}from"./parser/flow.js";import{TestRunner as f}from"./runner/index.js";import{ReportGenerator as u}from"./report/generator.js";import{BrowserAgent as m}from"./browser/agent.js";import{generateText as y}from"ai";import{createAnthropic as w}from"@ai-sdk/anthropic";import{createOpenAI as h}from"@ai-sdk/openai";import{createGoogleGenerativeAI as $}from"@ai-sdk/google";import{createMistral as b}from"@ai-sdk/mistral";import{createGroq as k}from"@ai-sdk/groq";import S from"yaml";function x(e){switch(e.provider){case"anthropic":return w({apiKey:e.api_key})(e.model);case"openai":return h({apiKey:e.api_key})(e.model);case"google":return $({apiKey:e.api_key})(e.model);case"mistral":return b({apiKey:e.api_key})(e.model);case"groq":return k({apiKey:e.api_key})(e.model);case"ollama":return h({apiKey:"ollama",baseURL:e.base_url||"http://localhost:11434/v1"})(e.model);default:throw new Error(`Unsupported provider: ${e.provider}`)}}l.config();const v=new e;function A(e){if("string"==typeof e)try{e=JSON.parse(e)}catch{return{}}if(!e||"object"!=typeof e||Array.isArray(e))return{};const o={};for(const[s,n]of Object.entries(e))o[String(s)]="string"==typeof n?n:JSON.stringify(n);return o}function I(e,s){const l=n.resolve(e);if(!t.existsSync(l))return console.log(o.yellow(` Skip (not found): ${l}`)),!1;const r=t.readFileSync(l,"utf-8");let a;try{a=S.parse(r)}catch(e){return console.log(o.red(` Invalid YAML: ${l}`)),console.log(o.gray(` ${e.message}`)),!1}if(!a||!a.profiles||"object"!=typeof a.profiles)return console.log(o.yellow(` No profiles in: ${l}`)),!1;let i=!1;for(const[e,o]of Object.entries(a.profiles)){if("inject"!==o.type)continue;const s="string"==typeof o.localStorage||o.localStorage&&(Array.isArray(o.localStorage)||"object"!=typeof o.localStorage),n="string"==typeof o.sessionStorage||o.sessionStorage&&(Array.isArray(o.sessionStorage)||"object"!=typeof o.sessionStorage);(s||n)&&(a.profiles[e]={...o,...s&&{localStorage:A(o.localStorage)},...n&&{sessionStorage:A(o.sessionStorage)}},i=!0)}if(!i)return console.log(o.gray(` No changes needed: ${l}`)),!1;if(s)return console.log(o.cyan(` Would fix: ${l}`)),!0;const c=l+".backup";return t.copyFileSync(l,c),t.writeFileSync(l,S.stringify(a,{indent:2,lineWidth:0})),console.log(o.green(` Fixed: ${l}`)),console.log(o.gray(` Backup: ${c}`)),!0}v.name("slapify").description("AI-powered test automation using natural language flow files").version("0.1.0"),v.command("init").description("Initialize Slapify in the current directory").option("-y, --yes","Skip prompts and use defaults").action(async e=>{const n=await import("readline");if(t.existsSync(".slapify"))return console.log(o.yellow("Slapify is already initialized in this directory.")),void console.log(o.gray("Delete .slapify folder to reinitialize."));console.log(o.blue.bold("\n๐Ÿ–๏ธ Welcome to Slapify!\n")),console.log(o.gray("AI-powered E2E testing that slaps - by slaps.dev\n"));const{findSystemBrowsers:l,initConfig:r}=await import("./config/loader.js");let a,i,c,d="anthropic";const g={anthropic:{name:"Anthropic (Claude)",envVar:"ANTHROPIC_API_KEY",defaultModel:"claude-haiku-4-5-20251001",models:[{id:"claude-haiku-4-5-20251001",name:"Haiku 4.5 - fast & cheap ($1/5M tokens)",recommended:!0},{id:"claude-sonnet-4-20250514",name:"Sonnet 4 - more capable ($3/15M tokens)"},{id:"custom",name:"Enter custom model ID"}]},openai:{name:"OpenAI",envVar:"OPENAI_API_KEY",defaultModel:"gpt-4o-mini",models:[{id:"gpt-4o-mini",name:"GPT-4o Mini - fast & cheap ($0.15/0.6M tokens)",recommended:!0},{id:"gpt-4.1-mini",name:"GPT-4.1 Mini - newer"},{id:"gpt-4o",name:"GPT-4o - more capable ($2.5/10M tokens)"},{id:"custom",name:"Enter custom model ID"}]},google:{name:"Google (Gemini)",envVar:"GOOGLE_API_KEY",defaultModel:"gemini-2.0-flash",models:[{id:"gemini-2.0-flash",name:"Gemini 2.0 Flash - fastest & cheapest",recommended:!0},{id:"gemini-1.5-flash",name:"Gemini 1.5 Flash - stable"},{id:"gemini-1.5-pro",name:"Gemini 1.5 Pro - more capable"},{id:"custom",name:"Enter custom model ID"}]},mistral:{name:"Mistral",envVar:"MISTRAL_API_KEY",askModel:!0,defaultModel:"mistral-small-latest"},groq:{name:"Groq (Fast inference)",envVar:"GROQ_API_KEY",askModel:!0,defaultModel:"llama-3.3-70b-versatile"},ollama:{name:"Ollama (Local)",envVar:"",askModel:!0,defaultModel:"llama3"}};if(e.yes)console.log(o.gray("Using default settings...\n"));else{const e=n.createInterface({input:process.stdin,output:process.stdout}),t=o=>new Promise(s=>e.question(o,s));console.log(o.cyan("1. Choose your LLM provider:\n")),console.log(" 1) Anthropic (Claude) "+o.green("- recommended")),console.log(" 2) OpenAI (GPT-4)"),console.log(" 3) Google (Gemini)"),console.log(" 4) Mistral"),console.log(" 5) Groq "+o.gray("- fast & free tier")),console.log(" 6) Ollama "+o.gray("- local, no API key")),console.log("");d={1:"anthropic",2:"openai",3:"google",4:"mistral",5:"groq",6:"ollama"}[await t(o.white(" Select [1]: "))]||"anthropic";const r=g[d];if(console.log(o.green(` โœ“ Using ${r.name}\n`)),r.models&&r.models.length>0){console.log(o.cyan(" Choose model:\n")),r.models.forEach((e,s)=>{const n=e.recommended?o.green(" โ† recommended"):"";console.log(` ${s+1}) ${e.name}${n}`)}),console.log("");const e=await t(o.white(" Select [1]: ")),s=parseInt(e)-1||0,n=r.models[s];if("custom"===n?.id){a=(await t(o.white(" Enter model ID: "))).trim()||r.defaultModel}else a=n?.id||r.defaultModel;console.log(o.green(` โœ“ Using model: ${a}\n`))}else if(r.askModel){console.log(o.gray(` Enter model ID (default: ${r.defaultModel})`)),"ollama"===d?console.log(o.gray(" Common models: llama3, mistral, codellama, phi3")):"groq"===d?console.log(o.gray(" Common models: llama-3.3-70b-versatile, mixtral-8x7b-32768")):"mistral"===d&&console.log(o.gray(" Common models: mistral-small-latest, mistral-large-latest")),console.log("");a=(await t(o.white(` Model [${r.defaultModel}]: `))).trim()||r.defaultModel,console.log(o.green(` โœ“ Using model: ${a}\n`)),"ollama"===d&&(console.log(o.gray(" Make sure Ollama is running: ollama serve")),console.log(""))}if("ollama"!==d){console.log(o.cyan("2. API Key verification:\n"));const n=r.envVar;let l=process.env[n];if(l)console.log(o.gray(` Found ${n} in environment`));else{console.log(o.yellow(` ${n} not found in environment`)),console.log(o.gray(" You can set it now or add it to your shell config later.\n"));const e=await t(o.white(" Enter API key (or press Enter to skip): "));e.trim()&&(l=e.trim())}let i=!1;for(;!i;){if(!l){console.log(o.yellow(`\n Remember to set ${n} before running tests.`));break}if("n"===(await t(o.white(" Verify API key with test call? (Y/n): "))).toLowerCase()){console.log(o.gray(" Skipping verification\n"));break}{e.pause();const c=s(" Verifying API key...").start();try{const e=x({provider:d,model:a||r.defaultModel||"test",api_key:l});(await y({model:e,prompt:"Reply with only the word 'pong'",maxTokens:10})).text.toLowerCase().includes("pong")?c.succeed(o.green("API key verified! โœ“")):c.succeed(o.green("API key works! (got response)")),i=!0}catch(e){c.fail(o.red("API key verification failed")),console.log(o.red(` Error: ${e.message}\n`))}if(e.resume(),!i){if("n"===(await t(o.white(" Try a different API key? (Y/n): "))).toLowerCase()){console.log(o.yellow(` Remember to set ${n} correctly before running tests.`));break}const e=await t(o.white(" Enter API key: "));if(!e.trim()){console.log(o.yellow(" No key entered, skipping.\n"));break}l=e.trim()}}}console.log("")}console.log(o.cyan(("ollama"===d?"2":"3")+". Browser setup:\n"));const p=l();if(p.length>0){console.log(" Found browsers on your system:"),p.forEach((e,s)=>{console.log(o.gray(` ${s+1}) ${e.name}`))}),console.log(o.gray(` ${p.length+1}) Download Chromium (~170MB)`)),console.log(o.gray(` ${p.length+2}) Enter custom path`)),console.log("");const e=await t(o.white(" Select [1]: ")),s=parseInt(e)||1;if(s<=p.length)i=p[s-1].path,c=!0,console.log(o.green(` โœ“ Using ${p[s-1].name}\n`));else if(s===p.length+2){const e=await t(o.white(" Enter browser path: "));e.trim()&&(i=e.trim(),c=!0,console.log(o.green(" โœ“ Using custom browser\n")))}else c=!1,console.log(o.green(" โœ“ Will download Chromium on first run\n"))}else{console.log(" No browsers found. Options:"),console.log(o.gray(" 1) Download Chromium automatically (~170MB)")),console.log(o.gray(" 2) Enter custom browser path")),console.log("");if("2"===await t(o.white(" Select [1]: "))){const e=await t(o.white(" Enter browser path: "));e.trim()&&(i=e.trim(),c=!0,console.log(o.green(" โœ“ Using custom browser\n")))}else c=!1,console.log(o.green(" โœ“ Will download Chromium on first run\n"))}e.close()}const p=s("Creating configuration...").start();try{r(process.cwd(),{provider:d,model:a,browserPath:i,useSystemBrowser:c}),p.succeed("Slapify initialized!"),console.log(""),console.log(o.green("Created:")),console.log(" ๐Ÿ“ .slapify/config.yaml - Configuration"),console.log(" ๐Ÿ” .slapify/credentials.yaml - Credentials (gitignored)"),console.log(" ๐Ÿ“ tests/example.flow - Sample test"),console.log("");const e=g[d];console.log(o.yellow("Next steps:")),console.log(""),"ollama"===d?(console.log(o.white(" 1. Make sure Ollama is running:")),console.log(o.cyan(" ollama serve")),console.log(o.cyan(" ollama pull llama3"))):(console.log(o.white(" 1. Set your API key:")),console.log(o.cyan(` export ${e.envVar}=your-key-here`))),console.log(""),console.log(o.white(" 2. Run the example test:")),console.log(o.cyan(" slapify run tests/example.flow")),console.log(""),console.log(o.white(" 3. Create your own tests:")),console.log(o.cyan(" slapify create my-first-test")),console.log(o.cyan(' slapify generate "test login for myapp.com"')),console.log(""),console.log(o.gray(" Config can be modified anytime in .slapify/config.yaml")),console.log("")}catch(e){p.fail(e.message),process.exit(1)}}),v.command("install").description("Install browser dependencies").action(()=>{const e=s("Checking agent-browser...").start();if(m.isInstalled())e.succeed("agent-browser is already installed");else{e.text="Installing agent-browser...";try{m.install(),e.succeed("Browser dependencies installed!")}catch(o){e.fail(`Installation failed: ${o.message}`),process.exit(1)}}}),v.command("run [files...]").description("Run flow test files").option("--headed","Run browser in headed mode (visible)").option("--report [format]","Generate report folder (html, markdown, json)").option("--output <dir>","Output directory for reports","./test-reports").option("--credentials <profile>","Default credentials profile to use").option("-p, --parallel","Run tests in parallel").option("-w, --workers <n>","Number of parallel workers (default: 4)","4").option("--performance","Run performance audit (scores, real-user metrics, framework & re-render analysis) and include in report").action(async(e,s)=>{try{const l=i();l||(console.log(o.red('No .slapify directory found. Run "slapify init" first.')),process.exit(1));const g=r(l),m=a(l);s.headed&&(g.browser={...g.browser,headless:!1});const y=void 0!==s.report;g.report={...g.report,format:"string"==typeof s.report?s.report:"html",output_dir:s.output,screenshots:y};let w=[];if(0===e.length){const e=n.join(process.cwd(),"tests");t.existsSync(e)&&(w=await d(e))}else for(const o of e)if(t.statSync(o).isDirectory()){const e=await d(o);w.push(...e)}else w.push(o);0===w.length&&(console.log(o.yellow("No .flow files found to run.")),process.exit(0));const h=new u(g.report),$=[],b=s.parallel&&w.length>1,k=parseInt(s.workers)||4;if(b){console.log(o.blue.bold(`\nโ”โ”โ” Running ${w.length} tests in parallel (${k} workers) โ”โ”โ”\n`));const e=[...w],s=new Map,t=new Map;for(const e of w){const s=n.basename(e,".flow");t.set(s,o.gray("โณ pending"))}const l=()=>{process.stdout.write("["+w.length+"A");for(const e of w){const o=n.basename(e,".flow"),s=t.get(o)||"";process.stdout.write(""),console.log(` ${o}: ${s}`)}};for(const e of w){const o=n.basename(e,".flow");console.log(` ${o}: ${t.get(o)}`)}const r=async e=>{const s=c(e),n=s.name;t.set(n,o.cyan("โ–ถ running...")),l();try{const e=new f(g,m),l=await e.runFlow(s);$.push(l),"passed"===l.status?t.set(n,o.green(`โœ“ passed (${l.passedSteps}/${l.totalSteps} steps, ${(l.duration/1e3).toFixed(1)}s)`)):t.set(n,o.red(`โœ— failed (${l.failedSteps} failed, ${l.passedSteps} passed)`))}catch(e){t.set(n,o.red(`โœ— error: ${e.message}`))}l()};for(;e.length>0||s.size>0;){for(;e.length>0&&s.size<k;){const o=e.shift(),n=r(o).then(()=>{s.delete(o)});s.set(o,n)}s.size>0&&await Promise.race(s.values())}console.log("")}else for(const e of w){const n=c(e),t=p(n);console.log(""),console.log(o.blue.bold(`โ”โ”โ” ${n.name} โ”โ”โ”`)),console.log(o.gray(` ${t.totalSteps} steps (${t.requiredSteps} required, ${t.optionalSteps} optional)`)),console.log("");try{const e=new f(g,m),t=await e.runFlow(n,e=>{const s=e.step,n="passed"===e.status?o.green("โœ“"):"failed"===e.status?o.red("โœ—"):o.yellow("โŠ˜"),t=s.optional?o.gray(" [optional]"):"",l=e.retried?o.yellow(" [retried]"):"",r=o.gray(`(${(e.duration/1e3).toFixed(1)}s)`);if(console.log(` ${n} ${s.text}${t}${l} ${r}`),"failed"===e.status&&e.error&&console.log(o.red(` โ””โ”€ ${e.error}`)),e.assumptions&&e.assumptions.length>0)for(const s of e.assumptions)console.log(o.gray(` โ””โ”€ ๐Ÿ’ก ${s}`))},!!s.performance);if(t.perfAudit){const e=t.perfAudit,s=[];e.vitals.fcp&&s.push(`FCP ${e.vitals.fcp}ms`),e.vitals.lcp&&s.push(`LCP ${e.vitals.lcp}ms`),null!=e.vitals.cls&&s.push(`CLS ${e.vitals.cls}`);const n=e.scores??e.lighthouse;n&&s.push(`Perf ${n.performance}/100`),console.log(o.cyan(` โšก Perf: ${s.join(" ยท ")}`))}$.push(t),console.log(""),"passed"===t.status?console.log(o.green.bold(" โœ“ PASSED")+o.gray(` (${t.passedSteps}/${t.totalSteps} steps in ${(t.duration/1e3).toFixed(1)}s)`)):console.log(o.red.bold(" โœ— FAILED")+o.gray(` (${t.failedSteps} failed, ${t.passedSteps} passed)`)),t.autoHandled.length>0&&console.log(o.gray(` โ„น Auto-handled: ${t.autoHandled.join(", ")}`))}catch(e){console.log(o.red(` โœ— ERROR: ${e.message}`))}}console.log(""),console.log(o.blue.bold("โ”โ”โ” Summary โ”โ”โ”"));const S=$.filter(e=>"passed"===e.status).length,x=$.filter(e=>"failed"===e.status).length,v=$.reduce((e,o)=>e+o.totalSteps,0),A=$.reduce((e,o)=>e+o.passedSteps,0);if(console.log(o.gray(` ${$.length} test file(s), ${v} total steps`)),0===x?console.log(o.green.bold(` โœ“ All ${S} test(s) passed! (${A}/${v} steps)`)):console.log(o.red.bold(` โœ— ${x}/${$.length} test(s) failed`)),y&&$.length>0){let e;e=1===$.length?h.saveAsFolder($[0]):h.saveSuiteAsFolder($),console.log(o.cyan(`\n ๐Ÿ“„ Report: ${e}`))}console.log(""),x>0&&process.exit(1)}catch(e){console.error(o.red(`Error: ${e.message}`)),process.exit(1)}}),v.command("create <name>").description("Create a new flow file").option("-d, --dir <directory>","Directory to create flow in","tests").action(async(e,s)=>{const l=await import("readline"),r=s.dir;t.existsSync(r)||t.mkdirSync(r,{recursive:!0});const a=e.endsWith(".flow")?e:`${e}.flow`,i=n.join(r,a);t.existsSync(i)&&(console.log(o.red(`File already exists: ${i}`)),process.exit(1)),console.log(o.blue(`\nCreating: ${i}`)),console.log(o.gray("Enter your test steps (one per line). Empty line to finish.\n"));const c=l.createInterface({input:process.stdin,output:process.stdout}),d=[`# ${e}`,""];let g=1;const p=()=>new Promise(e=>{c.question(o.cyan(`${g}. `),o=>{e(o)})});for(;;){const e=await p();if(""===e)break;d.push(e),g++}c.close(),d.length<=2?console.log(o.yellow("\nNo steps entered. File not created.")):(t.writeFileSync(i,d.join("\n")+"\n"),console.log(o.green(`\nโœ“ Created: ${i}`)),console.log(o.gray(` ${g-1} steps`)),console.log(o.gray(`\nRun with: slapify run ${i}`)))}),v.command("generate <prompt>").alias("gen").description("Generate a verified .flow file by running the goal as a task and recording what worked").option("-d, --dir <directory>","Directory to save flow","tests").option("--headed","Show browser window while running").action(async(e,s)=>{const n=i();n||(console.log(o.red('No .slapify directory found. Run "slapify init" first.')),process.exit(1));r(n);console.log(o.blue("\n๐Ÿค– Flow Generator\n")),console.log(o.gray(" Running the goal in the browser to discover the real path...\n"));const{runTask:t}=await import("./task/runner.js");let l;await t({goal:e,headed:s.headed,saveFlow:!0,flowOutputDir:s.dir,onEvent:e=>{"status_update"===e.type&&process.stdout.write(o.gray(` โ†’ ${e.message}\n`)),"message"===e.type&&console.log(o.white(`\n${e.text}`)),"flow_saved"===e.type&&(l=e.path),"done"===e.type&&console.log(o.green("\nโœ… Done")),"error"===e.type&&console.log(o.red(`\nโœ— ${e.error}`))}}),l?(console.log(o.green(`\nโœ“ Flow saved: ${l}`)),console.log(o.gray(` Run with: slapify run ${l}`))):console.log(o.yellow("\nโš  No flow was saved. The agent may not have completed the goal."))}),v.command("fix <file>").description("Analyze a failing test and suggest/apply fixes").option("--auto","Automatically apply suggested fixes without confirmation").option("--headed","Run browser in headed mode for debugging").action(async(e,n)=>{const l=i();l||(console.log(o.red('No .slapify directory found. Run "slapify init" first.')),process.exit(1)),t.existsSync(e)||(console.log(o.red(`File not found: ${e}`)),process.exit(1));const d=r(l),g=a(l);n.headed&&(d.browser={...d.browser,headless:!1}),d.report={...d.report,screenshots:!0};const p=await import("readline");let u=s("Running test to identify failures...").start();try{const l=c(e),r=new f(d,g),a=[];if("passed"===(await r.runFlow(l,e=>{"failed"===e.status&&e.error&&a.push({step:e.step.text,error:e.error,line:e.step.line,screenshot:e.screenshot})})).status)return void u.succeed("Test passed! No fixes needed.");if(u.info(`Found ${a.length} failing step(s)`),0===a.length)return void console.log(o.yellow("No specific step failures to fix."));const i=t.readFileSync(e,"utf-8"),m=i.split("\n");u=s("Analyzing failures and generating fixes...").start();const w=a.map(e=>`Line ${e.line}: "${e.step}"\n Error: ${e.error}`).join("\n\n"),h=await y({model:x(d.llm),system:`You are a test automation expert. Analyze failing test steps and suggest fixes.\n\nOriginal flow file:\n\`\`\`\n${i}\n\`\`\`\n\nFailing steps:\n${w}\n\nBased on the errors, suggest fixes for the flow file. Common issues and fixes:\n1. Element not found โ†’ Try more descriptive text, add wait, or make step optional\n2. Timeout โ†’ Add explicit wait or increase timeout\n3. Navigation error โ†’ Add wait after navigation, or split into smaller steps\n4. Element obscured โ†’ Add step to close popup/modal first\n5. Stale element โ†’ Add wait for page to stabilize\n\nRespond with JSON:\n{\n "analysis": "Brief explanation of what's wrong",\n "fixes": [\n {\n "line": 5,\n "original": "Click the submit button",\n "fixed": "Click the Submit button",\n "reason": "Button text is capitalized"\n }\n ],\n "additions": [\n {\n "afterLine": 4,\n "step": "[Optional] Wait for page to load",\n "reason": "Page might still be loading"\n }\n ]\n}`,prompt:"Analyze the failures and suggest specific fixes.",maxTokens:1500});u.succeed("Analysis complete");const $=h.text.match(/\{[\s\S]*\}/);if(!$)return void console.log(o.red("Could not parse AI response"));const b=JSON.parse($[0]);if(console.log(o.blue("\nโ”โ”โ” Analysis โ”โ”โ”\n")),console.log(o.white(b.analysis)),b.fixes?.length>0||b.additions?.length>0){if(console.log(o.blue("\nโ”โ”โ” Suggested Fixes โ”โ”โ”\n")),b.fixes?.length>0)for(const e of b.fixes)console.log(o.yellow(`Line ${e.line}:`)),console.log(o.red(` - ${e.original}`)),console.log(o.green(` + ${e.fixed}`)),console.log(o.gray(` Reason: ${e.reason}\n`));if(b.additions?.length>0){console.log(o.yellow("New steps to add:"));for(const e of b.additions)console.log(o.green(` + After line ${e.afterLine}: ${e.step}`)),console.log(o.gray(` Reason: ${e.reason}\n`))}let s=n.auto;if(!s){const e=p.createInterface({input:process.stdin,output:process.stdout}),n=await new Promise(s=>{e.question(o.cyan("Apply these fixes? (y/N): "),o=>{e.close(),s(o.trim().toLowerCase())})});s="y"===n||"yes"===n}if(s){let s=[...m];new Map;if(b.fixes)for(const e of b.fixes){const o=e.line-1;o>=0&&o<s.length&&(s[o]=e.fixed)}if(b.additions){const e=[...b.additions].sort((e,o)=>o.afterLine-e.afterLine);for(const o of e){const e=o.afterLine;s.splice(e,0,o.step)}}const n=s.join("\n"),l=e+".backup";t.writeFileSync(l,i),t.writeFileSync(e,n),console.log(o.green(`\nโœ“ Fixes applied to ${e}`)),console.log(o.gray(` Backup saved to ${l}`)),console.log(o.gray(`\nRun again with: slapify run ${e}`))}else console.log(o.yellow("No changes made."))}else console.log(o.yellow("\nNo automatic fixes suggested.")),console.log(o.gray("The failures may require manual investigation."))}catch(e){u.fail("Error"),console.error(o.red(`Error: ${e.message}`)),process.exit(1)}}),v.command("validate [files...]").description("Validate flow files for syntax issues").action(async e=>{let s=[];if(0===e.length){const e=n.join(process.cwd(),"tests");t.existsSync(e)&&(s=await d(e))}else s=e;if(0===s.length)return void console.log(o.yellow("No .flow files found."));let l=!1;for(const e of s)try{const s=c(e),n=g(s),t=p(s);if(n.length>0){l=!0,console.log(o.yellow(`โš ๏ธ ${e}`));for(const e of n)console.log(o.yellow(` ${e}`))}else console.log(o.green(`โœ… ${e}`)),console.log(o.gray(` ${t.totalSteps} steps (${t.requiredSteps} required, ${t.optionalSteps} optional)`))}catch(s){console.log(o.red(`โŒ ${e}`)),console.log(o.red(` ${s.message}`)),l=!0}l&&process.exit(1)}),v.command("list").description("List all flow files").action(async()=>{const e=n.join(process.cwd(),"tests");if(!t.existsSync(e))return void console.log(o.yellow("No tests directory found."));const s=await d(e);if(0!==s.length){console.log(o.blue(`\nFound ${s.length} flow file(s):\n`));for(const e of s){const s=c(e),t=p(s),l=n.relative(process.cwd(),e);console.log(` ${o.white(l)}`),console.log(o.gray(` ${t.totalSteps} steps (${t.requiredSteps} required, ${t.optionalSteps} optional)`))}console.log("")}else console.log(o.yellow("No .flow files found."))}),v.command("credentials").description("List configured credential profiles").action(()=>{const e=i();e||(console.log(o.red('No .slapify directory found. Run "slapify init" first.')),process.exit(1));const s=a(e),n=Object.keys(s.profiles);if(0===n.length)return console.log(o.yellow("No credential profiles configured.")),void console.log(o.gray("Edit .slapify/credentials.yaml to add profiles."));console.log(o.blue("\nConfigured credential profiles:\n"));for(const e of n){const n=s.profiles[e];console.log(` ${o.white(e)} (${n.type})`),n.username&&console.log(o.gray(` username: ${n.username}`)),n.email&&console.log(o.gray(` email: ${n.email}`)),n.totp_secret&&console.log(o.gray(" 2FA: TOTP configured")),n.fixed_otp&&console.log(o.gray(" 2FA: Fixed OTP configured"))}console.log("")}),v.command("fix-credentials [files...]").description("Fix credential YAML files where localStorage/sessionStorage were saved as JSON strings").option("--dry-run","Only print what would be fixed").action((e,s)=>{const t=[];if(e&&e.length>0)t.push(...e.map(e=>n.resolve(e)));else{const e=process.cwd();t.push(n.join(e,"temp_credentials.yaml"));const o=i();o&&t.push(n.join(o,"credentials.yaml"))}console.log(o.blue("\n๐Ÿ”ง Fix credential YAML files\n")),s.dryRun&&console.log(o.gray(" (dry run โ€“ no files will be modified)\n"));let l=0;for(const e of t)I(e,!!s.dryRun)&&l++;0===l&&t.length>0&&console.log(o.gray("\n No files needed fixing.")),console.log("")}),v.command("interactive [url]").alias("i").description("Run steps interactively").option("--headed","Run browser in headed mode").action(async(e,s)=>{console.log(o.blue("\n๐Ÿงช Slapify Interactive Mode")),console.log(o.gray('Type test steps and press Enter to execute. Type "exit" to quit.\n'));const n=i();n||(console.log(o.red('No .slapify directory found. Run "slapify init" first.')),process.exit(1));const t=r(n),l=a(n);s.headed&&(t.browser={...t.browser,headless:!1});new f(t,l);e&&console.log(o.gray(`Navigating to ${e}...`));const c=(await import("readline")).createInterface({input:process.stdin,output:process.stdout}),d=()=>{c.question(o.cyan("> "),async e=>{const s=e.trim();"exit"!==s.toLowerCase()&&"quit"!==s.toLowerCase()||(console.log(o.gray("\nGoodbye!")),c.close(),process.exit(0)),s?(console.log(o.gray(`Executing: ${s}`)),console.log(o.green("โœ“ Done")),d()):d()})};d()}),v.command("task [goal]").description('Run an autonomous AI agent task in plain English.\n The agent decides everything: what to do, when to schedule, when to sleep.\n Examples:\n slapify task "Go to linkedin.com and like the latest 3 posts"\n slapify task "Monitor my Gmail for new emails every 30 min and log subjects"\n slapify task "Order breakfast from Swiggy every day at 8am"').option("--headed","Show the browser window").option("--debug","Show all tool calls and internal steps").option("--report","Generate an HTML report after the task completes").option("--save-flow","Save agent steps as a reusable .flow file when done").option("--session <id>","Resume an existing task session").option("--list-sessions","List all task sessions").option("--logs <id>","Show logs for a task session").option("--max-iterations <n>","Safety cap on agent iterations (default 200)",parseInt).action(async(e,s)=>{if(s.listSessions){const{listSessions:e}=await import("./task/index.js"),s=e();if(0===s.length)return void console.log(o.gray("\nNo task sessions found.\n"));console.log(o.blue(`\n๐Ÿ“‹ Task Sessions (${s.length})\n`));for(const e of s){const s="completed"===e.status?o.green:"failed"===e.status?o.red:"scheduled"===e.status?o.blue:o.yellow;console.log(` ${s("โ—")} ${o.bold(e.id)}\n Goal: ${e.goal.slice(0,70)}${e.goal.length>70?"โ€ฆ":""}\n Status: ${s(e.status)} Iterations: ${e.iteration}\n Updated: ${new Date(e.updatedAt).toLocaleString()}\n`)}return}if(s.logs){const{loadSession:e}=await import("./task/index.js"),{loadEvents:n}=await import("./task/session.js"),t=e(s.logs);t||(console.log(o.red(`Session '${s.logs}' not found.`)),process.exit(1)),console.log(o.blue(`\n๐Ÿ“œ Logs: ${t.id}\n`)),console.log(o.gray(`Goal: ${t.goal}\n`));const l=n(s.logs);for(const e of l){const s=o.gray(new Date(e.ts).toLocaleTimeString());"llm_response"===e.type?e.text&&console.log(`${s} ๐Ÿค” ${o.cyan(e.text.slice(0,120))}`):"tool_call"===e.type?console.log(`${s} ๐Ÿ”ง ${o.yellow(e.toolName)} โ†’ ${o.gray(JSON.stringify(e.result).slice(0,80))}`):"tool_error"===e.type?console.log(`${s} โŒ ${o.red(e.toolName)} โ†’ ${o.red(e.error.slice(0,80))}`):"memory_update"===e.type?console.log(`${s} ๐Ÿง  ${o.magenta("remember")} ${e.key} = ${e.value.slice(0,60)}`):"scheduled"===e.type?console.log(`${s} โฐ ${o.blue("schedule")} ${e.cron} โ€” ${e.task}`):"sleeping_until"===e.type?console.log(`${s} ๐Ÿ˜ด ${o.blue("sleep")} until ${e.until}`):"session_end"===e.type&&console.log(`${s} โœ… ${o.green("done")} ${e.summary.slice(0,120)}`)}return void console.log("")}let n=e||s.session?e:void 0;if(n||s.session||(console.log(o.red('\nPlease provide a goal. Example:\n slapify task "Go to example.com and check the title"\n')),process.exit(1)),!n&&s.session){const{loadSession:e}=await import("./task/index.js"),t=e(s.session);t||(console.log(o.red(`Session '${s.session}' not found.`)),process.exit(1)),n=t.goal}i()||(console.log(o.red('\nNo .slapify directory found. Run "slapify init" first.\n')),process.exit(1));let t=null;const l=async e=>{if(s.report)try{const{loadEvents:s,saveTaskReport:n}=await import("./task/index.js"),t=n(e,s(e.id));console.log(o.cyan(`\n ๐Ÿ“Š Report: ${t}`))}catch(e){console.log(o.yellow(` โš  Could not generate report: ${e?.message}`))}},r=!!s.debug,a=()=>process.stdout.write("\r");console.log(o.blue("\n๐Ÿค– Slapify Task Agent\n")),console.log(o.white(` Goal: ${n}`)),s.session&&console.log(o.gray(` Resuming session: ${s.session}`)),console.log(o.gray([s.report?" --report: HTML report on exit":"",r?" --debug: verbose output":""," Ctrl+C to stop"].filter(Boolean).join(" ยท ")+"\n")),console.log(o.gray("โ”€".repeat(60))+"\n");let c=null,d=!1;const g=()=>{if(r||d||c)return;const e=["โ ‹","โ ™","โ น","โ ธ","โ ผ","โ ด","โ ฆ","โ ง","โ ‡","โ "];let s=0;c=setInterval(()=>{process.stdout.write(o.gray(`\r ${e[s++%e.length]} working...`))},80)};r||g();const{runTask:p}=await import("./task/index.js");let f=!1;const u=async()=>{if(!f){if(f=!0,clearInterval(c),c=null,d=!0,process.stdout.write("\r"),console.log(o.yellow("\n โšก Interrupted"+(s.report?" โ€” generating report...":""))),t){t.status="failed",t.finalSummary="Task interrupted by user (Ctrl+C).";const{saveSessionMeta:e}=await import("./task/session.js");e(t),await l(t)}console.log(o.gray(" Goodbye.\n")),process.exit(0)}};process.once("SIGINT",u);try{const e=()=>{c&&(clearInterval(c),c=null),process.stdout.write("\r")},i=await p({goal:n,sessionId:s.session,headed:s.headed,saveFlow:s.saveFlow,maxIterations:s.maxIterations,onHumanInput:async(s,n)=>{d=!0,e();const t=(await import("readline")).createInterface({input:process.stdin,output:process.stdout,terminal:!0}),l=await new Promise(e=>{t.question(` ${o.cyan("โ€บ")} `,o=>{t.close(),e(o.trim())})});return console.log(o.yellow("โ”€".repeat(60))+"\n"),d=!1,g(),l},onEvent:s=>{const n="status_update"===s.type||"human_input_needed"===s.type||"credentials_saved"===s.type||"done"===s.type||"error"===s.type||"tool_error"===s.type;n&&e(),(e=>{switch(e.type){case"thinking":r&&process.stdout.write(o.gray(" โŸณ thinking...\r"));break;case"message":r&&(a(),console.log(o.gray(` ๐Ÿ’ฌ ${e.text}`)));break;case"tool_start":if(r){a();const s=JSON.stringify(e.args);console.log(o.dim(` โ€บ ${o.cyan(e.toolName)} `)+o.gray(s.slice(0,100)+(s.length>100?"โ€ฆ":"")))}break;case"tool_done":r&&console.log(o.dim(` โœ“ ${e.result.slice(0,120)}`));break;case"tool_error":a(),console.log(o.red(` โœ— ${e.toolName}: ${e.error.slice(0,120)}`));break;case"status_update":a(),console.log(o.white(` ${e.message}`));break;case"human_input_needed":console.log("\n"+o.yellow("โ”€".repeat(60))),console.log(o.yellow.bold(" ๐Ÿ™‹ Agent needs your input")),console.log(o.white(`\n ${e.question}`)),e.hint&&console.log(o.gray(` ${e.hint}`));break;case"credentials_saved":a(),console.log(o.green(` ๐Ÿ’พ Credentials saved: '${e.profileName}' (${e.credType}) โ†’ .slapify/credentials.yaml`));break;case"scheduled":r&&(a(),console.log(o.dim(` โฐ scheduled: ${e.cron} โ€” ${e.task}`)));break;case"sleeping":r&&(a(),console.log(o.dim(` ๐Ÿ˜ด sleeping until ${new Date(e.until).toLocaleString()}`)));break;case"done":a(),console.log("\n"+o.green("โ”€".repeat(60))),console.log(o.green.bold(" โœ… Task complete!")),console.log(o.white(`\n ${e.summary}`)),console.log(o.green("โ”€".repeat(60)));break;case"error":a(),console.log(o.red(`\n โœ— Error: ${e.error}`))}})(s),n&&"done"!==s.type&&"error"!==s.type&&"human_input_needed"!==s.type&&g()},onSessionUpdate:e=>{t=e}});if(e(),process.removeListener("SIGINT",u),console.log(o.gray(`\n Session: ${i.id}`)),i.savedFlowPath&&console.log(o.cyan(` Flow saved: ${i.savedFlowPath}`)),Object.keys(i.memory).length>0){console.log(o.gray(` Memory (${Object.keys(i.memory).length} items):`));for(const[e,s]of Object.entries(i.memory))console.log(o.gray(` โ€ข ${e}: ${s.slice(0,80)}`))}await l(i),console.log("")}catch(e){process.removeListener("SIGINT",u),clearInterval(c),c=null,process.stdout.write("\r"),console.error(o.red(`\n Task failed: ${e?.message||e}`)),t&&await l(t),process.exit(1)}}),v.parse();