qa 0.0.20 → 0.0.22

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/LICENSE CHANGED
@@ -186,7 +186,7 @@ file or class name and description of purpose be included on the
186
186
  same "printed page" as the copyright notice for easier
187
187
  identification within third-party archives.
188
188
 
189
- Copyright 2024 CodelessQA
189
+ Copyright 2025 VollQ
190
190
 
191
191
  Licensed under the Apache License, Version 2.0 (the "License");
192
192
  you may not use this file except in compliance with the License.
@@ -0,0 +1,3 @@
1
+ import type { TestCommandParameters } from '../commands/types.js';
2
+ export declare function runAPITest(token: string, argv: TestCommandParameters): Promise<void>;
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,103 @@
1
+ import WebSocket from 'ws';
2
+ import { CLIReporter } from '../reporter.js';
3
+ import { WORKER_URL, PLATFORM_URL } from '../constants.js';
4
+ const PROBLEMATIC_ERROR_CODES = ['ECONNREFUSED', 'ECONNRESET', 'EPIPE', 'ETIMEDOUT'];
5
+ const WORKER_ENDPOINT = `http${WORKER_URL.slice(2)}/api`;
6
+ export async function runAPITest(token, argv) {
7
+ const { sessionId } = await initiateSession(token, argv.project);
8
+ await runTest(sessionId);
9
+ const { passed } = await deleteSession(token, sessionId);
10
+ console.log(`\n➡️ See more test details at ${PLATFORM_URL}/api-testing/tests/${sessionId}`);
11
+ process.exit(passed ? 0 : 1);
12
+ }
13
+ async function initiateSession(token, testId) {
14
+ try {
15
+ const res = await fetch(WORKER_ENDPOINT, {
16
+ method: 'POST',
17
+ headers: {
18
+ 'Content-Type': 'application/json',
19
+ Authorization: token
20
+ },
21
+ body: JSON.stringify({ testId })
22
+ });
23
+ if (!res.ok || res.status !== 200) {
24
+ const error = await res.json();
25
+ if (res.statusText === 'Unauthorized') {
26
+ throw new Error('\n🚨 Failed to authenticate with the platform, please login, via:\n\n' +
27
+ ' > qa login\n\n' +
28
+ 'If you are already logged in, please check if the token is correct.\n' +
29
+ 'More information can be found at: https://docs.vollq.ai/cli\n');
30
+ }
31
+ throw new Error(`Failed to initiate session: ${res.statusText}: ${error.message}`);
32
+ }
33
+ return await res.json();
34
+ }
35
+ catch (err) {
36
+ const error = err instanceof Error ? err : new Error('Unknown error');
37
+ if (error.message === 'fetch failed') {
38
+ console.error('⚠️ Failed to connect to the platform!\n' +
39
+ 'Please check your internet connection and try again.\n\n' +
40
+ 'If the problem persists, please let us know at: support@vollq.ai');
41
+ }
42
+ else {
43
+ console.error(error.message);
44
+ }
45
+ process.exit(1);
46
+ }
47
+ }
48
+ async function runTest(sessionId) {
49
+ const workerUrl = `${WORKER_URL}/api/${sessionId}`;
50
+ const ws = new WebSocket(workerUrl);
51
+ ws.on('error', (error) => {
52
+ if ('code' in error && PROBLEMATIC_ERROR_CODES.includes(error.code)) {
53
+ console.error(`⚠️ Failed to connect to worker at ${workerUrl}: ${error.code}!\n` +
54
+ 'This is unexpected, we apologize for the inconvenience!\n' +
55
+ 'Please send us a message and let us know at: support@vollq.ai\n\n' +
56
+ 'Thank you! 🙏');
57
+ process.exit(1);
58
+ return;
59
+ }
60
+ console.error(error);
61
+ });
62
+ const reporter = new CLIReporter();
63
+ await new Promise((resolve, reject) => {
64
+ ws.on('message', function message(data) {
65
+ try {
66
+ const msg = JSON.parse(data.toString());
67
+ if (msg.type === 'error') {
68
+ return reject(new Error(msg.error));
69
+ }
70
+ if (msg.type === 'log') {
71
+ return reporter.emitEvent(msg.payload);
72
+ }
73
+ if (msg.type === 'end') {
74
+ reporter.end();
75
+ return resolve(null);
76
+ }
77
+ }
78
+ catch (err) {
79
+ const error = err instanceof Error ? err : new Error('Unknown error');
80
+ return reject(new Error(`Uups! Something went wrong: ${error.message}`));
81
+ }
82
+ });
83
+ });
84
+ }
85
+ async function deleteSession(token, sessionId) {
86
+ try {
87
+ const res = await fetch(`${WORKER_ENDPOINT}/${sessionId}`, {
88
+ method: 'DELETE',
89
+ headers: {
90
+ Authorization: token
91
+ }
92
+ });
93
+ if (!res.ok || res.status !== 200) {
94
+ throw new Error(`Failed to delete session: ${res.statusText}`);
95
+ }
96
+ return await res.json();
97
+ }
98
+ catch (err) {
99
+ const error = err instanceof Error ? err : new Error('Unknown error');
100
+ console.error(`Failed to delete session: ${error.message}`);
101
+ return { passed: false };
102
+ }
103
+ }
package/dist/auth.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export declare function getAccessToken(tokenParam?: string): Promise<string>;
1
+ export declare function getAccessToken<EnsureAuth extends boolean = true>(tokenParam?: string, ensureAuth?: EnsureAuth | true): Promise<EnsureAuth extends true ? string : string | undefined>;
2
2
  //# sourceMappingURL=auth.d.ts.map
