@plune-ai/playwright 0.7.1 → 0.7.3

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/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/index.ts
2
- import { readFileSync as readFileSync2 } from "fs";
2
+ import { readFileSync as readFileSync3 } from "fs";
3
3
  import { resolve as resolve2 } from "path";
4
4
  import { stripVTControlCharacters as stripVTControlCharacters2 } from "util";
5
5
 
@@ -24,6 +24,7 @@ import { createHash } from "crypto";
24
24
  import { createReadStream as createReadStream2 } from "fs";
25
25
  import * as fs from "fs";
26
26
  import * as path2 from "path";
27
+ import { readFileSync as readFileSync2 } from "fs";
27
28
  import { createHash as createHash3 } from "crypto";
28
29
  var DEFAULT_API_URL = "https://beta-api.plune.ai";
29
30
  function resolveApiUrl(explicit) {
@@ -225,6 +226,7 @@ function createClient(opts) {
225
226
  upload: (path3, bytes, contentType) => send("POST", path3, { body: bytes, type: contentType }, uploadRetries ?? DEFAULT_RETRIES),
226
227
  del: (path3) => send("DELETE", path3),
227
228
  get: (path3) => send("GET", path3),
229
+ patch: (path3, body) => send("PATCH", path3, { body: JSON.stringify(body), type: "application/json" }),
228
230
  async put(url, headers, source) {
229
231
  const putRetries = uploadRetries ?? 3;
230
232
  let last = { ok: false, status: null, code: "network" };
@@ -432,7 +434,7 @@ function cutErrorContext(attempt, home) {
432
434
  const text = attempt.errors.map((e) => e.text).filter((t) => t !== "").join("\n\n");
433
435
  return cut(machineless(text, attempt.repoRoot, home));
434
436
  }
435
- var printable = (text) => text.replace(/[\u0000-\u001f\u007f-\u009f]/g, "?");
437
+ var printable = (text) => text.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, "?");
436
438
  var mediaTypeOf = (contentType) => contentType?.split(";")[0]?.trim().toLowerCase() || void 0;
437
439
  var TEXT_TYPES = /* @__PURE__ */ new Set(["application/json", "text/plain"]);
438
440
  var isTextType = (contentType) => TEXT_TYPES.has(mediaTypeOf(contentType) ?? "");
@@ -564,10 +566,175 @@ function appendBatch(file, batch) {
564
566
  fs.appendFileSync(file, `${JSON.stringify(line)}
565
567
  `, "utf8");
566
568
  }
569
+ var SNAPSHOT_MAX_BYTES = 16384;
570
+ var CALL = /\b(?:test|it)(?:\.(?:skip|fixme|only|fail|slow))?\s*\(/g;
571
+ var BEFORE_REGEX = /* @__PURE__ */ new Set([..."(,=:[!&|?{};+-*%<>~^"]);
572
+ function skipString(src, i, quote) {
573
+ for (let j = i + 1; j < src.length; j += 1) {
574
+ const c = src[j];
575
+ if (c === "\\") j += 1;
576
+ else if (c === quote) return j + 1;
577
+ else if (c === "\n") return -1;
578
+ }
579
+ return -1;
580
+ }
581
+ function skipTemplate(src, i) {
582
+ for (let j = i + 1; j < src.length; j += 1) {
583
+ const c = src[j];
584
+ if (c === "\\") j += 1;
585
+ else if (c === "`") return j + 1;
586
+ else if (c === "$" && src[j + 1] === "{") {
587
+ const end = matching(src, j + 2, "}");
588
+ if (end < 0) return -1;
589
+ j = end;
590
+ }
591
+ }
592
+ return -1;
593
+ }
594
+ function skipRegex(src, i) {
595
+ let inClass = false;
596
+ for (let j = i + 1; j < src.length; j += 1) {
597
+ const c = src[j];
598
+ if (c === "\\") j += 1;
599
+ else if (c === "\n") return -1;
600
+ else if (c === "[") inClass = true;
601
+ else if (c === "]") inClass = false;
602
+ else if (c === "/" && !inClass) {
603
+ let k = j + 1;
604
+ while (k < src.length && /[a-z]/i.test(src[k])) k += 1;
605
+ return k;
606
+ }
607
+ }
608
+ return -1;
609
+ }
610
+ function matching(src, i, close) {
611
+ const stack = [close];
612
+ let prev = "(";
613
+ while (i < src.length) {
614
+ const c = src[i];
615
+ const next = src[i + 1];
616
+ let to = -2;
617
+ if (c === "/" && next === "/") to = src.indexOf("\n", i);
618
+ else if (c === "/" && next === "*")
619
+ to = src.indexOf("*/", i + 2) < 0 ? -1 : src.indexOf("*/", i + 2) + 2;
620
+ else if (c === "'" || c === '"') to = skipString(src, i, c);
621
+ else if (c === "`") to = skipTemplate(src, i);
622
+ else if (c === "/" && BEFORE_REGEX.has(prev)) to = skipRegex(src, i);
623
+ if (to === -1) return -1;
624
+ if (to !== -2) {
625
+ if (c !== "/" || next !== "/" && next !== "*") prev = "a";
626
+ i = to;
627
+ continue;
628
+ }
629
+ if (c === "(") stack.push(")");
630
+ else if (c === "[") stack.push("]");
631
+ else if (c === "{") stack.push("}");
632
+ else if (c === ")" || c === "]" || c === "}") {
633
+ if (stack.pop() !== c) return -1;
634
+ if (stack.length === 0) return i;
635
+ }
636
+ if (!/\s/.test(c)) prev = c;
637
+ i += 1;
638
+ }
639
+ return -1;
640
+ }
641
+ function callTextAt(source, line, column) {
642
+ const lines = source.split("\n");
643
+ if (line < 1 || line > lines.length) return void 0;
644
+ const lineStart = lines.slice(0, line - 1).reduce((n, l) => n + l.length + 1, 0);
645
+ const lineEnd = lineStart + lines[line - 1].length;
646
+ const heads = [];
647
+ CALL.lastIndex = lineStart;
648
+ for (let h = CALL.exec(source); h !== null && h.index < lineEnd; h = CALL.exec(source))
649
+ heads.push(h);
650
+ const at = column === void 0 ? -1 : lineStart + column - 1;
651
+ const head = heads.find((h) => h.index <= at && at < h.index + h[0].length) ?? (heads.length === 1 ? heads[0] : void 0);
652
+ if (head === void 0) return void 0;
653
+ const end = matching(source, head.index + head[0].length, ")");
654
+ if (end < 0) return void 0;
655
+ const text = source.slice(head.index, end + 1).replace(/\r\n/g, "\n");
656
+ return Buffer.byteLength(text, "utf8") <= SNAPSHOT_MAX_BYTES ? text : void 0;
657
+ }
658
+ var CREDENTIAL = "password|passphrase|passwd|pass|pwd|token|secret|api[-_]?key|private[-_]?key|credential|auth|session|cookie";
659
+ var LITERAL = String.raw`(?<q>['"\x60])(?:\\.|(?!\k<q>)[^\\\n])*\k<q>`;
660
+ var TYPING = "(?:fill|type|pressSequentially)";
661
+ var SHAPES = [
662
+ { kind: "github-token", re: /\b(?:ghp|gho|ghs|ghu)_[A-Za-z0-9]{36}\b|\bgithub_pat_\w{20,}/g },
663
+ { kind: "api-key", re: /\bsk-[\w-]{20,}/g },
664
+ { kind: "api-key", re: /\b[sr]k_(?:live|test)_[A-Za-z0-9]{10,}/g },
665
+ { kind: "npm-token", re: /\bnpm_[A-Za-z0-9]{20,}/g },
666
+ { kind: "google-key", re: /\bAIza[\w-]{30,}/g },
667
+ { kind: "plune-token", re: /\bplune_[A-Za-z0-9_]{16,}/g },
668
+ { kind: "aws-key", re: /\bAKIA[0-9A-Z]{16}\b/g },
669
+ { kind: "slack-token", re: /\bxox[abprs]-[A-Za-z0-9-]{10,}/g },
670
+ {
671
+ kind: "private-key",
672
+ re: /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g
673
+ },
674
+ { kind: "jwt", re: /\beyJ[\w-]{10,}\.[\w-]{10,}\.[\w-]{10,}/g }
675
+ ];
676
+ var PLACES = [
677
+ // `password = '…'`, `apiKey: "…"`, `'x-api-key': '…'`
678
+ new RegExp(
679
+ String.raw`(?<lead>\b(?<role>[\w$-]*(?:${CREDENTIAL})[\w$-]*)['"]?\s*[:=]\s*)${LITERAL}`,
680
+ "gi"
681
+ ),
682
+ // `setToken('…')`: the call is named for a credential
683
+ new RegExp(String.raw`(?<lead>\b(?<role>[\w$]*(?:${CREDENTIAL})[\w$]*)\s*\(\s*)${LITERAL}`, "gi"),
684
+ // `.fill('#password', '…')`, `.type('#pwd', '…')`: the field is named in the same call
685
+ new RegExp(
686
+ String.raw`(?<lead>\.${TYPING}\(\s*['"][^'"\n]*?(?<role>${CREDENTIAL})[^'"\n]*['"]\s*,\s*)${LITERAL}`,
687
+ "gi"
688
+ ),
689
+ // `getByLabel('Password').fill('…')`, `getByRole('textbox', { name: 'Password' }).type('…')`: … or
690
+ // anywhere in the call the typing is chained off
691
+ new RegExp(
692
+ String.raw`(?<lead>\([^()\n]*?(?<role>${CREDENTIAL})[^()\n]*\)\s*\.${TYPING}\(\s*)${LITERAL}`,
693
+ "gi"
694
+ ),
695
+ // `{ name: 'session', value: '…' }`: a cookie (or any name/value pair) named for a credential
696
+ new RegExp(
697
+ String.raw`(?<lead>\bname\s*:\s*['"][^'"\n]*?(?<role>${CREDENTIAL})[^'"\n]*['"]\s*,\s*value\s*:\s*)${LITERAL}`,
698
+ "gi"
699
+ )
700
+ ];
701
+ var HEADER_LINE = /((?:^|\\[nr]|\x60)[ \t>*<+-]*['"]?)((?:proxy-)?authorization|(?:set-)?cookie|[\w-]*session[\w-]*)(['"]?[ \t]*:[ \t]*)(?![\w$.]+(?:\([^()\n]*\))?[ \t]*[,;)}\]])[^\s'"\x60\\][^\r\n'"\x60\\]*/gim;
702
+ var QUERY_PARAM = /([?&][\w.-]*(?:token|key|secret|password|passwd|pass|pwd|auth|signature|sig|credential|session)[\w.-]*=)(?!‹)[^&#\s'"\x60]+/gi;
703
+ function maskCredentials(text) {
704
+ let out = text;
705
+ for (const { kind, re } of SHAPES) out = out.replace(re, `\u2039${kind}\u203A`);
706
+ for (const re of PLACES) {
707
+ out = out.replace(re, (...args) => {
708
+ const groups = args.at(-1);
709
+ return `${groups.lead}${groups.q}\u2039${groups.role.toLowerCase().replace(/^[^a-z]+/, "")}\u203A${groups.q}`;
710
+ });
711
+ }
712
+ return out.replace(HEADER_LINE, "$1$2$3\u2039header\u203A").replace(/\b(Bearer)([ \t]+)(?!‹)[\w.~+/=-]{8,}/g, "$1$2\u2039credential\u203A").replace(
713
+ /\b(Basic|Token)([ \t]+)(?!‹)(?=[\w.~+/=-]*[\d=+/]|[\w.~+/=-]*[a-z][\w.~+/=-]*[A-Z])[\w.~+/=-]{8,}/g,
714
+ "$1$2\u2039credential\u203A"
715
+ ).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@");
716
+ }
717
+ function snapshotAt(at, files) {
718
+ let source = files.get(at.file);
719
+ if (source === void 0) {
720
+ try {
721
+ source = readFileSync2(at.file, "utf8");
722
+ } catch {
723
+ source = null;
724
+ }
725
+ files.set(at.file, source);
726
+ }
727
+ if (source === null) return void 0;
728
+ const text = callTextAt(source, at.line, at.column);
729
+ if (text === void 0) return void 0;
730
+ const masked = maskCredentials(text);
731
+ return Buffer.byteLength(masked, "utf8") <= SNAPSHOT_MAX_BYTES ? masked : void 0;
732
+ }
567
733
  var RESOLVE_CHUNK = 500;
568
734
  var BATCH_MAX = 500;
569
735
  var DISCOVER_MAX = 500;
570
736
  var BATCH_DEFAULT = 500;
737
+ var SNAPSHOT_UPDATES_MAX = 100;
571
738
  var SEND_CONCURRENCY = 4;
572
739
  var EXPECTED_MAX = 1e4;
573
740
  var KEY_MAX = 1024;
@@ -646,7 +813,13 @@ function textRefusal(bytes) {
646
813
  }
647
814
  return void 0;
648
815
  }
649
- function onDisk(result) {
816
+ function withoutTargets(result) {
817
+ if (result.targets === void 0) return result;
818
+ const { targets: _targets, ...rest } = result;
819
+ return rest;
820
+ }
821
+ function onDisk(deferred) {
822
+ const result = withoutTargets(deferred);
650
823
  if (!("files" in result) || result.files === void 0) return result;
651
824
  const { files, ...rest } = result;
652
825
  const kept = files.filter((f) => f.path !== void 0).map(({ body: _body, ...file }) => file);
@@ -697,68 +870,14 @@ function chunk(items, size) {
697
870
  for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
698
871
  return out;
699
872
  }
700
- function warnIfDropped(sent, run, log) {
701
- const names = Object.keys(sent);
702
- if (names.length === 0) return;
703
- if (names.some((name) => run[name] != null)) return;
704
- log(
705
- `plune: this deployment stored none of ${names.join(", ")} \u2014 it is older than the fields. The run is otherwise reported in full.`
706
- );
707
- }
708
- async function startRun(passed, declared2) {
709
- const env = readEnv();
710
- if (env.shardError !== void 0) throw new Error(env.shardError);
711
- if (env.configurationError !== void 0 && passed.configuration === void 0) throw new Error(env.configurationError);
712
- const stated = Object.fromEntries(Object.entries(passed).filter(([, v]) => v !== void 0));
713
- const cfg = { ...env.config, ...stated };
714
- const configuration = cfg.configuration !== void 0 && Object.keys(cfg.configuration).length > 0 ? cfg.configuration : void 0;
715
- const log = cfg.log ?? ((line) => void process.stderr.write(`${line}
716
- `));
717
- const fallbackPath = cfg.fallbackPath ?? DEFAULT_FALLBACK_PATH;
718
- const externalKey = cfg.externalKey ?? null;
719
- const sessionMarker = randomUUID();
720
- const batchSize = Math.min(cfg.batchSize ?? BATCH_DEFAULT, BATCH_MAX);
721
- const offerDiscovered = cfg.offerDiscovered ?? false;
722
- const token = cfg.token ?? loadToken() ?? "";
723
- const uploadsAtOnce = Math.min(Math.max(Math.floor(cfg.uploadConcurrency ?? UPLOAD_CONCURRENCY.default), UPLOAD_CONCURRENCY.min), UPLOAD_CONCURRENCY.max);
724
- const uploadRetries = Math.min(Math.max(Math.floor(cfg.uploadRetries ?? UPLOAD_RETRIES.default), UPLOAD_RETRIES.min), UPLOAD_RETRIES.max);
873
+ function fileSender(options) {
874
+ const { client, log, stats, uploadsAtOnce, uploadRetries } = options;
875
+ const without = options.without ?? "its result is reported without it";
725
876
  let retried = 0;
726
877
  let uploadMs = 0;
727
878
  let requests = 0;
728
879
  let existed = 0;
729
880
  let batchMissing = false;
730
- const client = createClient({
731
- apiUrl: resolveApiUrl(cfg.apiUrl),
732
- token,
733
- uploadRetries,
734
- onRetry: () => void (retried += 1),
735
- ...cfg.fetchImpl !== void 0 ? { fetchImpl: cfg.fetchImpl } : {}
736
- });
737
- const stats = {
738
- accepted: 0,
739
- duplicate: 0,
740
- conflict: 0,
741
- rejected: 0,
742
- unresolved: 0,
743
- offered: 0,
744
- created: 0,
745
- unoffered: 0,
746
- deferred: 0,
747
- screenshots: { uploaded: 0, skipped: 0, failed: 0 },
748
- textFiles: { uploaded: 0, skipped: 0, failed: 0 },
749
- otherFiles: { uploaded: 0, skipped: 0, failed: 0 }
750
- };
751
- const resolved = /* @__PURE__ */ new Map();
752
- let buffer = [];
753
- const discoveries = /* @__PURE__ */ new Map();
754
- const held = /* @__PURE__ */ new Map();
755
- let createdWithResult = 0;
756
- let createdUndelivered = 0;
757
- let runId = null;
758
- let joined = false;
759
- let offline = token === "";
760
- let done = false;
761
- const shortened = /* @__PURE__ */ new Set();
762
881
  const skipsSaid = /* @__PURE__ */ new Set();
763
882
  const countsOf = (kind) => kind === "text" ? stats.textFiles : kind === "file" ? stats.otherFiles : stats.screenshots;
764
883
  let bucketSeen = false;
@@ -767,168 +886,6 @@ async function startRun(passed, declared2) {
767
886
  const failedSaid = /* @__PURE__ */ new Set();
768
887
  const codesSaid = /* @__PURE__ */ new Set();
769
888
  const rooms = /* @__PURE__ */ new Map();
770
- function bound(keys) {
771
- return keys.map((key) => {
772
- const fit = boundKey(key);
773
- if (fit !== key && !shortened.has(key.value)) {
774
- shortened.add(key.value);
775
- if (shortened.size === 1) {
776
- log(
777
- `plune: a test name longer than ${KEY_MAX} characters was shortened to fit its key \u2014 ${JSON.stringify(printable(key.value.slice(0, 80)))}\u2026 Give the test a shorter name; until then this is its identity.`
778
- );
779
- }
780
- }
781
- return fit;
782
- });
783
- }
784
- const expected = declared2?.map(bound);
785
- if (offline) {
786
- log('plune: no API token \u2014 run "plune login" first. Results will be written to the fallback file.');
787
- }
788
- for (const warning of env.warnings) log(`plune: ${warning}`);
789
- if (env.ignored.length > 0) {
790
- log(`plune: ignoring ${env.ignored.join(", ")} \u2014 a run has nowhere to store them yet.`);
791
- }
792
- function defer(results) {
793
- appendBatch(fallbackPath, {
794
- runId,
795
- externalKey,
796
- session: sessionMarker,
797
- ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
798
- ...configuration !== void 0 ? { configuration } : {},
799
- results: results.map(onDisk)
800
- });
801
- stats.deferred += results.length;
802
- }
803
- async function resolveKeys(values) {
804
- const unknown = values.filter((k) => !resolved.has(keyId(k)));
805
- if (unknown.length === 0 || offline) return;
806
- for (const part of chunk(unknown, RESOLVE_CHUNK)) {
807
- const out = await client.post(
808
- "/v1/test-cases/resolve",
809
- { keys: part }
810
- );
811
- if (!out.ok || !Array.isArray(out.body?.results)) {
812
- log(`plune: could not look up test cases (${out.ok ? "the answer had no results" : out.detail || out.kind}).`);
813
- return;
814
- }
815
- for (const row of out.body.results) {
816
- if (typeof row?.key?.value === "string") resolved.set(keyId(row.key), row.testCaseId);
817
- }
818
- }
819
- }
820
- if (!offline) {
821
- if (expected !== void 0) await resolveKeys(expected.flat());
822
- const stated2 = expected?.slice(0, EXPECTED_MAX) ?? [];
823
- const configuration2 = stated2.length === 0 ? void 0 : {
824
- expected: stated2.flatMap((keys) => {
825
- const hit = keys.map((k) => resolved.get(keyId(k))).find((v) => typeof v === "string");
826
- if (typeof hit === "string") return [{ testCaseId: hit }];
827
- return keys[0] === void 0 ? [] : [{ externalKey: keys[0] }];
828
- }),
829
- // The claim travels with the list it is about (D20). A runner that could not enumerate
830
- // its tests has no list, and a claim without one is nothing the platform can check —
831
- // so it is not sent, rather than sent and silently meaningless.
832
- ...cfg.full === true ? { full: true } : {}
833
- };
834
- if (expected !== void 0 && expected.length > EXPECTED_MAX) {
835
- log(`plune: ${expected.length} tests is more than the run configuration holds \u2014 reporting the first ${EXPECTED_MAX}.`);
836
- }
837
- const described = {
838
- ...cfg.title !== void 0 ? { title: cfg.title } : {},
839
- ...cfg.environment !== void 0 ? { environment: cfg.environment } : {},
840
- ...cfg.labels !== void 0 ? { labels: cfg.labels } : {}
841
- };
842
- const request = {
843
- schemaVersion: 2,
844
- kind: cfg.kind ?? "automated",
845
- ...externalKey !== null ? { externalKey } : {},
846
- ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
847
- ...configuration2 !== void 0 ? { configuration: configuration2 } : {},
848
- // Named even when nobody named it — the list has to read without opening a row. Only what
849
- // the caller DESCRIBED goes to `warnIfDropped` below: a title this side invented is not one
850
- // a person will miss, and a deployment older than the field must not be nagged on every run.
851
- title: defaultRunTitle(),
852
- ...described
853
- };
854
- let start = await client.post("/v1/runs", request);
855
- if (!start.ok && start.status === 413 && configuration2 !== void 0) {
856
- log(
857
- `plune: the platform refused the run's list of expected tests as too large (${start.detail || start.kind}) \u2014 starting without it: the results still land, but this run counts no tests that did not run, and claims no full run.`
858
- );
859
- start = await client.post("/v1/runs", { ...request, configuration: void 0 });
860
- }
861
- if (start.ok && typeof start.body?.run?.id === "string") {
862
- runId = start.body.run.id;
863
- joined = start.status === 200;
864
- warnIfDropped(described, start.body.run, log);
865
- } else {
866
- const why = start.ok ? "the answer had no run" : start.detail || start.kind;
867
- log(`plune: could not start the run (${why}). Results will be written to ${fallbackPath}.`);
868
- }
869
- }
870
- function matchFor(result) {
871
- if (result.testCaseId !== void 0) return { kind: "found", testCaseId: result.testCaseId };
872
- let unanswered = false;
873
- for (const key of result.keys) {
874
- const hit = resolved.get(keyId(key));
875
- if (typeof hit === "string") return { kind: "found", testCaseId: hit };
876
- if (hit === void 0) unanswered = true;
877
- }
878
- return unanswered ? { kind: "unanswered" } : { kind: "unmatched" };
879
- }
880
- function remember(result) {
881
- if (!offerDiscovered) return;
882
- if (result.title === void 0 || result.specRef === void 0) return;
883
- if (result.keys.length === 0) return;
884
- const title = boundTitle(result.title);
885
- if (title !== result.title) shortened.add(result.title);
886
- discoveries.set(keyId(result.keys[0]), {
887
- keys: result.keys,
888
- title,
889
- source: result.source,
890
- specRef: result.specRef,
891
- rawStatus: result.rawStatus
892
- });
893
- for (const key of result.keys) held.set(keyId(key), result);
894
- }
895
- async function offer() {
896
- if (discoveries.size === 0 || offline || runId === null) return;
897
- const batches = chunk([...discoveries.values()], DISCOVER_MAX);
898
- for (const [index, batch] of batches.entries()) {
899
- const out = await client.post("/v1/review-items/discovered", {
900
- discovered: batch,
901
- runId
902
- });
903
- if (!out.ok || !Array.isArray(out.body?.results)) {
904
- stats.unoffered = batches.slice(index).reduce((n, rest) => n + rest.length, 0);
905
- stats.unofferedWhy = whyUnoffered(out);
906
- log(
907
- `plune: could not offer ${stats.unoffered} unknown test(s) for review (${out.ok ? "the answer had no results" : out.detail || out.kind}).`
908
- );
909
- return;
910
- }
911
- stats.offered += out.body.results.filter((r) => r?.outcome === "queued").length;
912
- const made = out.body.results.filter((r) => r?.outcome === "created");
913
- stats.created += made.length;
914
- const submissions = [];
915
- const filesByKey = /* @__PURE__ */ new Map();
916
- for (const r of made) {
917
- const pending = typeof r.id === "string" && r.id !== "" && typeof r.key?.value === "string" ? held.get(keyId(r.key)) : void 0;
918
- if (pending === void 0) continue;
919
- for (const key of pending.keys) held.delete(keyId(key));
920
- const { keys: _keys, files, ...rest } = pending;
921
- submissions.push({ ...rest, testCaseId: r.id });
922
- if (files !== void 0) filesByKey.set(pending.resultKey, files);
923
- }
924
- if (submissions.length > 0) {
925
- const before = stats.deferred;
926
- await send(submissions, filesByKey);
927
- createdWithResult += submissions.length;
928
- createdUndelivered += stats.deferred - before;
929
- }
930
- }
931
- }
932
889
  function skip(kind, name, why) {
933
890
  countsOf(kind).skipped += 1;
934
891
  if (why === "noStorage") noStorage += 1;
@@ -938,24 +895,25 @@ async function startRun(passed, declared2) {
938
895
  if (why === "noStorage") log(`plune: "${name}" not stored \u2014 ${SKIPPED[why]}.`);
939
896
  else log(`plune: ${KINDS[kind].label} "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
940
897
  }
898
+ const filesOf2 = (job) => `/v1/${job.owner ?? "results"}/${encodeURIComponent(job.id)}/files`;
941
899
  function ask(job, size) {
942
900
  requests += 1;
943
- return client.post(`/v1/results/${encodeURIComponent(job.id)}/files/uploads`, {
944
- files: [{ name: job.name, contentType: job.type, size }]
901
+ return client.post(`${filesOf2(job)}/uploads`, {
902
+ files: [{ name: job.name, contentType: job.type, size, ...job.key !== void 0 ? { key: job.key } : {} }]
945
903
  }, uploadRetries);
946
904
  }
947
905
  function failed(job, why) {
948
906
  countsOf(job.kind).failed += 1;
949
907
  if (!failedSaid.has(job.kind)) {
950
908
  failedSaid.add(job.kind);
951
- log(`plune: could not upload a ${KINDS[job.kind].label} (${why}) \u2014 its result is reported without it.`);
909
+ log(`plune: could not upload a ${KINDS[job.kind].label} (${why}) \u2014 ${without}.`);
952
910
  }
953
911
  }
954
912
  function failedToBucket(job, code) {
955
913
  countsOf(job.kind).failed += 1;
956
914
  if (codesSaid.has(code)) return;
957
915
  codesSaid.add(code);
958
- log(`plune: "${job.name}" not uploaded to your bucket (${code}) \u2014 its result is reported without it.`);
916
+ log(`plune: "${job.name}" not uploaded to your bucket (${code}) \u2014 ${without}.`);
959
917
  }
960
918
  function refusedHere(job, size) {
961
919
  if (job.kind === "screenshot") {
@@ -983,7 +941,7 @@ async function startRun(passed, declared2) {
983
941
  if (refusal !== void 0) return skip(kind, job.name, refusal);
984
942
  requests += 1;
985
943
  const out = await client.upload(
986
- `/v1/results/${encodeURIComponent(job.id)}/files?name=${encodeURIComponent(job.name)}`,
944
+ `${filesOf2(job)}?name=${encodeURIComponent(job.name)}`,
987
945
  bytes,
988
946
  job.type
989
947
  );
@@ -1005,8 +963,8 @@ async function startRun(passed, declared2) {
1005
963
  link = fresh;
1006
964
  }
1007
965
  requests += 1;
1008
- const done2 = await client.post(`/v1/files/${encodeURIComponent(link.id)}/complete`, {}, uploadRetries);
1009
- if (!done2.ok) return failedToBucket(job, codeOf(done2));
966
+ const done = await client.post(`/v1/files/${encodeURIComponent(link.id)}/complete`, {}, uploadRetries);
967
+ if (!done.ok) return failedToBucket(job, codeOf(done));
1010
968
  countsOf(job.kind).uploaded += 1;
1011
969
  }
1012
970
  let free = uploadsAtOnce;
@@ -1333,6 +1291,296 @@ async function startRun(passed, declared2) {
1333
1291
  else await uploadBatched(jobs);
1334
1292
  uploadMs += Date.now() - started;
1335
1293
  }
1294
+ return {
1295
+ upload,
1296
+ uploadEach,
1297
+ onRetry: () => void (retried += 1),
1298
+ get bucketSeen() {
1299
+ return bucketSeen;
1300
+ },
1301
+ get noStorage() {
1302
+ return noStorage;
1303
+ },
1304
+ get existed() {
1305
+ return existed;
1306
+ },
1307
+ get retried() {
1308
+ return retried;
1309
+ },
1310
+ get uploadMs() {
1311
+ return uploadMs;
1312
+ },
1313
+ get requests() {
1314
+ return requests;
1315
+ }
1316
+ };
1317
+ }
1318
+ function warnIfDropped(sent, run, log) {
1319
+ const names = Object.keys(sent);
1320
+ if (names.length === 0) return;
1321
+ if (names.some((name) => run[name] != null)) return;
1322
+ log(
1323
+ `plune: this deployment stored none of ${names.join(", ")} \u2014 it is older than the fields. The run is otherwise reported in full.`
1324
+ );
1325
+ }
1326
+ async function startRun(passed, declared2) {
1327
+ const env = readEnv();
1328
+ if (env.shardError !== void 0) throw new Error(env.shardError);
1329
+ if (env.configurationError !== void 0 && passed.configuration === void 0) throw new Error(env.configurationError);
1330
+ const stated = Object.fromEntries(Object.entries(passed).filter(([, v]) => v !== void 0));
1331
+ const cfg = { ...env.config, ...stated };
1332
+ const configuration = cfg.configuration !== void 0 && Object.keys(cfg.configuration).length > 0 ? cfg.configuration : void 0;
1333
+ const log = cfg.log ?? ((line) => void process.stderr.write(`${line}
1334
+ `));
1335
+ const fallbackPath = cfg.fallbackPath ?? DEFAULT_FALLBACK_PATH;
1336
+ const externalKey = cfg.externalKey ?? null;
1337
+ const sessionMarker = randomUUID();
1338
+ const batchSize = Math.min(cfg.batchSize ?? BATCH_DEFAULT, BATCH_MAX);
1339
+ const offerDiscovered = cfg.offerDiscovered ?? false;
1340
+ const token = cfg.token ?? loadToken() ?? "";
1341
+ const uploadsAtOnce = Math.min(Math.max(Math.floor(cfg.uploadConcurrency ?? UPLOAD_CONCURRENCY.default), UPLOAD_CONCURRENCY.min), UPLOAD_CONCURRENCY.max);
1342
+ const uploadRetries = Math.min(Math.max(Math.floor(cfg.uploadRetries ?? UPLOAD_RETRIES.default), UPLOAD_RETRIES.min), UPLOAD_RETRIES.max);
1343
+ const client = createClient({
1344
+ apiUrl: resolveApiUrl(cfg.apiUrl),
1345
+ token,
1346
+ uploadRetries,
1347
+ onRetry: () => files.onRetry(),
1348
+ ...cfg.fetchImpl !== void 0 ? { fetchImpl: cfg.fetchImpl } : {}
1349
+ });
1350
+ const stats = {
1351
+ accepted: 0,
1352
+ duplicate: 0,
1353
+ conflict: 0,
1354
+ rejected: 0,
1355
+ unresolved: 0,
1356
+ offered: 0,
1357
+ created: 0,
1358
+ unoffered: 0,
1359
+ deferred: 0,
1360
+ screenshots: { uploaded: 0, skipped: 0, failed: 0 },
1361
+ textFiles: { uploaded: 0, skipped: 0, failed: 0 },
1362
+ otherFiles: { uploaded: 0, skipped: 0, failed: 0 }
1363
+ };
1364
+ const files = fileSender({ client, log, stats, uploadsAtOnce, uploadRetries });
1365
+ const resolved = /* @__PURE__ */ new Map();
1366
+ let buffer = [];
1367
+ const discoveries = /* @__PURE__ */ new Map();
1368
+ const held = /* @__PURE__ */ new Map();
1369
+ let createdWithResult = 0;
1370
+ let createdUndelivered = 0;
1371
+ let runId = null;
1372
+ let joined = false;
1373
+ let offline = token === "";
1374
+ let targetsRefused = false;
1375
+ let done = false;
1376
+ const shortened = /* @__PURE__ */ new Set();
1377
+ const specFiles = /* @__PURE__ */ new Map();
1378
+ const snapshotByKey = /* @__PURE__ */ new Map();
1379
+ const snapshots = /* @__PURE__ */ new Map();
1380
+ function bound(keys) {
1381
+ return keys.map((key) => {
1382
+ const fit = boundKey(key);
1383
+ if (fit !== key && !shortened.has(key.value)) {
1384
+ shortened.add(key.value);
1385
+ if (shortened.size === 1) {
1386
+ log(
1387
+ `plune: a test name longer than ${KEY_MAX} characters was shortened to fit its key \u2014 ${JSON.stringify(printable(key.value.slice(0, 80)))}\u2026 Give the test a shorter name; until then this is its identity.`
1388
+ );
1389
+ }
1390
+ }
1391
+ return fit;
1392
+ });
1393
+ }
1394
+ const expected = declared2?.map(bound);
1395
+ if (offline) {
1396
+ log('plune: no API token \u2014 run "plune login" first. Results will be written to the fallback file.');
1397
+ }
1398
+ for (const warning of env.warnings) log(`plune: ${warning}`);
1399
+ if (env.ignored.length > 0) {
1400
+ log(`plune: ignoring ${env.ignored.join(", ")} \u2014 a run has nowhere to store them yet.`);
1401
+ }
1402
+ function defer(results) {
1403
+ appendBatch(fallbackPath, {
1404
+ runId,
1405
+ externalKey,
1406
+ session: sessionMarker,
1407
+ ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
1408
+ ...configuration !== void 0 ? { configuration } : {},
1409
+ results: results.map(onDisk)
1410
+ });
1411
+ stats.deferred += results.length;
1412
+ }
1413
+ async function resolveKeys(values) {
1414
+ const unknown = values.filter((k) => !resolved.has(keyId(k)));
1415
+ if (unknown.length === 0 || offline) return;
1416
+ for (const part of chunk(unknown, RESOLVE_CHUNK)) {
1417
+ const out = await client.post(
1418
+ "/v1/test-cases/resolve",
1419
+ { keys: part }
1420
+ );
1421
+ if (!out.ok || !Array.isArray(out.body?.results)) {
1422
+ log(`plune: could not look up test cases (${out.ok ? "the answer had no results" : out.detail || out.kind}).`);
1423
+ return;
1424
+ }
1425
+ for (const row of out.body.results) {
1426
+ if (typeof row?.key?.value === "string") resolved.set(keyId(row.key), row.testCaseId);
1427
+ }
1428
+ }
1429
+ }
1430
+ if (!offline) {
1431
+ if (expected !== void 0) await resolveKeys(expected.flat());
1432
+ const stated2 = expected?.slice(0, EXPECTED_MAX) ?? [];
1433
+ const configuration2 = stated2.length === 0 ? void 0 : {
1434
+ expected: stated2.flatMap((keys) => {
1435
+ const hit = keys.map((k) => resolved.get(keyId(k))).find((v) => typeof v === "string");
1436
+ if (typeof hit === "string") return [{ testCaseId: hit }];
1437
+ return keys[0] === void 0 ? [] : [{ externalKey: keys[0] }];
1438
+ }),
1439
+ // The claim travels with the list it is about. A runner that could not enumerate
1440
+ // its tests has no list, and a claim without one is nothing the platform can check —
1441
+ // so it is not sent, rather than sent and silently meaningless.
1442
+ ...cfg.full === true ? { full: true } : {}
1443
+ };
1444
+ if (expected !== void 0 && expected.length > EXPECTED_MAX) {
1445
+ log(`plune: ${expected.length} tests is more than the run configuration holds \u2014 reporting the first ${EXPECTED_MAX}.`);
1446
+ }
1447
+ const described = {
1448
+ ...cfg.title !== void 0 ? { title: cfg.title } : {},
1449
+ ...cfg.environment !== void 0 ? { environment: cfg.environment } : {},
1450
+ ...cfg.labels !== void 0 ? { labels: cfg.labels } : {}
1451
+ };
1452
+ const request = {
1453
+ schemaVersion: 2,
1454
+ kind: cfg.kind ?? "automated",
1455
+ ...externalKey !== null ? { externalKey } : {},
1456
+ ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
1457
+ ...configuration2 !== void 0 ? { configuration: configuration2 } : {},
1458
+ // Named even when nobody named it — the list has to read without opening a row. Only what
1459
+ // the caller DESCRIBED goes to `warnIfDropped` below: a title this side invented is not one
1460
+ // a person will miss, and a deployment older than the field must not be nagged on every run.
1461
+ title: defaultRunTitle(),
1462
+ ...described
1463
+ };
1464
+ let start = await client.post("/v1/runs", request);
1465
+ if (!start.ok && start.status === 413 && configuration2 !== void 0) {
1466
+ log(
1467
+ `plune: the platform refused the run's list of expected tests as too large (${start.detail || start.kind}) \u2014 starting without it: the results still land, but this run counts no tests that did not run, and claims no full run.`
1468
+ );
1469
+ start = await client.post("/v1/runs", { ...request, configuration: void 0 });
1470
+ }
1471
+ if (start.ok && typeof start.body?.run?.id === "string") {
1472
+ runId = start.body.run.id;
1473
+ joined = start.status === 200;
1474
+ warnIfDropped(described, start.body.run, log);
1475
+ } else {
1476
+ const why = start.ok ? "the answer had no run" : start.detail || start.kind;
1477
+ log(`plune: could not start the run (${why}). Results will be written to ${fallbackPath}.`);
1478
+ }
1479
+ }
1480
+ function matchFor(result) {
1481
+ if (result.testCaseId !== void 0) return { kind: "found", testCaseId: result.testCaseId };
1482
+ let unanswered = false;
1483
+ for (const key of result.keys) {
1484
+ const hit = resolved.get(keyId(key));
1485
+ if (typeof hit === "string") return { kind: "found", testCaseId: hit };
1486
+ if (hit === void 0) unanswered = true;
1487
+ }
1488
+ return unanswered ? { kind: "unanswered" } : { kind: "unmatched" };
1489
+ }
1490
+ function remember(result) {
1491
+ if (!offerDiscovered) return;
1492
+ if (result.title === void 0 || result.specRef === void 0) return;
1493
+ if (result.keys.length === 0) return;
1494
+ const title = boundTitle(result.title);
1495
+ if (title !== result.title) shortened.add(result.title);
1496
+ discoveries.set(keyId(result.keys[0]), {
1497
+ keys: result.keys,
1498
+ title,
1499
+ source: result.source,
1500
+ specRef: result.specRef,
1501
+ rawStatus: result.rawStatus
1502
+ });
1503
+ for (const key of result.keys) held.set(keyId(key), result);
1504
+ }
1505
+ async function offer() {
1506
+ if (discoveries.size === 0 || offline || runId === null) return;
1507
+ const batches = chunk([...discoveries.values()], DISCOVER_MAX);
1508
+ for (const [index, batch] of batches.entries()) {
1509
+ const out = await client.post("/v1/review-items/discovered", {
1510
+ discovered: batch,
1511
+ runId
1512
+ });
1513
+ if (!out.ok || !Array.isArray(out.body?.results)) {
1514
+ stats.unoffered = batches.slice(index).reduce((n, rest) => n + rest.length, 0);
1515
+ stats.unofferedWhy = whyUnoffered(out);
1516
+ log(
1517
+ `plune: could not offer ${stats.unoffered} unknown test(s) for review (${out.ok ? "the answer had no results" : out.detail || out.kind}).`
1518
+ );
1519
+ return;
1520
+ }
1521
+ stats.offered += out.body.results.filter((r) => r?.outcome === "queued").length;
1522
+ const made = out.body.results.filter((r) => r?.outcome === "created");
1523
+ stats.created += made.length;
1524
+ const submissions = [];
1525
+ const filesByKey = /* @__PURE__ */ new Map();
1526
+ for (const r of made) {
1527
+ const pending = typeof r.id === "string" && r.id !== "" && typeof r.key?.value === "string" ? held.get(keyId(r.key)) : void 0;
1528
+ if (pending === void 0) continue;
1529
+ for (const key of pending.keys) held.delete(keyId(key));
1530
+ const { keys: _keys, files: files2, ...rest } = pending;
1531
+ submissions.push({ ...rest, testCaseId: r.id });
1532
+ if (files2 !== void 0) filesByKey.set(pending.resultKey, files2);
1533
+ const text = snapshotByKey.get(pending.resultKey);
1534
+ if (text !== void 0) snapshots.set(r.id, text);
1535
+ }
1536
+ if (submissions.length > 0) {
1537
+ const before = stats.deferred;
1538
+ await send(submissions, filesByKey);
1539
+ createdWithResult += submissions.length;
1540
+ createdUndelivered += stats.deferred - before;
1541
+ }
1542
+ }
1543
+ }
1544
+ async function syncSnapshots() {
1545
+ if (snapshots.size === 0 || offline) return;
1546
+ const stored = /* @__PURE__ */ new Map();
1547
+ let cursor = null;
1548
+ do {
1549
+ const query = `type=automated&stability=0&limit=200${cursor === null ? "" : `&cursor=${encodeURIComponent(cursor)}`}`;
1550
+ const out = await client.get(`/v1/test-cases?${query}`);
1551
+ if (!out.ok || !Array.isArray(out.body?.testCases)) {
1552
+ log(`plune: could not update the code snapshots (${out.ok ? "the case list had no cases" : out.detail || out.kind}).`);
1553
+ return;
1554
+ }
1555
+ for (const row of out.body.testCases) {
1556
+ if (typeof row?.id === "string" && snapshots.has(row.id)) stored.set(row.id, row.codeSnapshotHash ?? null);
1557
+ }
1558
+ cursor = typeof out.body.nextCursor === "string" ? out.body.nextCursor : null;
1559
+ } while (cursor !== null && stored.size < snapshots.size);
1560
+ const sha = (text) => createHash2("sha256").update(text).digest("hex");
1561
+ const due = [...snapshots].filter(([id, text]) => stored.has(id) && stored.get(id) !== sha(text)).sort(([a], [b]) => sha(`${runId}:${a}`).localeCompare(sha(`${runId}:${b}`)));
1562
+ let updated = 0;
1563
+ let refused = 0;
1564
+ let tried = 0;
1565
+ for (const [id, text] of due.slice(0, SNAPSHOT_UPDATES_MAX)) {
1566
+ tried += 1;
1567
+ const out = await client.patch(`/v1/test-cases/${encodeURIComponent(id)}`, { codeSnapshot: text });
1568
+ if (out.ok) {
1569
+ updated += 1;
1570
+ continue;
1571
+ }
1572
+ if (out.kind === "auth" || out.kind === "unavailable" || out.status === 429) {
1573
+ log(`plune: could not update the code snapshot of test case ${id} (${out.detail || out.kind}); the rest are left as they are.`);
1574
+ break;
1575
+ }
1576
+ refused += 1;
1577
+ }
1578
+ const left = due.length - tried;
1579
+ const parts = [`${updated} code snapshot(s) updated`];
1580
+ if (refused > 0) parts.push(`${refused} not updated`);
1581
+ if (left > 0 && tried === Math.min(due.length, SNAPSHOT_UPDATES_MAX)) parts.push(`${left} left for the next run`);
1582
+ if (updated + refused > 0) log(`plune: ${parts.join(", ")}`);
1583
+ }
1336
1584
  const sending = /* @__PURE__ */ new Set();
1337
1585
  let sendError;
1338
1586
  let answered = false;
@@ -1373,9 +1621,11 @@ async function startRun(passed, declared2) {
1373
1621
  for (const result of pending) {
1374
1622
  const match = matchFor(result);
1375
1623
  if (match.kind === "found") {
1376
- const { keys: _keys, files, ...rest } = result;
1624
+ const { keys: _keys, files: files2, ...rest } = result;
1377
1625
  submissions.push({ ...rest, testCaseId: match.testCaseId });
1378
- if (files !== void 0) filesByKey.set(result.resultKey, files);
1626
+ const text = snapshotByKey.get(result.resultKey);
1627
+ if (text !== void 0) snapshots.set(match.testCaseId, text);
1628
+ if (files2 !== void 0) filesByKey.set(result.resultKey, files2);
1379
1629
  } else if (match.kind === "unmatched") {
1380
1630
  stats.unresolved += 1;
1381
1631
  remember(result);
@@ -1391,22 +1641,30 @@ async function startRun(passed, declared2) {
1391
1641
  await send(submissions, filesByKey);
1392
1642
  }
1393
1643
  async function send(submissions, filesByKey) {
1394
- for (const part of packed(submissions)) {
1644
+ for (const packedPart of packed(submissions)) {
1645
+ let part = targetsRefused ? packedPart.map(withoutTargets) : packedPart;
1395
1646
  if (offline) {
1396
1647
  defer(part);
1397
1648
  continue;
1398
1649
  }
1399
- const out = await client.post(
1650
+ const post = (results) => client.post(
1400
1651
  `/v1/runs/${runId}/results`,
1401
- // The job's combination on every batch (plune-ai/plune#1251); a refusal of it is a 422 said below as it came.
1402
- { results: part, ...configuration !== void 0 ? { configuration } : {} }
1652
+ // The job's combination on every batch; a refusal of it is a 422 said below as it came.
1653
+ { results, ...configuration !== void 0 ? { configuration } : {} }
1403
1654
  );
1655
+ let out = await post(part);
1656
+ if (!out.ok && out.kind === "invalid" && out.status === 400 && part.some((r) => r.targets !== void 0)) {
1657
+ if (!targetsRefused) log("plune: the platform does not take targets on a result yet \u2014 the results are sent without them.");
1658
+ targetsRefused = true;
1659
+ part = part.map(withoutTargets);
1660
+ out = await post(part);
1661
+ }
1404
1662
  const counts = out.ok ? out.body?.counts : void 0;
1405
1663
  const told = COUNTED.filter((k) => typeof counts?.[k] === "number");
1406
1664
  if (told.length > 0) {
1407
1665
  for (const k of told) stats[k] += counts[k];
1408
1666
  progress();
1409
- await upload(out.ok ? out.body?.items : void 0, filesByKey);
1667
+ await files.upload(out.ok ? out.body?.items : void 0, filesByKey);
1410
1668
  answered = true;
1411
1669
  continue;
1412
1670
  }
@@ -1442,10 +1700,10 @@ async function startRun(passed, declared2) {
1442
1700
  }
1443
1701
  const kinds = [stats.screenshots, stats.textFiles, stats.otherFiles];
1444
1702
  const sum = (what) => kinds.reduce((n, counts) => n + counts[what], 0);
1445
- if (bucketSeen) {
1446
- const other = sum("skipped") - noStorage;
1703
+ if (files.bucketSeen) {
1704
+ const other = sum("skipped") - files.noStorage;
1447
1705
  parts.push(
1448
- `${sum("uploaded")} file(s) uploaded to your bucket` + (noStorage > 0 ? `, ${noStorage} skipped (no bucket connected)` : "") + (other > 0 ? `, ${other} skipped` : "") + (sum("failed") > 0 ? `, ${sum("failed")} failed to upload` : "")
1706
+ `${sum("uploaded")} file(s) uploaded to your bucket` + (files.noStorage > 0 ? `, ${files.noStorage} skipped (no bucket connected)` : "") + (other > 0 ? `, ${other} skipped` : "") + (sum("failed") > 0 ? `, ${sum("failed")} failed to upload` : "")
1449
1707
  );
1450
1708
  } else {
1451
1709
  for (const said of [tally(stats.screenshots, "screenshot"), tally(stats.textFiles, "text file")]) {
@@ -1457,11 +1715,10 @@ async function startRun(passed, declared2) {
1457
1715
  }
1458
1716
  if (stats.deferred > 0) parts.push(`${stats.deferred} not delivered \u2014 written to ${fallbackPath}`);
1459
1717
  if (shortened.size > 0) parts.push(`${shortened.size} test name(s) shortened to fit a key`);
1460
- const files = [stats.screenshots, stats.textFiles, stats.otherFiles];
1461
- const total = (what) => files.reduce((n, counts) => n + counts[what], 0);
1462
- if (total("uploaded") + total("skipped") + total("failed") + existed > 0) {
1718
+ const total = (what) => kinds.reduce((n, counts) => n + counts[what], 0);
1719
+ if (total("uploaded") + total("skipped") + total("failed") + files.existed > 0) {
1463
1720
  log(
1464
- `plune: files \u2014 ${total("uploaded")} uploaded, ${total("skipped")} skipped, ${existed} already there (skipped), ${retried} retried, ${total("failed")} dropped, in ${(uploadMs / 1e3).toFixed(1)} s (${uploadsAtOnce} at once, ${requests} request(s) to Plune)`
1721
+ `plune: files \u2014 ${total("uploaded")} uploaded, ${total("skipped")} skipped, ${files.existed} already there (skipped), ${files.retried} retried, ${total("failed")} dropped, in ${(files.uploadMs / 1e3).toFixed(1)} s (${uploadsAtOnce} at once, ${files.requests} request(s) to Plune)`
1465
1722
  );
1466
1723
  }
1467
1724
  log(`plune: ${parts.join(" \xB7 ")}`);
@@ -1481,7 +1738,10 @@ async function startRun(passed, declared2) {
1481
1738
  return stats;
1482
1739
  },
1483
1740
  async add(result) {
1484
- buffer.push({ ...result, keys: bound(result.keys) });
1741
+ const { codeAt, ...rest } = result;
1742
+ const text = codeAt === void 0 ? void 0 : snapshotAt(codeAt, specFiles);
1743
+ if (text !== void 0) snapshotByKey.set(result.resultKey, text);
1744
+ buffer.push({ ...rest, keys: bound(result.keys) });
1485
1745
  if (buffer.length >= batchSize) await flushBuffer();
1486
1746
  },
1487
1747
  flush,
@@ -1490,6 +1750,7 @@ async function startRun(passed, declared2) {
1490
1750
  done = true;
1491
1751
  await flush();
1492
1752
  await offer();
1753
+ await syncSnapshots();
1493
1754
  let frozen;
1494
1755
  if (runId !== null && !offline) {
1495
1756
  const out = await client.post(`/v1/runs/${runId}/events`, {
@@ -1513,6 +1774,7 @@ async function startRun(passed, declared2) {
1513
1774
  done = true;
1514
1775
  await flush();
1515
1776
  await offer();
1777
+ await syncSnapshots();
1516
1778
  let frozen;
1517
1779
  const after = [];
1518
1780
  const shard = env.shard;
@@ -1587,7 +1849,7 @@ function metadataOf(result) {
1587
1849
  const found = result.attachments.find((a) => a.contentType === METADATA_TYPE3);
1588
1850
  if (found === void 0) return void 0;
1589
1851
  try {
1590
- const raw = found.body !== void 0 ? found.body.toString("utf8") : found.path !== void 0 ? readFileSync2(found.path, "utf8") : void 0;
1852
+ const raw = found.body !== void 0 ? found.body.toString("utf8") : found.path !== void 0 ? readFileSync3(found.path, "utf8") : void 0;
1591
1853
  return raw === void 0 ? void 0 : JSON.parse(raw);
1592
1854
  } catch {
1593
1855
  return void 0;
@@ -1604,7 +1866,7 @@ function statedIdOf(test, metadata, mapped) {
1604
1866
  function readIds(file) {
1605
1867
  let raw;
1606
1868
  try {
1607
- raw = readFileSync2(file, "utf8");
1869
+ raw = readFileSync3(file, "utf8");
1608
1870
  } catch {
1609
1871
  return {};
1610
1872
  }
@@ -1644,7 +1906,7 @@ function attemptOf(test, result, ctx) {
1644
1906
  name,
1645
1907
  contentType,
1646
1908
  ...path3 !== void 0 ? { path: path3 } : {},
1647
- // What a test attached from memory has no file: the bytes are the reporter's only copy (plune#928).
1909
+ // What a test attached from memory has no file: the bytes are the reporter's only copy.
1648
1910
  ...body !== void 0 ? { body } : {}
1649
1911
  })),
1650
1912
  ...ctx.buildHref !== void 0 ? { buildHref: ctx.buildHref } : {},
@@ -1671,13 +1933,15 @@ function pendingFrom(test, result, ctx, ids = {}) {
1671
1933
  // Anything the test named itself comes before what we derived from its location: a Qase or
1672
1934
  // TestRail id written by a fixture is a deliberate statement, and a file path is a guess.
1673
1935
  keys: [...metadata?.keys ?? [], ...keysFor(test)],
1674
- // Read only if nothing resolves this test, and then it is what the review queue shows (D14).
1936
+ // Read only if nothing resolves this test, and then it is what the review queue shows.
1675
1937
  // The full `describe > title` path rather than `test.title` alone: two suites in one file
1676
1938
  // routinely share a title, and "adds an item" on its own is not something a person can judge.
1677
1939
  title: titlesOf(test).join(" \u203A "),
1678
1940
  // The line as well as the file. A reviewer's first move on an unknown test is to open it, and
1679
1941
  // `specRef` is the only thing the entry carries that can take them there.
1680
1942
  specRef: `${fileOf2(test)}:${test.location.line}`,
1943
+ // Where the core reads the test's text for its case's code snapshot; never sent as it is.
1944
+ codeAt: { file: test.location.file, line: test.location.line, column: test.location.column },
1681
1945
  source: SOURCE,
1682
1946
  // The runner's own word, untouched. Mapping it is the platform's job and a project's setting.
1683
1947
  rawStatus: result.status,
@@ -1751,7 +2015,7 @@ var PluneReporter = class {
1751
2015
  ...this.options.externalKey !== void 0 ? { externalKey: this.options.externalKey } : {},
1752
2016
  ...this.options.batchSize !== void 0 ? { batchSize: this.options.batchSize } : {},
1753
2017
  ...this.options.fallbackPath !== void 0 ? { fallbackPath: this.options.fallbackPath } : {},
1754
- // Where it ran (plune#927): the commit Playwright wrote into `metadata.ci`, and its branch —
2018
+ // Where it ran: the commit Playwright wrote into `metadata.ci`, and its branch —
1755
2019
  // which Playwright gives on GitLab and Jenkins, and the core reads from the job on GitHub.
1756
2020
  meta: { runner: SOURCE, ...ciUrl !== void 0 ? { ciUrl } : {}, ...ciCommit(ci) }
1757
2021
  },