| 161 | }; |
| 162 | |
| 163 | export const startCommand = async ( |
| 164 | command: string, |
| 165 | args: string[], |
| 166 | { |
| 167 | startTimeout = DEFAULT_ASSERTION_TIMEOUT, |
| 168 | ...options |
| 169 | }: StartCommandOptions = {}, |
| 170 | ): Promise<TestCLI> => { |
| 171 | const child = spawn(command, args, options); |
| 172 | return new Promise((resolve, reject) => { |
| 173 | const onTimeout = () => { |
| 174 | cleanup(); |
| 175 | reject(new AssertionTimeoutError('startCommand', startTimeout)); |
| 176 | }; |
| 177 | const onError = (err) => { |
| 178 | cleanup(); |
| 179 | reject(err); |
| 180 | }; |
| 181 | const onSpawn = () => { |
| 182 | cleanup(); |
| 183 | resolve(createTestCLI(child)); |
| 184 | }; |
| 185 | const cleanup = () => { |
| 186 | child.removeListener('error', onError); |
| 187 | child.removeListener('spawn', onSpawn); |
| 188 | clearTimeout(timeoutId); |
| 189 | }; |
| 190 | |
| 191 | const timeoutId = setTimeout(onTimeout, startTimeout); |
| 192 | child.once('error', onError); |
| 193 | child.once('spawn', onSpawn); |
| 194 | |
| 195 | if (!SUPPORTS_SPAWN_EVENT) { |
| 196 | const onInterval = () => { |
| 197 | if (child.stdout.readable) { |
| 198 | clearInterval(intervalId); |
| 199 | onSpawn(); |
| 200 | } |
| 201 | }; |
| 202 | const intervalId = setInterval(onInterval, 100); |
| 203 | onInterval(); // check immediately |
| 204 | } |
| 205 | }); |
| 206 | }; |
| 207 | |
| 208 | /** |
| 209 | * Starts Snyk CLI and provides a test wrapper for performing typical actions |