@plune-ai/playwright 0.4.0 → 0.5.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/README.md CHANGED
@@ -130,8 +130,33 @@ under the name it was attached with: `testInfo.attach('checkout', { path })` arr
130
130
 
131
131
  Plune takes PNG, JPEG and WebP, up to 2 MB a file and 20 a result. An image outside those limits is
132
132
  skipped: the run summary counts it and says why, once per reason. Traces, videos and other files are
133
- not uploaded, and neither is an image attached as a `body` rather than a file — attach it with `path`.
134
- A screenshot that does not arrive never costs its result or your run's exit code.
133
+ not uploaded (a JSON or a text is: see below), and neither is an image attached as a `body` rather
134
+ than a file — attach it with `path`. A screenshot that does not arrive never costs its result or your
135
+ run's exit code.
136
+
137
+ ## JSON and text files
138
+
139
+ What a test attaches as JSON or plain text — the answer of an API, a log — is uploaded to its result
140
+ as well, beside the screenshots and for a test that passed as much as one that failed. Attach it with
141
+ a `body` or with a `path`; both are read:
142
+
143
+ ```ts
144
+ await testInfo.attach('api-response', { body: JSON.stringify(data), contentType: 'application/json' });
145
+ await testInfo.attach('server.log', { path: 'logs/server.log', contentType: 'text/plain' });
146
+ ```
147
+
148
+ Name the type: `application/json` or `text/plain` (a log is `text/plain`, whatever its file is
149
+ called). An attachment that names none is not uploaded, and its extension is not guessed at;
150
+ Markdown, HTML, CSV, traces and videos are not uploaded either. Plune takes UTF-8 text without NUL
151
+ bytes, up to 512 KiB a file and 10 a result — apart from the screenshots' 20. A text outside those
152
+ limits, an empty one, or one whose name starts with an underscore is skipped: the run summary counts
153
+ it and says why, once per reason. The reporter sends a file as it is; Plune cleans the credentials it
154
+ recognises out of a text before it keeps it. A file that does not arrive never costs its result or
155
+ your run's exit code.
156
+
157
+ A text attached as a `body` exists only in memory: it is uploaded once Plune has stored the result,
158
+ and is never written to `.plune/pending-results.jsonl`, so a result sent again with `plune run report`
159
+ goes without it.
135
160
 
136
161
  ## When Plune is unreachable
137
162
 
package/dist/index.cjs CHANGED
@@ -40,19 +40,20 @@ var import_node_util = require("util");
40
40
  var import_crypto = require("crypto");
41
41
  var import_fs = require("fs");
42
42
  var import_path = require("path");
43
+ var import_util = require("util");
43
44
  var import_fs2 = require("fs");
44
45
  var import_os = require("os");
45
46
  var import_path2 = require("path");
46
47
  var import_http = require("http");
47
48
  var import_https = require("https");
48
49
  var path = __toESM(require("path"), 1);
49
- var fs = __toESM(require("fs"), 1);
50
- var path2 = __toESM(require("path"), 1);
51
- var import_crypto2 = require("crypto");
52
50
  var import_fs3 = require("fs");
53
51
  var import_os2 = require("os");
54
52
  var import_path3 = require("path");
55
- var import_util = require("util");
53
+ var import_util2 = require("util");
54
+ var fs = __toESM(require("fs"), 1);
55
+ var path2 = __toESM(require("path"), 1);
56
+ var import_crypto2 = require("crypto");
56
57
  var DEFAULT_API_URL = "https://beta-api.plune.ai";
57
58
  function resolveApiUrl(explicit) {
58
59
  const raw = explicit ?? process.env["PLUNE_API_URL"] ?? DEFAULT_API_URL;
@@ -258,6 +259,131 @@ function ciCommit(reported, env = process.env) {
258
259
  ...branch !== void 0 ? { branch } : {}
259
260
  };
260
261
  }
