@flowspec-qa/runner-core 0.2.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/api-client.ts DELETED
@@ -1,170 +0,0 @@
1
- import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
2
- import { config } from './config.js';
3
-
4
- // Lazy singleton — created on first use so baseUrl is read after config is loaded
5
- let _client: AxiosInstance | null = null;
6
-
7
- function getClient(): AxiosInstance {
8
- if (!_client) {
9
- _client = axios.create({
10
- baseURL: config.get('baseUrl'),
11
- timeout: 30_000,
12
- headers: { 'Content-Type': 'application/json' },
13
- });
14
-
15
- // Attach Bearer token (API Key) to every request
16
- _client.interceptors.request.use((req) => {
17
- const apiKey = config.get('apiKey');
18
- if (apiKey) {
19
- req.headers['Authorization'] = `Bearer ${apiKey}`;
20
- }
21
- return req;
22
- });
23
-
24
- // Normalize error messages
25
- _client.interceptors.response.use(
26
- (res) => res,
27
- (err) => {
28
- const status = err.response?.status;
29
- const raw = err.response?.data?.detail || err.response?.data?.message || err.message;
30
- const msg = typeof raw === 'object' ? JSON.stringify(raw) : String(raw ?? 'Unknown error');
31
- const fullMsg = status ? `HTTP ${status}: ${msg}` : msg;
32
- return Promise.reject(new Error(fullMsg));
33
- }
34
- );
35
- }
36
- return _client;
37
- }
38
-
39
- export const apiClient = {
40
- async get<T>(url: string, cfg?: AxiosRequestConfig): Promise<T> {
41
- const res = await getClient().get<T>(url, cfg);
42
- return res.data;
43
- },
44
- async post<T>(url: string, data?: unknown, cfg?: AxiosRequestConfig): Promise<T> {
45
- const res = await getClient().post<T>(url, data, cfg);
46
- return res.data;
47
- },
48
- async getStream(url: string): Promise<NodeJS.ReadableStream> {
49
- const res = await getClient().get(url, { responseType: 'stream' });
50
- return res.data as NodeJS.ReadableStream;
51
- },
52
- async getArrayBuffer(url: string): Promise<Buffer> {
53
- const res = await getClient().get(url, { responseType: 'arraybuffer' });
54
- return Buffer.from(res.data as ArrayBuffer);
55
- },
56
-
57
- /** Update base URL at runtime (e.g. pointing to a self-hosted instance) */
58
- setBaseUrl(url: string): void {
59
- config.set('baseUrl', url);
60
- _client = null; // force recreation
61
- },
62
- };
63
-
64
- // ─── Typed API methods ─────────────────────────────────────────────────────
65
-
66
- export interface Project {
67
- id: string;
68
- name: string;
69
- entity_count?: number;
70
- }
71
-
72
- export interface Suite {
73
- entity_id: string;
74
- entity_title: string;
75
- suite_id: string; // TestSuite.id — used to download files
76
- framework: 'playwright' | 'cypress' | 'maestro';
77
- mode?: string;
78
- status?: string;
79
- created_at?: string;
80
- }
81
-
82
- export interface IngestResult {
83
- status: string;
84
- entity_id: string;
85
- project_id: string;
86
- plan_id: string;
87
- plan_url: string;
88
- chunks_ingested: number;
89
- duration_ms: number;
90
- collection: string;
91
- source: string;
92
- }
93
-
94
- export const FlowSpecQAApi = {
95
- async listProjects(): Promise<Project[]> {
96
- return apiClient.get<Project[]>('/api/config/projects');
97
- },
98
-
99
- async listSuites(entityId?: string): Promise<Suite[]> {
100
- const url = entityId
101
- ? `/api/automation/suites?entity_id=${entityId}`
102
- : '/api/automation/suites';
103
- const resp = await apiClient.get<{ suites: Suite[]; total: number }>(url);
104
- return resp.suites ?? [];
105
- },
106
-
107
- /** Download the ZIP of generated test files for a suite (suite_id = TestSuite.id) */
108
- async downloadSuiteZip(suiteId: string): Promise<Buffer> {
109
- return apiClient.getArrayBuffer(`/api/automation/download-suite/${suiteId}`);
110
- },
111
-
112
- async submitRunResult(payload: RunResultPayload): Promise<{ ok: boolean; exec_id: string }> {
113
- return apiClient.post('/api/automation/submit-run-result', payload);
114
- },
115
-
116
- async syncDiscoveryPlan(payload: {
117
- url: string;
118
- plan_content: string;
119
- framework: string;
120
- entity_id?: string;
121
- project_id?: string;
122
- raw_scan_data?: any;
123
- }): Promise<{ plan_id: string }> {
124
- return apiClient.post('/api/automation/discovery/sync', payload);
125
- },
126
-
127
- async ingestDiscoveryPlan(payload: {
128
- project_id: string;
129
- entity_id: string;
130
- source?: string;
131
- }): Promise<IngestResult> {
132
- // 60s timeout — embedding can take a few seconds for large plans
133
- return apiClient.post('/api/automation/discovery/ingest', payload, { timeout: 60_000 });
134
- },
135
-
136
- async analyzeVision(payload: {
137
- url: string;
138
- entity_id: string;
139
- project_id: string;
140
- screenshots: string[]; // base64 PNG images
141
- dom_elements: any[];
142
- page_title?: string;
143
- }): Promise<{ status: string; plan_content: string; screenshots_analyzed: number; dom_elements: number; analysis_chars: number }> {
144
- // 120s timeout — GPT-4o vision with multiple images can take time
145
- return apiClient.post('/api/automation/discovery/analyze-vision', payload, { timeout: 120_000 });
146
- },
147
- };
148
-
149
- export interface RunResultPayload {
150
- run_id: string;
151
- entity_id: string;
152
- framework: string;
153
- env_label: string;
154
- results: TestResultItem[];
155
- started_at: string;
156
- finished_at: string;
157
- runner_version: string;
158
- // Traceability fields
159
- machine_name?: string;
160
- machine_ip?: string;
161
- os_info?: string;
162
- executor?: string;
163
- }
164
-
165
- export interface TestResultItem {
166
- name: string;
167
- status: 'pass' | 'fail' | 'skip';
168
- duration_ms: number;
169
- error?: string | null;
170
- }
package/src/auth.ts DELETED
@@ -1,45 +0,0 @@
1
- import { config } from './config.js';
2
-
3
- export interface AuthStatus {
4
- authenticated: boolean;
5
- maskedKey?: string;
6
- }
7
-
8
- /**
9
- * Store the API Key locally and test it against the SaaS.
10
- * Keys use the format: sk-smrt-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
11
- */
12
- export async function login(apiKey: string): Promise<void> {
13
- if (!apiKey.startsWith('sk-smrt-')) {
14
- throw new Error('Invalid API Key format. Keys should start with "sk-smrt-"');
15
- }
16
- config.set('apiKey', apiKey);
17
- // Validate immediately by making a test call
18
- const { apiClient } = await import('./api-client.js');
19
- await apiClient.get('/api/config/projects'); // throws if key is invalid
20
- }
21
-
22
- export function logout(): void {
23
- config.set('apiKey', undefined);
24
- }
25
-
26
- export function getAuthStatus(): AuthStatus {
27
- const apiKey = config.get('apiKey');
28
- if (!apiKey) return { authenticated: false };
29
- return {
30
- authenticated: true,
31
- maskedKey: apiKey.slice(0, 12) + '*'.repeat(Math.max(0, apiKey.length - 12)),
32
- };
33
- }
34
-
35
- /**
36
- * Return the API Key to use as Bearer token.
37
- * The SaaS get_api_key_context dependency accepts: Authorization: Bearer sk-smrt-xxx
38
- */
39
- export function getBearerToken(): string {
40
- const apiKey = config.get('apiKey');
41
- if (!apiKey) {
42
- throw new Error('Not authenticated. Run: flowspecqa auth login');
43
- }
44
- return apiKey;
45
- }
@@ -1,63 +0,0 @@
1
- import path from 'path';
2
- import fs from 'fs/promises';
3
-
4
- export class BackupManager {
5
- private static readonly BACKUP_DIR = path.join(process.cwd(), '.flowspecqa', 'backups');
6
-
7
- /**
8
- * Creates a backup of a file before any AI-driven modification.
9
- * @param filePath Absolute path to the file to backup.
10
- * @param tag Optional tag to identify why the backup was created (e.g., 'healer').
11
- */
12
- static async createBackup(filePath: string, tag: string = 'auto'): Promise<string> {
13
- try {
14
- await fs.mkdir(this.BACKUP_DIR, { recursive: true });
15
-
16
- const fileName = path.basename(filePath);
17
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
18
- const backupFileName = `${timestamp}_${tag}_${fileName}`;
19
- const backupPath = path.join(this.BACKUP_DIR, backupFileName);
20
-
21
- await fs.copyFile(filePath, backupPath);
22
- return backupPath;
23
- } catch (error) {
24
- console.error('Failed to create backup:', error);
25
- throw error;
26
- }
27
- }
28
-
29
- /**
30
- * Lists available backups for a specific file.
31
- * @param fileName Name of the original file.
32
- */
33
- static async listBackups(fileName: string): Promise<string[]> {
34
- try {
35
- const files = await fs.readdir(this.BACKUP_DIR);
36
- return files
37
- .filter(f => f.endsWith(`_${fileName}`))
38
- .sort()
39
- .reverse();
40
- } catch {
41
- return [];
42
- }
43
- }
44
-
45
- /**
46
- * Restores a file from its most recent backup.
47
- * @param originalPath Absolute path to where the file should be restored.
48
- */
49
- static async rollback(originalPath: string): Promise<boolean> {
50
- const fileName = path.basename(originalPath);
51
- const backups = await this.listBackups(fileName);
52
-
53
- if (backups.length === 0) {
54
- return false;
55
- }
56
-
57
- const mostRecent = backups[0];
58
- const backupPath = path.join(this.BACKUP_DIR, mostRecent);
59
-
60
- await fs.copyFile(backupPath, originalPath);
61
- return true;
62
- }
63
- }
package/src/config.ts DELETED
@@ -1,52 +0,0 @@
1
- import Conf from 'conf';
2
- import path from 'path';
3
- import os from 'os';
4
-
5
- export interface RunnerConfig {
6
- apiKey?: string;
7
- runnerToken?: string;
8
- runnerTokenExpiry?: string; // ISO date
9
- baseUrl: string;
10
- suiteCacheDir: string;
11
- sanitizerPatterns: string[];
12
- }
13
-
14
- const DEFAULT_CONFIG: RunnerConfig = {
15
- baseUrl: 'https://www.flowspecqa.com',
16
- suiteCacheDir: path.join(os.homedir(), '.flowspecqa', 'suites'),
17
- sanitizerPatterns: [
18
- // Strip URLs, IPs, auth tokens from error messages before upload
19
- 'https?://[^\\s]+',
20
- '\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b',
21
- 'Bearer\\s+[A-Za-z0-9.\\-_]+',
22
- 'Authorization:\\s*[^\\r\\n]+',
23
- 'password["\']?\\s*[:=]\\s*["\']?[^"\'\\s&]+',
24
- ],
25
- };
26
-
27
- const conf = new Conf<RunnerConfig>({
28
- projectName: 'flowspecqa-runner',
29
- defaults: DEFAULT_CONFIG,
30
- });
31
-
32
- export const config = {
33
- get<K extends keyof RunnerConfig>(key: K): RunnerConfig[K] {
34
- return conf.get(key) as RunnerConfig[K];
35
- },
36
-
37
- set<K extends keyof RunnerConfig>(key: K, value: RunnerConfig[K]): void {
38
- conf.set(key, value);
39
- },
40
-
41
- getAll(): RunnerConfig {
42
- return conf.store as RunnerConfig;
43
- },
44
-
45
- clear(): void {
46
- conf.clear();
47
- },
48
-
49
- get configPath(): string {
50
- return conf.path;
51
- },
52
- };
package/src/devices.ts DELETED
@@ -1,196 +0,0 @@
1
- /**
2
- * FlowSpecQA Device Farm — USB device detection for Android and iOS.
3
- * Detects all devices connected via ADB (Android) and libimobiledevice/Xcode (iOS).
4
- */
5
- import { execSync } from 'child_process';
6
- import { existsSync, writeFileSync, readFileSync, unlinkSync } from 'fs';
7
- import { tmpdir } from 'os';
8
- import { join } from 'path';
9
-
10
- export interface DeviceInfo {
11
- id: string; // ADB serial or iOS UDID
12
- platform: 'android' | 'ios';
13
- name: string; // Human-readable model name
14
- status: 'ready' | 'offline' | 'unauthorized';
15
- osVersion?: string;
16
- }
17
-
18
- // ─── ADB path resolution ─────────────────────────────────────────────────────
19
-
20
- const ADB_COMMON_PATHS = [
21
- 'adb', // already on PATH
22
- '/opt/homebrew/share/android-commandlinetools/platform-tools/adb', // Homebrew
23
- `${process.env.HOME}/Library/Android/sdk/platform-tools/adb`, // Android Studio macOS
24
- '/usr/local/share/android-commandlinetools/platform-tools/adb', // Homebrew Intel
25
- '/usr/local/bin/adb', // manual install
26
- `${process.env.ANDROID_HOME}/platform-tools/adb`, // ANDROID_HOME env
27
- `${process.env.ANDROID_SDK_ROOT}/platform-tools/adb`, // ANDROID_SDK_ROOT env
28
- ];
29
-
30
- function resolveAdb(): string | null {
31
- for (const candidate of ADB_COMMON_PATHS) {
32
- if (!candidate) continue;
33
- try {
34
- execSync(`"${candidate}" version`, { stdio: 'ignore', timeout: 2000 });
35
- return candidate;
36
- } catch {}
37
- }
38
- return null;
39
- }
40
-
41
- // ─── Android ────────────────────────────────────────────────────────────────
42
-
43
- export function detectAndroidDevices(): DeviceInfo[] {
44
- const adb = resolveAdb();
45
- if (!adb) return [];
46
-
47
- try {
48
- const output = execSync(`"${adb}" devices -l`, {
49
- encoding: 'utf8',
50
- stdio: ['ignore', 'pipe', 'pipe'],
51
- });
52
-
53
- const devices: DeviceInfo[] = [];
54
- const lines = output.split('\n').slice(1); // skip "List of devices attached"
55
-
56
- for (const line of lines) {
57
- const trimmed = line.trim();
58
- if (!trimmed) continue;
59
-
60
- const parts = trimmed.split(/\s+/);
61
- const id = parts[0];
62
- const statusRaw = parts[1];
63
-
64
- if (!id || !statusRaw) continue;
65
-
66
- let status: DeviceInfo['status'];
67
- if (statusRaw === 'device') status = 'ready';
68
- else if (statusRaw === 'offline') status = 'offline';
69
- else if (statusRaw === 'unauthorized') status = 'unauthorized';
70
- else continue;
71
-
72
- // Extract model from -l output: model:SM_S911B → "Samsung SM-S911B"
73
- const modelMatch = trimmed.match(/model:(\S+)/);
74
- const productMatch = trimmed.match(/product:(\S+)/);
75
- const rawModel = modelMatch?.[1] ?? productMatch?.[1] ?? id;
76
- const name = rawModel.replace(/_/g, ' ').trim();
77
-
78
- // Try to get Android version
79
- let osVersion: string | undefined;
80
- if (status === 'ready') {
81
- try {
82
- osVersion = execSync(
83
- `"${adb}" -s ${id} shell getprop ro.build.version.release`,
84
- { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 3000 }
85
- ).trim();
86
- } catch {}
87
- }
88
-
89
- devices.push({ id, platform: 'android', name, status, osVersion });
90
- }
91
-
92
- return devices;
93
- } catch {
94
- return [];
95
- }
96
- }
97
-
98
- // ─── iOS ────────────────────────────────────────────────────────────────────
99
-
100
- export function detectIosDevices(): DeviceInfo[] {
101
- // Strategy 1: xcrun devicectl (Xcode 15+, macOS Sonoma+)
102
- const fromDevicectl = _detectViaDevicectl();
103
- if (fromDevicectl.length > 0) return fromDevicectl;
104
-
105
- // Strategy 2: idevice_id + ideviceinfo (libimobiledevice)
106
- return _detectViaLibimobiledevice();
107
- }
108
-
109
- function _detectViaDevicectl(): DeviceInfo[] {
110
- // Write JSON to a temp file to avoid stdout pollution from devicectl warnings
111
- const tmpFile = join(tmpdir(), `fsqa-devices-${Date.now()}.json`);
112
- try {
113
- execSync(
114
- `xcrun devicectl list devices --json-output "${tmpFile}" 2>/dev/null`,
115
- { stdio: 'ignore', timeout: 8000 }
116
- );
117
-
118
- if (!existsSync(tmpFile)) return [];
119
- const raw = readFileSync(tmpFile, 'utf8');
120
- const parsed = JSON.parse(raw);
121
- const result: any[] = parsed?.result?.devices ?? [];
122
-
123
- return result
124
- .filter((d: any) => {
125
- const transport = d.connectionProperties?.transportType ?? '';
126
- // Accept wired connections regardless of tunnel state (shows offline if not tunneled)
127
- return transport.toLowerCase().includes('wired');
128
- })
129
- .map((d: any) => {
130
- const tunnelState = d.connectionProperties?.tunnelState ?? '';
131
- const status: DeviceInfo['status'] =
132
- tunnelState === 'connected' ? 'ready' : 'offline';
133
-
134
- return {
135
- id: d.hardwareProperties?.udid ?? d.identifier ?? 'unknown',
136
- platform: 'ios' as const,
137
- name: d.deviceProperties?.name ?? d.hardwareProperties?.marketingName ?? 'iOS Device',
138
- status,
139
- osVersion: d.deviceProperties?.osVersionNumber,
140
- };
141
- });
142
- } catch {
143
- return [];
144
- } finally {
145
- try { unlinkSync(tmpFile); } catch {}
146
- }
147
- }
148
-
149
- function _detectViaLibimobiledevice(): DeviceInfo[] {
150
- try {
151
- const ids = execSync('idevice_id -l', {
152
- encoding: 'utf8',
153
- stdio: ['ignore', 'pipe', 'pipe'],
154
- timeout: 5000,
155
- }).trim().split('\n').filter(Boolean);
156
-
157
- return ids.map(udid => {
158
- let name = 'iOS Device';
159
- let osVersion: string | undefined;
160
-
161
- try {
162
- const info = execSync(`ideviceinfo -u ${udid} -k DeviceName`, {
163
- encoding: 'utf8',
164
- stdio: ['ignore', 'pipe', 'pipe'],
165
- timeout: 3000,
166
- }).trim();
167
- if (info) name = info;
168
- } catch {}
169
-
170
- try {
171
- osVersion = execSync(`ideviceinfo -u ${udid} -k ProductVersion`, {
172
- encoding: 'utf8',
173
- stdio: ['ignore', 'pipe', 'pipe'],
174
- timeout: 3000,
175
- }).trim();
176
- } catch {}
177
-
178
- return { id: udid, platform: 'ios' as const, name, status: 'ready' as const, osVersion };
179
- });
180
- } catch {
181
- return [];
182
- }
183
- }
184
-
185
- // ─── Unified detection ───────────────────────────────────────────────────────
186
-
187
- export function detectAllDevices(platform?: 'android' | 'ios' | 'all'): DeviceInfo[] {
188
- const target = platform ?? 'all';
189
- const android = target !== 'ios' ? detectAndroidDevices() : [];
190
- const ios = target !== 'android' ? detectIosDevices() : [];
191
- return [...android, ...ios];
192
- }
193
-
194
- export function readyDevices(platform?: 'android' | 'ios' | 'all'): DeviceInfo[] {
195
- return detectAllDevices(platform).filter(d => d.status === 'ready');
196
- }