summaryrefslogtreecommitdiff
path: root/packages/integrations/cloudflare/test/test-utils.js
blob: b4628825cf665d39ef8dcb47a77f46bb03560de3 (plain) (blame)
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
import { loadFixture as baseLoadFixture } from '../../../astro/test/test-utils.js';
import { spawn } from 'child_process';
import { fileURLToPath } from 'url';

export { fixLineEndings } from '../../../astro/test/test-utils.js';

/**
 * @typedef {import('../../../astro/test/test-utils').Fixture} Fixture
 */

export function loadFixture(config) {
	if (config?.root) {
		config.root = new URL(config.root, import.meta.url);
	}
	return baseLoadFixture(config);
}

const wranglerPath = fileURLToPath(
	new URL('../node_modules/wrangler/bin/wrangler.js', import.meta.url)
);

export function runCLI(basePath, { silent }) {
	const script = fileURLToPath(new URL(`${basePath}/dist/_worker.js`, import.meta.url));
	const p = spawn('node', [wranglerPath, 'dev', '-l', script]);

	p.stderr.setEncoding('utf-8');
	p.stdout.setEncoding('utf-8');

	const timeout = 10000;

	const ready = new Promise(async (resolve, reject) => {
		const failed = setTimeout(
			() => reject(new Error(`Timed out starting the wrangler CLI`)),
			timeout
		);

		(async function () {
			for (const msg of p.stderr) {
				if (!silent) {
					// eslint-disable-next-line
					console.error(msg);
				}
			}
		})();

		for await (const msg of p.stdout) {
			if (!silent) {
				// eslint-disable-next-line
				console.log(msg);
			}
			if (msg.includes(`Listening on`)) {
				break;
			}
		}

		clearTimeout(failed);
		resolve();
	});

	return {
		ready,
		stop() {
			p.kill();
		},
	};
}