package/dist/auth.js CHANGED
@@ -2,23 +2,26 @@ import fs from 'node:fs/promises';
2
2
  import { intro } from '@clack/prompts';
3
3
  import { askForUserAuth } from './commands/utils/prompts.js';
4
4
  import { TOKEN_PATH } from './constants.js';
5
- export async function getAccessToken(tokenParam) {
5
+ export async function getAccessToken(tokenParam, ensureAuth) {
6
6
  if (tokenParam) {
7
7
  return tokenParam;
8
8
  }
9
- const envVar = process.env.CODELESS_TOKEN;
9
+ const envVar = process.env.VOLLQ_TOKEN;
10
10
  if (envVar) {
11
11
  return envVar;
12
12
  }
13
13
  const hasAccess = await fs.access(TOKEN_PATH).then(() => true).catch(() => false);
14
14
  if (!hasAccess) {
15
- intro('Log into CodelessQA');
16
- return askForUserAuth();
15
+ if (ensureAuth) {
16
+ intro('Log into VollQ');
17
+ return askForUserAuth();
18
+ }
19
+ return undefined;
17
20
  }
18
21
  const rc = await fs.readFile(TOKEN_PATH, 'utf-8');
19
22
  const token = rc.split('\n').filter(Boolean).find((line) => line.startsWith('token='))?.split('=')[1];
20
- if (!token) {
21
- intro('Log into CodelessQA');
23
+ if (!token && ensureAuth) {
24
+ intro('Log into VollQ');
22
25
  return askForUserAuth();
23
26
  }
24
27
  return token;
@@ -16,4 +16,5 @@ export declare const builder: (yargs: Argv) => Argv<import("yargs").Omit<{}, "to
16
16
  };
17
17
  }>>;
18
18
  export declare const handler: (argv?: Record<keyof typeof cmdArgs, string>) => Promise<string>;
19
+ export declare function login(ticket: string, log?: (message?: any, ...optionalParams: any[]) => void): Promise<string>;
19
20
  //# sourceMappingURL=login.d.ts.map
@@ -35,29 +35,33 @@ export const handler = async (argv) => {
35
35
  '',
36
36
  '...waiting for user to be authenticated...'
37
37
  ].join('\n'));
38
- execSync(`open ${loginUrl}`);
39
38
  try {
40
- const token = await new Promise((resolve, reject) => {
41
- const timeout = setTimeout(() => reject(new Error('timed out')), LOGIN_TIMEOUT);
42
- const interval = setInterval(async () => {
43
- const res = await client.auth.verifyTicket({ params: { ticket } });
44
- if (res.status !== 200) {
45
- if (res.status === 500) {
46
- return reject(new Error('Internal server error'));
47
- }
48
- return;
49
- }
50
- clearInterval(interval);
51
- clearTimeout(timeout);
52
- return resolve(res.body.token);
53
- }, LOGIN_VERIFY_INTERVAL);
54
- });
55
- await fs.writeFile(TOKEN_PATH, `token=${token}\n`);
56
- console.log('🎉 Successfully logged in!');
57
- return token;
39
+ return login(ticket);
58
40
  }
59
41
  catch (err) {
60
42
  console.log(`🚨 Failed to log-in: ${err.message}`);
61
43
  process.exit(1);
62
44
  }
63
45
  };
46
+ export async function login(ticket, log = console.log) {
47
+ const loginUrl = `${PLATFORM_URL}/login/${ticket}`;
48
+ execSync(`open ${loginUrl}`);
49
+ const token = await new Promise((resolve, reject) => {
50
+ const timeout = setTimeout(() => reject(new Error('timed out')), LOGIN_TIMEOUT);
51
+ const interval = setInterval(async () => {
52
+ const res = await client.auth.verifyTicket({ params: { ticket } });
53
+ if (res.status !== 200) {
54
+ if (res.status === 500) {
55
+ return reject(new Error('Internal server error'));
56
+ }
57
+ return;
58
+ }
59
+ clearInterval(interval);
60
+ clearTimeout(timeout);
61
+ return resolve(res.body.token);
62
+ }, LOGIN_VERIFY_INTERVAL);
63
+ });
64
+ await fs.writeFile(TOKEN_PATH, `token=${token}\n`);
65
+ log('🎉 Successfully logged in!');
66
+ return token;
67
+ }
@@ -15,5 +15,5 @@ export declare const builder: (yargs: Argv) => Argv<import("yargs").Omit<{}, "to
15
15
  readonly type: "string";
