qatools-runner 0.0.0-stage → 0.1.1
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 +21 -0
- package/README.md +72 -2
- package/index.mjs +336 -0
- package/package.json +23 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 QATools
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,73 @@
|
|
|
1
|
-
#
|
|
1
|
+
# qatools-runner
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Run the Playwright tests you write in the
|
|
4
|
+
[QATools Playwright Online IDE](https://qatools.dev/playwright-ide)
|
|
5
|
+
in a **real browser on your own computer**. It is free, and there is no sign-up.
|
|
6
|
+
|
|
7
|
+
## Quick start
|
|
8
|
+
|
|
9
|
+
You need [Node.js 18 or newer](https://nodejs.org).
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npx qatools-runner
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
The runner prints a **pairing code**, like `K7Q-4MZ`. Then:
|
|
16
|
+
|
|
17
|
+
1. Open https://qatools.dev/playwright-ide
|
|
18
|
+
2. Click **My computer**, at the top right.
|
|
19
|
+
3. Type the pairing code and click **Connect**.
|
|
20
|
+
4. Press **▶ Run test**.
|
|
21
|
+
|
|
22
|
+
Your tests run in Chromium on your machine. The results come back to the IDE:
|
|
23
|
+
|
|
24
|
+
- pass or fail for each test, with timings
|
|
25
|
+
- the failing line, highlighted in the editor
|
|
26
|
+
- a screenshot of the moment a test failed
|
|
27
|
+
- the full Playwright HTML report
|
|
28
|
+
|
|
29
|
+
Turn on **Headed** to watch the browser click through your test. This works well
|
|
30
|
+
for learning and for live classes.
|
|
31
|
+
|
|
32
|
+
The first run installs Playwright and Chromium. This takes about a minute, and
|
|
33
|
+
only happens once.
|
|
34
|
+
|
|
35
|
+
## Options
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
npx qatools-runner --dir ~/my-tests # project folder (default: ~/qatools-practice)
|
|
39
|
+
npx qatools-runner --port 7358 # port (default: 7357)
|
|
40
|
+
npx qatools-runner --new-code # make a new pairing code
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
The pairing code stays the same when you restart the runner, so you pair only once.
|
|
44
|
+
It is saved in `~/.qatools-runner.json`.
|
|
45
|
+
|
|
46
|
+
## Is it safe?
|
|
47
|
+
|
|
48
|
+
The runner runs test code, so it is locked down:
|
|
49
|
+
|
|
50
|
+
- It listens on **127.0.0.1 only**. Other computers on your network cannot reach it.
|
|
51
|
+
- It answers **only the QATools IDE**. It checks the page's origin and the host name,
|
|
52
|
+
so other websites cannot use it.
|
|
53
|
+
- **Every request needs your pairing code.**
|
|
54
|
+
- It writes files **only inside its project folder**, and it only runs `playwright test`.
|
|
55
|
+
|
|
56
|
+
Your tests run with your own user's permissions, just like running
|
|
57
|
+
`npx playwright test` yourself. Only run test code that you understand.
|
|
58
|
+
|
|
59
|
+
## Browsers
|
|
60
|
+
|
|
61
|
+
Chrome, Edge and Firefox work. When you connect for the first time, Chrome or Edge may
|
|
62
|
+
ask to allow access to apps on your device. Click **Allow**.
|
|
63
|
+
|
|
64
|
+
Safari does not let websites talk to programs on your computer. Please use another
|
|
65
|
+
browser for this.
|
|
66
|
+
|
|
67
|
+
## Stop the runner
|
|
68
|
+
|
|
69
|
+
Press `Ctrl+C` in the terminal.
|
|
70
|
+
|
|
71
|
+
## License
|
|
72
|
+
|
|
73
|
+
MIT
|
package/index.mjs
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/* ─── QATools local runner ────────────────────────────────────────────────────
|
|
3
|
+
Runs the Playwright tests you write in the QATools Playwright Online IDE
|
|
4
|
+
(https://qatools.dev/playwright-ide) in a real browser on YOUR computer.
|
|
5
|
+
|
|
6
|
+
How it stays safe:
|
|
7
|
+
• listens on 127.0.0.1 only — nothing on your network can reach it
|
|
8
|
+
• answers only pages from qatools.dev (and the dev server), checked by Origin + Host
|
|
9
|
+
• every request needs the pairing code printed below
|
|
10
|
+
• it only writes into its own project folder and only runs `playwright test`
|
|
11
|
+
|
|
12
|
+
Usage: node runner/index.mjs [--dir <folder>] [--port 7357] [--new-code]
|
|
13
|
+
Node.js 18+ and npm are needed. No other dependencies. */
|
|
14
|
+
|
|
15
|
+
import http from 'node:http'
|
|
16
|
+
import { spawn } from 'node:child_process'
|
|
17
|
+
import crypto from 'node:crypto'
|
|
18
|
+
import fs from 'node:fs'
|
|
19
|
+
import os from 'node:os'
|
|
20
|
+
import path from 'node:path'
|
|
21
|
+
|
|
22
|
+
const VERSION = '0.1.1'
|
|
23
|
+
|
|
24
|
+
/* ── options ── */
|
|
25
|
+
const argv = process.argv.slice(2)
|
|
26
|
+
const opt = (name, def) => { const i = argv.indexOf(`--${name}`); return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : def }
|
|
27
|
+
const flag = name => argv.includes(`--${name}`)
|
|
28
|
+
if (flag('help') || flag('h')) {
|
|
29
|
+
console.log('QATools local runner\n\n --dir <folder> project folder (default ~/qatools-practice)\n --port <n> port on 127.0.0.1 (default 7357)\n --new-code make a new pairing code\n')
|
|
30
|
+
process.exit(0)
|
|
31
|
+
}
|
|
32
|
+
const PORT = Number(opt('port', process.env.QATOOLS_RUNNER_PORT || 7357))
|
|
33
|
+
const DIR = path.resolve(opt('dir', path.join(os.homedir(), 'qatools-practice')))
|
|
34
|
+
const ORIGINS = new Set([
|
|
35
|
+
'https://qatools.dev', 'https://www.qatools.dev',
|
|
36
|
+
'http://localhost:5173', 'http://127.0.0.1:5173', 'http://localhost:4173',
|
|
37
|
+
...(process.env.QATOOLS_RUNNER_ORIGINS || '').split(',').map(s => s.trim()).filter(Boolean),
|
|
38
|
+
])
|
|
39
|
+
const HOSTS = new Set([`127.0.0.1:${PORT}`, `localhost:${PORT}`])
|
|
40
|
+
const IS_WIN = process.platform === 'win32'
|
|
41
|
+
|
|
42
|
+
/* ── pairing code: kept between restarts so the IDE stays paired ── */
|
|
43
|
+
const STATE_FILE = process.env.QATOOLS_RUNNER_STATE || path.join(os.homedir(), '.qatools-runner.json')
|
|
44
|
+
function loadCode() {
|
|
45
|
+
if (!flag('new-code')) {
|
|
46
|
+
try { const s = JSON.parse(fs.readFileSync(STATE_FILE, 'utf8')); if (/^[A-Z0-9]{6}$/.test(s.code)) return s.code } catch { /* first run */ }
|
|
47
|
+
}
|
|
48
|
+
const abc = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789' // no 0/O, 1/I/L
|
|
49
|
+
const code = Array.from(crypto.randomBytes(6), b => abc[b % abc.length]).join('')
|
|
50
|
+
try { fs.writeFileSync(STATE_FILE, JSON.stringify({ code }), { mode: 0o600 }) } catch { /* fine */ }
|
|
51
|
+
return code
|
|
52
|
+
}
|
|
53
|
+
const CODE = loadCode()
|
|
54
|
+
const codeOk = given => {
|
|
55
|
+
if (typeof given !== 'string') return false
|
|
56
|
+
const a = Buffer.from(given.trim().toUpperCase().replace(/[^A-Z0-9]/g, '')), b = Buffer.from(CODE)
|
|
57
|
+
return a.length === b.length && crypto.timingSafeEqual(a, b)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/* ── helpers ── */
|
|
61
|
+
const stripAnsi = s => String(s ?? '').replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, '')
|
|
62
|
+
const exists = p => { try { fs.accessSync(p); return true } catch { return false } }
|
|
63
|
+
const BLOCKED_TOP = new Set(['node_modules', '.git', '.qatools', 'playwright-report', 'test-results'])
|
|
64
|
+
const ALLOWED_EXT = /\.(ts|js|mjs|cjs|json|md|txt|yml|yaml|csv|env\.example|gitignore)$|^\.gitignore$/i
|
|
65
|
+
|
|
66
|
+
/** Safe relative path inside DIR, or null. */
|
|
67
|
+
function safeRel(p) {
|
|
68
|
+
if (typeof p !== 'string' || !p || p.includes('\0') || p.length > 200) return null
|
|
69
|
+
const rel = path.normalize(p).replace(/\\/g, '/')
|
|
70
|
+
if (path.isAbsolute(rel) || rel.startsWith('../') || rel === '..' || rel.split('/').some(s => s === '..')) return null
|
|
71
|
+
if (BLOCKED_TOP.has(rel.split('/')[0])) return null
|
|
72
|
+
if (!ALLOWED_EXT.test(path.basename(rel))) return null
|
|
73
|
+
const abs = path.resolve(DIR, rel)
|
|
74
|
+
return abs.startsWith(DIR + path.sep) ? rel : null
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function readBody(req, limit = 5 * 1024 * 1024) {
|
|
78
|
+
return new Promise((resolve, reject) => {
|
|
79
|
+
let size = 0; const chunks = []
|
|
80
|
+
req.on('data', c => { size += c.length; if (size > limit) { reject(new Error('Request too large')); req.destroy() } else chunks.push(c) })
|
|
81
|
+
req.on('end', () => { try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')) } catch { reject(new Error('Bad JSON')) } })
|
|
82
|
+
req.on('error', reject)
|
|
83
|
+
})
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/* ── workspace sync ── */
|
|
87
|
+
const MANIFEST = path.join(DIR, '.qatools', 'manifest.json')
|
|
88
|
+
function syncFiles(files) {
|
|
89
|
+
if (!Array.isArray(files) || files.length > 300) throw new Error('Expected up to 300 files')
|
|
90
|
+
fs.mkdirSync(path.join(DIR, '.qatools'), { recursive: true })
|
|
91
|
+
const written = []
|
|
92
|
+
for (const f of files) {
|
|
93
|
+
const rel = safeRel(f?.path)
|
|
94
|
+
if (!rel || typeof f.content !== 'string' || f.content.length > 1_000_000) continue
|
|
95
|
+
const abs = path.join(DIR, rel)
|
|
96
|
+
fs.mkdirSync(path.dirname(abs), { recursive: true })
|
|
97
|
+
let same = false
|
|
98
|
+
try { same = fs.readFileSync(abs, 'utf8') === f.content } catch { /* new */ }
|
|
99
|
+
if (!same) fs.writeFileSync(abs, f.content)
|
|
100
|
+
written.push(rel)
|
|
101
|
+
}
|
|
102
|
+
/* remove files the IDE deleted (only ones this runner wrote before) */
|
|
103
|
+
let old = []
|
|
104
|
+
try { old = JSON.parse(fs.readFileSync(MANIFEST, 'utf8')) } catch { /* first sync */ }
|
|
105
|
+
for (const rel of old) if (!written.includes(rel) && safeRel(rel)) { try { fs.unlinkSync(path.join(DIR, rel)) } catch { /* gone */ } }
|
|
106
|
+
fs.writeFileSync(MANIFEST, JSON.stringify(written, null, 2))
|
|
107
|
+
/* runner config: the learner's config + both test folders + a JSON report for the IDE */
|
|
108
|
+
const hasCfg = written.includes('playwright.config.ts')
|
|
109
|
+
fs.writeFileSync(path.join(DIR, '.qatools', 'runner.config.ts'), `// Written by the QATools runner — do not edit.
|
|
110
|
+
import { defineConfig } from '@playwright/test'
|
|
111
|
+
${hasCfg ? "import base from '../playwright.config'\n" : "const base = { use: { baseURL: 'https://playground.qatools.dev' } }\n"}
|
|
112
|
+
export default defineConfig(base, {
|
|
113
|
+
testDir: '..',
|
|
114
|
+
testMatch: /(^|[\\\\/])(tests|lessons)[\\\\/].*\\.(spec|test)\\.[cm]?[jt]s$/,
|
|
115
|
+
outputDir: '../test-results',
|
|
116
|
+
reporter: [['list'], ['json', { outputFile: 'results.json' }], ['html', { open: 'never', outputFolder: '../playwright-report' }]],
|
|
117
|
+
})
|
|
118
|
+
`)
|
|
119
|
+
return written.length
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/* ── processes ── */
|
|
123
|
+
let current = null // the running child process
|
|
124
|
+
let browsersChecked = false
|
|
125
|
+
|
|
126
|
+
function run(cmd, args, send, extraEnv = {}) {
|
|
127
|
+
return new Promise(resolve => {
|
|
128
|
+
const child = spawn(IS_WIN ? `${cmd}.cmd` : cmd, args, {
|
|
129
|
+
cwd: DIR, shell: IS_WIN, windowsHide: true,
|
|
130
|
+
env: { ...process.env, FORCE_COLOR: '0', CI: '', PLAYWRIGHT_HTML_OPEN: 'never', ...extraEnv },
|
|
131
|
+
})
|
|
132
|
+
current = child
|
|
133
|
+
const pipe = stream => d => stripAnsi(d.toString()).split(/\r?\n/).forEach((line, i, arr) => {
|
|
134
|
+
if (i === arr.length - 1 && line === '') return
|
|
135
|
+
send({ type: 'log', stream, text: line })
|
|
136
|
+
})
|
|
137
|
+
child.stdout.on('data', pipe('out'))
|
|
138
|
+
child.stderr.on('data', pipe('err'))
|
|
139
|
+
child.on('error', e => { send({ type: 'log', stream: 'err', text: `Could not start ${cmd}: ${e.message}` }); current = null; resolve(127) })
|
|
140
|
+
child.on('close', code => { current = null; resolve(code ?? 1) })
|
|
141
|
+
})
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function stopCurrent() {
|
|
145
|
+
if (!current) return false
|
|
146
|
+
if (IS_WIN) spawn('taskkill', ['/pid', String(current.pid), '/T', '/F'], { windowsHide: true })
|
|
147
|
+
else current.kill('SIGTERM')
|
|
148
|
+
return true
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/* ── JSON report → compact results for the IDE ── */
|
|
152
|
+
function readResults() {
|
|
153
|
+
let rep
|
|
154
|
+
try { rep = JSON.parse(fs.readFileSync(path.join(DIR, '.qatools', 'results.json'), 'utf8')) } catch { return null }
|
|
155
|
+
const tests = []
|
|
156
|
+
const rel = p => (p ? path.relative(DIR, path.isAbsolute(p) ? p : path.join(DIR, p)).replace(/\\/g, '/') : null)
|
|
157
|
+
const walk = (suite, parents) => {
|
|
158
|
+
for (const spec of suite.specs ?? []) {
|
|
159
|
+
for (const t of spec.tests ?? []) {
|
|
160
|
+
const last = t.results?.[t.results.length - 1] ?? {}
|
|
161
|
+
const err = last.error ?? last.errors?.[0]
|
|
162
|
+
const shot = (last.attachments ?? []).find(a => a.contentType?.startsWith('image/') && a.path)
|
|
163
|
+
tests.push({
|
|
164
|
+
title: spec.title, describe: parents.filter(Boolean).join(' › ') || null,
|
|
165
|
+
file: (spec.file ?? suite.file ?? '').replace(/\\/g, '/'), line: spec.line,
|
|
166
|
+
project: t.projectName, status: last.status ?? (t.status === 'skipped' ? 'skipped' : 'unknown'),
|
|
167
|
+
outcome: t.status, duration: last.duration ?? 0, retries: Math.max(0, (t.results?.length ?? 1) - 1),
|
|
168
|
+
error: err ? stripAnsi(err.message ?? err.value ?? '').slice(0, 4000) : null,
|
|
169
|
+
errorLine: err?.location?.line ?? null,
|
|
170
|
+
errorFile: err?.location?.file ? rel(err.location.file) : null,
|
|
171
|
+
screenshot: shot ? rel(shot.path) : null,
|
|
172
|
+
})
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
for (const s of suite.suites ?? []) walk(s, [...parents, s.title && !/\.[cm]?[jt]s$/.test(s.title) ? s.title : null])
|
|
176
|
+
}
|
|
177
|
+
for (const s of rep.suites ?? []) walk(s, [])
|
|
178
|
+
return { tests, stats: rep.stats ?? null, errors: (rep.errors ?? []).map(e => stripAnsi(e.message ?? '')).slice(0, 5) }
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/* ── one test run, streamed to the IDE as NDJSON ── */
|
|
182
|
+
async function handleRun(body, res) {
|
|
183
|
+
const send = obj => { try { res.write(JSON.stringify(obj) + '\n') } catch { /* closed */ } }
|
|
184
|
+
const t0 = Date.now()
|
|
185
|
+
try {
|
|
186
|
+
send({ type: 'phase', text: `Writing ${syncFiles(body.files)} files to ${DIR}` })
|
|
187
|
+
if (!exists(path.join(DIR, 'node_modules', '@playwright', 'test'))) {
|
|
188
|
+
send({ type: 'phase', text: 'First run: installing @playwright/test (npm install) — about a minute…' })
|
|
189
|
+
const code = await run('npm', ['install', '--no-audit', '--no-fund'], send)
|
|
190
|
+
if (code !== 0) { send({ type: 'end', code, error: 'npm install failed — see the lines above.' }); return }
|
|
191
|
+
}
|
|
192
|
+
if (!browsersChecked) {
|
|
193
|
+
send({ type: 'phase', text: 'Checking the Chromium browser (downloads once, if needed)…' })
|
|
194
|
+
const code = await run('npx', ['playwright', 'install', 'chromium'], send)
|
|
195
|
+
if (code !== 0) { send({ type: 'end', code, error: 'Could not install Chromium — see the lines above.' }); return }
|
|
196
|
+
browsersChecked = true
|
|
197
|
+
}
|
|
198
|
+
const args = ['playwright', 'test', '--config', '.qatools/runner.config.ts']
|
|
199
|
+
const target = body.file ? safeRel(body.file) : null
|
|
200
|
+
if (body.file && !target) { send({ type: 'end', code: 1, error: `Not a test file: ${body.file}` }); return }
|
|
201
|
+
if (target) args.push(body.line && Number.isInteger(body.line) ? `${target}:${body.line}` : target)
|
|
202
|
+
if (body.headed) args.push('--headed')
|
|
203
|
+
if (body.project && /^[\w .-]{1,40}$/.test(body.project)) args.push('--project', body.project)
|
|
204
|
+
if (body.debugSlow) args.push('--workers', '1')
|
|
205
|
+
try { fs.rmSync(path.join(DIR, '.qatools', 'results.json'), { force: true }) } catch { /* fine */ }
|
|
206
|
+
send({ type: 'phase', text: `npx ${args.join(' ')}` })
|
|
207
|
+
const code = await run('npx', args, send, body.headed ? { PWDEBUG: '' } : {})
|
|
208
|
+
send({ type: 'results', ...(readResults() ?? { tests: [], stats: null, errors: [] }) })
|
|
209
|
+
send({ type: 'end', code, ms: Date.now() - t0, report: exists(path.join(DIR, 'playwright-report', 'index.html')) })
|
|
210
|
+
} catch (e) {
|
|
211
|
+
send({ type: 'end', code: 1, error: e.message })
|
|
212
|
+
} finally {
|
|
213
|
+
res.end()
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/* ── static files: HTML report + screenshots ── */
|
|
218
|
+
const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.svg': 'image/svg+xml', '.zip': 'application/zip', '.webm': 'video/webm', '.txt': 'text/plain; charset=utf-8', '.md': 'text/plain; charset=utf-8' }
|
|
219
|
+
function serveFile(res, root, rel) {
|
|
220
|
+
const abs = path.resolve(root, rel || 'index.html')
|
|
221
|
+
if (!abs.startsWith(root + path.sep) && abs !== root) { res.writeHead(403).end(); return }
|
|
222
|
+
fs.readFile(abs, (err, data) => {
|
|
223
|
+
if (err) { res.writeHead(404, { 'content-type': 'text/plain' }).end('Not found'); return }
|
|
224
|
+
res.writeHead(200, { 'content-type': MIME[path.extname(abs).toLowerCase()] ?? 'application/octet-stream', 'cache-control': 'no-store' }).end(data)
|
|
225
|
+
})
|
|
226
|
+
}
|
|
227
|
+
const cookieCode = req => (req.headers.cookie ?? '').split(';').map(s => s.trim()).find(s => s.startsWith('qatools_runner='))?.slice(15)
|
|
228
|
+
|
|
229
|
+
/* ── server ── */
|
|
230
|
+
const server = http.createServer(async (req, res) => {
|
|
231
|
+
/* DNS-rebinding guard: only answer to our own host names */
|
|
232
|
+
if (!HOSTS.has(req.headers.host ?? '')) { res.writeHead(421).end(); return }
|
|
233
|
+
const url = new URL(req.url, `http://${req.headers.host}`)
|
|
234
|
+
|
|
235
|
+
/* Report + screenshots open in a new tab (top-level navigation, no Origin):
|
|
236
|
+
/open?code=… sets a same-site cookie, then the files load normally. */
|
|
237
|
+
if (req.method === 'GET' && url.pathname === '/open') {
|
|
238
|
+
if (!codeOk(url.searchParams.get('code'))) { res.writeHead(401, { 'content-type': 'text/plain' }).end('Wrong pairing code'); return }
|
|
239
|
+
const p = url.searchParams.get('p') ?? ''
|
|
240
|
+
const to = url.searchParams.get('to') === 'shot' && /^(test-results|playwright-report)\/[\w./ -]+$/.test(p) && !p.includes('..')
|
|
241
|
+
? `/files/${p.split('/').map(encodeURIComponent).join('/')}` : '/report/index.html'
|
|
242
|
+
/* Not a 302: the click started on qatools.dev, and browsers do not send a
|
|
243
|
+
SameSite=Strict cookie on a redirect that another site started. This page
|
|
244
|
+
sets the cookie, then moves on from OUR origin, so the cookie is sent. */
|
|
245
|
+
res.writeHead(200, {
|
|
246
|
+
'set-cookie': `qatools_runner=${CODE}; Path=/; HttpOnly; SameSite=Strict`,
|
|
247
|
+
'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'referrer-policy': 'no-referrer',
|
|
248
|
+
}).end(`<!doctype html><meta charset="utf-8"><meta http-equiv="refresh" content="0;url=${to}"><title>Opening…</title>` +
|
|
249
|
+
`<p style="font:14px system-ui;padding:24px">Opening… <a href="${to}">continue</a></p><script>location.replace(${JSON.stringify(to)})</script>`)
|
|
250
|
+
return
|
|
251
|
+
}
|
|
252
|
+
if (req.method === 'GET' && (url.pathname.startsWith('/report/') || url.pathname.startsWith('/files/'))) {
|
|
253
|
+
if (!codeOk(cookieCode(req))) { res.writeHead(401, { 'content-type': 'text/plain' }).end('Open this from the IDE'); return }
|
|
254
|
+
if (url.pathname.startsWith('/report/')) serveFile(res, path.join(DIR, 'playwright-report'), decodeURIComponent(url.pathname.slice(8)))
|
|
255
|
+
else {
|
|
256
|
+
const rel = decodeURIComponent(url.pathname.slice(7))
|
|
257
|
+
if (!/^(test-results|playwright-report)\//.test(rel)) { res.writeHead(403).end(); return }
|
|
258
|
+
serveFile(res, DIR, rel)
|
|
259
|
+
}
|
|
260
|
+
return
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/* API: browser pages from allowed origins only */
|
|
264
|
+
const origin = req.headers.origin
|
|
265
|
+
if (!origin || !ORIGINS.has(origin)) { res.writeHead(403, { 'content-type': 'text/plain' }).end('This runner only talks to the QATools IDE.'); return }
|
|
266
|
+
const cors = {
|
|
267
|
+
'access-control-allow-origin': origin,
|
|
268
|
+
'access-control-allow-headers': 'content-type, x-qatools-code',
|
|
269
|
+
'access-control-allow-methods': 'GET, POST, OPTIONS',
|
|
270
|
+
'access-control-allow-private-network': 'true', // Chrome Private/Local Network Access
|
|
271
|
+
'access-control-max-age': '600',
|
|
272
|
+
vary: 'Origin',
|
|
273
|
+
}
|
|
274
|
+
if (req.method === 'OPTIONS') { res.writeHead(204, cors).end(); return }
|
|
275
|
+
const json = (status, obj) => res.writeHead(status, { ...cors, 'content-type': 'application/json' }).end(JSON.stringify(obj))
|
|
276
|
+
|
|
277
|
+
/* ping needs no code: lets the IDE say "runner found — enter the code" */
|
|
278
|
+
if (req.method === 'GET' && url.pathname === '/api/ping') { json(200, { app: 'qatools-runner', version: VERSION }); return }
|
|
279
|
+
if (!codeOk(req.headers['x-qatools-code'])) { json(401, { error: 'Wrong pairing code' }); return }
|
|
280
|
+
|
|
281
|
+
if (req.method === 'GET' && url.pathname === '/api/hello') {
|
|
282
|
+
json(200, {
|
|
283
|
+
app: 'qatools-runner', version: VERSION, node: process.version, os: `${os.type()} ${os.release()}`, dir: DIR,
|
|
284
|
+
installed: exists(path.join(DIR, 'node_modules', '@playwright', 'test')), busy: !!current,
|
|
285
|
+
})
|
|
286
|
+
return
|
|
287
|
+
}
|
|
288
|
+
if (req.method === 'GET' && url.pathname === '/api/file') {
|
|
289
|
+
const rel = url.searchParams.get('p') ?? ''
|
|
290
|
+
if (!/^(test-results|playwright-report)\//.test(rel)) { json(403, { error: 'Not allowed' }); return }
|
|
291
|
+
const abs = path.resolve(DIR, rel)
|
|
292
|
+
if (!abs.startsWith(DIR + path.sep)) { json(403, { error: 'Not allowed' }); return }
|
|
293
|
+
fs.readFile(abs, (err, data) => {
|
|
294
|
+
if (err) { json(404, { error: 'Not found' }); return }
|
|
295
|
+
res.writeHead(200, { ...cors, 'content-type': MIME[path.extname(abs).toLowerCase()] ?? 'application/octet-stream', 'cache-control': 'no-store' }).end(data)
|
|
296
|
+
})
|
|
297
|
+
return
|
|
298
|
+
}
|
|
299
|
+
if (req.method === 'POST' && url.pathname === '/api/stop') { json(200, { stopped: stopCurrent() }); return }
|
|
300
|
+
if (req.method === 'POST' && url.pathname === '/api/run') {
|
|
301
|
+
if (current) { json(409, { error: 'A run is already going. Stop it first.' }); return }
|
|
302
|
+
let body
|
|
303
|
+
try { body = await readBody(req) } catch (e) { json(400, { error: e.message }); return }
|
|
304
|
+
res.writeHead(200, { ...cors, 'content-type': 'application/x-ndjson; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' })
|
|
305
|
+
console.log(`▶ run ${body.file ?? 'all tests'}${body.line ? `:${body.line}` : ''}${body.headed ? ' (headed)' : ''}`)
|
|
306
|
+
req.on('close', () => { if (!res.writableEnded) stopCurrent() }) // IDE tab closed → stop
|
|
307
|
+
await handleRun(body, res)
|
|
308
|
+
return
|
|
309
|
+
}
|
|
310
|
+
json(404, { error: 'Not found' })
|
|
311
|
+
})
|
|
312
|
+
|
|
313
|
+
server.on('error', e => {
|
|
314
|
+
if (e.code === 'EADDRINUSE') console.error(`\n Port ${PORT} is busy — is the runner already running? Or start with --port 7358\n`)
|
|
315
|
+
else console.error(e)
|
|
316
|
+
process.exit(1)
|
|
317
|
+
})
|
|
318
|
+
|
|
319
|
+
server.listen(PORT, '127.0.0.1', () => {
|
|
320
|
+
fs.mkdirSync(DIR, { recursive: true })
|
|
321
|
+
const pretty = `${CODE.slice(0, 3)}-${CODE.slice(3)}`
|
|
322
|
+
console.log(`
|
|
323
|
+
┌──────────────────────────────────────────────────────┐
|
|
324
|
+
│ QATools local runner ${VERSION.padEnd(31)}│
|
|
325
|
+
│ │
|
|
326
|
+
│ Pairing code: ${pretty.padEnd(37)}│
|
|
327
|
+
│ │
|
|
328
|
+
│ In the IDE: Run on → My computer → enter the code. │
|
|
329
|
+
└──────────────────────────────────────────────────────┘
|
|
330
|
+
Listening on http://127.0.0.1:${PORT} (this computer only)
|
|
331
|
+
Project folder: ${DIR}
|
|
332
|
+
Press Ctrl+C to stop.
|
|
333
|
+
`)
|
|
334
|
+
})
|
|
335
|
+
|
|
336
|
+
for (const sig of ['SIGINT', 'SIGTERM']) process.on(sig, () => { stopCurrent(); console.log('\n Runner stopped.'); process.exit(0) })
|
package/package.json
CHANGED
|
@@ -1,6 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "qatools-runner",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Run the Playwright tests you write in the QATools Playwright Online IDE in a real browser on your own computer.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": {
|
|
8
|
+
"qatools-runner": "index.mjs"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"index.mjs",
|
|
12
|
+
"README.md",
|
|
13
|
+
"LICENSE"
|
|
14
|
+
],
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=18"
|
|
17
|
+
},
|
|
18
|
+
"homepage": "https://qatools.dev/playwright-ide",
|
|
19
|
+
"keywords": [
|
|
20
|
+
"playwright",
|
|
21
|
+
"testing",
|
|
22
|
+
"qatools",
|
|
23
|
+
"runner"
|
|
24
|
+
]
|
|
25
|
+
}
|