@plune-ai/playwright 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -34,6 +34,7 @@ __export(src_exports, {
34
34
  });
35
35
  module.exports = __toCommonJS(src_exports);
36
36
  var import_node_fs = require("fs");
37
+ var import_node_path = require("path");
37
38
  var import_node_util = require("util");
38
39
 
39
40
  // ../../dist/reporter-core.js
@@ -44,16 +45,20 @@ var import_util = require("util");
44
45
  var import_fs2 = require("fs");
45
46
  var import_os = require("os");
46
47
  var import_path2 = require("path");
48
+ var import_fs3 = require("fs");
49
+ var import_stream = require("stream");
47
50
  var import_http = require("http");
48
51
  var import_https = require("https");
49
52
  var path = __toESM(require("path"), 1);
50
- var import_fs3 = require("fs");
53
+ var import_fs4 = require("fs");
51
54
  var import_os2 = require("os");
52
55
  var import_path3 = require("path");
53
56
  var import_util2 = require("util");
57
+ var import_crypto2 = require("crypto");
58
+ var import_fs5 = require("fs");
54
59
  var fs = __toESM(require("fs"), 1);
55
60
  var path2 = __toESM(require("path"), 1);
56
- var import_crypto2 = require("crypto");
61
+ var import_crypto3 = require("crypto");
57
62
  var DEFAULT_API_URL = "https://beta-api.plune.ai";
58
63
  function resolveApiUrl(explicit) {
59
64
  const raw = explicit ?? process.env["PLUNE_API_URL"] ?? DEFAULT_API_URL;
@@ -73,20 +78,32 @@ function loadToken() {
73
78
  return null;
74
79
  }
75
80
  }
76
- var RETRY_DELAYS_MS = [300, 900];
81
+ var BACKOFF_BASE_MS = 300;
82
+ var BACKOFF_CAP_MS = 1e4;
83
+ var DEFAULT_RETRIES = 2;
84
+ var RETRY_AFTER_CAP_MS = 6e4;
85
+ function parseRetryAfter(raw, now = Date.now()) {
86
+ const text = raw?.trim();
87
+ if (text === void 0 || text === "") return null;
88
+ const seconds = /^\d+(\.\d+)?$/.test(text) ? Number(text) : (Date.parse(text) - now) / 1e3;
89
+ if (!Number.isFinite(seconds)) return null;
90
+ return Math.min(Math.max(seconds, 0) * 1e3, RETRY_AFTER_CAP_MS);
91
+ }
92
+ var POOLS = { "http:": new import_http.Agent({ keepAlive: true }), "https:": new import_https.Agent({ keepAlive: true }) };
77
93
  var IDLE_MS = 3e5;
