@blazediff/agent 0.1.3 → 0.2.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.js CHANGED
@@ -3,19 +3,19 @@
3
3
 
4
4
  var commander = require('commander');
5
5
  var playwright = require('playwright');
6
- var child_process = require('child_process');
7
6
  var fs = require('fs');
8
- var module$1 = require('module');
9
- var path2 = require('path');
10
7
  var promises = require('fs/promises');
8
+ var path2 = require('path');
9
+ var child_process = require('child_process');
11
10
  var os = require('os');
12
11
  var crypto$1 = require('crypto');
12
+ var module$1 = require('module');
13
+ var url = require('url');
13
14
  var langgraph = require('@langchain/langgraph');
14
15
  var sharp = require('sharp');
15
16
  var langgraphCheckpoint = require('@langchain/langgraph-checkpoint');
16
17
  var coreNative = require('@blazediff/core-native');
17
18
  var promises$1 = require('readline/promises');
18
- var url = require('url');
19
19
  var net = require('net');
20
20
  var util = require('util');
21
21
  var treeKill = require('tree-kill');
@@ -27,6 +27,9 @@ var path2__default = /*#__PURE__*/_interopDefault(path2);
27
27
  var sharp__default = /*#__PURE__*/_interopDefault(sharp);
28
28
  var treeKill__default = /*#__PURE__*/_interopDefault(treeKill);
29
29
 
30
+ // package.json
31
+ var package_default = {
32
+ version: "0.2.0"};
30
33
  var FROZEN_NOW = Date.UTC(2025, 0, 1, 0, 0, 0);
