@blazediff/agent 0.1.4 → 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/index.mjs CHANGED
@@ -5,6 +5,7 @@ import { chromium } from 'playwright';
5
5
  import { spawn } from 'child_process';
6
6
  import { existsSync } from 'fs';
7
7
  import { createRequire } from 'module';
8
+ import { pathToFileURL } from 'url';
8
9
  import { createHash } from 'crypto';
9
10
  import { compare } from '@blazediff/core-native';
10
11
  import { Annotation, Command, StateGraph, START, Send, END, interrupt } from '@langchain/langgraph';
@@ -96,7 +97,7 @@ async function closeBrowser() {
96
97
  function viewportKey(v) {
97
98
  return `${v.width}x${v.height}`;
98
99
  }
99
- async function createStableContext(viewport) {
100
+ async function createStableContext(viewport, baseURL) {
100
101
  const browser = await getBrowser();
101
102
  const context = await browser.newContext({
102
103
  viewport,
@@ -104,7 +105,8 @@ async function createStableContext(viewport) {
104
105
  reducedMotion: "reduce",
105
106
  forcedColors: "none",
106
107
  colorScheme: "light",
107
- bypassCSP: true
108
+ bypassCSP: true,
109
+ baseURL
108
110
  });
109
111
  await context.addInitScript(
110
112
  ({ frozenNow }) => {
@@ -146,23 +148,26 @@ async function createStableContext(viewport) {
146
148
  );
147
149
  return context;
148
150
  }
149
- async function acquireStableContext(viewport) {
151
+ async function acquireStableContext(viewport, options = {}) {
152
+ const usePool = options.pool !== false;
150
153
  const key = viewportKey(viewport);
151
- const pool = contextPool.get(key);
152
- if (pool && pool.length > 0) {
153
- const context2 = pool.pop();
154
- return { context: context2, viewport };
154
+ if (usePool) {
155
+ const pool = contextPool.get(key);
156
+ if (pool && pool.length > 0) {
157
+ const context2 = pool.pop();
158
+ return { context: context2, viewport, disposable: false };
159
+ }
155
160
  }
156
- const context = await createStableContext(viewport);
157
- return { context, viewport };
161
+ const context = await createStableContext(viewport, options.baseURL);
162
+ return { context, viewport, disposable: !usePool };
158
163
  }
159
164
  async function releaseStableContext(handle) {
160
- const key = viewportKey(handle.viewport);
161
- if (!cachedBrowser?.isConnected()) {
165
+ if (handle.disposable || !cachedBrowser?.isConnected()) {
162
166
  await handle.context.close().catch(() => {
163
167
  });
164
168
  return;
165
169
  }
170
+ const key = viewportKey(handle.viewport);
166
171
  const pool = contextPool.get(key);
167
172
  if (pool) {
168
173
  pool.push(handle.context);
@@ -221,14 +226,20 @@ async function applyMaskOverlays(page, masks) {
221
226
  }
222
227
 
223
228
  // src/browser/capture.ts
224
- async function captureScreenshot(baseUrl, opts, cwd = process.cwd()) {
229
+ async function captureScreenshot(baseUrl, opts, cwd = process.cwd(), auth) {
225
230
  const viewport = opts.viewport ?? DEFAULT_VIEWPORT;
226
231
  const waitFor = opts.waitFor ?? DEFAULT_WAIT_FOR;
227
232
  const masks = opts.mask ?? [];
228
233
  const fullPage = opts.fullPage ?? DEFAULT_FULL_PAGE;
229
- const handle = await acquireStableContext(viewport);
234
+ const handle = await acquireStableContext(viewport, {
235
+ pool: !auth,
236
+ baseURL: baseUrl || void 0
237
+ });
230
238
  const page = await openStablePage(handle);
231
239
  try {
240
+ if (auth) {
241
+ await auth.hook(page);
242
+ }
232
243
  const url = new URL(opts.url, baseUrl).toString();
233
244
  await page.goto(url, { waitUntil: "domcontentloaded", timeout: 3e4 });
234
245
  await waitForStability(page, waitFor);
@@ -301,6 +312,112 @@ async function installBrowsers(opts = {}) {
301
312
  const executablePath = await readExecutablePath();
302
313
  return { installed: Boolean(executablePath), executablePath, cliPath };
303
314
  }
315
+
316
+ // src/auth/env.ts
317
+ var LEGACY_REQUIRED = "required";
318
+ var DEFAULT_PERSONA = "default";
319
+ function canonicalPersona(auth) {
320
+ return auth === LEGACY_REQUIRED ? DEFAULT_PERSONA : auth;
321
+ }
322
+ var AuthHarnessError = class extends Error {
323
+ constructor(message, cause) {
324
+ super(message);
325
+ this.cause = cause;
326
+ this.name = "AuthHarnessError";
327
+ }
328
+ };
329
+ var moduleCache = /* @__PURE__ */ new Map();
330
+ async function loadAuthHarness(harnessFile) {
331
+ const absolute = path.isAbsolute(harnessFile) ? harnessFile : path.resolve(process.cwd(), harnessFile);
332
+ if (!existsSync(absolute)) {
333
+ throw new AuthHarnessError(
334
+ `auth harness not found at ${absolute}. Run \`blazediff-agent auth init\` to create one.`
335
+ );
336
+ }
337
+ const cached = moduleCache.get(absolute);
338
+ if (cached) return cached;
339
+ const url = pathToFileURL(absolute).href;
340
+ const loading = (async () => {
341
+ try {
342
+ const mod = await import(url);
343
+ if (typeof mod.login !== "function") {
344
+ throw new AuthHarnessError(
345
+ `auth harness at ${absolute} does not export a \`login\` function`
346
+ );
347
+ }
348
+ return { login: mod.login };
349
+ } catch (err) {
350
+ if (err instanceof AuthHarnessError) throw err;
351
+ throw new AuthHarnessError(
352
+ `failed to load auth harness at ${absolute}: ${err.message}`,
353
+ err
354
+ );
355
+ }
356
+ })();
357
+ moduleCache.set(absolute, loading);
358
+ return loading;
359
+ }
360
+ function loginPathOf(loginUrl) {
361
+ try {
362
+ return new URL(loginUrl, "http://placeholder").pathname;
363
+ } catch {
364
+ return loginUrl;
365
+ }
366
+ }
367
+ async function verifyPostLogin(page, loginUrl) {
368
+ const loginPath = loginPathOf(loginUrl);
369
+ let currentPath;
370
+ try {
371
+ currentPath = new URL(page.url()).pathname;
372
+ } catch {
373
+ currentPath = page.url();
374
+ }
375
+ if (loginPath && currentPath === loginPath) {
376
+ throw new AuthHarnessError(
377
+ `auth harness returned but page is still on the login URL (${currentPath}). Check that the harness submits the form and waits for redirect.`
378
+ );
379
+ }
380
+ await page.locator('input[type="password"]').first().waitFor({ state: "detached", timeout: 2e3 }).catch(() => {
381
+ });
382
+ const passwordInputs = await page.locator('input[type="password"]:visible').count().catch(() => 0);
383
+ if (passwordInputs > 0) {
384
+ throw new AuthHarnessError(
385
+ `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).`
386
+ );
387
+ }
388
+ }
389
+
390
+ // src/auth/hook.ts
391
+ var AuthConfigMissingError = class extends Error {
392
+ constructor(message) {
393
+ super(message);
394
+ this.name = "AuthConfigMissingError";
395
+ }
396
+ };
397
+ function buildAuthHook(persona, authConfig, cwd) {
398
+ if (!authConfig) {
399
+ throw new AuthConfigMissingError(
400
+ "auth required but .blazediff/config.json has no `auth` block. Run `blazediff-agent auth init`."
401
+ );
402
+ }
403
+ const harnessFile = path.isAbsolute(authConfig.harness) ? authConfig.harness : path.join(cwd, authConfig.harness);
404
+ const canonical = canonicalPersona(persona);
405
+ const loginUrl = authConfig.loginUrl;
406
+ return {
407
+ hook: async (page) => {
408
+ const mod = await loadAuthHarness(harnessFile);
409
+ try {
410
+ await mod.login(page, canonical);
411
+ } catch (err) {
412
+ throw new AuthHarnessError(
413
+ `auth harness threw for persona "${canonical}": ${err.message}`,
414
+ err
415
+ );
416
+ }
417
+ await verifyPostLogin(page, loginUrl);
418
+ }
419
+ };
420
+ }
304
421
  async function loadConfig(cwd = process.cwd()) {
305
422
  const file = paths(cwd).config;
306
423
  if (!existsSync(file)) return null;
@@ -437,10 +554,9 @@ function validateRoute(route, i) {
437
554
  return `route[${i}] missing url`;
438
555
  return null;
439
556
  }
440
- async function loadOrCreateManifest(cwd) {
557
+ async function loadOrCreateManifest(cwd, config) {
441
558
  const existing = await loadManifest(cwd);
442
559
  if (existing) return existing;
443
- const config = await loadConfig(cwd);
444
560
  return emptyManifest(config ? configHash(config) : "sha256:none");
445
561
  }
446
562
  async function runCaptures(opts) {
@@ -463,7 +579,8 @@ async function runCaptures(opts) {
463
579
  valid.push(r);
464
580
  }
465
581
  });
466
- let manifest = writeManifest ? await loadOrCreateManifest(cwd) : null;
582
+ const config = await loadConfig(cwd);
583
+ let manifest = writeManifest ? await loadOrCreateManifest(cwd, config) : null;
467
584
  let manifestUpdates = 0;
468
585
  const slot = new Array(valid.length);
469
586
  const semaphore = new Semaphore(opts.concurrency ?? defaultConcurrency());
@@ -473,6 +590,7 @@ async function runCaptures(opts) {
473
590
  (r, i) => semaphore.run(async () => {
474
591
  const mode = r.mode ?? defaultMode;
475
592
  try {
593
+ const auth = r.auth != null ? buildAuthHook(r.auth, config?.auth, cwd) : void 0;
476
594
  const shot = await captureScreenshot(
477
595
  opts.baseUrl,
478
596
  {
@@ -484,7 +602,8 @@ async function runCaptures(opts) {
484
602
  fullPage: r.fullPage,
485
603
  mode
486
604
  },
487
- cwd
605
+ cwd,
606
+ auth
488
607
  );
489
608
  slot[i] = {
490
609
  id: r.id,
@@ -503,7 +622,8 @@ async function runCaptures(opts) {
503
622
  viewport: r.viewport,
504
623
  mask: r.mask,
505
624
  waitFor: r.waitFor,
506
- fullPage: r.fullPage
625
+ fullPage: r.fullPage,
626
+ auth: r.auth ?? null
507
627
  })
508
628
  );
509
629
  manifestUpdates += 1;
@@ -612,9 +732,9 @@ function extractInternalLinks(base, target, hrefs) {
612
732
  try {
613
733
  const u = new URL(href, target);
614
734
  if (u.origin !== base.origin) continue;
615
- const path18 = u.pathname + u.search;
616
- if (path18.startsWith("/api/")) continue;
617
- out.push(path18);
735
+ const path20 = u.pathname + u.search;
736
+ if (path20.startsWith("/api/")) continue;
737
+ out.push(path20);
618
738
  } catch {
619
739
  }
620
740
  }
@@ -1685,9 +1805,6 @@ function narrowRegion(r) {
1685
1805
  confidence: r.confidence
1686
1806
  };
1687
1807
  }
1688
- function skipResult(entry, message) {
1689
- return { id: entry.id, url: entry.url, status: "pass", message };
1690
- }
1691
1808
  function staleResult(entry) {
1692
1809
  return {
1693
1810
  id: entry.id,
@@ -1696,6 +1813,14 @@ function staleResult(entry) {
1696
1813
  message: "captureHash mismatch: entry was edited without re-capturing"
1697
1814
  };
1698
1815
  }
1816
+ function errorResult(entry, message) {
1817
+ return {
1818
+ id: entry.id,
1819
+ url: entry.url,
1820
+ status: "fail",
1821
+ message
1822
+ };
1823
+ }
1699
1824
  function passResult(entry, baselinePath, actualPath) {
1700
1825
  return {
1701
1826
  id: entry.id,
@@ -1731,6 +1856,14 @@ function failResult(entry, outcome, actualPath, baselinePath, verdict) {
1731
1856
  }
1732
1857
 
1733
1858
  // src/graph/nodes/capture.ts
1859
+ var legacyAuthHinted = false;
1860
+ function maybePrintLegacyHint() {
1861
+ if (legacyAuthHinted) return;
1862
+ legacyAuthHinted = true;
1863
+ process.stderr.write(
1864
+ 'blazediff: manifest entries with auth: "required" are treated as persona "default" \u2014 please migrate.\n'
1865
+ );
1866
+ }
1734
1867
  function makeCaptureNode(semaphore) {
1735
1868
  return async function captureNode(state) {
1736
1869
  const entry = state.entry;
@@ -1738,45 +1871,64 @@ function makeCaptureNode(semaphore) {
1738
1871
  if (!entry || !options) {
1739
1872
  throw new Error("captureNode: entry or options missing");
1740
1873
  }
1741
- if (entry.auth === "required") {
1742
- return {
1743
- captureOutput: {
1744
- id: entry.id,
1745
- skipResult: skipResult(
1746
- entry,
1747
- "skipped: auth required (deferred to v0.2)"
1748
- )
1749
- }
1750
- };
1751
- }
1752
1874
  if (isEntryStale(entry)) {
1753
1875
  return {
1754
1876
  captureOutput: { id: entry.id, skipResult: staleResult(entry) }
1755
1877
  };
1756
1878
  }
1879
+ let auth;
1880
+ if (entry.auth !== null) {
1881
+ if (entry.auth === LEGACY_REQUIRED) maybePrintLegacyHint();
1882
+ try {
1883
+ auth = buildAuthHook(entry.auth, options.auth, options.cwd);
1884
+ } catch (err) {
1885
+ if (err instanceof AuthConfigMissingError) {
1886
+ return {
1887
+ captureOutput: {
1888
+ id: entry.id,
1889
+ skipResult: errorResult(entry, err.message)
1890
+ }
1891
+ };
1892
+ }
1893
+ throw err;
1894
+ }
1895
+ }
1757
1896
  const baselinePath = path.join(options.baselinesDir, `${entry.id}.png`);
1758
- const capture = await semaphore.run(
1759
- () => captureScreenshot(
1760
- options.baseUrl,
1761
- {
1897
+ try {
1898
+ const capture = await semaphore.run(
1899
+ () => captureScreenshot(
1900
+ options.baseUrl,
1901
+ {
1902
+ id: entry.id,
1903
+ url: entry.url,
1904
+ viewport: entry.viewport,
1905
+ mask: entry.mask,
1906
+ waitFor: entry.waitFor,
1907
+ fullPage: entry.fullPage ?? DEFAULT_FULL_PAGE,
1908
+ mode: "actual"
1909
+ },
1910
+ options.cwd,
1911
+ auth
1912
+ )
1913
+ );
1914
+ return {
1915
+ captureOutput: {
1762
1916
  id: entry.id,
1763
- url: entry.url,
1764
- viewport: entry.viewport,
1765
- mask: entry.mask,
1766
- waitFor: entry.waitFor,
1767
- fullPage: entry.fullPage ?? DEFAULT_FULL_PAGE,
1768
- mode: "actual"
1769
- },
1770
- options.cwd
1771
- )
1772
- );
1773
- return {
1774
- captureOutput: {
1775
- id: entry.id,
1776
- captureOutputPath: capture.outputPath,
1777
- baselinePath
1917
+ captureOutputPath: capture.outputPath,
1918
+ baselinePath
1919
+ }
1920
+ };
1921
+ } catch (err) {
1922
+ if (err instanceof AuthHarnessError) {
1923
+ return {
1924
+ captureOutput: {
1925
+ id: entry.id,
1926
+ skipResult: errorResult(entry, `auth: ${err.message}`)
1927
+ }
1928
+ };
1778
1929
  }
1779
- };
1930
+ throw err;
1931
+ }
1780
1932
  };
1781
1933
  }
1782
1934
 
@@ -2215,6 +2367,7 @@ async function runGraph(opts) {
2215
2367
  if (!opts.resume) {
2216
2368
  await checkpointer.deleteThread(threadId);
2217
2369
  }
2370
+ const config = await loadConfig(cwd);
2218
2371
  const input = opts.resume ? new Command({ resume: opts.resume }) : {
2219
2372
  options: {
2220
2373
  baseUrl: opts.baseUrl ?? "",
@@ -2223,7 +2376,8 @@ async function runGraph(opts) {
2223
2376
  concurrency,
2224
2377
  emitDiffPng: opts.emitDiffPng ?? true,
2225
2378
  judge: opts.judge ?? "none",
2226
- baselinesDir
2379
+ baselinesDir,
2380
+ auth: config?.auth
2227
2381
  }
2228
2382
  };
2229
2383
  let collect;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blazediff/agent",
3
- "version": "0.1.4",
3
+ "version": "0.2.0",
4
4
  "description": "Agentic visual regression for BlazeDiff. Auto-discovers routes, captures deterministic screenshots, runs CI checks.",
5
5
  "private": false,
6
6
  "publishConfig": {