@piwitests/reporter 0.66.0 → 0.68.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.
@@ -41,7 +41,7 @@ function errorMessage(error) {
41
41
  }
42
42
 
43
43
  // src/internal/config/env.ts
44
- var path2 = __toESM(require("path"));
44
+ var path3 = __toESM(require("path"));
45
45
 
46
46
  // src/internal/config/desktop.ts
47
47
  var fs = __toESM(require("fs"));
@@ -59,14 +59,23 @@ function processAlive(pid) {
59
59
  }
60
60
  }
61
61
  function readDesktopConfig(filePath) {
62
+ const file = readDesktopFile(filePath);
63
+ if (!file) return null;
64
+ if (file.pid !== null && !processAlive(file.pid)) return null;
65
+ return { url: file.url, token: file.token };
66
+ }
67
+ function readDesktopToken(filePath) {
68
+ return readDesktopFile(filePath)?.token ?? null;
69
+ }
70
+ function readDesktopFile(filePath) {
62
71
  try {
63
72
  const parsed = JSON.parse(fs.readFileSync(filePath, "utf8"));
64
73
  const url = parsed?.url;
65
74
  const token = parsed?.token;
66
75
  if (typeof url !== "string" || !url) return null;
67
76
  if (typeof token !== "string" || !token) return null;
68
- if (Number.isInteger(parsed?.pid) && parsed.pid > 0 && !processAlive(parsed.pid)) return null;
69
- return { url, token };
77
+ const pid = Number.isInteger(parsed?.pid) && parsed.pid > 0 ? parsed.pid : null;
78
+ return { url, token, pid };
70
79
  } catch {
71
80
  return null;
72
81
  }
@@ -134,6 +143,118 @@ function resolveRunLabel(configured, sharded) {
134
143
  return !sharded && ci.job ? `${ci.run}|${ci.job}` : ci.run;
135
144
  }
136
145
 
146
+ // ../core/src/run-request.ts
147
+ var RUN_REQUEST_LIMITS = {
148
+ tests: { min: 1, max: 200 },
149
+ repeatEach: { min: 1, max: 10 },
150
+ workers: { min: 1, max: 4 },
151
+ /** How long a request waits for a target to claim it, in milliseconds. */
152
+ lifetimeMs: 2 * 60 * 1e3,
153
+ /**
154
+ * How often a target that holds a request calls the instance at least, in milliseconds: it hears its stops from the
155
+ * list of requests. Past this silence the instance ends the request as an error.
156
+ */
157
+ silentTargetMs: 5 * 60 * 1e3,
158
+ /** How long a stop waits for the target to end a run, in milliseconds, before a second stop ends the request. */
159
+ stopGraceMs: 60 * 1e3
160
+ };
161
+ var REQUEST_TOKEN_PREFIX = "pdq_";
162
+ var REQUEST_TOKEN = /^pdq_[0-9a-f]{64}$/;
163
+ var REQUEST_RUN_ENV = {
164
+ tokenFile: "PIWI_REQUEST_TOKEN_FILE",
165
+ instance: "PIWI_REQUEST_INSTANCE"
166
+ };
167
+
168
+ // src/internal/support/private-file.ts
169
+ var crypto2 = __toESM(require("crypto"));
170
+ var fs3 = __toESM(require("fs"));
171
+ var os2 = __toESM(require("os"));
172
+ var path2 = __toESM(require("path"));
173
+ function privateTempDir() {
174
+ if (process.platform !== "win32") return os2.tmpdir();
175
+ const dir = path2.join(process.env.LOCALAPPDATA || path2.join(os2.homedir(), "AppData", "Local"), "piwi", "tmp");
176
+ try {
177
+ fs3.mkdirSync(dir, { recursive: true });
178
+ } catch {
179
+ }
180
+ return dir;
181
+ }
182
+ var NO_FOLLOW = fs3.constants.O_NOFOLLOW ?? 0;
183
+ var NO_WAIT = fs3.constants.O_NONBLOCK ?? 0;
184
+ function untrustedReason(stat) {
185
+ if (stat.isSymbolicLink()) return "it is a symbolic link";
186
+ if (!stat.isFile()) return "it is not a regular file";
187
+ if (typeof process.getuid === "function") {
188
+ if (stat.uid !== process.getuid()) return "another user owns it";
189
+ if (stat.mode & 18) return "other users may write to it";
190
+ if (stat.nlink > 1) return "it has another name";
191
+ }
192
+ return null;
193
+ }
194
+ function writePrivateFile(file, text) {
195
+ const temp = `${file}.${process.pid}.${crypto2.randomBytes(6).toString("hex")}.tmp`;
196
+ try {
197
+ fs3.writeFileSync(temp, text, { encoding: "utf8", flag: "wx", mode: 384 });
198
+ fs3.renameSync(temp, file);
199
+ } catch (error) {
200
+ fs3.rmSync(temp, { force: true });
201
+ throw error;
202
+ }
203
+ }
204
+ function readPrivateFile(file) {
205
+ const found = fs3.lstatSync(file, { throwIfNoEntry: false });
206
+ if (!found) return null;
207
+ const reason = untrustedReason(found);
208
+ if (reason) return { untrusted: reason };
209
+ const fd = fs3.openSync(file, fs3.constants.O_RDONLY | NO_FOLLOW | NO_WAIT);
210
+ try {
211
+ const stat = fs3.fstatSync(fd);
212
+ const opened = untrustedReason(stat);
213
+ if (opened) return { untrusted: opened };
214
+ return { text: fs3.readFileSync(fd, "utf8"), mode: stat.mode };
215
+ } finally {
216
+ fs3.closeSync(fd);
217
+ }
218
+ }
219
+
220
+ // src/internal/config/requested-run.ts
221
+ function readRequestedRun(env) {
222
+ const file = env[REQUEST_RUN_ENV.tokenFile];
223
+ const instance = env[REQUEST_RUN_ENV.instance];
224
+ if (!file && !instance) return null;
225
+ if (!file || !instance) {
226
+ return { problem: `${REQUEST_RUN_ENV.tokenFile} and ${REQUEST_RUN_ENV.instance} are set together, or not at all.` };
227
+ }
228
+ let url;
229
+ try {
230
+ url = new URL(instance);
231
+ } catch {
232
+ return { problem: `${REQUEST_RUN_ENV.instance} is not a URL.` };
233
+ }
234
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
235
+ return { problem: `${REQUEST_RUN_ENV.instance} is not an http or https URL.` };
236
+ }
237
+ let read;
238
+ try {
239
+ read = readPrivateFile(file);
240
+ } catch {
241
+ read = null;
242
+ }
243
+ if (!read) return { problem: `The request token file in ${REQUEST_RUN_ENV.tokenFile} cannot be read.` };
244
+ if ("untrusted" in read || readableByOthers(read.mode)) {
245
+ return { problem: `The request token file in ${REQUEST_RUN_ENV.tokenFile} is not this user's alone.` };
246
+ }
247
+ const token = read.text.trim();
248
+ if (!REQUEST_TOKEN.test(token)) {
249
+ return { problem: `The file in ${REQUEST_RUN_ENV.tokenFile} holds no request token.` };
250
+ }
251
+ return { instance: `${url.origin}${url.pathname.replace(/\/+$/, "")}`, token };
252
+ }
253
+ function readableByOthers(mode) {
254
+ if (typeof process.getuid !== "function") return false;
255
+ return (mode & 36) !== 0;
256
+ }
257
+
137
258
  // src/internal/config/env.ts
