@piwitests/reporter 0.64.0 → 0.65.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/cli/index.js CHANGED
@@ -1022,6 +1022,26 @@ function desktopAppMode(option, envValue) {
1022
1022
  return "fallback";
1023
1023
  }
1024
1024
 
1025
+ // src/internal/transport/http-client.ts
1026
+ var https = __toESM(require("https"));
1027
+ var http = __toESM(require("http"));
1028
+ var import_node_url2 = require("url");
1029
+ var import_form_data = __toESM(require("form-data"));
1030
+ var FAILURE_DETAIL_MAX = 500;
1031
+ function failureDetail(res) {
1032
+ let text = null;
1033
+ try {
1034
+ const body = JSON.parse(res.text);
1035
+ text = typeof body?.message === "string" ? body.message : body?.statusMessage;
1036
+ } catch {
1037
+ if (/^text\/plain\b/i.test(res.headers["content-type"] ?? "")) text = res.text;
1038
+ }
1039
+ if (typeof text !== "string") return null;
1040
+ const line = text.replace(/[\p{Cc}\s]+/gu, " ").trim();
1041
+ if (!line) return null;
1042
+ return line.length > FAILURE_DETAIL_MAX ? `${line.slice(0, FAILURE_DETAIL_MAX - 1)}\u2026` : line;
1043
+ }
1044
+
1025
1045
  // src/internal/support/connection.ts
1026
1046
  var fs6 = __toESM(require("fs"));
1027
1047
  var path9 = __toESM(require("path"));
@@ -1176,7 +1196,12 @@ async function fetchBugSpec(args, specDir) {
1176
1196
  throw new Error(`could not reach ${args.serverUrl} (${e.message})`);
1177
1197
  }
1178
1198
  if (res.status === 404) throw new Error(`no bug report #${args.id} on ${args.serverUrl}`);
1179
- if (res.status === 401 || res.status === 403) throw new Error(`the dashboard refused the API key (${res.status})`);
1199
+ if (res.status === 401) throw new Error("the dashboard refused the API key (401)");
1200
+ if (res.status === 403) {
1201
+ const contentType = res.headers.get("content-type") ?? void 0;
1202
+ const detail = failureDetail({ text: await res.text().catch(() => ""), headers: { "content-type": contentType } });
1203
+ throw new Error(`the dashboard refused the request (403)${detail ? `: ${detail}` : ""}`);
1204
+ }
1180
1205
  if (!res.ok) throw new Error(`the dashboard answered ${res.status}`);
1181
1206
  const body = await res.json();
1182
1207
  if (typeof body.code !== "string" || typeof body.path !== "string") throw new Error("the dashboard sent no spec");
@@ -1192,9 +1217,9 @@ function realFolder(dir) {
1192
1217
  return path10.join(fs7.realpathSync(current), ...rest);
1193
1218
  }
1194
1219
  function folderInRepository(root, dir) {
1195
- const relative8 = path10.relative(realFolder(root), realFolder(dir));
1196
- if (relative8.startsWith("..") || path10.isAbsolute(relative8)) return void 0;
1197
- return relative8.split(path10.sep).join("/");
1220
+ const relative9 = path10.relative(realFolder(root), realFolder(dir));
1221
+ if (relative9.startsWith("..") || path10.isAbsolute(relative9)) return void 0;
1222
+ return relative9.split(path10.sep).join("/");
1198
1223
  }