31
34
  var STABILITY_CSS = `
32
35
  *,*::before,*::after{
@@ -80,7 +83,7 @@ async function closeBrowser() {
80
83
  function viewportKey(v) {
81
84
  return `${v.width}x${v.height}`;
82
85
  }
83
- async function createStableContext(viewport) {
86
+ async function createStableContext(viewport, baseURL) {
84
87
  const browser = await getBrowser();
85
88
  const context = await browser.newContext({
86
89
  viewport,
@@ -88,7 +91,8 @@ async function createStableContext(viewport) {
88
91
  reducedMotion: "reduce",
89
92
  forcedColors: "none",
90
93
  colorScheme: "light",
91
- bypassCSP: true
94
+ bypassCSP: true,
95
+ baseURL
92
96
  });
93
97
  await context.addInitScript(
94
98
  ({ frozenNow }) => {
@@ -130,23 +134,26 @@ async function createStableContext(viewport) {
130
134
  );
131
135
  return context;
132
136
  }
133
- async function acquireStableContext(viewport) {
137
+ async function acquireStableContext(viewport, options = {}) {
138
+ const usePool = options.pool !== false;
134
139
  const key = viewportKey(viewport);
135
- const pool = contextPool.get(key);
136
- if (pool && pool.length > 0) {
137
- const context2 = pool.pop();
138
- return { context: context2, viewport };
140
+ if (usePool) {
141
+ const pool = contextPool.get(key);
142
+ if (pool && pool.length > 0) {
143
+ const context2 = pool.pop();
144
+ return { context: context2, viewport, disposable: false };
145
+ }
139
146
  }
140
- const context = await createStableContext(viewport);
141
- return { context, viewport };
147
+ const context = await createStableContext(viewport, options.baseURL);
148
+ return { context, viewport, disposable: !usePool };
142
149
  }
143
150
  async function releaseStableContext(handle) {
144
- const key = viewportKey(handle.viewport);
145
- if (!cachedBrowser?.isConnected()) {
151
+ if (handle.disposable || !cachedBrowser?.isConnected()) {
146
152
  await handle.context.close().catch(() => {
147
153
  });
148
154
  return;
149
155
  }
156
+ const key = viewportKey(handle.viewport);
150
157
  const pool = contextPool.get(key);
151
158
  if (pool) {
152
159
  pool.push(handle.context);
@@ -203,6 +210,387 @@ async function applyMaskOverlays(page, masks) {
203
210
  }
204
211
  }, selectors);
205
212
  }
213
+ var CodegenError = class extends Error {
214
+ constructor(message) {
215
+ super(message);
216
+ this.name = "CodegenError";
217
+ }
218
+ };
219
+ async function runCodegen(opts) {
220
+ const tmp = await promises.mkdtemp(path2__default.default.join(os.tmpdir(), "blazediff-codegen-"));
221
+ const scriptPath = path2__default.default.join(tmp, "recording.js");
222
+ const command = opts.command ?? "npx";
223
+ const args = opts.args ?? [
224
+ "playwright",
225
+ "codegen",
226
+ "--target=javascript",
227
+ `--output=${scriptPath}`,
228
+ opts.loginUrl
229
+ ];
230
+ await new Promise((resolve, reject) => {
231
+ const child = child_process.spawn(command, args, {
232
+ cwd: opts.cwd ?? process.cwd(),
233
+ stdio: opts.stdio ?? "inherit"
234
+ });
235
+ child.on("error", (err) => {
236
+ reject(
237
+ new CodegenError(
238
+ `failed to spawn \`${command} ${args.join(" ")}\`: ${err.message}. Ensure Playwright is installed (\`npx playwright install\`).`
239
+ )
240
+ );
241
+ });
242
+ child.on("exit", (code) => {
243
+ if (code === 0) {
244
+ resolve();
245
+ return;
246
+ }
247
+ reject(
248
+ new CodegenError(
249
+ `playwright codegen exited with code ${code}. Re-run after fixing the recording.`
250
+ )
251
+ );
252
+ });
253
+ });
254
+ let rawSource;
255
+ try {
256
+ rawSource = await promises.readFile(scriptPath, "utf8");
257
+ } catch (err) {
258
+ await promises.rm(tmp, { recursive: true, force: true }).catch(() => {
259
+ });
260
+ throw new CodegenError(
261
+ `codegen did not write to ${scriptPath}: ${err.message}`
262
+ );
263
+ }
264
+ if (!rawSource.trim()) {
265
+ await promises.rm(tmp, { recursive: true, force: true }).catch(() => {
266
+ });
267
+ throw new CodegenError(
268
+ "codegen output is empty. Re-run and complete the login flow before closing the recorder."
269
+ );
270
+ }
271
+ return { rawSource, scriptPath };
272
+ }
273
+
274
+ // src/auth/env.ts
275
+ var LEGACY_REQUIRED = "required";
276
+ var DEFAULT_PERSONA = "default";
277
+ function canonicalPersona(auth) {
278
+ return auth === LEGACY_REQUIRED ? DEFAULT_PERSONA : auth;
279
+ }
280
+ function envVarsForPersona(persona) {
281
+ const upper = canonicalPersona(persona).toUpperCase().replace(/[^A-Z0-9]/g, "_");
282
+ return {
283
+ email: `BLAZEDIFF_AUTH_${upper}_EMAIL`,
284
+ password: `BLAZEDIFF_AUTH_${upper}_PASSWORD`
285
+ };
286
+ }
287
+ function personasFromManifest(manifest) {
288
+ const set = /* @__PURE__ */ new Set();
289
+ for (const entry of manifest.entries) {
290
+ if (entry.auth !== null) set.add(canonicalPersona(entry.auth));
291
+ }
292
+ return Array.from(set).sort();
293
+ }
294
+ function validatePersonas(personas, env = process.env) {
295
+ const missing = [];
296
+ for (const persona of personas) {
297
+ const { email, password } = envVarsForPersona(persona);
298
+ const vars = [];
299
+ if (!env[email]) vars.push(email);
300
+ if (!env[password]) vars.push(password);
301
+ if (vars.length > 0) missing.push({ persona, vars });
302
+ }
303
+ return missing;
304
+ }
305
+ function formatMissingEnv(missing) {
306
+ const lines = missing.map(
307
+ (m) => ` persona "${m.persona}": missing ${m.vars.join(", ")}`
308
+ );
309
+ return [
310
+ `auth env vars missing for ${missing.length} persona(s):`,
311
+ ...lines,
312
+ " set them and re-run, or run `blazediff-agent auth init` to record a harness"
313
+ ].join("\n");
314
+ }
315
+
316
+ // src/auth/postprocess.ts
317
+ var POSITIONAL_RE = /:nth-child\(|:nth-of-type\(|\s>\s/;
318
+ var EMAIL_RE = /\b(email|username|user_?name)\b/;
319
+ var PASSWORD_RE = /\bpassword\b/;
320
+ function normalizeSelector(selector) {
321
+ return selector.toLowerCase().replace(/['"`]/g, "");
322
+ }
323
+ function looksLikeEmail(selector) {
324
+ return EMAIL_RE.test(normalizeSelector(selector));
325
+ }
326
+ function looksLikePassword(selector) {
327
+ return PASSWORD_RE.test(normalizeSelector(selector));
328
+ }
329
+ function selectorIsPositional(selector) {
330
+ return POSITIONAL_RE.test(selector);
331
+ }
332
+ function escapeForRegex(s) {
333
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
334
+ }
335
+ var FILL_RE = /await\s+page(?:\.getByLabel\(([^)]*)\)|\.getByPlaceholder\(([^)]*)\)|\.locator\(([^)]*)\))?\s*\.fill\((['"`])((?:\\.|(?!\4)[^\\])*)\4\)/g;
336
+ function* iterateFills(source) {
337
+ const re = new RegExp(FILL_RE.source, "g");
338
+ let m = re.exec(source);
339
+ while (m !== null) {
340
+ const selector = (m[1] ?? "") + (m[2] ?? "") + (m[3] ?? "");
341
+ yield {
342
+ full: m[0],
343
+ selector: selector.replace(/^['"`]|['"`]$/g, ""),
344
+ value: m[5],
345
+ quote: m[4]
346
+ };
347
+ m = re.exec(source);
348
+ }
349
+ }
350
+ function extractActionBody(source) {
351
+ const markers = [
352
+ "async ({ page }) => {",
353
+ "async ({page}) => {",
354
+ "async function run(page) {",
355
+ "async function login(page) {"
356
+ ];
357
+ for (const marker of markers) {
358
+ const start = source.indexOf(marker);
359
+ if (start === -1) continue;
360
+ const open = start + marker.length;
361
+ let depth = 1;
362
+ let i = open;
363
+ while (i < source.length && depth > 0) {
364
+ const c = source[i];
365
+ if (c === "{") depth += 1;
366
+ else if (c === "}") depth -= 1;
367
+ if (depth === 0) break;
368
+ i += 1;
369
+ }
370
+ if (depth === 0) {
371
+ return { body: source.slice(open, i).trim(), found: true };
372
+ }
373
+ }
374
+ const lines = source.split("\n").filter((l) => /^\s*await\s+page\./.test(l));
375
+ if (lines.length > 0) {
376
+ return { body: lines.join("\n").trim(), found: true };
377
+ }
378
+ return { body: "", found: false };
379
+ }
380
+ function indent(body, prefix) {
381
+ return body.split("\n").map((line) => line.length > 0 ? prefix + line : line).join("\n");
382
+ }
383
+ function postprocessCodegen(rawCodegen, opts) {
384
+ const warnings = [];
385
+ const extracted = extractActionBody(rawCodegen);
386
+ if (!extracted.found) {
387
+ warnings.push(
388
+ "could not parse codegen output \u2014 wrote raw actions; please review .blazediff/auth.js"
389
+ );
390
+ }
391
+ let body = (extracted.body || rawCodegen.trim()).replace(
392
+ /^\s*await\s+page\.goto\([^)]*\)\s*;?\s*\n?/,
393
+ ""
394
+ );
395
+ let rewroteEmail = false;
396
+ let rewrotePassword = false;
397
+ let sawPositional = false;
398
+ const fills = Array.from(iterateFills(body));
399
+ for (const call of fills) {
400
+ if (selectorIsPositional(call.selector)) sawPositional = true;
401
+ const isPassword = looksLikePassword(call.selector);
402
+ const isEmail = !isPassword && looksLikeEmail(call.selector);
403
+ if (!isPassword && !isEmail) continue;
404
+ const replacement = call.full.replace(
405
+ new RegExp(
406
+ `(${escapeForRegex(call.quote)})${escapeForRegex(call.value)}(${escapeForRegex(call.quote)})`
407
+ ),
408
+ isPassword ? "password" : "email"
409
+ );
410
+ body = body.replace(call.full, replacement);
411
+ if (isPassword) rewrotePassword = true;
412
+ else rewroteEmail = true;
413
+ }
414
+ if (sawPositional) {
415
+ warnings.push(
416
+ "codegen used positional selectors (e.g. nth-child). Review and replace with attribute selectors for stability."
417
+ );
418
+ }
419
+ if (!rewroteEmail) {
420
+ warnings.push(
421
+ "no email/username field detected \u2014 the harness will not read BLAZEDIFF_AUTH_*_EMAIL. Edit the file by hand if needed."
422
+ );
423
+ }
424
+ if (!rewrotePassword) {
425
+ warnings.push(
426
+ "no password field detected \u2014 the harness will not read BLAZEDIFF_AUTH_*_PASSWORD. Edit the file by hand if needed."
427
+ );
428
+ }
429
+ const { email, password } = envVarsForPersona(opts.persona);
430
+ const loginUrlJson = JSON.stringify(opts.loginUrl);
431
+ const source = `// Generated by \`blazediff-agent auth init\`.
432
+ // Credentials live in env vars (e.g. ${email}, ${password}).
433
+ // Each persona reads BLAZEDIFF_AUTH_<PERSONA>_EMAIL / _PASSWORD.
434
+
435
+ export async function login(page, persona = ${JSON.stringify(opts.persona)}) {
436
+ const upper = persona.toUpperCase().replace(/[^A-Z0-9]/g, "_");
437
+ const email = process.env[\`BLAZEDIFF_AUTH_\${upper}_EMAIL\`];
438
+ const password = process.env[\`BLAZEDIFF_AUTH_\${upper}_PASSWORD\`];
439
+ if (!email || !password) {
440
+ throw new Error(
441
+ \`missing BLAZEDIFF_AUTH_\${upper}_EMAIL / _PASSWORD env vars for persona "\${persona}"\`,
442
+ );
443
+ }
444
+ await page.goto(${loginUrlJson});
445
+ ${indent(body, " ")}
446
+ }
447
+ `;
448
+ return { source, warnings, rewroteEmail, rewrotePassword };
449
+ }
450
+ var BLAZEDIFF_DIR = ".blazediff";
451
+ var paths = (cwd = process.cwd()) => {
452
+ const root = path2__default.default.join(cwd, BLAZEDIFF_DIR);
453
+ return {
454
+ root,
455
+ config: path2__default.default.join(root, "config.json"),
456
+ manifest: path2__default.default.join(root, "manifest.json"),
457
+ baselines: path2__default.default.join(root, "baselines"),
458
+ actual: path2__default.default.join(root, "actual"),
459
+ judgments: path2__default.default.join(root, "judgments"),
460
+ checkpoints: path2__default.default.join(root, "checkpoints"),
461
+ summary: path2__default.default.join(root, "summary.md"),
462
+ gitignore: path2__default.default.join(root, ".gitignore"),
463
+ serverLog: path2__default.default.join(root, "dev-server.log"),
464
+ serverPid: path2__default.default.join(root, "dev-server.pid")
465
+ };
466
+ };
467
+
468
+ // src/config.ts
469
+ async function loadConfig(cwd = process.cwd()) {
470
+ const file = paths(cwd).config;
471
+ if (!fs.existsSync(file)) return null;
472
+ return JSON.parse(await promises.readFile(file, "utf8"));
473
+ }
474
+ async function saveConfig(config, cwd = process.cwd()) {
475
+ const file = paths(cwd).config;
476
+ await promises.mkdir(path2__default.default.dirname(file), { recursive: true });
477
+ await promises.writeFile(file, `${JSON.stringify(config, null, 2)}
478
+ `, "utf8");
479
+ }
480
+ function configHash(config) {
481
+ return `sha256:${crypto$1.createHash("sha256").update(JSON.stringify(config)).digest("hex")}`;
482
+ }
483
+ function resolveBaseUrl(config, override) {
484
+ if (override) return override;
485
+ if (config?.baseUrl) return config.baseUrl;
486
+ if (config?.devServer) return `http://127.0.0.1:${config.devServer.port}`;
487
+ throw new Error("no baseUrl: pass --base-url or run `blazediff-agent init`");
488
+ }
489
+
490
+ // src/cli/commands/auth.ts
491
+ function looksLikeProduction(url) {
492
+ try {
493
+ const u = new URL(url);
494
+ const host = u.hostname;
495
+ if (host === "localhost" || host === "127.0.0.1" || host === "::1") {
496
+ return false;
497
+ }
498
+ if (/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[0-1])\.)/.test(host)) {
499
+ return false;
500
+ }
501
+ return true;
502
+ } catch {
503
+ return false;
504
+ }
505
+ }
506
+ function resolveLoginUrl(opts, config) {
507
+ if (opts.loginUrl) return opts.loginUrl;
508
+ if (config?.auth?.loginUrl) return config.auth.loginUrl;
509
+ const baseUrl = config?.baseUrl;
510
+ if (!baseUrl) {
511
+ throw new Error(
512
+ "no login URL: pass --login-url <url> or run `blazediff-agent init` first."
513
+ );
514
+ }
515
+ return new URL("/login", baseUrl).toString();
516
+ }
517
+ function registerAuth(program, out) {
518
+ const cmd = program.command("auth").description("manage auth harnesses for protected routes");
519
+ cmd.command("init").description(
520
+ "record an interactive login via playwright codegen and write .blazediff/auth.js"
521
+ ).option("--persona <name>", "persona name", DEFAULT_PERSONA).option("--login-url <url>", "URL of the login form").option("--allow-production", "skip the non-prod URL guard").option("--force", "overwrite an existing .blazediff/auth.js").option(
522
+ "--output <path>",
523
+ "override the harness output path (default: .blazediff/auth.js)"
524
+ ).action(async (opts) => {
525
+ const config = await loadConfig();
526
+ const loginUrl = resolveLoginUrl(opts, config);
527
+ if (looksLikeProduction(loginUrl) && !opts.allowProduction) {
528
+ throw new Error(
529
+ `refusing to record against what looks like a production URL: ${loginUrl}. Pass --allow-production to override.`
530
+ );
531
+ }
532
+ const harnessPath = opts.output ? path2__default.default.isAbsolute(opts.output) ? opts.output : path2__default.default.join(process.cwd(), opts.output) : path2__default.default.join(paths().root, "auth.js");
533
+ if (fs.existsSync(harnessPath) && !opts.force) {
534
+ throw new Error(`refusing to overwrite ${harnessPath} (use --force).`);
535
+ }
536
+ process.stderr.write(
537
+ `recording login flow at ${loginUrl} via playwright codegen...
538
+ log in, then close the recorder window. Credentials you type will be rewritten to env vars before saving.
539
+ `
540
+ );
541
+ let rawSource;
542
+ let scriptPath;
543
+ try {
544
+ const result = await runCodegen({ loginUrl });
545
+ rawSource = result.rawSource;
546
+ scriptPath = result.scriptPath;
547
+ } catch (err) {
548
+ throw new Error(`codegen failed: ${err.message}`);
549
+ }
550
+ const processed = postprocessCodegen(rawSource, {
551
+ persona: opts.persona,
552
+ loginUrl
553
+ });
554
+ await promises.mkdir(path2__default.default.dirname(harnessPath), { recursive: true });
555
+ await promises.writeFile(harnessPath, processed.source, "utf8");
556
+ await promises.rm(path2__default.default.dirname(scriptPath), {
557
+ recursive: true,
558
+ force: true
559
+ }).catch(() => {
560
+ });
561
+ const harnessRelative = path2__default.default.relative(process.cwd(), harnessPath) || "auth.js";
562
+ const nextConfig = config ? {
563
+ ...config,
564
+ auth: { harness: harnessRelative, loginUrl }
565
+ } : {
566
+ devServer: null,
567
+ auth: { harness: harnessRelative, loginUrl }
568
+ };
569
+ await saveConfig(nextConfig);
570
+ const { email, password } = envVarsForPersona(opts.persona);
571
+ for (const w of processed.warnings) {
572
+ process.stderr.write(` warning: ${w}
573
+ `);
574
+ }
575
+ const human = [
576
+ `wrote ${harnessPath}`,
577
+ ` persona: ${opts.persona}`,
578
+ ` loginUrl: ${loginUrl}`,
579
+ ` set ${email} and ${password} in your environment to run captures`
580
+ ].join("\n");
581
+ out.emit(
582
+ {
583
+ ok: true,
584
+ harness: harnessRelative,
585
+ loginUrl,
586
+ persona: opts.persona,
587
+ envVars: { email, password },
588
+ warnings: processed.warnings
589
+ },
590
+ human
591
+ );
592
+ });
593
+ }
206
594
  function resolvePlaywrightCli() {
207
595
  const require_ = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli.js', document.baseURI).href)));
208
596
  const pkgJson = require_.resolve("playwright/package.json");
@@ -264,6 +652,105 @@ function registerBrowsers(program, out) {
264
652
  })
265
653
  );
266
654
  }
655
+ var AuthHarnessError = class extends Error {
656
+ constructor(message, cause) {
657
+ super(message);
658
+ this.cause = cause;
659
+ this.name = "AuthHarnessError";
660
+ }
661
+ };
662
+ var moduleCache = /* @__PURE__ */ new Map();
663
+ async function loadAuthHarness(harnessFile) {
664
+ const absolute = path2__default.default.isAbsolute(harnessFile) ? harnessFile : path2__default.default.resolve(process.cwd(), harnessFile);
665
+ if (!fs.existsSync(absolute)) {
666
+ throw new AuthHarnessError(
667
+ `auth harness not found at ${absolute}. Run \`blazediff-agent auth init\` to create one.`
668
+ );
669
+ }
670
+ const cached = moduleCache.get(absolute);
671
+ if (cached) return cached;
672
+ const url$1 = url.pathToFileURL(absolute).href;
673
+ const loading = (async () => {
674
+ try {
675
+ const mod = await import(url$1);
676
+ if (typeof mod.login !== "function") {
677
+ throw new AuthHarnessError(
678
+ `auth harness at ${absolute} does not export a \`login\` function`
679
+ );
680
+ }
681
+ return { login: mod.login };
682
+ } catch (err) {
683
+ if (err instanceof AuthHarnessError) throw err;
684
+ throw new AuthHarnessError(
685
+ `failed to load auth harness at ${absolute}: ${err.message}`,
686
+ err
687
+ );
688
+ }
689
+ })();
690
+ moduleCache.set(absolute, loading);
691
+ return loading;
692
+ }
693
+ function loginPathOf(loginUrl) {
694
+ try {
695
+ return new URL(loginUrl, "http://placeholder").pathname;
696
+ } catch {
697
+ return loginUrl;
698
+ }
699
+ }
700
+ async function verifyPostLogin(page, loginUrl) {
701
+ const loginPath = loginPathOf(loginUrl);
702
+ let currentPath;
703
+ try {
704
+ currentPath = new URL(page.url()).pathname;
705
+ } catch {
706
+ currentPath = page.url();
707
+ }
708
+ if (loginPath && currentPath === loginPath) {
709
+ throw new AuthHarnessError(
710
+ `auth harness returned but page is still on the login URL (${currentPath}). Check that the harness submits the form and waits for redirect.`
711
+ );
712
+ }
713
+ await page.locator('input[type="password"]').first().waitFor({ state: "detached", timeout: 2e3 }).catch(() => {
714
+ });
715
+ const passwordInputs = await page.locator('input[type="password"]:visible').count().catch(() => 0);
716
+ if (passwordInputs > 0) {
717
+ throw new AuthHarnessError(
718
+ `auth harness returned but a visible password input is still on the page. The login likely did not complete (wrong credentials, captcha, or selectors out of date).`
719
+ );
720
+ }
721
+ }
722
+
723
+ // src/auth/hook.ts
724
+ var AuthConfigMissingError = class extends Error {
725
+ constructor(message) {
726
+ super(message);
727
+ this.name = "AuthConfigMissingError";
728
+ }
729
+ };
730
+ function buildAuthHook(persona, authConfig, cwd) {
731
+ if (!authConfig) {
732
+ throw new AuthConfigMissingError(
733
+ "auth required but .blazediff/config.json has no `auth` block. Run `blazediff-agent auth init`."
734
+ );
735
+ }
736
+ const harnessFile = path2__default.default.isAbsolute(authConfig.harness) ? authConfig.harness : path2__default.default.join(cwd, authConfig.harness);
737
+ const canonical = canonicalPersona(persona);
738
+ const loginUrl = authConfig.loginUrl;
739
+ return {
740
+ hook: async (page) => {
741
+ const mod = await loadAuthHarness(harnessFile);
742
+ try {
743
+ await mod.login(page, canonical);
744
+ } catch (err) {
745
+ throw new AuthHarnessError(
746
+ `auth harness threw for persona "${canonical}": ${err.message}`,
747
+ err
748
+ );
749
+ }
750
+ await verifyPostLogin(page, loginUrl);
751
+ }
752
+ };
753
+ }
267
754
  var DEFAULT_VIEWPORT = { width: 1280, height: 800 };
268
755
  var DEFAULT_WAIT_FOR = ["networkidle", "fonts"];
269
756
  var DEFAULT_FULL_PAGE = true;
@@ -280,33 +767,22 @@ function defaultConcurrency() {
280
767
  Math.min(MAX_AUTO_CONCURRENCY, cores - 1)
281
768
  );
282
769
  }