16
16
  };
17
17
  }>>;
18
- export declare const handler: () => Promise<void>;
18
+ export declare const handler: (argv: typeof cmdArgs) => Promise<void>;
19
19
  //# sourceMappingURL=start.d.ts.map
@@ -1,6 +1,15 @@
1
- import { remote } from 'webdriverio';
2
- // import { getAccessToken } from '../auth.js'
1
+ import { checkNodeVersion } from './utils/nodeVersion.js';
2
+ import { IDE } from '../ide/index.js';
3
+ import { getAccessToken } from '../auth.js';
3
4
  import { CLI_EPILOGUE } from '../constants.js';
5
+ let app;
6
+ const onShutdown = () => {
7
+ app?.handleShutdown();
8
+ process.exit(1);
9
+ };
10
+ process.on('SIGINT', onShutdown);
11
+ process.on('SIGTERM', onShutdown);
12
+ process.on('beforeExit', onShutdown);
4
13
  export const command = 'start [option]';
5
14
  export const desc = 'Start the CodelessQA IDE';
6
15
  export const cmdArgs = {
@@ -11,53 +20,14 @@ export const cmdArgs = {
11
20
  }
12
21
  };
13
22
  export const builder = (yargs) => {
23
+ checkNodeVersion();
14
24
  return yargs
15
25
  .options(cmdArgs)
16
26
  .example('qa start', desc)
17
27
  .epilogue(CLI_EPILOGUE)
18
28
  .help();
19
29
  };
20
- export const handler = async ( /*argv: typeof cmdArgs*/) => {
21
- // let token = await getAccessToken(argv.token as unknown as string)
22
- try {
23
- const [workbench, ide] = await Promise.all([
24
- remote({
25
- logLevel: 'error',
26
- capabilities: getCapabilities('1024,768', '100,100')
27
- }),
28
- remote({
29
- logLevel: 'error',
30
- capabilities: getCapabilities('500,768', '1124,100')
31
- })
32
- ]);
33
- const style = '"width: 100%; height: 100%; display: flex; flex-direction: column; justify-content: space-around; align-items: center;"';
34
- await Promise.all([
35
- openPage(workbench, `<h1 style=${style}>Workbench</h1>`),
36
- openPage(ide, `<div style=${style}>
37
- <h1>IDE</h1>
38
- <span>(I will close myself in 5s)</span>
39
- </div>`)
40
- ]);
41
- setTimeout(() => {
42
- workbench.deleteSession();
43
- ide.deleteSession();
44
- }, 5000);
45
- }
46
- catch (err) {
47
- console.error('Failed to start the CodelessQA IDE', err);
48
- }
30
+ export const handler = async (argv) => {
31
+ const token = await getAccessToken(argv.token);
32
+ app = await IDE.start(token);
49
33
  };
50
- function getCapabilities(windowSize, windowPosition) {
51
- return {
52
- browserName: 'chrome',
53
- 'goog:chromeOptions': {
54
- args: [
55
- `window-size=${windowSize}`,
56
- `window-position=${windowPosition}`,
57
- ]
58
- }
59
- };
60
- }
61
- function openPage(driver, html) {
62
- driver.url('data:text/html,' + html);
63
- }
@@ -1,5 +1,6 @@
1
1
  import type { Argv } from 'yargs';
2
- export declare const command = "test <project> [option]";
2
+ import type { TestCommandParameters } from './types.js';
3
+ export declare const command = "test <type> <project> [option]";
3
4
  export declare const desc = "Run a test on the codeless.qa platform";
4
5
  export declare const cmdArgs: {
5
6
  readonly token: {
@@ -12,7 +13,7 @@ export declare const cmdArgs: {
12
13
  readonly type: "string";
13
14
  };
14
15
  readonly reporter: {
15
- readonly desc: `Specify the reporter to use for the test (supported: ${string})`;
16
+ readonly desc: "Specify the reporter to use for the test (currently only \"spec\" is supported)";
16
17
  readonly type: "string";
17
18
  readonly default: "spec";
18
19
  readonly alias: "r";
@@ -29,13 +30,13 @@ export declare const builder: (yargs: Argv) => Argv<import("yargs").Omit<{}, "to
29
30
  readonly type: "string";
30
31
  };
31
32
  readonly reporter: {
32
- readonly desc: `Specify the reporter to use for the test (supported: ${string})`;
33
+ readonly desc: "Specify the reporter to use for the test (currently only \"spec\" is supported)";
33
34
  readonly type: "string";
34
35
  readonly default: "spec";
35
36
  readonly alias: "r";
36
37
  };
37
38
  }>>;
38
39
  export declare const handler: (argv: typeof cmdArgs & {
39
- project: string;
40
- }) => Promise<never>;
40
+ type: "api" | "ui";
41
+ } & TestCommandParameters) => Promise<void>;
41
42
  //# sourceMappingURL=test.d.ts.map
