@plune-ai/playwright 0.1.0

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Plune Contributors
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 ADDED
@@ -0,0 +1,112 @@
1
+ # @plune-ai/playwright
2
+
3
+ Report Playwright results to [Plune](https://plune.ai).
4
+
5
+ Add one line to your Playwright config and your runs, results and failures show up in Plune —
6
+ without touching a single test.
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ npm install --save-dev @plune-ai/playwright
12
+ npx plune login # from @plune-ai/cli — saves your API token
13
+ ```
14
+
15
+ The package has **no runtime dependencies**. It asks only for the `@playwright/test` you already
16
+ have.
17
+
18
+ ## Use
19
+
20
+ ```ts
21
+ // playwright.config.ts
22
+ import { defineConfig } from '@playwright/test';
23
+
24
+ export default defineConfig({
25
+ reporter: [['list'], ['@plune-ai/playwright']],
26
+ });
27
+ ```
28
+
29
+ That is the whole setup. Options, if you want them:
30
+
31
+ ```ts
32
+ ['@plune-ai/playwright', {
33
+ externalKey: process.env.GITHUB_RUN_ID, // several processes → one run
34
+ batchSize: 100, // results per request (max 500)
35
+ fallbackPath: '.plune/pending-results.jsonl',
36
+ apiUrl: 'https://beta-api.plune.ai', // or PLUNE_API_URL
37
+ token: process.env.PLUNE_TOKEN, // or whatever `plune login` saved
38
+ }]
39
+ ```
40
+
41
+ ## From CI, without editing the config
42
+
43
+ A committed config cannot know the run key of a job that does not exist yet, so the environment
44
+ fills in what you left out. Anything set in the config file wins.
45
+
46
+ | Variable | What it does |
47
+ |---|---|
48
+ | `PLUNE_TOKEN` | the API token — so a CI job need not run `plune login` |
49
+ | `PLUNE_RUN` | the shared run key: every process with the same value lands in one run |
50
+ | `PLUNE_API_URL` | the deployment to report to |
51
+ | `PLUNE_SHARED_RUN` | this process is one of several — do not close the run |
52
+ | `PLUNE_PROCEED` | the job closes the run itself, later |
53
+ | `PLUNE_BATCH_SIZE` | results per request (default 100, max 500) |
54
+ | `PLUNE_FALLBACK` | where unsent batches are written |
55
+
56
+ Flags are read by value, not by presence: `PLUNE_PROCEED=0` in a matrix cell means off.
57
+
58
+ `PLUNE_RUN_TITLE`, `PLUNE_ENV`, `PLUNE_LABELS` and `PLUNE_GROUP` are **not supported yet** — a Plune
59
+ run has nowhere to store them. Setting one prints a line saying it was ignored, rather than
60
+ accepting it and quietly dropping it.
61
+
62
+ ## Sharding
63
+
64
+ Give every shard the same `externalKey` (or set `PLUNE_RUN`) and they land in one Plune run
65
+ instead of four:
66
+
67
+ ```yaml
68
+ env:
69
+ PLUNE_RUN: ${{ github.run_id }}-${{ github.run_attempt }}
70
+ ```
71
+
72
+ A shard **never closes the run** — it cannot know the others have finished. Whoever does know
73
+ closes it: your `merge-reports` step, or `plune run finish <id>`. Until then the run reads as
74
+ still running, which is the truth.
75
+
76
+ ## How a result finds its test case
77
+
78
+ In order, first match wins:
79
+
80
+ 1. a `PluneId` annotation on the test — names the case outright;
81
+ 2. a `@P<id>` token in the title — the same statement, where you can see it in the report. The id
82
+ follows `@P` with **no space**: `@Ptc-1a2b`;
83
+ 3. an `application/plune.metadata+json` attachment — for a fixture or helper that knows the id, or
84
+ a key from another tool: `{"id": "tc-1a2b"}` or `{"keys": [{"kind": "qase", "value": "Q-9"}]}`;
85
+ 4. the Playwright test id (`playwright-id`), stable across shards and merges;
86
+ 5. the file and title path (`path-title`) — the spec file relative to your `testDir`, then each
87
+ `describe` and the test title, e.g. `cart.spec.ts#cart#rejects a negative quantity`.
88
+
89
+ ```ts
90
+ test('rejects a negative quantity', { annotation: { type: 'PluneId', description: 'tc-1a2b' } },
91
+ async ({ page }) => { /* … */ });
92
+ ```
93
+
94
+ A result whose test matches no case is **not** sent and **not** invented — a made-up id would
95
+ write into somebody else's history. The run summary says how many there were.
96
+
97
+ ## When Plune is unreachable
98
+
99
+ Nothing is lost and nothing fails. An unreachable platform, a refused token or an already-closed
100
+ run all append the batch to `.plune/pending-results.jsonl` and let your test run finish with its
101
+ own exit code. The reporter prints one line saying what happened.
102
+
103
+ ## What it does not decide
104
+
105
+ The status. Playwright's own word — `passed`, `failed`, `timedOut`, `interrupted`, `skipped` —
106
+ goes to Plune as-is, and Plune maps it per project. So your team can decide that a timeout counts
107
+ as `broken` (the default) or as something else, and change its mind, without waiting for a release
108
+ of this package.
109
+
110
+ ## Licence
111
+
112
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,511 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ default: () => PluneReporter
34
+ });
35
+ module.exports = __toCommonJS(src_exports);
36
+ var import_node_fs = require("fs");
37
+
38
+ // ../../dist/reporter-core.js
39
+ var import_fs = require("fs");
40
+ var import_os = require("os");
41
+ var import_path = require("path");
42
+ var fs = __toESM(require("fs"), 1);
43
+ var path = __toESM(require("path"), 1);
44
+ var import_crypto = require("crypto");
45
+ var DEFAULT_API_URL = "https://beta-api.plune.ai";
46
+ function resolveApiUrl(explicit) {
47
+ const raw = explicit ?? process.env["PLUNE_API_URL"] ?? DEFAULT_API_URL;
48
+ return raw.replace(/\/+$/, "");
49
+ }
50
+ function credentialsFile() {
51
+ const base = process.env["XDG_CONFIG_HOME"]?.trim() || (0, import_path.join)((0, import_os.homedir)(), ".config");
52
+ return (0, import_path.join)(base, "plune", "credentials.json");
53
+ }
54
+ function loadToken() {
55
+ try {
56
+ const parsed = JSON.parse((0, import_fs.readFileSync)(credentialsFile(), "utf-8"));
57
+ return typeof parsed.token === "string" && parsed.token.length > 0 ? parsed.token : null;
58
+ } catch {
59
+ return null;
60
+ }
61
+ }
62
+ var RETRY_DELAYS_MS = [300, 900];
63
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
64
+ async function detailOf(res) {
65
+ try {
66
+ const body = await res.json();
67
+ return typeof body.error === "string" ? body.error : "";
68
+ } catch {
69
+ return "";
70
+ }
71
+ }
72
+ function retryAfterMs(res) {
73
+ const raw = res.headers.get("retry-after");
74
+ if (raw === null) return null;
75
+ const seconds = Number(raw.trim());
76
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1e3 : null;
77
+ }
78
+ function classify(status) {
79
+ if (status === 401 || status === 403) return "auth";
80
+ if (status === 409) return "conflict";
81
+ if (status === 400) return "invalid";
82
+ if (status === 429 || status >= 500) return "unavailable";
83
+ return "other";
84
+ }
85
+ function createClient(opts) {
86
+ const doFetch = opts.fetchImpl ?? fetch;
87
+ const wait = opts.wait ?? sleep;
88
+ const base = opts.apiUrl.replace(/\/+$/, "");
89
+ const scrub = (text) => opts.token === "" ? text : text.split(opts.token).join("***");
90
+ async function post(path2, body) {
91
+ let last = {
92
+ kind: "unavailable",
93
+ status: null,
94
+ detail: "no attempt was made"
95
+ };
96
+ for (let attempt = 0; attempt <= RETRY_DELAYS_MS.length; attempt += 1) {
97
+ let res;
98
+ try {
99
+ res = await doFetch(`${base}${path2}`, {
100
+ method: "POST",
101
+ headers: { "content-type": "application/json", authorization: `Bearer ${opts.token}` },
102
+ body: JSON.stringify(body)
103
+ });
104
+ } catch (err) {
105
+ last = { kind: "unavailable", status: null, detail: scrub(String(err)) };
106
+ if (attempt < RETRY_DELAYS_MS.length) await wait(RETRY_DELAYS_MS[attempt]);
107
+ continue;
108
+ }
109
+ if (res.ok) return { ok: true, status: res.status, body: await res.json() };
110
+ const detail = scrub(await detailOf(res));
111
+ const kind = classify(res.status);
112
+ last = { kind, status: res.status, detail };
113
+ if (kind !== "unavailable") break;
114
+ if (attempt < RETRY_DELAYS_MS.length) {
115
+ await wait(retryAfterMs(res) ?? RETRY_DELAYS_MS[attempt]);
116
+ }
117
+ }
118
+ return { ok: false, ...last };
119
+ }
120
+ return { post };
121
+ }
122
+ var UNSUPPORTED_VARS = [
123
+ "PLUNE_RUN_TITLE",
124
+ "PLUNE_ENV",
125
+ "PLUNE_LABELS",
126
+ "PLUNE_GROUP"
127
+ ];
128
+ function value(env, name) {
129
+ const raw = env[name]?.trim();
130
+ return raw === void 0 || raw === "" ? void 0 : raw;
131
+ }
132
+ function flag(env, name) {
133
+ const raw = value(env, name)?.toLowerCase();
134
+ return raw === "1" || raw === "true" || raw === "yes" || raw === "on";
135
+ }
136
+ function count(env, name) {
137
+ const raw = value(env, name);
138
+ if (raw === void 0) return void 0;
139
+ const n = Number(raw);
140
+ return Number.isInteger(n) && n > 0 ? n : void 0;
141
+ }
142
+ function readEnv(env = process.env) {
143
+ const externalKey = value(env, "PLUNE_RUN");
144
+ const token = value(env, "PLUNE_TOKEN");
145
+ const apiUrl = value(env, "PLUNE_API_URL");
146
+ const fallbackPath = value(env, "PLUNE_FALLBACK");
147
+ const batchSize = count(env, "PLUNE_BATCH_SIZE");
148
+ return {
149
+ config: {
150
+ ...externalKey !== void 0 ? { externalKey } : {},
151
+ ...token !== void 0 ? { token } : {},
152
+ ...apiUrl !== void 0 ? { apiUrl } : {},
153
+ ...fallbackPath !== void 0 ? { fallbackPath } : {},
154
+ ...batchSize !== void 0 ? { batchSize } : {}
155
+ },
156
+ // Two names for two situations that end the same way. `SHARED_RUN` says other processes are
157
+ // reporting into this run; `PROCEED` says the job will close it on its own schedule. Either
158
+ // way this process must not be the one to call it finished.
159
+ keepOpen: flag(env, "PLUNE_SHARED_RUN") || flag(env, "PLUNE_PROCEED"),
160
+ ignored: UNSUPPORTED_VARS.filter((name) => value(env, name) !== void 0)
161
+ };
162
+ }
163
+ var DEFAULT_FALLBACK_PATH = path.join(".plune", "pending-results.jsonl");
164
+ function appendBatch(file, batch) {
165
+ fs.mkdirSync(path.dirname(file), { recursive: true });
166
+ const line = {
167
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
168
+ runId: batch.runId,
169
+ externalKey: batch.externalKey,
170
+ results: batch.results
171
+ };
172
+ fs.appendFileSync(file, `${JSON.stringify(line)}
173
+ `, "utf8");
174
+ }
175
+ var RESOLVE_CHUNK = 500;
176
+ var BATCH_MAX = 500;
177
+ var BATCH_DEFAULT = 100;
178
+ var EXPECTED_MAX = 1e4;
179
+ function chunk(items, size) {
180
+ const out = [];
181
+ for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
182
+ return out;
183
+ }
184
+ async function startRun(passed, expected) {
185
+ const env = readEnv();
186
+ const stated = Object.fromEntries(Object.entries(passed).filter(([, v]) => v !== void 0));
187
+ const cfg = { ...env.config, ...stated };
188
+ const log = cfg.log ?? ((line) => void process.stderr.write(`${line}
189
+ `));
190
+ const fallbackPath = cfg.fallbackPath ?? DEFAULT_FALLBACK_PATH;
191
+ const externalKey = cfg.externalKey ?? null;
192
+ const batchSize = Math.min(cfg.batchSize ?? BATCH_DEFAULT, BATCH_MAX);
193
+ const token = cfg.token ?? loadToken() ?? "";
194
+ const client = createClient({
195
+ apiUrl: resolveApiUrl(cfg.apiUrl),
196
+ token,
197
+ ...cfg.fetchImpl !== void 0 ? { fetchImpl: cfg.fetchImpl } : {}
198
+ });
199
+ const stats = {
200
+ accepted: 0,
201
+ duplicate: 0,
202
+ conflict: 0,
203
+ rejected: 0,
204
+ unresolved: 0,
205
+ deferred: 0
206
+ };
207
+ const resolved = /* @__PURE__ */ new Map();
208
+ let buffer = [];
209
+ let runId = null;
210
+ let joined = false;
211
+ let offline = token === "";
212
+ let done = false;
213
+ if (offline) {
214
+ log('plune: no API token \u2014 run "plune login" first. Results will be written to the fallback file.');
215
+ }
216
+ if (env.ignored.length > 0) {
217
+ log(`plune: ignoring ${env.ignored.join(", ")} \u2014 a run has nowhere to store them yet.`);
218
+ }
219
+ function defer(results) {
220
+ appendBatch(fallbackPath, { runId, externalKey, results });
221
+ stats.deferred += results.length;
222
+ }
223
+ async function resolveKeys(values) {
224
+ const unknown = values.filter((k) => !resolved.has(k.value));
225
+ if (unknown.length === 0 || offline) return;
226
+ for (const part of chunk(unknown, RESOLVE_CHUNK)) {
227
+ const out = await client.post(
228
+ "/v1/test-cases/resolve",
229
+ { keys: part }
230
+ );
231
+ if (!out.ok) {
232
+ log(`plune: could not look up test cases (${out.detail || out.kind}).`);
233
+ return;
234
+ }
235
+ for (const row of out.body.results) resolved.set(row.key.value, row.testCaseId);
236
+ }
237
+ }
238
+ if (!offline) {
239
+ if (expected !== void 0) await resolveKeys(expected.flat());
240
+ const declared = expected?.slice(0, EXPECTED_MAX) ?? [];
241
+ const configuration = declared.length === 0 ? void 0 : {
242
+ expected: declared.flatMap((keys) => {
243
+ const hit = keys.map((k) => resolved.get(k.value)).find((v) => typeof v === "string");
244
+ if (typeof hit === "string") return [{ testCaseId: hit }];
245
+ return keys[0] === void 0 ? [] : [{ externalKey: keys[0] }];
246
+ })
247
+ };
248
+ if (expected !== void 0 && expected.length > EXPECTED_MAX) {
249
+ log(`plune: ${expected.length} tests is more than the run configuration holds \u2014 reporting the first ${EXPECTED_MAX}.`);
250
+ }
251
+ const start = await client.post("/v1/runs", {
252
+ schemaVersion: 2,
253
+ kind: cfg.kind ?? "automated",
254
+ ...externalKey !== null ? { externalKey } : {},
255
+ ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
256
+ ...configuration !== void 0 ? { configuration } : {}
257
+ });
258
+ if (start.ok) {
259
+ runId = start.body.run.id;
260
+ joined = start.status === 200;
261
+ } else {
262
+ log(`plune: could not start the run (${start.detail || start.kind}). Results will be written to ${fallbackPath}.`);
263
+ }
264
+ }
265
+ function matchFor(result) {
266
+ if (result.testCaseId !== void 0) return { kind: "found", testCaseId: result.testCaseId };
267
+ let unanswered = false;
268
+ for (const key of result.keys) {
269
+ const hit = resolved.get(key.value);
270
+ if (typeof hit === "string") return { kind: "found", testCaseId: hit };
271
+ if (hit === void 0) unanswered = true;
272
+ }
273
+ return unanswered ? { kind: "unanswered" } : { kind: "unmatched" };
274
+ }
275
+ async function flush() {
276
+ if (buffer.length === 0) return;
277
+ const pending = buffer;
278
+ buffer = [];
279
+ if (offline || runId === null) {
280
+ defer(pending);
281
+ return;
282
+ }
283
+ await resolveKeys(pending.flatMap((p) => p.keys));
284
+ const submissions = [];
285
+ const unanswered = [];
286
+ for (const result of pending) {
287
+ const match = matchFor(result);
288
+ if (match.kind === "found") {
289
+ const { keys: _keys, ...rest } = result;
290
+ submissions.push({ ...rest, testCaseId: match.testCaseId });
291
+ } else if (match.kind === "unmatched") {
292
+ stats.unresolved += 1;
293
+ } else {
294
+ unanswered.push(result);
295
+ }
296
+ }
297
+ if (unanswered.length > 0) defer(unanswered);
298
+ if (submissions.length === 0) return;
299
+ const out = await client.post(
300
+ `/v1/runs/${runId}/results`,
301
+ { results: submissions }
302
+ );
303
+ if (out.ok) {
304
+ stats.accepted += out.body.counts.accepted ?? 0;
305
+ stats.duplicate += out.body.counts.duplicate ?? 0;
306
+ stats.conflict += out.body.counts.conflict ?? 0;
307
+ stats.rejected += out.body.counts.rejected ?? 0;
308
+ return;
309
+ }
310
+ if (out.kind === "auth") {
311
+ log('plune: the API token was refused \u2014 run "plune login" with a fresh one.');
312
+ offline = true;
313
+ } else if (out.kind === "conflict") {
314
+ log(`plune: this run is closed \u2014 ${out.detail}`);
315
+ } else {
316
+ log(`plune: could not send results (${out.detail || out.kind}).`);
317
+ }
318
+ defer(submissions);
319
+ }
320
+ function summarise() {
321
+ const parts = [`${stats.accepted} accepted`];
322
+ if (stats.duplicate > 0) parts.push(`${stats.duplicate} already reported`);
323
+ if (stats.conflict > 0) parts.push(`${stats.conflict} conflicting`);
324
+ if (stats.rejected > 0) parts.push(`${stats.rejected} rejected`);
325
+ if (stats.unresolved > 0) parts.push(`${stats.unresolved} with no matching test case`);
326
+ if (stats.deferred > 0) parts.push(`${stats.deferred} written to ${fallbackPath}`);
327
+ log(`plune: ${parts.join(" \xB7 ")}`);
328
+ }
329
+ return {
330
+ get runId() {
331
+ return runId;
332
+ },
333
+ get joined() {
334
+ return joined;
335
+ },
336
+ get stats() {
337
+ return stats;
338
+ },
339
+ async add(result) {
340
+ buffer.push(result);
341
+ if (buffer.length >= batchSize) await flush();
342
+ },
343
+ flush,
344
+ async finish(reason) {
345
+ if (done) return;
346
+ done = true;
347
+ await flush();
348
+ if (runId !== null && !offline) {
349
+ const out = await client.post(`/v1/runs/${runId}/events`, {
350
+ event: "finish",
351
+ ...reason !== void 0 ? { reason } : {}
352
+ });
353
+ if (!out.ok) log(`plune: could not close run ${runId} (${out.detail || out.kind}).`);
354
+ }
355
+ summarise();
356
+ },
357
+ async leaveOpen() {
358
+ if (done) return;
359
+ done = true;
360
+ await flush();
361
+ if (runId !== null) {
362
+ log(`plune: run ${runId} is still open \u2014 close it with "plune run finish ${runId}".`);
363
+ }
364
+ summarise();
365
+ }
366
+ };
367
+ }
368
+ function sha256(input) {
369
+ return (0, import_crypto.createHash)("sha256").update(input, "utf8").digest("hex");
370
+ }
371
+ var RESULT_KEY_MAX = 200;
372
+ var HASH_CHARS = 32;
373
+ function resultKey(testId, retry) {
374
+ const plain = `${testId}#${retry}`;
375
+ return plain.length <= RESULT_KEY_MAX ? plain : `${sha256(testId).slice(0, HASH_CHARS)}#${retry}`;
376
+ }
377
+
378
+ // src/index.ts
379
+ var SOURCE = "playwright";
380
+ function fileOf(test) {
381
+ for (let suite = test.parent; suite !== void 0; suite = suite.parent) {
382
+ if (suite.type === "file") return suite.title;
383
+ }
384
+ return "";
385
+ }
386
+ function titlesOf(test) {
387
+ const titles = [test.title];
388
+ for (let suite = test.parent; suite !== void 0 && suite.type === "describe"; suite = suite.parent) {
389
+ if (suite.title !== "") titles.unshift(suite.title);
390
+ }
391
+ return titles;
392
+ }
393
+ function keysFor(test) {
394
+ return [
395
+ { kind: "playwright-id", value: test.id },
396
+ { kind: "path-title", value: [fileOf(test), ...titlesOf(test)].join("#") }
397
+ ];
398
+ }
399
+ var METADATA_TYPE = "application/plune.metadata+json";
400
+ var TOKEN = /@P([A-Za-z0-9_-]+)/;
401
+ function metadataOf(result) {
402
+ const found = result.attachments.find((a) => a.contentType === METADATA_TYPE);
403
+ if (found === void 0) return void 0;
404
+ try {
405
+ const raw = found.body !== void 0 ? found.body.toString("utf8") : found.path !== void 0 ? (0, import_node_fs.readFileSync)(found.path, "utf8") : void 0;
406
+ return raw === void 0 ? void 0 : JSON.parse(raw);
407
+ } catch {
408
+ return void 0;
409
+ }
410
+ }
411
+ function statedIdOf(test, metadata) {
412
+ const annotation = test.annotations.find((a) => a.type === "PluneId")?.description;
413
+ if (annotation !== void 0 && annotation !== "") return annotation;
414
+ const token = TOKEN.exec(test.title)?.[1];
415
+ if (token !== void 0) return token;
416
+ return metadata?.id !== void 0 && metadata.id !== "" ? metadata.id : void 0;
417
+ }
418
+ function errorTextOf(result) {
419
+ return result.errors.map((e) => e.stack ?? e.message ?? e.value ?? "").filter((text) => text !== "").join("\n\n");
420
+ }
421
+ function pendingFrom(test, result) {
422
+ const metadata = metadataOf(result);
423
+ const pluneId = statedIdOf(test, metadata);
424
+ const expected = test.expectedStatus;
425
+ const errorContext = errorTextOf(result);
426
+ const startedAt = result.startTime;
427
+ return {
428
+ resultKey: resultKey(test.id, result.retry),
429
+ ...pluneId !== void 0 ? { testCaseId: pluneId } : {},
430
+ // Anything the test named itself comes before what we derived from its location: a Qase or
431
+ // TestRail id written by a fixture is a deliberate statement, and a file path is a guess.
432
+ keys: [...metadata?.keys ?? [], ...keysFor(test)],
433
+ source: SOURCE,
434
+ // The runner's own word, untouched. Mapping it is the platform's job and a project's setting.
435
+ rawStatus: result.status,
436
+ // `passed` is the default and says nothing; the other two are `test.fail()` and `test.skip()`,
437
+ // and they happen to be spelled the same on both sides — so this is a pass-through, not a map.
438
+ ...expected === "failed" || expected === "skipped" ? { expectedStatus: expected } : {},
439
+ execution: {
440
+ startedAt: startedAt.toISOString(),
441
+ finishedAt: new Date(startedAt.getTime() + result.duration).toISOString(),
442
+ durationMs: result.duration,
443
+ retry: result.retry,
444
+ worker: String(result.workerIndex)
445
+ },
446
+ ...errorContext !== "" ? { errorContext } : {}
447
+ };
448
+ }
449
+ var PluneReporter = class {
450
+ options;
451
+ session = null;
452
+ /** Results arrive from a sync callback; this serialises them into the async core. */
453
+ chain = Promise.resolve();
454
+ keepOpen = false;
455
+ complained = false;
456
+ constructor(options = {}) {
457
+ this.options = options;
458
+ }
459
+ /** Playwright reads this to pick the v2 calling convention (`onConfigure` + `onBegin(suite)`). */
460
+ version() {
461
+ return "v2";
462
+ }
463
+ /** Nothing is drawn; the runner's own reporter keeps the terminal. */
464
+ printsToStdio() {
465
+ return false;
466
+ }
467
+ onConfigure(config) {
468
+ this.keepOpen = config.shard !== null && config.shard !== void 0 || readEnv().keepOpen;
469
+ }
470
+ onBegin(suite) {
471
+ const tests = suite.allTests();
472
+ this.session = startRun(
473
+ {
474
+ ...this.options.apiUrl !== void 0 ? { apiUrl: this.options.apiUrl } : {},
475
+ ...this.options.token !== void 0 ? { token: this.options.token } : {},
476
+ ...this.options.externalKey !== void 0 ? { externalKey: this.options.externalKey } : {},
477
+ ...this.options.batchSize !== void 0 ? { batchSize: this.options.batchSize } : {},
478
+ ...this.options.fallbackPath !== void 0 ? { fallbackPath: this.options.fallbackPath } : {},
479
+ meta: { runner: SOURCE }
480
+ },
481
+ tests.map(keysFor)
482
+ );
483
+ }
484
+ onTestEnd(test, result) {
485
+ const session = this.session;
486
+ if (session === null) return;
487
+ this.chain = this.chain.then(async () => {
488
+ (await session).add(pendingFrom(test, result));
489
+ }).catch((err) => this.giveUp(err));
490
+ }
491
+ async onEnd(_result) {
492
+ const session = this.session;
493
+ if (session === null) return;
494
+ try {
495
+ await this.chain;
496
+ const run = await session;
497
+ if (this.keepOpen) await run.leaveOpen();
498
+ else await run.finish();
499
+ } catch (err) {
500
+ this.giveUp(err);
501
+ }
502
+ }
503
+ /** Say it once, then stay out of the way. The test run's own outcome is not ours to change. */
504
+ giveUp(err) {
505
+ if (this.complained) return;
506
+ this.complained = true;
507
+ const reason = err instanceof Error ? err.message : String(err);
508
+ process.stderr.write(`plune: reporting stopped \u2014 ${reason}
509
+ `);
510
+ }
511
+ };
@@ -0,0 +1,38 @@
1
+ import { FullConfig, Suite, TestCase, TestResult, FullResult } from '@playwright/test/reporter';
2
+
3
+ interface PluneReporterOptions {
4
+ /** Platform base URL. Defaults to `PLUNE_API_URL`, then beta. */
5
+ apiUrl?: string;
6
+ /** API token. Defaults to whatever `plune login` saved. */
7
+ token?: string;
8
+ /**
9
+ * The key that makes several processes land in one run — shards, or a `merge-reports` step.
10
+ * Falls back to `PLUNE_RUN`, which the core reads; without either, this run is its own.
11
+ */
12
+ externalKey?: string;
13
+ /** Results per request. The platform's ceiling is 500. */
14
+ batchSize?: number;
15
+ /** Where unsent batches are written. Defaults to `.plune/pending-results.jsonl`. */
16
+ fallbackPath?: string;
17
+ }
18
+ declare class PluneReporter {
19
+ private readonly options;
20
+ private session;
21
+ /** Results arrive from a sync callback; this serialises them into the async core. */
22
+ private chain;
23
+ private keepOpen;
24
+ private complained;
25
+ constructor(options?: PluneReporterOptions);
26
+ /** Playwright reads this to pick the v2 calling convention (`onConfigure` + `onBegin(suite)`). */
27
+ version(): 'v2';
28
+ /** Nothing is drawn; the runner's own reporter keeps the terminal. */
29
+ printsToStdio(): boolean;
30
+ onConfigure(config: FullConfig): void;
31
+ onBegin(suite: Suite): void;
32
+ onTestEnd(test: TestCase, result: TestResult): void;
33
+ onEnd(_result: FullResult): Promise<void>;
34
+ /** Say it once, then stay out of the way. The test run's own outcome is not ours to change. */
35
+ private giveUp;
36
+ }
37
+
38
+ export { type PluneReporterOptions, PluneReporter as default };
@@ -0,0 +1,38 @@
1
+ import { FullConfig, Suite, TestCase, TestResult, FullResult } from '@playwright/test/reporter';
2
+
3
+ interface PluneReporterOptions {
4
+ /** Platform base URL. Defaults to `PLUNE_API_URL`, then beta. */
5
+ apiUrl?: string;
6
+ /** API token. Defaults to whatever `plune login` saved. */
7
+ token?: string;
8
+ /**
9
+ * The key that makes several processes land in one run — shards, or a `merge-reports` step.
10
+ * Falls back to `PLUNE_RUN`, which the core reads; without either, this run is its own.
11
+ */
12
+ externalKey?: string;
13
+ /** Results per request. The platform's ceiling is 500. */
14
+ batchSize?: number;
15
+ /** Where unsent batches are written. Defaults to `.plune/pending-results.jsonl`. */
16
+ fallbackPath?: string;
17
+ }
18
+ declare class PluneReporter {
19
+ private readonly options;
20
+ private session;
21
+ /** Results arrive from a sync callback; this serialises them into the async core. */
22
+ private chain;
23
+ private keepOpen;
24
+ private complained;
25
+ constructor(options?: PluneReporterOptions);
26
+ /** Playwright reads this to pick the v2 calling convention (`onConfigure` + `onBegin(suite)`). */
27
+ version(): 'v2';
28
+ /** Nothing is drawn; the runner's own reporter keeps the terminal. */
29
+ printsToStdio(): boolean;
30
+ onConfigure(config: FullConfig): void;
31
+ onBegin(suite: Suite): void;
32
+ onTestEnd(test: TestCase, result: TestResult): void;
33
+ onEnd(_result: FullResult): Promise<void>;
34
+ /** Say it once, then stay out of the way. The test run's own outcome is not ours to change. */
35
+ private giveUp;
36
+ }
37
+
38
+ export { type PluneReporterOptions, PluneReporter as default };
package/dist/index.js ADDED
@@ -0,0 +1,480 @@
1
+ // src/index.ts
2
+ import { readFileSync as readFileSync2 } from "fs";
3
+
4
+ // ../../dist/reporter-core.js
5
+ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
6
+ import { homedir } from "os";
7
+ import { dirname, join } from "path";
8
+ import * as fs from "fs";
9
+ import * as path from "path";
10
+ import { createHash } from "crypto";
11
+ var DEFAULT_API_URL = "https://beta-api.plune.ai";
12
+ function resolveApiUrl(explicit) {
13
+ const raw = explicit ?? process.env["PLUNE_API_URL"] ?? DEFAULT_API_URL;
14
+ return raw.replace(/\/+$/, "");
15
+ }
16
+ function credentialsFile() {
17
+ const base = process.env["XDG_CONFIG_HOME"]?.trim() || join(homedir(), ".config");
18
+ return join(base, "plune", "credentials.json");
19
+ }
20
+ function loadToken() {
21
+ try {
22
+ const parsed = JSON.parse(readFileSync(credentialsFile(), "utf-8"));
23
+ return typeof parsed.token === "string" && parsed.token.length > 0 ? parsed.token : null;
24
+ } catch {
25
+ return null;
26
+ }
27
+ }
28
+ var RETRY_DELAYS_MS = [300, 900];
29
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
30
+ async function detailOf(res) {
31
+ try {
32
+ const body = await res.json();
33
+ return typeof body.error === "string" ? body.error : "";
34
+ } catch {
35
+ return "";
36
+ }
37
+ }
38
+ function retryAfterMs(res) {
39
+ const raw = res.headers.get("retry-after");
40
+ if (raw === null) return null;
41
+ const seconds = Number(raw.trim());
42
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1e3 : null;
43
+ }
44
+ function classify(status) {
45
+ if (status === 401 || status === 403) return "auth";
46
+ if (status === 409) return "conflict";
47
+ if (status === 400) return "invalid";
48
+ if (status === 429 || status >= 500) return "unavailable";
49
+ return "other";
50
+ }
51
+ function createClient(opts) {
52
+ const doFetch = opts.fetchImpl ?? fetch;
53
+ const wait = opts.wait ?? sleep;
54
+ const base = opts.apiUrl.replace(/\/+$/, "");
55
+ const scrub = (text) => opts.token === "" ? text : text.split(opts.token).join("***");
56
+ async function post(path2, body) {
57
+ let last = {
58
+ kind: "unavailable",
59
+ status: null,
60
+ detail: "no attempt was made"
61
+ };
62
+ for (let attempt = 0; attempt <= RETRY_DELAYS_MS.length; attempt += 1) {
63
+ let res;
64
+ try {
65
+ res = await doFetch(`${base}${path2}`, {
66
+ method: "POST",
67
+ headers: { "content-type": "application/json", authorization: `Bearer ${opts.token}` },
68
+ body: JSON.stringify(body)
69
+ });
70
+ } catch (err) {
71
+ last = { kind: "unavailable", status: null, detail: scrub(String(err)) };
72
+ if (attempt < RETRY_DELAYS_MS.length) await wait(RETRY_DELAYS_MS[attempt]);
73
+ continue;
74
+ }
75
+ if (res.ok) return { ok: true, status: res.status, body: await res.json() };
76
+ const detail = scrub(await detailOf(res));
77
+ const kind = classify(res.status);
78
+ last = { kind, status: res.status, detail };
79
+ if (kind !== "unavailable") break;
80
+ if (attempt < RETRY_DELAYS_MS.length) {
81
+ await wait(retryAfterMs(res) ?? RETRY_DELAYS_MS[attempt]);
82
+ }
83
+ }
84
+ return { ok: false, ...last };
85
+ }
86
+ return { post };
87
+ }
88
+ var UNSUPPORTED_VARS = [
89
+ "PLUNE_RUN_TITLE",
90
+ "PLUNE_ENV",
91
+ "PLUNE_LABELS",
92
+ "PLUNE_GROUP"
93
+ ];
94
+ function value(env, name) {
95
+ const raw = env[name]?.trim();
96
+ return raw === void 0 || raw === "" ? void 0 : raw;
97
+ }
98
+ function flag(env, name) {
99
+ const raw = value(env, name)?.toLowerCase();
100
+ return raw === "1" || raw === "true" || raw === "yes" || raw === "on";
101
+ }
102
+ function count(env, name) {
103
+ const raw = value(env, name);
104
+ if (raw === void 0) return void 0;
105
+ const n = Number(raw);
106
+ return Number.isInteger(n) && n > 0 ? n : void 0;
107
+ }
108
+ function readEnv(env = process.env) {
109
+ const externalKey = value(env, "PLUNE_RUN");
110
+ const token = value(env, "PLUNE_TOKEN");
111
+ const apiUrl = value(env, "PLUNE_API_URL");
112
+ const fallbackPath = value(env, "PLUNE_FALLBACK");
113
+ const batchSize = count(env, "PLUNE_BATCH_SIZE");
114
+ return {
115
+ config: {
116
+ ...externalKey !== void 0 ? { externalKey } : {},
117
+ ...token !== void 0 ? { token } : {},
118
+ ...apiUrl !== void 0 ? { apiUrl } : {},
119
+ ...fallbackPath !== void 0 ? { fallbackPath } : {},
120
+ ...batchSize !== void 0 ? { batchSize } : {}
121
+ },
122
+ // Two names for two situations that end the same way. `SHARED_RUN` says other processes are
123
+ // reporting into this run; `PROCEED` says the job will close it on its own schedule. Either
124
+ // way this process must not be the one to call it finished.
125
+ keepOpen: flag(env, "PLUNE_SHARED_RUN") || flag(env, "PLUNE_PROCEED"),
126
+ ignored: UNSUPPORTED_VARS.filter((name) => value(env, name) !== void 0)
127
+ };
128
+ }
129
+ var DEFAULT_FALLBACK_PATH = path.join(".plune", "pending-results.jsonl");
130
+ function appendBatch(file, batch) {
131
+ fs.mkdirSync(path.dirname(file), { recursive: true });
132
+ const line = {
133
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
134
+ runId: batch.runId,
135
+ externalKey: batch.externalKey,
136
+ results: batch.results
137
+ };
138
+ fs.appendFileSync(file, `${JSON.stringify(line)}
139
+ `, "utf8");
140
+ }
141
+ var RESOLVE_CHUNK = 500;
142
+ var BATCH_MAX = 500;
143
+ var BATCH_DEFAULT = 100;
144
+ var EXPECTED_MAX = 1e4;
145
+ function chunk(items, size) {
146
+ const out = [];
147
+ for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
148
+ return out;
149
+ }
150
+ async function startRun(passed, expected) {
151
+ const env = readEnv();
152
+ const stated = Object.fromEntries(Object.entries(passed).filter(([, v]) => v !== void 0));
153
+ const cfg = { ...env.config, ...stated };
154
+ const log = cfg.log ?? ((line) => void process.stderr.write(`${line}
155
+ `));
156
+ const fallbackPath = cfg.fallbackPath ?? DEFAULT_FALLBACK_PATH;
157
+ const externalKey = cfg.externalKey ?? null;
158
+ const batchSize = Math.min(cfg.batchSize ?? BATCH_DEFAULT, BATCH_MAX);
159
+ const token = cfg.token ?? loadToken() ?? "";
160
+ const client = createClient({
161
+ apiUrl: resolveApiUrl(cfg.apiUrl),
162
+ token,
163
+ ...cfg.fetchImpl !== void 0 ? { fetchImpl: cfg.fetchImpl } : {}
164
+ });
165
+ const stats = {
166
+ accepted: 0,
167
+ duplicate: 0,
168
+ conflict: 0,
169
+ rejected: 0,
170
+ unresolved: 0,
171
+ deferred: 0
172
+ };
173
+ const resolved = /* @__PURE__ */ new Map();
174
+ let buffer = [];
175
+ let runId = null;
176
+ let joined = false;
177
+ let offline = token === "";
178
+ let done = false;
179
+ if (offline) {
180
+ log('plune: no API token \u2014 run "plune login" first. Results will be written to the fallback file.');
181
+ }
182
+ if (env.ignored.length > 0) {
183
+ log(`plune: ignoring ${env.ignored.join(", ")} \u2014 a run has nowhere to store them yet.`);
184
+ }
185
+ function defer(results) {
186
+ appendBatch(fallbackPath, { runId, externalKey, results });
187
+ stats.deferred += results.length;
188
+ }
189
+ async function resolveKeys(values) {
190
+ const unknown = values.filter((k) => !resolved.has(k.value));
191
+ if (unknown.length === 0 || offline) return;
192
+ for (const part of chunk(unknown, RESOLVE_CHUNK)) {
193
+ const out = await client.post(
194
+ "/v1/test-cases/resolve",
195
+ { keys: part }
196
+ );
197
+ if (!out.ok) {
198
+ log(`plune: could not look up test cases (${out.detail || out.kind}).`);
199
+ return;
200
+ }
201
+ for (const row of out.body.results) resolved.set(row.key.value, row.testCaseId);
202
+ }
203
+ }
204
+ if (!offline) {
205
+ if (expected !== void 0) await resolveKeys(expected.flat());
206
+ const declared = expected?.slice(0, EXPECTED_MAX) ?? [];
207
+ const configuration = declared.length === 0 ? void 0 : {
208
+ expected: declared.flatMap((keys) => {
209
+ const hit = keys.map((k) => resolved.get(k.value)).find((v) => typeof v === "string");
210
+ if (typeof hit === "string") return [{ testCaseId: hit }];
211
+ return keys[0] === void 0 ? [] : [{ externalKey: keys[0] }];
212
+ })
213
+ };
214
+ if (expected !== void 0 && expected.length > EXPECTED_MAX) {
215
+ log(`plune: ${expected.length} tests is more than the run configuration holds \u2014 reporting the first ${EXPECTED_MAX}.`);
216
+ }
217
+ const start = await client.post("/v1/runs", {
218
+ schemaVersion: 2,
219
+ kind: cfg.kind ?? "automated",
220
+ ...externalKey !== null ? { externalKey } : {},
221
+ ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
222
+ ...configuration !== void 0 ? { configuration } : {}
223
+ });
224
+ if (start.ok) {
225
+ runId = start.body.run.id;
226
+ joined = start.status === 200;
227
+ } else {
228
+ log(`plune: could not start the run (${start.detail || start.kind}). Results will be written to ${fallbackPath}.`);
229
+ }
230
+ }
231
+ function matchFor(result) {
232
+ if (result.testCaseId !== void 0) return { kind: "found", testCaseId: result.testCaseId };
233
+ let unanswered = false;
234
+ for (const key of result.keys) {
235
+ const hit = resolved.get(key.value);
236
+ if (typeof hit === "string") return { kind: "found", testCaseId: hit };
237
+ if (hit === void 0) unanswered = true;
238
+ }
239
+ return unanswered ? { kind: "unanswered" } : { kind: "unmatched" };
240
+ }
241
+ async function flush() {
242
+ if (buffer.length === 0) return;
243
+ const pending = buffer;
244
+ buffer = [];
245
+ if (offline || runId === null) {
246
+ defer(pending);
247
+ return;
248
+ }
249
+ await resolveKeys(pending.flatMap((p) => p.keys));
250
+ const submissions = [];
251
+ const unanswered = [];
252
+ for (const result of pending) {
253
+ const match = matchFor(result);
254
+ if (match.kind === "found") {
255
+ const { keys: _keys, ...rest } = result;
256
+ submissions.push({ ...rest, testCaseId: match.testCaseId });
257
+ } else if (match.kind === "unmatched") {
258
+ stats.unresolved += 1;
259
+ } else {
260
+ unanswered.push(result);
261
+ }
262
+ }
263
+ if (unanswered.length > 0) defer(unanswered);
264
+ if (submissions.length === 0) return;
265
+ const out = await client.post(
266
+ `/v1/runs/${runId}/results`,
267
+ { results: submissions }
268
+ );
269
+ if (out.ok) {
270
+ stats.accepted += out.body.counts.accepted ?? 0;
271
+ stats.duplicate += out.body.counts.duplicate ?? 0;
272
+ stats.conflict += out.body.counts.conflict ?? 0;
273
+ stats.rejected += out.body.counts.rejected ?? 0;
274
+ return;
275
+ }
276
+ if (out.kind === "auth") {
277
+ log('plune: the API token was refused \u2014 run "plune login" with a fresh one.');
278
+ offline = true;
279
+ } else if (out.kind === "conflict") {
280
+ log(`plune: this run is closed \u2014 ${out.detail}`);
281
+ } else {
282
+ log(`plune: could not send results (${out.detail || out.kind}).`);
283
+ }
284
+ defer(submissions);
285
+ }
286
+ function summarise() {
287
+ const parts = [`${stats.accepted} accepted`];
288
+ if (stats.duplicate > 0) parts.push(`${stats.duplicate} already reported`);
289
+ if (stats.conflict > 0) parts.push(`${stats.conflict} conflicting`);
290
+ if (stats.rejected > 0) parts.push(`${stats.rejected} rejected`);
291
+ if (stats.unresolved > 0) parts.push(`${stats.unresolved} with no matching test case`);
292
+ if (stats.deferred > 0) parts.push(`${stats.deferred} written to ${fallbackPath}`);
293
+ log(`plune: ${parts.join(" \xB7 ")}`);
294
+ }
295
+ return {
296
+ get runId() {
297
+ return runId;
298
+ },
299
+ get joined() {
300
+ return joined;
301
+ },
302
+ get stats() {
303
+ return stats;
304
+ },
305
+ async add(result) {
306
+ buffer.push(result);
307
+ if (buffer.length >= batchSize) await flush();
308
+ },
309
+ flush,
310
+ async finish(reason) {
311
+ if (done) return;
312
+ done = true;
313
+ await flush();
314
+ if (runId !== null && !offline) {
315
+ const out = await client.post(`/v1/runs/${runId}/events`, {
316
+ event: "finish",
317
+ ...reason !== void 0 ? { reason } : {}
318
+ });
319
+ if (!out.ok) log(`plune: could not close run ${runId} (${out.detail || out.kind}).`);
320
+ }
321
+ summarise();
322
+ },
323
+ async leaveOpen() {
324
+ if (done) return;
325
+ done = true;
326
+ await flush();
327
+ if (runId !== null) {
328
+ log(`plune: run ${runId} is still open \u2014 close it with "plune run finish ${runId}".`);
329
+ }
330
+ summarise();
331
+ }
332
+ };
333
+ }
334
+ function sha256(input) {
335
+ return createHash("sha256").update(input, "utf8").digest("hex");
336
+ }
337
+ var RESULT_KEY_MAX = 200;
338
+ var HASH_CHARS = 32;
339
+ function resultKey(testId, retry) {
340
+ const plain = `${testId}#${retry}`;
341
+ return plain.length <= RESULT_KEY_MAX ? plain : `${sha256(testId).slice(0, HASH_CHARS)}#${retry}`;
342
+ }
343
+
344
+ // src/index.ts
345
+ var SOURCE = "playwright";
346
+ function fileOf(test) {
347
+ for (let suite = test.parent; suite !== void 0; suite = suite.parent) {
348
+ if (suite.type === "file") return suite.title;
349
+ }
350
+ return "";
351
+ }
352
+ function titlesOf(test) {
353
+ const titles = [test.title];
354
+ for (let suite = test.parent; suite !== void 0 && suite.type === "describe"; suite = suite.parent) {
355
+ if (suite.title !== "") titles.unshift(suite.title);
356
+ }
357
+ return titles;
358
+ }
359
+ function keysFor(test) {
360
+ return [
361
+ { kind: "playwright-id", value: test.id },
362
+ { kind: "path-title", value: [fileOf(test), ...titlesOf(test)].join("#") }
363
+ ];
364
+ }
365
+ var METADATA_TYPE = "application/plune.metadata+json";
366
+ var TOKEN = /@P([A-Za-z0-9_-]+)/;
367
+ function metadataOf(result) {
368
+ const found = result.attachments.find((a) => a.contentType === METADATA_TYPE);
369
+ if (found === void 0) return void 0;
370
+ try {
371
+ const raw = found.body !== void 0 ? found.body.toString("utf8") : found.path !== void 0 ? readFileSync2(found.path, "utf8") : void 0;
372
+ return raw === void 0 ? void 0 : JSON.parse(raw);
373
+ } catch {
374
+ return void 0;
375
+ }
376
+ }
377
+ function statedIdOf(test, metadata) {
378
+ const annotation = test.annotations.find((a) => a.type === "PluneId")?.description;
379
+ if (annotation !== void 0 && annotation !== "") return annotation;
380
+ const token = TOKEN.exec(test.title)?.[1];
381
+ if (token !== void 0) return token;
382
+ return metadata?.id !== void 0 && metadata.id !== "" ? metadata.id : void 0;
383
+ }
384
+ function errorTextOf(result) {
385
+ return result.errors.map((e) => e.stack ?? e.message ?? e.value ?? "").filter((text) => text !== "").join("\n\n");
386
+ }
387
+ function pendingFrom(test, result) {
388
+ const metadata = metadataOf(result);
389
+ const pluneId = statedIdOf(test, metadata);
390
+ const expected = test.expectedStatus;
391
+ const errorContext = errorTextOf(result);
392
+ const startedAt = result.startTime;
393
+ return {
394
+ resultKey: resultKey(test.id, result.retry),
395
+ ...pluneId !== void 0 ? { testCaseId: pluneId } : {},
396
+ // Anything the test named itself comes before what we derived from its location: a Qase or
397
+ // TestRail id written by a fixture is a deliberate statement, and a file path is a guess.
398
+ keys: [...metadata?.keys ?? [], ...keysFor(test)],
399
+ source: SOURCE,
400
+ // The runner's own word, untouched. Mapping it is the platform's job and a project's setting.
401
+ rawStatus: result.status,
402
+ // `passed` is the default and says nothing; the other two are `test.fail()` and `test.skip()`,
403
+ // and they happen to be spelled the same on both sides — so this is a pass-through, not a map.
404
+ ...expected === "failed" || expected === "skipped" ? { expectedStatus: expected } : {},
405
+ execution: {
406
+ startedAt: startedAt.toISOString(),
407
+ finishedAt: new Date(startedAt.getTime() + result.duration).toISOString(),
408
+ durationMs: result.duration,
409
+ retry: result.retry,
410
+ worker: String(result.workerIndex)
411
+ },
412
+ ...errorContext !== "" ? { errorContext } : {}
413
+ };
414
+ }
415
+ var PluneReporter = class {
416
+ options;
417
+ session = null;
418
+ /** Results arrive from a sync callback; this serialises them into the async core. */
419
+ chain = Promise.resolve();
420
+ keepOpen = false;
421
+ complained = false;
422
+ constructor(options = {}) {
423
+ this.options = options;
424
+ }
425
+ /** Playwright reads this to pick the v2 calling convention (`onConfigure` + `onBegin(suite)`). */
426
+ version() {
427
+ return "v2";
428
+ }
429
+ /** Nothing is drawn; the runner's own reporter keeps the terminal. */
430
+ printsToStdio() {
431
+ return false;
432
+ }
433
+ onConfigure(config) {
434
+ this.keepOpen = config.shard !== null && config.shard !== void 0 || readEnv().keepOpen;
435
+ }
436
+ onBegin(suite) {
437
+ const tests = suite.allTests();
438
+ this.session = startRun(
439
+ {
440
+ ...this.options.apiUrl !== void 0 ? { apiUrl: this.options.apiUrl } : {},
441
+ ...this.options.token !== void 0 ? { token: this.options.token } : {},
442
+ ...this.options.externalKey !== void 0 ? { externalKey: this.options.externalKey } : {},
443
+ ...this.options.batchSize !== void 0 ? { batchSize: this.options.batchSize } : {},
444
+ ...this.options.fallbackPath !== void 0 ? { fallbackPath: this.options.fallbackPath } : {},
445
+ meta: { runner: SOURCE }
446
+ },
447
+ tests.map(keysFor)
448
+ );
449
+ }
450
+ onTestEnd(test, result) {
451
+ const session = this.session;
452
+ if (session === null) return;
453
+ this.chain = this.chain.then(async () => {
454
+ (await session).add(pendingFrom(test, result));
455
+ }).catch((err) => this.giveUp(err));
456
+ }
457
+ async onEnd(_result) {
458
+ const session = this.session;
459
+ if (session === null) return;
460
+ try {
461
+ await this.chain;
462
+ const run = await session;
463
+ if (this.keepOpen) await run.leaveOpen();
464
+ else await run.finish();
465
+ } catch (err) {
466
+ this.giveUp(err);
467
+ }
468
+ }
469
+ /** Say it once, then stay out of the way. The test run's own outcome is not ours to change. */
470
+ giveUp(err) {
471
+ if (this.complained) return;
472
+ this.complained = true;
473
+ const reason = err instanceof Error ? err.message : String(err);
474
+ process.stderr.write(`plune: reporting stopped \u2014 ${reason}
475
+ `);
476
+ }
477
+ };
478
+ export {
479
+ PluneReporter as default
480
+ };
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@plune-ai/playwright",
3
+ "version": "0.1.0",
4
+ "description": "Report Playwright results to Plune — a reporter and, later, a test importer.",
5
+ "keywords": [
6
+ "playwright",
7
+ "reporter",
8
+ "plune",
9
+ "test-management",
10
+ "tms",
11
+ "qa"
12
+ ],
13
+ "type": "module",
14
+ "main": "./dist/index.cjs",
15
+ "module": "./dist/index.js",
16
+ "types": "./dist/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js",
21
+ "require": "./dist/index.cjs"
22
+ }
23
+ },
24
+ "files": [
25
+ "dist",
26
+ "README.md",
27
+ "LICENSE"
28
+ ],
29
+ "engines": {
30
+ "node": ">=20.0.0"
31
+ },
32
+ "peerDependencies": {
33
+ "@playwright/test": ">=1.44.0"
34
+ },
35
+ "devDependencies": {
36
+ "@playwright/test": "^1.44.0",
37
+ "@types/node": "^25.9.1",
38
+ "tsup": "^8.0.0",
39
+ "typescript": "^5.4.0",
40
+ "vitest": "^1.6.0",
41
+ "@plune-ai/cli": "0.7.0"
42
+ },
43
+ "repository": {
44
+ "type": "git",
45
+ "url": "git+https://github.com/plune-ai/cli.git",
46
+ "directory": "packages/playwright"
47
+ },
48
+ "license": "MIT",
49
+ "publishConfig": {
50
+ "access": "public"
51
+ },
52
+ "scripts": {
53
+ "build": "tsup",
54
+ "typecheck": "tsc --noEmit",
55
+ "test": "tsup && vitest run",
56
+ "test:e2e": "tsup && vitest run -c vitest.e2e.config.ts"
57
+ }
58
+ }