138
259
  var DEFAULTS = {
139
260
  projectName: "default-project",
@@ -142,6 +263,7 @@ var DEFAULTS = {
142
263
  liveFileUploads: true,
143
264
  collectScmInfo: true,
144
265
  collectCiInfo: true,
266
+ collectEnvironmentInfo: true,
145
267
  collectPerformanceMetrics: true,
146
268
  captureLocators: true,
147
269
  capturePageState: true,
@@ -171,6 +293,7 @@ var DEFAULTS = {
171
293
  var PIWI_ENV_KEYS = {
172
294
  serverUrl: "PIWI_DASHBOARD_URL",
173
295
  desktopApp: "PIWI_DESKTOP_APP",
296
+ desktopKey: "PIWI_DESKTOP_KEY",
174
297
  projectName: "PIWI_PROJECT_NAME",
175
298
  verbose: "PIWI_VERBOSE",
176
299
  apiKey: "PIWI_API_KEY",
@@ -189,6 +312,7 @@ var PIWI_ENV_KEYS = {
189
312
  failOnFlakyTests: "PIWI_FAIL_ON_FLAKY_TESTS",
190
313
  uploadTraces: "PIWI_UPLOAD_TRACES",
191
314
  uploadReport: "PIWI_UPLOAD_REPORT",
315
+ collectEnvironmentInfo: "PIWI_COLLECT_ENVIRONMENT_INFO",
192
316
  captureLocators: "PIWI_CAPTURE_LOCATORS",
193
317
  capturePageState: "PIWI_CAPTURE_PAGE_STATE",
194
318
  capturePageInventory: "PIWI_CAPTURE_PAGE_INVENTORY",
@@ -220,6 +344,7 @@ var PIWI_ENV_KEYS = {
220
344
  };
221
345
  var PIWI_DESKTOP_CONFIG_ENV = "PIWI_DESKTOP_CONFIG";
222
346
  var PIWI_SHARD_ENV = "PIWI_SHARD";
347
+ var PIWI_RUN_LOG_ENV = "PIWI_RUN_LOG";
223
348
  function readBool(val) {
224
349
  if (val === void 0) return void 0;
225
350
  return ["true", "1", "yes", "on"].includes(val.trim().toLowerCase());
@@ -248,6 +373,7 @@ var ENV_FALLBACK_SPECS = [
248
373
  { option: "failOnFlakyTests", env: PIWI_ENV_KEYS.failOnFlakyTests, kind: "bool" },
249
374
  { option: "uploadTraces", env: PIWI_ENV_KEYS.uploadTraces, kind: "bool" },
250
375
  { option: "uploadReport", env: PIWI_ENV_KEYS.uploadReport, kind: "bool" },
376
+ { option: "collectEnvironmentInfo", env: PIWI_ENV_KEYS.collectEnvironmentInfo, kind: "bool" },
251
377
  { option: "captureLocators", env: PIWI_ENV_KEYS.captureLocators, kind: "bool" },
252
378
  { option: "capturePageState", env: PIWI_ENV_KEYS.capturePageState, kind: "bool" },
253
379
  { option: "capturePageInventory", env: PIWI_ENV_KEYS.capturePageInventory, kind: "bool" },
@@ -272,9 +398,15 @@ function desktopAppMode(option, envValue) {
272
398
  return "fallback";
273
399
  }
274
400
  var desktopDiscovered = false;
401
+ var desktopTokenHeld = false;
402
+ var requestedRunInstance = null;
403
+ var requestedRunError = null;
275
404
  var desktopReplacedServerUrl = null;
276
405
  var dotEnvUse = null;
277
406
  var ignoredEnv = [];
407
+ function usedDesktopToken() {
408
+ return desktopTokenHeld;
409
+ }
278
410
  function resolveOptions(raw, configDir) {
279
411
  const env = process.env;
280
412
  const mergedRaw = { ...raw };
@@ -294,7 +426,7 @@ function resolveOptions(raw, configDir) {
294
426
  }
295
427
  dotEnvUse = null;
296
428
  if (configDir) {
297
- const file = path2.join(configDir, ".env");
429
+ const file = path3.join(configDir, ".env");
298
430
  const dotEnv = readDotEnv(file);
299
431
  const keys = [];
300
432
  for (const option of DOTENV_OPTIONS) {
@@ -306,8 +438,12 @@ function resolveOptions(raw, configDir) {
306
438
  if (keys.length > 0) dotEnvUse = { file, keys };
307
439
  }
308
440
  desktopDiscovered = false;
441
+ desktopTokenHeld = false;
309
442
  desktopReplacedServerUrl = null;
310
- const mode = desktopAppMode(mergedRaw.desktopApp, env[PIWI_ENV_KEYS.desktopApp]);
443
+ const requested = readRequestedRun(env);
444
+ requestedRunInstance = requested && "instance" in requested ? requested.instance : null;
445
+ requestedRunError = requested && "problem" in requested ? requested.problem : null;
446
+ const mode = requested ? "off" : desktopAppMode(mergedRaw.desktopApp, env[PIWI_ENV_KEYS.desktopApp]);
311
447
  mergedRaw.desktopApp = mode;
312
448
  const serverUrlUnset = mergedRaw.serverUrl === void 0;
313
449
  const apiKeyUnset = mergedRaw.apiKey === void 0 || mergedRaw.apiKey === null;
@@ -324,6 +460,7 @@ function resolveOptions(raw, configDir) {
324
460
  desktopDiscovered = true;
325
461
  }
326
462
  }
463
+ desktopTokenHeld = desktopDiscovered || env[PIWI_ENV_KEYS.desktopKey] === "1" && !!env[PIWI_ENV_KEYS.apiKey] && mergedRaw.apiKey === env[PIWI_ENV_KEYS.apiKey] || typeof mergedRaw.apiKey === "string" && mergedRaw.apiKey !== "" && readDesktopToken(env[PIWI_DESKTOP_CONFIG_ENV] || defaultDesktopConfigPath()) === mergedRaw.apiKey;
327
464
  const coverage = { ...mergedRaw.coverage };
328
465
  const coverageBrowser = env[PIWI_ENV_KEYS.coverageBrowser];
329
466
  const coverageServer = env[PIWI_ENV_KEYS.coverageServer];
@@ -342,6 +479,24 @@ function resolveOptions(raw, configDir) {
342
479
  if (externalId.onDuplicate === void 0 && externalIdOnDuplicate)
343
480
  externalId.onDuplicate = externalIdOnDuplicate;
344
481
  if (Object.keys(externalId).length > 0) mergedRaw.externalId = externalId;
482
+ if (requested && "instance" in requested) {
483
+ desktopTokenHeld = false;
484
+ mergedRaw.serverUrl = requested.instance;
485
+ mergedRaw.apiKey = requested.token;
486
+ mergedRaw.username = null;
487
+ mergedRaw.password = null;
488
+ mergedRaw.enabled = true;
489
+ mergedRaw.streaming = true;
490
+ mergedRaw.keep = false;
491
+ mergedRaw.sampleAriaOnPass = false;
492
+ mergedRaw.uploadManifest = false;
493
+ mergedRaw.captureCodeReach = false;
494
+ mergedRaw.collectEnvironmentInfo = false;
495
+ delete mergedRaw.coverage;
496
+ mergedRaw.ai = { ...mergedRaw.ai, mode: "replay" };
497
+ } else if (requested) {
498
+ mergedRaw.enabled = false;
499
+ }
345
500
  const opts = { ...DEFAULTS, ...mergedRaw };
346
501
  if (env[PIWI_ENV_KEYS.verbose] !== void 0) opts.verbose = readBool(env[PIWI_ENV_KEYS.verbose]);
347
502
  return opts;
@@ -353,6 +508,77 @@ var http = __toESM(require("http"));
353
508
  var import_node_url = require("url");
354
509
  var import_form_data = __toESM(require("form-data"));
355
510
 
511
+ // ../core/src/hmac.ts
512
+ async function hmacSha256Hex(key, message) {
513
+ const encoder = new TextEncoder();
514
+ const cryptoKey = await crypto.subtle.importKey(
515
+ "raw",
516
+ encoder.encode(key),
517
+ { name: "HMAC", hash: "SHA-256" },
518
+ false,
519
+ ["sign"]
520
+ );
521
+ return hex(new Uint8Array(await crypto.subtle.sign("HMAC", cryptoKey, encoder.encode(message))));
522
+ }
523
+ function randomHex(byteCount) {
524
+ return hex(crypto.getRandomValues(new Uint8Array(byteCount)));
525
+ }
526
+ function hex(bytes) {
527
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
528
+ }
529
+
530
+ // ../core/src/desktop-proof.ts
531
+ var DESKTOP_CHALLENGE_HEADER = "x-piwi-desktop-challenge";
532
+ var DESKTOP_PROOF_HEADER = "x-piwi-desktop-proof";
533
+ function newDesktopChallenge() {
534
+ return randomHex(32);
535
+ }
536
+ function desktopTokenProof(token, port, challenge) {
537
+ return hmacSha256Hex(token, `piwi-desktop-proof:${port}:${challenge}`);
538
+ }
539
+ var PROOF_TIMEOUT_MS = 5e3;
540
+ function sameHex(a, b) {
541
+ if (a.length !== b.length) return false;
542
+ let diff = 0;
543
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
544
+ return diff === 0;
545
+ }
546
+ async function proveDesktopServer(baseUrl, token, options = {}) {
547
+ let url;
548
+ try {
549
+ url = new URL(baseUrl);
550
+ } catch {
551
+ return "unreachable";
552
+ }
553
+ const request3 = options.request ?? ((target, init) => fetch(target, { ...init, redirect: "error" }));
554
+ const challenge = newDesktopChallenge();
555
+ let res;
556
+ try {
557
+ res = await request3(new URL("/api/health", url).href, {
558
+ headers: { [DESKTOP_CHALLENGE_HEADER]: challenge },
559
+ signal: AbortSignal.timeout(options.timeoutMs ?? PROOF_TIMEOUT_MS)
560
+ });
561
+ } catch {
562
+ return "unreachable";
563
+ }
564
+ const proof = res.headers.get(DESKTOP_PROOF_HEADER);
565
+ if (!proof) return res.status === 200 ? "unproven" : "unreachable";
566
+ const port = Number(url.port || (url.protocol === "https:" ? 443 : 80));
567
+ return sameHex(proof, await desktopTokenProof(token, port, challenge)) ? "proven" : "unproven";
568
+ }
569
+ function shareInFlight() {
570
+ const running = /* @__PURE__ */ new Map();
571
+ return (key, check) => {
572
+ const existing = running.get(key);
573
+ if (existing) return existing;
574
+ const started = check().finally(() => {
575
+ if (running.get(key) === started) running.delete(key);
576
+ });
577
+ running.set(key, started);
578
+ return started;
579
+ };
580
+ }
581
+
356
582
  // src/internal/support/logger.ts
357
583
  var Logger = class {
358
584
  constructor(verbose = false) {
@@ -384,6 +610,15 @@ var HttpError = class extends Error {
384
610
  this.name = "HttpError";
385
611
  }
386
612
  };
613
+ var DesktopNotProvenError = class extends Error {
614
+ constructor(serverUrl, proof) {
615
+ super(
616
+ proof === "unreachable" ? `The desktop app at ${serverUrl} did not answer, so its token is not sent and nothing is uploaded.` : `The desktop app's token is not sent to ${serverUrl}: the server there did not prove it holds the token, so nothing is uploaded. Restart or update the desktop app, or name another instance with a server URL and an API key.`
617
+ );
618
+ this.name = "DesktopNotProvenError";
619
+ if (proof === "unreachable") this.code = "ECONNREFUSED";
620
+ }
621
+ };
387
622
  var FAILURE_DETAIL_MAX = 500;
388
623
  function failureDetail(res) {
389
624
  let text = null;
@@ -436,16 +671,21 @@ var HttpClient = class {
436
671
  * @param uploadTimeout Socket inactivity timeout of a multipart upload, or of
437
672
  * a run's results sent as JSON, in ms (default 10 min): the
438
673
  * dashboard answers one only once it has stored all of it.
674
+ * @param desktopToken The desktop app's token when `serverUrl` is the app's: a request that carries it waits for
675
+ * the server to prove it holds it, and without the proof nothing is sent.
439
676
  */
440
- constructor(serverUrl, logger2 = new Logger(), timeout = 3e4, uploadTimeout = 10 * 60 * 1e3) {
677
+ constructor(serverUrl, logger2 = new Logger(), timeout = 3e4, uploadTimeout = 10 * 60 * 1e3, desktopToken = null) {
441
678
  this.serverUrl = serverUrl;
442
679
  this.logger = logger2;
443
680
  this.timeout = timeout;
444
681
  this.uploadTimeout = uploadTimeout;
682
+ this.desktopToken = desktopToken;
445
683
  /** Requests in flight, so `close` can abort them. */
446
684
  this.inFlight = /* @__PURE__ */ new Set();
447
685
  /** Set by `close`: every later request fails with this reason. */
448
686
  this.closedReason = null;
687
+ this.loginAnnounced = false;
688
+ this.proofsInFlight = shareInFlight();
449
689
  this.warnIfInsecureTransport();
450
690
  }
451
691
  /**
@@ -494,7 +734,9 @@ var HttpClient = class {
494
734
  async resolveAuth(options) {
495
735
  if (options.apiKey) return options.apiKey;
496
736
  if (options.username && options.password) {
497
- this.logger.info(`Authenticating as ${options.username}...`);
737
+ if (this.loginAnnounced) this.logger.debug(`Authenticating as ${options.username} again...`);
738
+ else this.logger.info(`Authenticating as ${options.username}...`);
739
+ this.loginAnnounced = true;
498
740
  return this.login(options.username, options.password);
499
741
  }
500
742
  return null;
@@ -603,7 +845,21 @@ var HttpClient = class {
603
845
  * Unified request core: transport, headers, auth, response accumulation, timeout. Nothing is sent to a `serverUrl`
604
846
  * that is not an `http://` or `https://` URL.
605
847
  */
606
- request(method, pathname, opts) {
848
+ async request(method, pathname, opts) {
849
+ if (!this.desktopToken || opts.auth !== this.desktopToken) return this.send(method, pathname, opts);
850
+ await this.requireDesktopProof();
851
+ return this.send(method, pathname, opts);
852
+ }
853
+ /**
854
+ * Resolves once the server proved it holds the desktop token. Each request that carries the token asks for its own
855
+ * proof; requests that arrive while a proof is being asked share it, and a proof that has arrived is never used for
856
+ * a later request.
857
+ */
858
+ async requireDesktopProof() {
859
+ const proof = await this.proofsInFlight("proof", () => proveDesktopServer(this.serverUrl, this.desktopToken));
860
+ if (proof !== "proven") throw new DesktopNotProvenError(this.serverUrl, proof);
861
+ }
862
+ send(method, pathname, opts) {
607
863
  return new Promise((resolve4, reject) => {
608
864
  if (this.closedReason !== null) {
609
865
  reject(new Error(this.closedReason));
@@ -676,7 +932,7 @@ var HttpClient = class {
676
932
  }
677
933
  applyAuth(headers, auth) {
678
934
  if (!auth) return;
679
- if (auth.startsWith("pd_")) {
935
+ if (auth.startsWith("pd_") || auth.startsWith(REQUEST_TOKEN_PREFIX)) {
680
936
  headers["Authorization"] = `Bearer ${auth}`;
681
937
  } else {
682
938
  headers["Cookie"] = auth;
@@ -685,14 +941,14 @@ var HttpClient = class {
685
941
  };
686
942
 
687
943
  // src/internal/support/instance-id.ts
688
- var crypto = __toESM(require("crypto"));
689
- var os2 = __toESM(require("os"));
944
+ var crypto3 = __toESM(require("crypto"));
945
+ var os3 = __toESM(require("os"));
690
946
  function hashForProject(projectName) {
691
- return crypto.createHash("sha1").update(projectName).digest("hex").slice(0, 16);
947
+ return crypto3.createHash("sha1").update(projectName).digest("hex").slice(0, 16);
692
948
  }
693
949
  function computeInstanceId(projectName, runLabel) {
694
- const seed = runLabel ? `${projectName}|${runLabel}` : `${os2.hostname()}|${projectName}`;
695
- return crypto.createHash("sha256").update(seed).digest("hex").slice(0, 16);
950
+ const seed = runLabel ? `${projectName}|${runLabel}` : `${os3.hostname()}|${projectName}`;
951
+ return crypto3.createHash("sha256").update(seed).digest("hex").slice(0, 16);
696
952
  }
697
953
 
698
954
  // src/internal/support/shard-info.ts
@@ -739,9 +995,9 @@ var MAX_REGION_SNAPSHOT = 1024 * 1024;
739
995
  var MAX_AGENT_SNAPSHOT = 1024 * 1024;
740
996
 
741
997
  // src/internal/support/test-paths.ts
742
- var path3 = __toESM(require("path"));
998
+ var path4 = __toESM(require("path"));
743
999
  function configDirFromConfig(config) {
744
- if (config?.configFile) return path3.dirname(config.configFile);
1000
+ if (config?.configFile) return path4.dirname(config.configFile);
745
1001
  if (config?.rootDir) return config.rootDir;
746
1002
  return process.cwd();
747
1003
  }
@@ -864,35 +1120,6 @@ function isLiveViewKey(value) {
864
1120
  // src/internal/support/setup-file.ts
865
1121
  var path5 = __toESM(require("path"));
866
1122
  var fs4 = __toESM(require("fs"));
867
-
868
- // src/internal/support/private-file.ts
869
- var crypto2 = __toESM(require("crypto"));
870
- var fs3 = __toESM(require("fs"));
871
- var os3 = __toESM(require("os"));
872
- var path4 = __toESM(require("path"));
873
- function privateTempDir() {
874
- if (process.platform !== "win32") return os3.tmpdir();
875
- const dir = path4.join(process.env.LOCALAPPDATA || path4.join(os3.homedir(), "AppData", "Local"), "piwi", "tmp");
876
- try {
877
- fs3.mkdirSync(dir, { recursive: true });
878
- } catch {
879
- }
880
- return dir;
881
- }
882
- var NO_FOLLOW = fs3.constants.O_NOFOLLOW ?? 0;
883
- var NO_WAIT = fs3.constants.O_NONBLOCK ?? 0;
884
- function writePrivateFile(file, text) {
885
- const temp = `${file}.${process.pid}.${crypto2.randomBytes(6).toString("hex")}.tmp`;
886
- try {
887
- fs3.writeFileSync(temp, text, { encoding: "utf8", flag: "wx", mode: 384 });
888
- fs3.renameSync(temp, file);
889
- } catch (error) {
890
- fs3.rmSync(temp, { force: true });
891
- throw error;
892
- }
893
- }
894
-
895
- // src/internal/support/setup-file.ts
896
1123
  var logger = new Logger();
897
1124
  function getSetupFilePath(projectName, pid = process.pid) {
898
1125
  return path5.join(privateTempDir(), `piwi-dashboard-setup-${hashForProject(projectName)}-${pid}.json`);
@@ -900,6 +1127,30 @@ function getSetupFilePath(projectName, pid = process.pid) {
900
1127
  function writeSetupInfo(info) {
901
1128
  writePrivateFile(getSetupFilePath(info.projectName), JSON.stringify(info));
902
1129
  }
1130
+ function writeSetupFailure(projectName, failed) {
1131
+ const failure = { projectName, failed };
1132
+ try {
1133
+ writePrivateFile(getSetupFilePath(projectName), JSON.stringify(failure));
1134
+ } catch {
1135
+ }
1136
+ }
1137
+
1138
+ // src/internal/support/run-url.ts
1139
+ function runUrl(serverUrl, runId) {
1140
+ return `${serverUrl.replace(/\/+$/, "")}/test-runs/${runId}`;
1141
+ }
1142
+ function answeredRunUrl(answer, serverUrl, runId) {
1143
+ const named = answer?.runUrl;
1144
+ if (typeof named === "string" && named.length <= 2048 && !/[\s()<>"'`\\]/.test(named)) {
1145
+ if (/^\/[^/]/.test(named)) return `${serverUrl.replace(/\/+$/, "")}${named}`;
1146
+ try {
1147
+ const url = new URL(named);
1148
+ if (url.protocol === "http:" || url.protocol === "https:") return url.href;
1149
+ } catch {
1150
+ }
1151
+ }
1152
+ return runUrl(serverUrl, runId);
1153
+ }
903
1154
 
904
1155
  // src/internal/support/aria-sampling.ts
905
1156
  var path6 = __toESM(require("path"));
@@ -1163,8 +1414,8 @@ var MAX_MANIFEST_BYTES = 4 * 1024 * 1024;
1163
1414
  function instrumentationManifestUrls(baseUrl) {
1164
1415
  const base = new URL(baseUrl);
1165
1416
  const root = new URL(INSTRUMENTATION_MANIFEST_PATH, base).toString();
1166
- const path11 = base.pathname.replace(/\/+$/, "");
1167
- return path11 ? [new URL(`${path11}${INSTRUMENTATION_MANIFEST_PATH}`, base).toString(), root] : [root];
1417
+ const path12 = base.pathname.replace(/\/+$/, "");
1418
+ return path12 ? [new URL(`${path12}${INSTRUMENTATION_MANIFEST_PATH}`, base).toString(), root] : [root];
1168
1419
  }
1169
1420
  async function fetchInstrumentationManifest(baseUrl, fetchImpl = fetch) {
1170
1421
  try {
@@ -1183,6 +1434,7 @@ async function fetchManifestAt(manifestUrl, fetchImpl) {
1183
1434
  const res = await fetchImpl(manifestUrl, { signal: AbortSignal.timeout(INSTRUMENTATION_FETCH_TIMEOUT_MS) });
1184
1435
  return res.ok ? parseManifestJson(await res.text()) : null;
1185
1436
  }
1437
+ var MAX_ENVIRONMENT_BYTES = 64 * 1024;
1186
1438
 
1187
1439
  // src/internal/manifest/run-manifests.ts
1188
1440
  async function lookupProjectId(httpClient, auth, projectName) {
@@ -1196,7 +1448,7 @@ async function uploadManifest(httpClient, auth, projectId, upload, logger2) {
1196
1448
  }
1197
1449
 
1198
1450
  // src/internal/collect/source-checksums.ts
1199
- var crypto3 = __toESM(require("crypto"));
1451
+ var crypto4 = __toESM(require("crypto"));
1200
1452
  var fs7 = __toESM(require("fs"));
1201
1453
  var path8 = __toESM(require("path"));
1202
1454
 
@@ -1260,7 +1512,42 @@ function getReporterVersion() {
1260
1512
  return cachedVersion;
1261
1513
  }
1262
1514
 
1515
+ // src/internal/support/run-log.ts
1516
+ var import_node_crypto = require("crypto");
1517
+ var fs9 = __toESM(require("fs"));
1518
+ var path11 = __toESM(require("path"));
1519
+ var READ_MS = 1e3;
1520
+ function relayRunLog(print, env = process.env) {
1521
+ const file = path11.join(privateTempDir(), `piwi-run-log-${(0, import_node_crypto.randomBytes)(12).toString("hex")}.txt`);
1522
+ writePrivateFile(file, "");
1523
+ env[PIWI_RUN_LOG_ENV] = file;
1524
+ let printed = 0;
1525
+ const flush = () => {
1526
+ let text;
1527
+ try {
1528
+ const found = readPrivateFile(file);
1529
+ if (!found || !("text" in found)) return;
1530
+ text = found.text;
1531
+ } catch {
1532
+ return;
1533
+ }
1534
+ const end = text.lastIndexOf("\n") + 1;
1535
+ if (end <= printed) return;
1536
+ const lines = text.slice(printed, end).split("\n");
1537
+ printed = end;
1538
+ for (const line of lines) if (line) print(line);
1539
+ };
1540
+ const timer = setInterval(flush, READ_MS);
1541
+ timer.unref();
1542
+ return () => {
1543
+ clearInterval(timer);
1544
+ flush();
1545
+ fs9.rmSync(file, { force: true });
1546
+ };
1547
+ }
1548
+
1263
1549
  // src/public/global-setup.ts
1550
+ var relaying = false;
1264
1551
  function createGlobalSetup(options, userSetup) {
1265
1552
  return async function globalSetupFn(config) {
1266
1553
  const configDir = configDirFromConfig(config);
@@ -1304,10 +1591,21 @@ function createGlobalSetup(options, userSetup) {
1304
1591
  if (userSetup) return userSetup(config);
1305
1592
  return;
1306
1593
  }
1307
- const httpClient = new HttpClient(opts.serverUrl, logger2);
1594
+ const httpClient = new HttpClient(
1595
+ opts.serverUrl,
1596
+ logger2,
1597
+ void 0,
1598
+ void 0,
1599
+ usedDesktopToken() ? opts.apiKey ?? null : null
1600
+ );
1601
+ const registers = opts.streaming !== false;
1602
+ let registered = false;
1308
1603
  try {
1309
1604
  const auth = await httpClient.resolveAuth(opts);
1310
- if (opts.streaming !== false) await registerRun(httpClient, auth, opts, config, logger2);
1605
+ if (registers) {
1606
+ await registerRun(httpClient, auth, opts, config, logger2);
1607
+ registered = true;
1608
+ }
1311
1609
  if (opts.projectName) clearAriaSampleFile(opts.projectName);
1312
1610
  const wantsAria = opts.sampleAriaOnPass !== false && !!opts.projectName;
1313
1611
  const committedManifest = opts.uploadManifest !== false ? readCommittedManifest(configDirFromConfig(config)) : null;
@@ -1346,6 +1644,7 @@ function createGlobalSetup(options, userSetup) {
1346
1644
  }
1347
1645
  } catch (error) {
1348
1646
  logger2.warn(`Could not register global setup: ${errorMessage(error)}`);
1647
+ if (registers && !registered && opts.projectName) writeSetupFailure(opts.projectName, errorMessage(error));
1349
1648
  }
1350
1649
  if (userSetup) return userSetup(config);
1351
1650
  };
@@ -1373,16 +1672,28 @@ async function registerRun(httpClient, auth, opts, config, logger2) {
1373
1672
  },
1374
1673
  auth
1375
1674
  );
1376
- if (response?.runId && response?.setupToken) {
1377
- const liveViewKey = response.liveView?.key;
1378
- writeSetupInfo({
1379
- runId: response.runId,
1380
- setupToken: response.setupToken,
1381
- projectName: opts.projectName,
1382
- ...isLiveViewKey(liveViewKey) ? { liveViewKey } : {},
1383
- ...response.liveView?.refused === "local" ? { liveViewLocal: true } : {}
1384
- });
1385
- logger2.debug(`Global setup: initializing run #${response.runId}`);
1675
+ if (!response?.runId || !response?.setupToken) {
1676
+ throw new Error("the answer to /api/test-runs/setup names no run");
1677
+ }
1678
+ const liveViewKey = response.liveView?.key;
1679
+ const runUrl2 = answeredRunUrl(response, httpClient.baseUrl, response.runId);
1680
+ writeSetupInfo({
1681
+ runId: response.runId,
1682
+ setupToken: response.setupToken,
1683
+ projectName: opts.projectName,
1684
+ ...isLiveViewKey(liveViewKey) ? { liveViewKey } : {},
1685
+ ...response.liveView?.refused === "local" ? { liveViewLocal: true } : {},
1686
+ runUrl: runUrl2
1687
+ });
1688
+ logger2.info(`View live progress: ${runUrl2}`);
1689
+ if (isLiveViewKey(liveViewKey) && detectCi(process.env) && !relaying) {
1690
+ try {
1691
+ const stopRelay = relayRunLog((line) => logger2.info(line));
1692
+ relaying = true;
1693
+ process.once("exit", stopRelay);
1694
+ } catch (error) {
1695
+ logger2.debug(`Global setup: the live view's lines go to no file (${errorMessage(error)})`);
1696
+ }
1386
1697
  }
1387
1698
  }
1388
1699