1199
1224
  function fileFilter(file) {
1200
1225
  const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -1289,21 +1314,73 @@ var VALUE_MATCHERS = /* @__PURE__ */ new Set([
1289
1314
  "toHaveCount"
1290
1315
  ]);
1291
1316
 
1317
+ // ../core/src/glob.ts
1318
+ function dotTakes(char) {
1319
+ return char !== "\n" && char !== "\r" && char !== "\u2028" && char !== "\u2029";
1320
+ }
1321
+ function canonicalize(char) {
1322
+ const upper = char.toUpperCase();
1323
+ if (upper.length !== 1) return char;
1324
+ return char.charCodeAt(0) >= 128 && upper.charCodeAt(0) < 128 ? char : upper;
1325
+ }
1326
+ function globTokens(pattern, syntax) {
1327
+ const tokens = [];
1328
+ for (let i = 0; i < pattern.length; i++) {
1329
+ const char = pattern[i];
1330
+ if (char === "*") {
1331
+ const globstar = !!syntax.segments && pattern[i + 1] === "*";
1332
+ if (globstar) i++;
1333
+ tokens.push({ kind: "run", slash: !syntax.segments || globstar });
1334
+ } else if (char === "?" && syntax.questionMark) {
1335
+ tokens.push({ kind: "one", slash: !syntax.segments });
1336
+ } else {
1337
+ tokens.push({ kind: "char", char });
1338
+ }
1339
+ }
1340
+ return tokens;
1341
+ }
1342
+ function compileGlob(tokens, ignoreCase = false) {
1343
+ const steps = ignoreCase ? tokens.map((token) => token.kind === "char" ? { ...token, char: canonicalize(token.char) } : token) : tokens;
1344
+ const end = steps.length;
1345
+ return (text) => {
1346
+ const seen = new Int32Array(end + 1).fill(-1);
1347
+ let current = [];
1348
+ let next = [];
1349
+ const reach = (list, from, step) => {
1350
+ for (let state = from; seen[state] !== step; state++) {
1351
+ seen[state] = step;
1352
+ list.push(state);
1353
+ if (state === end || steps[state].kind !== "run") break;
1354
+ }
1355
+ };
1356
+ reach(current, 0, 0);
1357
+ for (let i = 0; i < text.length; i++) {
1358
+ const char = ignoreCase ? canonicalize(text[i]) : text[i];
1359
+ const dot = dotTakes(char);
1360
+ for (const state of current) {
1361
+ if (state === end) continue;
1362
+ const token = steps[state];
1363
+ const takes = token.kind === "char" ? token.char === char : token.slash ? dot : char !== "/";
1364
+ if (takes) reach(next, token.kind === "run" ? state : state + 1, i + 1);
1365
+ }
1366
+ if (next.length === 0) return false;
1367
+ [current, next] = [next, current];
1368
+ next.length = 0;
1369
+ }
1370
+ return seen[end] === text.length;
1371
+ };
1372
+ }
1373
+ function globMatcher(pattern, syntax = {}) {
1374
+ return compileGlob(globTokens(pattern, syntax), syntax.ignoreCase);
1375
+ }
1376
+
1292
1377
  // ../core/src/function-match.ts
1293
1378
  function paramArgKey(source) {
1294
1379
  return source.path ? `${source.param}.${source.path}` : source.param;
1295
1380
  }
1296
- function globToRegExp(glob) {
1297
- const escaped = glob.split("**").map((part) => part.replace(/[.?+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*")).join(".*");
1298
- return new RegExp(`^${escaped}$`);
1299
- }
1300
1381
  function urlMatches(pattern, url) {
1301
1382
  if (!pattern) return true;
1302
- try {
1303
- return globToRegExp(pattern).test(url);
1304
- } catch {
1305
- return true;
1306
- }
1383
+ return globMatcher(pattern, { segments: true })(url);
1307
1384
  }
1308
1385
  function scoreTargetMatch(pattern, candidate) {
1309
1386
  if (!candidate) return pattern.role || pattern.testId || pattern.name ? 0 : 0.3;
@@ -3150,28 +3227,45 @@ function segmentMatches(pattern, segment) {
3150
3227
  while (pattern[p] === "*") p++;
3151
3228
  return p === pattern.length;
3152
3229
  }
3230
+ var LINE_TERMINATOR = /[\n\r\u2028\u2029]/;
3231
+ function cleanTails(parts) {
3232
+ const clean = new Uint8Array(parts.length + 1);
3233
+ clean[parts.length] = 1;
3234
+ for (let j = parts.length - 1; j >= 0; j--) clean[j] = clean[j + 1] && !LINE_TERMINATOR.test(parts[j]) ? 1 : 0;
3235
+ return clean;
3236
+ }
3153
3237
  function pathPatternMatcher(pattern) {
3154
3238
  const { segments, floating } = patternParts(pattern);
3155
3239
  if (floating) {
3156
3240
  const only = segments[0];
3157
- return (path25) => path25.split("/").some((part) => segmentMatches(only, part));
3241
+ if (only === "**") return (path25) => !LINE_TERMINATOR.test(path25);
3242
+ return (path25) => {
3243
+ const parts = path25.split("/");
3244
+ const clean = cleanTails(parts);
3245
+ for (let j = 0; j < parts.length; j++) {
3246
+ if (segmentMatches(only, parts[j]) && clean[j + 1]) return true;
3247
+ if (LINE_TERMINATOR.test(parts[j])) return false;
3248
+ }
3249
+ return false;
3250
+ };
3158
3251
  }
3159
3252
  return (path25) => {
3160
3253
  const parts = path25.split("/");
3254
+ const clean = cleanTails(parts);
3161
3255
  let at = new Uint8Array(parts.length);
3162
3256
  at[0] = 1;
3163
3257
  for (let i = 0; i < segments.length; i++) {
3164
3258
  const segment = segments[i];
3165
3259
  const isLast = i === segments.length - 1;
3166
3260
  if (segment === "**") {
3167
- if (isLast) return at.includes(1);
3261
+ if (isLast) return at.some((reached, j) => reached === 1 && clean[j] === 1);
3168
3262
  for (let j = 1; j < parts.length; j++) if (at[j - 1] && parts[j - 1] !== "") at[j] = 1;
3169
3263
  continue;
3170
3264
  }
3171
3265
  const next = new Uint8Array(parts.length);
3172
3266
  for (let j = 0; j < parts.length; j++) {
3173
3267
  if (!at[j] || !segmentMatches(segment, parts[j])) continue;
3174
- if (isLast) return true;
3268
+ if (isLast && clean[j + 1]) return true;
3175
3269
  if (j + 1 < parts.length) next[j + 1] = 1;
3176
3270
  }
3177
3271
  at = next;
@@ -3241,6 +3335,7 @@ function compileCoverageScope(scope) {
3241
3335
 
3242
3336
  // src/internal/collect/metadata-collector.ts
3243
3337
  var import_node_child_process3 = require("child_process");
3338
+ var import_node_util = require("util");
3244
3339
 
3245
3340
  // src/internal/support/errors.ts
3246
3341
  function errorMessage(error) {
@@ -3844,8 +3939,8 @@ function relativeTo(path25, root) {
3844
3939
  const head = path25.slice(0, base.length);
3845
3940
  const inside = drive ? head.toLowerCase() === base.toLowerCase() : head === base;
3846
3941
  if (!inside) return null;
3847
- const relative8 = path25.slice(base.length);
3848
- return relative8 || null;
3942
+ const relative9 = path25.slice(base.length);
3943
+ return relative9 || null;
3849
3944
  }
3850
3945
  function reportPathCandidates(raw, { repoRoot, bases }) {
3851
3946
  const slash = (value) => value.replace(/\\/g, "/");
@@ -3856,8 +3951,8 @@ function reportPathCandidates(raw, { repoRoot, bases }) {
3856
3951
  const add = (absolute) => {
3857
3952
  const normalized = normalizeSlashPath(absolute);
3858
3953
  if (!normalized) return;
3859
- const relative8 = normalized.startsWith("/_/") ? normalized.slice(3) : relativeTo(normalized, root);
3860
- if (relative8 && !out.includes(relative8)) out.push(relative8);
3954
+ const relative9 = normalized.startsWith("/_/") ? normalized.slice(3) : relativeTo(normalized, root);
3955
+ if (relative9 && !out.includes(relative9)) out.push(relative9);
3861
3956
  };
3862
3957
  if (isAbsolutePath(path25)) {
3863
3958
  add(path25);
@@ -4636,21 +4731,21 @@ function formatP(p) {
4636
4731
  }
4637
4732
  var FlakeError = class extends Error {
4638
4733
  };
4639
- async function getJson(http, url) {
4640
- const res = await fetch(`${http.serverUrl}${url}`, { headers: http.headers });
4734
+ async function getJson(http2, url) {
4735
+ const res = await fetch(`${http2.serverUrl}${url}`, { headers: http2.headers });
4641
4736
  if (!res.ok) {
4642
4737
  const body = await res.json().catch(() => ({}));
4643
4738
  throw new FlakeError(body.message || `the dashboard returned ${res.status} for ${url.split("?")[0]}`);
4644
4739
  }
4645
4740
  return await res.json();
4646
4741
  }
4647
- async function resolveTestCase(http, test, project, apiKey) {
4742
+ async function resolveTestCase(http2, test, project, apiKey) {
4648
4743
  if (/^\d+$/.test(test)) return Number(test);
4649
4744
  const m = /^(.+):(\d+)$/.exec(test);
4650
4745
  if (!m) throw new FlakeError(`"${test}" is neither a test case id nor file:line`);
4651
- const projectId = await resolveProjectId({ serverUrl: http.serverUrl, apiKey, project, key: "" });
4746
+ const projectId = await resolveProjectId({ serverUrl: http2.serverUrl, apiKey, project, key: "" });
4652
4747
  const found = await getJson(
4653
- http,
4748
+ http2,
4654
4749
  `/api/projects/${projectId}/flake-lab/test?location=${encodeURIComponent(`${m[1].replace(/\\/g, "/")}:${m[2]}`)}`
4655
4750
  );
4656
4751
  return found.testCaseId;
@@ -4880,12 +4975,12 @@ async function loadPlan(args, commit) {
4880
4975
  "no dashboard to read the plan from: pass --server-url or set PIWI_DASHBOARD_URL (or run it offline with --plan <file>)"
4881
4976
  );
4882
4977
  }
4883
- const http = {
4978
+ const http2 = {
4884
4979
  serverUrl: connection.serverUrl,
4885
4980
  headers: connection.apiKey ? { "X-API-Key": connection.apiKey } : {}
4886
4981
  };
4887
4982
  try {
4888
- const testCaseId = await resolveTestCase(http, args.test, connection.project, connection.apiKey);
4983
+ const testCaseId = await resolveTestCase(http2, args.test, connection.project, connection.apiKey);
4889
4984
  const params = new URLSearchParams({
4890
4985
  kind: args.verify ? "verify" : "reproduce",
4891
4986
  source: args.source ?? (process.env.CI ? "ci" : "cli"),
@@ -4894,7 +4989,7 @@ async function loadPlan(args, commit) {
4894
4989
  });
4895
4990
  if (commit) params.set("commit", commit);
4896
4991
  if (args.runs) params.set("runs", String(args.runs));
4897
- return { plan: await getJson(http, `/api/test-cases/${testCaseId}/flake-plan?${params}`), http };
4992
+ return { plan: await getJson(http2, `/api/test-cases/${testCaseId}/flake-plan?${params}`), http: http2 };
4898
4993
  } catch (error) {
4899
4994
  if (error instanceof FlakeError) throw error;
4900
4995
  throw new FlakeError(
@@ -4927,9 +5022,9 @@ async function runFlake(argv, runner) {
4927
5022
  }
4928
5023
  const commit = gitHead();
4929
5024
  let plan;
4930
- let http;
5025
+ let http2;
4931
5026
  try {
4932
- ({ plan, http } = await loadPlan(args, commit));
5027
+ ({ plan, http: http2 } = await loadPlan(args, commit));
4933
5028
  } catch (error) {
4934
5029
  console.error(`piwi flake: ${error.message}`);
4935
5030
  return EXIT_ERROR5;
@@ -4976,11 +5071,11 @@ ${tail}`);
4976
5071
  const { verdict, reproducingArm } = sessionVerdict(plan.kind, session.arms);
4977
5072
  const ran = [session.control, ...session.arms.filter((a) => !a.skipped)];
4978
5073
  let uploaded = false;
4979
- if (args.upload && http && plan.experimentId) {
5074
+ if (args.upload && http2 && plan.experimentId) {
4980
5075
  try {
4981
- const res = await fetch(`${http.serverUrl}/api/projects/${plan.projectId}/flake-lab/results`, {
5076
+ const res = await fetch(`${http2.serverUrl}/api/projects/${plan.projectId}/flake-lab/results`, {
4982
5077
  method: "POST",
4983
- headers: { "Content-Type": "application/json", ...http.headers },
5078
+ headers: { "Content-Type": "application/json", ...http2.headers },
4984
5079
  body: JSON.stringify({
4985
5080
  experimentId: plan.experimentId,
4986
5081
  commit,
@@ -5236,15 +5331,20 @@ async function runGate(argv, env = process.env, cwd = process.cwd()) {
5236
5331
  if (argv.includes("--json")) {
5237
5332
  console.log(JSON.stringify(result, null, 2));
5238
5333
  } else {
5239
- console.log(formatGateResult(result));
5334
+ const { runUrl } = result.facts;
5335
+ const link = runUrl.startsWith("/") ? `${args.serverUrl}${runUrl}` : runUrl;
5336
+ console.log(formatGateResult({ ...result, facts: { ...result.facts, runUrl: link } }));
5240
5337
  }
5241
5338
  if (result.verdict === "inconclusive") return EXIT_INCONCLUSIVE;
5242
5339
  return result.passed ? EXIT_OK5 : EXIT_VIOLATED;
5243
5340
  }
5244
5341
 
5245
5342
  // src/cli/init.ts
5343
+ var import_node_child_process7 = require("child_process");
5246
5344
  var fs16 = __toESM(require("fs"));
5247
5345
  var path20 = __toESM(require("path"));
5346
+ var readline = __toESM(require("readline"));
5347
+ var tty = __toESM(require("tty"));
5248
5348
 
5249
5349
  // src/cli/report.ts
5250
5350
  var STATUS_MARK = {
@@ -5287,13 +5387,25 @@ function readPackageJson(root) {
5287
5387
  return { pkg: null, pkgPath: null };
5288
5388
  }
5289
5389
  }
5290
- function detectPackageManager(root, pkg) {
5390
+ function declaredPackageManager(dir, pkg) {
5291
5391
  const declared = pkg?.packageManager?.split("@")[0];
5292
5392
  if (declared === "pnpm" || declared === "yarn" || declared === "bun" || declared === "npm") return declared;
5293
5393
  for (const [file, manager] of LOCKFILES) {
5294
- if (fs14.existsSync(path18.join(root, file))) return manager;
5394
+ if (fs14.existsSync(path18.join(dir, file))) return manager;
5395
+ }
5396
+ return null;
5397
+ }
5398
+ function detectPackageManager(root, pkg) {
5399
+ let dir = root;
5400
+ let dirPkg = pkg;
5401
+ for (; ; ) {
5402
+ const manager = declaredPackageManager(dir, dirPkg);
5403
+ if (manager) return manager;
5404
+ const parent = path18.dirname(dir);
5405
+ if (parent === dir || fs14.existsSync(path18.join(dir, ".git"))) return "npm";
5406
+ dir = parent;
5407
+ dirPkg = readPackageJson(dir).pkg;
5295
5408
  }
5296
- return "npm";
5297
5409
  }
5298
5410
  function findConfig(root) {
5299
5411
  for (const name of CONFIG_NAMES2) {
@@ -5314,6 +5426,91 @@ function hasReporter(pkg) {
5314
5426
  if (!pkg) return false;
5315
5427
  return Boolean(pkg.dependencies?.[REPORTER_PACKAGE] || pkg.devDependencies?.[REPORTER_PACKAGE]);
5316
5428
  }
5429
+ function stringList(value) {
5430
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
5431
+ }
5432
+ function yamlScalar(text) {
5433
+ const value = text.trim();
5434
+ const quoted2 = /^(['"])(.*?)\1/.exec(value);
5435
+ return quoted2 ? quoted2[2] : value.replace(/\s+#.*$/, "").trim();
5436
+ }
5437
+ function pnpmWorkspaceGlobs(yaml) {
5438
+ const flow = /^packages\s*:\s*\[([^\]]*)\]/m.exec(yaml);
5439
+ if (flow) return flow[1].split(",").map(yamlScalar).filter(Boolean);
5440
+ const lines = yaml.split(/\r?\n/);
5441
+ const start = lines.findIndex((line) => /^packages\s*:\s*(#.*)?$/.test(line));
5442
+ if (start === -1) return [];
5443
+ const globs = [];
5444
+ for (const line of lines.slice(start + 1)) {
5445
+ if (/^\s*(#.*)?$/.test(line)) continue;
5446
+ const item = /^\s*-\s+(.*)$/.exec(line);
5447
+ if (!item) break;
5448
+ globs.push(yamlScalar(item[1]));
5449
+ }
5450
+ return globs.filter(Boolean);
5451
+ }
5452
+ function workspaceGlobs(root, pkg) {
5453
+ const declared = pkg?.workspaces;
5454
+ const globs = stringList(
5455
+ typeof declared === "object" && declared !== null && "packages" in declared ? declared.packages : declared
5456
+ );
5457
+ try {
5458
+ globs.push(...pnpmWorkspaceGlobs(fs14.readFileSync(path18.join(root, "pnpm-workspace.yaml"), "utf-8")));
5459
+ } catch {
5460
+ }
5461
+ return globs;
5462
+ }
5463
+ function isDirectory(dir) {
5464
+ try {
5465
+ return fs14.statSync(dir).isDirectory();
5466
+ } catch {
5467
+ return false;
5468
+ }
5469
+ }
5470
+ function subfolders(dir) {
5471
+ try {
5472
+ return fs14.readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && entry.name !== "node_modules" && !entry.name.startsWith(".")).map((entry) => path18.join(dir, entry.name));
5473
+ } catch {
5474
+ return [];
5475
+ }
5476
+ }
5477
+ function namePattern(segment) {
5478
+ const source = segment.split(/([*?])/).map((part) => part === "*" ? ".*" : part === "?" ? "." : part.replace(/[.+^${}()|[\]\\]/g, "\\$&")).join("");
5479
+ return new RegExp(`^${source}$`);
5480
+ }
5481
+ function expandGlob(root, glob) {
5482
+ const segments = glob.split("/").filter((segment) => segment !== "" && segment !== ".");
5483
+ const found = [];
5484
+ const walk = (dir, index) => {
5485
+ if (index === segments.length) {
5486
+ found.push(dir);
5487
+ return;
5488
+ }
5489
+ const segment = segments[index];
5490
+ if (segment === "**") {
5491
+ walk(dir, index + 1);
5492
+ for (const child of subfolders(dir)) walk(child, index);
5493
+ } else if (/[*?]/.test(segment)) {
5494
+ const pattern = namePattern(segment);
5495
+ for (const child of subfolders(dir)) if (pattern.test(path18.basename(child))) walk(child, index + 1);
5496
+ } else if (isDirectory(path18.join(dir, segment))) {
5497
+ walk(path18.join(dir, segment), index + 1);
5498
+ }
5499
+ };
5500
+ walk(root, 0);
5501
+ return found;
5502
+ }
5503
+ function workspacePackagesWithConfig(root) {
5504
+ const absRoot = path18.resolve(root);
5505
+ const globs = workspaceGlobs(absRoot, readPackageJson(absRoot).pkg);
5506
+ const excluded = new Set(
5507
+ globs.filter((glob) => glob.startsWith("!")).flatMap((glob) => expandGlob(absRoot, glob.slice(1)))
5508
+ );
5509
+ const packages = new Set(
5510
+ globs.filter((glob) => !glob.startsWith("!")).flatMap((glob) => expandGlob(absRoot, glob)).filter((dir) => dir !== absRoot && !excluded.has(dir) && fs14.existsSync(path18.join(dir, "package.json")))
5511
+ );
5512
+ return [...packages].filter((dir) => findConfig(dir) !== null).map((dir) => path18.relative(absRoot, dir).split(path18.sep).join("/")).sort();
5513
+ }
5317
5514
  function detectProject(root) {
5318
5515
  const absRoot = path18.resolve(root);
5319
5516
  const { pkg, pkgPath } = readPackageJson(absRoot);
@@ -5384,7 +5581,7 @@ function matchClosingParen(src, openIndex) {
5384
5581
  }
5385
5582
  function optionsLiteral(opts) {
5386
5583
  const lines = [];
5387
- if (opts.serverUrl) lines.push(` serverUrl: ${quote2(opts.serverUrl)},`);
5584
+ if (opts.serverUrl) lines.push(` serverUrl: process.env.PIWI_DASHBOARD_URL || ${quote2(opts.serverUrl)},`);
5388
5585
  lines.push(` projectName: ${quote2(opts.projectName)},`);
5389
5586
  if (opts.desktopApp) lines.push(` desktopApp: ${quote2(opts.desktopApp)},`);
5390
5587
  return `{
@@ -5440,7 +5637,7 @@ function upsertEnvKeys(existing, entries) {
5440
5637
  let text = existing;
5441
5638
  const added = [];
5442
5639
  for (const [key, value] of entries) {
5443
- if (new RegExp(`^\\s*${key}=`, "m").test(text)) continue;
5640
+ if (new RegExp(`^\\s*(?:export\\s+)?${key}\\s*=`, "m").test(text)) continue;
5444
5641
  if (text.length && !text.endsWith("\n")) text += "\n";
5445
5642
  text += `${key}=${value}
5446
5643
  `;
@@ -5448,6 +5645,28 @@ function upsertEnvKeys(existing, entries) {
5448
5645
  }
5449
5646
  return { text, added };
5450
5647
  }
5648
+ function recordDevDependency(source, name, range) {
5649
+ let pkg;
5650
+ try {
5651
+ pkg = JSON.parse(source);
5652
+ } catch {
5653
+ return { text: source, status: "manual" };
5654
+ }
5655
+ if (!pkg || typeof pkg !== "object" || Array.isArray(pkg)) return { text: source, status: "manual" };
5656
+ const record = pkg;
5657
+ const listed = (field) => {
5658
+ const value = record[field];
5659
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
5660
+ };
5661
+ if (name in listed("dependencies") || name in listed("devDependencies")) return { text: source, status: "already" };
5662
+ record.devDependencies = Object.fromEntries(
5663
+ Object.entries({ ...listed("devDependencies"), [name]: range }).sort(([a], [b]) => a.localeCompare(b, "en"))
5664
+ );
5665
+ const indent = /^[ \t]+(?=")/m.exec(source)?.[0] ?? " ";
5666
+ const eol = source.includes("\r\n") ? "\r\n" : "\n";
5667
+ const text = JSON.stringify(record, null, indent).replace(/\n/g, eol) + (source.endsWith("\n") ? eol : "");
5668
+ return { text, status: "updated" };
5669
+ }
5451
5670
  function ensureGitignoreEntry(existing, entry = ".env") {
5452
5671
  const present = existing.split(/\r?\n/).some((line) => line.trim() === entry);
5453
5672
  if (present) return { text: existing, added: false };
@@ -5712,6 +5931,12 @@ What it does (each step is idempotent and safe to re-run):
5712
5931
  - records PIWI_* connection settings in .env / .env.example and .gitignore
5713
5932
  - installs the Piwi agent skills so your coding agent can use them
5714
5933
 
5934
+ In a monorepo, run it in the package that holds the playwright.config, or pass
5935
+ --cwd <package>. At a workspace root with no playwright.config of its own
5936
+ ("workspaces" in package.json, or pnpm-workspace.yaml), it wires the workspace
5937
+ package that has one. When several have one, it asks which in a terminal; in CI,
5938
+ without a terminal or with --json, it wires none and lists them.
5939
+
5715
5940
  Options:
5716
5941
  --server-url <url> Dashboard URL to write into the config (env PIWI_DASHBOARD_URL,
5717
5942
  default ${DEFAULT_SERVER_URL})
@@ -5721,8 +5946,9 @@ Options:
5721
5946
  --desktop-app <mode> Write desktopApp into the config: "prefer" sends local runs to the
5722
5947
  Piwi desktop app while it runs, and CI runs to --server-url
5723
5948
  --api-key <key> API key to write into .env (env PIWI_API_KEY), where the reporter
5724
- reads it. Omit to keep it a .env.example placeholder you fill in
5725
- yourself.
5949
+ reads it; never into a .env git tracks or cannot say it does not,
5950
+ nor through a link. Omit to keep it a .env.example placeholder you
5951
+ fill in yourself.
5726
5952
  --cwd <path> Project root to operate on (default: current directory)
5727
5953
  --skills <list> Comma-separated skills to install, or "all" / "none"
5728
5954
  (default: ${WORKFLOW_SKILLS.join(", ")})
@@ -5753,15 +5979,18 @@ function resolveSkillSlugs(raw) {
5753
5979
  return raw.split(",").map((slug) => slug.trim()).filter(Boolean);
5754
5980
  }
5755
5981
  function parseInitArgs(argv, env, cwd) {
5756
- const root = path20.resolve(readOption6(argv, "--cwd") ?? cwd);
5982
+ const root = path20.resolve(cwd, readOption6(argv, "--cwd") ?? ".");
5757
5983
  const detected = detectProject(root);
5984
+ const noServerUrl = argv.includes("--no-server-url");
5985
+ const flagKey = readOption6(argv, "--api-key");
5758
5986
  return {
5759
5987
  root,
5760
- serverUrl: argv.includes("--no-server-url") ? "" : (readOption6(argv, "--server-url") ?? env.PIWI_DASHBOARD_URL ?? DEFAULT_SERVER_URL).replace(/\/$/, ""),
5988
+ serverUrl: noServerUrl ? "" : (readOption6(argv, "--server-url") ?? env.PIWI_DASHBOARD_URL ?? DEFAULT_SERVER_URL).replace(/\/$/, ""),
5761
5989
  projectName: readOption6(argv, "--project") ?? detected.suggestedProjectName,
5762
5990
  desktopApp: argv.includes("--desktop-app") ? readOption6(argv, "--desktop-app") ?? "" : null,
5763
5991
  // The desktop app needs no key, and a key with no URL keeps the reporter from finding it.
5764
- apiKey: argv.includes("--no-server-url") ? null : readOption6(argv, "--api-key") ?? env.PIWI_API_KEY ?? null,
5992
+ apiKey: noServerUrl ? null : flagKey ?? env.PIWI_API_KEY ?? null,
5993
+ apiKeyFromEnv: !noServerUrl && flagKey === void 0 && Boolean(env.PIWI_API_KEY),
5765
5994
  skillsDir: readOption6(argv, "--skills-dir") ?? DEFAULT_SKILLS_DIR,
5766
5995
  skillSlugs: resolveSkillSlugs(readOption6(argv, "--skills")),
5767
5996
  install: !argv.includes("--no-install"),
@@ -5801,8 +6030,8 @@ function stepInstallReporter(project, opts) {
5801
6030
  status: "manual",
5802
6031
  detail: `No package.json here \u2014 run \`npm init\`, then \`${installCommand(project.packageManager)}\``
5803
6032
  };
5804
- if (opts.dryRun || !opts.install)
5805
- return { step, status: "manual", detail: `Run \`${installCommand(project.packageManager)}\`` };
6033
+ if (!opts.install) return stepRecordReporter(project, opts);
6034
+ if (opts.dryRun) return { step, status: "manual", detail: `Run \`${installCommand(project.packageManager)}\`` };
5806
6035
  const [command, args] = installArgv(project.packageManager);
5807
6036
  const status = runPackageManager(command, args, opts.root);
5808
6037
  if (status === 0) return { step, status: "updated", detail: `Installed ${REPORTER_PACKAGE}` };
@@ -5812,6 +6041,28 @@ function stepInstallReporter(project, opts) {
5812
6041
  detail: `\`${installCommand(project.packageManager)}\` failed (exit ${status ?? "unknown"}) \u2014 install it by hand`
5813
6042
  };
5814
6043
  }
6044
+ function stepRecordReporter(project, opts) {
6045
+ const step = "dependency";
6046
+ const file = "package.json";
6047
+ const version = readTemplatesVersion(findTemplatesDir(__dirname));
6048
+ const range = version === "0.0.0" ? "latest" : `^${version}`;
6049
+ const pkgPath = project.packageJsonPath ?? path20.join(project.root, file);
6050
+ const edit = recordDevDependency(readFileOr(pkgPath, ""), REPORTER_PACKAGE, range);
6051
+ if (edit.status === "manual")
6052
+ return {
6053
+ step,
6054
+ file,
6055
+ status: "manual",
6056
+ detail: `Could not read package.json \u2014 run \`${installCommand(project.packageManager)}\``
6057
+ };
6058
+ if (edit.status === "updated" && !opts.dryRun) fs16.writeFileSync(pkgPath, edit.text);
6059
+ return {
6060
+ step,
6061
+ file,
6062
+ status: edit.status,
6063
+ detail: edit.status === "updated" ? `Recorded ${REPORTER_PACKAGE} ${range} in devDependencies \u2014 run \`${project.packageManager} install\` to install it` : `${REPORTER_PACKAGE} is already a dependency`
6064
+ };
6065
+ }
5815
6066
  function stepConfig(project, opts) {
5816
6067
  const step = "config";
5817
6068
  if (!project.configPath)
@@ -5865,7 +6116,44 @@ function stepFixtures(project, opts) {
5865
6116
  detail: "Created capture fixtures \u2014 import `test` from here in your specs"
5866
6117
  };
5867
6118
  }
5868
- function stepEnv(project, opts) {
6119
+ function gitTracking(root, file) {
6120
+ const { status } = (0, import_node_child_process7.spawnSync)("git", ["ls-files", "--error-unmatch", "--", file], {
6121
+ cwd: root,
6122
+ stdio: "ignore",
6123
+ windowsHide: true
6124
+ });
6125
+ if (status === 0) return "tracked";
6126
+ if (status === 1) return "untracked";
6127
+ return inRepository(root) ? "unknown" : "untracked";
6128
+ }
6129
+ function inRepository(dir) {
6130
+ for (let current = path20.resolve(dir); ; current = path20.dirname(current)) {
6131
+ if (fs16.existsSync(path20.join(current, ".git"))) return true;
6132
+ if (path20.dirname(current) === current) return false;
6133
+ }
6134
+ }
6135
+ var KEY_IN_ENVIRONMENT = "set PIWI_API_KEY in the environment (in CI, as a secret)";
6136
+ function envKeyBlock(root) {
6137
+ const tracking = gitTracking(root, ".env");
6138
+ if (tracking === "tracked") {
6139
+ return {
6140
+ why: "git tracks .env",
6141
+ instead: `${KEY_IN_ENVIRONMENT}, or untrack the file with \`git rm --cached .env\``
6142
+ };
6143
+ }
6144
+ if (tracking === "unknown") {
6145
+ return {
6146
+ why: "git did not say whether it tracks .env",
6147
+ instead: `${KEY_IN_ENVIRONMENT}, or make \`git ls-files .env\` work here`
6148
+ };
6149
+ }
6150
+ const env = fs16.lstatSync(path20.join(root, ".env"), { throwIfNoEntry: false });
6151
+ if (env && (env.isSymbolicLink() || env.nlink > 1)) {
6152
+ return { why: ".env is a link", instead: `${KEY_IN_ENVIRONMENT}, or put a file of its own in place of the link` };
6153
+ }
6154
+ return null;
6155
+ }
6156
+ function stepEnv(project, opts, envBlock) {
5869
6157
  const results = [];
5870
6158
  const examplePath = path20.join(project.root, ".env.example");
5871
6159
  const example = upsertEnvKeys(readFileOr(examplePath, ""), [
@@ -5879,7 +6167,21 @@ function stepEnv(project, opts) {
5879
6167
  status: example.added.length ? "updated" : "already",
5880
6168
  detail: example.added.length ? `Recorded ${example.added.join(", ")}` : "connection template already present"
5881
6169
  });
5882
- if (opts.apiKey) {
6170
+ if (opts.apiKey && envBlock && opts.apiKeyFromEnv) {
6171
+ results.push({
6172
+ step: "env",
6173
+ file: ".env",
6174
+ status: "already",
6175
+ detail: `PIWI_API_KEY is set in the environment, where the reporter reads it; ${envBlock.why}, so no key is written into it`
6176
+ });
6177
+ } else if (opts.apiKey && envBlock) {
6178
+ results.push({
6179
+ step: "env",
6180
+ file: ".env",
6181
+ status: "manual",
6182
+ detail: `${envBlock.why}, so the API key is not written into it \u2014 ${envBlock.instead} and run init again`
6183
+ });
6184
+ } else if (opts.apiKey) {
5883
6185
  const envPath = path20.join(project.root, ".env");
5884
6186
  const entries = [["PIWI_API_KEY", opts.apiKey]];
5885
6187
  if (opts.serverUrl) entries.unshift(["PIWI_DASHBOARD_URL", opts.serverUrl]);
@@ -5903,9 +6205,13 @@ function stepEnv(project, opts) {
5903
6205
  }
5904
6206
  return results;
5905
6207
  }
5906
- function nextSteps(opts, steps) {
6208
+ function nextSteps(opts, steps, envBlock) {
5907
6209
  const out = [];
5908
- if (!opts.apiKey && opts.serverUrl) {
6210
+ if (!opts.apiKey && opts.serverUrl && envBlock) {
6211
+ out.push(
6212
+ `If your dashboard has authentication on, create an API key (Settings \u2192 Account \u2192 API keys). ${envBlock.why}, so keep the key out of it: ${envBlock.instead}.`
6213
+ );
6214
+ } else if (!opts.apiKey && opts.serverUrl) {
5909
6215
  out.push(
5910
6216
  "If your dashboard has authentication on, create an API key (Settings \u2192 Account \u2192 API keys) and put it in .env as PIWI_API_KEY: the reporter reads it from the .env next to your Playwright config. Keep .env out of git; in CI, set PIWI_API_KEY as a secret."
5911
6217
  );
@@ -5930,23 +6236,125 @@ function nextSteps(opts, steps) {
5930
6236
  );
5931
6237
  return out;
5932
6238
  }
5933
- async function runInit(argv, env = process.env, cwd = process.cwd()) {
6239
+ function askLine(question, input, output) {
6240
+ return new Promise((resolve11) => {
6241
+ const rl = readline.createInterface({ input, output });
6242
+ rl.once("close", () => resolve11(null));
6243
+ rl.once("SIGINT", () => rl.close());
6244
+ rl.question(question, (answer) => {
6245
+ resolve11(answer);
6246
+ rl.close();
6247
+ });
6248
+ });
6249
+ }
6250
+ function terminalAsk(env, isTerminal = tty.isatty) {
6251
+ if (detectCi(env) || !isTerminal(0) || !isTerminal(1)) return null;
6252
+ return (question) => askLine(question, process.stdin, process.stdout);
6253
+ }
6254
+ async function choosePackage(packages, ask) {
6255
+ console.log(`
6256
+ No playwright.config here, and ${packages.length} workspace packages have one:
6257
+ `);
6258
+ packages.forEach((pkg, index) => console.log(` ${index + 1}. ${pkg}`));
6259
+ console.log("");
6260
+ for (; ; ) {
6261
+ const answer = (await ask(`Which one should init wire? [1-${packages.length}, Enter for none] `))?.trim();
6262
+ if (!answer) return null;
6263
+ const choice = Number(answer);
6264
+ if (Number.isInteger(choice) && choice >= 1 && choice <= packages.length) return packages[choice - 1];
6265
+ }
6266
+ }
6267
+ async function chooseWorkspacePackage(root, ask) {
6268
+ const packages = workspacePackagesWithConfig(root);
6269
+ if (!packages.length) return null;
6270
+ if (packages.length === 1) return { root, packages, wired: packages[0] };
6271
+ return { root, packages, wired: ask ? await choosePackage(packages, ask) : null };
6272
+ }
6273
+ function inPackage(opts, argv, root) {
6274
+ return { ...opts, root, projectName: readOption6(argv, "--project") ?? detectProject(root).suggestedProjectName };
6275
+ }
6276
+ function unwiredWorkspace(workspace, cwd) {
6277
+ const flags = workspace.packages.map(
6278
+ (pkg) => `\`--cwd ${path20.relative(cwd, path20.join(workspace.root, pkg)) || "."}\``
6279
+ );
6280
+ return {
6281
+ step: {
6282
+ step: "config",
6283
+ status: "manual",
6284
+ detail: `No playwright.config here; ${workspace.packages.length} workspace packages have one (${workspace.packages.join(", ")}) \u2014 run init again with \`--cwd <package>\` for the one to wire`
6285
+ },
6286
+ guidance: [
6287
+ `Run the same command again with ${flags.slice(0, -1).join(", ")} or ${flags[flags.length - 1]}, for the package to wire.`
6288
+ ]
6289
+ };
6290
+ }
6291
+ function printOutcome(opts, project, workspace, steps, guidance) {
6292
+ if (opts.json) {
6293
+ console.log(
6294
+ JSON.stringify(
6295
+ {
6296
+ dryRun: opts.dryRun,
6297
+ project: {
6298
+ root: project.root,
6299
+ packageManager: project.packageManager,
6300
+ configPath: project.configPath ? path20.relative(project.root, project.configPath) : null,
6301
+ projectName: opts.projectName,
6302
+ serverUrl: opts.serverUrl,
6303
+ desktopApp: opts.desktopApp
6304
+ },
6305
+ ...workspace ? { workspace } : {},
6306
+ steps,
6307
+ nextSteps: guidance
6308
+ },
6309
+ null,
6310
+ 2
6311
+ )
6312
+ );
6313
+ return;
6314
+ }
6315
+ if (workspace?.wired && workspace.packages.length === 1) {
6316
+ console.log(
6317
+ `
6318
+ No playwright.config here, so init wires ${workspace.wired}, the one workspace package that has one.`
6319
+ );
6320
+ }
6321
+ const where = workspace?.wired ? ` in ${workspace.wired}` : "";
6322
+ console.log(`
6323
+ Piwi setup${opts.dryRun ? " (dry run \u2014 nothing written)" : ""} for "${opts.projectName}"${where}:
6324
+ `);
6325
+ for (const step of steps) console.log(formatStep(step));
6326
+ console.log("\nNext:");
6327
+ for (const line of guidance) console.log(` \u2022 ${line}`);
6328
+ console.log("");
6329
+ }
6330
+ async function runInit(argv, env = process.env, cwd = process.cwd(), ask = terminalAsk(env)) {
5934
6331
  if (argv.includes("-h") || argv.includes("--help")) {
5935
6332
  console.log(USAGE8);
5936
6333
  return 0;
5937
6334
  }
5938
- const opts = parseInitArgs(argv, env, cwd);
6335
+ let opts = parseInitArgs(argv, env, cwd);
5939
6336
  if (opts.desktopApp !== null && !DESKTOP_APP_MODES2.includes(opts.desktopApp)) {
5940
6337
  console.error(`--desktop-app must be one of ${DESKTOP_APP_MODES2.join(", ")} (got "${opts.desktopApp}")`);
5941
6338
  return 1;
5942
6339
  }
5943
- const project = detectProject(opts.root);
6340
+ let project = detectProject(opts.root);
6341
+ const workspace = opts.skillsOnly || project.configPath ? null : await chooseWorkspacePackage(project.root, opts.json ? null : ask);
6342
+ if (workspace && !workspace.wired) {
6343
+ const { step, guidance } = unwiredWorkspace(workspace, cwd);
6344
+ printOutcome(opts, project, workspace, [step], guidance);
6345
+ return 0;
6346
+ }
6347
+ if (workspace?.wired) {
6348
+ opts = inPackage(opts, argv, path20.join(workspace.root, workspace.wired));
6349
+ project = detectProject(opts.root);
6350
+ }
5944
6351
  const steps = [];
6352
+ const envBlock = envKeyBlock(project.root);
5945
6353
  if (!opts.skillsOnly) {
5946
6354
  steps.push(stepInstallReporter(project, opts));
5947
6355
  steps.push(stepConfig(project, opts));
5948
6356
  steps.push(stepFixtures(project, opts));
5949
- steps.push(...stepEnv(project, opts));
6357
+ steps.push(...stepEnv(project, opts, envBlock));
5950
6358
  }
5951
6359
  if (!opts.noSkills && opts.skillSlugs.length) {
5952
6360
  steps.push(
@@ -5960,43 +6368,14 @@ async function runInit(argv, env = process.env, cwd = process.cwd()) {
5960
6368
  })
5961
6369
  );
5962
6370
  }
5963
- const guidance = nextSteps(opts, steps);
5964
- if (opts.json) {
5965
- console.log(
5966
- JSON.stringify(
5967
- {
5968
- dryRun: opts.dryRun,
5969
- project: {
5970
- root: project.root,
5971
- packageManager: project.packageManager,
5972
- configPath: project.configPath ? path20.relative(project.root, project.configPath) : null,
5973
- projectName: opts.projectName,
5974
- serverUrl: opts.serverUrl,
5975
- desktopApp: opts.desktopApp
5976
- },
5977
- steps,
5978
- nextSteps: guidance
5979
- },
5980
- null,
5981
- 2
5982
- )
5983
- );
5984
- } else {
5985
- console.log(`
5986
- Piwi setup${opts.dryRun ? " (dry run \u2014 nothing written)" : ""} for "${opts.projectName}":
5987
- `);
5988
- for (const step of steps) console.log(formatStep(step));
5989
- console.log("\nNext:");
5990
- for (const line of guidance) console.log(` \u2022 ${line}`);
5991
- console.log("");
5992
- }
6371
+ printOutcome(opts, project, workspace, steps, nextSteps(opts, steps, envBlock));
5993
6372
  return steps.some((s) => s.status === "error") ? 1 : 0;
5994
6373
  }
5995
6374
 
5996
6375
  // src/cli/select.ts
5997
6376
  var fs18 = __toESM(require("fs"));
5998
6377
  var path22 = __toESM(require("path"));
5999
- var import_node_child_process7 = require("child_process");
6378
+ var import_node_child_process8 = require("child_process");
6000
6379
 
6001
6380
  // ../core/src/diff-anchors.ts
6002
6381
  var RENAME_FROM = `rename from `;
@@ -7074,7 +7453,7 @@ function printWarnings(resolution) {
7074
7453
  for (const w of resolution.warnings) console.error(`piwi: warning [${w.code}] ${w.message}`);
7075
7454
  }
7076
7455
  function git2(args) {
7077
- return (0, import_node_child_process7.execFileSync)("git", ["-c", "core.quotePath=false", ...args], {
7456
+ return (0, import_node_child_process8.execFileSync)("git", ["-c", "core.quotePath=false", ...args], {
7078
7457
  encoding: "utf-8",
7079
7458
  stdio: ["ignore", "pipe", "ignore"],
7080
7459
  maxBuffer: 256 * 1024 * 1024
@@ -7285,7 +7664,7 @@ async function runRun(argv, env = process.env) {
7285
7664
  // src/cli/preflight.ts
7286
7665
  var fs19 = __toESM(require("fs"));
7287
7666
  var path23 = __toESM(require("path"));
7288
- var import_node_child_process8 = require("child_process");
7667
+ var import_node_child_process9 = require("child_process");
7289
7668
 
7290
7669
  // ../core/src/locator-edit.ts
7291
7670
  function escapeForQuote(value, quote3) {
@@ -7408,7 +7787,7 @@ function parsePreflightArgs(argv) {
7408
7787
  };
7409
7788
  }
7410
7789
  function git3(cwd, args) {
7411
- return (0, import_node_child_process8.execFileSync)("git", args, {
7790
+ return (0, import_node_child_process9.execFileSync)("git", args, {
7412
7791
  cwd,
7413
7792
  encoding: "utf-8",
7414
7793
  stdio: ["ignore", "pipe", "pipe"],
@@ -7825,9 +8204,9 @@ function probePlaywrightArgs(playwrightArgs2, testTitles) {
7825
8204
  return args;
7826
8205
  }
7827
8206
  async function runProbe(argv) {
7828
- const sep6 = argv.indexOf("--");
7829
- const own = sep6 < 0 ? argv : argv.slice(0, sep6);
7830
- const playwrightArgs2 = sep6 < 0 ? [] : argv.slice(sep6 + 1);
8207
+ const sep7 = argv.indexOf("--");
8208
+ const own = sep7 < 0 ? argv : argv.slice(0, sep7);
8209
+ const playwrightArgs2 = sep7 < 0 ? [] : argv.slice(sep7 + 1);
7831
8210
  if (own.includes("-h") || own.includes("--help")) {
7832
8211
  console.log(USAGE11);
7833
8212
  return EXIT_OK8;