-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathrun-e2e-local.mjs
More file actions
170 lines (155 loc) · 4.99 KB
/
run-e2e-local.mjs
File metadata and controls
170 lines (155 loc) · 4.99 KB
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
#!/usr/bin/env node
/**
* E2E local: build, spawn Fastify + Next, poll until healthy, run Playwright, cleanup on exit.
* No wait-on. Uses ALLOW_TEST, PGLITE, DB-backed token for @test.ai.
* When SKIP_BUILD=1, skip build step (assumes .next exists with NEXT_PUBLIC_API_URL=http://localhost:3001).
*/
import { spawn, spawnSync } from 'node:child_process'
import { existsSync, readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
const scriptDir = dirname(fileURLToPath(import.meta.url))
const nextDir = dirname(scriptDir)
const repoRoot = dirname(dirname(nextDir))
function loadEnvTest() {
const path = join(repoRoot, 'apps/fastify/.env.test')
if (!existsSync(path)) return {}
const lines = readFileSync(path, 'utf8').split('\n')
const out = {}
for (const line of lines) {
const idx = line.indexOf('=')
if (idx < 0 || line.startsWith('#')) continue
const key = line.slice(0, idx).trim()
let val = line.slice(idx + 1).trim()
if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'")))
val = val.slice(1, -1)
out[key] = val
}
return out
}
function waitForUrl(url, timeoutMs = 60_000) {
const start = Date.now()
return new Promise(resolve => {
const check = async () => {
try {
const res = await fetch(url, { signal: AbortSignal.timeout(2000) })
if (res.ok || res.status === 307) return resolve(true)
} catch {
// continue
}
if (Date.now() - start > timeoutMs) return resolve(false)
setTimeout(check, 500)
}
check()
})
}
async function main() {
// eslint-disable-next-line turbo/no-undeclared-env-vars -- set by root test:e2e script
if (!process.env.SKIP_KILL_PORTS)
try {
spawnSync('bash', [join(repoRoot, 'scripts/kill-test-servers.sh')], {
cwd: repoRoot,
stdio: 'pipe',
})
} catch {
/* ignore - ports may not be in use or bash unavailable */
}
// eslint-disable-next-line turbo/no-undeclared-env-vars -- set by root test:e2e or user
if (!process.env.SKIP_BUILD) {
const loadedForBuild = loadEnvTest()
const buildEnv = {
...process.env,
...loadedForBuild,
JWT_SECRET:
loadedForBuild.JWT_SECRET ??
process.env.JWT_SECRET ??
'e2e-jwt-secret-min-32-chars-for-tests',
}
const build = spawn('pnpm', ['-F', '@repo/next', 'run', 'build:e2e'], {
cwd: repoRoot,
stdio: 'inherit',
env: buildEnv,
})
const buildCode = await new Promise(r => build.on('exit', c => r(c ?? 1)))
if (buildCode !== 0) process.exit(buildCode)
}
const loaded = loadEnvTest()
const env = {
...process.env,
...loaded,
ALLOW_TEST: 'true',
PGLITE: 'true',
NODE_ENV: 'test',
NEXT_PUBLIC_API_URL: 'http://localhost:3001',
JWT_SECRET:
loaded.JWT_SECRET ?? process.env.JWT_SECRET ?? 'e2e-jwt-secret-min-32-chars-for-tests',
}
const fastify = spawn('node', ['--import', 'tsx', 'server.ts'], {
cwd: join(repoRoot, 'apps/fastify'),
env,
stdio: 'ignore',
})
const next = spawn('pnpm', ['exec', 'next', 'start'], {
cwd: nextDir,
env: { ...env, PORT: '3000' },
stdio: 'ignore',
})
const killAll = (signal = 'SIGTERM') => {
fastify.kill(signal)
next.kill(signal)
}
const waitForExits = (timeoutMs = 2000) =>
Promise.race([
Promise.all([
new Promise(r => fastify.once('exit', r)),
new Promise(r => next.once('exit', r)),
]),
new Promise(r => setTimeout(r, timeoutMs)),
])
const cleanup = () => {
killAll('SIGTERM')
}
process.on('SIGINT', () => {
cleanup()
process.exit(130)
})
process.on('SIGTERM', () => {
cleanup()
process.exit(143)
})
if (!(await waitForUrl('http://localhost:3001/health'))) {
killAll('SIGKILL')
process.stderr.write('E2E local: API unreachable at http://localhost:3001/health\n')
process.exit(1)
}
if (!(await waitForUrl('http://localhost:3000'))) {
killAll('SIGKILL')
process.stderr.write('E2E local: App unreachable at http://localhost:3000\n')
process.exit(1)
}
await new Promise(r => setTimeout(r, 2000))
const userArgs = process.argv.slice(2).filter(a => a !== '--')
const hasWorkers = userArgs.some(a => a.startsWith('--workers='))
const pwArgs = ['exec', 'playwright', 'test', ...(hasWorkers ? [] : ['--workers=1']), ...userArgs]
const hasProjectArg = pwArgs.some(a => a.startsWith('--project='))
const finalPwArgs = !hasProjectArg ? [...pwArgs, '--project=auth', '--project=chromium'] : pwArgs
const pw = spawn('pnpm', finalPwArgs, {
cwd: nextDir,
env,
stdio: 'inherit',
})
let exitCode = 0
pw.on('exit', c => {
exitCode = c ?? 1
})
await new Promise(r => pw.on('exit', r))
cleanup()
await waitForExits(5000)
if (fastify.exitCode == null) fastify.kill('SIGKILL')
if (next.exitCode == null) next.kill('SIGKILL')
process.exit(exitCode)
}
main().catch(err => {
process.stderr.write(`${String(err)}\n`)
process.exit(1)
})