@plune-ai/playwright 0.7.4 → 0.8.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.
@@ -0,0 +1,337 @@
1
+ // src/fixture.ts
2
+ import {
3
+ test as base,
4
+ expect
5
+ } from "@playwright/test";
6
+
7
+ // src/findings.ts
8
+ import { stripVTControlCharacters } from "util";
9
+
10
+ // ../../dist/reporter-core.js
11
+ import { TextDecoder } from "util";
12
+ import { Agent as HttpAgent, request as httpRequest } from "http";
13
+ import { Agent as HttpsAgent, request as httpsRequest } from "https";
14
+ import * as path2 from "path";
15
+ var POOLS = { "http:": new HttpAgent({ keepAlive: true }), "https:": new HttpsAgent({ keepAlive: true }) };
16
+ var HEADLINE_LIMIT = 8 * 1024;
17
+ var DIRECT_BATCH_BYTES = 6 * 1024 * 1024;
18
+ var DEFAULT_FALLBACK_PATH = path2.join(".plune", "pending-results.jsonl");
19
+ var BEFORE_REGEX = /* @__PURE__ */ new Set([..."(,=:[!&|?{};+-*%<>~^"]);
20
+ var CREDENTIAL = "password|passphrase|passwd|pass|pwd|token|secret|api[-_]?key|private[-_]?key|credential|auth|session|cookie";
21
+ var LITERAL = String.raw`(?<q>['"\x60])(?:\\.|(?!\k<q>)[^\\\n])*\k<q>`;
22
+ var TYPING = "(?:fill|type|pressSequentially)";
23
+ var SHAPES = [
24
+ { kind: "github-token", re: /\b(?:ghp|gho|ghs|ghu)_[A-Za-z0-9]{36}\b|\bgithub_pat_\w{20,}/g },
25
+ { kind: "api-key", re: /\bsk-[\w-]{20,}/g },
26
+ { kind: "api-key", re: /\b[sr]k_(?:live|test)_[A-Za-z0-9]{10,}/g },
27
+ { kind: "npm-token", re: /\bnpm_[A-Za-z0-9]{20,}/g },
28
+ { kind: "google-key", re: /\bAIza[\w-]{30,}/g },
29
+ { kind: "plune-token", re: /\bplune_[A-Za-z0-9_]{16,}/g },
30
+ { kind: "aws-key", re: /\bAKIA[0-9A-Z]{16}\b/g },
31
+ { kind: "slack-token", re: /\bxox[abprs]-[A-Za-z0-9-]{10,}/g },
32
+ {
33
+ kind: "private-key",
34
+ re: /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g
35
+ },
36
+ { kind: "jwt", re: /\beyJ[\w-]{10,}\.[\w-]{10,}\.[\w-]{10,}/g }
37
+ ];
38
+ var PLACES = [
39
+ // `password = '…'`, `apiKey: "…"`, `'x-api-key': '…'`
40
+ new RegExp(
41
+ String.raw`(?<lead>\b(?<role>[\w$-]*(?:${CREDENTIAL})[\w$-]*)['"]?\s*[:=]\s*)${LITERAL}`,
42
+ "gi"
43
+ ),
44
+ // `setToken('…')`: the call is named for a credential
45
+ new RegExp(String.raw`(?<lead>\b(?<role>[\w$]*(?:${CREDENTIAL})[\w$]*)\s*\(\s*)${LITERAL}`, "gi"),
46
+ // `.fill('#password', '…')`, `.type('#pwd', '…')`: the field is named in the same call
47
+ new RegExp(
48
+ String.raw`(?<lead>\.${TYPING}\(\s*['"][^'"\n]*?(?<role>${CREDENTIAL})[^'"\n]*['"]\s*,\s*)${LITERAL}`,
49
+ "gi"
50
+ ),
51
+ // `getByLabel('Password').fill('…')`, `getByRole('textbox', { name: 'Password' }).type('…')`: … or
52
+ // anywhere in the call the typing is chained off
53
+ new RegExp(
54
+ String.raw`(?<lead>\([^()\n]*?(?<role>${CREDENTIAL})[^()\n]*\)\s*\.${TYPING}\(\s*)${LITERAL}`,
55
+ "gi"
56
+ ),
57
+ // `{ name: 'session', value: '…' }`: a cookie (or any name/value pair) named for a credential
58
+ new RegExp(
59
+ String.raw`(?<lead>\bname\s*:\s*['"][^'"\n]*?(?<role>${CREDENTIAL})[^'"\n]*['"]\s*,\s*value\s*:\s*)${LITERAL}`,
60
+ "gi"
61
+ )
62
+ ];
63
+ var HEADER_LINE = /((?:^|\\[nr]|\x60)[ \t>*<+-]*['"]?)((?:proxy-)?authorization|(?:set-)?cookie|[\w-]*session[\w-]*)(['"]?[ \t]*:[ \t]*)(?![\w$.]+(?:\([^()\n]*\))?[ \t]*[,;)}\]])[^\s'"\x60\\][^\r\n'"\x60\\]*/gim;
64
+ var QUERY_PARAM = /([?&][\w.-]*(?:token|key|secret|password|passwd|pass|pwd|auth|signature|sig|credential|session)[\w.-]*=)(?!‹)[^&#\s'"\x60]+/gi;
65
+ function maskCredentials(text) {
66
+ let out = text;
67
+ for (const { kind, re } of SHAPES) out = out.replace(re, `\u2039${kind}\u203A`);
68
+ for (const re of PLACES) {
69
+ out = out.replace(re, (...args) => {
70
+ const groups = args.at(-1);
71
+ return `${groups.lead}${groups.q}\u2039${groups.role.toLowerCase().replace(/^[^a-z]+/, "")}\u203A${groups.q}`;
72
+ });
73
+ }
74
+ return out.replace(HEADER_LINE, "$1$2$3\u2039header\u203A").replace(/\b(Bearer)([ \t]+)(?!‹)[\w.~+/=-]{8,}/g, "$1$2\u2039credential\u203A").replace(
75
+ /\b(Basic|Token)([ \t]+)(?!‹)(?=[\w.~+/=-]*[\d=+/]|[\w.~+/=-]*[a-z][\w.~+/=-]*[A-Z])[\w.~+/=-]{8,}/g,
76
+ "$1$2\u2039credential\u203A"
77
+ ).replace(/\b(PLUNE_[A-Z0-9_]*=)(?!‹)[^\s'"\x60;,)]+/g, "$1\u2039env-secret\u203A").replace(QUERY_PARAM, "$1\u2039credential\u203A").replace(/\b([a-z][\w+.-]*:\/\/)[^\s/@'"\x60]+@/gi, "$1\u2039credential\u203A@");
78
+ }
79
+ var SCREENSHOT_BYTES = 2 * 1024 * 1024;
80
+ var SCREENSHOTS_PER_RESULT = 20;
81
+ var TEXT_BYTES = 512 * 1024;
82
+ var TEXTS_PER_RESULT = 10;
83
+ var UTF8 = new TextDecoder("utf-8", { fatal: true });
84
+ var SKIPPED = {
85
+ hidden: "its name starts with an underscore, which hides an attachment in Playwright's own reports too",
86
+ type: "Plune takes PNG, JPEG and WebP",
87
+ limit: `a result holds at most ${SCREENSHOTS_PER_RESULT}`,
88
+ missing: "the file cannot be read on this machine",
89
+ size: "Plune takes a file of at most 2 MB",
90
+ textLimit: `a result holds at most ${TEXTS_PER_RESULT} text files`,
91
+ textSize: "Plune takes a text file of at most 512 KiB",
92
+ empty: "the file is empty",
93
+ binary: "the file holds a NUL byte, and Plune takes UTF-8 text without one",
94
+ encoding: "Plune takes UTF-8 text only",
95
+ noStorage: "no storage bucket is connected to this project"
96
+ };
97
+ var BATCH_BYTES = 8 * 1024 * 1024;
98
+ var ENVELOPE_BYTES = Buffer.byteLength(JSON.stringify({ results: [] }));
99
+
100
+ // src/findings.ts
101
+ var FINDINGS_TYPE = "application/plune.findings+json";
102
+ var FINDINGS_MAX = 20;
103
+ var OMITTED_MAX = 1e5;
104
+ var TEXT_MAX = 300;
105
+ var METHOD = /^[A-Z]{1,16}$/;
106
+ var PATH = /^\/(?!\/)[^?#]*$/;
107
+ function clip(text, max = TEXT_MAX) {
108
+ const cut = text.slice(0, max);
109
+ return /[\ud800-\udbff]$/.test(cut) ? cut.slice(0, -1) : cut;
110
+ }
111
+ var WORK_MAX = 4e3;
112
+ var SEPARATORS = String.raw`\s"'\x60<>`;
113
+ var SEPARATOR = new RegExp(`[${SEPARATORS}]`);
114
+ var TOKEN = new RegExp(`[^${SEPARATORS}]+`, "g");
115
+ var SCHEME = /(?:https?|wss?):\/\//i;
116
+ var PATH_START = /(?:^|[(\[{=:,;])\.{0,2}\//;
117
+ var NAMED_QUERY = /\?[\w\-.[\]%]+=/;
118
+ function markIn(token, from) {
119
+ const at = token.slice(from).search(/[?#]/);
120
+ return at === -1 ? token.length : from + at;
121
+ }
122
+ function withoutQuery(token) {
123
+ const named = token.search(NAMED_QUERY);
124
+ let out = named === -1 ? token : token.slice(0, named);
125
+ const scheme = SCHEME.exec(out);
126
+ if (scheme !== null) {
127
+ const from = scheme.index + scheme[0].length;
128
+ const rest = out.slice(from, markIn(out, from));
129
+ const slash = rest.indexOf("/");
130
+ const user = rest.lastIndexOf("@", slash === -1 ? rest.length : slash);
131
+ return out.slice(0, from) + rest.slice(user + 1);
132
+ }
133
+ const path = PATH_START.exec(out);
134
+ if (path !== null) out = out.slice(0, markIn(out, path.index));
135
+ return out;
136
+ }
137
+ var SECRET_MARK = "\u2039env-secret\u203A";
138
+ var SECRET_MIN = 4;
139
+ function secretValues(names, env = process.env) {
140
+ const forms = /* @__PURE__ */ new Set();
141
+ for (const name of Array.isArray(names) ? names : []) {
142
+ const value = typeof name === "string" ? env[name] : void 0;
143
+ if (value === void 0 || value.length < SECRET_MIN) continue;
144
+ forms.add(value);
145
+ for (const encode of [encodeURIComponent, encodeURI]) {
146
+ try {
147
+ forms.add(encode(value));
148
+ } catch {
149
+ }
150
+ }
151
+ }
152
+ return [...forms].sort((a, b) => b.length - a.length);
153
+ }
154
+ function withoutSecrets(text, secrets) {
155
+ let out = text;
156
+ for (const secret of secrets) out = out.split(secret).join(SECRET_MARK);
157
+ return out;
158
+ }
159
+ function cleaned(raw, secrets) {
160
+ const window = raw.slice(0, WORK_MAX + (secrets[0]?.length ?? 0));
161
+ const text = withoutSecrets(window, secrets);
162
+ let head = clip(text, WORK_MAX);
163
+ const next = text.length > head.length ? text[head.length] : raw[window.length];
164
+ if (next !== void 0 && !SEPARATOR.test(next)) {
165
+ let end = head.length;
166
+ while (end > 0 && !SEPARATOR.test(head[end - 1])) end -= 1;
167
+ head = head.slice(0, end);
168
+ }
169
+ const masked = maskCredentials(stripVTControlCharacters(head));
170
+ const flat = masked.replace(TOKEN, withoutQuery).replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ");
171
+ return clip(flat.trim());
172
+ }
173
+ function createCollector(slowMs, secrets = []) {
174
+ let items = [];
175
+ let omitted = 0;
176
+ const drop = () => {
177
+ omitted = Math.min(OMITTED_MAX, omitted + 1);
178
+ };
179
+ const keep = (finding) => {
180
+ items.push(finding);
181
+ items.sort((a, b) => a.at - b.at);
182
+ if (items.length > FINDINGS_MAX) {
183
+ items = items.slice(0, FINDINGS_MAX);
184
+ drop();
185
+ }
186
+ };
187
+ const text = (kind, raw, at) => {
188
+ const clean = cleaned(String(raw), secrets);
189
+ if (clean === "") drop();
190
+ else keep({ kind, text: clean, at });
191
+ };
192
+ const place = (url, rawMethod) => {
193
+ let parsed;
194
+ try {
195
+ parsed = new URL(url);
196
+ } catch {
197
+ return null;
198
+ }
199
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
200
+ const method = String(rawMethod).toUpperCase();
201
+ const path = maskCredentials(withoutSecrets(parsed.pathname, secrets));
202
+ return METHOD.test(method) && PATH.test(path) && path.length <= TEXT_MAX ? { method, path } : void 0;
203
+ };
204
+ const request = (kind, seen, extra) => {
205
+ const where = place(seen.url, seen.method);
206
+ if (where === null) return;
207
+ if (where === void 0) drop();
208
+ else keep({ kind, ...where, ...extra, at: seen.at });
209
+ };
210
+ return {
211
+ console(raw, at) {
212
+ if (String(raw).startsWith("Failed to load resource:")) return;
213
+ text("console", raw, at);
214
+ },
215
+ pageError(message, at) {
216
+ text("page_error", message, at);
217
+ },
218
+ response({ status, durationMs, ...seen }) {
219
+ const ms = Number.isFinite(durationMs) ? Math.max(0, Math.round(durationMs)) : void 0;
220
+ const extra = {
221
+ ...Number.isInteger(status) && status >= 100 && status <= 599 ? { status } : {},
222
+ ...ms !== void 0 ? { durationMs: ms } : {}
223
+ };
224
+ if (status >= 400) request("request_failed", seen, extra);
225
+ else if (ms !== void 0 && ms >= slowMs) request("request_slow", seen, extra);
226
+ },
227
+ failed({ errorText, ...seen }) {
228
+ if (errorText?.includes("net::ERR_ABORTED") === true) return;
229
+ request("request_failed", seen, {});
230
+ },
231
+ result() {
232
+ return { items: [...items], omitted };
233
+ }
234
+ };
235
+ }
236
+ function watch(context, slowMs, secrets = []) {
237
+ const collector = createCollector(slowMs, secrets);
238
+ const started = /* @__PURE__ */ new WeakMap();
239
+ const settled = /* @__PURE__ */ new WeakSet();
240
+ const startOf = (request) => {
241
+ const own = request.timing().startTime;
242
+ return own > 0 ? own : started.get(request) ?? Date.now();
243
+ };
244
+ const once = (request) => {
245
+ if (settled.has(request)) return false;
246
+ settled.add(request);
247
+ return true;
248
+ };
249
+ const quiet = (listener) => (arg) => {
250
+ try {
251
+ void Promise.resolve(listener(arg)).catch(() => void 0);
252
+ } catch {
253
+ }
254
+ };
255
+ try {
256
+ context.on(
257
+ "console",
258
+ quiet((message) => {
259
+ if (message.type() === "error") collector.console(message.text(), Date.now());
260
+ })
261
+ );
262
+ context.on(
263
+ "weberror",
264
+ quiet(
265
+ (webError) => collector.pageError(webError.error().message, Date.now())
266
+ )
267
+ );
268
+ context.on(
269
+ "request",
270
+ quiet((request) => {
271
+ started.set(request, Date.now());
272
+ })
273
+ );
274
+ context.on(
275
+ "requestfailed",
276
+ quiet((request) => {
277
+ if (!once(request)) return;
278
+ const errorText = request.failure()?.errorText;
279
+ collector.failed({
280
+ url: request.url(),
281
+ method: request.method(),
282
+ at: startOf(request),
283
+ ...errorText !== void 0 ? { errorText } : {}
284
+ });
285
+ })
286
+ );
287
+ context.on(
288
+ "response",
289
+ quiet(async (response) => {
290
+ const request = response.request();
291
+ await response.finished();
292
+ if (!once(request)) return;
293
+ const end = request.timing().responseEnd;
294
+ collector.response({
295
+ url: request.url(),
296
+ method: request.method(),
297
+ status: response.status(),
298
+ at: startOf(request),
299
+ durationMs: end >= 0 ? end : Date.now() - (started.get(request) ?? Date.now())
300
+ });
301
+ })
302
+ );
303
+ } catch {
304
+ }
305
+ return collector;
306
+ }
307
+
308
+ // src/fixture.ts
309
+ var SLOW_MS = 3e3;
310
+ var findingsFixtures = {
311
+ pluneFindings: [true, { option: true }],
312
+ pluneSlowRequestMs: [SLOW_MS, { option: true }],
313
+ pluneSecretEnv: [[], { option: true }],
314
+ context: async ({ context, pluneFindings, pluneSlowRequestMs, pluneSecretEnv }, use, testInfo) => {
315
+ const collector = pluneFindings ? watch(
316
+ context,
317
+ Number.isFinite(pluneSlowRequestMs) && pluneSlowRequestMs >= 0 ? pluneSlowRequestMs : SLOW_MS,
318
+ // Read when the test's browser opens: the values this worker has now.
319
+ secretValues(pluneSecretEnv)
320
+ ) : void 0;
321
+ await use(context);
322
+ if (collector === void 0) return;
323
+ try {
324
+ await testInfo.attach("plune-findings", {
325
+ body: JSON.stringify(collector.result()),
326
+ contentType: FINDINGS_TYPE
327
+ });
328
+ } catch {
329
+ }
330
+ }
331
+ };
332
+ var test = base.extend(findingsFixtures);
333
+ export {
334
+ expect,
335
+ findingsFixtures,
336
+ test
337
+ };
package/dist/index.cjs CHANGED
@@ -35,7 +35,7 @@ __export(src_exports, {
35
35
  module.exports = __toCommonJS(src_exports);
36
36
  var import_node_fs = require("fs");
37
37
  var import_node_path = require("path");
38
- var import_node_util = require("util");
38
+ var import_node_util2 = require("util");
39
39
 
40
40
  // ../../dist/reporter-core.js
41
41
  var import_crypto = require("crypto");
@@ -441,7 +441,7 @@ function failureOf(attempt, home = (0, import_os2.homedir)()) {
441
441
  const headline = line !== void 0 && jsonBytes(line) <= HEADLINE_LIMIT ? line : void 0;
442
442
  const steps = chainOf(attempt.steps);
443
443
  const location = error === void 0 ? void 0 : fromRoot(placeOf(error, attempt.testFile), attempt.repoRoot);
444
- const artifacts = attempt.attachments.filter((a) => a.path !== void 0 && !a.name.startsWith("_") && a.contentType !== METADATA_TYPE).map(({ name, contentType }) => ({ name: fileNameOf(name), ...contentType ? { contentType } : {} })).filter((a) => a.name !== "");
444
+ const artifacts = attempt.attachments.filter((a) => a.path !== void 0 && !a.name.startsWith("_") && !READ_NOT_KEPT.has(a.contentType ?? "")).map(({ name, contentType }) => ({ name: fileNameOf(name), ...contentType ? { contentType } : {} })).filter((a) => a.name !== "");
445
445
  const ciUrl = webLink(attempt.buildHref);
446
446
  const failure = {
447
447
  ...headline !== void 0 ? { headline } : {},
@@ -514,7 +514,7 @@ function cut(text) {
514
514
  return { text: [...lines.slice(0, head), omitted(tail - head), ...lines.slice(tail)].join("\n"), omitted: text.length - kept.length };
515
515
  }
516
516
  var omitted = (lines) => `\u2026[omitted ${lines} lines]\u2026`;
517
- var METADATA_TYPE = "application/plune.metadata+json";
517
+ var READ_NOT_KEPT = /* @__PURE__ */ new Set(["application/plune.metadata+json", "application/plune.findings+json"]);
518
518
  var REPO_RELATIVE = /^(?![A-Za-z][A-Za-z0-9+.-]*:)(?![\\/~])(?!(?:.*[\\/])?\.\.(?:[\\/]|$)).+$/;
519
519
  var FRAME = /^\s+at (?:.*? \()?(.+?):(\d+):(\d+)\)?$/;
520
520
  var FRAME_MAX = 8192;
@@ -811,7 +811,7 @@ var TYPE_BY_EXTENSION = {
811
811
  ".jpeg": "image/jpeg",
812
812
  ".webp": "image/webp"
813
813
  };
814
- var METADATA_TYPE2 = "application/plune.metadata+json";
814
+ var READ_NOT_KEPT2 = /* @__PURE__ */ new Set(["application/plune.metadata+json", "application/plune.findings+json"]);
815
815
  var NAME_MAX = 200;
816
816
  function nameOf(file) {
817
817
  const own = file.name.split(/[\\/]/).pop()?.trim() || (file.path === void 0 ? "" : (0, import_path.basename)(file.path));
@@ -873,12 +873,17 @@ function textRefusal(bytes) {
873
873
  return void 0;
874
874
  }
875
875
  function withoutTargets(result) {
876
- if (result.targets === void 0) return result;
877
- const { targets: _targets, ...rest } = result;
876
+ if (result.targets === void 0 && result.traceUrl === void 0) return result;
877
+ const { targets: _targets, traceUrl: _traceUrl, ...rest } = result;
878
+ return rest;
879
+ }
880
+ function withoutFindings(result) {
881
+ if (result.findings === void 0) return result;
882
+ const { findings: _findings, ...rest } = result;
878
883
  return rest;
879
884
  }
880
885
  function onDisk(deferred) {
881
- const result = withoutTargets(deferred);
886
+ const result = withoutFindings(withoutTargets(deferred));
882
887
  if (!("files" in result) || result.files === void 0) return result;
883
888
  const { files, ...rest } = result;
884
889
  const kept = files.filter((f) => f.path !== void 0).map(({ body: _body, ...file }) => file);
@@ -1328,7 +1333,7 @@ function fileSender(options) {
1328
1333
  if (item?.status !== "accepted" || typeof item.id !== "string" || typeof item.resultKey !== "string") continue;
1329
1334
  for (const file of filesByKey.get(item.resultKey) ?? []) {
1330
1335
  const type = mediaTypeOf(file.contentType) ?? (file.path === void 0 ? void 0 : TYPE_BY_EXTENSION[(0, import_path.extname)(file.path).toLowerCase()]);
1331
- if (type === void 0 || type === METADATA_TYPE2) continue;
1336
+ if (type === void 0 || READ_NOT_KEPT2.has(type)) continue;
1332
1337
  const kind = kindOf(type);
1333
1338
  if (kind !== "text" && file.path === void 0) continue;
1334
1339
  const name = nameOf(file);
@@ -1431,6 +1436,7 @@ async function startRun(passed, declared2) {
1431
1436
  let joined = false;
1432
1437
  let offline = token === "";
1433
1438
  let targetsRefused = false;
1439
+ let findingsRefused = false;
1434
1440
  let done = false;
1435
1441
  const shortened = /* @__PURE__ */ new Set();
1436
1442
  const specFiles = /* @__PURE__ */ new Map();
@@ -1702,6 +1708,7 @@ async function startRun(passed, declared2) {
1702
1708
  async function send(submissions, filesByKey) {
1703
1709
  for (const packedPart of packed(submissions)) {
1704
1710
  let part = targetsRefused ? packedPart.map(withoutTargets) : packedPart;
1711
+ if (findingsRefused) part = part.map(withoutFindings);
1705
1712
  if (offline) {
1706
1713
  defer(part);
1707
1714
  continue;
@@ -1712,12 +1719,22 @@ async function startRun(passed, declared2) {
1712
1719
  { results, ...configuration !== void 0 ? { configuration } : {} }
1713
1720
  );
1714
1721
  let out = await post(part);
1715
- if (!out.ok && out.kind === "invalid" && out.status === 400 && part.some((r) => r.targets !== void 0)) {
1716
- if (!targetsRefused) log("plune: the platform does not take targets on a result yet \u2014 the results are sent without them.");
1722
+ let withoutItsFindings = false;
1723
+ if (!out.ok && out.kind === "invalid" && out.status === 400 && part.some((r) => r.findings !== void 0)) {
1724
+ withoutItsFindings = true;
1725
+ part = part.map(withoutFindings);
1726
+ out = await post(part);
1727
+ }
1728
+ if (!out.ok && out.kind === "invalid" && out.status === 400 && part.some((r) => r.targets !== void 0 || r.traceUrl !== void 0)) {
1729
+ if (!targetsRefused) log("plune: the platform does not take targets or a trace link on a result yet \u2014 the results are sent without them.");
1717
1730
  targetsRefused = true;
1718
1731
  part = part.map(withoutTargets);
1719
1732
  out = await post(part);
1720
1733
  }
1734
+ if (withoutItsFindings && out.ok) {
1735
+ if (!findingsRefused) log("plune: the platform does not take findings on a result yet \u2014 the results are sent without them.");
1736
+ findingsRefused = true;
1737
+ }
1721
1738
  const counts = out.ok ? out.body?.counts : void 0;
1722
1739
  const told = COUNTED.filter((k) => typeof counts?.[k] === "number");
1723
1740
  if (told.length > 0) {
@@ -1900,6 +1917,62 @@ function resultKey(testId, retry) {
1900
1917
  return plain.length <= RESULT_KEY_MAX ? plain : `${sha256(testId).slice(0, HASH_CHARS)}#${retry}`;
1901
1918
  }
1902
1919
 
1920
+ // src/findings.ts
1921
+ var import_node_util = require("util");
1922
+ var FINDINGS_TYPE = "application/plune.findings+json";
1923
+ var FINDINGS_MAX = 20;
1924
+ var OMITTED_MAX = 1e5;
1925
+ var TEXT_MAX = 300;
1926
+ var METHOD = /^[A-Z]{1,16}$/;
1927
+ var PATH = /^\/(?!\/)[^?#]*$/;
1928
+ function clip(text, max = TEXT_MAX) {
1929
+ const cut2 = text.slice(0, max);
1930
+ return /[\ud800-\udbff]$/.test(cut2) ? cut2.slice(0, -1) : cut2;
1931
+ }
1932
+ var SEPARATORS = String.raw`\s"'\x60<>`;
1933
+ var SEPARATOR = new RegExp(`[${SEPARATORS}]`);
1934
+ var TOKEN = new RegExp(`[^${SEPARATORS}]+`, "g");
1935
+ var isCount = (value2, min, max) => typeof value2 === "number" && Number.isInteger(value2) && value2 >= min && value2 <= max;
1936
+ var isText = (value2) => typeof value2 === "string" && value2.length >= 1 && value2.length <= TEXT_MAX;
1937
+ function toWire(raw, steps) {
1938
+ if (typeof raw !== "object" || raw === null) return void 0;
1939
+ const { items, omitted: omitted2 } = raw;
1940
+ if (!Array.isArray(items)) return void 0;
1941
+ const kept = [];
1942
+ let dropped = isCount(omitted2, 0, OMITTED_MAX) ? omitted2 : 0;
1943
+ for (const item of items) {
1944
+ const finding = kept.length < FINDINGS_MAX ? wireItem(item, steps) : void 0;
1945
+ if (finding === void 0) dropped += 1;
1946
+ else kept.push(finding);
1947
+ }
1948
+ return { items: kept, omitted: Math.min(OMITTED_MAX, dropped) };
1949
+ }
1950
+ function wireItem(item, steps) {
1951
+ if (typeof item !== "object" || item === null) return void 0;
1952
+ const { kind, text, method, path: path3, status, durationMs, at } = item;
1953
+ if (typeof at !== "number" || !Number.isFinite(at)) return void 0;
1954
+ const index = steps.findIndex((s) => s.start <= at && at < s.end);
1955
+ const title = index === -1 ? "" : clip(steps[index].title);
1956
+ const step = title === "" ? {} : { step: { index: index + 1, title } };
1957
+ if (kind === "console" || kind === "page_error") {
1958
+ return isText(text) ? { kind, text, ...step } : void 0;
1959
+ }
1960
+ if (kind !== "request_failed" && kind !== "request_slow") return void 0;
1961
+ if (typeof method !== "string" || !METHOD.test(method)) return void 0;
1962
+ if (!isText(path3) || !PATH.test(path3)) return void 0;
1963
+ if (status !== void 0 && !isCount(status, 100, 599)) return void 0;
1964
+ if (durationMs !== void 0 && !isCount(durationMs, 0, Number.MAX_SAFE_INTEGER))
1965
+ return void 0;
1966
+ return {
1967
+ kind,
1968
+ method,
1969
+ path: path3,
1970
+ ...status !== void 0 ? { status } : {},
1971
+ ...durationMs !== void 0 ? { durationMs } : {},
1972
+ ...step
1973
+ };
1974
+ }
1975
+
1903
1976
  // src/index.ts
1904
1977
  var SOURCE = "playwright";
1905
1978
  function fileOf2(test) {
@@ -1924,22 +1997,42 @@ function keysFor(test) {
1924
1997
  { kind: "path-title", value: pathTitleOf(test) }
1925
1998
  ];
1926
1999
  }
1927
- var METADATA_TYPE3 = "application/plune.metadata+json";
1928
- var TOKEN = /@P([A-Za-z0-9_-]+)/;
2000
+ var METADATA_TYPE = "application/plune.metadata+json";
2001
+ var TOKEN2 = /@P([A-Za-z0-9_-]+)/;
1929
2002
  function metadataOf(result) {
1930
- const found = result.attachments.find((a) => a.contentType === METADATA_TYPE3);
2003
+ const found = result.attachments.find((a) => a.contentType === METADATA_TYPE);
1931
2004
  if (found === void 0) return void 0;
1932
2005
  try {
1933
- const raw = found.body !== void 0 ? found.body.toString("utf8") : found.path !== void 0 ? (0, import_node_fs.readFileSync)(found.path, "utf8") : void 0;
2006
+ const raw = textOfAttachment(found);
1934
2007
  return raw === void 0 ? void 0 : JSON.parse(raw);
1935
2008
  } catch {
1936
2009
  return void 0;
1937
2010
  }
1938
2011
  }
2012
+ function textOfAttachment(found) {
2013
+ if (found.body !== void 0) return found.body.toString("utf8");
2014
+ return found.path !== void 0 ? (0, import_node_fs.readFileSync)(found.path, "utf8") : void 0;
2015
+ }
2016
+ function findingsOf(result) {
2017
+ const found = result.attachments.find((a) => a.contentType === FINDINGS_TYPE);
2018
+ if (found === void 0) return void 0;
2019
+ try {
2020
+ const raw = textOfAttachment(found);
2021
+ if (raw === void 0) return void 0;
2022
+ const steps = (result.steps ?? []).filter((step) => step.category === "test.step").map((step, i, all) => {
2023
+ const start = step.startTime.getTime();
2024
+ const end = step.duration >= 0 ? start + step.duration : all[i + 1]?.startTime.getTime() ?? Infinity;
2025
+ return { title: step.title, start, end };
2026
+ });
2027
+ return toWire(JSON.parse(raw), steps);
2028
+ } catch {
2029
+ return void 0;
2030
+ }
2031
+ }
1939
2032
  function statedIdOf(test, metadata, mapped) {
1940
2033
  const annotation = test.annotations.find((a) => a.type === "PluneId")?.description;
1941
2034
  if (annotation !== void 0 && annotation !== "") return annotation;
1942
- const token = TOKEN.exec(test.title)?.[1];
2035
+ const token = TOKEN2.exec(test.title)?.[1];
1943
2036
  if (token !== void 0) return token;
1944
2037
  if (metadata?.id !== void 0 && metadata.id !== "") return metadata.id;
1945
2038
  return mapped;
@@ -1970,7 +2063,7 @@ function textOf(error) {
1970
2063
  const lines = error.stack?.split("\n") ?? [];
1971
2064
  const at = lines.findIndex((line) => line.startsWith(" at "));
1972
2065
  const tokens = [(at === -1 ? lines : lines.slice(0, at)).join("\n") || message];
1973
- if (error.snippet) tokens.push("", (0, import_node_util.stripVTControlCharacters)(error.snippet));
2066
+ if (error.snippet) tokens.push("", (0, import_node_util2.stripVTControlCharacters)(error.snippet));
1974
2067
  if (at !== -1) tokens.push(lines.slice(at).join("\n"));
1975
2068
  if (error.cause) tokens.push(`[cause]: ${textOf(error.cause)}`);
1976
2069
  return tokens.join("\n");
@@ -2007,6 +2100,7 @@ function pendingFrom(test, result, ctx, ids = {}) {
2007
2100
  const errorContext = errorContextFields(attempt);
2008
2101
  const failure = NOT_FAILED.has(result.status) ? void 0 : failureOf(attempt);
2009
2102
  const files = filesOf(attempt);
2103
+ const findings = result.status === "passed" ? void 0 : findingsOf(result);
2010
2104
  const startedAt = result.startTime;
2011
2105
  return {
2012
2106
  resultKey: resultKey(test.id, result.retry),
@@ -2039,7 +2133,10 @@ function pendingFrom(test, result, ctx, ids = {}) {
2039
2133
  ...errorContext,
2040
2134
  ...failure !== void 0 ? { failure } : {},
2041
2135
  // Every attempt's, a passed one's too; the core uploads the screenshots and the text files once the result is stored.
2042
- ...files.length > 0 ? { files } : {}
2136
+ ...files.length > 0 ? { files } : {},
2137
+ // Only with an attempt that did not pass: the run page shows what the browser reported under a failure,
2138
+ // and nowhere else. Each attempt carries its own attachment, so a retry sends its own findings.
2139
+ ...findings !== void 0 ? { findings } : {}
2043
2140
  };
2044
2141
  }
2045
2142
  var PluneReporter = class {