-
-
Notifications
You must be signed in to change notification settings - Fork 737
/
Copy pathpause.js
205 lines (183 loc) · 6.3 KB
/
pause.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
const colors = require('chalk');
const readline = require('readline');
const ora = require('ora-classic');
const debug = require('debug')('codeceptjs:pause');
const container = require('./container');
const history = require('./history');
const store = require('./store');
const AiAssistant = require('./ai');
const recorder = require('./recorder');
const event = require('./event');
const output = require('./output');
const { methodsOfObject } = require('./utils');
// npm install colors
let rl;
let nextStep;
let finish;
let next;
let registeredVariables = {};
const aiAssistant = new AiAssistant();
/**
* Pauses test execution and starts interactive shell
* @param {Object<string, *>} [passedObject]
*/
const pause = function (passedObject = {}) {
if (store.dryRun) return;
next = false;
// add listener to all next steps to provide next() functionality
event.dispatcher.on(event.step.after, () => {
recorder.add('Start next pause session', () => {
if (!next) return;
return pauseSession();
});
});
recorder.add('Start new session', () => pauseSession(passedObject));
};
function pauseSession(passedObject = {}) {
registeredVariables = passedObject;
recorder.session.start('pause');
if (!next) {
let vars = Object.keys(registeredVariables).join(', ');
if (vars) vars = `(vars: ${vars})`;
output.print(colors.yellow(' Interactive shell started'));
output.print(colors.yellow(' Use JavaScript syntax to try steps in action'));
output.print(colors.yellow(` - Press ${colors.bold('ENTER')} to run the next step`));
output.print(colors.yellow(` - Press ${colors.bold('TAB')} twice to see all available commands`));
output.print(colors.yellow(` - Type ${colors.bold('exit')} + Enter to exit the interactive shell`));
output.print(colors.yellow(` - Prefix ${colors.bold('=>')} to run js commands ${colors.bold(vars)}`));
if (aiAssistant.isEnabled) {
output.print(colors.blue(` ${colors.bold('OpenAI is enabled! (experimental)')} Write what you want and make OpenAI run it`));
output.print(colors.blue(' Please note, only HTML fragments with interactive elements are sent to OpenAI'));
output.print(colors.blue(' Ideas: ask it to fill forms for you or to click'));
} else {
output.print(colors.blue(` Enable OpenAI assistant by setting ${colors.bold('OPENAI_API_KEY')} env variable`));
}
}
rl = readline.createInterface(process.stdin, process.stdout, completer);
rl.on('line', parseInput);
rl.on('close', () => {
if (!next) console.log('Exiting interactive shell....');
});
return new Promise(((resolve) => {
finish = resolve;
// eslint-disable-next-line
return askForStep();
}));
}
/* eslint-disable */
async function parseInput(cmd) {
rl.pause();
next = false;
recorder.session.start('pause');
if (cmd === '') next = true;
if (!cmd || cmd === 'resume' || cmd === 'exit') {
finish();
recorder.session.restore();
rl.close();
history.save();
return nextStep();
}
for (const k of Object.keys(registeredVariables)) {
eval(`var ${k} = registeredVariables['${k}'];`); // eslint-disable-line no-eval
}
let executeCommand = Promise.resolve();
const getCmd = () => {
debug('Command:', cmd)
return cmd;
};
let isCustomCommand = false;
let lastError = null;
let isAiCommand = false;
let $res;
try {
const locate = global.locate; // enable locate in this context
const I = container.support('I');
if (cmd.trim().startsWith('=>')) {
isCustomCommand = true;
cmd = cmd.trim().substring(2, cmd.length);
} else if (aiAssistant.isEnabled && !cmd.match(/^\w+\(/) && cmd.includes(' ')) {
const currentOutputLevel = output.level();
output.level(0);
const res = I.grabSource();
isAiCommand = true;
executeCommand = executeCommand.then(async () => {
try {
const html = await res;
aiAssistant.setHtmlContext(html);
} catch (err) {
output.print(output.styles.error(' ERROR '), 'Can\'t get HTML context', err.stack);
return;
} finally {
output.level(currentOutputLevel);
}
// aiAssistant.mockResponse("```js\nI.click('Sign in');\n```");
const spinner = ora("Processing OpenAI request...").start();
cmd = await aiAssistant.writeSteps(cmd);
spinner.stop();
output.print('');
output.print(colors.blue(aiAssistant.getResponse()));
output.print('');
return cmd;
})
} else {
cmd = `I.${cmd}`;
}
executeCommand = executeCommand.then(async () => {
const cmd = getCmd();
if (!cmd) return;
return eval(cmd); // eslint-disable-line no-eval
}).catch((err) => {
debug(err);
if (isAiCommand) return;
if (!lastError) output.print(output.styles.error(' ERROR '), err.message);
debug(err.stack)
lastError = err.message;
})
const val = await executeCommand;
if (isCustomCommand) {
if (val !== undefined) console.log('Result', '$res=', val); // eslint-disable-line
$res = val;
}
if (cmd?.startsWith('I.see') || cmd?.startsWith('I.dontSee')) {
output.print(output.styles.success(' OK '), cmd);
}
if (cmd?.startsWith('I.grab')) {
output.print(output.styles.debug(val));
}
history.push(cmd); // add command to history when successful
} catch (err) {
if (!lastError) output.print(output.styles.error(' ERROR '), err.message);
lastError = err.message;
}
recorder.session.catch((err) => {
const msg = err.cliMessage ? err.cliMessage() : err.message;
// pop latest command from history because it failed
history.pop();
if (isAiCommand) return;
if (!lastError) output.print(output.styles.error(' FAIL '), msg);
lastError = err.message;
});
recorder.add('ask for next step', askForStep);
nextStep();
}
/* eslint-enable */
function askForStep() {
return new Promise(((resolve) => {
nextStep = resolve;
rl.setPrompt(' I.', 3);
rl.resume();
rl.prompt([false]);
}));
}
function completer(line) {
const I = container.support('I');
const completions = methodsOfObject(I);
const hits = completions.filter((c) => {
if (c.indexOf(line) === 0) {
return c;
}
return null;
});
return [hits && hits.length ? hits : completions, line];
}
module.exports = pause;