sniff-qa 0.8.1 → 0.9.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/.claude-plugin/icon.png +0 -0
- package/.claude-plugin/plugin.json +9 -2
- package/CHANGELOG.md +34 -0
- package/README.md +144 -105
- package/dist/{anthropic-api-ZR3UEB3Z.js → anthropic-api-7PHYF6PN.js} +2 -2
- package/dist/{chunk-7ZOFYET5.js → chunk-64FUDSRY.js} +30 -13
- package/dist/chunk-64FUDSRY.js.map +1 -0
- package/dist/{chunk-CZKMOAXU.js → chunk-7BLJCICM.js} +2 -2
- package/dist/{chunk-EGANHIIE.js → chunk-T72SLMTY.js} +48 -5
- package/dist/chunk-T72SLMTY.js.map +1 -0
- package/dist/{claude-code-ZFTBQXY4.js → claude-code-GJPWO6DN.js} +2 -2
- package/dist/{claude-exploration-provider-QJH6IPYU.js → claude-exploration-provider-XOVJPJ23.js} +2 -2
- package/dist/claude-exploration-provider-XOVJPJ23.js.map +1 -0
- package/dist/cli/index.js +28 -14
- package/dist/cli/index.js.map +1 -1
- package/dist/crawl-XPHT3KIZ.js +23 -0
- package/dist/{crawl-command-RDWGHZC4.js → crawl-command-JHZN4GK7.js} +10 -6
- package/dist/{crawl-command-RDWGHZC4.js.map → crawl-command-JHZN4GK7.js.map} +1 -1
- package/dist/{ensure-browsers-AYKMLUHV.js → ensure-browsers-5NAQQMEC.js} +29 -15
- package/dist/ensure-browsers-5NAQQMEC.js.map +1 -0
- package/dist/{formatter-HC3LT3VH.js → formatter-4VI3ZX5Y.js} +29 -6
- package/dist/formatter-4VI3ZX5Y.js.map +1 -0
- package/dist/generator-AFHVMWC3.js +7 -0
- package/dist/index.d.ts +15 -5
- package/dist/index.js +3 -3
- package/dist/mcp/server.js +22 -9
- package/dist/mcp/server.js.map +1 -1
- package/dist/{prompt-builder-D3FBH534.js → prompt-builder-JT3GQBYP.js} +2 -2
- package/dist/prompt-builder-JT3GQBYP.js.map +1 -0
- package/dist/{provider-BCKFVPTN.js → provider-MMQ6EIBV.js} +6 -6
- package/dist/{quality-run-YAURB242.js → quality-run-KJMBBAQT.js} +2 -2
- package/dist/{report-7FQFH4HW.js → report-XK2MCX2N.js} +3 -3
- package/dist/{unified-YSOTPG5B.js → unified-OEGLPOGE.js} +7 -7
- package/dist/{write-report-6RJWN54I.js → write-report-Y4UPVXUO.js} +2 -2
- package/package.json +6 -8
- package/dist/chunk-7ZOFYET5.js.map +0 -1
- package/dist/chunk-EGANHIIE.js.map +0 -1
- package/dist/claude-exploration-provider-QJH6IPYU.js.map +0 -1
- package/dist/crawl-ZXZRF4Q7.js +0 -15
- package/dist/ensure-browsers-AYKMLUHV.js.map +0 -1
- package/dist/formatter-HC3LT3VH.js.map +0 -1
- package/dist/generator-HIFV67NI.js +0 -7
- package/dist/prompt-builder-D3FBH534.js.map +0 -1
- /package/dist/{anthropic-api-ZR3UEB3Z.js.map → anthropic-api-7PHYF6PN.js.map} +0 -0
- /package/dist/{chunk-CZKMOAXU.js.map → chunk-7BLJCICM.js.map} +0 -0
- /package/dist/{claude-code-ZFTBQXY4.js.map → claude-code-GJPWO6DN.js.map} +0 -0
- /package/dist/{crawl-ZXZRF4Q7.js.map → crawl-XPHT3KIZ.js.map} +0 -0
- /package/dist/{generator-HIFV67NI.js.map → generator-AFHVMWC3.js.map} +0 -0
- /package/dist/{provider-BCKFVPTN.js.map → provider-MMQ6EIBV.js.map} +0 -0
- /package/dist/{quality-run-YAURB242.js.map → quality-run-KJMBBAQT.js.map} +0 -0
- /package/dist/{report-7FQFH4HW.js.map → report-XK2MCX2N.js.map} +0 -0
- /package/dist/{unified-YSOTPG5B.js.map → unified-OEGLPOGE.js.map} +0 -0
- /package/dist/{write-report-6RJWN54I.js.map → write-report-Y4UPVXUO.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/crawl/engine.ts","../src/crawl/noise.ts","../src/crawl/evidence.ts","../src/crawl/crawler.ts","../src/crawl/detectors/page-health.ts","../src/crawl/detectors/runtime-errors.ts","../src/crawl/detectors/content.ts","../src/crawl/detectors/a11y.ts","../src/crawl/detectors/responsive.ts","../src/crawl/detectors/forms.ts","../src/crawl/detectors/loading.ts","../src/crawl/detectors/flow.ts","../src/crawl/index.ts"],"sourcesContent":["import type { Browser, BrowserContext, BrowserContextOptions, Page, APIRequestContext } from 'playwright';\nimport { join } from 'node:path';\nimport { mkdir } from 'node:fs/promises';\nimport { PageEvidence } from './evidence.js';\nimport { normalizeUrl, isEngineInducedFailure } from './noise.js';\nimport { extractLinks, isCrawlable, checkLinks } from './crawler.js';\nimport type { CrawlReport, QaFinding, RawFinding, Severity, Confidence } from './types.js';\nimport type { DetectorContext } from './detectors/context.js';\nimport { pageHealthDetector } from './detectors/page-health.js';\nimport { runtimeErrorDetector } from './detectors/runtime-errors.js';\nimport { contentDetector } from './detectors/content.js';\nimport { a11yDetector } from './detectors/a11y.js';\nimport { responsiveDetector } from './detectors/responsive.js';\nimport { formsDetector } from './detectors/forms.js';\nimport { loadingStateDetector } from './detectors/loading.js';\nimport { flowDetector } from './detectors/flow.js';\nimport { useStorageState, redactText, redactValue } from '../core/redaction.js';\n\nexport interface CrawlOptions {\n startUrl: string;\n maxPages?: number;\n headless?: boolean;\n includeMobile?: boolean;\n outputDir?: string;\n settleMs?: number;\n linkTimeoutMs?: number;\n onProgress?: (msg: string) => void;\n /**\n * Path to a Playwright storage-state JSON file, so the walk runs as a\n * logged-in user. Loading it also installs the report redactor, so the\n * credentials it holds never reach a written artifact or a progress line.\n */\n storageState?: string;\n}\n\nconst DESKTOP = { width: 1280, height: 800 };\nconst MOBILE = { width: 375, height: 812 };\nconst PASSIVE = [pageHealthDetector, runtimeErrorDetector, contentDetector];\nconst INTERACTION = [formsDetector, loadingStateDetector, flowDetector];\n\nfunction routeOf(url: string): string {\n try { return new URL(url).pathname.replace(/\\/+$/, '') || '/'; } catch { return url; }\n}\n\nfunction safeName(s: string): string {\n // Redact before building the name: a token in a path segment would otherwise\n // be burned into a screenshot filename on disk, where no later pass reaches.\n return redactText(s).replace(/[^a-zA-Z0-9]/g, '_').slice(0, 60) || 'root';\n}\n\nexport async function runCrawl(opts: CrawlOptions): Promise<CrawlReport> {\n const maxPages = opts.maxPages ?? 25;\n const headless = opts.headless ?? true;\n const includeMobile = opts.includeMobile ?? true;\n const settleMs = opts.settleMs ?? 3500;\n const linkTimeoutMs = opts.linkTimeoutMs ?? 10000;\n const rawLog = opts.onProgress ?? (() => {});\n // Progress lines quote routes and reach stderr while the crawl is still\n // running, long before any report is assembled.\n const log = (msg: string): void => rawLog(redactText(msg));\n const startUrl = normalizeUrl(opts.startUrl);\n const baseOrigin = new URL(startUrl).origin;\n const startedAt = performance.now();\n\n const outputDir = opts.outputDir ?? join(process.cwd(), 'sniff-reports', 'crawl');\n await mkdir(outputDir, { recursive: true }).catch(() => {});\n\n // Parse the storage state once, then derive both the browser context state\n // and the redaction secret list from that same object.\n const storageState: BrowserContextOptions['storageState'] | undefined = opts.storageState\n ? ((await useStorageState(opts.storageState)) as BrowserContextOptions['storageState'])\n : undefined;\n const authOption: BrowserContextOptions = storageState ? { storageState } : {};\n\n const playwright = await import('playwright');\n const browser: Browser = await playwright.chromium.launch({ headless });\n\n const raw: Array<RawFinding & { url: string; route: string; viewport: 'desktop' | 'mobile'; screenshotPath?: string }> = [];\n const visited: string[] = [];\n const brokenRoutes = new Set<string>();\n const linkRegistry: Array<{ url: string; sourceRoute: string; external: boolean }> = [];\n const linkSeen = new Set<string>();\n let linksChecked = 0;\n\n try {\n const context: BrowserContext = await browser.newContext({ viewport: DESKTOP, ignoreHTTPSErrors: true, ...authOption });\n const page: Page = await context.newPage();\n page.setDefaultTimeout(8000);\n const evidence = new PageEvidence(baseOrigin);\n evidence.attach(page);\n\n async function navigateAndSettle(url: string): Promise<number | null> {\n evidence.reset();\n let status: number | null = null;\n try {\n const resp = await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 15000 });\n status = resp ? resp.status() : null;\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n if (!isEngineInducedFailure(msg)) status = null;\n }\n // bounded settle so a hung request (never-idle) doesn't stall the crawl\n await page.waitForLoadState('networkidle', { timeout: settleMs }).catch(() => {});\n return status;\n }\n\n const queue: string[] = [startUrl];\n while (queue.length > 0 && visited.length < maxPages) {\n const url = queue.shift()!;\n if (visited.includes(url)) continue;\n visited.push(url);\n const route = routeOf(url);\n log(`scan ${route}`);\n\n const navStatus = await navigateAndSettle(url);\n\n const ctx: DetectorContext = {\n page, url, route, viewport: 'desktop', navStatus, evidence, baseOrigin,\n freshNavigate: async () => { await navigateAndSettle(url); },\n };\n\n // Broken pages: emit only the broken-page finding and skip everything\n // else — running a11y/content/interaction on a 404/500 is noise.\n if (navStatus !== null && navStatus >= 400) {\n brokenRoutes.add(route);\n const bf = await pageHealthDetector(ctx).catch(() => [] as RawFinding[]);\n let bshot: string | undefined;\n if (bf.length > 0) {\n bshot = join(outputDir, `${safeName(route)}-desktop.png`);\n await page.screenshot({ path: bshot, fullPage: false }).catch(() => { bshot = undefined; });\n }\n for (const f of bf) raw.push({ ...f, url, route, viewport: 'desktop', ...(bshot ? { screenshotPath: bshot } : {}) });\n continue;\n }\n\n const pageFindings: RawFinding[] = [];\n for (const det of PASSIVE) {\n try { pageFindings.push(...(await det(ctx))); } catch { /* isolate */ }\n }\n try { pageFindings.push(...(await a11yDetector(ctx))); } catch { /* isolate */ }\n\n // Extract links before interaction probes navigate away.\n const links = await extractLinks(page, baseOrigin);\n for (const l of [...links.internal.map((u) => ({ u, ext: false })), ...links.external.map((u) => ({ u, ext: true }))]) {\n if (linkSeen.has(l.u)) continue;\n linkSeen.add(l.u);\n linkRegistry.push({ url: l.u, sourceRoute: route, external: l.ext });\n }\n for (const internal of links.internal) {\n if (!visited.includes(internal) && !queue.includes(internal) && isCrawlable(internal, baseOrigin)) {\n queue.push(internal);\n }\n }\n\n // Interaction probes (each re-navigates from a clean state).\n for (const det of INTERACTION) {\n try { pageFindings.push(...(await det(ctx))); } catch { /* isolate */ }\n }\n\n // One screenshot per route as shared proof; re-navigate for a clean shot.\n let shot: string | undefined;\n if (pageFindings.length > 0) {\n await navigateAndSettle(url);\n shot = join(outputDir, `${safeName(route)}-desktop.png`);\n await page.screenshot({ path: shot, fullPage: false }).catch(() => { shot = undefined; });\n }\n\n for (const f of pageFindings) {\n raw.push({ ...f, url, route, viewport: 'desktop', ...(shot ? { screenshotPath: shot } : {}) });\n }\n }\n\n // ── Broken-link checking (class 2) ───────────────────────────────────\n log(`checking ${linkRegistry.length} links`);\n const request: APIRequestContext = context.request;\n const linkFindings = await checkLinks(request, linkRegistry, { timeout: linkTimeoutMs });\n linksChecked = linkRegistry.length;\n for (const f of linkFindings) {\n const src = linkRegistry.find((l) => f.title.includes(l.url));\n const route = src?.sourceRoute ?? routeOf(startUrl);\n raw.push({ ...f, url: src?.url ?? startUrl, route, viewport: 'desktop' });\n }\n\n await context.close();\n\n // ── Mobile pass: a11y (target-size) + responsive overflow ────────────\n if (includeMobile && visited.length > 0) {\n const mctx: BrowserContext = await browser.newContext({ viewport: MOBILE, ignoreHTTPSErrors: true, ...authOption });\n const mpage: Page = await mctx.newPage();\n mpage.setDefaultTimeout(8000);\n const mevidence = new PageEvidence(baseOrigin);\n mevidence.attach(mpage);\n for (const url of visited) {\n const route = routeOf(url);\n if (brokenRoutes.has(route)) continue; // don't re-scan broken pages on mobile\n log(`mobile ${route}`);\n mevidence.reset();\n try { await mpage.goto(url, { waitUntil: 'domcontentloaded', timeout: 15000 }); } catch { /* skip */ }\n await mpage.waitForLoadState('networkidle', { timeout: settleMs }).catch(() => {});\n const mc: DetectorContext = {\n page: mpage, url, route, viewport: 'mobile', navStatus: null, evidence: mevidence, baseOrigin,\n freshNavigate: async () => { try { await mpage.goto(url, { waitUntil: 'domcontentloaded' }); } catch { /* */ } },\n };\n const mf: RawFinding[] = [];\n try { mf.push(...(await a11yDetector(mc))); } catch { /* */ }\n try { mf.push(...(await responsiveDetector(mc))); } catch { /* */ }\n let shot: string | undefined;\n if (mf.length > 0) {\n shot = join(outputDir, `${safeName(route)}-mobile.png`);\n await mpage.screenshot({ path: shot, fullPage: false }).catch(() => { shot = undefined; });\n }\n for (const f of mf) raw.push({ ...f, url, route, viewport: 'mobile', ...(shot ? { screenshotPath: shot } : {}) });\n }\n await mctx.close();\n }\n } finally {\n await browser.close();\n }\n\n // ── Dedupe + assemble QaFindings ───────────────────────────────────────\n const seen = new Set<string>();\n const findings: QaFinding[] = [];\n for (const r of raw) {\n const key = `${r.ruleId}|${r.route}|${r.dedupeKey ?? r.title}`;\n if (seen.has(key)) continue;\n seen.add(key);\n findings.push({\n ruleId: r.ruleId,\n issueClass: r.issueClass,\n title: r.title,\n severity: r.severity,\n confidence: r.confidence,\n reproduction: {\n url: r.url,\n route: r.route,\n steps: r.steps ?? [`Navigate to ${r.route}`],\n ...(r.screenshotPath ? { screenshotPath: r.screenshotPath } : {}),\n ...(r.consoleExcerpt ? { consoleExcerpt: r.consoleExcerpt } : {}),\n ...(r.networkExcerpt ? { networkExcerpt: r.networkExcerpt } : {}),\n },\n suggestedFix: r.suggestedFix,\n ...(r.needsOutOfBandVerification ? { needsOutOfBandVerification: true } : {}),\n });\n }\n\n findings.sort((a, b) => sevRank(b.severity) - sevRank(a.severity) || a.issueClass - b.issueClass);\n\n const bySeverity: Record<string, number> = {};\n const byConfidence: Record<string, number> = {};\n const byIssueClass: Record<string, number> = {};\n for (const f of findings) {\n bySeverity[f.severity] = (bySeverity[f.severity] ?? 0) + 1;\n byConfidence[f.confidence] = (byConfidence[f.confidence] ?? 0) + 1;\n byIssueClass[String(f.issueClass)] = (byIssueClass[String(f.issueClass)] ?? 0) + 1;\n }\n\n // Redact once, here, so every consumer of the report (the JSON and HTML\n // writers, stdout, the terminal summary, the MCP payload) receives the same\n // clean object. A no-op when no storage state was loaded.\n return redactValue({\n findings,\n stats: {\n pagesVisited: visited.length,\n linksChecked,\n durationMs: Math.round(performance.now() - startedAt),\n startUrl,\n },\n routes: visited.map(routeOf),\n runAt: new Date().toISOString(),\n summary: { total: findings.length, bySeverity, byConfidence, byIssueClass },\n });\n}\n\nfunction sevRank(s: Severity): number {\n return { critical: 5, high: 4, medium: 3, low: 2, info: 1 }[s] ?? 0;\n}\n\nexport type { Confidence };\n","// Noise filtering — the single biggest lever on trust. The old engine flagged\n// every console.error and every HTTP>=400 (favicons, analytics, expected auth)\n// as high/critical, which is the #1 reason QA tools get abandoned. These\n// helpers keep first-party, user-visible signal and drop the rest.\n\n/** Normalize a URL for de-dupe: drop fragment, trailing slash, lowercase host. */\nexport function normalizeUrl(raw: string): string {\n try {\n const u = new URL(raw);\n u.hash = '';\n u.hostname = u.hostname.toLowerCase();\n let s = u.toString();\n // strip a single trailing slash on the path (but keep root \"/\")\n s = s.replace(/\\/(?=$|\\?)/, (m, off) => (u.pathname === '/' ? m : ''));\n return s.replace(/\\/$/, (m) => (u.pathname === '/' ? m : ''));\n } catch {\n return raw;\n }\n}\n\nexport function sameOrigin(url: string, baseOrigin: string): boolean {\n try {\n return new URL(url).origin === baseOrigin;\n } catch {\n return false;\n }\n}\n\n/** Third-party hosts whose requests are never the app's own bug. */\nconst THIRD_PARTY_HOST = /(google-analytics|googletagmanager|doubleclick|google\\.com\\/(ads|pagead)|segment\\.(io|com)|sentry\\.io|hotjar|posthog|datadoghq|mixpanel|amplitude|fullstory|intercom|facebook\\.(com|net)|connect\\.facebook|fonts\\.(googleapis|gstatic)|gstatic\\.com|cloudflareinsights|newrelic|nr-data|bugsnag|launchdarkly|stripe\\.com\\/v\\d)/i;\n\n/** Paths that are framework/dev-server plumbing, not the user's app. */\nconst PLUMBING_PATH = /(\\/favicon\\.ico|\\.map(\\?|$)|\\/robots\\.txt|\\/sitemap\\.xml|\\/_next\\/static\\/.*\\.js\\.map|\\/__nextjs|\\/_next\\/webpack-hmr|\\/@vite\\/|\\/__vite_ping|\\/@react-refresh|\\/sockjs-node|\\/_nuxt\\/|\\/__webpack_hmr|hot-update\\.json|\\/\\.well-known\\/)/i;\n\n/** Static asset extensions we don't treat as broken \"pages\" or \"links\". */\nexport const ASSET_EXT = /\\.(png|jpe?g|gif|svg|webp|avif|ico|css|js|mjs|woff2?|ttf|eot|map|json|webmanifest|mp4|webm|wasm)(\\?|$)/i;\n\n/** Is this request URL irrelevant to \"did the app break\" (so 4xx/5xx is noise)? */\nexport function isIgnorableRequest(url: string): boolean {\n return THIRD_PARTY_HOST.test(url) || PLUMBING_PATH.test(url);\n}\n\n/** Expected/authentication statuses we downgrade rather than flag as failures. */\nexport function isExpectedAuthStatus(status: number): boolean {\n return status === 401 || status === 403;\n}\n\n/** Failures caused by the engine itself (aborted navigations, our own cancels). */\nexport function isEngineInducedFailure(errorText: string | undefined): boolean {\n if (!errorText) return false;\n return /ERR_ABORTED|net::ERR_BLOCKED_BY_CLIENT|context (or browser )?(was )?closed|Target closed|frame was detached/i.test(\n errorText,\n );\n}\n\n/** Console lines that are dev/library chatter, never the app's own defect. */\nconst CONSOLE_NOISE = /(Download the React DevTools|\\[vite\\]|\\[HMR\\]|\\[webpack|Lighthouse|DevTools failed to load|source ?map|React Router Future Flag|was preloaded using link preload but not used|Slow network is detected|Tracking Prevention|net::ERR_|favicon|Failed to load resource)/i;\n\nexport function isConsoleNoise(text: string): boolean {\n return CONSOLE_NOISE.test(text);\n}\n\n/** Visible-text placeholder/mock tokens that should never ship to production. */\nexport const PLACEHOLDER_PATTERNS: Array<{ id: string; re: RegExp; label: string }> = [\n { id: 'lorem', re: /\\blorem ipsum\\b/i, label: 'Lorem ipsum placeholder text' },\n { id: 'todo', re: /\\b(TODO|FIXME|TBD|XXX)\\b[:\\s]/, label: 'TODO/FIXME placeholder note' },\n { id: 'test-email', re: /\\b(test@test\\.com|test@example\\.com|user@example\\.com|admin@admin\\.com|foo@bar\\.com)\\b/i, label: 'Test/placeholder email address' },\n { id: 'example-email', re: /\\b[a-z0-9._%+-]+@example\\.(com|org|net)\\b/i, label: 'example.com placeholder email' },\n { id: 'placeholder-phone', re: /\\b(123[-.\\s]?456[-.\\s]?7890|555[-.\\s]?555[-.\\s]?5555|000[-.\\s]?000[-.\\s]?0000)\\b/, label: 'Placeholder phone number' },\n { id: 'lipsum-name', re: /\\b(John Doe|Jane Doe|Lorem Ipsum)\\b/, label: 'Placeholder name' },\n { id: 'dummy', re: /\\b(dummy (text|data|content)|placeholder (text|content)|your text here|insert .* here)\\b/i, label: 'Dummy/placeholder content' },\n];\n","import type { Page, ConsoleMessage, Response, Request } from 'playwright';\nimport {\n isIgnorableRequest,\n isExpectedAuthStatus,\n isEngineInducedFailure,\n isConsoleNoise,\n sameOrigin,\n} from './noise.js';\n\nexport interface NetworkEvent {\n url: string;\n status: number;\n method: string;\n resourceType: string;\n firstParty: boolean;\n expectedAuth: boolean;\n}\n\nexport interface FailedRequest {\n url: string;\n method: string;\n resourceType: string;\n errorText: string;\n firstParty: boolean;\n}\n\nexport interface ConsoleError {\n text: string;\n location: string;\n}\n\nexport interface PageError {\n message: string;\n stack?: string;\n}\n\n/**\n * Captures console errors, uncaught exceptions, and network failures for a\n * single page, applying the noise filter so only first-party, user-relevant\n * signal survives. Listeners are attached once; call `reset()` before each\n * navigation to scope events to the route being visited.\n */\nexport class PageEvidence {\n consoleErrors: ConsoleError[] = [];\n pageErrors: PageError[] = [];\n /** Filtered HTTP>=400 responses (favicons/analytics/HMR removed). */\n networkFailures: NetworkEvent[] = [];\n /** Filtered request failures (engine-induced aborts removed). */\n failedRequests: FailedRequest[] = [];\n /** All responses (used by detectors to reason about first-party fetches). */\n responses: NetworkEvent[] = [];\n\n private readonly baseOrigin: string;\n private attached = false;\n\n constructor(baseOrigin: string) {\n this.baseOrigin = baseOrigin;\n }\n\n attach(page: Page): void {\n if (this.attached) return;\n this.attached = true;\n\n page.on('console', (msg: ConsoleMessage) => {\n if (msg.type() !== 'error') return;\n const text = msg.text();\n if (isConsoleNoise(text)) return;\n this.consoleErrors.push({ text, location: msg.location()?.url || page.url() });\n });\n\n page.on('pageerror', (err: Error) => {\n if (isConsoleNoise(err.message)) return;\n this.pageErrors.push({ message: err.message, ...(err.stack ? { stack: err.stack } : {}) });\n });\n\n page.on('response', (res: Response) => {\n const url = res.url();\n const status = res.status();\n const ev: NetworkEvent = {\n url,\n status,\n method: res.request().method(),\n resourceType: res.request().resourceType(),\n firstParty: sameOrigin(url, this.baseOrigin),\n expectedAuth: isExpectedAuthStatus(status),\n };\n this.responses.push(ev);\n if (status >= 400 && !isIgnorableRequest(url) && !ev.expectedAuth) {\n this.networkFailures.push(ev);\n }\n });\n\n page.on('requestfailed', (req: Request) => {\n const errorText = req.failure()?.errorText ?? 'unknown error';\n const url = req.url();\n if (isEngineInducedFailure(errorText) || isIgnorableRequest(url)) return;\n this.failedRequests.push({\n url,\n method: req.method(),\n resourceType: req.resourceType(),\n errorText,\n firstParty: sameOrigin(url, this.baseOrigin),\n });\n });\n }\n\n reset(): void {\n this.consoleErrors = [];\n this.pageErrors = [];\n this.networkFailures = [];\n this.failedRequests = [];\n this.responses = [];\n }\n\n /** First-party non-2xx XHR/fetch responses — the \"failed API call\" signal. */\n firstPartyApiFailures(): NetworkEvent[] {\n return this.networkFailures.filter(\n (e) => e.firstParty && (e.resourceType === 'xhr' || e.resourceType === 'fetch'),\n );\n }\n\n consoleExcerpt(limit = 5): string[] {\n return [\n ...this.pageErrors.map((e) => `Uncaught: ${e.message}`),\n ...this.consoleErrors.map((e) => `console.error: ${e.text}`),\n ].slice(0, limit);\n }\n\n networkExcerpt(limit = 5): string[] {\n return [\n ...this.networkFailures.map((e) => `${e.method} ${e.url} -> ${e.status}`),\n ...this.failedRequests.map((e) => `${e.method} ${e.url} -> FAILED (${e.errorText})`),\n ].slice(0, limit);\n }\n}\n","import type { Page, APIRequestContext } from 'playwright';\nimport { normalizeUrl, sameOrigin, ASSET_EXT } from './noise.js';\nimport type { RawFinding } from './types.js';\n\nexport interface PageLinks {\n internal: string[];\n external: string[];\n}\n\n/** Extract absolute, de-duplicated anchor targets from the live DOM. */\nexport async function extractLinks(page: Page, baseOrigin: string): Promise<PageLinks> {\n const hrefs = await page\n .evaluate(() =>\n Array.from(document.querySelectorAll('a[href]'))\n .map((a) => (a as HTMLAnchorElement).href)\n .filter(Boolean),\n )\n .catch(() => [] as string[]);\n\n const internal = new Set<string>();\n const external = new Set<string>();\n for (const raw of hrefs) {\n if (/^(mailto:|tel:|javascript:|#)/i.test(raw)) continue;\n let abs: string;\n try { abs = new URL(raw, page.url()).toString(); } catch { continue; }\n if (!/^https?:/i.test(abs)) continue;\n const norm = normalizeUrl(abs);\n if (sameOrigin(abs, baseOrigin)) internal.add(norm);\n else external.add(norm);\n }\n return { internal: [...internal], external: [...external] };\n}\n\n/** Should this same-origin URL be crawled (visited with a browser)? */\nexport function isCrawlable(url: string, baseOrigin: string): boolean {\n if (!sameOrigin(url, baseOrigin)) return false;\n try {\n const path = new URL(url).pathname;\n if (ASSET_EXT.test(path)) return false;\n if (path.startsWith('/api/')) return false; // API endpoints aren't pages\n } catch { return false; }\n return true;\n}\n\n/**\n * Class 2 — broken links. Checks every discovered link with a real HTTP request\n * (internal: GET, sharing the browser context's cookies; external: HEAD with a\n * GET fallback). A link is broken if it errors or returns >=400. Each broken\n * link is attributed to the source route that referenced it.\n */\nexport async function checkLinks(\n request: APIRequestContext,\n links: Array<{ url: string; sourceRoute: string; external: boolean }>,\n opts: { timeout: number } = { timeout: 10000 },\n): Promise<RawFinding[]> {\n const findings: RawFinding[] = [];\n const seen = new Set<string>();\n\n for (const link of links) {\n if (seen.has(link.url)) continue;\n seen.add(link.url);\n\n let status = 0;\n let errored = false;\n let errText = '';\n try {\n const res = link.external\n ? await request.fetch(link.url, { method: 'HEAD', timeout: opts.timeout, maxRedirects: 5 })\n : await request.get(link.url, { timeout: opts.timeout, maxRedirects: 5 });\n status = res.status();\n // Some servers reject HEAD; retry external with GET before trusting a 4xx/5xx.\n if (link.external && status >= 400 && status !== 404) {\n try {\n const res2 = await request.get(link.url, { timeout: opts.timeout, maxRedirects: 5 });\n status = res2.status();\n } catch { /* keep first status */ }\n }\n } catch (e) {\n errored = true;\n errText = e instanceof Error ? e.message : String(e);\n }\n\n if (errored || status >= 400) {\n const detail = errored ? `request failed (${errText.split('\\n')[0]})` : `HTTP ${status}`;\n findings.push({\n ruleId: link.external ? 'links/broken-external' : 'links/broken-internal',\n issueClass: 2,\n title: `Broken ${link.external ? 'external' : 'internal'} link: ${link.url} (${detail})`,\n severity: link.external ? 'medium' : 'high',\n confidence: 'confirmed',\n steps: [`On ${link.sourceRoute}, the link to ${link.url} ${errored ? 'does not resolve' : `returns ${detail}`}`],\n networkExcerpt: [`${link.url} -> ${errored ? 'FAILED: ' + errText.split('\\n')[0] : status}`],\n suggestedFix: link.external\n ? 'Update or remove the dead external link.'\n : 'Fix the href or add the missing route; this internal link leads nowhere.',\n dedupeKey: `link:${link.url}`,\n });\n }\n }\n return findings;\n}\n","import type { Detector, DetectorContext } from './context.js';\nimport type { RawFinding } from '../types.js';\n\nconst STACK_TRACE_RE =\n /(\\bat\\s+\\w[\\w.]*\\s*\\(.*:\\d+:\\d+\\)|Cannot read propert(y|ies) of (undefined|null)|\\bTypeError:|\\bReferenceError:|Unhandled (Runtime )?Error|Application error: a (server|client)-side exception|Internal Server Error|Traceback \\(most recent call last\\))/;\n\n/**\n * Class 1 — broken pages/routes. Three signals:\n * - the navigation returned a 4xx/5xx\n * - a 2xx page rendered (almost) nothing (blank/white screen)\n * - the visible content is a raw stack trace / crash screen\n */\nexport const pageHealthDetector: Detector = async (ctx: DetectorContext): Promise<RawFinding[]> => {\n const findings: RawFinding[] = [];\n\n if (ctx.navStatus !== null && ctx.navStatus >= 400) {\n const isServer = ctx.navStatus >= 500;\n findings.push({\n ruleId: 'route/broken-page',\n issueClass: 1,\n title: `Page returns HTTP ${ctx.navStatus}`,\n severity: isServer ? 'critical' : 'high',\n confidence: 'confirmed',\n steps: [`Navigate to ${ctx.route}`, `Server responded with HTTP ${ctx.navStatus}`],\n suggestedFix: isServer\n ? 'The route throws server-side. Check the server logs/handler for this path and return a valid page or a proper error page.'\n : 'The route is not found. Fix the link that points here, add the missing route, or return a helpful 404 page.',\n });\n }\n\n // DOM-level signals only make sense if we actually rendered something.\n const dom = await ctx.page\n .evaluate(() => {\n const body = document.body;\n const text = (body?.innerText || '').trim();\n const main = document.querySelector('main, [role=\"main\"], #root, #app, #__next');\n const mainText = (main?.textContent || '').trim();\n const interactive = document.querySelectorAll('a[href], button, input, select, textarea, [role=\"button\"]').length;\n return { textLen: text.length, sample: text.slice(0, 400), mainText: mainText.length, interactive };\n })\n .catch(() => null);\n\n if (dom && (ctx.navStatus === null || ctx.navStatus < 400)) {\n // Crash screen: a raw stack trace / framework error is visible to the user.\n if (STACK_TRACE_RE.test(dom.sample)) {\n findings.push({\n ruleId: 'route/crash-screen',\n issueClass: 1,\n title: 'Raw error / stack trace shown to the user',\n severity: 'high',\n confidence: 'confirmed',\n steps: [`Navigate to ${ctx.route}`, 'The page renders a raw stack trace / crash screen'],\n suggestedFix: 'Catch the error and render a friendly error state; never expose stack traces to users.',\n dedupeKey: 'crash',\n });\n } else if (dom.textLen < 12 && dom.interactive === 0) {\n // Blank render: a 200 that shows essentially nothing and offers no controls.\n findings.push({\n ruleId: 'route/blank-render',\n issueClass: 1,\n title: 'Page renders blank (no visible content or controls)',\n severity: 'high',\n confidence: 'likely',\n steps: [`Navigate to ${ctx.route}`, 'The page loaded (HTTP 2xx) but rendered no visible content'],\n suggestedFix: 'A 200 response rendered an empty document, likely a client-side render crash or missing data. Check the console for errors and verify the page mounts.',\n dedupeKey: 'blank',\n });\n }\n }\n\n return findings;\n};\n","import type { Detector, DetectorContext } from './context.js';\nimport type { RawFinding } from '../types.js';\n\n/**\n * Class 3 — console errors, uncaught exceptions, and failed first-party network\n * requests observed during the visit. Evidence is already noise-filtered\n * (favicons / analytics / HMR / expected-auth removed) in PageEvidence.\n */\nexport const runtimeErrorDetector: Detector = async (ctx: DetectorContext): Promise<RawFinding[]> => {\n const findings: RawFinding[] = [];\n const { evidence } = ctx;\n\n // Uncaught exceptions — always a real defect.\n const seenExc = new Set<string>();\n for (const err of evidence.pageErrors) {\n const key = err.message.slice(0, 120);\n if (seenExc.has(key)) continue;\n seenExc.add(key);\n findings.push({\n ruleId: 'js/uncaught-exception',\n issueClass: 3,\n title: `Uncaught exception: ${err.message.slice(0, 100)}`,\n severity: 'high',\n confidence: 'confirmed',\n steps: [`Navigate to ${ctx.route}`, `An uncaught exception was thrown: ${err.message}`],\n consoleExcerpt: [err.stack ? err.stack.split('\\n').slice(0, 4).join('\\n') : err.message],\n suggestedFix: 'Fix the thrown error; an uncaught exception can halt the rest of the page script (other features silently stop working).',\n dedupeKey: key,\n });\n }\n\n // console.error — real, but a notch lower than a thrown exception.\n const seenCon = new Set<string>();\n for (const c of evidence.consoleErrors) {\n const key = c.text.slice(0, 120);\n if (seenCon.has(key)) continue;\n seenCon.add(key);\n findings.push({\n ruleId: 'console/error',\n issueClass: 3,\n title: `Console error: ${c.text.slice(0, 100)}`,\n severity: 'medium',\n confidence: 'likely',\n steps: [`Navigate to ${ctx.route}`, `console.error logged: ${c.text}`],\n consoleExcerpt: [c.text],\n suggestedFix: 'Investigate the logged error; console errors often mark a feature that failed silently.',\n dedupeKey: key,\n });\n }\n\n // Failed first-party API calls (xhr/fetch non-2xx).\n const seenNet = new Set<string>();\n for (const ev of evidence.firstPartyApiFailures()) {\n const key = `${ev.method} ${ev.url}`;\n if (seenNet.has(key)) continue;\n seenNet.add(key);\n const isServer = ev.status >= 500;\n findings.push({\n ruleId: 'network/failed-request',\n issueClass: 3,\n title: `Failed request: ${ev.method} ${shortPath(ev.url)} → ${ev.status}`,\n severity: isServer ? 'high' : 'medium',\n confidence: 'confirmed',\n steps: [`Navigate to ${ctx.route}`, `The page requested ${ev.method} ${ev.url} which returned HTTP ${ev.status}`],\n networkExcerpt: [`${ev.method} ${ev.url} -> ${ev.status}`],\n suggestedFix: isServer\n ? 'The API endpoint errors (5xx). Check the server handler; the page likely shows stale or missing data.'\n : 'The API call failed (4xx). Verify the endpoint URL and request shape.',\n dedupeKey: key,\n });\n }\n\n return findings;\n};\n\nfunction shortPath(u: string): string {\n try { return new URL(u).pathname; } catch { return u; }\n}\n","import type { Detector, DetectorContext } from './context.js';\nimport type { RawFinding } from '../types.js';\nimport { PLACEHOLDER_PATTERNS } from '../noise.js';\n\n/**\n * Class 4 — empty data and placeholder/fake data. Both read only VISIBLE text\n * (innerText), never raw HTML/comments, to avoid false credit and to match what\n * a user actually sees.\n */\nexport const contentDetector: Detector = async (ctx: DetectorContext): Promise<RawFinding[]> => {\n const findings: RawFinding[] = [];\n\n const data = await ctx.page\n .evaluate(() => {\n const visibleText = (document.body?.innerText || '').trim();\n\n // Empty collections: a data table (thead + empty tbody) or a labelled\n // list/grid that renders zero items and shows no empty-state message.\n function isShown(el: Element): boolean {\n const s = getComputedStyle(el as HTMLElement);\n return s.display !== 'none' && s.visibility !== 'hidden';\n }\n function nearbyText(el: Element): string {\n const scope = el.closest('section, main, article, div, body') || el.parentElement || el;\n return (scope.textContent || '').toLowerCase();\n }\n const EMPTY_HINT = /(no |empty|nothing|0 results|no results|you (have|don'?t)|once you|get started|add your first|haven'?t)/i;\n\n const empties: Array<{ kind: string; label: string }> = [];\n\n // data tables\n for (const table of Array.from(document.querySelectorAll('table'))) {\n if (!isShown(table)) continue;\n const headCols = table.querySelectorAll('thead th, thead td').length;\n const bodyRows = table.querySelectorAll('tbody tr').length;\n if (headCols >= 2 && bodyRows === 0) {\n const heading = (table.closest('section, main, body')?.querySelector('h1,h2,h3')?.textContent || '').trim();\n if (!EMPTY_HINT.test(nearbyText(table))) {\n empties.push({ kind: 'table', label: heading || 'data table' });\n }\n }\n }\n // labelled lists/grids\n for (const list of Array.from(document.querySelectorAll('ul[aria-label], ol[aria-label], [role=\"list\"], [data-testid*=\"list\" i], [class*=\"results\" i]'))) {\n if (!isShown(list)) continue;\n const items = list.querySelectorAll('li, [role=\"listitem\"], [class*=\"item\" i]').length;\n if (items === 0 && !EMPTY_HINT.test(nearbyText(list))) {\n const label = (list.getAttribute('aria-label') || '').trim();\n empties.push({ kind: 'list', label: label || 'list' });\n }\n }\n\n return { visibleText, empties };\n })\n .catch(() => null);\n\n if (!data) return findings;\n\n for (const e of data.empties) {\n findings.push({\n ruleId: 'data/empty-collection',\n issueClass: 4,\n title: `Empty ${e.kind} with no empty-state (\"${e.label}\")`,\n severity: 'medium',\n confidence: 'likely',\n steps: [`Navigate to ${ctx.route}`, `The \"${e.label}\" ${e.kind} rendered with zero rows/items and no empty-state message`],\n suggestedFix: 'Either load the data or render a clear empty-state (\"You have no orders yet\"). A silently empty table reads as a bug.',\n dedupeKey: `empty:${e.kind}:${e.label}`,\n });\n }\n\n // Placeholder / mock data left in the rendered page.\n for (const p of PLACEHOLDER_PATTERNS) {\n const m = data.visibleText.match(p.re);\n if (m) {\n findings.push({\n ruleId: 'data/placeholder-content',\n issueClass: 4,\n title: `${p.label} visible in the page`,\n severity: 'medium',\n confidence: 'confirmed',\n steps: [`Navigate to ${ctx.route}`, `Found placeholder/mock content: \"${m[0]}\"`],\n suggestedFix: 'Replace placeholder/mock data with real content (or guard it out of production builds).',\n dedupeKey: `placeholder:${p.id}`,\n });\n }\n }\n\n return findings;\n};\n","import type { Detector, DetectorContext } from './context.js';\nimport type { RawFinding, Severity } from '../types.js';\n\nfunction mapAxeImpact(impact: string | null | undefined): Severity {\n switch (impact) {\n case 'critical': return 'high';\n case 'serious': return 'high';\n case 'moderate': return 'medium';\n case 'minor': return 'low';\n default: return 'medium';\n }\n}\n\n// axe rule id -> our issue class. target-size is a responsive/touch concern (10).\nfunction issueClassFor(axeId: string): number {\n return axeId === 'target-size' ? 10 : 11;\n}\n\n/**\n * Class 11 (accessibility) + the touch-target part of class 10, via axe-core.\n * axe is designed to emit zero false positives (uncertain checks are\n * \"incomplete\", which we drop), so every violation is reported as `confirmed`.\n * One finding per violation (not per node) to keep volume sane.\n */\nexport const a11yDetector: Detector = async (ctx: DetectorContext): Promise<RawFinding[]> => {\n let AxeBuilder: typeof import('@axe-core/playwright').AxeBuilder;\n try {\n ({ AxeBuilder } = await import('@axe-core/playwright'));\n } catch {\n return [];\n }\n\n let builder = new AxeBuilder({ page: ctx.page }).withTags(['wcag2a', 'wcag2aa', 'wcag21aa']);\n if (ctx.viewport === 'mobile') {\n builder = builder.withRules(['target-size']);\n }\n\n let results;\n try {\n results = await builder.analyze();\n } catch {\n return [];\n }\n\n const findings: RawFinding[] = [];\n\n // Deterministic missing-label check (axe's `label` rule misses some cases).\n const unlabeled = await ctx.page\n .evaluate(() => {\n const TYPES = ['text', 'email', 'password', 'tel', 'search', 'number', 'url', ''];\n const controls = Array.from(document.querySelectorAll('input, select, textarea')) as HTMLInputElement[];\n const out: string[] = [];\n for (const c of controls) {\n const type = (c.getAttribute('type') || '').toLowerCase();\n if (c.tagName === 'INPUT' && !TYPES.includes(type)) continue; // skip submit/button/checkbox/radio/hidden\n const s = getComputedStyle(c);\n if (s.display === 'none' || s.visibility === 'hidden') continue;\n const hasAria = c.getAttribute('aria-label') || c.getAttribute('aria-labelledby') || c.getAttribute('title');\n const labelledBy = c.id ? document.querySelector(`label[for=\"${CSS.escape(c.id)}\"]`) : null;\n const wrapping = c.closest('label');\n if (!hasAria && !labelledBy && !wrapping) {\n out.push((c.getAttribute('name') || c.getAttribute('placeholder') || type || 'field').slice(0, 30));\n }\n }\n return out;\n })\n .catch(() => [] as string[]);\n\n if (unlabeled.length > 0) {\n findings.push({\n ruleId: 'a11y/label-missing',\n issueClass: 11,\n title: `Form control${unlabeled.length > 1 ? 's' : ''} without an accessible label (${unlabeled.length})`,\n severity: 'medium',\n confidence: 'confirmed',\n steps: [`Navigate to ${ctx.route}`, `Found input(s) with no <label>, aria-label, or title: ${unlabeled.join(', ')}`],\n suggestedFix: 'Associate a <label for> (or aria-label) with every form control so screen readers and clicks on the label work.',\n dedupeKey: 'label-missing',\n });\n }\n\n for (const v of results.violations) {\n const nodeCount = v.nodes.length;\n const sampleHtml = v.nodes.slice(0, 2).map((n) => n.html.slice(0, 120));\n findings.push({\n ruleId: `a11y/${v.id}`,\n issueClass: issueClassFor(v.id),\n title: `${v.help}${nodeCount > 1 ? ` (${nodeCount} elements)` : ''}`,\n severity: mapAxeImpact(v.impact),\n confidence: 'confirmed',\n steps: [\n `Navigate to ${ctx.route}${ctx.viewport === 'mobile' ? ' (mobile viewport)' : ''}`,\n `axe-core WCAG check \"${v.id}\" failed: ${v.description}`,\n ...sampleHtml.map((h) => `element: ${h}`),\n ],\n suggestedFix: `${v.help}. See ${v.helpUrl}`,\n dedupeKey: `a11y:${v.id}`,\n });\n }\n return findings;\n};\n","import type { Detector, DetectorContext } from './context.js';\nimport type { RawFinding } from '../types.js';\n\n/**\n * Class 10 — responsive layout. Horizontal overflow at mobile width is a\n * high-precision signal: if the document scrolls sideways on a phone, the\n * layout is broken. Run on the mobile pass only (tap-target size is handled by\n * axe's target-size rule in the a11y detector).\n */\nexport const responsiveDetector: Detector = async (ctx: DetectorContext): Promise<RawFinding[]> => {\n if (ctx.viewport !== 'mobile') return [];\n const findings: RawFinding[] = [];\n\n // ── Tap targets below the 24x24 WCAG 2.2 minimum (buttons/controls) ────\n const tiny = await ctx.page\n .evaluate(() => {\n const MIN = 24;\n const controls = Array.from(\n document.querySelectorAll('button, [role=\"button\"], input[type=\"submit\"], input[type=\"button\"], a.btn, a.button'),\n ) as HTMLElement[];\n const out: Array<{ label: string; w: number; h: number }> = [];\n for (const c of controls) {\n const s = getComputedStyle(c);\n if (s.display === 'none' || s.visibility === 'hidden') continue;\n const r = c.getBoundingClientRect();\n if (r.width === 0 || r.height === 0) continue;\n if (r.width < MIN || r.height < MIN) {\n out.push({ label: (c.textContent || c.getAttribute('aria-label') || c.tagName).trim().slice(0, 30), w: Math.round(r.width), h: Math.round(r.height) });\n }\n }\n return out;\n })\n .catch(() => [] as Array<{ label: string; w: number; h: number }>);\n\n if (tiny.length > 0) {\n const sample = tiny.slice(0, 4).map((t) => `\"${t.label}\" ${t.w}x${t.h}px`).join(', ');\n findings.push({\n ruleId: 'responsive/tap-target-too-small',\n issueClass: 10,\n title: `Tap target${tiny.length > 1 ? 's' : ''} below 24x24px (${tiny.length})`,\n severity: 'low',\n confidence: 'likely',\n steps: [`Navigate to ${ctx.route} at 375px (mobile) width`, `Found ${tiny.length} control(s) smaller than the 24x24px minimum: ${sample}`],\n suggestedFix: 'Give interactive controls at least a 24x24px (ideally 44x44px) touch area via padding/min-height.',\n dedupeKey: 'tap-target',\n });\n }\n\n const overflow = await ctx.page\n .evaluate(() => {\n const doc = document.documentElement;\n const slack = 4; // ignore sub-pixel rounding\n const scrollW = doc.scrollWidth;\n const clientW = doc.clientWidth;\n if (scrollW <= clientW + slack) return null;\n\n // find the widest element that exceeds the viewport, for the proof\n let worst: { tag: string; width: number; desc: string } | null = null;\n for (const el of Array.from(document.body.querySelectorAll('*'))) {\n const r = (el as HTMLElement).getBoundingClientRect();\n if (r.width > clientW + slack && (!worst || r.width > worst.width)) {\n const cls = (el as HTMLElement).className && typeof (el as HTMLElement).className === 'string'\n ? '.' + (el as HTMLElement).className.trim().split(/\\s+/).join('.')\n : '';\n worst = { tag: el.tagName.toLowerCase(), width: Math.round(r.width), desc: el.tagName.toLowerCase() + cls.slice(0, 60) };\n }\n }\n return { scrollW, clientW, worst };\n })\n .catch(() => null);\n\n if (!overflow) return findings;\n\n const culprit = overflow.worst ? ` Widest offender: <${overflow.worst.desc}> at ${overflow.worst.width}px.` : '';\n findings.push({\n ruleId: 'responsive/horizontal-overflow',\n issueClass: 10,\n title: 'Horizontal overflow at mobile width',\n severity: 'medium',\n confidence: 'confirmed',\n steps: [\n `Navigate to ${ctx.route} at 375px (mobile) width`,\n `The document scrolls horizontally: content is ${overflow.scrollW}px wide in a ${overflow.clientW}px viewport.${culprit}`,\n ],\n suggestedFix: 'Constrain fixed-width elements (use max-width:100%, overflow-x handling, or responsive units) so the page fits the viewport.',\n dedupeKey: 'overflow',\n });\n return findings;\n};\n","import type { Page } from 'playwright';\nimport type { Detector, DetectorContext } from './context.js';\nimport type { RawFinding } from '../types.js';\n\nconst SUCCESS_RE = /(success|thank you|thanks|confirmed|order (placed|received)|received|we'?ll be in touch|check your email|submitted|saved|welcome)/i;\nconst SUBMIT_TEXT_RE = /(submit|create|sign ?up|register|continue|next|save|place order|pay|checkout|send|log ?in|sign ?in|subscribe|apply)/i;\n\ninterface Snapshot {\n url: string;\n textLen: number;\n alerts: number;\n invalidField: boolean;\n successText: boolean;\n}\n\nasync function snapshot(page: Page): Promise<Snapshot> {\n return page.evaluate((successSrc) => {\n const re = new RegExp(successSrc, 'i');\n const text = document.body?.innerText || '';\n const alerts = document.querySelectorAll('[role=\"alert\"], [aria-live], .error, .invalid, .field-error, [class*=\"error\" i]').length;\n const invalidField = Array.from(document.querySelectorAll('input, select, textarea')).some(\n (el) => (el as HTMLInputElement).validity && !(el as HTMLInputElement).validity.valid,\n );\n return { url: location.href, textLen: text.length, alerts, invalidField, successText: re.test(text) };\n }, SUCCESS_RE.source);\n}\n\nasync function fillForm(page: Page, formIdx: number, email: string): Promise<boolean> {\n const form = page.locator('form').nth(formIdx);\n const inputs = form.locator('input:visible, textarea:visible, select:visible');\n const n = await inputs.count().catch(() => 0);\n let filledAny = false;\n for (let i = 0; i < n; i++) {\n const el = inputs.nth(i);\n const type = (await el.getAttribute('type').catch(() => '') || '').toLowerCase();\n const name = ((await el.getAttribute('name').catch(() => '')) || '') + ' ' + ((await el.getAttribute('placeholder').catch(() => '')) || '');\n try {\n if (type === 'checkbox' || type === 'radio') { await el.check({ timeout: 1000 }); filledAny = true; }\n else if (type === 'email' || /email/i.test(name)) { await el.fill(email, { timeout: 1000 }); filledAny = true; }\n else if (type === 'password') { await el.fill('Passw0rd!23', { timeout: 1000 }); filledAny = true; }\n else if (type === 'tel' || /phone/i.test(name)) { await el.fill('5551234567', { timeout: 1000 }); filledAny = true; }\n else if (type === 'number') { await el.fill('1', { timeout: 1000 }); filledAny = true; }\n else if (type === '' || type === 'text' || type === 'search' || el) { await el.fill('QA Test 123', { timeout: 1000 }); filledAny = true; }\n } catch { /* skip uncooperative field */ }\n }\n return filledAny;\n}\n\nasync function findSubmit(page: Page, formIdx: number) {\n const form = page.locator('form').nth(formIdx);\n let btn = form.locator('button[type=\"submit\"], input[type=\"submit\"]').first();\n if (await btn.count() === 0) {\n const buttons = form.locator('button, [role=\"button\"]');\n const bn = await buttons.count();\n for (let i = 0; i < bn; i++) {\n const t = (await buttons.nth(i).innerText().catch(() => '')) || '';\n if (SUBMIT_TEXT_RE.test(t)) { btn = buttons.nth(i); break; }\n if (i === bn - 1) btn = buttons.first();\n }\n }\n return btn;\n}\n\n/**\n * Class 5 (broken forms) + class 9 (silent async). For each form we click the\n * submit control and assert SOMETHING observable happened (navigation, a\n * network call, a DOM change, a validation message, or a success message).\n * - nothing at all happened -> form/submit-noop (the button is dead)\n * - a request fired but the UI is inert-> async/no-success-feedback (silent)\n * - an invalid email was accepted -> form/no-validation\n * The clean control page's working form (which navigates on submit) is the\n * explicit false-positive guard.\n */\nexport const formsDetector: Detector = async (ctx: DetectorContext): Promise<RawFinding[]> => {\n const findings: RawFinding[] = [];\n const formCount = await ctx.page.locator('form').count().catch(() => 0);\n if (formCount === 0) return findings;\n\n const limit = Math.min(formCount, 2);\n for (let f = 0; f < limit; f++) {\n // ── Pass A: submit with valid values, observe any effect ──────────────\n await ctx.freshNavigate();\n const hasSubmit = (await findSubmit(ctx.page, f).then((b) => b.count()).catch(() => 0)) > 0;\n if (!hasSubmit) continue;\n\n await fillForm(ctx.page, f, 'qa.tester@example.org');\n const before = await snapshot(ctx.page);\n\n let postRequest = false;\n let anyRequest = false;\n const onReq = (req: import('playwright').Request) => {\n anyRequest = true;\n if (req.method() === 'POST' || req.method() === 'PUT' || req.method() === 'PATCH') postRequest = true;\n };\n ctx.page.on('request', onReq);\n const submit = await findSubmit(ctx.page, f);\n await submit.click({ timeout: 2000 }).catch(() => {});\n await ctx.page.waitForTimeout(1200);\n ctx.page.off('request', onReq);\n\n const after = await snapshot(ctx.page).catch(() => before);\n const urlChanged = after.url !== before.url;\n const domChanged = Math.abs(after.textLen - before.textLen) > 8;\n const newAlert = after.alerts > before.alerts || after.invalidField;\n const success = after.successText && !before.successText;\n const observableEffect = urlChanged || domChanged || newAlert || success || anyRequest;\n\n if (!observableEffect) {\n findings.push({\n ruleId: 'form/submit-noop',\n issueClass: 5,\n title: 'Submit button does nothing',\n severity: 'high',\n confidence: 'likely',\n steps: [`Navigate to ${ctx.route}`, 'Fill the form with valid values', 'Click the submit button', 'Nothing happens: no navigation, no request, no message, no visible change'],\n suggestedFix: 'Wire the submit handler (or form action). A dead submit button blocks the whole flow.',\n dedupeKey: `submit-noop:${f}`,\n });\n } else if (postRequest && !urlChanged && !domChanged && !success) {\n findings.push({\n ruleId: 'async/no-success-feedback',\n issueClass: 9,\n title: 'Form submits but shows no success feedback',\n severity: 'high',\n confidence: 'likely',\n steps: [`Navigate to ${ctx.route}`, 'Fill and submit the form', 'A request was sent, but the UI shows no success message, redirect, or change'],\n suggestedFix: 'Render a clear success state (message/redirect) after the request resolves; users cannot tell if the action worked.',\n needsOutOfBandVerification: true,\n dedupeKey: `no-success:${f}`,\n });\n }\n\n // ── Pass B: invalid email accepted with no validation ─────────────────\n const hasEmail = await ctx.page\n .locator('form').nth(f)\n .locator('input[type=\"email\"], input[name*=\"email\" i], input[placeholder*=\"email\" i]')\n .count().catch(() => 0);\n if (hasEmail > 0) {\n await ctx.freshNavigate();\n await fillForm(ctx.page, f, 'notanemail');\n const b2 = await snapshot(ctx.page);\n const submit2 = await findSubmit(ctx.page, f);\n await submit2.click({ timeout: 2000 }).catch(() => {});\n await ctx.page.waitForTimeout(1000);\n const a2 = await snapshot(ctx.page).catch(() => b2);\n // Validation fired if the field is marked invalid or a new error appeared.\n const validationFired = a2.invalidField || a2.alerts > b2.alerts;\n if (!validationFired) {\n findings.push({\n ruleId: 'form/no-validation',\n issueClass: 5,\n title: 'Invalid email accepted without validation',\n severity: 'medium',\n confidence: 'likely',\n steps: [`Navigate to ${ctx.route}`, 'Enter an invalid email (\"notanemail\")', 'Submit the form', 'No validation error fires and the value is accepted'],\n suggestedFix: 'Validate the email field (use type=\"email\" or explicit validation) and show an inline error for invalid input.',\n dedupeKey: `no-validation:${f}`,\n });\n }\n }\n }\n\n return findings;\n};\n","import type { Detector, DetectorContext } from './context.js';\nimport type { RawFinding } from '../types.js';\n\nconst ERROR_TEXT_RE = /(error|failed|failure|something went wrong|went wrong|try again|couldn'?t|could not|unable to|problem loading|retry)/i;\n\n/**\n * Class 8 — loading / error states.\n * - stuck spinner: a loading indicator is still visible after the page has\n * had ample time to settle (e.g. a request that never resolves).\n * - missing error state: a first-party API call failed but the page shows no\n * error affordance at all (the failure is swallowed).\n */\nexport const loadingStateDetector: Detector = async (ctx: DetectorContext): Promise<RawFinding[]> => {\n const findings: RawFinding[] = [];\n\n const spinnerSel =\n '[class*=\"spin\" i],[class*=\"loading\" i],[class*=\"loader\" i],[class*=\"skeleton\" i],[role=\"progressbar\"],[aria-busy=\"true\"]';\n\n const stillSpinning = async (): Promise<boolean> =>\n ctx.page\n .evaluate((sel) => {\n const els = Array.from(document.querySelectorAll(sel));\n return els.some((el) => {\n const s = getComputedStyle(el as HTMLElement);\n const r = (el as HTMLElement).getBoundingClientRect();\n return s.display !== 'none' && s.visibility !== 'hidden' && s.opacity !== '0' && r.width > 0 && r.height > 0;\n });\n }, spinnerSel)\n .catch(() => false);\n\n if (await stillSpinning()) {\n // Confirm it is genuinely stuck (still there after a further wait).\n await ctx.page.waitForTimeout(2500);\n if (await stillSpinning()) {\n findings.push({\n ruleId: 'loading/stuck-spinner',\n issueClass: 8,\n title: 'Loading spinner never resolves',\n severity: 'medium',\n confidence: 'likely',\n steps: [`Navigate to ${ctx.route}`, 'A loading indicator is still spinning after the page has had ample time to settle', 'A request likely hung and the UI is stuck loading'],\n suggestedFix: 'Add a timeout/fallback for the pending request and resolve the loading state (render data, an empty state, or an error).',\n networkExcerpt: ctx.evidence.networkExcerpt(),\n dedupeKey: 'stuck-spinner',\n });\n }\n }\n\n // Missing error state: a first-party call failed but nothing tells the user.\n const apiFailures = ctx.evidence.firstPartyApiFailures();\n if (apiFailures.length > 0) {\n const hasErrorUi = await ctx.page\n .evaluate((src) => {\n const re = new RegExp(src, 'i');\n const hasAlert = document.querySelector('[role=\"alert\"]') !== null;\n return hasAlert || re.test(document.body?.innerText || '');\n }, ERROR_TEXT_RE.source)\n .catch(() => true);\n if (!hasErrorUi) {\n const f = apiFailures[0]!;\n findings.push({\n ruleId: 'state/missing-error-state',\n issueClass: 8,\n title: 'Failed request shows no error state to the user',\n severity: 'medium',\n confidence: 'likely',\n steps: [`Navigate to ${ctx.route}`, `A request failed (${f.method} ${f.url} → ${f.status})`, 'The page shows no error message, retry, or fallback, so the failure is silent'],\n suggestedFix: 'Render a visible error state when a request fails (message + retry), instead of swallowing the error.',\n networkExcerpt: ctx.evidence.networkExcerpt(),\n dedupeKey: 'missing-error-state',\n });\n }\n }\n\n return findings;\n};\n","import type { Detector, DetectorContext } from './context.js';\nimport type { RawFinding } from '../types.js';\n\nconst FORWARD_RE = /\\b(next|continue|forward|proceed|step\\s?2|go on)\\b/i;\nconst BACK_RE = /\\b(back|previous|prev|go back)\\b/i;\nconst FINISH_RE = /\\b(finish|done|complete|submit|next|continue|confirm)\\b/i;\nconst PRIMARY_ACTION_RE = /\\b(checkout|buy now|buy|purchase|add to cart|place order|get started|sign\\s?up|start free|book now|proceed to|continue to)\\b/i;\nconst SENTINEL = 'SNIFFSTATE12345';\n\n/**\n * Class 6 (state-loss), class 7 (flow dead-end), class 12 (unclear action).\n */\nexport const flowDetector: Detector = async (ctx: DetectorContext): Promise<RawFinding[]> => {\n const findings: RawFinding[] = [];\n\n // ── State-loss + dead-end (multi-step flows only) ─────────────────────\n await ctx.freshNavigate();\n const trackSel = await ctx.page\n .evaluate(() => {\n const inputs = Array.from(document.querySelectorAll('input')) as HTMLInputElement[];\n const el = inputs.find((i) => {\n const t = (i.type || 'text').toLowerCase();\n const s = getComputedStyle(i);\n return ['text', 'email', 'search', 'tel', ''].includes(t) && s.display !== 'none' && s.visibility !== 'hidden';\n });\n if (!el) return null;\n if (el.id) return `#${CSS.escape(el.id)}`;\n if (el.name) return `[name=\"${CSS.escape(el.name)}\"]`;\n return null;\n })\n .catch(() => null);\n\n const forward = ctx.page.locator('button:visible, a:visible, [role=\"button\"]').filter({ hasText: FORWARD_RE }).first();\n const hasForward = (await forward.count().catch(() => 0)) > 0;\n\n if (trackSel && hasForward) {\n await ctx.page.fill(trackSel, SENTINEL, { timeout: 1500 }).catch(() => {});\n await forward.click({ timeout: 2000 }).catch(() => {});\n await ctx.page.waitForTimeout(800);\n\n // Dead-end: after advancing, fill any inputs on this step then look for a\n // forward/finish control that is permanently disabled with no enabled path.\n await ctx.page.locator('input[type=\"checkbox\"]:visible').first().check({ timeout: 800 }).catch(() => {});\n const deadEnd = await ctx.page\n .evaluate((sources: string[]) => {\n const [finishSrc, fwdSrc] = sources;\n const finishRe = new RegExp(finishSrc, 'i');\n const fwdRe = new RegExp(fwdSrc, 'i');\n const ctrls = Array.from(document.querySelectorAll('button, a, [role=\"button\"], input[type=\"submit\"]')) as HTMLElement[];\n const visible = ctrls.filter((c) => {\n const s = getComputedStyle(c);\n const r = c.getBoundingClientRect();\n return s.display !== 'none' && s.visibility !== 'hidden' && r.width > 0 && r.height > 0;\n });\n const forwardish = visible.filter((c) => finishRe.test(c.textContent || '') || fwdRe.test(c.textContent || ''));\n if (forwardish.length === 0) return false;\n const anyEnabled = forwardish.some((c) => !(c as HTMLButtonElement).disabled && c.getAttribute('aria-disabled') !== 'true');\n return !anyEnabled; // a forward/finish control exists but all are disabled\n }, [FINISH_RE.source, FORWARD_RE.source])\n .catch(() => false);\n\n if (deadEnd) {\n findings.push({\n ruleId: 'flow/dead-end',\n issueClass: 7,\n title: 'Multi-step flow dead-ends (no enabled way forward)',\n severity: 'high',\n confidence: 'likely',\n steps: [`Navigate to ${ctx.route}`, 'Advance past the first step', 'Fill the step inputs', 'The only forward/finish control stays disabled, so the flow cannot be completed'],\n suggestedFix: 'Enable the forward/finish control when the step is valid, or provide another way to complete the flow.',\n dedupeKey: 'dead-end',\n });\n }\n\n // Go back and check the earlier field survived.\n const back = ctx.page.locator('button:visible, a:visible, [role=\"button\"]').filter({ hasText: BACK_RE }).first();\n if ((await back.count().catch(() => 0)) > 0) {\n await back.click({ timeout: 2000 }).catch(() => {});\n } else {\n await ctx.page.goBack({ timeout: 3000 }).catch(() => {});\n }\n await ctx.page.waitForTimeout(700);\n\n const restored = await ctx.page.locator(trackSel).inputValue({ timeout: 1500 }).catch(() => null);\n if (restored !== null && restored !== SENTINEL) {\n findings.push({\n ruleId: 'flow/state-loss',\n issueClass: 6,\n title: 'Form state lost on back navigation',\n severity: 'high',\n confidence: 'likely',\n steps: [`Navigate to ${ctx.route}`, `Enter a value in the first field`, 'Advance to the next step', 'Go back', 'The value was wiped (state not preserved)'],\n suggestedFix: 'Preserve multi-step form state (keep it in state/store or restore it on back) so users do not lose their progress.',\n dedupeKey: 'state-loss',\n });\n }\n }\n\n // ── Unclear / buried primary action (class 12) ────────────────────────\n await ctx.freshNavigate().catch(() => {});\n const buried = await ctx.page\n .evaluate((actionSrc) => {\n const re = new RegExp(actionSrc, 'i');\n // Anchors only: tiny buttons are a tap-target concern (handled separately);\n // this detector is about navigation CTAs that are visually buried.\n const els = Array.from(document.querySelectorAll('a[href]')) as HTMLElement[];\n const out: Array<{ text: string; reason: string }> = [];\n for (const el of els) {\n const text = (el.textContent || '').trim();\n if (!text || !re.test(text)) continue;\n const s = getComputedStyle(el);\n const r = el.getBoundingClientRect();\n const fontSize = parseFloat(s.fontSize) || 16;\n const opacity = parseFloat(s.opacity);\n const offscreen = r.right < 0 || r.bottom < 0 || r.left > (window.innerWidth || 1280);\n let reason = '';\n if (fontSize < 12) reason = `tiny font (${fontSize}px)`;\n else if (!Number.isNaN(opacity) && opacity < 0.4) reason = `near-transparent (opacity ${opacity})`;\n else if (r.width > 0 && r.width < 8) reason = 'almost zero width';\n else if (offscreen) reason = 'positioned off-screen';\n if (reason) out.push({ text: text.slice(0, 40), reason });\n }\n return out;\n }, PRIMARY_ACTION_RE.source)\n .catch(() => []);\n\n for (const b of buried) {\n findings.push({\n ruleId: 'flow/unclear-action',\n issueClass: 12,\n title: `Primary action \"${b.text}\" is hard to find`,\n severity: 'low',\n confidence: 'uncertain',\n steps: [`Navigate to ${ctx.route}`, `The primary action \"${b.text}\" is rendered with low prominence: ${b.reason}`],\n suggestedFix: 'Give the primary action clear visual prominence (readable size, sufficient contrast, obvious placement).',\n dedupeKey: `unclear:${b.text}`,\n });\n }\n\n return findings;\n};\n","export { runCrawl } from './engine.js';\nexport { renderHtmlReport } from './report-html.js';\nexport type { CrawlOptions } from './engine.js';\nexport type {\n QaFinding,\n RawFinding,\n CrawlReport,\n CrawlStats,\n Reproduction,\n Confidence,\n Severity,\n} from './types.js';\n\nimport { relative, isAbsolute } from 'node:path';\nimport type { CrawlReport, QaFinding } from './types.js';\nimport { SEV_ORDER, fixFirst, verdictLine } from './verdict.js';\n\nexport { fixFirst, severityCounts, verdictLine, isFailing } from './verdict.js';\n\nexport interface ReportTextOptions {\n /** Show `uncertain` findings too. */\n all?: boolean;\n /**\n * The real exit decision, when the caller has it (`--fail-on` plus the\n * assert budget). Left out, the verdict fails on a critical or high finding.\n */\n failed?: boolean;\n /** Screenshot paths under this folder print relative to it. */\n cwd?: string;\n}\n\n/** A path under `cwd` prints relative, so a report line stays short. */\nfunction displayPath(path: string, cwd: string | undefined): string {\n if (!cwd || !isAbsolute(path)) return path;\n const rel = relative(cwd, path);\n return rel && !rel.startsWith('..') && !isAbsolute(rel) ? rel : path;\n}\n\n/**\n * Render a CrawlReport for the terminal. The order is fixed: the verdict, the\n * findings to fix first, then every finding by severity. By default\n * `uncertain` findings are hidden (shown with `all: true`).\n */\nexport function formatReportText(report: CrawlReport, opts: ReportTextOptions = {}): string {\n const shown = report.findings.filter((f) => opts.all || f.confidence !== 'uncertain');\n const hidden = report.findings.length - shown.length;\n const { pagesVisited, linksChecked, durationMs } = report.stats;\n const lines: string[] = [];\n\n lines.push('');\n lines.push(` VERDICT ${verdictLine(shown, opts.failed)}`);\n lines.push(\n ` Walked ${pagesVisited} page${pagesVisited === 1 ? '' : 's'}, checked ${linksChecked} link${linksChecked === 1 ? '' : 's'}, in ${(durationMs / 1000).toFixed(1)}s.` +\n (hidden > 0 ? ` ${hidden} low-confidence finding${hidden === 1 ? '' : 's'} hidden, show with --all.` : ''),\n );\n lines.push('');\n\n if (shown.length === 0) return lines.join('\\n');\n\n const first = fixFirst(shown);\n lines.push(first.length === shown.length ? ' Fix these:' : ' Fix these first:');\n first.forEach((f, i) => {\n lines.push(` ${i + 1}. ${f.title} on ${f.reproduction.route} [${f.severity}]`);\n });\n lines.push('');\n lines.push(' Every finding, with the steps that reproduce it:');\n lines.push('');\n\n const bySev = new Map<string, QaFinding[]>();\n for (const f of shown) {\n const arr = bySev.get(f.severity) ?? [];\n arr.push(f);\n bySev.set(f.severity, arr);\n }\n\n for (const sev of SEV_ORDER) {\n const arr = bySev.get(sev);\n if (!arr || arr.length === 0) continue;\n lines.push(` ${sev.toUpperCase()} (${arr.length})`);\n for (const f of arr) {\n lines.push(` • [${f.confidence}] ${f.title}`);\n lines.push(` ${f.reproduction.route} (${f.ruleId})`);\n for (const s of f.reproduction.steps) lines.push(` - ${s}`);\n lines.push(` fix: ${f.suggestedFix}`);\n if (f.needsOutOfBandVerification) lines.push(` note: needs out-of-band verification (e.g. confirm the email/job actually completed)`);\n if (f.reproduction.screenshotPath) lines.push(` shot: ${displayPath(f.reproduction.screenshotPath, opts.cwd)}`);\n lines.push('');\n }\n }\n return lines.join('\\n');\n}\n"],"mappings":";;;;;;;;;;;;AACA,SAAS,YAAY;AACrB,SAAS,aAAa;;;ACIf,SAAS,aAAa,KAAqB;AAChD,MAAI;AACF,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,UAAI,EAAE,aAAa,eAAgB,OAAM,KAAK,eAAe,YAAY,EAAE,aAAa,gBAAgB,KAAK,GAAG,CAAC,EAAE;AACnH,YAAM,KAAK,EAAE;AAAA,IACf;AAAA,EACF;AACA,SAAO,MAAM,KAAK,IAAI;AACxB;","names":[]}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { mkdir, writeFile, readFile } from "fs/promises";
|
|
3
3
|
import { join } from "path";
|
|
4
4
|
async function generateTests(analysis, options) {
|
|
5
|
-
const { resolveProvider } = await import("./provider-
|
|
5
|
+
const { resolveProvider } = await import("./provider-MMQ6EIBV.js");
|
|
6
6
|
const resolution = await resolveProvider(options.ai);
|
|
7
7
|
const provider = resolution.provider;
|
|
8
8
|
if (!provider) {
|
|
@@ -77,4 +77,4 @@ function routePathToFileName(routePath) {
|
|
|
77
77
|
export {
|
|
78
78
|
generateTests
|
|
79
79
|
};
|
|
80
|
-
//# sourceMappingURL=chunk-
|
|
80
|
+
//# sourceMappingURL=chunk-7BLJCICM.js.map
|
|
@@ -1,5 +1,36 @@
|
|
|
1
|
-
// src/crawl/
|
|
1
|
+
// src/crawl/verdict.ts
|
|
2
2
|
var SEV_ORDER = ["critical", "high", "medium", "low", "info"];
|
|
3
|
+
var CONF_ORDER = ["confirmed", "likely", "uncertain"];
|
|
4
|
+
var DEFAULT_FAIL_ON = ["critical", "high"];
|
|
5
|
+
function rank(order, value) {
|
|
6
|
+
const i = order.indexOf(value);
|
|
7
|
+
return i === -1 ? order.length : i;
|
|
8
|
+
}
|
|
9
|
+
function severityCounts(findings) {
|
|
10
|
+
const parts = [];
|
|
11
|
+
for (const sev of SEV_ORDER) {
|
|
12
|
+
const n = findings.filter((f) => f.severity === sev).length;
|
|
13
|
+
if (n > 0) parts.push(`${n} ${sev}`);
|
|
14
|
+
}
|
|
15
|
+
return parts.join(", ");
|
|
16
|
+
}
|
|
17
|
+
function fixFirst(findings, limit = 3) {
|
|
18
|
+
return [...findings].sort(
|
|
19
|
+
(a, b) => rank(SEV_ORDER, a.severity) - rank(SEV_ORDER, b.severity) || rank(CONF_ORDER, a.confidence) - rank(CONF_ORDER, b.confidence)
|
|
20
|
+
).slice(0, limit);
|
|
21
|
+
}
|
|
22
|
+
function isFailing(findings, failed) {
|
|
23
|
+
return failed ?? findings.some((f) => DEFAULT_FAIL_ON.includes(f.severity));
|
|
24
|
+
}
|
|
25
|
+
function verdictLine(findings, failed) {
|
|
26
|
+
const n = findings.length;
|
|
27
|
+
if (n === 0) return "PASS: no findings";
|
|
28
|
+
const word = isFailing(findings, failed) ? "FAIL" : "PASS";
|
|
29
|
+
const gate = word === "PASS" ? ", none at a failing severity" : "";
|
|
30
|
+
return `${word}: ${n} finding${n === 1 ? "" : "s"} (${severityCounts(findings)})${gate}`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// src/crawl/report-html.ts
|
|
3
34
|
var SEV_COLOR = {
|
|
4
35
|
critical: "#ff5c7a",
|
|
5
36
|
high: "#ff8a5c",
|
|
@@ -39,7 +70,10 @@ function renderHtmlReport(report, opts = {}) {
|
|
|
39
70
|
const shown = report.findings;
|
|
40
71
|
const counts = SEV_ORDER.map((s) => ({ s, n: report.summary.bySeverity[s] ?? 0 })).filter((x) => x.n > 0);
|
|
41
72
|
const chips = counts.map((c) => `<span class="chip" style="--c:${SEV_COLOR[c.s]}">${c.n} ${c.s}</span>`).join("");
|
|
42
|
-
const cards = shown.length ? SEV_ORDER.flatMap((sev) => shown.filter((f) => f.severity === sev)).map(findingCard).join("") :
|
|
73
|
+
const cards = shown.length ? SEV_ORDER.flatMap((sev) => shown.filter((f) => f.severity === sev)).map(findingCard).join("") : "";
|
|
74
|
+
const failing = isFailing(shown);
|
|
75
|
+
const first = fixFirst(shown);
|
|
76
|
+
const firstList = first.length ? `<section class="first"><h2>${first.length === shown.length ? "Fix these" : "Fix these first"}</h2><ol>${first.map((f) => `<li>${esc(f.title)} on <span class="route">${esc(f.reproduction.route)}</span> <span class="rule">${esc(f.severity)}</span></li>`).join("")}</ol></section>` : "";
|
|
43
77
|
return `<!doctype html>
|
|
44
78
|
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
45
79
|
<title>${esc(title)}</title>
|
|
@@ -67,12 +101,16 @@ function renderHtmlReport(report, opts = {}) {
|
|
|
67
101
|
.fix{margin:10px 0 0;color:#cbd5e1;font-size:14px}
|
|
68
102
|
.oob{color:#fbbf24;font-size:13px;margin:8px 0 0}
|
|
69
103
|
.shot{display:inline-block;margin-top:8px;color:#34d399;font-size:13px}
|
|
70
|
-
.
|
|
104
|
+
.verdict{font-size:18px;font-weight:700;margin:0 0 14px;padding:12px 16px;border-radius:10px;color:var(--c);border:1px solid color-mix(in srgb,var(--c) 50%,transparent);background:color-mix(in srgb,var(--c) 10%,transparent)}
|
|
105
|
+
.first{margin:0 0 28px} .first h2{font-size:15px;margin:0 0 6px;color:#aab2c5} .first ol{margin:0}
|
|
106
|
+
.all{font-size:15px;margin:0 0 4px;color:#aab2c5}
|
|
71
107
|
footer{margin-top:40px;color:#5b6275;font-size:12px;text-align:center}
|
|
72
108
|
</style></head>
|
|
73
109
|
<body><div class="wrap">
|
|
74
110
|
<h1>${esc(title)}</h1>
|
|
75
111
|
<p class="sub">Autonomous QA scan of <code>${esc(report.stats.startUrl)}</code></p>
|
|
112
|
+
<p class="verdict" style="--c:${failing ? "#ff5c7a" : "#34d399"}">${esc(verdictLine(shown))}</p>
|
|
113
|
+
${firstList}
|
|
76
114
|
<div>
|
|
77
115
|
<span class="stat">${report.stats.pagesVisited} pages</span>
|
|
78
116
|
<span class="stat">${report.stats.linksChecked} links checked</span>
|
|
@@ -80,12 +118,17 @@ function renderHtmlReport(report, opts = {}) {
|
|
|
80
118
|
<span class="stat">${(report.stats.durationMs / 1e3).toFixed(1)}s</span>
|
|
81
119
|
</div>
|
|
82
120
|
<div class="chips">${chips || '<span class="chip" style="--c:#34d399">0 issues</span>'}</div>
|
|
83
|
-
${cards}
|
|
121
|
+
${cards ? `<h2 class="all">Every finding, with the steps that reproduce it</h2>${cards}` : ""}
|
|
84
122
|
<footer>Generated by sniff \xB7 ${esc(report.runAt)}</footer>
|
|
85
123
|
</div></body></html>`;
|
|
86
124
|
}
|
|
87
125
|
|
|
88
126
|
export {
|
|
127
|
+
SEV_ORDER,
|
|
128
|
+
severityCounts,
|
|
129
|
+
fixFirst,
|
|
130
|
+
isFailing,
|
|
131
|
+
verdictLine,
|
|
89
132
|
renderHtmlReport
|
|
90
133
|
};
|
|
91
|
-
//# sourceMappingURL=chunk-
|
|
134
|
+
//# sourceMappingURL=chunk-T72SLMTY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/crawl/verdict.ts","../src/crawl/report-html.ts"],"sourcesContent":["import type { QaFinding } from './types.js';\n\nexport const SEV_ORDER = ['critical', 'high', 'medium', 'low', 'info'] as const;\nconst CONF_ORDER = ['confirmed', 'likely', 'uncertain'] as const;\n\n/** Severities that fail a run when the caller does not say otherwise. */\nconst DEFAULT_FAIL_ON: readonly string[] = ['critical', 'high'];\n\nfunction rank<T extends string>(order: readonly T[], value: string): number {\n const i = order.indexOf(value as T);\n return i === -1 ? order.length : i;\n}\n\n/** \"1 critical, 13 high, 9 medium\", in severity order, zero counts left out. */\nexport function severityCounts(findings: readonly QaFinding[]): string {\n const parts: string[] = [];\n for (const sev of SEV_ORDER) {\n const n = findings.filter((f) => f.severity === sev).length;\n if (n > 0) parts.push(`${n} ${sev}`);\n }\n return parts.join(', ');\n}\n\n/**\n * The findings to fix first: worst severity first, then the most certain.\n * The sort is stable, so equal findings keep the order the walk found them in.\n */\nexport function fixFirst(findings: readonly QaFinding[], limit = 3): QaFinding[] {\n return [...findings]\n .sort(\n (a, b) =>\n rank(SEV_ORDER, a.severity) - rank(SEV_ORDER, b.severity) ||\n rank(CONF_ORDER, a.confidence) - rank(CONF_ORDER, b.confidence),\n )\n .slice(0, limit);\n}\n\n/**\n * Whether the shown findings fail the run. Callers that know the real exit\n * decision (the `--fail-on` gate plus the assert budget) pass it in; everyone\n * else gets the default gate, critical or high.\n */\nexport function isFailing(findings: readonly QaFinding[], failed?: boolean): boolean {\n return failed ?? findings.some((f) => DEFAULT_FAIL_ON.includes(f.severity));\n}\n\n/** One line a reader can act on: \"FAIL: 26 findings (1 critical, 13 high)\". */\nexport function verdictLine(findings: readonly QaFinding[], failed?: boolean): string {\n const n = findings.length;\n if (n === 0) return 'PASS: no findings';\n const word = isFailing(findings, failed) ? 'FAIL' : 'PASS';\n const gate = word === 'PASS' ? ', none at a failing severity' : '';\n return `${word}: ${n} finding${n === 1 ? '' : 's'} (${severityCounts(findings)})${gate}`;\n}\n","import type { CrawlReport, QaFinding } from './types.js';\nimport { SEV_ORDER, fixFirst, isFailing, verdictLine } from './verdict.js';\n\nconst SEV_COLOR: Record<string, string> = {\n critical: '#ff5c7a', high: '#ff8a5c', medium: '#ffd166', low: '#6ee7b7', info: '#8ab4ff',\n};\nconst CONF_COLOR: Record<string, string> = {\n confirmed: '#34d399', likely: '#fbbf24', uncertain: '#94a3b8',\n};\n\nfunction esc(s: string): string {\n return String(s).replace(/[&<>\"']/g, (c) =>\n ({ '&': '&', '<': '<', '>': '>', '\"': '"', \"'\": ''' }[c] as string));\n}\n\nfunction findingCard(f: QaFinding): string {\n const steps = f.reproduction.steps.map((s) => `<li>${esc(s)}</li>`).join('');\n const net = (f.reproduction.networkExcerpt ?? []).map((s) => `<code>${esc(s)}</code>`).join('');\n const con = (f.reproduction.consoleExcerpt ?? []).map((s) => `<code>${esc(s)}</code>`).join('');\n const shot = f.reproduction.screenshotPath\n ? `<a class=\"shot\" href=\"${esc(f.reproduction.screenshotPath)}\">screenshot</a>` : '';\n const oob = f.needsOutOfBandVerification\n ? `<p class=\"oob\">⚠ Needs out-of-band verification (confirm the email/async job actually completed).</p>` : '';\n return `\n <article class=\"card\" data-sev=\"${f.severity}\">\n <header>\n <span class=\"sev\" style=\"--c:${SEV_COLOR[f.severity] ?? '#888'}\">${f.severity}</span>\n <span class=\"conf\" style=\"--c:${CONF_COLOR[f.confidence] ?? '#888'}\">${f.confidence}</span>\n <h3>${esc(f.title)}</h3>\n </header>\n <div class=\"meta\"><span class=\"route\">${esc(f.reproduction.route)}</span><span class=\"rule\">${esc(f.ruleId)}</span></div>\n <details open><summary>Reproduction</summary><ol>${steps}</ol>${con ? `<div class=\"ex\">${con}</div>` : ''}${net ? `<div class=\"ex\">${net}</div>` : ''}${shot}</details>\n <p class=\"fix\"><strong>Fix:</strong> ${esc(f.suggestedFix)}</p>\n ${oob}\n </article>`;\n}\n\n/** Render a self-contained (no external refs/scripts) dark-mode HTML report. */\nexport function renderHtmlReport(report: CrawlReport, opts: { title?: string } = {}): string {\n const title = opts.title ?? 'sniff report';\n const shown = report.findings;\n const counts = SEV_ORDER.map((s) => ({ s, n: report.summary.bySeverity[s] ?? 0 })).filter((x) => x.n > 0);\n const chips = counts.map((c) => `<span class=\"chip\" style=\"--c:${SEV_COLOR[c.s]}\">${c.n} ${c.s}</span>`).join('');\n const cards = shown.length\n ? SEV_ORDER.flatMap((sev) => shown.filter((f) => f.severity === sev)).map(findingCard).join('')\n : '';\n // Verdict first, then what to fix first, then the detail.\n const failing = isFailing(shown);\n const first = fixFirst(shown);\n const firstList = first.length\n ? `<section class=\"first\"><h2>${first.length === shown.length ? 'Fix these' : 'Fix these first'}</h2><ol>${first\n .map((f) => `<li>${esc(f.title)} on <span class=\"route\">${esc(f.reproduction.route)}</span> <span class=\"rule\">${esc(f.severity)}</span></li>`)\n .join('')}</ol></section>`\n : '';\n\n return `<!doctype html>\n<html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>${esc(title)}</title>\n<style>\n :root{color-scheme:dark}\n *{box-sizing:border-box}\n body{margin:0;background:#0b0e14;color:#e6e9ef;font:15px/1.55 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}\n .wrap{max-width:860px;margin:0 auto;padding:32px 20px 80px}\n h1{font-size:24px;margin:0 0 4px} .sub{color:#8b93a7;margin:0 0 20px}\n .chips{display:flex;gap:8px;flex-wrap:wrap;margin:16px 0 28px}\n .chip{font-size:13px;padding:4px 10px;border-radius:999px;border:1px solid color-mix(in srgb,var(--c) 50%,transparent);color:var(--c);background:color-mix(in srgb,var(--c) 12%,transparent)}\n .stat{display:inline-block;margin-right:18px;color:#8b93a7;font-size:13px}\n .card{background:#11151f;border:1px solid #1e2533;border-radius:12px;padding:16px 18px;margin:14px 0}\n .card header{display:flex;align-items:center;gap:8px;flex-wrap:wrap}\n .card h3{font-size:16px;margin:6px 0 0;flex-basis:100%}\n .sev,.conf{font-size:11px;text-transform:uppercase;letter-spacing:.04em;font-weight:700;padding:3px 8px;border-radius:6px;color:var(--c);border:1px solid color-mix(in srgb,var(--c) 45%,transparent)}\n .meta{display:flex;gap:12px;margin:8px 0;font-size:13px}\n .route{color:#8ab4ff;font-family:ui-monospace,Menlo,monospace}\n .rule{color:#6b7280;font-family:ui-monospace,Menlo,monospace}\n details{margin:8px 0;border-top:1px solid #1e2533;padding-top:8px}\n summary{cursor:pointer;color:#aab2c5;font-size:13px}\n ol{margin:8px 0;padding-left:20px;color:#c7cdda}\n .ex{margin:6px 0;display:flex;flex-direction:column;gap:4px}\n code{background:#0b0e14;border:1px solid #1e2533;border-radius:6px;padding:4px 8px;font-size:12px;color:#9fb6e0;overflow-x:auto}\n .fix{margin:10px 0 0;color:#cbd5e1;font-size:14px}\n .oob{color:#fbbf24;font-size:13px;margin:8px 0 0}\n .shot{display:inline-block;margin-top:8px;color:#34d399;font-size:13px}\n .verdict{font-size:18px;font-weight:700;margin:0 0 14px;padding:12px 16px;border-radius:10px;color:var(--c);border:1px solid color-mix(in srgb,var(--c) 50%,transparent);background:color-mix(in srgb,var(--c) 10%,transparent)}\n .first{margin:0 0 28px} .first h2{font-size:15px;margin:0 0 6px;color:#aab2c5} .first ol{margin:0}\n .all{font-size:15px;margin:0 0 4px;color:#aab2c5}\n footer{margin-top:40px;color:#5b6275;font-size:12px;text-align:center}\n</style></head>\n<body><div class=\"wrap\">\n <h1>${esc(title)}</h1>\n <p class=\"sub\">Autonomous QA scan of <code>${esc(report.stats.startUrl)}</code></p>\n <p class=\"verdict\" style=\"--c:${failing ? '#ff5c7a' : '#34d399'}\">${esc(verdictLine(shown))}</p>\n ${firstList}\n <div>\n <span class=\"stat\">${report.stats.pagesVisited} pages</span>\n <span class=\"stat\">${report.stats.linksChecked} links checked</span>\n <span class=\"stat\">${shown.length} findings</span>\n <span class=\"stat\">${(report.stats.durationMs / 1000).toFixed(1)}s</span>\n </div>\n <div class=\"chips\">${chips || '<span class=\"chip\" style=\"--c:#34d399\">0 issues</span>'}</div>\n ${cards ? `<h2 class=\"all\">Every finding, with the steps that reproduce it</h2>${cards}` : ''}\n <footer>Generated by sniff · ${esc(report.runAt)}</footer>\n</div></body></html>`;\n}\n"],"mappings":";AAEO,IAAM,YAAY,CAAC,YAAY,QAAQ,UAAU,OAAO,MAAM;AACrE,IAAM,aAAa,CAAC,aAAa,UAAU,WAAW;AAGtD,IAAM,kBAAqC,CAAC,YAAY,MAAM;AAE9D,SAAS,KAAuB,OAAqB,OAAuB;AAC1E,QAAM,IAAI,MAAM,QAAQ,KAAU;AAClC,SAAO,MAAM,KAAK,MAAM,SAAS;AACnC;AAGO,SAAS,eAAe,UAAwC;AACrE,QAAM,QAAkB,CAAC;AACzB,aAAW,OAAO,WAAW;AAC3B,UAAM,IAAI,SAAS,OAAO,CAAC,MAAM,EAAE,aAAa,GAAG,EAAE;AACrD,QAAI,IAAI,EAAG,OAAM,KAAK,GAAG,CAAC,IAAI,GAAG,EAAE;AAAA,EACrC;AACA,SAAO,MAAM,KAAK,IAAI;AACxB;AAMO,SAAS,SAAS,UAAgC,QAAQ,GAAgB;AAC/E,SAAO,CAAC,GAAG,QAAQ,EAChB;AAAA,IACC,CAAC,GAAG,MACF,KAAK,WAAW,EAAE,QAAQ,IAAI,KAAK,WA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AY,MAAM,SACpB,8BAA8B,MAAM,WAAW,MAAM,SAAS,cAAc,iBAAiB,YAAY,MACtG,IAAI,CAAC,MAAM,OAAO,IAAI,EAAE,KAAK,CAAC,2BAA2B,IAAI,EAAE,aAAa,KAAK,CAAC,8BAA8B,IAAI,EAAE,QAAQ,CAAC,cAAc,EAC7I,KAAK,EAAE,CAAC,oBACX;AAEJ,SAAO;AAAA;AAAA,SAEA,IAAI,KAAK,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,QA+BX,IAAI,KAAK,CAAC;AAAA,+CAC6B,IAAI,OAAO,MAAM,QAAQ,CAAC;AAAA,kCACvC,UAAU,YAAY,SAAS,KAAK,IAAI,YAAY,KAAK,CAAC,CAAC;AAAA,IACzF,SAAS;AAAA;AAAA,yBAEY,OAAO,MAAM,YAAY;AAAA,yBACzB,OAAO,MAAM,YAAY;AAAA,yBACzB,MAAM,MAAM;AAAA,0BACX,OAAO,MAAM,aAAa,KAAM,QAAQ,CAAC,CAAC;AAAA;AAAA,uBAE7C,SAAS,wDAAwD;AAAA,IACpF,QAAQ,uEAAuE,KAAK,KAAK,EAAE;AAAA,oCAC9D,IAAI,OAAO,KAAK,CAAC;AAAA;AAElD;","names":[]}
|
|
@@ -9,7 +9,7 @@ var ClaudeCodeProvider = class {
|
|
|
9
9
|
this.command = command;
|
|
10
10
|
}
|
|
11
11
|
async generateTests(context) {
|
|
12
|
-
const { buildSystemPrompt, buildUserPrompt } = await import("./prompt-builder-
|
|
12
|
+
const { buildSystemPrompt, buildUserPrompt } = await import("./prompt-builder-JT3GQBYP.js");
|
|
13
13
|
const { parseGeneratedTest } = await import("./response-parser-PUGNWF7S.js");
|
|
14
14
|
const systemPrompt = buildSystemPrompt();
|
|
15
15
|
const userPrompt = buildUserPrompt(context);
|
|
@@ -43,4 +43,4 @@ var ClaudeCodeProvider = class {
|
|
|
43
43
|
export {
|
|
44
44
|
ClaudeCodeProvider
|
|
45
45
|
};
|
|
46
|
-
//# sourceMappingURL=claude-code-
|
|
46
|
+
//# sourceMappingURL=claude-code-GJPWO6DN.js.map
|
package/dist/{claude-exploration-provider-QJH6IPYU.js → claude-exploration-provider-XOVJPJ23.js}
RENAMED
|
@@ -25,7 +25,7 @@ Respond with ONLY a JSON object matching this shape:
|
|
|
25
25
|
{
|
|
26
26
|
"action": "click" | "fill" | "navigate" | "scroll" | "done",
|
|
27
27
|
"selector": "CSS selector for click/fill targets",
|
|
28
|
-
"value": "value to fill for fill actions
|
|
28
|
+
"value": "value to fill for fill actions; use edge-case data like XSS payloads, SQL injection, Unicode, boundary values",
|
|
29
29
|
"url": "URL for navigate actions",
|
|
30
30
|
"reasoning": "why you chose this action"
|
|
31
31
|
}
|
|
@@ -123,4 +123,4 @@ Priorities:
|
|
|
123
123
|
export {
|
|
124
124
|
ClaudeExplorationProvider
|
|
125
125
|
};
|
|
126
|
-
//# sourceMappingURL=claude-exploration-provider-
|
|
126
|
+
//# sourceMappingURL=claude-exploration-provider-XOVJPJ23.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/exploration/claude-exploration-provider.ts"],"sourcesContent":["import { execFile as execFileCb } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport type { ExplorationProvider } from '../ai/types.js';\nimport type { PageState, ExplorationActionLog, ExplorationDecision } from './types.js';\nimport { selectPayload } from './edge-cases.js';\n\nconst execFile = promisify(execFileCb);\n\nconst VALID_ACTIONS = new Set(['click', 'fill', 'navigate', 'scroll', 'done']);\n\n/**\n * Claude Code CLI-based ExplorationProvider.\n * Falls back to a deterministic heuristic if the CLI is unavailable.\n */\nexport class ClaudeExplorationProvider implements ExplorationProvider {\n async decideNextAction(\n pageState: PageState,\n history: ExplorationActionLog[],\n ): Promise<ExplorationDecision> {\n try {\n return await this.callClaude(pageState, history);\n } catch (err) {\n // Fallback on ENOENT (CLI not installed) or any other error\n if (\n err instanceof Error &&\n 'code' in err &&\n (err as NodeJS.ErrnoException).code === 'ENOENT'\n ) {\n return this.deterministicFallback(pageState, history);\n }\n // On any other error (timeout, parse failure, etc.), also fall back\n return this.deterministicFallback(pageState, history);\n }\n }\n\n private async callClaude(\n pageState: PageState,\n history: ExplorationActionLog[],\n ): Promise<ExplorationDecision> {\n const systemPrompt = `You are a chaos monkey exploring a web application to find bugs.\nYou will be given the current page state (URL, title, interactive elements, form fields) and recent action history.\nRespond with ONLY a JSON object matching this shape:\n{\n \"action\": \"click\" | \"fill\" | \"navigate\" | \"scroll\" | \"done\",\n \"selector\": \"CSS selector for click/fill targets\",\n \"value\": \"value to fill for fill actions; use edge-case data like XSS payloads, SQL injection, Unicode, boundary values\",\n \"url\": \"URL for navigate actions\",\n \"reasoning\": \"why you chose this action\"\n}\n\nPriorities:\n1. Fill form fields with hostile/edge-case values (XSS, SQLi, Unicode, boundary)\n2. Click submit buttons to trigger form validation\n3. Click buttons and interactive elements not yet visited\n4. Navigate to unvisited links\n5. Return {\"action\":\"done\",\"reasoning\":\"...\"} when all elements have been tested`;\n\n const recentHistory = history.slice(-5).map((h) => ({\n step: h.step,\n action: h.action,\n selector: h.target.selector,\n url: h.url,\n }));\n\n const userPrompt = JSON.stringify({\n currentPage: {\n url: pageState.url,\n title: pageState.title,\n interactiveElements: pageState.interactiveElements.slice(0, 20),\n formFields: pageState.formFields.slice(0, 15),\n },\n recentHistory,\n });\n\n const { stdout } = await execFile('claude', [\n '--print',\n '--output-format', 'json',\n '--system-prompt', systemPrompt,\n userPrompt,\n ], {\n timeout: 30_000,\n maxBuffer: 1024 * 1024,\n });\n\n // Parse Claude Code JSON envelope: {\"type\":\"result\",\"subtype\":\"success\",\"result\":\"...\"}\n const envelope = JSON.parse(stdout);\n const rawContent = envelope.result ?? stdout;\n\n // Extract JSON from the response (may contain markdown fences)\n const jsonStr = typeof rawContent === 'string'\n ? rawContent.replace(/```json?\\n?/g, '').replace(/```/g, '').trim()\n : JSON.stringify(rawContent);\n\n const decision = JSON.parse(jsonStr) as ExplorationDecision;\n\n // Validate decision shape (T-04-05: reject unknown action types)\n if (!decision.action || !VALID_ACTIONS.has(decision.action)) {\n return { action: 'done', reasoning: 'Invalid action type in AI response' };\n }\n\n if (!decision.reasoning) {\n decision.reasoning = 'AI provided no reasoning';\n }\n\n return decision;\n }\n\n /**\n * Deterministic fallback when Claude Code CLI is unavailable.\n * Strategy: fill first unfilled form field -> click first unvisited button -> navigate first unvisited link -> done.\n */\n private deterministicFallback(\n pageState: PageState,\n history: ExplorationActionLog[],\n ): ExplorationDecision {\n const stepIndex = history.length;\n const visitedSelectors = new Set(history.map((h) => h.target.selector));\n\n // 1. Fill first unfilled form field\n for (const field of pageState.formFields) {\n if (!visitedSelectors.has(field.selector)) {\n const { value } = selectPayload(field.type, stepIndex);\n return {\n action: 'fill',\n selector: field.selector,\n value,\n reasoning: `Deterministic fallback: filling form field \"${field.name}\" (${field.type}) with edge-case payload`,\n };\n }\n }\n\n // 2. Click first unvisited button/submit\n const buttons = pageState.interactiveElements.filter(\n (el) => el.tag === 'button' || el.type === 'submit',\n );\n for (const btn of buttons) {\n if (!visitedSelectors.has(btn.selector)) {\n return {\n action: 'click',\n selector: btn.selector,\n reasoning: `Deterministic fallback: clicking unvisited button \"${btn.text}\"`,\n };\n }\n }\n\n // 3. Navigate to first unvisited link\n const links = pageState.interactiveElements.filter((el) => el.tag === 'a');\n for (const link of links) {\n if (!visitedSelectors.has(link.selector)) {\n return {\n action: 'click',\n selector: link.selector,\n reasoning: `Deterministic fallback: clicking unvisited link \"${link.text}\"`,\n };\n }\n }\n\n // 4. Done — all elements visited\n return {\n action: 'done',\n reasoning: 'Deterministic fallback: all visible elements have been visited',\n };\n }\n}\n"],"mappings":";;;;;AAAA,SAAS,YAAY,kBAAkB;AACvC,SAAS,iBAAiB;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W,QAAQ,OAAO;AACxB,UAAI,CAAC,iBAAiB,IAAI,KAAK,QAAQ,GAAG;AACxC,eAAO;AAAA,UACL,QAAQ;AAAA,UACR,UAAU,KAAK;AAAA,UACf,WAAW,oDAAoD,KAAK,IAAI;AAAA,QAC1E;AAAA,MACF;AAAA,IACF;AAGA,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,WAAW;AAAA,IACb;AAAA,EACF;AACF;","names":[]}
|
package/dist/cli/index.js
CHANGED
|
@@ -14,11 +14,26 @@ if (process.argv.includes("--mcp")) {
|
|
|
14
14
|
await startMcpServer(caps);
|
|
15
15
|
} else {
|
|
16
16
|
const { Command } = await import("commander");
|
|
17
|
-
const { ensurePlaywrightBrowsers } = await import("../ensure-browsers-
|
|
17
|
+
const { ensurePlaywrightBrowsers } = await import("../ensure-browsers-5NAQQMEC.js");
|
|
18
18
|
const { getVersion } = await import("../version-FLE7ZHDX.js");
|
|
19
19
|
const program = new Command();
|
|
20
|
-
program.name("sniff").description(
|
|
21
|
-
|
|
20
|
+
program.name("sniff").description(
|
|
21
|
+
"Walks your running app in a real browser and reports what is broken, with the steps that reproduce it.\nWith no app running it reads your source instead. No API key, no account."
|
|
22
|
+
).version(getVersion()).addHelpText("after", `
|
|
23
|
+
Start here:
|
|
24
|
+
$ sniff --url http://localhost:3000 walk a running app and print the report
|
|
25
|
+
$ sniff --url http://localhost:3000 --report
|
|
26
|
+
also write sniff-reports/sniff-report.html
|
|
27
|
+
$ sniff scan read the source only, no browser
|
|
28
|
+
$ sniff doctor check Node, the browser and the dev server
|
|
29
|
+
|
|
30
|
+
Exit codes:
|
|
31
|
+
0 no finding reached the --fail-on severities (default: critical,high)
|
|
32
|
+
1 a finding reached them, an assert budget was breached, or sniff could not run
|
|
33
|
+
|
|
34
|
+
A walk clicks buttons and submits forms. Point it at a dev or staging app.
|
|
35
|
+
Docs: https://github.com/Aboudjem/sniff#readme`);
|
|
36
|
+
program.argument("[target]", "Project directory to scan (default: current directory)").option("--url <url>", "URL of the running app to walk (default: the dev server found on a common port)").option("--ci", "CI mode: headless and non-interactive").option("--no-browser", "Force source-only scan even if URL is configured").option("--explore", "Run optional AI exploration after browser checks", false).option("--no-explore", "Skip AI exploration (kept for compatibility; exploration is off by default)").option("--max-steps <n>", "Cap AI exploration steps when --explore is used (default: 50)").option("--headed", "Show the browser window (alias for --no-headless)").option("--no-headless", "Show the browser window").option("--format <formats>", "Report formats: html, json, junit (comma-separated)").option("--fail-on <severities>", "Exit non-zero on these severities (default: critical,high)", "critical,high").option("--json", "Output results as JSON").option("--report", "Write a self-contained HTML report to sniff-reports/sniff-report.html").option("--all", "Show low-confidence findings too (hidden by default)").option("--max-pages <n>", "Max pages to crawl during the flow-walk (default: 25)").option("--no-mobile", "Skip the mobile (375px) responsive pass").option("--storage-state <path>", "Playwright storage-state JSON, so the walk runs as a logged-in user. Cookie and token values from it are redacted from every written report.").option("--track-flakes", "Track test flakiness across runs").option("--discover", "Run autonomous E2E discovery (scenarios + edge cases)").option("--max-scenarios <n>", "Cap total scenarios for discovery (default: 50)").option("--max-variants-per-scenario <n>", "Cap edge variants per scenario (default: 3)").option("--max-variants-per-run <n>", "Cap edge variants per run (default: 40)").option("--realism <profile>", "Discovery realism: robot, careful-user, casual-user, frustrated-user, power-user").option("--seed <n>", "Replay a specific random seed").option("--only <filter>", "Filter discovery scenarios by id substring or app type").option("--app-type <types>", "Filter discovery app types (comma-separated); only generates scenarios for these types if the classifier matches them").option("--force-app-type <type>", "Force a single app type, bypassing the classifier entirely (use when classification returns blank)").option("--no-llm", "Disable LLM-backed discovery polish").option("--non-interactive", "Non-interactive mode for discovery (skips prompts and countdown)").option("--regenerate", "Regenerate sniff-scenarios/ before running (prompts on hand-edits)").option("--regenerate-only", "Regenerate sniff-scenarios/ and exit without running").option("--force-regenerate", "Regenerate sniff-scenarios/ and overwrite hand-edits").option("--verbose", "Print classification breakdown (top 3 guesses + matched signals per dimension)").option("--dry-run", "Discover: generate scenarios + classify without running browser or writing reports").action(async (target, options) => {
|
|
22
37
|
const rootDir = target ? (await import("path")).resolve(target) : process.cwd();
|
|
23
38
|
if (options.discover || options.regenerate || options.regenerateOnly || options.forceRegenerate || options.dryRun) {
|
|
24
39
|
const { loadConfig: loadConfig2 } = await import("../loader-Z2DUGG5Z.js");
|
|
@@ -53,7 +68,7 @@ if (process.argv.includes("--mcp")) {
|
|
|
53
68
|
});
|
|
54
69
|
process.exit(result.exitCode);
|
|
55
70
|
}
|
|
56
|
-
const { unifiedCommand } = await import("../unified-
|
|
71
|
+
const { unifiedCommand } = await import("../unified-OEGLPOGE.js");
|
|
57
72
|
const { loadConfig } = await import("../loader-Z2DUGG5Z.js");
|
|
58
73
|
const config = await loadConfig(rootDir);
|
|
59
74
|
let url = options.url ?? config.browser?.baseUrl;
|
|
@@ -74,7 +89,7 @@ if (process.argv.includes("--mcp")) {
|
|
|
74
89
|
const pc = (await import("picocolors")).default;
|
|
75
90
|
if (wantsBrowser) {
|
|
76
91
|
await ensurePlaywrightBrowsers(config.browser?.projects);
|
|
77
|
-
const { crawlCommand } = await import("../crawl-command-
|
|
92
|
+
const { crawlCommand } = await import("../crawl-command-JHZN4GK7.js");
|
|
78
93
|
const storageState = options.storageState ? (await import("path")).resolve(options.storageState) : config.browser?.storageState;
|
|
79
94
|
const code = await crawlCommand({
|
|
80
95
|
rootDir,
|
|
@@ -122,11 +137,11 @@ if (process.argv.includes("--mcp")) {
|
|
|
122
137
|
});
|
|
123
138
|
program.command("scan").description("Source-only scan (no browser): placeholder/TODO/console.log/dead links/etc.").argument("[target]", "Project directory (default: current directory)").option("--json", "Output results as JSON").option("--fail-on <severities>", "Exit non-zero on these severities (default: critical,high)", "critical,high").action(async (target, options) => {
|
|
124
139
|
const rootDir = target ? (await import("path")).resolve(target) : process.cwd();
|
|
125
|
-
const { unifiedCommand } = await import("../unified-
|
|
140
|
+
const { unifiedCommand } = await import("../unified-OEGLPOGE.js");
|
|
126
141
|
await unifiedCommand({ rootDir, explore: false, json: options.json, failOn: options.failOn });
|
|
127
142
|
});
|
|
128
143
|
program.command("report").description("View last scan results").option("--json", "Output as JSON").option("--format <formats>", "Regenerate report in specified formats (comma-separated: html,json,junit)").option("--output <dir>", "Output directory for regenerated reports").action(async (options) => {
|
|
129
|
-
const { reportCommand } = await import("../report-
|
|
144
|
+
const { reportCommand } = await import("../report-XK2MCX2N.js");
|
|
130
145
|
await reportCommand(options);
|
|
131
146
|
});
|
|
132
147
|
program.command("update-baselines").description("Update visual regression baselines").option("--yes", "Skip confirmation prompt").action(async (options) => {
|
|
@@ -186,14 +201,13 @@ ${pc.bold("sniff doctor")}
|
|
|
186
201
|
const nodeMajor = parseInt(nodeVersion.slice(1), 10);
|
|
187
202
|
const nodeOk = nodeMajor >= 22;
|
|
188
203
|
console.log(` ${nodeOk ? pc.green("OK") : pc.red("!! ")} Node.js ${nodeVersion} ${nodeOk ? "" : "(need 22+)"}`);
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
204
|
+
const { checkPlaywrightBrowsers } = await import("../ensure-browsers-5NAQQMEC.js");
|
|
205
|
+
const browser = await checkPlaywrightBrowsers(["chromium"]);
|
|
206
|
+
if (browser.status === "installed") {
|
|
207
|
+
console.log(` ${pc.green("OK")} Chromium downloaded`);
|
|
208
|
+
} else {
|
|
209
|
+
console.log(` ${pc.yellow("--")} Chromium not downloaded yet (the first walk downloads it, about 165 MB, or run: npx playwright install chromium)`);
|
|
195
210
|
}
|
|
196
|
-
console.log(` ${playwrightOk ? pc.green("OK") : pc.yellow("--")} Playwright ${playwrightOk ? "installed" : "not installed (auto-installs on first browser scan)"}`);
|
|
197
211
|
const { loadConfig } = await import("../loader-Z2DUGG5Z.js");
|
|
198
212
|
let hasConfig = false;
|
|
199
213
|
try {
|