262
+ function failureOf(attempt, home = (0, import_os2.homedir)()) {
263
+ const error = chosen(attempt);
264
+ const line = error === void 0 ? void 0 : firstLine(machineless(error.text, attempt.repoRoot, home));
265
+ const headline = line !== void 0 && jsonBytes(line) <= HEADLINE_LIMIT ? line : void 0;
266
+ const steps = chainOf(attempt.steps);
267
+ const location = error === void 0 ? void 0 : fromRoot(placeOf(error, attempt.testFile), attempt.repoRoot);
268
+ 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 !== "");
269
+ const ciUrl = webLink(attempt.buildHref);
270
+ const failure = {
271
+ ...headline !== void 0 ? { headline } : {},
272
+ ...steps.length > 0 ? { steps } : {},
273
+ ...location !== void 0 ? { location } : {},
274
+ ...artifacts.length > 0 ? { artifacts } : {},
275
+ ...ciUrl !== void 0 ? { ciUrl } : {}
276
+ };
277
+ return Object.keys(failure).length === 0 ? void 0 : failure;
278
+ }
279
+ function repoRootOf(dir, stopAt) {
280
+ for (let here = (0, import_path3.resolve)(dir); ; here = (0, import_path3.dirname)(here)) {
281
+ if ((0, import_fs3.existsSync)((0, import_path3.join)(here, ".git"))) return here;
282
+ if (here === stopAt || (0, import_path3.dirname)(here) === here) return void 0;
283
+ }
284
+ }
285
+ function errorContextOf(attempt, home = (0, import_os2.homedir)()) {
286
+ const text = attempt.errors.map((e) => e.text).filter((t) => t !== "").join("\n\n");
287
+ return cut(machineless(text, attempt.repoRoot, home));
288
+ }
289
+ var mediaTypeOf = (contentType) => contentType?.split(";")[0]?.trim().toLowerCase() || void 0;
290
+ var TEXT_TYPES = /* @__PURE__ */ new Set(["application/json", "text/plain"]);
291
+ var isTextType = (contentType) => TEXT_TYPES.has(mediaTypeOf(contentType) ?? "");
292
+ function filesOf(attempt) {
293
+ return attempt.attachments.filter((a) => a.path !== void 0 || a.body !== void 0 && isTextType(a.contentType));
294
+ }
295
+ function machineless(raw, repoRoot, home) {
296
+ let text = (0, import_util2.stripVTControlCharacters)(raw).replaceAll("\x1B", "");
297
+ const root = repoRoot === void 0 ? void 0 : pathIn(repoRoot);
298
+ if (root !== void 0) text = text.replace(new RegExp(`${PATH_START}${root.source}[\\\\/]+`, root.flags), "");
299
+ const own = pathIn(home);
300
+ if (own !== void 0) text = text.replace(new RegExp(`${PATH_START}${own.source}(?![\\w.-])`, own.flags), "~");
301
+ if (repoRoot === void 0) text = text.replace(ANY_HOME, "~");
302
+ return text;
303
+ }
304
+ var PATH_START = "(?<![\\w.~%/\\\\-])";
305
+ var TEXT_LIMIT = 524288;
306
+ var HEADLINE_LIMIT = 8 * 1024;
307
+ var jsonBytes = (text) => Buffer.byteLength(JSON.stringify(text)) - 2;
308
+ var ANY_HOME = /(?<=^|[\s'"`(=,[])(?:(?:file|webpack|webpack-internal):(?:\\*\/){2,3})?(?:\\*\/home\\*\/|\\*\/Users\\*\/|[A-Za-z]:[\\/]+Users[\\/]+)[^\\/\s'"`:*?<>|]+/g;
309
+ function pathIn(path3) {
310
+ const parts = path3.split(/[\\/]+/);
311
+ while (parts.length > 1 && parts.at(-1) === "") parts.pop();
312
+ if (!parts.some((part) => part !== "" && !/^[A-Za-z]:$/.test(part))) return void 0;
313
+ const joined = parts.map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\\\/]+");
314
+ const escaped = /^\/(?!\/)/.test(path3) ? joined.replace("[\\\\/]+", "\\\\*\\/") : joined;
315
+ const url = "(?:(?:file|webpack|webpack-internal):(?:\\\\*\\/){2,3})?";
316
+ return new RegExp(`${url}${escaped}`, /^[A-Za-z]:$/.test(parts[0]) ? "gi" : "g");
317
+ }
318
+ var fileNameOf = (name) => /^(?:file:\/\/|[\\/]|~[\\/]|[A-Za-z]:[\\/])/.test(name) ? name.split(/[\\/]/).pop() ?? "" : name;
319
+ function cut(text) {
320
+ if (jsonBytes(text) <= TEXT_LIMIT) return text;
321
+ const lines = text.split("\n");
322
+ const size = lines.map((line) => jsonBytes(line) + 2);
323
+ const budget = TEXT_LIMIT - jsonBytes(omitted(lines.length));
324
+ let used = 0;
325
+ let head = 0;
326
+ let tail = lines.length;
327
+ while (head < tail && used + size[head] <= budget / 2) used += size[head++];
328
+ while (tail > head && used + size[tail - 1] <= budget) used += size[--tail];
329
+ return [...lines.slice(0, head), omitted(tail - head), ...lines.slice(tail)].join("\n");
330
+ }
331
+ var omitted = (lines) => `\u2026[omitted ${lines} lines]\u2026`;
332
+ var METADATA_TYPE = "application/plune.metadata+json";
333
+ var REPO_RELATIVE = /^(?![A-Za-z][A-Za-z0-9+.-]*:)(?![\\/~])(?!(?:.*[\\/])?\.\.(?:[\\/]|$)).+$/;
334
+ var FRAME = /^\s+at (?:.*? \()?(.+?):(\d+):(\d+)\)?$/;
335
+ var FRAME_MAX = 8192;
336
+ var firstLine = (text) => (0, import_util2.stripVTControlCharacters)(text).split("\n").map((line) => line.trim()).find((line) => line !== "");
337
+ function chosen({ status, errors }) {
338
+ if (status === "timedOut") {
339
+ const timeout = errors.findIndex((e) => firstLine(e.text)?.startsWith("Test timeout of ") === true);
340
+ if (timeout !== -1 && timeout + 1 < errors.length) return errors[timeout + 1];
341
+ }
342
+ return errors[0];
343
+ }
344
+ function chainOf(steps) {
345
+ const chain = [];
346
+ for (let failed = steps.find((s) => s.failed); failed !== void 0; failed = failed.steps.find((s) => s.failed)) {
347
+ chain.push(failed.title);
348
+ }
349
+ return chain;
350
+ }
351
+ function placeOf(error, testFile) {
352
+ const own = normal(testFile);
353
+ let first;
354
+ for (const line of (0, import_util2.stripVTControlCharacters)(error.text).split("\n")) {
355
+ if (line.length > FRAME_MAX) continue;
356
+ const frame = FRAME.exec(line);
357
+ if (frame === null) continue;
358
+ const place = { file: fileOf(frame[1]), line: Number(frame[2]), column: Number(frame[3]) };
359
+ if (normal(place.file) === own) return place;
360
+ if (first === void 0 && !normal(place.file).includes("/node_modules/")) first = place;
361
+ }
362
+ return error.location ?? first;
363
+ }
364
+ function fileOf(raw) {
365
+ if (!raw.startsWith("file://")) return raw;
366
+ let path3 = raw.slice("file://".length);
367
+ try {
368
+ path3 = decodeURIComponent(path3);
369
+ } catch {
370
+ }
371
+ return /^\/[A-Za-z]:\//.test(path3) ? path3.slice(1) : path3;
372
+ }
373
+ var normal = (path3) => import_path3.posix.normalize(path3.replace(/\\/g, "/")).replace(/^([a-z]):/, (_, drive) => `${drive.toUpperCase()}:`);
374
+ function fromRoot(place, root) {
375
+ if (place === void 0 || root === void 0 || !Number.isInteger(place.line) || place.line < 1) return void 0;
376
+ const base = normal(root).replace(/\/+$/, "");
377
+ const file = normal(place.file);
378
+ if (!file.startsWith(`${base}/`)) return void 0;
379
+ const relative = file.slice(base.length + 1);
380
+ if (!REPO_RELATIVE.test(relative)) return void 0;
381
+ const column = place.column !== void 0 && Number.isInteger(place.column) && place.column >= 1 ? place.column : void 0;
382
+ return column === void 0 ? { file: relative, line: place.line } : { file: relative, line: place.line, column };
383
+ }
384
+ function webLink(href) {
385
+ return href !== void 0 && /^https?:\/\//i.test(href) && URL.canParse(href) ? href : void 0;
386
+ }
261
387
  var DEFAULT_FALLBACK_PATH = path2.join(".plune", "pending-results.jsonl");
262
388
  function appendBatch(file, batch) {
263
389
  fs.mkdirSync(path2.dirname(file), { recursive: true });
@@ -283,6 +409,9 @@ var COUNTED = ["accepted", "duplicate", "conflict", "rejected"];
283
409
  var SCREENSHOT_TYPES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/webp"]);
284
410
  var SCREENSHOT_BYTES = 2 * 1024 * 1024;
285
411
  var SCREENSHOTS_PER_RESULT = 20;
412
+ var TEXT_BYTES = 512 * 1024;
413
+ var TEXTS_PER_RESULT = 10;
414
+ var UTF8 = new import_util.TextDecoder("utf-8", { fatal: true });
286
415
  var TYPE_BY_EXTENSION = {
287
416
  ".png": "image/png",
288
417
  ".jpg": "image/jpeg",
@@ -292,8 +421,8 @@ var TYPE_BY_EXTENSION = {
292
421
  var UPLOADS_AT_ONCE = 4;
293
422
  var NAME_MAX = 200;
294
423
  function nameOf(file) {
295
- const own = file.name.split(/[\\/]/).pop()?.trim() || (0, import_path.basename)(file.path);
296
- const fileExt = (0, import_path.extname)(file.path);
424
+ const own = file.name.split(/[\\/]/).pop()?.trim() || (file.path === void 0 ? "" : (0, import_path.basename)(file.path));
425
+ const fileExt = file.path === void 0 ? "" : (0, import_path.extname)(file.path);
297
426
  const ownExt = (0, import_path.extname)(own);
298
427
  const typed = ownExt !== "" && (ownExt.toLowerCase() === fileExt.toLowerCase() || TYPE_BY_EXTENSION[ownExt.toLowerCase()] !== void 0);
299
428
  const ext = typed ? ownExt : fileExt;
@@ -309,8 +438,46 @@ var SKIPPED = {
309
438
  type: "Plune takes PNG, JPEG and WebP",
310
439
  limit: `a result holds at most ${SCREENSHOTS_PER_RESULT}`,
311
440
  missing: "the file cannot be read on this machine",
312
- size: "Plune takes a file of at most 2 MB"
441
+ size: "Plune takes a file of at most 2 MB",
442
+ textLimit: `a result holds at most ${TEXTS_PER_RESULT} text files`,
443
+ textSize: "Plune takes a text file of at most 512 KiB",
444
+ empty: "the file is empty",
445
+ binary: "the file holds a NUL byte, and Plune takes UTF-8 text without one",
446
+ encoding: "Plune takes UTF-8 text only"
447
+ };
448
+ var KINDS = {
449
+ screenshot: { label: "screenshot", bytes: SCREENSHOT_BYTES, room: SCREENSHOTS_PER_RESULT, limit: "limit", size: "size" },
450
+ text: { label: "text file", bytes: TEXT_BYTES, room: TEXTS_PER_RESULT, limit: "textLimit", size: "textSize" }
313
451
  };
452
+ function kindOf(type) {
453
+ if (type.startsWith("image/")) return "screenshot";
454
+ return TEXT_TYPES.has(type) ? "text" : void 0;
455
+ }
456
+ function textTypeOf(contentType, type) {
457
+ const charset = /;\s*charset\s*=\s*"?([^\s";]+)"?/i.exec(contentType)?.[1];
458
+ return charset?.toLowerCase() === "utf-8" ? `${type}; charset=utf-8` : type;
459
+ }
460
+ function textRefusal(bytes) {
461
+ if (bytes.length > TEXT_BYTES) return "textSize";
462
+ if (bytes.length === 0) return "empty";
463
+ if (bytes.includes(0)) return "binary";
464
+ try {
465
+ UTF8.decode(bytes);
466
+ } catch {
467
+ return "encoding";
468
+ }
469
+ return void 0;
470
+ }
471
+ function onDisk(result) {
472
+ if (!("files" in result) || result.files === void 0) return result;
473
+ const { files, ...rest } = result;
474
+ const kept = files.filter((f) => f.path !== void 0).map(({ body: _body, ...file }) => file);
475
+ return kept.length === 0 ? rest : { ...rest, files: kept };
476
+ }
477
+ function tally(counts, noun) {
478
+ if (counts.uploaded + counts.skipped + counts.failed === 0) return void 0;
479
+ return `${counts.uploaded} ${noun}(s) uploaded` + (counts.skipped > 0 ? `, ${counts.skipped} skipped` : "") + (counts.failed > 0 ? `, ${counts.failed} failed to upload` : "");
480
+ }
314
481
  function boundKey(key) {
315
482
  if (key.value.length <= KEY_MAX) return key;
316
483
  const digest = (0, import_crypto.createHash)("sha256").update(key.value).digest("hex").slice(0, 16);
@@ -386,7 +553,8 @@ async function startRun(passed, declared2) {
386
553
  created: 0,
387
554
  unoffered: 0,
388
555
  deferred: 0,
389
- screenshots: { uploaded: 0, skipped: 0, failed: 0 }
556
+ screenshots: { uploaded: 0, skipped: 0, failed: 0 },
557
+ textFiles: { uploaded: 0, skipped: 0, failed: 0 }
390
558
  };
391
559
  const resolved = /* @__PURE__ */ new Map();
392
560
  let buffer = [];
@@ -397,6 +565,7 @@ async function startRun(passed, declared2) {
397
565
  let done = false;
398
566
  const shortened = /* @__PURE__ */ new Set();
399
567
  const skipsSaid = /* @__PURE__ */ new Set();
568
+ const countsOf = (kind) => kind === "text" ? stats.textFiles : stats.screenshots;
400
569
  function bound(keys) {
401
570
  return keys.map((key) => {
402
571
  const fit = boundKey(key);
@@ -424,7 +593,7 @@ async function startRun(passed, declared2) {
424
593
  externalKey,
425
594
  session: sessionMarker,
426
595
  ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
427
- results
596
+ results: results.map(onDisk)
428
597
  });
429
598
  stats.deferred += results.length;
430
599
  }
@@ -532,57 +701,74 @@ async function startRun(passed, declared2) {
532
701
  stats.created += out.body.results.filter((r) => r?.outcome === "created").length;
533
702
  }
534
703
  }
535
- function skip(name, why) {
536
- stats.screenshots.skipped += 1;
537
- if (skipsSaid.has(why)) return;
538
- skipsSaid.add(why);
539
- log(`plune: screenshot "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
704
+ function skip(kind, name, why) {
705
+ countsOf(kind).skipped += 1;
706
+ if (skipsSaid.has(`${kind}/${why}`)) return;
707
+ skipsSaid.add(`${kind}/${why}`);
708
+ log(`plune: ${KINDS[kind].label} "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
540
709
  }
541
- async function uploadOne(shot) {
710
+ async function uploadOne(job) {
711
+ const { kind } = job;
712
+ const { label, bytes: ceiling, size } = KINDS[kind];
542
713
  let bytes;
543
- try {
544
- if ((await import_fs.promises.stat(shot.path)).size > SCREENSHOT_BYTES) return skip(shot.name, "size");
545
- bytes = await import_fs.promises.readFile(shot.path);
546
- } catch {
547
- return skip(shot.name, "missing");
714
+ if (job.body !== void 0) bytes = job.body;
715
+ else if (job.path === void 0) return skip(kind, job.name, "missing");
716
+ else {
717
+ try {
718
+ if ((await import_fs.promises.stat(job.path)).size > ceiling) return skip(kind, job.name, size);
719
+ bytes = await import_fs.promises.readFile(job.path);
720
+ } catch {
721
+ return skip(kind, job.name, "missing");
722
+ }
548
723
  }
724
+ const refusal = kind === "text" ? textRefusal(bytes) : void 0;
725
+ if (refusal !== void 0) return skip(kind, job.name, refusal);
549
726
  const out = await client.upload(
550
- `/v1/results/${encodeURIComponent(shot.id)}/files?name=${encodeURIComponent(shot.name)}`,
727
+ `/v1/results/${encodeURIComponent(job.id)}/files?name=${encodeURIComponent(job.name)}`,
551
728
  bytes,
552
- shot.type
729
+ job.type
553
730
  );
731
+ const counts = countsOf(kind);
554
732
  if (out.ok) {
555
- stats.screenshots.uploaded += 1;
733
+ counts.uploaded += 1;
556
734
  return;
557
735
  }
558
- stats.screenshots.failed += 1;
559
- if (stats.screenshots.failed === 1) {
560
- log(`plune: could not upload a screenshot (${out.detail || out.kind}) \u2014 its result is reported without it.`);
736
+ counts.failed += 1;
737
+ if (counts.failed === 1) {
738
+ log(`plune: could not upload a ${label} (${out.detail || out.kind}) \u2014 its result is reported without it.`);
561
739
  }
562
740
  }
563
741
  async function upload(items, filesByKey) {
564
742
  if (filesByKey.size === 0 || !Array.isArray(items)) return;
565
- const shots = [];
743
+ const jobs = [];
566
744
  for (const item of items) {
567
745
  if (item?.status !== "accepted" || typeof item.id !== "string" || typeof item.resultKey !== "string") continue;
568
- let room = SCREENSHOTS_PER_RESULT;
746
+ const room = { screenshot: KINDS.screenshot.room, text: KINDS.text.room };
569
747
  for (const file of filesByKey.get(item.resultKey) ?? []) {
570
- const type = file.contentType?.split(";")[0]?.trim().toLowerCase() || TYPE_BY_EXTENSION[(0, import_path.extname)(file.path).toLowerCase()];
571
- if (!type?.startsWith("image/")) continue;
748
+ const type = mediaTypeOf(file.contentType) ?? (file.path === void 0 ? void 0 : TYPE_BY_EXTENSION[(0, import_path.extname)(file.path).toLowerCase()]);
749
+ const kind = type === void 0 ? void 0 : kindOf(type);
750
+ if (type === void 0 || kind === void 0 || kind === "screenshot" && file.path === void 0) continue;
572
751
  const name = nameOf(file);
573
- if (file.name.startsWith("_")) skip(name, "hidden");
574
- else if (!SCREENSHOT_TYPES.has(type)) skip(name, "type");
575
- else if (room === 0) skip(name, "limit");
752
+ if (file.name.startsWith("_")) skip(kind, name, "hidden");
753
+ else if (kind === "screenshot" && !SCREENSHOT_TYPES.has(type)) skip(kind, name, "type");
754
+ else if (room[kind] === 0) skip(kind, name, KINDS[kind].limit);
576
755
  else {
577
- room -= 1;
578
- shots.push({ id: item.id, name, type, path: file.path });
756
+ room[kind] -= 1;
757
+ jobs.push({
758
+ id: item.id,
759
+ kind,
760
+ name,
761
+ type: kind === "text" ? textTypeOf(file.contentType ?? "", type) : type,
762
+ ...file.body !== void 0 ? { body: file.body } : {},
763
+ ...file.path !== void 0 ? { path: file.path } : {}
764
+ });
579
765
  }
580
766
  }
581
767
  }
582
768
  let next = 0;
583
769
  await Promise.all(
584
- Array.from({ length: Math.min(UPLOADS_AT_ONCE, shots.length) }, async () => {
585
- while (next < shots.length) await uploadOne(shots[next++]);
770
+ Array.from({ length: Math.min(UPLOADS_AT_ONCE, jobs.length) }, async () => {
771
+ while (next < jobs.length) await uploadOne(jobs[next++]);
586
772
  })
587
773
  );
588
774
  }
@@ -660,11 +846,8 @@ async function startRun(passed, declared2) {
660
846
  if (stats.unresolved > 0) parts.push(`${stats.unresolved} with no matching test case`);
661
847
  if (stats.offered > 0) parts.push(`${stats.offered} offered for review`);
662
848
  if (stats.created > 0) parts.push(`${stats.created} added as cases (trusted source)`);
663
- const shots = stats.screenshots;
664
- if (shots.uploaded + shots.skipped + shots.failed > 0) {
665
- parts.push(
666
- `${shots.uploaded} screenshot(s) uploaded` + (shots.skipped > 0 ? `, ${shots.skipped} skipped` : "") + (shots.failed > 0 ? `, ${shots.failed} failed to upload` : "")
667
- );
849
+ for (const said of [tally(stats.screenshots, "screenshot"), tally(stats.textFiles, "text file")]) {
850
+ if (said !== void 0) parts.push(said);
668
851
  }
669
852
  if (stats.deferred > 0) parts.push(`${stats.deferred} not delivered \u2014 written to ${fallbackPath}`);
670
853
  if (shortened.size > 0) parts.push(`${shortened.size} test name(s) shortened to fit a key`);
@@ -726,128 +909,6 @@ function resultKey(testId, retry) {
726
909
  const plain = `${testId}#${retry}`;
727
910
  return plain.length <= RESULT_KEY_MAX ? plain : `${sha256(testId).slice(0, HASH_CHARS)}#${retry}`;
728
911
  }
729
- function failureOf(attempt, home = (0, import_os2.homedir)()) {
730
- const error = chosen(attempt);
731
- const line = error === void 0 ? void 0 : firstLine(machineless(error.text, attempt.repoRoot, home));
732
- const headline = line !== void 0 && jsonBytes(line) <= HEADLINE_LIMIT ? line : void 0;
733
- const steps = chainOf(attempt.steps);
734
- const location = error === void 0 ? void 0 : fromRoot(placeOf(error, attempt.testFile), attempt.repoRoot);
735
- 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 !== "");
736
- const ciUrl = webLink(attempt.buildHref);
737
- const failure = {
738
- ...headline !== void 0 ? { headline } : {},
739
- ...steps.length > 0 ? { steps } : {},
740
- ...location !== void 0 ? { location } : {},
741
- ...artifacts.length > 0 ? { artifacts } : {},
742
- ...ciUrl !== void 0 ? { ciUrl } : {}
743
- };
744
- return Object.keys(failure).length === 0 ? void 0 : failure;
745
- }
746
- function repoRootOf(dir, stopAt) {
747
- for (let here = (0, import_path3.resolve)(dir); ; here = (0, import_path3.dirname)(here)) {
748
- if ((0, import_fs3.existsSync)((0, import_path3.join)(here, ".git"))) return here;
749
- if (here === stopAt || (0, import_path3.dirname)(here) === here) return void 0;
750
- }
751
- }
752
- function errorContextOf(attempt, home = (0, import_os2.homedir)()) {
753
- const text = attempt.errors.map((e) => e.text).filter((t) => t !== "").join("\n\n");
754
- return cut(machineless(text, attempt.repoRoot, home));
755
- }
756
- function filesOf(attempt) {
757
- return attempt.attachments.filter((a) => a.path !== void 0);
758
- }
759
- function machineless(raw, repoRoot, home) {
760
- let text = (0, import_util.stripVTControlCharacters)(raw).replaceAll("\x1B", "");
761
- const root = repoRoot === void 0 ? void 0 : pathIn(repoRoot);
762
- if (root !== void 0) text = text.replace(new RegExp(`${PATH_START}${root.source}[\\\\/]+`, root.flags), "");
763
- const own = pathIn(home);
764
- if (own !== void 0) text = text.replace(new RegExp(`${PATH_START}${own.source}(?![\\w.-])`, own.flags), "~");
765
- if (repoRoot === void 0) text = text.replace(ANY_HOME, "~");
766
- return text;
767
- }
768
- var PATH_START = "(?<![\\w.~%/\\\\-])";
769
- var TEXT_LIMIT = 524288;
770
- var HEADLINE_LIMIT = 8 * 1024;
771
- var jsonBytes = (text) => Buffer.byteLength(JSON.stringify(text)) - 2;
772
- var ANY_HOME = /(?<=^|[\s'"`(=,[])(?:(?:file|webpack|webpack-internal):(?:\\*\/){2,3})?(?:\\*\/home\\*\/|\\*\/Users\\*\/|[A-Za-z]:[\\/]+Users[\\/]+)[^\\/\s'"`:*?<>|]+/g;
773
- function pathIn(path3) {
774
- const parts = path3.split(/[\\/]+/);
775
- while (parts.length > 1 && parts.at(-1) === "") parts.pop();
776
- if (!parts.some((part) => part !== "" && !/^[A-Za-z]:$/.test(part))) return void 0;
777
- const joined = parts.map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\\\/]+");
778
- const escaped = /^\/(?!\/)/.test(path3) ? joined.replace("[\\\\/]+", "\\\\*\\/") : joined;
779
- const url = "(?:(?:file|webpack|webpack-internal):(?:\\\\*\\/){2,3})?";
780
- return new RegExp(`${url}${escaped}`, /^[A-Za-z]:$/.test(parts[0]) ? "gi" : "g");
781
- }
782
- var fileNameOf = (name) => /^(?:file:\/\/|[\\/]|~[\\/]|[A-Za-z]:[\\/])/.test(name) ? name.split(/[\\/]/).pop() ?? "" : name;
783
- function cut(text) {
784
- if (jsonBytes(text) <= TEXT_LIMIT) return text;
785
- const lines = text.split("\n");
786
- const size = lines.map((line) => jsonBytes(line) + 2);
787
- const budget = TEXT_LIMIT - jsonBytes(omitted(lines.length));
788
- let used = 0;
789
- let head = 0;
790
- let tail = lines.length;
791
- while (head < tail && used + size[head] <= budget / 2) used += size[head++];
792
- while (tail > head && used + size[tail - 1] <= budget) used += size[--tail];
793
- return [...lines.slice(0, head), omitted(tail - head), ...lines.slice(tail)].join("\n");
794
- }
795
- var omitted = (lines) => `\u2026[omitted ${lines} lines]\u2026`;
796
- var METADATA_TYPE = "application/plune.metadata+json";
797
- var REPO_RELATIVE = /^(?![A-Za-z][A-Za-z0-9+.-]*:)(?![\\/~])(?!(?:.*[\\/])?\.\.(?:[\\/]|$)).+$/;
798
- var FRAME = /^\s+at (?:.*? \()?(.+?):(\d+):(\d+)\)?$/;
799
- var FRAME_MAX = 8192;
800
- var firstLine = (text) => (0, import_util.stripVTControlCharacters)(text).split("\n").map((line) => line.trim()).find((line) => line !== "");
801
- function chosen({ status, errors }) {
802
- if (status === "timedOut") {
803
- const timeout = errors.findIndex((e) => firstLine(e.text)?.startsWith("Test timeout of ") === true);
804
- if (timeout !== -1 && timeout + 1 < errors.length) return errors[timeout + 1];
805
- }
806
- return errors[0];
807
- }
808
- function chainOf(steps) {
809
- const chain = [];
810
- for (let failed = steps.find((s) => s.failed); failed !== void 0; failed = failed.steps.find((s) => s.failed)) {
811
- chain.push(failed.title);
812
- }
813
- return chain;
814
- }
815
- function placeOf(error, testFile) {
816
- const own = normal(testFile);
817
- let first;
818
- for (const line of (0, import_util.stripVTControlCharacters)(error.text).split("\n")) {
819
- if (line.length > FRAME_MAX) continue;
820
- const frame = FRAME.exec(line);
821
- if (frame === null) continue;
822
- const place = { file: fileOf(frame[1]), line: Number(frame[2]), column: Number(frame[3]) };
823
- if (normal(place.file) === own) return place;
824
- if (first === void 0 && !normal(place.file).includes("/node_modules/")) first = place;
825
- }
826
- return error.location ?? first;
827
- }
828
- function fileOf(raw) {
829
- if (!raw.startsWith("file://")) return raw;
830
- let path3 = raw.slice("file://".length);
831
- try {
832
- path3 = decodeURIComponent(path3);
833
- } catch {
834
- }
835
- return /^\/[A-Za-z]:\//.test(path3) ? path3.slice(1) : path3;
836
- }
837
- var normal = (path3) => import_path3.posix.normalize(path3.replace(/\\/g, "/")).replace(/^([a-z]):/, (_, drive) => `${drive.toUpperCase()}:`);
838
- function fromRoot(place, root) {
839
- if (place === void 0 || root === void 0 || !Number.isInteger(place.line) || place.line < 1) return void 0;
840
- const base = normal(root).replace(/\/+$/, "");
841
- const file = normal(place.file);
842
- if (!file.startsWith(`${base}/`)) return void 0;
843
- const relative = file.slice(base.length + 1);
844
- if (!REPO_RELATIVE.test(relative)) return void 0;
845
- const column = place.column !== void 0 && Number.isInteger(place.column) && place.column >= 1 ? place.column : void 0;
846
- return column === void 0 ? { file: relative, line: place.line } : { file: relative, line: place.line, column };
847
- }
848
- function webLink(href) {
849
- return href !== void 0 && /^https?:\/\//i.test(href) && URL.canParse(href) ? href : void 0;
850
- }
851
912
 
852
913
  // src/index.ts
853
914
  var SOURCE = "playwright";
@@ -909,10 +970,12 @@ function attemptOf(test, result, ctx) {
909
970
  status: result.status,
910
971
  errors: result.errors.map((e) => ({ text: textOf(e), ...e.location !== void 0 ? { location: e.location } : {} })),
911
972
  steps: declared(result.steps ?? []),
912
- attachments: result.attachments.map(({ name, contentType, path: path3 }) => ({
973
+ attachments: result.attachments.map(({ name, contentType, path: path3, body }) => ({
913
974
  name,
914
975
  contentType,
915
- ...path3 !== void 0 ? { path: path3 } : {}
976
+ ...path3 !== void 0 ? { path: path3 } : {},
977
+ // What a test attached from memory has no file: the bytes are the reporter's only copy (plune#928).
978
+ ...body !== void 0 ? { body } : {}
916
979
  })),
917
980
  ...ctx.buildHref !== void 0 ? { buildHref: ctx.buildHref } : {},
918
981
  testFile: test.location.file,
@@ -956,7 +1019,7 @@ function pendingFrom(test, result, ctx) {
956
1019
  },
957
1020
  ...errorContext !== "" ? { errorContext } : {},
958
1021
  ...failure !== void 0 ? { failure } : {},
959
- // Every attempt's, a passed one's too; the core uploads the screenshots once the result is stored.
1022
+ // Every attempt's, a passed one's too; the core uploads the screenshots and the text files once the result is stored.
960
1023
  ...files.length > 0 ? { files } : {}
961
1024
  };
962
1025
  }
package/dist/index.js CHANGED
@@ -6,19 +6,20 @@ import { stripVTControlCharacters as stripVTControlCharacters2 } from "util";
6
6
  import { createHash, randomUUID } from "crypto";
7
7
  import { promises as disk } from "fs";
8
8
  import { basename as basename2, extname } from "path";
9
+ import { TextDecoder } from "util";
9
10
  import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
10
11
  import { homedir } from "os";
11
12
  import { dirname, join } from "path";
12
13
  import { request as httpRequest } from "http";
13
14
  import { request as httpsRequest } from "https";
14
15
  import * as path from "path";
15
- import * as fs from "fs";
16
- import * as path2 from "path";
17
- import { createHash as createHash2 } from "crypto";
18
16
  import { existsSync as existsSync2 } from "fs";
19
17
  import { homedir as homedir2 } from "os";
20
- import { dirname as dirname3, join as join3, posix, resolve } from "path";
18
+ import { dirname as dirname2, join as join2, posix, resolve } from "path";
21
19
  import { stripVTControlCharacters } from "util";
20
+ import * as fs from "fs";
21
+ import * as path2 from "path";
22
+ import { createHash as createHash2 } from "crypto";
22
23
  var DEFAULT_API_URL = "https://beta-api.plune.ai";
23
24
  function resolveApiUrl(explicit) {
24
25
  const raw = explicit ?? process.env["PLUNE_API_URL"] ?? DEFAULT_API_URL;
@@ -224,6 +225,131 @@ function ciCommit(reported, env = process.env) {
224
225
  ...branch !== void 0 ? { branch } : {}
225
226
  };
226
227
  }
228
+ function failureOf(attempt, home = homedir2()) {
229
+ const error = chosen(attempt);
230
+ const line = error === void 0 ? void 0 : firstLine(machineless(error.text, attempt.repoRoot, home));
231
+ const headline = line !== void 0 && jsonBytes(line) <= HEADLINE_LIMIT ? line : void 0;
232
+ const steps = chainOf(attempt.steps);
233
+ const location = error === void 0 ? void 0 : fromRoot(placeOf(error, attempt.testFile), attempt.repoRoot);
234
+ 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 !== "");
235
+ const ciUrl = webLink(attempt.buildHref);
236
+ const failure = {
237
+ ...headline !== void 0 ? { headline } : {},
238
+ ...steps.length > 0 ? { steps } : {},
239
+ ...location !== void 0 ? { location } : {},
240
+ ...artifacts.length > 0 ? { artifacts } : {},
241
+ ...ciUrl !== void 0 ? { ciUrl } : {}
242
+ };
243
+ return Object.keys(failure).length === 0 ? void 0 : failure;
244
+ }
245
+ function repoRootOf(dir, stopAt) {
246
+ for (let here = resolve(dir); ; here = dirname2(here)) {
247
+ if (existsSync2(join2(here, ".git"))) return here;
248
+ if (here === stopAt || dirname2(here) === here) return void 0;
249
+ }
250
+ }
251
+ function errorContextOf(attempt, home = homedir2()) {
252
+ const text = attempt.errors.map((e) => e.text).filter((t) => t !== "").join("\n\n");
253
+ return cut(machineless(text, attempt.repoRoot, home));
254
+ }
255
+ var mediaTypeOf = (contentType) => contentType?.split(";")[0]?.trim().toLowerCase() || void 0;
256
+ var TEXT_TYPES = /* @__PURE__ */ new Set(["application/json", "text/plain"]);
257
+ var isTextType = (contentType) => TEXT_TYPES.has(mediaTypeOf(contentType) ?? "");
258
+ function filesOf(attempt) {
259
+ return attempt.attachments.filter((a) => a.path !== void 0 || a.body !== void 0 && isTextType(a.contentType));
260
+ }
261
+ function machineless(raw, repoRoot, home) {
262
+ let text = stripVTControlCharacters(raw).replaceAll("\x1B", "");
263
+ const root = repoRoot === void 0 ? void 0 : pathIn(repoRoot);
264
+ if (root !== void 0) text = text.replace(new RegExp(`${PATH_START}${root.source}[\\\\/]+`, root.flags), "");
265
+ const own = pathIn(home);
266
+ if (own !== void 0) text = text.replace(new RegExp(`${PATH_START}${own.source}(?![\\w.-])`, own.flags), "~");
267
+ if (repoRoot === void 0) text = text.replace(ANY_HOME, "~");
268
+ return text;
269
+ }
270
+ var PATH_START = "(?<![\\w.~%/\\\\-])";
271
+ var TEXT_LIMIT = 524288;
272
+ var HEADLINE_LIMIT = 8 * 1024;
273
+ var jsonBytes = (text) => Buffer.byteLength(JSON.stringify(text)) - 2;
274
+ var ANY_HOME = /(?<=^|[\s'"`(=,[])(?:(?:file|webpack|webpack-internal):(?:\\*\/){2,3})?(?:\\*\/home\\*\/|\\*\/Users\\*\/|[A-Za-z]:[\\/]+Users[\\/]+)[^\\/\s'"`:*?<>|]+/g;
275
+ function pathIn(path3) {
276
+ const parts = path3.split(/[\\/]+/);
277
+ while (parts.length > 1 && parts.at(-1) === "") parts.pop();
278
+ if (!parts.some((part) => part !== "" && !/^[A-Za-z]:$/.test(part))) return void 0;
279
+ const joined = parts.map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\\\/]+");
280
+ const escaped = /^\/(?!\/)/.test(path3) ? joined.replace("[\\\\/]+", "\\\\*\\/") : joined;
281
+ const url = "(?:(?:file|webpack|webpack-internal):(?:\\\\*\\/){2,3})?";
282
+ return new RegExp(`${url}${escaped}`, /^[A-Za-z]:$/.test(parts[0]) ? "gi" : "g");
283
+ }
284
+ var fileNameOf = (name) => /^(?:file:\/\/|[\\/]|~[\\/]|[A-Za-z]:[\\/])/.test(name) ? name.split(/[\\/]/).pop() ?? "" : name;
285
+ function cut(text) {
286
+ if (jsonBytes(text) <= TEXT_LIMIT) return text;
287
+ const lines = text.split("\n");
288
+ const size = lines.map((line) => jsonBytes(line) + 2);
289
+ const budget = TEXT_LIMIT - jsonBytes(omitted(lines.length));
290
+ let used = 0;
291
+ let head = 0;
292
+ let tail = lines.length;
293
+ while (head < tail && used + size[head] <= budget / 2) used += size[head++];
294
+ while (tail > head && used + size[tail - 1] <= budget) used += size[--tail];
295
+ return [...lines.slice(0, head), omitted(tail - head), ...lines.slice(tail)].join("\n");
296
+ }
297
+ var omitted = (lines) => `\u2026[omitted ${lines} lines]\u2026`;
298
+ var METADATA_TYPE = "application/plune.metadata+json";
299
+ var REPO_RELATIVE = /^(?![A-Za-z][A-Za-z0-9+.-]*:)(?![\\/~])(?!(?:.*[\\/])?\.\.(?:[\\/]|$)).+$/;
300
+ var FRAME = /^\s+at (?:.*? \()?(.+?):(\d+):(\d+)\)?$/;
301
+ var FRAME_MAX = 8192;
302
+ var firstLine = (text) => stripVTControlCharacters(text).split("\n").map((line) => line.trim()).find((line) => line !== "");
303
+ function chosen({ status, errors }) {
304
+ if (status === "timedOut") {
305
+ const timeout = errors.findIndex((e) => firstLine(e.text)?.startsWith("Test timeout of ") === true);
306
+ if (timeout !== -1 && timeout + 1 < errors.length) return errors[timeout + 1];
307
+ }
308
+ return errors[0];
309
+ }
310
+ function chainOf(steps) {
311
+ const chain = [];
312
+ for (let failed = steps.find((s) => s.failed); failed !== void 0; failed = failed.steps.find((s) => s.failed)) {
313
+ chain.push(failed.title);
314
+ }
315
+ return chain;
316
+ }
317
+ function placeOf(error, testFile) {
318
+ const own = normal(testFile);
319
+ let first;
320
+ for (const line of stripVTControlCharacters(error.text).split("\n")) {
321
+ if (line.length > FRAME_MAX) continue;
322
+ const frame = FRAME.exec(line);
323
+ if (frame === null) continue;
324
+ const place = { file: fileOf(frame[1]), line: Number(frame[2]), column: Number(frame[3]) };
325
+ if (normal(place.file) === own) return place;
326
+ if (first === void 0 && !normal(place.file).includes("/node_modules/")) first = place;
327
+ }
328
+ return error.location ?? first;
329
+ }
330
+ function fileOf(raw) {
331
+ if (!raw.startsWith("file://")) return raw;
332
+ let path3 = raw.slice("file://".length);
333
+ try {
334
+ path3 = decodeURIComponent(path3);
335
+ } catch {
336
+ }
337
+ return /^\/[A-Za-z]:\//.test(path3) ? path3.slice(1) : path3;
338
+ }
339
+ var normal = (path3) => posix.normalize(path3.replace(/\\/g, "/")).replace(/^([a-z]):/, (_, drive) => `${drive.toUpperCase()}:`);
340
+ function fromRoot(place, root) {
341
+ if (place === void 0 || root === void 0 || !Number.isInteger(place.line) || place.line < 1) return void 0;
342
+ const base = normal(root).replace(/\/+$/, "");
343
+ const file = normal(place.file);
344
+ if (!file.startsWith(`${base}/`)) return void 0;
345
+ const relative = file.slice(base.length + 1);
346
+ if (!REPO_RELATIVE.test(relative)) return void 0;
347
+ const column = place.column !== void 0 && Number.isInteger(place.column) && place.column >= 1 ? place.column : void 0;
348
+ return column === void 0 ? { file: relative, line: place.line } : { file: relative, line: place.line, column };
349
+ }
350
+ function webLink(href) {
351
+ return href !== void 0 && /^https?:\/\//i.test(href) && URL.canParse(href) ? href : void 0;
352
+ }
227
353
  var DEFAULT_FALLBACK_PATH = path2.join(".plune", "pending-results.jsonl");
228
354
  function appendBatch(file, batch) {
229
355
  fs.mkdirSync(path2.dirname(file), { recursive: true });
@@ -249,6 +375,9 @@ var COUNTED = ["accepted", "duplicate", "conflict", "rejected"];
249
375
  var SCREENSHOT_TYPES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/webp"]);
250
376
  var SCREENSHOT_BYTES = 2 * 1024 * 1024;
251
377
  var SCREENSHOTS_PER_RESULT = 20;
378
+ var TEXT_BYTES = 512 * 1024;
379
+ var TEXTS_PER_RESULT = 10;
380
+ var UTF8 = new TextDecoder("utf-8", { fatal: true });
252
381
  var TYPE_BY_EXTENSION = {
253
382
  ".png": "image/png",
254
383
  ".jpg": "image/jpeg",
@@ -258,8 +387,8 @@ var TYPE_BY_EXTENSION = {
258
387
  var UPLOADS_AT_ONCE = 4;
259
388
  var NAME_MAX = 200;
260
389
  function nameOf(file) {
261
- const own = file.name.split(/[\\/]/).pop()?.trim() || basename2(file.path);
262
- const fileExt = extname(file.path);
390
+ const own = file.name.split(/[\\/]/).pop()?.trim() || (file.path === void 0 ? "" : basename2(file.path));
391
+ const fileExt = file.path === void 0 ? "" : extname(file.path);
263
392
  const ownExt = extname(own);
264
393
  const typed = ownExt !== "" && (ownExt.toLowerCase() === fileExt.toLowerCase() || TYPE_BY_EXTENSION[ownExt.toLowerCase()] !== void 0);
265
394
  const ext = typed ? ownExt : fileExt;
@@ -275,8 +404,46 @@ var SKIPPED = {
275
404
  type: "Plune takes PNG, JPEG and WebP",
276
405
  limit: `a result holds at most ${SCREENSHOTS_PER_RESULT}`,
277
406
  missing: "the file cannot be read on this machine",
278
- size: "Plune takes a file of at most 2 MB"
407
+ size: "Plune takes a file of at most 2 MB",
408
+ textLimit: `a result holds at most ${TEXTS_PER_RESULT} text files`,
409
+ textSize: "Plune takes a text file of at most 512 KiB",
410
+ empty: "the file is empty",
411
+ binary: "the file holds a NUL byte, and Plune takes UTF-8 text without one",
412
+ encoding: "Plune takes UTF-8 text only"
279
413
  };
414
+ var KINDS = {
415
+ screenshot: { label: "screenshot", bytes: SCREENSHOT_BYTES, room: SCREENSHOTS_PER_RESULT, limit: "limit", size: "size" },
416
+ text: { label: "text file", bytes: TEXT_BYTES, room: TEXTS_PER_RESULT, limit: "textLimit", size: "textSize" }
417
+ };
418
+ function kindOf(type) {
419
+ if (type.startsWith("image/")) return "screenshot";
420
+ return TEXT_TYPES.has(type) ? "text" : void 0;
421
+ }
422
+ function textTypeOf(contentType, type) {
423
+ const charset = /;\s*charset\s*=\s*"?([^\s";]+)"?/i.exec(contentType)?.[1];
424
+ return charset?.toLowerCase() === "utf-8" ? `${type}; charset=utf-8` : type;
425
+ }
426
+ function textRefusal(bytes) {
427
+ if (bytes.length > TEXT_BYTES) return "textSize";
428
+ if (bytes.length === 0) return "empty";
429
+ if (bytes.includes(0)) return "binary";
430
+ try {
431
+ UTF8.decode(bytes);
432
+ } catch {
433
+ return "encoding";
434
+ }
435
+ return void 0;
436
+ }
437
+ function onDisk(result) {
438
+ if (!("files" in result) || result.files === void 0) return result;
439
+ const { files, ...rest } = result;
440
+ const kept = files.filter((f) => f.path !== void 0).map(({ body: _body, ...file }) => file);
441
+ return kept.length === 0 ? rest : { ...rest, files: kept };
442
+ }
443
+ function tally(counts, noun) {
444
+ if (counts.uploaded + counts.skipped + counts.failed === 0) return void 0;
445
+ return `${counts.uploaded} ${noun}(s) uploaded` + (counts.skipped > 0 ? `, ${counts.skipped} skipped` : "") + (counts.failed > 0 ? `, ${counts.failed} failed to upload` : "");
446
+ }
280
447
  function boundKey(key) {
281
448
  if (key.value.length <= KEY_MAX) return key;
282
449
  const digest = createHash("sha256").update(key.value).digest("hex").slice(0, 16);
@@ -352,7 +519,8 @@ async function startRun(passed, declared2) {
352
519
  created: 0,
353
520
  unoffered: 0,
354
521
  deferred: 0,
355
- screenshots: { uploaded: 0, skipped: 0, failed: 0 }
522
+ screenshots: { uploaded: 0, skipped: 0, failed: 0 },
523
+ textFiles: { uploaded: 0, skipped: 0, failed: 0 }
356
524
  };
357
525
  const resolved = /* @__PURE__ */ new Map();
358
526
  let buffer = [];
@@ -363,6 +531,7 @@ async function startRun(passed, declared2) {
363
531
  let done = false;
364
532
  const shortened = /* @__PURE__ */ new Set();
365
533
  const skipsSaid = /* @__PURE__ */ new Set();
534
+ const countsOf = (kind) => kind === "text" ? stats.textFiles : stats.screenshots;
366
535
  function bound(keys) {
367
536
  return keys.map((key) => {
368
537
  const fit = boundKey(key);
@@ -390,7 +559,7 @@ async function startRun(passed, declared2) {
390
559
  externalKey,
391
560
  session: sessionMarker,
392
561
  ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
393
- results
562
+ results: results.map(onDisk)
394
563
  });
395
564
  stats.deferred += results.length;
396
565
  }
@@ -498,57 +667,74 @@ async function startRun(passed, declared2) {
498
667
  stats.created += out.body.results.filter((r) => r?.outcome === "created").length;
499
668
  }
500
669
  }
501
- function skip(name, why) {
502
- stats.screenshots.skipped += 1;
503
- if (skipsSaid.has(why)) return;
504
- skipsSaid.add(why);
505
- log(`plune: screenshot "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
670
+ function skip(kind, name, why) {
671
+ countsOf(kind).skipped += 1;
672
+ if (skipsSaid.has(`${kind}/${why}`)) return;
673
+ skipsSaid.add(`${kind}/${why}`);
674
+ log(`plune: ${KINDS[kind].label} "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
506
675
  }
507
- async function uploadOne(shot) {
676
+ async function uploadOne(job) {
677
+ const { kind } = job;
678
+ const { label, bytes: ceiling, size } = KINDS[kind];
508
679
  let bytes;
509
- try {
510
- if ((await disk.stat(shot.path)).size > SCREENSHOT_BYTES) return skip(shot.name, "size");
511
- bytes = await disk.readFile(shot.path);
512
- } catch {
513
- return skip(shot.name, "missing");
680
+ if (job.body !== void 0) bytes = job.body;
681
+ else if (job.path === void 0) return skip(kind, job.name, "missing");
682
+ else {
683
+ try {
684
+ if ((await disk.stat(job.path)).size > ceiling) return skip(kind, job.name, size);
685
+ bytes = await disk.readFile(job.path);
686
+ } catch {
687
+ return skip(kind, job.name, "missing");
688
+ }
514
689
  }
690
+ const refusal = kind === "text" ? textRefusal(bytes) : void 0;
691
+ if (refusal !== void 0) return skip(kind, job.name, refusal);
515
692
  const out = await client.upload(
516
- `/v1/results/${encodeURIComponent(shot.id)}/files?name=${encodeURIComponent(shot.name)}`,
693
+ `/v1/results/${encodeURIComponent(job.id)}/files?name=${encodeURIComponent(job.name)}`,
517
694
  bytes,
518
- shot.type
695
+ job.type
519
696
  );
697
+ const counts = countsOf(kind);
520
698
  if (out.ok) {
521
- stats.screenshots.uploaded += 1;
699
+ counts.uploaded += 1;
522
700
  return;
523
701
  }
524
- stats.screenshots.failed += 1;
525
- if (stats.screenshots.failed === 1) {
526
- log(`plune: could not upload a screenshot (${out.detail || out.kind}) \u2014 its result is reported without it.`);
702
+ counts.failed += 1;
703
+ if (counts.failed === 1) {
704
+ log(`plune: could not upload a ${label} (${out.detail || out.kind}) \u2014 its result is reported without it.`);
527
705
  }
528
706
  }
529
707
  async function upload(items, filesByKey) {
530
708
  if (filesByKey.size === 0 || !Array.isArray(items)) return;
531
- const shots = [];
709
+ const jobs = [];
532
710
  for (const item of items) {
533
711
  if (item?.status !== "accepted" || typeof item.id !== "string" || typeof item.resultKey !== "string") continue;
534
- let room = SCREENSHOTS_PER_RESULT;
712
+ const room = { screenshot: KINDS.screenshot.room, text: KINDS.text.room };
535
713
  for (const file of filesByKey.get(item.resultKey) ?? []) {
536
- const type = file.contentType?.split(";")[0]?.trim().toLowerCase() || TYPE_BY_EXTENSION[extname(file.path).toLowerCase()];
537
- if (!type?.startsWith("image/")) continue;
714
+ const type = mediaTypeOf(file.contentType) ?? (file.path === void 0 ? void 0 : TYPE_BY_EXTENSION[extname(file.path).toLowerCase()]);
715
+ const kind = type === void 0 ? void 0 : kindOf(type);
716
+ if (type === void 0 || kind === void 0 || kind === "screenshot" && file.path === void 0) continue;
538
717
  const name = nameOf(file);
539
- if (file.name.startsWith("_")) skip(name, "hidden");
540
- else if (!SCREENSHOT_TYPES.has(type)) skip(name, "type");
541
- else if (room === 0) skip(name, "limit");
718
+ if (file.name.startsWith("_")) skip(kind, name, "hidden");
719
+ else if (kind === "screenshot" && !SCREENSHOT_TYPES.has(type)) skip(kind, name, "type");
720
+ else if (room[kind] === 0) skip(kind, name, KINDS[kind].limit);
542
721
  else {
543
- room -= 1;
544
- shots.push({ id: item.id, name, type, path: file.path });
722
+ room[kind] -= 1;
723
+ jobs.push({
724
+ id: item.id,
725
+ kind,
726
+ name,
727
+ type: kind === "text" ? textTypeOf(file.contentType ?? "", type) : type,
728
+ ...file.body !== void 0 ? { body: file.body } : {},
729
+ ...file.path !== void 0 ? { path: file.path } : {}
730
+ });
545
731
  }
546
732
  }
547
733
  }
548
734
  let next = 0;
549
735
  await Promise.all(
550
- Array.from({ length: Math.min(UPLOADS_AT_ONCE, shots.length) }, async () => {
551
- while (next < shots.length) await uploadOne(shots[next++]);
736
+ Array.from({ length: Math.min(UPLOADS_AT_ONCE, jobs.length) }, async () => {
737
+ while (next < jobs.length) await uploadOne(jobs[next++]);
552
738
  })
553
739
  );
554
740
  }
@@ -626,11 +812,8 @@ async function startRun(passed, declared2) {
626
812
  if (stats.unresolved > 0) parts.push(`${stats.unresolved} with no matching test case`);
627
813
  if (stats.offered > 0) parts.push(`${stats.offered} offered for review`);
628
814
  if (stats.created > 0) parts.push(`${stats.created} added as cases (trusted source)`);
629
- const shots = stats.screenshots;
630
- if (shots.uploaded + shots.skipped + shots.failed > 0) {
631
- parts.push(
632
- `${shots.uploaded} screenshot(s) uploaded` + (shots.skipped > 0 ? `, ${shots.skipped} skipped` : "") + (shots.failed > 0 ? `, ${shots.failed} failed to upload` : "")
633
- );
815
+ for (const said of [tally(stats.screenshots, "screenshot"), tally(stats.textFiles, "text file")]) {
816
+ if (said !== void 0) parts.push(said);
634
817
  }
635
818
  if (stats.deferred > 0) parts.push(`${stats.deferred} not delivered \u2014 written to ${fallbackPath}`);
636
819
  if (shortened.size > 0) parts.push(`${shortened.size} test name(s) shortened to fit a key`);
@@ -692,128 +875,6 @@ function resultKey(testId, retry) {
692
875
  const plain = `${testId}#${retry}`;
693
876
  return plain.length <= RESULT_KEY_MAX ? plain : `${sha256(testId).slice(0, HASH_CHARS)}#${retry}`;
694
877
  }
695
- function failureOf(attempt, home = homedir2()) {
696
- const error = chosen(attempt);
697
- const line = error === void 0 ? void 0 : firstLine(machineless(error.text, attempt.repoRoot, home));
698
- const headline = line !== void 0 && jsonBytes(line) <= HEADLINE_LIMIT ? line : void 0;
699
- const steps = chainOf(attempt.steps);
700
- const location = error === void 0 ? void 0 : fromRoot(placeOf(error, attempt.testFile), attempt.repoRoot);
701
- 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 !== "");
702
- const ciUrl = webLink(attempt.buildHref);
703
- const failure = {
704
- ...headline !== void 0 ? { headline } : {},
705
- ...steps.length > 0 ? { steps } : {},
706
- ...location !== void 0 ? { location } : {},
707
- ...artifacts.length > 0 ? { artifacts } : {},
708
- ...ciUrl !== void 0 ? { ciUrl } : {}
709
- };
710
- return Object.keys(failure).length === 0 ? void 0 : failure;
711
- }
712
- function repoRootOf(dir, stopAt) {
713
- for (let here = resolve(dir); ; here = dirname3(here)) {
714
- if (existsSync2(join3(here, ".git"))) return here;
715
- if (here === stopAt || dirname3(here) === here) return void 0;
716
- }
717
- }
718
- function errorContextOf(attempt, home = homedir2()) {
719
- const text = attempt.errors.map((e) => e.text).filter((t) => t !== "").join("\n\n");
720
- return cut(machineless(text, attempt.repoRoot, home));
721
- }
722
- function filesOf(attempt) {
723
- return attempt.attachments.filter((a) => a.path !== void 0);
724
- }
725
- function machineless(raw, repoRoot, home) {
726
- let text = stripVTControlCharacters(raw).replaceAll("\x1B", "");
727
- const root = repoRoot === void 0 ? void 0 : pathIn(repoRoot);
728
- if (root !== void 0) text = text.replace(new RegExp(`${PATH_START}${root.source}[\\\\/]+`, root.flags), "");
729
- const own = pathIn(home);
730
- if (own !== void 0) text = text.replace(new RegExp(`${PATH_START}${own.source}(?![\\w.-])`, own.flags), "~");
731
- if (repoRoot === void 0) text = text.replace(ANY_HOME, "~");
732
- return text;
733
- }
734
- var PATH_START = "(?<![\\w.~%/\\\\-])";
735
- var TEXT_LIMIT = 524288;
736
- var HEADLINE_LIMIT = 8 * 1024;
737
- var jsonBytes = (text) => Buffer.byteLength(JSON.stringify(text)) - 2;
738
- var ANY_HOME = /(?<=^|[\s'"`(=,[])(?:(?:file|webpack|webpack-internal):(?:\\*\/){2,3})?(?:\\*\/home\\*\/|\\*\/Users\\*\/|[A-Za-z]:[\\/]+Users[\\/]+)[^\\/\s'"`:*?<>|]+/g;
739
- function pathIn(path3) {
740
- const parts = path3.split(/[\\/]+/);
741
- while (parts.length > 1 && parts.at(-1) === "") parts.pop();
742
- if (!parts.some((part) => part !== "" && !/^[A-Za-z]:$/.test(part))) return void 0;
743
- const joined = parts.map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\\\/]+");
744
- const escaped = /^\/(?!\/)/.test(path3) ? joined.replace("[\\\\/]+", "\\\\*\\/") : joined;
745
- const url = "(?:(?:file|webpack|webpack-internal):(?:\\\\*\\/){2,3})?";
746
- return new RegExp(`${url}${escaped}`, /^[A-Za-z]:$/.test(parts[0]) ? "gi" : "g");
747
- }
748
- var fileNameOf = (name) => /^(?:file:\/\/|[\\/]|~[\\/]|[A-Za-z]:[\\/])/.test(name) ? name.split(/[\\/]/).pop() ?? "" : name;
749
- function cut(text) {
750
- if (jsonBytes(text) <= TEXT_LIMIT) return text;
751
- const lines = text.split("\n");
752
- const size = lines.map((line) => jsonBytes(line) + 2);
753
- const budget = TEXT_LIMIT - jsonBytes(omitted(lines.length));
754
- let used = 0;
755
- let head = 0;
756
- let tail = lines.length;
757
- while (head < tail && used + size[head] <= budget / 2) used += size[head++];
758
- while (tail > head && used + size[tail - 1] <= budget) used += size[--tail];
759
- return [...lines.slice(0, head), omitted(tail - head), ...lines.slice(tail)].join("\n");
760
- }
761
- var omitted = (lines) => `\u2026[omitted ${lines} lines]\u2026`;
762
- var METADATA_TYPE = "application/plune.metadata+json";
763
- var REPO_RELATIVE = /^(?![A-Za-z][A-Za-z0-9+.-]*:)(?![\\/~])(?!(?:.*[\\/])?\.\.(?:[\\/]|$)).+$/;
764
- var FRAME = /^\s+at (?:.*? \()?(.+?):(\d+):(\d+)\)?$/;
765
- var FRAME_MAX = 8192;
766
- var firstLine = (text) => stripVTControlCharacters(text).split("\n").map((line) => line.trim()).find((line) => line !== "");
767
- function chosen({ status, errors }) {
768
- if (status === "timedOut") {
769
- const timeout = errors.findIndex((e) => firstLine(e.text)?.startsWith("Test timeout of ") === true);
770
- if (timeout !== -1 && timeout + 1 < errors.length) return errors[timeout + 1];
771
- }
772
- return errors[0];
773
- }
774
- function chainOf(steps) {
775
- const chain = [];
776
- for (let failed = steps.find((s) => s.failed); failed !== void 0; failed = failed.steps.find((s) => s.failed)) {
777
- chain.push(failed.title);
778
- }
779
- return chain;
780
- }
781
- function placeOf(error, testFile) {
782
- const own = normal(testFile);
783
- let first;
784
- for (const line of stripVTControlCharacters(error.text).split("\n")) {
785
- if (line.length > FRAME_MAX) continue;
786
- const frame = FRAME.exec(line);
787
- if (frame === null) continue;
788
- const place = { file: fileOf(frame[1]), line: Number(frame[2]), column: Number(frame[3]) };
789
- if (normal(place.file) === own) return place;
790
- if (first === void 0 && !normal(place.file).includes("/node_modules/")) first = place;
791
- }
792
- return error.location ?? first;
793
- }
794
- function fileOf(raw) {
795
- if (!raw.startsWith("file://")) return raw;
796
- let path3 = raw.slice("file://".length);
797
- try {
798
- path3 = decodeURIComponent(path3);
799
- } catch {
800
- }
801
- return /^\/[A-Za-z]:\//.test(path3) ? path3.slice(1) : path3;
802
- }
803
- var normal = (path3) => posix.normalize(path3.replace(/\\/g, "/")).replace(/^([a-z]):/, (_, drive) => `${drive.toUpperCase()}:`);
804
- function fromRoot(place, root) {
805
- if (place === void 0 || root === void 0 || !Number.isInteger(place.line) || place.line < 1) return void 0;
806
- const base = normal(root).replace(/\/+$/, "");
807
- const file = normal(place.file);
808
- if (!file.startsWith(`${base}/`)) return void 0;
809
- const relative = file.slice(base.length + 1);
810
- if (!REPO_RELATIVE.test(relative)) return void 0;
811
- const column = place.column !== void 0 && Number.isInteger(place.column) && place.column >= 1 ? place.column : void 0;
812
- return column === void 0 ? { file: relative, line: place.line } : { file: relative, line: place.line, column };
813
- }
814
- function webLink(href) {
815
- return href !== void 0 && /^https?:\/\//i.test(href) && URL.canParse(href) ? href : void 0;
816
- }
817
878
 
818
879
  // src/index.ts
819
880
  var SOURCE = "playwright";
@@ -875,10 +936,12 @@ function attemptOf(test, result, ctx) {
875
936
  status: result.status,
876
937
  errors: result.errors.map((e) => ({ text: textOf(e), ...e.location !== void 0 ? { location: e.location } : {} })),
877
938
  steps: declared(result.steps ?? []),
878
- attachments: result.attachments.map(({ name, contentType, path: path3 }) => ({
939
+ attachments: result.attachments.map(({ name, contentType, path: path3, body }) => ({
879
940
  name,
880
941
  contentType,
881
- ...path3 !== void 0 ? { path: path3 } : {}
942
+ ...path3 !== void 0 ? { path: path3 } : {},
943
+ // What a test attached from memory has no file: the bytes are the reporter's only copy (plune#928).
944
+ ...body !== void 0 ? { body } : {}
882
945
  })),
883
946
  ...ctx.buildHref !== void 0 ? { buildHref: ctx.buildHref } : {},
884
947
  testFile: test.location.file,
@@ -922,7 +985,7 @@ function pendingFrom(test, result, ctx) {
922
985
  },
923
986
  ...errorContext !== "" ? { errorContext } : {},
924
987
  ...failure !== void 0 ? { failure } : {},
925
- // Every attempt's, a passed one's too; the core uploads the screenshots once the result is stored.
988
+ // Every attempt's, a passed one's too; the core uploads the screenshots and the text files once the result is stored.
926
989
  ...files.length > 0 ? { files } : {}
927
990
  };
928
991
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plune-ai/playwright",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Report Playwright results to Plune — a reporter and, later, a test importer.",
5
5
  "keywords": [
6
6
  "playwright",
@@ -38,7 +38,7 @@
38
38
  "tsup": "^8.0.0",
39
39
  "typescript": "^5.4.0",
40
40
  "vitest": "^1.6.0",
41
- "@plune-ai/cli": "0.16.0"
41
+ "@plune-ai/cli": "0.17.0"
42
42
  },
43
43
  "repository": {
44
44
  "type": "git",