78
94
  function nodeTransport(url, init, idleMs = IDLE_MS) {
79
- return new Promise((resolve2, reject) => {
95
+ return new Promise((resolve22, reject) => {
80
96
  const target = new URL(url);
81
97
  const send = target.protocol === "https:" ? import_https.request : import_http.request;
82
- const req = send(target, { method: init.method, headers: init.headers }, (res) => {
98
+ const agent = POOLS[target.protocol === "https:" ? "https:" : "http:"];
99
+ const req = send(target, { method: init.method, headers: init.headers, agent }, (res) => {
83
100
  const chunks = [];
84
101
  res.on("data", (chunk2) => chunks.push(chunk2));
85
102
  res.on("error", reject);
86
103
  res.on("end", () => {
87
104
  const status = res.statusCode ?? 0;
88
105
  const text = Buffer.concat(chunks).toString("utf8");
89
- resolve2({
106
+ resolve22({
90
107
  ok: status >= 200 && status <= 299,
91
108
  status,
92
109
  headers: {
@@ -104,20 +121,60 @@ function nodeTransport(url, init, idleMs = IDLE_MS) {
104
121
  req.end(init.body);
105
122
  });
106
123
  }
124
+ var withoutLength = (headers) => Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== "content-length"));
125
+ function nodePut(url, headers, source, idleMs) {
126
+ return new Promise((resolve22, reject) => {
127
+ const target = new URL(url);
128
+ const send = target.protocol === "https:" ? import_https.request : import_http.request;
129
+ const length = "body" in source ? source.body.length : source.size;
130
+ let answered;
131
+ const settle = (err) => answered !== void 0 ? resolve22(answered) : reject(err);
132
+ const req = send(
133
+ target,
134
+ { method: "PUT", headers: { ...withoutLength(headers), "content-length": String(length) } },
135
+ (res) => {
136
+ const retry = res.headers["retry-after"];
137
+ answered = { status: res.statusCode ?? 0, retryAfter: Array.isArray(retry) ? retry[0] ?? null : retry ?? null };
138
+ res.on("error", settle);
139
+ res.on("close", () => {
140
+ resolve22(answered);
141
+ req.destroy();
142
+ });
143
+ res.resume();
144
+ }
145
+ );
146
+ req.setTimeout(idleMs, () => req.destroy(Object.assign(new Error("idle"), { code: "ETIMEDOUT" })));
147
+ req.on("error", settle);
148
+ if ("body" in source) req.end(source.body);
149
+ else (0, import_stream.pipeline)((0, import_fs3.createReadStream)(source.path), req, (err) => err ? settle(err) : void 0);
150
+ });
151
+ }
152
+ var codeOfError = (err) => {
153
+ const code = err?.code;
154
+ return typeof code === "string" && /^[A-Z0-9_]{2,40}$/.test(code) ? code : "network";
155
+ };
107
156
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
108
157
  async function detailOf(res) {
109
158
  try {
110
159
  const body = await res.json();
111
- return typeof body.error === "string" ? body.error : "";
160
+ const q = body.quota;
161
+ return {
162
+ ...typeof body.shardsExpected === "number" && Number.isInteger(body.shardsExpected) ? { shardsExpected: body.shardsExpected } : {},
163
+ detail: typeof body.error === "string" ? body.error : "",
164
+ ...typeof q === "object" && q !== null && !Array.isArray(q) ? { quota: q } : {},
165
+ ...typeof body.code === "string" && /^[a-z0-9_]{1,60}$/.test(body.code) ? { code: body.code } : {}
166
+ };
112
167
  } catch {
113
- return "";
168
+ return { detail: "" };
114
169
  }
115
170
  }
116
- function retryAfterMs(res) {
117
- const raw = res.headers.get("retry-after");
118
- if (raw === null) return null;
119
- const seconds = Number(raw.trim());
120
- return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1e3 : null;
171
+ function describeQuota(q) {
172
+ const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
173
+ const kind = typeof q["kind"] === "string" ? q["kind"].slice(0, 60) : "limit";
174
+ const [used, limit] = [num(q["used"]), num(q["limit"])];
175
+ const parts = [used !== void 0 && limit !== void 0 ? `${kind}: ${used} of ${limit} used` : kind];
176
+ if (typeof q["resetsAt"] === "string" && q["resetsAt"] !== "") parts.push(`resets ${q["resetsAt"].slice(0, 40)}`);
177
+ return parts.join(", ");
121
178
  }
122
179
  function classify(status) {
123
180
  if (status === 401 || status === 403) return "auth";
@@ -129,15 +186,34 @@ function classify(status) {
129
186
  function createClient(opts) {
130
187
  const doFetch = opts.fetchImpl ?? nodeTransport;
131
188
  const wait = opts.wait ?? sleep;
189
+ const uploadRetries = opts.uploadRetries === void 0 ? void 0 : Math.max(0, Math.floor(opts.uploadRetries));
190
+ const random = opts.random ?? Math.random;
191
+ const now = opts.now ?? Date.now;
192
+ let pausedUntil = 0;
193
+ const jittered = (ms) => Math.round(ms * (1 + random() * 0.5));
194
+ async function backOff(attempt, said) {
195
+ opts.onRetry?.();
196
+ const ms = jittered(said ?? Math.min(BACKOFF_BASE_MS * 2 ** attempt, BACKOFF_CAP_MS));
197
+ const until = now() + ms;
198
+ pausedUntil = Math.max(pausedUntil, until);
199
+ await wait(ms);
200
+ return until;
201
+ }
202
+ async function respectPause(mine) {
203
+ const left = pausedUntil - now();
204
+ if (pausedUntil > mine && left > 0) await wait(left + Math.round(random() * 250));
205
+ }
132
206
  const base = opts.apiUrl.replace(/\/+$/, "");
133
207
  const scrub = (text) => opts.token === "" ? text : text.split(opts.token).join("***");
134
- async function send(method, path3, payload) {
208
+ async function send(method, path3, payload, retries = DEFAULT_RETRIES) {
135
209
  let last = {
136
210
  kind: "unavailable",
137
211
  status: null,
138
212
  detail: "no attempt was made"
139
213
  };
140
- for (let attempt = 0; attempt <= RETRY_DELAYS_MS.length; attempt += 1) {
214
+ let mine = 0;
215
+ for (let attempt = 0; attempt <= retries; attempt += 1) {
216
+ await respectPause(mine);
141
217
  let res;
142
218
  try {
143
219
  res = await doFetch(`${base}${path3}`, {
@@ -150,7 +226,8 @@ function createClient(opts) {
150
226
  });
151
227
  } catch (err) {
152
228
  last = { kind: "unavailable", status: null, detail: scrub(String(err)) };
153
- if (attempt < RETRY_DELAYS_MS.length) await wait(RETRY_DELAYS_MS[attempt]);
229
+ if (attempt >= Math.min(retries, DEFAULT_RETRIES)) break;
230
+ mine = await backOff(attempt, null);
154
231
  continue;
155
232
  }
156
233
  if (res.ok) {
@@ -161,23 +238,76 @@ function createClient(opts) {
161
238
  return { ok: false, kind: "other", status: res.status, detail: "the answer was not JSON" };
162
239
  }
163
240
  }
164
- const detail = scrub(await detailOf(res));
241
+ const said = await detailOf(res);
165
242
  const kind = classify(res.status);
166
- last = { kind, status: res.status, detail };
243
+ last = { kind, status: res.status, detail: scrub(said.detail), ...said.code !== void 0 ? { code: said.code } : {}, ...said.shardsExpected !== void 0 ? { shardsExpected: said.shardsExpected } : {} };
167
244
  if (kind !== "unavailable") break;
168
- if (attempt < RETRY_DELAYS_MS.length) {
169
- await wait(retryAfterMs(res) ?? RETRY_DELAYS_MS[attempt]);
245
+ const said429 = parseRetryAfter(res.headers.get("retry-after"), now());
246
+ if (res.status === 429 && (said.quota !== void 0 || said429 === null)) {
247
+ last.kind = "invalid";
248
+ last.detail = `quota exceeded (${said.quota === void 0 ? "no Retry-After" : scrub(describeQuota(said.quota))})`;
249
+ if (said.detail) last.detail += ` \u2014 ${scrub(said.detail)}`;
250
+ break;
170
251
  }
252
+ if (attempt >= (said429 === null ? Math.min(retries, DEFAULT_RETRIES) : retries)) break;
253
+ mine = await backOff(attempt, said429);
171
254
  }
172
255
  return { ok: false, ...last };
173
256
  }
174
257
  return {
175
- post: (path3, body) => send("POST", path3, { body: JSON.stringify(body), type: "application/json" }),
176
- upload: (path3, bytes, contentType) => send("POST", path3, { body: bytes, type: contentType }),
177
- del: (path3) => send("DELETE", path3)
258
+ post: (path3, body, retries) => send("POST", path3, { body: JSON.stringify(body), type: "application/json" }, retries),
259
+ upload: (path3, bytes, contentType) => send("POST", path3, { body: bytes, type: contentType }, uploadRetries ?? DEFAULT_RETRIES),
260
+ del: (path3) => send("DELETE", path3),
261
+ get: (path3) => send("GET", path3),
262
+ async put(url, headers, source) {
263
+ const putRetries = uploadRetries ?? 3;
264
+ let last = { ok: false, status: null, code: "network" };
265
+ let mine = 0;
266
+ for (let attempt = 0; attempt <= putRetries; attempt += 1) {
267
+ await respectPause(mine);
268
+ try {
269
+ let status;
270
+ let retryAfter;
271
+ if (opts.fetchImpl === void 0) ({ status, retryAfter } = await nodePut(url, headers, source, IDLE_MS));
272
+ else {
273
+ const body = "body" in source ? source.body : await (0, import_fs3.openAsBlob)(source.path);
274
+ const res = await opts.fetchImpl(url, { method: "PUT", headers: withoutLength(headers), body });
275
+ await res.arrayBuffer().catch(() => void 0);
276
+ status = res.status;
277
+ retryAfter = res.headers.get("retry-after");
278
+ }
279
+ if (status >= 200 && status <= 299) return { ok: true };
280
+ last = { ok: false, status, code: `bucket_${status}` };
281
+ if (status < 500 && status !== 429) return last;
282
+ const said = parseRetryAfter(retryAfter, now());
283
+ if (attempt >= (said === null ? Math.min(putRetries, 3) : putRetries)) return last;
284
+ mine = await backOff(attempt, said);
285
+ continue;
286
+ } catch (err) {
287
+ last = { ok: false, status: null, code: codeOfError(err) };
288
+ }
289
+ if (attempt >= Math.min(putRetries, 3)) return last;
290
+ mine = await backOff(attempt, null);
291
+ }
292
+ return last;
293
+ }
178
294
  };
179
295
  }
180
296
  var UNSUPPORTED_VARS = ["PLUNE_GROUP"];
297
+ var SHARDS_MAX = 1e3;
298
+ function shardOf(env) {
299
+ const raw = value(env, "PLUNE_SHARD");
300
+ if (raw === void 0) return {};
301
+ const m = /^(\d{1,4})\/(\d{1,4})$/.exec(raw);
302
+ const [k, n] = m ? [Number(m[1]), Number(m[2])] : [0, 0];
303
+ if (k >= 1 && k <= n && n <= SHARDS_MAX) return { shard: { index: k, total: n } };
304
+ return {
305
+ error: `PLUNE_SHARD=${JSON.stringify(raw.slice(0, 40))} is not "k/N" with 1 <= k <= N <= ${SHARDS_MAX} (for example 2/4) - nothing was sent.`
306
+ };
307
+ }
308
+ var UPLOAD_CONCURRENCY = { min: 1, max: 32, default: 16 };
309
+ var UPLOAD_RETRIES = { min: 0, max: 20, default: 6 };
310
+ var IMPORT_TIMEOUT = { min: 0, max: 86400, default: 600 };
181
311
  function value(env, name) {
182
312
  const raw = env[name]?.trim();
183
313
  return raw === void 0 || raw === "" ? void 0 : raw;
@@ -192,6 +322,14 @@ function count(env, name) {
192
322
  const n = Number(raw);
193
323
  return Number.isInteger(n) && n > 0 ? n : void 0;
194
324
  }
325
+ function bounded(env, name, range, warnings) {
326
+ const raw = value(env, name);
327
+ if (raw === void 0) return void 0;
328
+ const n = Number(raw);
329
+ if (/^\d+$/.test(raw) && n >= range.min && n <= range.max) return n;
330
+ warnings.push(`${name}=${JSON.stringify(raw.slice(0, 40))} is not a whole number from ${range.min} to ${range.max} \u2014 using ${range.default}.`);
331
+ return void 0;
332
+ }
195
333
  function list(env, name) {
196
334
  const raw = value(env, name);
197
335
  if (raw === void 0) return void 0;
@@ -204,11 +342,16 @@ function readEnv(env = process.env) {
204
342
  const apiUrl = value(env, "PLUNE_API_URL");
205
343
  const fallbackPath = value(env, "PLUNE_FALLBACK");
206
344
  const batchSize = count(env, "PLUNE_BATCH_SIZE");
345
+ const warnings = [];
346
+ const uploadConcurrency = bounded(env, "PLUNE_UPLOAD_CONCURRENCY", UPLOAD_CONCURRENCY, warnings);
347
+ const uploadRetries = bounded(env, "PLUNE_UPLOAD_RETRIES", UPLOAD_RETRIES, warnings);
348
+ const importTimeout = bounded(env, "PLUNE_IMPORT_TIMEOUT", IMPORT_TIMEOUT, warnings);
207
349
  const title = value(env, "PLUNE_RUN_TITLE");
208
350
  const environment = value(env, "PLUNE_ENV");
209
351
  const labels = list(env, "PLUNE_LABELS");
210
352
  const offerDiscovered = flag(env, "PLUNE_CREATE");
211
353
  const full = flag(env, "PLUNE_FULL_RUN");
354
+ const { shard, error: shardError } = shardOf(env);
212
355
  return {
213
356
  config: {
214
357
  ...externalKey !== void 0 ? { externalKey } : {},
@@ -216,6 +359,8 @@ function readEnv(env = process.env) {
216
359
  ...apiUrl !== void 0 ? { apiUrl } : {},
217
360
  ...fallbackPath !== void 0 ? { fallbackPath } : {},
218
361
  ...batchSize !== void 0 ? { batchSize } : {},
362
+ ...uploadConcurrency !== void 0 ? { uploadConcurrency } : {},
363
+ ...uploadRetries !== void 0 ? { uploadRetries } : {},
219
364
  ...title !== void 0 ? { title } : {},
220
365
  ...environment !== void 0 ? { environment } : {},
221
366
  ...labels !== void 0 ? { labels } : {},
@@ -227,8 +372,14 @@ function readEnv(env = process.env) {
227
372
  // Two names for two situations that end the same way. `SHARED_RUN` says other processes are
228
373
  // reporting into this run; `PROCEED` says the job will close it on its own schedule. Either
229
374
  // way this process must not be the one to call it finished.
230
- keepOpen: flag(env, "PLUNE_SHARED_RUN") || flag(env, "PLUNE_PROCEED"),
231
- ignored: UNSUPPORTED_VARS.filter((name) => value(env, name) !== void 0)
375
+ // `PLUNE_SHARD` implies it: the run is joined by the shared key and this process does not close it
376
+ // by itself; `leaveOpen` reports the shard instead.
377
+ keepOpen: flag(env, "PLUNE_SHARED_RUN") || flag(env, "PLUNE_PROCEED") || shard !== void 0 || shardError !== void 0,
378
+ ...shard !== void 0 ? { shard } : {},
379
+ ...shardError !== void 0 ? { shardError } : {},
380
+ ...importTimeout !== void 0 ? { importTimeout } : {},
381
+ ignored: UNSUPPORTED_VARS.filter((name) => value(env, name) !== void 0),
382
+ warnings
232
383
  };
233
384
  }
234
385
  function defaultRunTitle(env = process.env, now = /* @__PURE__ */ new Date(), cwd = process.cwd()) {
@@ -278,14 +429,22 @@ function failureOf(attempt, home = (0, import_os2.homedir)()) {
278
429
  }
279
430
  function repoRootOf(dir, stopAt) {
280
431
  for (let here = (0, import_path3.resolve)(dir); ; here = (0, import_path3.dirname)(here)) {
281
- if ((0, import_fs3.existsSync)((0, import_path3.join)(here, ".git"))) return here;
432
+ if ((0, import_fs4.existsSync)((0, import_path3.join)(here, ".git"))) return here;
282
433
  if (here === stopAt || (0, import_path3.dirname)(here) === here) return void 0;
283
434
  }
284
435
  }
285
- function errorContextOf(attempt, home = (0, import_os2.homedir)()) {
436
+ function errorContextFields(attempt, home = (0, import_os2.homedir)()) {
437
+ const { text, omitted: omitted2 } = cutErrorContext(attempt, home);
438
+ return {
439
+ ...text !== "" ? { errorContext: text } : {},
440
+ ...omitted2 > 0 ? { errorContextOmitted: omitted2 } : {}
441
+ };
442
+ }
443
+ function cutErrorContext(attempt, home) {
286
444
  const text = attempt.errors.map((e) => e.text).filter((t) => t !== "").join("\n\n");
287
445
  return cut(machineless(text, attempt.repoRoot, home));
288
446
  }
447
+ var printable = (text) => text.replace(/[\u0000-\u001f\u007f-\u009f]/g, "?");
289
448
  var mediaTypeOf = (contentType) => contentType?.split(";")[0]?.trim().toLowerCase() || void 0;
290
449
  var TEXT_TYPES = /* @__PURE__ */ new Set(["application/json", "text/plain"]);
291
450
  var isTextType = (contentType) => TEXT_TYPES.has(mediaTypeOf(contentType) ?? "");
@@ -317,7 +476,7 @@ function pathIn(path3) {
317
476
  }
318
477
  var fileNameOf = (name) => /^(?:file:\/\/|[\\/]|~[\\/]|[A-Za-z]:[\\/])/.test(name) ? name.split(/[\\/]/).pop() ?? "" : name;
319
478
  function cut(text) {
320
- if (jsonBytes(text) <= TEXT_LIMIT) return text;
479
+ if (jsonBytes(text) <= TEXT_LIMIT) return { text, omitted: 0 };
321
480
  const lines = text.split("\n");
322
481
  const size = lines.map((line) => jsonBytes(line) + 2);
323
482
  const budget = TEXT_LIMIT - jsonBytes(omitted(lines.length));
@@ -326,7 +485,8 @@ function cut(text) {
326
485
  let tail = lines.length;
327
486
  while (head < tail && used + size[head] <= budget / 2) used += size[head++];
328
487
  while (tail > head && used + size[tail - 1] <= budget) used += size[--tail];
329
- return [...lines.slice(0, head), omitted(tail - head), ...lines.slice(tail)].join("\n");
488
+ const kept = [...lines.slice(0, head), ...lines.slice(tail)].join("\n");
489
+ return { text: [...lines.slice(0, head), omitted(tail - head), ...lines.slice(tail)].join("\n"), omitted: text.length - kept.length };
330
490
  }
331
491
  var omitted = (lines) => `\u2026[omitted ${lines} lines]\u2026`;
332
492
  var METADATA_TYPE = "application/plune.metadata+json";
@@ -384,6 +544,23 @@ function fromRoot(place, root) {
384
544
  function webLink(href) {
385
545
  return href !== void 0 && /^https?:\/\//i.test(href) && URL.canParse(href) ? href : void 0;
386
546
  }
547
+ var FILES_BATCH_MAX = 100;
548
+ var DIRECT_BATCH_BYTES = 6 * 1024 * 1024;
549
+ var BATCH_PIPELINES = 2;
550
+ async function sha256File(path3) {
551
+ const hash = (0, import_crypto2.createHash)("sha256");
552
+ for await (const part of (0, import_fs5.createReadStream)(path3)) hash.update(part);
553
+ return hash.digest("hex");
554
+ }
555
+ var sha256Bytes = (bytes) => (0, import_crypto2.createHash)("sha256").update(bytes).digest("hex");
556
+ var BUCKET_CODES = /* @__PURE__ */ new Set([
557
+ "bucket_unreachable",
558
+ "not_connected",
559
+ "platform_not_configured",
560
+ "upload_expired",
561
+ "file_mismatch",
562
+ "file_missing"
563
+ ]);
387
564
  var DEFAULT_FALLBACK_PATH = path2.join(".plune", "pending-results.jsonl");
388
565
  function appendBatch(file, batch) {
389
566
  fs.mkdirSync(path2.dirname(file), { recursive: true });
@@ -401,7 +578,8 @@ function appendBatch(file, batch) {
401
578
  var RESOLVE_CHUNK = 500;
402
579
  var BATCH_MAX = 500;
403
580
  var DISCOVER_MAX = 500;
404
- var BATCH_DEFAULT = 100;
581
+ var BATCH_DEFAULT = 500;
582
+ var SEND_CONCURRENCY = 4;
405
583
  var EXPECTED_MAX = 1e4;
406
584
  var KEY_MAX = 1024;
407
585
  var TITLE_MAX = 300;
@@ -418,7 +596,7 @@ var TYPE_BY_EXTENSION = {
418
596
  ".jpeg": "image/jpeg",
419
597
  ".webp": "image/webp"
420
598
  };
421
- var UPLOADS_AT_ONCE = 4;
599
+ var METADATA_TYPE2 = "application/plune.metadata+json";
422
600
  var NAME_MAX = 200;
423
601
  function nameOf(file) {
424
602
  const own = file.name.split(/[\\/]/).pop()?.trim() || (file.path === void 0 ? "" : (0, import_path.basename)(file.path));
@@ -443,15 +621,26 @@ var SKIPPED = {
443
621
  textSize: "Plune takes a text file of at most 512 KiB",
444
622
  empty: "the file is empty",
445
623
  binary: "the file holds a NUL byte, and Plune takes UTF-8 text without one",
446
- encoding: "Plune takes UTF-8 text only"
624
+ encoding: "Plune takes UTF-8 text only",
625
+ noStorage: "no storage bucket is connected to this project"
447
626
  };
627
+ var BUCKET_FOUND = "plune: storage bucket found for this project \u2014 screenshots, text, trace and video go straight to it over short-lived links.";
448
628
  var KINDS = {
449
629
  screenshot: { label: "screenshot", bytes: SCREENSHOT_BYTES, room: SCREENSHOTS_PER_RESULT, limit: "limit", size: "size" },
450
- text: { label: "text file", bytes: TEXT_BYTES, room: TEXTS_PER_RESULT, limit: "textLimit", size: "textSize" }
630
+ text: { label: "text file", bytes: TEXT_BYTES, room: TEXTS_PER_RESULT, limit: "textLimit", size: "textSize" },
631
+ // Only the label is used: a file of this kind has no home in the database, so no ceiling of its own is known here.
632
+ file: { label: "file", bytes: 0, room: 0, limit: "limit", size: "size" }
451
633
  };
452
634
  function kindOf(type) {
453
635
  if (type.startsWith("image/")) return "screenshot";
454
- return TEXT_TYPES.has(type) ? "text" : void 0;
636
+ return TEXT_TYPES.has(type) ? "text" : "file";
637
+ }
638
+ var codeOf = (out) => out.code ?? (out.status === null ? "network" : `http_${out.status}`);
639
+ function linkOf(item) {
640
+ const link = item;
641
+ if (typeof link?.id !== "string" || typeof link.url !== "string") return void 0;
642
+ const headers = typeof link.headers === "object" && link.headers !== null ? link.headers : {};
643
+ return { id: link.id, url: link.url, headers };
455
644
  }
456
645
  function textTypeOf(contentType, type) {
457
646
  const charset = /;\s*charset\s*=\s*"?([^\s";]+)"?/i.exec(contentType)?.[1];
@@ -528,6 +717,7 @@ function warnIfDropped(sent, run, log) {
528
717
  }
529
718
  async function startRun(passed, declared2) {
530
719
  const env = readEnv();
720
+ if (env.shardError !== void 0) throw new Error(env.shardError);
531
721
  const stated = Object.fromEntries(Object.entries(passed).filter(([, v]) => v !== void 0));
532
722
  const cfg = { ...env.config, ...stated };
533
723
  const log = cfg.log ?? ((line) => void process.stderr.write(`${line}
@@ -538,9 +728,18 @@ async function startRun(passed, declared2) {
538
728
  const batchSize = Math.min(cfg.batchSize ?? BATCH_DEFAULT, BATCH_MAX);
539
729
  const offerDiscovered = cfg.offerDiscovered ?? false;
540
730
  const token = cfg.token ?? loadToken() ?? "";
731
+ const uploadsAtOnce = Math.min(Math.max(Math.floor(cfg.uploadConcurrency ?? UPLOAD_CONCURRENCY.default), UPLOAD_CONCURRENCY.min), UPLOAD_CONCURRENCY.max);
732
+ const uploadRetries = Math.min(Math.max(Math.floor(cfg.uploadRetries ?? UPLOAD_RETRIES.default), UPLOAD_RETRIES.min), UPLOAD_RETRIES.max);
733
+ let retried = 0;
734
+ let uploadMs = 0;
735
+ let requests = 0;
736
+ let existed = 0;
737
+ let batchMissing = false;
541
738
  const client = createClient({
542
739
  apiUrl: resolveApiUrl(cfg.apiUrl),
543
740
  token,
741
+ uploadRetries,
742
+ onRetry: () => void (retried += 1),
544
743
  ...cfg.fetchImpl !== void 0 ? { fetchImpl: cfg.fetchImpl } : {}
545
744
  });
546
745
  const stats = {
@@ -554,18 +753,28 @@ async function startRun(passed, declared2) {
554
753
  unoffered: 0,
555
754
  deferred: 0,
556
755
  screenshots: { uploaded: 0, skipped: 0, failed: 0 },
557
- textFiles: { uploaded: 0, skipped: 0, failed: 0 }
756
+ textFiles: { uploaded: 0, skipped: 0, failed: 0 },
757
+ otherFiles: { uploaded: 0, skipped: 0, failed: 0 }
558
758
  };
559
759
  const resolved = /* @__PURE__ */ new Map();
560
760
  let buffer = [];
561
761
  const discoveries = /* @__PURE__ */ new Map();
762
+ const held = /* @__PURE__ */ new Map();
763
+ let createdWithResult = 0;
764
+ let createdUndelivered = 0;
562
765
  let runId = null;
563
766
  let joined = false;
564
767
  let offline = token === "";
565
768
  let done = false;
566
769
  const shortened = /* @__PURE__ */ new Set();
567
770
  const skipsSaid = /* @__PURE__ */ new Set();
568
- const countsOf = (kind) => kind === "text" ? stats.textFiles : stats.screenshots;
771
+ const countsOf = (kind) => kind === "text" ? stats.textFiles : kind === "file" ? stats.otherFiles : stats.screenshots;
772
+ let bucketSeen = false;
773
+ let noStorage = 0;
774
+ let uploadsMissing = false;
775
+ const failedSaid = /* @__PURE__ */ new Set();
776
+ const codesSaid = /* @__PURE__ */ new Set();
777
+ const rooms = /* @__PURE__ */ new Map();
569
778
  function bound(keys) {
570
779
  return keys.map((key) => {
571
780
  const fit = boundKey(key);
@@ -573,7 +782,7 @@ async function startRun(passed, declared2) {
573
782
  shortened.add(key.value);
574
783
  if (shortened.size === 1) {
575
784
  log(
576
- `plune: a test name longer than ${KEY_MAX} characters was shortened to fit its key \u2014 "${key.value.slice(0, 80)}\u2026". Give the test a shorter name; until then this is its identity.`
785
+ `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.`
577
786
  );
578
787
  }
579
788
  }
@@ -584,6 +793,7 @@ async function startRun(passed, declared2) {
584
793
  if (offline) {
585
794
  log('plune: no API token \u2014 run "plune login" first. Results will be written to the fallback file.');
586
795
  }
796
+ for (const warning of env.warnings) log(`plune: ${warning}`);
587
797
  if (env.ignored.length > 0) {
588
798
  log(`plune: ignoring ${env.ignored.join(", ")} \u2014 a run has nowhere to store them yet.`);
589
799
  }
@@ -636,7 +846,7 @@ async function startRun(passed, declared2) {
636
846
  ...cfg.environment !== void 0 ? { environment: cfg.environment } : {},
637
847
  ...cfg.labels !== void 0 ? { labels: cfg.labels } : {}
638
848
  };
639
- const start = await client.post("/v1/runs", {
849
+ const request = {
640
850
  schemaVersion: 2,
641
851
  kind: cfg.kind ?? "automated",
642
852
  ...externalKey !== null ? { externalKey } : {},
@@ -647,7 +857,14 @@ async function startRun(passed, declared2) {
647
857
  // a person will miss, and a deployment older than the field must not be nagged on every run.
648
858
  title: defaultRunTitle(),
649
859
  ...described
650
- });
860
+ };
861
+ let start = await client.post("/v1/runs", request);
862
+ if (!start.ok && start.status === 413 && configuration !== void 0) {
863
+ log(
864
+ `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.`
865
+ );
866
+ start = await client.post("/v1/runs", { ...request, configuration: void 0 });
867
+ }
651
868
  if (start.ok && typeof start.body?.run?.id === "string") {
652
869
  runId = start.body.run.id;
653
870
  joined = start.status === 200;
@@ -680,6 +897,7 @@ async function startRun(passed, declared2) {
680
897
  specRef: result.specRef,
681
898
  rawStatus: result.rawStatus
682
899
  });
900
+ held.set(result.keys[0].value, result);
683
901
  }
684
902
  async function offer() {
685
903
  if (discoveries.size === 0 || offline || runId === null) return;
@@ -698,24 +916,71 @@ async function startRun(passed, declared2) {
698
916
  return;
699
917
  }
700
918
  stats.offered += out.body.results.filter((r) => r?.outcome === "queued").length;
701
- stats.created += out.body.results.filter((r) => r?.outcome === "created").length;
919
+ const made = out.body.results.filter((r) => r?.outcome === "created");
920
+ stats.created += made.length;
921
+ const submissions = [];
922
+ const filesByKey = /* @__PURE__ */ new Map();
923
+ for (const r of made) {
924
+ const pending = typeof r.id === "string" && r.id !== "" ? held.get(r.key?.value) : void 0;
925
+ if (pending === void 0) continue;
926
+ held.delete(r.key.value);
927
+ const { keys: _keys, files, ...rest } = pending;
928
+ submissions.push({ ...rest, testCaseId: r.id });
929
+ if (files !== void 0) filesByKey.set(pending.resultKey, files);
930
+ }
931
+ if (submissions.length > 0) {
932
+ const before = stats.deferred;
933
+ await send(submissions, filesByKey);
934
+ createdWithResult += submissions.length;
935
+ createdUndelivered += stats.deferred - before;
936
+ }
702
937
  }
703
938
  }
704
939
  function skip(kind, name, why) {
705
940
  countsOf(kind).skipped += 1;
706
- if (skipsSaid.has(`${kind}/${why}`)) return;
707
- skipsSaid.add(`${kind}/${why}`);
708
- log(`plune: ${KINDS[kind].label} "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
941
+ if (why === "noStorage") noStorage += 1;
942
+ const said = why === "noStorage" ? why : `${kind}/${why}`;
943
+ if (skipsSaid.has(said)) return;
944
+ skipsSaid.add(said);
945
+ if (why === "noStorage") log(`plune: "${name}" not stored \u2014 ${SKIPPED[why]}.`);
946
+ else log(`plune: ${KINDS[kind].label} "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
947
+ }
948
+ function ask(job, size) {
949
+ requests += 1;
950
+ return client.post(`/v1/results/${encodeURIComponent(job.id)}/files/uploads`, {
951
+ files: [{ name: job.name, contentType: job.type, size }]
952
+ }, uploadRetries);
953
+ }
954
+ function failed(job, why) {
955
+ countsOf(job.kind).failed += 1;
956
+ if (!failedSaid.has(job.kind)) {
957
+ failedSaid.add(job.kind);
958
+ log(`plune: could not upload a ${KINDS[job.kind].label} (${why}) \u2014 its result is reported without it.`);
959
+ }
960
+ }
961
+ function failedToBucket(job, code) {
962
+ countsOf(job.kind).failed += 1;
963
+ if (codesSaid.has(code)) return;
964
+ codesSaid.add(code);
965
+ log(`plune: "${job.name}" not uploaded to your bucket (${code}) \u2014 its result is reported without it.`);
709
966
  }
710
- async function uploadOne(job) {
967
+ function refusedHere(job, size) {
968
+ if (job.kind === "screenshot") {
969
+ if (!SCREENSHOT_TYPES.has(job.type)) return "type";
970
+ if (size > SCREENSHOT_BYTES) return "size";
971
+ }
972
+ if (job.kind === "text" && size > TEXT_BYTES) return "textSize";
973
+ return void 0;
974
+ }
975
+ async function uploadDirect(job, size) {
711
976
  const { kind } = job;
712
- const { label, bytes: ceiling, size } = KINDS[kind];
977
+ if (kind === "file") return skip(kind, job.name, "noStorage");
978
+ const { bytes: ceiling, size: tooBig } = KINDS[kind];
979
+ if (size > ceiling) return skip(kind, job.name, tooBig);
713
980
  let bytes;
714
981
  if (job.body !== void 0) bytes = job.body;
715
- else if (job.path === void 0) return skip(kind, job.name, "missing");
716
982
  else {
717
983
  try {
718
- if ((await import_fs.promises.stat(job.path)).size > ceiling) return skip(kind, job.name, size);
719
984
  bytes = await import_fs.promises.readFile(job.path);
720
985
  } catch {
721
986
  return skip(kind, job.name, "missing");
@@ -723,37 +988,342 @@ async function startRun(passed, declared2) {
723
988
  }
724
989
  const refusal = kind === "text" ? textRefusal(bytes) : void 0;
725
990
  if (refusal !== void 0) return skip(kind, job.name, refusal);
991
+ requests += 1;
726
992
  const out = await client.upload(
727
993
  `/v1/results/${encodeURIComponent(job.id)}/files?name=${encodeURIComponent(job.name)}`,
728
994
  bytes,
729
995
  job.type
730
996
  );
731
- const counts = countsOf(kind);
732
- if (out.ok) {
733
- counts.uploaded += 1;
997
+ if (out.ok) countsOf(kind).uploaded += 1;
998
+ else failed(job, out.detail || out.kind);
999
+ }
1000
+ async function uploadToBucket(job, size, first) {
1001
+ const source = job.body !== void 0 ? { body: job.body } : { path: job.path, size };
1002
+ let link = first;
1003
+ for (let renewed = false; ; ) {
1004
+ const put = await client.put(link.url, link.headers, source);
1005
+ if (put.ok) break;
1006
+ if (put.status !== 403 || renewed) return failedToBucket(job, put.code);
1007
+ renewed = true;
1008
+ const again = await ask(job, size);
1009
+ if (!again.ok) return failedToBucket(job, codeOf(again));
1010
+ const fresh = linkOf(again.body?.files?.[0]);
1011
+ if (fresh === void 0) return failedToBucket(job, "bad_answer");
1012
+ link = fresh;
1013
+ }
1014
+ requests += 1;
1015
+ const done2 = await client.post(`/v1/files/${encodeURIComponent(link.id)}/complete`, {}, uploadRetries);
1016
+ if (!done2.ok) return failedToBucket(job, codeOf(done2));
1017
+ countsOf(job.kind).uploaded += 1;
1018
+ }
1019
+ let free = uploadsAtOnce;
1020
+ const waiting = [];
1021
+ async function gated(work) {
1022
+ if (free === 0) await new Promise((resolve22) => waiting.push(resolve22));
1023
+ else free -= 1;
1024
+ try {
1025
+ return await work();
1026
+ } finally {
1027
+ const next = waiting.shift();
1028
+ if (next !== void 0) next();
1029
+ else free += 1;
1030
+ }
1031
+ }
1032
+ async function plan(job) {
1033
+ const { kind } = job;
1034
+ let size;
1035
+ if (job.body !== void 0) size = job.body.length;
1036
+ else if (job.path === void 0) return void skip(kind, job.name, "missing");
1037
+ else {
1038
+ try {
1039
+ size = (await import_fs.promises.stat(job.path)).size;
1040
+ } catch {
1041
+ return void skip(kind, job.name, "missing");
1042
+ }
1043
+ }
1044
+ if (size === 0) return void skip(kind, job.name, "empty");
1045
+ const direct = () => {
1046
+ if (kind === "file") return void skip(kind, job.name, "noStorage");
1047
+ const roomKey = `${job.id}/${kind}`;
1048
+ const left = rooms.get(roomKey) ?? KINDS[kind].room;
1049
+ if (left === 0) return void skip(kind, job.name, KINDS[kind].limit);
1050
+ rooms.set(roomKey, left - 1);
1051
+ return () => uploadDirect(job, size);
1052
+ };
1053
+ if (uploadsMissing) return direct();
1054
+ const out = await gated(() => ask(job, size));
1055
+ if (!out.ok) {
1056
+ if (out.status === 404 && out.detail === "" && out.code === void 0) {
1057
+ uploadsMissing = true;
1058
+ return direct();
1059
+ }
1060
+ if (out.code !== void 0) failedToBucket(job, out.code);
1061
+ else failed(job, out.detail || out.kind);
1062
+ return void 0;
1063
+ }
1064
+ const item = out.body?.files?.[0];
1065
+ if (item?.skipped === "no_storage") return void skip(kind, job.name, refusedHere(job, size) ?? "noStorage");
1066
+ if (item?.direct === true) return direct();
1067
+ const link = linkOf(item);
1068
+ if (link === void 0) return void failed(job, "bad_answer");
1069
+ if (!bucketSeen) {
1070
+ bucketSeen = true;
1071
+ log(BUCKET_FOUND);
1072
+ }
1073
+ return () => uploadToBucket(job, size, link);
1074
+ }
1075
+ async function uploadEach(jobs) {
1076
+ const byResult = /* @__PURE__ */ new Map();
1077
+ for (const job of jobs) byResult.set(job.id, [...byResult.get(job.id) ?? [], job]);
1078
+ await Promise.all(
1079
+ [...byResult.values()].map(async (group) => {
1080
+ const work = [];
1081
+ for (const job of group) {
1082
+ const act = await plan(job);
1083
+ if (act !== void 0) work.push(gated(act));
1084
+ }
1085
+ await Promise.all(work);
1086
+ })
1087
+ );
1088
+ }
1089
+ async function measure(job) {
1090
+ let size;
1091
+ if (job.body !== void 0) size = job.body.length;
1092
+ else if (job.path === void 0) return void skip(job.kind, job.name, "missing");
1093
+ else {
1094
+ try {
1095
+ size = (await import_fs.promises.stat(job.path)).size;
1096
+ } catch {
1097
+ return void skip(job.kind, job.name, "missing");
1098
+ }
1099
+ }
1100
+ if (size === 0) return void skip(job.kind, job.name, "empty");
1101
+ return size;
1102
+ }
1103
+ const routeMissing = (out) => !out.ok && out.status === 404 && out.detail === "" && out.code === void 0;
1104
+ function takeRoom(job) {
1105
+ if (job.kind === "file") {
1106
+ skip(job.kind, job.name, "noStorage");
1107
+ return false;
1108
+ }
1109
+ const roomKey = `${job.id}/${job.kind}`;
1110
+ const left = rooms.get(roomKey) ?? KINDS[job.kind].room;
1111
+ if (left === 0) {
1112
+ skip(job.kind, job.name, KINDS[job.kind].limit);
1113
+ return false;
1114
+ }
1115
+ rooms.set(roomKey, left - 1);
1116
+ return true;
1117
+ }
1118
+ function refusedItem(job, size, item) {
1119
+ const code = item.code ?? "refused";
1120
+ if (code === "duplicate") existed += 1;
1121
+ else if (code === "no_storage") skip(job.kind, job.name, refusedHere(job, size) ?? "noStorage");
1122
+ else if (code === "too_many_files") skip(job.kind, job.name, KINDS[job.kind].limit);
1123
+ else if (BUCKET_CODES.has(code)) failedToBucket(job, code);
1124
+ else failed(job, code);
1125
+ }
1126
+ const itemPause = (round) => new Promise((r) => setTimeout(r, Math.min(250 * 2 ** round, 4e3)));
1127
+ async function batchOf(jobs) {
1128
+ if (batchMissing) return uploadEach(jobs);
1129
+ const sized = [];
1130
+ for (const job of jobs) {
1131
+ const size = await measure(job);
1132
+ if (size === void 0) continue;
1133
+ try {
1134
+ sized.push({ job, size, sha256: job.body !== void 0 ? sha256Bytes(job.body) : await sha256File(job.path) });
1135
+ } catch {
1136
+ skip(job.kind, job.name, "missing");
1137
+ }
1138
+ }
1139
+ if (sized.length === 0) return;
1140
+ const announced = await gated(() => {
1141
+ requests += 1;
1142
+ return client.post(
1143
+ "/v1/files/uploads-batch",
1144
+ { items: sized.map((s) => ({ resultId: s.job.id, name: s.job.name, contentType: s.job.type, size: s.size, sha256: s.sha256 })) },
1145
+ uploadRetries
1146
+ );
1147
+ });
1148
+ if (routeMissing(announced)) {
1149
+ batchMissing = true;
1150
+ return uploadEach(sized.map((s) => s.job));
1151
+ }
1152
+ const verdicts = announced.ok ? announced.body?.items : void 0;
1153
+ if (!announced.ok || !Array.isArray(verdicts) || verdicts.length !== sized.length) {
1154
+ for (const s of sized) {
1155
+ if (announced.ok) failed(s.job, "bad_answer");
1156
+ else if (announced.code !== void 0) failedToBucket(s.job, announced.code);
1157
+ else failed(s.job, announced.detail || announced.kind);
1158
+ }
734
1159
  return;
735
1160
  }
736
- counts.failed += 1;
737
- if (counts.failed === 1) {
738
- log(`plune: could not upload a ${label} (${out.detail || out.kind}) \u2014 its result is reported without it.`);
1161
+ const puts = [];
1162
+ const directs = [];
1163
+ sized.forEach((s, i) => {
1164
+ const v = verdicts[i] ?? {};
1165
+ if (v.status === "exists") existed += 1;
1166
+ else if (v.status === "direct") {
1167
+ if (takeRoom(s.job)) directs.push(s);
1168
+ } else if (v.status === "upload") {
1169
+ const link = linkOf(v);
1170
+ if (link === void 0) return failed(s.job, "bad_answer");
1171
+ if (!bucketSeen) {
1172
+ bucketSeen = true;
1173
+ log(BUCKET_FOUND);
1174
+ }
1175
+ puts.push({ s, link });
1176
+ } else if (v.status === "refused") refusedItem(s.job, s.size, v);
1177
+ else failed(s.job, "bad_answer");
1178
+ });
1179
+ const toComplete = [];
1180
+ await Promise.all(
1181
+ puts.map(
1182
+ ({ s, link: first }) => gated(async () => {
1183
+ const source = s.job.body !== void 0 ? { body: s.job.body } : { path: s.job.path, size: s.size };
1184
+ let link = first;
1185
+ for (let renewed = false; ; ) {
1186
+ const put = await client.put(link.url, link.headers, source);
1187
+ if (put.ok) break;
1188
+ if (put.status !== 403 || renewed) return failedToBucket(s.job, put.code);
1189
+ renewed = true;
1190
+ requests += 1;
1191
+ const again = await client.post(
1192
+ "/v1/files/uploads-batch",
1193
+ { items: [{ resultId: s.job.id, name: s.job.name, contentType: s.job.type, size: s.size, sha256: s.sha256 }] },
1194
+ uploadRetries
1195
+ );
1196
+ const fresh = again.ok ? linkOf(again.body?.items?.[0]) : void 0;
1197
+ if (fresh === void 0) return failedToBucket(s.job, again.ok ? "bad_answer" : codeOf(again));
1198
+ link = fresh;
1199
+ }
1200
+ toComplete.push({ job: s.job, id: link.id });
1201
+ })
1202
+ )
1203
+ );
1204
+ await complete(toComplete);
1205
+ await sendDirect(directs);
1206
+ }
1207
+ async function complete(items) {
1208
+ for (let round = 0; items.length > 0; round += 1) {
1209
+ const out = await gated(() => {
1210
+ requests += 1;
1211
+ return client.post("/v1/files/complete-batch", { ids: items.map((i) => i.id) }, uploadRetries);
1212
+ });
1213
+ if (routeMissing(out)) {
1214
+ await Promise.all(
1215
+ items.map(
1216
+ (i) => gated(async () => {
1217
+ requests += 1;
1218
+ const one = await client.post(`/v1/files/${encodeURIComponent(i.id)}/complete`, {}, uploadRetries);
1219
+ if (one.ok) countsOf(i.job.kind).uploaded += 1;
1220
+ else failedToBucket(i.job, codeOf(one));
1221
+ })
1222
+ )
1223
+ );
1224
+ return;
1225
+ }
1226
+ const verdicts = out.ok ? out.body?.items : void 0;
1227
+ if (!out.ok || !Array.isArray(verdicts) || verdicts.length !== items.length) {
1228
+ for (const i of items) failedToBucket(i.job, out.ok ? "bad_answer" : codeOf(out));
1229
+ return;
1230
+ }
1231
+ const again = [];
1232
+ items.forEach((i, at) => {
1233
+ const v = verdicts[at] ?? {};
1234
+ if (v.status === "ready") countsOf(i.job.kind).uploaded += 1;
1235
+ else if (v.retryable === true && round < Math.min(uploadRetries, 3)) again.push(i);
1236
+ else refusedItem(i.job, 0, v.status === "refused" ? v : { code: "bad_answer" });
1237
+ });
1238
+ items = again;
1239
+ if (items.length > 0) {
1240
+ retried += items.length;
1241
+ await itemPause(round);
1242
+ }
739
1243
  }
740
1244
  }
1245
+ async function sendDirect(items) {
1246
+ const groups = [];
1247
+ let bytes = 0;
1248
+ for (const item of items) {
1249
+ const group = groups[groups.length - 1];
1250
+ if (group === void 0 || group.length >= FILES_BATCH_MAX || bytes + item.size > DIRECT_BATCH_BYTES) {
1251
+ groups.push([item]);
1252
+ bytes = item.size;
1253
+ } else {
1254
+ group.push(item);
1255
+ bytes += item.size;
1256
+ }
1257
+ }
1258
+ for (const group of groups) {
1259
+ const body = [];
1260
+ const sent = [];
1261
+ for (const { job, size } of group) {
1262
+ const { kind } = job;
1263
+ if (size > KINDS[kind].bytes) {
1264
+ skip(kind, job.name, KINDS[kind].size);
1265
+ continue;
1266
+ }
1267
+ let data;
1268
+ try {
1269
+ data = job.body ?? await import_fs.promises.readFile(job.path);
1270
+ } catch {
1271
+ skip(kind, job.name, "missing");
1272
+ continue;
1273
+ }
1274
+ const refusal = kind === "text" ? textRefusal(data) : void 0;
1275
+ if (refusal !== void 0) {
1276
+ skip(kind, job.name, refusal);
1277
+ continue;
1278
+ }
1279
+ body.push({ resultId: job.id, name: job.name, contentType: job.type, data: data.toString("base64") });
1280
+ sent.push({ job, size });
1281
+ }
1282
+ if (body.length === 0) continue;
1283
+ const out = await gated(() => {
1284
+ requests += 1;
1285
+ return client.post("/v1/files/direct-batch", { items: body }, uploadRetries);
1286
+ });
1287
+ if (routeMissing(out)) {
1288
+ batchMissing = true;
1289
+ for (const { job, size } of sent) await gated(() => uploadDirect(job, size));
1290
+ continue;
1291
+ }
1292
+ const verdicts = out.ok ? out.body?.items : void 0;
1293
+ if (!out.ok || !Array.isArray(verdicts) || verdicts.length !== sent.length) {
1294
+ for (const { job } of sent) failed(job, out.ok ? "bad_answer" : out.detail || out.kind);
1295
+ continue;
1296
+ }
1297
+ sent.forEach(({ job }, i) => {
1298
+ const v = verdicts[i] ?? {};
1299
+ if (v.status === "stored") countsOf(job.kind).uploaded += 1;
1300
+ else if (v.status === "exists") existed += 1;
1301
+ else refusedItem(job, 0, v.status === "refused" ? v : { code: "bad_answer" });
1302
+ });
1303
+ }
1304
+ }
1305
+ async function uploadBatched(jobs) {
1306
+ const batches = chunk(jobs, FILES_BATCH_MAX);
1307
+ let next = 0;
1308
+ await Promise.all(
1309
+ Array.from({ length: Math.min(BATCH_PIPELINES, batches.length) }, async () => {
1310
+ for (let at = next++; at < batches.length; at = next++) await batchOf(batches[at]);
1311
+ })
1312
+ );
1313
+ }
741
1314
  async function upload(items, filesByKey) {
742
1315
  if (filesByKey.size === 0 || !Array.isArray(items)) return;
743
1316
  const jobs = [];
744
1317
  for (const item of items) {
745
1318
  if (item?.status !== "accepted" || typeof item.id !== "string" || typeof item.resultKey !== "string") continue;
746
- const room = { screenshot: KINDS.screenshot.room, text: KINDS.text.room };
747
1319
  for (const file of filesByKey.get(item.resultKey) ?? []) {
748
1320
  const type = mediaTypeOf(file.contentType) ?? (file.path === void 0 ? void 0 : TYPE_BY_EXTENSION[(0, import_path.extname)(file.path).toLowerCase()]);
749
- const kind = type === void 0 ? void 0 : kindOf(type);
750
- if (type === void 0 || kind === void 0 || kind === "screenshot" && file.path === void 0) continue;
1321
+ if (type === void 0 || type === METADATA_TYPE2) continue;
1322
+ const kind = kindOf(type);
1323
+ if (kind !== "text" && file.path === void 0) continue;
751
1324
  const name = nameOf(file);
752
1325
  if (file.name.startsWith("_")) skip(kind, name, "hidden");
753
- else if (kind === "screenshot" && !SCREENSHOT_TYPES.has(type)) skip(kind, name, "type");
754
- else if (room[kind] === 0) skip(kind, name, KINDS[kind].limit);
755
1326
  else {
756
- room[kind] -= 1;
757
1327
  jobs.push({
758
1328
  id: item.id,
759
1329
  kind,
@@ -765,14 +1335,34 @@ async function startRun(passed, declared2) {
765
1335
  }
766
1336
  }
767
1337
  }
768
- let next = 0;
769
- await Promise.all(
770
- Array.from({ length: Math.min(UPLOADS_AT_ONCE, jobs.length) }, async () => {
771
- while (next < jobs.length) await uploadOne(jobs[next++]);
772
- })
773
- );
1338
+ const started = Date.now();
1339
+ if (batchMissing) await uploadEach(jobs);
1340
+ else await uploadBatched(jobs);
1341
+ uploadMs += Date.now() - started;
1342
+ }
1343
+ const sending = /* @__PURE__ */ new Set();
1344
+ let sendError;
1345
+ let answered = false;
1346
+ async function dispatch(work) {
1347
+ while (sending.size >= (answered ? SEND_CONCURRENCY : 1)) await Promise.race(sending);
1348
+ const task = work().catch((err) => {
1349
+ sendError ??= err;
1350
+ }).finally(() => sending.delete(task));
1351
+ sending.add(task);
1352
+ }
1353
+ async function settle() {
1354
+ while (sending.size > 0) await Promise.all([...sending]);
1355
+ if (sendError !== void 0) {
1356
+ const err = sendError;
1357
+ sendError = void 0;
1358
+ throw err;
1359
+ }
774
1360
  }
775
1361
  async function flush() {
1362
+ await flushBuffer();
1363
+ await settle();
1364
+ }
1365
+ async function flushBuffer() {
776
1366
  if (buffer.length === 0) return;
777
1367
  const pending = buffer;
778
1368
  buffer = [];
@@ -780,6 +1370,9 @@ async function startRun(passed, declared2) {
780
1370
  defer(pending);
781
1371
  return;
782
1372
  }
1373
+ await dispatch(() => deliver(pending));
1374
+ }
1375
+ async function deliver(pending) {
783
1376
  await resolveKeys(pending.flatMap((p) => p.keys));
784
1377
  const submissions = [];
785
1378
  const unanswered = [];
@@ -802,6 +1395,9 @@ async function startRun(passed, declared2) {
802
1395
  progress();
803
1396
  return;
804
1397
  }
1398
+ await send(submissions, filesByKey);
1399
+ }
1400
+ async function send(submissions, filesByKey) {
805
1401
  for (const part of packed(submissions)) {
806
1402
  if (offline) {
807
1403
  defer(part);
@@ -817,6 +1413,7 @@ async function startRun(passed, declared2) {
817
1413
  for (const k of told) stats[k] += counts[k];
818
1414
  progress();
819
1415
  await upload(out.ok ? out.body?.items : void 0, filesByKey);
1416
+ answered = true;
820
1417
  continue;
821
1418
  }
822
1419
  if (out.ok) {
@@ -845,17 +1442,40 @@ async function startRun(passed, declared2) {
845
1442
  if (stats.rejected > 0) parts.push(`${stats.rejected} rejected`);
846
1443
  if (stats.unresolved > 0) parts.push(`${stats.unresolved} with no matching test case`);
847
1444
  if (stats.offered > 0) parts.push(`${stats.offered} offered for review`);
848
- if (stats.created > 0) parts.push(`${stats.created} added as cases (trusted source)`);
849
- for (const said of [tally(stats.screenshots, "screenshot"), tally(stats.textFiles, "text file")]) {
850
- if (said !== void 0) parts.push(said);
1445
+ if (stats.created > 0) {
1446
+ const recorded = createdWithResult === stats.created && createdUndelivered === 0;
1447
+ parts.push(`${stats.created} added as cases (trusted source)${recorded ? " and their results recorded" : ""}`);
1448
+ }
1449
+ const kinds = [stats.screenshots, stats.textFiles, stats.otherFiles];
1450
+ const sum = (what) => kinds.reduce((n, counts) => n + counts[what], 0);
1451
+ if (bucketSeen) {
1452
+ const other = sum("skipped") - noStorage;
1453
+ parts.push(
1454
+ `${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` : "")
1455
+ );
1456
+ } else {
1457
+ for (const said of [tally(stats.screenshots, "screenshot"), tally(stats.textFiles, "text file")]) {
1458
+ if (said !== void 0) parts.push(said);
1459
+ }
1460
+ const other = stats.otherFiles;
1461
+ if (other.skipped > 0) parts.push(`${other.skipped} file(s) not stored (no bucket connected)`);
1462
+ if (other.failed > 0) parts.push(`${other.failed} file(s) failed to upload`);
851
1463
  }
852
1464
  if (stats.deferred > 0) parts.push(`${stats.deferred} not delivered \u2014 written to ${fallbackPath}`);
853
1465
  if (shortened.size > 0) parts.push(`${shortened.size} test name(s) shortened to fit a key`);
1466
+ const files = [stats.screenshots, stats.textFiles, stats.otherFiles];
1467
+ const total = (what) => files.reduce((n, counts) => n + counts[what], 0);
1468
+ if (total("uploaded") + total("skipped") + total("failed") + existed > 0) {
1469
+ log(
1470
+ `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)`
1471
+ );
1472
+ }
854
1473
  log(`plune: ${parts.join(" \xB7 ")}`);
855
1474
  if (stats.deferred > 0 && process.env["GITHUB_ACTIONS"] === "true") {
856
1475
  log(`::warning::${stats.deferred} result(s) were not delivered to Plune \u2014 see the reporting step's log.`);
857
1476
  }
858
1477
  }
1478
+ const shardLines = [];
859
1479
  return {
860
1480
  get runId() {
861
1481
  return runId;
@@ -868,40 +1488,73 @@ async function startRun(passed, declared2) {
868
1488
  },
869
1489
  async add(result) {
870
1490
  buffer.push({ ...result, keys: bound(result.keys) });
871
- if (buffer.length >= batchSize) await flush();
1491
+ if (buffer.length >= batchSize) await flushBuffer();
872
1492
  },
873
1493
  flush,
874
1494
  async finish(reason) {
875
- if (done) return;
1495
+ if (done) return void 0;
876
1496
  done = true;
877
1497
  await flush();
878
1498
  await offer();
1499
+ let frozen;
879
1500
  if (runId !== null && !offline) {
880
1501
  const out = await client.post(`/v1/runs/${runId}/events`, {
881
1502
  event: "finish",
882
1503
  ...reason !== void 0 ? { reason } : {}
883
1504
  });
884
1505
  if (!out.ok) log(`plune: could not close run ${runId} (${out.detail || out.kind}).`);
885
- else if (typeof out.body?.detached === "number" && out.body.detached > 0) {
886
- log(`plune: ${out.body.detached} test case(s) marked detached \u2014 this full run no longer reports them.`);
1506
+ else {
1507
+ frozen = out.body?.summary ?? void 0;
1508
+ if (typeof out.body?.detached === "number" && out.body.detached > 0) {
1509
+ log(`plune: ${out.body.detached} test case(s) marked detached \u2014 this full run no longer reports them.`);
1510
+ }
887
1511
  }
888
1512
  }
889
1513
  summarise();
1514
+ return frozen;
890
1515
  },
891
- async leaveOpen() {
892
- if (done) return;
1516
+ shardLines,
1517
+ async leaveOpen(opts) {
1518
+ if (done) return void 0;
893
1519
  done = true;
894
1520
  await flush();
895
1521
  await offer();
896
- if (runId !== null) {
1522
+ let frozen;
1523
+ const after = [];
1524
+ const shard = env.shard;
1525
+ let counted = false;
1526
+ let mismatch;
1527
+ if (runId !== null && shard !== void 0 && !offline) {
1528
+ const out = await client.post(`/v1/runs/${runId}/events`, { event: "finish", shardIndex: shard.index, shardsExpected: shard.total });
1529
+ if (out.ok && typeof out.body?.shardsReported === "number") {
1530
+ counted = true;
1531
+ frozen = out.body.summary ?? void 0;
1532
+ const n = out.body.shardsExpected ?? shard.total;
1533
+ if (out.body.run?.statusEvent === "finished") after.push("plune: run closed");
1534
+ after.push(`plune: shard ${shard.index} of ${shard.total} done \u2014 ${out.body.shardsReported} of ${n} shards reported`);
1535
+ } else if (out.ok || out.kind === "invalid") {
1536
+ log('plune: the platform does not support shard auto-close yet \u2014 the run is left open for "plune run finish".');
1537
+ } else if (out.code === "shards_mismatch") {
1538
+ mismatch = new Error(
1539
+ `PLUNE_SHARD=${shard.index}/${shard.total} says ${shard.total} shards, but run ${runId} already expects ${out.shardsExpected ?? "a different number of"} \u2014 every shard of one run must use the same N. The results are uploaded; the run is left open.`
1540
+ );
1541
+ } else {
1542
+ log(`plune: could not report shard ${shard.index} of ${shard.total} to run ${runId} (${out.detail || out.kind}) \u2014 the results are uploaded; close the run with "plune run finish ${runId}".`);
1543
+ }
1544
+ }
1545
+ if (runId !== null && !counted) {
897
1546
  log(`plune: run ${runId} is still open \u2014 close it with "plune run finish ${runId}".`);
898
1547
  }
899
1548
  summarise();
1549
+ shardLines.push(...after);
1550
+ if (opts?.holdShardLines !== true) for (const line of after) log(line);
1551
+ if (mismatch !== void 0) throw mismatch;
1552
+ return frozen;
900
1553
  }
901
1554
  };
902
1555
  }
903
1556
  function sha256(input) {
904
- return (0, import_crypto2.createHash)("sha256").update(input, "utf8").digest("hex");
1557
+ return (0, import_crypto3.createHash)("sha256").update(input, "utf8").digest("hex");
905
1558
  }
906
1559
  var RESULT_KEY_MAX = 200;
907
1560
  var HASH_CHARS = 32;
@@ -925,16 +1578,19 @@ function titlesOf(test) {
925
1578
  }
926
1579
  return titles;
927
1580
  }
1581
+ function pathTitleOf(test) {
1582
+ return [fileOf2(test), ...titlesOf(test)].join("#");
1583
+ }
928
1584
  function keysFor(test) {
929
1585
  return [
930
1586
  { kind: "playwright-id", value: test.id },
931
- { kind: "path-title", value: [fileOf2(test), ...titlesOf(test)].join("#") }
1587
+ { kind: "path-title", value: pathTitleOf(test) }
932
1588
  ];
933
1589
  }
934
- var METADATA_TYPE2 = "application/plune.metadata+json";
1590
+ var METADATA_TYPE3 = "application/plune.metadata+json";
935
1591
  var TOKEN = /@P([A-Za-z0-9_-]+)/;
936
1592
  function metadataOf(result) {
937
- const found = result.attachments.find((a) => a.contentType === METADATA_TYPE2);
1593
+ const found = result.attachments.find((a) => a.contentType === METADATA_TYPE3);
938
1594
  if (found === void 0) return void 0;
939
1595
  try {
940
1596
  const raw = found.body !== void 0 ? found.body.toString("utf8") : found.path !== void 0 ? (0, import_node_fs.readFileSync)(found.path, "utf8") : void 0;
@@ -943,12 +1599,32 @@ function metadataOf(result) {
943
1599
  return void 0;
944
1600
  }
945
1601
  }
946
- function statedIdOf(test, metadata) {
1602
+ function statedIdOf(test, metadata, mapped) {
947
1603
  const annotation = test.annotations.find((a) => a.type === "PluneId")?.description;
948
1604
  if (annotation !== void 0 && annotation !== "") return annotation;
949
1605
  const token = TOKEN.exec(test.title)?.[1];
950
1606
  if (token !== void 0) return token;
951
- return metadata?.id !== void 0 && metadata.id !== "" ? metadata.id : void 0;
1607
+ if (metadata?.id !== void 0 && metadata.id !== "") return metadata.id;
1608
+ return mapped;
1609
+ }
1610
+ function readIds(file) {
1611
+ let raw;
1612
+ try {
1613
+ raw = (0, import_node_fs.readFileSync)(file, "utf8");
1614
+ } catch {
1615
+ return {};
1616
+ }
1617
+ try {
1618
+ const parsed = JSON.parse(raw);
1619
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) && Object.values(parsed).every((v) => typeof v === "string" && v !== ""))
1620
+ return parsed;
1621
+ } catch {
1622
+ }
1623
+ process.stderr.write(
1624
+ `plune: ${file} is not a JSON object of path-title to case id strings - ignored, tests resolve as if it were absent
1625
+ `
1626
+ );
1627
+ return {};
952
1628
  }
953
1629
  var NOT_FAILED = /* @__PURE__ */ new Set(["passed", "skipped"]);
954
1630
  function textOf(error) {
@@ -982,12 +1658,16 @@ function attemptOf(test, result, ctx) {
982
1658
  ...ctx.repoRoot !== void 0 ? { repoRoot: ctx.repoRoot } : {}
983
1659
  };
984
1660
  }
985
- function pendingFrom(test, result, ctx) {
1661
+ function pendingFrom(test, result, ctx, ids = {}) {
986
1662
  const metadata = metadataOf(result);
987
- const pluneId = statedIdOf(test, metadata);
1663
+ const pluneId = statedIdOf(
1664
+ test,
1665
+ metadata,
1666
+ Object.hasOwn(ids, pathTitleOf(test)) ? ids[pathTitleOf(test)] : void 0
1667
+ );
988
1668
  const expected = test.expectedStatus;
989
1669
  const attempt = attemptOf(test, result, ctx);
990
- const errorContext = errorContextOf(attempt);
1670
+ const errorContext = errorContextFields(attempt);
991
1671
  const failure = NOT_FAILED.has(result.status) ? void 0 : failureOf(attempt);
992
1672
  const files = filesOf(attempt);
993
1673
  const startedAt = result.startTime;
@@ -1017,7 +1697,7 @@ function pendingFrom(test, result, ctx) {
1017
1697
  retry: result.retry,
1018
1698
  worker: String(result.workerIndex)
1019
1699
  },
1020
- ...errorContext !== "" ? { errorContext } : {},
1700
+ ...errorContext,
1021
1701
  ...failure !== void 0 ? { failure } : {},
1022
1702
  // Every attempt's, a passed one's too; the core uploads the screenshots and the text files once the result is stored.
1023
1703
  ...files.length > 0 ? { files } : {}
@@ -1035,6 +1715,8 @@ var PluneReporter = class {
1035
1715
  /** Kept whole: `metadata.ci` is written into it after `onConfigure`, so it is read at the run's opening. */
1036
1716
  config = null;
1037
1717
  context = {};
1718
+ /** The mapfile, read on the first result so a run that reports nothing never touches the disk. */
1719
+ ids = null;
1038
1720
  constructor(options = {}) {
1039
1721
  this.options = options;
1040
1722
  }
@@ -1087,7 +1769,10 @@ var PluneReporter = class {
1087
1769
  onTestEnd(test, result) {
1088
1770
  const session = this.open();
1089
1771
  this.chain = this.chain.then(async () => {
1090
- await (await session).add(pendingFrom(test, result, this.context));
1772
+ this.ids ??= readIds(
1773
+ (0, import_node_path.resolve)(this.options.idsFile ?? process.env["PLUNE_IDS_FILE"] ?? "plune/ids.json")
1774
+ );
1775
+ await (await session).add(pendingFrom(test, result, this.context, this.ids));
1091
1776
  }).catch((err) => this.giveUp(err));
1092
1777
  }
1093
1778
  async onEnd(_result) {