283
- var BLAZEDIFF_DIR = ".blazediff";
284
- var paths = (cwd = process.cwd()) => {
285
- const root = path2__default.default.join(cwd, BLAZEDIFF_DIR);
286
- return {
287
- root,
288
- config: path2__default.default.join(root, "config.json"),
289
- manifest: path2__default.default.join(root, "manifest.json"),
290
- baselines: path2__default.default.join(root, "baselines"),
291
- actual: path2__default.default.join(root, "actual"),
292
- judgments: path2__default.default.join(root, "judgments"),
293
- checkpoints: path2__default.default.join(root, "checkpoints"),
294
- summary: path2__default.default.join(root, "summary.md"),
295
- gitignore: path2__default.default.join(root, ".gitignore"),
296
- serverLog: path2__default.default.join(root, "dev-server.log"),
297
- serverPid: path2__default.default.join(root, "dev-server.pid")
298
- };
299
- };
300
770
 
301
771
  // src/browser/capture.ts
302
- async function captureScreenshot(baseUrl, opts, cwd = process.cwd()) {
772
+ async function captureScreenshot(baseUrl, opts, cwd = process.cwd(), auth) {
303
773
  const viewport = opts.viewport ?? DEFAULT_VIEWPORT;
304
774
  const waitFor = opts.waitFor ?? DEFAULT_WAIT_FOR;
305
775
  const masks = opts.mask ?? [];
306
776
  const fullPage = opts.fullPage ?? DEFAULT_FULL_PAGE;
307
- const handle = await acquireStableContext(viewport);
777
+ const handle = await acquireStableContext(viewport, {
778
+ pool: !auth,
779
+ baseURL: baseUrl || void 0
780
+ });
308
781
  const page = await openStablePage(handle);
309
782
  try {
783
+ if (auth) {
784
+ await auth.hook(page);
785
+ }
310
786
  const url = new URL(opts.url, baseUrl).toString();
311
787
  await page.goto(url, { waitUntil: "domcontentloaded", timeout: 3e4 });
312
788
  await waitForStability(page, waitFor);
@@ -332,26 +808,6 @@ async function captureScreenshot(baseUrl, opts, cwd = process.cwd()) {
332
808
  await releaseStableContext(handle);
333
809
  }
334
810
  }
335
- async function loadConfig(cwd = process.cwd()) {
336
- const file = paths(cwd).config;
337
- if (!fs.existsSync(file)) return null;
338
- return JSON.parse(await promises.readFile(file, "utf8"));
339
- }
340
- async function saveConfig(config, cwd = process.cwd()) {
341
- const file = paths(cwd).config;
342
- await promises.mkdir(path2__default.default.dirname(file), { recursive: true });
343
- await promises.writeFile(file, `${JSON.stringify(config, null, 2)}
344
- `, "utf8");
345
- }
346
- function configHash(config) {
347
- return `sha256:${crypto$1.createHash("sha256").update(JSON.stringify(config)).digest("hex")}`;
348
- }
349
- function resolveBaseUrl(config, override) {
350
- if (override) return override;
351
- if (config?.baseUrl) return config.baseUrl;
352
- if (config?.devServer) return `http://127.0.0.1:${config.devServer.port}`;
353
- throw new Error("no baseUrl: pass --base-url or run `blazediff-agent init`");
354
- }
355
811
 
356
812
  // src/graph/semaphore.ts
357
813
  var Semaphore = class {
@@ -474,10 +930,9 @@ function validateRoute(route, i) {
474
930
  return `route[${i}] missing url`;
475
931
  return null;
476
932
  }
477
- async function loadOrCreateManifest(cwd) {
933
+ async function loadOrCreateManifest(cwd, config) {
478
934
  const existing = await loadManifest(cwd);
479
935
  if (existing) return existing;
480
- const config = await loadConfig(cwd);
481
936
  return emptyManifest(config ? configHash(config) : "sha256:none");
482
937
  }
483
938
  async function runCaptures(opts) {
@@ -500,7 +955,8 @@ async function runCaptures(opts) {
500
955
  valid.push(r);
501
956
  }
502
957
  });
503
- let manifest = writeManifest ? await loadOrCreateManifest(cwd) : null;
958
+ const config = await loadConfig(cwd);
959
+ let manifest = writeManifest ? await loadOrCreateManifest(cwd, config) : null;
504
960
  let manifestUpdates = 0;
505
961
  const slot = new Array(valid.length);
506
962
  const semaphore = new Semaphore(opts.concurrency ?? defaultConcurrency());
@@ -510,6 +966,7 @@ async function runCaptures(opts) {
510
966
  (r, i) => semaphore.run(async () => {
511
967
  const mode = r.mode ?? defaultMode;
512
968
  try {
969
+ const auth = r.auth != null ? buildAuthHook(r.auth, config?.auth, cwd) : void 0;
513
970
  const shot = await captureScreenshot(
514
971
  opts.baseUrl,
515
972
  {
@@ -521,7 +978,8 @@ async function runCaptures(opts) {
521
978
  fullPage: r.fullPage,
522
979
  mode
523
980
  },
524
- cwd
981
+ cwd,
982
+ auth
525
983
  );
526
984
  slot[i] = {
527
985
  id: r.id,
@@ -540,7 +998,8 @@ async function runCaptures(opts) {
540
998
  viewport: r.viewport,
541
999
  mask: r.mask,
542
1000
  waitFor: r.waitFor,
543
- fullPage: r.fullPage
1001
+ fullPage: r.fullPage,
1002
+ auth: r.auth ?? null
544
1003
  })
545
1004
  );
546
1005
  manifestUpdates += 1;
@@ -1626,9 +2085,6 @@ function narrowRegion(r) {
1626
2085
  confidence: r.confidence
1627
2086
  };
1628
2087
  }
1629
- function skipResult(entry, message) {
1630
- return { id: entry.id, url: entry.url, status: "pass", message };
1631
- }
1632
2088
  function staleResult(entry) {
1633
2089
  return {
1634
2090
  id: entry.id,
@@ -1637,6 +2093,14 @@ function staleResult(entry) {
1637
2093
  message: "captureHash mismatch: entry was edited without re-capturing"
1638
2094
  };
1639
2095
  }
2096
+ function errorResult(entry, message) {
2097
+ return {
2098
+ id: entry.id,
2099
+ url: entry.url,
2100
+ status: "fail",
2101
+ message
2102
+ };
2103
+ }
1640
2104
  function passResult(entry, baselinePath, actualPath) {
1641
2105
  return {
1642
2106
  id: entry.id,
@@ -1672,6 +2136,14 @@ function failResult(entry, outcome, actualPath, baselinePath, verdict) {
1672
2136
  }
1673
2137
 
1674
2138
  // src/graph/nodes/capture.ts
2139
+ var legacyAuthHinted = false;
2140
+ function maybePrintLegacyHint() {
2141
+ if (legacyAuthHinted) return;
2142
+ legacyAuthHinted = true;
2143
+ process.stderr.write(
2144
+ 'blazediff: manifest entries with auth: "required" are treated as persona "default" \u2014 please migrate.\n'
2145
+ );
2146
+ }
1675
2147
  function makeCaptureNode(semaphore) {
1676
2148
  return async function captureNode(state) {
1677
2149
  const entry = state.entry;
@@ -1679,45 +2151,64 @@ function makeCaptureNode(semaphore) {
1679
2151
  if (!entry || !options) {
1680
2152
  throw new Error("captureNode: entry or options missing");
1681
2153
  }
1682
- if (entry.auth === "required") {
1683
- return {
1684
- captureOutput: {
1685
- id: entry.id,
1686
- skipResult: skipResult(
1687
- entry,
1688
- "skipped: auth required (deferred to v0.2)"
1689
- )
1690
- }
1691
- };
1692
- }
1693
2154
  if (isEntryStale(entry)) {
1694
2155
  return {
1695
2156
  captureOutput: { id: entry.id, skipResult: staleResult(entry) }
1696
2157
  };
1697
2158
  }
2159
+ let auth;
2160
+ if (entry.auth !== null) {
2161
+ if (entry.auth === LEGACY_REQUIRED) maybePrintLegacyHint();
2162
+ try {
2163
+ auth = buildAuthHook(entry.auth, options.auth, options.cwd);
2164
+ } catch (err) {
2165
+ if (err instanceof AuthConfigMissingError) {
2166
+ return {
2167
+ captureOutput: {
2168
+ id: entry.id,
2169
+ skipResult: errorResult(entry, err.message)
2170
+ }
2171
+ };
2172
+ }
2173
+ throw err;
2174
+ }
2175
+ }
1698
2176
  const baselinePath = path2__default.default.join(options.baselinesDir, `${entry.id}.png`);
1699
- const capture = await semaphore.run(
1700
- () => captureScreenshot(
1701
- options.baseUrl,
1702
- {
2177
+ try {
2178
+ const capture = await semaphore.run(
2179
+ () => captureScreenshot(
2180
+ options.baseUrl,
2181
+ {
2182
+ id: entry.id,
2183
+ url: entry.url,
2184
+ viewport: entry.viewport,
2185
+ mask: entry.mask,
2186
+ waitFor: entry.waitFor,
2187
+ fullPage: entry.fullPage ?? DEFAULT_FULL_PAGE,
2188
+ mode: "actual"
2189
+ },
2190
+ options.cwd,
2191
+ auth
2192
+ )
2193
+ );
2194
+ return {
2195
+ captureOutput: {
1703
2196
  id: entry.id,
1704
- url: entry.url,
1705
- viewport: entry.viewport,
1706
- mask: entry.mask,
1707
- waitFor: entry.waitFor,
1708
- fullPage: entry.fullPage ?? DEFAULT_FULL_PAGE,
1709
- mode: "actual"
1710
- },
1711
- options.cwd
1712
- )
1713
- );
1714
- return {
1715
- captureOutput: {
1716
- id: entry.id,
1717
- captureOutputPath: capture.outputPath,
1718
- baselinePath
2197
+ captureOutputPath: capture.outputPath,
2198
+ baselinePath
2199
+ }
2200
+ };
2201
+ } catch (err) {
2202
+ if (err instanceof AuthHarnessError) {
2203
+ return {
2204
+ captureOutput: {
2205
+ id: entry.id,
2206
+ skipResult: errorResult(entry, `auth: ${err.message}`)
2207
+ }
2208
+ };
1719
2209
  }
1720
- };
2210
+ throw err;
2211
+ }
1721
2212
  };
1722
2213
  }
1723
2214
  async function fileExists3(p) {
@@ -2223,6 +2714,7 @@ async function runGraph(opts) {
2223
2714
  if (!opts.resume) {
2224
2715
  await checkpointer.deleteThread(threadId);
2225
2716
  }
2717
+ const config = await loadConfig(cwd);
2226
2718
  const input = opts.resume ? new langgraph.Command({ resume: opts.resume }) : {
2227
2719
  options: {
2228
2720
  baseUrl: opts.baseUrl ?? "",
@@ -2231,7 +2723,8 @@ async function runGraph(opts) {
2231
2723
  concurrency,
2232
2724
  emitDiffPng: opts.emitDiffPng ?? true,
2233
2725
  judge: opts.judge ?? "none",
2234
- baselinesDir
2726
+ baselinesDir,
2727
+ auth: config?.auth
2235
2728
  }
2236
2729
  };
2237
2730
  let collect;
@@ -2395,6 +2888,14 @@ function registerCheck(program, out) {
2395
2888
  if (report2.failed > 0) process.exitCode = 1;
2396
2889
  return;
2397
2890
  }
2891
+ const manifest = await loadManifest();
2892
+ if (manifest) {
2893
+ const personas = personasFromManifest(manifest);
2894
+ const missing = validatePersonas(personas);
2895
+ if (missing.length > 0) {
2896
+ throw new Error(formatMissingEnv(missing));
2897
+ }
2898
+ }
2398
2899
  const baseUrl = resolveBaseUrl(await loadConfig(), opts.baseUrl);
2399
2900
  const report = await runGraph({
2400
2901
  baseUrl,
@@ -2454,9 +2955,9 @@ function extractInternalLinks(base, target, hrefs) {
2454
2955
  try {
2455
2956
  const u = new URL(href, target);
2456
2957
  if (u.origin !== base.origin) continue;
2457
- const path23 = u.pathname + u.search;
2458
- if (path23.startsWith("/api/")) continue;
2459
- out.push(path23);
2958
+ const path27 = u.pathname + u.search;
2959
+ if (path27.startsWith("/api/")) continue;
2960
+ out.push(path27);
2460
2961
  } catch {
2461
2962
  }
2462
2963
  }
@@ -2824,7 +3325,11 @@ function registerInit(program, out) {
2824
3325
  // src/cli/commands/manifest.ts
2825
3326
  function registerManifest(program, out) {
2826
3327
  const cmd = program.command("manifest").description("manage .blazediff/manifest.json");
2827
- cmd.command("add <id>").requiredOption("--url <url>").option("--viewport <WxH>", "viewport", "1280x800").option("--mask <selectors>", "selectors", "").option("--wait-for <list>", "wait list", "networkidle,fonts").option("--no-full-page", "viewport-only (default: full page)").option("--auth <required|none>", "mark auth-gated", "none").option("--created-by <agent|human>", "provenance", "agent").action(async (id, opts) => {
3328
+ cmd.command("add <id>").requiredOption("--url <url>").option("--viewport <WxH>", "viewport", "1280x800").option("--mask <selectors>", "selectors", "").option("--wait-for <list>", "wait list", "networkidle,fonts").option("--no-full-page", "viewport-only (default: full page)").option(
3329
+ "--auth <persona|none>",
3330
+ 'persona name for auth-gated capture (e.g. "default"); "none" to skip auth',
3331
+ "none"
3332
+ ).option("--created-by <agent|human>", "provenance", "agent").action(async (id, opts) => {
2828
3333
  const config = await loadConfig();
2829
3334
  if (!config)
2830
3335
  throw new Error("no config. Run `blazediff-agent init` first.");
@@ -2836,7 +3341,7 @@ function registerManifest(program, out) {
2836
3341
  mask: parseMaskList(opts.mask),
2837
3342
  waitFor: parseWaitFor(opts.waitFor),
2838
3343
  fullPage: opts.fullPage,
2839
- auth: opts.auth === "required" ? "required" : null,
3344
+ auth: opts.auth === "none" || opts.auth === "" ? null : opts.auth,
2840
3345
  createdBy: opts.createdBy
2841
3346
  });
2842
3347
  await saveManifest(addOrReplaceEntry(manifest, entry));
@@ -3526,7 +4031,7 @@ function makeOutput(getRootOpts) {
3526
4031
 
3527
4032
  // src/cli.ts
3528
4033
  function buildProgram() {
3529
- const program = new commander.Command().name("blazediff-agent").description("Agentic visual regression for BlazeDiff").version("0.1.2").option("-C, --cwd <path>", "operate on a different directory").option("--json", "emit JSON to stdout where applicable").option("--quiet", "suppress non-error output");
4034
+ const program = new commander.Command().name("blazediff-agent").description("Agentic visual regression for BlazeDiff").version(package_default.version).option("-C, --cwd <path>", "operate on a different directory").option("--json", "emit JSON to stdout where applicable").option("--quiet", "suppress non-error output");
3530
4035
  const out = makeOutput(() => program.opts());
3531
4036
  registerOnboard(program, out);
3532
4037
  registerInit(program, out);
@@ -3536,6 +4041,7 @@ function buildProgram() {
3536
4041
  registerBrowsers(program, out);
3537
4042
  registerDiff(program, out);
3538
4043
  registerManifest(program, out);
4044
+ registerAuth(program, out);
3539
4045
  registerCheck(program, out);
3540
4046
  registerRewrite(program, out);
3541
4047
  registerReset(program, out);