@plune-ai/playwright 0.7.1 → 0.7.2

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;
@@ -697,68 +864,14 @@ function chunk(items, size) {
697
864
  for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
698
865
  return out;
699
866
  }
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);
867
+ function fileSender(options) {
868
+ const { client, log, stats, uploadsAtOnce, uploadRetries } = options;
869
+ const without = options.without ?? "its result is reported without it";
725
870
  let retried = 0;
726
871
  let uploadMs = 0;
727
872
  let requests = 0;
728
873
  let existed = 0;
729
874
  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
875
  const skipsSaid = /* @__PURE__ */ new Set();
763
876
  const countsOf = (kind) => kind === "text" ? stats.textFiles : kind === "file" ? stats.otherFiles : stats.screenshots;
764
877
  let bucketSeen = false;
@@ -767,168 +880,6 @@ async function startRun(passed, declared2) {
767
880
  const failedSaid = /* @__PURE__ */ new Set();
768
881
  const codesSaid = /* @__PURE__ */ new Set();
769
882
  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
883
  function skip(kind, name, why) {
933
884
  countsOf(kind).skipped += 1;
934
885
  if (why === "noStorage") noStorage += 1;
@@ -938,24 +889,25 @@ async function startRun(passed, declared2) {
938
889
  if (why === "noStorage") log(`plune: "${name}" not stored \u2014 ${SKIPPED[why]}.`);
939
890
  else log(`plune: ${KINDS[kind].label} "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
940
891
  }
892
+ const filesOf2 = (job) => `/v1/${job.owner ?? "results"}/${encodeURIComponent(job.id)}/files`;
941
893
  function ask(job, size) {
942
894
  requests += 1;
943
- return client.post(`/v1/results/${encodeURIComponent(job.id)}/files/uploads`, {
944
- files: [{ name: job.name, contentType: job.type, size }]
895
+ return client.post(`${filesOf2(job)}/uploads`, {
896
+ files: [{ name: job.name, contentType: job.type, size, ...job.key !== void 0 ? { key: job.key } : {} }]
945
897
  }, uploadRetries);
946
898
  }
947
899
  function failed(job, why) {
948
900
  countsOf(job.kind).failed += 1;
949
901
  if (!failedSaid.has(job.kind)) {
950
902
  failedSaid.add(job.kind);
951
- log(`plune: could not upload a ${KINDS[job.kind].label} (${why}) \u2014 its result is reported without it.`);
903
+ log(`plune: could not upload a ${KINDS[job.kind].label} (${why}) \u2014 ${without}.`);
952
904
  }
953
905
  }
954
906
  function failedToBucket(job, code) {
955
907
  countsOf(job.kind).failed += 1;
956
908
  if (codesSaid.has(code)) return;
957
909
  codesSaid.add(code);
958
- log(`plune: "${job.name}" not uploaded to your bucket (${code}) \u2014 its result is reported without it.`);
910
+ log(`plune: "${job.name}" not uploaded to your bucket (${code}) \u2014 ${without}.`);
959
911
  }
960
912
  function refusedHere(job, size) {
961
913
  if (job.kind === "screenshot") {
@@ -983,7 +935,7 @@ async function startRun(passed, declared2) {
983
935
  if (refusal !== void 0) return skip(kind, job.name, refusal);
984
936
  requests += 1;
985
937
  const out = await client.upload(
986
- `/v1/results/${encodeURIComponent(job.id)}/files?name=${encodeURIComponent(job.name)}`,
938
+ `${filesOf2(job)}?name=${encodeURIComponent(job.name)}`,
987
939
  bytes,
988
940
  job.type
989
941
  );
@@ -1005,8 +957,8 @@ async function startRun(passed, declared2) {
1005
957
  link = fresh;
1006
958
  }
1007
959
  requests += 1;
1008
- const done2 = await client.post(`/v1/files/${encodeURIComponent(link.id)}/complete`, {}, uploadRetries);
1009
- if (!done2.ok) return failedToBucket(job, codeOf(done2));
960
+ const done = await client.post(`/v1/files/${encodeURIComponent(link.id)}/complete`, {}, uploadRetries);
961
+ if (!done.ok) return failedToBucket(job, codeOf(done));
1010
962
  countsOf(job.kind).uploaded += 1;
1011
963
  }
1012
964
  let free = uploadsAtOnce;
@@ -1333,6 +1285,295 @@ async function startRun(passed, declared2) {
1333
1285
  else await uploadBatched(jobs);
1334
1286
  uploadMs += Date.now() - started;
1335
1287
  }
1288
+ return {
1289
+ upload,
1290
+ uploadEach,
1291
+ onRetry: () => void (retried += 1),
1292
+ get bucketSeen() {
1293
+ return bucketSeen;
1294
+ },
1295
+ get noStorage() {
1296
+ return noStorage;
1297
+ },
1298
+ get existed() {
1299
+ return existed;
1300
+ },
1301
+ get retried() {
1302
+ return retried;
1303
+ },
1304
+ get uploadMs() {
1305
+ return uploadMs;
1306
+ },
1307
+ get requests() {
1308
+ return requests;
1309
+ }
1310
+ };
1311
+ }
1312
+ function warnIfDropped(sent, run, log) {
1313
+ const names = Object.keys(sent);
1314
+ if (names.length === 0) return;
1315
+ if (names.some((name) => run[name] != null)) return;
1316
+ log(
1317
+ `plune: this deployment stored none of ${names.join(", ")} \u2014 it is older than the fields. The run is otherwise reported in full.`
1318
+ );
1319
+ }
1320
+ async function startRun(passed, declared2) {
1321
+ const env = readEnv();
1322
+ if (env.shardError !== void 0) throw new Error(env.shardError);
1323
+ if (env.configurationError !== void 0 && passed.configuration === void 0) throw new Error(env.configurationError);
1324
+ const stated = Object.fromEntries(Object.entries(passed).filter(([, v]) => v !== void 0));
1325
+ const cfg = { ...env.config, ...stated };
1326
+ const configuration = cfg.configuration !== void 0 && Object.keys(cfg.configuration).length > 0 ? cfg.configuration : void 0;
1327
+ const log = cfg.log ?? ((line) => void process.stderr.write(`${line}
1328
+ `));
1329
+ const fallbackPath = cfg.fallbackPath ?? DEFAULT_FALLBACK_PATH;
1330
+ const externalKey = cfg.externalKey ?? null;
1331
+ const sessionMarker = randomUUID();
1332
+ const batchSize = Math.min(cfg.batchSize ?? BATCH_DEFAULT, BATCH_MAX);
1333
+ const offerDiscovered = cfg.offerDiscovered ?? false;
1334
+ const token = cfg.token ?? loadToken() ?? "";
1335
+ const uploadsAtOnce = Math.min(Math.max(Math.floor(cfg.uploadConcurrency ?? UPLOAD_CONCURRENCY.default), UPLOAD_CONCURRENCY.min), UPLOAD_CONCURRENCY.max);
1336
+ const uploadRetries = Math.min(Math.max(Math.floor(cfg.uploadRetries ?? UPLOAD_RETRIES.default), UPLOAD_RETRIES.min), UPLOAD_RETRIES.max);
1337
+ const client = createClient({
1338
+ apiUrl: resolveApiUrl(cfg.apiUrl),
1339
+ token,
1340
+ uploadRetries,
1341
+ onRetry: () => files.onRetry(),
1342
+ ...cfg.fetchImpl !== void 0 ? { fetchImpl: cfg.fetchImpl } : {}
1343
+ });
1344
+ const stats = {
1345
+ accepted: 0,
1346
+ duplicate: 0,
1347
+ conflict: 0,
1348
+ rejected: 0,
1349
+ unresolved: 0,
1350
+ offered: 0,
1351
+ created: 0,
1352
+ unoffered: 0,
1353
+ deferred: 0,
1354
+ screenshots: { uploaded: 0, skipped: 0, failed: 0 },
1355
+ textFiles: { uploaded: 0, skipped: 0, failed: 0 },
1356
+ otherFiles: { uploaded: 0, skipped: 0, failed: 0 }
1357
+ };
1358
+ const files = fileSender({ client, log, stats, uploadsAtOnce, uploadRetries });
1359
+ const resolved = /* @__PURE__ */ new Map();
1360
+ let buffer = [];
1361
+ const discoveries = /* @__PURE__ */ new Map();
1362
+ const held = /* @__PURE__ */ new Map();
1363
+ let createdWithResult = 0;
1364
+ let createdUndelivered = 0;
1365
+ let runId = null;
1366
+ let joined = false;
1367
+ let offline = token === "";
1368
+ let done = false;
1369
+ const shortened = /* @__PURE__ */ new Set();
1370
+ const specFiles = /* @__PURE__ */ new Map();
1371
+ const snapshotByKey = /* @__PURE__ */ new Map();
1372
+ const snapshots = /* @__PURE__ */ new Map();
1373
+ function bound(keys) {
1374
+ return keys.map((key) => {
1375
+ const fit = boundKey(key);
1376
+ if (fit !== key && !shortened.has(key.value)) {
1377
+ shortened.add(key.value);
1378
+ if (shortened.size === 1) {
1379
+ log(
1380
+ `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.`
1381
+ );
1382
+ }
1383
+ }
1384
+ return fit;
1385
+ });
1386
+ }
1387
+ const expected = declared2?.map(bound);
1388
+ if (offline) {
1389
+ log('plune: no API token \u2014 run "plune login" first. Results will be written to the fallback file.');
1390
+ }
1391
+ for (const warning of env.warnings) log(`plune: ${warning}`);
1392
+ if (env.ignored.length > 0) {
1393
+ log(`plune: ignoring ${env.ignored.join(", ")} \u2014 a run has nowhere to store them yet.`);
1394
+ }
1395
+ function defer(results) {
1396
+ appendBatch(fallbackPath, {
1397
+ runId,
1398
+ externalKey,
1399
+ session: sessionMarker,
1400
+ ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
1401
+ ...configuration !== void 0 ? { configuration } : {},
1402
+ results: results.map(onDisk)
1403
+ });
1404
+ stats.deferred += results.length;
1405
+ }
1406
+ async function resolveKeys(values) {
1407
+ const unknown = values.filter((k) => !resolved.has(keyId(k)));
1408
+ if (unknown.length === 0 || offline) return;
1409
+ for (const part of chunk(unknown, RESOLVE_CHUNK)) {
1410
+ const out = await client.post(
1411
+ "/v1/test-cases/resolve",
1412
+ { keys: part }
1413
+ );
1414
+ if (!out.ok || !Array.isArray(out.body?.results)) {
1415
+ log(`plune: could not look up test cases (${out.ok ? "the answer had no results" : out.detail || out.kind}).`);
1416
+ return;
1417
+ }
1418
+ for (const row of out.body.results) {
1419
+ if (typeof row?.key?.value === "string") resolved.set(keyId(row.key), row.testCaseId);
1420
+ }
1421
+ }
1422
+ }
1423
+ if (!offline) {
1424
+ if (expected !== void 0) await resolveKeys(expected.flat());
1425
+ const stated2 = expected?.slice(0, EXPECTED_MAX) ?? [];
1426
+ const configuration2 = stated2.length === 0 ? void 0 : {
1427
+ expected: stated2.flatMap((keys) => {
1428
+ const hit = keys.map((k) => resolved.get(keyId(k))).find((v) => typeof v === "string");
1429
+ if (typeof hit === "string") return [{ testCaseId: hit }];
1430
+ return keys[0] === void 0 ? [] : [{ externalKey: keys[0] }];
1431
+ }),
1432
+ // The claim travels with the list it is about. A runner that could not enumerate
1433
+ // its tests has no list, and a claim without one is nothing the platform can check —
1434
+ // so it is not sent, rather than sent and silently meaningless.
1435
+ ...cfg.full === true ? { full: true } : {}
1436
+ };
1437
+ if (expected !== void 0 && expected.length > EXPECTED_MAX) {
1438
+ log(`plune: ${expected.length} tests is more than the run configuration holds \u2014 reporting the first ${EXPECTED_MAX}.`);
1439
+ }
1440
+ const described = {
1441
+ ...cfg.title !== void 0 ? { title: cfg.title } : {},
1442
+ ...cfg.environment !== void 0 ? { environment: cfg.environment } : {},
1443
+ ...cfg.labels !== void 0 ? { labels: cfg.labels } : {}
1444
+ };
1445
+ const request = {
1446
+ schemaVersion: 2,
1447
+ kind: cfg.kind ?? "automated",
1448
+ ...externalKey !== null ? { externalKey } : {},
1449
+ ...cfg.meta !== void 0 ? { meta: cfg.meta } : {},
1450
+ ...configuration2 !== void 0 ? { configuration: configuration2 } : {},
1451
+ // Named even when nobody named it — the list has to read without opening a row. Only what
1452
+ // the caller DESCRIBED goes to `warnIfDropped` below: a title this side invented is not one
1453
+ // a person will miss, and a deployment older than the field must not be nagged on every run.
1454
+ title: defaultRunTitle(),
1455
+ ...described
1456
+ };
1457
+ let start = await client.post("/v1/runs", request);
1458
+ if (!start.ok && start.status === 413 && configuration2 !== void 0) {
1459
+ log(
1460
+ `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.`
1461
+ );
1462
+ start = await client.post("/v1/runs", { ...request, configuration: void 0 });
1463
+ }
1464
+ if (start.ok && typeof start.body?.run?.id === "string") {
1465
+ runId = start.body.run.id;
1466
+ joined = start.status === 200;
1467
+ warnIfDropped(described, start.body.run, log);
1468
+ } else {
1469
+ const why = start.ok ? "the answer had no run" : start.detail || start.kind;
1470
+ log(`plune: could not start the run (${why}). Results will be written to ${fallbackPath}.`);
1471
+ }
1472
+ }
1473
+ function matchFor(result) {
1474
+ if (result.testCaseId !== void 0) return { kind: "found", testCaseId: result.testCaseId };
1475
+ let unanswered = false;
1476
+ for (const key of result.keys) {
1477
+ const hit = resolved.get(keyId(key));
1478
+ if (typeof hit === "string") return { kind: "found", testCaseId: hit };
1479
+ if (hit === void 0) unanswered = true;
1480
+ }
1481
+ return unanswered ? { kind: "unanswered" } : { kind: "unmatched" };
1482
+ }
1483
+ function remember(result) {
1484
+ if (!offerDiscovered) return;
1485
+ if (result.title === void 0 || result.specRef === void 0) return;
1486
+ if (result.keys.length === 0) return;
1487
+ const title = boundTitle(result.title);
1488
+ if (title !== result.title) shortened.add(result.title);
1489
+ discoveries.set(keyId(result.keys[0]), {
1490
+ keys: result.keys,
1491
+ title,
1492
+ source: result.source,
1493
+ specRef: result.specRef,
1494
+ rawStatus: result.rawStatus
1495
+ });
1496
+ for (const key of result.keys) held.set(keyId(key), result);
1497
+ }
1498
+ async function offer() {
1499
+ if (discoveries.size === 0 || offline || runId === null) return;
1500
+ const batches = chunk([...discoveries.values()], DISCOVER_MAX);
1501
+ for (const [index, batch] of batches.entries()) {
1502
+ const out = await client.post("/v1/review-items/discovered", {
1503
+ discovered: batch,
1504
+ runId
1505
+ });
1506
+ if (!out.ok || !Array.isArray(out.body?.results)) {
1507
+ stats.unoffered = batches.slice(index).reduce((n, rest) => n + rest.length, 0);
1508
+ stats.unofferedWhy = whyUnoffered(out);
1509
+ log(
1510
+ `plune: could not offer ${stats.unoffered} unknown test(s) for review (${out.ok ? "the answer had no results" : out.detail || out.kind}).`
1511
+ );
1512
+ return;
1513
+ }
1514
+ stats.offered += out.body.results.filter((r) => r?.outcome === "queued").length;
1515
+ const made = out.body.results.filter((r) => r?.outcome === "created");
1516
+ stats.created += made.length;
1517
+ const submissions = [];
1518
+ const filesByKey = /* @__PURE__ */ new Map();
1519
+ for (const r of made) {
1520
+ const pending = typeof r.id === "string" && r.id !== "" && typeof r.key?.value === "string" ? held.get(keyId(r.key)) : void 0;
1521
+ if (pending === void 0) continue;
1522
+ for (const key of pending.keys) held.delete(keyId(key));
1523
+ const { keys: _keys, files: files2, ...rest } = pending;
1524
+ submissions.push({ ...rest, testCaseId: r.id });
1525
+ if (files2 !== void 0) filesByKey.set(pending.resultKey, files2);
1526
+ const text = snapshotByKey.get(pending.resultKey);
1527
+ if (text !== void 0) snapshots.set(r.id, text);
1528
+ }
1529
+ if (submissions.length > 0) {
1530
+ const before = stats.deferred;
1531
+ await send(submissions, filesByKey);
1532
+ createdWithResult += submissions.length;
1533
+ createdUndelivered += stats.deferred - before;
1534
+ }
1535
+ }
1536
+ }
1537
+ async function syncSnapshots() {
1538
+ if (snapshots.size === 0 || offline) return;
1539
+ const stored = /* @__PURE__ */ new Map();
1540
+ let cursor = null;
1541
+ do {
1542
+ const query = `type=automated&stability=0&limit=200${cursor === null ? "" : `&cursor=${encodeURIComponent(cursor)}`}`;
1543
+ const out = await client.get(`/v1/test-cases?${query}`);
1544
+ if (!out.ok || !Array.isArray(out.body?.testCases)) {
1545
+ log(`plune: could not update the code snapshots (${out.ok ? "the case list had no cases" : out.detail || out.kind}).`);
1546
+ return;
1547
+ }
1548
+ for (const row of out.body.testCases) {
1549
+ if (typeof row?.id === "string" && snapshots.has(row.id)) stored.set(row.id, row.codeSnapshotHash ?? null);
1550
+ }
1551
+ cursor = typeof out.body.nextCursor === "string" ? out.body.nextCursor : null;
1552
+ } while (cursor !== null && stored.size < snapshots.size);
1553
+ const sha = (text) => createHash2("sha256").update(text).digest("hex");
1554
+ const due = [...snapshots].filter(([id, text]) => stored.has(id) && stored.get(id) !== sha(text)).sort(([a], [b]) => sha(`${runId}:${a}`).localeCompare(sha(`${runId}:${b}`)));
1555
+ let updated = 0;
1556
+ let refused = 0;
1557
+ let tried = 0;
1558
+ for (const [id, text] of due.slice(0, SNAPSHOT_UPDATES_MAX)) {
1559
+ tried += 1;
1560
+ const out = await client.patch(`/v1/test-cases/${encodeURIComponent(id)}`, { codeSnapshot: text });
1561
+ if (out.ok) {
1562
+ updated += 1;
1563
+ continue;
1564
+ }
1565
+ if (out.kind === "auth" || out.kind === "unavailable" || out.status === 429) {
1566
+ log(`plune: could not update the code snapshot of test case ${id} (${out.detail || out.kind}); the rest are left as they are.`);
1567
+ break;
1568
+ }
1569
+ refused += 1;
1570
+ }
1571
+ const left = due.length - tried;
1572
+ const parts = [`${updated} code snapshot(s) updated`];
1573
+ if (refused > 0) parts.push(`${refused} not updated`);
1574
+ if (left > 0 && tried === Math.min(due.length, SNAPSHOT_UPDATES_MAX)) parts.push(`${left} left for the next run`);
1575
+ if (updated + refused > 0) log(`plune: ${parts.join(", ")}`);
1576
+ }
1336
1577
  const sending = /* @__PURE__ */ new Set();
1337
1578
  let sendError;
1338
1579
  let answered = false;
@@ -1373,9 +1614,11 @@ async function startRun(passed, declared2) {
1373
1614
  for (const result of pending) {
1374
1615
  const match = matchFor(result);
1375
1616
  if (match.kind === "found") {
1376
- const { keys: _keys, files, ...rest } = result;
1617
+ const { keys: _keys, files: files2, ...rest } = result;
1377
1618
  submissions.push({ ...rest, testCaseId: match.testCaseId });
1378
- if (files !== void 0) filesByKey.set(result.resultKey, files);
1619
+ const text = snapshotByKey.get(result.resultKey);
1620
+ if (text !== void 0) snapshots.set(match.testCaseId, text);
1621
+ if (files2 !== void 0) filesByKey.set(result.resultKey, files2);
1379
1622
  } else if (match.kind === "unmatched") {
1380
1623
  stats.unresolved += 1;
1381
1624
  remember(result);
@@ -1398,7 +1641,7 @@ async function startRun(passed, declared2) {
1398
1641
  }
1399
1642
  const out = await client.post(
1400
1643
  `/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.
1644
+ // The job's combination on every batch; a refusal of it is a 422 said below as it came.
1402
1645
  { results: part, ...configuration !== void 0 ? { configuration } : {} }
1403
1646
  );
1404
1647
  const counts = out.ok ? out.body?.counts : void 0;
@@ -1406,7 +1649,7 @@ async function startRun(passed, declared2) {
1406
1649
  if (told.length > 0) {
1407
1650
  for (const k of told) stats[k] += counts[k];
1408
1651
  progress();
1409
- await upload(out.ok ? out.body?.items : void 0, filesByKey);
1652
+ await files.upload(out.ok ? out.body?.items : void 0, filesByKey);
1410
1653
  answered = true;
1411
1654
  continue;
1412
1655
  }
@@ -1442,10 +1685,10 @@ async function startRun(passed, declared2) {
1442
1685
  }
1443
1686
  const kinds = [stats.screenshots, stats.textFiles, stats.otherFiles];
1444
1687
  const sum = (what) => kinds.reduce((n, counts) => n + counts[what], 0);
1445
- if (bucketSeen) {
1446
- const other = sum("skipped") - noStorage;
1688
+ if (files.bucketSeen) {
1689
+ const other = sum("skipped") - files.noStorage;
1447
1690
  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` : "")
1691
+ `${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
1692
  );
1450
1693
  } else {
1451
1694
  for (const said of [tally(stats.screenshots, "screenshot"), tally(stats.textFiles, "text file")]) {
@@ -1457,11 +1700,10 @@ async function startRun(passed, declared2) {
1457
1700
  }
1458
1701
  if (stats.deferred > 0) parts.push(`${stats.deferred} not delivered \u2014 written to ${fallbackPath}`);
1459
1702
  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) {
1703
+ const total = (what) => kinds.reduce((n, counts) => n + counts[what], 0);
1704
+ if (total("uploaded") + total("skipped") + total("failed") + files.existed > 0) {
1463
1705
  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)`
1706
+ `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
1707
  );
1466
1708
  }
1467
1709
  log(`plune: ${parts.join(" \xB7 ")}`);
@@ -1481,7 +1723,10 @@ async function startRun(passed, declared2) {
1481
1723
  return stats;
1482
1724
  },
1483
1725
  async add(result) {
1484
- buffer.push({ ...result, keys: bound(result.keys) });
1726
+ const { codeAt, ...rest } = result;
1727
+ const text = codeAt === void 0 ? void 0 : snapshotAt(codeAt, specFiles);
1728
+ if (text !== void 0) snapshotByKey.set(result.resultKey, text);
1729
+ buffer.push({ ...rest, keys: bound(result.keys) });
1485
1730
  if (buffer.length >= batchSize) await flushBuffer();
1486
1731
  },
1487
1732
  flush,
@@ -1490,6 +1735,7 @@ async function startRun(passed, declared2) {
1490
1735
  done = true;
1491
1736
  await flush();
1492
1737
  await offer();
1738
+ await syncSnapshots();
1493
1739
  let frozen;
1494
1740
  if (runId !== null && !offline) {
1495
1741
  const out = await client.post(`/v1/runs/${runId}/events`, {
@@ -1513,6 +1759,7 @@ async function startRun(passed, declared2) {
1513
1759
  done = true;
1514
1760
  await flush();
1515
1761
  await offer();
1762
+ await syncSnapshots();
1516
1763
  let frozen;
1517
1764
  const after = [];
1518
1765
  const shard = env.shard;
@@ -1587,7 +1834,7 @@ function metadataOf(result) {
1587
1834
  const found = result.attachments.find((a) => a.contentType === METADATA_TYPE3);
1588
1835
  if (found === void 0) return void 0;
1589
1836
  try {
1590
- const raw = found.body !== void 0 ? found.body.toString("utf8") : found.path !== void 0 ? readFileSync2(found.path, "utf8") : void 0;
1837
+ const raw = found.body !== void 0 ? found.body.toString("utf8") : found.path !== void 0 ? readFileSync3(found.path, "utf8") : void 0;
1591
1838
  return raw === void 0 ? void 0 : JSON.parse(raw);
1592
1839
  } catch {
1593
1840
  return void 0;
@@ -1604,7 +1851,7 @@ function statedIdOf(test, metadata, mapped) {
1604
1851
  function readIds(file) {
1605
1852
  let raw;
1606
1853
  try {
1607
- raw = readFileSync2(file, "utf8");
1854
+ raw = readFileSync3(file, "utf8");
1608
1855
  } catch {
1609
1856
  return {};
1610
1857
  }
@@ -1644,7 +1891,7 @@ function attemptOf(test, result, ctx) {
1644
1891
  name,
1645
1892
  contentType,
1646
1893
  ...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).
1894
+ // What a test attached from memory has no file: the bytes are the reporter's only copy.
1648
1895
  ...body !== void 0 ? { body } : {}
1649
1896
  })),
1650
1897
  ...ctx.buildHref !== void 0 ? { buildHref: ctx.buildHref } : {},
@@ -1671,13 +1918,15 @@ function pendingFrom(test, result, ctx, ids = {}) {
1671
1918
  // Anything the test named itself comes before what we derived from its location: a Qase or
1672
1919
  // TestRail id written by a fixture is a deliberate statement, and a file path is a guess.
1673
1920
  keys: [...metadata?.keys ?? [], ...keysFor(test)],
1674
- // Read only if nothing resolves this test, and then it is what the review queue shows (D14).
1921
+ // Read only if nothing resolves this test, and then it is what the review queue shows.
1675
1922
  // The full `describe > title` path rather than `test.title` alone: two suites in one file
1676
1923
  // routinely share a title, and "adds an item" on its own is not something a person can judge.
1677
1924
  title: titlesOf(test).join(" \u203A "),
1678
1925
  // The line as well as the file. A reviewer's first move on an unknown test is to open it, and
1679
1926
  // `specRef` is the only thing the entry carries that can take them there.
1680
1927
  specRef: `${fileOf2(test)}:${test.location.line}`,
1928
+ // Where the core reads the test's text for its case's code snapshot; never sent as it is.
1929
+ codeAt: { file: test.location.file, line: test.location.line, column: test.location.column },
1681
1930
  source: SOURCE,
1682
1931
  // The runner's own word, untouched. Mapping it is the platform's job and a project's setting.
1683
1932
  rawStatus: result.status,
@@ -1751,7 +2000,7 @@ var PluneReporter = class {
1751
2000
  ...this.options.externalKey !== void 0 ? { externalKey: this.options.externalKey } : {},
1752
2001
  ...this.options.batchSize !== void 0 ? { batchSize: this.options.batchSize } : {},
1753
2002
  ...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 —
2003
+ // Where it ran: the commit Playwright wrote into `metadata.ci`, and its branch —
1755
2004
  // which Playwright gives on GitLab and Jenkins, and the core reads from the job on GitHub.
1756
2005
  meta: { runner: SOURCE, ...ciUrl !== void 0 ? { ciUrl } : {}, ...ciCommit(ci) }
1757
2006
  },