@@ -1,16 +1,8 @@
1
- import { spawn } from 'node:child_process';
2
- import { createRequire } from 'node:module';
3
- import WebSocket from 'ws';
4
- import { getAuthenticatedClient } from '@codeless.qa/contracts/client';
5
- import { pullTestSuite } from '../api.js';
1
+ import { runAPITest } from '../api/index.js';
2
+ import { runUITest } from '../ui/index.js';
6
3
  import { getAccessToken } from '../auth.js';
7
- import { CLI_EPILOGUE, WORKER_URL, PLATFORM_URL } from '../constants.js';
8
- const SUPPORTED_REPORTER = [
9
- 'classic', 'doc', 'dot', 'dump', 'json', 'jsonstream', 'landing',
10
- 'list', 'markdown', 'min', 'nyan', 'progress', 'silent', 'spec',
11
- 'tap', 'xunit'
12
- ];
13
- export const command = 'test <project> [option]';
4
+ import { CLI_EPILOGUE } from '../constants.js';
5
+ export const command = 'test <type> <project> [option]';
14
6
  export const desc = 'Run a test on the codeless.qa platform';
15
7
  export const cmdArgs = {
16
8
  token: {
@@ -23,78 +15,31 @@ export const cmdArgs = {
23
15
  type: 'string',
24
16
  },
25
17
  reporter: {
26
- desc: `Specify the reporter to use for the test (supported: ${SUPPORTED_REPORTER.join(', ')})`,
18
+ desc: 'Specify the reporter to use for the test (currently only "spec" is supported)',
27
19
  type: 'string',
28
20
  default: 'spec',
29
21
  alias: 'r',
30
22
  }
31
23
  };
32
- const require = createRequire(import.meta.url);
33
24
  export const builder = (yargs) => {
34
25
  return yargs
35
26
  .options(cmdArgs)
36
- .example('qa test myAPI', 'Runs test on API named "myAPI"')
37
- .example('qa test myAPI -r nyan', 'Runs tests using the Nyan reporter')
27
+ .example('qa test ui login', 'Runs a UI browser test named "login"')
28
+ .example('qa test api myAPI', 'Runs test on API named "myAPI"')
29
+ .example('qa test api myAPI -r nyan', 'Runs tests using the Nyan reporter')
38
30
  .epilogue(CLI_EPILOGUE)
39
31
  .help();
40
32
  };
41
33
  export const handler = async (argv) => {
42
34
  const token = await getAccessToken(argv.token);
43
- const client = getAuthenticatedClient(token);
44
- const reporter = argv.reporter;
45
- if (!SUPPORTED_REPORTER.includes(reporter)) {
46
- throw new Error(`Reporter ${argv.reporter} is not supported, please select one of the following: ${SUPPORTED_REPORTER.join(', ')}`);
35
+ if (argv.reporter !== 'spec') {
36
+ throw new Error('Currently only the "spec" reporter is supported!');
47
37
  }
48
- const { testplan, specification } = await pullTestSuite(client, argv.project);
49
- const workerUrl = `${WORKER_URL}/session`;
50
- const ws = new WebSocket(workerUrl);
51
- ws.on('open', function open() {
52
- const payload = {
53
- type: 0,
54
- value: {
55
- testplan,
56
- specification
57
- }
58
- };
59
- ws.send(JSON.stringify(payload));
60
- });
61
- ws.on('error', (error) => {
62
- if ('code' in error && error.code === 'ECONNRESET') {
63
- console.error(`Failed to connect to worker at ${workerUrl}: ${error.message}!\n` +
64
- 'This is unexpected, we apologize for the inconvenience!\n' +
65
- 'Please send us a message and let us know at: support@codeless.qa\n\n' +
66
- 'Thank you! 🙏');
67
- process.exit(1);
68
- return;
69
- }
70
- console.error(error);
71
- });
72
- const { success, sessionId } = await new Promise((resolve, reject) => {
73
- const reporterProcess = spawn('node', [require.resolve('tap-mocha-reporter'), reporter], {
74
- stdio: ['pipe', 'inherit', 'inherit']
75
- });
76
- ws.on('message', function message(data) {
77
- try {
78
- const msg = JSON.parse(data.toString());
79
- if ('error' in msg && msg.error) {
80
- return reject(new Error(msg.error));
81
- }
82
- if (msg.type === 3) {
83
- return reporterProcess.stdin.write(msg.value.log);
84
- }
85
- if (msg.type === 2) {
86
- return resolve(msg.value);
87
- }
88
- if (msg.type === 4) {
89
- return reject(new Error(msg.value.error));
90
- }
91
- }
92
- catch (err) {
93
- const error = err instanceof Error ? err : new Error('Unknown error');
94
- return reject(new Error(`Uups! Something went wrong: ${error.message}`));
95
- }
96
- });
97
- });
98
- console.log(`\n➡️ See more test details at ${PLATFORM_URL}/api-testing/tests/${sessionId}`);
99
- process.exit(success ? 0 : 1);
38
+ if (argv.type === 'ui') {
39
+ return runUITest(token, argv);
40
+ }
41
+ if (argv.type === 'api') {
42
+ return runAPITest(token, argv);
43
+ }
44
+ throw new Error(`Invalid test type "${argv.type}", use "api" or "ui". See \`qa test --help\` for more information.`);
100
45
  };
@@ -0,0 +1,5 @@
1
+ export interface TestCommandParameters {
2
+ reporter?: string;
3
+ project: string;
4
+ }
5
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ export declare function checkNodeVersion(): boolean;
2
+ //# sourceMappingURL=nodeVersion.d.ts.map
@@ -0,0 +1,24 @@
1
+ import p from 'picocolors';
2
+ export function checkNodeVersion() {
3
+ const currentVersion = process.versions.node;
4
+ const majorVersion = parseInt(currentVersion.split('.')[0]);
5
+ const requiredVersion = 21;
6
+ if (majorVersion < requiredVersion) {
7
+ console.error(p.red(`
8
+ ╔════════════════════════════════════════════════════════════╗
9
+ ║ Version Check Failed ║
10
+ ╚════════════════════════════════════════════════════════════╝
11
+ `));
12
+ console.error(p.yellow(`The "qa" CLI requires Node.js v${requiredVersion} or higher.`));
13
+ console.error(p.yellow('Please upgrade your Node.js installation.'));
14
+ console.error(p.yellow('\nTo upgrade Node.js:'));
15
+ console.error(p.cyan(`
16
+ 1. Visit: https://nodejs.org
17
+ 2. Or use a version manager like nvm:
18
+ nvm install ${requiredVersion}
19
+ nvm use ${requiredVersion}
20
+ `));
21
+ process.exit(1);
22
+ }
23
+ return true;
24
+ }
package/dist/constants.js CHANGED
@@ -3,10 +3,10 @@ import { homedir } from 'node:os';
3
3
  import { createRequire } from 'node:module';
4
4
  const require = createRequire(import.meta.url);
5
5
  export const pkg = require('../package.json');
6
- export const CLI_EPILOGUE = `Documentation: https://codeless.qa/docs/cli
6
+ export const CLI_EPILOGUE = `Documentation: https://docs.vollq.ai/cli
7
7
  qa (v${pkg.version})
8
- © 2024 CodelessQA, Inc.
8
+ © 2025 VollQ, Inc.
9
9
  `;
10
10
  export const PLATFORM_URL = process.env.CODELESSQA_PLATFORM_URL || 'https://codeless.qa' || 'http://localhost:4000';
11
11
  export const WORKER_URL = process.env.CODELESSQA_WORKER_URL || 'wss://worker.codeless.qa' || 'ws://localhost:8080';
12
- export const TOKEN_PATH = path.join(homedir(), '/.codeless-qa');
12
+ export const TOKEN_PATH = path.join(homedir(), '/.vollqrc');
@@ -0,0 +1,8 @@
1
+ export declare class IDE {
2
+ #private;
3
+ static start(token?: string): Promise<IDE>;
4
+ constructor(token?: string);
5
+ start(): Promise<this>;
6
+ handleShutdown(): Promise<void>;
7
+ }
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,173 @@
1
+ import url from 'node:url';
2
+ import path from 'node:path';
3
+ import getPort from 'get-port';
4
+ import Fastify from 'fastify';
5
+ import staticServer from '@fastify/static';
6
+ import websocket from '@fastify/websocket';
7
+ import LocalDriver from 'localdriver';
8
+ import { v4 as uuidv4 } from 'uuid';
9
+ import { NeuralSpec } from 'neuralspec';
10
+ import { remote } from 'webdriverio';
11
+ import { WebSocketClient } from '@codeless.qa/contracts';
12
+ import { getCapabilities, attachTokenToWindow } from './utils.js';
13
+ import { login } from '../commands/login.js';
14
+ export class IDE {
15
+ #isShuttingDown = false;
16
+ #token;
17
+ #messager;
18
+ #fastify;
19
+ #ideSession;
20
+ #workbenchSession;
21
+ static start(token) {
22
+ const ideApp = new IDE(token);
23
+ return ideApp.start();
24
+ }
25
+ constructor(token) {
26
+ this.#token = token;
27
+ this.#fastify = Fastify({ logger: true });
28
+ }
29
+ async start() {
30
+ const url = await this.#startApplication();
31
+ await this.#startSessions(url);
32
+ return this;
33
+ }
34
+ async handleShutdown() {
35
+ if (this.#isShuttingDown) {
36
+ return;
37
+ }
38
+ this.#isShuttingDown = true;
39
+ try {
40
+ this.#messager = undefined;
41
+ this.#fastify.log.info('Shutting down the CodelessQA IDE');
42
+ await Promise.all([
43
+ this.#ideSession?.deleteSession(),
44
+ this.#workbenchSession?.deleteSession(),
45
+ this.#fastify.close()
46
+ ]).catch((err) => {
47
+ this.#fastify.log.error('Failed to close the application', err);
48
+ });
49
+ process.exit(0);
50
+ }
51
+ catch (error) {
52
+ console.error('Error during shutdown:', error);
53
+ process.exit(1);
54
+ }
55
+ }
56
+ async #startApplication() {
57
+ try {
58
+ const port = await getPort({
59
+ /**
60
+ * pick between 6000 and 6005 which are whitelisted ports to access the API without CORS
61
+ */
62
+ port: [...Array(5)].map((_, i) => i + 8000)
63
+ });
64
+ const appPath = path.dirname(url.fileURLToPath(import.meta.resolve('@codeless.qa/ide')));
65
+ this.#fastify.log.info(`Serve IDE from ${appPath}`);
66
+ await this.#fastify.register(websocket);
67
+ await this.#fastify.register(staticServer, {
68
+ root: appPath,
69
+ prefix: '/',
70
+ index: 'index.html'
71
+ });
72
+ this.#fastify.get('/ws', { websocket: true }, (socket) => {
73
+ this.#messager = new WebSocketClient(socket);
74
+ this.#messager.onCommand('runWorkflow', this.#runSuggestion.bind(this));
75
+ this.#messager.onCommand('runTest', this.#runTest.bind(this));
76
+ this.#messager.onCommand('closeApp', this.handleShutdown.bind(this));
77
+ this.#messager.onCommand('login', this.#login.bind(this));
78
+ });
79
+ const ideUrl = await this.#fastify.listen({ port });
80
+ this.#fastify.log.info(`IDE is running on ${ideUrl}`);
81
+ return ideUrl;
82
+ }
83
+ catch (err) {
84
+ this.#fastify.log.error('Failed to start the CodelessQA IDE', err);
85
+ throw err;
86
+ }
87
+ }
88
+ async #startSessions(url) {
89
+ try {
90
+ const [workbench, ide] = await Promise.all([
91
+ remote({
92
+ /**
93
+ * run workbench with `localdriver` package so we can request tests to
94
+ * execute from the cloud
95
+ */
96
+ automationProtocol: LocalDriver.protocolPath,
97
+ logLevel: 'error',
98
+ capabilities: getCapabilities('workbench'),
99
+ }),
100
+ remote({
101
+ logLevel: 'error',
102
+ capabilities: getCapabilities('ide')
103
+ })
104
+ ]);
105
+ this.#ideSession = ide;
106
+ this.#workbenchSession = workbench;
107
+ /**
108
+ * Inject the token into the IDE session
109
+ */
110
+ if (this.#token) {
111
+ await this.#registerToken(this.#token);
112
+ }
113
+ await Promise.all([
114
+ this.#ideSession.url(url),
115
+ this.#workbenchSession.url('https://codelessqa.com'),
116
+ ]);
117
+ }
118
+ catch (err) {
119
+ console.error('Failed to start the CodelessQA IDE', err);
120
+ }
121
+ }
122
+ #registerToken(token) {
123
+ return Promise.all([
124
+ this.#ideSession?.addInitScript(attachTokenToWindow, token),
125
+ this.#ideSession?.execute(attachTokenToWindow, token)
126
+ ]).catch((err) => {
127
+ this.#fastify.log.error('Failed to attach token to the IDE session', err);
128
+ });
129
+ }
130
+ async #runSuggestion({ prompt }) {
131
+ if (!this.#workbenchSession) {
132
+ throw new Error('Workbench session is not available');
133
+ }
134
+ const ai = new NeuralSpec({
135
+ driver: this.#workbenchSession,
136
+ token: this.#token
137
+ });
138
+ ai.onAgentEvent((event) => {
139
+ this.#messager?.emit('agentEvent', event);
140
+ });
141
+ return ai.do(prompt).end({ closeBrowserSession: false })
142
+ .then(({ workflowId }) => {
143
+ if (workflowId) {
144
+ this.#messager?.emit('workflowFinished', { workflowId });
145
+ }
146
+ return ({ result: 'success', workflowId });
147
+ }, (err) => {
148
+ const error = err instanceof Error ? err : new Error(`An error occurred: ${err}`);
149
+ const message = `Failed to run the suggestion: ${prompt}, ${error.message}`;
150
+ this.#fastify.log.error(error.stack);
151
+ return { error: message, result: 'error' };
152
+ });
153
+ }
154
+ async #runTest({ name }) {
155
+ if (!this.#workbenchSession) {
156
+ throw new Error('IDE session is not available');
157
+ }
158
+ this.#fastify.log.info(`Run test "${name}" in workbench`);
159
+ await this.#workbenchSession.startTest(name);
160
+ }
161
+ async #login() {
162
+ const ticket = uuidv4();
163
+ try {
164
+ const token = await login(ticket, this.#fastify.log.info.bind(this.#fastify.log));
165
+ await this.#registerToken(token);
166
+ return { token };
167
+ }
168
+ catch (err) {
169
+ this.#fastify.log.error(`Failed to log-in: ${err.message}`);
170
+ return {};
171
+ }
172
+ }
173
+ }
@@ -0,0 +1,14 @@
1
+ declare const appSettings: {
2
+ readonly ide: {
3
+ readonly size: "500,900";
4
+ readonly position: "1590,100";
5
+ };
6
+ readonly workbench: {
7
+ readonly size: "1440,900";
8
+ readonly position: "100,100";
9
+ };
10
+ };
11
+ export declare function getCapabilities(appName: keyof typeof appSettings): WebdriverIO.Capabilities;
12
+ export declare function attachTokenToWindow(token: string): void;
13
+ export {};
14
+ //# sourceMappingURL=utils.d.ts.map
@@ -0,0 +1,53 @@
1
+ /// <reference types="webdriverio" />
2
+ const appSettings = {
3
+ ide: {
4
+ size: '500,900',
5
+ position: '1590,100'
6
+ },
7
+ workbench: {
8
+ size: '1440,900',
9
+ position: '100,100'
10
+ }
11
+ };
12
+ export function getCapabilities(appName) {
13
+ const appArgs = [];
14
+ const prefs = {};
15
+ /**
16
+ * when in development, open IDE with devtools opened
17
+ */
18
+ if (typeof process.argv[1] === 'string' && process.argv[1].includes('packages/qa/') && appName === 'ide') {
19
+ appArgs.push('auto-open-devtools-for-tabs', 'new-window', 'start-maximized', 'disable-infobars');
20
+ Object.assign(prefs, {
21
+ devtools: {
22
+ preferences: {
23
+ 'panel-selectedTab': '"console"',
24
+ currentDockState: '"undocked"',
25
+ }
26
+ }
27
+ });
28
+ }
29
+ return {
30
+ browserName: 'chrome',
31
+ browserVersion: 'latest',
32
+ 'wdio:chromedriverOptions': {
33
+ /**
34
+ * spawn driver process in detached mode so we can smoothly close the process
35
+ */
36
+ spawnOpts: {
37
+ detached: true
38
+ }
39
+ },
40
+ 'goog:chromeOptions': {
41
+ args: [
42
+ `window-size=${appSettings[appName].size}`,
43
+ `window-position=${appSettings[appName].position}`,
44
+ ...appArgs
45
+ ],
46
+ prefs
47
+ }
48
+ };
49
+ }
50
+ export function attachTokenToWindow(token) {
51
+ // @ts-expect-error missing window types
52
+ globalThis.window.__VOLLQ_TOKEN = token;
53
+ }
@@ -0,0 +1,8 @@
1
+ import { type TestEvent } from 'node:test/reporters';
2
+ export declare class CLIReporter {
3
+ #private;
4
+ constructor();
5
+ emitEvent(events: TestEvent[]): void;
6
+ end(): void;
7
+ }
8
+ //# sourceMappingURL=reporter.d.ts.map
@@ -0,0 +1,24 @@
1
+ import { spec } from 'node:test/reporters';
2
+ export class CLIReporter {
3
+ #reporter;
4
+ constructor() {
5
+ this.#reporter = new spec();
6
+ console.log('');
7
+ }
8
+ emitEvent(events) {
9
+ events.map((ev) => {
10
+ if (ev.type === 'test:fail') {
11
+ const error = ev.data.details.error.cause;
12
+ if (typeof error === 'object' && 'message' in error && 'stack' in error) {
13
+ const newError = new Error(error.message);
14
+ newError.stack = error.stack;
15
+ ev.data.details.error.cause = newError;
16
+ }
17
+ }
18
+ return ev;
19
+ }).forEach((ev) => (this.#reporter._transform(ev, 'utf-8', (_, report) => process.stdout.write(report || ''))));
20
+ }
21
+ end() {
22
+ this.#reporter._flush((_, log) => process.stdout.write(log || ''));
23
+ }
24
+ }
@@ -0,0 +1,3 @@
1
+ import type { TestCommandParameters } from '../commands/types.js';
2
+ export declare function runUITest(token: string, argv: TestCommandParameters): Promise<void>;
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,29 @@
1
+ import LocalDriver from 'localdriver';
2
+ import { remote } from 'webdriverio';
3
+ import { CLIReporter } from '../reporter.js';
4
+ export async function runUITest(token, argv) {
5
+ let driver;
6
+ const reporterProcess = new CLIReporter();
7
+ try {
8
+ driver = await remote({
9
+ automationProtocol: LocalDriver.protocolPath,
10
+ logLevel: 'error',
11
+ capabilities: {
12
+ browserName: 'chrome',
13
+ // @ts-expect-error not yet types
14
+ 'vollq:token': token
15
+ }
16
+ });
17
+ await driver.startTest(argv.project, reporterProcess.emitEvent.bind(reporterProcess));
18
+ }
19
+ catch (err) {
20
+ const error = err instanceof Error ? err : new Error(`Failed to run test: ${err}`);
21
+ console.error(error);
22
+ process.exit(1);
23
+ }
24
+ finally {
25
+ await driver?.deleteSession();
26
+ reporterProcess.end();
27
+ console.log('');
28
+ }
29
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "qa",
3
- "version": "0.0.20",
3
+ "version": "0.0.22",
4
4
  "author": "Christian Bromann <christian@codeless.qa>",
5
5
  "description": "Codeless QA CLI",
6
6
  "license": "Apache-2.0",
@@ -11,20 +11,29 @@
11
11
  "keywords": [],
12
12
  "dependencies": {
13
13
  "@clack/prompts": "^0.8.1",
14
- "@types/uuid": "^9.0.8",
15
- "@types/ws": "^8.5.10",
16
- "@types/yargs": "^17.0.32",
14
+ "@fastify/static": "^8.0.4",
15
+ "@fastify/websocket": "^11.0.2",
16
+ "fastify": "^5.2.1",
17
+ "get-port": "^7.1.0",
17
18
  "openapi-types": "^12.1.3",
19
+ "picocolors": "^1.1.1",
18
20
  "tap-mocha-reporter": "^5.0.4",
19
21
  "uuid": "^11.0.3",
20
- "ws": "^8.17.0",
22
+ "ws": "^8.18.0",
21
23
  "yargs": "^17.7.2",
22
- "webdriverio": "^9.5.0",
23
- "@codeless.qa/contracts": "0.0.10"
24
+ "webdriverio": "^9.6.4",
25
+ "@codeless.qa/contracts": "0.0.11",
26
+ "@codeless.qa/ide": "0.0.4",
27
+ "localdriver": "0.0.2",
28
+ "neuralspec": "0.0.2"
24
29
  },
25
30
  "devDependencies": {
31
+ "@types/uuid": "^9.0.8",
32
+ "@types/ws": "^8.5.10",
33
+ "@types/yargs": "^17.0.32",
26
34
  "replace-in-files-cli": "^3.0.0",
27
- "typescript": "^5.6.3"
35
+ "typescript": "^5.6.3",
36
+ "vitest": "^2.1.8"
28
37
  },
29
38
  "scripts": {
30
39
  "build": "run-s build:*",
@@ -32,6 +41,8 @@
32
41
  "build:replace": "run-s build:replace:*",
33
42
  "build:replace:platform": "replace-in-files --string='process.env.PLATFORM_URL' --replacement=\"process.env.CODELESSQA_PLATFORM_URL || '$PLATFORM_URL'\" ./dist/constants.js",
34
43
  "build:replace:worker": "replace-in-files --string='process.env.WORKER_URL' --replacement=\"process.env.CODELESSQA_WORKER_URL || '$WORKER_URL'\" ./dist/constants.js",
35
- "start": "tsc --watch --preserveWatchOutput"
44
+ "start": "tsc --watch --preserveWatchOutput",
45
+ "test": "run-s test.*",
46
+ "test.unit": "echo \"Error: no test specified\" && exit 0"
36
47
  }
37
48
  }
package/dist/api.d.ts DELETED
@@ -1,8 +0,0 @@
1
- import { type TestSuite } from '@codeless.qa/contracts';
2
- import { type Client } from '@codeless.qa/contracts/client';
3
- import { type OpenAPIV3 } from 'openapi-types';
4
- export declare function pullTestSuite(client: Client, project: string): Promise<{
5
- testplan: TestSuite;
6
- specification: OpenAPIV3.Document;
7
- }>;
8
- //# sourceMappingURL=api.d.ts.map
package/dist/api.js DELETED
@@ -1,28 +0,0 @@
1
- export async function pullTestSuite(client, project) {
2
- const apis = await client.specifications.get().catch((error) => {
3
- throw new Error(`Failed to fetch APIs: ${error} (${error.cause.code})`);
4
- });
5
- if (apis.status !== 200) {
6
- const error = apis.status === 401 ? apis.body.error : 'unknown';
7
- throw new Error(`Failed to fetch APIs: ${error}`);
8
- }
9
- const api = apis.body.data.find((api) => api.name === project);
10
- if (!api) {
11
- throw new Error(`API ${project} not found, please select one of the following: ${apis.body.data.map((api) => api.name).join(', ')}`);
12
- }
13
- const { body: specification, status } = await client.specification.get({ params: { id: api.id } });
14
- if (status !== 200) {
15
- throw new Error('Failed to fetch specification');
16
- }
17
- const testplan = await client.specification.test.get({ params: { id: api.id } });
18
- if (testplan.status !== 200) {
19
- throw new Error('Failed to fetch test plan');
20
- }
21
- if (!testplan.body.data) {
22
- throw new Error(`No test plan found for API ${project}, create on at https://codeless.qa/api-testing/specifications/${api.id}/plan`);
23
- }
24
- return {
25
- testplan: testplan.body.data,
26
- specification: specification.data.specification
27
- };
28
- }