diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..485d1f2 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,54 @@ +name: Tests and package checks + +on: + pull_request: + push: + branches: ['**'] + workflow_call: + +permissions: + contents: read + +jobs: + test: + runs-on: ${{ matrix.os }} + timeout-minutes: 15 + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-latest + python: '3.8' + extras: test + - os: ubuntu-latest + python: '3.12' + extras: 'test,full' + - os: ubuntu-latest + python: '3.14' + extras: 'test,full' + - os: windows-latest + python: '3.14' + extras: test + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v6 + with: + python-version: ${{ matrix.python }} + cache: pip + - name: Install package and test dependencies + run: | + python -m pip install --upgrade pip + python -m pip install ".[${{ matrix.extras }}]" "setuptools>=61" build wheel twine + - name: Run deterministic regression and integration tests + run: python -m pytest + - name: Build and validate distributions + run: | + python -m build --no-isolation + python -m twine check dist/* + - name: Smoke test the installed wheel outside the source import path + run: | + python -m pip install --no-deps --force-reinstall dist/*.whl + python -I tests/wheel_smoke.py diff --git a/.github/workflows/tfq0seo-publish.yml b/.github/workflows/tfq0seo-publish.yml index 1889f2f..5858ff4 100644 --- a/.github/workflows/tfq0seo-publish.yml +++ b/.github/workflows/tfq0seo-publish.yml @@ -1,36 +1,71 @@ name: Publish to PyPI on: - release: - types: [created] push: tags: - - 'v*' # Trigger on version tags + - 'v*' + +permissions: + contents: read jobs: + checks: + if: github.event.deleted == false + uses: ./.github/workflows/tests.yml + build: + needs: checks + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v6 + with: + python-version: '3.14' + - name: Install build tools + run: python -m pip install build twine + - name: Build package + run: python -m build + - name: Validate release version and distributions + env: + RELEASE_TAG: ${{ github.ref_name }} + run: | + python -m twine check dist/* + python - <<'PY' + import os + from email.parser import BytesParser + from pathlib import Path + from zipfile import ZipFile + + wheel, = Path('dist').glob('*.whl') + with ZipFile(wheel) as archive: + metadata_path, = ( + name for name in archive.namelist() + if name.endswith('.dist-info/METADATA') + ) + metadata = BytesParser().parsebytes(archive.read(metadata_path)) + expected = 'v' + metadata['Version'] + if os.environ['RELEASE_TAG'] != expected: + raise SystemExit('Release tag must match package version: ' + expected) + PY + - name: Store validated distributions + uses: actions/upload-artifact@v7 + with: + name: python-distributions + path: dist/ + if-no-files-found: error + deploy: + needs: build runs-on: ubuntu-latest environment: name: pypi url: https://pypi.org/p/tfq0seo permissions: - id-token: write # IMPORTANT: mandatory for trusted publishing - + id-token: write steps: - - uses: actions/checkout@v4 - - - name: Set up Python - uses: actions/setup-python@v4 - with: - python-version: '3.x' - - - name: Install dependencies - run: | - python -m pip install --upgrade pip - pip install build twine - - - name: Build package - run: python -m build - - - name: Publish package distributions to PyPI - uses: pypa/gh-action-pypi-publish@release/v1 + - name: Download validated distributions + uses: actions/download-artifact@v8 + with: + name: python-distributions + path: dist/ + - name: Publish distributions to PyPI + uses: pypa/gh-action-pypi-publish@release/v1 diff --git a/.gitignore b/.gitignore index f4d054a..0d889b8 100644 --- a/.gitignore +++ b/.gitignore @@ -144,6 +144,8 @@ cython_debug/ # Reports reports/ *.html +# Bundled report templates are source files, not generated reports. +!tfq0seo/templates/*.html *.csv *.xlsx *.json diff --git a/MANIFEST.in b/MANIFEST.in index b670bce..74ac621 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -4,6 +4,8 @@ include requirements.txt include pyproject.toml recursive-include tfq0seo/templates *.html recursive-include tfq0seo *.py +recursive-include tests *.py +recursive-include docs *.md *.benchmark global-exclude __pycache__ global-exclude *.py[co] global-exclude .DS_Store diff --git a/README.md b/README.md index cf70e29..a354347 100644 --- a/README.md +++ b/README.md @@ -1,46 +1,421 @@ -# TFQ0SEO - SEO Analysis Tool +# TFQ0SEO -[![PyPI version](https://img.shields.io/pypi/v/tfq0seo.svg)](https://pypi.org/project/tfq0seo/) -[![License](https://img.shields.io/pypi/l/tfq0seo.svg)](https://github.com/tfq0/tfq0seo/blob/main/LICENSE) -[![Python Versions](https://img.shields.io/pypi/pyversions/tfq0seo.svg)](https://pypi.org/project/tfq0seo/) -[![Downloads](https://img.shields.io/pypi/dm/tfq0seo.svg)](https://pypi.org/project/tfq0seo/) +TFQ0SEO is a Python library and CLI for crawling HTML and producing static SEO +reports. It checks metadata, content, technical markup, resource hints, and +links. Reports distinguish failed analyses from unavailable measurements. -A high-performance SEO analysis tool that generates professional reports. +## Installation -## Features +Python 3.8 or newer is supported. Install from this checkout to use these changes: -- **Comprehensive analysis** -- **Handles 500+ pages** -- **Beautiful reports** -- **Concurrent processing** -- **Simple CLI** +```bash +python -m pip install . +# Optional lxml parser, Excel export, and pandas compatibility dependency: +python -m pip install ".[full]" +``` -## Installation +`python -m pip install tfq0seo` installs the published release, which may differ +from this checkout. JSON, HTML, and CSV work with the base installation. XLSX +requires `openpyxl`, included in the `full` extra. + +## CLI ```bash -pip install tfq0seo +# Single page; JSON goes to stdout when --output is omitted. +tfq0seo analyze https://example.com --format json + +# Site crawl with explicit scope limits. +tfq0seo crawl https://example.com --depth 5 --max-pages 500 --concurrent 10 --format html --output report.html + +# UTF-8 file: one URL per line; blank lines and # comments are ignored. +tfq0seo batch urls.txt --format json --output batch.json + +# XML sitemap or sitemap index. +tfq0seo sitemap https://example.com/sitemap.xml --max-pages 500 --format json --output sitemap.json + +# Convert an existing page or site report. +tfq0seo export --input batch.json --format xlsx --output batch.xlsx ``` -## Quick Start +All commands accept `--config config.yaml` (JSON is also supported). Use +`tfq0seo COMMAND --help` for command options. Incomplete analyses and request +failures return a nonzero exit code; an explicitly requested report is written +first so that failures remain inspectable. -### Single Page Analysis -```bash -tfq0seo analyze https://example.com +Crawling follows eligible HTTP(S) links in the starting site's hostname/port +scope, including standard HTTP-to-HTTPS transitions. Redirect destinations are +checked against that scope. Explicit `allowed_domains` can expand it. +Robots rules and TLS verification are enabled by default. Queries are retained, +fragments do not create separate crawl targets, and excluded patterns still +apply. Page, depth, response-size, request, and site crawl-time limits bound work. +Reaching a limit is reported; it is not proof that the entire site was analyzed. + +## Configuration + +CLI precedence is: built-in/profile defaults, configuration file, `TFQ0SEO_` +environment variables, then explicitly supplied command options. An omitted +CLI option does not overwrite a configuration-file value. + +```yaml +profile: standard +max_memory_mb: 1024 +crawler: + max_concurrent: 10 + max_connections_per_host: 5 + max_pages: 500 + max_depth: 5 + timeout: 30 + connect_timeout: 10 + read_timeout: 30 + max_crawl_time: 3600 + max_page_size: 10485760 + respect_robots_txt: true + verify_ssl: true + delay_between_requests: 0.2 + max_retries: 3 + use_sitemap: true +analysis: + analysis_mode: standard + enabled_analyzers: [seo, content, technical, performance, links] + max_analysis_threads: 4 + check_broken_links: true + check_internal_links: true + check_external_links: false + check_content_uniqueness: true + target_keywords: [] +export: + primary_format: html + output_directory: ./reports + html_template: enhanced + filename_pattern: "{domain}_{timestamp}_{format}" +``` + +For example, `TFQ0SEO_CRAWLER_MAX_PAGES=100` overrides the page budget. +`TFQ0SEO_ANALYSIS_ENABLED_ANALYZERS=seo,technical` selects those analyzers. +Lists also accept JSON arrays; mappings use JSON objects. Booleans accept +`true`/`false`, `yes`/`no`, and `1`/`0`. String settings remain strings. + +Profiles are `quick`, `standard`, `deep`, `enterprise`, `dev`, and `custom`. +`quick` selects SEO and technical analysis with a smaller crawl budget. `deep` +increases crawl limits and bypasses the analysis cache. `enterprise` changes +concurrency and crawl budgets; it does not enable a separate service or browser. +Explicit values override profile defaults. + +In Python, `apply_profile()` replaces values controlled by the selected preset. +Use `merge({'profile': ...})` to change preset defaults while retaining explicit +overrides. Applying `custom` only changes the label. + +Other implemented settings include crawler headers/user agent, redirects, +rate limits, retry statuses/backoff, domain/scheme/exclusion filters, sitemap +discovery, proxy, connection pooling, DNS/robots cache TTLs, and bounded analysis +cache size/TTL. Analysis supports weighted category scores and bounded optional +external link checks. `Config.SUPPORTED_FIELDS` lists the active component +settings in [config.py](https://github.com/TFQ0/tfq0seo/blob/main/tfq0seo/core/config.py). + +`max_memory_mb` is a sampled process-RSS guard checked during page-analysis +progress, not a hard allocation limit. Synchronous report assembly can exceed +it; the recorded 2,000-page workload peaked above the default 1,024 MiB value. +Budget memory for the complete report and use an external process limit when +a hard bound is required. See the scale validation results below. + +Unknown keys, invalid types, conflicting aliases, and retired configuration +fields fail validation. Active dataclasses and saved configurations expose +supported settings only. JavaScript execution, HTTP/2 selection, background +monitoring, webhooks, email delivery, PDF export, and `dry_run` remain +unimplemented. Use the explicit `Config.migrate_dict()` migration for older +configuration files; it removes only retired values matching their historical +defaults and rejects unsupported requested behavior. See the +[configuration migration guide](https://github.com/TFQ0/tfq0seo/blob/main/docs/configuration-migration.md) before upgrading. + +## Python API + +```python +import asyncio + +from tfq0seo import SEOAnalyzer +from tfq0seo.core.config import Config +from tfq0seo.exporters.base import ExportManager + + +async def main(): + config = Config.from_dict({"crawler": {"max_pages": 100}}) + analyzer = SEOAnalyzer(config) + pages = [page async for page in analyzer.crawl_site("https://example.com")] + report = analyzer.generate_site_report(pages) + ExportManager(config.export).export(report, "json", "report.json") + + +asyncio.run(main()) +``` + +`analyze_url(url)` returns one page result. `analyze_urls(urls)` is an async +iterator for a batch. `analyze_sitemap(url)` returns a list after discovery and +analysis. `generate_batch_report()` and `generate_site_report()` aggregate page +records. Use the completed report for link health: streamed pages may precede +observations of their linked targets. Reusing an analyzer starts a fresh run +while retaining its bounded analysis cache. + +## Interpreting results + +Results carry `schema_version: "1.0"`; compatible dictionary contracts are +defined in [models.py](https://github.com/TFQ0/tfq0seo/blob/main/tfq0seo/core/models.py). + +- Page `status` is `complete`, `partial`, `error`, or `skipped`. Fetch failures + retain their URL, status, and error. Analyzer failures have an error and a + `null` score. Truncated HTML produces partial coverage. +- `coverage` identifies enabled/completed/failed analyzers and content + completeness. Site `summary` records page outcomes, crawl completeness, + limits, and discovery failures. Successful static analysis does not mean + every linked URL was checked. +- Site `pages.detailed` retains every usable page; `pages.failed` and + `pages.skipped` retain other outcomes. HTML pagination does not truncate the + underlying report. CSV and XLSX include all page outcomes. +- Scores are weighted static-rule heuristics, not search ranking predictions, + validated business KPIs, or an exhaustive accessibility audit. Informational + content heuristics do not lower scores. +- `load_time` and `html_fetch_time` describe observed HTTP HTML retrieval. + Browser load time, Core Web Vitals, TTFB, asset download sizes, and other + unobserved measurements are `null`/not measured. JavaScript is not rendered. +- Broken links require an observed HTTP error. Unvisited targets remain + unchecked. External checks are opt-in and bounded; connection failures are + retained separately from HTTP error evidence. +- JSON-LD checks inspect local syntax/shape. Language/readability checks are + conservative and may be unavailable. They do not validate eligibility for + search-engine features or infer authority and link velocity. + Readability never downloads dictionaries at runtime. If the installed + textstat backend needs unavailable local NLTK `corpora/cmudict` data, estimates + remain `null`, with an explicit unavailable status and missing-resource reason. + Provision the `cmudict` corpus during environment setup if you need those + estimates; see [NLTK's data installation guide](https://www.nltk.org/data.html). + +HTML escapes page-supplied text and restricts clickable URLs to HTTP(S). CSV and +XLSX neutralize formula-like text. The enhanced HTML report uses optional +Chart.js from a CDN for charts; its page table remains usable without it. + +## Site-wide canonical and link analysis + +Completed site reports include `site_analysis`, derived from the supplied page +inventory without additional network requests. Canonical observations include +eligible HTML declarations and HTTP `Link` headers. HTML targets use the +document base; header targets use the response URL. Declarations outside the +HTML head, alternate qualifiers, and other header anchor contexts remain +recorded as ineligible. Malformed headers, missing facts, and incomplete HTML +retain uncertainty. + +The report identifies conflicting targets, canonical chains and cycles, +observed redirects, HTTP errors at declared targets, and observed `noindex` +directives at targets. A self-reference is not a cycle. Unfetched and +unavailable destinations are unverified. Chain records store the immediate +target, terminal, hop count, and cycle identifier; shared cycles are stored +once, avoiding repeated full paths in large reports. + +The internal-link graph retains distinct source/target pairs, nofollow hints, +incoming/outgoing counts, connected groups, and shortest observed link depth. +Redirect aliases resolve to observed final URLs; query strings remain distinct. +Depth starts at the crawl's entry URL, or observed homepages when aggregating a +batch. Without an entry page, depth and reachability remain unavailable. A page +with no observed incoming links is a candidate for investigation, not proof of +an orphan page. Self links do not count as incoming links, and nofollow hints +do not remove edges from this observational graph. + +Site findings have registered `site.*` rule IDs, evidence, references, and zero +penalty. They appear in site issues and recommendations without changing page +scores or rewriting historical page evidence. Page rule coverage remains +separate from graph coverage. HTML includes the complete observations table; +CSV/XLSX page rows include canonical and link metrics; JSON retains the graph +and cycle records. These checks do not determine a search engine's selected +canonical or a page's actual index status. The supporting guidance is +[Google's canonical documentation](https://developers.google.com/search/docs/crawling-indexing/consolidate-duplicate-urls) +and [link guidance](https://developers.google.com/search/docs/crawling-indexing/links-crawlable). + +## Shared facts and result contracts + +Each page analysis extracts one `PageFacts` snapshot before dispatching the five +analyzers. They reuse its metadata, headings, robots directives, document base, +images, scripts, links, and text. Specialized checks remain in their existing +analyzer modules. The snapshot is immutable, and collection access returns +independent values so concurrent analyzers cannot alter one another's evidence. + +The original analyzer call signatures remain supported. Standalone callers can +also share extraction explicitly: + +```python +from bs4 import BeautifulSoup +from tfq0seo.page_facts import extract_page_facts +from tfq0seo.analyzers.seo import analyze_seo +from tfq0seo.analyzers.content import analyze_content + +soup = BeautifulSoup('Example

Example

', 'html.parser') +url = 'https://example.test/' +facts = extract_page_facts(soup, url, headers=None) +seo = analyze_seo(soup, url, facts=facts) +content = analyze_content(soup, url, facts=facts) ``` -### Full Site Crawl +Keep the source document unchanged while using its snapshot. A supplied +snapshot must belong to the same document, URL, and explicit header/bot context. +`headers=None` means unavailable; `{}` means an observed empty header mapping. +Repeated response headers retain every value. Fetch timings can remain `null` +and describe their existing network stages rather than browser measurements. + +Page results include an additive `page_facts` record with extraction version, +provenance, hashes, counts, and shared observations. Its default export omits raw +response-header values, full HTML/text, and script bodies. The extraction +version also participates in cache identity. + +[models.py](https://github.com/TFQ0/tfq0seo/blob/main/tfq0seo/core/models.py) defines fetch, rule, analyzer, page, and site +contracts and re-exports `PageFacts`. Malformed supplied fields raise +`ContractError` with a field path before analysis or export. Invalid analyzer +outputs become explicit analyzer errors with unavailable scores and are not +cached. Rule validation checks evidence, provenance, applicability, and nested +observations before merging or scoring. + +Report validation checks present fields without rewriting historical rule IDs, +scores, or unknown extension fields. New producer envelopes receive stricter +checks. Non-finite numbers and unsupported Python objects are rejected rather +than silently converted to strings; invalid reports are rejected before opening +an output file. JSON schema version `1.0` and existing report layouts remain +supported. Validators are available in +[report_contracts.py](https://github.com/TFQ0/tfq0seo/blob/main/tfq0seo/core/report_contracts.py). + +## Rules, applicability, and scoring + +The rule registry in [rules.py](https://github.com/TFQ0/tfq0seo/blob/main/tfq0seo/rules.py) contains immutable definitions +registered by each analyzer. Every active rule has a stable ID, a category owner, +severity, recommendation, applicability description, supporting reference URLs, +and a review date. The reference supports the observation or guidance; numeric +penalties are TFQ0SEO policy, not weights supplied by search engines. + +Each analyzer returns `rule_results` with structured evidence and explicit +`pass`, `fail`, `informational`, `unknown`, `not_applicable`, or `error` outcomes. +`issues` contains failed checks and informational observations. Unknown and +inapplicable evaluations include a reason and remain visible in rule coverage; +they are never silently counted as passes. Disabling an analyzer does not imply +that its rules passed. A rule execution error makes the page partial and avoids +caching that incomplete analysis. + +Scoring policy **2.0** deducts 15, 7, or 3 points for a failed, applicable, +scored critical, warning, or notice rule. Each rule is deducted once per page, +even when multiple analyzers observe it. Its registered owner receives the +deduction; if that analyzer is unavailable, the first reporting analyzer in the +fixed order `seo, content, technical, performance, links` receives it. Category +scores start at 100 and floor at zero. The overall score uses the configured +category weights, normalized across available categories. Zero weights are +respected. Site scores average the available page scores. + +Page `scoring.deductions` records rule IDs, observers, category attribution, and +penalties. Recommendations use the registry ID rather than matching message +text. Duplicate findings retain all observations, and site issue groups retain +evidence for every affected page. Diagnostic sub-scores inside analyzer data are +not additive components of the overall score. + +Informational, unknown, inapplicable, and errored evaluations incur no penalty. +For example, an observed `noindex` directive is reported without assuming it is +unintentional. Optional social metadata, keyword-density targets, metadata +length heuristics, and unmeasured browser effects are not universal failures. +A high score therefore describes the scored observations and must be read +alongside coverage; it does not establish that unavailable checks passed. + +JSON keeps schema version `1.0` with additive rule fields and records independent +ruleset/scoring versions. Scores from policy 2.0 are not directly comparable to +older reports. Cache identity includes both versions. Reference review dates +record an actual review, not automatic proof that a document is still current. + +When extending an analyzer, register the definition, evaluate it with +`RuleCollector.check`, supply the observed evidence and applicability, and derive +findings/recommendations/scores through the shared helpers. Test positive, +negative, unavailable, and inapplicable cases. Reuse shared IDs for the same +underlying condition and increment the ruleset version when changing rule +behavior; increment the scoring version when changing the deduction policy. + +## Development and verification + ```bash -tfq0seo crawl https://example.com --depth 5 --max-pages 500 --concurrent 20 --format html --output full-report.html +python -m venv .venv +# Activate .venv using your shell's command, then: +python -m pip install -e ".[test,full]" "setuptools>=61" build wheel twine +python -m pytest + +python -m build --no-isolation +python -m twine check dist/* +# Install the generated .whl with --no-deps --force-reinstall, then: +python -I tests/wheel_smoke.py + +# Reproducible offline analysis/report workload; no HTTP requests: +python -m tfq0seo.benchmark --pages 500 --output benchmark.json +# Compare varied fixtures and retain repeated measurements and environment: +python -m tfq0seo.benchmark --suite --pages 500 2000 --repetitions 3 --timeout-seconds 600 --output scale.json ``` -## Analysis Categories +Tests cover analyzers, configuration precedence, crawl scope/robots/retries, +timeouts and cancellation, report completeness, CLI failure handling, export +safety, and a real 500-page crawl against a local HTTP fixture. Tests block +non-loopback socket connections and do not depend on public websites. + +The benchmark measures fixture parsing, static analysis, and aggregation with +the analysis cache disabled. It reports complete/partial/failed/skipped counts, +successful-page throughput, elapsed time, and sampled process RSS. A sampled +maximum can miss short memory peaks. Results depend on the machine and fixture; +they are not browser-performance measurements or a production-site capacity +guarantee. Basic, content-heavy, link-dense, and mixed scenarios retain every +raw measurement, workload/source fingerprints, full effective configuration, +dependency versions, and per-case summaries. See the +[scale validation guide and recorded measurements](https://github.com/TFQ0/tfq0seo/blob/main/docs/scale-validation.md) +for workload definitions, resource limits, and measured results. Network +benchmark functions remain explicit opt-in Python APIs. + +GitHub Actions runs regression tests and distribution checks across Python 3.8, +3.12, and 3.14, with Windows and Linux jobs and base/optional dependencies. The +release workflow requires these checks and a release tag matching `v` plus the +package version before publishing. + +## Publishing to PyPI + +Releases use [PyPI Trusted Publishing](https://docs.pypi.org/trusted-publishers/) +through GitHub Actions. No PyPI API token or password is used by the workflow. +Tests and the package build run without OIDC permission. The separate `deploy` +job downloads the validated distributions and is the only job with +`id-token: write`, which allows it to request a short-lived publishing identity. + +Complete this one-time setup before publishing a release: + +1. In the `TFQ0/tfq0seo` GitHub repository, open **Settings → Environments** + and create or verify the environment named `pypi`. Restrict its deployment + tags to `v*`; optionally require a reviewer if available for the repository. +2. On PyPI, open **Your projects → tfq0seo → Manage → Publishing** and add a + GitHub publisher to the existing project with these exact values: -1. **SEO Analysis** + | PyPI field | Value | + | --- | --- | + | Owner | `TFQ0` | + | Repository name | `tfq0seo` | + | Workflow name | `tfq0seo-publish.yml` | + | Environment name | `pypi` | -2. **Content Quality** + The workflow field is the filename, without `.github/workflows/`, rather + than the display name `Publish to PyPI`. The environment must match the + workflow. See [PyPI's publisher setup guide](https://docs.pypi.org/trusted-publishers/adding-a-publisher/). +3. Commit and push the release workflow and its reusable + `.github/workflows/tests.yml` together with the intended package changes. + Keep the registered workflow filename unchanged. -3. **Technical SEO** +For each release, update `tfq0seo/__init__.py` to a new, unused package version, +commit it, then create and push a tag that is `v` followed by that version +(for example, `v3.0.0`). Pushing a `v*` tag triggers the workflow; no package-name +prefix or GitHub release is required. Branch pushes, other tag names, and tag +deletions do not publish. The version check reads the built wheel's metadata +without installing or hard-coding the package name. Approve the `pypi` +deployment if a reviewer is required. Tests and distribution checks must pass +before the upload starts. -4. **Performance** +After the first successful Trusted Publishing release, revoke the old PyPI +upload token and remove its GitHub Actions secret if it is no longer used by +another workflow. Do not add `username` or `password` inputs to the publishing +action; they would select credential-based authentication instead of OIDC. -5. **Link Analysis** +Local tests cannot exercise GitHub's OIDC exchange with PyPI. The first release +run verifies the registered publisher end to end. If PyPI reports an invalid +publisher, compare the repository owner, repository name, workflow filename, +and environment against the values above before retrying. PyPI does not allow +an uploaded distribution filename to be reused, so retries after a successful +upload require checking what was already published. diff --git a/docs/benchmarks/2026-09-21-python312-2000-basic.benchmark b/docs/benchmarks/2026-09-21-python312-2000-basic.benchmark new file mode 100644 index 0000000..09567f8 --- /dev/null +++ b/docs/benchmarks/2026-09-21-python312-2000-basic.benchmark @@ -0,0 +1,541 @@ +{ + "benchmark_schema_version": 2, + "status": "complete", + "benchmarks": [ + { + "type": "offline", + "fixture_version": 1, + "scenario": "basic", + "requested_pages": 2000, + "network_access": false, + "config": { + "crawler": { + "max_concurrent": 20, + "max_connections_per_host": 5, + "timeout": 30, + "connect_timeout": 10, + "read_timeout": 30, + "user_agent": "tfq0seo/3.0.0 (+https://github.com/TFQ0/tfq0seo)", + "custom_headers": {}, + "follow_redirects": true, + "max_redirects": 10, + "max_pages": 2000, + "max_depth": 5, + "max_page_size": 10485760, + "max_crawl_time": 3600, + "delay_between_requests": 0.0, + "adaptive_delay": true, + "min_delay": 0.0, + "max_delay": 5.0, + "rate_limit_per_second": null, + "respect_robots_txt": true, + "robots_cache_ttl": 86400, + "crawl_delay_factor": 1.0, + "allowed_domains": [], + "allowed_schemes": [ + "http", + "https" + ], + "excluded_patterns": [ + "\\.pdf$", + "\\.zip$", + "\\.exe$", + "\\.dmg$", + "/wp-admin", + "/admin", + "/login", + "\\?.*session", + "\\?.*utm_" + ], + "store_html": false, + "max_retries": 3, + "retry_on_status": [ + 429, + 500, + 502, + 503, + 504 + ], + "retry_backoff_factor": 2.0, + "cache_enabled": false, + "cache_ttl": 3600, + "cache_size_mb": 100, + "use_sitemap": true, + "discover_sitemaps": true, + "use_connection_pooling": true, + "dns_cache_ttl": 300, + "verify_ssl": true, + "proxy": null + }, + "analysis": { + "enabled_analyzers": [ + "seo", + "content", + "technical", + "performance", + "links" + ], + "analysis_mode": "standard", + "parallel_analysis": true, + "max_analysis_threads": 4, + "check_external_links": false, + "check_internal_links": true, + "check_broken_links": true, + "max_external_links_per_page": 100, + "external_link_timeout": 10, + "target_keywords": [], + "check_content_uniqueness": true, + "score_weights": { + "seo": 0.3, + "content": 0.25, + "technical": 0.2, + "performance": 0.15, + "links": 0.1 + } + }, + "export": { + "formats": [ + "html" + ], + "primary_format": "html", + "html_template": "optimized", + "output_directory": "./reports", + "filename_pattern": "{domain}_{timestamp}_{format}" + }, + "profile": "standard", + "version": "3.0.0", + "debug": false, + "continue_on_error": true, + "max_memory_mb": 1024 + }, + "fixture": { + "version": 1, + "generated_pages": 2000, + "html_bytes": 842670, + "dom_elements": 20000, + "href_references": 2000, + "image_elements": 0, + "analyzed_word_count": 34000, + "pages_with_word_count": 2000, + "variants": { + "basic": 2000, + "content-heavy": 0, + "link-dense": 0 + }, + "sha256": "4a920316238e0083f5d2eae7ca894faa843a26de85d1524aa348900e09a22650" + }, + "timeout_seconds": 360.0, + "timed_out": false, + "timeout_scope": "Cooperative checks between pages and after reporting; synchronous work can overrun the deadline.", + "report_completeness": { + "expected_pages": 2000, + "retained_rows": 2000, + "unique_urls": 2000, + "missing_urls": 0, + "unexpected_urls": 0, + "duplicate_rows": 0, + "complete": true + }, + "readability": { + "status_counts": { + "not_requested": 2000 + }, + "missing_resources": [] + }, + "workload": "Fixture generation, HTML parsing, static analysis, site report aggregation and retained-URL verification; no HTTP, browser or export measurement", + "analysis_duration_seconds": 101.17349219997413, + "report_duration_seconds": 64.62061670003459, + "report_pages": 2000, + "report_status": "complete", + "report_summary": { + "total_pages": 2000, + "successful_pages": 2000, + "partial_pages": 0, + "failed_pages": 0, + "skipped_pages": 0, + "analysis_mode": "standard", + "analysis_timestamp": 1789963088.9000018, + "analysis_duration": 0, + "crawl_complete": false, + "limits_reached": [], + "discovery_errors": [], + "scope_note": "Results describe fetched pages; unvisited targets remain unchecked." + }, + "rule_coverage": { + "counts": { + "pass": 72000, + "fail": 0, + "informational": 8000, + "unknown": 4000, + "not_applicable": 52000, + "error": 0 + }, + "assessed": 80000, + "total": 136000, + "ratio": 0.9523809523809523, + "scope": "Counts are unique rule evaluations per page, not a complete site inventory." + }, + "site_analysis": { + "version": "1.0", + "coverage": { + "inventory_pages": 2000, + "pages_with_facts": 2000, + "complete_html_pages": 2000, + "crawl_complete": false, + "note": "A completed crawl still obeys its configured scope. Missing targets and paths remain unverified." + }, + "node_count": 2000, + "edge_count": 2000, + "finding_count": 0 + }, + "status": "complete", + "successful_pages": 2000, + "partial_pages": 0, + "failed_pages": 0, + "skipped_pages": 0, + "observed_results": 2000, + "missing_results": 0, + "pages_analyzed": 2000, + "pages_per_second": 12.035083143516117, + "avg_time_per_page": 0.08309041060000891, + "duration_seconds": 166.18082120001782, + "clock": "perf_counter", + "memory_rss_start_mb": 76.672, + "memory_rss_end_mb": 882.762, + "memory_rss_delta_mb": 806.09, + "memory_sampled_peak_mb": 1496.578, + "memory_sample_count": 2221, + "memory_sampling_interval_seconds": 0.05, + "memory_measurement": "Sampled process RSS; allocations between samples may be missed.", + "memory_used_mb": 806.09, + "errors": [], + "timestamp": "2026-09-21T03:58:18.883772+00:00", + "repetition": 1, + "run_order": 1 + }, + { + "type": "offline", + "fixture_version": 1, + "scenario": "basic", + "requested_pages": 2000, + "network_access": false, + "config": { + "crawler": { + "max_concurrent": 20, + "max_connections_per_host": 5, + "timeout": 30, + "connect_timeout": 10, + "read_timeout": 30, + "user_agent": "tfq0seo/3.0.0 (+https://github.com/TFQ0/tfq0seo)", + "custom_headers": {}, + "follow_redirects": true, + "max_redirects": 10, + "max_pages": 2000, + "max_depth": 5, + "max_page_size": 10485760, + "max_crawl_time": 3600, + "delay_between_requests": 0.0, + "adaptive_delay": true, + "min_delay": 0.0, + "max_delay": 5.0, + "rate_limit_per_second": null, + "respect_robots_txt": true, + "robots_cache_ttl": 86400, + "crawl_delay_factor": 1.0, + "allowed_domains": [], + "allowed_schemes": [ + "http", + "https" + ], + "excluded_patterns": [ + "\\.pdf$", + "\\.zip$", + "\\.exe$", + "\\.dmg$", + "/wp-admin", + "/admin", + "/login", + "\\?.*session", + "\\?.*utm_" + ], + "store_html": false, + "max_retries": 3, + "retry_on_status": [ + 429, + 500, + 502, + 503, + 504 + ], + "retry_backoff_factor": 2.0, + "cache_enabled": false, + "cache_ttl": 3600, + "cache_size_mb": 100, + "use_sitemap": true, + "discover_sitemaps": true, + "use_connection_pooling": true, + "dns_cache_ttl": 300, + "verify_ssl": true, + "proxy": null + }, + "analysis": { + "enabled_analyzers": [ + "seo", + "content", + "technical", + "performance", + "links" + ], + "analysis_mode": "standard", + "parallel_analysis": true, + "max_analysis_threads": 4, + "check_external_links": false, + "check_internal_links": true, + "check_broken_links": true, + "max_external_links_per_page": 100, + "external_link_timeout": 10, + "target_keywords": [], + "check_content_uniqueness": true, + "score_weights": { + "seo": 0.3, + "content": 0.25, + "technical": 0.2, + "performance": 0.15, + "links": 0.1 + } + }, + "export": { + "formats": [ + "html" + ], + "primary_format": "html", + "html_template": "optimized", + "output_directory": "./reports", + "filename_pattern": "{domain}_{timestamp}_{format}" + }, + "profile": "standard", + "version": "3.0.0", + "debug": false, + "continue_on_error": true, + "max_memory_mb": 1024 + }, + "fixture": { + "version": 1, + "generated_pages": 2000, + "html_bytes": 842670, + "dom_elements": 20000, + "href_references": 2000, + "image_elements": 0, + "analyzed_word_count": 34000, + "pages_with_word_count": 2000, + "variants": { + "basic": 2000, + "content-heavy": 0, + "link-dense": 0 + }, + "sha256": "4a920316238e0083f5d2eae7ca894faa843a26de85d1524aa348900e09a22650" + }, + "timeout_seconds": 360.0, + "timed_out": false, + "timeout_scope": "Cooperative checks between pages and after reporting; synchronous work can overrun the deadline.", + "report_completeness": { + "expected_pages": 2000, + "retained_rows": 2000, + "unique_urls": 2000, + "missing_urls": 0, + "unexpected_urls": 0, + "duplicate_rows": 0, + "complete": true + }, + "readability": { + "status_counts": { + "not_requested": 2000 + }, + "missing_resources": [] + }, + "workload": "Fixture generation, HTML parsing, static analysis, site report aggregation and retained-URL verification; no HTTP, browser or export measurement", + "analysis_duration_seconds": 100.86997210001573, + "report_duration_seconds": 63.24567219999153, + "report_pages": 2000, + "report_status": "complete", + "report_summary": { + "total_pages": 2000, + "successful_pages": 2000, + "partial_pages": 0, + "failed_pages": 0, + "skipped_pages": 0, + "analysis_mode": "standard", + "analysis_timestamp": 1789963253.6594498, + "analysis_duration": 0, + "crawl_complete": false, + "limits_reached": [], + "discovery_errors": [], + "scope_note": "Results describe fetched pages; unvisited targets remain unchecked." + }, + "rule_coverage": { + "counts": { + "pass": 72000, + "fail": 0, + "informational": 8000, + "unknown": 4000, + "not_applicable": 52000, + "error": 0 + }, + "assessed": 80000, + "total": 136000, + "ratio": 0.9523809523809523, + "scope": "Counts are unique rule evaluations per page, not a complete site inventory." + }, + "site_analysis": { + "version": "1.0", + "coverage": { + "inventory_pages": 2000, + "pages_with_facts": 2000, + "complete_html_pages": 2000, + "crawl_complete": false, + "note": "A completed crawl still obeys its configured scope. Missing targets and paths remain unverified." + }, + "node_count": 2000, + "edge_count": 2000, + "finding_count": 0 + }, + "status": "complete", + "successful_pages": 2000, + "partial_pages": 0, + "failed_pages": 0, + "skipped_pages": 0, + "observed_results": 2000, + "missing_results": 0, + "pages_analyzed": 2000, + "pages_per_second": 12.158286938222352, + "avg_time_per_page": 0.0822484289999993, + "duration_seconds": 164.4968579999986, + "clock": "perf_counter", + "memory_rss_start_mb": 355.57, + "memory_rss_end_mb": 925.75, + "memory_rss_delta_mb": 570.18, + "memory_sampled_peak_mb": 1496.406, + "memory_sample_count": 2235, + "memory_sampling_interval_seconds": 0.05, + "memory_measurement": "Sampled process RSS; allocations between samples may be missed.", + "memory_used_mb": 570.18, + "errors": [], + "timestamp": "2026-09-21T04:01:03.765129+00:00", + "repetition": 2, + "run_order": 2 + } + ], + "summaries": [ + { + "scenario": "basic", + "requested_pages": 2000, + "runs": 2, + "complete_runs": 2, + "partial_runs": 0, + "failed_runs": 0, + "metrics_scope": "Only complete runs; inspect raw outcomes for excluded failed or partial runs.", + "metrics": { + "duration_seconds": { + "median": 165.3388396000082, + "min": 164.4968579999986, + "max": 166.18082120001782 + }, + "analysis_duration_seconds": { + "median": 101.02173214999493, + "min": 100.86997210001573, + "max": 101.17349219997413 + }, + "report_duration_seconds": { + "median": 63.93314445001306, + "min": 63.24567219999153, + "max": 64.62061670003459 + }, + "pages_per_second": { + "median": 12.096685040869234, + "min": 12.035083143516117, + "max": 12.158286938222352 + }, + "memory_rss_delta_mb": { + "median": 688.135, + "min": 570.18, + "max": 806.09 + }, + "memory_sampled_peak_mb": { + "median": 1496.492, + "min": 1496.406, + "max": 1496.578 + } + } + } + ], + "system_info": { + "os": { + "system": "Windows", + "release": "11", + "version": "10.0.26200" + }, + "architecture": "AMD64", + "cpu_model": "AMD Ryzen 7 7735HS with Radeon Graphics", + "cpu_count": 16, + "physical_cpu_count": 8, + "memory_total_gb": 63.21, + "python_version": "3.12.14 (main, Aug 25 2026, 14:01:42) [MSC v.1944 64 bit (AMD64)]", + "python_implementation": "CPython", + "package_version": "3.0.0", + "installed_distribution_version": "3.0.0", + "schema_version": "1.0", + "ruleset_version": "2026.09.21", + "scoring_version": "2.0", + "facts_version": "1.1", + "direct_dependencies": { + "aiohttp": "3.14.3", + "beautifulsoup4": "4.15.0", + "click": "8.5.0", + "jinja2": "3.1.6", + "rich": "15.0.0", + "textstat": "0.7.13", + "validators": "0.35.0", + "pyyaml": "6.0.3", + "python-dateutil": "2.9.0.post0", + "urllib3": "2.7.0", + "psutil": "7.2.2" + }, + "optional_dependencies": { + "lxml": "6.1.3", + "openpyxl": "3.1.5", + "pandas": "3.0.5" + }, + "readability_dependencies": { + "nltk": "3.10.3", + "pyphen": "0.18.1", + "cmudict": null + }, + "source_fingerprint": { + "algorithm": "sha256", + "scope": "package Python source paths and bytes", + "file_count": 23, + "digest": "077a203b8b1c65de3022f4001a48cc6a1897e89624e9e7e8f967d20f525f4893" + }, + "timestamp": "2026-09-21T03:55:32.697657+00:00" + }, + "source_unchanged_during_suite": true, + "errors": [], + "suite": { + "scenarios": [ + "basic" + ], + "page_counts": [ + 2000 + ], + "repetitions": 2, + "timeout_seconds": 360.0, + "order": "Page counts, then scenarios, then repetitions, in supplied order.", + "isolation": "Same process; fresh analyzer per run, disabled page cache; library caches and allocator state may remain warm." + }, + "execution_guard": { + "dns_attempts": 0, + "external_connection_attempts": 0, + "network_policy": "DNS and non-loopback TCP connects blocked; loopback allowed for asyncio internals.", + "parent_hard_timeout_seconds": 1200 + } +} diff --git a/docs/benchmarks/2026-09-21-python312-2000-mixed.benchmark b/docs/benchmarks/2026-09-21-python312-2000-mixed.benchmark new file mode 100644 index 0000000..e4d81b9 --- /dev/null +++ b/docs/benchmarks/2026-09-21-python312-2000-mixed.benchmark @@ -0,0 +1,547 @@ +{ + "benchmark_schema_version": 2, + "status": "complete", + "benchmarks": [ + { + "type": "offline", + "fixture_version": 1, + "scenario": "mixed", + "requested_pages": 2000, + "network_access": false, + "config": { + "crawler": { + "max_concurrent": 20, + "max_connections_per_host": 5, + "timeout": 30, + "connect_timeout": 10, + "read_timeout": 30, + "user_agent": "tfq0seo/3.0.0 (+https://github.com/TFQ0/tfq0seo)", + "custom_headers": {}, + "follow_redirects": true, + "max_redirects": 10, + "max_pages": 2000, + "max_depth": 5, + "max_page_size": 10485760, + "max_crawl_time": 3600, + "delay_between_requests": 0.0, + "adaptive_delay": true, + "min_delay": 0.0, + "max_delay": 5.0, + "rate_limit_per_second": null, + "respect_robots_txt": true, + "robots_cache_ttl": 86400, + "crawl_delay_factor": 1.0, + "allowed_domains": [], + "allowed_schemes": [ + "http", + "https" + ], + "excluded_patterns": [ + "\\.pdf$", + "\\.zip$", + "\\.exe$", + "\\.dmg$", + "/wp-admin", + "/admin", + "/login", + "\\?.*session", + "\\?.*utm_" + ], + "store_html": false, + "max_retries": 3, + "retry_on_status": [ + 429, + 500, + 502, + 503, + 504 + ], + "retry_backoff_factor": 2.0, + "cache_enabled": false, + "cache_ttl": 3600, + "cache_size_mb": 100, + "use_sitemap": true, + "discover_sitemaps": true, + "use_connection_pooling": true, + "dns_cache_ttl": 300, + "verify_ssl": true, + "proxy": null + }, + "analysis": { + "enabled_analyzers": [ + "seo", + "content", + "technical", + "performance", + "links" + ], + "analysis_mode": "standard", + "parallel_analysis": true, + "max_analysis_threads": 4, + "check_external_links": false, + "check_internal_links": true, + "check_broken_links": true, + "max_external_links_per_page": 100, + "external_link_timeout": 10, + "target_keywords": [], + "check_content_uniqueness": true, + "score_weights": { + "seo": 0.3, + "content": 0.25, + "technical": 0.2, + "performance": 0.15, + "links": 0.1 + } + }, + "export": { + "formats": [ + "html" + ], + "primary_format": "html", + "html_template": "optimized", + "output_directory": "./reports", + "filename_pattern": "{domain}_{timestamp}_{format}" + }, + "profile": "standard", + "version": "3.0.0", + "debug": false, + "continue_on_error": true, + "max_memory_mb": 1024 + }, + "fixture": { + "version": 1, + "generated_pages": 2000, + "html_bytes": 8158500, + "dom_elements": 143352, + "href_references": 27308, + "image_elements": 5336, + "analyzed_word_count": 898986, + "pages_with_word_count": 2000, + "variants": { + "basic": 667, + "content-heavy": 667, + "link-dense": 666 + }, + "sha256": "028909e0dea50dfb82979acf9129d3cdb5b1b46026423fdc7ce3867cbb88839f" + }, + "timeout_seconds": 360.0, + "timed_out": false, + "timeout_scope": "Cooperative checks between pages and after reporting; synchronous work can overrun the deadline.", + "report_completeness": { + "expected_pages": 2000, + "retained_rows": 2000, + "unique_urls": 2000, + "missing_urls": 0, + "unexpected_urls": 0, + "duplicate_rows": 0, + "complete": true + }, + "readability": { + "status_counts": { + "not_requested": 667, + "unavailable": 1333 + }, + "missing_resources": [ + "nltk:corpora/cmudict" + ] + }, + "workload": "Fixture generation, HTML parsing, static analysis, site report aggregation and retained-URL verification; no HTTP, browser or export measurement", + "analysis_duration_seconds": 132.48825890000444, + "report_duration_seconds": 70.79365659999894, + "report_pages": 2000, + "report_status": "complete", + "report_summary": { + "total_pages": 2000, + "successful_pages": 2000, + "partial_pages": 0, + "failed_pages": 0, + "skipped_pages": 0, + "analysis_mode": "standard", + "analysis_timestamp": 1789963457.3870037, + "analysis_duration": 0, + "crawl_complete": false, + "limits_reached": [], + "discovery_errors": [], + "scope_note": "Results describe fetched pages; unvisited targets remain unchecked." + }, + "rule_coverage": { + "counts": { + "pass": 77294, + "fail": 0, + "informational": 9373, + "unknown": 5333, + "not_applicable": 44000, + "error": 0 + }, + "assessed": 86667, + "total": 136000, + "ratio": 0.9420326086956522, + "scope": "Counts are unique rule evaluations per page, not a complete site inventory." + }, + "site_analysis": { + "version": "1.0", + "coverage": { + "inventory_pages": 2000, + "pages_with_facts": 2000, + "complete_html_pages": 2000, + "crawl_complete": false, + "note": "A completed crawl still obeys its configured scope. Missing targets and paths remain unverified." + }, + "node_count": 2000, + "edge_count": 23312, + "finding_count": 0 + }, + "status": "complete", + "successful_pages": 2000, + "partial_pages": 0, + "failed_pages": 0, + "skipped_pages": 0, + "observed_results": 2000, + "missing_results": 0, + "pages_analyzed": 2000, + "pages_per_second": 9.816020526068504, + "avg_time_per_page": 0.10187427759999991, + "duration_seconds": 203.74855519999983, + "clock": "perf_counter", + "memory_rss_start_mb": 76.684, + "memory_rss_end_mb": 1060.215, + "memory_rss_delta_mb": 983.531, + "memory_sampled_peak_mb": 1702.445, + "memory_sample_count": 2798, + "memory_sampling_interval_seconds": 0.05, + "memory_measurement": "Sampled process RSS; allocations between samples may be missed.", + "memory_used_mb": 983.531, + "errors": [], + "timestamp": "2026-09-21T04:04:29.047144+00:00", + "repetition": 1, + "run_order": 1 + }, + { + "type": "offline", + "fixture_version": 1, + "scenario": "mixed", + "requested_pages": 2000, + "network_access": false, + "config": { + "crawler": { + "max_concurrent": 20, + "max_connections_per_host": 5, + "timeout": 30, + "connect_timeout": 10, + "read_timeout": 30, + "user_agent": "tfq0seo/3.0.0 (+https://github.com/TFQ0/tfq0seo)", + "custom_headers": {}, + "follow_redirects": true, + "max_redirects": 10, + "max_pages": 2000, + "max_depth": 5, + "max_page_size": 10485760, + "max_crawl_time": 3600, + "delay_between_requests": 0.0, + "adaptive_delay": true, + "min_delay": 0.0, + "max_delay": 5.0, + "rate_limit_per_second": null, + "respect_robots_txt": true, + "robots_cache_ttl": 86400, + "crawl_delay_factor": 1.0, + "allowed_domains": [], + "allowed_schemes": [ + "http", + "https" + ], + "excluded_patterns": [ + "\\.pdf$", + "\\.zip$", + "\\.exe$", + "\\.dmg$", + "/wp-admin", + "/admin", + "/login", + "\\?.*session", + "\\?.*utm_" + ], + "store_html": false, + "max_retries": 3, + "retry_on_status": [ + 429, + 500, + 502, + 503, + 504 + ], + "retry_backoff_factor": 2.0, + "cache_enabled": false, + "cache_ttl": 3600, + "cache_size_mb": 100, + "use_sitemap": true, + "discover_sitemaps": true, + "use_connection_pooling": true, + "dns_cache_ttl": 300, + "verify_ssl": true, + "proxy": null + }, + "analysis": { + "enabled_analyzers": [ + "seo", + "content", + "technical", + "performance", + "links" + ], + "analysis_mode": "standard", + "parallel_analysis": true, + "max_analysis_threads": 4, + "check_external_links": false, + "check_internal_links": true, + "check_broken_links": true, + "max_external_links_per_page": 100, + "external_link_timeout": 10, + "target_keywords": [], + "check_content_uniqueness": true, + "score_weights": { + "seo": 0.3, + "content": 0.25, + "technical": 0.2, + "performance": 0.15, + "links": 0.1 + } + }, + "export": { + "formats": [ + "html" + ], + "primary_format": "html", + "html_template": "optimized", + "output_directory": "./reports", + "filename_pattern": "{domain}_{timestamp}_{format}" + }, + "profile": "standard", + "version": "3.0.0", + "debug": false, + "continue_on_error": true, + "max_memory_mb": 1024 + }, + "fixture": { + "version": 1, + "generated_pages": 2000, + "html_bytes": 8158500, + "dom_elements": 143352, + "href_references": 27308, + "image_elements": 5336, + "analyzed_word_count": 898986, + "pages_with_word_count": 2000, + "variants": { + "basic": 667, + "content-heavy": 667, + "link-dense": 666 + }, + "sha256": "028909e0dea50dfb82979acf9129d3cdb5b1b46026423fdc7ce3867cbb88839f" + }, + "timeout_seconds": 360.0, + "timed_out": false, + "timeout_scope": "Cooperative checks between pages and after reporting; synchronous work can overrun the deadline.", + "report_completeness": { + "expected_pages": 2000, + "retained_rows": 2000, + "unique_urls": 2000, + "missing_urls": 0, + "unexpected_urls": 0, + "duplicate_rows": 0, + "complete": true + }, + "readability": { + "status_counts": { + "not_requested": 667, + "unavailable": 1333 + }, + "missing_resources": [ + "nltk:corpora/cmudict" + ] + }, + "workload": "Fixture generation, HTML parsing, static analysis, site report aggregation and retained-URL verification; no HTTP, browser or export measurement", + "analysis_duration_seconds": 123.17364019999513, + "report_duration_seconds": 60.40574000001652, + "report_pages": 2000, + "report_status": "complete", + "report_summary": { + "total_pages": 2000, + "successful_pages": 2000, + "partial_pages": 0, + "failed_pages": 0, + "skipped_pages": 0, + "analysis_mode": "standard", + "analysis_timestamp": 1789963644.561493, + "analysis_duration": 0, + "crawl_complete": false, + "limits_reached": [], + "discovery_errors": [], + "scope_note": "Results describe fetched pages; unvisited targets remain unchecked." + }, + "rule_coverage": { + "counts": { + "pass": 77294, + "fail": 0, + "informational": 9373, + "unknown": 5333, + "not_applicable": 44000, + "error": 0 + }, + "assessed": 86667, + "total": 136000, + "ratio": 0.9420326086956522, + "scope": "Counts are unique rule evaluations per page, not a complete site inventory." + }, + "site_analysis": { + "version": "1.0", + "coverage": { + "inventory_pages": 2000, + "pages_with_facts": 2000, + "complete_html_pages": 2000, + "crawl_complete": false, + "note": "A completed crawl still obeys its configured scope. Missing targets and paths remain unverified." + }, + "node_count": 2000, + "edge_count": 23312, + "finding_count": 0 + }, + "status": "complete", + "successful_pages": 2000, + "partial_pages": 0, + "failed_pages": 0, + "skipped_pages": 0, + "observed_results": 2000, + "missing_results": 0, + "pages_analyzed": 2000, + "pages_per_second": 10.867857227312523, + "avg_time_per_page": 0.09201445869999589, + "duration_seconds": 184.02891739999177, + "clock": "perf_counter", + "memory_rss_start_mb": 526.355, + "memory_rss_end_mb": 1005.086, + "memory_rss_delta_mb": 478.73, + "memory_sampled_peak_mb": 1704.723, + "memory_sample_count": 2495, + "memory_sampling_interval_seconds": 0.05, + "memory_measurement": "Sampled process RSS; allocations between samples may be missed.", + "memory_used_mb": 478.73, + "errors": [], + "timestamp": "2026-09-21T04:07:33.590864+00:00", + "repetition": 2, + "run_order": 2 + } + ], + "summaries": [ + { + "scenario": "mixed", + "requested_pages": 2000, + "runs": 2, + "complete_runs": 2, + "partial_runs": 0, + "failed_runs": 0, + "metrics_scope": "Only complete runs; inspect raw outcomes for excluded failed or partial runs.", + "metrics": { + "duration_seconds": { + "median": 193.8887362999958, + "min": 184.02891739999177, + "max": 203.74855519999983 + }, + "analysis_duration_seconds": { + "median": 127.83094954999979, + "min": 123.17364019999513, + "max": 132.48825890000444 + }, + "report_duration_seconds": { + "median": 65.59969830000773, + "min": 60.40574000001652, + "max": 70.79365659999894 + }, + "pages_per_second": { + "median": 10.341938876690513, + "min": 9.816020526068504, + "max": 10.867857227312523 + }, + "memory_rss_delta_mb": { + "median": 731.1305, + "min": 478.73, + "max": 983.531 + }, + "memory_sampled_peak_mb": { + "median": 1703.5839999999998, + "min": 1702.445, + "max": 1704.723 + } + } + } + ], + "system_info": { + "os": { + "system": "Windows", + "release": "11", + "version": "10.0.26200" + }, + "architecture": "AMD64", + "cpu_model": "AMD Ryzen 7 7735HS with Radeon Graphics", + "cpu_count": 16, + "physical_cpu_count": 8, + "memory_total_gb": 63.21, + "python_version": "3.12.14 (main, Aug 25 2026, 14:01:42) [MSC v.1944 64 bit (AMD64)]", + "python_implementation": "CPython", + "package_version": "3.0.0", + "installed_distribution_version": "3.0.0", + "schema_version": "1.0", + "ruleset_version": "2026.09.21", + "scoring_version": "2.0", + "facts_version": "1.1", + "direct_dependencies": { + "aiohttp": "3.14.3", + "beautifulsoup4": "4.15.0", + "click": "8.5.0", + "jinja2": "3.1.6", + "rich": "15.0.0", + "textstat": "0.7.13", + "validators": "0.35.0", + "pyyaml": "6.0.3", + "python-dateutil": "2.9.0.post0", + "urllib3": "2.7.0", + "psutil": "7.2.2" + }, + "optional_dependencies": { + "lxml": "6.1.3", + "openpyxl": "3.1.5", + "pandas": "3.0.5" + }, + "readability_dependencies": { + "nltk": "3.10.3", + "pyphen": "0.18.1", + "cmudict": null + }, + "source_fingerprint": { + "algorithm": "sha256", + "scope": "package Python source paths and bytes", + "file_count": 23, + "digest": "077a203b8b1c65de3022f4001a48cc6a1897e89624e9e7e8f967d20f525f4893" + }, + "timestamp": "2026-09-21T04:01:05.292881+00:00" + }, + "source_unchanged_during_suite": true, + "errors": [], + "suite": { + "scenarios": [ + "mixed" + ], + "page_counts": [ + 2000 + ], + "repetitions": 2, + "timeout_seconds": 360.0, + "order": "Page counts, then scenarios, then repetitions, in supplied order.", + "isolation": "Same process; fresh analyzer per run, disabled page cache; library caches and allocator state may remain warm." + }, + "execution_guard": { + "dns_attempts": 0, + "external_connection_attempts": 0, + "network_policy": "DNS and non-loopback TCP connects blocked; loopback allowed for asyncio internals.", + "parent_hard_timeout_seconds": 1200 + } +} diff --git a/docs/benchmarks/2026-09-21-python312-500-suite.benchmark b/docs/benchmarks/2026-09-21-python312-500-suite.benchmark new file mode 100644 index 0000000..a27ca0a --- /dev/null +++ b/docs/benchmarks/2026-09-21-python312-500-suite.benchmark @@ -0,0 +1,1947 @@ +{ + "benchmark_schema_version": 2, + "status": "complete", + "benchmarks": [ + { + "type": "offline", + "fixture_version": 1, + "scenario": "basic", + "requested_pages": 500, + "network_access": false, + "config": { + "crawler": { + "max_concurrent": 20, + "max_connections_per_host": 5, + "timeout": 30, + "connect_timeout": 10, + "read_timeout": 30, + "user_agent": "tfq0seo/3.0.0 (+https://github.com/TFQ0/tfq0seo)", + "custom_headers": {}, + "follow_redirects": true, + "max_redirects": 10, + "max_pages": 500, + "max_depth": 5, + "max_page_size": 10485760, + "max_crawl_time": 3600, + "delay_between_requests": 0.0, + "adaptive_delay": true, + "min_delay": 0.0, + "max_delay": 5.0, + "rate_limit_per_second": null, + "respect_robots_txt": true, + "robots_cache_ttl": 86400, + "crawl_delay_factor": 1.0, + "allowed_domains": [], + "allowed_schemes": [ + "http", + "https" + ], + "excluded_patterns": [ + "\\.pdf$", + "\\.zip$", + "\\.exe$", + "\\.dmg$", + "/wp-admin", + "/admin", + "/login", + "\\?.*session", + "\\?.*utm_" + ], + "store_html": false, + "max_retries": 3, + "retry_on_status": [ + 429, + 500, + 502, + 503, + 504 + ], + "retry_backoff_factor": 2.0, + "cache_enabled": false, + "cache_ttl": 3600, + "cache_size_mb": 100, + "use_sitemap": true, + "discover_sitemaps": true, + "use_connection_pooling": true, + "dns_cache_ttl": 300, + "verify_ssl": true, + "proxy": null + }, + "analysis": { + "enabled_analyzers": [ + "seo", + "content", + "technical", + "performance", + "links" + ], + "analysis_mode": "standard", + "parallel_analysis": true, + "max_analysis_threads": 4, + "check_external_links": false, + "check_internal_links": true, + "check_broken_links": true, + "max_external_links_per_page": 100, + "external_link_timeout": 10, + "target_keywords": [], + "check_content_uniqueness": true, + "score_weights": { + "seo": 0.3, + "content": 0.25, + "technical": 0.2, + "performance": 0.15, + "links": 0.1 + } + }, + "export": { + "formats": [ + "html" + ], + "primary_format": "html", + "html_template": "optimized", + "output_directory": "./reports", + "filename_pattern": "{domain}_{timestamp}_{format}" + }, + "profile": "standard", + "version": "3.0.0", + "debug": false, + "continue_on_error": true, + "max_memory_mb": 1024 + }, + "fixture": { + "version": 1, + "generated_pages": 500, + "html_bytes": 209670, + "dom_elements": 5000, + "href_references": 500, + "image_elements": 0, + "analyzed_word_count": 8500, + "pages_with_word_count": 500, + "variants": { + "basic": 500, + "content-heavy": 0, + "link-dense": 0 + }, + "sha256": "6353532d2488bb21abd01d87b3a94c596b050d10e120e9ab48a79baf07d01884" + }, + "timeout_seconds": 360.0, + "timed_out": false, + "timeout_scope": "Cooperative checks between pages and after reporting; synchronous work can overrun the deadline.", + "report_completeness": { + "expected_pages": 500, + "retained_rows": 500, + "unique_urls": 500, + "missing_urls": 0, + "unexpected_urls": 0, + "duplicate_rows": 0, + "complete": true + }, + "readability": { + "status_counts": { + "not_requested": 500 + }, + "missing_resources": [] + }, + "workload": "Fixture generation, HTML parsing, static analysis, site report aggregation and retained-URL verification; no HTTP, browser or export measurement", + "analysis_duration_seconds": 24.186609499971382, + "report_duration_seconds": 16.15168629999971, + "report_pages": 500, + "report_status": "complete", + "report_summary": { + "total_pages": 500, + "successful_pages": 500, + "partial_pages": 0, + "failed_pages": 0, + "skipped_pages": 0, + "analysis_mode": "standard", + "analysis_timestamp": 1789962562.9254942, + "analysis_duration": 0, + "crawl_complete": false, + "limits_reached": [], + "discovery_errors": [], + "scope_note": "Results describe fetched pages; unvisited targets remain unchecked." + }, + "rule_coverage": { + "counts": { + "pass": 18000, + "fail": 0, + "informational": 2000, + "unknown": 1000, + "not_applicable": 13000, + "error": 0 + }, + "assessed": 20000, + "total": 34000, + "ratio": 0.9523809523809523, + "scope": "Counts are unique rule evaluations per page, not a complete site inventory." + }, + "site_analysis": { + "version": "1.0", + "coverage": { + "inventory_pages": 500, + "pages_with_facts": 500, + "complete_html_pages": 500, + "crawl_complete": false, + "note": "A completed crawl still obeys its configured scope. Missing targets and paths remain unverified." + }, + "node_count": 500, + "edge_count": 500, + "finding_count": 0 + }, + "status": "complete", + "successful_pages": 500, + "partial_pages": 0, + "failed_pages": 0, + "skipped_pages": 0, + "observed_results": 500, + "missing_results": 0, + "pages_analyzed": 500, + "pages_per_second": 12.366761225640792, + "avg_time_per_page": 0.08086191540001891, + "duration_seconds": 40.43095770000946, + "clock": "perf_counter", + "memory_rss_start_mb": 76.902, + "memory_rss_end_mb": 321.105, + "memory_rss_delta_mb": 244.203, + "memory_sampled_peak_mb": 431.445, + "memory_sample_count": 553, + "memory_sampling_interval_seconds": 0.05, + "memory_measurement": "Sampled process RSS; allocations between samples may be missed.", + "memory_used_mb": 244.203, + "errors": [], + "timestamp": "2026-09-21T03:49:25.429868+00:00", + "repetition": 1, + "run_order": 1 + }, + { + "type": "offline", + "fixture_version": 1, + "scenario": "basic", + "requested_pages": 500, + "network_access": false, + "config": { + "crawler": { + "max_concurrent": 20, + "max_connections_per_host": 5, + "timeout": 30, + "connect_timeout": 10, + "read_timeout": 30, + "user_agent": "tfq0seo/3.0.0 (+https://github.com/TFQ0/tfq0seo)", + "custom_headers": {}, + "follow_redirects": true, + "max_redirects": 10, + "max_pages": 500, + "max_depth": 5, + "max_page_size": 10485760, + "max_crawl_time": 3600, + "delay_between_requests": 0.0, + "adaptive_delay": true, + "min_delay": 0.0, + "max_delay": 5.0, + "rate_limit_per_second": null, + "respect_robots_txt": true, + "robots_cache_ttl": 86400, + "crawl_delay_factor": 1.0, + "allowed_domains": [], + "allowed_schemes": [ + "http", + "https" + ], + "excluded_patterns": [ + "\\.pdf$", + "\\.zip$", + "\\.exe$", + "\\.dmg$", + "/wp-admin", + "/admin", + "/login", + "\\?.*session", + "\\?.*utm_" + ], + "store_html": false, + "max_retries": 3, + "retry_on_status": [ + 429, + 500, + 502, + 503, + 504 + ], + "retry_backoff_factor": 2.0, + "cache_enabled": false, + "cache_ttl": 3600, + "cache_size_mb": 100, + "use_sitemap": true, + "discover_sitemaps": true, + "use_connection_pooling": true, + "dns_cache_ttl": 300, + "verify_ssl": true, + "proxy": null + }, + "analysis": { + "enabled_analyzers": [ + "seo", + "content", + "technical", + "performance", + "links" + ], + "analysis_mode": "standard", + "parallel_analysis": true, + "max_analysis_threads": 4, + "check_external_links": false, + "check_internal_links": true, + "check_broken_links": true, + "max_external_links_per_page": 100, + "external_link_timeout": 10, + "target_keywords": [], + "check_content_uniqueness": true, + "score_weights": { + "seo": 0.3, + "content": 0.25, + "technical": 0.2, + "performance": 0.15, + "links": 0.1 + } + }, + "export": { + "formats": [ + "html" + ], + "primary_format": "html", + "html_template": "optimized", + "output_directory": "./reports", + "filename_pattern": "{domain}_{timestamp}_{format}" + }, + "profile": "standard", + "version": "3.0.0", + "debug": false, + "continue_on_error": true, + "max_memory_mb": 1024 + }, + "fixture": { + "version": 1, + "generated_pages": 500, + "html_bytes": 209670, + "dom_elements": 5000, + "href_references": 500, + "image_elements": 0, + "analyzed_word_count": 8500, + "pages_with_word_count": 500, + "variants": { + "basic": 500, + "content-heavy": 0, + "link-dense": 0 + }, + "sha256": "6353532d2488bb21abd01d87b3a94c596b050d10e120e9ab48a79baf07d01884" + }, + "timeout_seconds": 360.0, + "timed_out": false, + "timeout_scope": "Cooperative checks between pages and after reporting; synchronous work can overrun the deadline.", + "report_completeness": { + "expected_pages": 500, + "retained_rows": 500, + "unique_urls": 500, + "missing_urls": 0, + "unexpected_urls": 0, + "duplicate_rows": 0, + "complete": true + }, + "readability": { + "status_counts": { + "not_requested": 500 + }, + "missing_resources": [] + }, + "workload": "Fixture generation, HTML parsing, static analysis, site report aggregation and retained-URL verification; no HTTP, browser or export measurement", + "analysis_duration_seconds": 26.558759699983057, + "report_duration_seconds": 15.826399100013077, + "report_pages": 500, + "report_status": "complete", + "report_summary": { + "total_pages": 500, + "successful_pages": 500, + "partial_pages": 0, + "failed_pages": 0, + "skipped_pages": 0, + "analysis_mode": "standard", + "analysis_timestamp": 1789962605.4694152, + "analysis_duration": 0, + "crawl_complete": false, + "limits_reached": [], + "discovery_errors": [], + "scope_note": "Results describe fetched pages; unvisited targets remain unchecked." + }, + "rule_coverage": { + "counts": { + "pass": 18000, + "fail": 0, + "informational": 2000, + "unknown": 1000, + "not_applicable": 13000, + "error": 0 + }, + "assessed": 20000, + "total": 34000, + "ratio": 0.9523809523809523, + "scope": "Counts are unique rule evaluations per page, not a complete site inventory." + }, + "site_analysis": { + "version": "1.0", + "coverage": { + "inventory_pages": 500, + "pages_with_facts": 500, + "complete_html_pages": 500, + "crawl_complete": false, + "note": "A completed crawl still obeys its configured scope. Missing targets and paths remain unverified." + }, + "node_count": 500, + "edge_count": 500, + "finding_count": 0 + }, + "status": "complete", + "successful_pages": 500, + "partial_pages": 0, + "failed_pages": 0, + "skipped_pages": 0, + "observed_results": 500, + "missing_results": 0, + "pages_analyzed": 500, + "pages_per_second": 11.77114630579592, + "avg_time_per_page": 0.08495349340001121, + "duration_seconds": 42.476746700005606, + "clock": "perf_counter", + "memory_rss_start_mb": 245.605, + "memory_rss_end_mb": 322.59, + "memory_rss_delta_mb": 76.984, + "memory_sampled_peak_mb": 430.887, + "memory_sample_count": 583, + "memory_sampling_interval_seconds": 0.05, + "memory_measurement": "Sampled process RSS; allocations between samples may be missed.", + "memory_used_mb": 76.984, + "errors": [], + "timestamp": "2026-09-21T03:50:07.998789+00:00", + "repetition": 2, + "run_order": 2 + }, + { + "type": "offline", + "fixture_version": 1, + "scenario": "content-heavy", + "requested_pages": 500, + "network_access": false, + "config": { + "crawler": { + "max_concurrent": 20, + "max_connections_per_host": 5, + "timeout": 30, + "connect_timeout": 10, + "read_timeout": 30, + "user_agent": "tfq0seo/3.0.0 (+https://github.com/TFQ0/tfq0seo)", + "custom_headers": {}, + "follow_redirects": true, + "max_redirects": 10, + "max_pages": 500, + "max_depth": 5, + "max_page_size": 10485760, + "max_crawl_time": 3600, + "delay_between_requests": 0.0, + "adaptive_delay": true, + "min_delay": 0.0, + "max_delay": 5.0, + "rate_limit_per_second": null, + "respect_robots_txt": true, + "robots_cache_ttl": 86400, + "crawl_delay_factor": 1.0, + "allowed_domains": [], + "allowed_schemes": [ + "http", + "https" + ], + "excluded_patterns": [ + "\\.pdf$", + "\\.zip$", + "\\.exe$", + "\\.dmg$", + "/wp-admin", + "/admin", + "/login", + "\\?.*session", + "\\?.*utm_" + ], + "store_html": false, + "max_retries": 3, + "retry_on_status": [ + 429, + 500, + 502, + 503, + 504 + ], + "retry_backoff_factor": 2.0, + "cache_enabled": false, + "cache_ttl": 3600, + "cache_size_mb": 100, + "use_sitemap": true, + "discover_sitemaps": true, + "use_connection_pooling": true, + "dns_cache_ttl": 300, + "verify_ssl": true, + "proxy": null + }, + "analysis": { + "enabled_analyzers": [ + "seo", + "content", + "technical", + "performance", + "links" + ], + "analysis_mode": "standard", + "parallel_analysis": true, + "max_analysis_threads": 4, + "check_external_links": false, + "check_internal_links": true, + "check_broken_links": true, + "max_external_links_per_page": 100, + "external_link_timeout": 10, + "target_keywords": [], + "check_content_uniqueness": true, + "score_weights": { + "seo": 0.3, + "content": 0.25, + "technical": 0.2, + "performance": 0.15, + "links": 0.1 + } + }, + "export": { + "formats": [ + "html" + ], + "primary_format": "html", + "html_template": "optimized", + "output_directory": "./reports", + "filename_pattern": "{domain}_{timestamp}_{format}" + }, + "profile": "standard", + "version": "3.0.0", + "debug": false, + "continue_on_error": true, + "max_memory_mb": 1024 + }, + "fixture": { + "version": 1, + "generated_pages": 500, + "html_bytes": 4739555, + "dom_elements": 76000, + "href_references": 500, + "image_elements": 4000, + "analyzed_word_count": 600500, + "pages_with_word_count": 500, + "variants": { + "basic": 0, + "content-heavy": 500, + "link-dense": 0 + }, + "sha256": "4fe8906021560317f0a1f36139b78b9f3ffd62d163f2d064b070b70746386946" + }, + "timeout_seconds": 360.0, + "timed_out": false, + "timeout_scope": "Cooperative checks between pages and after reporting; synchronous work can overrun the deadline.", + "report_completeness": { + "expected_pages": 500, + "retained_rows": 500, + "unique_urls": 500, + "missing_urls": 0, + "unexpected_urls": 0, + "duplicate_rows": 0, + "complete": true + }, + "readability": { + "status_counts": { + "unavailable": 500 + }, + "missing_resources": [ + "nltk:corpora/cmudict" + ] + }, + "workload": "Fixture generation, HTML parsing, static analysis, site report aggregation and retained-URL verification; no HTTP, browser or export measurement", + "analysis_duration_seconds": 38.38801830000011, + "report_duration_seconds": 18.198708300013095, + "report_pages": 500, + "report_status": "complete", + "report_summary": { + "total_pages": 500, + "successful_pages": 500, + "partial_pages": 0, + "failed_pages": 0, + "skipped_pages": 0, + "analysis_mode": "standard", + "analysis_timestamp": 1789962661.7445223, + "analysis_duration": 0, + "crawl_complete": false, + "limits_reached": [], + "discovery_errors": [], + "scope_note": "Results describe fetched pages; unvisited targets remain unchecked." + }, + "rule_coverage": { + "counts": { + "pass": 20500, + "fail": 0, + "informational": 3000, + "unknown": 1500, + "not_applicable": 9000, + "error": 0 + }, + "assessed": 23500, + "total": 34000, + "ratio": 0.94, + "scope": "Counts are unique rule evaluations per page, not a complete site inventory." + }, + "site_analysis": { + "version": "1.0", + "coverage": { + "inventory_pages": 500, + "pages_with_facts": 500, + "complete_html_pages": 500, + "crawl_complete": false, + "note": "A completed crawl still obeys its configured scope. Missing targets and paths remain unverified." + }, + "node_count": 500, + "edge_count": 500, + "finding_count": 0 + }, + "status": "complete", + "successful_pages": 500, + "partial_pages": 0, + "failed_pages": 0, + "skipped_pages": 0, + "observed_results": 500, + "missing_results": 0, + "pages_analyzed": 500, + "pages_per_second": 8.816645281778309, + "avg_time_per_page": 0.11342182519997004, + "duration_seconds": 56.71091259998502, + "clock": "perf_counter", + "memory_rss_start_mb": 266.5, + "memory_rss_end_mb": 385.672, + "memory_rss_delta_mb": 119.172, + "memory_sampled_peak_mb": 503.48, + "memory_sample_count": 746, + "memory_sampling_interval_seconds": 0.05, + "memory_measurement": "Sampled process RSS; allocations between samples may be missed.", + "memory_used_mb": 119.172, + "errors": [], + "timestamp": "2026-09-21T03:51:04.801500+00:00", + "repetition": 1, + "run_order": 3 + }, + { + "type": "offline", + "fixture_version": 1, + "scenario": "content-heavy", + "requested_pages": 500, + "network_access": false, + "config": { + "crawler": { + "max_concurrent": 20, + "max_connections_per_host": 5, + "timeout": 30, + "connect_timeout": 10, + "read_timeout": 30, + "user_agent": "tfq0seo/3.0.0 (+https://github.com/TFQ0/tfq0seo)", + "custom_headers": {}, + "follow_redirects": true, + "max_redirects": 10, + "max_pages": 500, + "max_depth": 5, + "max_page_size": 10485760, + "max_crawl_time": 3600, + "delay_between_requests": 0.0, + "adaptive_delay": true, + "min_delay": 0.0, + "max_delay": 5.0, + "rate_limit_per_second": null, + "respect_robots_txt": true, + "robots_cache_ttl": 86400, + "crawl_delay_factor": 1.0, + "allowed_domains": [], + "allowed_schemes": [ + "http", + "https" + ], + "excluded_patterns": [ + "\\.pdf$", + "\\.zip$", + "\\.exe$", + "\\.dmg$", + "/wp-admin", + "/admin", + "/login", + "\\?.*session", + "\\?.*utm_" + ], + "store_html": false, + "max_retries": 3, + "retry_on_status": [ + 429, + 500, + 502, + 503, + 504 + ], + "retry_backoff_factor": 2.0, + "cache_enabled": false, + "cache_ttl": 3600, + "cache_size_mb": 100, + "use_sitemap": true, + "discover_sitemaps": true, + "use_connection_pooling": true, + "dns_cache_ttl": 300, + "verify_ssl": true, + "proxy": null + }, + "analysis": { + "enabled_analyzers": [ + "seo", + "content", + "technical", + "performance", + "links" + ], + "analysis_mode": "standard", + "parallel_analysis": true, + "max_analysis_threads": 4, + "check_external_links": false, + "check_internal_links": true, + "check_broken_links": true, + "max_external_links_per_page": 100, + "external_link_timeout": 10, + "target_keywords": [], + "check_content_uniqueness": true, + "score_weights": { + "seo": 0.3, + "content": 0.25, + "technical": 0.2, + "performance": 0.15, + "links": 0.1 + } + }, + "export": { + "formats": [ + "html" + ], + "primary_format": "html", + "html_template": "optimized", + "output_directory": "./reports", + "filename_pattern": "{domain}_{timestamp}_{format}" + }, + "profile": "standard", + "version": "3.0.0", + "debug": false, + "continue_on_error": true, + "max_memory_mb": 1024 + }, + "fixture": { + "version": 1, + "generated_pages": 500, + "html_bytes": 4739555, + "dom_elements": 76000, + "href_references": 500, + "image_elements": 4000, + "analyzed_word_count": 600500, + "pages_with_word_count": 500, + "variants": { + "basic": 0, + "content-heavy": 500, + "link-dense": 0 + }, + "sha256": "4fe8906021560317f0a1f36139b78b9f3ffd62d163f2d064b070b70746386946" + }, + "timeout_seconds": 360.0, + "timed_out": false, + "timeout_scope": "Cooperative checks between pages and after reporting; synchronous work can overrun the deadline.", + "report_completeness": { + "expected_pages": 500, + "retained_rows": 500, + "unique_urls": 500, + "missing_urls": 0, + "unexpected_urls": 0, + "duplicate_rows": 0, + "complete": true + }, + "readability": { + "status_counts": { + "unavailable": 500 + }, + "missing_resources": [ + "nltk:corpora/cmudict" + ] + }, + "workload": "Fixture generation, HTML parsing, static analysis, site report aggregation and retained-URL verification; no HTTP, browser or export measurement", + "analysis_duration_seconds": 38.643274099973496, + "report_duration_seconds": 18.205546300043352, + "report_pages": 500, + "report_status": "complete", + "report_summary": { + "total_pages": 500, + "successful_pages": 500, + "partial_pages": 0, + "failed_pages": 0, + "skipped_pages": 0, + "analysis_mode": "standard", + "analysis_timestamp": 1789962719.008702, + "analysis_duration": 0, + "crawl_complete": false, + "limits_reached": [], + "discovery_errors": [], + "scope_note": "Results describe fetched pages; unvisited targets remain unchecked." + }, + "rule_coverage": { + "counts": { + "pass": 20500, + "fail": 0, + "informational": 3000, + "unknown": 1500, + "not_applicable": 9000, + "error": 0 + }, + "assessed": 23500, + "total": 34000, + "ratio": 0.94, + "scope": "Counts are unique rule evaluations per page, not a complete site inventory." + }, + "site_analysis": { + "version": "1.0", + "coverage": { + "inventory_pages": 500, + "pages_with_facts": 500, + "complete_html_pages": 500, + "crawl_complete": false, + "note": "A completed crawl still obeys its configured scope. Missing targets and paths remain unverified." + }, + "node_count": 500, + "edge_count": 500, + "finding_count": 0 + }, + "status": "complete", + "successful_pages": 500, + "partial_pages": 0, + "failed_pages": 0, + "skipped_pages": 0, + "observed_results": 500, + "missing_results": 0, + "pages_analyzed": 500, + "pages_per_second": 8.777253043750113, + "avg_time_per_page": 0.11393086139997467, + "duration_seconds": 56.96543069998734, + "clock": "perf_counter", + "memory_rss_start_mb": 304.891, + "memory_rss_end_mb": 402.797, + "memory_rss_delta_mb": 97.906, + "memory_sampled_peak_mb": 503.594, + "memory_sample_count": 750, + "memory_sampling_interval_seconds": 0.05, + "memory_measurement": "Sampled process RSS; allocations between samples may be missed.", + "memory_used_mb": 97.906, + "errors": [], + "timestamp": "2026-09-21T03:52:01.905169+00:00", + "repetition": 2, + "run_order": 4 + }, + { + "type": "offline", + "fixture_version": 1, + "scenario": "link-dense", + "requested_pages": 500, + "network_access": false, + "config": { + "crawler": { + "max_concurrent": 20, + "max_connections_per_host": 5, + "timeout": 30, + "connect_timeout": 10, + "read_timeout": 30, + "user_agent": "tfq0seo/3.0.0 (+https://github.com/TFQ0/tfq0seo)", + "custom_headers": {}, + "follow_redirects": true, + "max_redirects": 10, + "max_pages": 500, + "max_depth": 5, + "max_page_size": 10485760, + "max_crawl_time": 3600, + "delay_between_requests": 0.0, + "adaptive_delay": true, + "min_delay": 0.0, + "max_delay": 5.0, + "rate_limit_per_second": null, + "respect_robots_txt": true, + "robots_cache_ttl": 86400, + "crawl_delay_factor": 1.0, + "allowed_domains": [], + "allowed_schemes": [ + "http", + "https" + ], + "excluded_patterns": [ + "\\.pdf$", + "\\.zip$", + "\\.exe$", + "\\.dmg$", + "/wp-admin", + "/admin", + "/login", + "\\?.*session", + "\\?.*utm_" + ], + "store_html": false, + "max_retries": 3, + "retry_on_status": [ + 429, + 500, + 502, + 503, + 504 + ], + "retry_backoff_factor": 2.0, + "cache_enabled": false, + "cache_ttl": 3600, + "cache_size_mb": 100, + "use_sitemap": true, + "discover_sitemaps": true, + "use_connection_pooling": true, + "dns_cache_ttl": 300, + "verify_ssl": true, + "proxy": null + }, + "analysis": { + "enabled_analyzers": [ + "seo", + "content", + "technical", + "performance", + "links" + ], + "analysis_mode": "standard", + "parallel_analysis": true, + "max_analysis_threads": 4, + "check_external_links": false, + "check_internal_links": true, + "check_broken_links": true, + "max_external_links_per_page": 100, + "external_link_timeout": 10, + "target_keywords": [], + "check_content_uniqueness": true, + "score_weights": { + "seo": 0.3, + "content": 0.25, + "technical": 0.2, + "performance": 0.15, + "links": 0.1 + } + }, + "export": { + "formats": [ + "html" + ], + "primary_format": "html", + "html_template": "optimized", + "output_directory": "./reports", + "filename_pattern": "{domain}_{timestamp}_{format}" + }, + "profile": "standard", + "version": "3.0.0", + "debug": false, + "continue_on_error": true, + "max_memory_mb": 1024 + }, + "fixture": { + "version": 1, + "generated_pages": 500, + "html_bytes": 1139540, + "dom_elements": 26500, + "href_references": 19500, + "image_elements": 0, + "analyzed_word_count": 65000, + "pages_with_word_count": 500, + "variants": { + "basic": 0, + "content-heavy": 0, + "link-dense": 500 + }, + "sha256": "9de529c73969d8330328f2ddc650ceb4053feab22bde3d77f07efc648efd2dc2" + }, + "timeout_seconds": 360.0, + "timed_out": false, + "timeout_scope": "Cooperative checks between pages and after reporting; synchronous work can overrun the deadline.", + "report_completeness": { + "expected_pages": 500, + "retained_rows": 500, + "unique_urls": 500, + "missing_urls": 0, + "unexpected_urls": 0, + "duplicate_rows": 0, + "complete": true + }, + "readability": { + "status_counts": { + "unavailable": 500 + }, + "missing_resources": [ + "nltk:corpora/cmudict" + ] + }, + "workload": "Fixture generation, HTML parsing, static analysis, site report aggregation and retained-URL verification; no HTTP, browser or export measurement", + "analysis_duration_seconds": 33.71322609996423, + "report_duration_seconds": 19.14739220001502, + "report_pages": 500, + "report_status": "complete", + "report_summary": { + "total_pages": 500, + "successful_pages": 500, + "partial_pages": 0, + "failed_pages": 0, + "skipped_pages": 0, + "analysis_mode": "standard", + "analysis_timestamp": 1789962771.9639814, + "analysis_duration": 0, + "crawl_complete": false, + "limits_reached": [], + "discovery_errors": [], + "scope_note": "Results describe fetched pages; unvisited targets remain unchecked." + }, + "rule_coverage": { + "counts": { + "pass": 19500, + "fail": 0, + "informational": 2000, + "unknown": 1500, + "not_applicable": 11000, + "error": 0 + }, + "assessed": 21500, + "total": 34000, + "ratio": 0.9347826086956522, + "scope": "Counts are unique rule evaluations per page, not a complete site inventory." + }, + "site_analysis": { + "version": "1.0", + "coverage": { + "inventory_pages": 500, + "pages_with_facts": 500, + "complete_html_pages": 500, + "crawl_complete": false, + "note": "A completed crawl still obeys its configured scope. Missing targets and paths remain unverified." + }, + "node_count": 500, + "edge_count": 16500, + "finding_count": 0 + }, + "status": "complete", + "successful_pages": 500, + "partial_pages": 0, + "failed_pages": 0, + "skipped_pages": 0, + "observed_results": 500, + "missing_results": 0, + "pages_analyzed": 500, + "pages_per_second": 9.438788530436288, + "avg_time_per_page": 0.10594579979998525, + "duration_seconds": 52.972899899992626, + "clock": "perf_counter", + "memory_rss_start_mb": 304.648, + "memory_rss_end_mb": 403.016, + "memory_rss_delta_mb": 98.367, + "memory_sampled_peak_mb": 514.043, + "memory_sample_count": 736, + "memory_sampling_interval_seconds": 0.05, + "memory_measurement": "Sampled process RSS; allocations between samples may be missed.", + "memory_used_mb": 98.367, + "errors": [], + "timestamp": "2026-09-21T03:52:55.004628+00:00", + "repetition": 1, + "run_order": 5 + }, + { + "type": "offline", + "fixture_version": 1, + "scenario": "link-dense", + "requested_pages": 500, + "network_access": false, + "config": { + "crawler": { + "max_concurrent": 20, + "max_connections_per_host": 5, + "timeout": 30, + "connect_timeout": 10, + "read_timeout": 30, + "user_agent": "tfq0seo/3.0.0 (+https://github.com/TFQ0/tfq0seo)", + "custom_headers": {}, + "follow_redirects": true, + "max_redirects": 10, + "max_pages": 500, + "max_depth": 5, + "max_page_size": 10485760, + "max_crawl_time": 3600, + "delay_between_requests": 0.0, + "adaptive_delay": true, + "min_delay": 0.0, + "max_delay": 5.0, + "rate_limit_per_second": null, + "respect_robots_txt": true, + "robots_cache_ttl": 86400, + "crawl_delay_factor": 1.0, + "allowed_domains": [], + "allowed_schemes": [ + "http", + "https" + ], + "excluded_patterns": [ + "\\.pdf$", + "\\.zip$", + "\\.exe$", + "\\.dmg$", + "/wp-admin", + "/admin", + "/login", + "\\?.*session", + "\\?.*utm_" + ], + "store_html": false, + "max_retries": 3, + "retry_on_status": [ + 429, + 500, + 502, + 503, + 504 + ], + "retry_backoff_factor": 2.0, + "cache_enabled": false, + "cache_ttl": 3600, + "cache_size_mb": 100, + "use_sitemap": true, + "discover_sitemaps": true, + "use_connection_pooling": true, + "dns_cache_ttl": 300, + "verify_ssl": true, + "proxy": null + }, + "analysis": { + "enabled_analyzers": [ + "seo", + "content", + "technical", + "performance", + "links" + ], + "analysis_mode": "standard", + "parallel_analysis": true, + "max_analysis_threads": 4, + "check_external_links": false, + "check_internal_links": true, + "check_broken_links": true, + "max_external_links_per_page": 100, + "external_link_timeout": 10, + "target_keywords": [], + "check_content_uniqueness": true, + "score_weights": { + "seo": 0.3, + "content": 0.25, + "technical": 0.2, + "performance": 0.15, + "links": 0.1 + } + }, + "export": { + "formats": [ + "html" + ], + "primary_format": "html", + "html_template": "optimized", + "output_directory": "./reports", + "filename_pattern": "{domain}_{timestamp}_{format}" + }, + "profile": "standard", + "version": "3.0.0", + "debug": false, + "continue_on_error": true, + "max_memory_mb": 1024 + }, + "fixture": { + "version": 1, + "generated_pages": 500, + "html_bytes": 1139540, + "dom_elements": 26500, + "href_references": 19500, + "image_elements": 0, + "analyzed_word_count": 65000, + "pages_with_word_count": 500, + "variants": { + "basic": 0, + "content-heavy": 0, + "link-dense": 500 + }, + "sha256": "9de529c73969d8330328f2ddc650ceb4053feab22bde3d77f07efc648efd2dc2" + }, + "timeout_seconds": 360.0, + "timed_out": false, + "timeout_scope": "Cooperative checks between pages and after reporting; synchronous work can overrun the deadline.", + "report_completeness": { + "expected_pages": 500, + "retained_rows": 500, + "unique_urls": 500, + "missing_urls": 0, + "unexpected_urls": 0, + "duplicate_rows": 0, + "complete": true + }, + "readability": { + "status_counts": { + "unavailable": 500 + }, + "missing_resources": [ + "nltk:corpora/cmudict" + ] + }, + "workload": "Fixture generation, HTML parsing, static analysis, site report aggregation and retained-URL verification; no HTTP, browser or export measurement", + "analysis_duration_seconds": 34.6492362000281, + "report_duration_seconds": 19.69594499998493, + "report_pages": 500, + "report_status": "complete", + "report_summary": { + "total_pages": 500, + "successful_pages": 500, + "partial_pages": 0, + "failed_pages": 0, + "skipped_pages": 0, + "analysis_mode": "standard", + "analysis_timestamp": 1789962826.5033512, + "analysis_duration": 0, + "crawl_complete": false, + "limits_reached": [], + "discovery_errors": [], + "scope_note": "Results describe fetched pages; unvisited targets remain unchecked." + }, + "rule_coverage": { + "counts": { + "pass": 19500, + "fail": 0, + "informational": 2000, + "unknown": 1500, + "not_applicable": 11000, + "error": 0 + }, + "assessed": 21500, + "total": 34000, + "ratio": 0.9347826086956522, + "scope": "Counts are unique rule evaluations per page, not a complete site inventory." + }, + "site_analysis": { + "version": "1.0", + "coverage": { + "inventory_pages": 500, + "pages_with_facts": 500, + "complete_html_pages": 500, + "crawl_complete": false, + "note": "A completed crawl still obeys its configured scope. Missing targets and paths remain unverified." + }, + "node_count": 500, + "edge_count": 16500, + "finding_count": 0 + }, + "status": "complete", + "successful_pages": 500, + "partial_pages": 0, + "failed_pages": 0, + "skipped_pages": 0, + "observed_results": 500, + "missing_results": 0, + "pages_analyzed": 500, + "pages_per_second": 9.181063967421467, + "avg_time_per_page": 0.10891983800008893, + "duration_seconds": 54.459919000044465, + "clock": "perf_counter", + "memory_rss_start_mb": 329.891, + "memory_rss_end_mb": 399.477, + "memory_rss_delta_mb": 69.586, + "memory_sampled_peak_mb": 511.332, + "memory_sample_count": 745, + "memory_sampling_interval_seconds": 0.05, + "memory_measurement": "Sampled process RSS; allocations between samples may be missed.", + "memory_used_mb": 69.586, + "errors": [], + "timestamp": "2026-09-21T03:53:49.585114+00:00", + "repetition": 2, + "run_order": 6 + }, + { + "type": "offline", + "fixture_version": 1, + "scenario": "mixed", + "requested_pages": 500, + "network_access": false, + "config": { + "crawler": { + "max_concurrent": 20, + "max_connections_per_host": 5, + "timeout": 30, + "connect_timeout": 10, + "read_timeout": 30, + "user_agent": "tfq0seo/3.0.0 (+https://github.com/TFQ0/tfq0seo)", + "custom_headers": {}, + "follow_redirects": true, + "max_redirects": 10, + "max_pages": 500, + "max_depth": 5, + "max_page_size": 10485760, + "max_crawl_time": 3600, + "delay_between_requests": 0.0, + "adaptive_delay": true, + "min_delay": 0.0, + "max_delay": 5.0, + "rate_limit_per_second": null, + "respect_robots_txt": true, + "robots_cache_ttl": 86400, + "crawl_delay_factor": 1.0, + "allowed_domains": [], + "allowed_schemes": [ + "http", + "https" + ], + "excluded_patterns": [ + "\\.pdf$", + "\\.zip$", + "\\.exe$", + "\\.dmg$", + "/wp-admin", + "/admin", + "/login", + "\\?.*session", + "\\?.*utm_" + ], + "store_html": false, + "max_retries": 3, + "retry_on_status": [ + 429, + 500, + 502, + 503, + 504 + ], + "retry_backoff_factor": 2.0, + "cache_enabled": false, + "cache_ttl": 3600, + "cache_size_mb": 100, + "use_sitemap": true, + "discover_sitemaps": true, + "use_connection_pooling": true, + "dns_cache_ttl": 300, + "verify_ssl": true, + "proxy": null + }, + "analysis": { + "enabled_analyzers": [ + "seo", + "content", + "technical", + "performance", + "links" + ], + "analysis_mode": "standard", + "parallel_analysis": true, + "max_analysis_threads": 4, + "check_external_links": false, + "check_internal_links": true, + "check_broken_links": true, + "max_external_links_per_page": 100, + "external_link_timeout": 10, + "target_keywords": [], + "check_content_uniqueness": true, + "score_weights": { + "seo": 0.3, + "content": 0.25, + "technical": 0.2, + "performance": 0.15, + "links": 0.1 + } + }, + "export": { + "formats": [ + "html" + ], + "primary_format": "html", + "html_template": "optimized", + "output_directory": "./reports", + "filename_pattern": "{domain}_{timestamp}_{format}" + }, + "profile": "standard", + "version": "3.0.0", + "debug": false, + "continue_on_error": true, + "max_memory_mb": 1024 + }, + "fixture": { + "version": 1, + "generated_pages": 500, + "html_bytes": 2031413, + "dom_elements": 35852, + "href_references": 6808, + "image_elements": 1336, + "analyzed_word_count": 224986, + "pages_with_word_count": 500, + "variants": { + "basic": 167, + "content-heavy": 167, + "link-dense": 166 + }, + "sha256": "8159d57ed4cd52f09f9903ef580de5a7baabb8a4a5fe0403e15f95bbf1aa8e0b" + }, + "timeout_seconds": 360.0, + "timed_out": false, + "timeout_scope": "Cooperative checks between pages and after reporting; synchronous work can overrun the deadline.", + "report_completeness": { + "expected_pages": 500, + "retained_rows": 500, + "unique_urls": 500, + "missing_urls": 0, + "unexpected_urls": 0, + "duplicate_rows": 0, + "complete": true + }, + "readability": { + "status_counts": { + "not_requested": 167, + "unavailable": 333 + }, + "missing_resources": [ + "nltk:corpora/cmudict" + ] + }, + "workload": "Fixture generation, HTML parsing, static analysis, site report aggregation and retained-URL verification; no HTTP, browser or export measurement", + "analysis_duration_seconds": 32.74250110000139, + "report_duration_seconds": 18.548192699963693, + "report_pages": 500, + "report_status": "complete", + "report_summary": { + "total_pages": 500, + "successful_pages": 500, + "partial_pages": 0, + "failed_pages": 0, + "skipped_pages": 0, + "analysis_mode": "standard", + "analysis_timestamp": 1789962878.1674123, + "analysis_duration": 0, + "crawl_complete": false, + "limits_reached": [], + "discovery_errors": [], + "scope_note": "Results describe fetched pages; unvisited targets remain unchecked." + }, + "rule_coverage": { + "counts": { + "pass": 19333, + "fail": 0, + "informational": 2334, + "unknown": 1333, + "not_applicable": 11000, + "error": 0 + }, + "assessed": 21667, + "total": 34000, + "ratio": 0.9420434782608695, + "scope": "Counts are unique rule evaluations per page, not a complete site inventory." + }, + "site_analysis": { + "version": "1.0", + "coverage": { + "inventory_pages": 500, + "pages_with_facts": 500, + "complete_html_pages": 500, + "crawl_complete": false, + "note": "A completed crawl still obeys its configured scope. Missing targets and paths remain unverified." + }, + "node_count": 500, + "edge_count": 5812, + "finding_count": 0 + }, + "status": "complete", + "successful_pages": 500, + "partial_pages": 0, + "failed_pages": 0, + "skipped_pages": 0, + "observed_results": 500, + "missing_results": 0, + "pages_analyzed": 500, + "pages_per_second": 9.724673639562882, + "avg_time_per_page": 0.10283121440000832, + "duration_seconds": 51.41560720000416, + "clock": "perf_counter", + "memory_rss_start_mb": 344.445, + "memory_rss_end_mb": 411.102, + "memory_rss_delta_mb": 66.656, + "memory_sampled_peak_mb": 484.855, + "memory_sample_count": 706, + "memory_sampling_interval_seconds": 0.05, + "memory_measurement": "Sampled process RSS; allocations between samples may be missed.", + "memory_used_mb": 66.656, + "errors": [], + "timestamp": "2026-09-21T03:54:41.123237+00:00", + "repetition": 1, + "run_order": 7 + }, + { + "type": "offline", + "fixture_version": 1, + "scenario": "mixed", + "requested_pages": 500, + "network_access": false, + "config": { + "crawler": { + "max_concurrent": 20, + "max_connections_per_host": 5, + "timeout": 30, + "connect_timeout": 10, + "read_timeout": 30, + "user_agent": "tfq0seo/3.0.0 (+https://github.com/TFQ0/tfq0seo)", + "custom_headers": {}, + "follow_redirects": true, + "max_redirects": 10, + "max_pages": 500, + "max_depth": 5, + "max_page_size": 10485760, + "max_crawl_time": 3600, + "delay_between_requests": 0.0, + "adaptive_delay": true, + "min_delay": 0.0, + "max_delay": 5.0, + "rate_limit_per_second": null, + "respect_robots_txt": true, + "robots_cache_ttl": 86400, + "crawl_delay_factor": 1.0, + "allowed_domains": [], + "allowed_schemes": [ + "http", + "https" + ], + "excluded_patterns": [ + "\\.pdf$", + "\\.zip$", + "\\.exe$", + "\\.dmg$", + "/wp-admin", + "/admin", + "/login", + "\\?.*session", + "\\?.*utm_" + ], + "store_html": false, + "max_retries": 3, + "retry_on_status": [ + 429, + 500, + 502, + 503, + 504 + ], + "retry_backoff_factor": 2.0, + "cache_enabled": false, + "cache_ttl": 3600, + "cache_size_mb": 100, + "use_sitemap": true, + "discover_sitemaps": true, + "use_connection_pooling": true, + "dns_cache_ttl": 300, + "verify_ssl": true, + "proxy": null + }, + "analysis": { + "enabled_analyzers": [ + "seo", + "content", + "technical", + "performance", + "links" + ], + "analysis_mode": "standard", + "parallel_analysis": true, + "max_analysis_threads": 4, + "check_external_links": false, + "check_internal_links": true, + "check_broken_links": true, + "max_external_links_per_page": 100, + "external_link_timeout": 10, + "target_keywords": [], + "check_content_uniqueness": true, + "score_weights": { + "seo": 0.3, + "content": 0.25, + "technical": 0.2, + "performance": 0.15, + "links": 0.1 + } + }, + "export": { + "formats": [ + "html" + ], + "primary_format": "html", + "html_template": "optimized", + "output_directory": "./reports", + "filename_pattern": "{domain}_{timestamp}_{format}" + }, + "profile": "standard", + "version": "3.0.0", + "debug": false, + "continue_on_error": true, + "max_memory_mb": 1024 + }, + "fixture": { + "version": 1, + "generated_pages": 500, + "html_bytes": 2031413, + "dom_elements": 35852, + "href_references": 6808, + "image_elements": 1336, + "analyzed_word_count": 224986, + "pages_with_word_count": 500, + "variants": { + "basic": 167, + "content-heavy": 167, + "link-dense": 166 + }, + "sha256": "8159d57ed4cd52f09f9903ef580de5a7baabb8a4a5fe0403e15f95bbf1aa8e0b" + }, + "timeout_seconds": 360.0, + "timed_out": false, + "timeout_scope": "Cooperative checks between pages and after reporting; synchronous work can overrun the deadline.", + "report_completeness": { + "expected_pages": 500, + "retained_rows": 500, + "unique_urls": 500, + "missing_urls": 0, + "unexpected_urls": 0, + "duplicate_rows": 0, + "complete": true + }, + "readability": { + "status_counts": { + "not_requested": 167, + "unavailable": 333 + }, + "missing_resources": [ + "nltk:corpora/cmudict" + ] + }, + "workload": "Fixture generation, HTML parsing, static analysis, site report aggregation and retained-URL verification; no HTTP, browser or export measurement", + "analysis_duration_seconds": 32.458557199977804, + "report_duration_seconds": 17.584410300012678, + "report_pages": 500, + "report_status": "complete", + "report_summary": { + "total_pages": 500, + "successful_pages": 500, + "partial_pages": 0, + "failed_pages": 0, + "skipped_pages": 0, + "analysis_mode": "standard", + "analysis_timestamp": 1789962928.5882554, + "analysis_duration": 0, + "crawl_complete": false, + "limits_reached": [], + "discovery_errors": [], + "scope_note": "Results describe fetched pages; unvisited targets remain unchecked." + }, + "rule_coverage": { + "counts": { + "pass": 19333, + "fail": 0, + "informational": 2334, + "unknown": 1333, + "not_applicable": 11000, + "error": 0 + }, + "assessed": 21667, + "total": 34000, + "ratio": 0.9420434782608695, + "scope": "Counts are unique rule evaluations per page, not a complete site inventory." + }, + "site_analysis": { + "version": "1.0", + "coverage": { + "inventory_pages": 500, + "pages_with_facts": 500, + "complete_html_pages": 500, + "crawl_complete": false, + "note": "A completed crawl still obeys its configured scope. Missing targets and paths remain unverified." + }, + "node_count": 500, + "edge_count": 5812, + "finding_count": 0 + }, + "status": "complete", + "successful_pages": 500, + "partial_pages": 0, + "failed_pages": 0, + "skipped_pages": 0, + "observed_results": 500, + "missing_results": 0, + "pages_analyzed": 500, + "pages_per_second": 9.970011402092945, + "avg_time_per_page": 0.10030078800010961, + "duration_seconds": 50.1503940000548, + "clock": "perf_counter", + "memory_rss_start_mb": 334.938, + "memory_rss_end_mb": 416.07, + "memory_rss_delta_mb": 81.133, + "memory_sampled_peak_mb": 483.355, + "memory_sample_count": 696, + "memory_sampling_interval_seconds": 0.05, + "memory_measurement": "Sampled process RSS; allocations between samples may be missed.", + "memory_used_mb": 81.133, + "errors": [], + "timestamp": "2026-09-21T03:55:31.409435+00:00", + "repetition": 2, + "run_order": 8 + } + ], + "summaries": [ + { + "scenario": "basic", + "requested_pages": 500, + "runs": 2, + "complete_runs": 2, + "partial_runs": 0, + "failed_runs": 0, + "metrics_scope": "Only complete runs; inspect raw outcomes for excluded failed or partial runs.", + "metrics": { + "duration_seconds": { + "median": 41.45385220000753, + "min": 40.43095770000946, + "max": 42.476746700005606 + }, + "analysis_duration_seconds": { + "median": 25.37268459997722, + "min": 24.186609499971382, + "max": 26.558759699983057 + }, + "report_duration_seconds": { + "median": 15.989042700006394, + "min": 15.826399100013077, + "max": 16.15168629999971 + }, + "pages_per_second": { + "median": 12.068953765718355, + "min": 11.77114630579592, + "max": 12.366761225640792 + }, + "memory_rss_delta_mb": { + "median": 160.5935, + "min": 76.984, + "max": 244.203 + }, + "memory_sampled_peak_mb": { + "median": 431.166, + "min": 430.887, + "max": 431.445 + } + } + }, + { + "scenario": "content-heavy", + "requested_pages": 500, + "runs": 2, + "complete_runs": 2, + "partial_runs": 0, + "failed_runs": 0, + "metrics_scope": "Only complete runs; inspect raw outcomes for excluded failed or partial runs.", + "metrics": { + "duration_seconds": { + "median": 56.83817164998618, + "min": 56.71091259998502, + "max": 56.96543069998734 + }, + "analysis_duration_seconds": { + "median": 38.515646199986804, + "min": 38.38801830000011, + "max": 38.643274099973496 + }, + "report_duration_seconds": { + "median": 18.202127300028224, + "min": 18.198708300013095, + "max": 18.205546300043352 + }, + "pages_per_second": { + "median": 8.79694916276421, + "min": 8.777253043750113, + "max": 8.816645281778309 + }, + "memory_rss_delta_mb": { + "median": 108.539, + "min": 97.906, + "max": 119.172 + }, + "memory_sampled_peak_mb": { + "median": 503.53700000000003, + "min": 503.48, + "max": 503.594 + } + } + }, + { + "scenario": "link-dense", + "requested_pages": 500, + "runs": 2, + "complete_runs": 2, + "partial_runs": 0, + "failed_runs": 0, + "metrics_scope": "Only complete runs; inspect raw outcomes for excluded failed or partial runs.", + "metrics": { + "duration_seconds": { + "median": 53.716409450018546, + "min": 52.972899899992626, + "max": 54.459919000044465 + }, + "analysis_duration_seconds": { + "median": 34.181231149996165, + "min": 33.71322609996423, + "max": 34.6492362000281 + }, + "report_duration_seconds": { + "median": 19.421668599999975, + "min": 19.14739220001502, + "max": 19.69594499998493 + }, + "pages_per_second": { + "median": 9.309926248928878, + "min": 9.181063967421467, + "max": 9.438788530436288 + }, + "memory_rss_delta_mb": { + "median": 83.9765, + "min": 69.586, + "max": 98.367 + }, + "memory_sampled_peak_mb": { + "median": 512.6875, + "min": 511.332, + "max": 514.043 + } + } + }, + { + "scenario": "mixed", + "requested_pages": 500, + "runs": 2, + "complete_runs": 2, + "partial_runs": 0, + "failed_runs": 0, + "metrics_scope": "Only complete runs; inspect raw outcomes for excluded failed or partial runs.", + "metrics": { + "duration_seconds": { + "median": 50.78300060002948, + "min": 50.1503940000548, + "max": 51.41560720000416 + }, + "analysis_duration_seconds": { + "median": 32.6005291499896, + "min": 32.458557199977804, + "max": 32.74250110000139 + }, + "report_duration_seconds": { + "median": 18.066301499988185, + "min": 17.584410300012678, + "max": 18.548192699963693 + }, + "pages_per_second": { + "median": 9.847342520827914, + "min": 9.724673639562882, + "max": 9.970011402092945 + }, + "memory_rss_delta_mb": { + "median": 73.8945, + "min": 66.656, + "max": 81.133 + }, + "memory_sampled_peak_mb": { + "median": 484.105, + "min": 483.355, + "max": 484.855 + } + } + } + ], + "system_info": { + "os": { + "system": "Windows", + "release": "11", + "version": "10.0.26200" + }, + "architecture": "AMD64", + "cpu_model": "AMD Ryzen 7 7735HS with Radeon Graphics", + "cpu_count": 16, + "physical_cpu_count": 8, + "memory_total_gb": 63.21, + "python_version": "3.12.14 (main, Aug 25 2026, 14:01:42) [MSC v.1944 64 bit (AMD64)]", + "python_implementation": "CPython", + "package_version": "3.0.0", + "installed_distribution_version": "3.0.0", + "schema_version": "1.0", + "ruleset_version": "2026.09.21", + "scoring_version": "2.0", + "facts_version": "1.1", + "direct_dependencies": { + "aiohttp": "3.14.3", + "beautifulsoup4": "4.15.0", + "click": "8.5.0", + "jinja2": "3.1.6", + "rich": "15.0.0", + "textstat": "0.7.13", + "validators": "0.35.0", + "pyyaml": "6.0.3", + "python-dateutil": "2.9.0.post0", + "urllib3": "2.7.0", + "psutil": "7.2.2" + }, + "optional_dependencies": { + "lxml": "6.1.3", + "openpyxl": "3.1.5", + "pandas": "3.0.5" + }, + "readability_dependencies": { + "nltk": "3.10.3", + "pyphen": "0.18.1", + "cmudict": null + }, + "source_fingerprint": { + "algorithm": "sha256", + "scope": "package Python source paths and bytes", + "file_count": 23, + "digest": "077a203b8b1c65de3022f4001a48cc6a1897e89624e9e7e8f967d20f525f4893" + }, + "timestamp": "2026-09-21T03:48:44.996515+00:00" + }, + "source_unchanged_during_suite": true, + "errors": [], + "suite": { + "scenarios": [ + "basic", + "content-heavy", + "link-dense", + "mixed" + ], + "page_counts": [ + 500 + ], + "repetitions": 2, + "timeout_seconds": 360.0, + "order": "Page counts, then scenarios, then repetitions, in supplied order.", + "isolation": "Same process; fresh analyzer per run, disabled page cache; library caches and allocator state may remain warm." + }, + "execution_guard": { + "dns_attempts": 0, + "external_connection_attempts": 0, + "network_policy": "DNS and non-loopback TCP connects blocked; loopback allowed for asyncio internals.", + "parent_hard_timeout_seconds": 1200 + } +} diff --git a/docs/configuration-migration.md b/docs/configuration-migration.md new file mode 100644 index 0000000..f9350ef --- /dev/null +++ b/docs/configuration-migration.md @@ -0,0 +1,249 @@ +# Configuration migration for 3.0.0 + +The configuration schema now contains only settings used by the application. +Previously, saved configurations included options for unimplemented features. +Those fields have been removed from the dataclass constructors, validated input, +and serialized configuration. The `MonitoringConfig` class and the entire +`monitoring` section have also been removed. + +Normal loading does not silently discard these fields. `Config.from_dict()`, +`Config.from_file()`, `Config.from_env()`, and `Config.merge()` reject retired keys, +including keys set to their historical defaults. Errors identify the setting and +point to explicit migration. Remove corresponding retired environment variables +before running the CLI; the CLI does not migrate configuration automatically. + +## Explicit migration + +`Config.migrate_dict(data)` returns `(canonical_data, warnings)`: + +- `canonical_data` is a new dictionary containing validated, canonical overrides. + It preserves supplied active settings and profile selection without inserting + unspecified defaults. It can be passed to `Config.from_dict()` or serialized. +- `warnings` is a list of strings identifying removed retired defaults and + canonicalized aliases. Messages do not include supplied values. +- Retired fields are removed **only when their supplied value matches the + historical default below and has a valid historical type**. For example, + `false` is not accepted as an integer zero, and `0` is not accepted as `false`. + Float settings accept finite integer equivalents; integer settings reject + floats. Lists and dictionaries must match their complete historical contents. +- Unknown keys, malformed sections, conflicting aliases, invalid active settings, + and nondefault retired values raise `ValueError`. No partial result is returned. +- The input is not modified. Migration performs no file writes, network requests, + directory creation, or delivery actions. + +Read the warnings before using the migrated configuration. Write a separate file +to keep the original available for review: + +```python +import json +from pathlib import Path +from tfq0seo.core.config import Config + +legacy_path = Path("config.json") +legacy = json.loads(legacy_path.read_text(encoding="utf-8")) +canonical, warnings = Config.migrate_dict(legacy) +for warning in warnings: + print(warning) + +# Exclusive creation prevents overwriting an existing configuration. +with Path("config.v3.json").open("x", encoding="utf-8") as handle: + json.dump(canonical, handle, indent=2, allow_nan=False) + +config = Config.from_dict(canonical) +``` + +For YAML, use `yaml.safe_load()` to obtain the input dictionary and +`yaml.safe_dump()` to serialize `canonical`. `Config.save()` remains available +for saving a fully resolved configuration; serializing `canonical` instead keeps +unspecified profile defaults unspecified for subsequent profile changes. + +Migration does not discard a nondefault retired field just because its parent +feature is disabled. For example, an old `export.smtp_password` value causes an +error even when `export.send_email` is `false`. Review the unsupported behavior, +remove it explicitly from a copy of the input, and rerun migration. Credentials +in active settings such as `crawler.custom_headers` and `crawler.proxy` remain in +the returned data; value-free diagnostics do not redact the configuration itself. + +## Supported settings and aliases + +The active global settings are `crawler`, `analysis`, `export`, `profile`, +`version`, `debug`, `continue_on_error`, and `max_memory_mb`. `debug` is preserved +as profile metadata, including the development profile default. It does not +configure Python logging. `version` is configuration/report metadata, not a +package version override. + +Working crawler aliases remain accepted by dictionary, file, environment, and +merge entry points. Serialized configurations use canonical keys: + +| Alias in `crawler` | Canonical key | Notes | +| --- | --- | --- | +| `concurrent_requests` | `max_concurrent` | `null` means no alias override; still accepted by `CrawlerConfig` directly. | +| `max_content_length` | `max_page_size` | Maximum response bytes. | +| `retry_attempts` | `max_retries` | Number of retries. | +| `adaptive_throttle` | `adaptive_delay` | Boolean. | +| `follow_sitemap` | `use_sitemap` | Boolean. | + +Supplying an alias and its canonical key with different values is an error. +Migration reports alias normalization; ordinary loading continues to accept these +aliases without requiring migration. + +Active analysis settings are `enabled_analyzers`, `analysis_mode`, +`parallel_analysis`, `max_analysis_threads`, `check_external_links`, +`check_internal_links`, `check_broken_links`, `max_external_links_per_page`, +`external_link_timeout`, `target_keywords`, `check_content_uniqueness`, and +`score_weights`. Analyzer selection and supported modes remain available; +individual retired check flags do not control rule execution or thresholds. + +Active export settings are `formats`, `primary_format`, `html_template`, +`output_directory`, and `filename_pattern`. Supported formats are `html`, `json`, +`csv`, and `xlsx`; `OutputFormat.PDF`, `OutputFormat.MARKDOWN`, and +`OutputFormat.XML` were removed. Unsupported format requests are rejected and +are not rewritten by migration. + +`Config.SUPPORTED_FIELDS` lists the active fields for each component. The crawler +entry includes the working `concurrent_requests` constructor alias; the +serialized crawler configuration contains `max_concurrent` instead. + +## Retired crawler settings + +Every key in this table is under `crawler`. Values use JSON notation. + +| Removed key | Historical default | +| --- | --- | +| `semaphore_limit` | `30` | +| `total_timeout` | `300` | +| `rotate_user_agents` | `false` | +| `user_agent_list` | `[]` | +| `redirect_cache_ttl` | `3600` | +| `include_query_strings`, `normalize_urls` | `true` | +| `parse_javascript`, `execute_javascript` | `false` | +| `wait_for_javascript` | `0.0` | +| `compress_stored_html`, `prioritize_sitemap_urls` | `true` | +| `use_http2` | `false` | + +Use the existing `max_concurrent` to control concurrency and `max_crawl_time` for +the crawl deadline. These are not automatic renames of `semaphore_limit` or +`total_timeout`: the retired options never controlled the crawler, and the active +settings may already be present with different values. URL identity follows the +shared URL resolver; there is no toggle to remove query strings. JavaScript +execution, user-agent rotation, HTTP/2 selection, and the other removed behaviors +have no configuration replacement. + +## Retired analysis settings + +Every key in this table is under `analysis`. + +| Removed key | Historical default | +| --- | --- | +| `validate_anchors` | `true` | +| `check_images`, `check_image_optimization`, `check_alt_text`, `check_image_dimensions` | `true` | +| `max_image_size_kb` | `500` | +| `min_content_length` | `100` | +| `max_content_length` | `100000` | +| `optimal_content_length` | `1500` | +| `check_readability` | `true` | +| `target_reading_level` | `8` | +| `check_keyword_density`, `keyword_variations` | `true` | +| `min_unique_content_ratio` | `0.7` | +| `check_meta_tags`, `check_structured_data`, `validate_structured_data` | `true` | +| `check_open_graph`, `check_twitter_cards`, `check_canonical_urls`, `check_hreflang` | `true` | +| `check_sitemaps`, `check_robots_txt` | `true` | +| `check_https`, `check_security_headers`, `check_mixed_content` | `true` | +| `check_mobile_friendly`, `check_page_speed`, `check_core_web_vitals` | `true` | +| `check_compression`, `check_caching`, `check_minification`, `check_http2` | `true` | +| `max_page_load_time` | `3.0` | +| `max_ttfb` | `0.8` | +| `max_fcp` | `1.8` | +| `max_lcp` | `2.5` | +| `max_fid` | `100.0` | +| `max_cls` | `0.1` | +| `max_page_size_mb` | `3.0` | +| `check_accessibility` | `true` | +| `wcag_level` | `"AA"` | + +Removing these inert settings does not turn checks on or off. Findings are +controlled by the implemented analyzers and rule registry. In particular, +declaring a Core Web Vitals threshold or WCAG level never provided browser +measurements or a conformance assessment. `crawler.use_sitemap`, +`crawler.discover_sitemaps`, and `crawler.respect_robots_txt` remain separate, +implemented crawler controls. + +## Retired export settings + +Every key in this table is under `export`. + +| Removed key | Historical default | +| --- | --- | +| `include_inline_css`, `include_inline_js`, `minify_html` | `true` | +| `html_theme` | `"light"` | +| `include_charts` | `true` | +| `charts_library` | `"chartjs"` | +| `include_raw_data`, `include_page_content`, `include_screenshots`, `include_har_files` | `false` | +| `data_sampling_rate` | `1.0` | +| `max_issues_per_page` | `100` | +| `max_pages_in_report` | `1000` | +| `create_subdirectories` | `true` | +| `compress_output` | `false` | +| `compression_format` | `"zip"` | +| `split_large_reports` | `true` | +| `split_threshold_mb` | `50` | +| `generate_summary`, `generate_executive_report` | `true` | +| `send_email` | `false` | +| `email_recipients` | `[]` | +| `email_subject_template` | `"SEO Report for {domain}"` | +| `smtp_server`, `smtp_username`, `smtp_password` | `null` | +| `smtp_port` | `587` | +| `upload_to_cloud` | `false` | +| `cloud_provider`, `cloud_bucket`, `cloud_path_prefix` | `null` | +| `send_to_api` | `false` | +| `api_endpoint`, `api_key` | `null` | +| `api_method` | `"POST"` | + +Select a supported template using `html_template` and a supported output format +using `formats`. Report content comes from the report schema and template; the +removed flags did not alter it. Email, cloud/API delivery, screenshots, HAR +capture, compression, and report splitting have no built-in replacement. + +## Retired monitoring and global settings + +Every key in the next table is under the removed `monitoring` section. + +| Removed key | Historical default | +| --- | --- | +| `enabled` | `false` | +| `collect_metrics` | `true` | +| `metrics_interval` | `60` | +| `metrics_retention_days` | `30` | +| `enable_alerts` | `false` | +| `alert_thresholds` | `{"error_rate": 0.05, "avg_response_time": 5.0, "memory_usage_mb": 500.0, "broken_links_ratio": 0.1}` | +| `log_level` | `"info"` | +| `log_to_file` | `true` | +| `log_file_path` | `"./logs/tfq0seo.log"` | +| `log_rotation` | `"daily"` | +| `log_retention_days` | `7` | +| `log_format` | `"json"` | +| `show_progress` | `true` | +| `progress_update_interval` | `1.0` | +| `detailed_progress`, `webhook_enabled` | `false` | +| `webhook_url` | `null` | +| `webhook_events` | `["analysis_complete", "error", "threshold_exceeded"]` | + +An empty `monitoring` section, or a section containing only matching historical +defaults, is removed during explicit migration. There is no background monitoring, +alerting, webhook, or log-rotation service configured by the application. Configure +Python logging in the calling program if needed; `debug` does not replace the +retired logging settings. + +The following top-level settings were also removed: + +| Removed key | Historical default | Migration meaning | +| --- | --- | --- | +| `dry_run` | `false` | No dry-run mode exists. Review and remove a `true` request explicitly. | +| `temp_directory` | `"./temp"` | No configurable application temporary directory exists. | +| `features` | `{}` | No feature-flag mechanism consumes this mapping. | +| `metadata` | `{}` | No custom metadata mapping is consumed; `version` remains available. | + +Retired attributes assigned dynamically to a configuration object are rejected by +validation and serialization. Use the migration API on the old dictionary before +constructing an active configuration, rather than attaching removed attributes +to a dataclass instance. diff --git a/docs/scale-validation.md b/docs/scale-validation.md new file mode 100644 index 0000000..91212ea --- /dev/null +++ b/docs/scale-validation.md @@ -0,0 +1,80 @@ +# Offline scale validation + +`python -m tfq0seo.benchmark` runs the original 500-page basic fixture without HTTP requests. It measures fixture generation, HTML parsing, the configured static analyzers, site report generation, and verification that every expected URL remains in the report. It does not measure crawling, remote latency, browser rendering, or HTML/CSV/XLSX export. + +```sh +# Original default workload +python -m tfq0seo.benchmark --output benchmark.json + +# Varied workloads at two sizes, with three measurements of each case +python -m tfq0seo.benchmark --suite --pages 500 2000 --repetitions 3 --timeout-seconds 600 --output scale.json + +# One larger workload +python -m tfq0seo.benchmark --scenario link-dense --pages 5000 --timeout-seconds 600 --output links-5000.json +``` + +`--scenario` selects one workload; `--suite` selects all four. They are mutually exclusive. Repetitions execute sequentially in the same process, ordered by page count, scenario, and repetition. Each measurement creates a fresh analyzer with the standard configuration, disables page caching, and sets `crawler.max_pages` to the fixture size. Full effective configuration is recorded. Library caches and Python allocator state can remain warm, so the raw run order and starting RSS matter when comparing repetitions. There is no discarded warm-up run. + +## Workloads + +Fixture version 1 generates deterministic `https://benchmark.test/page/{index}` documents. The `.test` references are parsed but never fetched. Each run records a SHA-256 over every generated URL and its UTF-8 HTML, byte and DOM totals, href references, image counts, analyzed word counts, and the number of documents of each variant. + +| Scenario | Documents | +| --- | --- | +| `basic` | Original compact English fixture: one heading, one paragraph, and a link to the next page in a ring. Its original markup is unchanged. | +| `content-heavy` | English articles with 12 sections, 24 paragraphs (about 1,200 words), eight images, a 20-row table, stylesheet/script references, and a self canonical. | +| `link-dense` | The basic page plus 32 internal hrefs, four external references, mail and fragment links, and a self canonical. Small fixtures can repeat internal targets; graph edges are deduplicated by the report implementation. | +| `mixed` | Repeats basic, content-heavy, and link-dense documents in that order. | + +All supplied page fetch records have HTTP status 200 and complete local HTML. SEO findings are expected; an unfavorable rule result does not mean the analyzer failed. Browser measurements remain unavailable. Offline workload tests prohibit DNS and crawler fetches, including downloads attempted by indirect dependencies. Readability uses only installed resources; its status counts and missing resources are recorded because availability changes the work performed on longer English documents. + +## Recorded evidence + +The JSON output contains every raw run and per-case median/minimum/maximum summaries. Summary metrics include only complete runs; excluded partial and failed run counts remain explicit. Each run reports successful, partial, failed, skipped, and missing page results. Report verification checks both row count and the exact set of expected URLs, detecting duplicate rows that could conceal missing pages. Site graph node/edge counts, coverage, report summary, and rule coverage are retained. + +The environment record includes OS, CPU model and logical/physical counts, RAM, Python, package version, installed direct and optional dependency versions, readability dependency versions, schema/rules/scoring/facts versions, and a hash of package Python source paths and bytes. An absent installed distribution is recorded as `null`. The suite fails if package source changes during the run. Timestamps use UTC. + +Elapsed time uses `time.perf_counter()`. Separate analysis and report durations help locate work, while total duration also includes retained-URL verification and benchmark bookkeeping. Process RSS is sampled every 50 ms and at both ends. `memory_sampled_peak_mb` is the largest observed RSS, not a true allocation peak; short-lived allocations can be missed. Start, end, and delta RSS are included. Legacy `memory_used_mb` means RSS delta. Measurements describe the whole Python process, including loaded dependencies and retained library caches. + +`--timeout-seconds` is a cooperative per-run deadline. It cancels awaitable work and checks between pages and after reporting, but cannot interrupt synchronous analysis/report work or forcibly terminate worker threads. Use a process supervisor with a hard timeout for unattended runs. A timeout keeps already observed page counts and returns a failed run. Exit codes are 0 for an entirely complete suite, 1 for incomplete/failed runs (including changed source), 2 for invalid CLI arguments, and 130 for interruption. + +## Measurements + +Measured on 21 September 2026 using Python 3.12.14 on Windows 11 (10.0.26200), an AMD Ryzen 7 7735HS (8 physical / 16 logical CPUs), and 63.21 GiB RAM. Package 3.0.0 used ruleset `2026.09.21`, facts `1.1`, and site analysis `1.0`. Package Python source fingerprint: `077a203b8b1c65de3022f4001a48cc6a1897e89624e9e7e8f967d20f525f4893`. + +Each case has two repetitions. The 500-page cases share one process; larger case groups start fresh processes. Full tests and wheel checks finished before measurement. A supervisor set a 1,200-second hard timeout per command, alongside the 360-second cooperative deadline per run. DNS and non-loopback TCP connections were blocked and counted; loopback remained available for asyncio internals. + +The measured CLI workloads were: + +```sh +python -m tfq0seo.benchmark --suite --pages 500 --repetitions 2 --timeout-seconds 360 --output docs/benchmarks/2026-09-21-python312-500-suite.benchmark +python -m tfq0seo.benchmark --scenario basic --pages 2000 --repetitions 2 --timeout-seconds 360 --output docs/benchmarks/2026-09-21-python312-2000-basic.benchmark +python -m tfq0seo.benchmark --scenario mixed --pages 2000 --repetitions 2 --timeout-seconds 360 --output docs/benchmarks/2026-09-21-python312-2000-mixed.benchmark +``` + +| Pages | Scenario | Median total seconds (range) | Median report seconds | Median complete pages/second | Highest sampled RSS (MiB) | +| ---: | --- | ---: | ---: | ---: | ---: | +| 500 | basic | 41.45 (40.43–42.48) | 15.99 | 12.07 | 431.44 | +| 500 | content-heavy | 56.84 (56.71–56.97) | 18.20 | 8.80 | 503.59 | +| 500 | link-dense | 53.72 (52.97–54.46) | 19.42 | 9.31 | 514.04 | +| 500 | mixed | 50.78 (50.15–51.42) | 18.07 | 9.85 | 484.86 | +| 2,000 | basic | 165.34 (164.50–166.18) | 63.93 | 12.10 | 1,496.58 | +| 2,000 | mixed | 193.89 (184.03–203.75) | 65.60 | 10.34 | 1,704.72 | + +All 12 runs (12,000 page analyses across repetitions) completed with every expected URL retained exactly once, zero partial/failed/skipped/missing results, no timeouts, and zero blocked DNS or external connection attempts. The 500-page link-dense reports retained 16,500 observed graph edges; mixed reports retained 5,812 edges at 500 pages and 23,312 at 2,000 pages. All three artifacts matched the current package source fingerprint, and it remained unchanged during measurement. Fixture hashes and readability statuses also matched between repetitions of each case. + +The local NLTK `corpora/cmudict` resource was absent. Longer English documents recorded unavailable readability estimates with explicit missing-resource metadata; basic documents were below the readability word threshold. The measured workload therefore includes content analysis but excludes calculation of those unavailable readability formulas. It also excludes browser metrics, HTTP crawling, and export serialization. These results do not establish network-crawl capacity or maximum supported site size. + +Raw evidence uses the `.benchmark` extension with standard JSON content: + +- [500 pages, all four scenarios, two repetitions](benchmarks/2026-09-21-python312-500-suite.benchmark) +- [2,000 basic pages, two repetitions](benchmarks/2026-09-21-python312-2000-basic.benchmark) +- [2,000 mixed pages, two repetitions](benchmarks/2026-09-21-python312-2000-mixed.benchmark) + +At 2,000 pages, median time was 3.99 times the 500-page basic median and 3.82 times the 500-page mixed median, for four times as many pages. These fixture-specific ratios do not establish general time complexity. The larger mixed timings varied by 19.72 seconds across two repeats; keep repetition and process context when comparing future results. + +The 2,000-page reports reached about 1.46 GiB sampled RSS for basic and 1.66 GiB for mixed content. The recorded `max_memory_mb=1024` setting checks process memory during page-processing progress; it is not a hard memory bound on synchronous report assembly. Large reports can exceed it. This is a practical capacity limit to consider before increasing site size. Next, profile report generation and investigate reducing retained objects and copies. Validation stops at 2,000 pages; 5,000 pages were not measured. + +The 40 benchmark regression tests passed on Python 3.12 and 3.14, including deterministic real-analyzer fixtures, blocked DNS/fetch attempts, deadline behavior, outcome counting, retained-URL checks, CLI validation, and metadata. Final artifacts were parsed as strict JSON and checked against the current source and their recorded outcomes. + +Results are observations for the recorded machine and configuration, not throughput or capacity guarantees for arbitrary websites. Real sites can have larger DOMs, denser graphs, slow remote responses, or different analyzer workloads. diff --git a/pyproject.toml b/pyproject.toml index 77ec55d..e9f4bd0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta" [project] name = "tfq0seo" -version = "2.3.2" -description = "Fast SEO analysis tool with reports" +dynamic = ["version"] +description = "Static SEO analysis with evidence-based reports" authors = [{name = "TFQ0 SEO Team"}] readme = "README.md" requires-python = ">=3.8" @@ -32,6 +32,7 @@ dependencies = [ ] [project.optional-dependencies] +test = ["pytest>=7.0", "openpyxl>=3.0.0"] full = [ "lxml>=4.9.0", "openpyxl>=3.0.0", @@ -41,8 +42,18 @@ full = [ [project.scripts] tfq0seo = "tfq0seo.cli:main" +[project.urls] +Repository = "https://github.com/TFQ0/tfq0seo" + +[tool.setuptools.dynamic] +version = {attr = "tfq0seo.__version__"} + [tool.setuptools.packages.find] include = ["tfq0seo*"] [tool.setuptools.package-data] tfq0seo = ["templates/*.html"] + +[tool.pytest.ini_options] +testpaths = ["tests"] +addopts = "-ra" diff --git a/requirements.txt b/requirements.txt index c673fec..27de60b 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,17 +1,3 @@ -# Core dependencies -aiohttp>=3.8.0 -beautifulsoup4>=4.11.0 -click>=8.1.0 -jinja2>=3.1.0 -rich>=12.6.0 -textstat>=0.7.3 -validators>=0.20.0 -pyyaml>=6.0 -python-dateutil>=2.8.0 -urllib3>=1.26.0 -psutil>=5.9.0 - -# Optional dependencies for full features -lxml>=4.9.0 -openpyxl>=3.0.0 -pandas>=1.5.0 +# Install the project with its optional export/parser dependencies. +# Run from the repository root; pyproject.toml is the dependency source. +.[full] diff --git a/setup.py b/setup.py index d101a6c..18b7209 100644 --- a/setup.py +++ b/setup.py @@ -1,50 +1,4 @@ -"""Setup configuration for tfq0seo package.""" -from setuptools import setup, find_packages +"""Compatibility entry point; package metadata lives in pyproject.toml.""" +from setuptools import setup -with open("README.md", "r", encoding="utf-8") as fh: - long_description = fh.read() - -setup( - name="tfq0seo", - version="2.3.2", - author="TFQ0 SEO Team", - description="Fast SEO analysis tool with reports", - long_description=long_description, - long_description_content_type="text/markdown", - url="https://github.com/tfq0seo/tfq0seo", - packages=find_packages(), - package_data={ - "tfq0seo": ["templates/*.html"], - }, - install_requires=[ - "aiohttp>=3.8.0", - "beautifulsoup4>=4.11.0", - "click>=8.1.0", - "jinja2>=3.1.0", - "rich>=12.6.0", - "textstat>=0.7.3", - "validators>=0.20.0", - "pyyaml>=6.0", - "python-dateutil>=2.8.0", - "urllib3>=1.26.0", - "psutil>=5.9.0", - ], - extras_require={ - "full": ["lxml>=4.9.0", "openpyxl>=3.0.0", "pandas>=1.5.0"], - }, - entry_points={ - "console_scripts": ["tfq0seo=tfq0seo.cli:main"], - }, - python_requires=">=3.8", - classifiers=[ - "Development Status :: 4 - Beta", - "Intended Audience :: Developers", - "Topic :: Internet :: WWW/HTTP :: Site Management", - "License :: OSI Approved :: MIT License", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - ], -) +setup() diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..bd817c5 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,66 @@ +"""Deterministic HTTP fixtures. The suite must never contact public sites.""" + +import ipaddress +import os +import socket +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +import pytest + + +@pytest.fixture(autouse=True) +def isolate_network_and_configuration(monkeypatch): + for name in os.environ: + if name.startswith('TFQ0SEO_'): + monkeypatch.delenv(name) + original = socket.socket.connect + original_ex = socket.socket.connect_ex + + def check(address): + if isinstance(address, tuple): + host = address[0] + if host != 'localhost' and not ipaddress.ip_address(host).is_loopback: + raise AssertionError('Tests may connect only to loopback addresses') + + def connect(sock, address): + check(address) + return original(sock, address) + + def connect_ex(sock, address): + check(address) + return original_ex(sock, address) + + monkeypatch.setattr(socket.socket, 'connect', connect) + monkeypatch.setattr(socket.socket, 'connect_ex', connect_ex) + + +@pytest.fixture +def http_site(): + """Route map values are (status, headers, body); no implicit charset.""" + routes, requests = {}, [] + + class Handler(BaseHTTPRequestHandler): + def do_GET(self): + requests.append(self.path) + status, headers, body = routes.get(self.path, (404, {}, 'Not found')) + body = body.encode('utf-8') if isinstance(body, str) else body + self.send_response(status) + for name, value in headers.items(): + self.send_header(name, value) + self.send_header('Content-Length', str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + server = ThreadingHTTPServer(('127.0.0.1', 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield 'http://127.0.0.1:' + str(server.server_port), routes, requests + finally: + server.shutdown() + server.server_close() + thread.join(timeout=5) diff --git a/tests/test_analyzers.py b/tests/test_analyzers.py new file mode 100644 index 0000000..c224c34 --- /dev/null +++ b/tests/test_analyzers.py @@ -0,0 +1,327 @@ +"""Regression fixtures for analyzer correctness and measurement provenance.""" + +import json + +import pytest +from bs4 import BeautifulSoup +from multidict import CIMultiDict + +from tfq0seo.analyzers import ( + analyze_content, analyze_links, analyze_performance, analyze_seo, analyze_technical, +) +from tfq0seo.analyzers.common import parse_robots +from tfq0seo.analyzers.content import detect_language, extract_text_content +from tfq0seo.analyzers.links import estimate_domain_authority, normalize_url +from tfq0seo.analyzers.performance import analyze_javascript_optimization, is_third_party +from tfq0seo.analyzers.seo import analyze_heading_structure, analyze_internal_linking_seo +from tfq0seo.analyzers.technical import analyze_crawlability, analyze_performance_indicators +from tfq0seo.urls import classify_url, resolve_url + + +URL = 'https://example.com/articles/' + + +def document(body='', head='', lang='en'): + return BeautifulSoup( + f'Example page title for testing' + f'' + f'{head}{body}', 'html.parser') + + +def rule_ids(result): + return {issue.get('rule_id') for issue in result['issues']} + + +@pytest.mark.parametrize('body', [ + '

Historical information

Records for 2001 2002 2003.

', + '

', + '

Visible heading

', +]) +def test_content_accepts_previously_crashing_markup(body): + result = analyze_content(document(body), URL) + assert 'error' not in result + assert 0 <= result['score'] <= 100 + json.dumps(result, allow_nan=False) + + +def test_content_extraction_preserves_original_and_does_not_hide_arbitrary_classes(): + soup = document('
Visible words
') + before = str(soup) + content = extract_text_content(soup) + assert 'Visible words' in content + assert 'Secret' not in content + assert str(soup) == before + + +def test_content_length_and_keyword_density_are_not_ranking_requirements(): + short = document('

Informations sur le produit

Produit utile.

', lang='fr') + long = document('

Informations sur le produit

' + 'produit ' * 3500 + '

', lang='fr') + short_result = analyze_content(short, URL, ['produit']) + long_result = analyze_content(long, URL, ['produit']) + assert short_result['score'] == long_result['score'] + assert not any('word count' in issue['message'].lower() or 'stuffing' in issue['message'].lower() + for result in (short_result, long_result) for issue in result['issues']) + + +def test_empty_alt_is_valid_for_decorative_images(): + soup = document('

Accessible page heading

') + assert 'images.missing_alt' not in rule_ids(analyze_content(soup, URL)) + assert 'images.missing_alt' not in rule_ids(analyze_seo(soup, URL)) + + +def test_missing_alt_reports_a_stable_rule_and_evidence(): + soup = document('

Accessible page heading

') + for analyzer in (analyze_content, analyze_seo): + issue = next(issue for issue in analyzer(soup, URL)['issues'] if issue.get('rule_id') == 'images.missing_alt') + assert issue['evidence'] + + +def test_language_prefers_declaration_and_does_not_assume_latin_text_is_english(): + assert detect_language('Bonjour le monde, nous sommes ici.') == 'und' + assert detect_language('Bonjour le monde', 'fr-CA') == 'fr' + assert detect_language('私は日本語を話します') == 'ja' + result = analyze_content(document('

日本語のページです

内容を説明します。

', lang='ja'), URL) + assert result['data']['metrics']['word_count'] is None + assert result['data']['metrics']['word_count_method'] == 'unavailable' + assert result['data']['structure']['has_call_to_action'] is None + assert not any('introduction' in issue['message'] or 'call-to-action' in issue['message'] for issue in result['issues']) + + +@pytest.mark.parametrize('meta,headers,expected_index,expected_follow', [ + ('', None, True, True), + ('', None, True, False), + ('', None, True, False), + ('', None, False, False), + ('', None, False, False), + ('', {'X-Robots-Tag': ['otherbot: noindex', 'nofollow', 'googlebot: noindex']}, True, True), + ('', {'X-Robots-Tag': 'googlebot: noindex, otherbot: nofollow'}, True, False), + ('', {'X-Robots-Tag': 'otherbot: noindex, googlebot: nofollow'}, False, True), + ('', {'X-Robots-Tag': 'all, none'}, True, True), +]) +def test_robots_combines_applicable_directives(meta, headers, expected_index, expected_follow): + soup = document(head=meta) + parsed = parse_robots(soup, headers) + assert parsed['noindex'] is expected_index + assert parsed['nofollow'] is expected_follow + technical = analyze_crawlability(soup, headers) + assert technical.noindex is expected_index + assert technical.nofollow is expected_follow + seo = analyze_seo(soup, URL, headers=headers) + assert ('robots.noindex' in rule_ids(seo)) is expected_index + + +def test_repeated_headers_and_restrictive_snippet_values_are_preserved(): + headers = CIMultiDict([('X-Robots-Tag', 'max-snippet: -1'), + ('X-Robots-Tag', 'googlebot: noindex, max-snippet: 20')]) + parsed = parse_robots(document(), headers) + assert parsed['noindex'] is True + assert parsed['max_snippet'] == 20 + assert len(parsed['evidence']) == 2 + + +def test_indexability_does_not_claim_robots_txt_crawl_access(): + result = analyze_technical(document(head=''), URL) + assert result['data']['crawlability']['indexability'] == 'blocked_by_robots' + assert result['data']['crawlability']['crawl_access'] == 'unknown' + assert result['data']['crawlability']['status'] == 'unknown' + + +@pytest.mark.parametrize('doctype', ['', '']) +def test_valid_html5_doctype_is_recognized(doctype): + soup = BeautifulSoup(doctype + '

Heading

', 'html.parser') + ids = rule_ids(analyze_technical(soup, URL)) + assert 'html.doctype_missing' not in ids + assert 'html.doctype_legacy' not in ids + + +def test_missing_doctype_is_reported(): + soup = BeautifulSoup('

Heading

', 'html.parser') + assert 'html.doctype_missing' in rule_ids(analyze_technical(soup, URL)) + + +@pytest.mark.parametrize('attribute', ['async', 'defer', 'async=""', 'defer="defer"', 'type="module"']) +def test_nonblocking_scripts_use_html_boolean_attribute_semantics(attribute): + soup = document(head=f'') + result = analyze_performance(soup, URL) + assert analyze_javascript_optimization(soup)['render_blocking'] == 0 + assert 'performance.blocking_scripts' not in rule_ids(result) + assert not result['data']['critical_rendering_path']['render_blocking_resources'] + + +def test_blocking_script_finding_and_font_preloads(): + soup = document(head='') + result = analyze_performance(soup, URL) + assert 'performance.blocking_scripts' in rule_ids(result) + assert result['resources']['fonts'] == ['https://example.com/font.woff2'] + assert result['grade'] == ('A' if result['score'] >= 90 else 'B' if result['score'] >= 80 else 'C' if result['score'] >= 70 else 'D' if result['score'] >= 60 else 'F') + + +def test_script_origin_checks_use_resolved_urls_instead_of_brand_substrings(): + soup = document(head='' + '') + scripts = analyze_performance(soup, URL)['data']['javascript_optimization'] + assert [script['url'] for script in scripts['third_party_scripts']] == ['https://assets.other.test/a.js'] + assert scripts['minified_scripts'] is None + assert scripts['minified_filename_references'] == 1 + + +@pytest.mark.parametrize('fetch_time', [None, 0, 1.25]) +def test_no_fabricated_browser_timings_or_passing_resource_budgets(fetch_time): + soup = document('', head='') + result = analyze_performance(soup, URL, load_time=fetch_time, content_length=500) + data = result['data'] + for key in ('load_time', 'lcp', 'inp', 'fid', 'cls', 'fcp', 'tti', 'tbt', 'ttfb'): + assert data['metrics'][key] is None + assert data['metric_sources'][key] == 'not_measured' + assert data['metrics']['html_fetch_time'] == (fetch_time or None) + assert data['metrics']['html_content_bytes'] == 500 + assert data['performance_level'] is None + for category in data['performance_budget'].values(): + for metric in category.values(): + assert metric['current'] is None + assert metric['status'] == 'unknown' + assert data['image_optimization']['savings_potential_kb'] is None + assert data['caching_strategy']['estimated_cache_hit_rate'] is None + assert data['network_metrics']['total_requests'] is None + assert data['network_metrics']['referenced_resources'] == 2 + json.dumps(result, allow_nan=False) + + +@pytest.mark.parametrize('payload', [ + {'@context': 'https://schema.org', '@graph': [{'@type': 'Organization', 'name': 'Example', 'url': 'https://example.com'}]}, + [{'@context': 'https://schema.org', '@type': 'Organization', 'name': 'Example', 'url': 'https://example.com'}], + {'@context': 'https://schema.org', '@type': ['Organization', 'Thing'], 'name': 'Example', 'url': 'https://example.com'}, +]) +def test_valid_jsonld_graphs_arrays_and_type_arrays(payload): + result = analyze_seo(document(head=''), URL) + nodes = result['data']['structured_data'] + assert len(nodes) == 1 + assert nodes[0]['valid'] is True + assert nodes[0]['errors'] == [] + assert nodes[0]['rich_snippet_eligible'] is None + assert nodes[0]['eligibility_status'] == 'unknown' + + +@pytest.mark.parametrize('payload', ['[null]', '[]', '{"@graph": 42}', '{bad json']) +def test_invalid_or_empty_jsonld_does_not_crash_analyzer(payload): + result = analyze_seo(document(head=''), URL) + assert any(issue['category'] == 'Structured Data' for issue in result['issues']) + json.dumps(result, allow_nan=False) + + +def test_heading_order_is_checked_in_document_order(): + skipped = analyze_heading_structure(document('

Main

Skipped

Later

')) + valid = analyze_heading_structure(document('

Main

A

A1

B

B1

')) + assert skipped['hierarchy_valid'] is False + assert valid['hierarchy_valid'] is True + + +def test_url_resolution_preserves_meaningful_url_components(): + reference = '/path//item/?source=a&ref=b&utm_source=c&empty=&x=1&x=2#section' + assert normalize_url(reference, URL) == 'https://example.com' + reference + soup = document(f'Item details') + result = analyze_links(soup, URL) + assert result['data']['internal_links'][0]['url'] == 'https://example.com' + reference + assert result['data']['internal_links'][0]['href'] == reference + + +@pytest.mark.parametrize('reference,expected', [ + ('child//leaf/', 'https://example.com/articles/child//leaf/'), + ('../child//leaf/?ref=a&empty=&q=2&q=1#x', 'https://example.com/child//leaf/?ref=a&empty=&q=2&q=1#x'), + ('a/./b/../c//d', 'https://example.com/articles/a/c//d'), + ('/a//b/../c/', 'https://example.com/a//c/'), + ('//EXAMPLE.COM:443/a//b/', 'https://example.com/a//b/'), + ('?', 'https://example.com/articles/?'), + ('#part', 'https://example.com/articles/#part'), + ('', 'https://example.com/articles/'), + ('https://BÜCHER.example:443/a', 'https://xn--bcher-kva.example/a'), +]) +def test_shared_resolver_preserves_uri_reference_semantics(reference, expected): + assert resolve_url(reference, URL) == expected + + +@pytest.mark.parametrize('reference', ['http://[', 'https://example.com:99999/', 'https://bad host/', None]) +def test_shared_resolver_rejects_malformed_authorities_without_raising(reference): + assert resolve_url(reference, URL) is None + + +def test_shared_classifier_matches_standard_protocol_transitions_and_exact_hosts(): + assert classify_url('http://EXAMPLE.com:80/', URL) == 'internal' + assert classify_url('https://example.com:8443/', URL) == 'external' + assert classify_url('https://sub.example.com/', URL) == 'external' + assert classify_url('https://example.com.attacker.test/', URL) == 'external' + + +def test_link_classification_is_consistent_and_honors_html_base(): + soup = document('RelativeExternal' + 'HomeEmail' + 'Telephone', head='') + seo = analyze_internal_linking_seo(soup, URL) + links = analyze_links(soup, URL)['data'] + assert seo['internal_count'] == links['metrics']['internal_links'] == 1 + assert seo['external_count'] == links['metrics']['external_links'] == 2 + assert len(links['non_http_links']) == 2 + assert links['external_links'][0]['url'] == 'https://outside.test/page/' + assert is_third_party('/relative.js', URL) is False + assert is_third_party('//outside.test/app.js', URL) is True + + +def test_malformed_link_is_reported_without_losing_other_link_evidence(): + result = analyze_links(document('BadGood'), URL) + assert 'links.invalid_url' in rule_ids(result) + assert len(result['data']['internal_links']) == 1 + + +def test_no_authority_velocity_or_incomplete_graph_claims_and_no_link_truncation(): + assert estimate_domain_authority('google.com.attacker.example') is None + assert estimate_domain_authority('google.com') is None + body = ''.join(f'Page {index}' for index in range(220)) + result = analyze_links(document(body), URL) + assert len(result['data']['internal_links']) == 220 + assert result['data']['link_velocity']['links_per_day'] is None + assert result['data']['internal_structure']['orphan_pages'] is None + assert result['data']['link_health_status'] == 'not_checked' + assert result['data']['broken_links'] is None + assert not any('toxic' in issue['message'] or 'velocity' in issue['message'] for issue in result['issues']) + + +def test_header_hints_do_not_fabricate_protocol_caching_or_security_failures(): + headers = {'Alt-Svc': 'h3=":443"', 'Cache-Control': 'no-cache, max-age=600', + 'Content-Security-Policy': "default-src 'self'; style-src 'unsafe-inline'; frame-ancestors 'none'"} + indicators = analyze_performance_indicators(headers) + assert indicators.protocol_version.value == 'Unknown' + assert indicators.cache_ttl == 600 + assert indicators.compression_ratio is None + assert indicators.server_push_enabled is None + result = analyze_technical(document(), URL, headers=headers) + messages = [issue['message'] for issue in result['issues']] + assert 'No caching configured' not in messages + assert 'CSP allows unsafe-inline scripts' not in messages + assert 'Missing X-Frame-Options header' not in messages + + +def test_absent_header_measurement_is_unknown(): + result = analyze_technical(document(), URL, headers=None) + assert result['data']['security']['hsts'] is None + assert result['data']['security']['source'] == 'not_measured' + assert not any('Missing HSTS' in issue['message'] or 'Content not compressed' in issue['message'] for issue in result['issues']) + + +def test_no_deprecated_rich_result_recommendations(): + soup = document('

FAQ and how to guide

Frequently asked questions and step by step answers.

') + seo = analyze_seo(soup, URL) + content = analyze_content(soup, URL) + suggested = json.dumps(seo['data']['opportunities']) + json.dumps(content['data'].get('schema_suggestions', [])) + assert 'FAQPage' not in suggested + assert 'How-To' not in suggested + assert '50%' not in suggested + + +@pytest.mark.parametrize('analyzer', [analyze_content, analyze_seo, analyze_technical, analyze_performance, analyze_links]) +def test_analyzer_result_is_strict_json_and_input_is_not_mutated(analyzer): + soup = document('

Page heading for this example

Next page') + before = str(soup) + result = analyzer(soup, URL) + assert set(('score', 'issues', 'data', 'recommendations')) <= result.keys() + json.dumps(result, allow_nan=False) + assert str(soup) == before diff --git a/tests/test_app.py b/tests/test_app.py new file mode 100644 index 0000000..7b3a692 --- /dev/null +++ b/tests/test_app.py @@ -0,0 +1,271 @@ +import asyncio +import copy + +import pytest +from bs4 import BeautifulSoup + +from tfq0seo.core.app import AnalysisCache, AnalysisMode, SEOAnalyzer +from tfq0seo.core.config import Config +from tfq0seo.core.report_optimizer import aggregate_issues, generate_performance_metrics + + +def page(url='https://example.test/', title='Example', body='

Example

'): + html = f'{title}{body}' + return {'url': url, 'status_code': 200, 'soup': BeautifulSoup(html, 'html.parser'), + 'headers': {}, 'load_time': 0.2, 'content_length': len(html.encode('utf-8'))} + + +def config(**crawler): + return Config.from_dict({'crawler': {'use_sitemap': False, 'respect_robots_txt': False, + 'max_retries': 0, **crawler}}) + + +def test_analysis_mode_and_enabled_selection(): + cfg = Config.from_dict({'profile': 'quick'}) + analyzer = SEOAnalyzer(cfg) + result = asyncio.run(analyzer.analyze_page(page())) + assert analyzer.mode == AnalysisMode.QUICK + assert 'seo' in result and 'technical' in result + assert 'performance' not in result + assert result['coverage']['failed_analyzers'] == [] + + +def test_configured_weights_are_used_without_double_penalty(): + cfg = Config.from_dict({'analysis': {'score_weights': {'seo': 0.8, 'content': 0.2}}}) + analyzer = SEOAnalyzer(cfg) + assert analyzer._calculate_weighted_score({'seo': {'score': 100}, 'content': {'score': 0}}) == 80 + assert analyzer._calculate_weighted_score({'seo': {'score': None, 'error': 'failed'}}) is None + + +def test_analyzer_exception_is_not_a_zero_website_score(monkeypatch): + def fail(*args, **kwargs): + raise TypeError('implementation failure') + monkeypatch.setattr('tfq0seo.core.app.analyze_content', fail) + result = asyncio.run(SEOAnalyzer(config()).analyze_page(page())) + assert result['status'] == 'partial' + assert result['content']['score'] is None + assert result['analyzer_errors']['content'] == 'implementation failure' + assert result['coverage']['ratio'] == 0.8 + assert result['content']['issues'] == [] + + +def test_cache_tracks_content_and_does_not_share_mutable_results(): + async def run(): + analyzer = SEOAnalyzer(config()) + first = await analyzer.analyze_page(page()) + first['seo']['data']['title']['text'] = 'Mutated' + cached = await analyzer.analyze_page(page()) + changed = await analyzer.analyze_page(page(title='Changed')) + assert cached['cached'] is True + assert cached['seo']['data']['title']['text'] == 'Example' + assert changed['seo']['data']['title']['text'] == 'Changed' + assert not changed.get('cached') + asyncio.run(run()) + + +def test_cache_obeys_size_and_expiry(): + cache = AnalysisCache(ttl_seconds=0) + cache.set('a', {'score': 90}) + assert cache.get('a') is None + cache = AnalysisCache(max_bytes=1) + cache.set('a', {'score': 90}) + assert not cache.cache + + +def test_report_is_complete_consistent_and_does_not_mutate_inputs(): + pages = [{'url': f'https://example.test/{i}', 'status_code': 200, 'status': 'complete', + 'overall_score': 90, 'seo': {'score': 90}, 'load_time': 2, + 'issues': [{'severity': 'warning', 'category': 'SEO', 'message': 'Example finding'}]} + for i in range(500)] + original = copy.deepcopy(pages) + report = SEOAnalyzer(config()).generate_site_report(pages) + assert len(report['pages']['summary']) == len(report['pages']['detailed']) == 500 + assert report['issues']['counts']['total'] == 500 + assert report['issues']['aggregated'][0]['pages_affected'] == 500 + assert report['recommendations']['executive']['overview']['overall_score'] == report['scores']['overall'] == 90 + assert report['recommendations']['executive']['key_metrics']['total_issues'] == 500 + assert pages == original + + +def test_broken_links_resolve_after_target_is_analyzed(): + async def run(): + analyzer = SEOAnalyzer(config()) + home = await analyzer.analyze_page(page(body='

Example

Missing')) + failure = await analyzer.analyze_page({'url': 'https://example.test/missing', + 'status_code': 404, 'error': 'HTTP 404'}) + report = analyzer.generate_site_report([home, failure]) + updated = report['pages']['detailed'][0] + assert updated['links']['data']['link_health']['broken'] == 1 + issue = next(item for item in updated['issues'] if item.get('rule_id') == 'links.broken') + assert issue['evidence']['http_statuses']['https://example.test/missing'] == 404 + assert report['status'] == 'partial' + assert report['summary']['failed_pages'] == 1 + assert len(report['pages']['failed']) == 1 + asyncio.run(run()) + + +def test_http_statuses_and_even_median_are_preserved(): + metrics = generate_performance_metrics([{'load_time': 1, 'status_code': 200}, + {'load_time': 3, 'status_code': 404, 'error': 'HTTP 404'}]) + assert metrics['status_codes'][404] == 1 + assert metrics['load_time_stats']['median'] == 2 + + +def test_rule_aggregation_retains_unique_page_evidence(): + issues = [{'rule_id': 'seo.title', 'message': str(i), 'category': 'SEO', 'severity': 'warning', + 'url': f'https://example.test/{i}'} for i in range(8)] + aggregated, stats = aggregate_issues(issues) + assert len(aggregated) == 1 + assert len(aggregated[0]['pages']) == 8 + assert len(aggregated[0]['example_pages']) == 5 + assert stats['total_issues'] == 8 + + +def test_repeated_runs_do_not_mix_results(http_site): + base, routes, _ = http_site + routes['/first'] = (200, {'Content-Type': 'text/html'}, 'First

First

') + routes['/second'] = (200, {'Content-Type': 'text/html'}, 'Second

Second

') + async def run(): + analyzer = SEOAnalyzer(config(max_concurrent=1)) + await analyzer.analyze_url(base + '/first') + await analyzer.analyze_url(base + '/second') + assert len(analyzer.results) == analyzer.stats.total_pages == 1 + assert analyzer.results[0]['url'].endswith('/second') + asyncio.run(run()) + + +def test_crawl_at_one_concurrent_request_finishes(http_site): + base, routes, _ = http_site + routes['/'] = (200, {'Content-Type': 'text/html'}, 'Home

Home

Child') + routes['/child'] = (200, {'Content-Type': 'text/html'}, 'Child

Child

') + async def run(): + analyzer = SEOAnalyzer(config(max_concurrent=1, max_pages=2)) + results = [item async for item in analyzer.crawl_site(base + '/')] + assert len(results) == 2 + assert analyzer.generate_site_report()['summary']['crawl_complete'] + asyncio.run(asyncio.wait_for(run(), timeout=10)) + + +def test_batch_deduplicates_fetch_identity_before_applying_page_limit(http_site): + base, routes, requests = http_site + routes['/a'] = routes['/b'] = (200, {'Content-Type': 'text/html'}, 'Page

Page

') + async def run(): + analyzer = SEOAnalyzer(config(max_pages=2)) + results = [result async for result in analyzer.analyze_urls( + [base + '/a#one', base + '/a#two', base + '/b'])] + assert len(results) == 2 + assert all(result['status'] == 'complete' for result in results) + assert {result['url'] for result in results} == {base + '/a', base + '/b'} + assert sorted(requests) == ['/a', '/b'] + asyncio.run(run()) + + +def test_explicit_sitemap_preserves_failed_child_discovery_coverage(http_site): + base, routes, _ = http_site + routes['/index.xml'] = (200, {'Content-Type': 'application/xml'}, + '/pages.xml' + '/broken.xml') + routes['/pages.xml'] = (200, {'Content-Type': 'application/xml'}, + '/one') + routes['/broken.xml'] = (200, {'Content-Type': 'application/xml'}, 'One

One

') + async def run(): + analyzer = SEOAnalyzer(config()) + results = await analyzer.analyze_sitemap(base + '/index.xml') + assert len(results) == 1 and results[0]['status'] == 'complete' + summary = analyzer.generate_site_report()['summary'] + assert any(error['url'] == base + '/broken.xml' for error in summary['discovery_errors']) + assert summary['crawl_complete'] is False + asyncio.run(run()) + + +def test_explicit_sitemap_page_cap_is_visible_in_report(http_site): + base, routes, requests = http_site + routes['/sitemap.xml'] = (200, {'Content-Type': 'application/xml'}, + '/one/two') + routes['/one'] = routes['/two'] = (200, {'Content-Type': 'text/html'}, 'Page

Page

') + async def run(): + analyzer = SEOAnalyzer(config(max_pages=1)) + results = await analyzer.analyze_sitemap(base + '/sitemap.xml') + assert len(results) == 1 + assert '/two' not in requests + summary = analyzer.generate_site_report()['summary'] + assert 'max_pages' in summary['limits_reached'] + assert summary['crawl_complete'] is False + asyncio.run(run()) + + +def test_external_link_error_cancels_and_awaits_sibling_fetches(monkeypatch): + async def run(): + analyzer = SEOAnalyzer(config(max_concurrent=2)) + analyzer.results = [{'links': {'data': {'external_links': [ + {'url': 'https://example.test/fail'}, + {'url': 'https://example.test/pending'}, + ]}}}] + started = asyncio.Event() + pending = set() + + async def fetch(crawler, url): + if url.endswith('/fail'): + await started.wait() + raise RuntimeError('Fixture unexpected fetch failure') + task = asyncio.current_task() + pending.add(task) + started.set() + try: + await asyncio.Event().wait() + finally: + pending.discard(task) + + monkeypatch.setattr('tfq0seo.core.app.Crawler.fetch_page', fetch) + try: + with pytest.raises(RuntimeError, match='unexpected fetch failure'): + await analyzer._check_external_links() + assert not pending + finally: + # Keep the regression bounded even if cleanup regresses. + leftovers = list(pending) + for task in leftovers: + task.cancel() + await asyncio.gather(*leftovers, return_exceptions=True) + asyncio.run(asyncio.wait_for(run(), 2)) + + +def test_malformed_explicit_sitemap_returns_error_report(http_site): + base, routes, requests = http_site + routes['/broken.xml'] = (200, {'Content-Type': 'application/xml'}, 'Fixture title{body}', 'html.parser')} + + +def only_analyzer(name, **analysis): + return Config.from_dict({'analysis': {'enabled_analyzers': [name], 'score_weights': {name: 1.0}, **analysis}}) + + +def test_cli_environment_profile_changes_effective_behavior(monkeypatch): + monkeypatch.setenv('TFQ0SEO_PROFILE', 'quick') + config = _configuration(None) + assert config.profile == ConfigProfile.QUICK + assert config.analysis.analysis_mode == 'quick' + assert config.analysis.enabled_analyzers == ['seo', 'technical'] + assert config.crawler.max_pages == 50 + + +def test_environment_alias_overrides_default_canonical_concurrency(monkeypatch): + monkeypatch.setenv('TFQ0SEO_CRAWLER_CONCURRENT_REQUESTS', '2') + config = _configuration(None) + assert config.crawler.effective_concurrency == 2 + assert _configuration(None, max_concurrent=3).crawler.effective_concurrency == 3 + + +@pytest.mark.parametrize(('name', 'value', 'attribute'), [ + ('TFQ0SEO_EXPORT_OUTPUT_DIRECTORY', 'reports,archive', 'output_directory'), + ('TFQ0SEO_EXPORT_FILENAME_PATTERN', '12345', 'filename_pattern'), +]) +def test_string_environment_values_are_not_coerced_to_other_types(monkeypatch, name, value, attribute): + monkeypatch.setenv(name, value) + assert getattr(Config.from_env().export, attribute) == value + + +def test_explicit_constructor_component_precedes_profile_defaults(): + config = Config(profile=ConfigProfile.QUICK, crawler=CrawlerConfig(max_pages=17)) + assert config.crawler.max_pages == 17 + + +def test_empty_effective_quick_selection_is_rejected_before_fetching(): + with pytest.raises(ValueError): + SEOAnalyzer(only_analyzer('links', analysis_mode='quick')) + + +def test_cache_keeps_new_fetch_timing_observations(): + async def run(): + analyzer = SEOAnalyzer(only_analyzer('seo')) + first = raw_page() + first['timings'] = {'ttfb': 0.1, 'body': 0.4} + await analyzer.analyze_page(first) + second = dict(first, timings={'ttfb': 0.3, 'body': 0.2}) + result = await analyzer.analyze_page(second) + assert result['timings'] == second['timings'] + asyncio.run(run()) + + +def test_resolved_broken_links_update_scores_consistently(): + async def run(): + analyzer = SEOAnalyzer(only_analyzer('links')) + source = raw_page(body='

Fixture

Missing page') + page = await analyzer.analyze_page(source) + failure = await analyzer.analyze_page({'url': 'https://example.test/missing', 'status_code': 404, 'error': 'HTTP 404'}) + expected = analyze_links(source['soup'], source['url'], broken_links={failure['url']})['score'] + report = analyzer.generate_site_report([page, failure]) + resolved = report['pages']['detailed'][0] + assert resolved['links']['score'] == expected + assert resolved['overall_score'] == expected + assert report['scores']['overall'] == expected + assert len([issue for issue in resolved['issues'] if issue.get('rule_id') == 'links.broken']) == 1 + # Regenerating a report must not compound the penalty or mutate input records. + original = copy.deepcopy(resolved) + second = analyzer.generate_site_report([resolved, failure]) + assert second['scores']['overall'] == expected + assert resolved == original + asyncio.run(run()) + + +def test_closing_batch_generator_cancels_fetches_before_session_exit(monkeypatch): + exits = [] + active = set() + + class FakeCrawler: + def __init__(self, config): + pass + + async def __aenter__(self): + return self + + async def __aexit__(self, *args): + exits.append(len(active)) + + async def fetch_page(self, url): + task = asyncio.current_task() + active.add(task) + try: + if url.endswith('/ready'): + await asyncio.sleep(0) + return {'url': url, 'error': 'Completed fixture request'} + await asyncio.Event().wait() + finally: + active.discard(task) + + monkeypatch.setattr('tfq0seo.core.app.Crawler', FakeCrawler) + + async def run(): + config = Config.from_dict({'crawler': {'max_concurrent': 2}}) + analyzer = SEOAnalyzer(config) + generator = analyzer.analyze_urls(['https://example.test/ready', 'https://example.test/pending']) + try: + await asyncio.wait_for(generator.__anext__(), timeout=1) + await generator.aclose() + assert exits == [0] + finally: + # Ensure a regression cannot leave fixture tasks alive after the test. + pending = list(active) + for task in pending: + task.cancel() + await asyncio.gather(*pending, return_exceptions=True) + await generator.aclose() + asyncio.run(run()) + + +def test_cancelled_analyzers_keep_running_work_within_thread_limit(): + first_started = threading.Event() + release = threading.Event() + lock = threading.Lock() + counts = {'active': 0, 'maximum': 0} + + def blocking_analyzer(): + with lock: + counts['active'] += 1 + counts['maximum'] = max(counts['maximum'], counts['active']) + first_started.set() + try: + release.wait(timeout=2) + return {'score': 100, 'issues': []} + finally: + with lock: + counts['active'] -= 1 + + async def run(): + analyzer = SEOAnalyzer(only_analyzer('seo', max_analysis_threads=1)) + first = asyncio.create_task(analyzer._run_analyzer_safe('seo', blocking_analyzer)) + second = None + try: + for _ in range(100): + if first_started.is_set(): + break + await asyncio.sleep(0.005) + assert first_started.is_set() + first.cancel() + with pytest.raises(asyncio.CancelledError): + await first + second = asyncio.create_task(analyzer._run_analyzer_safe('seo', blocking_analyzer)) + await asyncio.sleep(0.05) + finally: + release.set() + await asyncio.gather(*([second] if second else []), return_exceptions=True) + if not first.done(): + first.cancel() + await asyncio.gather(first, return_exceptions=True) + assert counts['maximum'] == 1 + asyncio.run(run()) diff --git a/tests/test_benchmark.py b/tests/test_benchmark.py new file mode 100644 index 0000000..6022dbc --- /dev/null +++ b/tests/test_benchmark.py @@ -0,0 +1,323 @@ +"""Benchmark outcomes use controlled fixtures, never public web targets.""" + +import asyncio +import json +import socket +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest + +from tfq0seo import benchmark + + +@pytest.mark.parametrize('result', [None, {}, {'url': 'https://example.test/', 'status': 'error', 'error': 'Timed out'}]) +def test_failed_single_analysis_never_becomes_successful_throughput(monkeypatch, result): + analyzer = SimpleNamespace(analyze_url=AsyncMock(return_value=result)) + monkeypatch.setattr(benchmark, 'SEOAnalyzer', lambda config: analyzer) + measured = asyncio.run(benchmark.benchmark_single_page('https://example.test/')) + assert measured['status'] == 'failed' + assert measured['successful_pages'] == measured['pages_analyzed'] == 0 + assert measured['failed_pages'] == 1 + assert measured['pages_per_second'] == 0 + assert measured['avg_time_per_page'] is None + + +def test_batch_counts_outcomes_and_uses_monotonic_elapsed_time(monkeypatch): + class Analyzer: + def __init__(self, config): + pass + + async def analyze_urls(self, urls): + yield {'url': urls[0], 'status': 'complete', 'overall_score': 90} + yield {'url': urls[1], 'status': 'partial', 'analyzer_errors': {'seo': 'Fixture failure'}} + yield {'url': urls[2], 'status': 'error', 'error': 'Fixture timeout'} + yield {'url': urls[3], 'status': 'skipped', 'skipped': True} + + monkeypatch.setattr(benchmark, 'SEOAnalyzer', Analyzer) + clock = iter([1000.0, 1002.0]) + monkeypatch.setattr(benchmark.time, 'perf_counter', lambda: next(clock)) + urls = [f'https://example.test/{index}' for index in range(4)] + result = asyncio.run(benchmark.benchmark_batch(urls)) + assert result['status'] == 'failed' + assert result['successful_pages'] == result['partial_pages'] == result['failed_pages'] == result['skipped_pages'] == 1 + assert result['observed_results'] == 4 + assert result['duration_seconds'] == 2 + assert result['pages_per_second'] == 0.5 + assert result['clock'] == 'perf_counter' + assert set(result['errors']) == {'Fixture failure', 'Fixture timeout'} + + +def test_exception_preserves_already_recorded_outcomes(monkeypatch): + class Analyzer: + def __init__(self, config): + pass + + async def crawl_site(self, url): + yield {'url': url, 'status': 'complete', 'overall_score': 90} + raise TimeoutError('Fixture crawl interrupted') + + monkeypatch.setattr(benchmark, 'SEOAnalyzer', Analyzer) + result = asyncio.run(benchmark.benchmark_crawl('https://example.test/')) + assert result['status'] == 'failed' + assert result['successful_pages'] == 1 + assert result['observed_results'] == 1 + assert result['errors'] == ['TimeoutError: Fixture crawl interrupted'] + + +def test_missing_batch_results_are_incomplete(monkeypatch): + class Analyzer: + def __init__(self, config): + pass + + async def analyze_urls(self, urls): + yield {'url': urls[0], 'status': 'complete', 'overall_score': 90} + + monkeypatch.setattr(benchmark, 'SEOAnalyzer', Analyzer) + result = asyncio.run(benchmark.benchmark_batch(['https://example.test/one', 'https://example.test/two'])) + assert result['status'] == 'partial' + assert result['missing_results'] == 1 + + +def test_offline_fixture_measures_analysis_and_reporting_without_fetches(monkeypatch): + async def forbid(*args, **kwargs): + raise AssertionError('Offline benchmark must not fetch a URL') + + monkeypatch.setattr('tfq0seo.core.app.Crawler.fetch_page', forbid) + result = asyncio.run(benchmark.benchmark_offline(3)) + assert result['status'] == 'complete' + assert result['successful_pages'] == result['report_pages'] == 3 + assert result['network_access'] is False + assert result['fixture_version'] == 1 + assert result['memory_sample_count'] >= 2 + assert result['memory_sampled_peak_mb'] >= result['memory_rss_start_mb'] + assert result['memory_sampled_peak_mb'] >= result['memory_rss_end_mb'] + assert result['memory_rss_delta_mb'] == pytest.approx(result['memory_rss_end_mb'] - result['memory_rss_start_mb'], abs=0.002) + assert 'between samples may be missed' in result['memory_measurement'] + assert 'memory_peak_mb' not in result + + +def test_default_suite_uses_500_offline_pages_and_saves_metrics(tmp_path, monkeypatch, capsys): + calls = [] + + async def offline(page_count): + calls.append(page_count) + return {'status': 'complete', 'successful_pages': page_count, 'type': 'offline'} + + async def forbidden(*args, **kwargs): + raise AssertionError('Default benchmark unexpectedly uses a network workload') + + monkeypatch.setattr(benchmark, 'benchmark_offline', offline) + for name in ('benchmark_single_page', 'benchmark_batch', 'benchmark_crawl'): + monkeypatch.setattr(benchmark, name, forbidden) + path = tmp_path / 'benchmark.json' + result = asyncio.run(benchmark.run_all_benchmarks(output_file=str(path))) + assert calls == [500] + assert result['status'] == 'complete' + assert json.loads(path.read_text(encoding='utf-8')) == result + assert benchmark.compare_with_targets() == {} + assert 'grade' not in capsys.readouterr().out.lower() + + +@pytest.mark.parametrize(('status', 'expected_exit'), [('complete', 0), ('partial', 1), ('failed', 1)]) +def test_cli_exit_code_reflects_benchmark_status(tmp_path, monkeypatch, status, expected_exit): + async def offline(page_count): + return {'status': status, 'successful_pages': 0, 'type': 'offline'} + + monkeypatch.setattr(benchmark, 'benchmark_offline', offline) + path = tmp_path / 'outcome.json' + assert benchmark.main(['--pages', '2', '--output', str(path)]) == expected_exit + assert json.loads(path.read_text(encoding='utf-8'))['status'] == status + + +def test_cli_exceptions_return_failure(monkeypatch, capsys): + async def fail(*args, **kwargs): + raise RuntimeError('Fixture setup failed') + + monkeypatch.setattr(benchmark, 'run_all_benchmarks', fail) + assert benchmark.main([]) == 1 + assert 'Fixture setup failed' in capsys.readouterr().err + + +@pytest.mark.parametrize('pages', [0, -1]) +def test_invalid_fixture_size_is_rejected(pages): + with pytest.raises(ValueError, match='positive integer'): + asyncio.run(benchmark.benchmark_offline(pages)) + with pytest.raises(SystemExit) as failure: + benchmark.main(['--pages', str(pages)]) + assert failure.value.code == 2 + + +@pytest.mark.parametrize('scenario', benchmark.SCENARIOS) +def test_varied_fixtures_are_reproducible_complete_and_offline(monkeypatch, scenario): + attempts = [] + + def no_dns(*args, **kwargs): + attempts.append(args) + raise AssertionError('Offline fixtures must not resolve network addresses') + + async def no_fetch(*args, **kwargs): + attempts.append(args) + raise AssertionError('Offline fixtures must not fetch any resources') + + monkeypatch.setattr(socket, 'getaddrinfo', no_dns) + monkeypatch.setattr('tfq0seo.core.app.Crawler.fetch_page', no_fetch) + first = asyncio.run(benchmark.benchmark_offline(3, scenario)) + second = asyncio.run(benchmark.benchmark_offline(3, scenario)) + assert attempts == [] + assert first['status'] == second['status'] == 'complete' + assert first['fixture'] == second['fixture'] + assert len(first['fixture']['sha256']) == 64 + assert first['fixture']['generated_pages'] == 3 + assert first['fixture']['pages_with_word_count'] == 3 + assert sum(first['readability']['status_counts'].values()) == 3 + assert first['report_completeness'] == { + 'expected_pages': 3, 'retained_rows': 3, 'unique_urls': 3, 'missing_urls': 0, + 'unexpected_urls': 0, 'duplicate_rows': 0, 'complete': True, + } + assert first['analysis_duration_seconds'] > 0 + assert first['report_duration_seconds'] > 0 + assert first['config']['crawler']['cache_enabled'] is False + assert first['config']['crawler']['max_pages'] == 3 + assert first['site_analysis']['node_count'] == 3 + if scenario == 'content-heavy': + assert first['fixture']['image_elements'] == 24 + assert first['fixture']['html_bytes'] > 20000 + assert first['fixture']['analyzed_word_count'] > 3000 + elif scenario == 'link-dense': + assert first['fixture']['href_references'] == 117 + elif scenario == 'mixed': + assert first['fixture']['variants'] == {'basic': 1, 'content-heavy': 1, 'link-dense': 1} + + +def test_report_duplicate_urls_fail_even_when_row_count_matches(monkeypatch): + class Analyzer: + def __init__(self, config): + pass + + async def analyze_page(self, page): + return {'url': page['url'], 'status': 'complete', 'overall_score': 90} + + def generate_site_report(self, pages): + return {'status': 'complete', 'pages': {'detailed': [pages[0], pages[0]]}} + + monkeypatch.setattr(benchmark, 'SEOAnalyzer', Analyzer) + result = asyncio.run(benchmark.benchmark_offline(2)) + assert result['successful_pages'] == result['report_pages'] == 2 + assert result['status'] == 'failed' + assert result['report_completeness']['duplicate_rows'] == 1 + assert result['report_completeness']['missing_urls'] == 1 + assert 'expected fixture URLs' in result['errors'][0] + + +def test_offline_timeout_preserves_observed_results_and_reports_failure(monkeypatch): + class Analyzer: + def __init__(self, config): + self.calls = 0 + + async def analyze_page(self, page): + self.calls += 1 + if self.calls > 1: + await asyncio.sleep(1) + return {'url': page['url'], 'status': 'complete', 'overall_score': 90} + + monkeypatch.setattr(benchmark, 'SEOAnalyzer', Analyzer) + result = asyncio.run(benchmark.benchmark_offline(3, timeout_seconds=0.05)) + assert result['status'] == 'failed' + assert result['timed_out'] is True + assert result['successful_pages'] == result['observed_results'] == 1 + assert result['missing_results'] == 2 + assert result['report_completeness'] is None + assert 'deadline' in result['errors'][0] + + +def test_suite_records_repeat_order_and_excludes_incomplete_runs_from_metrics(tmp_path, monkeypatch): + calls = [] + + async def offline(page_count, scenario='basic', timeout_seconds=None): + calls.append((page_count, scenario, timeout_seconds)) + return {'status': 'partial' if len(calls) == 2 else 'complete', 'successful_pages': page_count, + 'duration_seconds': 100 if len(calls) == 2 else 2, 'pages_per_second': page_count / 2} + + monkeypatch.setattr(benchmark, 'benchmark_offline', offline) + result = asyncio.run(benchmark.run_all_benchmarks( + output_file=str(tmp_path / 'suite.json'), scenarios=['mixed', 'basic'], page_counts=[3, 5], + repetitions=2, timeout_seconds=10)) + assert calls == [(size, scenario, 10) for size in (3, 5) for scenario in ('mixed', 'basic') for _ in range(2)] + assert result['status'] == 'partial' + assert [run['run_order'] for run in result['benchmarks']] == list(range(1, 9)) + assert [run['repetition'] for run in result['benchmarks']] == [1, 2] * 4 + summary = result['summaries'][0] + assert summary['runs'] == 2 and summary['complete_runs'] == summary['partial_runs'] == 1 + assert summary['metrics']['duration_seconds'] == {'median': 2, 'min': 2, 'max': 2} + assert result['suite']['repetitions'] == 2 + assert 'Same process' in result['suite']['isolation'] + + +def test_environment_records_dependency_versions_and_implementation(monkeypatch): + def installed(name): + if name == 'openpyxl': + raise benchmark.importlib_metadata.PackageNotFoundError(name) + return 'fixture-version' + + monkeypatch.setattr(benchmark.importlib_metadata, 'version', installed) + environment = benchmark._environment() + assert set(environment['direct_dependencies']) == set(benchmark.DIRECT_DEPENDENCIES) + assert all(value == 'fixture-version' for value in environment['direct_dependencies'].values()) + assert environment['optional_dependencies']['openpyxl'] is None + assert environment['schema_version'] == benchmark.SCHEMA_VERSION + assert environment['ruleset_version'] == benchmark.RULESET_VERSION + assert environment['facts_version'] == benchmark.FACTS_VERSION + assert environment['package_version'] == benchmark.__version__ + assert environment['os']['system'] and environment['architecture'] + assert environment['cpu_count'] > 0 + assert environment['source_fingerprint']['file_count'] > 0 + assert len(environment['source_fingerprint']['digest']) == 64 + json.dumps(environment, allow_nan=False) + + +def test_changed_source_during_suite_invalidates_comparison(tmp_path, monkeypatch): + fingerprints = iter([{'digest': 'before'}, {'digest': 'after'}]) + monkeypatch.setattr(benchmark, '_source_fingerprint', lambda: next(fingerprints)) + monkeypatch.setattr(benchmark, 'benchmark_offline', AsyncMock(return_value={'status': 'complete'})) + result = asyncio.run(benchmark.run_all_benchmarks(1, str(tmp_path / 'changed.json'))) + assert result['source_unchanged_during_suite'] is False + assert result['status'] == 'failed' + + +def test_cli_accepts_scenarios_sizes_repetitions_and_deadline(tmp_path, monkeypatch): + run = AsyncMock(return_value={'status': 'complete'}) + monkeypatch.setattr(benchmark, 'run_all_benchmarks', run) + path = str(tmp_path / 'suite.json') + assert benchmark.main(['--suite', '--pages', '500', '2000', '--repetitions', '3', + '--timeout-seconds', '600', '--output', path]) == 0 + run.assert_awaited_once_with(500, path, page_counts=[500, 2000], scenarios=benchmark.SCENARIOS, + repetitions=3, timeout_seconds=600) + + +@pytest.mark.parametrize('options', [ + {'scenario': 'missing'}, {'timeout_seconds': float('nan')}, {'timeout_seconds': float('inf')}, + {'timeout_seconds': 0}, {'timeout_seconds': True}, +]) +def test_invalid_offline_options_are_rejected(options): + with pytest.raises(ValueError): + asyncio.run(benchmark.benchmark_offline(1, **options)) + + +@pytest.mark.parametrize('options', [ + {'scenarios': []}, {'page_counts': []}, {'repetitions': 0}, {'repetitions': True}, + {'scenarios': ['basic', 'basic']}, {'page_counts': [500, 500]}, +]) +def test_invalid_suite_options_are_rejected_before_running(options): + with pytest.raises(ValueError): + asyncio.run(benchmark.run_all_benchmarks(**options)) + + +@pytest.mark.parametrize('args', [ + ['--suite', '--scenario', 'mixed'], ['--repetitions', '0'], ['--timeout-seconds', 'nan'], + ['--timeout-seconds', 'inf'], ['--timeout-seconds', '-1'], +]) +def test_invalid_suite_cli_options_exit_two(args): + with pytest.raises(SystemExit) as failure: + benchmark.main(args) + assert failure.value.code == 2 diff --git a/tests/test_canonical_facts.py b/tests/test_canonical_facts.py new file mode 100644 index 0000000..ca1f757 --- /dev/null +++ b/tests/test_canonical_facts.py @@ -0,0 +1,178 @@ +"""Canonical observations preserve context and uncertainty without raw headers.""" + +import json + +import pytest +from bs4 import BeautifulSoup +from multidict import CIMultiDict + +from tfq0seo.page_facts import FACTS_VERSION, extract_page_facts + + +URL = 'https://example.test/articles/page?view=all' + + +def facts(head='', body='', headers=None): + soup = BeautifulSoup('' + head + '' + body + '', 'html.parser') + return extract_page_facts(soup, URL, headers) + + +def test_html_canonical_records_keep_all_declarations_and_head_placement(): + observed = facts('' + '' + '', + '') + declarations = observed.canonical['declarations'] + assert [item['url'] for item in declarations] == [ + 'https://cdn.test/base/child//?x=1&x=2&empty=#part', + 'https://cdn.test/second', 'https://cdn.test/body'] + assert [item['eligible'] for item in declarations] == [True, True, False] + assert declarations[-1]['reason'] == 'HTML canonical declaration is outside the head.' + assert [link['in_head'] for link in observed.link_tags] == [True, True, False] + assert all(item['source'] == 'html' for item in declarations) + assert observed.canonical['parse_errors'] == 0 + + +@pytest.mark.parametrize('attribute', ['hreflang="en"', 'lang="en"', 'media="all"', 'type="text/html"', + 'hreflang', 'TYPE=""']) +def test_alternate_html_attributes_make_declaration_ineligible(attribute): + declaration = facts('').canonical['declarations'][0] + assert declaration['url'] == 'https://example.test/target' + assert declaration['eligible'] is False + assert 'alternate-version attributes' in declaration['reason'] + + +@pytest.mark.parametrize('href', [None, '', ' ', 'javascript:alert(1)', 'mailto:user@example.test', + 'https://[', 'https://example.test:wrong/', '/bad%xx', '/two words']) +def test_invalid_html_targets_keep_raw_evidence_without_graph_edges(href): + soup = BeautifulSoup('', 'html.parser') + if href is not None: + soup.link['href'] = href + observation = extract_page_facts(soup, URL).canonical + assert observation['declarations'] == [{ + 'href': href, 'url': None, 'source': 'html', 'eligible': False, + 'reason': 'Canonical target is missing or is not a valid HTTP(S) URL.'}] + assert observation['parse_errors'] == 0 # Parsed HTML observation, not ambiguous HTTP syntax. + + +@pytest.mark.parametrize('headers,checked', [(None, False), ({}, True), ({'Link': ''}, True)]) +def test_header_observation_state_distinguishes_unknown_and_no_declarations(headers, checked): + assert facts(headers=headers).canonical == {'declarations': [], 'headers_checked': checked, 'parse_errors': 0} + + +def test_repeated_http_link_fields_use_response_base_and_preserve_reference_semantics(): + observed = facts('', headers=CIMultiDict([ + ('Link', '; rel=canonical'), + ('link', '; ReL="alternate CANONICAL"'), + ])) + assert observed.canonical == {'declarations': [ + {'href': 'next//?x=1&x=2&empty=#part', + 'url': 'https://example.test/articles/next//?x=1&x=2&empty=#part', + 'source': 'http_link', 'eligible': True, 'reason': ''}, + {'href': 'https://EXAMPLE.test:443/second', 'url': 'https://example.test/second', + 'source': 'http_link', 'eligible': True, 'reason': ''}], + 'headers_checked': True, 'parse_errors': 0} + + +def test_http_commas_semicolons_and_escaped_quotes_do_not_split_link_values(): + header = ('; rel="canonical alternate"; title="text, semi; ' + '\\"quote\\" and \\\\ slash"; x-flag, ' + '; rel=preload; title="canonical, unrelated", ' + '; rel=canonical; title*=UTF-8\'en\'some%20title') + observation = facts(headers={'Link': header}).canonical + assert observation['parse_errors'] == 0 + assert [item['href'] for item in observation['declarations']] == ['/one,two;three?x=1,2', '/last'] + assert all(item['eligible'] for item in observation['declarations']) + + +@pytest.mark.parametrize('anchor,eligible', [ + ('', True), ('?view=all', True), ('https://EXAMPLE.test:443/articles/page?view=all', True), + ('/other', False), ('#part', False), ('https://outside.test/', False), + ('mailto:someone@example.test', False), +]) +def test_anchor_context_is_resolved_against_response_and_never_silently_ignored(anchor, eligible): + observation = facts('', + headers={'Link': '; rel=canonical; anchor="' + anchor + '"'}).canonical + assert observation['parse_errors'] == 0 + assert observation['declarations'][0]['eligible'] is eligible + assert observation['declarations'][0]['url'] == 'https://example.test/canonical' + assert bool(observation['declarations'][0]['reason']) is not eligible + + +def test_empty_http_uri_reference_is_a_valid_self_reference(): + assert facts(headers={'Link': '<>; rel=canonical'}).canonical['declarations'] == [ + {'href': '', 'url': URL, 'source': 'http_link', 'eligible': True, 'reason': ''}] + + +@pytest.mark.parametrize('header', [ + '; rel=canonical; rel=alternate', + '; rel=alternate; rel=canonical', + '; rel=canonical; anchor=""; anchor="/other"', + '; rel=canonical; anchor', + '; rel=canonical; anchor="http://["', + '; rel=canonical; anchor="http://example.test:bad"', + '; rel=canonical; title="unterminated', + '; rel=canonical; title="unterminated\\', + '; rel=canonical; title="control\x01character"', + '; rel=canonical stray', + '; rel=canonical;', + '; rel=canonical; =bad', + '; rel=canonical; title=', + '; rel=canonical', + '; rel=canonical', + '; rel=canonical', +]) +def test_malformed_recognizable_http_canonicals_are_errors_and_never_edges(header): + observation = facts(headers={'Link': header}).canonical + assert observation['parse_errors'] == 1 + assert len(observation['declarations']) == 1 + assert observation['declarations'][0]['eligible'] is False + assert observation['declarations'][0]['reason'] + + +@pytest.mark.parametrize('header', ['not-a-link', ' rel=canonical', '; rel', + '; rel=""', '; rel=" "', '; rel="invalid,relation"', + '; title="canonical"', '; rel=canonical']) +def test_unparseable_link_fields_do_not_claim_reliable_canonical_absence(header): + observation = facts(headers={'Link': header}).canonical + assert observation['parse_errors'] == 1 + assert observation['declarations'] == [] + assert observation['headers_checked'] is True + + +def test_bad_field_does_not_discard_other_independently_parseable_fields(): + observation = facts(headers={'Link': [ + '; rel=canonical, ; rel=canonical; title="unclosed, ; rel=canonical', + 'garbage, ; rel=canonical', + ]}).canonical + assert observation['parse_errors'] == 2 + assert [(item['href'], item['eligible']) for item in observation['declarations']] == [ + ('/before', True), ('/broken', False), ('/after', True)] + + +@pytest.mark.parametrize('parameter', ['hreflang=en', 'lang=en', 'media="screen, print"', 'type="text/html"']) +def test_http_alternate_parameters_are_retained_as_ignored_canonicals(parameter): + observation = facts(headers={'Link': '; rel=canonical; ' + parameter}).canonical + assert observation['parse_errors'] == 0 + assert observation['declarations'][0]['eligible'] is False + assert 'alternate-version attributes' in observation['declarations'][0]['reason'] + + +def test_canonical_export_is_detached_json_and_excludes_unrelated_header_secrets(): + observed = facts('', headers={ + 'Set-Cookie': 'COOKIE_SECRET', 'Authorization': 'AUTH_SECRET', + 'Link': '; rel=canonical; title="LINK_TITLE_SECRET", ' + '; rel=preload', + }) + expected = observed.canonical + observed.canonical['declarations'][0]['href'] = '/changed' + export = observed.to_dict() + encoded = json.dumps(export, allow_nan=False) + assert export['facts_version'] == FACTS_VERSION == '1.1' + assert export['canonical'] == expected + assert json.loads(encoded) == export + assert 'COOKIE_SECRET' not in encoded and 'AUTH_SECRET' not in encoded + assert 'LINK_TITLE_SECRET' not in encoded and 'UNRELATED_TARGET_SECRET' not in encoded + export['canonical']['declarations'].clear() + assert observed.canonical == expected diff --git a/tests/test_cli.py b/tests/test_cli.py new file mode 100644 index 0000000..042c284 --- /dev/null +++ b/tests/test_cli.py @@ -0,0 +1,119 @@ +import json +from unittest.mock import AsyncMock + +from click.testing import CliRunner + +from tfq0seo.cli import cli + + +def write_config(tmp_path, **crawler): + path = tmp_path / 'config.json' + path.write_text(json.dumps({'profile': 'quick', 'crawler': { + 'respect_robots_txt': False, 'use_sitemap': False, 'max_retries': 0, **crawler}}), encoding='utf-8') + return str(path) + + +def test_failed_analyze_has_nonzero_exit_and_visible_error(monkeypatch): + monkeypatch.setattr('tfq0seo.cli.SEOAnalyzer.analyze_url', AsyncMock(return_value={ + 'url': 'https://example.test', 'status': 'error', 'status_code': 0, + 'error': 'Fixture timeout', 'overall_score': None, 'issues': []})) + result = CliRunner().invoke(cli, ['analyze', 'https://example.test']) + assert result.exit_code == 1 + assert 'Fixture timeout' in result.output + assert 'Unavailable' in result.output + + +def test_partial_analysis_exports_evidence_then_exits_nonzero(tmp_path, monkeypatch): + monkeypatch.setattr('tfq0seo.cli.SEOAnalyzer.analyze_url', AsyncMock(return_value={ + 'url': 'https://example.test', 'status': 'partial', 'overall_score': 80, + 'analyzer_errors': {'content': 'Fixture analyzer failure'}, 'issues': []})) + output = tmp_path / 'partial.json' + result = CliRunner().invoke(cli, ['analyze', 'https://example.test', '-f', 'json', '-o', str(output)]) + assert result.exit_code == 1 + assert json.loads(output.read_text(encoding='utf-8'))['analyzer_errors']['content'] == 'Fixture analyzer failure' + + +def test_config_values_survive_unspecified_cli_defaults(tmp_path, monkeypatch): + captured = {} + async def crawl(self, url): + captured.update(self.config.crawler.as_dict()) + yield {'url': url, 'status_code': 200, 'status': 'complete', 'overall_score': 90, + 'issues': [], 'seo': {'score': 90}} + monkeypatch.setattr('tfq0seo.cli.SEOAnalyzer.crawl_site', crawl) + result = CliRunner().invoke(cli, ['crawl', 'https://example.test', '-c', write_config( + tmp_path, max_depth=1, max_pages=7, max_concurrent=2), '-o', str(tmp_path / 'report.json'), '-f', 'json']) + assert result.exit_code == 0, result.output + assert captured['max_depth'] == 1 + assert captured['max_pages'] == 7 + assert captured['max_concurrent'] == 2 + assert captured['respect_robots_txt'] is False + + +def test_explicit_cli_value_overrides_config(tmp_path, monkeypatch): + captured = {} + async def crawl(self, url): + captured.update(self.config.crawler.as_dict()) + yield {'url': url, 'status_code': 200, 'overall_score': 90, 'issues': []} + monkeypatch.setattr('tfq0seo.cli.SEOAnalyzer.crawl_site', crawl) + result = CliRunner().invoke(cli, ['crawl', 'https://example.test', '-c', write_config(tmp_path, max_pages=7), + '--max-pages', '3', '-o', str(tmp_path / 'report.json'), '-f', 'json']) + assert result.exit_code == 0, result.output + assert captured['max_pages'] == 3 + + +def test_invalid_cli_concurrency_rejected_before_network(tmp_path): + result = CliRunner().invoke(cli, ['crawl', 'https://example.test', '--concurrent', '0', '-o', str(tmp_path / 'x.json')]) + assert result.exit_code == 2 + + +def test_all_cli_workflows_against_local_http(http_site, tmp_path): + base, routes, _ = http_site + for path in ('/one', '/two'): + routes[path] = (200, {'Content-Type': 'text/html'}, f'{path}

{path}

') + routes['/sitemap.xml'] = (200, {'Content-Type': 'application/xml'}, + f'{base}/one{base}/two') + cfg = write_config(tmp_path) + runner = CliRunner() + single = runner.invoke(cli, ['analyze', base + '/one', '-c', cfg, '-f', 'json']) + assert single.exit_code == 0, single.output + assert json.loads(single.output)['url'] == base + '/one' + urls = tmp_path / 'urls.txt' + urls.write_text(f' # comment\n{base}/one\n\n{base}/two\n', encoding='utf-8') + for command, target in [('batch', str(urls)), ('sitemap', base + '/sitemap.xml')]: + output = tmp_path / (command + '.json') + result = runner.invoke(cli, [command, target, '-c', cfg, '-f', 'json', '-o', str(output)]) + assert result.exit_code == 0, result.output + report = json.loads(output.read_text(encoding='utf-8')) + assert report['summary']['total_pages'] == 2 + assert len(report['pages']['detailed']) == 2 + csv_output = output.with_suffix('.csv') + converted = runner.invoke(cli, ['export', '-i', str(output), '-f', 'csv', '-o', str(csv_output)]) + assert converted.exit_code == 0, converted.output + assert csv_output.exists() + + +def test_empty_batch_and_malformed_json_export_fail(tmp_path): + urls = tmp_path / 'empty.txt' + urls.write_text(' # comment\n', encoding='utf-8') + result = CliRunner().invoke(cli, ['batch', str(urls), '-o', str(tmp_path / 'report.json')]) + assert result.exit_code == 1 and 'no URLs' in result.output + invalid = tmp_path / 'invalid.json' + invalid.write_text('[]', encoding='utf-8') + result = CliRunner().invoke(cli, ['export', '-i', str(invalid), '-f', 'csv', '-o', str(tmp_path / 'x.csv')]) + assert result.exit_code == 1 and 'JSON object' in result.output + + +def test_500_page_crawl_keeps_complete_json(http_site, tmp_path): + base, routes, _ = http_site + links = ''.join(f'Page {i}' for i in range(499)) + routes['/'] = (200, {'Content-Type': 'text/html'}, f'Home

Home

{links}') + for i in range(499): + routes[f'/page/{i}'] = (200, {'Content-Type': 'text/html'}, f'Page {i}

Page {i}

') + cfg = write_config(tmp_path, max_pages=500, max_depth=1) + output = tmp_path / 'full.json' + result = CliRunner().invoke(cli, ['crawl', base + '/', '-c', cfg, '-f', 'json', '-o', str(output)]) + assert result.exit_code == 0, result.output + report = json.loads(output.read_text(encoding='utf-8')) + assert report['summary']['total_pages'] == report['summary']['successful_pages'] == 500 + assert len(report['pages']['detailed']) == 500 + assert len({page['url'] for page in report['pages']['detailed']}) == 500 diff --git a/tests/test_config.py b/tests/test_config.py new file mode 100644 index 0000000..c9417b0 --- /dev/null +++ b/tests/test_config.py @@ -0,0 +1,160 @@ +import math + +import pytest + +from tfq0seo.core.config import Config, ConfigProfile, CrawlerConfig + + +def test_profile_precedes_explicit_values(): + cfg = Config.from_dict({'profile': 'quick', 'crawler': {'max_pages': 17}}) + assert cfg.crawler.max_pages == 17 + assert cfg.analysis.analysis_mode == 'quick' + assert cfg.analysis.enabled_analyzers == ['seo', 'technical'] + assert Config(profile=ConfigProfile.DEVELOPMENT).crawler.verify_ssl is True + + +@pytest.mark.parametrize('first', ['quick', 'standard', 'deep', 'enterprise', 'dev']) +@pytest.mark.parametrize('second', ['quick', 'standard', 'deep', 'enterprise', 'dev']) +def test_reapplying_profiles_matches_fresh_profile_defaults(first, second): + cfg = Config(profile=first) + cfg.apply_profile(second) + assert cfg.to_dict() == Config(profile=second).to_dict() + + +def test_apply_profile_replaces_controlled_overrides_and_keeps_unrelated_values(): + cfg = Config.from_dict({ + 'profile': 'quick', 'crawler': {'max_pages': 17, 'user_agent': 'CustomAgent/1.0'}, + 'analysis': {'target_keywords': ['example']}, + }) + cfg.apply_profile('standard') + assert cfg.crawler.max_pages == 500 + assert cfg.analysis.analysis_mode == 'standard' + assert cfg.crawler.user_agent == 'CustomAgent/1.0' + assert cfg.analysis.target_keywords == ['example'] + # Applying a preset explicitly must not resurrect the old max_pages later. + assert cfg.merge({'profile': 'deep'}).crawler.max_pages == 1000 + + +def test_merge_profile_still_preserves_explicit_overrides(): + cfg = Config.from_dict({'profile': 'quick', 'crawler': {'max_pages': 17}}) + merged = cfg.merge({'profile': 'standard'}) + assert merged.crawler.max_pages == 17 + assert merged.analysis.analysis_mode == 'standard' + assert merged.analysis.enabled_analyzers == Config().analysis.enabled_analyzers + + +def test_custom_profile_preserves_current_settings(): + cfg = Config(profile='quick') + before = cfg.to_dict() + cfg.apply_profile('custom') + before['profile'] = 'custom' + assert cfg.to_dict() == before + + +def test_constructor_debug_override_survives_initial_profile_application(): + cfg = Config(profile='quick', debug=True) + assert cfg.debug is True + cfg.apply_profile('standard') + assert cfg.debug is False + + +def test_crawler_profile_clears_stale_concurrency_alias(): + cfg = CrawlerConfig(concurrent_requests=2, max_pages=17, user_agent='CustomAgent/1.0') + cfg.apply_profile('standard') + assert cfg.concurrent_requests is None + assert cfg.effective_concurrency == CrawlerConfig().effective_concurrency + assert cfg.max_pages == CrawlerConfig().max_pages + assert cfg.user_agent == 'CustomAgent/1.0' + + +def test_merge_does_not_reset_unrelated_values(): + cfg = Config() + cfg.crawler.max_pages = 123 + cfg.analysis.target_keywords = ['example'] + merged = cfg.merge({'debug': True}) + assert merged.debug + assert merged.crawler.max_pages == 123 + assert merged.analysis.target_keywords == ['example'] + assert cfg.debug is False + + +@pytest.mark.parametrize('data', [ + {'crawler': {'max_pages': 0}}, {'crawler': {'max_depth': -1}}, + {'crawler': {'max_concurrent': 0}}, {'crawler': {'timeout': '30'}}, + {'crawler': {'rate_limit_per_second': 0}}, {'crawler': {'retry_backoff_factor': math.nan}}, + {'crawler': {'excluded_patterns': ['[']}}, {'crawler': {'max_pages': True}}, + {'crawler': {'execute_javascript': True}}, {'crawler': {'use_http2': True}}, + {'analysis': {'enabled_analyzers': ['missing']}}, {'analysis': {'enabled_analyzers': []}}, + {'analysis': {'score_weights': {'seo': -1.0, 'content': 2.0}}}, + {'analysis': {'score_weights': {'seo': math.inf}}}, + {'export': {'formats': ['pdf']}}, {'export': {'send_email': True}}, + {'dry_run': True}, {'crawler': {'typo': 1}}, {'typo': 1}, [], +]) +def test_invalid_settings_fail(data): + with pytest.raises((ValueError, TypeError)): + Config.from_dict(data) + + +def test_concurrency_alias_and_conflict(): + cfg = Config.from_dict({'crawler': {'concurrent_requests': 1}}) + assert cfg.crawler.effective_concurrency == 1 + assert cfg.crawler.as_dict()['max_concurrent'] == 1 + assert 'concurrent_requests' not in cfg.crawler.as_dict() + with pytest.raises(ValueError, match='Conflicting'): + Config.from_dict({'crawler': {'concurrent_requests': 2, 'max_concurrent': 3}}) + + +@pytest.mark.parametrize('alias,canonical,value', [ + ('max_content_length', 'max_page_size', 1024), + ('retry_attempts', 'max_retries', 2), + ('adaptive_throttle', 'adaptive_delay', False), + ('follow_sitemap', 'use_sitemap', False), +]) +def test_legacy_aliases_are_canonicalized_without_mutating_input(alias, canonical, value): + data = {'crawler': {alias: value}} + cfg = Config.from_dict(data) + assert getattr(cfg.crawler, canonical) == value + assert data == {'crawler': {alias: value}} + with pytest.raises(ValueError, match='Conflicting'): + Config.from_dict({'crawler': {alias: value, canonical: not value if isinstance(value, bool) else value + 1}}) + + +def test_null_concurrency_alias_does_not_override_canonical_value(): + cfg = Config.from_dict({'crawler': {'concurrent_requests': None, 'max_concurrent': 7}}) + assert cfg.crawler.effective_concurrency == 7 + + +@pytest.mark.parametrize('suffix', ['.json', '.yaml']) +def test_config_roundtrip(tmp_path, suffix): + cfg = Config.from_dict({'profile': 'quick', 'crawler': {'max_pages': 7}}) + path = tmp_path / ('config' + suffix) + cfg.save(path) + assert Config.from_file(path).to_dict() == cfg.to_dict() + + +def test_bad_file_is_not_silently_replaced(tmp_path): + with pytest.raises(FileNotFoundError): + Config.from_file(tmp_path / 'missing.json') + path = tmp_path / 'broken.json' + path.write_text('{bad', encoding='utf-8') + with pytest.raises(ValueError): + Config.from_file(path) + + +def test_environment_uses_the_same_types_and_profiles(monkeypatch): + monkeypatch.setenv('TFQ0SEO_PROFILE', 'quick') + monkeypatch.setenv('TFQ0SEO_CRAWLER_MAX_PAGES', '12') + monkeypatch.setenv('TFQ0SEO_ANALYSIS_TARGET_KEYWORDS', 'one') + monkeypatch.setenv('TFQ0SEO_CRAWLER_VERIFY_SSL', 'true') + cfg = Config.from_env() + assert cfg.analysis.analysis_mode == 'quick' + assert cfg.crawler.max_pages == 12 + assert cfg.analysis.target_keywords == ['one'] + assert cfg.crawler.verify_ssl is True + + +def test_validation_has_no_filesystem_side_effects(tmp_path): + cfg = Config() + cfg.export.output_directory = str(tmp_path / 'unused') + assert cfg.validate() == {} + assert not (tmp_path / 'unused').exists() diff --git a/tests/test_config_migration.py b/tests/test_config_migration.py new file mode 100644 index 0000000..24533e5 --- /dev/null +++ b/tests/test_config_migration.py @@ -0,0 +1,288 @@ +"""Legacy files require an explicit, loss-aware configuration migration.""" + +import copy +import json +import math +from dataclasses import fields + +import pytest + +from tfq0seo.core.config import ( + AnalysisConfig, Config, ConfigProfile, CrawlerConfig, ExportConfig, + OutputFormat, _RETIRED_DEFAULTS, +) + + +def test_serialization_contains_only_active_settings(): + cfg = Config() + saved = cfg.to_dict() + assert set(saved) == { + 'crawler', 'analysis', 'export', 'profile', 'version', 'debug', + 'continue_on_error', 'max_memory_mb', + } + assert set(Config.SUPPORTED_FIELDS) == {'crawler', 'analysis', 'export'} + for section, component in ( + ('crawler', CrawlerConfig), ('analysis', AnalysisConfig), ('export', ExportConfig), + ): + active = {item.name for item in fields(component)} + assert Config.SUPPORTED_FIELDS[section] == active + assert not active.intersection(_RETIRED_DEFAULTS[section]) + assert set(saved[section]) == active - {'concurrent_requests'} + assert {item.value for item in OutputFormat} == {'html', 'json', 'csv', 'xlsx'} + + +def test_all_known_historical_defaults_can_be_explicitly_migrated(): + legacy = copy.deepcopy(_RETIRED_DEFAULTS) + legacy.update(legacy.pop('global')) + legacy.update({'profile': 'deep', 'debug': True}) + legacy['crawler'].update({'max_pages': 17, 'concurrent_requests': 3}) + legacy['analysis']['target_keywords'] = ['migration'] + legacy['export']['formats'] = ['html', 'json'] + before = copy.deepcopy(legacy) + + migrated, warnings = Config.migrate_dict(legacy) + + assert legacy == before + assert migrated == { + 'profile': 'deep', 'debug': True, + 'crawler': {'max_pages': 17, 'max_concurrent': 3}, + 'analysis': {'target_keywords': ['migration']}, + 'export': {'formats': ['html', 'json']}, + } + for section, defaults in _RETIRED_DEFAULTS.items(): + for name in defaults: + path = name if section == 'global' else section + '.' + name + assert any(path in warning for warning in warnings) + assert any('monitoring section' in warning for warning in warnings) + assert any('concurrent_requests to crawler.max_concurrent' in warning for warning in warnings) + resolved = Config.from_dict(migrated) + assert resolved.crawler.max_depth == 10 + assert resolved.crawler.max_pages == 17 + assert resolved.debug is True + + +def test_migration_preserves_sparse_profile_overrides_and_copies_nested_values(): + original = {'profile': ConfigProfile.QUICK, 'crawler': {'max_pages': 17}, + 'analysis': {'target_keywords': ['initial']}} + migrated, warnings = Config.migrate_dict(original) + assert migrated['profile'] == 'quick' + assert set(migrated) == {'profile', 'crawler', 'analysis'} + assert warnings == [] + resolved = Config.from_dict(migrated).merge({'profile': 'deep'}) + assert resolved.crawler.max_pages == 17 + assert resolved.crawler.max_depth == 10 + migrated['analysis']['target_keywords'].append('changed') + assert original['analysis']['target_keywords'] == ['initial'] + assert Config.migrate_dict({}) == ({}, []) + + +@pytest.mark.parametrize('section,name,value', [ + ('crawler', 'execute_javascript', True), + ('crawler', 'normalize_urls', False), + ('analysis', 'check_alt_text', False), + ('analysis', 'max_lcp', 5.0), + ('export', 'send_email', True), + ('export', 'html_theme', 'dark'), + ('monitoring', 'enabled', True), + ('monitoring', 'log_to_file', False), + ('global', 'dry_run', True), + ('global', 'temp_directory', '/custom'), + ('global', 'features', {'custom': True}), + ('global', 'metadata', {'custom': 'value'}), +]) +def test_migration_rejects_requested_unsupported_behavior(section, name, value): + data = {name: value} if section == 'global' else {section: {name: value}} + before = copy.deepcopy(data) + with pytest.raises(ValueError, match='cannot be migrated automatically') as caught: + Config.migrate_dict(data) + assert name in str(caught.value) + assert 'docs/configuration-migration.md' in str(caught.value) + assert data == before + + +@pytest.mark.parametrize('section,name,value', [ + ('crawler', 'parse_javascript', 0), + ('crawler', 'include_query_strings', 1), + ('crawler', 'semaphore_limit', 30.0), + ('crawler', 'wait_for_javascript', False), + ('crawler', 'user_agent_list', ()), + ('analysis', 'validate_anchors', 1), + ('analysis', 'max_image_size_kb', 500.0), + ('export', 'data_sampling_rate', True), + ('export', 'include_har_files', 0), + ('export', 'smtp_port', '587'), + ('export', 'smtp_password', ''), + ('monitoring', 'enabled', 0), + ('monitoring', 'metrics_interval', 60.0), + ('monitoring', 'progress_update_interval', math.inf), + ('global', 'dry_run', 0), + ('global', 'features', []), + ('global', 'metadata', None), +]) +def test_invalid_legacy_types_are_not_silently_dropped(section, name, value): + data = {name: value} if section == 'global' else {section: {name: value}} + with pytest.raises(ValueError, match='invalid type'): + Config.migrate_dict(data) + + +@pytest.mark.parametrize('number', [math.nan, math.inf, -math.inf, 10 ** 400]) +def test_nonfinite_or_unrepresentable_legacy_numbers_fail_cleanly(number): + with pytest.raises(ValueError, match='invalid type'): + Config.migrate_dict({'analysis': {'max_fid': number}}) + + +def test_declared_legacy_float_defaults_accept_finite_integer_equivalents(): + migrated, _ = Config.migrate_dict({ + 'crawler': {'wait_for_javascript': 0}, + 'analysis': {'max_fid': 100.0, 'max_page_load_time': 3}, + 'monitoring': {'alert_thresholds': { + 'error_rate': 0.05, 'avg_response_time': 5, + 'memory_usage_mb': 500.0, 'broken_links_ratio': 0.10, + }}, + }) + assert migrated == {'crawler': {}, 'analysis': {}} + + +@pytest.mark.parametrize('data', [ + {'export': {'send_email': False, 'smtp_password': 'PRIVATE-VALUE'}}, + {'export': {'send_to_api': False, 'api_key': 'PRIVATE-VALUE'}}, + {'monitoring': {'webhook_enabled': False, 'webhook_url': 'PRIVATE-VALUE'}}, + {'profile': 'PRIVATE-VALUE'}, + {'crawler': {'excluded_patterns': ['[PRIVATE-VALUE']}}, + {'crawler': {'concurrent_requests': 'PRIVATE-VALUE'}}, + {'analysis': {'score_weights': 'PRIVATE-VALUE'}}, +]) +def test_migration_errors_never_echo_supplied_values(data): + with pytest.raises(ValueError) as caught: + Config.migrate_dict(data) + assert 'PRIVATE-VALUE' not in str(caught.value) + + +@pytest.mark.parametrize('data', [ + [], None, {'unknown': 'value'}, {'crawler': {'unknown': 'value'}}, + {'monitoring': {'unknown': 'value'}}, {'crawler': None}, + {'analysis': []}, {'export': 'value'}, {'monitoring': False}, + {3: 'value'}, {'crawler': {3: 'value'}}, + {'crawler': {'max_pages': 0}}, {'debug': 1}, +]) +def test_migration_also_validates_active_settings_and_mapping_structure(data): + with pytest.raises(ValueError): + Config.migrate_dict(data) + + +@pytest.mark.parametrize('alias,canonical,value', [ + ('concurrent_requests', 'max_concurrent', 3), + ('max_content_length', 'max_page_size', 1000), + ('retry_attempts', 'max_retries', 1), + ('adaptive_throttle', 'adaptive_delay', False), + ('follow_sitemap', 'use_sitemap', False), +]) +def test_migration_keeps_functional_aliases_and_rejects_conflicts(alias, canonical, value): + data, warnings = Config.migrate_dict({'crawler': {alias: value}}) + assert data == {'crawler': {canonical: value}} + assert len(warnings) == 1 + assert alias in warnings[0] and canonical in warnings[0] + conflict = not value if isinstance(value, bool) else value + 1 + with pytest.raises(ValueError, match='Conflicting'): + Config.migrate_dict({'crawler': {alias: value, canonical: conflict}}) + + +@pytest.mark.parametrize('values', [ + {'concurrent_requests': True, 'max_concurrent': 1}, + {'concurrent_requests': 1, 'max_concurrent': True}, + {'adaptive_throttle': 0, 'adaptive_delay': False}, + {'follow_sitemap': True, 'use_sitemap': 1}, +]) +def test_alias_equality_cannot_hide_invalid_boolean_numeric_types(values): + for constructor in (Config.from_dict, Config.migrate_dict): + with pytest.raises(ValueError, match='invalid type'): + constructor({'crawler': values}) + + +def test_null_concurrency_alias_is_still_explicitly_empty(): + migrated, warnings = Config.migrate_dict({ + 'crawler': {'concurrent_requests': None, 'max_concurrent': 7}, + }) + assert migrated == {'crawler': {'max_concurrent': 7}} + assert 'empty crawler.concurrent_requests' in warnings[0] + + +@pytest.mark.parametrize('data', [ + {'crawler': {'parse_javascript': False}}, + {'analysis': {'check_images': True}}, + {'export': {'send_email': False}}, + {'monitoring': {}}, {'dry_run': False}, {'temp_directory': './temp'}, +]) +def test_regular_loading_and_merging_require_explicit_migration(data): + for constructor in (Config.from_dict, Config().merge): + with pytest.raises(ValueError, match=r'Config\.migrate_dict\(\)'): + constructor(data) + + +@pytest.mark.parametrize('suffix', ['.json', '.yaml']) +def test_saved_legacy_files_migrate_then_roundtrip(tmp_path, suffix): + legacy = {'profile': 'quick', 'crawler': {'max_pages': 7, 'use_http2': False}, + 'monitoring': {}, 'export': {'send_email': False}} + old = tmp_path / 'legacy.json' + old.write_text(json.dumps(legacy), encoding='utf-8') + with pytest.raises(ValueError, match='retired'): + Config.from_file(old) + canonical, warnings = Config.migrate_dict(json.loads(old.read_text(encoding='utf-8'))) + assert warnings + cfg = Config.from_dict(canonical) + new = tmp_path / ('migrated' + suffix) + cfg.save(new) + assert Config.from_file(new).to_dict() == cfg.to_dict() + assert 'monitoring' not in cfg.to_dict() + assert old.read_text(encoding='utf-8') == json.dumps(legacy) + + +@pytest.mark.parametrize('key,value', [ + ('CRAWLER_PARSE_JAVASCRIPT', 'false'), ('ANALYSIS_CHECK_IMAGES', 'true'), + ('EXPORT_SEND_EMAIL', 'false'), ('MONITORING_ENABLED', 'false'), ('DRY_RUN', 'false'), +]) +def test_retired_environment_keys_require_explicit_removal(monkeypatch, key, value): + monkeypatch.setenv('CONFIG_MIGRATION_TEST_' + key, value) + with pytest.raises(ValueError, match='retired'): + Config.from_env('CONFIG_MIGRATION_TEST_') + + +def test_environment_aliases_keep_canonical_type_parsing(monkeypatch): + prefix = 'CONFIG_MIGRATION_TEST_' + monkeypatch.setenv(prefix + 'CRAWLER_FOLLOW_SITEMAP', 'no') + monkeypatch.setenv(prefix + 'CRAWLER_ADAPTIVE_THROTTLE', 'yes') + monkeypatch.setenv(prefix + 'CRAWLER_CONCURRENT_REQUESTS', 'null') + monkeypatch.setenv(prefix + 'CRAWLER_MAX_CONCURRENT', '3') + cfg = Config.from_env(prefix) + assert cfg.crawler.use_sitemap is False + assert cfg.crawler.adaptive_delay is True + assert cfg.crawler.effective_concurrency == 3 + + +@pytest.mark.parametrize('section,name,value', [ + ('crawler', 'execute_javascript', False), + ('analysis', 'check_images', True), + ('export', 'send_email', False), + ('global', 'temp_directory', './temp'), + ('global', 'monitoring', {}), +]) +def test_attached_retired_attributes_cannot_be_silently_serialized(section, name, value): + cfg = Config() + target = cfg if section == 'global' else getattr(cfg, section) + setattr(target, name, value) + assert cfg.validate() + with pytest.raises(ValueError, match='retired'): + cfg.to_dict() + if section == 'crawler': + with pytest.raises(ValueError, match='retired'): + cfg.crawler.as_dict() + + +def test_migration_has_no_filesystem_side_effects(tmp_path): + output = tmp_path / 'not-created' + canonical, _ = Config.migrate_dict({ + 'export': {'output_directory': str(output), 'send_email': False}, + 'temp_directory': './temp', + }) + assert canonical == {'export': {'output_directory': str(output)}} + assert not output.exists() diff --git a/tests/test_content_performance_link_rules.py b/tests/test_content_performance_link_rules.py new file mode 100644 index 0000000..546566f --- /dev/null +++ b/tests/test_content_performance_link_rules.py @@ -0,0 +1,250 @@ +"""Rule identities, evidence, coverage, and advisory boundaries of static checks.""" + +import json + +import pytest +from bs4 import BeautifulSoup + +from tfq0seo.analyzers import content, links, performance +from tfq0seo.rules import get_rule, recommendations_for, score_findings + + +URL = 'https://example.test/page/' + + +def document(body='

A useful page

', head='', lang='en'): + return BeautifulSoup(f'{head}{body}', 'html.parser') + + +def outcomes(result): + return {item['rule_id']: item for item in result['rule_results']} + + +def assert_registered(item): + rule = get_rule(item['rule_id']) + assert item['fix'] == rule.recommendation + assert item['owner'] == rule.owner + assert item['references'] == list(rule.references) + assert item['reviewed_on'] == '2026-09-14' + assert isinstance(item['evidence'], (dict, list)) + assert item['rule_applicability'] + assert item['applicability'] in ('applicable', 'not_applicable', 'unknown') + if item['status'] in ('unknown', 'not_applicable', 'error'): + assert item['reason'] + assert item['penalty'] == 0 + json.dumps(item, allow_nan=False) + + +@pytest.mark.parametrize('module,rule_id', [ + (content, 'content.repeated_sentences'), + (performance, 'performance.blocking_scripts'), + (links, 'links.broken'), +]) +def test_registry_guidance_and_scoring_do_not_depend_on_message(module, rule_id): + first = module.create_issue('Changed category', 'notice', 'CSS image keyword cache readability', + rule_id=rule_id, evidence={'observed': True}) + second = module.create_issue('Changed category', 'critical', 'Entirely different wording', + rule_id=rule_id, evidence={'observed': True}) + for item in (first, second): + assert_registered(item) + assert first['fix'] == second['fix'] + assert first['severity'] == second['severity'] + assert score_findings([first]) == score_findings([second]) + assert recommendations_for([first, second]) == [get_rule(rule_id).recommendation] + + +@pytest.mark.parametrize('analyzer', [content.analyze_content, performance.analyze_performance, links.analyze_links]) +def test_active_findings_and_coverage_preserve_structured_provenance(analyzer): + soup = document('

Details

', + '') + before = str(soup) + result = analyzer(soup, URL) + assert result['rule_results'] + for item in result['rule_results']: + assert_registered(item) + assert result['issues'] == [item for item in result['rule_results'] if item['status'] in ('fail', 'informational')] + assert result['score'] == score_findings(result['issues']) + assert sum(result['rule_coverage']['counts'].values()) == result['rule_coverage']['total'] + assert str(soup) == before + json.dumps(result, allow_nan=False) + + +def test_content_editorial_matches_are_advisory_with_evidence(): + sentence = 'This is an intentionally repeated sentence for our example' + body = ('

Example content overview

Example content overview

' + '

Lorem ipsum. It was prepared by an editor. Historical dates: 1999 2004 2010.

' + + ''.join(f'
Small useful section {number}.
' for number in range(4)) + + f'

{sentence}. {sentence}.

') + result = content.analyze_content(document(body), URL, ['unrelated']) + findings = outcomes(result) + for rule_id in ('content.placeholder_content', 'content.similar_h1', 'content.short_sections', + 'content.historical_years', 'content.repeated_sentences', 'content.target_keywords_headings'): + assert findings[rule_id]['status'] == 'informational' + assert findings[rule_id]['penalty'] == 0 + assert findings[rule_id]['evidence'] + assert result['score'] == 100 + assert findings['content.placeholder_content']['evidence']['matched_phrases'] == ['lorem ipsum'] + assert findings['content.repeated_sentences']['evidence']['sentences'][0]['count'] == 2 + + +def test_content_helper_retains_legacy_types_with_registered_rules(): + soup = document('

Overview

It was prepared by a person. It was prepared by another person.

') + found = content.detect_content_issues(content.extract_text_content(soup), soup) + passive = next(item for item in found if item['rule_id'] == 'content.passive_voice') + assert passive['type'] == 'passive_voice' + assert passive['status'] == 'informational' + assert passive['evidence']['sentence_count'] == 2 + assert_registered(passive) + + +@pytest.mark.parametrize('fre,grade,expected', [(49, 13, 'informational'), (50, 12, 'pass')]) +def test_readability_thresholds_are_explicit_and_unscored(monkeypatch, fre, grade, expected): + monkeypatch.setattr(content, 'calculate_advanced_readability', lambda *args: {'flesch_reading_ease': fre, 'consensus_grade': grade}) + result = content.analyze_content(document('

Overview

' + 'word ' * 100 + '

'), URL) + found = outcomes(result) + for rule_id in ('content.readability_difficult', 'content.readability_grade'): + assert found[rule_id]['status'] == expected + assert found[rule_id]['evidence']['value'] is not None + assert result['score'] == 100 + + +def test_unavailable_readability_does_not_become_passing_or_penalized(monkeypatch): + monkeypatch.setattr(content, 'calculate_advanced_readability', lambda *args: {'error': 'metric unavailable'}) + result = content.analyze_content(document('

Overview

' + 'word ' * 100 + '

'), URL) + found = outcomes(result) + assert found['content.readability_difficult']['status'] == 'unknown' + assert found['content.readability_grade']['status'] == 'unknown' + assert found['content.readability_difficult']['evidence']['error'] == 'metric unavailable' + assert result['score'] == 100 + assert result['rule_coverage']['counts']['unknown'] == 2 + + +def test_language_and_missing_target_keywords_control_applicability(): + result = content.analyze_content(document('

日本語

内容です。
', lang='ja'), URL) + found = outcomes(result) + for rule_id in ('content.readability_difficult', 'content.readability_grade', 'content.passive_voice', + 'content.short_sections', 'content.target_keywords_headings'): + assert found[rule_id]['status'] == 'not_applicable' + assert result['data']['metrics']['word_count'] is None + assert result['score'] == 100 + + +def test_shared_heading_identity_does_not_parse_message_text(monkeypatch): + soup = document('

Details

') + before = content.analyze_content(soup, URL) + original = content.heading_facts + + def renamed_facts(soup): + facts = original(soup) + facts['issues'] = ['Translated text'] * len(facts['issues']) + for item in facts['findings']: + item['message'] = 'Translated text' + return facts + + monkeypatch.setattr(content, 'heading_facts', renamed_facts) + after = content.analyze_content(soup, URL) + assert after['score'] == before['score'] == 86 + assert set(outcomes(after)) == set(outcomes(before)) + assert after['recommendations'] == before['recommendations'] + + +@pytest.mark.parametrize('script_type', ['application/ld+json', 'application/json', 'importmap', 'speculationrules', 'module', ' MODULE ', ' ', 'text/javascript; charset=utf-8']) +def test_data_blocks_and_modules_are_not_classic_parser_blockers(script_type): + result = performance.analyze_performance(document(head=f''), URL) + assert outcomes(result)['performance.blocking_scripts']['status'] == 'pass' + assert result['data']['javascript_optimization']['render_blocking'] == 0 + assert result['score'] == 100 + + +@pytest.mark.parametrize('attributes', ['type="text/javascript1.5"', 'type="application/x-ecmascript"', + 'type=" TEXT/X-JAVASCRIPT "', 'language="JavaScript"', 'type=""']) +def test_classic_javascript_mime_aliases_keep_their_parser_blocking_evidence(attributes): + result = performance.analyze_performance(document(head=f''), URL) + assert outcomes(result)['performance.blocking_scripts']['status'] == 'fail' + + +def test_blocking_script_rule_records_static_evidence_without_invented_metrics(): + result = performance.analyze_performance(document(head=''), URL, 1.5, 1000) + finding = outcomes(result)['performance.blocking_scripts'] + assert finding['status'] == 'fail' + assert finding['evidence']['urls'] == ['/app.js'] + assert finding['evidence']['browser_timing_measured'] is False + assert result['score'] == 93 + assert result['data']['metrics']['html_fetch_time'] == 1.5 + assert result['data']['metrics']['lcp'] is None + assert result['data']['metrics']['inp'] is None + assert result['data']['metrics']['cls'] is None + + +def test_performance_legacy_observations_have_structured_advisory_findings(): + body = '

Overview

' + 'Text' * 21 + head = ('' + '') + result = performance.analyze_performance(document(body, head), URL) + for key in ('image_optimization', 'performance_patterns'): + assert result['data'][key]['findings'] + for item in result['data'][key]['findings']: + assert_registered(item) + assert item['status'] == 'informational' + assert result['data']['image_optimization']['issues'] + assert result['data']['performance_patterns']['bad_patterns'] + assert result['score'] == 100 + + +@pytest.mark.parametrize('markup', [ + '', + 'Next page', + '', + 'Next page', +]) +def test_link_accessible_name_fallbacks_avoid_false_findings(markup): + result = links.analyze_links(document(markup), URL) + assert outcomes(result)['links.missing_anchor']['status'] == 'pass' + assert result['data']['internal_links'][0]['anchor_text'] == 'Next page' + + +def test_link_checks_include_complete_evidence_and_explicit_successes(): + markup = 'InvalidAction' + result = links.analyze_links(document(markup), URL) + found = outcomes(result) + for rule_id in ('links.missing_anchor', 'links.invalid_url', 'links.javascript_url'): + assert found[rule_id]['status'] == 'fail' + assert len(found[rule_id]['evidence']['links']) == 1 + assert found['links.broken']['status'] == 'unknown' + assert result['score'] == 79 + + +@pytest.mark.parametrize('known_failures', [None, set(), {'https://example.test/other'}]) +def test_absent_failure_evidence_does_not_imply_healthy_destinations(known_failures): + result = links.analyze_links(document('Next'), URL, known_failures) + finding = outcomes(result)['links.broken'] + assert finding['status'] == 'unknown' + assert finding['evidence']['unchecked_urls'] == ['https://example.test/next'] + assert finding['penalty'] == 0 + assert result['score'] == 100 + + +def test_broken_link_failure_and_inapplicable_link_health(): + result = links.analyze_links(document('NextNext again'), URL, {'https://example.test/next'}) + finding = outcomes(result)['links.broken'] + assert finding['status'] == 'fail' + assert finding['source'] == 'supplied_destination_checks' + assert finding['evidence']['http_link_count'] == 2 + assert result['score'] == 85 + no_links = links.analyze_links(document(), URL) + assert outcomes(no_links)['links.broken']['status'] == 'not_applicable' + assert no_links['score'] == 100 + + +def test_legacy_link_heuristics_retain_types_without_spam_verdicts(): + anchors = links.analyze_anchor_text_distribution(['click here'] * 4 + ['go'] * 6)['issues'] + sample = [{'url': 'https://other.test/partner', 'is_internal': False, 'anchor_text': 'Sponsored partner', + 'context': 'Advertisement', 'rel': [], 'is_hidden': True}] * 6 + schemes = links.detect_link_schemes(sample) + assert anchors and schemes + for item in anchors + schemes: + assert item['type'] + assert_registered(item) + assert item['status'] == 'informational' + assert item['penalty'] == 0 + assert score_findings(anchors + schemes) == 100 diff --git a/tests/test_crawler.py b/tests/test_crawler.py new file mode 100644 index 0000000..d7f88d9 --- /dev/null +++ b/tests/test_crawler.py @@ -0,0 +1,590 @@ +"""Crawler regressions use loopback HTTP or bounded coroutine fixtures only.""" + +import asyncio +import time +from collections import Counter +from contextlib import asynccontextmanager + +import pytest +from aiohttp import web +from bs4 import BeautifulSoup + +from tfq0seo.core.crawler import Crawler, RateLimiter + + +def config(**overrides): + return { + 'respect_robots_txt': False, + 'use_sitemap': False, + 'adaptive_delay': False, + 'max_retries': 0, + 'retry_backoff_factor': 0, + **overrides, + } + + +@asynccontextmanager +async def serve(handler): + app = web.Application() + app.router.add_get('/{path:.*}', handler) + runner = web.AppRunner(app) + await runner.setup() + site = web.TCPSite(runner, '127.0.0.1', 0) + await site.start() + port = site._server.sockets[0].getsockname()[1] + try: + yield f'http://127.0.0.1:{port}' + finally: + await runner.cleanup() + + +def html(text='PageHello', status=200): + return web.Response(body=text.encode('utf-8'), status=status, + headers={'Content-Type': 'text/html'}) + + +def test_canonical_configuration_overrides_legacy_aliases(): + crawler = Crawler(config( + max_page_size=2048, max_content_length=4096, + max_retries=0, retry_attempts=5, + use_sitemap=False, follow_sitemap=True, + adaptive_delay=False, adaptive_throttle=True, + delay_between_requests=0.01, rate_limit_per_second=20, + )) + assert crawler.max_content_length == 2048 + assert crawler.retry_attempts == 0 + assert crawler.follow_sitemap is False + assert crawler.adaptive_throttle is False + assert crawler.rate_limiter.delay == 0.05 + assert crawler.verify_ssl is True + legacy = Crawler({'max_content_length': 4096, 'retry_attempts': 2, + 'follow_sitemap': False, 'adaptive_throttle': False}) + assert legacy.max_content_length == 4096 + assert legacy.retry_attempts == 2 + assert legacy.follow_sitemap is False + assert legacy.adaptive_throttle is False + + +@pytest.mark.parametrize('setting', [ + {'max_concurrent': 0}, {'max_concurrent': 1.5}, {'max_pages': 0}, + {'timeout': float('nan')}, {'max_crawl_time': -1}, + {'max_page_size': 0}, {'max_retries': -1}, + {'rate_limit_per_second': 0}, {'excluded_patterns': ['[']}, + {'verify_ssl': 'false'}, {'allowed_schemes': ['file']}, +]) +def test_invalid_configuration_fails_before_session(setting): + with pytest.raises(ValueError): + Crawler(setting) + + +@pytest.mark.parametrize('left,right', [ + ('/Product', '/product'), ('/?id=AbC', '/?id=abc'), + ('/a/', '/a'), ('/a//b', '/a/b'), + ('/?ref=a', '/?ref=b'), ('/?source=a', '/?source=b'), + ('/?key=', '/'), ('/?', '/'), ('/?a=1&b=2', '/?b=2&a=1'), +]) +def test_url_identity_preserves_path_and_query_semantics(left, right): + crawler = Crawler() + assert crawler.normalize_url('https://example.test' + left) != crawler.normalize_url('https://example.test' + right) + + +def test_url_identity_normalizes_only_safe_authority_and_fragment(): + crawler = Crawler() + assert crawler.normalize_url('HTTPS://EXAMPLE.TEST:443/Page?Id=AbC#part') == 'https://example.test/Page?Id=AbC' + assert crawler.normalize_url('https://www.example.test/') != crawler.normalize_url('https://example.test/') + + +def test_hostname_scope_and_explicit_wildcards(): + crawler = Crawler({'allowed_domains': ['example.test']}) + assert crawler.is_valid_url('https://example.test/a', 'https://example.test/') + assert not crawler.is_valid_url('https://example.test.attacker.test/a', 'https://example.test/') + assert not crawler.is_valid_url('https://child.example.test/a', 'https://example.test/') + wildcard = Crawler({'allowed_domains': ['*.example.test']}) + assert wildcard.is_valid_url('https://child.example.test/a', 'https://example.test/') + assert not wildcard.is_valid_url('https://example.test/a', 'https://example.test/') + assert not wildcard.is_valid_url('https://badexample.test/a', 'https://example.test/') + default = Crawler() + assert default.is_valid_url('https://example.test/a', 'http://example.test/') + assert default.is_valid_url('https://example.test:443/a', 'http://example.test:80/') + assert not default.is_valid_url('http://example.test:8001/a', 'http://example.test:8000/') + assert not default.is_valid_url('https://www.example.test/a', 'https://example.test/') + + +def test_charset_free_html_and_optional_storage(http_site): + base, routes, _ = http_site + routes['/plain'] = (200, {'Content-Type': 'text/html'}, 'Plain') + routes['/encoded'] = (200, {'Content-Type': 'text/html'}, + b'Caf\xe9') + + async def run(): + async with Crawler(config(store_html=False)) as crawler: + plain = await crawler.fetch_page(base + '/plain') + encoded = await crawler.fetch_page(base + '/encoded') + assert plain['status_code'] == 200 and 'error' not in plain + assert plain['soup'].title.string == 'Plain' + assert 'html' not in plain + assert encoded['soup'].title.string == 'Café' + assert encoded['requested_url'] == base + '/encoded' + asyncio.run(run()) + + +def test_transport_honors_verified_tls_timeout_and_headers(monkeypatch): + async def run(): + async def handler(request): + assert request.headers['User-Agent'] == 'TestBot' + assert request.headers['X-Audit'] == 'yes' + return html() + async with serve(handler) as base: + async with Crawler(config(custom_headers={'user-agent': 'TestBot', 'X-Audit': 'yes'}, + timeout=3, connect_timeout=1, read_timeout=2)) as crawler: + original = crawler.session.get + calls = [] + + def get(url, **kwargs): + calls.append(kwargs) + return original(url, **kwargs) + monkeypatch.setattr(crawler.session, 'get', get) + result = await crawler.fetch_page(base + '/') + assert crawler.session.timeout.total == 3 + assert crawler.session.timeout.sock_read == 2 + assert crawler.session.timeout.sock_connect == 1 + assert 'error' not in result + assert calls[0]['ssl'] is True + assert calls[0]['allow_redirects'] is False + asyncio.run(run()) + + +def test_connection_pooling_can_be_disabled(): + async def run(): + async with Crawler(config(use_connection_pooling=False)) as crawler: + assert crawler.session.connector.force_close is True + asyncio.run(run()) + + +def test_repeated_robots_headers_preserve_all_directives(): + async def run(): + async def handler(request): + return web.Response(body=b'Page', headers=[ + ('Content-Type', 'text/html'), + ('X-Robots-Tag', 'noindex'), + ('X-Robots-Tag', 'nofollow'), + ]) + async with serve(handler) as base: + async with Crawler(config()) as crawler: + result = await crawler.fetch_page(base + '/') + assert result['headers']['X-Robots-Tag'] == ['noindex', 'nofollow'] + asyncio.run(run()) + + +def test_timeout_retries_and_retains_terminal_failure(): + async def run(): + counts = Counter() + async def handler(request): + counts[request.path] += 1 + if request.path == '/always' or counts[request.path] == 1: + await asyncio.sleep(0.08) + return html() + async with serve(handler) as base: + async with Crawler(config(timeout=0.025, max_retries=1)) as crawler: + success = await crawler.fetch_page(base + '/once') + failed = await crawler.fetch_page(base + '/always') + assert counts['/once'] == counts['/always'] == 2 + assert success['status_code'] == 200 + assert failed['status_code'] == 0 and failed['error'] == 'Timeout' + assert crawler.failed_urls[base + '/always'] == 'Timeout' + asyncio.run(run()) + + +def test_retryable_status_and_retry_after_are_enforced(): + async def run(): + starts = [] + async def handler(request): + starts.append(time.monotonic()) + if len(starts) == 1: + return web.Response(status=429, headers={'Retry-After': '0.04'}) + return html() + async with serve(handler) as base: + async with Crawler(config(max_retries=1)) as crawler: + result = await crawler.fetch_page(base + '/') + assert result['status_code'] == 200 + assert len(starts) == 2 + assert starts[1] - starts[0] >= 0.035 + assert crawler.stats.rate_limit_hits == 1 + asyncio.run(run()) + + +def test_http_errors_are_terminal_results_after_retries(http_site): + base, routes, requests = http_site + routes['/unavailable'] = (503, {'Content-Type': 'text/html'}, 'Unavailable') + async def run(): + async with Crawler(config(max_retries=2)) as crawler: + rows = await crawler.crawl_urls([base + '/unavailable']) + assert requests.count('/unavailable') == 3 + assert len(rows) == 1 and rows[0]['error'] == 'HTTP 503' + assert rows[0]['status_code'] == 503 + assert crawler.get_statistics()['failed_pages'] == 1 + asyncio.run(run()) + + +def test_truncated_response_is_marked_incomplete(http_site): + base, routes, _ = http_site + routes['/large'] = (200, {'Content-Type': 'text/html'}, '' + 'x' * 1000 + '') + async def run(): + async with Crawler(config(max_page_size=64)) as crawler: + result = await crawler.fetch_page(base + '/large') + assert result['truncated'] is True + assert result['content_length'] == 64 + assert 'max_page_size' in result['error'] + assert 'soup' not in result + assert 'max_page_size' in crawler.get_statistics()['limits_reached'] + asyncio.run(run()) + + +def test_download_time_includes_streamed_body(monkeypatch): + async def run(): + reading_body = asyncio.Event() + read_bounded = Crawler._read_bounded + + async def observed_read(crawler, response, limit): + reading_body.set() + return await read_bounded(crawler, response, limit) + + monkeypatch.setattr(Crawler, '_read_bounded', observed_read) + + async def handler(request): + response = web.StreamResponse(headers={'Content-Type': 'text/html'}) + await response.prepare(request) + await response.write(b'') + # Start the delay only after the client records header arrival. + # Otherwise scheduling can move part of it into headers_seconds. + await reading_body.wait() + body_ready = time.monotonic() + 0.06 + while True: + remaining = body_ready - time.monotonic() + if remaining <= 0: + break + await asyncio.sleep(remaining) + await response.write(b'Delayed body') + await response.write_eof() + return response + async with serve(handler) as base: + async with Crawler(config()) as crawler: + result = await crawler.fetch_page(base + '/') + assert result['load_time'] >= 0.05 + assert result['timings']['download_seconds'] >= 0.05 + assert result['soup'].title.string == 'Delayed body' + asyncio.run(run()) + + +def test_redirect_uses_final_url_and_html_base_for_discovery(http_site): + base, routes, requests = http_site + routes['/old'] = (302, {'Location': '/new/'}, '') + routes['/new/'] = (200, {'Content-Type': 'text/html'}, + 'Child') + routes['/assets/child'] = (200, {'Content-Type': 'text/html'}, 'Child') + async def run(): + async with Crawler(config(max_pages=5)) as crawler: + rows = await crawler.crawl_site(base + '/old') + assert len(rows) == 2 + assert rows[0]['url'] == base + '/new/' + assert rows[0]['requested_url'] == base + '/old' + assert rows[0]['redirect_chain'][0]['status_code'] == 302 + assert rows[0]['depth'] == 0 + assert rows[1]['depth'] == 1 + assert rows[1]['parent_url'] == base + '/new/' + assert '/assets/child' in requests and '/child' not in requests + asyncio.run(run()) + + +def test_malformed_links_and_redirect_locations_do_not_abort_crawl(http_site): + base, routes, requests = http_site + routes['/'] = (200, {'Content-Type': 'text/html'}, + 'InvalidGood') + routes['/good'] = (200, {'Content-Type': 'text/html'}, 'Good') + routes['/redirect'] = (302, {'Location': 'http://['}, '') + async def run(): + async with Crawler(config()) as crawler: + rows = await crawler.crawl_site(base + '/') + invalid = await crawler.fetch_page(base + '/redirect') + assert len(rows) == 2 + assert '/good' in requests + assert invalid['error'] == 'Invalid redirect Location' + asyncio.run(run()) + + +def test_relative_links_preserve_duplicate_slashes(): + crawler = Crawler(config()) + soup = BeautifulSoup('Page', 'html.parser') + assert crawler.extract_links(soup, 'https://example.test/dir/') == [ + ('https://example.test/dir/a//b?key=&key=Two', 5), + ] + + +def test_duplicate_batch_seeds_do_not_consume_page_budget(http_site): + base, routes, requests = http_site + routes['/a'] = routes['/b'] = (200, {'Content-Type': 'text/html'}, 'Page') + async def run(): + async with Crawler(config(max_pages=2)) as crawler: + rows = await crawler.crawl_urls([base + '/a#one', base + '/a#two', base + '/b']) + assert len(rows) == 2 + assert sorted(requests) == ['/a', '/b'] + asyncio.run(run()) + + +def test_off_scope_redirect_is_blocked_but_explicit_batch_seeds_work(): + async def run(): + off_scope_requests = [] + async def outside(request): + off_scope_requests.append(request.path) + return html() + async with serve(outside) as outside_base: + async def inside(request): + if request.path == '/redirect': + raise web.HTTPFound(outside_base + '/unexpected') + return html() + async with serve(inside) as base: + async with Crawler(config()) as crawler: + blocked = await crawler.fetch_page(base + '/redirect') + assert blocked['skipped'] is True + assert not off_scope_requests + rows = await crawler.crawl_urls([base + '/one', outside_base + '/requested']) + assert len(rows) == 2 + assert all(row['status_code'] == 200 for row in rows) + assert off_scope_requests == ['/requested'] + asyncio.run(run()) + + +def test_page_budget_reserves_inflight_requests_and_depth_zero(http_site): + base, routes, requests = http_site + routes['/'] = (200, {'Content-Type': 'text/html'}, + ''.join(f'Page' for i in range(10))) + for i in range(10): + routes[f'/p{i}'] = (200, {'Content-Type': 'text/html'}, 'Page') + async def run(): + async with Crawler(config(max_pages=2, max_concurrent=8)) as crawler: + rows = await crawler.crawl_site(base + '/') + assert len(rows) == len(requests) == 2 + requests.clear() + async with Crawler(config(max_depth=0, max_pages=10)) as crawler: + rows = await crawler.crawl_site(base + '/') + assert len(rows) == len(requests) == 1 + assert 'max_depth' in crawler.limit_reasons + asyncio.run(run()) + + +def test_depth_priority_preserves_shallow_coverage(): + async def run(): + counts = Counter() + async def handler(request): + counts[request.path] += 1 + if request.path == '/': + return html('FastSlow') + if request.path == '/fast': + return html('Middle') + if request.path == '/slow': + await asyncio.sleep(0.03) + return html('Shared') + if request.path == '/middle': + return html('Shared') + if request.path == '/shared': + return html('Leaf') + return html() + async with serve(handler) as base: + async with Crawler(config(max_depth=3)) as crawler: + await crawler.crawl_site(base + '/') + assert counts['/leaf'] == 1 + assert counts['/shared'] == 1 + asyncio.run(run()) + + +def test_rate_limiter_serializes_origin_starts_and_honors_floor(): + async def run(): + limiter = RateLimiter(initial_delay=0.02) + limiter.set_minimum_delay('a', 0.03) + for _ in range(20): + limiter.record_response('a', 0.001) + starts = [] + async def wait(): + await limiter.wait('a') + starts.append(time.monotonic()) + await asyncio.gather(*(wait() for _ in range(4))) + assert all(right - left >= 0.025 for left, right in zip(starts, starts[1:])) + assert len(limiter.response_times['a']) == 10 + asyncio.run(run()) + + +def test_robots_is_cached_uses_request_identity_and_blocks_paths(): + async def run(): + counts = Counter() + async def handler(request): + counts[request.path] += 1 + assert request.headers['User-Agent'] == 'AuditBot' + if request.path == '/robots.txt': + return web.Response(text='User-agent: AuditBot\nDisallow: /private\n') + return html() + async with serve(handler) as base: + async with Crawler(config(respect_robots_txt=True, user_agent='AuditBot')) as crawler: + results = await crawler.crawl_urls([base + '/public', base + '/private', base + '/other']) + assert counts['/robots.txt'] == 1 + assert counts['/private'] == 0 + assert len(results) == 3 + assert next(r for r in results if r['url'].endswith('/private'))['error'] == 'Blocked by robots.txt' + asyncio.run(run()) + + +def test_unreachable_robots_does_not_allow_crawl(http_site): + base, routes, requests = http_site + routes['/robots.txt'] = (503, {}, '') + routes['/'] = (200, {'Content-Type': 'text/html'}, 'Private') + async def run(): + async with Crawler(config(respect_robots_txt=True)) as crawler: + result = await crawler.fetch_page(base + '/') + assert result['error'] == 'Blocked by robots.txt' + assert requests == ['/robots.txt'] + asyncio.run(run()) + + +def test_sitemap_parser_needs_no_lxml_handles_cycles_and_over_100_urls(http_site, monkeypatch): + base, routes, requests = http_site + monkeypatch.setattr('tfq0seo.core.crawler.PARSER', 'html.parser') + routes['/index.xml'] = (200, {'Content-Type': 'application/xml'}, + f'' + f'{base}/index.xml' + f'{base}/pages.xml') + routes['/pages.xml'] = (200, {'Content-Type': 'application/xml'}, + '' + ''.join(f'{base}/page/{i}' for i in range(150)) + '') + async def run(): + async with Crawler(config(max_pages=200)) as crawler: + urls = await crawler.parse_sitemap(base + '/index.xml') + assert len(urls) == 150 + assert requests == ['/index.xml', '/pages.xml'] + asyncio.run(run()) + + +def test_sitemap_scope_applies_to_child_indexes_and_page_locations(http_site): + base, routes, requests = http_site + routes['/index.xml'] = (200, {'Content-Type': 'application/xml'}, + 'http://127.0.0.1:1/child.xml' + '/pages.xml') + routes['/pages.xml'] = (200, {'Content-Type': 'application/xml'}, + 'http://127.0.0.1:1/offscope' + '/excluded/page/ok') + async def run(): + async with Crawler(config(excluded_patterns=['/excluded/'])) as crawler: + urls = await crawler.parse_sitemap(base + '/index.xml') + assert urls == [base + '/ok'] + assert requests == ['/index.xml', '/pages.xml'] + assert len(crawler.discovery_errors) == 3 + asyncio.run(run()) + + +@pytest.mark.parametrize('encoding', ['utf-8', 'utf-16']) +def test_sitemap_rejects_dtd_and_entities(http_site, encoding): + base, routes, requests = http_site + payload = ']>&secret;' + routes['/unsafe.xml'] = (200, {'Content-Type': 'application/xml'}, payload.encode(encoding)) + async def run(): + async with Crawler(config()) as crawler: + urls = await crawler.parse_sitemap(base + '/unsafe.xml') + assert urls == [] + assert crawler.discovery_errors + assert 'document type' in crawler.discovery_errors[0]['error'] + assert requests == ['/unsafe.xml'] + asyncio.run(run()) + + +def test_sitemap_bytes_and_discovery_count_are_bounded(http_site): + base, routes, requests = http_site + routes['/large.xml'] = (200, {'Content-Type': 'application/xml'}, '' + ' ' * 1000 + '') + async def run(): + async with Crawler(config(max_page_size=64)) as crawler: + assert await crawler.parse_sitemap(base + '/large.xml') == [] + assert 'max_page_size' in crawler.limit_reasons + for i in range(30): + routes[f'/map{i}.xml'] = (200, {'Content-Type': 'application/xml'}, + f'/map{i+1}.xml') + requests.clear() + async with Crawler(config(max_pages=1)) as crawler: + assert await crawler.parse_sitemap(base + '/map0.xml') == [] + assert len(requests) <= 16 + assert 'sitemap_discovery' in crawler.limit_reasons + asyncio.run(run()) + + +def test_sitemap_discovery_stops_after_requested_urls(http_site): + base, routes, requests = http_site + routes['/robots.txt'] = (200, {}, f'Sitemap: {base}/declared.xml\nSitemap: {base}/unused.xml\n') + routes['/declared.xml'] = (200, {'Content-Type': 'application/xml'}, '/first/second') + async def run(): + async with Crawler(config(use_sitemap=True)) as crawler: + urls = await crawler.discover_sitemap_urls(base + '/', max_urls=1) + assert urls == [base + '/first'] + assert requests == ['/robots.txt', '/declared.xml'] + asyncio.run(run()) + + +def test_guessed_missing_sitemaps_are_not_declared_discovery_errors(http_site): + base, routes, _ = http_site + routes['/robots.txt'] = (200, {}, f'Sitemap: {base}/declared.xml\n') + async def run(): + async with Crawler(config(use_sitemap=True)) as crawler: + assert await crawler.discover_sitemap_urls(base + '/') == [] + assert len(crawler.discovery_errors) == 1 + assert crawler.discovery_errors[0]['url'] == base + '/declared.xml' + assert crawler.discovery_errors[0]['error'] == 'HTTP 404' + asyncio.run(run()) + + +def test_crawl_deadline_retains_inflight_failures_and_cleans_up(): + async def run(): + running = set() + crawler = Crawler(config(max_crawl_time=0.04, max_concurrent=2, max_pages=2)) + async def stalled(url): + task = asyncio.current_task() + running.add(task) + try: + await asyncio.Event().wait() + finally: + running.discard(task) + crawler.fetch_page = stalled + rows = await crawler.crawl_urls(['https://example.test/one', 'https://example.test/two']) + assert len(rows) == 2 + assert all(row['error'] == 'Crawl time limit exceeded' for row in rows) + assert 'max_crawl_time' in crawler.limit_reasons + assert not running + asyncio.run(run()) + + +def test_cancelling_crawl_cancels_and_awaits_fetch_tasks(): + async def run(): + running = set() + started = asyncio.Event() + crawler = Crawler(config(max_concurrent=2)) + async def stalled(url): + task = asyncio.current_task() + running.add(task) + if len(running) == 2: + started.set() + try: + await asyncio.Event().wait() + finally: + running.discard(task) + crawler.fetch_page = stalled + task = asyncio.create_task(crawler.crawl_urls(['https://example.test/one', 'https://example.test/two'])) + await asyncio.wait_for(started.wait(), 1) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert not running + asyncio.run(run()) + + +@pytest.mark.parametrize('url', ['not a URL', 'file:///private', 'https://example.test:invalid/', 'javascript:alert(1)', 'http://127.0.0.1:0/']) +def test_invalid_seeds_return_terminal_errors_without_network(url): + async def run(): + async with Crawler(config()) as crawler: + result = await crawler.fetch_page(url) + assert result['status_code'] == 0 and result['error'] + assert result['load_time'] is None + assert crawler.stats.requests_made == 0 + asyncio.run(run()) diff --git a/tests/test_crawler_deadline_contract.py b/tests/test_crawler_deadline_contract.py new file mode 100644 index 0000000..95a3f1d --- /dev/null +++ b/tests/test_crawler_deadline_contract.py @@ -0,0 +1,114 @@ +"""Deadline outcomes depend on cancellation cause, never a second clock reading.""" + +import asyncio +import time +from types import SimpleNamespace + +import pytest + +import tfq0seo.core.crawler as crawler_module +from tfq0seo.core.crawler import Crawler + + +def crawler_config(**options): + return {'respect_robots_txt': False, 'use_sitemap': False, 'max_retries': 0, + 'adaptive_delay': False, 'max_concurrent': 2, 'max_pages': 2, + 'max_crawl_time': 0.02, **options} + + +def fake_crawler_clock(monkeypatch): + clock = [10.0] + # Do not patch the standard-library time module used by asyncio's real timer. + monkeypatch.setattr(crawler_module, 'time', + SimpleNamespace(monotonic=lambda: clock[0], time=time.time)) + return clock + + +def test_early_timeout_retains_every_inflight_url_and_awaits_cleanup(monkeypatch): + clock = fake_crawler_clock(monkeypatch) + + async def run(): + crawler = Crawler(crawler_config()) + started, cleaned = set(), set() + + async def stalled(url): + started.add(url) + try: + await asyncio.Event().wait() + finally: + await asyncio.sleep(0) + cleaned.add(url) + + crawler.fetch_page = stalled + urls = ['https://example.test/one', 'https://example.test/two'] + rows = await crawler.crawl_urls(urls) + assert clock[0] == 10.0 # The crawler's sampled clock still precedes its deadline. + assert sorted(row['url'] for row in rows) == urls + assert all(row['error'] == 'Crawl time limit exceeded' for row in rows) + assert all(row['status_code'] == 0 and row['outcome'] == 'failed' for row in rows) + assert set(crawler.failed_urls) == set(urls) + assert 'max_crawl_time' in crawler.limit_reasons + assert started == cleaned == set(urls) + assert crawler._deadline is None + + asyncio.run(run()) + + +def test_external_cancellation_after_sampled_deadline_does_not_fabricate_timeouts(monkeypatch): + clock = fake_crawler_clock(monkeypatch) + + async def run(): + crawler = Crawler(crawler_config(max_crawl_time=30)) + ready = asyncio.Event() + started, cleaned = set(), set() + + async def stalled(url): + started.add(url) + if len(started) == 2: + ready.set() + try: + await asyncio.Event().wait() + finally: + await asyncio.sleep(0) + cleaned.add(url) + + crawler.fetch_page = stalled + urls = ['https://example.test/one', 'https://example.test/two'] + task = asyncio.create_task(crawler.crawl_urls(urls)) + await asyncio.wait_for(ready.wait(), 1) + clock[0] = 100.0 # Clock position alone cannot establish the cancellation cause. + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert crawler.results == [] + assert crawler.failed_urls == {} + assert 'max_crawl_time' not in crawler.limit_reasons + assert started == cleaned == set(urls) + assert crawler._deadline is None + + asyncio.run(run()) + + +def test_timeout_preserves_depth_parent_and_preexisting_results(monkeypatch): + fake_crawler_clock(monkeypatch) + + async def run(): + crawler = Crawler(crawler_config(max_depth=3)) + previous = {'url': 'https://example.test/previous', 'status_code': 200, 'outcome': 'success'} + crawler.results.append(previous) + urls = ['https://example.test/child-one', 'https://example.test/child-two'] + parent = 'https://example.test/parent' + for url in urls: + crawler._enqueue(url, depth=2, parent_url=parent) + + async def stalled(url): + await asyncio.Event().wait() + + crawler.fetch_page = stalled + rows = await crawler._run_with_deadline(crawler._run_queue(2, follow_links=False), parent) + assert rows[0] is previous + assert sorted(row['url'] for row in rows[1:]) == urls + assert all(row['depth'] == 2 and row['parent_url'] == parent for row in rows[1:]) + assert len(rows) == 3 + + asyncio.run(run()) diff --git a/tests/test_exporters.py b/tests/test_exporters.py new file mode 100644 index 0000000..73068ae --- /dev/null +++ b/tests/test_exporters.py @@ -0,0 +1,274 @@ +"""Exercise exports using application results and untrusted audited content.""" + +import asyncio +import copy +import csv +import json +import re +from pathlib import Path + +import pytest +from bs4 import BeautifulSoup +from jinja2 import FileSystemLoader +from openpyxl import load_workbook + +from tfq0seo.core.app import SEOAnalyzer +from tfq0seo.exporters.base import ExportManager + + +@pytest.fixture +def page(): + html = '''A useful title for the local export fixture + + +

Export fixture

A short local fixture for analysis.

+ ''' + return asyncio.run(SEOAnalyzer().analyze_page({ + 'url': 'https://example.test/fixture', 'status_code': 200, 'load_time': 0.125, + 'content_length': len(html.encode()), 'headers': {'Content-Type': 'text/html'}, + 'soup': BeautifulSoup(html, 'html.parser'), + })) + + +@pytest.fixture +def exporter(tmp_path): + return ExportManager({'output_directory': str(tmp_path)}) + + +@pytest.mark.parametrize('template', ['report', 'enhanced', 'optimized']) +@pytest.mark.parametrize('kind', ['single', 'site']) +def test_actual_results_render_all_templates(tmp_path, page, template, kind): + data = page if kind == 'single' else SEOAnalyzer().generate_site_report([page]) + before = copy.deepcopy(data) + exporter = ExportManager({'output_directory': str(tmp_path), 'html_template': template}) + path = Path(exporter.export(data, 'html')) + soup = BeautifulSoup(path.read_text(encoding='utf-8'), 'html.parser') + text = soup.get_text(' ', strip=True) + assert 'SEO Analysis' in text or 'TFQ0SEO Analysis' in text + assert 'Not measured' in text or str(round(page['overall_score'])) in text + assert "'recommendation':" not in text + assert data == before + prepared = exporter._prepare_html_data(data) + assert prepared['category_scores']['seo'] == page['seo']['score'] + if kind == 'site': + assert prepared['aggregated_issues'] == data['issues']['aggregated'] + assert prepared['aggregation_stats'] == data['issues']['stats'] + + +@pytest.mark.parametrize('kind', ['single', 'site']) +def test_actual_results_export_csv_excel_json(tmp_path, exporter, page, kind): + data = page if kind == 'single' else SEOAnalyzer().generate_site_report([page]) + original = copy.deepcopy(data) + csv_path = Path(exporter.export(data, 'csv')) + with csv_path.open(encoding='utf-8', newline='') as stream: + rows = list(csv.DictReader(stream)) + assert len(rows) == 1 + assert rows[0]['title'] == page['seo']['data']['title']['text'] + assert rows[0]['description'] == page['seo']['data']['description']['text'] + assert float(rows[0]['seo_score']) == page['seo']['score'] + workbook = load_workbook(exporter.export(data, 'xlsx')) + assert workbook['Summary']['B3'].value == pytest.approx(page['overall_score']) + assert workbook['Pages'].max_row == 2 + assert workbook['Issues'].max_row > 1 + assert workbook['Recommendations'].max_row > 1 + workbook.close() + json_path = Path(exporter.export(data, 'json')) + assert json.loads(json_path.read_text(encoding='utf-8')) == json.loads(json.dumps(data)) + assert data == original + + +@pytest.mark.parametrize('template', ['report', 'enhanced', 'optimized', 'fallback']) +def test_untrusted_page_content_is_inert(tmp_path, page, template): + payload = '' + html = f'FixtureFixture' + data = asyncio.run(SEOAnalyzer().analyze_page({ + 'url': 'https://example.test/hostile', 'status_code': 200, 'load_time': 0.1, + 'headers': {}, 'soup': BeautifulSoup(html, 'html.parser'), + })) + observed = next(issue for issue in data['issues'] + if payload in json.dumps(issue.get('evidence', {}), ensure_ascii=False)) + # Keep the analyzer's evidence and also exercise imported message escaping, + # including the minimal fallback template that does not display rule metadata. + observed['message'] = 'Imported report message: ' + payload + # The imported report path also accepts untrusted URL strings. + data['url'] = 'javascript:alert(1)' + exporter = ExportManager({'output_directory': str(tmp_path), 'html_template': 'report' if template == 'fallback' else template}) + if template == 'fallback': + exporter.jinja_env.loader = FileSystemLoader(str(tmp_path / 'missing-templates')) + path = Path(exporter.export(data, 'html')) + rendered = path.read_text(encoding='utf-8') + soup = BeautifulSoup(rendered, 'html.parser') + assert not soup.select('[onerror]') + assert not soup.find('img') + assert all(not str(link.get('href', '')).lower().startswith('javascript:') for link in soup.find_all('a')) + assert payload in soup.get_text() + assert 'innerHTML' not in rendered + + +@pytest.mark.parametrize('value', ['=1+1', '+SUM(A1:A2)', '-1+2', '@SUM(A1)', '\t=1+1', '\r=1+1']) +def test_spreadsheet_formula_injection_is_neutralized(exporter, page, value): + page['seo']['data']['title']['text'] = value + page['issues'][0]['message'] = value + page['recommendations'] = [{'recommendation': value, 'priority': 'high', 'impact': {'value': value}}] + with Path(exporter.export(page, 'csv')).open(encoding='utf-8', newline='') as stream: + row = next(csv.DictReader(stream)) + assert row['title'] == "'" + value + workbook = load_workbook(exporter.export(page, 'xlsx'), data_only=False) + for sheet in workbook: + for cells in sheet: + assert all(cell.data_type != 'f' for cell in cells) + # XML backends may preserve or normalize carriage returns in inline strings. + def normalize_line_endings(cell_value): + if isinstance(cell_value, str): + return cell_value.replace('\r\n', '\n').replace('\r', '\n') + return cell_value + + excel_value = normalize_line_endings("'" + value) + assert normalize_line_endings(workbook['Recommendations']['A2'].value) == excel_value + assert any(normalize_line_endings(c.value) == excel_value for row in workbook['Issues'] for c in row) + workbook.close() + + +@pytest.mark.parametrize('template', ['report', 'enhanced', 'optimized']) +def test_failed_and_unmeasured_results_do_not_become_zero(tmp_path, template): + exporter = ExportManager({'output_directory': str(tmp_path), 'html_template': template}) + data = {'url': 'https://example.test/failed', 'error': 'Connection failed', 'overall_score': None, + 'performance': {'score': None, 'status': 'not_measured', 'data': {'metrics': {'lcp': None, 'fid': None}}}, + 'seo': {'score': None, 'error': 'SEO analysis failed'}} + path = Path(exporter.export(data, 'html')) + soup = BeautifulSoup(path.read_text(encoding='utf-8'), 'html.parser') + text = soup.get_text(' ', strip=True) + assert 'Not measured' in text + assert 'Connection failed' in text + assert 'SEO analysis failed' in text + assert '0/100' not in text + assert all(value is None for value in exporter._prepare_html_data(data)['category_scores'].values()) + + +@pytest.mark.parametrize('template', ['report', 'enhanced', 'optimized']) +def test_every_page_survives_large_report_export(tmp_path, page, template): + pages = [dict(copy.deepcopy(page), url=f'https://example.test/page-{index}') for index in range(505)] + failed = {'url': 'https://example.test/failed', 'error': 'Timed out', 'overall_score': None} + report = SEOAnalyzer().generate_site_report(pages + [failed]) + exporter = ExportManager({'output_directory': str(tmp_path), 'html_template': template}) + prepared = exporter._prepare_html_data(report) + assert len(prepared['pages_summary']) == 506 + assert prepared['pages_summary'][-1]['error'] == 'Timed out' + html = Path(exporter.export(report, 'html')).read_text(encoding='utf-8') + if template == 'optimized': + embedded = re.search(r'const pagesData = (.*);', html).group(1) + assert len(json.loads(embedded)) == 506 + else: + soup = BeautifulSoup(html, 'html.parser') + assert len(soup.select('.pages-table tbody tr')) == 506 + with Path(exporter.export(report, 'csv')).open(encoding='utf-8', newline='') as stream: + rows = list(csv.DictReader(stream)) + assert len(rows) == 506 + assert rows[-1]['error'] == 'Timed out' + workbook = load_workbook(exporter.export(report, 'xlsx'), read_only=True) + assert workbook['Pages'].max_row == 507 + workbook.close() + archived = json.loads(Path(exporter.export(report, 'json')).read_text(encoding='utf-8')) + assert len(archived['pages']['detailed']) == 505 + assert len(archived['pages']['failed']) == 1 + + +def test_export_preserves_missing_measurements_and_full_text(exporter, page): + title = 'A long title ' * 30 + page['seo']['data']['title']['text'] = title + page['content']['data']['readability'] = {'flesch_reading_ease': None} + page['performance']['score'] = None + with Path(exporter.export(page, 'csv')).open(encoding='utf-8', newline='') as stream: + row = next(csv.DictReader(stream)) + assert row['title'] == title + assert row['flesch_reading_ease'] == '' + assert row['performance_score'] == '' + + +def test_fallback_to_csv_when_excel_extra_is_missing(exporter, page, monkeypatch): + monkeypatch.setattr('tfq0seo.exporters.base.OPENPYXL_AVAILABLE', False) + path = Path(exporter.export(page, 'xlsx')) + assert path.suffix == '.csv' + assert path.exists() + + +def test_enhanced_separates_observed_zero_from_unmeasured_metrics(tmp_path, page): + exporter = ExportManager({'output_directory': str(tmp_path), 'html_template': 'enhanced'}) + page['overall_score'] = 0 + page['performance'] = {'score': None, 'data': { + 'measurement_status': 'browser_not_measured', + 'metrics': {'html_fetch_time': 0, 'content_size_mb': 0, 'lcp': None, 'inp': None}, + }} + path = Path(exporter.export(page, 'html')) + soup = BeautifulSoup(path.read_text(encoding='utf-8'), 'html.parser') + metrics = {card.select_one('.metric-label').get_text(strip=True): + card.select_one('.metric-value').get_text(strip=True) + for card in soup.select('#performance .metric-card')} + assert metrics['HTML fetch time'] == '0.00s' + assert metrics['HTML size'] == '0.00MB' + assert metrics['Largest Contentful Paint'] == 'Not measured' + assert metrics['Interaction to Next Paint'] == 'Not measured' + assert '0/100' in soup.get_text() + + +@pytest.mark.parametrize('url', ['data:text/html,', '//example.test/path', 'https:\n//example.test']) +def test_report_rejects_unsafe_or_ambiguous_link_schemes(tmp_path, url): + exporter = ExportManager({'output_directory': str(tmp_path), 'html_template': 'report'}) + path = Path(exporter.export({'url': url}, 'html')) + soup = BeautifulSoup(path.read_text(encoding='utf-8'), 'html.parser') + assert not soup.select('.url-info a') + + +@pytest.mark.parametrize(('pattern', 'expected_name'), [ + ('audit-{domain}.{format}', 'audit-example.test.csv'), + ('{format}-for-{domain}', 'csv-for-example.test.csv'), +]) +def test_configured_filename_patterns(tmp_path, page, pattern, expected_name): + exporter = ExportManager({'output_directory': str(tmp_path), 'filename_pattern': pattern}) + output = Path(exporter.export(page, 'csv')) + assert output == tmp_path / expected_name + assert output.is_file() + + +def test_filename_timestamp_is_available_for_nested_site_reports(tmp_path, page): + exporter = ExportManager({'output_directory': str(tmp_path), 'filename_pattern': '{domain}-{timestamp}.{format}'}) + report = SEOAnalyzer().generate_site_report([page]) + output = Path(exporter.export(report, 'json')) + assert re.fullmatch(r'example\.test-\d{8}_\d{6}_\d{6}\.json', output.name) + assert output.parent == tmp_path + + +@pytest.mark.parametrize('pattern', [ + '{unknown}', '{domain.__class__}', '{domain[0]}', '{domain!r}', '{domain:>30}', + '{domain', '../{domain}', '..\\{domain}', '/outside/{domain}', 'C:\\outside\\{domain}', '', + 'audit:stream', 'NUL', 'CON', 'report\nname', +]) +def test_invalid_filename_patterns_are_rejected_before_writing(tmp_path, page, monkeypatch, pattern): + exporter = ExportManager({'output_directory': str(tmp_path), 'filename_pattern': pattern}) + + def unexpected_write(*args, **kwargs): + raise AssertionError('An invalid filename reached the writer') + + # Intercept dispatch so a validation regression cannot write devices or NTFS streams. + monkeypatch.setattr(exporter, 'export_json', unexpected_write) + with pytest.raises(ValueError): + exporter.export(page, 'json') + assert list(tmp_path.iterdir()) == [] + + +def test_explicit_output_path_takes_precedence_over_filename_pattern(tmp_path, page): + exporter = ExportManager({'output_directory': str(tmp_path), 'filename_pattern': '{unknown}'}) + output = tmp_path / 'requested.json' + assert exporter.export(page, 'json', str(output)) == str(output) + assert output.is_file() + + +@pytest.mark.parametrize('value', [float('nan'), float('inf'), float('-inf')]) +def test_nonfinite_json_values_are_rejected_without_truncating_existing_report(tmp_path, exporter, value): + output = tmp_path / 'preserved.json' + previous = '{"previous_report": true}\n' + output.write_text(previous, encoding='utf-8') + data = {'url': 'https://example.test/', 'measurements': [{'value': value}]} + with pytest.raises(ValueError): + exporter.export(data, 'json', str(output)) + assert output.read_text(encoding='utf-8') == previous diff --git a/tests/test_model_contracts.py b/tests/test_model_contracts.py new file mode 100644 index 0000000..37cbe11 --- /dev/null +++ b/tests/test_model_contracts.py @@ -0,0 +1,299 @@ +"""Live contracts reject malformed observations before scoring or aggregation.""" + +import asyncio +import copy +import json + +import pytest +from bs4 import BeautifulSoup +from multidict import CIMultiDict + +from tfq0seo.core.app import SEOAnalyzer +from tfq0seo.core.config import Config +from tfq0seo.core.crawler import Crawler +from tfq0seo.core.models import (ContractError, PageFacts, normalize_fetch_result, + validate_analyzer_result, validate_json_value, + validate_rule_result) +from tfq0seo.rules import RuleCollector, merge_rule_results, rule_result + + +def raw_page(**overrides): + return {'url': 'https://example.test/', 'status_code': 200, + 'soup': BeautifulSoup('Fixture

Fixture

', 'html.parser'), + **overrides} + + +def only_seo(): + return SEOAnalyzer(Config.from_dict({'analysis': {'enabled_analyzers': ['seo'], 'score_weights': {'seo': 1}}})) + + +@pytest.mark.parametrize(('field', 'value'), [ + ('url', None), ('status_code', '200'), ('status_code', True), ('status_code', 99), + ('status_code', 600), ('headers', []), ('headers', {'X-Test': 7}), + ('headers', {'X-Test': ['one', None]}), ('load_time', float('nan')), + ('load_time', -1), ('timings', {'total_seconds': float('inf')}), ('timings', None), + ('content_length', 1.5), ('truncated', 'false'), ('depth', -1), + ('soup', '

Unparsed

'), ('redirect_chain', ['https://example.test/old']), + ('redirect_chain', [{'url': 'https://example.test/old', 'status_code': 200, 'location': '/'}]), + ('outcome', 'unknown'), ('extra', object()), +]) +def test_invalid_fetch_fields_fail_with_a_path_before_any_analysis(field, value): + analyzer = only_seo() + with pytest.raises(ContractError) as error: + asyncio.run(analyzer.analyze_page(raw_page(**{field: value}))) + assert error.value.path.startswith('$.fetch.' + field) + assert analyzer.stats.successful_analyses == 0 + assert not analyzer.cache.cache + + +def test_fetch_normalization_preserves_unavailable_and_repeated_observations(): + headers = CIMultiDict([('Content-Security-Policy', "default-src 'self'"), + ('content-security-policy', "script-src 'none'")]) + raw = raw_page(headers=headers, load_time=None, timings={'network_seconds': 0.2, 'headers_seconds': None}, + redirect_chain=[{'url': 'https://example.test/old', 'status_code': 301, + 'location': 'https://example.test/'}], extra={'retained': [1]}) + value = normalize_fetch_result(raw) + assert value['soup'] is raw['soup'] + assert value['load_time'] is None + assert value['timings'] == raw['timings'] + assert value['headers']['Content-Security-Policy'] == ["default-src 'self'", "script-src 'none'"] + value['redirect_chain'][0]['location'] = '/changed' + value['extra']['retained'].append(2) + assert raw['redirect_chain'][0]['location'] == 'https://example.test/' + assert raw['extra']['retained'] == [1] + assert normalize_fetch_result(raw_page())['headers'] is None + assert normalize_fetch_result(raw_page(headers={}))['headers'] == {} + + +def test_crawler_preserves_every_header_instance_without_duplicate_case_keys(): + headers = CIMultiDict([('Content-Security-Policy', "default-src 'self'"), + ('content-security-policy', "script-src 'none'"), + ('X-Robots-Tag', 'noindex'), ('x-robots-tag', 'nofollow'), + ('Content-Type', 'text/html')]) + result = Crawler._response_headers(headers) + assert len(result) == 3 + assert result['Content-Security-Policy'] == ["default-src 'self'", "script-src 'none'"] + assert result['X-Robots-Tag'] == ['noindex', 'nofollow'] + assert result['Content-Type'] == 'text/html' + + +def test_transport_failure_keeps_headers_unavailable_and_has_no_dom(): + failure = Crawler({})._failure('https://example.test/', 'Connection unavailable') + normalized = normalize_fetch_result(failure) + assert normalized['headers'] is None + assert normalized['load_time'] is None + assert normalized['status_code'] == 0 + assert 'soup' not in normalized + + +@pytest.mark.parametrize(('outcome', 'expected'), [('failed', 'error'), ('skipped', 'skipped')]) +def test_fetch_outcome_cannot_be_promoted_to_a_successful_analysis(outcome, expected): + result = asyncio.run(only_seo().analyze_page(raw_page(outcome=outcome))) + assert result['status'] == expected + assert result['overall_score'] is None + assert 'seo' not in result + assert result.get('error') or result.get('reason') + + +def test_contradictory_fetch_outcomes_are_rejected(): + with pytest.raises(ContractError, match='outcome'): + normalize_fetch_result(raw_page(outcome='success', error='failed')) + with pytest.raises(ContractError, match='outcome'): + normalize_fetch_result(raw_page(outcome='failed', skipped=True)) + + +@pytest.mark.parametrize(('field', 'value'), [ + ('evidence', None), ('source', ''), ('confidence', 'guessed'), ('references', []), + ('reviewed_on', 'yesterday'), ('applicability', 'unknown'), ('owner', 'seo'), + ('severity', 'critical'), ('penalty', -1), ('reported_by', ['missing']), + ('details', {'timing': float('nan')}), ('observations', [{'status': 'pass', 'evidence': None}]), +]) +def test_complete_rule_contract_rejects_invalid_metadata_and_nested_values(field, value): + rule = rule_result('images.missing_alt', {'images': ['/photo.png']}) + rule[field] = value + with pytest.raises(ContractError): + validate_rule_result(rule) + with pytest.raises(ContractError): + merge_rule_results([rule]) + + +def test_rule_builder_validates_details_and_measurement_source(): + with pytest.raises(ContractError, match='details'): + rule_result('images.missing_alt', {}, details={'unsupported': object()}) + with pytest.raises(ContractError, match='source'): + rule_result('images.missing_alt', {}, source='') + + +@pytest.mark.parametrize('invalid', [ + {'score': 100, 'issues': [None]}, {'score': 100, 'issues': [], 'data': None}, + {'score': 100, 'issues': [], 'data': {'metric': float('inf')}}, + {'score': 100, 'issues': [], 'rule_results': [{'rule_id': 'images.missing_alt', 'status': 'fail'}]}, +]) +def test_bad_analyzer_output_is_an_explicit_uncached_error(monkeypatch, invalid): + monkeypatch.setattr('tfq0seo.core.app.analyze_seo', lambda *args, **kwargs: copy.deepcopy(invalid)) + analyzer = only_seo() + result = asyncio.run(analyzer.analyze_page(raw_page())) + assert result['status'] == 'error' + assert result['seo']['score'] is None + assert result['overall_score'] is None + assert result['coverage']['failed_analyzers'] == ['seo'] + assert '$.seo' in result['analyzer_errors']['seo'] + assert not analyzer.cache.cache + + +def test_missing_headers_remain_unknown_in_rule_evidence(): + analyzer = only_seo() + result = asyncio.run(analyzer.analyze_page(raw_page())) + rule = next(item for item in result['rule_results'] if item['rule_id'] == 'robots.noindex') + assert rule['status'] == 'unknown' + assert rule['evidence']['headers_checked'] is False + assert result['page_facts']['headers_observed'] is False + + +def test_valid_rule_and_analyzer_contract_round_trip(): + collector = RuleCollector('content') + collector.check('images.missing_alt', None, {'images': None}, reason='Image extraction unavailable') + result = {'score': 100, 'issues': collector.issues, 'rule_results': collector.results, 'data': {}} + assert validate_analyzer_result(result) is result + assert json.loads(json.dumps(result, allow_nan=False)) == result + assert PageFacts.__name__ == 'PageFacts' + + +def test_json_validation_rejects_cycles_without_rejecting_shared_values(): + shared = {'value': [1, None]} + assert validate_json_value([shared, shared]) == [shared, shared] + shared['cycle'] = shared + with pytest.raises(ContractError, match='circular'): + validate_json_value(shared) + + +def test_archived_rules_retain_recorded_guidance_and_scores_during_aggregation(): + async def run(): + analyzer = SEOAnalyzer(Config()) + page = await analyzer.analyze_page(raw_page(headers={})) + page['scoring']['ruleset_version'] = 'archived-policy' + for collection in [page['rule_results'], page['issues'], page['links']['rule_results']]: + for item in collection: + item['rule_version'] = 'archived-policy' + issue = rule_result('images.missing_alt', {'images': ['/photo.png']}) + issue.update(rule_id='archived.removed_rule', rule_version='archived-policy', fix='Recorded archive advice') + page['issues'] = [issue] + recorded_score = page['overall_score'] + report = analyzer.generate_site_report([page]) + assert report['scores']['overall'] == recorded_score + assert report['pages']['detailed'][0]['issues'] == [issue] + assert report['recommendations']['specific'][0]['description'] == 'Recorded archive advice' + assert report['scoring']['version'] == 'legacy_or_mixed' + asyncio.run(run()) + + +def test_different_rule_versions_keep_separate_evidence_groups(): + from tfq0seo.core.report_optimizer import aggregate_issues + first = rule_result('images.missing_alt', {'images': ['/first.png']}) + second = dict(first, rule_version='archived', evidence={'images': ['/second.png']}) + groups, _ = aggregate_issues([first, second]) + assert len(groups) == 2 + assert groups[0]['evidence'] != groups[1]['evidence'] + + +def test_site_aggregation_rejects_missing_identity_and_summary_only_findings(): + with pytest.raises(ContractError) as error: + only_seo().generate_site_report([{}]) + assert error.value.path == '$.pages[0].url' + with pytest.raises(ContractError) as error: + only_seo().generate_site_report([{'url': 'https://example.test/', 'issues': {'warning': 2}}]) + assert error.value.path == '$.pages[0].issues' + + +def test_archived_null_http_status_stays_unavailable_during_aggregation(): + report = only_seo().generate_site_report([{'url': 'https://example.test/', 'status_code': None, + 'overall_score': 95, 'issues': []}]) + assert report['pages']['detailed'][0]['status_code'] is None + assert report['performance_metrics']['status_codes'] == {0: 1} + assert report['technical_health']['broken_links'] == [] + + +def test_facts_version_invalidates_analysis_cache(monkeypatch): + async def run(): + analyzer = only_seo() + raw = raw_page() + await analyzer.analyze_page(raw) + assert (await analyzer.analyze_page(raw)).get('cached') + monkeypatch.setattr('tfq0seo.core.app.FACTS_VERSION', 'next-facts') + assert not (await analyzer.analyze_page(raw)).get('cached') + asyncio.run(run()) + + +@pytest.mark.parametrize('change', ['missing_evaluation', 'missing_issue', 'legacy_issue', 'missing_error']) +def test_inconsistent_live_results_never_disappear_into_success(monkeypatch, change): + rule = rule_result('images.missing_alt', {'images': ['/photo.png']}) + invalid = {'score': 93, 'issues': [rule], 'rule_results': [rule], 'data': {}} + if change == 'missing_evaluation': + invalid['rule_results'] = [] + elif change == 'missing_issue': + invalid['issues'] = [] + elif change == 'legacy_issue': + invalid['issues'] = [{'message': 'A legacy finding', 'category': 'SEO', 'severity': 'warning'}] + invalid['rule_results'] = [] + else: + invalid = {'status': 'error', 'score': None, 'issues': [], 'data': {}} + monkeypatch.setattr('tfq0seo.core.app.analyze_seo', lambda *args, **kwargs: invalid) + page = asyncio.run(only_seo().analyze_page(raw_page())) + assert page['status'] == 'error' + assert page['overall_score'] is None + assert page['seo']['error'] + + +@pytest.mark.parametrize(('field', 'value'), [ + ('penalty', 999), ('fix', 'Unregistered advice'), ('references', ['unreviewed reference']), + ('rule_version', 'outdated'), ('reviewed_on', '2020-01-01'), + ('rule_applicability', 'All websites'), +]) +def test_live_registry_metadata_cannot_be_replaced(field, value): + rule = rule_result('images.missing_alt', {}) + rule[field] = value + with pytest.raises(ContractError) as error: + validate_rule_result(rule) + assert error.value.path == '$.' + field + + +@pytest.mark.parametrize('changes', [ + {'status': 'pass', 'applicability': 'not_applicable'}, {'reported_by': 7}, + {'reported_by': ['unknown_analyzer']}, {'status': 'error', 'reason': ''}, +]) +def test_nested_observations_obey_the_outcome_contract(changes): + rule = merge_rule_results([rule_result('images.missing_alt', {})])[0] + rule['observations'][0].update(changes) + with pytest.raises(ContractError) as error: + validate_rule_result(rule) + assert error.value.path.startswith('$.observations[0].') + + +@pytest.mark.parametrize('parallel', [False, True]) +def test_application_extracts_one_snapshot_for_all_five_analyzers(monkeypatch, parallel): + import tfq0seo.core.app as app + import tfq0seo.page_facts as extraction + calls, snapshots = [], [] + original = extraction.extract_page_facts + + def extract(*args, **kwargs): + calls.append(args[1]) + return original(*args, **kwargs) + + monkeypatch.setattr(app, 'extract_page_facts', extract) + monkeypatch.setattr(extraction, 'extract_page_facts', extract) + for name in ('seo', 'content', 'technical', 'performance', 'links'): + analyze = getattr(app, 'analyze_' + name) + + def observe(*args, _analyze=analyze, **kwargs): + snapshots.append(kwargs['facts']) + return _analyze(*args, **kwargs) + + monkeypatch.setattr(app, 'analyze_' + name, observe) + analyzer = SEOAnalyzer(Config.from_dict({'analysis': {'parallel_analysis': parallel}})) + page = asyncio.run(analyzer.analyze_page(raw_page(headers={}))) + assert not page['analyzer_errors'] + assert calls == [page['url']] + assert len(snapshots) == 5 + assert all(snapshot is snapshots[0] for snapshot in snapshots) + json.dumps(page, allow_nan=False) diff --git a/tests/test_page_facts.py b/tests/test_page_facts.py new file mode 100644 index 0000000..01ff55a --- /dev/null +++ b/tests/test_page_facts.py @@ -0,0 +1,231 @@ +"""Shared snapshots retain HTML semantics and isolate analyzer observations.""" + +import asyncio +import copy +import json +from dataclasses import FrozenInstanceError, replace + +import pytest +from bs4 import BeautifulSoup +from multidict import CIMultiDict + +from tfq0seo.analyzers.content import analyze_content, extract_text_content +from tfq0seo.analyzers.seo import analyze_seo +from tfq0seo.page_facts import FACTS_VERSION, ensure_page_facts, extract_page_facts + + +URL = 'https://example.test/articles/' + + +def document(body='', head='', lang='en'): + return BeautifulSoup(f'Example{head}' + f'{body}', 'html.parser') + + +def test_snapshot_collections_and_nested_storage_are_isolated_from_mutation(): + soup = document('

Heading

') + headers = {'X-Robots-Tag': ['nofollow']} + facts = extract_page_facts(soup, URL, headers) + before = facts.to_dict() + images = facts.images + images[0]['attrs']['class'].append('changed') + facts.headers['x-robots-tag'].append('noindex') + facts.headings['headings']['h1'].clear() + headers['X-Robots-Tag'].append('noindex') + soup.img['src'] = '/changed.png' + assert facts.to_dict() == before + with pytest.raises(FrozenInstanceError): + facts.base_url = 'https://other.test/' + with pytest.raises(TypeError): + facts._snapshot['images'][0]['attrs']['src'] = '/changed.png' + assert copy.deepcopy(facts) is facts + + +def test_declarations_preserve_order_boolean_presence_and_empty_attributes(): + soup = document('

Main

Subsection

', + '' + '' + '') + facts = extract_page_facts(soup, URL) + assert [meta['attrs']['content'] for meta in facts.meta] == ['', 'width=device-width'] + assert 'alt' in facts.images[0]['attrs'] and facts.images[0]['attrs']['alt'] == '' + assert 'alt' not in facts.images[1]['attrs'] + assert 'async' in facts.scripts[0]['attrs'] + assert 'defer' in facts.scripts[1]['attrs'] + assert facts.scripts[2]['text'] == 'export default 1;' + assert all(script['in_head'] for script in facts.scripts) + assert facts.doctype == ('html',) + assert facts.headings['findings'][0]['rule_id'] == 'headings.skipped_level' + assert facts.dom_size == len(soup.find_all(True)) + + +def test_anchor_snapshot_keeps_accessible_name_inputs_and_reference_semantics(): + soup = document('' + 'Accessible label', '') + facts = extract_page_facts(soup, URL) + anchor = facts.anchors[0] + assert anchor['text'] == 'Go now' + assert anchor['text_compact'] == 'Gonow' + assert anchor['labelled_text'] == 'Accessible label' + assert anchor['image_alt_text'] == 'Picture' + assert anchor['position'] == 'nav' + assert anchor['parent_tags'][0] == 'nav' + assert anchor['url'] == 'https://outside.test/base/child//?x=1&x=2&empty=' + assert anchor['url_kind'] == 'external' + assert anchor['attrs']['href'] == 'child//?x=1&x=2&empty=' + + +@pytest.mark.parametrize('headers,observed', [(None, False), ({}, True)]) +def test_unknown_headers_are_distinct_from_observed_empty_headers(headers, observed): + facts = extract_page_facts(document(), URL, headers) + assert facts.headers == headers + assert facts.robots['headers_checked'] is observed + assert facts.to_dict()['headers_observed'] is observed + + +def test_repeated_headers_and_bot_scope_survive_extraction(): + headers = CIMultiDict([('X-Robots-Tag', 'otherbot: noindex'), + ('x-robots-tag', 'googlebot: nofollow'), + ('Content-Security-Policy', "default-src 'self'"), + ('Content-Security-Policy', "script-src 'none'")]) + facts = extract_page_facts(document(), URL, headers, 'OtherBot') + assert facts.user_agent == 'otherbot' + assert facts.robots['noindex'] is True + assert facts.robots['nofollow'] is False + assert facts.headers['content-security-policy'] == ["default-src 'self'", "script-src 'none'"] + assert len(facts.headers['x-robots-tag']) == 2 + + +def test_default_export_omits_bulk_text_scripts_and_raw_response_headers(): + soup = document('

LONG_BODY_MARKER

', '') + facts = extract_page_facts(soup, URL, {'Set-Cookie': 'session=COOKIE_SECRET'}) + exported = facts.to_dict() + encoded = json.dumps(exported, allow_nan=False) + assert exported['facts_version'] == FACTS_VERSION + assert exported['header_names'] == ['set-cookie'] + assert 'headers' not in exported + assert 'COOKIE_SECRET' not in encoded + assert 'LONG_BODY_MARKER' not in encoded + assert 'PRIVATE_SCRIPT_MARKER' not in encoded + assert 'html' not in exported and 'content_text' not in exported and 'text' not in exported + assert exported['paragraph_count'] == 1 + assert exported['scripts'][0]['text_length'] == len('PRIVATE_SCRIPT_MARKER') + full = facts.to_dict(include_content=True) + assert full['html'] == str(soup) + assert full['paragraphs'] == ['LONG_BODY_MARKER'] + assert full['scripts'][0]['text'] == 'PRIVATE_SCRIPT_MARKER' + + +@pytest.mark.parametrize('body,plain,structured', [ + ('

First words

Second\nwords

', 'Example First words Second words', 'Example\nFirst words\nSecond\nwords'), + ('

Visible

', 'Example Visible', 'Example\nVisible'), + ('Vector' + '

Hidden

Shown

', 'Example Shown', 'Example\nShown'), +]) +def test_shared_content_text_preserves_existing_cleaning_behavior(body, plain, structured): + soup = document(body) + before = str(soup) + facts = extract_page_facts(soup, URL) + assert facts.content_text == plain + assert extract_text_content(soup, preserve_structure=True) == structured + assert str(soup) == before + + +@pytest.mark.parametrize('analyzer', [analyze_seo, analyze_content]) +def test_supplied_snapshot_avoids_reextraction_and_matches_standalone_output(monkeypatch, analyzer): + soup = document('

Heading

Some content.

Next page') + expected = analyzer(soup, URL) + facts = extract_page_facts(soup, URL) + + def no_extraction(*args, **kwargs): + raise AssertionError('Shared facts were extracted twice') + + monkeypatch.setattr('tfq0seo.page_facts.extract_page_facts', no_extraction) + monkeypatch.setattr('tfq0seo.analyzers.common.heading_facts', no_extraction) + monkeypatch.setattr('tfq0seo.analyzers.common.parse_robots', no_extraction) + actual = analyzer(soup, URL, facts=facts) + assert actual == expected + assert json.loads(json.dumps(actual, allow_nan=False)) == actual + + +def test_seo_uses_supplied_snapshot_bot_and_headers_when_arguments_are_omitted(): + soup = document() + facts = extract_page_facts(soup, URL, {'X-Robots-Tag': 'otherbot: noindex'}, 'otherbot') + result = analyze_seo(soup, URL, facts=facts) + assert result['data']['robots_analysis']['noindex'] is True + assert result['data']['robots_analysis']['headers_checked'] is True + + +def test_supplied_snapshots_reject_mismatched_input_context(): + soup = document() + facts = extract_page_facts(soup, URL, {'X-Robots-Tag': 'nofollow'}, 'otherbot') + with pytest.raises(ValueError, match='URL and soup'): + ensure_page_facts(soup, URL + 'different', facts=facts) + with pytest.raises(ValueError, match='URL and soup'): + ensure_page_facts(document(), URL, facts=facts) + with pytest.raises(ValueError, match='headers'): + ensure_page_facts(soup, URL, headers={}, facts=facts) + with pytest.raises(ValueError, match='agent'): + analyze_seo(soup, URL, user_agent='googlebot', facts=facts) + with pytest.raises(TypeError, match='PageFacts'): + ensure_page_facts(soup, URL, facts={}) + + +@pytest.mark.parametrize('value', [object(), float('nan'), ['valid', object()]]) +def test_nonportable_parser_attributes_are_rejected_instead_of_stringified(value): + soup = document('') + soup.img['data-custom'] = value + with pytest.raises(TypeError, match='attribute value'): + extract_page_facts(soup, URL) + + +@pytest.mark.parametrize('headers', [{'X-Value': object()}, {'X-Value': [1]}, {1: 'value'}]) +def test_invalid_header_values_are_rejected_without_implicit_conversion(headers): + with pytest.raises(TypeError, match='header'): + extract_page_facts(document(), URL, headers) + + +def test_direct_constructor_rejects_incomplete_or_nonportable_snapshots(): + facts = extract_page_facts(document(), URL) + with pytest.raises(ValueError, match='complete snapshot'): + replace(facts, _snapshot={}) + with pytest.raises(TypeError, match='language'): + replace(facts, language=object()) + malformed = dict(facts._snapshot) + malformed['extra'] = object() + with pytest.raises(TypeError, match='finite JSON primitives'): + replace(facts, _snapshot=malformed) + + +def test_application_extracts_one_snapshot_and_passes_it_to_all_five_analyzers(monkeypatch): + from tfq0seo.core import app + from tfq0seo import page_facts as module + + extracted, received = [], {} + original_extract = module.extract_page_facts + + def counted_extract(*args, **kwargs): + facts = original_extract(*args, **kwargs) + extracted.append(facts) + return facts + + monkeypatch.setattr(module, 'extract_page_facts', counted_extract) + monkeypatch.setattr(app, 'extract_page_facts', counted_extract) + for name in ('seo', 'content', 'technical', 'performance', 'links'): + function = getattr(app, 'analyze_' + name) + + def observe(*args, _name=name, _function=function, **kwargs): + received[_name] = kwargs.get('facts') + return _function(*args, **kwargs) + + monkeypatch.setattr(app, 'analyze_' + name, observe) + soup = document('

Example

Content.

Next page') + before = str(soup) + result = asyncio.run(app.SEOAnalyzer().analyze_page({'url': URL, 'soup': soup, 'headers': {}, 'status_code': 200})) + assert result['status'] == 'complete', result.get('analyzer_errors') + assert len(extracted) == 1 + assert len(received) == 5 and all(facts is extracted[0] for facts in received.values()) + assert result['page_facts'] == extracted[0].to_dict() + assert str(soup) == before + assert json.loads(json.dumps(result, allow_nan=False)) == result diff --git a/tests/test_readability_offline.py b/tests/test_readability_offline.py new file mode 100644 index 0000000..69b6c08 --- /dev/null +++ b/tests/test_readability_offline.py @@ -0,0 +1,145 @@ +"""Readability must not download optional dictionaries during analysis.""" + +import json +import socket +from types import SimpleNamespace + +import pytest +from bs4 import BeautifulSoup + +from tfq0seo.analyzers import content +from tfq0seo.core.models import validate_analyzer_result + + +TEXT = ('This simple guide explains how people can read and understand a useful article. ' * 12).strip() + + +@pytest.fixture +def forbid_network(monkeypatch): + calls = [] + + def forbidden(*args, **kwargs): + calls.append(args) + raise AssertionError('Readability must not request network access or dictionary downloads') + + monkeypatch.setattr(socket, 'getaddrinfo', forbidden) + monkeypatch.setattr(socket, 'create_connection', forbidden) + nltk = pytest.importorskip('nltk') + monkeypatch.setattr(nltk, 'download', forbidden) + yield calls + assert calls == [] + + +def test_missing_local_dictionary_returns_null_estimates_without_downloading(monkeypatch, tmp_path, forbid_network): + nltk = pytest.importorskip('nltk') + monkeypatch.setattr(nltk.data, 'path', [str(tmp_path)]) + for _ in range(2): + result = content.calculate_advanced_readability(TEXT, 'en') + assert result['status'] == 'unavailable' + assert result['source'] == 'textstat' + assert result['resource_policy'] == 'local_only' + assert result['missing_resources'] == ['nltk:corpora/cmudict'] + assert 'Runtime resource downloads are disabled' in result['reason'] + assert all(result[key] is None for key in content._READABILITY_VALUES) + assert json.loads(json.dumps(result, allow_nan=False)) == result + + +def test_corrupt_local_dictionary_archive_is_unavailable_without_downloading(monkeypatch, tmp_path, forbid_network): + nltk = pytest.importorskip('nltk') + archive = tmp_path / 'corpora' / 'cmudict.zip' + archive.parent.mkdir() + archive.write_bytes(b'Not a ZIP archive') + monkeypatch.setattr(nltk.data, 'path', [str(tmp_path)]) + result = content.calculate_advanced_readability(TEXT, 'en') + assert result['status'] == 'unavailable' + assert result['consensus_grade'] is None + + +def test_english_analyzer_marks_readability_unknown_when_local_dictionary_is_missing(monkeypatch, tmp_path, forbid_network): + nltk = pytest.importorskip('nltk') + monkeypatch.setattr(nltk.data, 'path', [str(tmp_path)]) + soup = BeautifulSoup('Guide

Guide

' + + TEXT + '

', 'html.parser') + result = content.analyze_content(soup, 'https://example.test/guide') + validate_analyzer_result(result) + assert result['data']['language'] == 'en' + assert result['data']['readability']['status'] == 'unavailable' + assert 'Difficult to read' not in result['data']['quality_assessment']['weaknesses'] + for rule_id in ('content.readability_difficult', 'content.readability_grade'): + rule = next(item for item in result['rule_results'] if item['rule_id'] == rule_id) + assert rule['status'] == 'unknown' + assert rule['evidence']['value'] is None + assert rule['evidence']['measurement_status'] == 'unavailable' + assert 'local NLTK' in rule['reason'] + assert rule['penalty'] == 0 + + +def test_installed_local_dictionary_allows_real_textstat_estimates(monkeypatch, tmp_path, forbid_network): + nltk = pytest.importorskip('nltk') + from nltk.corpus.reader import CMUDictCorpusReader + from textstat.backend.utils._get_cmudict import get_cmudict + from textstat.backend.counts._count_syllables import count_syllables + + dictionary = tmp_path / 'corpora' / 'cmudict' + dictionary.mkdir(parents=True) + (dictionary / 'cmudict').write_text('GUIDE 1 G AY1 D\nARTICLE 1 AA1 R T IH0 K AH0 L\n', encoding='utf-8') + monkeypatch.setattr(nltk.data, 'path', [str(tmp_path)]) + monkeypatch.setattr(nltk.corpus, 'cmudict', CMUDictCorpusReader(str(dictionary), ['cmudict'])) + get_cmudict.cache_clear() + count_syllables.cache_clear() + try: + result = content.calculate_advanced_readability(TEXT, 'en') + assert result['status'] == 'estimate', result + assert result['resource_policy'] == 'local_only' + assert result['missing_resources'] == [] + assert isinstance(result['flesch_reading_ease'], (int, float)) + assert isinstance(result['consensus_grade'], (int, float)) + assert result['syllable_count'] > 0 + assert 'error' not in result + assert json.loads(json.dumps(result, allow_nan=False)) == result + finally: + get_cmudict.cache_clear() + count_syllables.cache_clear() + + +def test_legacy_packaged_resource_backend_does_not_require_nltk_corpus(monkeypatch, forbid_network): + nltk = pytest.importorskip('nltk') + + def unexpected_lookup(*args, **kwargs): + raise AssertionError('Legacy textstat uses packaged dictionaries') + + monkeypatch.setattr(nltk.data, 'find', unexpected_lookup) + # textstat 0.7.3-0.7.5 expose these metric methods without a backend package. + method_names = ('flesch_reading_ease', 'flesch_kincaid_grade', 'gunning_fog', 'smog_index', + 'automated_readability_index', 'coleman_liau_index', 'linsear_write_formula', + 'dale_chall_readability_score', 'text_standard', 'reading_time', + 'syllable_count', 'polysyllabcount', 'sentence_count') + legacy = SimpleNamespace(**{name: (lambda *args, **kwargs: 12.0) for name in method_names}) + monkeypatch.setattr(content, 'textstat', legacy) + result = content.calculate_advanced_readability(TEXT, 'en') + assert result['status'] == 'estimate' + assert result['consensus_grade'] == 12.0 + + +def test_non_english_readability_does_not_check_or_download_english_resources(monkeypatch, forbid_network): + def unexpected_check(): + raise AssertionError('English resource checks are not applicable') + + monkeypatch.setattr(content, '_readability_resource_error', unexpected_check) + result = content.calculate_advanced_readability('هذا نص عربي للاختبار.', 'ar') + assert result['status'] == 'not_applicable' + assert 'flesch_reading_ease' not in result + + +def test_local_metric_failure_does_not_leave_partial_or_fabricated_estimates(monkeypatch, forbid_network): + monkeypatch.setattr(content, '_readability_resource_error', lambda: None) + monkeypatch.setattr(content.textstat, 'flesch_reading_ease', lambda text: 73.0) + + def failed_metric(text): + raise LookupError('Local dictionary file cannot be read') + + monkeypatch.setattr(content.textstat, 'flesch_kincaid_grade', failed_metric) + result = content.calculate_advanced_readability(TEXT, 'en') + assert result['status'] == 'unavailable' + assert 'cannot be read' in result['error'] + assert all(result[key] is None for key in content._READABILITY_VALUES) diff --git a/tests/test_report_contracts.py b/tests/test_report_contracts.py new file mode 100644 index 0000000..01de80d --- /dev/null +++ b/tests/test_report_contracts.py @@ -0,0 +1,209 @@ +"""Shared producer/import contracts and export validation boundaries.""" + +import asyncio +import copy +import csv +import json +from pathlib import Path + +import pytest +from bs4 import BeautifulSoup +from click.testing import CliRunner +from openpyxl import load_workbook + +from tfq0seo.cli import cli +from tfq0seo.core.app import SEOAnalyzer +from tfq0seo.core.models import ContractError +from tfq0seo.core.report_contracts import validate_page_result, validate_report, validate_site_report +from tfq0seo.exporters.base import ExportManager + + +@pytest.fixture +def page(): + html = 'Example title

Example heading

Useful words for this local fixture.

' + return asyncio.run(SEOAnalyzer().analyze_page({'url': 'https://example.test/page', 'status_code': 200, + 'soup': BeautifulSoup(html, 'html.parser'), 'content_length': len(html), 'headers': {}})) + + +def test_real_generated_envelopes_validate_strictly_without_mutation(page): + report = SEOAnalyzer().generate_site_report([page]) + for value, validator in ((page, validate_page_result), (report, validate_site_report)): + original = copy.deepcopy(value) + assert validator(value, strict=True) is value + assert validate_report(value, strict=True) is value + assert value == original + + +def test_minimal_error_site_and_failed_page_remain_exportable(): + site = {'schema_version': '1.0', 'status': 'error', 'error': 'No pages to analyze'} + assert validate_site_report(site, strict=True) is site + assert validate_report(site, strict=True) is site + page = asyncio.run(SEOAnalyzer().analyze_page({'url': 'https://example.test/failure', 'status_code': 404, 'error': 'Not found'})) + assert validate_page_result(page, strict=True) is page + + +def test_imported_unknown_rules_and_untrusted_strings_are_not_rewritten(): + archived = {'schema_version': 'historical', 'url': 'javascript:alert(1)', + 'issues': [{'rule_id': 'removed.old_rule', 'rule_version': 'old', 'message': '', + 'evidence': {'html': ''}, 'fix': 'Original archived guidance'}], + 'recommendations': ['Original recommendation'], 'page_facts': {'future_key': ['additive', None]}} + original = copy.deepcopy(archived) + assert validate_report(archived) is archived + assert archived == original + + +@pytest.mark.parametrize('pages', [ + [{'url': 'https://example.test/', 'score': None, 'issues': {'total': 3}}], + {'summary': [{'url': 'https://example.test/', 'score': 75, 'issues': {'warning': 2}}]}, + {'detailed': [{'url': 'https://example.test/', 'seo': {'score': 80}}], 'failed': [], 'skipped': []}, +]) +def test_historical_page_shapes_and_missing_optional_fields_are_supported(pages): + report = {'pages': pages, 'recommendations': ['Legacy guidance']} + assert validate_report(report) is report + + +def test_strict_site_can_contain_compatible_legacy_pages(page): + report = SEOAnalyzer().generate_site_report([page]) + report['pages']['detailed'] = [{'url': page['url'], 'overall_score': 70}] + assert validate_site_report(report, strict=True) is report + + +def test_site_generation_accepts_legacy_pages_without_http_measurements(): + report = SEOAnalyzer().generate_site_report([{'url': 'https://example.test/legacy', 'overall_score': 70, 'issues': []}]) + assert report['pages']['summary'][0]['status_code'] is None + assert validate_site_report(report, strict=True) is report + + +@pytest.mark.parametrize('payload,path', [ + ({'seo': None}, '$.seo'), + ({'seo': {'data': None}}, '$.seo.data'), + ({'content': {'data': {'metrics': []}}}, '$.content.data.metrics'), + ({'content': {'data': {'metrics': {'word_count': 'many'}}}}, '$.content.data.metrics.word_count'), + ({'content': {'data': {'readability': None}}}, '$.content.data.readability'), + ({'seo': {'data': {'title': {'text': []}}}}, '$.seo.data.title.text'), + ({'seo': {'data': {'structured_data': None}}}, '$.seo.data.structured_data'), + ({'issues': [None]}, '$.issues[0]'), + ({'issues': [{'severity': []}]}, '$.issues[0].severity'), + ({'issue_counts': {'total': True}}, '$.issue_counts.total'), + ({'overall_score': '90'}, '$.overall_score'), + ({'overall_score': 101}, '$.overall_score'), + ({'scores': None}, '$.scores'), + ({'scores': {'categories': {'seo': []}}}, '$.scores.categories.seo'), + ({'recommendations': [False]}, '$.recommendations[0]'), + ({'recommendations': {'specific': [7]}}, '$.recommendations.specific[0]'), + ({'pages': [{'url': 'https://example.test/'}, 7]}, '$.pages[1]'), + ({'pages': {'failed': {}}}, '$.pages.failed'), + ({'pages': {'detailed': [{'url': 7}]}}, '$.pages.detailed[0].url'), + ({'pages': [], 'issues': {'aggregated': [None]}}, '$.issues.aggregated[0]'), +]) +def test_present_malformed_structure_is_rejected_with_its_path(payload, path): + with pytest.raises(ContractError) as caught: + validate_report(payload) + assert path in str(caught.value) + + +@pytest.mark.parametrize('value', [float('nan'), float('inf'), float('-inf'), object(), {'unsupported'}, (1, 2)]) +def test_nonportable_nested_extension_values_are_rejected(value): + with pytest.raises(ContractError) as caught: + validate_report({'url': 'https://example.test/', 'future_extension': {'value': value}}) + assert 'future_extension' in str(caught.value) + + +def test_strict_envelope_missing_fields_report_the_producer_path(): + with pytest.raises(ContractError) as caught: + validate_page_result({'url': 'https://example.test/'}, strict=True, path='$.pages[0]') + assert '$.pages[0].schema_version' in str(caught.value) + with pytest.raises(ContractError) as caught: + validate_site_report({'schema_version': '1.0', 'status': 'complete'}, strict=True) + assert '$.summary' in str(caught.value) + + +def test_strict_failed_page_cannot_claim_a_measured_score(page): + page.update(status='error', error='Fetch failed', overall_score=100) + with pytest.raises(ContractError) as caught: + validate_page_result(page, strict=True) + assert '$.overall_score' in str(caught.value) + page['overall_score'] = None + assert validate_page_result(page, strict=True) is page + + +def test_strict_failed_page_requires_an_explanation(page): + page.update(status='error', overall_score=None) + with pytest.raises(ContractError) as caught: + validate_page_result(page, strict=True) + assert '$.error' in str(caught.value) + + +@pytest.mark.parametrize('format', ['json', 'csv', 'xlsx', 'html']) +@pytest.mark.parametrize('direct', [False, True]) +def test_all_writer_entry_points_reject_invalid_payload_before_truncation(tmp_path, format, direct): + exporter = ExportManager({'output_directory': str(tmp_path)}) + destination = tmp_path / ('existing.' + format) + destination.write_bytes(b'previous report') + payload = {'url': 'https://example.test/', 'content': {'data': {'metrics': None}}} + with pytest.raises(ContractError): + if direct: + getattr(exporter, 'export_' + format)(payload, destination) + else: + exporter.export(payload, format, str(destination)) + assert destination.read_bytes() == b'previous report' + + +@pytest.mark.parametrize('literal', ['NaN', 'Infinity', '-Infinity', '1e400']) +def test_cli_rejects_nonfinite_json_before_creating_output(tmp_path, monkeypatch, literal): + monkeypatch.chdir(tmp_path) + source = tmp_path / 'source.json' + destination = tmp_path / 'report.csv' + source.write_text('{"url":"https://example.test/","overall_score":' + literal + '}', encoding='utf-8') + result = CliRunner().invoke(cli, ['export', '-i', str(source), '-f', 'csv', '-o', str(destination)]) + assert result.exit_code != 0 + assert 'finite' in result.output.lower() + assert not destination.exists() + + +@pytest.mark.parametrize('site', [False, True]) +def test_real_word_count_reaches_csv_and_excel(tmp_path, page, site): + expected = page['content']['data']['metrics']['word_count'] + report = SEOAnalyzer().generate_site_report([page]) if site else page + exporter = ExportManager({'output_directory': str(tmp_path)}) + with Path(exporter.export(report, 'csv')).open(encoding='utf-8', newline='') as stream: + assert int(next(csv.DictReader(stream))['word_count']) == expected + workbook = load_workbook(exporter.export(report, 'xlsx'), read_only=True) + try: + sheet = workbook['Pages'] + headers = [cell.value for cell in next(sheet.iter_rows())] + values = [cell.value for cell in next(sheet.iter_rows(min_row=2, max_row=2))] + assert values[headers.index('Word Count')] == expected + finally: + workbook.close() + + +def test_real_word_count_reaches_enhanced_html(tmp_path, page): + exporter = ExportManager({'output_directory': str(tmp_path), 'html_template': 'enhanced'}) + output = Path(exporter.export(page, 'html')) + soup = BeautifulSoup(output.read_text(encoding='utf-8'), 'html.parser') + values = {card.select_one('.metric-label').get_text(strip=True): card.select_one('.metric-value').get_text(strip=True) + for card in soup.select('#content .metric-card')} + assert values['Word Count'] == str(page['content']['data']['metrics']['word_count']) + + +def test_legacy_flat_word_count_and_explicit_unknown_nested_count_are_preserved(tmp_path): + exporter = ExportManager({'output_directory': str(tmp_path)}) + legacy = {'url': 'https://example.test/', 'content': {'data': {'word_count': 12}}} + assert exporter._flatten_page_data(legacy)['word_count'] == 12 + legacy['content']['data']['metrics'] = {'word_count': None} + assert exporter._flatten_page_data(legacy)['word_count'] is None + assert exporter._prepare_html_data(legacy)['content_data']['word_count'] is None + + +def test_partial_legacy_summary_and_string_recommendations_still_render(tmp_path): + report = {'pages': [{'url': 'https://example.test/', 'score': 75}], + 'recommendations': {'executive': {'overview': {'overall_health': 'Archived assessment'}}, + 'specific': ['Preserve this legacy recommendation']}, + 'aggregation_stats': {'unique_issues': 1}} + original = copy.deepcopy(report) + output = ExportManager({'output_directory': str(tmp_path)}).export(report, 'html') + text = BeautifulSoup(Path(output).read_text(encoding='utf-8'), 'html.parser').get_text(' ', strip=True) + assert 'Archived assessment' in text + assert 'Preserve this legacy recommendation' in text + assert report == original diff --git a/tests/test_rule_reports.py b/tests/test_rule_reports.py new file mode 100644 index 0000000..f9a8cd7 --- /dev/null +++ b/tests/test_rule_reports.py @@ -0,0 +1,128 @@ +"""Rule provenance is readable and inert across the existing HTML layouts.""" + +import asyncio +import copy +import json +import re +from pathlib import Path + +import pytest +from bs4 import BeautifulSoup + +from tfq0seo.core.app import SEOAnalyzer +from tfq0seo.core.config import Config +from tfq0seo.exporters.base import ExportManager + + +TEMPLATES = ('report', 'enhanced', 'optimized') + + +@pytest.fixture +def analyzed_page(): + config = Config.from_dict({'analysis': {'enabled_analyzers': ['seo'], 'score_weights': {'seo': 1.0}}}) + html = 'Rule report

Example

' + return asyncio.run(SEOAnalyzer(config).analyze_page({ + 'url': 'https://example.test/report/', 'status_code': 200, 'headers': {}, + 'load_time': 0.1, 'soup': BeautifulSoup(html, 'html.parser'), + })) + + +def render(tmp_path, template, data): + exporter = ExportManager({'output_directory': str(tmp_path), 'html_template': template}) + path = Path(exporter.export(data, 'html')) + html = path.read_text(encoding='utf-8') + return BeautifulSoup(html, 'html.parser'), html, exporter + + +@pytest.mark.parametrize('template', TEMPLATES) +@pytest.mark.parametrize('kind', ('page', 'site')) +def test_rule_metadata_and_policy_render_from_application_results(tmp_path, analyzed_page, template, kind): + data = analyzed_page if kind == 'page' else SEOAnalyzer().generate_site_report([analyzed_page]) + before = copy.deepcopy(data) + soup, _, exporter = render(tmp_path, template, data) + metadata = soup.select_one('.rule-metadata[data-rule-id="images.missing_alt"]') + assert metadata is not None + text = metadata.get_text(' ', strip=True) + for expected in ('Rule:', 'Outcome: fail', 'Applicability: applicable', 'Observation source:', 'Rule reviewed: 2026-09-14'): + assert expected in text + assert metadata.select_one('details.rule-evidence summary').get_text() == 'Recorded evidence' + evidence = json.loads(metadata.select_one('details.rule-evidence pre').get_text()) + assert '/image.png' in json.dumps(evidence) + assert metadata.select_one('.rule-references a')['href'].startswith('https://') + assert 'Rule deduction: 7 points' in text + if kind == 'site': + per_page = next(details for details in metadata.select('details') + if details.select_one('summary').get_text() == 'Evidence by affected page') + assert json.loads(per_page.select_one('pre').get_text())[0]['url'] == analyzed_page['url'] + overview = soup.select_one('.rule-assessment') + assert data['scoring']['version'] in overview.get_text() + assert data['scoring']['policy'] in overview.get_text() + assert 'not search ranking factors' in overview.get_text() + assert 'unknown' in overview.select_one('.rule-coverage-counts').get_text() + assert 'not passed checks' in overview.get_text() + assert exporter._prepare_html_data(data)['rule_coverage'] == data['rule_coverage'] + assert data == before + + +@pytest.mark.parametrize('template', TEMPLATES) +def test_untrusted_rule_metadata_is_text_not_executable_markup(tmp_path, analyzed_page, template): + payload = '' + issue = { + 'rule_id': payload, 'category': 'Imported rule', 'severity': 'warning', 'message': 'Imported finding', + 'status': payload, 'applicability': payload, 'rule_applicability': payload, + 'reason': payload, 'source': payload, 'reviewed_on': payload, + 'references': ['javascript:alert(1)', 'data:text/html,' + payload, '//example.test/path', + 'https:\n//example.test', 'https://example.test/reference?q="' + payload], + 'evidence': {'observed': payload}, 'observations': [{'evidence': payload}], + } + data = copy.deepcopy(analyzed_page) + data['issues'] = [issue] + data['scoring'] = {'version': payload, 'ruleset_version': payload, 'policy': payload, + 'scope': payload, 'weights': {'seo': payload}} + data['rule_coverage'] = {'total': 1, 'assessed': 0, 'counts': {'unknown': 1}, 'scope': payload} + soup, rendered, _ = render(tmp_path, template, data) + assert not soup.find('img') + assert not soup.select('[onerror]') + assert not any('alert(2)' in (script.string or '') and '\\u003c' not in (script.string or '') + for script in soup.find_all('script')) + assert 'innerHTML' not in rendered + metadata = soup.select_one('.rule-metadata') + assert metadata['data-rule-id'] == payload + assert payload in metadata.get_text() + assert json.loads(metadata.select_one('.rule-evidence pre').get_text()) == {'observed': payload} + references = metadata.select('.rule-references a') + assert len(references) == 1 + assert references[0]['href'].startswith('https://example.test/reference') + assert payload in soup.select_one('.rule-assessment').get_text() + + +@pytest.mark.parametrize('template', TEMPLATES) +def test_legacy_reports_without_rule_metadata_still_render(tmp_path, template): + data = {'url': 'https://example.test/legacy', 'overall_score': 70, + 'issues': [{'category': 'Legacy', 'severity': 'warning', 'message': 'Legacy observation'}]} + soup, _, _ = render(tmp_path, template, data) + assert 'Legacy observation' in soup.get_text() + assert not soup.select('.rule-metadata') + assert not soup.select('.rule-assessment') + + +@pytest.mark.parametrize('template', TEMPLATES) +def test_scoring_version_list_survives_older_site_adapter_shape(tmp_path, template): + data = {'scores': {'overall': None, 'scoring_versions': ['older-policy', '2.0']}, 'pages': []} + soup, _, _ = render(tmp_path, template, data) + assert 'Scoring versions: older-policy, 2.0' in soup.select_one('.rule-assessment').get_text(' ', strip=True) + + +@pytest.mark.parametrize('template', TEMPLATES) +def test_rule_metadata_does_not_drop_paginated_pages(tmp_path, analyzed_page, template): + pages = [dict(copy.deepcopy(analyzed_page), url=f'https://example.test/page-{index}') for index in range(25)] + report = SEOAnalyzer().generate_site_report(pages) + soup, html, exporter = render(tmp_path, template, report) + assert len(exporter._prepare_html_data(report)['pages_summary']) == 25 + if template == 'optimized': + embedded = re.search(r'const pagesData = (.*);', html).group(1) + assert len(json.loads(embedded)) == 25 + assert 'Page 1 of 2' in soup.get_text() + else: + assert len(soup.select('.pages-table tbody tr')) == 25 + assert soup.select('.rule-metadata') diff --git a/tests/test_rules.py b/tests/test_rules.py new file mode 100644 index 0000000..46c72be --- /dev/null +++ b/tests/test_rules.py @@ -0,0 +1,289 @@ +"""Behavioral guarantees for reviewed rules and shared scoring.""" + +import asyncio +import copy +import dataclasses +from datetime import date + +import pytest +from bs4 import BeautifulSoup + +from tfq0seo.core.app import SEOAnalyzer +from tfq0seo.core.config import Config +from tfq0seo.core.report_optimizer import aggregate_issues, generate_specific_recommendations +from tfq0seo.rules import (RULES, RuleCollector, get_rule, register_rules, rule_result, + merge_rule_results, rule_coverage, score_findings, recommendations_for) + + +def test_registered_rules_have_reviewed_metadata(): + for rule_id, definition in RULES.items(): + assert rule_id == definition.rule_id + assert definition.applicability and definition.recommendation + assert definition.references and all(reference.startswith('https://') for reference in definition.references) + assert date.fromisoformat(definition.reviewed_on) <= date.today() + with pytest.raises(TypeError): + RULES['new.rule'] = get_rule('headings.empty') + with pytest.raises(dataclasses.FrozenInstanceError): + get_rule('headings.empty').severity = 'notice' + + +def test_conflicting_registration_is_atomic(): + original = dict(RULES) + with pytest.raises(ValueError, match='Conflicting'): + register_rules([dataclasses.replace(get_rule('headings.empty'), rule_id='test.atomic'), + dataclasses.replace(get_rule('headings.empty'), severity='critical')]) + assert dict(RULES) == original + + +@pytest.mark.parametrize('failed,applicable,expected', [ + (True, True, 'fail'), (False, True, 'pass'), (None, True, 'unknown'), + (True, None, 'unknown'), (True, False, 'not_applicable'), +]) +def test_applicability_and_observation_control_status(failed, applicable, expected): + collector = RuleCollector('content') + result = collector.check('headings.empty', failed, {'text': ''}, applicable=applicable, + reason='Fixture provides context for unavailable or inapplicable checks.') + assert result['status'] == expected + assert score_findings(collector.issues) == (93 if expected == 'fail' else 100) + + +def test_errors_and_advisories_do_not_penalize_a_site(): + collector = RuleCollector('seo') + collector.check('robots.noindex', True, {'directives': ['noindex']}) + collector.check('headings.empty', None, {'text': None}, status='error', reason='Fixture extraction error') + assert collector.issues[0]['status'] == 'informational' + assert collector.coverage['counts']['error'] == 1 + assert score_findings(collector.results) == 100 + + +@pytest.mark.parametrize('evidence', [None, 'message only', {'duration': float('nan')}, {'element': object()}]) +def test_nonportable_or_unstructured_evidence_is_rejected(evidence): + with pytest.raises((ValueError, TypeError)): + rule_result('headings.empty', evidence) + + +def test_unknown_results_need_an_explanation(): + with pytest.raises(ValueError, match='explanation'): + rule_result('headings.empty', {}, status='unknown') + with pytest.raises(ValueError, match='Unregistered'): + rule_result('unknown.rule', {'text': ''}) + + +def test_message_changes_cannot_change_fix_severity_or_score(): + first = rule_result('headings.empty', {'text': ''}, message='Missing title or cache or font') + second = rule_result('headings.empty', {'text': ''}, message='Translated description of the same finding') + assert first['fix'] == second['fix'] == get_rule('headings.empty').recommendation + assert score_findings([first]) == score_findings([second]) == 93 + assert recommendations_for([first, second]) == [first['fix']] + + +def test_duplicate_rule_evidence_is_retained_with_one_penalty(): + seo = RuleCollector('seo') + content = RuleCollector('content') + seo.check('headings.empty', True, {'positions': [0]}) + content.check('headings.empty', True, {'positions': [0, 3]}) + results = seo.results + content.results + merged = merge_rule_results(results) + assert len(merged) == 1 and len(merged[0]['observations']) == 2 + assert merged[0]['reported_by'] == ['content', 'seo'] + assert score_findings(results) == 93 + assert rule_coverage(results)['counts']['fail'] == 1 + assert merge_rule_results(merged) == merged + + +def synthetic_categories(): + result = {} + for name in ('seo', 'content'): + collector = RuleCollector(name) + collector.check('images.missing_alt', True, {'urls': ['/image.png']}) + result[name] = {'score': score_findings(collector.issues), 'issues': collector.issues, + 'rule_results': collector.results} + return result + + +def test_category_ownership_prevents_cross_category_penalties(): + analyzer = SEOAnalyzer(Config.from_dict({'analysis': {'score_weights': {'seo': 0.5, 'content': 0.5}}})) + result = synthetic_categories() + analyzer._apply_rule_scoring(result) + assert result['seo']['score'] == 100 + assert result['content']['score'] == 93 + assert analyzer._calculate_weighted_score(result) == 96.5 + assert len(result['scoring']['deductions']) == 1 + assert result['scoring']['deductions'][0]['score_owner'] == 'content' + snapshot = copy.deepcopy(result) + analyzer._apply_rule_scoring(result) + assert result == snapshot + + +def test_disabled_owner_uses_one_observer_and_zero_weights_are_respected(): + analyzer = SEOAnalyzer(Config.from_dict({'analysis': {'score_weights': {'seo': 1.0, 'content': 0.0}}})) + result = synthetic_categories() + analyzer._apply_rule_scoring(result) + assert analyzer._calculate_weighted_score(result) == 100 + del result['content'] + analyzer._apply_rule_scoring(result) + assert result['seo']['score'] == 93 + assert analyzer._calculate_weighted_score(result) == 93 + + +def test_site_aggregation_groups_by_id_and_keeps_each_pages_evidence(): + issues = [dict(rule_result('headings.empty', {'position': i}, category=category), url=url) + for i, category, url in ((0, 'SEO', 'https://example.test/a'), (2, 'Content', 'https://example.test/b'))] + grouped, _ = aggregate_issues(issues) + assert len(grouped) == 1 and grouped[0]['pages_affected'] == 2 + assert len(grouped[0]['evidence_by_page']) == 2 + grouped[0]['fix'] = 'Incorrect cached text' + recs = generate_specific_recommendations({'issues': {'aggregated': grouped}}) + assert recs[0]['description'] == get_rule('headings.empty').recommendation + + +def test_ruleset_version_participates_in_cache_identity(monkeypatch): + async def run(): + analyzer = SEOAnalyzer(Config.from_dict({'profile': 'quick'})) + raw = {'url': 'https://example.test/', 'status_code': 200, 'headers': {}, + 'soup': BeautifulSoup('Fixture

Fixture

', 'html.parser')} + first = await analyzer.analyze_page(raw) + assert not first.get('analyzer_errors'), first + assert (await analyzer.analyze_page(raw)).get('cached') + monkeypatch.setattr('tfq0seo.core.app.RULESET_VERSION', 'fixture-next') + assert not (await analyzer.analyze_page(raw)).get('cached') + asyncio.run(run()) + + +def test_failed_canonical_owner_does_not_hide_a_valid_observer_deduction(): + analyzer = SEOAnalyzer(Config.from_dict({'analysis': {'score_weights': {'seo': 0.5, 'content': 0.5}}})) + result = synthetic_categories() + result['content'] = {'score': None, 'status': 'error', 'error': 'Content extraction failed', 'issues': []} + analyzer._apply_rule_scoring(result) + assert result['content']['score'] is None + assert result['seo']['score'] == 93 + assert result['scoring']['deductions'][0]['score_owner'] == 'seo' + assert analyzer._calculate_weighted_score(result) == 93 + + +def test_unknown_and_error_rule_coverage_survives_page_scoring(): + analyzer = SEOAnalyzer(Config.from_dict({'analysis': {'score_weights': {'content': 1.0}}})) + collector = RuleCollector('content') + collector.check('headings.empty', None, {'headings': None}, reason='HTML unavailable') + collector.check('images.missing_alt', None, {'images': None}, status='error', reason='Image extraction failed') + result = {'content': {'score': 100, 'issues': [], 'rule_results': collector.results}} + analyzer._apply_rule_scoring(result) + assert result['rule_coverage']['counts']['pass'] == 0 + assert result['rule_coverage']['counts']['unknown'] == 1 + assert result['rule_coverage']['counts']['error'] == 1 + assert result['rule_coverage']['ratio'] == 0 + assert result['scoring']['deductions'] == [] + + +def test_rule_error_marks_analyzer_and_page_partial_without_penalty(monkeypatch): + def partial_content(*args, **kwargs): + collector = RuleCollector('content') + collector.check('headings.empty', None, {'headings': None}, status='error', reason='Fixture extraction error') + collector.check('images.missing_alt', False, {'images': []}) + return {'score': 100, 'issues': [], 'rule_results': collector.results, 'data': {}} + + monkeypatch.setattr('tfq0seo.core.app.analyze_content', partial_content) + + async def run(): + analyzer = SEOAnalyzer(Config.from_dict({'analysis': {'enabled_analyzers': ['content'], 'score_weights': {'content': 1.0}}})) + raw = {'url': 'https://example.test/', 'status_code': 200, + 'soup': BeautifulSoup('

Fixture

', 'html.parser')} + page = await analyzer.analyze_page(raw) + assert page['status'] == 'partial' + assert page['content']['status'] == 'partial' + assert page['coverage']['partial_analyzers'] == ['content'] + assert page['rule_coverage']['counts']['error'] == 1 + assert page['overall_score'] == 100 + assert not (await analyzer.analyze_page(raw)).get('cached') + asyncio.run(run()) + + +def test_scoring_version_invalidates_analyzer_cache(monkeypatch): + async def run(): + analyzer = SEOAnalyzer(Config.from_dict({'analysis': {'enabled_analyzers': ['links'], 'score_weights': {'links': 1.0}}})) + raw = {'url': 'https://example.test/', 'status_code': 200, + 'soup': BeautifulSoup('Next', 'html.parser')} + await analyzer.analyze_page(raw) + assert (await analyzer.analyze_page(raw)).get('cached') + monkeypatch.setattr('tfq0seo.core.app.SCORING_VERSION', 'fixture-new-scoring') + assert not (await analyzer.analyze_page(raw)).get('cached') + asyncio.run(run()) + + +def test_postcrawl_rule_resolution_replaces_outcomes_and_is_idempotent(): + async def run(): + analyzer = SEOAnalyzer(Config.from_dict({'analysis': {'enabled_analyzers': ['links'], 'score_weights': {'links': 1.0}}})) + raw = {'url': 'https://example.test/', 'status_code': 200, + 'soup': BeautifulSoup('Next', 'html.parser')} + source = await analyzer.analyze_page(raw) + for status_code, outcome, score in ((None, 'unknown', 100), (200, 'pass', 100), (404, 'fail', 85), (200, 'pass', 100)): + targets = [] if status_code is None else [{'url': 'https://example.test/next', 'status_code': status_code}] + analyzer._resolve_site_links([source] + targets) + broken = [item for item in source['rule_results'] if item['rule_id'] == 'links.broken'] + assert len(broken) == 1 and broken[0]['status'] == outcome + assert source['overall_score'] == score + assert len(source['scoring']['deductions']) == (1 if outcome == 'fail' else 0) + assert bool(source['recommendations']) == (outcome == 'fail') + snapshot = copy.deepcopy(source) + analyzer._resolve_site_links([source] + targets) + assert source == snapshot + asyncio.run(run()) + + +def test_legacy_page_link_resolution_does_not_promote_an_incomplete_ruleset(): + analyzer = SEOAnalyzer(Config.from_dict({'analysis': {'enabled_analyzers': ['links'], 'score_weights': {'links': 1.0}}})) + legacy_issue = {'category': 'Links', 'severity': 'warning', 'message': 'Legacy accessible-name issue', 'fix': 'Add link text'} + source = {'url': 'https://example.test/', 'status_code': 200, 'overall_score': 93, + 'issues': [copy.deepcopy(legacy_issue)], + 'links': {'score': 93, 'issues': [copy.deepcopy(legacy_issue)], + 'data': {'internal_links': [{'url': 'https://example.test/next'}]}}} + analyzer._resolve_site_links([source, {'url': 'https://example.test/next', 'status_code': 200}]) + assert source['overall_score'] == 93 + assert any(issue['message'] == legacy_issue['message'] for issue in source['issues']) + + +def test_real_analyzers_charge_missing_alt_only_once(): + async def run(): + analyzer = SEOAnalyzer(Config()) + template = ('Useful fixture' + '' + '

Useful fixture

') + results = [] + for alt in ('alt="A photo"', ''): + result = await analyzer.analyze_page({'url': 'https://example.test/', 'status_code': 200, + 'headers': {}, 'soup': BeautifulSoup(template.format(alt=alt), 'html.parser')}) + assert not result['analyzer_errors'] + results.append(result) + good, missing = results + assert {name: good[name]['score'] - missing[name]['score'] for name in + ('seo', 'content', 'technical', 'performance', 'links')} == { + 'seo': 0, 'content': 7, 'technical': 0, 'performance': 0, 'links': 0} + assert good['overall_score'] - missing['overall_score'] == 1.75 + deductions = [item for item in missing['scoring']['deductions'] if item['rule_id'] == 'images.missing_alt'] + assert len(deductions) == 1 + assert deductions[0]['reported_by'] == ['content', 'seo'] + assert missing['seo']['data']['scores']['total'] == missing['seo']['score'] + assert missing['content']['data']['quality_assessment']['score'] == missing['content']['score'] + asyncio.run(run()) + + +def test_merged_confirmed_failure_does_not_hide_an_evaluation_error(): + collector = RuleCollector('content') + collector.check('headings.empty', True, {'text': ''}) + collector.check('headings.empty', None, {'text': None}, status='error', reason='Fixture extraction failed') + assert collector.coverage['counts']['fail'] == 1 + assert collector.coverage['has_errors'] + assert score_findings(collector.results) == 93 + + +def test_resolved_link_health_updates_legacy_data_fields(): + async def run(): + analyzer = SEOAnalyzer(Config.from_dict({'analysis': {'enabled_analyzers': ['links'], 'score_weights': {'links': 1.0}}})) + source = await analyzer.analyze_page({'url': 'https://example.test/', 'status_code': 200, + 'soup': BeautifulSoup('Next', 'html.parser')}) + analyzer._resolve_site_links([source, {'url': 'https://example.test/next', 'status_code': 404}]) + data = source['links']['data'] + assert data['link_health_status'] == data['link_health']['status'] == 'complete' + assert data['recommendations'] == source['links']['recommendations'] + assert data['broken_links'] == ['https://example.test/next'] + asyncio.run(run()) diff --git a/tests/test_seo_rules.py b/tests/test_seo_rules.py new file mode 100644 index 0000000..62239ad --- /dev/null +++ b/tests/test_seo_rules.py @@ -0,0 +1,200 @@ +"""Reviewed SEO rules distinguish observed failures from optional metadata.""" + +import json + +import pytest +from bs4 import BeautifulSoup +from multidict import CIMultiDict + +from tfq0seo.analyzers.seo import SEO_RULES, analyze_seo, create_issue +from tfq0seo.rules import get_rule, recommendations_for, score_findings + + +URL = 'https://example.test/article/' + + +def document(head='', body='

Example

', title='Example', lang='en', viewport=True, charset=True): + return BeautifulSoup( + '' + + (f'{title}' if title is not None else '') + + ('' if viewport else '') + + ('' if charset else '') + + head + '' + body + '', 'html.parser') + + +def by_id(result): + return {rule['rule_id']: rule for rule in result['rule_results']} + + +def test_every_seo_evaluation_has_registered_metadata_evidence_and_an_explicit_outcome(): + result = analyze_seo(document(), URL) + rules = by_id(result) + assert set(rule.rule_id for rule in SEO_RULES) <= rules.keys() + assert len(rules) == len(result['rule_results']) + for rule in rules.values(): + definition = get_rule(rule['rule_id']) + assert rule['evidence'] is not None + assert rule['fix'] == definition.recommendation + assert rule['references'] == list(definition.references) + assert rule['reviewed_on'] == '2026-09-14' + assert rule['rule_applicability'] + if rule['status'] in ('unknown', 'not_applicable'): + assert rule['reason'] + assert result['coverage']['counts']['unknown'] > 0 + assert result['coverage']['counts']['not_applicable'] > 0 + assert result['score'] == score_findings(result['issues']) + assert result['recommendations'] == recommendations_for(result['issues']) + json.dumps(result, allow_nan=False) + + +def test_optional_metadata_absence_is_not_a_ranking_failure(): + result = analyze_seo(document(), URL) + rules = by_id(result) + assert result['score'] == 100 + assert rules['seo.description_missing']['status'] == 'informational' + assert rules['seo.canonical_preference']['status'] == 'unknown' + assert rules['seo.jsonld_eligibility']['status'] == 'unknown' + assert rules['seo.og_incomplete']['status'] == 'not_applicable' + assert rules['seo.favicon_missing']['status'] == 'not_applicable' + assert not any('Twitter' in issue['message'] for issue in result['issues']) + + +@pytest.mark.parametrize('title,description', [ + ('短い', '説明'), + ('نص عربي قصير', 'وصف الصفحة.'), + ('A descriptive title that is longer than sixty characters can still identify its subject', 'summary ' * 100), +]) +def test_title_and_description_have_no_universal_length_or_english_cta_requirement(title, description): + result = analyze_seo(document(title=title, head=f''), URL) + assert result['score'] == 100 + assert not any('too short' in issue['message'] or 'too long' in issue['message'] + or 'call-to-action' in issue['message'] or 'too wide' in issue['message'] + for issue in result['issues']) + assert result['data']['serp_preview']['status'] == 'illustrative' + + +def test_repetition_is_an_editorial_hint_and_does_not_change_title_fix_selection(): + result = analyze_seo(document(title='Example Example Example'), URL) + repetition = by_id(result)['seo.title_repetition'] + assert repetition['status'] == 'informational' + assert repetition['evidence']['repeated_words'] == {'example': 3} + assert result['score'] == 100 + issue = create_issue('Meta Tags', 'critical', 'Description canonical heading arbitrary words', + rule_id='seo.title_missing', evidence={'title': None}) + assert issue['fix'] == get_rule('seo.title_missing').recommendation + with pytest.raises(ValueError, match='rule_id'): + create_issue('Meta Tags', 'critical', 'Missing title') + + +@pytest.mark.parametrize('href', ['http://[', 'mailto:info@example.test', 'javascript:alert(1)']) +def test_invalid_canonical_has_stable_id_and_retains_href_evidence(href): + rule = by_id(analyze_seo(document(head=f''), URL))['seo.canonical_invalid'] + assert rule['status'] == 'fail' + assert rule['evidence']['href'] == href + + +def test_relative_canonical_preserves_query_and_duplicate_slash_semantics(): + result = analyze_seo(document(head=''), URL) + assert result['data']['canonical'] == URL + 'child//item/?x=1&x=2&empty=' + assert by_id(result)['seo.canonical_invalid']['status'] == 'pass' + + +def test_open_graph_description_is_optional_and_partial_objects_are_contextual(): + head = ''.join(f'' for name, value in ( + ('og:title', 'Example'), ('og:type', 'website'), ('og:image', '/image.png'), ('og:url', URL))) + result = analyze_seo(document(head=head), URL) + assert by_id(result)['seo.og_incomplete']['status'] == 'pass' + assert by_id(result)['seo.og_image_dimensions']['status'] == 'informational' + partial = by_id(analyze_seo(document(head=''), URL)) + assert partial['seo.og_incomplete']['status'] == 'informational' + assert partial['seo.og_incomplete']['evidence']['missing'] == ['og:type', 'og:image', 'og:url'] + + +@pytest.mark.parametrize('payload', [ + {'@context': 'https://schema.org', '@type': 'Article'}, + {'@context': 'https://schema.org', '@type': 'Product', 'offers': {'@type': 'AggregateOffer'}}, + {'@id': 'https://example.test/entity'}, + {'@context': 'https://schema.org', '@graph': [{'@type': 'Organization'}, {'@id': '#person'}]}, + [{'@type': ['https://schema.org/Thing']}], +]) +def test_jsonld_shapes_do_not_invent_required_properties_or_rich_result_eligibility(payload): + result = analyze_seo(document(head=''), URL) + assert by_id(result)['seo.jsonld_shape']['status'] == 'pass' + assert all(node['valid'] and not node['errors'] for node in result['data']['structured_data']) + assert all(node['rich_snippet_eligible'] is None for node in result['data']['structured_data']) + assert by_id(result)['seo.jsonld_eligibility']['status'] == 'unknown' + + +@pytest.mark.parametrize('payload,rule_id', [ + ('{bad json', 'seo.jsonld_syntax'), + ('{"price":NaN}', 'seo.jsonld_syntax'), + ('{"@graph":42}', 'seo.jsonld_shape'), + ('{"@type":["Thing",42]}', 'seo.jsonld_shape'), +]) +def test_jsonld_failures_keep_structured_parser_evidence(payload, rule_id): + result = analyze_seo(document(head=''), URL) + rule = by_id(result)[rule_id] + assert rule['status'] == 'fail' + assert rule['evidence']['errors'][0]['script_index'] == 0 + json.dumps(result, allow_nan=False) + + +def test_empty_jsonld_is_valid_but_has_no_entity_to_assess(): + rules = by_id(analyze_seo(document(head=''), URL)) + assert rules['seo.jsonld_syntax']['status'] == 'pass' + assert rules['seo.jsonld_shape']['status'] == 'pass' + assert rules['seo.jsonld_empty']['status'] == 'informational' + + +def test_encoding_absence_is_unknown_and_http_charset_prevents_false_missing_declaration(): + soup = document(charset=False) + assert by_id(analyze_seo(soup, URL))['seo.charset_missing']['status'] == 'unknown' + headers = {'content-type': 'text/html; charset="UTF-8"'} + rules = by_id(analyze_seo(soup, URL, headers=headers)) + assert rules['seo.charset_missing']['status'] == 'pass' + assert rules['seo.charset_non_utf8']['status'] == 'pass' + + +@pytest.mark.parametrize('language', ['fr-CA', 'zh-Hant', 'i-klingon', 'x-private']) +def test_language_shape_check_does_not_reject_private_or_grandfathered_tags(language): + rules = by_id(analyze_seo(document(lang=language), URL)) + assert rules['seo.language_format']['status'] == 'pass' + assert rules['seo.language_format']['evidence']['registry_checked'] is False + + +def test_malformed_language_has_a_distinct_registered_rule(): + assert by_id(analyze_seo(document(lang='en_US'), URL))['seo.language_format']['status'] == 'fail' + assert by_id(analyze_seo(document(lang=None), URL))['language.missing']['status'] == 'fail' + + +@pytest.mark.parametrize('viewport', ['width = device-width, USER-SCALABLE = NO', 'width=device-width, maximum-scale=1']) +def test_viewport_zoom_check_parses_whitespace_case_and_numeric_limits(viewport): + soup = document(viewport=False, head=f'') + rules = by_id(analyze_seo(soup, URL)) + assert rules['mobile.viewport_zoom_disabled']['status'] == 'fail' + assert rules['seo.viewport_width']['status'] == 'pass' + + +def test_robots_restrictions_are_observed_without_assuming_publisher_intent(): + headers = CIMultiDict([('X-Robots-Tag', 'otherbot: noindex'), ('X-Robots-Tag', 'googlebot: nofollow')]) + result = analyze_seo(document(head=''), URL, headers=headers) + rules = by_id(result) + assert rules['robots.noindex']['status'] == 'pass' + assert rules['robots.nofollow']['status'] == 'informational' + assert rules['robots.nosnippet']['status'] == 'informational' + assert result['score'] == 100 + + +def test_repeated_heading_failures_are_one_rule_penalty_with_all_evidence(): + result = analyze_seo(document(body='

Later

'), URL) + empty = by_id(result)['headings.empty'] + assert len(empty['evidence']['findings']) == 2 + assert result['score'] == 93 + assert by_id(result)['headings.skipped_level']['status'] == 'informational' + + +def test_filename_extensions_do_not_claim_image_optimization_was_measured(): + result = analyze_seo(document(body='

Example

'), URL) + assert result['data']['images']['non_optimized'] is None + assert result['data']['images']['non_modern_filename_references'] == 1 + assert by_id(result)['images.missing_dimensions']['status'] == 'informational' diff --git a/tests/test_shared_fact_analyzers.py b/tests/test_shared_fact_analyzers.py new file mode 100644 index 0000000..0959840 --- /dev/null +++ b/tests/test_shared_fact_analyzers.py @@ -0,0 +1,162 @@ +"""Technical, performance, and link analyzers consume one shared page snapshot.""" + +import copy +import json +from concurrent.futures import ThreadPoolExecutor + +import pytest +from bs4 import BeautifulSoup + +from tfq0seo.analyzers import analyze_links, analyze_performance, analyze_technical +from tfq0seo.analyzers.common import is_nonblocking_script +from tfq0seo.page_facts import extract_page_facts + + +URL = 'https://example.test/start/' +HEADERS = {'Content-Type': 'text/html; charset=utf-8', + 'X-Robots-Tag': ['googlebot: noindex', 'bingbot: nofollow'], + 'Content-Security-Policy': ["script-src 'none'", "script-src 'unsafe-eval'; frame-ancestors 'none'"]} + + +def document(): + return BeautifulSoup('''Example + + + + + +

Heading

Destination label

+ +

Outside

+ Hero + Action + ''', 'html.parser') + + +def run(analyzer, soup, facts=None): + kwargs = {'facts': facts} if facts is not None else {} + if analyzer is analyze_technical: + return analyzer(soup, URL, headers=HEADERS, **kwargs) + if analyzer is analyze_performance: + return analyzer(soup, URL, load_time=0.25, content_length=2048, **kwargs) + return analyzer(soup, URL, **kwargs) + + +@pytest.mark.parametrize('analyzer', [analyze_technical, analyze_performance, analyze_links]) +def test_shared_snapshot_matches_standalone_public_api(analyzer): + soup = document() + facts = extract_page_facts(soup, URL, HEADERS) + standalone = run(analyzer, soup) + shared = run(analyzer, soup, facts) + assert shared == standalone + json.dumps(shared, allow_nan=False) + + +def test_supplied_snapshot_prevents_common_reextraction(monkeypatch): + soup = document() + facts = extract_page_facts(soup, URL, HEADERS) + original_find_all = soup.find_all + + def no_common_scan(name=None, *args, **kwargs): + if isinstance(name, str) and name in ('a', 'img', 'script', 'meta', 'link'): + raise AssertionError('Shared HTML collection was scanned again: ' + name) + return original_find_all(name, *args, **kwargs) + + def no_snapshot(*args, **kwargs): + raise AssertionError('A second PageFacts snapshot was extracted') + + monkeypatch.setattr(soup, 'find_all', no_common_scan) + monkeypatch.setattr('tfq0seo.page_facts.extract_page_facts', no_snapshot) + for analyzer in (analyze_technical, analyze_performance, analyze_links): + result = run(analyzer, soup, facts) + assert 'error' not in result + + +@pytest.mark.parametrize('analyzer', [analyze_technical, analyze_performance, analyze_links]) +def test_standalone_analyzer_builds_exactly_one_snapshot(analyzer, monkeypatch): + import tfq0seo.page_facts as module + original = module.extract_page_facts + calls = [] + + def counted(*args, **kwargs): + calls.append(args) + return original(*args, **kwargs) + + monkeypatch.setattr(module, 'extract_page_facts', counted) + run(analyzer, document()) + assert len(calls) == 1 + + +def test_parallel_analyzers_do_not_modify_soup_snapshot_or_each_other(): + soup = document() + before = str(soup) + facts = extract_page_facts(soup, URL, HEADERS) + original_snapshot = facts.to_dict(include_content=True) + with ThreadPoolExecutor(max_workers=3) as pool: + outputs = list(pool.map(lambda analyzer: run(analyzer, soup, facts), + (analyze_technical, analyze_performance, analyze_links))) + outputs[2]['data']['internal_links'][0]['rel'].append('changed') + outputs[0]['data']['crawlability']['robots_analysis']['evidence'].clear() + assert str(soup) == before + assert facts.to_dict(include_content=True) == original_snapshot + repeated = run(analyze_links, soup, facts) + assert 'changed' not in repeated['data']['internal_links'][0]['rel'] + + +@pytest.mark.parametrize('headers,expected', [(None, 'unknown'), ({}, 'informational')]) +def test_technical_respects_snapshot_header_observation_state(headers, expected): + soup = document() + facts = extract_page_facts(soup, URL, headers) + result = analyze_technical(soup, URL, facts=facts) + rules = {item['rule_id']: item for item in result['rule_results']} + assert rules['security.hsts_missing']['status'] == expected + assert rules['security.hsts_missing']['evidence']['headers_checked'] is (headers is not None) + + +def test_technical_adopts_snapshot_user_agent_and_preserves_repeated_headers(): + soup = document() + facts = extract_page_facts(soup, URL, HEADERS, user_agent='bingbot') + result = analyze_technical(soup, URL, facts=facts) + robots = result['data']['crawlability']['robots_analysis'] + assert robots['user_agent'] == 'bingbot' + assert robots['nofollow'] is True + assert robots['noindex'] is False + csp = next(item for item in result['rule_results'] if item['rule_id'] == 'security.csp_unsafe_eval') + assert len(csp['evidence']['policies']) == 2 + + +@pytest.mark.parametrize('analyzer', [analyze_technical, analyze_performance, analyze_links]) +def test_supplied_snapshot_rejects_different_source_or_url(analyzer): + soup = document() + facts = extract_page_facts(soup, URL, HEADERS) + with pytest.raises(ValueError, match='URL and soup'): + analyzer(document(), URL, facts=facts) + with pytest.raises(ValueError, match='URL and soup'): + analyzer(soup, URL + 'other', facts=facts) + + +def test_technical_rejects_conflicting_explicit_context(): + soup = document() + facts = extract_page_facts(soup, URL, HEADERS) + with pytest.raises(ValueError, match='response headers'): + analyze_technical(soup, URL, headers={}, facts=facts) + with pytest.raises(ValueError, match='user agent'): + analyze_technical(soup, URL, user_agent='bingbot', facts=facts) + + +def test_shared_link_names_context_and_url_identity_are_preserved(): + soup = document() + facts = extract_page_facts(soup, URL, HEADERS) + result = analyze_links(soup, URL, facts=facts) + links = result['data']['internal_links'] + assert links[0]['url'] == 'https://example.test/assets/a//b?key=&key=Two' + assert links[0]['anchor_text'] == 'Destination label' + assert links[0]['type'] == 'navigation' + assert links[1]['anchor_text'] == 'Hero' + assert all(isinstance(item, list) for item in result['data']['anchor_analysis']['most_common']) + + +@pytest.mark.parametrize('attributes,expected', [({}, False), ({'async': ''}, True), + ({'defer': 'false'}, True), ({'type': 'module'}, True)]) +def test_nonblocking_script_helper_accepts_primitive_attributes(attributes, expected): + assert is_nonblocking_script(copy.deepcopy(attributes)) is expected diff --git a/tests/test_site_analysis.py b/tests/test_site_analysis.py new file mode 100644 index 0000000..325c9ba --- /dev/null +++ b/tests/test_site_analysis.py @@ -0,0 +1,227 @@ +"""Cross-page checks use observed facts; absence is never a network failure.""" + +import asyncio +import copy +import csv +import json + +import pytest +from bs4 import BeautifulSoup + +from tfq0seo.core.app import SEOAnalyzer +from tfq0seo.core.config import Config +from tfq0seo.core.models import ContractError, validate_rule_result +from tfq0seo.core.report_contracts import validate_site_report +from tfq0seo.exporters.base import ExportManager +from tfq0seo.site_analysis import analyze_site + + +BASE = 'https://example.test' + + +def page(path, targets=(), links=(), status=200, noindex=False, truncated=False): + url = BASE + path + result = {'url': url, 'status_code': status, 'truncated': truncated} + if status >= 400: + result.update(error='Observed HTTP error', status='error') + return result + result['page_facts'] = { + 'canonical': {'declarations': [{'href': target, 'url': BASE + target if target.startswith('/') else target, + 'eligible': True, 'source': 'html', 'reason': ''} for target in targets], + 'headers_checked': True, 'parse_errors': 0}, + 'robots': {'noindex': noindex, 'nofollow': False}, + 'anchors': [{'url': BASE + target, 'attrs': {'rel': []}} for target in links], + } + return result + + +def rows(report): + return {item['url'][len(BASE):]: item for item in report['pages']} + + +def ids(report, path): + return {item['rule_id'] for item in report['findings'] if item['url'] == BASE + path} + + +def test_canonical_chain_and_target_redirect_use_observed_aliases(): + final = page('/final', ['/final']) + final.update(requested_url=BASE + '/old', redirect_chain=[{'url': BASE + '/old'}]) + result = analyze_site([page('/a', ['/b']), page('/b', ['/old']), final]) + indexed = rows(result) + assert indexed['/a']['canonical_hops'] == 3 + assert indexed['/a']['canonical_terminal'] == BASE + '/final' + assert indexed['/a']['canonical_status'] == 'chain' + assert indexed['/final']['canonical_status'] == 'self' + assert 'site.canonical_target_redirect' in ids(result, '/b') + assert 'site.canonical_chain' in ids(result, '/a') + + +def test_cycles_are_stored_once_and_self_canonicals_are_not_cycles(): + result = analyze_site([page('/a', ['/b']), page('/b', ['/a']), page('/before', ['/a']), page('/self', ['/self'])]) + indexed = rows(result) + assert result['canonicals']['cycles'] == [{'id': 0, 'urls': [BASE + '/a', BASE + '/b']}] + for path in ('/a', '/b', '/before'): + assert indexed[path]['canonical_status'] == 'cycle' + assert indexed[path]['canonical_hops'] is None + assert indexed[path]['canonical_cycle_id'] == 0 + assert 'site.canonical_cycle' not in ids(result, '/self') + + +def test_conflicting_and_duplicate_canonical_declarations(): + result = analyze_site([page('/conflict', ['/a', '/b']), page('/same', ['/a', '/a']), page('/a', ['/a'])]) + assert rows(result)['/conflict']['canonical_status'] == 'conflict' + assert rows(result)['/same']['canonical_status'] == 'resolved' + assert 'site.canonical_conflict' in ids(result, '/conflict') + assert 'site.canonical_conflict' not in ids(result, '/same') + + +def test_only_observed_http_errors_and_noindex_produce_target_findings(): + unavailable = page('/unavailable') + unavailable.pop('page_facts') + unavailable.update(status_code=0, error='Connection refused') + result = analyze_site([page('/a', ['/404']), page('/b', ['/private']), page('/c', ['/missing']), + page('/d', ['/unavailable']), page('/e', ['https://other.test/']), + page('/404', status=404), page('/private', ['/private'], noindex=True), unavailable]) + assert 'site.canonical_target_error' in ids(result, '/a') + assert 'site.canonical_target_noindex' in ids(result, '/b') + assert 'site.canonical_target_error' not in ids(result, '/c') | ids(result, '/d') | ids(result, '/e') + assert rows(result)['/c']['canonical_status'] == 'unchecked' + assert rows(result)['/d']['canonical_status'] == 'unknown' + assert result['canonicals']['unchecked_targets'] == [BASE + '/missing', 'https://other.test/'] + + +def test_missing_partial_and_malformed_facts_do_not_prove_canonical_absence(): + legacy = {'url': BASE + '/legacy', 'status_code': 200} + malformed = page('/malformed') + malformed['page_facts']['canonical']['parse_errors'] = 1 + headers_unknown = page('/headers') + headers_unknown['page_facts']['canonical']['headers_checked'] = False + result = analyze_site([legacy, malformed, headers_unknown, page('/partial', truncated=True), page('/none')]) + for path in ('/legacy', '/malformed', '/headers', '/partial'): + assert rows(result)[path]['canonical_status'] == 'unknown' + assert rows(result)['/none']['canonical_status'] == 'none' + assert result['coverage']['crawl_complete'] is False + + +def test_directed_link_depth_components_and_candidates_are_conservative(): + pages = [page('/', links=['/a', '/a#fragment', '/outside']), page('/a', links=['/b']), + page('/b'), page('/self', links=['/self']), page('/island1', links=['/island2']), + page('/island2', links=['/island1'])] + pages[0]['page_facts']['anchors'][0]['attrs']['rel'] = ['nofollow'] + result = analyze_site(pages, start_url=BASE + '/', crawl_complete=False) + indexed = rows(result) + assert result['links']['edge_count'] == 6 + assert len(result['links']['components']) == 3 + assert indexed['/a']['incoming_links'] == 1 + assert indexed['/b']['link_depth'] == 2 + assert indexed['/self']['incoming_links'] == 0 + assert indexed['/self']['reachable'] is False + assert 'site.links_no_incoming' in ids(result, '/self') + assert 'site.links_unreachable' in ids(result, '/island1') + assert 'site.links_no_incoming' not in ids(result, '/') + assert result['links']['unfetched_targets'] == [BASE + '/outside'] + assert next(item for item in result['links']['edges'] if item['target'] == BASE + '/a')['nofollow'] is False + for item in result['findings']: + validate_rule_result(item) + assert item['scope'] == 'site' and item['penalty'] == 0 and item['status'] == 'informational' + + +def test_batch_without_an_entry_page_does_not_invent_depth(): + result = analyze_site([page('/a', links=['/b']), page('/b')]) + assert result['links']['roots'] == [] + assert all(item['link_depth'] is None and item['reachable'] is None for item in result['pages']) + + +def test_queries_remain_distinct_and_redirect_aliases_coalesce_link_targets(): + final = page('/final') + final['requested_url'] = BASE + '/old' + result = analyze_site([page('/', links=['/old', '/final', '/?a=1', '/?a=2', '/#top']), final, + page('/?a=1'), page('/?a=2')]) + assert rows(result)['/final']['incoming_links'] == 1 + assert result['links']['node_count'] == 4 + assert result['links']['edge_count'] == 4 + + +def test_results_are_order_independent_and_inputs_are_unchanged(): + pages = [page('/', ['/a'], ['/a']), page('/a', ['/b']), page('/b', ['/b'])] + before = copy.deepcopy(pages) + assert analyze_site(pages) == analyze_site(list(reversed(pages))) + assert pages == before + + +def test_long_canonical_chain_does_not_recurse_or_copy_all_path_suffixes(): + count = 2200 + pages = [page('/' + str(index), ['/' + str(min(index + 1, count - 1))]) for index in range(count)] + result = analyze_site(pages) + assert rows(result)['/0']['canonical_hops'] == count - 1 + assert rows(result)['/0']['canonical_terminal'] == BASE + '/' + str(count - 1) + assert len(json.dumps(result)) < count * 6000 + + +def analyzed_report(): + async def run(): + analyzer = SEOAnalyzer(Config.from_dict({'crawler': {'cache_enabled': False}})) + pages = [] + for path, head, links in [('/', '', 'A'), + ('/a', '', 'B'), + ('/b', '', '')]: + html = 'Page' + head + '

Page

' + links + '' + pages.append(await analyzer.analyze_page({'url': BASE + path, 'status_code': 200, + 'headers': {}, 'soup': BeautifulSoup(html, 'html.parser')})) + before = copy.deepcopy(pages) + result = analyzer.generate_site_report(pages) + assert pages == before + assert [item['overall_score'] for item in result['pages']['detailed']] == [item['overall_score'] for item in pages] + return result + return asyncio.run(run()) + + +def test_site_findings_reach_recommendations_and_all_export_formats(tmp_path): + report = analyzed_report() + validate_site_report(report, strict=True) + assert any(item['rule_id'] == 'site.canonical_chain' for item in report['recommendations']['specific']) + for template in ('report', 'enhanced', 'optimized'): + exporter = ExportManager({'output_directory': str(tmp_path), 'html_template': template}) + html = tmp_path / (template + '.html') + exporter.export(report, 'html', str(html)) + assert 'Site-wide analysis' in html.read_text(encoding='utf-8') + assert 'Canonical and internal-link observations' in html.read_text(encoding='utf-8') + exporter.export(report, 'csv', str(tmp_path / 'site.csv')) + with (tmp_path / 'site.csv').open(encoding='utf-8', newline='') as stream: + exported = list(csv.DictReader(stream)) + assert exported[0]['canonical_hops'] == '2' + assert exported[2]['link_depth'] == '2' + exporter.export(report, 'xlsx', str(tmp_path / 'site.xlsx')) + from openpyxl import load_workbook + workbook = load_workbook(tmp_path / 'site.xlsx', read_only=True) + assert 'Canonical Targets' in next(workbook['Pages'].values) + workbook.close() + + +@pytest.mark.parametrize('mutate', [ + lambda report: report['site_analysis']['links'].update(edge_count=-1), + lambda report: report['site_analysis']['links']['edges'][0].update(nofollow='false'), + lambda report: report['site_analysis']['pages'][0].update(canonical_hops=True), + lambda report: report['site_analysis']['pages'][0].update(canonical_targets='invalid'), + lambda report: report['pages']['detailed'][0]['site_analysis'].update(incoming_links=-1), +]) +def test_malformed_site_contract_is_rejected_before_export(tmp_path, mutate): + report = analyzed_report() + mutate(report) + path = tmp_path / 'protected.html' + path.write_text('Keep me', encoding='utf-8') + with pytest.raises(ContractError): + ExportManager({'output_directory': str(tmp_path)}).export(report, 'html', str(path)) + assert path.read_text(encoding='utf-8') == 'Keep me' + + +def test_html_site_observations_escape_untrusted_urls(tmp_path): + report = analyzed_report() + row = report['site_analysis']['pages'][0] + row.update(url='javascript:alert(1)', canonical_terminal='') + path = tmp_path / 'escaped.html' + ExportManager({'output_directory': str(tmp_path)}).export(report, 'html', str(path)) + html = path.read_text(encoding='utf-8') + assert 'href="javascript:' not in html + assert '' not in html + assert '<script>alert(1)</script>' in html diff --git a/tests/test_site_analysis_review.py b/tests/test_site_analysis_review.py new file mode 100644 index 0000000..9bc4d18 --- /dev/null +++ b/tests/test_site_analysis_review.py @@ -0,0 +1,78 @@ +"""Regression cases found during independent cross-page analysis review.""" + +import pytest +from bs4 import BeautifulSoup + +from tfq0seo.core.app import SEOAnalyzer +from tfq0seo.core.models import ContractError +from tfq0seo.page_facts import extract_page_facts +from tfq0seo.site_analysis import analyze_site + + +BASE = 'https://example.test' + + +def source_page(path='/source', canonical='/old'): + soup = BeautifulSoup('', 'html.parser') + return {'url': BASE + path, 'status_code': 200, 'issues': [], + 'page_facts': extract_page_facts(soup, BASE + path, {}).to_dict()} + + +def test_canonical_redirect_to_observed_http_error_retains_final_response_evidence(): + final = {'url': BASE + '/gone', 'requested_url': BASE + '/old', 'status_code': 404, + 'error': 'HTTP 404', 'status': 'error', + 'redirect_chain': [{'url': BASE + '/old', 'status_code': 301, 'location': BASE + '/gone'}]} + report = analyze_site([source_page(), final]) + row = next(row for row in report['pages'] if row['url'] == BASE + '/source') + assert row['canonical_terminal'] == BASE + '/gone' + assert row['canonical_status'] == 'http_error' + rules = {item['rule_id'] for item in report['findings'] if item['url'] == BASE + '/source'} + assert {'site.canonical_target_redirect', 'site.canonical_target_error'} <= rules + + +def test_canonical_redirect_to_observed_non_html_response_retains_redirect_evidence(): + final = {'url': BASE + '/file.pdf', 'requested_url': BASE + '/old', 'status_code': 200, + 'error': 'Non-HTML content: application/pdf', 'status': 'skipped', 'skipped': True, + 'redirect_chain': [{'url': BASE + '/old', 'status_code': 302, 'location': BASE + '/file.pdf'}]} + report = analyze_site([source_page(), final]) + row = next(row for row in report['pages'] if row['url'] == BASE + '/source') + assert row['canonical_terminal'] == BASE + '/file.pdf' + assert row['canonical_status'] == 'unknown' # The target's own canonical remains unobserved. + assert any(item['rule_id'] == 'site.canonical_target_redirect' for item in report['findings']) + + +@pytest.mark.parametrize('status', [301, 302, 303, 307, 308]) +def test_observed_unfollowed_canonical_redirect_is_reported_without_inventing_its_destination(status): + target = {'url': BASE + '/old', 'requested_url': BASE + '/old', 'status_code': status, + 'error': 'Redirect not followed', 'status': 'skipped', 'skipped': True, 'redirect_chain': []} + report = analyze_site([source_page(), target]) + rules = {item['rule_id'] for item in report['findings'] if item['url'] == BASE + '/source'} + assert 'site.canonical_target_redirect' in rules + assert 'site.canonical_target_error' not in rules + row = next(row for row in report['pages'] if row['url'] == BASE + '/source') + assert row['canonical_terminal'] == BASE + '/old' + assert row['canonical_status'] == 'unknown' + + +@pytest.mark.parametrize('page_facts', [ + {'robots': None}, + {'anchors': None}, + {'canonical': {'declarations': None}}, + {'canonical': {'declarations': [None]}}, +]) +def test_malformed_archived_fact_fields_are_rejected_at_the_report_boundary(page_facts): + record = {'url': BASE + '/archive', 'status_code': 200, 'issues': [], 'page_facts': page_facts} + with pytest.raises(ContractError, match='page_facts'): + SEOAnalyzer().generate_site_report([record]) + + +def test_incomplete_archived_fact_objects_do_not_establish_absence_or_html_coverage(): + record = {'url': BASE + '/archive', 'status_code': 200, + 'page_facts': {'canonical': {'headers_checked': True}}} + report = analyze_site([record]) + row = report['pages'][0] + assert row['canonical_status'] == 'unknown' + assert row['outgoing_links'] is None + assert row['content_complete'] is False + assert report['coverage']['complete_html_pages'] == 0 diff --git a/tests/test_site_graph_review.py b/tests/test_site_graph_review.py new file mode 100644 index 0000000..43b09ad --- /dev/null +++ b/tests/test_site_graph_review.py @@ -0,0 +1,136 @@ +"""Independent regressions for graph ambiguity, context, and source coverage.""" + +import asyncio +import copy + +from bs4 import BeautifulSoup + +from tfq0seo.core.app import SEOAnalyzer +from tfq0seo.core.config import Config +from tfq0seo.page_facts import extract_page_facts +from tfq0seo.site_analysis import analyze_site + + +BASE = 'https://example.test' + + +def page(url, html=''): + soup = BeautifulSoup(html, 'html.parser') + return {'url': url, 'status_code': 200, 'issues': [], + 'page_facts': extract_page_facts(soup, url, {}).to_dict()} + + +def test_conflicting_target_responses_are_unknown_independent_of_record_order(): + async def run(): + analyzer = SEOAnalyzer(Config.from_dict({'analysis': {'enabled_analyzers': ['links']}})) + source = await analyzer.analyze_page({ + 'url': BASE + '/', 'status_code': 200, 'headers': {}, + 'soup': BeautifulSoup('Target', 'html.parser'), + }) + good = page(BASE + '/target') + bad = {'url': BASE + '/target', 'status_code': 404, 'error': 'Observed HTTP 404', + 'status': 'error', 'overall_score': None, 'issues': []} + outcomes = [] + for records in ([source, good, bad], [source, bad, good]): + report = analyzer.generate_site_report(records) + result = report['pages']['detailed'][0] + health = result['links']['data']['link_health'] + rule = next(item for item in result['links']['rule_results'] + if item['rule_id'] == 'links.broken') + outcomes.append((result['overall_score'], health, rule['status'])) + assert outcomes[0] == outcomes[1] + _, health, status = outcomes[0] + assert health['unchecked'] == 1 and health['broken'] == 0 + assert status == 'unknown' + + asyncio.run(run()) + + +def test_fresh_batch_report_does_not_inherit_previous_crawl_context(monkeypatch): + class CrawlerStub: + def __init__(self, settings): + self.results = [] + self.limit_reasons = [] + self.discovery_errors = [] + + async def __aenter__(self): + return self + + async def __aexit__(self, *args): + return None + + async def crawl_site(self, start_url, max_pages): + self.results.append({ + 'url': start_url, 'status_code': 200, 'headers': {}, + 'soup': BeautifulSoup('Previous crawl', 'html.parser'), + }) + return self.results + + monkeypatch.setattr('tfq0seo.core.app.Crawler', CrawlerStub) + + async def run(): + analyzer = SEOAnalyzer(Config.from_dict({'analysis': {'enabled_analyzers': ['links']}})) + previous = [result async for result in analyzer.crawl_site('https://previous.test/start')] + assert previous + assert analyzer.generate_site_report()['summary']['crawl_complete'] is True + + fresh = [page(BASE + '/', 'Child'), page(BASE + '/child')] + report = analyzer.generate_batch_report(fresh) + graph = report['site_analysis'] + assert graph['links']['roots'] == [BASE + '/'] + assert graph['links']['root_source'] == 'observed_homepages' + assert graph['coverage']['crawl_complete'] is False + assert report['summary']['crawl_complete'] is False + assert next(row for row in graph['pages'] if row['url'] == BASE + '/child')['link_depth'] == 1 + + asyncio.run(run()) + + +def test_partial_fact_sections_do_not_count_as_complete_html_coverage(): + archive = {'url': BASE + '/archive', 'status_code': 200, 'issues': [], + 'page_facts': {'anchors': [], 'robots': {}, 'canonical': {'declarations': []}}} + # Partial historical facts remain valid input; their missing observations + # must not become a claim that all extraction sources were available. + report = SEOAnalyzer().generate_site_report([archive]) + assert report['site_analysis']['coverage']['complete_html_pages'] == 0 + assert report['site_analysis']['pages'][0]['content_complete'] is False + assert report['site_analysis']['pages'][0]['canonical_status'] == 'unknown' + + +def test_repeated_url_canonical_conflict_evidence_is_order_independent(): + first = page(BASE + '/same', '') + second = page(BASE + '/same', '') + assert analyze_site([first, second]) == analyze_site([second, first]) + + +def test_external_link_observations_are_scoped_to_current_run_result_objects(): + async def run(): + analyzer = SEOAnalyzer(Config.from_dict({'analysis': { + 'enabled_analyzers': ['links'], 'check_external_links': True, + }})) + target = 'https://other.test/target' + source = await analyzer.analyze_page({ + 'url': BASE + '/', 'status_code': 200, 'headers': {}, + 'soup': BeautifulSoup('Target', 'html.parser'), + }) + analyzer.results = [source] + analyzer.link_checks = [{'url': target, 'status_code': 404, 'error': 'Observed HTTP 404'}] + + # A newly collected list of the current run's objects, as used by the + # CLI, retains observations made for that run. + current = analyzer.generate_batch_report([source]) + assert current['technical_health']['link_checks'] == analyzer.link_checks + assert current['pages']['detailed'][0]['links']['data']['link_health']['broken'] == 1 + + # An independent imported copy contains the same page URL but does not + # carry the previous run's external-fetch evidence. + fresh = analyzer.generate_batch_report([copy.deepcopy(source)]) + assert fresh['technical_health']['link_checks'] == [] + assert fresh['technical_health']['broken_links'] == [] + health = fresh['pages']['detailed'][0]['links']['data']['link_health'] + assert health['unchecked'] == 1 and health['broken'] == 0 + rule = next(item for item in fresh['pages']['detailed'][0]['links']['rule_results'] + if item['rule_id'] == 'links.broken') + assert rule['status'] == 'unknown' + + asyncio.run(run()) diff --git a/tests/test_technical_rules.py b/tests/test_technical_rules.py new file mode 100644 index 0000000..e9cc00b --- /dev/null +++ b/tests/test_technical_rules.py @@ -0,0 +1,297 @@ +"""Technical rule evidence, applicability, and registry-only scoring regressions.""" + +import json + +import pytest +from bs4 import BeautifulSoup +from multidict import CIMultiDict + +from tfq0seo.analyzers.technical import ( + TECHNICAL_RULES, analyze_technical, analyze_mobile_optimization, + analyze_security_headers, detect_javascript_seo_issues, create_issue, +) +from tfq0seo.rules import get_rule, recommendations_for, score_findings + + +URL = 'https://example.com/page' + + +def document(body='

Readable page content.

', head='', lang='en', viewport='width=device-width', + doctype=''): + viewport_tag = f'' if viewport is not None else '' + return BeautifulSoup(f'{doctype}{viewport_tag}' + f'{head}{body}', 'html.parser') + + +def evaluate(soup=None, *, headers=None, url=URL, status_code=200): + result = analyze_technical(soup if soup is not None else document(), url, + headers=headers, status_code=status_code) + return result, {item['rule_id']: item for item in result['rule_results']} + + +def test_every_active_rule_has_reviewed_metadata_and_structured_results(): + result, rules = evaluate(headers={}) + assert set(TECHNICAL_RULES) <= rules.keys() + assert len(rules) == len(result['rule_results']) + assert result['coverage'] == result['rule_coverage'] + assert result['coverage']['total'] == len(rules) + for item in rules.values(): + definition = get_rule(item['rule_id']) + assert item['reviewed_on'] == '2026-09-14' + assert item['references'] == list(definition.references) + assert isinstance(item['evidence'], (dict, list)) + assert item['fix'] == definition.recommendation + if item['status'] in ('unknown', 'not_applicable'): + assert item['reason'] + json.dumps(result, allow_nan=False) + + +def test_optional_header_policies_do_not_lower_score_or_claim_insecurity(): + result, rules = evaluate(headers={}) + assert result['score'] == 100 + for rule_id in ('security.hsts_missing', 'security.csp_missing', 'security.frame_policy_missing', + 'technical.http_compression'): + assert rules[rule_id]['status'] == 'informational' + assert rules[rule_id]['penalty'] == 0 + assert result['data']['security']['level'] is None + assert result['data']['security']['level_status'] == 'not_assessed' + assert result['data']['security']['vulnerabilities'] == [] + assert 'heuristic' in result['data']['security']['header_configuration_level_method'] + + +def test_missing_response_context_is_unknown_instead_of_a_pass_or_failure(): + result, rules = evaluate(headers=None, status_code=0) + for rule_id in ('security.hsts_missing', 'security.hsts_invalid', 'security.csp_missing', + 'security.frame_policy_missing', 'security.xfo_invalid', + 'security.cors_wildcard_credentials', 'technical.http_compression', + 'technical.http_server_error', 'technical.http_client_error', 'technical.http_redirect', + 'robots.noindex', 'robots.nofollow', 'robots.nosnippet'): + assert rules[rule_id]['status'] == 'unknown', rule_id + assert rules[rule_id]['penalty'] == 0 + assert result['score'] == 100 + assert result['data']['security']['hsts'] is None + + +@pytest.mark.parametrize('status,rule_id,expected', [ + (503, 'technical.http_server_error', 'fail'), (404, 'technical.http_client_error', 'fail'), + (302, 'technical.http_redirect', 'informational'), (301, 'technical.http_redirect', 'informational'), + (307, 'technical.http_redirect', 'informational'), (308, 'technical.http_redirect', 'informational'), + (304, 'technical.http_redirect', 'pass'), (200, 'technical.http_server_error', 'pass'), +]) +def test_status_rules_use_observed_semantics(status, rule_id, expected): + result, rules = evaluate(headers={}, status_code=status) + assert rules[rule_id]['status'] == expected + assert rules[rule_id]['evidence']['status_code'] == status + if expected == 'informational': + assert result['score'] == 100 + assert 'consider using 301' not in str(result) + + +@pytest.mark.parametrize('url,https_status,hsts_status', [ + ('http://example.com/', 'fail', 'not_applicable'), + ('https://example.com/', 'pass', 'informational'), + ('http://localhost:8000/', 'not_applicable', 'not_applicable'), + ('http://127.0.0.1:8000/', 'not_applicable', 'not_applicable'), + ('http://[::1]:8000/', 'not_applicable', 'not_applicable'), + ('https://192.0.2.1/', 'pass', 'not_applicable'), +]) +def test_transport_policy_scope(url, https_status, hsts_status): + _, rules = evaluate(headers={}, url=url) + assert rules['security.https_missing']['status'] == https_status + assert rules['security.hsts_missing']['status'] == hsts_status + + +@pytest.mark.parametrize('policy,status', [ + ('max-age=86400', 'pass'), ('max-age=0', 'pass'), ('max-age="3600"', 'pass'), + ('max-age = 3600 ; includeSubDomains', 'pass'), + ('max-age="3\\600"; extension="one; max-age=1"', 'pass'), + ('max-age=31536000; includeSubDomains', 'pass'), + ('max-age=-1', 'fail'), ('max-age=12abc', 'fail'), ('max-age=1; max-age=2', 'fail'), + ('notmax-age=3600', 'fail'), ('includeSubDomains', 'fail'), + ('max-age=3600; includeSubDomains=1', 'fail'), +]) +def test_hsts_validation_does_not_impose_one_year_on_every_site(policy, status): + _, rules = evaluate(headers={'Strict-Transport-Security': policy}) + assert rules['security.hsts_invalid']['status'] == status + assert rules['security.hsts_preload_incomplete']['status'] == 'not_applicable' + assert not any('less than recommended' in text for text in analyze_security_headers( + {'Strict-Transport-Security': policy}).vulnerabilities) + + +def test_repeated_hsts_fields_use_first_policy_and_preload_is_conditional(): + headers = CIMultiDict([('Strict-Transport-Security', 'max-age=3600'), + ('Strict-Transport-Security', 'max-age=-1')]) + _, rules = evaluate(headers=headers) + assert rules['security.hsts_invalid']['status'] == 'pass' + assert len(rules['security.hsts_invalid']['evidence']['values']) == 2 + _, partial = evaluate(headers={'Strict-Transport-Security': 'max-age=3600; preload'}) + assert partial['security.hsts_preload_incomplete']['status'] == 'informational' + _, ready = evaluate(headers={'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload'}) + assert ready['security.hsts_preload_incomplete']['status'] == 'pass' + + +def test_large_hsts_duration_keeps_evidence_without_integer_conversion_failure(): + policy = 'max-age=' + '9' * 5000 + '; includeSubDomains; preload' + result, rules = evaluate(headers={'Strict-Transport-Security': policy}) + assert rules['security.hsts_invalid']['status'] == 'pass' + assert rules['security.hsts_preload_incomplete']['status'] == 'pass' + assert rules['security.hsts_invalid']['evidence']['values'] == [policy] + assert result['data']['security']['hsts_max_age'] is None + json.dumps(result, allow_nan=False) + + +@pytest.mark.parametrize('policy,inline,eval_,wildcard', [ + ("default-src 'self'; style-src 'unsafe-inline'; frame-ancestors 'none'", 'pass', 'pass', 'pass'), + ("script-src 'unsafe-inline' 'unsafe-eval'; default-src *", 'informational', 'informational', 'informational'), + ("script-src 'unsafe-inline' 'nonce-YWJjZA=='", 'pass', 'pass', 'pass'), + ("script-src 'none'; script-src 'unsafe-inline'", 'pass', 'pass', 'pass'), +]) +def test_csp_observations_respect_directives_and_do_not_claim_exploitability(policy, inline, eval_, wildcard): + result, rules = evaluate(headers={'Content-Security-Policy': policy}) + assert rules['security.csp_unsafe_inline']['status'] == inline + assert rules['security.csp_unsafe_eval']['status'] == eval_ + assert rules['security.csp_wildcard_default']['status'] == wildcard + assert result['score'] == 100 + for item in result['issues']: + assert item['penalty'] == 0 + + +def test_separate_csp_policies_keep_provenance_and_frame_ancestors_alternative(): + headers = CIMultiDict([('Content-Security-Policy', "script-src 'unsafe-inline'"), + ('Content-Security-Policy', "script-src 'none'; frame-ancestors 'none'")]) + _, rules = evaluate(headers=headers) + evidence = rules['security.csp_unsafe_inline']['evidence'] + assert len(evidence['policies']) == 2 + assert evidence['effective_browser_policy_checked'] is False + assert rules['security.frame_policy_missing']['status'] == 'pass' + + +def test_meta_csp_is_observed_but_cannot_supply_frame_ancestors(): + soup = document(head='') + _, rules = evaluate(soup, headers={}) + assert rules['security.csp_missing']['status'] == 'pass' + assert rules['security.frame_policy_missing']['status'] == 'informational' + + +@pytest.mark.parametrize('value,status', [(' deny ', 'pass'), ('SAMEORIGIN', 'pass'), + ('DENY,DENY', 'pass'), ('DENY,SAMEORIGIN', 'fail'), + ('ALLOW-FROM https://example.com', 'fail'), ('invalid', 'fail')]) +def test_configured_xfo_validation(value, status): + _, rules = evaluate(headers={'X-Frame-Options': value}) + assert rules['security.xfo_invalid']['status'] == status + + +@pytest.mark.parametrize('origin,credentials,status', [('*', 'true', 'fail'), ('*', 'false', 'pass'), + ('*', 'TRUE', 'pass'), ('https://example.com', 'true', 'pass')]) +def test_cors_wildcard_means_incompatible_credentials_not_data_exposure(origin, credentials, status): + _, rules = evaluate(headers={'Access-Control-Allow-Origin': origin, + 'Access-Control-Allow-Credentials': credentials}) + item = rules['security.cors_wildcard_credentials'] + assert item['status'] == status + assert item['evidence']['credentialed_request_tested'] is False + assert 'expos' not in item['message'] + + +@pytest.mark.parametrize('viewport,missing,zoom', [ + (None, 'fail', 'not_applicable'), (' ', 'fail', 'not_applicable'), + ('width=device-width', 'pass', 'pass'), ('user-scalable = NO', 'pass', 'fail'), + ('user-scalable=0', 'pass', 'fail'), ('maximum-scale = 1.5', 'pass', 'fail'), + ('maximum-scale=2', 'pass', 'pass'), ('maximum-scale=10', 'pass', 'pass'), + ('maximum-scale=nan', 'pass', 'pass'), ('maximum-scale=invalid', 'pass', 'pass'), +]) +def test_viewport_rules_use_authored_values_and_zoom_boundary(viewport, missing, zoom): + _, rules = evaluate(document(viewport=viewport), headers={}) + assert rules['mobile.viewport_missing']['status'] == missing + assert rules['mobile.viewport_zoom_disabled']['status'] == zoom + + +def test_markup_does_not_prove_layout_plugins_pwa_or_javascript_execution(): + soup = document('
Text
' + '' + '

Text

', + head='') + result, rules = evaluate(soup, headers={}) + assert result['data']['mobile']['readiness'] is None + assert result['data']['mobile']['pwa_ready'] is None + profile = analyze_mobile_optimization(soup) + assert profile.uses_plugins is False + assert profile.horizontal_scrolling is None + assert profile.text_readability is None + assert result['data']['javascript_seo']['spa_detected'] is None + assert rules['technical.javascript_redirect_reference']['status'] == 'informational' + assert rules['technical.javascript_redirect_reference']['evidence']['executed'] is None + assert detect_javascript_seo_issues(soup)['recommendations'] == [] + assert result['score'] == 100 + + +def test_url_name_advice_preserves_query_semantics_and_omits_session_values(): + result, rules = evaluate(url=URL + '?SID=private-token&sid=&a=1&a=2', headers={}) + item = rules['technical.url_session_parameter'] + assert item['status'] == 'informational' + assert item['evidence']['parameter_names'] == ['SID', 'sid'] + assert 'private-token' not in json.dumps(item) + assert result['data']['url']['parameters'] == 3 + assert result['score'] == 100 + + +@pytest.mark.parametrize('lang,status', [('en', 'pass'), ('fr-CA', 'pass'), (' ', 'fail')]) +def test_language_declaration_has_explicit_evidence(lang, status): + _, rules = evaluate(document(lang=lang), headers={}) + assert rules['language.missing']['status'] == status + + +def test_charset_prefers_transport_declaration_and_uses_shared_advisory_rule(): + result, rules = evaluate(headers={'Content-Type': 'text/html; charset="windows-1252"'}) + assert result['data']['international']['charset'] == 'windows-1252' + assert rules['seo.charset_non_utf8']['status'] == 'informational' + assert rules['seo.charset_non_utf8']['owner'] == 'seo' + assert result['score'] == 100 + + +def test_mixed_resource_references_use_document_base_without_claiming_network_requests(): + soup = document('Link', + head='') + _, rules = evaluate(soup, headers={}) + item = rules['technical.http_resource_reference'] + assert item['status'] == 'informational' + assert item['evidence']['count'] == 1 + assert item['evidence']['references'][0]['url'] == 'http://assets.example/a/picture.jpg' + assert item['evidence']['effective_requests_checked'] is False + + +def test_obsolete_elements_are_advisory_and_doctype_is_syntax_specific(): + result, rules = evaluate(document('
Text
', + doctype=''), headers={}) + assert rules['technical.deprecated_elements']['status'] == 'informational' + assert rules['html.doctype_legacy']['status'] == 'informational' + assert result['score'] == 100 + _, xml_rules = evaluate(document(doctype=''), headers={'Content-Type': 'application/xhtml+xml'}) + assert xml_rules['html.doctype_missing']['status'] == 'not_applicable' + _, missing = evaluate(document(doctype=''), headers={}) + assert missing['html.doctype_missing']['status'] == 'fail' + + +def test_non_html_response_does_not_acquire_html_failures(): + _, rules = evaluate(BeautifulSoup('

JSON-looking content

', 'html.parser'), + headers={'Content-Type': 'application/json'}) + for rule_id in ('html.doctype_missing', 'mobile.viewport_missing', 'language.missing', + 'technical.http_compression', 'security.csp_missing'): + assert rules[rule_id]['status'] == 'not_applicable' + + +def test_scoring_and_guidance_are_only_registry_based_and_input_is_unchanged(): + soup = document('

Text

', lang='', viewport=None, doctype='') + before = str(soup) + result, _ = evaluate(soup, url='http://example.com/', headers={'X-Frame-Options': 'invalid'}, status_code=503) + assert str(soup) == before + assert result['score'] == score_findings(result['issues'], owner='technical') + assert result['recommendations'] == recommendations_for(result['issues']) + assert result['data']['recommendations'] == result['recommendations'] + # Changing words cannot choose advice or severity through a substring match. + first = create_issue('Anything', 'notice', 'cache mobile security protocol URL', + rule_id='html.doctype_missing', evidence={'doctype': None}) + second = create_issue('Anything', 'critical', 'Completely different words', + rule_id='html.doctype_missing', evidence={'doctype': None}) + assert first['fix'] == second['fix'] == get_rule('html.doctype_missing').recommendation + assert first['severity'] == second['severity'] == 'warning' + json.dumps(result, allow_nan=False) diff --git a/tests/wheel_smoke.py b/tests/wheel_smoke.py new file mode 100644 index 0000000..5af9c4f --- /dev/null +++ b/tests/wheel_smoke.py @@ -0,0 +1,129 @@ +"""Run with python -I after installing a built wheel, not an editable checkout.""" + +import asyncio +import csv +import importlib.util +import json +import tempfile +from pathlib import Path + +from bs4 import BeautifulSoup + +import tfq0seo +from tfq0seo.core.config import Config +from tfq0seo.core.report_contracts import validate_page_result, validate_site_report +from tfq0seo.exporters.base import ExportManager +from tfq0seo.page_facts import FACTS_VERSION +from tfq0seo.rules import RULESET_VERSION, SCORING_VERSION +from tfq0seo.site_analysis import SITE_ANALYSIS_VERSION + + +async def main(): + source_root = Path(__file__).resolve().parents[1] + if Path(tfq0seo.__file__).resolve().parent == source_root / 'tfq0seo': + raise AssertionError('Smoke test imported the source checkout instead of the installed wheel') + legacy = {'profile': 'quick', 'crawler': {'use_http2': False, 'max_pages': 2, 'concurrent_requests': 2}, + 'analysis': {'min_content_length': 100}} + before = json.loads(json.dumps(legacy)) + try: + Config.from_dict(legacy) + except ValueError as error: + assert 'Config.migrate_dict()' in str(error) + else: + raise AssertionError('Retired settings must require explicit migration') + migrated, warnings = Config.migrate_dict(legacy) + assert legacy == before + assert migrated == {'profile': 'quick', 'crawler': {'max_pages': 2, 'max_concurrent': 2}, 'analysis': {}} + assert any('crawler.use_http2' in warning for warning in warnings) + assert any('analysis.min_content_length' in warning for warning in warnings) + try: + Config.migrate_dict({'crawler': {'use_http2': True}}) + except ValueError as error: + assert 'cannot be migrated automatically' in str(error) + else: + raise AssertionError('Migration must reject unsupported non-default behavior') + cfg = Config.from_dict(migrated) + assert cfg.crawler.max_pages == 2 and cfg.crawler.max_concurrent == 2 + analyzer = tfq0seo.SEOAnalyzer(cfg) + result = await analyzer.analyze_page({ + 'url': 'https://example.test/', 'status_code': 200, + 'soup': BeautifulSoup('Example' + '

Example

' + 'Final page', 'html.parser'), + 'headers': {}, + }) + assert not result.get('error') and not result.get('analyzer_errors'), result + assert validate_page_result(result, strict=True) is result + assert result['page_facts']['facts_version'] == FACTS_VERSION + assert result['page_facts']['headers_observed'] is True + assert 'headers' not in result['page_facts'] + assert result['scoring']['version'] == SCORING_VERSION + assert result['scoring']['ruleset_version'] == RULESET_VERSION + assert result['rule_coverage']['counts']['fail'] > 0 + deductions = [item for item in result['scoring']['deductions'] if item['rule_id'] == 'images.missing_alt'] + assert len(deductions) == 1 and deductions[0]['penalty'] == 7 + final = await analyzer.analyze_page({ + 'url': 'https://example.test/final', 'requested_url': 'https://example.test/old', 'status_code': 200, + 'redirect_chain': [{'url': 'https://example.test/old', 'status_code': 301, + 'location': 'https://example.test/final'}], + 'soup': BeautifulSoup('Final' + '

Final

', 'html.parser'), + 'headers': {'Link': '; rel="canonical"'}, + }) + assert not final.get('error') and not final.get('analyzer_errors'), final + assert validate_page_result(final, strict=True) is final + canonical = final['page_facts']['canonical'] + assert canonical['headers_checked'] is True and canonical['parse_errors'] == 0 + assert canonical['declarations'][0]['source'] == 'http_link' + assert canonical['declarations'][0]['eligible'] is True + with tempfile.TemporaryDirectory(prefix='tfq0seo-wheel-') as directory: + exporter = ExportManager({'output_directory': directory}) + report = analyzer.generate_site_report([result, final]) + assert validate_site_report(report, strict=True) is report + site = report['site_analysis'] + assert site['version'] == SITE_ANALYSIS_VERSION + indexed = {row['url']: row for row in site['pages']} + assert indexed[result['url']]['canonical_status'] == 'chain' + assert indexed[result['url']]['canonical_hops'] == 2 + assert indexed[result['url']]['canonical_terminal'] == final['url'] + assert indexed[final['url']]['canonical_status'] == 'self' + assert indexed[final['url']]['incoming_links'] == 1 + assert indexed[final['url']]['link_depth'] == 1 + assert site['links']['node_count'] == 2 and site['links']['edge_count'] == 1 + assert {'site.canonical_chain', 'site.canonical_target_redirect'} <= { + item['rule_id'] for item in site['findings']} + for filename in ('rule_metadata.html', 'site_analysis.html'): + assert (Path(tfq0seo.__file__).resolve().parent / 'templates' / filename).is_file() + exporter.jinja_env.get_template(filename) + templates = {'report': 'report.html', 'enhanced': 'enhanced_report.html', 'optimized': 'optimized_report.html'} + for template, filename in templates.items(): + packaged_template = Path(tfq0seo.__file__).resolve().parent / 'templates' / filename + assert packaged_template.is_file(), 'Missing packaged template: ' + filename + exporter.jinja_env.get_template(filename) # Do not permit the exporter's inline fallback. + exporter.config['html_template'] = template + output = Path(exporter.export(report, 'html', str(Path(directory) / filename))) + assert output.is_file() and output.stat().st_size > 0 + rendered = BeautifulSoup(output.read_text(encoding='utf-8'), 'html.parser') + assert rendered.select_one('.rule-metadata[data-rule-id="images.missing_alt"]') + assert SCORING_VERSION in rendered.select_one('.rule-assessment').get_text() + section = rendered.select_one('section[aria-label="Site-wide analysis"]') + assert section and 'Canonical and internal-link observations' in section.get_text() + assert len(section.select('tbody tr')) == 2 + assert 'chain' in section.get_text() and final['url'] in section.get_text() + formats = ['json', 'html', 'csv'] + if importlib.util.find_spec('openpyxl'): + formats.append('xlsx') + for format in formats: + output = Path(exporter.export(report, format)) + assert output.is_file() and output.stat().st_size > 0 + exported = json.loads(next(Path(directory).glob('*.json')).read_text(encoding='utf-8')) + assert exported['schema_version'] == '1.0' + assert exported['site_analysis'] == site + with next(Path(directory).glob('*.csv')).open(encoding='utf-8', newline='') as stream: + csv_rows = list(csv.DictReader(stream)) + assert len(csv_rows) == 2 and csv_rows[0]['canonical_hops'] == '2' + print('Installed wheel smoke test passed:', tfq0seo.__version__) + + +if __name__ == '__main__': + asyncio.run(main()) diff --git a/tfq0seo/__init__.py b/tfq0seo/__init__.py index a234fd5..fd5d2a5 100644 --- a/tfq0seo/__init__.py +++ b/tfq0seo/__init__.py @@ -1,6 +1,6 @@ """TFQ0SEO - SEO analysis tool with reports.""" -__version__ = "2.3.2" +__version__ = "3.0.0" __author__ = "TFQ0 SEO Team" from .core.app import SEOAnalyzer diff --git a/tfq0seo/analyzers/common.py b/tfq0seo/analyzers/common.py new file mode 100644 index 0000000..eaf89fb --- /dev/null +++ b/tfq0seo/analyzers/common.py @@ -0,0 +1,365 @@ +"""Shared parsing of observed page facts used by the analyzers.""" + +import re +from typing import Any, Dict, List, Optional +from urllib.parse import urlsplit +from ..urls import classify_url, is_internal_url, resolve_url +from ..rules import rule_result + + +def make_issue(category: str, severity: str, message: str, + details: Optional[Dict] = None, rule_id: Optional[str] = None, + evidence: Optional[Any] = None, source: str = 'html', + confidence: str = 'high', applicable: Optional[bool] = True, + status: str = 'fail', reason: str = '') -> Dict[str, Any]: + """Compatibility adapter; IDs and evidence are mandatory for new findings. + + Severity and recommendations come from the registry, never message text. + The positional severity argument remains accepted for existing callers. + """ + return rule_result(rule_id, evidence, message=message, category=category, + status=status, applicable=applicable, reason=reason, + source=source, confidence=confidence, details=details) + + +def heading_facts(soup: Any) -> Dict[str, Any]: + """Extract headings and check level transitions in document order.""" + headings = {f'h{level}': [] for level in range(1, 7)} + issues = [] + findings = [] + previous_level = 0 + for position, heading in enumerate(soup.find_all(re.compile(r'^h[1-6]$'))): + text = heading.get_text(' ', strip=True) + headings[heading.name].append({'text': text, 'length': len(text)}) + if not text: + message = f'Empty {heading.name.upper()} heading' + issues.append(message) + findings.append({'rule_id': 'headings.empty', 'message': message, + 'evidence': {'tag': heading.name, 'position': position, 'text': text}}) + level = int(heading.name[1]) + if previous_level and level > previous_level + 1: + message = f'Heading hierarchy broken: H{previous_level} followed by H{level}' + issues.append(message) + findings.append({'rule_id': 'headings.skipped_level', 'message': message, + 'evidence': {'previous_level': previous_level, 'level': level, 'position': position}}) + previous_level = level + if not headings['h1']: + issues.append('No H1 tag found') + findings.append({'rule_id': 'headings.missing_h1', 'message': 'No H1 tag found', + 'evidence': {'h1_count': 0}}) + lengths = [heading['length'] for group in headings.values() for heading in group] + return { + 'headings': headings, 'total_count': len(lengths), + 'hierarchy_valid': not issues, + 'average_length': round(sum(lengths) / len(lengths), 1) if lengths else 0, + 'issues': issues, + 'findings': findings, + } + + +def document_base_url(soup: Any, page_url: str) -> str: + """Honor the first HTML base href when it resolves to an HTTP URL.""" + base = soup.find('base', href=True) + if base: + resolved = resolve_url(base.get('href', ''), page_url) + if resolved and urlsplit(resolved).scheme.lower() in ('http', 'https'): + return resolved + return page_url + + + + + + + + +def header_values(headers: Any, name: str) -> List[str]: + """Read all instances, including multidicts and list-valued mappings.""" + if headers is None: + return [] + if hasattr(headers, 'getall'): + try: + return [str(value) for value in headers.getall(name)] + except KeyError: + pass + values = [] + for key, value in headers.items(): + if str(key).lower() == name.lower(): + if isinstance(value, (list, tuple)): + values.extend(str(item) for item in value) + else: + values.append(str(value)) + return values + + +def normalized_headers(headers: Any) -> Dict[str, str]: + if headers is None: + return {} + return {str(key).lower(): ', '.join(header_values(headers, str(key))) for key in headers} + + +_HTTP_TOKEN = re.compile(r"[!#$%&'*+\-.^_`|~0-9A-Za-z]+") +_URI_CHARACTERS = re.compile(r"[A-Za-z0-9\-._~:/?#\[\]@!$&'()*+,;=%]*") +_CANONICAL_QUALIFIERS = {'hreflang', 'lang', 'media', 'type'} + + +def _valid_uri_reference(value: str, allow_iri: bool = False) -> bool: + """Reject malformed references before the deliberately permissive URL resolver.""" + if re.search(r'%(?![0-9A-Fa-f]{2})', value) or value.count('#') > 1: + return False + if allow_iri: + if any(character.isspace() or ord(character) < 32 or ord(character) == 127 + or character in '<>"{}|\\^`' for character in value): + return False + elif not _URI_CHARACTERS.fullmatch(value): + return False + try: + parsed = urlsplit(value) + if parsed.netloc: + parsed.port # Validate any authority's port spelling and range. + except ValueError: + return False + if (parsed.scheme.lower() in ('http', 'https') or (not parsed.scheme and parsed.netloc)) and not resolve_url( + value, 'https://canonical-context.invalid/'): + return False + return bool(parsed.scheme or ':' not in parsed.path.split('/', 1)[0]) + + +def _canonical_target(href: Any, base_url: str, *, html: bool = False) -> Optional[str]: + if not isinstance(href, str): + return None + value = href.strip() if html else href + if (html and not value) or not _valid_uri_reference(value, allow_iri=html): + return None + resolved = resolve_url(value, base_url) + return resolved if resolved and urlsplit(resolved).scheme in ('http', 'https') else None + + +def _split_link_values(value: str) -> List[str]: + """Split the HTTP list without splitting commas in targets or quoted strings. + + Unbalanced delimiters keep the remainder together, so it cannot accidentally + become a valid canonical declaration after a malformed quoted parameter. + """ + values, start = [], 0 + in_target = in_quote = escaped = False + for index, character in enumerate(value): + if in_target: + if character == '>': + in_target = False + elif in_quote: + if escaped: + escaped = False + elif character == '\\': + escaped = True + elif character == '"': + in_quote = False + elif character == '<': + in_target = True + elif character == '"': + in_quote = True + elif character == ',': + if value[start:index].strip(' \t'): + values.append(value[start:index].strip(' \t')) + start = index + 1 + if value[start:].strip(' \t'): + values.append(value[start:].strip(' \t')) + return values + + +def _parse_link_value(value: str): + """Parse RFC 8288 link parameters; return safe partial evidence on failure.""" + parameters = [] + if not value.startswith('<') or '>' not in value: + return None, parameters, 'Malformed HTTP Link target syntax.' + end = value.index('>') + href, position = value[1:end], end + 1 + while position < len(value): + if value[position] in ' \t': + position += 1 + continue + if value[position] != ';': + return href, parameters, 'Malformed HTTP Link parameter separator.' + position += 1 + while position < len(value) and value[position] in ' \t': + position += 1 + match = _HTTP_TOKEN.match(value, position) + if not match: + return href, parameters, 'Malformed HTTP Link parameter name.' + name, position = match.group().lower(), match.end() + while position < len(value) and value[position] in ' \t': + position += 1 + parameter = None + if position < len(value) and value[position] == '=': + position += 1 + while position < len(value) and value[position] in ' \t': + position += 1 + if position < len(value) and value[position] == '"': + position += 1 + characters = [] + closed = False + while position < len(value): + character = value[position] + position += 1 + if character == '"': + closed = True + break + if character == '\\': + if position == len(value): + break + character = value[position] + position += 1 + if (ord(character) < 32 and character != '\t') or ord(character) == 127 or ord(character) > 255: + return href, parameters, 'Invalid character in HTTP Link quoted parameter.' + characters.append(character) + if not closed: + return href, parameters, 'Unterminated HTTP Link quoted parameter.' + parameter = ''.join(characters) + else: + match = _HTTP_TOKEN.match(value, position) + if not match: + return href, parameters, 'Malformed HTTP Link parameter value.' + parameter, position = match.group(), match.end() + parameters.append((name, parameter)) + if not _valid_uri_reference(href): + return href, parameters, 'Malformed HTTP Link URI reference.' + return href, parameters, '' + + +def canonical_facts(link_tags: List[Dict[str, Any]], page_url: str, + base_url: str, headers: Any = None) -> Dict[str, Any]: + """Observe canonical declarations without treating parse failures as absence. + + HTTP Link syntax and context follow RFC 8288 sections 3.1-3.3. Eligibility + also applies Google Search's head placement and alternate-attribute rules: + https://developers.google.com/search/docs/crawling-indexing/consolidate-duplicate-urls + No raw header or unrelated parameter values are retained in these facts. + """ + declarations, parse_errors = [], 0 + for link in link_tags: + attrs = {name.lower(): value for name, value in link['attrs'].items()} + rel = attrs.get('rel') or [] + rel = rel.split() if isinstance(rel, str) else rel + if 'canonical' not in [token.lower() for token in rel]: + continue + href = attrs.get('href') + href = href if isinstance(href, str) else None + target = _canonical_target(href, base_url, html=True) + reasons = [] + if not link.get('in_head', False): + reasons.append('HTML canonical declaration is outside the head.') + if _CANONICAL_QUALIFIERS.intersection(attrs): + reasons.append('Canonical declaration has alternate-version attributes.') + if target is None: + reasons.append('Canonical target is missing or is not a valid HTTP(S) URL.') + declarations.append({'href': href, 'url': target, 'source': 'html', + 'eligible': not reasons, 'reason': ' '.join(reasons)}) + + response_url = _canonical_target(page_url, page_url) + for field_value in header_values(headers, 'Link'): + for value in _split_link_values(field_value): + href, parameters, error = _parse_link_value(value) + rel_values = [parameter for name, parameter in parameters if name == 'rel'] + anchors = [parameter for name, parameter in parameters if name == 'anchor'] + if len(rel_values) != 1 or not (rel_values[0] or '').strip(): + error = error or 'HTTP Link requires one nonempty rel parameter.' + elif any(not (re.fullmatch(r'[a-z][a-z0-9.-]*', token, re.I) or + (_valid_uri_reference(token) and urlsplit(token).scheme)) + for token in rel_values[0].split()): + error = error or 'Malformed HTTP Link relation type.' + if len(anchors) > 1 or (anchors and (anchors[0] is None or not _valid_uri_reference(anchors[0]))): + error = error or 'HTTP Link anchor context is malformed or repeated.' + if error: + parse_errors += 1 + # Keep recognizable canonical evidence from malformed parameters, + # but never use any part of that link-value as an eligible edge. + if not any('canonical' in (parameter or '').lower().split() for parameter in rel_values): + continue + target = _canonical_target(href, page_url) + reasons = [error] if error else [] + if anchors and not error and _canonical_target(anchors[0], page_url) != response_url: + reasons.append('HTTP Link anchor identifies a different context.') + if _CANONICAL_QUALIFIERS.intersection(name for name, _ in parameters): + reasons.append('Canonical declaration has alternate-version attributes.') + if target is None: + reasons.append('Canonical target is not a valid HTTP(S) URL.') + declarations.append({'href': href, 'url': target, 'source': 'http_link', + 'eligible': not reasons, 'reason': ' '.join(reasons)}) + return {'declarations': declarations, 'headers_checked': headers is not None, + 'parse_errors': parse_errors} + + +_VALUE_DIRECTIVES = {'max-snippet', 'max-image-preview', 'max-video-preview', 'unavailable_after'} +_FLAG_DIRECTIVES = {'all', 'none', 'index', 'noindex', 'follow', 'nofollow', 'nosnippet', + 'noarchive', 'notranslate', 'noimageindex', 'indexifembedded'} + + +def _parse_directives(value: str, user_agent: str, scoped: bool) -> Dict[str, List[str]]: + found = {} + agent = None + for part in value.split(','): + part = part.strip().lower() + if not part: + continue + name, separator, argument = part.partition(':') + name = name.strip() + if scoped and separator and name not in _VALUE_DIRECTIVES: + agent = name + part = argument.strip() + name, separator, argument = part.partition(':') + name = name.strip() + if agent not in (None, '*', user_agent): + continue + if name in _VALUE_DIRECTIVES and separator: + found.setdefault(name, []).append(argument.strip()) + elif name in _FLAG_DIRECTIVES and not separator: + found.setdefault(name, []).append('') + return found + + +def parse_robots(soup: Any, headers: Any = None, user_agent: str = 'googlebot') -> Dict[str, Any]: + """Combine applicable robots directives; restrictive flags always win.""" + user_agent = user_agent.lower() + evidence = [] + directives = {} + for meta in soup.find_all('meta'): + name = str(meta.get('name', '')).strip().lower() + if name in ('robots', user_agent): + value = str(meta.get('content', '')) + evidence.append({'source': 'meta', 'name': name, 'value': value}) + for key, values in _parse_directives(value, user_agent, False).items(): + directives.setdefault(key, []).extend(values) + for value in header_values(headers, 'X-Robots-Tag'): + evidence.append({'source': 'header', 'name': 'X-Robots-Tag', 'value': value}) + for key, values in _parse_directives(value, user_agent, True).items(): + directives.setdefault(key, []).extend(values) + flags = set(directives) + if 'none' in flags: + flags.update(('noindex', 'nofollow')) + snippet_values = [] + for value in directives.get('max-snippet', []): + try: + snippet_values.append(int(value)) + except ValueError: + pass + limited_snippets = [value for value in snippet_values if value >= 0] + return { + 'user_agent': user_agent, 'status': 'observed', 'source': 'html_and_headers', + 'directives': sorted(flags), 'evidence': evidence, + 'headers_checked': headers is not None, + 'noindex': 'noindex' in flags, 'nofollow': 'nofollow' in flags, + 'nosnippet': 'nosnippet' in flags, 'noarchive': 'noarchive' in flags, + 'max_snippet': min(limited_snippets) if limited_snippets else (-1 if snippet_values else None), + 'indexability': 'blocked_by_robots' if 'noindex' in flags else 'no_blocking_directive_observed', + } + + +def is_nonblocking_script(script: Any) -> bool: + has_attr = getattr(script, 'has_attr', None) + has_async = has_attr('async') if callable(has_attr) else 'async' in script + has_defer = has_attr('defer') if callable(has_attr) else 'defer' in script + return has_async or has_defer or str(script.get('type', '')).lower() == 'module' + + +def score_grade(score: float) -> str: + return 'A' if score >= 90 else 'B' if score >= 80 else 'C' if score >= 70 else 'D' if score >= 60 else 'F' diff --git a/tfq0seo/analyzers/content.py b/tfq0seo/analyzers/content.py index f42a544..ea6d2fe 100644 --- a/tfq0seo/analyzers/content.py +++ b/tfq0seo/analyzers/content.py @@ -3,6 +3,7 @@ import re import math import hashlib +from zipfile import BadZipFile from typing import Dict, List, Any, Optional, Tuple, Set from collections import Counter, defaultdict from bs4 import BeautifulSoup, NavigableString, Tag @@ -10,6 +11,52 @@ from dataclasses import dataclass, field from enum import Enum import unicodedata +from .common import heading_facts, make_issue +from ..page_facts import PageFacts, ensure_page_facts, extract_content_text +from ..rules import RuleDefinition, RuleCollector, register_rules, score_findings, recommendations_for + + +_CONTENT_REFERENCE = 'https://developers.google.com/search/docs/fundamentals/creating-helpful-content' +_READABILITY_REFERENCE = 'https://www.w3.org/WAI/WCAG22/Understanding/reading-level.html' +CONTENT_RULES = ( + RuleDefinition('content.readability_difficult', 'content', 'notice', + 'Review the reading difficulty for the intended audience; offer a simpler explanation or supplemental content when useful.', + 'English text with at least 100 whitespace-delimited words and an available Flesch estimate; editorial review only.', + (_READABILITY_REFERENCE,), '2026-09-14', scored=False), + RuleDefinition('content.readability_grade', 'content', 'notice', + 'Check whether specialist vocabulary suits the intended readers and explain unfamiliar concepts when needed.', + 'English text with at least 100 whitespace-delimited words and an available estimated grade; this is not a WCAG conformance test.', + (_READABILITY_REFERENCE,), '2026-09-14', scored=False), + RuleDefinition('content.target_keywords_headings', 'content', 'notice', + 'Review whether headings describe their sections clearly. Include supplied topic terms only when natural and relevant.', + 'A caller supplied target keywords; exact phrase absence does not establish a search ranking problem.', + (_CONTENT_REFERENCE,), '2026-09-14', scored=False), + RuleDefinition('content.placeholder_content', 'content', 'notice', + 'Review the matched text in context and replace it only if it is unfinished copy rather than intentional content.', + 'Static text contains a known English placeholder phrase; page intent requires human review.', + (_CONTENT_REFERENCE,), '2026-09-14', scored=False), + RuleDefinition('content.passive_voice', 'content', 'notice', + 'Review the matched sentences for clarity. Passive voice may be appropriate for the subject and audience.', + 'English text matches a simple passive-voice pattern in more than 30% of sampled sentences; a local editorial heuristic.', + (_READABILITY_REFERENCE,), '2026-09-14', scored=False), + RuleDefinition('content.similar_h1', 'content', 'notice', + 'Check whether the similar headings identify distinct sections. Similar headings alone do not establish keyword cannibalization.', + 'At least two H1 elements have high token overlap; the 70% threshold is a local review heuristic.', + ('https://www.w3.org/WAI/tutorials/page-structure/headings/',), '2026-09-14', scored=False), + RuleDefinition('content.short_sections', 'content', 'notice', + 'Review whether each section fulfills its purpose; there is no minimum section word count for search rankings.', + 'More than three section, article, or div elements contain fewer than 50 whitespace-delimited words; local descriptive heuristic only.', + (_CONTENT_REFERENCE,), '2026-09-14', scored=False), + RuleDefinition('content.historical_years', 'content', 'notice', + 'Verify dates only if the page is intended to describe current information. Preserve accurate historical references.', + 'Text contains at least three references to years before 2016; historical dates do not establish outdated content.', + (_CONTENT_REFERENCE,), '2026-09-14', scored=False), + RuleDefinition('content.repeated_sentences', 'content', 'notice', + 'Review repeated sentences in context and remove only unintended repetition.', + 'The same sentence longer than 30 characters appears more than once in this document; quotations and repeated interface text may be intentional.', + (_CONTENT_REFERENCE,), '2026-09-14', scored=False), +) +register_rules(CONTENT_RULES) class ContentQuality(Enum): @@ -35,96 +82,42 @@ class ContentMetrics: speaking_time_minutes: float = 0.0 -def create_issue(category: str, severity: str, message: str, details: Optional[Dict] = None) -> Dict[str, Any]: - """Create an enhanced issue dictionary with recommendations.""" - issue = { - 'category': category, - 'severity': severity, # critical, warning, notice - 'message': message - } - if details: - issue['details'] = details - - # Add fix recommendations based on issue type - if 'word count' in message.lower(): - issue['fix'] = "Add more comprehensive content. Aim for 600-2000 words for blog posts, 300-500 for product pages." - elif 'readability' in message.lower(): - issue['fix'] = "Simplify sentences, use shorter words, and break up long paragraphs." - elif 'keyword' in message.lower(): - issue['fix'] = "Distribute keywords naturally throughout the content. Aim for 1-2% keyword density." - elif 'heading' in message.lower() or 'h1' in message.lower(): - issue['fix'] = "Add proper heading structure: one H1, multiple H2s, and H3s as needed for hierarchy." - - return issue +def create_issue(category: str, severity: str, message: str, details: Optional[Dict] = None, + rule_id: Optional[str] = None, evidence: Any = None, + confidence: str = 'high') -> Dict[str, Any]: + """Compatibility helper; registered rule identity supplies the guidance.""" + return make_issue(category, severity, message, details, rule_id, evidence, + confidence=confidence) def extract_text_content(soup: BeautifulSoup, preserve_structure: bool = False) -> str: - """Extract clean text content with optional structure preservation.""" - # Clone soup to avoid modifying original - soup_copy = BeautifulSoup(str(soup), 'html.parser') - - # Remove unwanted elements - for element in soup_copy(['script', 'style', 'noscript', 'iframe', 'svg']): - element.decompose() - - # Remove hidden elements - for element in soup_copy.find_all(style=re.compile(r'display:\s*none')): - element.decompose() - - for element in soup_copy.find_all(class_=re.compile(r'(hidden|invisible|hide)')): - element.decompose() - - if preserve_structure: - # Preserve paragraph and heading structure - text_parts = [] - for element in soup_copy.find_all(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li', 'div']): - text = element.get_text(separator=' ', strip=True) - if text and len(text) > 20: # Minimum meaningful text - text_parts.append(text) - text = '\n'.join(text_parts) - else: - # Get all text - text = soup_copy.get_text(separator=' ') - - # Advanced cleaning - text = re.sub(r'\s+', ' ', text) # Normalize whitespace - text = re.sub(r'[\r\n]+', '\n', text) # Normalize line breaks - text = re.sub(r'[^\S\n]+', ' ', text) # Remove extra spaces but keep line breaks - text = text.strip() - - return text + """Compatibility entry point for the shared nonmutating text extractor.""" + return extract_content_text(soup, preserve_structure) -def detect_language(text: str) -> str: - """Detect the primary language of the content.""" - # Simple language detection based on character sets - # In production, use langdetect or similar library - - # Check for Arabic - if re.search(r'[\u0600-\u06FF]', text): - return 'ar' - - # Check for Chinese - if re.search(r'[\u4E00-\u9FFF]', text): - return 'zh' - - # Check for Japanese - if re.search(r'[\u3040-\u309F\u30A0-\u30FF]', text): +def detect_language(text: str, declared_language: Optional[str] = None) -> str: + """Prefer the document language; return und when the evidence is insufficient.""" + if declared_language and re.fullmatch(r'[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*', declared_language.strip()): + return declared_language.strip().split('-')[0].lower() + letters = sum(unicodedata.category(char).startswith('L') for char in text) + if not letters: + return 'und' + kana = len(re.findall(r'[\u3040-\u309F\u30A0-\u30FF]', text)) + han = len(re.findall(r'[\u4E00-\u9FFF]', text)) + if kana and (kana + han) / letters > 0.5: return 'ja' - - # Check for Korean - if re.search(r'[\uAC00-\uD7AF]', text): + if han / letters > 0.5: + return 'zh' + if len(re.findall(r'[\u0600-\u06FF]', text)) / letters > 0.5: + return 'ar' + if len(re.findall(r'[\uAC00-\uD7AF]', text)) / letters > 0.5: return 'ko' - - # Check for Cyrillic (Russian, etc.) - if re.search(r'[\u0400-\u04FF]', text): - return 'ru' - - # Default to English - return 'en' + # Latin and Cyrillic scripts do not identify a language by themselves. + return 'und' -def analyze_content_structure(soup: BeautifulSoup) -> Dict[str, Any]: +def analyze_content_structure(soup: BeautifulSoup, language: str = 'und', + plain_text: Optional[str] = None, *, facts: Optional[PageFacts] = None) -> Dict[str, Any]: """Analyze the structural elements of content.""" structure = { 'has_introduction': False, @@ -153,37 +146,43 @@ def analyze_content_structure(soup: BeautifulSoup) -> Dict[str, Any]: } } + counts = facts.tag_counts if facts is not None else None + images = [record['attrs'] for record in facts.images] if facts is not None else soup.find_all('img') + + def count(tag): + return counts.get(tag, 0) if counts is not None else len(soup.find_all(tag)) + # Check for semantic HTML5 elements for element in ['article', 'section', 'aside', 'nav', 'main', 'figure']: - structure['semantic_elements'][element] = len(soup.find_all(element)) + structure['semantic_elements'][element] = count(element) # Media elements - structure['media_elements']['images'] = len(soup.find_all('img')) - structure['media_elements']['videos'] = len(soup.find_all(['video', 'iframe'])) - structure['media_elements']['audio'] = len(soup.find_all('audio')) + structure['media_elements']['images'] = len(images) + structure['media_elements']['videos'] = count('video') + count('iframe') + structure['media_elements']['audio'] = count('audio') # Check for infographics (images with certain patterns) - for img in soup.find_all('img'): + for img in images: alt_text = img.get('alt', '').lower() src = img.get('src', '').lower() if any(word in alt_text or word in src for word in ['infographic', 'chart', 'graph', 'diagram']): structure['media_elements']['infographics'] += 1 # Interactive elements - structure['interactive_elements']['forms'] = len(soup.find_all('form')) - structure['interactive_elements']['buttons'] = len(soup.find_all(['button', 'input[type="submit"]'])) - structure['interactive_elements']['links'] = len(soup.find_all('a', href=True)) - structure['interactive_elements']['tables'] = len(soup.find_all('table')) + structure['interactive_elements']['forms'] = count('form') + structure['interactive_elements']['buttons'] = len(soup.select('button, input[type="submit"]')) + structure['interactive_elements']['links'] = len(facts.anchors) if facts is not None else len(soup.find_all('a', href=True)) + structure['interactive_elements']['tables'] = count('table') # Detect introduction and conclusion - paragraphs = soup.find_all('p') - if paragraphs: - first_para_text = paragraphs[0].get_text().lower() + paragraphs = facts.paragraphs if facts is not None else [paragraph.get_text() for paragraph in soup.find_all('p')] + if paragraphs and language == 'en': + first_para_text = paragraphs[0].lower() intro_keywords = ['introduction', 'welcome', 'this article', 'this post', 'we will', 'let\'s explore'] structure['has_introduction'] = any(keyword in first_para_text for keyword in intro_keywords) if len(paragraphs) > 1: - last_para_text = paragraphs[-1].get_text().lower() + last_para_text = paragraphs[-1].lower() conclusion_keywords = ['conclusion', 'summary', 'in conclusion', 'to sum up', 'finally', 'in summary'] structure['has_conclusion'] = any(keyword in last_para_text for keyword in conclusion_keywords) @@ -194,17 +193,48 @@ def analyze_content_structure(soup: BeautifulSoup) -> Dict[str, Any]: r'(limited time|don\'t miss|act now|today only)' ] - text = extract_text_content(soup).lower() - for pattern in cta_patterns: + text = (plain_text if plain_text is not None else extract_text_content(soup)).lower() + for pattern in cta_patterns if language == 'en' else []: if re.search(pattern, text): structure['has_call_to_action'] = True break + if language != 'en': + for key in ('has_introduction', 'has_conclusion', 'has_call_to_action'): + structure[key] = None + structure['editorial_detection_status'] = 'heuristic' if language == 'en' else 'not_applicable' return structure +_READABILITY_VALUES = ( + 'flesch_reading_ease', 'flesch_kincaid_grade', 'gunning_fog', 'smog_index', + 'ari', 'coleman_liau', 'linsear_write', 'dale_chall', 'consensus_grade', + 'reading_time_seconds', 'speaking_time_seconds', 'lexical_diversity', + 'syllable_count', 'polysyllable_count', 'sentence_count', 'average_sentence_length', + 'reading_level', +) + + +def _readability_resource_error() -> Optional[str]: + """Check local corpus availability before textstat's automatic download path. + + Older textstat releases use packaged Pyphen/CMU dictionaries. Releases with + the backend package call nltk.download when corpora/cmudict is absent; + nltk.data.find itself only checks local paths and archives. + """ + if getattr(textstat, 'backend', None) is None: + return None + try: + import nltk.data + nltk.data.find('corpora/cmudict') + except (ImportError, LookupError, OSError, BadZipFile): + return ('Readability is unavailable because the installed textstat backend requires ' + 'local NLTK corpora/cmudict data. Runtime resource downloads are disabled.') + return None + + def calculate_advanced_readability(text: str, language: str = 'en') -> Dict[str, Any]: - """Calculate comprehensive readability metrics.""" + """Calculate readability estimates using installed, local resources only.""" metrics = {} if language != 'en': @@ -214,8 +244,18 @@ def calculate_advanced_readability(text: str, language: str = 'en') -> Dict[str, metrics['word_count'] = len(words) metrics['sentence_count'] = len([s for s in sentences if s.strip()]) metrics['average_sentence_length'] = len(words) / max(1, len(sentences)) + metrics.update(status='not_applicable', source='local_text_statistics', + reason='English readability formulas are not applicable to this language.') return metrics - + + metrics = dict.fromkeys(_READABILITY_VALUES) + metrics.update(status='unavailable', source='textstat', resource_policy='local_only') + resource_error = _readability_resource_error() + if resource_error: + metrics.update(error=resource_error, reason=resource_error, + missing_resources=['nltk:corpora/cmudict']) + return metrics + try: # Standard readability scores metrics['flesch_reading_ease'] = round(textstat.flesch_reading_ease(text), 1) @@ -263,9 +303,11 @@ def calculate_advanced_readability(text: str, language: str = 'en') -> Dict[str, metrics['reading_level'] = 'Difficult (College)' else: metrics['reading_level'] = 'Very Difficult (Graduate)' - + + metrics.update(status='estimate', missing_resources=[]) except Exception as e: - metrics['error'] = str(e) + metrics.update(dict.fromkeys(_READABILITY_VALUES)) + metrics.update(error=str(e), reason='The local readability calculation could not be completed.') return metrics @@ -378,158 +420,71 @@ def analyze_keyword_optimization(text: str, target_keywords: Optional[List[str]] def detect_content_issues(text: str, soup: BeautifulSoup) -> List[Dict[str, Any]]: - """Detect various content quality issues.""" - issues = [] - - # Check for Lorem Ipsum or placeholder text - placeholder_patterns = [ - r'lorem ipsum', - r'coming soon', - r'under construction', - r'placeholder', - r'sample text', - r'test content' - ] - - text_lower = text.lower() - for pattern in placeholder_patterns: - if re.search(pattern, text_lower): - issues.append({ - 'type': 'placeholder_content', - 'severity': 'critical', - 'message': f'Placeholder content detected: "{pattern}"' - }) - - # Check for excessive use of passive voice - passive_indicators = [ - r'was \w+ed by', - r'were \w+ed by', - r'is being \w+ed', - r'has been \w+ed', - r'will be \w+ed' - ] - - passive_count = 0 - sentences = re.split(r'[.!?]+', text) - for sentence in sentences: - for pattern in passive_indicators: - if re.search(pattern, sentence.lower()): - passive_count += 1 - break - - if len(sentences) > 0: - passive_ratio = passive_count / len(sentences) - if passive_ratio > 0.3: - issues.append({ - 'type': 'passive_voice', - 'severity': 'notice', - 'message': f'Excessive passive voice usage ({passive_count} sentences, {passive_ratio*100:.1f}%)' - }) - - # Check for keyword cannibalization - h1_tags = soup.find_all('h1') - h2_tags = soup.find_all('h2') - - if len(h1_tags) > 1: - h1_texts = [h1.get_text().lower() for h1 in h1_tags] - # Check for similar H1s - for i, h1_1 in enumerate(h1_texts): - for h1_2 in h1_texts[i+1:]: - similarity = len(set(h1_1.split()) & set(h1_2.split())) / max(len(h1_1.split()), len(h1_2.split())) - if similarity > 0.7: - issues.append({ - 'type': 'keyword_cannibalization', - 'severity': 'warning', - 'message': 'Multiple similar H1 tags may cause keyword cannibalization' - }) - break - - # Check for thin content sections + """Return registered editorial observations with the legacy type keys.""" + collector = RuleCollector('content') + html = soup.find('html') + language = detect_language(text, html.get('lang') if html else None) + _detect_content_rules(text, soup, collector, language) + return collector.issues + + +def _detect_content_rules(text: str, soup: BeautifulSoup, collector: RuleCollector, + language: str, *, facts: Optional[PageFacts] = None) -> None: + patterns = ('lorem ipsum', 'coming soon', 'under construction', 'placeholder', 'sample text', 'test content') + matches = [phrase for phrase in patterns if phrase in text.lower()] + result = collector.check('content.placeholder_content', bool(matches), + evidence={'matched_phrases': matches}, category='Content', confidence='low', + message=f'Possible placeholder phrases found: {", ".join(matches)}') + result['type'] = 'placeholder_content' + + sentences = [sentence.strip() for sentence in re.split(r'[.!?]+', text) if sentence.strip()] + passive_patterns = (r'was \w+ed by', r'were \w+ed by', r'is being \w+ed', r'has been \w+ed', r'will be \w+ed') + passive = [sentence for sentence in sentences if any(re.search(pattern, sentence.lower()) for pattern in passive_patterns)] + passive_ratio = len(passive) / len(sentences) if sentences else 0 + result = collector.check('content.passive_voice', passive_ratio > 0.3, + evidence={'sentences': passive, 'sentence_count': len(sentences), 'ratio': passive_ratio, 'threshold': 0.3, 'language': language}, + applicable=language == 'en' and bool(sentences), reason='Requires English text with identifiable sentences.', + category='Content', confidence='low', + message=f'Passive-voice patterns found in {len(passive)} sentences ({passive_ratio * 100:.1f}% of the sample)') + result['type'] = 'passive_voice' + + h1_texts = ([heading['text'].lower() for heading in facts.headings['headings']['h1']] if facts is not None + else [heading.get_text(' ', strip=True).lower() for heading in soup.find_all('h1')]) + similar = [] + for index, first in enumerate(h1_texts): + for second in h1_texts[index + 1:]: + similarity = len(set(first.split()) & set(second.split())) / max(1, len(first.split()), len(second.split())) + if similarity > 0.7: + similar.append({'first': first, 'second': second, 'token_overlap': similarity}) + result = collector.check('content.similar_h1', bool(similar), + evidence={'pairs': similar, 'h1_count': len(h1_texts), 'threshold': 0.7}, applicable=len(h1_texts) > 1, + reason='Requires at least two H1 headings.', category='Content', confidence='low', + message=f'{len(similar)} H1 pairs share similar wording; review whether this is intentional') + result['type'] = 'keyword_cannibalization' + sections = soup.find_all(['section', 'article', 'div']) - thin_sections = 0 - for section in sections: - section_text = section.get_text(strip=True) - if len(section_text) > 0 and len(section_text.split()) < 50: - thin_sections += 1 - - if thin_sections > 3: - issues.append({ - 'type': 'thin_content_sections', - 'severity': 'notice', - 'message': f'{thin_sections} sections with very little content (<50 words)' - }) - - # Check for outdated content indicators - current_year = 2024 # Update this - old_year_pattern = r'\b(19[0-9]{2}|200[0-9]|201[0-5])\b' - old_years = re.findall(old_year_pattern, text) - if old_years and len(old_years) > 2: - issues.append({ - 'type': 'potentially_outdated', - 'severity': 'notice', - 'message': f'Content contains old year references: {", ".join(set(old_years)[:5])}' - }) - - return issues + short_sections = [] + for index, section in enumerate(sections): + section_text = section.get_text(' ', strip=True) + count = len(section_text.split()) + if section_text and count < 50: + short_sections.append({'index': index, 'element': section.name, 'word_count': count}) + result = collector.check('content.short_sections', len(short_sections) > 3, + evidence={'sections': short_sections, 'count': len(short_sections), 'word_threshold': 50, 'language': language}, + applicable=bool(sections) and language not in ('zh', 'ja'), reason='Requires sections and a supported whitespace word count.', + category='Content', confidence='low', message=f'{len(short_sections)} sections contain fewer than 50 whitespace-delimited words; length alone is not a quality problem') + result['type'] = 'thin_content_sections' + + years = re.findall(r'\b(19[0-9]{2}|200[0-9]|201[0-5])\b', text) + result = collector.check('content.historical_years', len(years) > 2, + evidence={'years': years, 'cutoff_year': 2016}, category='Content', confidence='low', + message=f'Historical year references found: {", ".join(sorted(set(years))[:5])}; review only if this page should describe current events') + result['type'] = 'potentially_outdated' def calculate_content_score(metrics: Dict[str, Any], issues: List[Dict[str, Any]]) -> Tuple[float, str]: """Calculate overall content score and quality level.""" - score = 100.0 - - # Word count scoring - word_count = metrics.get('word_count', 0) - if word_count < 100: - score -= 25 - elif word_count < 300: - score -= 15 - elif word_count < 600: - score -= 5 - elif word_count > 2500: - score -= 3 # Very long content may need splitting - - # Readability scoring - if 'readability' in metrics: - fre = metrics['readability'].get('flesch_reading_ease', 60) - if fre < 30: - score -= 15 # Very difficult - elif fre < 50: - score -= 7 # Difficult - elif fre > 80: - score += 5 # Easy to read - - # Structure scoring - if 'structure' in metrics: - structure = metrics['structure'] - if structure.get('semantic_elements', {}).get('article', 0) > 0: - score += 3 - if structure.get('has_introduction'): - score += 2 - if structure.get('has_conclusion'): - score += 2 - if structure.get('has_call_to_action'): - score += 3 - - # Media scoring - if 'structure' in metrics: - media = metrics['structure'].get('media_elements', {}) - if media.get('images', 0) > 0: - score += 5 - if media.get('videos', 0) > 0: - score += 3 - - # Deduct for issues - for issue in issues: - severity = issue.get('severity', 'notice') - if severity == 'critical': - score -= 15 - elif severity == 'warning': - score -= 7 - elif severity == 'notice': - score -= 2 - - # Ensure score is within bounds - score = max(0, min(100, score)) + score = score_findings(issues) # Determine quality level if score >= 90: @@ -546,18 +501,22 @@ def calculate_content_score(metrics: Dict[str, Any], issues: List[Dict[str, Any] return score, quality.value -def analyze_content(soup: BeautifulSoup, url: str, target_keywords: Optional[List[str]] = None) -> Dict[str, Any]: +def analyze_content(soup: BeautifulSoup, url: str, target_keywords: Optional[List[str]] = None, + *, facts: Optional[PageFacts] = None) -> Dict[str, Any]: """Enhanced content analysis with comprehensive quality assessment.""" - issues = [] + page_facts = ensure_page_facts(soup, url, facts=facts) + collector = RuleCollector('content') data = {} # Extract text with structure preservation - text = extract_text_content(soup, preserve_structure=True) - plain_text = extract_text_content(soup, preserve_structure=False) + plain_text = page_facts.content_text # Detect language - language = detect_language(plain_text) + declared_language = page_facts.language + language = detect_language(plain_text, declared_language) data['language'] = language + data['language_source'] = 'html_lang' if declared_language and language != 'und' else 'script_heuristic' if language != 'und' else 'unknown' + data['score_scope'] = 'static_content_checks' # Basic metrics words = plain_text.split() @@ -569,11 +528,11 @@ def analyze_content(soup: BeautifulSoup, url: str, target_keywords: Optional[Lis metrics = ContentMetrics( word_count=word_count, sentence_count=sentence_count, - paragraph_count=len(soup.find_all('p')), + paragraph_count=len(page_facts.paragraphs), unique_words=len(set(words)), lexical_diversity=len(set(words)) / max(1, word_count), avg_sentence_length=word_count / max(1, sentence_count), - avg_paragraph_length=word_count / max(1, len(soup.find_all('p'))), + avg_paragraph_length=word_count / max(1, len(page_facts.paragraphs)), reading_time_minutes=word_count / 200, # Average reading speed speaking_time_minutes=word_count / 150 # Average speaking speed ) @@ -589,123 +548,79 @@ def analyze_content(soup: BeautifulSoup, url: str, target_keywords: Optional[Lis 'reading_time_minutes': round(metrics.reading_time_minutes, 1), 'speaking_time_minutes': round(metrics.speaking_time_minutes, 1) } - - # Word count analysis - if word_count < 300: - issues.append(create_issue('Content', 'warning', - f'Low word count ({word_count}), recommended minimum 300 words for SEO')) - elif word_count < 600: - issues.append(create_issue('Content', 'notice', - f'Moderate word count ({word_count}), consider expanding to 600+ words')) - elif word_count > 3000: - issues.append(create_issue('Content', 'notice', - f'Very long content ({word_count} words), consider splitting into multiple pages')) + data['metrics']['word_count_method'] = 'whitespace' + data['metrics']['reading_time_status'] = 'estimate' + if language in ('zh', 'ja'): + data['metrics'].update(word_count=None, unique_words=None, lexical_diversity=None, + avg_sentence_length=None, avg_paragraph_length=None, + reading_time_minutes=None, speaking_time_minutes=None, + word_count_method='unavailable', reading_time_status='unknown') # Readability analysis + readability = {} if word_count >= 100: readability = calculate_advanced_readability(plain_text, language) data['readability'] = readability - - if language == 'en' and 'flesch_reading_ease' in readability: - fre = readability['flesch_reading_ease'] - if fre < 30: - issues.append(create_issue('Content', 'warning', - f'Very difficult to read (Flesch score: {fre})')) - elif fre < 50: - issues.append(create_issue('Content', 'notice', - f'Fairly difficult to read (Flesch score: {fre})')) - - # Check grade level - grade = readability.get('consensus_grade', 12) - if grade > 12: - issues.append(create_issue('Content', 'notice', - f'College-level reading required (grade {grade})')) + fre = readability.get('flesch_reading_ease') + grade = readability.get('consensus_grade') + readability_applies = language == 'en' and word_count >= 100 + for rule_id, value, failed, label, threshold in ( + ('content.readability_difficult', fre, fre < 50 if fre is not None else None, 'Flesch reading ease', 50), + ('content.readability_grade', grade, grade > 12 if grade is not None else None, 'Estimated reading grade', 12), + ): + collector.check(rule_id, failed, + evidence={'metric': label, 'value': value, 'threshold': threshold, 'language': language, + 'word_count': word_count, 'error': readability.get('error'), + 'measurement_status': readability.get('status'), 'source': readability.get('source')}, + applicable=readability_applies, reason=(readability.get('reason') if readability_applies and value is None + else None) or 'Requires English text with at least 100 words and a readability estimate.', + category='Content', confidence='low', message=f'{label}: {value}; review suitability for the intended audience') # Content structure analysis - structure = analyze_content_structure(soup) + structure = analyze_content_structure(soup, language, plain_text, facts=page_facts) data['structure'] = structure - # Check for important structural elements - if not structure['has_introduction']: - issues.append(create_issue('Content', 'notice', - 'No clear introduction detected')) - - if word_count > 500 and not structure['has_conclusion']: - issues.append(create_issue('Content', 'notice', - 'No clear conclusion detected for long-form content')) - - if not structure['has_call_to_action']: - issues.append(create_issue('Content', 'notice', - 'No call-to-action detected')) - - # Heading analysis - headings = { - 'h1': soup.find_all('h1'), - 'h2': soup.find_all('h2'), - 'h3': soup.find_all('h3'), - 'h4': soup.find_all('h4'), - 'h5': soup.find_all('h5'), - 'h6': soup.find_all('h6') - } - - heading_structure = {k: len(v) for k, v in headings.items()} - data['heading_structure'] = heading_structure - - # H1 analysis - if heading_structure['h1'] == 0: - issues.append(create_issue('Content', 'critical', 'No H1 heading found')) - elif heading_structure['h1'] > 1: - issues.append(create_issue('Content', 'warning', - f'Multiple H1 headings ({heading_structure["h1"]}), should have only one')) - else: - h1_text = headings['h1'][0].get_text() - h1_length = len(h1_text) - if h1_length < 20: - issues.append(create_issue('Content', 'notice', - f'H1 heading too short ({h1_length} characters)')) - elif h1_length > 70: - issues.append(create_issue('Content', 'notice', - f'H1 heading too long ({h1_length} characters), aim for 20-70')) - - # Check heading hierarchy - if heading_structure['h3'] > 0 and heading_structure['h2'] == 0: - issues.append(create_issue('Content', 'notice', - 'H3 headings found without H2 headings (improper hierarchy)')) - - if word_count > 300 and heading_structure['h2'] == 0: - issues.append(create_issue('Content', 'warning', - 'No H2 headings found, consider adding subheadings for better structure')) + # Heading observations are shared with the SEO analyzer. + heading_data = page_facts.headings + headings = heading_data['headings'] + data['heading_structure'] = {level: len(records) for level, records in headings.items()} + + for rule_id in ('headings.missing_h1', 'headings.empty', 'headings.skipped_level'): + matches = [finding for finding in heading_data['findings'] if finding['rule_id'] == rule_id] + collector.check(rule_id, bool(matches), category='Content', + message='; '.join(finding['message'] for finding in matches), + evidence={'headings': heading_data['headings'], 'findings': matches}) # Keyword optimization analysis keyword_analysis = analyze_keyword_optimization(plain_text, target_keywords) data['keyword_analysis'] = keyword_analysis - # Check for keyword stuffing - for keyword, density in keyword_analysis['keyword_density'].items(): - if density > 3.0: - issues.append(create_issue('Content', 'warning', - f'Possible keyword stuffing: "{keyword}" appears with {density}% density')) - break + keyword_analysis['status'] = 'descriptive_statistics' + if language in ('zh', 'ja'): + keyword_analysis['keyword_density'] = {} + keyword_analysis['status'] = 'not_applicable' # Check keyword placement in headings + keywords_in_headings = [] if target_keywords: - keywords_in_headings = [] for keyword in target_keywords: keyword_lower = keyword.lower() for level, tags in headings.items(): for tag in tags: - if keyword_lower in tag.get_text().lower(): + if keyword_lower in tag['text'].lower(): keywords_in_headings.append(keyword) break keyword_analysis['keyword_placement']['in_headings'] = keywords_in_headings - if not keywords_in_headings: - issues.append(create_issue('Content', 'notice', - 'Target keywords not found in any headings')) + collector.check('content.target_keywords_headings', not keywords_in_headings, + evidence={'target_keywords': target_keywords or [], 'matched_keywords': keywords_in_headings, + 'headings': heading_data['headings']}, applicable=bool(target_keywords), + reason='Requires caller-supplied target keywords.', category='Content', confidence='low', + message='Target keyword phrases not found in headings; assess relevance in context') # Media optimization - images = soup.find_all('img') + images = [record['attrs'] for record in page_facts.images] data['image_analysis'] = { 'total_images': len(images), 'images_with_alt': 0, @@ -715,7 +630,7 @@ def analyze_content(soup: BeautifulSoup, url: str, target_keywords: Optional[Lis } for img in images: - if img.get('alt'): + if 'alt' in img: data['image_analysis']['images_with_alt'] += 1 if img.get('title'): data['image_analysis']['images_with_title'] += 1 @@ -724,42 +639,36 @@ def analyze_content(soup: BeautifulSoup, url: str, target_keywords: Optional[Lis if img.get('srcset') or 'responsive' in img.get('class', []): data['image_analysis']['responsive_images'] += 1 - if images and data['image_analysis']['images_with_alt'] < len(images): - missing_alt = len(images) - data['image_analysis']['images_with_alt'] - issues.append(create_issue('Content', 'warning', - f'{missing_alt} images missing alt text')) - - if word_count > 500 and len(images) == 0: - issues.append(create_issue('Content', 'notice', - 'No images found in long-form content, consider adding visual elements')) + missing_alt = [dict(index=index, src=image.get('src', '')) for index, image in enumerate(images) if 'alt' not in image] + collector.check('images.missing_alt', bool(missing_alt), applicable=bool(images), + reason='Requires image elements.', category='Content', + message=f'{len(missing_alt)} images missing alt attributes', + evidence={'count': len(missing_alt), 'images': missing_alt}) # Lists and formatting - ul_count = len(soup.find_all('ul')) - ol_count = len(soup.find_all('ol')) + tag_counts = page_facts.tag_counts + ul_count = tag_counts.get('ul', 0) + ol_count = tag_counts.get('ol', 0) data['list_usage'] = { 'unordered_lists': ul_count, 'ordered_lists': ol_count, 'total_lists': ul_count + ol_count } - if word_count > 500 and data['list_usage']['total_lists'] == 0: - issues.append(create_issue('Content', 'notice', - 'No lists found, consider using bullet points for better readability')) - # Detect content issues - content_issues = detect_content_issues(plain_text, soup) - for issue in content_issues: - issues.append(create_issue('Content', issue['severity'], issue['message'])) + _detect_content_rules(plain_text, soup, collector, language, facts=page_facts) # Check for duplicate content sentences_list = [s.strip() for s in sentences if len(s.strip()) > 30] - if sentences_list: - sentence_counts = Counter(sentences_list) - repeated = [s for s, count in sentence_counts.items() if count > 1] - if repeated: - issues.append(create_issue('Content', 'warning', - f'Found {len(repeated)} repeated sentences')) - data['repeated_sentences'] = repeated[:3] # Store first 3 for reference + sentence_counts = Counter(sentences_list) + repeated = [sentence for sentence, count in sentence_counts.items() if count > 1] + collector.check('content.repeated_sentences', bool(repeated), applicable=bool(sentences_list), + reason='Requires sentences longer than 30 characters.', category='Content', confidence='low', + message=f'Found {len(repeated)} repeated sentences; review whether repetition is intentional', + evidence={'sentences': [{'text': sentence, 'count': sentence_counts[sentence]} for sentence in repeated], + 'minimum_characters': 30}) + if repeated: + data['repeated_sentences'] = repeated[:3] # Schema markup suggestions schema_suggestions = [] @@ -767,19 +676,13 @@ def analyze_content(soup: BeautifulSoup, url: str, target_keywords: Optional[Lis # Detect content type for schema suggestions if any(word in plain_text.lower() for word in ['recipe', 'ingredients', 'cook', 'prep time']): schema_suggestions.append('Recipe') - if any(word in plain_text.lower() for word in ['faq', 'frequently asked', 'question', 'answer']): - schema_suggestions.append('FAQPage') - if any(word in plain_text.lower() for word in ['how to', 'step by step', 'tutorial', 'guide']): - schema_suggestions.append('HowTo') if any(word in plain_text.lower() for word in ['review', 'rating', 'stars', 'pros and cons']): schema_suggestions.append('Review') if any(word in plain_text.lower() for word in ['article', 'author', 'published', 'written by']): schema_suggestions.append('Article') - if schema_suggestions: + if schema_suggestions and language == 'en': data['schema_suggestions'] = schema_suggestions - issues.append(create_issue('Content', 'notice', - f'Consider adding schema markup: {", ".join(schema_suggestions)}')) # Calculate overall content score all_metrics = { @@ -788,6 +691,7 @@ def analyze_content(soup: BeautifulSoup, url: str, target_keywords: Optional[Lis 'structure': structure } + issues = collector.issues score, quality = calculate_content_score(all_metrics, issues) # Add quality assessment @@ -799,8 +703,6 @@ def analyze_content(soup: BeautifulSoup, url: str, target_keywords: Optional[Lis } # Identify strengths - if word_count >= 600: - data['quality_assessment']['strengths'].append('Good content length') if structure['has_call_to_action']: data['quality_assessment']['strengths'].append('Has call-to-action') if len(images) > 0: @@ -809,15 +711,16 @@ def analyze_content(soup: BeautifulSoup, url: str, target_keywords: Optional[Lis data['quality_assessment']['strengths'].append('Good vocabulary diversity') # Identify weaknesses - if word_count < 300: - data['quality_assessment']['weaknesses'].append('Content too short') - if 'readability' in data and data['readability'].get('flesch_reading_ease', 60) < 40: + if fre is not None and fre < 40: data['quality_assessment']['weaknesses'].append('Difficult to read') - if heading_structure['h1'] != 1: + if heading_data['issues']: data['quality_assessment']['weaknesses'].append('H1 issues') return { 'score': max(0, score), 'issues': issues, - 'data': data - } \ No newline at end of file + 'data': data, + 'recommendations': recommendations_for(issues), + 'rule_results': collector.results, + 'rule_coverage': collector.coverage, + } diff --git a/tfq0seo/analyzers/links.py b/tfq0seo/analyzers/links.py index a57865f..e899e7b 100644 --- a/tfq0seo/analyzers/links.py +++ b/tfq0seo/analyzers/links.py @@ -1,4 +1,4 @@ -"""Advanced link analyzer with comprehensive link quality assessment and SEO optimization.""" +"""Static link evidence extraction and local accessibility checks.""" import re import math @@ -9,6 +9,61 @@ from dataclasses import dataclass, field from enum import Enum from bs4 import BeautifulSoup, Tag +from .common import (classify_url, document_base_url, is_internal_url, + make_issue, resolve_url) +from ..rules import RuleDefinition, RuleCollector, register_rules, score_findings, recommendations_for +from ..page_facts import PageFacts, ensure_page_facts + + +_LINK_REFERENCE = 'https://developers.google.com/search/docs/crawling-indexing/links-crawlable' +_SPAM_REFERENCE = 'https://developers.google.com/search/docs/essentials/spam-policies' +LINK_RULES = ( + RuleDefinition('links.missing_anchor', 'links', 'warning', + 'Give the link an accessible name using meaningful text, a suitable image alternative, or an appropriate accessible label.', + 'HTTP(S) links have no text, image alternative, aria-label, resolvable aria-labelledby, or title in the supplied HTML; CSS-generated and script-generated names are not assessed.', + ('https://www.w3.org/WAI/WCAG22/Understanding/link-purpose-in-context.html', _LINK_REFERENCE), '2026-09-14'), + RuleDefinition('links.invalid_url', 'links', 'warning', + 'Replace the invalid href with a valid destination, or use a button for an action.', + 'An anchor href cannot be resolved as a valid URL reference in this document.', + (_LINK_REFERENCE,), '2026-09-14'), + RuleDefinition('links.javascript_url', 'links', 'warning', + 'Use a real href for navigation; use a button for an action that has no URL.', + 'An anchor uses a javascript URL rather than a crawlable destination.', + (_LINK_REFERENCE, 'https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/a'), '2026-09-14'), + RuleDefinition('links.broken', 'links', 'critical', + 'Verify the failed destination, update the link to a working URL, or remove it if it no longer serves a purpose.', + 'The supplied destination checks identify failed linked URLs; unchecked destinations are unknown, and transient failures require verification.', + ('https://developers.google.com/crawling/docs/troubleshooting/http-status-codes',), '2026-09-14'), + RuleDefinition('links.repeated_anchor', 'links', 'notice', + 'Review repeated anchor text in context; consistent navigation labels may be appropriate.', + 'A multiword anchor exceeds 10% of the sample; this local threshold does not establish over-optimization.', + (_LINK_REFERENCE,), '2026-09-14', scored=False), + RuleDefinition('links.generic_anchor', 'links', 'notice', + 'Check whether link purpose is clear from its accessible name and surrounding context.', + 'A known English generic anchor exceeds a combined 20% of the sample; purpose can still be provided by context.', + (_LINK_REFERENCE,), '2026-09-14', scored=False), + RuleDefinition('links.short_anchor', 'links', 'notice', + 'Review short anchor labels in their context; length does not establish keyword targeting or manipulation.', + 'Anchors matching the legacy 2-4 character pattern exceed 30% of the sample; descriptive observation only.', + (_LINK_REFERENCE,), '2026-09-14', scored=False), + RuleDefinition('links.repeated_external_domain', 'links', 'notice', + 'Review whether repeated references to this destination help readers; there is no universal maximum link count.', + 'More than five references point to one external domain; repeated references do not establish a link scheme.', + (_LINK_REFERENCE,), '2026-09-14', scored=False), + RuleDefinition('links.reciprocal_wording', 'links', 'notice', + 'Review the relationship and purpose of the link; wording alone does not establish an excessive link exchange.', + 'External link wording contains exchange, partner, reciprocal, or link-to-us; a low-confidence text heuristic.', + (_SPAM_REFERENCE,), '2026-09-14', scored=False), + RuleDefinition('links.paid_wording', 'links', 'notice', + 'If the link is paid or sponsored, qualify it with sponsored or nofollow. First verify the commercial relationship.', + 'Link text or context contains a commercial keyword without sponsored/nofollow; the relationship is not verified.', + (_LINK_REFERENCE,), '2026-09-14', scored=False), + RuleDefinition('links.hidden', 'links', 'notice', + 'Review the hidden link in context; navigation and interactive interfaces can legitimately hide links until needed.', + 'Caller-supplied or inline HTML evidence marks a link hidden; this does not establish manipulative intent.', + (_SPAM_REFERENCE,), '2026-09-14', scored=False), +) +register_rules(LINK_RULES) class LinkType(Enum): @@ -59,7 +114,7 @@ class LinkProfile: anchor_text: str context: str = "" type: LinkType = LinkType.CONTENT - quality: LinkQuality = LinkQuality.MEDIUM + quality: Optional[LinkQuality] = None attributes: Dict[str, Any] = field(default_factory=dict) position: str = "body" depth: int = 0 @@ -67,119 +122,24 @@ class LinkProfile: has_title: bool = False opens_new_tab: bool = False is_javascript: bool = False - domain_authority_estimate: int = 0 + domain_authority_estimate: Optional[int] = None -def create_issue(category: str, severity: str, message: str, details: Optional[Dict] = None) -> Dict[str, Any]: - """Create an enhanced issue dictionary with recommendations.""" - issue = { - 'category': category, - 'severity': severity, # critical, warning, notice - 'message': message - } - if details: - issue['details'] = details - - # Add fix recommendations based on issue type - if 'broken' in message.lower(): - issue['fix'] = "Fix or remove broken links. Use 301 redirects for moved content." - elif 'anchor text' in message.lower(): - issue['fix'] = "Use descriptive, keyword-rich anchor text that tells users what to expect." - elif 'nofollow' in message.lower(): - issue['fix'] = "Use nofollow for untrusted content, sponsored for paid links, ugc for user content." - elif 'external' in message.lower(): - issue['fix'] = "Balance external links with internal links. Link to authoritative sources." - - return issue +def create_issue(category: str, severity: str, message: str, details: Optional[Dict] = None, + rule_id: Optional[str] = None, evidence: Any = None, + confidence: str = 'high') -> Dict[str, Any]: + """Compatibility helper; registered rule identity supplies the guidance.""" + return make_issue(category, severity, message, details, rule_id, evidence, + confidence=confidence) def normalize_url(url: str, base_url: str) -> str: - """Advanced URL normalization for consistency.""" - if not url: - return "" - - # Handle special protocols - if url.startswith(('mailto:', 'tel:', 'javascript:', 'data:', '#')): - return url - - # Make URL absolute - absolute = urljoin(base_url, url) - - # Parse URL - parsed = urlparse(absolute) - - # Normalize domain (remove www if present) - netloc = parsed.netloc.lower() - if netloc.startswith('www.'): - netloc_no_www = netloc[4:] - else: - netloc_no_www = netloc - - # Normalize path - path = parsed.path - if path: - # Remove duplicate slashes - path = re.sub(r'/+', '/', path) - # Remove trailing slash except for root - if len(path) > 1 and path.endswith('/'): - path = path[:-1] - else: - path = '/' - - # Remove common tracking parameters - if parsed.query: - params = parse_qs(parsed.query) - tracking_params = { - 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', - 'fbclid', 'gclid', 'msclkid', 'ref', 'source', 'track' - } - cleaned_params = {k: v for k, v in params.items() if k.lower() not in tracking_params} - if cleaned_params: - from urllib.parse import urlencode - query = urlencode(cleaned_params, doseq=True) - else: - query = '' - else: - query = parsed.query - - # Reconstruct URL - normalized = f"{parsed.scheme}://{netloc}{path}" - if query: - normalized += f"?{query}" - - return normalized + """Resolve links while preserving paths, query order, and fragments.""" + return resolve_url(url, base_url) or url def is_internal_link(url: str, base_url: str) -> bool: - """Check if a URL is internal with subdomain handling.""" - if not url: - return True - - # Special URLs are not internal - if url.startswith(('mailto:', 'tel:', 'javascript:', 'data:')): - return False - - # Fragment-only links are internal - if url.startswith('#'): - return True - - # Parse both URLs - base_parsed = urlparse(base_url) - url_parsed = urlparse(urljoin(base_url, url)) - - # Get base domains (without www) - base_domain = base_parsed.netloc.lower().replace('www.', '') - url_domain = url_parsed.netloc.lower().replace('www.', '') - - # Check if same domain or subdomain - if base_domain == url_domain: - return True - - # Check for subdomain relationship - if url_domain.endswith('.' + base_domain) or base_domain.endswith('.' + url_domain): - return True - - return False + return is_internal_url(url, base_url) def extract_link_context(link_element: Tag, chars_before: int = 50, chars_after: int = 50) -> str: @@ -210,18 +170,21 @@ def extract_link_context(link_element: Tag, chars_before: int = 50, chars_after: return "" -def detect_link_type(link_element: Tag, href: str) -> LinkType: +def detect_link_type(link_element: Any, href: str) -> LinkType: """Detect the type/purpose of a link based on context.""" # Check link location in page structure - parent_chain = [] - current = link_element - for _ in range(5): # Check up to 5 parents - if current.parent: - current = current.parent - parent_chain.append(current.name) + if isinstance(link_element, dict): + parent_chain = link_element['parent_tags'][:5] + parent_roles = link_element['parent_roles'] + parent_classes = link_element['parent_classes'] + else: + parents = list(link_element.parents) + parent_chain = [parent.name for parent in parents[:5]] + parent_roles = [parent.get('role') for parent in parents if hasattr(parent, 'get')] + parent_classes = [str(parent.get('class', [])) for parent in parents if hasattr(parent, 'get')] # Navigation links - if 'nav' in parent_chain or any(p.get('role') == 'navigation' for p in link_element.parents if hasattr(p, 'get')): + if 'nav' in parent_chain or 'navigation' in parent_roles: return LinkType.NAVIGATION # Footer links @@ -229,11 +192,11 @@ def detect_link_type(link_element: Tag, href: str) -> LinkType: return LinkType.FOOTER # Sidebar links - if 'aside' in parent_chain or any('sidebar' in str(p.get('class', [])).lower() for p in link_element.parents if hasattr(p, 'get')): + if 'aside' in parent_chain or any('sidebar' in classes.lower() for classes in parent_classes): return LinkType.SIDEBAR # Breadcrumb links - if any('breadcrumb' in str(p.get('class', [])).lower() for p in link_element.parents if hasattr(p, 'get')): + if any('breadcrumb' in classes.lower() for classes in parent_classes): return LinkType.BREADCRUMB # Social media links @@ -260,105 +223,14 @@ def detect_link_type(link_element: Tag, href: str) -> LinkType: return LinkType.CONTENT -def assess_link_quality(link_profile: LinkProfile, is_internal: bool) -> LinkQuality: - """Assess the quality of a link based on various factors.""" - score = 50 # Start with neutral score - - # Anchor text quality - anchor = link_profile.anchor_text.lower() - if not anchor or anchor in ['click here', 'here', 'link', 'this']: - score -= 20 - elif len(anchor) > 60: - score -= 10 - elif len(anchor.split()) >= 3: # Good descriptive anchor - score += 10 - - # Link type scoring - if link_profile.type == LinkType.NAVIGATION: - score += 5 - elif link_profile.type == LinkType.AFFILIATE: - score -= 10 - elif link_profile.type == LinkType.SOCIAL: - score += 0 # Neutral - - # Attributes scoring - if link_profile.opens_new_tab and not link_profile.attributes.get('rel', ''): - score -= 15 # Security issue - - if link_profile.is_javascript: - score -= 10 # Not crawlable - - if link_profile.has_title: - score += 5 # Good for accessibility - - # Position scoring - if link_profile.position == 'header': - score += 10 - elif link_profile.position == 'footer': - score -= 5 - - # External link specific scoring - if not is_internal: - if link_profile.domain_authority_estimate > 50: - score += 20 - elif link_profile.domain_authority_estimate < 20: - score -= 15 - - # Determine quality level - if score >= 70: - return LinkQuality.HIGH - elif score >= 40: - return LinkQuality.MEDIUM - elif score >= 20: - return LinkQuality.LOW - else: - return LinkQuality.TOXIC +def assess_link_quality(link_profile: LinkProfile, is_internal: bool) -> Optional[LinkQuality]: + """Destination quality cannot be established from this page's markup.""" + return None -def estimate_domain_authority(domain: str) -> int: - """Estimate domain authority based on domain characteristics.""" - # This is a simplified estimation. In production, use APIs like Moz or Ahrefs - score = 30 # Default score - - # Well-known high-authority domains - high_authority = { - 'google.com': 100, 'youtube.com': 100, 'facebook.com': 100, - 'wikipedia.org': 100, 'amazon.com': 96, 'twitter.com': 94, - 'linkedin.com': 98, 'github.com': 96, 'microsoft.com': 95, - 'apple.com': 95, 'stackoverflow.com': 93, 'medium.com': 92, - 'reddit.com': 91, 'bbc.com': 94, 'cnn.com': 93, 'nytimes.com': 94, - 'forbes.com': 95, 'harvard.edu': 95, 'mit.edu': 94, 'stanford.edu': 95, - '.gov': 90, '.edu': 70, '.org': 50 - } - - # Check exact matches - domain_lower = domain.lower() - for auth_domain, auth_score in high_authority.items(): - if auth_domain in domain_lower: - return auth_score - - # TLD scoring - if domain.endswith('.gov'): - score = 90 - elif domain.endswith('.edu'): - score = 70 - elif domain.endswith('.org'): - score = 50 - elif domain.endswith(('.io', '.ai', '.app')): - score = 40 - - # Domain length (shorter is often better) - domain_name = domain.split('.')[0] - if len(domain_name) <= 10: - score += 10 - elif len(domain_name) > 20: - score -= 10 - - # Hyphens in domain (often lower quality) - if '-' in domain: - score -= 10 * domain.count('-') - - return max(0, min(100, score)) +def estimate_domain_authority(domain: str) -> Optional[int]: + """No authority dataset is available; domain spelling is not a measure.""" + return None def calculate_pagerank_flow(internal_links: List[Dict], max_iterations: int = 10) -> Dict[str, float]: @@ -434,6 +306,8 @@ def analyze_anchor_text_distribution(anchor_texts: List[str]) -> Dict[str, Any]: for text, percentage in distribution.items(): if percentage > 10 and len(text.split()) > 1: # Multi-word anchor issues.append({ + **create_issue('Links', 'notice', 'A repeated anchor label is common in the sample', + rule_id='links.repeated_anchor', evidence={'anchor': text, 'percentage': percentage, 'threshold': 10}, confidence='low'), 'type': 'over_optimization', 'anchor': text, 'percentage': percentage @@ -444,6 +318,8 @@ def analyze_anchor_text_distribution(anchor_texts: List[str]) -> Dict[str, Any]: generic_percentage = sum(distribution.get(anchor, 0) for anchor in generic_anchors) if generic_percentage > 20: issues.append({ + **create_issue('Links', 'notice', 'Generic English labels are common in the anchor sample', + rule_id='links.generic_anchor', evidence={'percentage': generic_percentage, 'threshold': 20, 'labels': generic_anchors}, confidence='low'), 'type': 'generic_overuse', 'percentage': generic_percentage }) @@ -454,6 +330,8 @@ def analyze_anchor_text_distribution(anchor_texts: List[str]) -> Dict[str, Any]: exact_match_percentage = sum(distribution[text] for text in exact_matches) if exact_match_percentage > 30: issues.append({ + **create_issue('Links', 'notice', 'Short labels are common in the anchor sample', + rule_id='links.short_anchor', evidence={'percentage': exact_match_percentage, 'threshold': 30, 'labels': exact_matches}, confidence='low'), 'type': 'exact_match_overuse', 'percentage': exact_match_percentage }) @@ -463,7 +341,7 @@ def analyze_anchor_text_distribution(anchor_texts: List[str]) -> Dict[str, Any]: 'distribution': distribution, 'issues': issues, 'unique_anchors': len(counter), - 'most_common': counter.most_common(10) + 'most_common': [list(item) for item in counter.most_common(10)] } @@ -484,6 +362,8 @@ def detect_link_schemes(links: List[Dict]) -> List[Dict[str, Any]]: for domain, count in domain_counts.items(): if count > 5: # More than 5 links to same external domain schemes.append({ + **create_issue('Links', 'notice', 'Multiple links reference the same external domain', + rule_id='links.repeated_external_domain', evidence={'domain': domain, 'count': count, 'threshold': 5}, confidence='low'), 'type': 'excessive_linking', 'domain': domain, 'count': count @@ -496,6 +376,9 @@ def detect_link_schemes(links: List[Dict]) -> List[Dict[str, Any]]: anchor = link.get('anchor_text', '').lower() if any(indicator in url or indicator in anchor for indicator in reciprocal_indicators): schemes.append({ + **create_issue('Links', 'notice', 'Link wording suggests reviewing the relationship with the destination', + rule_id='links.reciprocal_wording', evidence={'url': link.get('url', ''), 'anchor': anchor, + 'matched_terms': [term for term in reciprocal_indicators if term in url or term in anchor]}, confidence='low'), 'type': 'potential_reciprocal', 'url': link.get('url', '') }) @@ -510,6 +393,9 @@ def detect_link_schemes(links: List[Dict]) -> List[Dict[str, Any]]: if any(indicator in anchor or indicator in context for indicator in paid_indicators): if 'sponsored' not in rel and 'nofollow' not in rel: schemes.append({ + **create_issue('Links', 'notice', 'Commercial wording appears without a sponsored or nofollow qualifier', + rule_id='links.paid_wording', evidence={'url': link.get('url', ''), 'anchor': anchor, 'context': context, + 'rel': rel, 'matched_terms': [term for term in paid_indicators if term in anchor or term in context]}, confidence='low'), 'type': 'untagged_paid_link', 'url': link.get('url', '') }) @@ -518,6 +404,8 @@ def detect_link_schemes(links: List[Dict]) -> List[Dict[str, Any]]: for link in links: if link.get('is_hidden', False): schemes.append({ + **create_issue('Links', 'notice', 'A link is marked hidden; review its interface context', + rule_id='links.hidden', evidence={'url': link.get('url', ''), 'is_hidden': True}, confidence='low'), 'type': 'hidden_link', 'url': link.get('url', '') }) @@ -526,447 +414,123 @@ def detect_link_schemes(links: List[Dict]) -> List[Dict[str, Any]]: def analyze_link_velocity(links: List[Dict], timeframe_days: int = 30) -> Dict[str, Any]: - """Analyze link growth patterns and velocity.""" - # This is simplified - in production, you'd track link changes over time - total_links = len(links) - - # Calculate estimated velocity - links_per_day = total_links / max(1, timeframe_days) - - # Determine if velocity is suspicious - velocity_assessment = 'normal' - if links_per_day > 100: - velocity_assessment = 'very_high' - elif links_per_day > 50: - velocity_assessment = 'high' - elif links_per_day < 1: - velocity_assessment = 'low' - + """A single page snapshot provides no evidence of link growth.""" return { - 'total_links': total_links, - 'timeframe_days': timeframe_days, - 'links_per_day': round(links_per_day, 2), - 'assessment': velocity_assessment + 'total_links': len(links), 'timeframe_days': None, 'links_per_day': None, + 'assessment': 'unknown', 'status': 'not_measured', 'source': 'requires_history', } def analyze_internal_link_structure(internal_links: List[Dict], soup: BeautifulSoup) -> Dict[str, Any]: - """Analyze internal linking structure and optimization.""" - structure = { - 'total_internal': len(internal_links), - 'orphan_pages': [], - 'link_depth_distribution': defaultdict(int), - 'hub_pages': [], - 'cornerstone_candidates': [], - 'siloing_score': 0 + """Full graph conclusions are deferred to the post-crawl aggregation.""" + return { + 'total_internal': len(internal_links), 'orphan_pages': None, + 'link_depth_distribution': None, 'hub_pages': None, + 'cornerstone_candidates': None, 'siloing_score': None, + 'status': 'not_assessed', 'source': 'page_links_only', } - - if not internal_links: - return structure - - # Count links per page - page_link_counts = defaultdict(int) - for link in internal_links: - to_url = link.get('url', '') - page_link_counts[to_url] += 1 - - # Identify hub pages (pages with many incoming links) - avg_links = sum(page_link_counts.values()) / max(1, len(page_link_counts)) - for page, count in page_link_counts.items(): - if count > avg_links * 2: - structure['hub_pages'].append({ - 'url': page, - 'incoming_links': count - }) - - # Identify potential cornerstone content - # (Pages with both many incoming and outgoing links) - outgoing_counts = defaultdict(int) - for link in internal_links: - from_url = link.get('from_url', '') - outgoing_counts[from_url] += 1 - - for page in set(page_link_counts.keys()) & set(outgoing_counts.keys()): - if page_link_counts[page] > avg_links and outgoing_counts[page] > avg_links: - structure['cornerstone_candidates'].append({ - 'url': page, - 'incoming': page_link_counts[page], - 'outgoing': outgoing_counts[page] - }) - - # Analyze link depth (simplified) - for link in internal_links: - depth = link.get('depth', 0) - structure['link_depth_distribution'][depth] += 1 - - # Calculate siloing score (how well topics are grouped) - # This is simplified - proper siloing analysis would require content analysis - category_patterns = ['/blog/', '/products/', '/services/', '/resources/'] - category_links = defaultdict(int) - - for link in internal_links: - url = link.get('url', '') - for pattern in category_patterns: - if pattern in url: - category_links[pattern] += 1 - break - - if category_links: - # Higher score if links are well-distributed across categories - total_categorized = sum(category_links.values()) - entropy = 0 - for count in category_links.values(): - if count > 0: - prob = count / total_categorized - entropy -= prob * math.log2(prob) - - max_entropy = math.log2(len(category_links)) - structure['siloing_score'] = round((entropy / max_entropy * 100) if max_entropy > 0 else 0, 2) - - return structure -def analyze_links(soup: BeautifulSoup, url: str, broken_links: Optional[Set[str]] = None) -> Dict[str, Any]: - """Advanced link analysis with comprehensive quality assessment.""" - issues = [] - data = {} - - # Extract word count for link density calculation - text_content = soup.get_text(strip=True) - word_count = len(text_content.split()) - - # Find all links with detailed extraction - all_links = soup.find_all('a') - link_profiles = [] - - internal_links = [] - external_links = [] - anchor_texts = [] - - # Analyze each link in detail - for link_element in all_links: - href = link_element.get('href', '') - if not href: - continue - - # Extract comprehensive link information - anchor_text = link_element.get_text(strip=True) - title = link_element.get('title', '') - rel = link_element.get('rel', []) - target = link_element.get('target', '') - link_class = link_element.get('class', []) - - # Normalize URL - try: - normalized_url = normalize_url(href, url) - except: - normalized_url = href - - # Determine if internal - is_internal = is_internal_link(href, url) - - # Extract context - context = extract_link_context(link_element) - - # Detect link type - link_type = detect_link_type(link_element, href) - - # Determine position - position = 'body' - for parent in link_element.parents: - if parent.name == 'header': - position = 'header' - break - elif parent.name == 'footer': - position = 'footer' - break - elif parent.name == 'nav': - position = 'navigation' - break - - # Check for hidden link - is_hidden = False - style = link_element.get('style', '') - if 'display:none' in style.replace(' ', '') or 'visibility:hidden' in style: - is_hidden = True - - # Check if image link - is_image_link = bool(link_element.find('img')) - - # Create link profile - profile = LinkProfile( - url=normalized_url, - anchor_text=anchor_text, - context=context, - type=link_type, - attributes={ - 'rel': rel, - 'target': target, - 'title': title, - 'class': link_class, - 'is_hidden': is_hidden - }, - position=position, - is_image_link=is_image_link, - has_title=bool(title), - opens_new_tab=(target == '_blank'), - is_javascript=href.startswith('javascript:') - ) - - # Estimate domain authority for external links - if not is_internal: - domain = urlparse(normalized_url).netloc - profile.domain_authority_estimate = estimate_domain_authority(domain) - - # Assess link quality - profile.quality = assess_link_quality(profile, is_internal) - - # Store profile - link_profiles.append(profile) - - # Categorize for basic analysis +def analyze_links(soup: BeautifulSoup, url: str, broken_links: Optional[Set[str]] = None, *, + facts: Optional[PageFacts] = None) -> Dict[str, Any]: + """Extract complete link evidence; defer destination health to the crawler.""" + facts = ensure_page_facts(soup, url, facts=facts) + collector = RuleCollector('links') + internal_links, external_links, non_http_links = [], [], [] + anchor_texts, missing_anchors = [], [] + for record in facts.anchors: + element = record['attrs'] + href = element.get('href', '') + kind, resolved = record['url_kind'], record['url'] + anchor = record['labelled_text'] or record['text'] + if not anchor: + anchor = str(element.get('aria-label', '')).strip() + if not anchor: + anchor = record['image_alt_text'] + if not anchor: + anchor = str(element.get('title', '')).strip() + rel = element.get('rel', []) + rel = rel if isinstance(rel, list) else str(rel).split() + rel = [str(value).lower() for value in rel] + position = record['position'] + style = re.sub(r'\s+', '', element.get('style', '').lower()) link_data = { - 'url': normalized_url, - 'anchor_text': anchor_text, - 'text': anchor_text, - 'rel': rel, - 'target': target, - 'context': context, - 'type': link_type.value, - 'quality': profile.quality.value, - 'position': position, - 'is_internal': is_internal, - 'is_hidden': is_hidden, - 'from_url': url + 'url': resolved, 'href': href, 'anchor_text': anchor, 'text': anchor, + 'rel': rel, 'target': element.get('target', ''), + 'context': record['context'], + 'type': detect_link_type(record, href).value, 'type_status': 'heuristic', + 'quality': None, 'quality_status': 'not_assessed', + 'position': position, 'is_internal': kind == 'internal', + 'is_hidden': 'hidden' in element or 'display:none' in style or 'visibility:hidden' in style, + 'from_url': url, 'url_kind': kind, } - - if is_internal: + if kind == 'internal': internal_links.append(link_data) - else: + elif kind == 'external': external_links.append(link_data) - - if anchor_text: - anchor_texts.append(anchor_text) - - # Calculate metrics - metrics = LinkMetrics( - total_links=len(link_profiles), - internal_links=len(internal_links), - external_links=len(external_links) - ) - - # Analyze rel attributes - for profile in link_profiles: - rel_values = profile.attributes.get('rel', []) - if isinstance(rel_values, list): - rel_str = ' '.join(rel_values) - else: - rel_str = str(rel_values) - - rel_lower = rel_str.lower() - if 'nofollow' in rel_lower: - metrics.nofollow_links += 1 else: - metrics.dofollow_links += 1 - - if 'sponsored' in rel_lower: - metrics.sponsored_links += 1 - if 'ugc' in rel_lower: - metrics.ugc_links += 1 - - # Calculate ratios and density - if metrics.total_links > 0: - metrics.internal_external_ratio = metrics.internal_links / max(1, metrics.external_links) - metrics.link_density = (metrics.total_links / max(1, word_count)) * 100 - - if anchor_texts: - metrics.avg_anchor_length = sum(len(a.split()) for a in anchor_texts) / len(anchor_texts) - - # Count unique external domains - external_domains = set() - for link in external_links: - domain = urlparse(link['url']).netloc - if domain: - external_domains.add(domain) - metrics.unique_domains = len(external_domains) - - # Store metrics - data['metrics'] = { - 'total_links': metrics.total_links, - 'internal_links': metrics.internal_links, - 'external_links': metrics.external_links, - 'dofollow_links': metrics.dofollow_links, - 'nofollow_links': metrics.nofollow_links, - 'sponsored_links': metrics.sponsored_links, - 'ugc_links': metrics.ugc_links, - 'link_density': round(metrics.link_density, 2), - 'internal_external_ratio': round(metrics.internal_external_ratio, 2), - 'avg_anchor_length': round(metrics.avg_anchor_length, 2), - 'unique_domains': metrics.unique_domains + non_http_links.append(link_data) + if kind in ('internal', 'external'): + if anchor: + anchor_texts.append(anchor) + else: + missing_anchors.append(link_data) + links = internal_links + external_links + words = facts.text.split() + domains = sorted({urlparse(link['url']).netloc for link in external_links}) + nofollow = sum('nofollow' in link['rel'] for link in links) + metrics = { + 'total_links': len(links), 'internal_links': len(internal_links), + 'external_links': len(external_links), 'non_http_links': len(non_http_links), + 'dofollow_links': len(links) - nofollow, 'nofollow_links': nofollow, + 'sponsored_links': sum('sponsored' in link['rel'] for link in links), + 'ugc_links': sum('ugc' in link['rel'] for link in links), + 'link_density': round(len(links) / len(words) * 100, 2) if words else None, + 'internal_external_ratio': round(len(internal_links) / len(external_links), 2) if external_links else None, + 'avg_anchor_length': round(sum(len(anchor.split()) for anchor in anchor_texts) / len(anchor_texts), 2) if anchor_texts else None, + 'unique_domains': len(domains), } - - # Check for broken links - if broken_links: - found_broken = [] - for link in internal_links + external_links: - if link['url'] in broken_links: - found_broken.append(link['url']) - metrics.broken_links += 1 - - if found_broken: - issues.append(create_issue('Links', 'critical', - f'{len(found_broken)} broken links found', - {'broken_links': found_broken[:10]})) - data['broken_links'] = found_broken - - # Analyze anchor text distribution + collector.check('links.missing_anchor', bool(missing_anchors), + evidence={'links': missing_anchors, 'http_link_count': len(links)}, category='Links', + applicable=bool(links), reason='Requires HTTP(S) links.', + message=f'{len(missing_anchors)} web links have no accessible name in the supplied HTML') + invalid = [link for link in non_http_links if link['url_kind'] == 'invalid'] + collector.check('links.invalid_url', bool(invalid), evidence={'links': invalid}, category='Links', + applicable=bool(links or non_http_links), reason='Requires anchor elements with href.', + message=f'{len(invalid)} links have empty or invalid URL references') + javascript = [link for link in non_http_links if link['url_kind'] == 'javascript'] + collector.check('links.javascript_url', bool(javascript), evidence={'links': javascript}, category='Links', + applicable=bool(links or non_http_links), reason='Requires anchor elements with href.', + message=f'{len(javascript)} JavaScript links have no crawlable URL destination') + found_broken = [link['url'] for link in links if broken_links is not None and link['url'] in broken_links] + broken_result = collector.check('links.broken', True if found_broken else None, + evidence={'urls': found_broken, 'http_link_count': len(links), 'known_failures_supplied': broken_links is not None, + 'unchecked_urls': sorted({link['url'] for link in links} - set(found_broken))}, + applicable=bool(links), category='Links', source='supplied_destination_checks', + reason='No HTTP(S) links to check.' if not links else 'Only known failed URLs are available; other destination health is unknown.', + message=f'{len(found_broken)} broken links found' if found_broken else 'Destination health has not been established') + if found_broken: + broken_result['details'] = {'broken_links': found_broken} anchor_analysis = analyze_anchor_text_distribution(anchor_texts) - data['anchor_analysis'] = anchor_analysis - - if anchor_analysis['diversity_score'] < 50: - issues.append(create_issue('Links', 'warning', - f'Low anchor text diversity (score: {anchor_analysis["diversity_score"]}%)')) - - for issue in anchor_analysis['issues']: - if issue['type'] == 'over_optimization': - issues.append(create_issue('Links', 'warning', - f'Anchor text "{issue["anchor"]}" is over-optimized ({issue["percentage"]:.1f}%)')) - elif issue['type'] == 'generic_overuse': - issues.append(create_issue('Links', 'warning', - f'Too many generic anchor texts ({issue["percentage"]:.1f}%)')) - - # Analyze internal link structure - internal_structure = analyze_internal_link_structure(internal_links, soup) - data['internal_structure'] = internal_structure - - # Detect link schemes - all_link_data = internal_links + external_links - link_schemes = detect_link_schemes(all_link_data) - if link_schemes: - data['potential_schemes'] = link_schemes - for scheme in link_schemes[:3]: # Report top 3 - if scheme['type'] == 'excessive_linking': - issues.append(create_issue('Links', 'warning', - f'Excessive links to {scheme["domain"]} ({scheme["count"]} links)')) - elif scheme['type'] == 'untagged_paid_link': - issues.append(create_issue('Links', 'critical', - f'Potential paid link without proper rel attributes')) - - # Analyze link velocity - velocity_analysis = analyze_link_velocity(all_link_data) - data['link_velocity'] = velocity_analysis - - if velocity_analysis['assessment'] == 'very_high': - issues.append(create_issue('Links', 'warning', - 'Unusually high link velocity detected')) - - # Quality distribution - quality_distribution = Counter(p.quality.value for p in link_profiles) - data['quality_distribution'] = dict(quality_distribution) - - toxic_links = quality_distribution.get('toxic', 0) - if toxic_links > 0: - issues.append(create_issue('Links', 'critical', - f'{toxic_links} potentially toxic links detected')) - - # Link type distribution - type_distribution = Counter(p.type.value for p in link_profiles) - data['type_distribution'] = dict(type_distribution) - - # Position distribution - position_distribution = Counter(p.position for p in link_profiles) - data['position_distribution'] = dict(position_distribution) - - # Navigation analysis - nav_links = [p for p in link_profiles if p.type == LinkType.NAVIGATION] - if len(nav_links) == 0: - issues.append(create_issue('Links', 'warning', - 'No navigation links detected')) - elif len(nav_links) > 50: - issues.append(create_issue('Links', 'notice', - f'Too many navigation links ({len(nav_links)}), consider simplifying')) - - # Footer link analysis - footer_links = [p for p in link_profiles if p.position == 'footer'] - if len(footer_links) > 100: - issues.append(create_issue('Links', 'notice', - f'Excessive footer links ({len(footer_links)})')) - - # External link quality check - low_quality_external = [p for p in link_profiles - if not is_internal_link(p.url, url) and p.quality == LinkQuality.LOW] - if len(low_quality_external) > 5: - issues.append(create_issue('Links', 'warning', - f'{len(low_quality_external)} low-quality external links detected')) - - # Check for nofollow on all external links - external_dofollow = [l for l in external_links - if 'nofollow' not in str(l.get('rel', '')).lower()] - if len(external_dofollow) > 10: - issues.append(create_issue('Links', 'notice', - f'{len(external_dofollow)} external dofollow links - consider using nofollow for untrusted content')) - - # Check for security issues - security_issues = [p for p in link_profiles - if p.opens_new_tab and 'noopener' not in str(p.attributes.get('rel', '')).lower()] - if security_issues: - issues.append(create_issue('Links', 'warning', - f'{len(security_issues)} links with target="_blank" missing rel="noopener"')) - - # JavaScript links - js_links = [p for p in link_profiles if p.is_javascript] - if js_links: - issues.append(create_issue('Links', 'warning', - f'{len(js_links)} JavaScript links are not crawlable by search engines')) - - # Calculate overall score - score = 100 - - # Score based on metrics - if metrics.total_links == 0: - score -= 30 - elif metrics.link_density > 10: - score -= 15 - elif metrics.link_density > 5: - score -= 5 - - # Score based on balance - if metrics.internal_external_ratio < 0.5: - score -= 10 - elif metrics.internal_external_ratio > 10: - score -= 5 - - # Score based on quality - high_quality_percentage = (quality_distribution.get('high', 0) / max(1, metrics.total_links)) * 100 - if high_quality_percentage < 20: - score -= 10 - - # Score based on issues - for issue in issues: - if issue['severity'] == 'critical': - score -= 15 - elif issue['severity'] == 'warning': - score -= 7 - elif issue['severity'] == 'notice': - score -= 3 - - # Add recommendations - data['recommendations'] = [] - - if metrics.internal_external_ratio < 1: - data['recommendations'].append('Add more internal links to improve site navigation and SEO') - - if anchor_analysis['diversity_score'] < 70: - data['recommendations'].append('Increase anchor text diversity for better SEO') - - if toxic_links > 0: - data['recommendations'].append('Review and remove potentially toxic links') - - if len(internal_structure['hub_pages']) < 3: - data['recommendations'].append('Create hub pages with comprehensive internal linking') - - return { - 'score': max(0, min(100, score)), - 'issues': issues, - 'data': data - } \ No newline at end of file + # Distribution describes the sample; it does not establish over-optimization. + anchor_analysis['issues'] = [] + anchor_analysis['status'] = 'descriptive_statistics' + data = { + 'score_scope': 'static_link_checks', 'metrics': metrics, + 'internal_links': internal_links, 'external_links': external_links, + 'non_http_links': non_http_links, 'external_domains': domains, + 'anchor_analysis': anchor_analysis, + 'internal_structure': analyze_internal_link_structure(internal_links, soup), + 'link_velocity': analyze_link_velocity(links), + 'authority_status': 'not_measured', 'quality_distribution': {'unknown': len(links)}, + 'type_distribution': dict(Counter(link['type'] for link in links)), + 'position_distribution': dict(Counter(link['position'] for link in links)), + 'broken_links': found_broken if broken_links is not None else None, + 'link_health_status': 'partial' if broken_links is not None else 'not_checked', + } + issues = collector.issues + score = score_findings(issues) + recommendations = recommendations_for(issues) + data['recommendations'] = recommendations + return {'score': score, 'issues': issues, 'data': data, 'recommendations': recommendations, + 'rule_results': collector.results, 'rule_coverage': collector.coverage} diff --git a/tfq0seo/analyzers/performance.py b/tfq0seo/analyzers/performance.py index b00b273..0a0a849 100644 --- a/tfq0seo/analyzers/performance.py +++ b/tfq0seo/analyzers/performance.py @@ -1,4 +1,4 @@ -"""Advanced performance analyzer with Core Web Vitals, resource optimization, and network analysis.""" +"""Static performance inspection with explicit measurement provenance.""" import re import math @@ -9,6 +9,41 @@ from dataclasses import dataclass, field from enum import Enum from bs4 import BeautifulSoup, Tag +from .common import (classify_url, document_base_url, is_nonblocking_script, + make_issue, resolve_url, score_grade) +from ..rules import RuleDefinition, RuleCollector, register_rules, score_findings, recommendations_for +from ..page_facts import PageFacts, ensure_page_facts + + +_SCRIPT_REFERENCE = 'https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script' +PERFORMANCE_RULES = ( + RuleDefinition('performance.blocking_scripts', 'performance', 'warning', + 'Review parser-blocking scripts in a browser trace. Use defer for order-dependent scripts or async for independent scripts only when compatible with their behavior.', + 'External classic JavaScript in head lacks async/defer. Static attributes identify parser-blocking candidates; timing impact is not measured.', + (_SCRIPT_REFERENCE, 'https://html.spec.whatwg.org/multipage/scripting.html#the-script-element', + 'https://mimesniff.spec.whatwg.org/#javascript-mime-type'), '2026-09-14'), + RuleDefinition('performance.responsive_images', 'performance', 'notice', + 'Check image display sizes and transfer sizes across devices; supply responsive sources where they improve the actual image use case.', + 'Image elements lack srcset/sizes hints. Small fixed-size images and vector images may need no alternatives; the 30% threshold is a local review heuristic.', + ('https://web.dev/articles/responsive-images',), '2026-09-14', scored=False), + RuleDefinition('performance.large_inline_scripts', 'performance', 'notice', + 'Measure the cost of the inline JavaScript before changing its loading or caching strategy.', + 'Executable inline script text exceeds 1000 characters; this local review threshold does not measure transfer or execution cost.', + (_SCRIPT_REFERENCE,), '2026-09-14', scored=False), + RuleDefinition('performance.jquery_references', 'performance', 'notice', + 'Inspect the referenced scripts for duplicate libraries before removing any dependency.', + 'Multiple script URLs contain a jQuery naming pattern; plugins and custom filenames may be legitimate.', + (_SCRIPT_REFERENCE,), '2026-09-14', scored=False), + RuleDefinition('performance.inline_styles', 'performance', 'notice', + 'Review style maintenance and browser measurements before moving repeated styles into a stylesheet.', + 'More than 20 elements have inline style attributes; this local count does not establish a rendering problem.', + ('https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/style',), '2026-09-14', scored=False), + RuleDefinition('performance.document_write', 'performance', 'notice', + 'Review whether document.write is actually executed and replace it with DOM APIs when feasible.', + 'Executable inline JavaScript contains a document.write text reference; comments and unreachable code can match.', + ('https://developer.mozilla.org/en-US/docs/Web/API/Document/write',), '2026-09-14', scored=False), +) +register_rules(PERFORMANCE_RULES) class ResourceType(Enum): @@ -38,35 +73,36 @@ class ResourceProfile: """Detailed resource information.""" url: str type: ResourceType - size: int = 0 - load_time: float = 0.0 + size: Optional[int] = None + load_time: Optional[float] = None is_render_blocking: bool = False is_async: bool = False is_deferred: bool = False is_lazy: bool = False is_critical: bool = False is_third_party: bool = False - is_cached: bool = False + is_cached: Optional[bool] = None priority: str = "auto" compression: Optional[str] = None - cache_duration: int = 0 + cache_duration: Optional[int] = None @dataclass class PerformanceMetrics: """Container for performance metrics.""" - load_time: float = 0.0 - dom_content_loaded: float = 0.0 - time_to_first_byte: float = 0.0 - first_contentful_paint: float = 0.0 - largest_contentful_paint: float = 0.0 - first_input_delay: float = 0.0 - cumulative_layout_shift: float = 0.0 - time_to_interactive: float = 0.0 - speed_index: float = 0.0 - total_blocking_time: float = 0.0 - max_potential_fid: float = 0.0 - total_byte_weight: int = 0 + load_time: Optional[float] = None + dom_content_loaded: Optional[float] = None + time_to_first_byte: Optional[float] = None + first_contentful_paint: Optional[float] = None + largest_contentful_paint: Optional[float] = None + first_input_delay: Optional[float] = None + interaction_to_next_paint: Optional[float] = None + cumulative_layout_shift: Optional[float] = None + time_to_interactive: Optional[float] = None + speed_index: Optional[float] = None + total_blocking_time: Optional[float] = None + max_potential_fid: Optional[float] = None + total_byte_weight: Optional[int] = None dom_size: int = 0 @@ -90,37 +126,39 @@ class OptimizationOpportunity: title: str impact: str # high, medium, low category: str - estimated_savings_ms: float = 0 - estimated_savings_bytes: int = 0 + estimated_savings_ms: Optional[float] = None + estimated_savings_bytes: Optional[int] = None description: str = "" implementation: str = "" -def create_issue(category: str, severity: str, message: str, details: Optional[Dict] = None) -> Dict[str, Any]: - """Create an enhanced issue with optimization guidance.""" - issue = { - 'category': category, - 'severity': severity, - 'message': message - } - if details: - issue['details'] = details - - # Add specific optimization recommendations - if 'image' in message.lower(): - issue['fix'] = "Optimize images: Use WebP/AVIF formats, implement lazy loading, serve responsive images with srcset" - elif 'script' in message.lower() or 'javascript' in message.lower(): - issue['fix'] = "Optimize scripts: Minify, bundle, use async/defer, implement code splitting, remove unused code" - elif 'css' in message.lower() or 'stylesheet' in message.lower(): - issue['fix'] = "Optimize CSS: Extract critical CSS, minify, remove unused rules, implement CSS-in-JS for components" - elif 'cache' in message.lower(): - issue['fix'] = "Implement caching: Set proper Cache-Control headers, use CDN, implement service worker caching" - elif 'font' in message.lower(): - issue['fix'] = "Optimize fonts: Use font-display: swap, preload critical fonts, subset fonts, use variable fonts" +def create_issue(category: str, severity: str, message: str, details: Optional[Dict] = None, + rule_id: Optional[str] = None, evidence: Any = None, + confidence: str = 'high') -> Dict[str, Any]: + """Compatibility helper; registered rule identity supplies the guidance.""" + return make_issue(category, severity, message, details, rule_id, evidence, + confidence=confidence) + + +def _is_classic_javascript(script: Tag) -> bool: + """Exclude module scripts and data blocks from parser-blocking checks.""" + if not (script.has_attr('type') if isinstance(script, Tag) else 'type' in script): + language = str(script.get('language', '')) + script_type = ('text/' + language) if language else 'text/javascript' else: - issue['fix'] = "Review performance best practices and implement appropriate optimizations" - - return issue + declared_type = str(script.get('type', '')) + script_type = 'text/javascript' if declared_type == '' else declared_type.strip(' \t\n\r\f') + script_type = script_type.lower() + return script_type in ( + 'application/ecmascript', 'application/javascript', 'application/x-ecmascript', + 'application/x-javascript', 'text/ecmascript', 'text/javascript', 'text/javascript1.0', + 'text/javascript1.1', 'text/javascript1.2', 'text/javascript1.3', 'text/javascript1.4', + 'text/javascript1.5', 'text/jscript', 'text/livescript', 'text/x-ecmascript', 'text/x-javascript', + ) + + +def _is_executable_script(script: Tag) -> bool: + return _is_classic_javascript(script) or str(script.get('type', '')).strip().lower() == 'module' def detect_resource_type(element: Tag, url: str = "") -> ResourceType: @@ -158,29 +196,8 @@ def detect_resource_type(element: Tag, url: str = "") -> ResourceType: def is_third_party(resource_url: str, page_url: str) -> bool: - """Check if a resource is from a third-party domain.""" - if not resource_url or resource_url.startswith(('data:', 'blob:', '#')): - return False - - try: - resource_domain = urlparse(resource_url).netloc - page_domain = urlparse(page_url).netloc - - # Remove www prefix for comparison - resource_domain = resource_domain.replace('www.', '') - page_domain = page_domain.replace('www.', '') - - # Check if same domain or subdomain - if resource_domain == page_domain: - return False - - # Check if subdomain of main domain - if resource_domain.endswith('.' + page_domain) or page_domain.endswith('.' + resource_domain): - return False - - return True - except: - return False + """Classify resource references using the same URL rules as link analysis.""" + return classify_url(resource_url, page_url) == 'external' def calculate_resource_priority(resource: ResourceProfile) -> str: @@ -201,44 +218,27 @@ def calculate_resource_priority(resource: ResourceProfile) -> str: return "auto" -def estimate_compression_savings(content: str, content_type: str) -> int: - """Estimate potential compression savings.""" - if not content: - return 0 - - original_size = len(content.encode('utf-8')) - - # Estimate compression ratio based on content type - compression_ratios = { - 'html': 0.3, - 'css': 0.25, - 'js': 0.35, - 'json': 0.2, - 'svg': 0.3, - 'xml': 0.25 - } - - ratio = 0.5 # Default - for type_key, type_ratio in compression_ratios.items(): - if type_key in content_type.lower(): - ratio = type_ratio - break - - estimated_compressed = int(original_size * ratio) - return original_size - estimated_compressed +def estimate_compression_savings(content: str, content_type: str) -> Optional[int]: + """Actual transfer savings require compressed and uncompressed byte counts.""" + return None -def analyze_critical_rendering_path(soup: BeautifulSoup) -> Dict[str, Any]: +def analyze_critical_rendering_path(soup: BeautifulSoup, *, facts: Optional[PageFacts] = None) -> Dict[str, Any]: """Analyze the critical rendering path.""" critical_path = { 'render_blocking_resources': [], 'critical_request_chains': [], - 'estimated_savings_ms': 0 + 'estimated_savings_ms': None, + 'status': 'static_candidates', + 'source': 'html', + 'critical_request_chains_status': 'unknown' } # Find render-blocking resources # CSS in head without media queries - for link in soup.find_all('link', rel='stylesheet'): + links = ([record['attrs'] for record in facts.link_tags if 'stylesheet' in record['attrs'].get('rel', [])] + if facts is not None else soup.find_all('link', rel='stylesheet')) + for link in links: media = link.get('media', 'all') if media in ['all', 'screen', '']: critical_path['render_blocking_resources'].append({ @@ -248,84 +248,90 @@ def analyze_critical_rendering_path(soup: BeautifulSoup) -> Dict[str, Any]: }) # Scripts in head without async/defer - head = soup.find('head') - if head: - for script in head.find_all('script', src=True): - if not script.get('async') and not script.get('defer'): - critical_path['render_blocking_resources'].append({ - 'type': 'script', - 'url': script.get('src', ''), - 'impact': 'high' - }) - - # Estimate impact (100ms per blocking resource as rough estimate) - critical_path['estimated_savings_ms'] = len(critical_path['render_blocking_resources']) * 100 + if facts is not None: + scripts = [record['attrs'] for record in facts.scripts if record['in_head'] and 'src' in record['attrs']] + else: + head = soup.find('head') + scripts = head.find_all('script', src=True) if head else [] + for script in scripts: + if _is_classic_javascript(script) and not is_nonblocking_script(script): + critical_path['render_blocking_resources'].append({ + 'type': 'script', 'url': script.get('src', ''), 'impact': 'high' + }) return critical_path -def detect_performance_patterns(soup: BeautifulSoup) -> Dict[str, Any]: - """Detect common performance patterns and anti-patterns.""" - patterns = { - 'good_patterns': [], - 'bad_patterns': [], - 'opportunities': [] - } - - # Good patterns - if soup.find('link', rel='preconnect'): - patterns['good_patterns'].append('Uses preconnect for third-party origins') - - if soup.find('link', rel='dns-prefetch'): - patterns['good_patterns'].append('Uses DNS prefetching') - - if soup.find('link', rel='preload'): - patterns['good_patterns'].append('Uses resource preloading') - - if soup.find('script', attrs={'type': 'module'}): +def _script_records(soup: BeautifulSoup, facts: Optional[PageFacts] = None) -> List[Dict[str, Any]]: + if facts is not None: + return facts.scripts + return [{'attrs': dict(script.attrs), 'text': script.string or '', + 'in_head': script.find_parent('head') is not None, 'index': index} + for index, script in enumerate(soup.find_all('script'))] + + +def detect_performance_patterns(soup: BeautifulSoup, *, facts: Optional[PageFacts] = None) -> Dict[str, Any]: + """Describe source patterns using the shared attribute and script snapshot.""" + patterns = {'good_patterns': [], 'bad_patterns': [], 'opportunities': [], + 'status': 'heuristic', 'source': 'html'} + links = [record['attrs'] for record in facts.link_tags] if facts is not None else soup.find_all('link') + scripts = _script_records(soup, facts) + images = [record['attrs'] for record in facts.images] if facts is not None else soup.find_all('img') + metas = [record['attrs'] for record in facts.meta] if facts is not None else soup.find_all('meta') + for relation, message in ( + ('preconnect', 'Declares preconnect hints'), ('dns-prefetch', 'Uses DNS prefetching'), + ('preload', 'Uses resource preloading'), + ): + if any(relation in link.get('rel', []) for link in links): + patterns['good_patterns'].append(message) + if any(script['attrs'].get('type') == 'module' for script in scripts): patterns['good_patterns'].append('Uses ES6 modules') - - if soup.find('img', loading='lazy'): + if any(image.get('loading') == 'lazy' for image in images): patterns['good_patterns'].append('Implements lazy loading for images') - - # Check for service worker - if soup.find('script', string=re.compile(r'serviceWorker|navigator\.serviceWorker')): - patterns['good_patterns'].append('Has service worker for offline support') - - # Bad patterns - inline_scripts = soup.find_all('script', src=False) - large_inline_scripts = [s for s in inline_scripts if s.string and len(s.string) > 1000] + if any(re.search(r'serviceWorker|navigator\.serviceWorker', script['text']) for script in scripts): + patterns['good_patterns'].append('Contains a service worker code reference; registration was not verified') + inline_scripts = [script for script in scripts if 'src' not in script['attrs'] and _is_executable_script(script['attrs'])] + large_inline_scripts = [script for script in inline_scripts if len(script['text']) > 1000] if large_inline_scripts: patterns['bad_patterns'].append(f'Large inline scripts ({len(large_inline_scripts)} found)') - - # Multiple jQuery versions - jquery_scripts = soup.find_all('script', src=re.compile(r'jquery[\.-]')) + jquery_scripts = [script for script in scripts if re.search(r'jquery[\.-]', script['attrs'].get('src', ''))] if len(jquery_scripts) > 1: - patterns['bad_patterns'].append('Multiple jQuery versions detected') - - # Inline styles on many elements + patterns['bad_patterns'].append('Multiple jQuery-named script references; review for duplicate loading') elements_with_style = soup.find_all(style=True) if len(elements_with_style) > 20: patterns['bad_patterns'].append(f'Excessive inline styles ({len(elements_with_style)} elements)') - - # document.write usage - if soup.find('script', string=re.compile(r'document\.write')): + if any(re.search(r'document\.write', script['text']) for script in scripts): patterns['bad_patterns'].append('Uses document.write() which blocks parsing') - - # Opportunities - if not soup.find('link', rel='modulepreload'): + if not any('modulepreload' in link.get('rel', []) for link in links): patterns['opportunities'].append('Consider modulepreload for ES6 modules') - - if not soup.find('meta', attrs={'http-equiv': 'Accept-CH'}): + if not any(meta.get('http-equiv') == 'Accept-CH' for meta in metas): patterns['opportunities'].append('Consider Client Hints for responsive images') - - if not soup.find('link', attrs={'as': 'font', 'crossorigin': True}): + if not any(link.get('as') == 'font' and 'crossorigin' in link for link in links): patterns['opportunities'].append('Preload fonts with crossorigin attribute') - + collector = RuleCollector('performance') + observations = ( + ('performance.large_inline_scripts', bool(large_inline_scripts), + {'scripts': [{'characters': len(script['text'])} for script in large_inline_scripts], 'threshold_characters': 1000}, + f'Large inline script text ({len(large_inline_scripts)} found)', bool(inline_scripts)), + ('performance.jquery_references', len(jquery_scripts) > 1, + {'urls': [script['attrs'].get('src', '') for script in jquery_scripts]}, + 'Multiple jQuery-named script references; review for duplicate loading', bool(jquery_scripts)), + ('performance.inline_styles', len(elements_with_style) > 20, + {'element_count': len(elements_with_style), 'threshold': 20}, + f'Inline styles found on {len(elements_with_style)} elements', bool(elements_with_style)), + ('performance.document_write', any(re.search(r'document\.write', script['text']) for script in inline_scripts), + {'matches': [script['text'] for script in inline_scripts if re.search(r'document\.write', script['text'])]}, + 'Inline script text contains document.write; execution was not verified', bool(inline_scripts)), + ) + for rule_id, failed, evidence, message, applicable in observations: + collector.check(rule_id, failed, evidence=evidence, message=message, category='Performance', + applicable=applicable, reason='Requires matching HTML elements.', confidence='low') + patterns['findings'] = collector.issues + patterns['rule_results'] = collector.results return patterns -def analyze_image_optimization(soup: BeautifulSoup) -> Dict[str, Any]: +def analyze_image_optimization(soup: BeautifulSoup, *, facts: Optional[PageFacts] = None) -> Dict[str, Any]: """Analyze image optimization opportunities.""" image_analysis = { 'total_images': 0, @@ -334,10 +340,12 @@ def analyze_image_optimization(soup: BeautifulSoup) -> Dict[str, Any]: 'with_dimensions': 0, 'responsive_images': 0, 'issues': [], - 'savings_potential_kb': 0 + 'savings_potential_kb': None, + 'savings_status': 'unknown', + 'source': 'html_attributes' } - images = soup.find_all('img') + images = [record['attrs'] for record in facts.images] if facts is not None else soup.find_all('img') image_analysis['total_images'] = len(images) for img in images: @@ -361,636 +369,264 @@ def analyze_image_optimization(soup: BeautifulSoup) -> Dict[str, Any]: # Calculate issues and savings if image_analysis['total_images'] > 0: - # Estimate 30% savings with WebP/AVIF - unoptimized = image_analysis['total_images'] - image_analysis['optimized_formats'] - image_analysis['savings_potential_kb'] = unoptimized * 50 # Assume 50KB average savings per image - - if image_analysis['lazy_loaded'] < image_analysis['total_images'] * 0.5: - image_analysis['issues'].append('Most images are not lazy loaded') - if image_analysis['with_dimensions'] < image_analysis['total_images'] * 0.8: image_analysis['issues'].append('Many images missing width/height attributes') if image_analysis['responsive_images'] < image_analysis['total_images'] * 0.3: image_analysis['issues'].append('Few responsive images implemented') + collector = RuleCollector('performance') + missing_dimensions = [dict(index=index, src=img.get('src', '')) for index, img in enumerate(images) + if not (img.get('width') and img.get('height'))] + collector.check('images.missing_dimensions', bool(missing_dimensions), + evidence={'images': missing_dimensions, 'count': len(missing_dimensions), 'css_layout_checked': False}, + applicable=bool(images), reason='Requires image elements.', category='Performance', confidence='low', + message=f'{len(missing_dimensions)} images lack width/height attributes; CSS may reserve their layout space') + collector.check('performance.responsive_images', image_analysis['responsive_images'] < len(images) * 0.3, + evidence={'image_count': len(images), 'with_responsive_attributes': image_analysis['responsive_images'], 'ratio_threshold': 0.3}, + applicable=bool(images), reason='Requires image elements.', category='Performance', confidence='low', + message='Few image elements declare responsive sources; review whether variants are useful') + image_analysis['findings'] = collector.issues + image_analysis['rule_results'] = collector.results return image_analysis -def analyze_javascript_optimization(soup: BeautifulSoup) -> Dict[str, Any]: - """Analyze JavaScript optimization opportunities.""" +def analyze_javascript_optimization(soup: BeautifulSoup, page_url: Optional[str] = None, *, + facts: Optional[PageFacts] = None) -> Dict[str, Any]: + """Analyze JavaScript attributes using the shared script snapshot.""" js_analysis = { - 'total_scripts': 0, - 'async_scripts': 0, - 'defer_scripts': 0, - 'module_scripts': 0, - 'inline_scripts': 0, - 'minified_scripts': 0, - 'render_blocking': 0, - 'third_party_scripts': [], - 'bundle_analysis': {} + 'total_scripts': 0, 'async_scripts': 0, 'defer_scripts': 0, 'module_scripts': 0, + 'inline_scripts': 0, 'minified_scripts': None, 'minified_filename_references': 0, + 'minification_status': 'not_measured', 'render_blocking': 0, + 'third_party_scripts': [], 'third_party_status': 'observed_references', 'bundle_analysis': {} } - - scripts = soup.find_all('script') + scripts = _script_records(soup, facts) js_analysis['total_scripts'] = len(scripts) - - for script in scripts: + base_url = facts.base_url if facts is not None else document_base_url(soup, page_url) if page_url else None + for record in scripts: + script, text = record['attrs'], record['text'] src = script.get('src', '') - if src: - # External script - if script.get('async'): + if 'async' in script: js_analysis['async_scripts'] += 1 - elif script.get('defer'): + if 'defer' in script: js_analysis['defer_scripts'] += 1 - else: - # Check if in head (render-blocking) - if script.find_parent('head'): - js_analysis['render_blocking'] += 1 - - # Check for modules + if _is_classic_javascript(script) and not is_nonblocking_script(script) and record['in_head']: + js_analysis['render_blocking'] += 1 if script.get('type') == 'module': js_analysis['module_scripts'] += 1 - - # Check for minification if '.min.js' in src or '-min.js' in src or '.prod.js' in src: - js_analysis['minified_scripts'] += 1 - - # Detect third-party scripts - third_party_patterns = [ - 'google-analytics', 'googletagmanager', 'facebook', - 'twitter', 'linkedin', 'hotjar', 'mixpanel', 'segment', - 'intercom', 'drift', 'hubspot', 'zendesk' - ] - - for pattern in third_party_patterns: - if pattern in src.lower(): - js_analysis['third_party_scripts'].append({ - 'name': pattern, - 'url': src, - 'async': bool(script.get('async')), - 'defer': bool(script.get('defer')) - }) - break + js_analysis['minified_filename_references'] += 1 + if page_url and classify_url(src, page_url, base_url) == 'external': + resolved = resolve_url(src, base_url) + js_analysis['third_party_scripts'].append({ + 'name': urlparse(resolved).hostname, 'url': resolved, + 'async': 'async' in script, 'defer': 'defer' in script + }) else: - # Inline script js_analysis['inline_scripts'] += 1 - - # Check size of inline script - if script.string: - size = len(script.string) - if size > 10000: # 10KB - if 'large_inline' not in js_analysis['bundle_analysis']: - js_analysis['bundle_analysis']['large_inline'] = [] - js_analysis['bundle_analysis']['large_inline'].append(size) - + if len(text) > 10000: + js_analysis['bundle_analysis'].setdefault('large_inline', []).append(len(text)) return js_analysis def calculate_performance_score(metrics: PerformanceMetrics, resource_count: int) -> Tuple[int, str]: - """Calculate overall performance score and grade.""" + """Score only supplied measurements; missing values incur no penalty.""" score = 100 - - # Core Web Vitals weights (40% of score) - # LCP - if metrics.largest_contentful_paint > 4.0: - score -= 15 - elif metrics.largest_contentful_paint > 2.5: - score -= 8 - - # FID - if metrics.first_input_delay > 300: - score -= 15 - elif metrics.first_input_delay > 100: - score -= 8 - - # CLS - if metrics.cumulative_layout_shift > 0.25: - score -= 10 - elif metrics.cumulative_layout_shift > 0.1: - score -= 5 - - # Other metrics (60% of score) - # Load time - if metrics.load_time > 5.0: - score -= 20 - elif metrics.load_time > 3.0: - score -= 10 - elif metrics.load_time > 2.0: - score -= 5 - - # Page weight - mb_size = metrics.total_byte_weight / (1024 * 1024) - if mb_size > 5.0: - score -= 15 - elif mb_size > 3.0: - score -= 10 - elif mb_size > 2.0: - score -= 5 - - # Resource count - if resource_count > 100: - score -= 10 - elif resource_count > 70: - score -= 5 - - # Time to Interactive - if metrics.time_to_interactive > 7.3: - score -= 10 - elif metrics.time_to_interactive > 5.2: - score -= 5 - - # Total Blocking Time - if metrics.total_blocking_time > 600: - score -= 10 - elif metrics.total_blocking_time > 300: - score -= 5 - - # Determine grade + checks = ( + (metrics.largest_contentful_paint, 4.0, 15, 2.5, 8), + (metrics.interaction_to_next_paint, 500, 15, 200, 8), + (metrics.cumulative_layout_shift, 0.25, 10, 0.1, 5), + (metrics.load_time, 5.0, 20, 3.0, 10), + (metrics.total_byte_weight, 5 * 1024 * 1024, 15, 3 * 1024 * 1024, 10), + (metrics.total_blocking_time, 600, 10, 300, 5), + ) + for value, poor, poor_penalty, moderate, moderate_penalty in checks: + if value is not None and math.isfinite(value): + if value > poor: + score -= poor_penalty + elif value > moderate: + score -= moderate_penalty score = max(0, min(100, score)) - - if score >= 90: - grade = 'A' - elif score >= 80: - grade = 'B' - elif score >= 70: - grade = 'C' - elif score >= 60: - grade = 'D' - else: - grade = 'F' - - return score, grade + return score, score_grade(score) def generate_performance_budget(metrics: PerformanceMetrics, resources: Dict) -> Dict[str, Any]: - """Generate a performance budget recommendation.""" + """Budgets remain unknown until the corresponding quantity is measured.""" budget = { 'metrics': { 'load_time': {'target': 3.0, 'current': metrics.load_time}, 'lcp': {'target': 2.5, 'current': metrics.largest_contentful_paint}, - 'fid': {'target': 100, 'current': metrics.first_input_delay}, + 'inp': {'target': 200, 'current': metrics.interaction_to_next_paint}, 'cls': {'target': 0.1, 'current': metrics.cumulative_layout_shift}, - 'tti': {'target': 5.0, 'current': metrics.time_to_interactive} + 'tti': {'target': 5.0, 'current': metrics.time_to_interactive}, }, 'resources': { - 'total_size': {'target': 2000000, 'current': metrics.total_byte_weight}, # 2MB - 'images': {'target': 1000000, 'current': 0}, # 1MB for images - 'scripts': {'target': 500000, 'current': 0}, # 500KB for JS - 'stylesheets': {'target': 200000, 'current': 0}, # 200KB for CSS - 'fonts': {'target': 300000, 'current': 0} # 300KB for fonts + 'total_size': {'target': 2000000, 'current': metrics.total_byte_weight}, + 'images': {'target': 1000000, 'current': None}, + 'scripts': {'target': 500000, 'current': None}, + 'stylesheets': {'target': 200000, 'current': None}, + 'fonts': {'target': 300000, 'current': None}, }, 'counts': { - 'total_requests': {'target': 50, 'current': resources.get('total', 0) if isinstance(resources.get('total'), int) else len(resources.get('total', []))}, - 'third_party_requests': {'target': 10, 'current': 0} - } + 'total_requests': {'target': 50, 'current': None}, + 'third_party_requests': {'target': 10, 'current': None}, + }, } - - # Calculate if budget is met - for category in budget: - for metric in budget[category]: - target = budget[category][metric]['target'] - current = budget[category][metric]['current'] - budget[category][metric]['status'] = 'pass' if current <= target else 'fail' - if current > 0: - budget[category][metric]['ratio'] = round(current / target, 2) - + for category in budget.values(): + for value in category.values(): + current = value['current'] + value['source'] = 'not_measured' if current is None else 'supplied_measurement' + value['status'] = 'unknown' if current is None else 'pass' if current <= value['target'] else 'fail' + if current is not None: + value['ratio'] = round(current / value['target'], 2) return budget -def detect_caching_strategy(soup: BeautifulSoup) -> Dict[str, Any]: - """Detect caching and CDN usage.""" - caching = { - 'has_service_worker': False, - 'uses_cdn': False, - 'cdn_providers': [], - 'cache_control_hints': [], - 'estimated_cache_hit_rate': 0 +def detect_caching_strategy(soup: BeautifulSoup, *, facts: Optional[PageFacts] = None) -> Dict[str, Any]: + """Record HTML hints without inferring cache policy or cache hit rates.""" + providers = { + 'cloudflare': ('cdnjs.cloudflare.com',), 'cloudfront': ('cloudfront.net',), + 'fastly': ('fastly.net',), 'akamai': ('akamaihd.net',), + 'jsdelivr': ('jsdelivr.net',), 'unpkg': ('unpkg.com',), } - - # Check for service worker - if soup.find('script', string=re.compile(r'serviceWorker|navigator\.serviceWorker')): - caching['has_service_worker'] = True - - # Check for CDN usage - cdn_patterns = { - 'cloudflare': ['cloudflare', 'cdnjs'], - 'cloudfront': ['cloudfront', 'amazonaws'], - 'fastly': ['fastly'], - 'akamai': ['akamai'], - 'maxcdn': ['maxcdn'], - 'jsdelivr': ['jsdelivr'], - 'unpkg': ['unpkg'], - 'staticaly': ['staticaly'] + found = set() + if facts is not None: + elements = [record['attrs'] for record in facts.link_tags + facts.scripts + facts.images] + else: + elements = soup.find_all(['link', 'script', 'img']) + for element in elements: + reference = element.get('src') or element.get('href') or '' + try: + hostname = urlparse(reference).hostname or '' + except ValueError: + continue + for provider, domains in providers.items(): + if any(hostname == domain or hostname.endswith('.' + domain) for domain in domains): + found.add(provider) + registration_hint = any(re.search(r'navigator\.serviceWorker\.register', script['text']) + for script in _script_records(soup, facts)) + return { + 'has_service_worker': None, 'service_worker_registration_reference': registration_hint, + 'uses_cdn': None, 'cdn_providers': sorted(found), 'cache_control_hints': [], + 'estimated_cache_hit_rate': None, 'status': 'unknown', 'source': 'html_references_only', } - - all_resources = soup.find_all(['link', 'script', 'img'], src=True) + \ - soup.find_all(['link', 'script', 'img'], href=True) - - for element in all_resources: - url = element.get('src', '') or element.get('href', '') - for provider, patterns in cdn_patterns.items(): - if any(pattern in url.lower() for pattern in patterns): - if provider not in caching['cdn_providers']: - caching['cdn_providers'].append(provider) - caching['uses_cdn'] = True - - # Estimate cache hit rate based on resource types - static_resources = len([e for e in all_resources - if any(ext in str(e.get('src', '') or e.get('href', '')) - for ext in ['.css', '.js', '.jpg', '.png', '.woff'])]) - - if static_resources > 0: - # Assume 70% cache hit rate for static resources with proper caching - caching['estimated_cache_hit_rate'] = 70 if caching['uses_cdn'] else 30 - - return caching -def analyze_performance(soup: BeautifulSoup, url: str, load_time: float = 0, content_length: int = 0) -> Dict[str, Any]: - """Advanced performance analysis with comprehensive metrics and optimization detection.""" - issues = [] - data = {} - - # Initialize performance metrics - metrics = PerformanceMetrics( - load_time=load_time, - total_byte_weight=content_length, - dom_size=len(soup.find_all()) - ) - - # Estimate Core Web Vitals based on available data - # LCP estimate (based on load time and content) - metrics.largest_contentful_paint = load_time * 0.8 if load_time > 0 else 2.5 - - # FID estimate (based on JavaScript complexity) - scripts = soup.find_all('script') - if len(scripts) > 15: - metrics.first_input_delay = 300 - elif len(scripts) > 8: - metrics.first_input_delay = 150 - else: - metrics.first_input_delay = 50 - - # CLS estimate (based on layout stability factors) - cls_factors = 0 - images_without_dimensions = len([img for img in soup.find_all('img') - if not (img.get('width') and img.get('height'))]) - if images_without_dimensions > 3: - cls_factors += 2 - - fonts_loaded = len(soup.find_all('link', rel='preload', as_='font')) - if fonts_loaded > 4: - cls_factors += 1 - - if not soup.find('style'): # No critical CSS - cls_factors += 1 - - metrics.cumulative_layout_shift = min(0.5, cls_factors * 0.1) - - # Estimate other metrics - metrics.time_to_interactive = load_time * 1.5 if load_time > 0 else 3.8 - metrics.first_contentful_paint = load_time * 0.3 if load_time > 0 else 1.8 - metrics.total_blocking_time = len(scripts) * 50 # Rough estimate - metrics.time_to_first_byte = load_time * 0.2 if load_time > 0 else 0.8 - - # Store basic metrics - data['metrics'] = { - 'load_time': round(metrics.load_time, 2), - 'dom_size': metrics.dom_size, - 'content_size_mb': round(content_length / (1024 * 1024), 2), - 'lcp': round(metrics.largest_contentful_paint, 2), - 'fid': round(metrics.first_input_delay), - 'cls': round(metrics.cumulative_layout_shift, 3), - 'fcp': round(metrics.first_contentful_paint, 2), - 'tti': round(metrics.time_to_interactive, 2), - 'tbt': round(metrics.total_blocking_time), - 'ttfb': round(metrics.time_to_first_byte, 2) +def analyze_performance(soup: BeautifulSoup, url: str, load_time: float = 0, + content_length: int = 0, *, facts: Optional[PageFacts] = None) -> Dict[str, Any]: + """Inspect static HTML. Browser timing and network budgets are unavailable.""" + facts = ensure_page_facts(soup, url, facts=facts) + collector = RuleCollector('performance') + metrics = PerformanceMetrics(dom_size=facts.dom_size) + fetch_time = load_time if isinstance(load_time, (int, float)) and math.isfinite(load_time) and load_time > 0 else None + html_bytes = content_length if isinstance(content_length, int) and content_length >= 0 else None + # A default zero does not establish that an HTTP response was observed. + if html_bytes == 0 and fetch_time is None: + html_bytes = None + data = { + 'score_scope': 'static_html_checks', + 'measurement_status': 'browser_not_measured', + 'measurement_source': 'html_and_optional_document_fetch', + 'metrics': { + 'load_time': None, 'html_fetch_time': fetch_time, + 'dom_size': metrics.dom_size, 'html_content_bytes': html_bytes, + 'content_size_mb': round(html_bytes / (1024 * 1024), 4) if html_bytes is not None else None, + 'lcp': None, 'inp': None, 'fid': None, 'cls': None, 'fcp': None, + 'tti': None, 'tbt': None, 'ttfb': None, + }, } - - # Analyze resources in detail - resources = defaultdict(list) + data['metric_sources'] = { + key: ('html_document' if key == 'dom_size' else + 'document_fetch' if key in ('html_fetch_time', 'html_content_bytes', 'content_size_mb') and value is not None else + 'not_measured') + for key, value in data['metrics'].items() + } + resources = {key: [] for key in ('scripts', 'stylesheets', 'images', 'fonts', 'videos')} resource_profiles = [] - - # Scripts - scripts = soup.find_all('script') + base_url = facts.base_url + + def add_resource(element, attribute, resource_type, group, in_head=False): + reference = element.get(attribute, '') + resolved = resolve_url(reference, base_url) + if not resolved: + return + resources[group].append(resolved) + resource_profiles.append(ResourceProfile( + url=resolved, type=resource_type, + is_async='async' in element if resource_type == ResourceType.SCRIPT else False, + is_deferred=('defer' in element or element.get('type') == 'module') if resource_type == ResourceType.SCRIPT else False, + is_render_blocking=(_is_classic_javascript(element) and not is_nonblocking_script(element) and in_head) if resource_type == ResourceType.SCRIPT else False, + is_lazy=element.get('loading') == 'lazy', + is_third_party=classify_url(reference, url, base_url) == 'external', + )) + + scripts, links = facts.scripts, facts.link_tags for script in scripts: - src = script.get('src', '') - if src: - profile = ResourceProfile( - url=src, - type=ResourceType.SCRIPT, - is_async=bool(script.get('async')), - is_deferred=bool(script.get('defer')), - is_render_blocking=not (script.get('async') or script.get('defer')), - is_third_party=is_third_party(src, url) - ) - profile.priority = calculate_resource_priority(profile) - resource_profiles.append(profile) - resources['scripts'].append(src) - - # Stylesheets - stylesheets = soup.find_all('link', rel='stylesheet') - for link in stylesheets: - href = link.get('href', '') - if href: - profile = ResourceProfile( - url=href, - type=ResourceType.STYLESHEET, - is_render_blocking=True, - is_third_party=is_third_party(href, url), - is_critical=(link.find_parent('head') is not None) - ) - profile.priority = calculate_resource_priority(profile) - resource_profiles.append(profile) - resources['stylesheets'].append(href) - - # Images - images = soup.find_all('img') - for img in images: - src = img.get('src', '') or img.get('data-src', '') - if src: - profile = ResourceProfile( - url=src, - type=ResourceType.IMAGE, - is_lazy=img.get('loading') == 'lazy', - is_third_party=is_third_party(src, url) - ) - # Check if above the fold (simplified check) - parent = img.find_parent(['header', 'nav', 'hero', 'banner']) - profile.is_critical = parent is not None - profile.priority = calculate_resource_priority(profile) - resource_profiles.append(profile) - resources['images'].append(src) - - # Fonts - font_links = soup.find_all('link', rel='preload', as_='font') - for link in font_links: - href = link.get('href', '') - if href: - profile = ResourceProfile( - url=href, - type=ResourceType.FONT, - is_critical=True, - is_third_party=is_third_party(href, url) - ) - profile.priority = calculate_resource_priority(profile) - resource_profiles.append(profile) - resources['fonts'].append(href) - - # Videos - videos = soup.find_all(['video', 'iframe']) - for video in videos: - if video.name == 'video': - src = video.get('src', '') - else: # iframe - src = video.get('src', '') - if not ('youtube' in src or 'vimeo' in src or 'video' in src): - continue - - if src: - profile = ResourceProfile( - url=src, - type=ResourceType.VIDEO, - is_lazy=video.get('loading') == 'lazy', - is_third_party=is_third_party(src, url) - ) - profile.priority = 'low' - resource_profiles.append(profile) - resources['videos'].append(src) - - # Calculate total resources + if 'src' in script['attrs']: + add_resource(script['attrs'], 'src', ResourceType.SCRIPT, 'scripts', script['in_head']) + for link in links: + if 'stylesheet' in link['attrs'].get('rel', []): + add_resource(link['attrs'], 'href', ResourceType.STYLESHEET, 'stylesheets') + for image in facts.images: + img = image['attrs'] + add_resource(img, 'src' if img.get('src') else 'data-src', ResourceType.IMAGE, 'images') + for link in links: + if 'preload' in link['attrs'].get('rel', []) and link['attrs'].get('as') == 'font': + add_resource(link['attrs'], 'href', ResourceType.FONT, 'fonts') + for video in soup.find_all('video'): + add_resource(video.attrs, 'src', ResourceType.VIDEO, 'videos') + for source in video.find_all('source', src=True): + add_resource(source.attrs, 'src', ResourceType.VIDEO, 'videos') resources['total'] = len(resource_profiles) data['total_resources'] = resources['total'] - - # Network metrics - network = NetworkMetrics( - total_requests=len(resource_profiles), - total_size=content_length - ) - - third_party_resources = [r for r in resource_profiles if r.is_third_party] - network.third_party_requests = len(third_party_resources) - - # Extract unique domains - for profile in resource_profiles: - try: - domain = urlparse(profile.url).netloc - if domain: - network.domains.add(domain) - except: - pass - + domains = sorted({urlparse(profile.url).netloc for profile in resource_profiles + if urlparse(profile.url).scheme in ('http', 'https')}) data['network_metrics'] = { - 'total_requests': network.total_requests, - 'third_party_requests': network.third_party_requests, - 'unique_domains': len(network.domains), - 'domains': list(network.domains)[:10] # Top 10 domains + 'total_requests': None, 'third_party_requests': None, + 'referenced_resources': len(resource_profiles), + 'third_party_references': sum(profile.is_third_party for profile in resource_profiles), + 'unique_domains': len(domains), 'domains': domains, + 'status': 'not_measured', 'source': 'html_references_only', } - - # Analyze critical rendering path - critical_path = analyze_critical_rendering_path(soup) + critical_path = analyze_critical_rendering_path(soup, facts=facts) data['critical_rendering_path'] = critical_path - - if len(critical_path['render_blocking_resources']) > 3: - issues.append(create_issue('Performance', 'critical', - f"{len(critical_path['render_blocking_resources'])} render-blocking resources found", - {'resources': critical_path['render_blocking_resources'][:5]})) - - # Detect performance patterns - patterns = detect_performance_patterns(soup) - data['performance_patterns'] = patterns - - for bad_pattern in patterns['bad_patterns']: - issues.append(create_issue('Performance', 'warning', bad_pattern)) - - # Image optimization analysis - image_analysis = analyze_image_optimization(soup) - data['image_optimization'] = image_analysis - - if image_analysis['total_images'] > 0: - if image_analysis['optimized_formats'] < image_analysis['total_images'] * 0.3: - issues.append(create_issue('Performance', 'warning', - f"Only {image_analysis['optimized_formats']}/{image_analysis['total_images']} images use modern formats (WebP/AVIF)")) - - if image_analysis['lazy_loaded'] < image_analysis['total_images'] * 0.5: - issues.append(create_issue('Performance', 'warning', - f"Only {image_analysis['lazy_loaded']}/{image_analysis['total_images']} images are lazy loaded")) - - # JavaScript optimization analysis - js_analysis = analyze_javascript_optimization(soup) - data['javascript_optimization'] = js_analysis - - if js_analysis['render_blocking'] > 2: - issues.append(create_issue('Performance', 'critical', - f"{js_analysis['render_blocking']} render-blocking scripts in head")) - - if js_analysis['third_party_scripts']: - issues.append(create_issue('Performance', 'notice', - f"{len(js_analysis['third_party_scripts'])} third-party scripts detected", - {'scripts': [s['name'] for s in js_analysis['third_party_scripts']]})) - - # Caching strategy detection - caching = detect_caching_strategy(soup) - data['caching_strategy'] = caching - - if not caching['has_service_worker']: - issues.append(create_issue('Performance', 'notice', - 'No service worker detected for offline support and caching')) - - if not caching['uses_cdn']: - issues.append(create_issue('Performance', 'warning', - 'Not using CDN for static assets delivery')) - - # Generate performance budget - budget = generate_performance_budget(metrics, resources) - data['performance_budget'] = budget - - # Count budget violations - budget_violations = 0 - for category in budget: - for metric in budget[category]: - if budget[category][metric].get('status') == 'fail': - budget_violations += 1 - - if budget_violations > 3: - issues.append(create_issue('Performance', 'warning', - f'{budget_violations} performance budget violations detected')) - - # Resource priorities - high_priority = [r for r in resource_profiles if calculate_resource_priority(r) == 'high'] - data['high_priority_resources'] = len(high_priority) - - # Check for resource hints - preconnect = soup.find_all('link', rel='preconnect') - dns_prefetch = soup.find_all('link', rel='dns-prefetch') - preload = soup.find_all('link', rel='preload') - prefetch = soup.find_all('link', rel='prefetch') - + data['performance_patterns'] = detect_performance_patterns(soup, facts=facts) + data['image_optimization'] = analyze_image_optimization(soup, facts=facts) + collector.results.extend(data['performance_patterns']['rule_results']) + collector.results.extend(data['image_optimization']['rule_results']) + javascript = analyze_javascript_optimization(soup, url, facts=facts) + data['javascript_optimization'] = javascript + blocking = [resource['url'] for resource in critical_path['render_blocking_resources'] if resource['type'] == 'script'] + collector.check('performance.blocking_scripts', bool(blocking), + evidence={'urls': blocking, 'count': len(blocking), 'browser_timing_measured': False}, + applicable=any('src' in script['attrs'] for script in scripts), reason='Requires external script elements.', + message=f'{len(blocking)} external classic scripts in head lack async or defer', category='Performance') + issues = collector.issues + data['caching_strategy'] = detect_caching_strategy(soup, facts=facts) + data['performance_budget'] = generate_performance_budget(metrics, resources) + data['high_priority_resources'] = None + data['priority_status'] = 'requires_browser_trace' data['resource_hints'] = { - 'preconnect': len(preconnect), - 'dns_prefetch': len(dns_prefetch), - 'preload': len(preload), - 'prefetch': len(prefetch) + name.replace('-', '_'): sum(name in link['attrs'].get('rel', []) for link in links) + for name in ('preconnect', 'dns-prefetch', 'preload', 'prefetch') } - - if len(preconnect) == 0 and network.third_party_requests > 5: - issues.append(create_issue('Performance', 'warning', - f'No preconnect hints but {network.third_party_requests} third-party requests')) - - # Optimization opportunities - opportunities = [] - - # Image optimization - if image_analysis['savings_potential_kb'] > 100: - opportunities.append(OptimizationOpportunity( - title="Optimize images", - impact="high" if image_analysis['savings_potential_kb'] > 500 else "medium", - category="images", - estimated_savings_bytes=image_analysis['savings_potential_kb'] * 1024, - description=f"Convert {image_analysis['total_images'] - image_analysis['optimized_formats']} images to WebP/AVIF", - implementation="Use image CDN or build process to automatically convert images" - )) - - # JavaScript optimization - if js_analysis['render_blocking'] > 0: - opportunities.append(OptimizationOpportunity( - title="Eliminate render-blocking scripts", - impact="high", - category="javascript", - estimated_savings_ms=js_analysis['render_blocking'] * 100, - description=f"Make {js_analysis['render_blocking']} scripts non-blocking", - implementation="Add async or defer attributes, or move scripts to bottom of body" - )) - - # Bundle size - if len(resources['scripts']) > 10: - opportunities.append(OptimizationOpportunity( - title="Reduce JavaScript bundles", - impact="medium", - category="javascript", - description=f"Consolidate {len(resources['scripts'])} script files", - implementation="Use webpack or rollup to bundle and tree-shake JavaScript" - )) - - # Critical CSS - if len(resources['stylesheets']) > 3 and not soup.find('style'): - opportunities.append(OptimizationOpportunity( - title="Extract critical CSS", - impact="high", - category="css", - estimated_savings_ms=200, - description="Inline critical CSS and defer non-critical styles", - implementation="Use critical CSS tools to extract above-the-fold styles" - )) - data['optimization_opportunities'] = [ { - 'title': o.title, - 'impact': o.impact, - 'category': o.category, - 'savings_ms': o.estimated_savings_ms, - 'savings_kb': round(o.estimated_savings_bytes / 1024), - 'description': o.description, - 'implementation': o.implementation + 'title': issue['title'], 'impact': 'requires_measurement', + 'rule_id': issue['rule_id'], 'category': 'performance', 'savings_ms': None, 'savings_kb': None, + 'status': 'unmeasured', 'source': 'html_attributes', + 'description': issue['message'], 'implementation': issue['fix'], } - for o in opportunities + for issue in issues ] - - # Calculate final score and grade - score, grade = calculate_performance_score(metrics, resources['total']) - - # Additional score adjustments based on issues - for issue in issues: - if issue['severity'] == 'critical': - score -= 10 - elif issue['severity'] == 'warning': - score -= 5 - elif issue['severity'] == 'notice': - score -= 2 - - score = max(0, min(100, score)) - - # Performance level classification - if metrics.load_time <= 1.0: - performance_level = PerformanceLevel.FAST - elif metrics.load_time <= 3.0: - performance_level = PerformanceLevel.MODERATE - elif metrics.load_time <= 5.0: - performance_level = PerformanceLevel.SLOW - else: - performance_level = PerformanceLevel.CRITICAL - - data['performance_level'] = performance_level.value + score = score_findings(issues) + grade = score_grade(score) + data['performance_level'] = None data['grade'] = grade - - # Summary recommendations - recommendations = [] - - if grade in ['D', 'F']: - recommendations.append("Critical performance issues detected. Prioritize render-blocking resource elimination.") - - if metrics.largest_contentful_paint > 2.5: - recommendations.append("Improve LCP: Optimize server response time, use CDN, preload critical resources.") - - if metrics.cumulative_layout_shift > 0.1: - recommendations.append("Reduce CLS: Add size attributes to images/videos, avoid inserting content above existing content.") - - if metrics.first_input_delay > 100: - recommendations.append("Improve FID: Break up long tasks, optimize JavaScript execution, use web workers.") - - if network.third_party_requests > 10: - recommendations.append("Reduce third-party impact: Lazy load third-party scripts, use facades for embeds.") - - if not caching['uses_cdn']: - recommendations.append("Implement CDN for global content delivery and improved caching.") - - data['recommendations'] = recommendations - + data['recommendations'] = recommendations_for(issues) return { - 'score': score, - 'grade': grade, - 'issues': issues, - 'data': data, - 'resources': dict(resources) - } \ No newline at end of file + 'score': score, 'grade': grade, 'issues': issues, 'data': data, + 'resources': resources, 'recommendations': data['recommendations'], + 'rule_results': collector.results, 'rule_coverage': collector.coverage, + } diff --git a/tfq0seo/analyzers/seo.py b/tfq0seo/analyzers/seo.py index 335dacb..0b474ee 100644 --- a/tfq0seo/analyzers/seo.py +++ b/tfq0seo/analyzers/seo.py @@ -10,14 +10,100 @@ from enum import Enum from datetime import datetime from bs4 import BeautifulSoup, Tag +from .common import classify_url, document_base_url, header_values, heading_facts, make_issue, parse_robots, resolve_url +from ..page_facts import PageFacts, ensure_page_facts +from ..rules import RuleDefinition, RuleCollector, register_rules, score_findings, recommendations_for + + +_SEARCH_DOCS = 'https://developers.google.com/search/docs/' +_TITLE_REFERENCE = _SEARCH_DOCS + 'appearance/title-link' +_SNIPPET_REFERENCE = _SEARCH_DOCS + 'appearance/snippet' +_CANONICAL_REFERENCE = _SEARCH_DOCS + 'crawling-indexing/consolidate-duplicate-urls' +_JSONLD_REFERENCE = 'https://www.w3.org/TR/json-ld11/' +_ENCODING_REFERENCE = 'https://html.spec.whatwg.org/multipage/semantics.html#charset' +_REVIEWED_ON = '2026-09-14' + +# References were reviewed on the recorded date. These are bounded HTML checks, +# not a prediction of rankings, search appearance, or complete standards conformance. +SEO_RULES = ( + RuleDefinition('seo.title_missing', 'seo', 'warning', + 'Provide a descriptive title that identifies the subject of this page.', + 'HTML documents intended to have a descriptive page title.', + (_TITLE_REFERENCE,), _REVIEWED_ON), + RuleDefinition('seo.title_repetition', 'seo', 'notice', + 'Review repeated title words in context; keep necessary names and natural phrasing.', + 'A whitespace-delimited title repeats a word; repetition alone does not establish keyword stuffing.', + (_TITLE_REFERENCE,), _REVIEWED_ON, scored=False), + RuleDefinition('seo.description_missing', 'seo', 'notice', + 'For pages you want to promote in search, consider a relevant summary in the meta description; snippets may use page content.', + 'A meta description is optional; its usefulness depends on the page and search intent.', + (_SNIPPET_REFERENCE,), _REVIEWED_ON, scored=False), + RuleDefinition('seo.meta_keywords', 'seo', 'notice', + 'Do not rely on meta keywords for Google Search; keep them only if another consumer needs them.', + 'An observed meta keywords tag; other consumers are not assessed.', + (_SEARCH_DOCS + 'crawling-indexing/special-tags',), _REVIEWED_ON, scored=False), + RuleDefinition('seo.canonical_preference', 'seo', 'notice', + 'If duplicate or similar URLs exist, choose a consistent canonical preference using supported signals.', + 'A canonical preference is optional and requires knowledge of duplicate or similar pages.', + (_CANONICAL_REFERENCE,), _REVIEWED_ON, scored=False), + RuleDefinition('seo.canonical_invalid', 'seo', 'warning', + 'Correct the declared canonical href so it resolves to the intended HTTP or HTTPS URL.', + 'An HTML canonical link is declared; HTTP Link headers and destination content are assessed separately.', + (_CANONICAL_REFERENCE,), _REVIEWED_ON), + RuleDefinition('seo.og_incomplete', 'seo', 'notice', + 'Complete the Open Graph object with og:title, og:type, og:image, and og:url when Open Graph sharing is intended.', + 'The page already declares at least one Open Graph property.', + ('https://ogp.me/',), _REVIEWED_ON, scored=False), + RuleDefinition('seo.og_image_dimensions', 'seo', 'notice', + 'Consider describing the Open Graph image dimensions for consumers that use them; these properties are optional.', + 'An Open Graph image is declared; its dimensions have not been fetched.', + ('https://ogp.me/',), _REVIEWED_ON, scored=False), + RuleDefinition('seo.jsonld_syntax', 'seo', 'warning', + 'Correct the recorded JSON syntax error in the JSON-LD script.', + 'Scripts explicitly declared as application/ld+json; only JSON syntax is checked here.', + (_JSONLD_REFERENCE,), _REVIEWED_ON), + RuleDefinition('seo.jsonld_shape', 'seo', 'warning', + 'Correct the recorded JSON-LD node, graph, or @type shape and validate with a JSON-LD processor.', + 'Locally inspected JSON-LD structures; remote contexts, keyword aliases, and vocabulary rules are not expanded.', + (_JSONLD_REFERENCE,), _REVIEWED_ON), + RuleDefinition('seo.jsonld_empty', 'seo', 'notice', + 'Review the empty JSON-LD script if it was intended to describe an entity.', + 'A valid JSON-LD script contains no locally extractable nodes; empty graphs are not syntax failures.', + (_JSONLD_REFERENCE,), _REVIEWED_ON, scored=False), + RuleDefinition('seo.jsonld_eligibility', 'seo', 'notice', + 'Check the relevant search feature documentation and validation tools if enhanced search appearance is intended.', + 'Search feature eligibility needs page purpose, content, vocabulary-specific requirements, and search-engine validation.', + (_SEARCH_DOCS + 'appearance/structured-data/sd-policies',), _REVIEWED_ON, scored=False), + RuleDefinition('seo.language_format', 'seo', 'notice', + 'Use a BCP 47 language tag for the document language; validate the complete tag against the language subtag registry.', + 'A nonempty lang attribute; this check catches only obviously malformed separators and characters.', + ('https://www.w3.org/International/articles/language-tags/',), _REVIEWED_ON), + RuleDefinition('seo.viewport_width', 'seo', 'notice', + 'Review the viewport configuration and test the actual layout on narrow screens.', + 'A viewport declaration is present; absence of device-width alone does not prove an unusable layout.', + ('https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/meta/name/viewport',), _REVIEWED_ON, scored=False), + RuleDefinition('seo.charset_missing', 'seo', 'notice', + 'Verify that the response or document declares its character encoding, accounting for any byte-order mark.', + 'Parsed HTML and optional response headers; original bytes and byte-order marks may be unavailable.', + (_ENCODING_REFERENCE,), _REVIEWED_ON, scored=False), + RuleDefinition('seo.charset_non_utf8', 'seo', 'notice', + 'Use UTF-8 consistently in the document bytes and declaration when updating the encoding.', + 'An encoding is explicitly declared; the actual original byte encoding is not verified.', + (_ENCODING_REFERENCE,), _REVIEWED_ON, scored=False), + RuleDefinition('seo.favicon_missing', 'seo', 'notice', + 'If a Google Search favicon is desired, declare an appropriate icon on the site homepage and verify crawl access.', + 'Homepage HTML only; a default favicon or other platform-specific icon may still exist.', + (_SEARCH_DOCS + 'appearance/favicon-in-search',), _REVIEWED_ON, scored=False), +) +register_rules(SEO_RULES) class SEOPriority(Enum): - """SEO priority levels for issues.""" - CRITICAL = "critical" # Will prevent indexing or ranking - HIGH = "high" # Significant ranking impact - MEDIUM = "medium" # Moderate ranking impact - LOW = "low" # Minor optimization opportunity + """Legacy presentation priorities; these do not predict ranking impact.""" + CRITICAL = "critical" + HIGH = "high" + MEDIUM = "medium" + LOW = "low" class SchemaType(Enum): @@ -79,7 +165,7 @@ class StructuredDataItem: properties: Dict[str, Any] is_valid: bool = True validation_errors: List[str] = field(default_factory=list) - rich_snippet_eligible: bool = False + rich_snippet_eligible: Optional[bool] = None snippet_type: Optional[RichSnippetType] = None @@ -108,40 +194,17 @@ class SERPPreview: description_pixels: int = 0 breadcrumbs: Optional[str] = None rich_snippets: List[str] = field(default_factory=list) - sitelinks_eligible: bool = False + sitelinks_eligible: Optional[bool] = None -def create_issue(category: str, severity: str, message: str, details: Optional[Dict] = None) -> Dict[str, Any]: - """Create an enhanced SEO issue with recommendations.""" - issue = { - 'category': category, - 'severity': severity, - 'message': message - } - if details: - issue['details'] = details - - # Add specific SEO recommendations - if 'title' in message.lower(): - issue['fix'] = "Optimize title: Include primary keyword, keep under 60 chars, make unique and compelling" - issue['impact'] = "High - Title tags are a primary ranking factor" - elif 'description' in message.lower(): - issue['fix'] = "Write compelling meta description: 150-160 chars, include keywords, add call-to-action" - issue['impact'] = "Medium - Affects click-through rate from search results" - elif 'structured data' in message.lower() or 'schema' in message.lower(): - issue['fix'] = "Implement Schema.org markup for rich snippets and better SERP visibility" - issue['impact'] = "High - Enables rich snippets and improves click-through rates" - elif 'canonical' in message.lower(): - issue['fix'] = "Add canonical URL to prevent duplicate content issues" - issue['impact'] = "High - Prevents duplicate content penalties" - elif 'h1' in message.lower() or 'heading' in message.lower(): - issue['fix'] = "Use single H1 with primary keyword, follow proper heading hierarchy" - issue['impact'] = "High - H1 tags signal main topic to search engines" - else: - issue['fix'] = "Review SEO best practices for this element" - issue['impact'] = "Varies based on implementation" - - return issue +def create_issue(category: str, severity: str, message: str, details: Optional[Dict] = None, + rule_id: Optional[str] = None, evidence: Any = None, + confidence: str = 'high') -> Dict[str, Any]: + """Compatibility wrapper; findings require an explicit registered rule.""" + if not rule_id or evidence is None: + raise ValueError('SEO findings require a registered rule_id and observed evidence') + return make_issue(category, severity, message, details, rule_id, evidence, + confidence=confidence) def calculate_text_pixel_width(text: str, font_size: int = 16) -> int: @@ -167,339 +230,124 @@ def calculate_text_pixel_width(text: str, font_size: int = 16) -> int: return total_width -def extract_meta_tags(soup: BeautifulSoup) -> MetaTagProfile: - """Extract comprehensive meta tag information.""" +def extract_meta_tags(soup: BeautifulSoup, *, facts: Optional[PageFacts] = None) -> MetaTagProfile: + """Build the legacy metadata profile from shared declaration records.""" profile = MetaTagProfile() - - # Basic meta tags - title_tag = soup.find('title') - if title_tag: - profile.title = title_tag.text.strip() - - # Standard meta tags - meta_mappings = { - 'description': 'description', - 'keywords': 'keywords', - 'author': 'author', - 'robots': 'robots', - 'googlebot': 'googlebot', - 'viewport': 'viewport' - } - - for name, attr in meta_mappings.items(): - tag = soup.find('meta', attrs={'name': name}) - if tag and tag.get('content'): - setattr(profile, attr, tag.get('content').strip()) - - # Charset - charset_tag = soup.find('meta', charset=True) - if charset_tag: - profile.charset = charset_tag.get('charset') - else: - charset_tag = soup.find('meta', attrs={'http-equiv': 'Content-Type'}) - if charset_tag: - content = charset_tag.get('content', '') - if 'charset=' in content: - profile.charset = content.split('charset=')[-1].strip() - - # Canonical URL - canonical = soup.find('link', attrs={'rel': 'canonical'}) - if canonical: - profile.canonical = canonical.get('href') - - # Alternate languages (hreflang) - for link in soup.find_all('link', attrs={'rel': 'alternate', 'hreflang': True}): - lang = link.get('hreflang') - href = link.get('href') - if lang and href: - profile.alternate_languages[lang] = href - - # Open Graph tags - for tag in soup.find_all('meta', property=re.compile('^og:')): - prop = tag.get('property') - content = tag.get('content') - if prop and content: - profile.og_tags[prop] = content - - # Twitter Card tags - for tag in soup.find_all('meta', attrs={'name': re.compile('^twitter:')}): - name = tag.get('name') - content = tag.get('content') - if name and content: - profile.twitter_tags[name] = content - - # Article meta tags - for tag in soup.find_all('meta', property=re.compile('^article:')): - prop = tag.get('property') - content = tag.get('content') - if prop and content: - profile.article_tags[prop] = content - - # Dublin Core metadata - for tag in soup.find_all('meta', attrs={'name': re.compile(r'^dc\.')}): - name = tag.get('name') - content = tag.get('content') - if name and content: - profile.dublin_core[name] = content - - # Custom meta tags - for tag in soup.find_all('meta'): - name = tag.get('name', '') - property = tag.get('property', '') - content = tag.get('content', '') - - # Skip already processed tags - if (name and not any(name.startswith(p) for p in ['description', 'keywords', 'author', 'robots', 'viewport', 'twitter', 'dc.']) - and content): - profile.custom_meta[name] = content - elif (property and not property.startswith(('og:', 'article:')) and content): - profile.custom_meta[property] = content - + title_tag = soup.find('title') if facts is None else None + profile.title = facts.title if facts is not None else title_tag.get_text().strip() if title_tag else None + metas = facts.meta if facts is not None else [{'attrs': tag.attrs} for tag in soup.find_all('meta')] + links = facts.link_tags if facts is not None else [{'attrs': tag.attrs} for tag in soup.find_all('link')] + mappings = {'description': 'description', 'keywords': 'keywords', 'author': 'author', + 'robots': 'robots', 'googlebot': 'googlebot', 'viewport': 'viewport'} + seen = set() + for record in metas: + attrs = record['attrs'] + name = str(attrs.get('name', '')) + key = name.casefold() + prop = str(attrs.get('property', '')) + content = str(attrs.get('content') or '').strip() + if key in mappings and key not in seen: + seen.add(key) + if content: + setattr(profile, mappings[key], content) + if 'charset' in attrs and profile.charset is None: + profile.charset = attrs['charset'] + if content: + if prop.startswith('og:'): + profile.og_tags[prop] = content + elif prop.startswith('article:'): + profile.article_tags[prop] = content + elif prop: + profile.custom_meta[prop] = content + if name.startswith('twitter:'): + profile.twitter_tags[name] = content + elif name.startswith('dc.'): + profile.dublin_core[name] = content + elif name and not any(name.startswith(prefix) for prefix in + ('description', 'keywords', 'author', 'robots', 'viewport', 'twitter', 'dc.')): + profile.custom_meta[name] = content + if profile.charset is None: + for record in metas: + attrs = record['attrs'] + if str(attrs.get('http-equiv', '')).casefold() == 'content-type': + match = re.search(r"charset\s*=\s*[\"']?([^;\s\"']+)", str(attrs.get('content', '')), re.I) + if match: + profile.charset = match.group(1) + break + canonical_seen = False + for record in links: + attrs = record['attrs'] + rel = attrs.get('rel', []) + rel = rel if isinstance(rel, list) else str(rel).split() + if 'canonical' in rel and not canonical_seen: + profile.canonical = attrs.get('href') + canonical_seen = True + if 'alternate' in rel and attrs.get('hreflang') and attrs.get('href'): + profile.alternate_languages[attrs['hreflang']] = attrs['href'] return profile def validate_structured_data(data: Dict[str, Any]) -> StructuredDataItem: - """Validate structured data against Schema.org requirements.""" - item = StructuredDataItem( - type=data.get('@type', 'Unknown'), - properties=data - ) - - # Basic validation - if '@context' not in data: - item.validation_errors.append("Missing @context") - item.is_valid = False - - if '@type' not in data: - item.validation_errors.append("Missing @type") + """Check the local @type shape without inventing required schema properties. + + A context or type need not occur on every node. Context expansion, vocabulary + validation, and search feature requirements require a separate validator. + """ + raw_type = data.get('@type') + types = raw_type if isinstance(raw_type, list) else [raw_type] + schema_types = [value for value in types if isinstance(value, str)] + item = StructuredDataItem(type=schema_types[0] if schema_types else 'Unknown', properties=data) + if '@type' in data and (not isinstance(raw_type, (str, list)) + or any(not isinstance(value, str) for value in types)): + item.validation_errors.append('@type must be a string or an array of strings') item.is_valid = False - - # Type-specific validation - schema_type = data.get('@type', '') - - # Product validation - if schema_type == 'Product': - required = ['name', 'image'] - recommended = ['description', 'sku', 'offers', 'aggregateRating', 'review'] - - for field in required: - if field not in data: - item.validation_errors.append(f"Product missing required field: {field}") - item.is_valid = False - - if 'offers' in data: - offer = data['offers'] if isinstance(data['offers'], dict) else data['offers'][0] - offer_required = ['priceCurrency', 'price'] - for field in offer_required: - if field not in offer: - item.validation_errors.append(f"Product offer missing: {field}") - - if 'aggregateRating' in data or 'review' in data: - item.rich_snippet_eligible = True - item.snippet_type = RichSnippetType.PRODUCT - - # Article validation - elif schema_type in ['Article', 'NewsArticle', 'BlogPosting']: - required = ['headline', 'datePublished', 'author'] - recommended = ['image', 'dateModified', 'publisher'] - - for field in required: - if field not in data: - item.validation_errors.append(f"Article missing required field: {field}") - item.is_valid = False - - item.rich_snippet_eligible = True - item.snippet_type = RichSnippetType.ARTICLE - - # Organization validation - elif schema_type == 'Organization': - required = ['name', 'url'] - recommended = ['logo', 'sameAs', 'contactPoint'] - - for field in required: - if field not in data: - item.validation_errors.append(f"Organization missing required field: {field}") - item.is_valid = False - - # LocalBusiness validation - elif 'LocalBusiness' in schema_type: - required = ['name', 'address'] - recommended = ['telephone', 'openingHours', 'geo', 'review'] - - for field in required: - if field not in data: - item.validation_errors.append(f"LocalBusiness missing required field: {field}") - item.is_valid = False - - if 'address' in data: - address_required = ['streetAddress', 'addressLocality', 'addressRegion', 'postalCode'] - address = data['address'] if isinstance(data['address'], dict) else {} - for field in address_required: - if field not in address: - item.validation_errors.append(f"Address missing: {field}") - - # FAQ validation - elif schema_type == 'FAQPage': - if 'mainEntity' not in data: - item.validation_errors.append("FAQPage missing mainEntity") - item.is_valid = False - else: - item.rich_snippet_eligible = True - item.snippet_type = RichSnippetType.FAQ - - # Recipe validation - elif schema_type == 'Recipe': - required = ['name', 'image', 'recipeIngredient', 'recipeInstructions'] - recommended = ['prepTime', 'cookTime', 'totalTime', 'recipeYield', 'nutrition', 'aggregateRating'] - - for field in required: - if field not in data: - item.validation_errors.append(f"Recipe missing required field: {field}") - item.is_valid = False - - if all(field in data for field in required): - item.rich_snippet_eligible = True - item.snippet_type = RichSnippetType.RECIPE - - # Event validation - elif schema_type == 'Event': - required = ['name', 'startDate', 'location'] - - for field in required: - if field not in data: - item.validation_errors.append(f"Event missing required field: {field}") - item.is_valid = False - - if all(field in data for field in required): - item.rich_snippet_eligible = True - item.snippet_type = RichSnippetType.EVENT - - # BreadcrumbList validation - elif schema_type == 'BreadcrumbList': - if 'itemListElement' not in data: - item.validation_errors.append("BreadcrumbList missing itemListElement") - item.is_valid = False - else: - item.rich_snippet_eligible = True - item.snippet_type = RichSnippetType.BREADCRUMBS - - # VideoObject validation - elif schema_type == 'VideoObject': - required = ['name', 'description', 'thumbnailUrl', 'uploadDate'] - - for field in required: - if field not in data: - item.validation_errors.append(f"VideoObject missing required field: {field}") - item.is_valid = False - - if all(field in data for field in required): - item.rich_snippet_eligible = True - item.snippet_type = RichSnippetType.VIDEO - return item -def analyze_heading_structure(soup: BeautifulSoup) -> Dict[str, Any]: - """Analyze heading hierarchy and structure.""" - headings = { - 'h1': [], 'h2': [], 'h3': [], 'h4': [], 'h5': [], 'h6': [] - } - - issues = [] - hierarchy_valid = True - - # Extract all headings - for level in range(1, 7): - tag_name = f'h{level}' - for heading in soup.find_all(tag_name): - text = heading.get_text(strip=True) - if text: - headings[tag_name].append({ - 'text': text, - 'length': len(text), - 'has_keywords': False # Would need keyword list to check - }) - - # Check H1 - if len(headings['h1']) == 0: - issues.append("No H1 tag found") - hierarchy_valid = False - elif len(headings['h1']) > 1: - issues.append(f"Multiple H1 tags found ({len(headings['h1'])})") - hierarchy_valid = False - - # Check hierarchy - prev_level = 0 - for level in range(1, 7): - tag_name = f'h{level}' - if headings[tag_name]: - if prev_level == 0: - prev_level = level - elif level > prev_level + 1: - issues.append(f"Heading hierarchy broken: H{prev_level} followed by H{level}") - hierarchy_valid = False - prev_level = level - - # Calculate metrics - total_headings = sum(len(h) for h in headings.values()) - avg_length = 0 - if total_headings > 0: - all_lengths = [h['length'] for heading_list in headings.values() for h in heading_list] - avg_length = sum(all_lengths) / len(all_lengths) - - return { - 'headings': headings, - 'total_count': total_headings, - 'hierarchy_valid': hierarchy_valid, - 'average_length': round(avg_length, 1), - 'issues': issues - } +def iter_structured_data(data: Any, context: Any = None): + """Yield nodes from top-level arrays/graphs, retaining inherited context.""" + if isinstance(data, list): + for node in data: + yield from iter_structured_data(node, context) + elif isinstance(data, dict): + local_context = data.get('@context', context) + if '@type' in data or '@graph' not in data: + node = dict(data) + if '@context' not in node and local_context is not None: + node['@context'] = local_context + yield node + if '@graph' in data: + graph = data['@graph'] + if not isinstance(graph, (dict, list)): + raise ValueError('@graph must contain a node object or array') + yield from iter_structured_data(graph, local_context) + else: + raise ValueError('JSON-LD must contain node objects or arrays') -def analyze_internal_linking_seo(soup: BeautifulSoup, url: str) -> Dict[str, Any]: - """Analyze internal linking from SEO perspective.""" - internal_links = [] - external_links = [] - - # Parse base URL - base_domain = urlparse(url).netloc - - for link in soup.find_all('a', href=True): - href = link.get('href', '') - text = link.get_text(strip=True) - - # Skip empty or anchor-only links - if not href or href.startswith('#'): +def analyze_heading_structure(soup: BeautifulSoup, *, facts: Optional[PageFacts] = None) -> Dict[str, Any]: + """Return shared heading facts in document order.""" + return facts.headings if facts is not None else heading_facts(soup) + + +def analyze_internal_linking_seo(soup: BeautifulSoup, url: str, *, facts: Optional[PageFacts] = None) -> Dict[str, Any]: + """Describe link counts using the shared URL classification and anchor records.""" + page_facts = ensure_page_facts(soup, url, facts=facts) + internal_links, external_links = [], [] + for record in page_facts.anchors: + kind = record['url_kind'] + if kind not in ('internal', 'external'): continue - - # Determine if internal - is_internal = True - if href.startswith(('http://', 'https://')): - link_domain = urlparse(href).netloc - is_internal = link_domain == base_domain or link_domain.endswith('.' + base_domain) - - link_data = { - 'url': href, - 'anchor_text': text, - 'is_follow': 'nofollow' not in (link.get('rel', []) if isinstance(link.get('rel'), list) else [link.get('rel', '')]) - } - - if is_internal: - internal_links.append(link_data) - else: - external_links.append(link_data) - - # Analyze anchor text diversity - internal_anchors = [l['anchor_text'].lower() for l in internal_links if l['anchor_text']] - anchor_diversity = len(set(internal_anchors)) / max(1, len(internal_anchors)) - - return { - 'internal_count': len(internal_links), - 'external_count': len(external_links), - 'follow_ratio': sum(1 for l in external_links if l['is_follow']) / max(1, len(external_links)), - 'anchor_diversity': round(anchor_diversity, 2), - 'top_anchors': Counter(internal_anchors).most_common(5) - } + rel = record['attrs'].get('rel', []) + rel = rel if isinstance(rel, list) else str(rel).split() + link_data = {'url': record['url'], 'anchor_text': record['text_compact'], + 'is_follow': 'nofollow' not in [str(value).casefold() for value in rel]} + (internal_links if kind == 'internal' else external_links).append(link_data) + anchors = [link['anchor_text'].lower() for link in internal_links if link['anchor_text']] + return {'internal_count': len(internal_links), 'external_count': len(external_links), + 'follow_ratio': sum(link['is_follow'] for link in external_links) / max(1, len(external_links)), + 'anchor_diversity': round(len(set(anchors)) / max(1, len(anchors)), 2), + 'top_anchors': [list(item) for item in Counter(anchors).most_common(5)]} def generate_serp_preview(meta_profile: MetaTagProfile, url: str) -> SERPPreview: @@ -549,550 +397,245 @@ def generate_serp_preview(meta_profile: MetaTagProfile, url: str) -> SERPPreview breadcrumbs=breadcrumbs ) - # Check sitelinks eligibility (simplified) - if meta_profile.og_tags and 'og:site_name' in meta_profile.og_tags: - preview.sitelinks_eligible = True - return preview def detect_seo_opportunities(soup: BeautifulSoup, meta_profile: MetaTagProfile, structured_data: List[StructuredDataItem]) -> List[Dict[str, Any]]: - """Detect SEO optimization opportunities.""" - opportunities = [] - - # Rich snippet opportunities - rich_snippet_types = [item.snippet_type for item in structured_data if item.rich_snippet_eligible] - - potential_snippets = { - RichSnippetType.FAQ: "FAQ rich snippets can increase CTR by 50%+", - RichSnippetType.HOW_TO: "How-To rich snippets provide step-by-step visibility", - RichSnippetType.RECIPE: "Recipe cards get prominent SERP placement", - RichSnippetType.PRODUCT: "Product rich snippets show price and ratings", - RichSnippetType.REVIEW: "Review stars increase CTR significantly", - RichSnippetType.VIDEO: "Video thumbnails attract more clicks" - } - - for snippet_type, benefit in potential_snippets.items(): - if snippet_type not in rich_snippet_types: - # Check if content suggests this type could be implemented - content = soup.get_text().lower() - - if snippet_type == RichSnippetType.FAQ and ('frequently asked' in content or 'faq' in content): - opportunities.append({ - 'type': 'rich_snippet', - 'opportunity': f"Add FAQ structured data", - 'benefit': benefit, - 'priority': 'high' - }) - elif snippet_type == RichSnippetType.HOW_TO and ('how to' in content or 'step' in content): - opportunities.append({ - 'type': 'rich_snippet', - 'opportunity': f"Add How-To structured data", - 'benefit': benefit, - 'priority': 'medium' - }) - elif snippet_type == RichSnippetType.PRODUCT and ('price' in content or '$' in content): - opportunities.append({ - 'type': 'rich_snippet', - 'opportunity': f"Add Product structured data", - 'benefit': benefit, - 'priority': 'high' - }) - - # Featured snippet opportunities - # Check for definition-style content - if soup.find(string=re.compile(r'(what is|definition of|meaning of)', re.I)): - opportunities.append({ - 'type': 'featured_snippet', - 'opportunity': "Optimize for definition featured snippet", - 'benefit': "Position 0 placement above organic results", - 'priority': 'high' - }) - - # Check for list content - if len(soup.find_all(['ul', 'ol'])) > 2: - opportunities.append({ - 'type': 'featured_snippet', - 'opportunity': "Optimize for list featured snippet", - 'benefit': "Prominent list display in search results", - 'priority': 'medium' - }) - - # Check for table content - if soup.find('table'): - opportunities.append({ - 'type': 'featured_snippet', - 'opportunity': "Optimize for table featured snippet", - 'benefit': "Table display directly in SERP", - 'priority': 'medium' - }) - - # International SEO opportunities - if not meta_profile.alternate_languages: - opportunities.append({ - 'type': 'international', - 'opportunity': "Add hreflang tags for international targeting", - 'benefit': "Serve correct language version to users", - 'priority': 'high' if 'lang' not in str(soup.find('html')) else 'low' - }) - - # E-commerce opportunities - if 'add to cart' in soup.get_text().lower() or 'buy now' in soup.get_text().lower(): - if not any(item.type == 'Product' for item in structured_data): - opportunities.append({ - 'type': 'ecommerce', - 'opportunity': "Add Product schema for e-commerce pages", - 'benefit': "Show price, availability, and ratings in SERP", - 'priority': 'critical' - }) - - # Local SEO opportunities - if any(word in soup.get_text().lower() for word in ['address', 'location', 'hours', 'directions']): - if not any('LocalBusiness' in item.type for item in structured_data): - opportunities.append({ - 'type': 'local', - 'opportunity': "Add LocalBusiness schema", - 'benefit': "Appear in local pack and maps", - 'priority': 'high' - }) - - return opportunities + """Return no content-type guesses from language-dependent keyword matches.""" + return [] def calculate_seo_scores(issues: List[Dict], data: Dict[str, Any]) -> SEOScore: - """Calculate detailed SEO scores by category.""" + """Retain score dimensions while using the shared, deduplicated rule policy.""" scores = SEOScore() - - # Calculate individual category scores - for issue in issues: - penalty = 0 - if issue['severity'] == 'critical': - penalty = 20 - elif issue['severity'] == 'warning': - penalty = 10 - elif issue['severity'] == 'notice': - penalty = 5 - - # Categorize and apply penalties - if 'meta' in issue['category'].lower() or 'title' in issue['message'].lower() or 'description' in issue['message'].lower(): - scores.meta_tags -= penalty - elif 'structured' in issue['message'].lower() or 'schema' in issue['message'].lower(): - scores.structured_data -= penalty - elif 'mobile' in issue['message'].lower() or 'viewport' in issue['message'].lower(): - scores.mobile -= penalty - elif 'social' in issue['message'].lower() or 'open graph' in issue['message'].lower() or 'twitter' in issue['message'].lower(): - scores.social -= penalty - elif 'heading' in issue['message'].lower() or 'h1' in issue['message'].lower(): - scores.content -= penalty - elif 'lang' in issue['message'].lower() or 'hreflang' in issue['message'].lower(): - scores.international -= penalty - elif 'alt' in issue['message'].lower(): - scores.accessibility -= penalty - elif 'https' in issue['message'].lower() or 'security' in issue['message'].lower(): - scores.security -= penalty - else: - scores.technical -= penalty - - # Ensure scores don't go negative - for attr in ['technical', 'content', 'meta_tags', 'structured_data', 'social', 'mobile', 'international', 'accessibility', 'security']: - value = getattr(scores, attr) - setattr(scores, attr, max(0, min(100, value))) - - # Calculate weighted total - weights = { - 'meta_tags': 0.20, - 'content': 0.20, - 'structured_data': 0.15, - 'technical': 0.15, - 'mobile': 0.10, - 'social': 0.05, - 'accessibility': 0.05, - 'international': 0.05, - 'security': 0.05 - } - - scores.total = sum(getattr(scores, category) * weight for category, weight in weights.items()) - scores.total = round(scores.total) - + dimensions = {'meta_tags': 'Meta Tags', 'structured_data': 'Structured Data', + 'mobile': 'Mobile SEO', 'social': 'Social SEO', 'content': 'Content SEO', + 'international': 'International SEO', 'accessibility': 'Accessibility SEO', + 'security': 'Security', 'technical': 'Technical SEO'} + for dimension, category in dimensions.items(): + setattr(scores, dimension, score_findings([issue for issue in issues if issue.get('category') == category])) + scores.total = score_findings(issues) return scores -def analyze_seo(soup: BeautifulSoup, url: str) -> Dict[str, Any]: - """Advanced SEO analysis with comprehensive optimization detection.""" - issues = [] - data = {} - - # Extract meta tags comprehensively - meta_profile = extract_meta_tags(soup) - - # Analyze meta title - if not meta_profile.title: - issues.append(create_issue('Meta Tags', 'critical', 'Missing page title')) - else: - title_length = len(meta_profile.title) - title_pixels = calculate_text_pixel_width(meta_profile.title) - - data['title'] = { - 'text': meta_profile.title, - 'length': title_length, - 'pixels': title_pixels - } - - if title_length < 30: - issues.append(create_issue('Meta Tags', 'warning', - f'Title too short ({title_length} chars, recommended 30-60)')) - elif title_length > 60: - issues.append(create_issue('Meta Tags', 'warning', - f'Title too long ({title_length} chars, recommended 30-60)')) - - if title_pixels > 600: - issues.append(create_issue('Meta Tags', 'warning', - f'Title too wide ({title_pixels}px, max 600px on desktop)')) - - # Check for keyword stuffing - words = meta_profile.title.lower().split() - word_counts = Counter(words) - if any(count > 2 for word, count in word_counts.items() if len(word) > 3): - issues.append(create_issue('Meta Tags', 'warning', 'Possible keyword stuffing in title')) - - # Analyze meta description - if not meta_profile.description: - issues.append(create_issue('Meta Tags', 'critical', 'Missing meta description')) - else: - desc_length = len(meta_profile.description) - desc_pixels = calculate_text_pixel_width(meta_profile.description) - - data['description'] = { - 'text': meta_profile.description, - 'length': desc_length, - 'pixels': desc_pixels - } - - if desc_length < 120: - issues.append(create_issue('Meta Tags', 'warning', - f'Meta description too short ({desc_length} chars, recommended 120-160)')) - elif desc_length > 160: - issues.append(create_issue('Meta Tags', 'warning', - f'Meta description too long ({desc_length} chars, recommended 120-160)')) - - if desc_pixels > 920: - issues.append(create_issue('Meta Tags', 'warning', - f'Description too wide ({desc_pixels}px, max 920px on desktop)')) - - # Check for call-to-action - cta_words = ['learn', 'discover', 'find', 'get', 'shop', 'buy', 'read', 'download', 'sign up', 'try'] - if not any(word in meta_profile.description.lower() for word in cta_words): - issues.append(create_issue('Meta Tags', 'notice', - 'Meta description lacks call-to-action')) - - # Check meta keywords - if meta_profile.keywords: - issues.append(create_issue('Meta Tags', 'notice', - 'Meta keywords tag is deprecated and ignored by search engines')) - - # Analyze canonical URL - if not meta_profile.canonical: - issues.append(create_issue('Technical SEO', 'warning', 'Missing canonical URL')) - else: - data['canonical'] = meta_profile.canonical - # Check if canonical matches current URL (simplified check) - if meta_profile.canonical != url and not url.endswith('/'): - if meta_profile.canonical != url + '/': - issues.append(create_issue('Technical SEO', 'notice', - 'Canonical URL differs from current URL')) - - # Analyze robots directives - if meta_profile.robots: - data['robots'] = meta_profile.robots - robots_lower = meta_profile.robots.lower() - - if 'noindex' in robots_lower: - issues.append(create_issue('Technical SEO', 'critical', - 'Page is set to noindex (will not appear in search results)')) - - if 'nofollow' in robots_lower: - issues.append(create_issue('Technical SEO', 'warning', - 'Page is set to nofollow (links will not pass PageRank)')) - - if 'nosnippet' in robots_lower: - issues.append(create_issue('Technical SEO', 'warning', - 'Page is set to nosnippet (no text snippet in SERP)')) - - if 'noarchive' in robots_lower: - issues.append(create_issue('Technical SEO', 'notice', - 'Page is set to noarchive (no cached version)')) - - # Analyze Open Graph tags - og_required = ['og:title', 'og:description', 'og:image', 'og:url', 'og:type'] - og_missing = [tag for tag in og_required if tag not in meta_profile.og_tags] - - if og_missing: - issues.append(create_issue('Social SEO', 'warning', - f'Missing Open Graph tags: {", ".join(og_missing)}')) - - if 'og:image' in meta_profile.og_tags: - # Check for high-res image - if 'og:image:width' not in meta_profile.og_tags or 'og:image:height' not in meta_profile.og_tags: - issues.append(create_issue('Social SEO', 'notice', - 'Open Graph image missing dimensions')) - +def analyze_seo(soup: BeautifulSoup, url: str, headers: Any = None, + user_agent: Optional[str] = None, *, facts: Optional[PageFacts] = None) -> Dict[str, Any]: + """Evaluate explicit SEO rules over observed HTML and optional headers.""" + page_facts = ensure_page_facts(soup, url, headers, user_agent, facts) + headers = page_facts.headers + user_agent = page_facts.user_agent + collector = RuleCollector('seo') + data = {'score_scope': 'static_html_rules'} + meta_profile = extract_meta_tags(soup, facts=page_facts) + + def check(rule_id, failed, evidence, message, category='Technical SEO', **kwargs): + if kwargs.get('applicable') is False and not kwargs.get('reason'): + kwargs['reason'] = 'The element required by this rule is not declared in the observed HTML.' + return collector.check(rule_id, failed, evidence, message=message, category=category, **kwargs) + + check('seo.title_missing', not bool(meta_profile.title), {'title': meta_profile.title}, + 'Missing page title', 'Meta Tags') + words = Counter((meta_profile.title or '').casefold().split()) + repeated = {word: count for word, count in words.items() if count > 2 and len(word) > 3} + check('seo.title_repetition', bool(repeated), {'repeated_words': repeated}, + 'Review repeated words in the page title', 'Meta Tags', applicable=bool(meta_profile.title), + reason='Whitespace repetition is an editorial hint, not a keyword-stuffing diagnosis.', confidence='low') + for name, value in (('title', meta_profile.title), ('description', meta_profile.description)): + if value: + data[name] = {'text': value, 'length': len(value), 'pixels': calculate_text_pixel_width(value), + 'pixel_source': 'approximate_character_widths', 'length_requirement': None} + check('seo.description_missing', not bool(meta_profile.description), {'description': meta_profile.description}, + 'No meta description is declared', 'Meta Tags', + reason='Google may generate snippets from page content; this is an optional editorial improvement.') + check('seo.meta_keywords', bool(meta_profile.keywords), {'keywords': meta_profile.keywords}, + 'Meta keywords are not used by Google Search', 'Meta Tags') + + base_url = page_facts.base_url + link_records = page_facts.link_tags + canonical_declared = any('canonical' in record['attrs'].get('rel', []) for record in link_records) + canonical_url = resolve_url(meta_profile.canonical, base_url) if canonical_declared else None + if canonical_url and urlparse(canonical_url).scheme not in ('http', 'https'): + canonical_url = None + check('seo.canonical_preference', False if canonical_url else None, + {'html_canonical': meta_profile.canonical, 'resolved_url': canonical_url}, + 'Canonical preference needs duplicate-page context', + reason='HTML observation only; a preference is optional and may also be expressed by other signals.') + check('seo.canonical_invalid', canonical_url is None, + {'href': meta_profile.canonical, 'base_url': base_url}, + 'The declared canonical does not resolve to an HTTP or HTTPS URL', applicable=canonical_declared) + if canonical_declared: + data['canonical'] = canonical_url + data['canonical_is_self_referencing'] = canonical_url == resolve_url(url, url) + + robots = page_facts.robots + data['robots'] = ', '.join(robots['directives']) + data['robots_analysis'] = robots + for directive in ('noindex', 'nofollow', 'nosnippet'): + observed = robots[directive] + check('robots.' + directive, observed if observed or headers is not None else None, + {'directives': robots['directives'], 'observations': robots['evidence'], + 'user_agent': user_agent, 'headers_checked': headers is not None}, + 'Page is set to ' + directive, source='html_and_headers', + reason='Review the directive against the intended publishing policy; absent headers leave coverage incomplete.') + + og_required = ('og:title', 'og:type', 'og:image', 'og:url') + og_missing = [name for name in og_required if name not in meta_profile.og_tags] + check('seo.og_incomplete', bool(og_missing), {'missing': og_missing, 'declared': meta_profile.og_tags}, + 'Open Graph object is missing basic properties', 'Social SEO', applicable=bool(meta_profile.og_tags)) + missing_og_dimensions = [name for name in ('og:image:width', 'og:image:height') if name not in meta_profile.og_tags] + check('seo.og_image_dimensions', bool(missing_og_dimensions), {'missing': missing_og_dimensions}, + 'Open Graph image dimensions are not declared', 'Social SEO', applicable='og:image' in meta_profile.og_tags) data['open_graph'] = meta_profile.og_tags - - # Analyze Twitter Card tags - if not meta_profile.twitter_tags: - issues.append(create_issue('Social SEO', 'warning', - 'Missing Twitter Card tags for better social sharing')) - else: - twitter_type = meta_profile.twitter_tags.get('twitter:card', 'summary') - - if twitter_type == 'summary_large_image': - required = ['twitter:title', 'twitter:description', 'twitter:image'] - twitter_missing = [tag for tag in required if tag not in meta_profile.twitter_tags] - if twitter_missing: - issues.append(create_issue('Social SEO', 'warning', - f'Missing Twitter Card tags: {", ".join(twitter_missing)}')) - data['twitter_card'] = meta_profile.twitter_tags - - # Analyze structured data + data['social_preview_status'] = 'not_measured' + structured_data_items = [] - - for script in soup.find_all('script', type='application/ld+json'): + syntax_errors, shape_errors, empty_scripts = [], [], [] + scripts = [record for record in page_facts.scripts + if str(record['attrs'].get('type', '')).casefold() == 'application/ld+json'] + parsed_scripts = 0 + + def reject_constant(value): + raise ValueError('Non-JSON numeric constant: ' + value) + + for index, script in enumerate(scripts): try: - json_data = json.loads(script.string) - - # Handle @graph arrays - if '@graph' in json_data: - for item in json_data['@graph']: - validated = validate_structured_data(item) - structured_data_items.append(validated) - else: - validated = validate_structured_data(json_data) - structured_data_items.append(validated) - - except json.JSONDecodeError: - issues.append(create_issue('Structured Data', 'critical', - 'Invalid JSON-LD structured data found')) - except Exception as e: - issues.append(create_issue('Structured Data', 'warning', - f'Error parsing structured data: {str(e)}')) - - if not structured_data_items: - issues.append(create_issue('Structured Data', 'warning', - 'No structured data (JSON-LD) found')) - else: - # Report validation errors - for item in structured_data_items: + json_data = json.loads(script['text'], parse_constant=reject_constant) + except (json.JSONDecodeError, ValueError) as exc: + syntax_errors.append({'script_index': index, 'error': str(exc), + 'line': getattr(exc, 'lineno', None), 'column': getattr(exc, 'colno', None)}) + continue + parsed_scripts += 1 + try: + nodes = list(iter_structured_data(json_data)) + except ValueError as exc: + shape_errors.append({'script_index': index, 'error': str(exc)}) + continue + if not nodes: + empty_scripts.append(index) + for node_index, node in enumerate(nodes): + item = validate_structured_data(node) + structured_data_items.append(item) if not item.is_valid: - for error in item.validation_errors[:3]: # Limit to 3 errors per item - issues.append(create_issue('Structured Data', 'warning', - f'{item.type}: {error}')) - - # Check for rich snippet eligibility - eligible_snippets = [item for item in structured_data_items if item.rich_snippet_eligible] - if eligible_snippets: - data['rich_snippets'] = [ - {'type': item.snippet_type.value, 'schema': item.type} - for item in eligible_snippets - ] - + shape_errors.append({'script_index': index, 'node_index': node_index, + 'type': item.type, 'errors': item.validation_errors}) + check('seo.jsonld_syntax', bool(syntax_errors), {'scripts': len(scripts), 'errors': syntax_errors}, + 'Invalid JSON syntax in declared JSON-LD', 'Structured Data', applicable=bool(scripts)) + check('seo.jsonld_shape', bool(shape_errors), {'parsed_scripts': parsed_scripts, 'errors': shape_errors}, + 'Unsupported JSON-LD node or type shape', 'Structured Data', applicable=bool(parsed_scripts), + reason='Only local node, graph and @type shapes are checked; this is not full JSON-LD validation.') + check('seo.jsonld_empty', bool(empty_scripts), {'script_indices': empty_scripts}, + 'JSON-LD scripts contain no locally extractable nodes', 'Structured Data', applicable=bool(parsed_scripts)) + check('seo.jsonld_eligibility', None, + {'jsonld_script_count': len(scripts), 'types': [item.type for item in structured_data_items], + 'other_syntax_checked': False}, 'Structured-data search eligibility is not assessed', 'Structured Data', + applicable=None, reason='Page purpose and feature-specific validation are unavailable; JSON-LD is optional.') data['structured_data'] = [ - { - 'type': item.type, - 'valid': item.is_valid, - 'rich_snippet_eligible': item.rich_snippet_eligible, - 'errors': item.validation_errors[:3] # Limit errors in output - } + {'type': item.type, 'valid': item.is_valid, 'rich_snippet_eligible': None, + 'eligibility_status': 'unknown', 'validation_scope': 'local_shape_checks', 'errors': item.validation_errors} for item in structured_data_items ] - - # Analyze language and international SEO - html_tag = soup.find('html') - if html_tag: - lang = html_tag.get('lang') - if not lang: - issues.append(create_issue('International SEO', 'warning', - 'Missing language declaration (lang attribute)')) - else: - data['language'] = lang - - # Check for proper language code format - if not re.match(r'^[a-z]{2}(-[A-Z]{2})?$', lang): - issues.append(create_issue('International SEO', 'notice', - f'Non-standard language code format: {lang}')) - - # Check hreflang tags + + lang = page_facts.language + check('language.missing', not bool(lang), {'lang': lang}, + 'Missing document language declaration', 'International SEO') + if lang: + data['language'] = lang + malformed_lang = bool(lang) and not bool(re.fullmatch(r'[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*', lang)) + check('seo.language_format', malformed_lang, {'lang': lang, 'registry_checked': False}, + 'Document language has a malformed language-tag shape', 'International SEO', applicable=bool(lang), + reason='This check does not validate registered subtags, tag ordering, or agreement with the text language.') if meta_profile.alternate_languages: data['hreflang'] = meta_profile.alternate_languages - - # Check for x-default - if 'x-default' not in meta_profile.alternate_languages: - issues.append(create_issue('International SEO', 'notice', - 'Missing x-default hreflang tag')) - - # Mobile SEO - if not meta_profile.viewport: - issues.append(create_issue('Mobile SEO', 'critical', - 'Missing viewport meta tag (not mobile-friendly)')) - else: - data['viewport'] = meta_profile.viewport - - # Check for proper viewport settings - if 'width=device-width' not in meta_profile.viewport: - issues.append(create_issue('Mobile SEO', 'warning', - 'Viewport not set to device-width')) - - if 'user-scalable=no' in meta_profile.viewport: - issues.append(create_issue('Mobile SEO', 'warning', - 'Viewport prevents user scaling (accessibility issue)')) - - # Analyze heading structure - heading_analysis = analyze_heading_structure(soup) + data['hreflang_status'] = 'site_validation_required' if meta_profile.alternate_languages else 'not_declared' + + viewport = meta_profile.viewport + settings = {} + for entry in re.split(r'[,;]', viewport or ''): + key, separator, value = entry.partition('=') + if separator: + settings[key.strip().casefold()] = value.strip().casefold() + check('mobile.viewport_missing', not bool(viewport), {'viewport': viewport}, + 'Missing viewport meta tag', 'Mobile SEO') + check('seo.viewport_width', settings.get('width') != 'device-width', {'viewport': viewport, 'settings': settings}, + 'Review the viewport width on narrow screens', 'Mobile SEO', applicable=bool(viewport), confidence='low') + zoom_disabled = settings.get('user-scalable') in ('no', '0') + try: + max_scale = float(settings.get('maximum-scale', 'nan')) + zoom_disabled = zoom_disabled or 0 < max_scale < 2 + except ValueError: + pass + check('mobile.viewport_zoom_disabled', zoom_disabled, {'viewport': viewport, 'settings': settings}, + 'Viewport requests restrictions on user zoom', 'Mobile SEO', applicable=bool(viewport), + reason='Browser enforcement varies; verify that users can enlarge text without loss of functionality.') + if viewport: + data['viewport'] = viewport + + heading_analysis = analyze_heading_structure(soup, facts=page_facts) data['heading_structure'] = heading_analysis - - for heading_issue in heading_analysis['issues']: - severity = 'critical' if 'No H1' in heading_issue else 'warning' - issues.append(create_issue('Content SEO', severity, heading_issue)) - - # Analyze images for SEO - images = soup.find_all('img') - images_without_alt = [] - images_without_dimensions = [] - large_images = [] - - for img in images: - src = img.get('src', '') - - # Check alt text - if not img.get('alt'): - images_without_alt.append(src) - - # Check dimensions - if not (img.get('width') and img.get('height')): - images_without_dimensions.append(src) - - # Check for WebP/modern formats - if src and not any(fmt in src.lower() for fmt in ['.webp', '.avif']): - large_images.append(src) - - if images_without_alt: - issues.append(create_issue('Accessibility SEO', 'warning', - f'{len(images_without_alt)} images missing alt text')) - - if images_without_dimensions: - issues.append(create_issue('Technical SEO', 'warning', - f'{len(images_without_dimensions)} images missing dimensions (causes CLS)')) - - data['images'] = { - 'total': len(images), - 'missing_alt': len(images_without_alt), - 'missing_dimensions': len(images_without_dimensions), - 'non_optimized': len(large_images) - } - - # Internal linking analysis - internal_linking = analyze_internal_linking_seo(soup, url) - data['internal_linking'] = internal_linking - - if internal_linking['internal_count'] < 3: - issues.append(create_issue('Content SEO', 'warning', - 'Too few internal links (less than 3)')) - - if internal_linking['anchor_diversity'] < 0.5: - issues.append(create_issue('Content SEO', 'notice', - 'Low internal anchor text diversity')) - - # Generate SERP preview - serp_preview = generate_serp_preview(meta_profile, url) - data['serp_preview'] = { - 'title': serp_preview.title, - 'description': serp_preview.description, - 'url': serp_preview.url, - 'breadcrumbs': serp_preview.breadcrumbs, - 'title_pixels': serp_preview.title_pixels, - 'description_pixels': serp_preview.description_pixels - } - - # Detect SEO opportunities - opportunities = detect_seo_opportunities(soup, meta_profile, structured_data_items) - data['opportunities'] = opportunities - - # Check for common SEO issues - # Check charset - if not meta_profile.charset: - issues.append(create_issue('Technical SEO', 'warning', - 'Missing charset declaration')) - elif meta_profile.charset.lower() != 'utf-8': - issues.append(create_issue('Technical SEO', 'notice', - f'Non-UTF-8 charset: {meta_profile.charset}')) - - # Check for favicon - if not soup.find('link', rel=re.compile('icon')): - issues.append(create_issue('Technical SEO', 'notice', - 'Missing favicon')) - - # Check for sitemap link - if not soup.find('link', rel='sitemap'): - issues.append(create_issue('Technical SEO', 'notice', - 'No sitemap link in HTML')) - - # Check for RSS/Atom feeds - if not soup.find('link', type=re.compile(r'application/(rss|atom)\+xml')): - issues.append(create_issue('Technical SEO', 'notice', - 'No RSS/Atom feed detected')) - - # Calculate comprehensive SEO scores + for rule_id in ('headings.missing_h1', 'headings.empty', 'headings.skipped_level'): + findings = [finding for finding in heading_analysis['findings'] if finding['rule_id'] == rule_id] + check(rule_id, bool(findings), {'findings': findings, 'headings': heading_analysis['headings']}, + '; '.join(finding['message'] for finding in findings) or 'Heading check passed', 'Content SEO') + + images = [record['attrs'] for record in page_facts.images] + missing_alt = [img.get('src', '') for img in images if 'alt' not in img] + missing_dimensions = [img.get('src', '') for img in images if not (img.get('width') and img.get('height'))] + non_modern_references = [img.get('src', '') for img in images + if img.get('src') and not re.search(r'\.(?:webp|avif)(?:[?#]|$)', img['src'], re.I)] + check('images.missing_alt', bool(missing_alt), {'urls': missing_alt, 'total_images': len(images)}, + f'{len(missing_alt)} images missing alt attributes', 'Accessibility SEO', applicable=bool(images)) + check('images.missing_dimensions', bool(missing_dimensions), {'urls': missing_dimensions}, + 'Images lack HTML dimensions; verify that layout space is reserved in CSS', + applicable=bool(images), confidence='low') + data['images'] = {'total': len(images), 'missing_alt': len(missing_alt), + 'missing_dimensions': len(missing_dimensions), 'non_optimized': None, + 'non_modern_filename_references': len(non_modern_references), + 'optimization_status': 'requires_resource_measurement'} + data['internal_linking'] = analyze_internal_linking_seo(soup, url, facts=page_facts) + + preview = generate_serp_preview(meta_profile, url) + data['serp_preview'] = {name: getattr(preview, name) for name in + ('title', 'description', 'url', 'breadcrumbs', 'title_pixels', 'description_pixels')} + data['serp_preview'].update({'status': 'illustrative', 'source': 'approximate_character_widths', + 'search_appearance_verified': False}) + data['opportunities'] = detect_seo_opportunities(soup, meta_profile, structured_data_items) + + response_types = header_values(headers, 'Content-Type') + header_charsets = [] + for content_type in response_types: + match = re.search(r"charset\s*=\s*[\"']?([^;\s\"']+)", content_type, re.I) + if match: + header_charsets.append(match.group(1)) + charset = header_charsets[0] if header_charsets else meta_profile.charset + encoding_evidence = {'html_charset': meta_profile.charset, 'header_charsets': header_charsets, + 'headers_checked': headers is not None, 'original_bytes_checked': False} + check('seo.charset_missing', False if charset else None, encoding_evidence, + 'Character encoding declaration needs verification', source='html_and_headers', + reason='No declaration observed does not exclude a byte-order mark in the original response.') + check('seo.charset_non_utf8', str(charset).casefold() not in ('utf-8', 'utf8'), encoding_evidence, + 'A non-UTF-8 encoding is declared', applicable=bool(charset), source='html_and_headers') + icon_links = [record['attrs'] for record in link_records if 'icon' in record['attrs'].get('rel', [])] + check('seo.favicon_missing', not bool(icon_links), {'icon_hrefs': [tag.get('href') for tag in icon_links]}, + 'No explicit homepage favicon link is declared', applicable=urlparse(url).path in ('', '/'), + reason='Default icon paths and image responses have not been requested.') + + issues = collector.issues seo_scores = calculate_seo_scores(issues, data) - - data['scores'] = { - 'total': seo_scores.total, - 'technical': seo_scores.technical, - 'content': seo_scores.content, - 'meta_tags': seo_scores.meta_tags, - 'structured_data': seo_scores.structured_data, - 'social': seo_scores.social, - 'mobile': seo_scores.mobile, - 'international': seo_scores.international, - 'accessibility': seo_scores.accessibility, - 'security': seo_scores.security - } - - # Generate recommendations based on scores - recommendations = [] - - if seo_scores.meta_tags < 70: - recommendations.append("Priority: Optimize meta tags (title, description) for better SERP visibility") - - if seo_scores.structured_data < 70: - recommendations.append("Priority: Implement structured data for rich snippets") - - if seo_scores.mobile < 70: - recommendations.append("Priority: Fix mobile SEO issues for mobile-first indexing") - - if seo_scores.content < 70: - recommendations.append("Priority: Improve content structure and heading hierarchy") - - if opportunities: - high_priority = [o for o in opportunities if o.get('priority') in ['critical', 'high']] - if high_priority: - recommendations.append(f"Opportunity: {high_priority[0]['opportunity']}") - + data['scores'] = {name: getattr(seo_scores, name) for name in + ('total', 'technical', 'content', 'meta_tags', 'structured_data', 'social', + 'mobile', 'international', 'accessibility', 'security')} + data['score_dimensions_scope'] = ( + 'Non-additive diagnostic subsets of rules observed by the SEO analyzer. ' + 'The page pipeline assigns each shared rule to one analyzer for aggregate scoring.' + ) + recommendations = recommendations_for(issues) data['recommendations'] = recommendations - - # Store meta profile data data['meta_profile'] = { - 'title': meta_profile.title, - 'description': meta_profile.description, - 'canonical': meta_profile.canonical, - 'robots': meta_profile.robots, - 'charset': meta_profile.charset, - 'og_tags': dict(list(meta_profile.og_tags.items())[:10]), # Limit output - 'twitter_tags': meta_profile.twitter_tags, - 'hreflang_count': len(meta_profile.alternate_languages) + 'title': meta_profile.title, 'description': meta_profile.description, + 'canonical': meta_profile.canonical, 'robots': meta_profile.robots, 'charset': meta_profile.charset, + 'og_tags': meta_profile.og_tags, 'twitter_tags': meta_profile.twitter_tags, + 'hreflang_count': len(meta_profile.alternate_languages), } - - return { - 'score': seo_scores.total, - 'issues': issues, - 'data': data - } \ No newline at end of file + return {'score': seo_scores.total, 'issues': issues, 'data': data, 'recommendations': recommendations, + 'rule_results': collector.results, 'rule_coverage': collector.coverage, 'coverage': collector.coverage} diff --git a/tfq0seo/analyzers/technical.py b/tfq0seo/analyzers/technical.py index 5f24dba..643bd30 100644 --- a/tfq0seo/analyzers/technical.py +++ b/tfq0seo/analyzers/technical.py @@ -2,13 +2,107 @@ import re import ipaddress -from typing import Dict, List, Any, Optional, Tuple, Set -from urllib.parse import urlparse, parse_qs, unquote -from collections import defaultdict, Counter +import math +from typing import Dict, List, Any, Optional +from urllib.parse import urlparse, parse_qs from dataclasses import dataclass, field from enum import Enum -from datetime import datetime, timedelta -from bs4 import BeautifulSoup, Comment +from bs4 import BeautifulSoup, Doctype +from .common import (document_base_url, header_values, make_issue, normalized_headers, + parse_robots, resolve_url) +from ..rules import RuleDefinition, RuleCollector, register_rules, score_findings, recommendations_for +from ..page_facts import PageFacts, ensure_page_facts + + +_REVIEWED = '2026-09-14' +_HSTS = 'https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Strict-Transport-Security' +_CSP = 'https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Security-Policy' +_SCRIPT_CSP = _CSP + '/script-src' +_XFO = 'https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Frame-Options' +_HTTP_STATUS = 'https://developers.google.com/crawling/docs/troubleshooting/http-status-codes' +_DOCTYPE = 'https://html.spec.whatwg.org/multipage/syntax.html#the-doctype' + + +# Optional deployment policies and source-code hints are observations, not defects. +TECHNICAL_RULES = register_rules([ + RuleDefinition('technical.http_server_error', 'technical', 'critical', + 'Investigate the server failure and restore the intended response.', + 'An observed HTTP response status in the 500-599 range.', (_HTTP_STATUS,), _REVIEWED), + RuleDefinition('technical.http_client_error', 'technical', 'critical', + 'Confirm the requested resource should exist or be accessible, then correct its response or incoming links.', + 'An observed HTTP response status in the 400-499 range.', (_HTTP_STATUS,), _REVIEWED), + RuleDefinition('technical.http_redirect', 'technical', 'notice', + 'Confirm the redirect destination and choose permanent or temporary semantics to match the intended change.', + 'An observed redirect response; permanence and publisher intent are not inferred.', + ('https://developers.google.com/search/docs/crawling-indexing/301-redirects',), _REVIEWED, scored=False), + RuleDefinition('security.hsts_missing', 'technical', 'notice', + 'Review whether this HTTPS domain should deploy HSTS; check subdomain readiness and existing browser or preload policy first.', + 'Observed response headers on an HTTPS domain; cached HSTS and preload membership are not checked.', + (_HSTS,), _REVIEWED, scored=False), + RuleDefinition('security.hsts_invalid', 'technical', 'warning', + 'Provide one valid HSTS policy with a single nonnegative integer max-age and no repeated directives.', + 'An HSTS header declared by an HTTPS domain.', + (_HSTS, 'https://www.rfc-editor.org/rfc/rfc6797.html'), _REVIEWED), + RuleDefinition('security.hsts_preload_incomplete', 'technical', 'notice', + 'If preloading is intended, verify all preload requirements, including max-age of at least one year and includeSubDomains.', + 'An HTTPS domain whose HSTS header explicitly includes preload; submission and subdomain behavior are unobserved.', + (_HSTS,), _REVIEWED, scored=False), + RuleDefinition('security.csp_missing', 'technical', 'notice', + 'Evaluate a Content Security Policy appropriate to the application and test it before enforcement.', + 'Observed headers and HTML without an enforcing CSP declaration; a universal policy is not assumed.', + (_CSP,), _REVIEWED, scored=False), + RuleDefinition('security.frame_policy_missing', 'technical', 'notice', + 'Decide which sites may embed this document and configure frame-ancestors or X-Frame-Options if restrictions are needed.', + 'Observed document response headers; whether embedding should be restricted is unknown.', + (_XFO, _CSP), _REVIEWED, scored=False), + RuleDefinition('security.csp_unsafe_inline', 'technical', 'notice', + 'Review the observed inline-script source expression in the context of all enforced CSP policies; consider nonces or hashes where suitable.', + 'A script source directive contains unsafe-inline without a nonce or hash in that directive; execution and combined policy effects are not tested.', + (_SCRIPT_CSP, _CSP), _REVIEWED, scored=False), + RuleDefinition('security.csp_unsafe_eval', 'technical', 'notice', + 'Check whether evaluated script strings are needed and remove unsafe-eval from the applicable policy where possible.', + 'An observed script source directive contains unsafe-eval; exploitability is not inferred.', + (_SCRIPT_CSP, _CSP), _REVIEWED, scored=False), + RuleDefinition('security.csp_wildcard_default', 'technical', 'notice', + 'Review the wildcard default source against the resources the application needs and its more specific directives.', + 'An observed CSP default-src directive contains a wildcard; effective resource permissions are not tested.', + (_CSP,), _REVIEWED, scored=False), + RuleDefinition('security.xfo_invalid', 'technical', 'warning', + 'Use a supported X-Frame-Options value, DENY or SAMEORIGIN, or replace it with an appropriate frame-ancestors policy.', + 'An observed X-Frame-Options declaration.', (_XFO,), _REVIEWED), + RuleDefinition('security.cors_wildcard_credentials', 'technical', 'warning', + 'For intended credentialed cross-origin access, allow a validated explicit origin; otherwise remove the credential permission.', + 'A response declares both a wildcard Access-Control-Allow-Origin and Access-Control-Allow-Credentials: true.', + ('https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS/Errors/CORSNotSupportingCredentials',), _REVIEWED), + RuleDefinition('technical.http_compression', 'technical', 'notice', + 'Measure response size and transfer savings before enabling a suitable content encoding for compressible responses.', + 'A body-bearing HTML response has observed headers without a non-identity Content-Encoding; negotiation and savings are unmeasured.', + ('https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Encoding',), _REVIEWED, scored=False), + RuleDefinition('technical.url_session_parameter', 'technical', 'notice', + 'Verify whether these parameter names carry session state. If they do, consider cookies and stable crawlable URLs without merging distinct content.', + 'URL query parameter names match common session identifiers; their meaning is not established.', + ('https://developers.google.com/search/docs/crawling-indexing/url-structure',), _REVIEWED, scored=False), + RuleDefinition('technical.javascript_redirect_reference', 'technical', 'notice', + 'Verify whether this code executes a redirect. If a server redirect matches the intended behavior, prefer it for predictable discovery.', + 'Inline script text references a location assignment or redirect method; execution and intent are unknown.', + ('https://developers.google.com/search/docs/crawling-indexing/301-redirects',), _REVIEWED, scored=False), + RuleDefinition('technical.http_resource_reference', 'technical', 'notice', + 'Update applicable resource references to HTTPS and verify the rendered network requests, including browser upgrades and blocks.', + 'An HTTPS document declares an HTTP subresource URL; an actual insecure network request is not established.', + ('https://developer.mozilla.org/en-US/docs/Web/Security/Defenses/Mixed_content',), _REVIEWED, scored=False), + RuleDefinition('technical.deprecated_elements', 'technical', 'notice', + 'Replace obsolete elements with supported semantic HTML and CSS after checking their intended presentation and behavior.', + 'Observed obsolete HTML elements; rendered breakage is not inferred.', + ('https://html.spec.whatwg.org/multipage/obsolete.html',), _REVIEWED, scored=False), + RuleDefinition('html.doctype_missing', 'technical', 'warning', + 'Start HTML documents with to request standards mode.', + 'Documents parsed as HTML syntax; XML/XHTML syntax does not require the HTML doctype.', + (_DOCTYPE,), _REVIEWED), + RuleDefinition('html.doctype_legacy', 'technical', 'notice', + 'Consider the modern HTML doctype when updating the document, and verify rendering before changing a legacy declaration.', + 'An observed legacy HTML doctype; quirks mode is not inferred from its age alone.', + (_DOCTYPE,), _REVIEWED, scored=False), +]) class SecurityLevel(Enum): @@ -26,6 +120,7 @@ class CrawlabilityStatus(Enum): PARTIALLY_BLOCKED = "partially_blocked" BLOCKED = "blocked" CONDITIONAL = "conditional" + UNKNOWN = "unknown" class MobileReadiness(Enum): @@ -71,7 +166,7 @@ class SecurityProfile: @dataclass class CrawlabilityProfile: """Crawlability and indexability analysis.""" - status: CrawlabilityStatus = CrawlabilityStatus.FULLY_CRAWLABLE + status: CrawlabilityStatus = CrawlabilityStatus.UNKNOWN robots_meta: Optional[str] = None x_robots_tag: Optional[str] = None canonical_url: Optional[str] = None @@ -84,8 +179,9 @@ class CrawlabilityProfile: unavailable_after: Optional[str] = None crawl_delay: Optional[float] = None blocked_resources: List[str] = field(default_factory=list) - javascript_required: bool = False + javascript_required: Optional[bool] = None ajax_crawlable: bool = False + robots_analysis: Dict[str, Any] = field(default_factory=dict) @dataclass @@ -96,9 +192,9 @@ class MobileProfile: mobile_readiness: MobileReadiness = MobileReadiness.DESKTOP_ONLY responsive_images: int = 0 total_images: int = 0 - touch_elements_size: bool = True - text_readability: bool = True - horizontal_scrolling: bool = False + touch_elements_size: Optional[bool] = None + text_readability: Optional[bool] = None + horizontal_scrolling: Optional[bool] = None uses_plugins: bool = False amp_version: Optional[str] = None pwa_ready: bool = False @@ -111,16 +207,16 @@ class PerformanceProfile: protocol_version: ProtocolVersion = ProtocolVersion.UNKNOWN compression_enabled: bool = False compression_type: Optional[str] = None - compression_ratio: float = 0.0 + compression_ratio: Optional[float] = None cache_control: Optional[str] = None - cache_ttl: int = 0 + cache_ttl: Optional[int] = None etag_present: bool = False last_modified: Optional[str] = None cdn_detected: bool = False cdn_provider: Optional[str] = None - server_push_enabled: bool = False - early_hints: bool = False - connection_reuse: bool = False + server_push_enabled: Optional[bool] = None + early_hints: Optional[bool] = None + connection_reuse: Optional[bool] = None keep_alive_timeout: int = 0 @@ -154,63 +250,118 @@ class InternationalProfile: rtl_support: bool = False -def create_issue(category: str, severity: str, message: str, details: Optional[Dict] = None) -> Dict[str, Any]: - """Create an enhanced technical issue with detailed recommendations.""" - issue = { - 'category': category, - 'severity': severity, - 'message': message - } - if details: - issue['details'] = details - - # Add specific technical recommendations - if 'security' in message.lower() or 'https' in message.lower(): - issue['fix'] = "Implement security headers: HSTS, CSP, X-Frame-Options. Use HTTPS everywhere with modern TLS." - issue['impact'] = "Critical - Security issues affect trust, rankings, and user safety" - elif 'cache' in message.lower(): - issue['fix'] = "Configure Cache-Control headers, use CDN, implement browser and edge caching strategies" - issue['impact'] = "High - Caching improves performance and reduces server load" - elif 'mobile' in message.lower() or 'viewport' in message.lower(): - issue['fix'] = "Add viewport meta tag, use responsive design, optimize for touch interfaces" - issue['impact'] = "Critical - Mobile-first indexing requires mobile optimization" - elif 'compression' in message.lower(): - issue['fix'] = "Enable Gzip or Brotli compression for text resources" - issue['impact'] = "High - Compression reduces bandwidth by 70-90%" - elif 'protocol' in message.lower() or 'http/2' in message.lower(): - issue['fix'] = "Upgrade to HTTP/2 or HTTP/3 for multiplexing and better performance" - issue['impact'] = "Medium - Modern protocols improve loading speed" - elif 'url' in message.lower(): - issue['fix'] = "Use clean, descriptive URLs without parameters. Implement URL rewriting." - issue['impact'] = "Medium - Clean URLs improve UX and SEO" - else: - issue['fix'] = "Review technical SEO best practices for this issue" - issue['impact'] = "Varies based on implementation" - - return issue +def create_issue(category: str, severity: str, message: str, details: Optional[Dict] = None, + rule_id: Optional[str] = None, evidence: Any = None, + confidence: str = 'high') -> Dict[str, Any]: + """Compatibility adapter; rule metadata and advice come only from the registry.""" + return make_issue(category, severity, message, details, rule_id, evidence, + confidence=confidence) + + +def _viewport_values(content: str) -> Dict[str, str]: + """Read authored viewport key/value pairs without inferring a rendered layout.""" + values = {} + for part in re.split(r'[,;]', content): + name, separator, value = part.partition('=') + if separator: + values[name.strip().lower()] = value.strip().lower() + return values + + +def _viewport_restricts_zoom(values: Dict[str, str]) -> bool: + if values.get('user-scalable') in ('no', '0'): + return True + try: + maximum = float(values.get('maximum-scale', '')) + except ValueError: + return False + return math.isfinite(maximum) and 0 <= maximum < 2 + + +def _has_nonce_or_hash(tokens: List[str]) -> bool: + return any(re.fullmatch(r"'(?:nonce|sha256|sha384|sha512)-[A-Za-z0-9+/_-]+={0,2}'", token) + for token in tokens) + + +def _csp_policies(headers: Any, soup: Optional[BeautifulSoup] = None, *, + facts: Optional[PageFacts] = None) -> List[Dict[str, Any]]: + """Preserve separate policies; duplicate directives use the first occurrence.""" + declarations = [('response_header', value) for value in header_values(headers, 'Content-Security-Policy')] + if soup is not None or facts is not None: + metas = [record['attrs'] for record in facts.meta] if facts is not None else soup.find_all('meta') + declarations.extend(('meta', str(meta.get('content', ''))) for meta in metas + if str(meta.get('http-equiv', '')).strip().lower() == 'content-security-policy') + policies = [] + for source, declaration in declarations: + # A combined header may contain several serialized policies. A meta value is one policy. + for value in declaration.split(',') if source == 'response_header' else [declaration]: + directives = {} + for part in value.split(';'): + words = part.strip().split() + if words: + directives.setdefault(words[0].lower(), words[1:]) + policies.append({'source': source, 'directives': directives}) + return policies + + +def _hsts_policy(headers: Any) -> Dict[str, Any]: + values = header_values(headers, 'Strict-Transport-Security') + directives = {} + if values: + # RFC 6797: browsers process only the first STS header field. + parts, current, quoted, escaped = [], [], False, False + for character in values[0]: + if character == ';' and not quoted: + parts.append(''.join(current)) + current = [] + continue + current.append(character) + if escaped: + escaped = False + elif quoted and character == '\\': + escaped = True + elif character == '"': + quoted = not quoted + parts.append(''.join(current)) + for part in parts: + name, separator, value = part.strip().partition('=') + if name: + directives.setdefault(name.strip().lower(), []).append(value.strip() if separator else None) + ages = directives.get('max-age', []) + age_text = ages[0] if len(ages) == 1 and ages[0] is not None else '' + if len(age_text) >= 2 and age_text.startswith('"') and age_text.endswith('"'): + age_text = re.sub(r'\\(.)', r'\1', age_text[1:-1]) + valid_age = bool(re.fullmatch(r'[0-9]+', age_text)) + duplicate_directives = [name for name, items in directives.items() if len(items) > 1] + invalid_include = any(value is not None for value in directives.get('includesubdomains', [])) + max_age = None + if valid_age: + digits = age_text.lstrip('0') or '0' + # Retain field text in evidence without reporting a clamped value as a measurement. + max_age = int(digits) if len(digits) < 19 else None + meets_preload_duration = valid_age and (len(digits) > 8 or + len(digits) == 8 and digits >= '31536000') + return {'values': values, 'selected_header': 0 if values else None, + 'max_age': max_age, 'includesubdomains': 'includesubdomains' in directives, + 'meets_preload_duration': meets_preload_duration, + 'preload': 'preload' in directives, 'duplicate_directives': duplicate_directives, + 'validation_scope': 'max-age and includeSubDomains values; duplicate directive names', + 'valid': bool(values) and valid_age and not duplicate_directives and not invalid_include} def analyze_security_headers(headers: Dict[str, str]) -> SecurityProfile: - """Comprehensive security header analysis.""" + """Describe header configuration; the legacy level is a coverage heuristic.""" profile = SecurityProfile() - headers_lower = {k.lower(): v for k, v in headers.items()} if headers else {} + headers_lower = normalized_headers(headers) # HSTS Analysis - hsts = headers_lower.get('strict-transport-security', '') - if hsts: + hsts = _hsts_policy(headers) + if hsts['values']: profile.hsts_enabled = True + profile.hsts_max_age = hsts['max_age'] or 0 + profile.hsts_includesubdomains = hsts['includesubdomains'] + profile.hsts_preload = hsts['preload'] - # Parse max-age - max_age_match = re.search(r'max-age=(\d+)', hsts) - if max_age_match: - profile.hsts_max_age = int(max_age_match.group(1)) - - profile.hsts_includesubdomains = 'includesubdomains' in hsts.lower() - profile.hsts_preload = 'preload' in hsts.lower() - - # Check for recommended values - if profile.hsts_max_age < 31536000: # Less than 1 year - profile.vulnerabilities.append("HSTS max-age less than recommended 1 year") # CSP Analysis csp = headers_lower.get('content-security-policy', '') @@ -219,12 +370,15 @@ def analyze_security_headers(headers: Dict[str, str]) -> SecurityProfile: profile.csp_policy = csp # Check for unsafe directives - if 'unsafe-inline' in csp: - profile.vulnerabilities.append("CSP allows unsafe-inline scripts") - if 'unsafe-eval' in csp: - profile.vulnerabilities.append("CSP allows unsafe-eval") - if '*' in csp and 'default-src' in csp: - profile.vulnerabilities.append("CSP default-src allows all origins") + for policy in _csp_policies(headers): + policies = policy['directives'] + script_policy = policies.get('script-src', policies.get('default-src', [])) + if "'unsafe-inline'" in script_policy and not _has_nonce_or_hash(script_policy): + profile.vulnerabilities.append("CSP script directive includes unsafe-inline without a nonce or hash") + if "'unsafe-eval'" in script_policy: + profile.vulnerabilities.append("CSP script directive includes unsafe-eval") + if '*' in policies.get('default-src', []): + profile.vulnerabilities.append("CSP default-src includes a wildcard") # X-Frame-Options xfo = headers_lower.get('x-frame-options', '') @@ -232,11 +386,11 @@ def analyze_security_headers(headers: Dict[str, str]) -> SecurityProfile: profile.xfo_enabled = True profile.xfo_policy = xfo.upper() - if xfo.upper() not in ['DENY', 'SAMEORIGIN']: + if xfo.strip().upper() not in ['DENY', 'SAMEORIGIN']: profile.vulnerabilities.append(f"Invalid X-Frame-Options value: {xfo}") # Other security headers - profile.x_content_type_options = 'x-content-type-options' in headers_lower + profile.x_content_type_options = headers_lower.get('x-content-type-options', '').lower() == 'nosniff' profile.x_xss_protection = 'x-xss-protection' in headers_lower profile.referrer_policy = headers_lower.get('referrer-policy') profile.permissions_policy = headers_lower.get('permissions-policy') or headers_lower.get('feature-policy') @@ -249,8 +403,9 @@ def analyze_security_headers(headers: Dict[str, str]) -> SecurityProfile: profile.cors_headers[header] = headers_lower[header] # Check for wildcard CORS - if profile.cors_headers.get('access-control-allow-origin') == '*': - profile.vulnerabilities.append("CORS allows all origins (wildcard)") + if (profile.cors_headers.get('access-control-allow-origin') == '*' and + profile.cors_headers.get('access-control-allow-credentials', '').lower() == 'true'): + profile.vulnerabilities.append("Wildcard CORS origin cannot authorize credentialed browser requests") # Calculate security level security_score = 0 @@ -285,107 +440,53 @@ def analyze_security_headers(headers: Dict[str, str]) -> SecurityProfile: return profile -def analyze_crawlability(soup: BeautifulSoup, headers: Dict[str, str] = None) -> CrawlabilityProfile: +def analyze_crawlability(soup: BeautifulSoup, headers: Dict[str, str] = None, + user_agent: str = 'googlebot', *, facts: Optional[PageFacts] = None) -> CrawlabilityProfile: """Analyze crawlability and indexability factors.""" profile = CrawlabilityProfile() - headers_lower = {k.lower(): v for k, v in headers.items()} if headers else {} - - # Check robots meta tag - robots_meta = soup.find('meta', attrs={'name': 'robots'}) - if robots_meta: - profile.robots_meta = robots_meta.get('content', '').lower() - - # Parse directives - if 'noindex' in profile.robots_meta: - profile.noindex = True - profile.status = CrawlabilityStatus.BLOCKED - if 'nofollow' in profile.robots_meta: - profile.nofollow = True - if 'noarchive' in profile.robots_meta: - profile.noarchive = True - if 'nosnippet' in profile.robots_meta: - profile.nosnippet = True - - # Parse max-snippet - max_snippet_match = re.search(r'max-snippet:(-?\d+)', profile.robots_meta) - if max_snippet_match: - profile.max_snippet = int(max_snippet_match.group(1)) - - # Parse max-image-preview - max_image_match = re.search(r'max-image-preview:(\w+)', profile.robots_meta) - if max_image_match: - profile.max_image_preview = max_image_match.group(1) - - # Parse unavailable_after - unavailable_match = re.search(r'unavailable_after:\s*([^,]+)', profile.robots_meta) - if unavailable_match: - profile.unavailable_after = unavailable_match.group(1) - - # Check X-Robots-Tag header - x_robots = headers_lower.get('x-robots-tag') - if x_robots: - profile.x_robots_tag = x_robots.lower() - - if 'noindex' in profile.x_robots_tag: - profile.noindex = True - profile.status = CrawlabilityStatus.BLOCKED - if 'nofollow' in profile.x_robots_tag: - profile.nofollow = True + robots = facts.robots if facts is not None else parse_robots(soup, headers, user_agent) + profile.robots_analysis = robots + for attribute in ('noindex', 'nofollow', 'nosnippet', 'noarchive', 'max_snippet'): + setattr(profile, attribute, robots[attribute]) + profile.robots_meta = ', '.join(item['value'] for item in robots['evidence'] if item['source'] == 'meta') or None + profile.x_robots_tag = ', '.join(item['value'] for item in robots['evidence'] if item['source'] == 'header') or None # Check canonical URL - canonical = soup.find('link', attrs={'rel': 'canonical'}) + canonical = (next((record['attrs'] for record in facts.link_tags + if 'canonical' in record['attrs'].get('rel', [])), None) + if facts is not None else soup.find('link', attrs={'rel': 'canonical'})) if canonical: profile.canonical_url = canonical.get('href') - # Check for JavaScript dependency - noscript = soup.find('noscript') - if noscript: - # Check if critical content is in noscript - noscript_text = noscript.get_text(strip=True) - if len(noscript_text) > 100: # Substantial content in noscript - profile.javascript_required = True - profile.status = CrawlabilityStatus.CONDITIONAL - # Check for AJAX crawlability (deprecated but still check) - ajax_meta = soup.find('meta', attrs={'name': 'fragment'}) + ajax_meta = (next((record['attrs'] for record in facts.meta if record['attrs'].get('name') == 'fragment'), None) + if facts is not None else soup.find('meta', attrs={'name': 'fragment'})) if ajax_meta and ajax_meta.get('content') == '!': profile.ajax_crawlable = True - # Check for blocked resources - # Look for robots.txt references in comments - for comment in soup.find_all(string=lambda text: isinstance(text, Comment)): - if 'disallow' in comment.lower() or 'robots.txt' in comment.lower(): - profile.blocked_resources.append(comment[:100]) - - # Determine final status - if profile.noindex: - profile.status = CrawlabilityStatus.BLOCKED - elif profile.javascript_required or profile.ajax_crawlable: - profile.status = CrawlabilityStatus.CONDITIONAL - elif profile.blocked_resources: - profile.status = CrawlabilityStatus.PARTIALLY_BLOCKED - else: - profile.status = CrawlabilityStatus.FULLY_CRAWLABLE + # Robots meta/header directives describe indexing, not robots.txt access. + # Static markup cannot establish whether a rendering engine needs JavaScript. return profile -def analyze_mobile_optimization(soup: BeautifulSoup) -> MobileProfile: - """Comprehensive mobile optimization analysis.""" +def analyze_mobile_optimization(soup: BeautifulSoup, *, facts: Optional[PageFacts] = None) -> MobileProfile: + """Describe markup hints; mobile_readiness is a legacy markup heuristic.""" profile = MobileProfile() # Check viewport - viewport = soup.find('meta', attrs={'name': 'viewport'}) + metas = [record['attrs'] for record in facts.meta] if facts is not None else soup.find_all('meta') + links = [record['attrs'] for record in facts.link_tags] if facts is not None else soup.find_all('link') + viewport = next((meta for meta in metas if re.fullmatch('viewport', str(meta.get('name', '')), re.I)), None) if viewport: - profile.viewport_configured = True - profile.viewport_content = viewport.get('content', '') + profile.viewport_content = str(viewport.get('content', '')).strip() + profile.viewport_configured = bool(profile.viewport_content) # Analyze viewport settings - viewport_lower = profile.viewport_content.lower() - - has_device_width = 'width=device-width' in viewport_lower - has_initial_scale = 'initial-scale=1' in viewport_lower - prevents_zoom = 'user-scalable=no' in viewport_lower or 'maximum-scale=1' in viewport_lower + viewport_values = _viewport_values(profile.viewport_content) + has_device_width = viewport_values.get('width') == 'device-width' + has_initial_scale = viewport_values.get('initial-scale') == '1' + prevents_zoom = _viewport_restricts_zoom(viewport_values) if has_device_width and has_initial_scale and not prevents_zoom: profile.mobile_readiness = MobileReadiness.OPTIMIZED @@ -395,7 +496,7 @@ def analyze_mobile_optimization(soup: BeautifulSoup) -> MobileProfile: profile.mobile_readiness = MobileReadiness.ADAPTIVE # Check responsive images - images = soup.find_all('img') + images = [record['attrs'] for record in facts.images] if facts is not None else soup.find_all('img') profile.total_images = len(images) for img in images: @@ -409,63 +510,51 @@ def analyze_mobile_optimization(soup: BeautifulSoup) -> MobileProfile: ]): profile.responsive_images += 1 - # Check for plugins + # Object/embed may be ordinary images or media, not a plugin dependency. plugins = soup.find_all(['embed', 'object', 'applet']) - profile.uses_plugins = len(plugins) > 0 - - # Check for Flash - for plugin in plugins: - if 'flash' in str(plugin).lower() or '.swf' in str(plugin): - profile.uses_plugins = True - profile.mobile_readiness = MobileReadiness.BROKEN + profile.uses_plugins = any(plugin.name == 'applet' or + str(plugin.get('type', '')).lower() == 'application/x-shockwave-flash' + for plugin in plugins) # Check for AMP amp_html = soup.find('html', attrs={'amp': True}) or soup.find('html', attrs={'⚡': True}) if amp_html: profile.amp_version = 'AMP' - amp_link = soup.find('link', attrs={'rel': 'amphtml'}) + amp_link = next((link for link in links if 'amphtml' in link.get('rel', [])), None) if amp_link: profile.amp_version = 'AMP Available' # Check for PWA indicators - manifest = soup.find('link', attrs={'rel': 'manifest'}) - service_worker = soup.find('script', string=re.compile(r'serviceWorker')) + manifest = next((link for link in links if 'manifest' in link.get('rel', [])), None) + service_worker = (any(re.search(r'serviceWorker', record['text']) for record in facts.scripts) + if facts is not None else soup.find('script', string=re.compile(r'serviceWorker'))) if manifest and service_worker: profile.pwa_ready = True # Check for app links # iOS - ios_app = soup.find('meta', attrs={'name': 'apple-itunes-app'}) + ios_app = next((meta for meta in metas if meta.get('name') == 'apple-itunes-app'), None) if ios_app: profile.app_links['ios'] = ios_app.get('content', '') # Android - android_app = soup.find('link', attrs={'rel': 'alternate', 'href': re.compile(r'android-app://')}) + android_app = next((link for link in links if 'alternate' in link.get('rel', []) + and re.search(r'android-app://', str(link.get('href', '')))), None) if android_app: profile.app_links['android'] = android_app.get('href', '') # Check touch icon - touch_icon = soup.find('link', attrs={'rel': re.compile(r'apple-touch-icon')}) + touch_icon = next((link for link in links if any(re.search(r'apple-touch-icon', rel) + for rel in link.get('rel', []))), None) if touch_icon: profile.app_links['touch_icon'] = touch_icon.get('href', '') - # Check for horizontal scrolling indicators - tables_without_scroll = soup.find_all('table', attrs={'width': re.compile(r'\d{4,}')}) - if tables_without_scroll: - profile.horizontal_scrolling = True - - # Check text size - small_fonts = soup.find_all(style=re.compile(r'font-size:\s*(\d+)(px|pt)')) - for element in small_fonts: - style = element.get('style', '') - size_match = re.search(r'font-size:\s*(\d+)', style) - if size_match: - size = int(size_match.group(1)) - if size < 12: # Less than 12px is too small for mobile - profile.text_readability = False - break + # Layout, touch targets, and text readability require rendered measurements. + profile.horizontal_scrolling = None + profile.text_readability = None + profile.touch_elements_size = None return profile @@ -473,47 +562,27 @@ def analyze_mobile_optimization(soup: BeautifulSoup) -> MobileProfile: def analyze_performance_indicators(headers: Dict[str, str] = None, soup: BeautifulSoup = None) -> PerformanceProfile: """Analyze technical performance indicators.""" profile = PerformanceProfile() - headers_lower = {k.lower(): v for k, v in headers.items()} if headers else {} - - # Detect protocol version - if headers: - # Check for HTTP/2 indicators - if ':status' in headers_lower or 'http2-settings' in headers_lower: - profile.protocol_version = ProtocolVersion.HTTP_2 - # Check for HTTP/3 indicators - elif 'alt-svc' in headers_lower and 'h3' in headers_lower['alt-svc']: - profile.protocol_version = ProtocolVersion.HTTP_3 - else: - # Default to HTTP/1.1 for most cases - profile.protocol_version = ProtocolVersion.HTTP_1_1 + headers_lower = normalized_headers(headers) + # Alt-Svc advertises capabilities; headers do not prove negotiated protocol. # Check compression content_encoding = headers_lower.get('content-encoding', '') - if content_encoding: + if content_encoding and content_encoding.strip().lower() != 'identity': profile.compression_enabled = True profile.compression_type = content_encoding - # Estimate compression ratio based on encoding type - if 'br' in content_encoding: - profile.compression_ratio = 0.8 # Brotli typically 20-30% better than gzip - elif 'gzip' in content_encoding: - profile.compression_ratio = 0.7 # Gzip typically 70% compression - elif 'deflate' in content_encoding: - profile.compression_ratio = 0.65 - # Cache analysis cache_control = headers_lower.get('cache-control', '') if cache_control: profile.cache_control = cache_control # Parse max-age - max_age_match = re.search(r'max-age=(\d+)', cache_control) + max_age_match = re.search(r'max-age\s*=\s*(\d+)', cache_control, re.I) if max_age_match: profile.cache_ttl = int(max_age_match.group(1)) - # Check for no-cache/no-store - if 'no-store' in cache_control or 'no-cache' in cache_control: - profile.cache_ttl = 0 + if 'no-store' in cache_control.lower(): + profile.cache_ttl = None # Check for ETag profile.etag_present = 'etag' in headers_lower @@ -538,20 +607,9 @@ def analyze_performance_indicators(headers: Dict[str, str] = None, soup: Beautif profile.cdn_provider = cdn_name break - # Check for server push (HTTP/2) - if 'link' in headers_lower and 'rel=preload' in headers_lower['link']: - if 'nopush' not in headers_lower['link']: - profile.server_push_enabled = True - - # Check for early hints (103 status) - if headers_lower.get('status') == '103': - profile.early_hints = True - # Connection settings connection = headers_lower.get('connection', '') if 'keep-alive' in connection.lower(): - profile.connection_reuse = True - # Parse Keep-Alive timeout keep_alive = headers_lower.get('keep-alive', '') timeout_match = re.search(r'timeout=(\d+)', keep_alive) @@ -577,7 +635,7 @@ def analyze_url_structure(url: str) -> URLProfile: # Count parameters if parsed.query: - params = parse_qs(parsed.query) + params = parse_qs(parsed.query, keep_blank_values=True) profile.parameters_count = len(params) # Check for tracking parameters @@ -639,19 +697,23 @@ def analyze_url_structure(url: str) -> URLProfile: return profile -def analyze_international_setup(soup: BeautifulSoup, headers: Dict[str, str] = None) -> InternationalProfile: +def analyze_international_setup(soup: BeautifulSoup, headers: Dict[str, str] = None, *, + facts: Optional[PageFacts] = None) -> InternationalProfile: """Analyze international and localization configuration.""" profile = InternationalProfile() - headers_lower = {k.lower(): v for k, v in headers.items()} if headers else {} + headers_lower = normalized_headers(headers) # Check language declaration html_tag = soup.find('html') - if html_tag and html_tag.get('lang'): + language = facts.language if facts is not None else html_tag.get('lang') if html_tag else None + if language is not None and str(language).strip(): profile.language_declared = True - profile.language_code = html_tag.get('lang') + profile.language_code = str(language).strip() # Check for hreflang tags - hreflang_links = soup.find_all('link', attrs={'rel': 'alternate', 'hreflang': True}) + hreflang_links = ([record['attrs'] for record in facts.link_tags + if 'alternate' in record['attrs'].get('rel', []) and 'hreflang' in record['attrs']] + if facts is not None else soup.find_all('link', attrs={'rel': 'alternate', 'hreflang': True})) if hreflang_links: profile.hreflang_configured = True for link in hreflang_links: @@ -661,21 +723,26 @@ def analyze_international_setup(soup: BeautifulSoup, headers: Dict[str, str] = N profile.hreflang_tags[lang] = href # Check charset - charset_meta = soup.find('meta', charset=True) + metas = [record['attrs'] for record in facts.meta] if facts is not None else soup.find_all('meta') + charset_meta = next((meta for meta in metas if 'charset' in (meta if isinstance(meta, dict) else meta.attrs)), None) if charset_meta: profile.charset = charset_meta.get('charset') else: - content_type = soup.find('meta', attrs={'http-equiv': 'Content-Type'}) + content_type = next((meta for meta in metas if re.fullmatch('content-type', str(meta.get('http-equiv', '')), re.I)), None) if content_type: content = content_type.get('content', '') - charset_match = re.search(r'charset=([^;]+)', content) + charset_match = re.search(r'charset\s*=\s*[\"\']?([^;\s\"\']+)', content, re.I) if charset_match: profile.charset = charset_match.group(1).strip() + header_charset = re.search(r'charset\s*=\s*[\"\']?([^;\s\"\']+)', + headers_lower.get('content-type', ''), re.I) + if header_charset: + profile.charset = header_charset.group(1) # Check for geo-targeting meta tags geo_tags = ['geo.region', 'geo.placename', 'geo.position', 'ICBM'] for tag_name in geo_tags: - geo_tag = soup.find('meta', attrs={'name': tag_name}) + geo_tag = next((meta for meta in metas if meta.get('name') == tag_name), None) if geo_tag: profile.geo_targeting = f"{tag_name}: {geo_tag.get('content', '')}" break @@ -695,13 +762,14 @@ def analyze_international_setup(soup: BeautifulSoup, headers: Dict[str, str] = N return profile -def detect_javascript_seo_issues(soup: BeautifulSoup) -> Dict[str, Any]: +def detect_javascript_seo_issues(soup: BeautifulSoup, *, facts: Optional[PageFacts] = None) -> Dict[str, Any]: """Detect JavaScript SEO issues and recommendations.""" issues = { - 'client_side_rendering': False, - 'spa_detected': False, + 'client_side_rendering': None, + 'spa_detected': None, + 'framework_container_detected': False, 'lazy_loaded_content': False, - 'infinite_scroll': False, + 'infinite_scroll': None, 'ajax_navigation': False, 'javascript_redirects': False, 'dynamic_meta_tags': False, @@ -718,8 +786,7 @@ def detect_javascript_seo_issues(soup: BeautifulSoup) -> Dict[str, Any]: for tag, attrs in spa_indicators: if soup.find(tag, attrs): - issues['spa_detected'] = True - issues['client_side_rendering'] = True + issues['framework_container_detected'] = True break # Check for lazy loading indicators @@ -731,15 +798,20 @@ def detect_javascript_seo_issues(soup: BeautifulSoup) -> Dict[str, Any]: ] for tag, attrs in lazy_indicators: - elements = soup.find_all(tag, attrs) if tag else soup.find_all(attrs=attrs) + if tag == 'img' and facts is not None: + elements = [record for record in facts.images + if all(record['attrs'].get(name) == value for name, value in attrs.items())] + else: + elements = soup.find_all(tag, attrs) if tag else soup.find_all(attrs=attrs) if elements: issues['lazy_loaded_content'] = True break # Check for infinite scroll - infinite_scroll_scripts = soup.find_all('script', string=re.compile(r'(IntersectionObserver|infinite.?scroll|waypoint)', re.I)) - if infinite_scroll_scripts: - issues['infinite_scroll'] = True + script_texts = ([record['text'] for record in facts.scripts] if facts is not None + else [script.string or '' for script in soup.find_all('script')]) + infinite_scroll_scripts = [text for text in script_texts if re.search(r'(IntersectionObserver|infinite.?scroll|waypoint)', text, re.I)] + issues['intersection_or_scroll_code_reference'] = bool(infinite_scroll_scripts) # Check for AJAX navigation ajax_nav_patterns = [ @@ -749,356 +821,350 @@ def detect_javascript_seo_issues(soup: BeautifulSoup) -> Dict[str, Any]: r'pjax' ] - for script in soup.find_all('script'): - if script.string: + for text in script_texts: + if text: for pattern in ajax_nav_patterns: - if re.search(pattern, script.string, re.I): + if re.search(pattern, text, re.I): issues['ajax_navigation'] = True break # Check for JavaScript redirects js_redirect_patterns = [ - r'window\.location', - r'location\.href', - r'location\.replace', - r'meta.*refresh' + r'(?:window\.)?location(?:\.href)?\s*=(?!=)', + r'(?:window\.)?location\.(?:replace|assign)\s*\(' ] - for script in soup.find_all('script'): - if script.string: + for text in script_texts: + if text: for pattern in js_redirect_patterns: - if re.search(pattern, script.string): + if re.search(pattern, text): issues['javascript_redirects'] = True break - # Generate recommendations - if issues['spa_detected']: - issues['recommendations'].append("Use server-side rendering (SSR) or pre-rendering for better SEO") - - if issues['infinite_scroll']: - issues['recommendations'].append("Provide paginated alternatives for infinite scroll content") - - if issues['ajax_navigation']: - issues['recommendations'].append("Ensure all navigation states have unique URLs and are crawlable") - - if issues['javascript_redirects']: - issues['recommendations'].append("Replace JavaScript redirects with server-side 301/302 redirects") - + # Advice is produced only by explicit registry evaluations in analyze_technical. return issues -def analyze_technical(soup: BeautifulSoup, url: str, headers: Dict[str, str] = None, status_code: int = 200) -> Dict[str, Any]: - """Advanced technical SEO analysis with comprehensive checks.""" - issues = [] - data = {} - - # Parse URL +def _check_security_rules(collector: RuleCollector, soup: BeautifulSoup, url: str, + headers: Any, html_document: bool, *, facts: Optional[PageFacts] = None) -> None: + """Evaluate declared header configuration without assuming deployment intent.""" + parsed = urlparse(url) + host = parsed.hostname or '' + try: + ipaddress.ip_address(host) + domain = False + except ValueError: + domain = bool(host) + hsts_applicable = parsed.scheme.lower() == 'https' and domain + hsts = _hsts_policy(headers) + hsts_evidence = {**hsts, 'headers_checked': headers is not None, + 'browser_hsts_state_checked': False, 'host': host} + hsts_reason = ('HSTS is a domain policy received over HTTPS; this URL is outside that scope.' + if not hsts_applicable else 'Response headers were not supplied.') + collector.check('security.hsts_missing', not bool(hsts['values']) if headers is not None else None, + hsts_evidence, applicable=hsts_applicable, reason=hsts_reason, + source='response_headers', category='Security', + message='No HSTS header observed on this HTTPS response') + declared_hsts = hsts_applicable and (bool(hsts['values']) if headers is not None else None) + collector.check('security.hsts_invalid', not hsts['valid'] if headers is not None else None, + hsts_evidence, applicable=declared_hsts, + reason=hsts_reason if not hsts_applicable or headers is None else 'No HSTS policy was declared.', + source='response_headers', category='Security', + message='Declared HSTS policy has an invalid max-age or repeated/invalid directives') + collector.check('security.hsts_preload_incomplete', + not hsts['meets_preload_duration'] or not hsts['includesubdomains'], + hsts_evidence, + applicable=hsts_applicable and (hsts['preload'] if headers is not None else None), + reason=hsts_reason if not hsts_applicable or headers is None else 'The policy does not request preloading.', + source='response_headers', category='Security', + message='Declared HSTS preload policy lacks a required duration or includeSubDomains') + + policies = _csp_policies(headers, soup, facts=facts) + policy_evidence = {'policies': policies, 'headers_checked': headers is not None, + 'effective_browser_policy_checked': False} + declared_csp = any(policy['directives'] for policy in policies) + collector.check('security.csp_missing', + not declared_csp if declared_csp or headers is not None else None, + policy_evidence, applicable=html_document, + reason='Response headers were not supplied.' if headers is None else 'This is not an HTML document.', + source='html_and_headers', category='Security', + message='No enforcing CSP declaration observed') + csp_applicable = html_document and (declared_csp if headers is not None or declared_csp else None) + for rule_id, token, message in ( + ('security.csp_unsafe_inline', "'unsafe-inline'", 'CSP script source expression includes unsafe-inline without a nonce or hash'), + ('security.csp_unsafe_eval', "'unsafe-eval'", 'CSP script source expression includes unsafe-eval'), + ('security.csp_wildcard_default', '*', 'CSP default source expression includes a wildcard'), + ): + matches = [] + for index, policy in enumerate(policies): + directives = policy['directives'] + directive = 'default-src' if token == '*' or 'script-src' not in directives else 'script-src' + values = directives.get(directive, []) + if token in [value.lower() for value in values] and not ( + token == "'unsafe-inline'" and _has_nonce_or_hash(values)): + matches.append({'policy_index': index, 'source': policy['source'], + 'directive': directive, 'expression': token}) + collector.check(rule_id, bool(matches), {**policy_evidence, 'matches': matches}, + applicable=csp_applicable, + reason='No enforcing CSP declaration observed, or response headers are unavailable.', + source='html_and_headers', category='Security', message=message) + + xfo_values = header_values(headers, 'X-Frame-Options') + frame_ancestors = [policy['directives']['frame-ancestors'] for policy in policies + if policy['source'] == 'response_header' and 'frame-ancestors' in policy['directives']] + frame_evidence = {'x_frame_options': xfo_values, 'frame_ancestors': frame_ancestors, + 'headers_checked': headers is not None, 'embedding_intent': None} + collector.check('security.frame_policy_missing', + not bool(xfo_values or frame_ancestors) if headers is not None else None, + frame_evidence, applicable=html_document, + reason='Response headers were not supplied.' if headers is None else 'This is not an HTML document.', + source='response_headers', category='Security', + message='No response header declaring a frame embedding restriction observed') + xfo_tokens = [token.strip().upper() for value in xfo_values for token in value.split(',')] + invalid_xfo = bool(xfo_tokens) and ( + any(token not in ('DENY', 'SAMEORIGIN') for token in xfo_tokens) or len(set(xfo_tokens)) > 1) + collector.check('security.xfo_invalid', invalid_xfo, frame_evidence, + applicable=html_document and (bool(xfo_values) if headers is not None else None), + reason='No X-Frame-Options header observed, or response headers are unavailable.', + source='response_headers', category='Security', + message='X-Frame-Options has an unsupported or conflicting value') + origins = [value.strip() for value in header_values(headers, 'Access-Control-Allow-Origin')] + credentials = [value.strip() for value in header_values(headers, 'Access-Control-Allow-Credentials')] + collector.check('security.cors_wildcard_credentials', + '*' in origins and 'true' in credentials if headers is not None else None, + {'allow_origin': origins, 'allow_credentials': credentials, + 'credentialed_request_tested': False, 'headers_checked': headers is not None}, + reason='Response headers were not supplied.', source='response_headers', category='Security', + message='Wildcard CORS origin cannot authorize credentialed browser requests') + + +def _http_resource_references(soup: BeautifulSoup, url: str, *, + facts: Optional[PageFacts] = None) -> List[Dict[str, str]]: + references = [] + base = facts.base_url if facts is not None else document_base_url(soup, url) + shared = ({'img': facts.images, 'script': facts.scripts, 'link': facts.link_tags} + if facts is not None else {}) + for tag_name, attr_name in ( + ('img', 'src'), ('script', 'src'), ('link', 'href'), ('iframe', 'src'), + ('source', 'src'), ('video', 'src'), ('video', 'poster'), ('audio', 'src'), + ('embed', 'src'), ('object', 'data'), + ): + elements = [record['attrs'] for record in shared[tag_name]] if tag_name in shared else soup.find_all(tag_name) + for element in elements: + if tag_name == 'link' and not any(str(rel).lower() in ('stylesheet', 'preload', 'icon') + for rel in element.get('rel', [])): + continue + raw = str(element.get(attr_name, '')).strip() + if not raw: + continue + resolved = resolve_url(raw, base) + if resolved and urlparse(resolved).scheme == 'http': + references.append({'type': tag_name, 'attribute': attr_name, 'url': resolved}) + return references + + +def analyze_technical(soup: BeautifulSoup, url: str, headers: Dict[str, str] = None, + status_code: int = 200, user_agent: Optional[str] = None, *, + facts: Optional[PageFacts] = None) -> Dict[str, Any]: + """Evaluate observed technical facts; retain unmeasured runtime properties as unknown.""" + facts = ensure_page_facts(soup, url, headers=headers, user_agent=user_agent, facts=facts) + headers, user_agent = facts.headers, facts.user_agent + collector = RuleCollector('technical') parsed_url = urlparse(url) - - # HTTPS check - data['https'] = parsed_url.scheme == 'https' - if not data['https']: - issues.append(create_issue('Security', 'critical', 'Site not using HTTPS')) - - # Status code analysis - data['status_code'] = status_code - if status_code >= 500: - issues.append(create_issue('Availability', 'critical', f'Server error status code {status_code}')) - elif status_code >= 400: - issues.append(create_issue('Availability', 'critical', f'Client error status code {status_code}')) - elif status_code >= 300: - if status_code == 301: - issues.append(create_issue('Redirects', 'notice', 'Permanent redirect (301)')) - elif status_code == 302: - issues.append(create_issue('Redirects', 'warning', 'Temporary redirect (302) - consider using 301 for SEO')) - else: - issues.append(create_issue('Redirects', 'warning', f'Redirect status {status_code}')) - - # Security analysis + scheme = parsed_url.scheme.lower() + host = parsed_url.hostname or '' + try: + loopback = ipaddress.ip_address(host).is_loopback + except ValueError: + loopback = host.lower().rstrip('.') == 'localhost' or host.lower().rstrip('.').endswith('.localhost') + content_types = header_values(headers, 'Content-Type') + media_type = content_types[0].split(';', 1)[0].strip().lower() if content_types else None + html_document = (media_type in ('text/html', 'application/xhtml+xml') if media_type else + not facts.is_xml or bool(facts.tag_counts.get('html'))) + html_syntax = html_document and not facts.is_xml and media_type != 'application/xhtml+xml' + data = {'https': scheme == 'https', 'status_code': status_code} + collector.check('security.https_missing', scheme == 'http', + {'scheme': scheme, 'host': host, 'loopback': loopback}, + applicable=scheme in ('http', 'https') and not loopback, + reason='The URL is outside the public HTTP/HTTPS document scope or uses local loopback.', + source='url', category='Security', message='Document URL uses HTTP') + measured_status = type(status_code) is int and 100 <= status_code <= 599 + status_evidence = {'status_code': status_code, 'status_observed': measured_status} + for rule_id, failed, message in ( + ('technical.http_server_error', 500 <= status_code <= 599 if measured_status else None, 'HTTP server error response'), + ('technical.http_client_error', 400 <= status_code <= 499 if measured_status else None, 'HTTP client error response'), + ('technical.http_redirect', status_code in (300, 301, 302, 303, 305, 307, 308) if measured_status else None, + 'HTTP redirect response; verify destination and intended permanence'), + ): + collector.check(rule_id, failed, status_evidence, reason='No valid HTTP response status was supplied.', + source='response_status', category='Availability', message=message) + security_profile = analyze_security_headers(headers) + hsts = _hsts_policy(headers) data['security'] = { - 'level': security_profile.security_level.value, - 'https': data['https'], - 'hsts': security_profile.hsts_enabled, - 'hsts_max_age': security_profile.hsts_max_age, - 'csp': security_profile.csp_enabled, - 'xfo': security_profile.xfo_enabled, - 'x_content_type_options': security_profile.x_content_type_options, - 'vulnerabilities': security_profile.vulnerabilities[:5] # Limit to top 5 + 'level': None, 'level_status': 'not_assessed', 'https': data['https'], + 'header_configuration_level': security_profile.security_level.value if headers is not None else None, + 'header_configuration_level_method': 'legacy_header_presence_heuristic', + 'hsts': bool(hsts['values']) if headers is not None else None, + 'hsts_max_age': hsts['max_age'], + 'csp': security_profile.csp_enabled if headers is not None else None, + 'xfo': security_profile.xfo_enabled if headers is not None else None, + 'x_content_type_options': security_profile.x_content_type_options if headers is not None else None, + 'vulnerabilities': [], 'vulnerabilities_status': 'not_tested', + 'source': 'response_headers' if headers is not None else 'not_measured', + 'scope': 'header_configuration', } - - # Report security issues - if not security_profile.hsts_enabled and data['https']: - issues.append(create_issue('Security', 'warning', 'Missing HSTS header for HTTPS site')) - - if security_profile.hsts_enabled and security_profile.hsts_max_age < 31536000: - issues.append(create_issue('Security', 'notice', - f'HSTS max-age too short ({security_profile.hsts_max_age}s), recommend 31536000')) - - if not security_profile.csp_enabled: - issues.append(create_issue('Security', 'warning', 'Missing Content Security Policy')) - - if not security_profile.xfo_enabled: - issues.append(create_issue('Security', 'notice', 'Missing X-Frame-Options header')) - - for vulnerability in security_profile.vulnerabilities[:3]: - issues.append(create_issue('Security', 'warning', vulnerability)) - - if security_profile.security_level == SecurityLevel.CRITICAL: - issues.append(create_issue('Security', 'critical', 'Critical security issues detected')) - - # Crawlability analysis - crawl_profile = analyze_crawlability(soup, headers) + _check_security_rules(collector, soup, url, headers, html_document, facts=facts) + + crawl_profile = analyze_crawlability(soup, headers, user_agent, facts=facts) + robots = crawl_profile.robots_analysis data['crawlability'] = { - 'status': crawl_profile.status.value, - 'noindex': crawl_profile.noindex, + 'status': crawl_profile.status.value, 'noindex': crawl_profile.noindex, 'nofollow': crawl_profile.nofollow, - 'canonical': crawl_profile.canonical_url, - 'javascript_required': crawl_profile.javascript_required + 'canonical': resolve_url(crawl_profile.canonical_url, facts.base_url) if crawl_profile.canonical_url else None, + 'javascript_required': None, 'indexability': robots['indexability'], + 'robots_analysis': robots, 'crawl_access': 'unknown', } - - if crawl_profile.noindex: - issues.append(create_issue('Crawlability', 'critical', 'Page is set to noindex')) - - if crawl_profile.nofollow: - issues.append(create_issue('Crawlability', 'warning', 'Page is set to nofollow')) - - if crawl_profile.javascript_required: - issues.append(create_issue('Crawlability', 'warning', 'Content requires JavaScript for crawling')) - - # Mobile optimization analysis - mobile_profile = analyze_mobile_optimization(soup) + for directive in ('noindex', 'nofollow', 'nosnippet'): + observed = robots[directive] + collector.check('robots.' + directive, observed if observed or headers is not None else None, + {'directives': robots['directives'], 'declarations': robots['evidence'], + 'headers_checked': headers is not None, 'user_agent': user_agent, + 'publisher_intent': None}, + reason='No restriction was observed in markup; response headers were not supplied.', + source='html_and_headers', category='Crawlability', + message='An applicable ' + directive + ' directive is declared') + + mobile_profile = analyze_mobile_optimization(soup, facts=facts) + viewports = [str(meta.get('content', '')).strip() for record in facts.meta for meta in [record['attrs']] + if str(meta.get('name', '')).strip().lower() == 'viewport'] + nonempty_viewports = [content for content in viewports if content] + viewport_settings = [_viewport_values(content) for content in nonempty_viewports] + viewport_evidence = {'declarations': viewports, 'settings': viewport_settings, 'rendered_layout_checked': False} + collector.check('mobile.viewport_missing', not bool(nonempty_viewports), viewport_evidence, + applicable=html_document, reason='This is not an HTML document.', + category='Mobile', message='No nonempty viewport meta declaration observed') + collector.check('mobile.viewport_zoom_disabled', any(_viewport_restricts_zoom(settings) for settings in viewport_settings), + viewport_evidence, applicable=html_document and bool(nonempty_viewports), + reason='No viewport declaration applies to this document.', category='Mobile', + message='An authored viewport setting restricts user zoom') data['mobile'] = { - 'readiness': mobile_profile.mobile_readiness.value, - 'viewport_configured': mobile_profile.viewport_configured, + 'readiness': None, 'layout_status': 'not_measured', 'source': 'html_attributes', + 'viewport_configured': bool(nonempty_viewports), 'responsive_images': f"{mobile_profile.responsive_images}/{mobile_profile.total_images}", - 'amp': mobile_profile.amp_version, - 'pwa_ready': mobile_profile.pwa_ready + 'responsive_images_method': 'markup_hints', + 'amp': mobile_profile.amp_version, 'amp_status': 'markup_hint', + 'pwa_ready': None, 'pwa_status': 'not_tested', + 'pwa_markup_indicators': mobile_profile.pwa_ready, } - - if not mobile_profile.viewport_configured: - issues.append(create_issue('Mobile', 'critical', 'Missing viewport meta tag')) - elif mobile_profile.viewport_content and 'user-scalable=no' in mobile_profile.viewport_content: - issues.append(create_issue('Mobile', 'warning', 'Viewport prevents user zooming (accessibility issue)')) - - if mobile_profile.uses_plugins: - issues.append(create_issue('Mobile', 'critical', 'Uses plugins not supported on mobile')) - - if mobile_profile.mobile_readiness == MobileReadiness.DESKTOP_ONLY: - issues.append(create_issue('Mobile', 'critical', 'Site not optimized for mobile')) - - if mobile_profile.horizontal_scrolling: - issues.append(create_issue('Mobile', 'warning', 'Content causes horizontal scrolling on mobile')) - - # Performance indicators + perf_profile = analyze_performance_indicators(headers, soup) data['performance'] = { 'protocol': perf_profile.protocol_version.value, 'compression': perf_profile.compression_type, - 'cache_ttl': perf_profile.cache_ttl, - 'cdn': perf_profile.cdn_provider or 'None detected', - 'etag': perf_profile.etag_present, - 'server_push': perf_profile.server_push_enabled + 'cache_ttl': perf_profile.cache_ttl, 'cdn': perf_profile.cdn_provider or 'None detected', + 'cdn_status': 'header_hint' if perf_profile.cdn_provider else 'not_established', + 'etag': perf_profile.etag_present if headers is not None else None, + 'server_push': None, 'source': 'response_headers' if headers is not None else 'not_measured', + 'protocol_status': 'unknown', 'transfer_savings': None, } - - if not perf_profile.compression_enabled: - issues.append(create_issue('Performance', 'warning', 'Content not compressed')) - - if perf_profile.cache_ttl == 0: - issues.append(create_issue('Performance', 'warning', 'No caching configured')) - elif perf_profile.cache_ttl < 3600: # Less than 1 hour - issues.append(create_issue('Performance', 'notice', f'Short cache TTL ({perf_profile.cache_ttl}s)')) - - if not perf_profile.cdn_detected: - issues.append(create_issue('Performance', 'notice', 'No CDN detected')) - - if perf_profile.protocol_version in [ProtocolVersion.HTTP_1_0, ProtocolVersion.HTTP_1_1]: - issues.append(create_issue('Performance', 'notice', 'Not using HTTP/2 or HTTP/3')) - - # URL structure analysis + has_body = measured_status and status_code >= 200 and status_code not in (204, 205, 304) + collector.check('technical.http_compression', + not perf_profile.compression_enabled if headers is not None else None, + {'content_encoding': header_values(headers, 'Content-Encoding'), + 'headers_checked': headers is not None, 'negotiation_checked': False, 'transfer_savings': None}, + applicable=html_document and (has_body if measured_status else None), + reason='Response headers or a body-bearing HTML response were not observed.', + source='response_headers', category='Performance', + message='No non-identity Content-Encoding observed for this response') + url_profile = analyze_url_structure(url) data['url'] = { - 'length': url_profile.length, - 'depth': url_profile.depth, - 'parameters': url_profile.parameters_count, - 'is_clean': url_profile.is_clean, - 'is_seo_friendly': url_profile.is_seo_friendly + 'length': url_profile.length, 'depth': url_profile.depth, 'parameters': url_profile.parameters_count, + 'is_clean': url_profile.is_clean, 'is_clean_method': 'legacy_url_shape_heuristic', + 'is_seo_friendly': None, 'quality_status': 'not_assessed', } - - if url_profile.length > 100: - issues.append(create_issue('URL Structure', 'warning', f'URL too long ({url_profile.length} chars)')) - - if url_profile.depth > 4: - issues.append(create_issue('URL Structure', 'notice', f'Deep URL structure (depth: {url_profile.depth})')) - - if url_profile.has_session_id: - issues.append(create_issue('URL Structure', 'critical', 'Session ID in URL')) - - if url_profile.uses_underscores: - issues.append(create_issue('URL Structure', 'notice', 'URL uses underscores instead of hyphens')) - - if url_profile.uses_uppercase: - issues.append(create_issue('URL Structure', 'warning', 'URL contains uppercase characters')) - - if not url_profile.is_seo_friendly: - issues.append(create_issue('URL Structure', 'warning', 'URL is not SEO-friendly')) - - # International setup - intl_profile = analyze_international_setup(soup, headers) + session_names = sorted(name for name in parse_qs(parsed_url.query, keep_blank_values=True) + if name.lower() in ('sessionid', 'session', 'sid', 'phpsessid', 'jsessionid')) + collector.check('technical.url_session_parameter', bool(session_names), + {'parameter_names': session_names, 'parameter_meanings_checked': False}, + source='url', category='URL Structure', message='Query uses a session-like parameter name') + + intl_profile = analyze_international_setup(soup, headers, facts=facts) data['international'] = { - 'language': intl_profile.language_code, - 'charset': intl_profile.charset, - 'hreflang_count': len(intl_profile.hreflang_tags), - 'geo_targeting': intl_profile.geo_targeting + 'language': intl_profile.language_code, 'charset': intl_profile.charset, + 'hreflang_count': len(intl_profile.hreflang_tags), 'geo_targeting': intl_profile.geo_targeting, } - - if not intl_profile.language_declared: - issues.append(create_issue('International', 'warning', 'Missing language declaration')) - - if intl_profile.charset and intl_profile.charset.lower() != 'utf-8': - issues.append(create_issue('International', 'warning', f'Non-UTF-8 charset: {intl_profile.charset}')) - - # JavaScript SEO issues - js_issues = detect_javascript_seo_issues(soup) + human_text = bool(facts.text) + collector.check('language.missing', not intl_profile.language_declared, + {'language': intl_profile.language_code, 'human_readable_text_observed': human_text}, + applicable=html_document and human_text, + reason='No human-readable HTML document content was observed.', + category='International', message='Primary document language is not declared') + charset = str(intl_profile.charset).strip() if intl_profile.charset else None + collector.check('seo.charset_non_utf8', charset.lower() not in ('utf-8', 'utf8') if charset else None, + {'declared_charset': charset, 'headers_checked': headers is not None, + 'original_bytes_checked': False}, applicable=html_document, + reason='No encoding declaration was observed; original bytes and byte-order marks were not checked.', + source='html_and_headers', category='International', + message='A non-UTF-8 character encoding is declared') + + js_issues = detect_javascript_seo_issues(soup, facts=facts) + js_issues['recommendations'] = [] + references = [] + for index, script in enumerate(facts.scripts): + if script['text']: + match = re.search(r'(?:window\.)?location(?:\.href)?\s*=(?!=)|(?:window\.)?location\.(?:replace|assign)\s*\(', + script['text']) + if match: + references.append({'script_index': index, 'expression': match.group(0)}) + collector.check('technical.javascript_redirect_reference', bool(references), + {'references': references, 'executed': None}, applicable=html_document, + reason='This is not an HTML document.', confidence='low', category='JavaScript SEO', + message='Inline script text references a location change; execution is unverified') data['javascript_seo'] = js_issues - - if js_issues['spa_detected']: - issues.append(create_issue('JavaScript SEO', 'warning', 'Single Page Application detected')) - - if js_issues['infinite_scroll']: - issues.append(create_issue('JavaScript SEO', 'notice', 'Infinite scroll detected')) - - if js_issues['javascript_redirects']: - issues.append(create_issue('JavaScript SEO', 'warning', 'JavaScript redirects detected')) - - # Mixed content check (for HTTPS sites) - if data['https']: - mixed_content = [] - - # Check various resource types - resource_tags = [ - ('img', 'src'), - ('script', 'src'), - ('link', 'href'), - ('iframe', 'src'), - ('source', 'src'), - ('video', 'src'), - ('audio', 'src'), - ('embed', 'src'), - ('object', 'data') - ] - - for tag_name, attr_name in resource_tags: - for element in soup.find_all(tag_name): - resource_url = element.get(attr_name, '') - if resource_url.startswith('http://'): - mixed_content.append({ - 'type': tag_name, - 'url': resource_url[:100] # Truncate long URLs - }) - - if mixed_content: - issues.append(create_issue('Security', 'critical', - f'Mixed content: {len(mixed_content)} insecure resources on HTTPS page')) - data['mixed_content'] = mixed_content[:10] # Limit to first 10 - - # Check for deprecated technologies - deprecated_found = [] - - # Flash - if soup.find_all(['embed', 'object'], attrs={'type': 'application/x-shockwave-flash'}): - deprecated_found.append('Flash') - - # Frameset - if soup.find('frameset'): - deprecated_found.append('Frameset') - - # Font tag - if soup.find('font'): - deprecated_found.append('Font tags') - - # Center tag - if soup.find('center'): - deprecated_found.append('Center tags') - - if deprecated_found: - issues.append(create_issue('Compatibility', 'warning', - f'Deprecated technologies: {", ".join(deprecated_found)}')) - - # Check DOCTYPE - doctype = None - for item in soup.contents: - if str(item).startswith('' not in doctype.lower(): - issues.append(create_issue('HTML Standards', 'notice', 'Non-HTML5 DOCTYPE')) - - # Check for structured data - json_ld = soup.find_all('script', type='application/ld+json') - microdata = soup.find_all(attrs={'itemscope': True}) - rdfa = soup.find_all(attrs={'typeof': True}) - + + http_references = _http_resource_references(soup, url, facts=facts) if data['https'] else [] + collector.check('technical.http_resource_reference', bool(http_references), + {'count': len(http_references), 'references': http_references[:20], + 'references_truncated': len(http_references) > 20, + 'effective_requests_checked': False}, + applicable=html_document and data['https'], + reason='Mixed-content checks apply to HTTPS HTML documents.', category='Security', + message='HTML declares HTTP subresource URLs on an HTTPS document') + data['mixed_content'] = http_references[:10] + data['mixed_content_status'] = 'source_references_only' + + tag_counts = facts.tag_counts + obsolete_counts = {tag: tag_counts.get(tag, 0) for tag in ('applet', 'frameset', 'frame', 'font', 'center')} + obsolete_counts = {tag: count for tag, count in obsolete_counts.items() if count} + flash = soup.find_all(['embed', 'object'], attrs={'type': re.compile(r'^application/x-shockwave-flash$', re.I)}) + if flash: + obsolete_counts['flash_mime_declaration'] = len(flash) + collector.check('technical.deprecated_elements', bool(obsolete_counts), + {'elements': obsolete_counts, 'rendered_behavior_checked': False}, + applicable=html_document, reason='This is not an HTML document.', category='Compatibility', + message='Obsolete HTML elements or legacy plugin markup observed') + doctype = facts.doctype[0] if facts.doctype else None + doctype_evidence = {'doctype': doctype, 'media_type': media_type, + 'parser_is_xml': facts.is_xml, 'rendering_mode_checked': False} + collector.check('html.doctype_missing', not bool(doctype), doctype_evidence, applicable=html_syntax, + reason='An HTML doctype is not required for XML/XHTML syntax.', category='HTML Standards', + message='Missing HTML DOCTYPE declaration') + collector.check('html.doctype_legacy', bool(doctype and doctype.strip().lower() != 'html'), + doctype_evidence, applicable=html_syntax and bool(doctype), + reason='No doctype in an HTML-syntax document was observed.', category='HTML Standards', + message='Legacy HTML doctype declaration observed') data['structured_data_types'] = { - 'json_ld': len(json_ld), - 'microdata': len(microdata), - 'rdfa': len(rdfa) + 'json_ld': sum(record['attrs'].get('type') == 'application/ld+json' for record in facts.scripts), + 'microdata': len(soup.find_all(attrs={'itemscope': True})), + 'rdfa': len(soup.find_all(attrs={'typeof': True})), } - - # Calculate technical score - score = 100 - - for issue in issues: - if issue['severity'] == 'critical': - score -= 15 - elif issue['severity'] == 'warning': - score -= 7 - elif issue['severity'] == 'notice': - score -= 3 - - # Additional scoring based on profiles - if security_profile.security_level in [SecurityLevel.POOR, SecurityLevel.CRITICAL]: - score -= 10 - - if crawl_profile.status == CrawlabilityStatus.BLOCKED: - score -= 20 - - if mobile_profile.mobile_readiness in [MobileReadiness.DESKTOP_ONLY, MobileReadiness.BROKEN]: - score -= 15 - - if not url_profile.is_seo_friendly: - score -= 5 - - score = max(0, min(100, score)) - - # Generate recommendations - recommendations = [] - - if not data['https']: - recommendations.append("Priority: Migrate to HTTPS immediately for security and SEO") - - if security_profile.security_level in [SecurityLevel.POOR, SecurityLevel.CRITICAL]: - recommendations.append("Priority: Implement security headers (HSTS, CSP, X-Frame-Options)") - - if mobile_profile.mobile_readiness == MobileReadiness.DESKTOP_ONLY: - recommendations.append("Priority: Implement responsive design for mobile-first indexing") - - if perf_profile.protocol_version == ProtocolVersion.HTTP_1_1: - recommendations.append("Upgrade to HTTP/2 or HTTP/3 for better performance") - - if not perf_profile.cdn_detected: - recommendations.append("Consider using a CDN for global performance") - - if js_issues['spa_detected']: - recommendations.append("Implement server-side rendering for SPA SEO") - + issues = collector.issues + recommendations = recommendations_for(issues) data['recommendations'] = recommendations - - return { - 'score': score, - 'issues': issues, - 'data': data - } \ No newline at end of file + data['javascript_seo']['recommendations'] = recommendations_for( + [issue for issue in issues if issue['rule_id'] == 'technical.javascript_redirect_reference']) + return {'score': score_findings(issues, owner='technical'), 'issues': issues, 'data': data, + 'recommendations': recommendations, 'rule_results': collector.results, + 'rule_coverage': collector.coverage, 'coverage': collector.coverage} diff --git a/tfq0seo/benchmark.py b/tfq0seo/benchmark.py index c9996e3..1591b80 100644 --- a/tfq0seo/benchmark.py +++ b/tfq0seo/benchmark.py @@ -1,282 +1,533 @@ -"""Benchmark script for tfq0seo performance testing.""" +"""Outcome-aware benchmarks; the default workload uses offline HTML fixtures.""" +import argparse import asyncio -import time +import hashlib import json +import math +import platform +import sys +import threading +import time +from datetime import datetime, timezone +from importlib import metadata as importlib_metadata +from pathlib import Path +from statistics import median +from typing import Any, Dict, Optional + import psutil -from datetime import datetime -from typing import Dict, Any +from bs4 import BeautifulSoup from .core.app import SEOAnalyzer from .core.config import Config +from .core.models import SCHEMA_VERSION +from .page_facts import FACTS_VERSION +from .rules import RULESET_VERSION, SCORING_VERSION +from . import __version__ + + +SCENARIOS = ('basic', 'content-heavy', 'link-dense', 'mixed') +DIRECT_DEPENDENCIES = ('aiohttp', 'beautifulsoup4', 'click', 'jinja2', 'rich', 'textstat', + 'validators', 'pyyaml', 'python-dateutil', 'urllib3', 'psutil') +OPTIONAL_DEPENDENCIES = ('lxml', 'openpyxl', 'pandas') + + +def _installed_version(name): + try: + return importlib_metadata.version(name) + except importlib_metadata.PackageNotFoundError: + return None -async def benchmark_single_page(url: str = "https://example.com") -> Dict[str, Any]: - """Benchmark single page analysis.""" - print(f"🔍 Benchmarking single page analysis: {url}") - - config = Config() - analyzer = SEOAnalyzer(config) - - # Memory before - process = psutil.Process() - mem_before = process.memory_info().rss / 1024 / 1024 # MB - - # Time the analysis - start_time = time.time() - result = await analyzer.analyze_url(url) - end_time = time.time() - - # Memory after - mem_after = process.memory_info().rss / 1024 / 1024 # MB - - duration = end_time - start_time - mem_used = mem_after - mem_before - - benchmark = { - 'type': 'single_page', - 'url': url, - 'duration_seconds': round(duration, 3), - 'memory_used_mb': round(mem_used, 2), - 'score': result.get('overall_score', 0) if result else 0, - 'issues_found': len(result.get('issues', [])) if result else 0, - 'timestamp': datetime.now().isoformat() +def _cpu_model(): + if sys.platform == 'win32': + try: + import winreg + with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'HARDWARE\DESCRIPTION\System\CentralProcessor\0') as key: + return winreg.QueryValueEx(key, 'ProcessorNameString')[0].strip() + except OSError: + pass + cpuinfo = Path('/proc/cpuinfo') + if sys.platform.startswith('linux') and cpuinfo.is_file(): + for line in cpuinfo.read_text(encoding='utf-8').splitlines(): + if line.lower().startswith('model name'): + return line.partition(':')[2].strip() + return platform.processor() or None + + +def _source_fingerprint(): + """Identify the measured Python implementation without recording local paths.""" + root = Path(__file__).resolve().parent + digest = hashlib.sha256() + count = 0 + for path in sorted(root.rglob('*.py')): + digest.update(path.relative_to(root).as_posix().encode('utf-8') + b'\0') + digest.update(path.read_bytes()) + count += 1 + return {'algorithm': 'sha256', 'scope': 'package Python source paths and bytes', + 'file_count': count, 'digest': digest.hexdigest()} + + +def _environment(): + return { + 'os': {'system': platform.system(), 'release': platform.release(), 'version': platform.version()}, + 'architecture': platform.machine(), 'cpu_model': _cpu_model(), + 'cpu_count': psutil.cpu_count(), 'physical_cpu_count': psutil.cpu_count(logical=False), + 'memory_total_gb': round(psutil.virtual_memory().total / (1024 ** 3), 2), + 'python_version': sys.version, 'python_implementation': platform.python_implementation(), + 'package_version': __version__, 'installed_distribution_version': _installed_version('tfq0seo'), + 'schema_version': SCHEMA_VERSION, 'ruleset_version': RULESET_VERSION, + 'scoring_version': SCORING_VERSION, 'facts_version': FACTS_VERSION, + 'direct_dependencies': {name: _installed_version(name) for name in DIRECT_DEPENDENCIES}, + 'optional_dependencies': {name: _installed_version(name) for name in OPTIONAL_DEPENDENCIES}, + 'readability_dependencies': {name: _installed_version(name) for name in ('nltk', 'pyphen', 'cmudict')}, + 'source_fingerprint': _source_fingerprint(), + 'timestamp': datetime.now(timezone.utc).isoformat(), } - - print(f"✅ Completed in {duration:.2f}s, Memory: {mem_used:.2f}MB") - print(f" Score: {benchmark['score']:.1f}/100, Issues: {benchmark['issues_found']}") - - return benchmark - - -async def benchmark_crawl(start_url: str = "https://example.com", max_pages: int = 10) -> Dict[str, Any]: - """Benchmark website crawl.""" - print(f"🕷️ Benchmarking crawl: {start_url} (max {max_pages} pages)") - - config = Config() - config.crawler.max_pages = max_pages - config.crawler.max_concurrent = 10 - analyzer = SEOAnalyzer(config) - - # Memory before - process = psutil.Process() - mem_before = process.memory_info().rss / 1024 / 1024 # MB - - # Time the crawl - start_time = time.time() - pages_analyzed = 0 - - async for result in analyzer.crawl_site(start_url): - pages_analyzed += 1 - if pages_analyzed % 5 == 0: - print(f" Analyzed {pages_analyzed} pages...") - - end_time = time.time() - - # Memory after - mem_after = process.memory_info().rss / 1024 / 1024 # MB - - duration = end_time - start_time - mem_used = mem_after - mem_before - pages_per_second = pages_analyzed / duration if duration > 0 else 0 - - benchmark = { - 'type': 'crawl', - 'start_url': start_url, - 'pages_analyzed': pages_analyzed, - 'max_pages': max_pages, - 'duration_seconds': round(duration, 3), - 'memory_used_mb': round(mem_used, 2), - 'pages_per_second': round(pages_per_second, 2), - 'avg_time_per_page': round(duration / pages_analyzed, 3) if pages_analyzed > 0 else 0, - 'timestamp': datetime.now().isoformat() + + +class _MemorySampler: + """Sample process RSS, retaining an observed maximum rather than a true peak.""" + + def __init__(self, interval: float = 0.05): + self.interval = interval + self.process = psutil.Process() + self.samples = [] + self.stop = threading.Event() + self.thread = threading.Thread(target=self._poll, daemon=True) + + def _sample(self): + self.samples.append(self.process.memory_info().rss / (1024 * 1024)) + + def _poll(self): + while not self.stop.wait(self.interval): + self._sample() + + def __enter__(self): + self._sample() + self.thread.start() + return self + + def __exit__(self, *args): + self.stop.set() + self.thread.join() + self._sample() + + def metrics(self): + delta = self.samples[-1] - self.samples[0] + return { + 'memory_rss_start_mb': round(self.samples[0], 3), + 'memory_rss_end_mb': round(self.samples[-1], 3), + 'memory_rss_delta_mb': round(delta, 3), + 'memory_sampled_peak_mb': round(max(self.samples), 3), + 'memory_sample_count': len(self.samples), + 'memory_sampling_interval_seconds': self.interval, + 'memory_measurement': 'Sampled process RSS; allocations between samples may be missed.', + # Retained for callers of the original benchmark API; this is a delta. + 'memory_used_mb': round(delta, 3), + } + + +def _outcome(result): + if not isinstance(result, dict) or not result or result.get('error') or result.get('status') == 'error': + return 'failed' + if result.get('skipped') or result.get('status') == 'skipped': + return 'skipped' + if result.get('status') == 'partial' or result.get('analyzer_errors'): + return 'partial' + return 'successful' if result.get('status') == 'complete' or 'overall_score' in result else 'failed' + + +async def _measure(kind, operation, metadata, expected_results=None): + """Measure an operation that records every observed page outcome.""" + pages = [] + operation_error = None + details = {} + with _MemorySampler() as memory: + started = time.perf_counter() + try: + details = await operation(pages.append) or {} + except Exception as exc: + operation_error = f'{type(exc).__name__}: {exc}' + duration = time.perf_counter() - started + + counts = {name: 0 for name in ('successful', 'partial', 'failed', 'skipped')} + for page in pages: + counts[_outcome(page)] += 1 + complete_count = counts['successful'] + missing = max(0, expected_results - len(pages)) if expected_results is not None else 0 + if operation_error or counts['failed'] or not pages or details.get('report_status') in ('error', 'failed'): + status = 'failed' + elif counts['partial'] or counts['skipped'] or missing or details.get('report_status') == 'partial': + status = 'partial' + else: + status = 'complete' + errors = [page.get('error') for page in pages if isinstance(page, dict) and page.get('error')] + for page in pages: + if isinstance(page, dict): + errors.extend(page.get('analyzer_errors', {}).values()) + if operation_error: + errors.append(operation_error) + result = { + 'type': kind, **metadata, **details, + 'status': status, + 'successful_pages': complete_count, + 'partial_pages': counts['partial'], + 'failed_pages': counts['failed'], + 'skipped_pages': counts['skipped'], + 'observed_results': len(pages), + 'missing_results': missing, + # These legacy names now count only complete analyses. + 'pages_analyzed': complete_count, + 'pages_per_second': complete_count / duration if duration > 0 else None, + 'avg_time_per_page': duration / complete_count if complete_count else None, + 'duration_seconds': duration, + 'clock': 'perf_counter', + **memory.metrics(), + 'errors': errors, + 'timestamp': datetime.now(timezone.utc).isoformat(), } - - print(f"✅ Completed {pages_analyzed} pages in {duration:.2f}s") - print(f" Speed: {pages_per_second:.2f} pages/sec, Memory: {mem_used:.2f}MB") - - return benchmark + if len(pages) == 1 and isinstance(pages[0], dict): + result['score'] = pages[0].get('overall_score') + result['issues_found'] = len(pages[0].get('issues', [])) + rate = result['pages_per_second'] + rate_text = f'{rate:.2f}' if rate is not None else 'unavailable' + print(f'{kind}: {status}; {complete_count} complete, {counts["partial"]} partial, ' + f'{counts["failed"]} failed, {counts["skipped"]} skipped; ' + f'{duration:.3f}s, {rate_text} complete pages/sec') + for error in errors: + print(f' {error}') + return result + + +async def benchmark_single_page(url: str = 'https://example.com') -> Dict[str, Any]: + """Benchmark one explicitly requested network analysis.""" + async def operation(record): + record(await SEOAnalyzer(Config()).analyze_url(url)) + return await _measure('single_page', operation, {'url': url}, expected_results=1) + + +async def benchmark_crawl(start_url: str = 'https://example.com', max_pages: int = 10) -> Dict[str, Any]: + """Benchmark a network crawl, counting incomplete and failed outcomes separately.""" + config = Config.from_dict({'crawler': {'max_pages': max_pages, 'max_concurrent': 10}}) + + async def operation(record): + async for result in SEOAnalyzer(config).crawl_site(start_url): + record(result) + return await _measure('crawl', operation, {'start_url': start_url, 'max_pages': max_pages}) async def benchmark_batch(urls: list, concurrent: int = 10) -> Dict[str, Any]: - """Benchmark batch URL analysis.""" - print(f"📦 Benchmarking batch analysis: {len(urls)} URLs") - - config = Config() - config.crawler.max_concurrent = concurrent - analyzer = SEOAnalyzer(config) - - # Memory before - process = psutil.Process() - mem_before = process.memory_info().rss / 1024 / 1024 # MB - - # Time the batch - start_time = time.time() - pages_analyzed = 0 - - async for result in analyzer.analyze_urls(urls): - pages_analyzed += 1 - - end_time = time.time() - - # Memory after - mem_after = process.memory_info().rss / 1024 / 1024 # MB - - duration = end_time - start_time - mem_used = mem_after - mem_before - pages_per_second = pages_analyzed / duration if duration > 0 else 0 - - benchmark = { - 'type': 'batch', - 'urls_count': len(urls), - 'pages_analyzed': pages_analyzed, - 'concurrent': concurrent, - 'duration_seconds': round(duration, 3), - 'memory_used_mb': round(mem_used, 2), - 'pages_per_second': round(pages_per_second, 2), - 'timestamp': datetime.now().isoformat() + """Benchmark unique supplied network URLs without treating failures as throughput.""" + unique_urls = list(dict.fromkeys(urls)) + config = Config.from_dict({'crawler': {'max_concurrent': concurrent, 'max_pages': max(1, len(unique_urls))}}) + + async def operation(record): + async for result in SEOAnalyzer(config).analyze_urls(unique_urls): + record(result) + return await _measure('batch', operation, {'urls_count': len(unique_urls), 'concurrent': concurrent}, + expected_results=len(unique_urls)) + + +def _fixture_html(index, page_count, scenario): + """Return stable HTML and its scenario; fixture version 1 is append-only.""" + variant = SCENARIOS[index % 3] if scenario == 'mixed' else scenario + head = ( + '' + f'Offline benchmark fixture page {index}' + '' + '' + ) + body = (f'

Fixture page {index}

Local benchmark content with stable markup.

' + f'Next fixture page') + if variant == 'content-heavy': + head += (f'' + '' + '') + paragraphs = [] + for section in range(12): + sentences = [ + f'Page {index} section {section} example {example} describes how a local team plans clear ' + 'instructions for readers. The guide explains each step with useful details and a short ' + 'review of the result. Readers can use this example to compare different choices and ' + 'record what they learn.' for example in range(2) + ] + paragraphs.append(f'

Topic {section}

' + + ''.join(f'

{sentence}

' for sentence in sentences) + '
') + body += '
' + ''.join(paragraphs) + '
' + body += ''.join(f'
Illustration {image}
Example {image}
' + for image in range(8)) + body += '' + body += ''.join(f'' for row in range(20)) + body += '
Local observations
ItemValue
Sample {row}{index + row}
' + elif variant == 'link-dense': + head += f'' + body += '' + body += ''.join(f'Reference {external}' + for external in range(4)) + body += 'ContactDetails' + body += '

Link inventory

Only HTML references are observed.

' + return head + '' + body + '', variant + + +def _check_offline_options(page_count, scenario, timeout_seconds): + if type(page_count) is not int or page_count <= 0: + raise ValueError('page_count must be a positive integer') + if scenario not in SCENARIOS: + raise ValueError('scenario must be one of: ' + ', '.join(SCENARIOS)) + if timeout_seconds is not None and (isinstance(timeout_seconds, bool) or + not isinstance(timeout_seconds, (int, float)) or not math.isfinite(timeout_seconds) or timeout_seconds <= 0): + raise ValueError('timeout_seconds must be a finite positive number') + + +async def benchmark_offline(page_count: int = 500, scenario: str = 'basic', + timeout_seconds: Optional[float] = None) -> Dict[str, Any]: + """Measure parsing, static analysis, and report aggregation over local fixtures. + + This workload does not fetch URLs or measure browser/network performance. + Page cache reuse is disabled, and the fixture version identifies comparable runs. + """ + _check_offline_options(page_count, scenario, timeout_seconds) + config = Config.from_dict({'crawler': {'cache_enabled': False, 'max_pages': page_count}}) + pages = [] + fixture = {'version': 1, 'generated_pages': 0, 'html_bytes': 0, 'dom_elements': 0, + 'href_references': 0, 'image_elements': 0, + 'analyzed_word_count': 0, 'pages_with_word_count': 0, + 'variants': {name: 0 for name in SCENARIOS[:3]}, 'sha256': None} + metadata = { + 'fixture_version': 1, 'scenario': scenario, 'requested_pages': page_count, + 'network_access': False, 'config': config.to_dict(), 'fixture': fixture, + 'timeout_seconds': timeout_seconds, 'timed_out': False, + 'timeout_scope': 'Cooperative checks between pages and after reporting; synchronous work can overrun the deadline.', + 'report_completeness': None, + 'readability': {'status_counts': {}, 'missing_resources': []}, + 'workload': 'Fixture generation, HTML parsing, static analysis, site report aggregation and retained-URL verification; no HTTP, browser or export measurement', } - - print(f"✅ Completed {pages_analyzed} URLs in {duration:.2f}s") - print(f" Speed: {pages_per_second:.2f} pages/sec, Memory: {mem_used:.2f}MB") - - return benchmark + async def operation(record): + started = time.perf_counter() + analyzer = SEOAnalyzer(config) + digest = hashlib.sha256() -def compare_with_targets() -> Dict[str, Any]: - """Compare benchmark results with target metrics.""" - targets = { - 'single_page': { - 'duration_seconds': 2.0, - 'memory_mb': 50 - }, - 'crawl_100': { - 'duration_seconds': 120, # 2 minutes for 100 pages - 'memory_mb': 200, - 'pages_per_second': 1.0 - }, - 'crawl_500': { - 'duration_seconds': 480, # 8 minutes for 500 pages - 'memory_mb': 500, - 'pages_per_second': 1.0 + def check_deadline(): + if timeout_seconds is not None and time.perf_counter() - started >= timeout_seconds: + metadata['timed_out'] = True + raise TimeoutError(f'Offline benchmark exceeded its {timeout_seconds:g}s cooperative deadline') + + for index in range(page_count): + check_deadline() + html, variant = _fixture_html(index, page_count, scenario) + url = f'https://benchmark.test/page/{index}' + encoded = html.encode('utf-8') + digest.update(url.encode('utf-8') + b'\0' + encoded + b'\0') + soup = BeautifulSoup(html, 'html.parser') + fixture['generated_pages'] += 1 + fixture['html_bytes'] += len(encoded) + fixture['dom_elements'] += len(soup.find_all(True)) + fixture['href_references'] += len(soup.find_all('a', href=True)) + fixture['image_elements'] += len(soup.find_all('img')) + fixture['variants'][variant] += 1 + fixture['sha256'] = digest.hexdigest() + result = await analyzer.analyze_page({ + 'url': url, + 'status_code': 200, + 'headers': {'Content-Type': 'text/html; charset=utf-8'}, + 'content_length': len(encoded), + 'soup': soup, + 'load_time': None, + }) + pages.append(result) + record(result) + if isinstance(result, dict): + content = result.get('content', {}).get('data', {}) + word_count = content.get('metrics', {}).get('word_count') + if type(word_count) is int: + fixture['analyzed_word_count'] += word_count + fixture['pages_with_word_count'] += 1 + readability = content.get('readability', {}) + status = readability.get('status', 'not_requested') + status_counts = metadata['readability']['status_counts'] + status_counts[status] = status_counts.get(status, 0) + 1 + metadata['readability']['missing_resources'] = sorted(set( + metadata['readability']['missing_resources'] + readability.get('missing_resources', []))) + check_deadline() + report_started = time.perf_counter() + metadata['analysis_duration_seconds'] = report_started - started + report = analyzer.generate_site_report(pages) + metadata['report_duration_seconds'] = time.perf_counter() - report_started + exported = report.get('pages', {}) + rows = [row for name in ('detailed', 'failed', 'skipped') for row in exported.get(name, [])] + urls = {row.get('url') for row in rows} + expected = {f'https://benchmark.test/page/{index}' for index in range(page_count)} + completeness = { + 'expected_pages': page_count, 'retained_rows': len(rows), 'unique_urls': len(urls), + 'missing_urls': len(expected - urls), 'unexpected_urls': len(urls - expected), + 'duplicate_rows': len(rows) - len(urls), + 'complete': len(rows) == page_count and urls == expected, } - } - - return targets + site = report.get('site_analysis', {}) + metadata.update({ + 'report_pages': len(rows), 'report_status': report.get('status'), + 'report_completeness': completeness, 'report_summary': report.get('summary', {}), + 'rule_coverage': report.get('rule_coverage', {}), + 'site_analysis': {'version': site.get('version'), 'coverage': site.get('coverage', {}), + 'node_count': site.get('links', {}).get('node_count'), + 'edge_count': site.get('links', {}).get('edge_count'), + 'finding_count': len(site.get('findings', []))}, + }) + if not completeness['complete']: + raise RuntimeError(f'Report retained {len(rows)} rows and {len(urls & expected)} of {page_count} expected fixture URLs') + check_deadline() + return {'report_status': report.get('status')} + + async def bounded_operation(record): + if timeout_seconds is None: + return await operation(record) + try: + return await asyncio.wait_for(operation(record), timeout_seconds) + except asyncio.TimeoutError as exc: + metadata['timed_out'] = True + raise TimeoutError(f'Offline benchmark exceeded its {timeout_seconds:g}s cooperative deadline') from exc + + return await _measure('offline', bounded_operation, metadata, expected_results=page_count) -async def run_all_benchmarks(): - """Run all benchmarks and save results.""" - print("=" * 60) - print("🚀 TFQ0SEO Performance Benchmark Suite") - print("=" * 60) - print() - +def compare_with_targets() -> Dict[str, Any]: + """Compatibility helper: no unverified, machine-independent targets are defined.""" + return {} + + +def _summarize_runs(runs): + groups = {} + for run in runs: + groups.setdefault((run['scenario'], run['requested_pages']), []).append(run) + summaries = [] + for (scenario, page_count), group in groups.items(): + complete = [run for run in group if run['status'] == 'complete'] + metrics = {} + for name in ('duration_seconds', 'analysis_duration_seconds', 'report_duration_seconds', + 'pages_per_second', 'memory_rss_delta_mb', 'memory_sampled_peak_mb'): + values = [run[name] for run in complete if isinstance(run.get(name), (int, float))] + if values: + metrics[name] = {'median': median(values), 'min': min(values), 'max': max(values)} + summaries.append({ + 'scenario': scenario, 'requested_pages': page_count, 'runs': len(group), + 'complete_runs': len(complete), 'partial_runs': sum(run['status'] == 'partial' for run in group), + 'failed_runs': sum(run['status'] == 'failed' for run in group), + 'metrics_scope': 'Only complete runs; inspect raw outcomes for excluded failed or partial runs.', + 'metrics': metrics, + }) + return summaries + + +async def run_all_benchmarks(page_count: int = 500, output_file: Optional[str] = None, *, + scenarios=None, repetitions: int = 1, page_counts=None, + timeout_seconds: Optional[float] = None): + """Save offline runs and summaries; default remains one basic 500-page run. + + Repetitions run in the same process, with a fresh analyzer and disabled page + cache. Library caches and allocator state can remain warm between runs. + """ + selected = list(scenarios) if scenarios is not None else ['basic'] + sizes = list(page_counts) if page_counts is not None else [page_count] + if not selected or not sizes: + raise ValueError('scenarios and page_counts must not be empty') + if type(repetitions) is not int or repetitions <= 0: + raise ValueError('repetitions must be a positive integer') + if len(set(selected)) != len(selected) or len(set(sizes)) != len(sizes): + raise ValueError('scenarios and page_counts must not contain duplicates') + for scenario in selected: + for size in sizes: + _check_offline_options(size, scenario, timeout_seconds) + environment = _environment() + benchmarks = [] + for size in sizes: + for scenario in selected: + for repetition in range(1, repetitions + 1): + # Preserve the original default call shape for API wrappers. + if scenario == 'basic' and timeout_seconds is None: + run = await benchmark_offline(size) + else: + run = await benchmark_offline(size, scenario=scenario, timeout_seconds=timeout_seconds) + run.update({'scenario': scenario, 'requested_pages': size, 'repetition': repetition, + 'run_order': len(benchmarks) + 1}) + benchmarks.append(run) + source_unchanged = environment['source_fingerprint'] == _source_fingerprint() + status = ('failed' if not source_unchanged or any(run['status'] == 'failed' for run in benchmarks) + else 'partial' if any(run['status'] != 'complete' for run in benchmarks) else 'complete') results = { - 'benchmarks': [], - 'system_info': { - 'cpu_count': psutil.cpu_count(), - 'memory_total_gb': round(psutil.virtual_memory().total / (1024**3), 2), - 'python_version': __import__('sys').version, - 'timestamp': datetime.now().isoformat() - } + 'benchmark_schema_version': 2, + 'status': status, + 'benchmarks': benchmarks, + 'summaries': _summarize_runs(benchmarks), + 'system_info': environment, + 'source_unchanged_during_suite': source_unchanged, + 'errors': [] if source_unchanged else ['Package Python source changed during measurement; repeat on a stable checkout.'], + 'suite': {'scenarios': selected, 'page_counts': sizes, 'repetitions': repetitions, + 'timeout_seconds': timeout_seconds, + 'order': 'Page counts, then scenarios, then repetitions, in supplied order.', + 'isolation': 'Same process; fresh analyzer per run, disabled page cache; library caches and allocator state may remain warm.'}, } - - # Test URLs - test_urls = [ - "https://example.com", - "https://httpbin.org/html", - "https://www.python.org", - "https://docs.python.org", - "https://pypi.org" - ] - - try: - # Single page benchmark - single_result = await benchmark_single_page(test_urls[0]) - results['benchmarks'].append(single_result) - print() - - # Batch benchmark - batch_result = await benchmark_batch(test_urls[:3], concurrent=3) - results['benchmarks'].append(batch_result) - print() - - # Small crawl benchmark - crawl_result = await benchmark_crawl(test_urls[0], max_pages=5) - results['benchmarks'].append(crawl_result) - print() - - except Exception as e: - print(f"❌ Benchmark error: {e}") - results['error'] = str(e) - - # Performance comparison - print("=" * 60) - print("📊 Performance vs Targets") - print("=" * 60) - - targets = compare_with_targets() - - for benchmark in results['benchmarks']: - if benchmark['type'] == 'single_page': - target = targets['single_page'] - speed_ratio = target['duration_seconds'] / benchmark['duration_seconds'] - status = "✅" if speed_ratio >= 1 else "⚠️" - print(f"{status} Single Page: {benchmark['duration_seconds']}s (target: {target['duration_seconds']}s)") - print(f" Speed ratio: {speed_ratio:.2f}x") - - # Save results - output_file = f"benchmark_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json" - with open(output_file, 'w') as f: - json.dump(results, f, indent=2) - - print() - print(f"💾 Results saved to: {output_file}") - + output = Path(output_file) if output_file else Path( + f'benchmark_{datetime.now().strftime("%Y%m%d_%H%M%S_%f")}.json') + output.parent.mkdir(parents=True, exist_ok=True) + with output.open('w', encoding='utf-8') as stream: + json.dump(results, stream, indent=2, ensure_ascii=False, allow_nan=False) + print(f'Benchmark results saved to: {output}') + for error in results['errors']: + print(error) return results -def main(): - """Main entry point for benchmark script.""" +def _positive_int(value): + try: + number = int(value) + if number > 0: + return number + except ValueError: + pass + raise argparse.ArgumentTypeError('must be a positive integer') + + +def _positive_float(value): + try: + number = float(value) + if math.isfinite(number) and number > 0: + return number + except ValueError: + pass + raise argparse.ArgumentTypeError('must be a finite positive number') + + +def main(argv=None): + """CLI exit codes: 0 complete, 1 failed/incomplete, 2 invalid arguments, 130 cancelled.""" + parser = argparse.ArgumentParser(description='Benchmark deterministic offline HTML analysis and reporting.') + parser.add_argument('--pages', type=_positive_int, nargs='+', default=[500], + help='one or more fixture page counts (default: 500)') + scenario_group = parser.add_mutually_exclusive_group() + scenario_group.add_argument('--scenario', choices=SCENARIOS, default='basic', help='fixture scenario (default: basic)') + scenario_group.add_argument('--suite', action='store_true', help='run every scenario') + parser.add_argument('--repetitions', type=_positive_int, default=1, help='runs per size and scenario (default: 1)') + parser.add_argument('--timeout-seconds', type=_positive_float, + help='cooperative deadline per run; synchronous work may overrun it') + parser.add_argument('--output', help='JSON results path (default: timestamped file)') + args = parser.parse_args(argv) try: - results = asyncio.run(run_all_benchmarks()) - - # Summary - print() - print("=" * 60) - print("✨ Benchmark Summary") - print("=" * 60) - - total_time = sum(b['duration_seconds'] for b in results['benchmarks']) - total_pages = sum(b.get('pages_analyzed', 1) for b in results['benchmarks']) - avg_speed = total_pages / total_time if total_time > 0 else 0 - - print(f"Total pages analyzed: {total_pages}") - print(f"Total time: {total_time:.2f}s") - print(f"Average speed: {avg_speed:.2f} pages/sec") - - # Performance grade - if avg_speed >= 2.0: - grade = "A+ (Excellent)" - elif avg_speed >= 1.5: - grade = "A (Very Good)" - elif avg_speed >= 1.0: - grade = "B (Good)" - elif avg_speed >= 0.5: - grade = "C (Acceptable)" - else: - grade = "D (Needs Improvement)" - - print(f"Performance Grade: {grade}") - + results = asyncio.run(run_all_benchmarks( + args.pages[0], args.output, page_counts=args.pages, + scenarios=SCENARIOS if args.suite else [args.scenario], + repetitions=args.repetitions, timeout_seconds=args.timeout_seconds)) + return 0 if results['status'] == 'complete' else 1 except KeyboardInterrupt: - print("\n⚠️ Benchmark interrupted by user") - except Exception as e: - print(f"\n❌ Benchmark failed: {e}") - import traceback - traceback.print_exc() + print('Benchmark interrupted.', file=sys.stderr) + return 130 + except Exception as exc: + print(f'Benchmark failed: {exc}', file=sys.stderr) + return 1 -if __name__ == "__main__": - main() +if __name__ == '__main__': + sys.exit(main()) diff --git a/tfq0seo/cli.py b/tfq0seo/cli.py index a3c407f..9663f8d 100644 --- a/tfq0seo/cli.py +++ b/tfq0seo/cli.py @@ -1,488 +1,224 @@ -"""CLI module for tfq0seo using Click and Rich for beautiful output.""" +"""Click commands for analysis, complete reports, and explicit failure statuses.""" import asyncio import json -import time -import sys +import logging from pathlib import Path from typing import Optional, List import click from rich.console import Console -from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TaskProgressColumn, TimeElapsedColumn from rich.table import Table -from rich.panel import Panel -from rich.layout import Layout -from rich.live import Live -from rich import print as rprint +from rich.text import Text +from . import __version__ from .core.app import SEOAnalyzer from .core.config import Config +from .core.models import ANALYZER_NAMES from .exporters.base import ExportManager console = Console() +FORMATS = click.Choice(['json', 'html', 'csv', 'xlsx']) +CONFIG_PATH = click.Path(exists=True, dir_okay=False) + + +def _reject_json_constant(value): + raise ValueError(f'Non-finite JSON number {value} is not allowed') def create_summary_table(results: dict) -> Table: - """Create a summary table for the results.""" - table = Table(title="Analysis Summary", show_header=True, header_style="bold magenta") - table.add_column("Metric", style="cyan", width=20) - table.add_column("Value", style="green") - - # Overall score - handle both old and new formats - score = 0 - if 'scores' in results and isinstance(results['scores'], dict): - score = results['scores'].get('overall', 0) - else: - score = results.get('overall_score', 0) - - score_style = "green" if score >= 80 else "yellow" if score >= 50 else "red" - table.add_row("Overall Score", f"[{score_style}]{score:.1f}/100[/{score_style}]") - - # Category scores - handle both formats - category_scores = {} - if 'scores' in results and isinstance(results['scores'], dict): - category_scores = results['scores'].get('categories', {}) - elif 'category_scores' in results: - category_scores = results['category_scores'] - - if category_scores: - for category, cat_score in category_scores.items(): - cat_style = "green" if cat_score >= 80 else "yellow" if cat_score >= 50 else "red" - table.add_row(f" {category}", f"[{cat_style}]{cat_score:.1f}[/{cat_style}]") - - # Issue counts - handle both old and new formats - if 'issues' in results: - if isinstance(results['issues'], dict): - # New format with nested structure - if 'counts' in results['issues']: - counts = results['issues']['counts'] - critical = counts.get('critical', 0) - warnings = counts.get('warning', 0) - notices = counts.get('notice', 0) - else: - # Try to extract from aggregated issues - issues_list = results['issues'].get('aggregated', []) - critical = sum(1 for i in issues_list if isinstance(i, dict) and i.get('severity') == 'critical') - warnings = sum(1 for i in issues_list if isinstance(i, dict) and i.get('severity') == 'warning') - notices = sum(1 for i in issues_list if isinstance(i, dict) and i.get('severity') == 'notice') - else: - # Old format - issues is a list - issues_list = results['issues'] - critical = sum(1 for i in issues_list if isinstance(i, dict) and i.get('severity') == 'critical') - warnings = sum(1 for i in issues_list if isinstance(i, dict) and i.get('severity') == 'warning') - notices = sum(1 for i in issues_list if isinstance(i, dict) and i.get('severity') == 'notice') - - table.add_row("Critical Issues", f"[red]{critical}[/red]") - table.add_row("Warnings", f"[yellow]{warnings}[/yellow]") - table.add_row("Notices", f"[blue]{notices}[/blue]") - elif 'issue_counts' in results: - # Fallback to issue_counts if available - counts = results['issue_counts'] - table.add_row("Critical Issues", f"[red]{counts.get('critical', 0)}[/red]") - table.add_row("Warnings", f"[yellow]{counts.get('warning', 0)}[/yellow]") - table.add_row("Notices", f"[blue]{counts.get('notice', 0)}[/blue]") - - # Performance metrics - handle both formats - if 'performance_metrics' in results: - # New format with detailed metrics - perf = results['performance_metrics'] - if 'load_time_stats' in perf: - table.add_row("Avg Load Time", f"{perf['load_time_stats'].get('mean', 0):.2f}s") - if 'pages_by_status' in perf: - successful = perf['pages_by_status'].get('2xx', 0) - table.add_row("Successful Pages", str(successful)) - elif 'performance' in results: - # Old format - perf = results['performance'] - if 'average_load_time' in perf: - table.add_row("Avg Load Time", f"{perf['average_load_time']:.2f}s") - elif 'load_time' in perf: - table.add_row("Load Time", f"{perf.get('load_time', 0):.2f}s") - if 'content_size' in perf: - table.add_row("Content Size", f"{perf.get('content_size', 0) / 1024:.1f}KB") - - # Summary information if available - if 'summary' in results: - summary = results['summary'] - table.add_row("Total Pages", str(summary.get('total_pages', 0))) - table.add_row("Successful Pages", str(summary.get('successful_pages', 0))) - if summary.get('failed_pages', 0) > 0: - table.add_row("Failed Pages", f"[red]{summary['failed_pages']}[/red]") - + table = Table(title='Analysis Summary', show_header=True) + table.add_column('Metric', style='cyan') + table.add_column('Value') + scores = results.get('scores', {}) + overall = scores.get('overall', results.get('overall_score')) + table.add_row('Overall Score', 'Unavailable' if overall is None else f'{overall:.1f}/100') + categories = scores.get('categories', results.get('category_scores', {})) + if not categories: + categories = {name: results[name].get('score') for name in ANALYZER_NAMES if name in results} + for name, score in categories.items(): + table.add_row(name, 'Unavailable' if score is None else f'{score:.1f}') + issues = results.get('issues', []) + counts = issues.get('counts', {}) if isinstance(issues, dict) else SEOAnalyzer._count_issues(issues) + for severity in ('critical', 'warning', 'notice'): + table.add_row(severity.title(), str(counts.get(severity, 0))) + timings = results.get('performance_metrics', {}).get('load_time_stats', {}) + if 'average' in timings: + table.add_row('Avg HTML Fetch Time', f"{timings['average']:.2f}s") + elif results.get('load_time') is not None: + table.add_row('HTML Fetch Time', f"{results['load_time']:.2f}s") + for name in ('total_pages', 'successful_pages', 'partial_pages', 'failed_pages', 'skipped_pages'): + if name in results.get('summary', {}): + table.add_row(name.replace('_', ' ').title(), str(results['summary'][name])) + table.add_row('Status', results.get('status', 'complete')) return table def create_issues_table(issues: List[dict], limit: int = 10) -> Table: - """Create a table showing top issues.""" - table = Table(title=f"Top {limit} Issues", show_header=True, header_style="bold magenta") - table.add_column("Severity", width=10) - table.add_column("Category", width=15) - table.add_column("Issue", width=50) - - # Sort issues by severity - severity_order = {'critical': 0, 'warning': 1, 'notice': 2} - sorted_issues = sorted(issues, key=lambda x: severity_order.get(x.get('severity', 'notice'), 3)) - - for issue in sorted_issues[:limit]: - severity = issue.get('severity', 'notice') - severity_style = "red" if severity == 'critical' else "yellow" if severity == 'warning' else "blue" - - table.add_row( - f"[{severity_style}]{severity.upper()}[/{severity_style}]", - issue.get('category', 'General'), - issue.get('message', 'No description')[:50] - ) - + table = Table(title=f'Top {limit} Issues') + for name in ('Severity', 'Category', 'Issue'): + table.add_column(name) + ordered = sorted(issues, key=lambda issue: {'critical': 0, 'warning': 1, 'notice': 2}.get(issue.get('severity'), 3)) + for issue in ordered[:limit]: + table.add_row(Text(issue.get('severity', 'notice')), Text(issue.get('category', 'General')), + Text(issue.get('message', ''))) return table +def _configuration(path: Optional[str], **crawler_overrides) -> Config: + cfg = Config.from_file(path) if path else Config() + environment = Config.environment_overrides() + if environment: + cfg = cfg.merge(environment) + changes = {name: value for name, value in crawler_overrides.items() if value is not None} + if changes: + cfg = cfg.merge({'crawler': changes}) + cfg.require_valid() + return cfg + + +def _report(data, cfg, format, output): + format = format or cfg.export.primary_format + if format == 'json' and output is None: + click.echo(json.dumps(data, indent=2, ensure_ascii=False, allow_nan=False)) + else: + console.print(create_summary_table(data)) + issues = data.get('issues', []) + if isinstance(issues, dict): + issues = issues.get('aggregated', []) + if issues: + console.print(create_issues_table(issues)) + if output is not None or not data.get('error'): + destination = ExportManager(cfg.export).export(data, format, output) + console.print(f'Report saved to: {destination}', markup=False) + if data.get('error'): + raise click.ClickException(data['error']) + if data.get('skipped'): + raise click.ClickException('Page was not analyzed: ' + data.get('reason', 'Skipped')) + if data.get('status') == 'partial' or data.get('analyzer_errors'): + errors = '; '.join(data.get('analyzer_errors', {}).values()) + raise click.ClickException('Analysis is incomplete; inspect the report for failures.' + (' ' + errors if errors else '')) + if data.get('status') == 'error': + raise click.ClickException('No pages were analyzed successfully; inspect the report for failures.') + + @click.group() -@click.version_option(version='2.3.2', prog_name='tfq0seo') +@click.version_option(version=__version__, prog_name='tfq0seo') def cli(): - """TFQ0SEO - Fast SEO analysis tool with reports.""" - pass + """Static SEO analysis with evidence and explicit coverage.""" @cli.command() @click.argument('url') -@click.option('--config', '-c', type=click.Path(exists=True), help='Configuration file (JSON/YAML)') -@click.option('--format', '-f', type=click.Choice(['json', 'html', 'csv', 'xlsx']), default='html', help='Output format') -@click.option('--output', '-o', type=click.Path(), help='Output file path') -@click.option('--verbose', '-v', is_flag=True, help='Verbose output') -def analyze(url: str, config: Optional[str], format: str, output: Optional[str], verbose: bool): +@click.option('--config', '-c', type=CONFIG_PATH) +@click.option('--format', '-f', type=FORMATS, default=None) +@click.option('--output', '-o', type=click.Path(dir_okay=False)) +@click.option('--verbose', '-v', is_flag=True) +def analyze(url, config, format, output, verbose): """Analyze a single URL.""" - with console.status(f"[bold green]Analyzing {url}...") as status: - # Load configuration - if config: - cfg = Config.from_file(config) - else: - cfg = Config() - - # Run analysis - analyzer = SEOAnalyzer(cfg) - - try: - # Run async analysis - results = asyncio.run(analyzer.analyze_url(url)) - - if not results: - console.print("[red]Analysis failed![/red]") - sys.exit(1) - - # Display summary - console.print("\n") - console.print(create_summary_table(results)) - - # Display top issues - if 'issues' in results and results['issues']: - console.print("\n") - console.print(create_issues_table(results['issues'])) - - # Export results - if output: - exporter = ExportManager(cfg.export) - exported_file = exporter.export(results, format, output) - console.print(f"\n[green]✓[/green] Report saved to: {exported_file}") - elif format != 'html': - # For non-HTML formats without output file, print to console - if format == 'json': - rprint(json.dumps(results, indent=2, default=str)) - - # Print recommendations - if verbose and 'recommendations' in results: - console.print("\n[bold]Recommendations:[/bold]") - for i, rec in enumerate(results['recommendations'][:5], 1): - console.print(f"{i}. {rec}") - - except Exception as e: - console.print(f"[red]Error during analysis: {e}[/red]") - if verbose: - import traceback - traceback.print_exc() - sys.exit(1) + try: + if verbose: + logging.basicConfig(level=logging.INFO) + cfg = _configuration(config) + result = asyncio.run(SEOAnalyzer(cfg).analyze_url(url)) + _report(result, cfg, format, output) + except click.ClickException: + raise + except Exception as exc: + raise click.ClickException(str(exc)) from exc @cli.command() @click.argument('url') -@click.option('--depth', '-d', type=int, default=5, help='Maximum crawl depth') -@click.option('--max-pages', '-m', type=int, default=100, help='Maximum pages to crawl') -@click.option('--concurrent', type=int, default=10, help='Concurrent requests') -@click.option('--config', '-c', type=click.Path(exists=True), help='Configuration file') -@click.option('--format', '-f', type=click.Choice(['json', 'html', 'csv', 'xlsx']), default='html') -@click.option('--output', '-o', type=click.Path(), required=True, help='Output file path') -@click.option('--follow-redirects/--no-follow-redirects', default=True, help='Follow redirects') -@click.option('--respect-robots/--ignore-robots', default=True, help='Respect robots.txt') -def crawl(url: str, depth: int, max_pages: int, concurrent: int, config: Optional[str], - format: str, output: str, follow_redirects: bool, respect_robots: bool): - """Crawl and analyze an entire website.""" - - # Load configuration - if config: - cfg = Config.from_file(config) - else: - cfg = Config() - - # Override with CLI options - cfg.crawler.max_depth = depth - cfg.crawler.max_pages = max_pages - cfg.crawler.max_concurrent = concurrent - cfg.crawler.follow_redirects = follow_redirects - cfg.crawler.respect_robots_txt = respect_robots - - analyzer = SEOAnalyzer(cfg) - - with Progress( - SpinnerColumn(), - TextColumn("[progress.description]{task.description}"), - BarColumn(), - TaskProgressColumn(), - TimeElapsedColumn(), - console=console - ) as progress: - - # Add crawling task - crawl_task = progress.add_task( - f"[cyan]Crawling {url}...", - total=max_pages - ) - - async def run_crawl(): - """Run the crawl with progress updates.""" - results = [] - analyzed = 0 - - async for page_result in analyzer.crawl_site(url): - analyzed += 1 - progress.update(crawl_task, advance=1, description=f"[cyan]Analyzed {analyzed}/{max_pages} pages") - - # Update with current URL - if 'url' in page_result: - progress.update(crawl_task, description=f"[cyan]Analyzing: {page_result['url'][:50]}...") - - results.append(page_result) - - # Show live stats - if analyzed % 10 == 0: - stats = analyzer.get_crawl_statistics() - console.print(f"[dim]Speed: {stats.get('pages_per_second', 0):.1f} pages/sec | " - f"Memory: {stats.get('memory_usage', 0):.1f}MB[/dim]") - - return results - - try: - # Run the crawl - results = asyncio.run(run_crawl()) - - if not results: - console.print("[red]No pages were analyzed![/red]") - sys.exit(1) - - # Generate report - progress.add_task("[green]Generating report...", total=None) - - # Aggregate results - report = analyzer.generate_site_report(results) - - # Export - exporter = ExportManager(cfg.export) - exported_file = exporter.export(report, format, output) - - # Show summary - console.print("\n") - console.print(Panel.fit( - f"[green]✓[/green] Crawl completed!\n" - f"Pages analyzed: {len(results)}\n" - f"Report saved to: {exported_file}", - title="Success", - border_style="green" - )) - - # Display summary table - console.print("\n") - console.print(create_summary_table(report)) - - except KeyboardInterrupt: - console.print("\n[yellow]Crawl interrupted by user[/yellow]") - sys.exit(1) - except Exception as e: - console.print(f"[red]Error during crawl: {e}[/red]") - import traceback - traceback.print_exc() - sys.exit(1) +@click.option('--depth', '-d', type=click.IntRange(min=0), default=None) +@click.option('--max-pages', '-m', type=click.IntRange(min=1), default=None) +@click.option('--concurrent', type=click.IntRange(min=1), default=None) +@click.option('--config', '-c', type=CONFIG_PATH) +@click.option('--format', '-f', type=FORMATS, default=None) +@click.option('--output', '-o', type=click.Path(dir_okay=False), required=True) +@click.option('--follow-redirects/--no-follow-redirects', default=None) +@click.option('--respect-robots/--ignore-robots', default=None) +def crawl(url, depth, max_pages, concurrent, config, format, output, follow_redirects, respect_robots): + """Crawl pages within the configured scope and export a complete report.""" + try: + cfg = _configuration(config, max_depth=depth, max_pages=max_pages, max_concurrent=concurrent, + follow_redirects=follow_redirects, respect_robots_txt=respect_robots) + analyzer = SEOAnalyzer(cfg) + async def run(): + return [page async for page in analyzer.crawl_site(url)] + results = asyncio.run(run()) + _report(analyzer.generate_site_report(results), cfg, format, output) + except click.ClickException: + raise + except Exception as exc: + raise click.ClickException(str(exc)) from exc @cli.command() -@click.argument('urls_file', type=click.Path(exists=True)) -@click.option('--concurrent', type=int, default=10, help='Concurrent requests') -@click.option('--config', '-c', type=click.Path(exists=True), help='Configuration file') -@click.option('--format', '-f', type=click.Choice(['json', 'html', 'csv', 'xlsx']), default='html') -@click.option('--output', '-o', type=click.Path(), required=True, help='Output file path') -def batch(urls_file: str, concurrent: int, config: Optional[str], format: str, output: str): - """Analyze a batch of URLs from a file.""" - - # Load URLs - with open(urls_file, 'r') as f: - urls = [line.strip() for line in f if line.strip() and not line.startswith('#')] - - if not urls: - console.print("[red]No valid URLs found in file![/red]") - sys.exit(1) - - console.print(f"[cyan]Found {len(urls)} URLs to analyze[/cyan]") - - # Load configuration - if config: - cfg = Config.from_file(config) - else: - cfg = Config() - - cfg.crawler.max_concurrent = concurrent - - analyzer = SEOAnalyzer(cfg) - - with Progress( - SpinnerColumn(), - TextColumn("[progress.description]{task.description}"), - BarColumn(), - TaskProgressColumn(), - TimeElapsedColumn(), - console=console - ) as progress: - - # Add task - batch_task = progress.add_task( - f"[cyan]Analyzing {len(urls)} URLs...", - total=len(urls) - ) - - async def run_batch(): - """Run batch analysis.""" - results = [] - - async for page_result in analyzer.analyze_urls(urls): - progress.update(batch_task, advance=1) - results.append(page_result) - - # Update description - if 'url' in page_result: - progress.update(batch_task, description=f"[cyan]Analyzed: {page_result['url'][:50]}...") - - return results - - try: - # Run batch analysis - results = asyncio.run(run_batch()) - - # Generate report - report = analyzer.generate_batch_report(results) - - # Export - exporter = ExportManager(cfg.export) - exported_file = exporter.export(report, format, output) - - # Show summary - console.print("\n") - console.print(Panel.fit( - f"[green]✓[/green] Batch analysis completed!\n" - f"URLs analyzed: {len(results)}\n" - f"Report saved to: {exported_file}", - title="Success", - border_style="green" - )) - - # Display summary - console.print("\n") - console.print(create_summary_table(report)) - - except Exception as e: - console.print(f"[red]Error during batch analysis: {e}[/red]") - sys.exit(1) +@click.argument('urls_file', type=CONFIG_PATH) +@click.option('--concurrent', type=click.IntRange(min=1), default=None) +@click.option('--config', '-c', type=CONFIG_PATH) +@click.option('--format', '-f', type=FORMATS, default=None) +@click.option('--output', '-o', type=click.Path(dir_okay=False), required=True) +def batch(urls_file, concurrent, config, format, output): + """Analyze URLs from a UTF-8 file (one per line).""" + try: + urls = [line.strip() for line in Path(urls_file).read_text(encoding='utf-8').splitlines() + if line.strip() and not line.lstrip().startswith('#')] + if not urls: + raise ValueError('The input file contains no URLs') + cfg = _configuration(config, max_concurrent=concurrent) + analyzer = SEOAnalyzer(cfg) + async def run(): + return [page async for page in analyzer.analyze_urls(urls)] + results = asyncio.run(run()) + _report(analyzer.generate_batch_report(results), cfg, format, output) + except click.ClickException: + raise + except Exception as exc: + raise click.ClickException(str(exc)) from exc @cli.command() @click.argument('sitemap_url') -@click.option('--max-pages', '-m', type=int, default=100, help='Maximum pages to analyze') -@click.option('--config', '-c', type=click.Path(exists=True), help='Configuration file') -@click.option('--format', '-f', type=click.Choice(['json', 'html', 'csv', 'xlsx']), default='html') -@click.option('--output', '-o', type=click.Path(), required=True, help='Output file path') -def sitemap(sitemap_url: str, max_pages: int, config: Optional[str], format: str, output: str): - """Analyze URLs from a sitemap.""" - - # Load configuration - if config: - cfg = Config.from_file(config) - else: - cfg = Config() - - cfg.crawler.max_pages = max_pages - - analyzer = SEOAnalyzer(cfg) - - with console.status(f"[bold green]Fetching sitemap from {sitemap_url}...") as status: - try: - # Analyze sitemap - results = asyncio.run(analyzer.analyze_sitemap(sitemap_url)) - - if not results: - console.print("[red]No URLs found in sitemap![/red]") - sys.exit(1) - - # Generate report - report = analyzer.generate_site_report(results) - - # Export - exporter = ExportManager(cfg.export) - exported_file = exporter.export(report, format, output) - - # Show summary - console.print("\n") - console.print(Panel.fit( - f"[green]✓[/green] Sitemap analysis completed!\n" - f"URLs analyzed: {len(results)}\n" - f"Report saved to: {exported_file}", - title="Success", - border_style="green" - )) - - # Display summary - console.print("\n") - console.print(create_summary_table(report)) - - except Exception as e: - console.print(f"[red]Error during sitemap analysis: {e}[/red]") - sys.exit(1) +@click.option('--max-pages', '-m', type=click.IntRange(min=1), default=None) +@click.option('--config', '-c', type=CONFIG_PATH) +@click.option('--format', '-f', type=FORMATS, default=None) +@click.option('--output', '-o', type=click.Path(dir_okay=False), required=True) +def sitemap(sitemap_url, max_pages, config, format, output): + """Analyze eligible URLs from an XML sitemap or sitemap index.""" + try: + cfg = _configuration(config, max_pages=max_pages) + analyzer = SEOAnalyzer(cfg) + results = asyncio.run(analyzer.analyze_sitemap(sitemap_url)) + _report(analyzer.generate_site_report(results), cfg, format, output) + except click.ClickException: + raise + except Exception as exc: + raise click.ClickException(str(exc)) from exc @cli.command() -@click.option('--input', '-i', 'input_file', type=click.Path(exists=True), required=True, help='Input JSON file') -@click.option('--format', '-f', type=click.Choice(['html', 'csv', 'xlsx']), required=True, help='Output format') -@click.option('--output', '-o', type=click.Path(), required=True, help='Output file path') -@click.option('--config', '-c', type=click.Path(exists=True), help='Configuration file') -def export(input_file: str, format: str, output: str, config: Optional[str]): - """Convert analysis results to different formats.""" - - # Load data - with open(input_file, 'r') as f: - data = json.load(f) - - # Load configuration - if config: - cfg = Config.from_file(config) - else: - cfg = Config() - - # Export - exporter = ExportManager(cfg.export) - exported_file = exporter.export(data, format, output) - - console.print(f"[green]✓[/green] Exported to: {exported_file}") +@click.option('--input', '-i', 'input_file', type=CONFIG_PATH, required=True) +@click.option('--format', '-f', type=click.Choice(['html', 'csv', 'xlsx']), required=True) +@click.option('--output', '-o', type=click.Path(dir_okay=False), required=True) +@click.option('--config', '-c', type=CONFIG_PATH) +def export(input_file, format, output, config): + """Convert a page or site JSON report to another format.""" + try: + data = json.loads(Path(input_file).read_text(encoding='utf-8'), parse_constant=_reject_json_constant) + if not isinstance(data, dict): + raise ValueError('A report must be a JSON object') + cfg = _configuration(config) + destination = ExportManager(cfg.export).export(data, format, output) + console.print(f'Exported to: {destination}', markup=False) + except Exception as exc: + raise click.ClickException(str(exc)) from exc def main(): - """Main entry point.""" cli() if __name__ == '__main__': - main() \ No newline at end of file + main() diff --git a/tfq0seo/core/app.py b/tfq0seo/core/app.py index 971dc08..e51bc21 100644 --- a/tfq0seo/core/app.py +++ b/tfq0seo/core/app.py @@ -4,17 +4,27 @@ import time import hashlib import json +import math +import copy +from functools import partial import psutil from typing import Dict, List, Any, Optional, AsyncIterator, Set, Tuple from urllib.parse import urlparse -from collections import defaultdict, Counter +from collections import defaultdict, Counter, OrderedDict from dataclasses import dataclass, field from enum import Enum -from datetime import datetime, timedelta import logging from .config import Config from .crawler import Crawler +from .models import (ANALYZER_NAMES, SCHEMA_VERSION, FetchResult, PageResult, SiteReport, + ContractError, normalize_fetch_result, validate_analyzer_result) +from .report_contracts import validate_page_result, validate_site_report +from ..page_facts import FACTS_VERSION, extract_page_facts +from ..urls import resolve_url +from ..site_analysis import analyze_site, url_identity +from ..rules import (RULESET_VERSION, SCORING_VERSION, get_rule, rule_result, + merge_rule_results, rule_coverage, finding_penalty, recommendations_for) from .report_optimizer import ( aggregate_issues, generate_specific_recommendations, @@ -94,831 +104,776 @@ class CrawlProgress: class AnalysisCache: - """Simple in-memory cache for analysis results.""" - - def __init__(self, ttl_seconds: int = 3600): - self.cache: Dict[str, Tuple[Dict, float]] = {} + """Bounded LRU cache of immutable snapshots, keyed by analysis inputs.""" + + def __init__(self, ttl_seconds: int = 3600, max_bytes: int = 100 * 1024 * 1024): + self.cache = OrderedDict() self.ttl = ttl_seconds - - def get(self, url: str) -> Optional[Dict]: - """Get cached result if not expired.""" - if url in self.cache: - result, timestamp = self.cache[url] - if time.time() - timestamp < self.ttl: - return result - else: - del self.cache[url] - return None - - def set(self, url: str, result: Dict) -> None: - """Cache a result.""" - self.cache[url] = (result, time.time()) - + self.max_bytes = max_bytes + self.size_bytes = 0 + + def get(self, key: str) -> Optional[Dict]: + entry = self.cache.get(key) + if entry is None: + return None + value, created, size = entry + if time.monotonic() - created >= self.ttl: + self.size_bytes -= size + del self.cache[key] + return None + self.cache.move_to_end(key) + return copy.deepcopy(value) + + def set(self, key: str, result: Dict) -> None: + self.clear_expired() + size = len(json.dumps(result, ensure_ascii=False, allow_nan=False).encode('utf-8')) + if size > self.max_bytes: + return + previous = self.cache.pop(key, None) + if previous: + self.size_bytes -= previous[2] + while self.cache and self.size_bytes + size > self.max_bytes: + self.size_bytes -= self.cache.popitem(last=False)[1][2] + self.cache[key] = (copy.deepcopy(result), time.monotonic(), size) + self.size_bytes += size + def clear_expired(self) -> None: - """Remove expired entries.""" - current_time = time.time() - expired = [url for url, (_, timestamp) in self.cache.items() - if current_time - timestamp >= self.ttl] - for url in expired: - del self.cache[url] + for key in list(self.cache): + if time.monotonic() - self.cache[key][1] >= self.ttl: + self.size_bytes -= self.cache.pop(key)[2] + + def clear(self) -> None: + self.cache.clear() + self.size_bytes = 0 class SEOAnalyzer: - """Advanced SEO analyzer with parallel processing and intelligent coordination.""" - - def __init__(self, config: Optional[Config] = None, mode: AnalysisMode = AnalysisMode.STANDARD): - """Initialize the SEO analyzer with configuration and mode.""" + """Coordinate bounded fetches, explicit analysis outcomes, and complete reports.""" + + def __init__(self, config: Optional[Config] = None, mode: Optional[AnalysisMode] = None): self.config = config or Config() - self.mode = mode + self.config.require_valid() + self.mode = AnalysisMode(mode or self.config.analysis.analysis_mode) + if not self._enabled_analyzers(): + raise ValueError('The selected mode has no enabled analyzers') + self.cache = AnalysisCache(self.config.crawler.cache_ttl, + self.config.crawler.cache_size_mb * 1024 * 1024) self.crawler = None + self._analysis_slots = None + self._analysis_loop = None + self._semaphore = None + self._start_time = None + self._reset_state() + + def _reset_state(self) -> None: self.results = [] self.broken_links: Set[str] = set() self.redirects: Dict[str, str] = {} - self.duplicate_content: Dict[str, List[str]] = defaultdict(list) - self.analysis_contexts: Dict[str, AnalysisContext] = {} + self.duplicate_content = defaultdict(list) + self.analysis_contexts = {} self.stats = AnalysisStats() self.progress = CrawlProgress() - self.cache = AnalysisCache(ttl_seconds=self.config.crawler.cache_ttl if hasattr(self.config.crawler, 'cache_ttl') else 3600) - self._semaphore = None - self._start_time = None - self._page_times: List[float] = [] - - # Ensure backward compatibility with crawler config - if not hasattr(self.config.crawler, 'concurrent_requests'): - self.config.crawler.concurrent_requests = getattr(self.config.crawler, 'max_concurrent', 10) - + self._page_times = [] + self.link_checks = [] + self._crawl_complete = False + self._run_limits = [] + self._discovery_errors = [] + self._site_start_url = None + + def _begin_run(self) -> None: + self.config.require_valid() + self._reset_state() + self._start_time = time.time() + self.stats.analysis_start = self._start_time + self._semaphore = asyncio.Semaphore(self.config.analysis.max_analysis_threads) + def _get_page_priority(self, url: str, depth: int = 0) -> PagePriority: - """Determine page priority based on URL and depth.""" - parsed = urlparse(url) - path = parsed.path.lower() - - # Homepage is always critical - if path in ['/', '', '/index.html', '/index.php']: - return PagePriority.CRITICAL - - # Key pages are high priority - key_paths = ['/about', '/contact', '/products', '/services', '/pricing', '/features'] - if any(path.startswith(p) for p in key_paths): - return PagePriority.HIGH - - # Depth-based priority - if depth <= 1: - return PagePriority.HIGH - elif depth <= 2: + try: + path = urlparse(url).path + except ValueError: return PagePriority.MEDIUM - else: - return PagePriority.LOW - + if path in ('', '/', '/index.html', '/index.php'): + return PagePriority.CRITICAL + return PagePriority.HIGH if depth <= 1 else PagePriority.MEDIUM if depth <= 2 else PagePriority.LOW + def _should_skip_analysis(self, url: str) -> bool: - """Check if URL should be skipped from analysis.""" - # Skip certain file types - skip_extensions = {'.pdf', '.doc', '.xls', '.zip', '.mp4', '.mp3', '.jpg', '.png', '.gif'} - parsed = urlparse(url) - path_lower = parsed.path.lower() - - return any(path_lower.endswith(ext) for ext in skip_extensions) - + try: + return urlparse(url).path.lower().endswith( + ('.pdf', '.doc', '.xls', '.zip', '.mp4', '.mp3', '.jpg', '.png', '.gif')) + except ValueError: + return False + def _calculate_content_hash(self, content: str) -> str: - """Calculate hash of content for duplicate detection.""" - # Normalize content for comparison - normalized = ' '.join(content.lower().split()) - return hashlib.md5(normalized.encode()).hexdigest()[:16] - - async def analyze_page(self, page_data: Dict[str, Any], context: Optional[AnalysisContext] = None) -> Dict[str, Any]: - """Analyze a single page with enhanced error handling and caching.""" + return hashlib.sha256(' '.join(content.split()).encode('utf-8')).hexdigest() + + def _enabled_analyzers(self) -> List[str]: + names = self.config.analysis.enabled_analyzers + return [name for name in names if self.mode != AnalysisMode.QUICK or name in ('seo', 'technical')] + + async def analyze_page(self, page_data: FetchResult, + context: Optional[AnalysisContext] = None) -> PageResult: + page_data = normalize_fetch_result(page_data, '$.fetch') url = page_data['url'] - - # Check cache first - if self.mode != AnalysisMode.DEEP: - cached = self.cache.get(url) - if cached: - logger.debug(f"Using cached analysis for {url}") - self.stats.successful_analyses += 1 - return cached - - # Create context if not provided - if not context: - context = AnalysisContext(url=url) - - # Handle errors - if 'error' in page_data: - self.stats.failed_analyses += 1 - return { - 'url': url, - 'error': page_data.get('error'), - 'status_code': page_data.get('status_code', 0), - 'context': { - 'depth': context.depth, - 'priority': context.priority.value - } - } - - soup = page_data.get('soup') - if not soup: - self.stats.failed_analyses += 1 - return { - 'url': url, - 'error': 'No content to analyze', - 'status_code': page_data.get('status_code', 0) - } - - # Skip non-HTML content - if self._should_skip_analysis(url): - self.stats.skipped_pages += 1 - return { - 'url': url, - 'skipped': True, - 'reason': 'Non-HTML content' - } - - # Track broken links and redirects - status_code = page_data.get('status_code', 200) - if status_code >= 400: - self.broken_links.add(url) - elif 300 <= status_code < 400: - redirect_url = page_data.get('redirect_url') - if redirect_url: - self.redirects[url] = redirect_url - - # Check for duplicate content - content_text = soup.get_text(strip=True) - content_hash = self._calculate_content_hash(content_text[:5000]) # First 5000 chars - self.duplicate_content[content_hash].append(url) - - # Initialize results - results = { - 'url': url, - 'status_code': status_code, - 'load_time': page_data.get('load_time', 0), + context = context or AnalysisContext(url=url, depth=page_data.get('depth', 0), + parent_url=page_data.get('parent_url')) + status = page_data.get('status_code', 0) + result = { + 'schema_version': SCHEMA_VERSION, 'url': url, + 'requested_url': page_data.get('requested_url', page_data.get('redirected_from') or url), + 'status_code': status, 'load_time': page_data.get('load_time'), 'content_length': page_data.get('content_length', 0), 'timestamp': page_data.get('timestamp', time.time()), - 'context': { - 'depth': context.depth, - 'priority': context.priority.value, - 'parent_url': context.parent_url - }, - 'content_hash': content_hash + 'timings': page_data.get('timings', {}), + 'redirect_chain': copy.deepcopy(page_data.get('redirect_chain', [])), + 'truncated': bool(page_data.get('truncated', False)), + 'context': {'depth': context.depth, 'priority': context.priority.value, + 'parent_url': context.parent_url}, + 'overall_score': None, 'issues': [], 'issue_counts': self._count_issues([]), + 'recommendations': [], 'status': 'complete' + } + if status >= 400: + self.broken_links.add(url) + if result['requested_url'] != url: + self.redirects[result['requested_url']] = url + if page_data.get('error') and (not page_data.get('skipped') or status >= 400): + result.update(status='error', error=str(page_data['error'])) + self._record_analysis(result) + return result + if page_data.get('skipped') or self._should_skip_analysis(url): + result.update(status='skipped', skipped=True, + reason=page_data.get('reason') or page_data.get('error') or 'Non-HTML content') + self._record_analysis(result) + return result + soup = page_data.get('soup') + if soup is None: + result.update(status='error', error='No HTML content to analyze') + self._record_analysis(result) + return result + + facts = extract_page_facts(soup, url, headers=page_data['headers']) + html = facts.html + content_hash = self._calculate_content_hash(facts.text) + result['content_hash'] = content_hash + result['page_facts'] = facts.to_dict() + signature = json.dumps({'url': url, 'html': html, 'headers': page_data['headers'], + 'status': status, 'load_time': result['load_time'], + 'content_length': result['content_length'], 'truncated': result['truncated'], + 'mode': self.mode.value, 'analysis': self.config.to_dict()['analysis'], + 'schema': SCHEMA_VERSION, 'ruleset': RULESET_VERSION, + 'scoring': SCORING_VERSION, 'facts': FACTS_VERSION}, sort_keys=True, allow_nan=False) + cache_key = hashlib.sha256(signature.encode('utf-8')).hexdigest() + cached = self.cache.get(cache_key) if self.config.crawler.cache_enabled and self.mode != AnalysisMode.DEEP else None + if cached is not None: + cached.update({key: result[key] for key in ('context', 'timestamp', 'requested_url', 'redirect_chain', 'timings')}) + cached.update(cached=True, analysis_time=0.0) + self._record_analysis(cached) + return cached + + functions = {'seo': analyze_seo, 'content': analyze_content, 'technical': analyze_technical, + 'performance': analyze_performance, 'links': analyze_links} + options = { + 'seo': {'headers': page_data['headers']}, + 'content': {'target_keywords': self.config.analysis.target_keywords}, + 'technical': {'headers': page_data['headers'], 'status_code': status}, + 'performance': {'load_time': result['load_time'], 'content_length': result['content_length']}, + # Target status is resolved after all available fetches, not in completion order. + 'links': {'broken_links': None}, } - + started = time.perf_counter() + names = self._enabled_analyzers() + outputs = await asyncio.gather(*[ + self._run_analyzer_safe(name, functions[name], soup, url, facts=facts, **options.get(name, {})) + for name in names]) + result.update(outputs) + errors = {name: result[name]['error'] for name in names if result[name].get('error')} + partial_analyzers = [name for name in names if result[name].get('status') == 'partial'] + result['coverage'] = {'enabled_analyzers': names, + 'completed_analyzers': [name for name in names if name not in errors], + 'failed_analyzers': list(errors), + 'partial_analyzers': partial_analyzers, + 'ratio': (len(names) - len(errors)) / len(names) if names else 0, + 'content_complete': not result['truncated'], + 'measurement_source': 'static_html'} + result['analyzer_errors'] = errors + if errors or partial_analyzers or result['truncated']: + result['status'] = 'partial' + if len(errors) == len(names): + result.update(status='error', error='All enabled analyzers failed') + self._apply_rule_scoring(result) + result['overall_score'] = self._calculate_weighted_score(result) + result['issues'] = self._aggregate_page_issues(result) + result['issue_counts'] = self._count_issues(result['issues']) + result['recommendations'] = self._generate_page_recommendations(result) + result['analysis_time'] = time.perf_counter() - started + self._record_analysis(result) + if self.config.crawler.cache_enabled and not errors and not partial_analyzers: + self.cache.set(cache_key, result) + return result + + async def _run_analyzer_safe(self, name, analyzer_func, *args, **kwargs): try: - start_time = time.time() - - # Run analyzers based on mode - if self.mode == AnalysisMode.QUICK: - # Quick mode: Only essential analyzers - tasks = [ - self._run_analyzer_safe('seo', analyze_seo, soup, url), - self._run_analyzer_safe('technical', analyze_technical, soup, url, - headers=page_data.get('headers'), - status_code=status_code) - ] - elif self.mode == AnalysisMode.DEEP: - # Deep mode: All analyzers with extra parameters - tasks = [ - self._run_analyzer_safe('seo', analyze_seo, soup, url), - self._run_analyzer_safe('content', analyze_content, soup, url, - target_keywords=self.config.analysis.target_keywords), - self._run_analyzer_safe('technical', analyze_technical, soup, url, - headers=page_data.get('headers'), - status_code=status_code), - self._run_analyzer_safe('performance', analyze_performance, soup, url, - load_time=page_data.get('load_time', 0), - content_length=page_data.get('content_length', 0)), - self._run_analyzer_safe('links', analyze_links, soup, url, - broken_links=self.broken_links) - ] - else: # STANDARD mode - # Standard mode: All analyzers with normal parameters - tasks = [ - self._run_analyzer_safe('seo', analyze_seo, soup, url), - self._run_analyzer_safe('content', analyze_content, soup, url, - target_keywords=self.config.analysis.target_keywords), - self._run_analyzer_safe('technical', analyze_technical, soup, url, - headers=page_data.get('headers'), - status_code=status_code), - self._run_analyzer_safe('performance', analyze_performance, soup, url, - load_time=page_data.get('load_time', 0), - content_length=page_data.get('content_length', 0)), - self._run_analyzer_safe('links', analyze_links, soup, url, - broken_links=self.broken_links if self.config.analysis.check_external_links else None) - ] - - # Run analyzers in parallel - analyzer_results = await asyncio.gather(*tasks, return_exceptions=True) - - # Process results - for analyzer_name, result in analyzer_results: - if isinstance(result, Exception): - logger.error(f"Analyzer {analyzer_name} failed for {url}: {result}") - results[analyzer_name] = {'score': 0, 'error': str(result)} - else: - results[analyzer_name] = result - - # Calculate weighted overall score - results['overall_score'] = self._calculate_weighted_score(results) - - # Aggregate all issues with deduplication - results['issues'] = self._aggregate_page_issues(results) - - # Issue counts - results['issue_counts'] = self._count_issues(results['issues']) - self.stats.total_issues += results['issue_counts']['total'] - self.stats.critical_issues += results['issue_counts']['critical'] - self.stats.warnings += results['issue_counts']['warning'] - self.stats.notices += results['issue_counts']['notice'] - - # Generate intelligent recommendations - results['recommendations'] = self._generate_page_recommendations(results) - - # Track analysis time - analysis_time = time.time() - start_time - results['analysis_time'] = analysis_time - self._page_times.append(analysis_time) - - # Cache successful result - self.cache.set(url, results) - - # Update stats - self.stats.successful_analyses += 1 - - except Exception as e: - logger.error(f"Analysis error for {url}: {e}") - results['error'] = f"Analysis error: {str(e)}" - results['overall_score'] = 0 - results['issues'] = [] + if self.config.analysis.parallel_analysis: + loop = asyncio.get_running_loop() + if self._analysis_loop is not loop: + self._analysis_loop = loop + self._analysis_slots = asyncio.Semaphore(self.config.analysis.max_analysis_threads) + slots = self._analysis_slots + await slots.acquire() + try: + future = loop.run_in_executor(None, partial(analyzer_func, *args, **kwargs)) + except Exception: + slots.release() + raise + # Cancelling the await cannot stop a running thread. Keep its + # reservation until the work really finishes. + def finished(completed): + slots.release() + if not completed.cancelled(): + completed.exception() # Retrieve failures even if the awaiting task was cancelled. + future.add_done_callback(finished) + value = await asyncio.shield(future) + else: + value = analyzer_func(*args, **kwargs) + validate_analyzer_result(value, '$.' + name) + if value.get('error'): + raise ValueError(str(value['error'])) + if 'rule_results' in value: + if not isinstance(value['rule_results'], list): + raise ValueError('Analyzer rule_results must be a list') + merge_rule_results(value['rule_results']) + value['rule_coverage'] = rule_coverage(value['rule_results']) + value['status'] = ('partial' if value.get('status') == 'partial' or + value.get('rule_coverage', {}).get('has_errors') else 'complete') + return name, value + except Exception as exc: + logger.error('Analyzer %s failed: %s', name, exc) + return name, {'status': 'error', 'score': None, 'error': str(exc), 'issues': [], 'data': {}} + + async def _run_analyzer(self, name, analyzer_func, *args): + return await self._run_analyzer_safe(name, analyzer_func, *args) + + @staticmethod + def _is_score(value): + return type(value) in (int, float) and math.isfinite(value) and 0 <= value <= 100 + + def _calculate_weighted_score(self, results) -> Optional[float]: + weighted, total = 0.0, 0.0 + for name, weight in self.config.analysis.score_weights.items(): + category = results.get(name, {}) + score = category.get('score') + if not category.get('error') and self._is_score(score): + weighted += score * weight + total += weight + return round(weighted / total, 2) if total else None + + def _apply_rule_scoring(self, result): + """Attribute each unique rule to one available category before weighting.""" + available = [name for name in ANALYZER_NAMES if isinstance(result.get(name), dict) + and not result[name].get('error') and 'rule_results' in result[name]] + if not available: + return # Previously exported payloads retain their original scoring semantics. + evaluations = [] + for name in available: + for original in result[name]['rule_results']: + evaluation = copy.deepcopy(original) + evaluation['reported_by'] = sorted(set(evaluation.get('reported_by', [])) | {name}) + evaluations.append(evaluation) + merged = merge_rule_results(evaluations) + penalties = {name: 0 for name in available} + ledger = [] + for evaluation in merged: + definition = get_rule(evaluation['rule_id']) + candidates = [name for name in available if name in evaluation.get('reported_by', [])] + owner = definition.owner if definition.owner in available else (candidates[0] if candidates else None) + penalty = finding_penalty(evaluation) + evaluation.update(score_owner=owner, penalty=penalty) + if owner is not None and penalty: + penalties[owner] += penalty + ledger.append({'rule_id': definition.rule_id, 'owner': definition.owner, + 'score_owner': owner, 'penalty': penalty, + 'reported_by': evaluation.get('reported_by', [])}) + for name in available: + result[name]['score'] = max(0, 100 - penalties[name]) + result[name]['score_scope'] = 'unique_rules_assigned_to_category' + result[name]['recommendations'] = recommendations_for(result[name].get('issues', [])) + data = result[name].get('data', {}) + if 'recommendations' in data: + data['recommendations'] = list(result[name]['recommendations']) + score = result[name]['score'] + if name == 'seo' and isinstance(data.get('scores'), dict): + data['scores']['total'] = score + elif name == 'content' and isinstance(data.get('quality_assessment'), dict): + data['quality_assessment']['score'] = score + data['quality_assessment']['quality_level'] = ( + 'excellent' if score >= 90 else 'good' if score >= 75 else + 'average' if score >= 60 else 'poor' if score >= 40 else 'very_poor') + elif name == 'performance': + grade = 'A' if score >= 90 else 'B' if score >= 80 else 'C' if score >= 70 else 'D' if score >= 60 else 'F' + result[name]['grade'] = data['grade'] = grade + result['rule_results'] = merged + result['rule_coverage'] = rule_coverage(merged) + result.setdefault('coverage', {})['rules'] = result['rule_coverage'] + result['scoring'] = { + 'version': SCORING_VERSION, 'ruleset_version': RULESET_VERSION, + 'policy': 'One 15/7/3 deduction per failed applicable critical/warning/notice rule; category scores floor at zero.', + 'ownership': 'Use the canonical owner when available; otherwise the first reporting analyzer in the fixed analyzer order.', + 'weights': dict(self.config.analysis.score_weights), 'deductions': ledger, + 'scope': 'Static checklist policy; unknown and inapplicable outcomes do not count as passed checks.', + } + + def _aggregate_page_issues(self, results): + if 'rule_results' in results: + return sorted([copy.deepcopy(item) for item in results['rule_results'] + if item['status'] in ('fail', 'informational')], + key=lambda item: {'critical': 0, 'warning': 1, 'notice': 2}[item['severity']]) + issues, seen = [], set() + for name in ANALYZER_NAMES: + for original in results.get(name, {}).get('issues', []): + issue = copy.deepcopy(original) + key = issue.get('rule_id') or (issue.get('category'), issue.get('message')) + if key in seen: + continue + seen.add(key) + issue.setdefault('source', name) + issue.setdefault('status', 'fail') + issues.append(issue) + return sorted(issues, key=lambda issue: {'critical': 0, 'warning': 1, 'notice': 2}.get(issue.get('severity'), 3)) + + @staticmethod + def _count_issues(issues): + counts = Counter(issue.get('severity', 'notice') for issue in issues) + return {**{name: counts[name] for name in ('critical', 'warning', 'notice')}, 'total': len(issues)} + + def _generate_page_recommendations(self, results): + recommendations, seen = [], set() + for issue in results.get('issues', []): + rule_id = issue.get('rule_id') + text = get_rule(rule_id).recommendation if 'rule_version' in issue else issue.get('fix') + key = rule_id or text + if not text or key in seen: + continue + seen.add(key) + recommendations.append({'priority': issue.get('severity', 'notice'), + 'category': issue.get('category', 'General'), + 'recommendation': text, 'rule_id': issue.get('rule_id')}) + return recommendations + + def _record_analysis(self, result): + validate_page_result(result, strict=True) + if result.get('error'): self.stats.failed_analyses += 1 - - return results - - async def _run_analyzer(self, name: str, analyzer_func: callable, *args) -> Tuple[str, Dict]: - """Run an analyzer with error handling (deprecated, use _run_analyzer_safe).""" + self.progress.errors.append(result['error']) + elif result.get('skipped'): + self.stats.skipped_pages += 1 + else: + self.stats.successful_analyses += 1 + counts = result.get('issue_counts', {}) + self.stats.total_issues += counts.get('total', 0) + self.stats.critical_issues += counts.get('critical', 0) + self.stats.warnings += counts.get('warning', 0) + self.stats.notices += counts.get('notice', 0) + self._page_times.append(result.get('analysis_time', 0)) + if result.get('content_hash'): + self.duplicate_content[result['content_hash']].append(result['url']) + self.progress.pages_analyzed += 1 + self.progress.current_url = result['url'] + self._update_progress() + + def _update_progress(self): + if self._start_time: + elapsed = max(time.time() - self._start_time, 0.000001) + self.progress.speed_pages_per_sec = self.progress.pages_analyzed / elapsed + memory = psutil.Process().memory_info().rss / 1024 / 1024 + self.stats.memory_peak_mb = max(self.stats.memory_peak_mb, memory) + if memory > self.config.max_memory_mb: + raise MemoryError(f'Process memory exceeded configured {self.config.max_memory_mb} MB limit') + + async def analyze_url(self, url: str) -> PageResult: + self._begin_run() try: - # Filter out None arguments for compatibility - filtered_args = [arg for arg in args if arg is not None] - result = analyzer_func(*filtered_args) - return (name, result) - except Exception as e: - logger.error(f"Analyzer {name} failed: {e}", exc_info=True) - return (name, {'score': 0, 'error': str(e), 'issues': []}) - - async def _run_analyzer_safe(self, name: str, analyzer_func: callable, *args, **kwargs) -> Tuple[str, Dict]: - """Run an analyzer with safe parameter handling.""" + async with Crawler(self.config.crawler.as_dict()) as crawler: + self.crawler = crawler + raw = await crawler.fetch_page(url) + result = await self.analyze_page(raw or {'url': url, 'error': 'No fetch result'}) + self.results.append(result) + await self._complete_run() + return result + finally: + self._calculate_final_stats() + + async def analyze_urls(self, urls: List[str]) -> AsyncIterator[PageResult]: + self._begin_run() try: - # Call analyzer with positional and keyword arguments - result = analyzer_func(*args, **kwargs) - return (name, result) - except TypeError as e: - # Try calling with only positional arguments for backward compatibility + async with Crawler(self.config.crawler.as_dict()) as crawler: + self.crawler = crawler + iterator = self._analyze_url_list(crawler, urls) + try: + async for result in iterator: + yield result + finally: + await iterator.aclose() + await self._complete_run() + finally: + self._calculate_final_stats() + + async def _analyze_url_list(self, crawler, urls): + urls = list(dict.fromkeys(self._url_identity(url) for url in urls)) + if len(urls) > self.config.crawler.max_pages: + self._run_limits.append('max_pages') + urls = urls[:self.config.crawler.max_pages] + limit = self.config.crawler.effective_concurrency + async def fetch_analyze(url): + raw = await crawler.fetch_page(url) + return await self.analyze_page(raw or {'url': url, 'error': 'No fetch result'}) + for start in range(0, len(urls), limit): + tasks = [asyncio.create_task(fetch_analyze(url)) for url in urls[start:start + limit]] try: - result = analyzer_func(*args) - return (name, result) - except Exception as e2: - logger.error(f"Analyzer {name} failed with both calling methods: {e}, {e2}") - return (name, {'score': 0, 'error': str(e), 'issues': []}) - except Exception as e: - logger.error(f"Analyzer {name} failed: {e}") - return (name, {'score': 0, 'error': str(e), 'issues': []}) - - def _calculate_weighted_score(self, results: Dict[str, Any]) -> float: - """Calculate weighted overall score with dynamic weighting.""" - # Dynamic weights based on analysis mode - if self.mode == AnalysisMode.QUICK: - weights = { - 'seo': 0.60, - 'technical': 0.40 - } - elif self.mode == AnalysisMode.DEEP: - weights = { - 'seo': 0.25, - 'content': 0.25, - 'technical': 0.20, - 'performance': 0.20, - 'links': 0.10 - } - else: # STANDARD - weights = { - 'seo': 0.30, - 'content': 0.25, - 'technical': 0.20, - 'performance': 0.15, - 'links': 0.10 - } - - total_score = 0 - total_weight = 0 - - for analyzer, weight in weights.items(): - if analyzer in results and 'score' in results[analyzer]: - score = results[analyzer]['score'] - # Apply penalty for critical issues - if analyzer in results and 'issues' in results[analyzer]: - critical_count = sum(1 for i in results[analyzer]['issues'] - if i.get('severity') == 'critical') - score *= (1 - critical_count * 0.1) # 10% penalty per critical issue - - total_score += score * weight - total_weight += weight - - return total_score / total_weight if total_weight > 0 else 0 - - def _aggregate_page_issues(self, results: Dict[str, Any]) -> List[Dict[str, Any]]: - """Aggregate and deduplicate issues from all analyzers.""" - all_issues = [] - seen_issues = set() - - for analyzer in ['seo', 'content', 'technical', 'performance', 'links']: - if analyzer in results and 'issues' in results[analyzer]: - for issue in results[analyzer]['issues']: - # Create unique key for deduplication - issue_key = f"{issue.get('category', '')}:{issue.get('message', '')}" - - if issue_key not in seen_issues: - seen_issues.add(issue_key) - # Add analyzer source - issue['source'] = analyzer - all_issues.append(issue) - - # Sort by severity (critical > warning > notice) - severity_order = {'critical': 0, 'warning': 1, 'notice': 2} - all_issues.sort(key=lambda x: severity_order.get(x.get('severity', 'notice'), 3)) - - return all_issues - - def _count_issues(self, issues: List[Dict[str, Any]]) -> Dict[str, int]: - """Count issues by severity.""" - counts = { - 'critical': 0, - 'warning': 0, - 'notice': 0, - 'total': len(issues) - } - - for issue in issues: - severity = issue.get('severity', 'notice') - if severity in counts: - counts[severity] += 1 - - return counts - - def _generate_page_recommendations(self, results: Dict[str, Any]) -> List[Dict[str, str]]: - """Generate intelligent, prioritized recommendations.""" - recommendations = [] - issues = results.get('issues', []) - - # Group issues by category - issues_by_category = defaultdict(list) - for issue in issues: - category = issue.get('category', 'General') - issues_by_category[category].append(issue) - - # Priority 1: Critical SEO issues - critical_seo = [i for i in issues if i.get('severity') == 'critical' and - i.get('source') == 'seo'] - - if critical_seo: - for issue in critical_seo[:2]: # Top 2 critical SEO issues - rec = { - 'priority': 'critical', - 'category': 'SEO', - 'recommendation': issue.get('fix', 'Fix critical SEO issue'), - 'impact': issue.get('impact', 'High impact on search visibility'), - 'effort': 'low' # Most critical issues are quick fixes - } - recommendations.append(rec) - - # Priority 2: Performance issues affecting Core Web Vitals - if 'performance' in results: - perf_data = results['performance'].get('data', {}) - - if perf_data.get('lcp', 0) > 2.5: - recommendations.append({ - 'priority': 'high', - 'category': 'Performance', - 'recommendation': 'Optimize Largest Contentful Paint (LCP)', - 'impact': 'Improves Core Web Vitals and search rankings', - 'effort': 'medium' - }) - - if perf_data.get('cls', 0) > 0.1: - recommendations.append({ - 'priority': 'high', - 'category': 'Performance', - 'recommendation': 'Fix Cumulative Layout Shift (CLS)', - 'impact': 'Better user experience and Core Web Vitals', - 'effort': 'low' - }) - - # Priority 3: Content optimization - if 'content' in results: - content_data = results['content'].get('data', {}) - - if content_data.get('word_count', 0) < 300: - recommendations.append({ - 'priority': 'high', - 'category': 'Content', - 'recommendation': f"Expand content from {content_data.get('word_count', 0)} to at least 300 words", - 'impact': 'Improves content relevance and ranking potential', - 'effort': 'medium' - }) - - if content_data.get('keyword_density', {}).get('primary', 0) < 0.5: - recommendations.append({ - 'priority': 'medium', - 'category': 'Content', - 'recommendation': 'Increase primary keyword usage naturally', - 'impact': 'Better keyword relevance', - 'effort': 'low' - }) - - # Priority 4: Technical improvements - if 'technical' in results: - tech_data = results['technical'].get('data', {}) - - if not tech_data.get('https'): - recommendations.append({ - 'priority': 'critical', - 'category': 'Security', - 'recommendation': 'Enable HTTPS with SSL certificate', - 'impact': 'Required for security and SEO', - 'effort': 'medium' - }) - - if tech_data.get('mobile', {}).get('readiness') == 'desktop_only': - recommendations.append({ - 'priority': 'critical', - 'category': 'Mobile', - 'recommendation': 'Implement responsive design', - 'impact': 'Required for mobile-first indexing', - 'effort': 'high' - }) - - # Sort by priority - priority_order = {'critical': 0, 'high': 1, 'medium': 2, 'low': 3} - recommendations.sort(key=lambda x: priority_order.get(x['priority'], 4)) - - return recommendations[:10] # Return top 10 recommendations - - def _update_progress(self) -> None: - """Update crawl progress statistics.""" - if self._start_time: - elapsed = time.time() - self._start_time - if elapsed > 0 and self.progress.pages_analyzed > 0: - self.progress.speed_pages_per_sec = self.progress.pages_analyzed / elapsed - - if self.progress.pages_remaining > 0 and self.progress.speed_pages_per_sec > 0: - self.progress.eta_seconds = self.progress.pages_remaining / self.progress.speed_pages_per_sec - - async def analyze_url(self, url: str) -> Dict[str, Any]: - """Analyze a single URL with full context.""" - self._start_time = time.time() - self.stats.analysis_start = self._start_time - - async with Crawler(self.config.crawler.__dict__) as crawler: - self.crawler = crawler - - # Fetch page - page_data = await crawler.fetch_page(url) - - if not page_data: - self.stats.failed_analyses += 1 - return {'url': url, 'error': 'Failed to fetch page'} - - # Create context - context = AnalysisContext( - url=url, - priority=self._get_page_priority(url) - ) - self.analysis_contexts[url] = context - - # Analyze - result = await self.analyze_page(page_data, context) - - # Update stats - self.stats.analysis_end = time.time() - self.stats.total_pages = 1 - - return result - - async def crawl_site(self, start_url: str) -> AsyncIterator[Dict[str, Any]]: - """Crawl and analyze a website with intelligent prioritization.""" - self._start_time = time.time() - self.stats.analysis_start = self._start_time - - # Use semaphore for parallel analysis control - self._semaphore = asyncio.Semaphore(self.config.crawler.concurrent_requests // 2) - - async with Crawler(self.config.crawler.__dict__) as crawler: - self.crawler = crawler - - # Start crawling - crawl_task = asyncio.create_task( - crawler.crawl_site(start_url, self.config.crawler.max_pages) - ) - - # Track processed pages - processed = 0 - analysis_tasks = [] - completed_urls = set() - - while not crawl_task.done() or processed < len(crawler.results) or analysis_tasks: - # Process new crawled pages - while processed < len(crawler.results): - page_data = crawler.results[processed] - processed += 1 - - url = page_data['url'] - if url in completed_urls: - continue - - # Create context - context = AnalysisContext( - url=url, - depth=page_data.get('depth', 0), - priority=self._get_page_priority(url, page_data.get('depth', 0)) - ) - self.analysis_contexts[url] = context - - # Update progress - self.progress.pages_crawled = processed - self.progress.pages_queued = len(crawler.results) - self.progress.current_url = url - self.progress.current_depth = context.depth - self._update_progress() - - # Start analysis task with semaphore - task = asyncio.create_task( - self._analyze_with_semaphore(page_data, context) - ) - analysis_tasks.append(task) - - # Check for completed analysis tasks - if analysis_tasks: - done, pending = await asyncio.wait( - analysis_tasks, - timeout=0.1, - return_when=asyncio.FIRST_COMPLETED - ) - - for task in done: - try: - result = await task - if result: - completed_urls.add(result['url']) + for task in asyncio.as_completed(tasks): + result = await task + self.results.append(result) + yield result + if result.get('error') and not self.config.continue_on_error: + raise RuntimeError(result['error']) + finally: + for task in tasks: + if not task.done(): + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + + async def analyze_sitemap(self, sitemap_url: str) -> List[PageResult]: + self._begin_run() + try: + async with Crawler(self.config.crawler.as_dict()) as discovery: + urls = await discovery.parse_sitemap(sitemap_url, self.config.crawler.max_pages) + self._run_limits.extend(discovery.limit_reasons) + self._discovery_errors.extend(copy.deepcopy(discovery.discovery_errors)) + if not urls: + self.results.append(await self.analyze_page({ + 'url': sitemap_url, 'error': 'Sitemap contains no eligible URLs', + })) + self.crawler = discovery + await self._complete_run() + return self.results + async with Crawler(self.config.crawler.as_dict()) as crawler: + self.crawler = crawler + async for _ in self._analyze_url_list(crawler, urls): + pass + await self._complete_run() + return self.results + finally: + self._calculate_final_stats() + + async def crawl_site(self, start_url: str) -> AsyncIterator[PageResult]: + self._begin_run() + self._site_start_url = start_url + tasks = set() + try: + async with Crawler(self.config.crawler.as_dict()) as crawler: + self.crawler = crawler + producer = asyncio.create_task(crawler.crawl_site(start_url, self.config.crawler.max_pages)) + processed = 0 + async def analyze(raw): + context = AnalysisContext(url=raw['url'], depth=raw.get('depth', 0), + priority=self._get_page_priority(raw['url'], raw.get('depth', 0)), + parent_url=raw.get('parent_url')) + try: + return await self._analyze_with_semaphore(raw, context) + finally: + raw.pop('soup', None) + raw.pop('html', None) + try: + while not producer.done() or processed < len(crawler.results) or tasks: + if producer.done(): + await producer + while processed < len(crawler.results) and len(tasks) < self.config.analysis.max_analysis_threads: + raw = crawler.results[processed] + processed += 1 + self.progress.pages_crawled = processed + tasks.add(asyncio.create_task(analyze(raw))) + if tasks: + done, _ = await asyncio.wait(tasks, timeout=0.05, return_when=asyncio.FIRST_COMPLETED) + for task in done: + tasks.remove(task) + result = await task self.results.append(result) - self.progress.pages_analyzed += 1 - self._update_progress() yield result - except Exception as e: - logger.error(f"Analysis task failed: {e}") - - analysis_tasks.remove(task) - - # Brief sleep to prevent busy waiting - if not done: - await asyncio.sleep(0.01) - else: - # Sleep when no tasks are pending - await asyncio.sleep(0.01) - - # Wait for remaining analysis tasks - if analysis_tasks: - remaining_results = await asyncio.gather(*analysis_tasks, return_exceptions=True) - for result in remaining_results: - if isinstance(result, Exception): - logger.error(f"Final analysis task failed: {result}") - elif result: - self.results.append(result) - self.progress.pages_analyzed += 1 - yield result - - # Ensure crawl completes - await crawl_task - - # Final stats update - self.stats.analysis_end = time.time() - self.stats.total_pages = len(self.results) + if result.get('error') and not self.config.continue_on_error: + raise RuntimeError(result['error']) + else: + await asyncio.sleep(0.005) + await producer + finally: + for task in [producer] + list(tasks): + if not task.done(): + task.cancel() + await asyncio.gather(producer, *tasks, return_exceptions=True) + await self._complete_run() + finally: self._calculate_final_stats() - - async def _analyze_with_semaphore(self, page_data: Dict[str, Any], context: AnalysisContext) -> Optional[Dict[str, Any]]: - """Analyze a page with semaphore control.""" + + async def _analyze_with_semaphore(self, page_data, context): + if self._semaphore is None: + self._semaphore = asyncio.Semaphore(self.config.analysis.max_analysis_threads) async with self._semaphore: - try: - return await self.analyze_page(page_data, context) - except Exception as e: - logger.error(f"Analysis failed for {page_data.get('url')}: {e}") - return None - - def _calculate_final_stats(self) -> None: - """Calculate final statistics.""" + return await self.analyze_page(page_data, context) + + async def _complete_run(self): + self._run_limits = sorted(set(self._run_limits) | set(getattr(self.crawler, 'limit_reasons', []))) + for error in getattr(self.crawler, 'discovery_errors', []): + if error not in self._discovery_errors: + self._discovery_errors.append(copy.deepcopy(error)) + self._crawl_complete = not (self._run_limits or self._discovery_errors) + if self.config.analysis.check_broken_links and self.config.analysis.check_external_links: + await self._check_external_links() + self._resolve_site_links(self.results) + + async def _check_external_links(self): + targets = [] + for page in self.results: + links = page.get('links', {}).get('data', {}).get('external_links', []) + targets.extend(link['url'] for link in links[:self.config.analysis.max_external_links_per_page] + if urlparse(link.get('url', '')).scheme in ('http', 'https')) + targets = list(dict.fromkeys(self._url_identity(url) for url in targets))[:self.config.crawler.max_pages] + if not targets: + return + settings = self.config.crawler.as_dict() + settings.update(timeout=self.config.analysis.external_link_timeout, use_sitemap=False) + async with Crawler(settings) as checker: + for start in range(0, len(targets), self.config.crawler.effective_concurrency): + tasks = [asyncio.create_task(checker.fetch_page(url)) for url in + targets[start:start + self.config.crawler.effective_concurrency]] + try: + results = await asyncio.gather(*tasks) + finally: + for task in tasks: + if not task.done(): + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + for result in results: + if result: + self.link_checks.append({key: result[key] for key in + ('url', 'requested_url', 'status_code', 'error') if key in result}) + + @staticmethod + def _url_identity(url): + return (resolve_url(url, url) or url).split('#', 1)[0] + + def _observed_statuses(self, pages): + observations = defaultdict(set) + for page in pages: + status = page.get('status_code') or 0 + observed_urls = [page.get('url'), page.get('requested_url')] + observed_urls.extend(hop.get('url') for hop in page.get('redirect_chain', [])) + for url in observed_urls: + if url: + observations[self._url_identity(url)].add(status) + # Repeated, contradictory observations cannot establish one outcome. + return {url: next(iter(statuses)) if len(statuses) == 1 else 0 + for url, statuses in observations.items()} + + def _resolve_site_links(self, pages, link_checks=None): + if not self.config.analysis.check_broken_links: + return + observations = self._observed_statuses(list(pages) + (self.link_checks if link_checks is None else link_checks)) + for page in pages: + analyzer = page.get('links') + if not analyzer or analyzer.get('error'): + continue + data = analyzer.setdefault('data', {}) + links = [] + if self.config.analysis.check_internal_links: + links.extend(data.get('internal_links', [])) + if self.config.analysis.check_external_links: + links.extend(data.get('external_links', [])) + targets = list(dict.fromkeys(self._url_identity(link['url']) for link in links + if urlparse(link.get('url', '')).scheme in ('http', 'https'))) + broken = [url for url in targets if observations.get(url, 0) >= 400] + checked = [url for url in targets if observations.get(url, 0) >= 100] + data['link_health'] = {'checked': len(checked), 'unchecked': len(targets) - len(checked), + 'broken': len(broken), 'source': 'observed_http_status', + 'status': 'complete' if len(checked) == len(targets) else 'partial'} + data['broken_links'] = broken + data['link_health_status'] = data['link_health']['status'] + if ('rule_results' not in analyzer or + page.get('scoring', {}).get('version') != SCORING_VERSION or + page.get('scoring', {}).get('ruleset_version') != RULESET_VERSION): + data['link_health']['scoring_status'] = 'Legacy scores and findings retained; link observations updated separately.' + continue + analyzer['issues'] = [issue for issue in analyzer.get('issues', []) + if issue.get('rule_id') != 'links.broken'] + outcome = 'fail' if broken else 'unknown' if len(checked) < len(targets) else 'pass' + link_result = rule_result('links.broken', + {'http_statuses': {url: observations[url] for url in checked}, + 'unchecked': [url for url in targets if url not in checked]}, + message=f'{len(broken)} broken link targets found', category='Links', + status=outcome, source='observed_http_status', + applicable=bool(targets), + reason=('No eligible link targets are selected for checking.' if not targets else + 'Some link targets have no HTTP observation.' if outcome == 'unknown' else ''), + details={'broken_links': broken}) + link_result['reported_by'] = ['links'] + analyzer['rule_results'] = [item for item in analyzer.get('rule_results', []) + if item.get('rule_id') != 'links.broken'] + [link_result] + analyzer['rule_coverage'] = rule_coverage(analyzer['rule_results']) + if broken: + analyzer['issues'].append(link_result) + self._apply_rule_scoring(page) + page['overall_score'] = self._calculate_weighted_score(page) + page['issues'] = self._aggregate_page_issues(page) + page['issue_counts'] = self._count_issues(page['issues']) + page['recommendations'] = self._generate_page_recommendations(page) + + def _calculate_final_stats(self): + self.stats.analysis_end = time.time() + self.stats.total_pages = len(self.results) if self._page_times: self.stats.avg_analysis_time = sum(self._page_times) / len(self._page_times) - - if self.results: - scores = [r.get('overall_score', 0) for r in self.results if 'error' not in r] - if scores: - self.stats.avg_page_score = sum(scores) / len(scores) - - # Memory peak - process = psutil.Process() - self.stats.memory_peak_mb = process.memory_info().rss / 1024 / 1024 - - def generate_site_report(self, page_results: Optional[List[Dict[str, Any]]] = None) -> Dict[str, Any]: - """Generate comprehensive site report with advanced analytics.""" - if page_results is None: - page_results = self.results - - if not page_results: - return {'error': 'No pages to analyze'} - - # Separate successful and failed pages - successful_pages = [p for p in page_results if 'error' not in p and not p.get('skipped')] - failed_pages = [p for p in page_results if 'error' in p] - skipped_pages = [p for p in page_results if p.get('skipped')] - - # Calculate aggregate scores by category - category_scores = defaultdict(list) - for page in successful_pages: - for category in ['seo', 'content', 'technical', 'performance', 'links']: - if category in page and 'score' in page[category]: - category_scores[category].append(page[category]['score']) - - # Aggregate all issues - all_issues = [] - for page in successful_pages: - page_issues = page.get('issues', []) - for issue in page_issues: - issue['url'] = page['url'] - all_issues.extend(page_issues) - - # Aggregate and deduplicate issues - aggregated_issues, aggregation_stats = aggregate_issues(all_issues) - - # Find duplicate content - duplicate_groups = [] - for content_hash, urls in self.duplicate_content.items(): - if len(urls) > 1: - duplicate_groups.append({ - 'hash': content_hash, - 'urls': urls, - 'count': len(urls) - }) - - # Compile comprehensive report + scores = [page['overall_score'] for page in self.results if self._is_score(page.get('overall_score'))] + self.stats.avg_page_score = sum(scores) / len(scores) if scores else 0 + counts = self._count_issues([issue for page in self.results for issue in page.get('issues', [])]) + self.stats.total_issues, self.stats.critical_issues = counts['total'], counts['critical'] + self.stats.warnings, self.stats.notices = counts['warning'], counts['notice'] + + def generate_batch_report(self, page_results=None): + return self.generate_site_report(page_results) + + def generate_site_report(self, page_results=None) -> SiteReport: + supplied = self.results if page_results is None else page_results + if not isinstance(supplied, list): + raise ContractError('$.pages', 'must be a list of page results') + for index, page in enumerate(supplied): + validate_page_result(page, path=f'$.pages[{index}]') + if not isinstance(page.get('url'), str) or not page['url'].strip(): + raise ContractError(f'$.pages[{index}].url', 'must identify the page being aggregated') + if 'issues' in page and not isinstance(page['issues'], list): + raise ContractError(f'$.pages[{index}].issues', 'aggregation requires issue records, not summary counts') + # Only the current run's actual result objects carry its crawl context. + # Imported or independently analyzed pages must not inherit old checks, + # entry URLs, limits, or timing from this analyzer instance. + current_run = (page_results is None or supplied is self.results or + bool(self.results) and Counter(map(id, supplied)) == Counter(map(id, self.results))) + link_checks = self.link_checks if current_run else [] + crawl_complete = self._crawl_complete if current_run else False + run_limits = copy.deepcopy(self._run_limits) if current_run else [] + discovery_errors = copy.deepcopy(self._discovery_errors) if current_run else [] + pages = copy.deepcopy(supplied) + if not pages: + return {'schema_version': SCHEMA_VERSION, 'status': 'error', 'error': 'No pages to analyze'} + self._resolve_site_links(pages, link_checks) + site_analysis = analyze_site(pages, start_url=self._site_start_url if current_run else None, + crawl_complete=crawl_complete) + site_pages = {row['url']: row for row in site_analysis['pages']} + for page in pages: + if url_identity(page['url']) in site_pages: + page['site_analysis'] = copy.deepcopy(site_pages[url_identity(page['url'])]) + usable = [page for page in pages if not page.get('error') and not page.get('skipped')] + failed = [page for page in pages if page.get('error')] + skipped = [page for page in pages if page.get('skipped')] + partial_pages = [page for page in usable if page.get('status') == 'partial'] + categories = {} + for name in ANALYZER_NAMES: + scores = [page[name]['score'] for page in usable if name in page + and not page[name].get('error') and self._is_score(page[name].get('score'))] + categories[name] = round(sum(scores) / len(scores), 2) if scores else None + scores = [page['overall_score'] for page in usable if self._is_score(page.get('overall_score'))] + overall = round(sum(scores) / len(scores), 2) if scores else None + issues = [{**copy.deepcopy(issue), 'url': page['url']} for page in usable for issue in page.get('issues', [])] + issues.extend(site_analysis['findings']) + aggregated, stats = aggregate_issues(issues) + counts = self._count_issues(issues) + duplicates = defaultdict(set) + redirect_targets = defaultdict(set) + for page in pages: + if self.config.analysis.check_content_uniqueness and page.get('content_hash'): + duplicates[page['content_hash']].add(page['url']) + if page.get('requested_url') and page['requested_url'] != page['url']: + redirect_targets[page['requested_url']].add(page['url']) + redirects = {url: next(iter(targets)) for url, targets in sorted(redirect_targets.items()) + if len(targets) == 1} + rule_counts = Counter() + for page in usable: + rule_counts.update(page.get('rule_coverage', {}).get('counts', {})) + assessed_rules = sum(rule_counts[status] for status in ('pass', 'fail', 'informational')) + attempted_rules = assessed_rules + rule_counts['unknown'] + rule_counts['error'] + current_scoring = bool(usable) and all( + page.get('scoring', {}).get('version') == SCORING_VERSION and + page.get('scoring', {}).get('ruleset_version') == RULESET_VERSION for page in usable) + duplicate_groups = [{'hash': key, 'urls': sorted(urls), 'count': len(urls)} + for key, urls in duplicates.items() if len(urls) > 1] + observations = self._observed_statuses(pages + link_checks) + broken = sorted({page['url'] for page in pages + link_checks + if observations.get(self._url_identity(page['url']), 0) >= 400}) report = { - 'summary': { - 'total_pages': len(page_results), - 'successful_pages': len(successful_pages), - 'failed_pages': len(failed_pages), - 'skipped_pages': len(skipped_pages), - 'analysis_mode': self.mode.value, - 'analysis_timestamp': time.time(), - 'analysis_duration': self.stats.analysis_end - self.stats.analysis_start if self.stats.analysis_end else 0 - }, - - 'scores': { - 'overall': sum(p.get('overall_score', 0) for p in successful_pages) / len(successful_pages) if successful_pages else 0, - 'categories': { - category: sum(scores) / len(scores) if scores else 0 - for category, scores in category_scores.items() - } - }, - - 'issues': { - 'aggregated': aggregated_issues, - 'stats': aggregation_stats, - 'counts': { - 'critical': self.stats.critical_issues, - 'warning': self.stats.warnings, - 'notice': self.stats.notices, - 'total': self.stats.total_issues, - 'unique': len(aggregated_issues) - }, - 'top_issues': aggregated_issues[:10] if aggregated_issues else [] - }, - - 'technical_health': { - 'broken_links': list(self.broken_links)[:50], # Limit to 50 - 'broken_links_count': len(self.broken_links), - 'redirects': dict(list(self.redirects.items())[:50]), # Limit to 50 - 'redirects_count': len(self.redirects), - 'duplicate_content': duplicate_groups[:20], # Top 20 duplicate groups - 'duplicate_content_count': len(duplicate_groups) - }, - - 'performance_metrics': generate_performance_metrics(successful_pages), - - 'crawl_stats': { - 'pages_per_second': self.progress.speed_pages_per_sec, - 'avg_analysis_time': self.stats.avg_analysis_time, - 'memory_peak_mb': self.stats.memory_peak_mb, - 'cache_hits': len([1 for p in successful_pages if p.get('cached')]), - 'depth_distribution': Counter(p.get('context', {}).get('depth', 0) for p in successful_pages) - }, - - 'recommendations': { - 'specific': generate_specific_recommendations({ - 'overall_score': report['scores']['overall'] if 'scores' in locals() else 0, - 'category_scores': category_scores, - 'aggregated_issues': aggregated_issues, - 'issue_counts': self.stats.__dict__ - }), - 'executive': create_executive_summary({ - 'overall_score': report['scores']['overall'] if 'scores' in locals() else 0, - 'issue_counts': { - 'critical': self.stats.critical_issues, - 'warning': self.stats.warnings, - 'notice': self.stats.notices - }, - 'summary': { - 'total_pages': len(page_results), - 'successful_pages': len(successful_pages) - } - }) - }, - - 'pages': { - 'summary': [ - { - 'url': p.get('url'), - 'score': p.get('overall_score', 0), - 'status_code': p.get('status_code'), - 'load_time': p.get('load_time', 0), - 'issues': p.get('issue_counts', {}), - 'priority': p.get('context', {}).get('priority'), - 'depth': p.get('context', {}).get('depth') - } for p in successful_pages[:100] # Limit to 100 - ], - 'detailed': successful_pages[:50] if len(successful_pages) <= 50 else [ - p for p in successful_pages if p.get('overall_score', 100) < 70 - ][:50], # Pages with issues - 'failed': [ - {'url': p.get('url'), 'error': p.get('error'), 'status_code': p.get('status_code', 0)} - for p in failed_pages[:20] - ] - }, - - 'metadata': { - 'analyzer_version': '2.0.0', - 'config': { - 'max_pages': self.config.crawler.max_pages, - 'analysis_mode': self.mode.value, - 'concurrent_requests': self.config.crawler.concurrent_requests - } - } + 'schema_version': SCHEMA_VERSION, + 'site_analysis': site_analysis, + 'status': 'error' if not usable else 'partial' if ( + failed or partial_pages or run_limits or discovery_errors) else 'complete', + 'summary': {'total_pages': len(pages), 'successful_pages': len(usable) - len(partial_pages), + 'partial_pages': len(partial_pages), 'failed_pages': len(failed), 'skipped_pages': len(skipped), + 'analysis_mode': self.mode.value, 'analysis_timestamp': time.time(), + 'analysis_duration': max(0, self.stats.analysis_end - self.stats.analysis_start) + if current_run and self.stats.analysis_end else 0, + 'crawl_complete': crawl_complete, + 'limits_reached': run_limits, + 'discovery_errors': discovery_errors, + 'scope_note': 'Results describe fetched pages; unvisited targets remain unchecked.'}, + 'scores': {'overall': overall, 'categories': categories, 'source': 'static_rule_heuristics', + 'scoring_versions': sorted({page['scoring']['version'] for page in usable if page.get('scoring')})}, + 'rule_coverage': {'counts': dict(rule_counts), 'assessed': assessed_rules, + 'total': sum(rule_counts.values()), + 'ratio': assessed_rules / attempted_rules if attempted_rules else None, + 'scope': 'Counts are unique rule evaluations per page, not a complete site inventory.'}, + 'scoring': {'version': SCORING_VERSION if current_scoring else 'legacy_or_mixed', + 'ruleset_version': RULESET_VERSION if current_scoring else None, + 'policy': ('Average page scores; each page deducts each failed applicable rule once in its assigned category.' + if current_scoring else 'Average recorded page scores; legacy or mixed inputs retain their original scoring semantics.'), + 'weights': dict(self.config.analysis.score_weights)}, + 'issues': {'aggregated': aggregated, 'stats': stats, 'counts': {**counts, 'unique': len(aggregated)}, + 'top_issues': aggregated[:10]}, + 'technical_health': {'broken_links': broken, 'broken_links_count': len(broken), + 'redirects': redirects, 'redirects_count': len(redirects), + 'duplicate_content': duplicate_groups, 'duplicate_content_count': len(duplicate_groups), + 'link_checks': copy.deepcopy(link_checks)}, + 'performance_metrics': generate_performance_metrics(pages), + 'crawl_stats': {'pages_per_second': self.progress.speed_pages_per_sec if current_run else 0, + 'avg_analysis_time': self.stats.avg_analysis_time if current_run else 0, + 'memory_peak_mb': self.stats.memory_peak_mb if current_run else 0, + 'cache_hits': sum(bool(page.get('cached')) for page in pages), + 'depth_distribution': dict(Counter(page.get('context', {}).get('depth', 0) for page in pages))}, + 'pages': {'summary': [{'url': page['url'], 'score': page.get('overall_score'), + 'status': page.get('status', 'complete'), 'status_code': page.get('status_code'), + 'load_time': page.get('load_time'), 'issues': page.get('issue_counts', {}), + 'priority': page.get('context', {}).get('priority'), + 'depth': page.get('context', {}).get('depth')} for page in usable], + 'detailed': usable, 'failed': failed, 'skipped': skipped}, + 'metadata': {'analyzer_version': self.config.version, 'schema_version': SCHEMA_VERSION, + 'config': {'max_pages': self.config.crawler.max_pages, 'analysis_mode': self.mode.value, + 'concurrent_requests': self.config.crawler.effective_concurrency, + 'enabled_analyzers': self._enabled_analyzers()}}, } - + recommendations = generate_specific_recommendations(report) + report['recommendations'] = {'specific': recommendations} + report['recommendations']['executive'] = create_executive_summary(report) + validate_site_report(report, strict=True) return report - - def get_real_time_stats(self) -> Dict[str, Any]: - """Get real-time statistics for monitoring.""" - process = psutil.Process() - - return { - 'progress': { - 'pages_queued': self.progress.pages_queued, - 'pages_crawled': self.progress.pages_crawled, - 'pages_analyzed': self.progress.pages_analyzed, - 'current_url': self.progress.current_url, - 'current_depth': self.progress.current_depth, - 'speed': self.progress.speed_pages_per_sec, - 'eta_seconds': self.progress.eta_seconds - }, - 'stats': { - 'successful': self.stats.successful_analyses, - 'failed': self.stats.failed_analyses, - 'skipped': self.stats.skipped_pages, - 'issues_found': self.stats.total_issues, - 'avg_score': self.stats.avg_page_score, - 'avg_time': self.stats.avg_analysis_time - }, - 'resources': { - 'memory_mb': process.memory_info().rss / 1024 / 1024, - 'cpu_percent': process.cpu_percent(), - 'threads': process.num_threads(), - 'cache_size': len(self.cache.cache) - }, - 'health': { - 'broken_links': len(self.broken_links), - 'redirects': len(self.redirects), - 'duplicate_content': len([g for g in self.duplicate_content.values() if len(g) > 1]), - 'errors': self.progress.errors[-10:] # Last 10 errors - } - } - - def get_crawl_statistics(self) -> Dict[str, Any]: - """Get current crawl statistics (backward compatibility).""" - return self.get_real_time_stats() - - def cleanup(self) -> None: - """Cleanup resources and clear caches.""" - self.cache.clear_expired() - self.results.clear() - self.broken_links.clear() - self.redirects.clear() - self.duplicate_content.clear() - self.analysis_contexts.clear() - self._page_times.clear() - - # Force garbage collection - import gc - gc.collect() \ No newline at end of file + + def get_real_time_stats(self): + return {'progress': {'pages_crawled': self.progress.pages_crawled, + 'pages_analyzed': self.progress.pages_analyzed, 'current_url': self.progress.current_url, + 'speed': self.progress.speed_pages_per_sec}, + 'stats': {'successful': self.stats.successful_analyses, 'failed': self.stats.failed_analyses, + 'skipped': self.stats.skipped_pages, 'issues_found': self.stats.total_issues, + 'avg_score': self.stats.avg_page_score, 'avg_time': self.stats.avg_analysis_time}, + 'resources': {'memory_mb': psutil.Process().memory_info().rss / 1024 / 1024, + 'cache_size': len(self.cache.cache)}, + 'health': {'broken_links': len(self.broken_links), 'redirects': len(self.redirects), + 'errors': self.progress.errors[-10:]}} + + def get_crawl_statistics(self): + stats = self.get_real_time_stats() + return {**stats, 'pages_per_second': self.progress.speed_pages_per_sec, + 'memory_usage': stats['resources']['memory_mb']} + + def cleanup(self): + self.cache.clear() + self._reset_state() diff --git a/tfq0seo/core/config.py b/tfq0seo/core/config.py index e079752..f6716e3 100644 --- a/tfq0seo/core/config.py +++ b/tfq0seo/core/config.py @@ -3,14 +3,13 @@ import os import json import yaml -import logging -from dataclasses import dataclass, field, asdict -from typing import Dict, Optional, List, Any, Union, Set +import math +import re +import copy +from dataclasses import dataclass, field, asdict, fields +from typing import Dict, Optional, List, Any, Union, Tuple, get_args, get_origin, get_type_hints from enum import Enum from pathlib import Path -from datetime import timedelta - -logger = logging.getLogger(__name__) class ConfigProfile(Enum): @@ -29,9 +28,6 @@ class OutputFormat(Enum): JSON = "json" CSV = "csv" XLSX = "xlsx" - PDF = "pdf" - MARKDOWN = "markdown" - XML = "xml" class LogLevel(Enum): @@ -46,48 +42,38 @@ class LogLevel(Enum): @dataclass class CrawlerConfig: """Advanced crawler configuration with validation.""" - # Concurrency settings + PROFILE_FIELDS = ('max_concurrent', 'concurrent_requests', 'max_pages', 'max_depth', + 'timeout', 'max_retries', 'cache_enabled', 'use_connection_pooling', + 'adaptive_delay') + # Concurrency and request timeouts max_concurrent: int = 20 - concurrent_requests: int = 10 # Alias for compatibility + concurrent_requests: Optional[int] = None # Legacy alias; max_concurrent is canonical. max_connections_per_host: int = 5 - semaphore_limit: int = 30 - - # Timeout settings timeout: int = 30 connect_timeout: int = 10 read_timeout: int = 30 - total_timeout: int = 300 - - # User agent and headers - user_agent: str = "tfq0seo/3.0.0 (Advanced SEO Bot; +https://github.com/tfq0seo)" + + # Request headers and redirects + user_agent: str = "tfq0seo/3.0.0 (+https://github.com/TFQ0/tfq0seo)" custom_headers: Dict[str, str] = field(default_factory=dict) - rotate_user_agents: bool = False - user_agent_list: List[str] = field(default_factory=list) - - # Redirect handling follow_redirects: bool = True max_redirects: int = 10 - redirect_cache_ttl: int = 3600 - - # Crawl limits + + # Crawl limits and rate limiting max_pages: int = 500 max_depth: int = 5 max_page_size: int = 10485760 # 10MB max_crawl_time: int = 3600 # 1 hour - - # Rate limiting delay_between_requests: float = 0.0 adaptive_delay: bool = True min_delay: float = 0.0 max_delay: float = 5.0 rate_limit_per_second: Optional[float] = None - - # Robots.txt handling + + # Robots and URL filtering respect_robots_txt: bool = True robots_cache_ttl: int = 86400 # 24 hours crawl_delay_factor: float = 1.0 # Multiplier for robots.txt delay - - # URL filtering allowed_domains: List[str] = field(default_factory=list) allowed_schemes: List[str] = field(default_factory=lambda: ['http', 'https']) excluded_patterns: List[str] = field(default_factory=lambda: [ @@ -95,64 +81,72 @@ class CrawlerConfig: r'/wp-admin', r'/admin', r'/login', r'\?.*session', r'\?.*utm_' ]) - include_query_strings: bool = True - normalize_urls: bool = True - - # Content handling - parse_javascript: bool = False - execute_javascript: bool = False - wait_for_javascript: float = 0.0 + + # Response storage, retries, and cache store_html: bool = False - compress_stored_html: bool = True - - # Retry settings max_retries: int = 3 retry_on_status: List[int] = field(default_factory=lambda: [429, 500, 502, 503, 504]) retry_backoff_factor: float = 2.0 - - # Cache settings cache_enabled: bool = True cache_ttl: int = 3600 cache_size_mb: int = 100 - - # Advanced features + + # Discovery and connections use_sitemap: bool = True discover_sitemaps: bool = True - prioritize_sitemap_urls: bool = True - use_http2: bool = True use_connection_pooling: bool = True dns_cache_ttl: int = 300 verify_ssl: bool = True proxy: Optional[str] = None - + + @property + def effective_concurrency(self) -> int: + return self.concurrent_requests if self.concurrent_requests is not None else self.max_concurrent + + def as_dict(self) -> Dict[str, Any]: + errors = _unexpected_field_issues(self, 'crawler') + if errors: + raise ValueError('; '.join(errors)) + values = asdict(self) + values['max_concurrent'] = self.effective_concurrency + values.pop('concurrent_requests', None) + return values + def validate(self) -> List[str]: - """Validate configuration and return list of issues.""" issues = [] - - if self.max_concurrent <= 0: - issues.append("max_concurrent must be positive") - if self.max_concurrent > 100: - issues.append("max_concurrent > 100 may cause issues") - - if self.timeout <= 0: - issues.append("timeout must be positive") - - if self.max_pages <= 0: - issues.append("max_pages must be positive") - - if self.max_depth < 0: - issues.append("max_depth must be non-negative") - - if self.delay_between_requests < 0: - issues.append("delay_between_requests must be non-negative") - - if self.rate_limit_per_second and self.rate_limit_per_second <= 0: - issues.append("rate_limit_per_second must be positive") - + for name in ('max_concurrent', 'max_connections_per_host', 'timeout', 'connect_timeout', + 'read_timeout', 'max_pages', 'max_page_size', 'max_crawl_time', 'cache_size_mb'): + if getattr(self, name) <= 0: + issues.append(f"{name} must be positive") + if self.concurrent_requests is not None and self.concurrent_requests <= 0: + issues.append('concurrent_requests must be positive') + for name in ('max_depth', 'max_redirects', 'max_retries', 'delay_between_requests', + 'retry_backoff_factor', 'min_delay', 'max_delay', 'cache_ttl', 'robots_cache_ttl'): + if getattr(self, name) < 0: + issues.append(f"{name} must be non-negative") + if self.rate_limit_per_second is not None and self.rate_limit_per_second <= 0: + issues.append('rate_limit_per_second must be positive') + if self.max_delay < self.min_delay: + issues.append('max_delay must be at least min_delay') + if not self.allowed_schemes or set(self.allowed_schemes) - {'http', 'https'}: + issues.append('allowed_schemes must contain only http and/or https') + for index, pattern in enumerate(self.excluded_patterns): + try: + re.compile(pattern) + except re.error: + issues.append(f'excluded_patterns[{index}] is not a valid regular expression') + if any(code < 400 or code > 599 for code in self.retry_on_status): + issues.append('retry_on_status must contain HTTP error status codes') return issues - + def apply_profile(self, profile: ConfigProfile) -> None: - """Apply a configuration profile.""" + """Replace preset-controlled values; CUSTOM leaves current values intact.""" + profile = ConfigProfile(profile) + if profile == ConfigProfile.CUSTOM: + return + defaults = CrawlerConfig() + for name in self.PROFILE_FIELDS: + setattr(self, name, getattr(defaults, name)) if profile == ConfigProfile.QUICK: self.max_concurrent = 30 self.max_pages = 50 @@ -166,96 +160,37 @@ def apply_profile(self, profile: ConfigProfile) -> None: self.max_depth = 10 self.timeout = 60 self.max_retries = 5 - self.parse_javascript = True elif profile == ConfigProfile.ENTERPRISE: self.max_concurrent = 50 self.max_pages = 10000 self.max_depth = 20 - self.use_http2 = True self.use_connection_pooling = True self.adaptive_delay = True elif profile == ConfigProfile.DEVELOPMENT: self.max_concurrent = 5 self.max_pages = 10 self.max_depth = 2 - self.verify_ssl = False @dataclass class AnalysisConfig: """Advanced analysis configuration.""" - # Analysis scope enabled_analyzers: List[str] = field(default_factory=lambda: [ 'seo', 'content', 'technical', 'performance', 'links' ]) analysis_mode: str = "standard" # quick, standard, deep parallel_analysis: bool = True max_analysis_threads: int = 4 - - # Link analysis - check_external_links: bool = True + + # Link and content analysis + check_external_links: bool = False check_internal_links: bool = True - validate_anchors: bool = True check_broken_links: bool = True max_external_links_per_page: int = 100 external_link_timeout: int = 10 - - # Image analysis - check_images: bool = True - check_image_optimization: bool = True - check_alt_text: bool = True - check_image_dimensions: bool = True - max_image_size_kb: int = 500 - - # Content analysis - min_content_length: int = 100 - max_content_length: int = 100000 - optimal_content_length: int = 1500 - check_readability: bool = True - target_reading_level: int = 8 # Grade level - check_keyword_density: bool = True target_keywords: List[str] = field(default_factory=list) - keyword_variations: bool = True check_content_uniqueness: bool = True - min_unique_content_ratio: float = 0.7 - - # SEO analysis - check_meta_tags: bool = True - check_structured_data: bool = True - validate_structured_data: bool = True - check_open_graph: bool = True - check_twitter_cards: bool = True - check_canonical_urls: bool = True - check_hreflang: bool = True - check_sitemaps: bool = True - check_robots_txt: bool = True - - # Technical analysis - check_https: bool = True - check_security_headers: bool = True - check_mixed_content: bool = True - check_mobile_friendly: bool = True - check_page_speed: bool = True - check_core_web_vitals: bool = True - check_compression: bool = True - check_caching: bool = True - check_minification: bool = True - check_http2: bool = True - - # Performance thresholds - max_page_load_time: float = 3.0 - max_ttfb: float = 0.8 - max_fcp: float = 1.8 - max_lcp: float = 2.5 - max_fid: float = 100 - max_cls: float = 0.1 - max_page_size_mb: float = 3.0 - - # Accessibility - check_accessibility: bool = True - wcag_level: str = "AA" # A, AA, AAA - - # Scoring weights + score_weights: Dict[str, float] = field(default_factory=lambda: { 'seo': 0.30, 'content': 0.25, @@ -263,500 +198,555 @@ class AnalysisConfig: 'performance': 0.15, 'links': 0.10 }) - + def validate(self) -> List[str]: - """Validate analysis configuration.""" issues = [] - - if not self.enabled_analyzers: - issues.append("No analyzers enabled") - - if sum(self.score_weights.values()) != 1.0: - issues.append("Score weights must sum to 1.0") - - if self.min_content_length < 0: - issues.append("min_content_length must be non-negative") - - if self.target_reading_level < 1 or self.target_reading_level > 20: - issues.append("target_reading_level should be between 1-20") - + known = {'seo', 'content', 'technical', 'performance', 'links'} + if not self.enabled_analyzers or set(self.enabled_analyzers) - known: + issues.append('enabled_analyzers must select known analyzers') + if len(set(self.enabled_analyzers)) != len(self.enabled_analyzers): + issues.append('enabled_analyzers must not contain duplicates') + if self.analysis_mode not in {'quick', 'standard', 'deep', 'custom'}: + issues.append('Unknown analysis_mode') + if set(self.score_weights) - known or any(v < 0 for v in self.score_weights.values()): + issues.append('score_weights must use known analyzers and non-negative values') + if not math.isclose(sum(self.score_weights.values()), 1.0, abs_tol=1e-9): + issues.append('Score weights must sum to 1.0') + if not any(self.score_weights.get(name, 0) > 0 for name in self.enabled_analyzers): + issues.append('At least one enabled analyzer must have positive weight') + if self.max_analysis_threads <= 0: + issues.append('max_analysis_threads must be positive') + if self.max_external_links_per_page <= 0 or self.external_link_timeout <= 0: + issues.append('External link limits must be positive') return issues @dataclass class ExportConfig: """Advanced export configuration.""" - # Output formats formats: List[str] = field(default_factory=lambda: ['html']) primary_format: str = 'html' - - # HTML settings html_template: str = "optimized" # report, enhanced, optimized - include_inline_css: bool = True - include_inline_js: bool = True - minify_html: bool = True - html_theme: str = "light" # light, dark, auto - include_charts: bool = True - charts_library: str = "chartjs" # chartjs, d3, highcharts - - # Data inclusion - include_raw_data: bool = False - include_page_content: bool = False - include_screenshots: bool = False - include_har_files: bool = False - data_sampling_rate: float = 1.0 # For large datasets - max_issues_per_page: int = 100 - max_pages_in_report: int = 1000 - - # File settings output_directory: str = "./reports" filename_pattern: str = "{domain}_{timestamp}_{format}" - create_subdirectories: bool = True - compress_output: bool = False - compression_format: str = "zip" # zip, tar, gz - - # Export options - split_large_reports: bool = True - split_threshold_mb: int = 50 - generate_summary: bool = True - generate_executive_report: bool = True - - # Email settings - send_email: bool = False - email_recipients: List[str] = field(default_factory=list) - email_subject_template: str = "SEO Report for {domain}" - smtp_server: Optional[str] = None - smtp_port: int = 587 - smtp_username: Optional[str] = None - smtp_password: Optional[str] = None - - # Cloud storage - upload_to_cloud: bool = False - cloud_provider: Optional[str] = None # s3, gcs, azure - cloud_bucket: Optional[str] = None - cloud_path_prefix: Optional[str] = None - - # API export - send_to_api: bool = False - api_endpoint: Optional[str] = None - api_key: Optional[str] = None - api_method: str = "POST" - + def validate(self) -> List[str]: - """Validate export configuration.""" issues = [] - - if not self.formats: - issues.append("No export formats specified") - + if not self.formats or set(self.formats) - {'html', 'json', 'csv', 'xlsx'}: + issues.append('Supported export formats are html, json, csv, xlsx') if self.primary_format not in self.formats: - issues.append("primary_format not in formats list") - - if self.send_email and not self.email_recipients: - issues.append("Email enabled but no recipients specified") - - if self.upload_to_cloud and not self.cloud_bucket: - issues.append("Cloud upload enabled but no bucket specified") - + issues.append('primary_format must be present in formats') + if self.html_template not in {'report', 'enhanced', 'optimized'}: + issues.append('Unknown html_template') return issues -@dataclass -class MonitoringConfig: - """Configuration for monitoring and alerting.""" - enabled: bool = False - - # Metrics collection - collect_metrics: bool = True - metrics_interval: int = 60 # seconds - metrics_retention_days: int = 30 - - # Alerting - enable_alerts: bool = False - alert_thresholds: Dict[str, float] = field(default_factory=lambda: { - 'error_rate': 0.05, # 5% error rate - 'avg_response_time': 5.0, # 5 seconds - 'memory_usage_mb': 500, - 'broken_links_ratio': 0.10 - }) - - # Logging - log_level: str = "info" - log_to_file: bool = True - log_file_path: str = "./logs/tfq0seo.log" - log_rotation: str = "daily" # daily, size, time - log_retention_days: int = 7 - log_format: str = "json" # json, text - - # Progress tracking - show_progress: bool = True - progress_update_interval: float = 1.0 - detailed_progress: bool = False - - # Webhooks - webhook_enabled: bool = False - webhook_url: Optional[str] = None - webhook_events: List[str] = field(default_factory=lambda: [ - 'analysis_complete', 'error', 'threshold_exceeded' - ]) +def _matches_type(value: Any, expected: Any) -> bool: + if expected is Any: + return True + origin, args = get_origin(expected), get_args(expected) + if origin is Union: + return any(_matches_type(value, option) for option in args) + if origin is list: + return isinstance(value, list) and all(_matches_type(item, args[0]) for item in value) + if origin is dict: + return isinstance(value, dict) and all( + _matches_type(k, args[0]) and _matches_type(v, args[1]) for k, v in value.items()) + if expected is float: + try: + return type(value) in (int, float) and math.isfinite(value) + except OverflowError: + return False + if expected in (bool, int): + return type(value) is expected + return isinstance(value, expected) + + +def _type_issues(obj: Any) -> List[str]: + annotations = get_type_hints(type(obj)) + return [f"{item.name} has an invalid type or non-finite value" + for item in fields(obj) + if not _matches_type(getattr(obj, item.name), annotations[item.name])] + + +# Retired settings are migration metadata only, never active configuration fields. +# These historical defaults let explicit migration distinguish inert saved values +# from unsupported behavior that a caller deliberately requested. +_RETIRED_DEFAULTS = { + 'crawler': { + 'semaphore_limit': 30, + 'total_timeout': 300, + 'rotate_user_agents': False, + 'user_agent_list': [], + 'redirect_cache_ttl': 3600, + 'include_query_strings': True, + 'normalize_urls': True, + 'parse_javascript': False, + 'execute_javascript': False, + 'wait_for_javascript': 0.0, + 'compress_stored_html': True, + 'prioritize_sitemap_urls': True, + 'use_http2': False, + }, + 'analysis': { + 'validate_anchors': True, + 'check_images': True, + 'check_image_optimization': True, + 'check_alt_text': True, + 'check_image_dimensions': True, + 'max_image_size_kb': 500, + 'min_content_length': 100, + 'max_content_length': 100000, + 'optimal_content_length': 1500, + 'check_readability': True, + 'target_reading_level': 8, + 'check_keyword_density': True, + 'keyword_variations': True, + 'min_unique_content_ratio': 0.7, + 'check_meta_tags': True, + 'check_structured_data': True, + 'validate_structured_data': True, + 'check_open_graph': True, + 'check_twitter_cards': True, + 'check_canonical_urls': True, + 'check_hreflang': True, + 'check_sitemaps': True, + 'check_robots_txt': True, + 'check_https': True, + 'check_security_headers': True, + 'check_mixed_content': True, + 'check_mobile_friendly': True, + 'check_page_speed': True, + 'check_core_web_vitals': True, + 'check_compression': True, + 'check_caching': True, + 'check_minification': True, + 'check_http2': True, + 'max_page_load_time': 3.0, + 'max_ttfb': 0.8, + 'max_fcp': 1.8, + 'max_lcp': 2.5, + 'max_fid': 100.0, + 'max_cls': 0.1, + 'max_page_size_mb': 3.0, + 'check_accessibility': True, + 'wcag_level': 'AA', + }, + 'export': { + 'include_inline_css': True, + 'include_inline_js': True, + 'minify_html': True, + 'html_theme': 'light', + 'include_charts': True, + 'charts_library': 'chartjs', + 'include_raw_data': False, + 'include_page_content': False, + 'include_screenshots': False, + 'include_har_files': False, + 'data_sampling_rate': 1.0, + 'max_issues_per_page': 100, + 'max_pages_in_report': 1000, + 'create_subdirectories': True, + 'compress_output': False, + 'compression_format': 'zip', + 'split_large_reports': True, + 'split_threshold_mb': 50, + 'generate_summary': True, + 'generate_executive_report': True, + 'send_email': False, + 'email_recipients': [], + 'email_subject_template': 'SEO Report for {domain}', + 'smtp_server': None, + 'smtp_port': 587, + 'smtp_username': None, + 'smtp_password': None, + 'upload_to_cloud': False, + 'cloud_provider': None, + 'cloud_bucket': None, + 'cloud_path_prefix': None, + 'send_to_api': False, + 'api_endpoint': None, + 'api_key': None, + 'api_method': 'POST', + }, + 'monitoring': { + 'enabled': False, + 'collect_metrics': True, + 'metrics_interval': 60, + 'metrics_retention_days': 30, + 'enable_alerts': False, + 'alert_thresholds': { + 'error_rate': 0.05, 'avg_response_time': 5.0, + 'memory_usage_mb': 500.0, 'broken_links_ratio': 0.1, + }, + 'log_level': 'info', + 'log_to_file': True, + 'log_file_path': './logs/tfq0seo.log', + 'log_rotation': 'daily', + 'log_retention_days': 7, + 'log_format': 'json', + 'show_progress': True, + 'progress_update_interval': 1.0, + 'detailed_progress': False, + 'webhook_enabled': False, + 'webhook_url': None, + 'webhook_events': ['analysis_complete', 'error', 'threshold_exceeded'], + }, + 'global': { + 'dry_run': False, + 'temp_directory': './temp', + 'features': {}, + 'metadata': {}, + }, +} + +_COMPONENT_TYPES = {'crawler': CrawlerConfig, 'analysis': AnalysisConfig, 'export': ExportConfig} +_CRAWLER_ALIASES = { + 'concurrent_requests': 'max_concurrent', 'max_content_length': 'max_page_size', + 'retry_attempts': 'max_retries', 'adaptive_throttle': 'adaptive_delay', + 'follow_sitemap': 'use_sitemap', +} + + +def _key_issues(keys, allowed, section: str) -> List[str]: + """Describe keys, never supplied values (which may contain credentials).""" + if any(not isinstance(key, str) for key in keys): + return [f'{section} configuration keys must be strings'] + prefix = '' if section == 'global' else section + '.' + retired = set(_RETIRED_DEFAULTS.get(section, {})) + if section == 'global': + retired.add('monitoring') + issues = [] + for key in sorted(set(keys) - set(allowed)): + if key in retired: + issues.append(f'{prefix}{key} was retired in 3.0.0; use Config.migrate_dict() for legacy defaults ' + 'or remove this unsupported setting after reviewing docs/configuration-migration.md') + else: + issues.append(f'Unknown {section} configuration key: {key}') + return issues + + +def _unexpected_field_issues(obj: Any, section: str) -> List[str]: + allowed = {item.name for item in fields(obj)} + # Config tracks explicit overrides privately; component settings have no private state. + if section == 'global': + allowed.add('_explicit_values') + return _key_issues(vars(obj), allowed, section) + + +def _same_legacy_default(value: Any, default: Any) -> bool: + """Use historical configuration types; bool and numeric equality are distinct.""" + if isinstance(default, dict): + return (isinstance(value, dict) and value.keys() == default.keys() and + all(_same_legacy_default(value[key], item) for key, item in default.items())) + if isinstance(default, list): + return (isinstance(value, list) and len(value) == len(default) and + all(_same_legacy_default(item, expected) for item, expected in zip(value, default))) + if type(default) is float: + return _matches_type(value, float) and value == default + return type(value) is type(default) and value == default @dataclass class Config: - """Main configuration container with advanced features.""" - # Core configurations - crawler: CrawlerConfig = field(default_factory=CrawlerConfig) - analysis: AnalysisConfig = field(default_factory=AnalysisConfig) - export: ExportConfig = field(default_factory=ExportConfig) - monitoring: MonitoringConfig = field(default_factory=MonitoringConfig) - - # Global settings + """Resolve profiles first, then explicit overrides; reject invalid input.""" + crawler: Optional[CrawlerConfig] = None + analysis: Optional[AnalysisConfig] = None + export: Optional[ExportConfig] = None profile: ConfigProfile = ConfigProfile.STANDARD - version: str = "3.0.0" - debug: bool = False - dry_run: bool = False + version: str = '3.0.0' + debug: bool = False # Profile metadata only; configure Python logging separately. continue_on_error: bool = True max_memory_mb: int = 1024 - temp_directory: str = "./temp" - - # Feature flags - features: Dict[str, bool] = field(default_factory=lambda: { - 'parallel_crawling': True, - 'intelligent_sampling': True, - 'auto_retry': True, - 'smart_caching': True, - 'predictive_crawling': False, - 'ai_recommendations': False - }) - - # Metadata - metadata: Dict[str, Any] = field(default_factory=dict) - + + SUPPORTED_FIELDS = { + name: frozenset(item.name for item in fields(component)) + for name, component in _COMPONENT_TYPES.items() + } + def __post_init__(self): - """Apply profile after initialization.""" - if self.profile != ConfigProfile.CUSTOM: - self.apply_profile(self.profile) - + supplied = {name: getattr(self, name) for name in _COMPONENT_TYPES} + supplied_debug = self.debug + self.crawler = CrawlerConfig() + self.analysis = AnalysisConfig() + self.export = ExportConfig() + try: + self.profile = ConfigProfile(self.profile) + except (ValueError, TypeError): + raise ValueError('profile must be quick, standard, deep, enterprise, dev, or custom') from None + self.apply_profile(self.profile) + if self.profile != ConfigProfile.DEVELOPMENT: + self.debug = supplied_debug + for name, component in supplied.items(): + if component is not None: + setattr(self, name, component) + @classmethod - def from_file(cls, filepath: Union[str, Path]) -> "Config": - """Load configuration from file with validation.""" + def from_file(cls, filepath: Union[str, Path]) -> 'Config': filepath = Path(filepath) - - if not filepath.exists(): - logger.warning(f"Config file not found: {filepath}, using defaults") - return cls() - - try: - with open(filepath, 'r', encoding='utf-8') as f: - if filepath.suffix == '.json': - data = json.load(f) - elif filepath.suffix in ['.yml', '.yaml']: - data = yaml.safe_load(f) or {} - else: - raise ValueError(f"Unsupported config format: {filepath.suffix}") - - config = cls.from_dict(data) - config.validate() - return config - - except Exception as e: - logger.error(f"Error loading config from {filepath}: {e}") - return cls() - + with filepath.open(encoding='utf-8') as handle: + if filepath.suffix.lower() == '.json': + data = json.load(handle) + elif filepath.suffix.lower() in ('.yaml', '.yml'): + data = yaml.safe_load(handle) + else: + raise ValueError(f'Unsupported config format: {filepath.suffix}') + return cls.from_dict({} if data is None else data) + @classmethod - def from_dict(cls, data: Dict) -> "Config": - """Create config from dictionary with validation.""" - config = cls() - - # Load profile first - if 'profile' in data: - try: - config.profile = ConfigProfile(data['profile']) - except ValueError: - logger.warning(f"Invalid profile: {data['profile']}, using STANDARD") - config.profile = ConfigProfile.STANDARD - - # Load sub-configurations - if 'crawler' in data: - for key, value in data['crawler'].items(): - if hasattr(config.crawler, key): - setattr(config.crawler, key, value) - - if 'analysis' in data: - for key, value in data['analysis'].items(): - if hasattr(config.analysis, key): - setattr(config.analysis, key, value) - - if 'export' in data: - for key, value in data['export'].items(): - if hasattr(config.export, key): - setattr(config.export, key, value) - - if 'monitoring' in data: - for key, value in data['monitoring'].items(): - if hasattr(config.monitoring, key): - setattr(config.monitoring, key, value) - - # Load global settings - for key in ['debug', 'dry_run', 'continue_on_error', 'max_memory_mb', 'temp_directory']: - if key in data: - setattr(config, key, data[key]) - - # Load features - if 'features' in data: - config.features.update(data['features']) - - # Load metadata - if 'metadata' in data: - config.metadata = data['metadata'] - + def from_dict(cls, data: Dict) -> 'Config': + if not isinstance(data, dict): + raise ValueError('Configuration must be an object') + data = cls._canonical_overrides(data) + errors = _key_issues(data, {item.name for item in fields(cls)}, 'global') + if errors: + raise ValueError('; '.join(errors)) + config = cls(profile=data.get('profile', 'standard')) + for section in _COMPONENT_TYPES: + values = data.get(section, {}) + if not isinstance(values, dict): + raise ValueError(f'{section} must be an object') + values = dict(values) + target = getattr(config, section) + allowed = {item.name for item in fields(target)} + errors = _key_issues(values, allowed, section) + if errors: + raise ValueError('; '.join(errors)) + for name, value in values.items(): + setattr(target, name, value) + for name, value in data.items(): + if name not in _COMPONENT_TYPES and name != 'profile': + setattr(config, name, value) + config._explicit_values = copy.deepcopy(data) + config.require_valid() return config - + + @staticmethod + def _canonical_overrides(data: Dict) -> Dict: + data = copy.deepcopy(data) + values = data.get('crawler') + if isinstance(values, dict): + annotations = get_type_hints(CrawlerConfig) + for alias, name in _CRAWLER_ALIASES.items(): + if alias in values: + value = values.pop(alias) + if value is None and alias == 'concurrent_requests': + continue + if not _matches_type(value, annotations[name]): + raise ValueError(f'crawler.{alias} has an invalid type or non-finite value') + if name in values and not _matches_type(values[name], annotations[name]): + raise ValueError(f'crawler.{name} has an invalid type or non-finite value') + if name in values and values[name] != value: + raise ValueError(f'Conflicting crawler settings: {alias} and {name}') + values[name] = value + return data + + @classmethod + def migrate_dict(cls, data: Dict) -> Tuple[Dict[str, Any], List[str]]: + """Explicitly remove retired historical defaults and canonicalize aliases. + + Return validated, sparse overrides and value-free migration warnings. + Unsupported non-default values, malformed input, and unknown keys fail; + the original mapping remains untouched and no files or networks are used. + """ + if not isinstance(data, dict): + raise ValueError('Configuration must be an object') + canonical = cls._canonical_overrides(data) + allowed_global = {item.name for item in fields(cls)} | set(_RETIRED_DEFAULTS['global']) | {'monitoring'} + errors = _key_issues(canonical, allowed_global, 'global') + warnings = [] + for section in ('crawler', 'analysis', 'export', 'monitoring', 'global'): + if section != 'global' and section not in canonical: + continue + values = canonical if section == 'global' else canonical[section] + if not isinstance(values, dict): + errors.append(f'{section} must be an object') + continue + defaults = _RETIRED_DEFAULTS[section] + if section != 'global': + errors.extend(_key_issues(values, set(cls.SUPPORTED_FIELDS.get(section, ())) | set(defaults), section)) + for name, default in defaults.items(): + if name not in values: + continue + path = name if section == 'global' else section + '.' + name + if not _same_legacy_default(values[name], default): + errors.append(f'{path} cannot be migrated automatically: it requests an unsupported non-default ' + 'value or has an invalid type; review docs/configuration-migration.md and remove it explicitly') + else: + del values[name] + warnings.append(f'Removed retired setting {path} at its historical default.') + if section == 'monitoring' and not values: + del canonical[section] + warnings.append('Removed the retired monitoring section.') + if errors: + raise ValueError('; '.join(errors)) + for alias, target in _CRAWLER_ALIASES.items(): + if isinstance(data.get('crawler'), dict) and alias in data['crawler']: + warnings.append(f'Canonicalized crawler.{alias} to crawler.{target}.' + if data['crawler'][alias] is not None else + f'Removed empty crawler.{alias} alias; crawler.{target} is unchanged.') + if isinstance(canonical.get('profile'), ConfigProfile): + canonical['profile'] = canonical['profile'].value + cls.from_dict(canonical) # Check active types, constraints, and profile overrides without expanding them. + return canonical, warnings + + @classmethod + def from_env(cls, prefix: str = 'TFQ0SEO_') -> 'Config': + return cls.from_dict(cls.environment_overrides(prefix)) + @classmethod - def from_env(cls, prefix: str = "TFQ0SEO_") -> "Config": - """Load configuration from environment variables.""" - config = cls() - - # Parse environment variables + def environment_overrides(cls, prefix: str = 'TFQ0SEO_') -> Dict: + data = {} for key, value in os.environ.items(): if not key.startswith(prefix): continue - - # Remove prefix and convert to lowercase - config_key = key[len(prefix):].lower() - - # Map to configuration paths - if config_key.startswith('crawler_'): - attr = config_key[8:] # Remove 'crawler_' - if hasattr(config.crawler, attr): - setattr(config.crawler, attr, cls._parse_env_value(value)) - - elif config_key.startswith('analysis_'): - attr = config_key[9:] # Remove 'analysis_' - if hasattr(config.analysis, attr): - setattr(config.analysis, attr, cls._parse_env_value(value)) - - elif config_key.startswith('export_'): - attr = config_key[7:] # Remove 'export_' - if hasattr(config.export, attr): - setattr(config.export, attr, cls._parse_env_value(value)) - - elif config_key.startswith('monitoring_'): - attr = config_key[11:] # Remove 'monitoring_' - if hasattr(config.monitoring, attr): - setattr(config.monitoring, attr, cls._parse_env_value(value)) - - elif config_key == 'profile': - try: - config.profile = ConfigProfile(value.lower()) - except ValueError: - logger.warning(f"Invalid profile from env: {value}") - - elif config_key == 'debug': - config.debug = value.lower() in ['true', '1', 'yes'] - - return config - + key = key[len(prefix):].lower() + section = next((s for s in ('crawler', 'analysis', 'export', 'monitoring') + if key.startswith(s + '_')), None) + if section: + name = key[len(section) + 1:] + canonical_name = _CRAWLER_ALIASES.get(name, name) if section == 'crawler' else name + annotation = (get_type_hints(_COMPONENT_TYPES[section]).get(canonical_name) + if section in _COMPONENT_TYPES else None) + if section == 'crawler' and name == 'concurrent_requests': + annotation = Optional[int] + data.setdefault(section, {})[name] = cls._parse_env_value(value, annotation) + else: + data[key] = cls._parse_env_value(value, get_type_hints(cls).get(key)) + return data + @staticmethod - def _parse_env_value(value: str) -> Any: - """Parse environment variable value to appropriate type.""" - # Boolean - if value.lower() in ['true', 'false']: - return value.lower() == 'true' - - # Integer + def _parse_env_value(value: str, annotation: Any = None) -> Any: + if annotation is str or annotation is ConfigProfile: + return value + if get_origin(annotation) is Union and str in get_args(annotation): + return None if value == 'null' else value + if annotation is bool: + if value.lower() in ('true', '1', 'yes'): + return True + if value.lower() in ('false', '0', 'no'): + return False + raise ValueError('Boolean environment settings must be true or false') + if get_origin(annotation) is list: + if value.strip().startswith('['): + return json.loads(value) + item_type = get_args(annotation)[0] + return [Config._parse_env_value(item.strip(), item_type) for item in value.split(',')] if value else [] try: - return int(value) - except ValueError: - pass - - # Float - try: - return float(value) - except ValueError: - pass - - # List (comma-separated) - if ',' in value: - return [v.strip() for v in value.split(',')] - - # String - return value - + return json.loads(value) + except (ValueError, TypeError): + if ',' in value: + return [v.strip() for v in value.split(',')] + return value + def apply_profile(self, profile: ConfigProfile) -> None: - """Apply a configuration profile to all sub-configs.""" - self.profile = profile - - if profile == ConfigProfile.QUICK: - # Quick scan settings - self.crawler.max_concurrent = 30 - self.crawler.max_pages = 50 - self.crawler.max_depth = 2 - self.crawler.timeout = 10 - self.analysis.analysis_mode = "quick" - self.analysis.enabled_analyzers = ['seo', 'technical'] - self.analysis.check_external_links = False - self.export.formats = ['html'] - self.export.include_raw_data = False - - elif profile == ConfigProfile.STANDARD: - # Default balanced settings (already set) - pass - - elif profile == ConfigProfile.DEEP: - # Comprehensive analysis - self.crawler.max_concurrent = 10 - self.crawler.max_pages = 1000 - self.crawler.max_depth = 10 - self.crawler.timeout = 60 - self.crawler.parse_javascript = True - self.analysis.analysis_mode = "deep" - self.analysis.enabled_analyzers = [ - 'seo', 'content', 'technical', 'performance', 'links' - ] - self.analysis.check_external_links = True - self.analysis.validate_structured_data = True - self.analysis.check_content_uniqueness = True - self.export.include_raw_data = True - self.export.generate_executive_report = True - - elif profile == ConfigProfile.ENTERPRISE: - # Large-scale optimized - self.crawler.max_concurrent = 50 - self.crawler.max_pages = 10000 - self.crawler.max_depth = 20 - self.crawler.use_http2 = True - self.crawler.use_connection_pooling = True - self.crawler.adaptive_delay = True - self.crawler.cache_enabled = True - self.analysis.parallel_analysis = True - self.analysis.max_analysis_threads = 8 - self.export.split_large_reports = True - self.monitoring.enabled = True - self.features['intelligent_sampling'] = True - self.features['predictive_crawling'] = True - - elif profile == ConfigProfile.DEVELOPMENT: - # Testing/development settings - self.crawler.max_concurrent = 5 - self.crawler.max_pages = 10 - self.crawler.max_depth = 2 - self.crawler.verify_ssl = False - self.debug = True - self.monitoring.log_level = "debug" - self.monitoring.detailed_progress = True - + """Apply a preset in place, replacing its controlled values. + + Unrelated settings survive. CUSTOM only changes the profile label. + Use merge({'profile': ...}) to retain explicit overrides while changing + preset defaults instead. + """ + self.profile = ConfigProfile(profile) + if self.profile != ConfigProfile.CUSTOM: + self.crawler.apply_profile(self.profile) + defaults = AnalysisConfig() + self.analysis.analysis_mode = defaults.analysis_mode + self.analysis.enabled_analyzers = defaults.enabled_analyzers + self.debug = False + if self.profile == ConfigProfile.QUICK: + self.analysis.analysis_mode = 'quick' + self.analysis.enabled_analyzers = ['seo', 'technical'] + elif self.profile == ConfigProfile.DEEP: + self.analysis.analysis_mode = 'deep' + elif self.profile == ConfigProfile.DEVELOPMENT: + self.debug = True + # An explicit in-place preset supersedes older overrides for these + # fields, so a later merge must not resurrect their previous values. + if hasattr(self, '_explicit_values'): + for section, names in ( + ('crawler', CrawlerConfig.PROFILE_FIELDS), + ('analysis', ('analysis_mode', 'enabled_analyzers')), + ): + for name in names: + self._explicit_values.get(section, {}).pop(name, None) + self._explicit_values.pop('debug', None) + if hasattr(self, '_explicit_values'): + self._explicit_values['profile'] = self.profile.value + def validate(self) -> Dict[str, List[str]]: - """Validate entire configuration and return issues by component.""" - issues = { - 'crawler': self.crawler.validate(), - 'analysis': self.analysis.validate(), - 'export': self.export.validate() - } - - # Global validations - global_issues = [] - - if self.max_memory_mb <= 0: - global_issues.append("max_memory_mb must be positive") - - if self.max_memory_mb < 256: - global_issues.append("max_memory_mb < 256MB may cause issues") - - temp_dir = Path(self.temp_directory) - if not temp_dir.exists(): - try: - temp_dir.mkdir(parents=True, exist_ok=True) - except Exception as e: - global_issues.append(f"Cannot create temp directory: {e}") - - if global_issues: - issues['global'] = global_issues - - # Log issues if any - for component, component_issues in issues.items(): - if component_issues: - for issue in component_issues: - logger.warning(f"Config validation ({component}): {issue}") - + issues = {} + for name, expected in _COMPONENT_TYPES.items(): + obj = getattr(self, name) + if not isinstance(obj, expected): + issues[name] = [f'{name} must be a {expected.__name__}'] + continue + errors = _type_issues(obj) + _unexpected_field_issues(obj, name) + if not errors and hasattr(obj, 'validate'): + errors.extend(obj.validate()) + if errors: + issues[name] = errors + global_errors = _type_issues(self) + _unexpected_field_issues(self, 'global') + if type(self.max_memory_mb) is int and self.max_memory_mb <= 0: + global_errors.append('max_memory_mb must be positive') + if global_errors: + issues['global'] = global_errors return issues - + + def require_valid(self) -> None: + issues = self.validate() + if issues: + raise ValueError('; '.join(f'{section}: {message}' for section, messages in issues.items() + for message in messages)) + def to_dict(self) -> Dict: - """Convert configuration to dictionary.""" - return { - 'profile': self.profile.value, - 'version': self.version, - 'crawler': asdict(self.crawler), - 'analysis': asdict(self.analysis), - 'export': asdict(self.export), - 'monitoring': asdict(self.monitoring), - 'debug': self.debug, - 'dry_run': self.dry_run, - 'continue_on_error': self.continue_on_error, - 'max_memory_mb': self.max_memory_mb, - 'temp_directory': self.temp_directory, - 'features': self.features, - 'metadata': self.metadata - } - + self.require_valid() + data = asdict(self) + data['profile'] = self.profile.value + data['crawler'] = self.crawler.as_dict() + return data + def save(self, filepath: Union[str, Path]) -> None: - """Save configuration to file.""" + self.require_valid() filepath = Path(filepath) - data = self.to_dict() - - # Ensure directory exists + if filepath.suffix.lower() not in ('.json', '.yaml', '.yml'): + raise ValueError(f'Unsupported config format: {filepath.suffix}') filepath.parent.mkdir(parents=True, exist_ok=True) - - try: - with open(filepath, 'w', encoding='utf-8') as f: - if filepath.suffix == '.json': - json.dump(data, f, indent=2, default=str) - elif filepath.suffix in ['.yml', '.yaml']: - yaml.safe_dump(data, f, default_flow_style=False, sort_keys=False) - else: - raise ValueError(f"Unsupported config format: {filepath.suffix}") - - logger.info(f"Configuration saved to {filepath}") - - except Exception as e: - logger.error(f"Error saving config to {filepath}: {e}") - raise - + with filepath.open('w', encoding='utf-8') as handle: + if filepath.suffix.lower() == '.json': + json.dump(self.to_dict(), handle, indent=2, allow_nan=False) + else: + yaml.safe_dump(self.to_dict(), handle, sort_keys=False) + def get_effective_config(self) -> Dict: - """Get the effective configuration after all overrides.""" - config = self.to_dict() - - # Add computed values - config['computed'] = { - 'total_timeout': self.crawler.total_timeout, - 'max_memory_bytes': self.max_memory_mb * 1024 * 1024, - 'cache_size_bytes': self.crawler.cache_size_mb * 1024 * 1024, - 'effective_max_concurrent': min( - self.crawler.max_concurrent, - self.crawler.semaphore_limit - ) - } - - return config - + self.require_valid() + return self.to_dict() + def merge(self, other: Union[Dict, 'Config']) -> 'Config': - """Merge with another configuration, with other taking precedence.""" - if isinstance(other, dict): - other = Config.from_dict(other) - - # Create a new config with merged values - merged_dict = self.to_dict() - other_dict = other.to_dict() - - # Deep merge - def deep_merge(base: Dict, override: Dict) -> Dict: - result = base.copy() - for key, value in override.items(): - if key in result and isinstance(result[key], dict) and isinstance(value, dict): - result[key] = deep_merge(result[key], value) - else: - result[key] = value + override = other.to_dict() if isinstance(other, Config) else other + if not isinstance(override, dict): + raise ValueError('Configuration overrides must be an object') + override = self._canonical_overrides(override) + def merge_values(base, changes): + result = dict(base) + for name, value in changes.items(): + result[name] = merge_values(result[name], value) if ( + name in result and isinstance(result[name], dict) and isinstance(value, dict) + ) else value return result - - merged_data = deep_merge(merged_dict, other_dict) - return Config.from_dict(merged_data) \ No newline at end of file + base = self.to_dict() + if 'profile' in override and override['profile'] != self.profile.value: + # A new profile supplies defaults, not overrides for every field. + previous_defaults = Config(profile=self.profile).to_dict() + def differences(current, defaults): + changed = {} + for name, value in current.items(): + if isinstance(value, dict) and isinstance(defaults.get(name), dict): + nested = differences(value, defaults[name]) + if nested: + changed[name] = nested + elif value != defaults.get(name): + changed[name] = value + return changed + base = merge_values(getattr(self, '_explicit_values', {}), differences(base, previous_defaults)) + base.pop('profile', None) + return Config.from_dict(merge_values(base, override)) diff --git a/tfq0seo/core/crawler.py b/tfq0seo/core/crawler.py index 095c88b..d8d0f94 100644 --- a/tfq0seo/core/crawler.py +++ b/tfq0seo/core/crawler.py @@ -1,41 +1,40 @@ -"""Advanced async crawler module with intelligent features and optimizations.""" +"""Bounded asynchronous crawling, URL discovery, and response collection.""" import asyncio +import heapq +import itertools +import logging +import math +import re import time -import hashlib -import random -from typing import Dict, List, Set, Optional, Any, Tuple -from urllib.parse import urljoin, urlparse, urlunparse, parse_qs, urlencode -from urllib.robotparser import RobotFileParser -from collections import deque, defaultdict +from collections import defaultdict, deque from dataclasses import dataclass, field -import re -import warnings -import logging +from datetime import datetime, timezone +from email.utils import parsedate_to_datetime +from typing import Any, Dict, List, Optional, Set, Tuple +from urllib.parse import urlparse, urlunparse +from urllib.robotparser import RobotFileParser +from xml.etree import ElementTree import aiohttp -from aiohttp import ClientTimeout, ClientError, ServerTimeoutError -from bs4 import BeautifulSoup, XMLParsedAsHTMLWarning -import validators - -# Suppress XML parsing warnings when handling sitemaps -warnings.filterwarnings("ignore", category=XMLParsedAsHTMLWarning) +from aiohttp import ClientError, ClientTimeout +from bs4 import BeautifulSoup, FeatureNotFound, UnicodeDammit +from ..urls import resolve_url +from .models import FetchResult, normalize_fetch_result -# Setup logging logger = logging.getLogger(__name__) +# XML discovery deliberately does not depend on the optional HTML parser. try: - from lxml import etree, html + import lxml.html as HTML_PARSER PARSER = 'lxml' - HTML_PARSER = html except ImportError: - PARSER = 'html.parser' HTML_PARSER = None + PARSER = 'html.parser' @dataclass class CrawlStats: - """Statistics tracker for crawl performance.""" start_time: float = field(default_factory=time.time) requests_made: int = 0 bytes_downloaded: int = 0 @@ -43,767 +42,925 @@ class CrawlStats: rate_limit_hits: int = 0 robots_blocked: int = 0 redirects_followed: int = 0 - + def get_summary(self) -> Dict[str, Any]: - elapsed = time.time() - self.start_time + elapsed = max(0, time.time() - self.start_time) return { 'elapsed_seconds': elapsed, 'requests_made': self.requests_made, - 'requests_per_second': self.requests_made / elapsed if elapsed > 0 else 0, + 'requests_per_second': self.requests_made / elapsed if elapsed else 0, 'bytes_downloaded': self.bytes_downloaded, 'mb_downloaded': self.bytes_downloaded / (1024 * 1024), 'errors': self.errors_encountered, 'rate_limits': self.rate_limit_hits, 'robots_blocked': self.robots_blocked, - 'redirects': self.redirects_followed + 'redirects': self.redirects_followed, } class URLQueue: - """Priority queue for URL management with deduplication.""" - - def __init__(self): - self.queue = deque() + """A bounded heap; the caller supplies normalized URL identities.""" + + def __init__(self, max_size: Optional[int] = None): + self.queue = [] self.seen = set() - self.priorities = {} - - def add(self, url: str, priority: int = 5, depth: int = 0): - """Add URL with priority (lower = higher priority).""" - url_hash = hashlib.md5(url.encode()).hexdigest() - if url_hash not in self.seen: - self.seen.add(url_hash) - self.queue.append((priority, depth, url)) - # Keep queue sorted by priority - self.queue = deque(sorted(self.queue, key=lambda x: (x[0], x[1]))) - + self.max_size = max_size + self._sequence = itertools.count() + + def add(self, url: str, priority: int = 5, depth: int = 0) -> bool: + if url in self.seen: + return False + if self.max_size is not None and len(self.seen) >= self.max_size: + return False + self.seen.add(url) + heapq.heappush(self.queue, (depth, priority, next(self._sequence), url)) + return True + def get(self) -> Optional[Tuple[int, int, str]]: - """Get next URL from queue.""" - if self.queue: - return self.queue.popleft() - return None - + if not self.queue: + return None + depth, priority, _, url = heapq.heappop(self.queue) + return priority, depth, url + def __len__(self): return len(self.queue) - + def has_url(self, url: str) -> bool: - """Check if URL has been seen.""" - url_hash = hashlib.md5(url.encode()).hexdigest() - return url_hash in self.seen + return url in self.seen class RateLimiter: - """Adaptive rate limiter for respectful crawling.""" - - def __init__(self, initial_delay: float = 0.1, max_delay: float = 5.0): + """Serialize request starts per origin, independently of request duration.""" + + def __init__(self, initial_delay: float = 0.1, max_delay: float = 5.0, + adaptive: bool = True): self.delay = initial_delay - self.max_delay = max_delay + self.max_delay = max(initial_delay, max_delay) + self.adaptive = adaptive self.last_request_time = defaultdict(float) - self.response_times = defaultdict(list) + self.response_times = defaultdict(lambda: deque(maxlen=10)) self.error_counts = defaultdict(int) - + self._locks = defaultdict(asyncio.Lock) + self._minimum_delays = defaultdict(float) + self._adaptive_delays = defaultdict(lambda: initial_delay) + self._not_before = defaultdict(float) + + def set_minimum_delay(self, domain: str, delay: float): + self._minimum_delays[domain] = max(self._minimum_delays[domain], delay) + + def defer(self, domain: str, delay: float): + self._not_before[domain] = max(self._not_before[domain], time.monotonic() + delay) + async def wait(self, domain: str): - """Wait appropriate time before next request.""" - now = time.time() - elapsed = now - self.last_request_time[domain] - - # Adaptive delay based on response times and errors - if self.error_counts[domain] > 3: - self.delay = min(self.delay * 2, self.max_delay) - elif self.response_times[domain]: - avg_response = sum(self.response_times[domain][-10:]) / len(self.response_times[domain][-10:]) - if avg_response > 2.0: # Slow server - self.delay = min(self.delay * 1.5, self.max_delay) - elif avg_response < 0.5: # Fast server - self.delay = max(self.delay * 0.8, 0.05) - - wait_time = max(0, self.delay - elapsed) - if wait_time > 0: - await asyncio.sleep(wait_time) - - self.last_request_time[domain] = time.time() - + async with self._locks[domain]: + delay = max(self.delay, self._minimum_delays[domain], + self._adaptive_delays[domain] if self.adaptive else 0) + while True: + ready_at = max(self.last_request_time[domain] + delay, + self._not_before[domain]) + remaining = ready_at - time.monotonic() + if remaining <= 0: + break + await asyncio.sleep(remaining) + self.last_request_time[domain] = time.monotonic() + def record_response(self, domain: str, response_time: float, is_error: bool = False): - """Record response metrics for adaptive throttling.""" self.response_times[domain].append(response_time) + self.error_counts[domain] = (self.error_counts[domain] + 1 if is_error + else max(0, self.error_counts[domain] - 1)) + if not self.adaptive: + return + current = self._adaptive_delays[domain] if is_error: - self.error_counts[domain] += 1 - else: - self.error_counts[domain] = max(0, self.error_counts[domain] - 1) + current = min(self.max_delay, max(0.05, current) * 2) + elif response_time > 2: + current = min(self.max_delay, max(0.05, current) * 1.5) + elif response_time < 0.5: + current = max(self.delay, current * 0.8) + self._adaptive_delays[domain] = current + + +class _SitemapTreeBuilder(ElementTree.TreeBuilder): + def doctype(self, name, pubid, system): + raise ValueError('Sitemaps containing a document type declaration are not supported') class EnhancedCrawler: - """Advanced async crawler with intelligent features.""" - + """Collect terminal page outcomes within an origin and resource budget. + + Direct/batch fetches use each supplied URL as their scope. Site crawling and + sitemap discovery stay on the starting hostname and port; changing between + standard HTTP and HTTPS ports is allowed. allowed_domains overrides that + scope using exact hostnames or explicit *.example.com subdomain patterns. + """ + def __init__(self, config=None): - """Initialize enhanced crawler with configuration.""" - self.config = config or {} + self.config = dict(config or {}) + + def option(name, default, *aliases): + for key in (name,) + aliases: + if key in self.config: + return self.config[key] + return default + + self.max_concurrent = option('max_concurrent', 10, 'concurrent_requests') + self.timeout = option('timeout', 30) + self.connect_timeout = option('connect_timeout', 10) + self.read_timeout = option('read_timeout', self.timeout) + self.user_agent = option('user_agent', 'tfq0seo/3.0.0 (SEO Crawler)') + self.follow_redirects = option('follow_redirects', True) + self.max_redirects = option('max_redirects', 5) + self.max_pages = option('max_pages', 500) + self.max_depth = option('max_depth', 5) + self.max_crawl_time = option('max_crawl_time', 3600) + self.allowed_domains = option('allowed_domains', []) + self.allowed_schemes = option('allowed_schemes', ['http', 'https']) + self.excluded_patterns = option('excluded_patterns', []) + self.respect_robots = option('respect_robots_txt', True) + self.robots_cache_ttl = option('robots_cache_ttl', 86400) + self.crawl_delay_factor = option('crawl_delay_factor', 1.0) + self.max_content_length = option('max_page_size', 10 * 1024 * 1024, 'max_content_length') + self.retry_attempts = option('max_retries', 3, 'retry_attempts') + self.retry_on_status = option('retry_on_status', [429, 500, 502, 503, 504]) + self.retry_delay = option('retry_backoff_factor', 2.0, 'retry_delay') + self.adaptive_throttle = option('adaptive_delay', True, 'adaptive_throttle') + self.parse_javascript = option('parse_javascript', False) + self.store_html = option('store_html', True) + self.follow_sitemap = option('use_sitemap', True, 'follow_sitemap') + self.discover_sitemaps = option('discover_sitemaps', True) + self.verify_ssl = option('verify_ssl', True) + self.proxy = option('proxy', None) + self._base_url = None + self._deadline = None + self._interrupted_fetches = None + self._validate_config() + + delay = max(option('delay_between_requests', 0), option('min_delay', 0)) + rate = option('rate_limit_per_second', None) + if rate is not None: + delay = max(delay, 1 / rate) + self.rate_limiter = RateLimiter(delay, option('max_delay', 5), self.adaptive_throttle) self.visited_urls: Set[str] = set() - self.failed_urls: Dict[str, str] = {} # URL -> error message + self.failed_urls: Dict[str, str] = {} self.results: List[Dict[str, Any]] = [] - self.robots_cache: Dict[str, Tuple[RobotFileParser, float]] = {} # Include expiry time + self.robots_cache: Dict[str, Tuple[RobotFileParser, float]] = {} + self._robots_locks = defaultdict(asyncio.Lock) + self._robots_sitemaps = {} self.session: Optional[aiohttp.ClientSession] = None - self.url_queue = URLQueue() - self.rate_limiter = RateLimiter() + self.url_queue = URLQueue(max_size=self._frontier_limit(self.max_pages)) + self._parents = {} self.stats = CrawlStats() - - # Configuration with defaults - self.max_concurrent = self.config.get('max_concurrent', 10) - self.timeout = self.config.get('timeout', 30) - self.user_agent = self.config.get('user_agent', 'tfq0seo/2.3.2 (Advanced Crawler)') - self.follow_redirects = self.config.get('follow_redirects', True) - self.max_redirects = self.config.get('max_redirects', 5) - self.max_pages = self.config.get('max_pages', 500) - self.max_depth = self.config.get('max_depth', 5) - self.allowed_domains = self.config.get('allowed_domains', []) - self.excluded_patterns = self.config.get('excluded_patterns', []) - self.respect_robots = self.config.get('respect_robots_txt', True) - self.max_content_length = self.config.get('max_content_length', 1024 * 1024) # 1MB - self.retry_attempts = self.config.get('retry_attempts', 2) - self.retry_delay = self.config.get('retry_delay', 1.0) - self.adaptive_throttle = self.config.get('adaptive_throttle', True) - self.parse_javascript = self.config.get('parse_javascript', False) - self.store_html = self.config.get('store_html', True) - self.follow_sitemap = self.config.get('follow_sitemap', True) - - # Advanced browser headers for better compatibility + self.limit_reasons: Set[str] = set() + self.discovery_errors: List[Dict[str, str]] = [] self.headers = { 'User-Agent': self.user_agent, - 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', - 'Accept-Language': 'en-US,en;q=0.9', + 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate', - 'DNT': '1', - 'Connection': 'keep-alive', - 'Upgrade-Insecure-Requests': '1', - 'Sec-Fetch-Dest': 'document', - 'Sec-Fetch-Mode': 'navigate', - 'Sec-Fetch-Site': 'none', - 'Cache-Control': 'max-age=0' } - + for key, value in option('custom_headers', {}).items(): + previous = next((name for name in self.headers if name.lower() == key.lower()), None) + if previous: + del self.headers[previous] + self.headers[key] = value + self.user_agent = next((value for key, value in self.headers.items() + if key.lower() == 'user-agent'), self.user_agent) + + def _validate_config(self): + positive = { + 'max_concurrent': self.max_concurrent, 'timeout': self.timeout, + 'connect_timeout': self.connect_timeout, 'read_timeout': self.read_timeout, + 'max_pages': self.max_pages, 'max_page_size': self.max_content_length, + 'max_crawl_time': self.max_crawl_time, + 'max_connections_per_host': self.config.get('max_connections_per_host', self.max_concurrent), + } + nonnegative = { + 'max_depth': self.max_depth, 'max_redirects': self.max_redirects, + 'max_retries': self.retry_attempts, 'retry_backoff_factor': self.retry_delay, + 'robots_cache_ttl': self.robots_cache_ttl, 'crawl_delay_factor': self.crawl_delay_factor, + 'dns_cache_ttl': self.config.get('dns_cache_ttl', 300), + } + for name in ('delay_between_requests', 'min_delay', 'max_delay'): + nonnegative[name] = self.config.get(name, 0) + if self.config.get('rate_limit_per_second') is not None: + positive['rate_limit_per_second'] = self.config['rate_limit_per_second'] + for name, value in positive.items(): + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value <= 0: + raise ValueError(f'{name} must be a positive finite number') + for name, value in nonnegative.items(): + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value < 0: + raise ValueError(f'{name} must be a non-negative finite number') + for name, value in ( + ('max_concurrent', self.max_concurrent), ('max_pages', self.max_pages), + ('max_page_size', self.max_content_length), ('max_depth', self.max_depth), + ('max_redirects', self.max_redirects), ('max_retries', self.retry_attempts), + ): + if not isinstance(value, int): + raise ValueError(f'{name} must be an integer') + if not isinstance(self.allowed_schemes, (list, tuple)) or not self.allowed_schemes or any(s not in ('http', 'https') for s in self.allowed_schemes): + raise ValueError('allowed_schemes must contain only http and/or https') + for name, values in (('allowed_domains', self.allowed_domains), ('excluded_patterns', self.excluded_patterns)): + if not isinstance(values, (list, tuple)) or any(not isinstance(v, str) for v in values): + raise ValueError(f'{name} must be a list of strings') + try: + self._excluded = [re.compile(pattern) for pattern in self.excluded_patterns] + except re.error as exc: + raise ValueError(f'Invalid excluded_patterns expression: {exc}') from exc + if not isinstance(self.retry_on_status, (list, tuple)) or any(not isinstance(s, int) or not 400 <= s <= 599 for s in self.retry_on_status): + raise ValueError('retry_on_status must be a list of HTTP error status codes') + headers = self.config.get('custom_headers', {}) + if not isinstance(headers, dict) or any(not isinstance(k, str) or not isinstance(v, str) for k, v in headers.items()): + raise ValueError('custom_headers must be a dictionary of strings') + for key in ('verify_ssl', 'follow_redirects', 'respect_robots_txt', 'store_html', + 'use_sitemap', 'discover_sitemaps', 'adaptive_delay', 'use_connection_pooling'): + if key in self.config and not isinstance(self.config[key], bool): + raise ValueError(f'{key} must be a boolean') + async def __aenter__(self): - """Async context manager entry.""" - # Advanced connector with connection pooling connector = aiohttp.TCPConnector( - limit=self.max_concurrent * 2, - limit_per_host=self.max_concurrent, - ttl_dns_cache=300, - enable_cleanup_closed=True, - force_close=False, - keepalive_timeout=30 + limit=self.max_concurrent, + limit_per_host=self.config.get('max_connections_per_host', self.max_concurrent), + ttl_dns_cache=self.config.get('dns_cache_ttl', 300), + ssl=self.verify_ssl, + force_close=not self.config.get('use_connection_pooling', True), ) - - timeout = ClientTimeout( - total=self.timeout, - connect=10, - sock_connect=10, - sock_read=self.timeout - ) - - # Cookie jar for session persistence - jar = aiohttp.CookieJar() - self.session = aiohttp.ClientSession( connector=connector, - timeout=timeout, + timeout=ClientTimeout(total=self.timeout, connect=self.connect_timeout, + sock_connect=self.connect_timeout, sock_read=self.read_timeout), headers=self.headers, - cookie_jar=jar, - trust_env=True, - trace_configs=[self._create_trace_config()] + trust_env=False, ) return self - + async def __aexit__(self, exc_type, exc_val, exc_tb): - """Async context manager exit.""" if self.session: await self.session.close() - # Wait a bit for connections to close properly - await asyncio.sleep(0.25) - - def _create_trace_config(self) -> aiohttp.TraceConfig: - """Create trace config for request monitoring.""" - trace_config = aiohttp.TraceConfig() - - async def on_request_start(session, trace_config_ctx, params): - trace_config_ctx.start = asyncio.get_event_loop().time() - self.stats.requests_made += 1 - - async def on_request_end(session, trace_config_ctx, params): - elapsed = asyncio.get_event_loop().time() - trace_config_ctx.start - domain = urlparse(str(params.url)).netloc - self.rate_limiter.record_response(domain, elapsed) - - trace_config.on_request_start.append(on_request_start) - trace_config.on_request_end.append(on_request_end) - return trace_config - + + @staticmethod + def _host(parsed): + return (parsed.hostname or '').rstrip('.').encode('idna').decode('ascii').lower() + + @staticmethod + def _port(parsed): + return parsed.port if parsed.port is not None else (443 if parsed.scheme == 'https' else 80) + def normalize_url(self, url: str) -> str: - """Advanced URL normalization for better deduplication.""" - # Parse URL - parsed = urlparse(url.lower()) - - # Normalize the domain - netloc = parsed.netloc - if netloc.startswith('www.'): - netloc = netloc[4:] - - # Normalize the path - path = parsed.path - path = re.sub(r'/+', '/', path) # Remove duplicate slashes - path = path.rstrip('/') if path != '/' else '/' - - # Sort and normalize query parameters - query_params = parse_qs(parsed.query) - # Remove common tracking parameters - tracking_params = {'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', - 'utm_content', 'fbclid', 'gclid', 'ref', 'source'} - query_params = {k: v for k, v in query_params.items() if k not in tracking_params} - - # Sort parameters for consistency - sorted_query = urlencode(sorted(query_params.items()), doseq=True) - - # Reconstruct normalized URL - normalized = urlunparse(( - 'https' if parsed.scheme == 'https' else 'http', - netloc, - path, - parsed.params, - sorted_query, - '' # Remove fragment - )) - - return normalized - - def is_valid_url(self, url: str, base_domain: str) -> bool: - """Enhanced URL validation with more checks.""" - # Basic validation - if not validators.url(url): - return False - - parsed = urlparse(url) - - # Check protocol - if parsed.scheme not in ('http', 'https'): + """Normalize the authority and fragment without changing path/query semantics.""" + try: + parsed = urlparse(url) + host = self._host(parsed) + if ':' in host: + host = f'[{host}]' + port = parsed.port + if port is not None and port != (443 if parsed.scheme.lower() == 'https' else 80): + host += f':{port}' + normalized = urlunparse((parsed.scheme.lower(), host, parsed.path or '/', + parsed.params, parsed.query, '')) + if '?' in url.split('#', 1)[0] and not parsed.query: + normalized += '?' + return normalized + except (ValueError, UnicodeError, TypeError): + return url + + def _valid_url(self, url: str, base_url: str, page: bool = True, + apply_filters: bool = True) -> bool: + if not isinstance(url, str) or re.search(r'[\x00-\x20\x7f]', url): return False - - # Check for data URLs or javascript - if parsed.scheme in ('data', 'javascript', 'mailto', 'tel', 'ftp'): + if resolve_url(url, url) is None: return False - - # Check domain restrictions - if self.allowed_domains: - if not any(domain in parsed.netloc for domain in self.allowed_domains): - return False - else: - # Default to same domain as base - base_parsed = urlparse(base_domain) - base_domain = base_parsed.netloc.replace('www.', '') - current_domain = parsed.netloc.replace('www.', '') - if base_domain != current_domain: + try: + parsed = urlparse(url) + host = self._host(parsed) + if parsed.scheme not in self.allowed_schemes or not host or parsed.username is not None or parsed.password is not None: return False - - # Check excluded patterns - for pattern in self.excluded_patterns: - if re.search(pattern, url): + if self._port(parsed) == 0: return False - - # Skip common non-HTML resources - path = parsed.path.lower() - skip_extensions = ( - '.jpg', '.jpeg', '.png', '.gif', '.webp', '.svg', '.ico', - '.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', - '.zip', '.rar', '.tar', '.gz', '.7z', - '.mp3', '.mp4', '.avi', '.mov', '.wmv', '.flv', - '.css', '.js', '.json', '.xml', '.txt', - '.woff', '.woff2', '.ttf', '.eot' - ) - if path.endswith(skip_extensions): + if self.allowed_domains: + allowed = False + for domain in self.allowed_domains: + wildcard = domain.startswith('*.') + configured = urlparse('//' + (domain[2:] if wildcard else domain)) + configured_host = self._host(configured) + match = (host.endswith('.' + configured_host) if wildcard else host == configured_host) + if match and (configured.port is None or self._port(parsed) == configured.port): + allowed = True + break + if not allowed: + return False + else: + base = urlparse(base_url) + if host != self._host(base): + return False + default_transition = ( + self._port(parsed) == (443 if parsed.scheme == 'https' else 80) + and self._port(base) == (443 if base.scheme == 'https' else 80) + ) + if not default_transition and self._port(parsed) != self._port(base): + return False + except (ValueError, UnicodeError, TypeError, AttributeError): return False - - # Skip admin/login/logout URLs - skip_paths = ['/wp-admin', '/admin', '/login', '/logout', '/signin', - '/signout', '/register', '/wp-login', '/user/login'] - if any(skip in path for skip in skip_paths): + if apply_filters and any(pattern.search(url) for pattern in self._excluded): return False - + if page: + path = parsed.path.lower() + extensions = ('.jpg', '.jpeg', '.png', '.gif', '.webp', '.svg', '.ico', + '.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', + '.zip', '.rar', '.tar', '.gz', '.7z', '.mp3', '.mp4', + '.avi', '.mov', '.wmv', '.flv', '.css', '.js', '.json', + '.xml', '.txt', '.woff', '.woff2', '.ttf', '.eot') + if path.endswith(extensions): + return False + if any(re.search(r'/' + part + r'(?:/|$|\.)', path) + for part in ('wp-admin', 'admin', 'login', 'logout', 'signin', + 'signout', 'register', 'wp-login')): + return False return True - + + def is_valid_url(self, url: str, base_domain: str) -> bool: + return self._valid_url(url, self._base_url or base_domain) + + def _origin(self, url): + parsed = urlparse(self.normalize_url(url)) + return f'{parsed.scheme}://{parsed.netloc}' + + def _failure(self, url: str, message: str, **fields) -> Dict[str, Any]: + result = {'url': url, 'requested_url': url, 'status_code': 0, + 'error': message, 'outcome': 'failed', 'headers': None, + 'redirect_chain': [], 'load_time': None, 'timestamp': time.time(), + 'timings': {'headers_seconds': None, 'download_seconds': None, + 'network_seconds': None, 'total_seconds': None}} + result.update(fields) + return result + + @staticmethod + def _response_headers(headers): + values, seen = {}, set() + for key in headers: + if key.lower() in seen: + continue + seen.add(key.lower()) + instances = headers.getall(key) + values[key] = instances if len(instances) > 1 else instances[0] + return values + + async def _read_bounded(self, response, limit): + content = bytearray() + async for chunk in response.content.iter_chunked(min(16384, limit + 1)): + self.stats.bytes_downloaded += len(chunk) + remaining = limit - len(content) + content.extend(chunk[:remaining]) + if len(chunk) > remaining: + return bytes(content), True + return bytes(content), False + + def _retry_after(self, value: Optional[str], attempt: int) -> float: + delay = self.retry_delay * (2 ** min(attempt, 20)) + if value: + try: + seconds = float(value) + except ValueError: + try: + date = parsedate_to_datetime(value) + if date.tzinfo is None: + date = date.replace(tzinfo=timezone.utc) + seconds = (date - datetime.now(timezone.utc)).total_seconds() + except (ValueError, TypeError, OverflowError): + seconds = 0 + if math.isfinite(seconds): + delay = max(delay, seconds) + return max(0, delay) + + async def _request(self, url: str, base_url: str, kind: str = 'page', + max_bytes: Optional[int] = None, retry_count: int = 0): + """Fetch bounded bytes; validate every redirect before sending it.""" + if self.session is None: + return self._failure(url, 'Crawler must be used as an async context manager') + requested_url = url + current = url + chain = [] + redirects_seen = set() + started = time.monotonic() + network_seconds = 0.0 + limit = max_bytes if max_bytes is not None else self.max_content_length + while True: + if not self._valid_url(current, base_url, page=(kind == 'page'), + apply_filters=(kind != 'robots')): + return self._failure(requested_url, 'URL is invalid, excluded, or outside crawl scope', + blocked_url=current, redirect_chain=chain, + outcome='skipped', skipped=True) + normalized = self.normalize_url(current) + if normalized in redirects_seen: + return self._failure(requested_url, 'Redirect loop', redirect_chain=chain) + redirects_seen.add(normalized) + if kind != 'robots' and not await self.check_robots_txt(current): + return self._failure(requested_url, 'Blocked by robots.txt', + blocked_url=current, redirect_chain=chain, + outcome='skipped', skipped=True) + origin = self._origin(current) + response_data = None + for attempt in range(retry_count, self.retry_attempts + 1): + await self.rate_limiter.wait(origin) + request_started = time.monotonic() + try: + self.stats.requests_made += 1 + async with self.session.get(current, allow_redirects=False, + ssl=self.verify_ssl, proxy=self.proxy) as response: + headers_seconds = time.monotonic() - request_started + content, truncated = await self._read_bounded(response, limit) + request_seconds = time.monotonic() - request_started + network_seconds += request_seconds + status = response.status + response_data = { + 'url': str(response.url), 'requested_url': requested_url, + 'status_code': status, 'headers': self._response_headers(response.headers), + 'content_type': response.headers.get('Content-Type', '').lower(), + 'content': content, 'content_length': len(content), + 'truncated': truncated, 'redirect_chain': list(chain), + 'load_time': network_seconds, 'timestamp': time.time(), + 'timings': {'headers_seconds': headers_seconds, + 'download_seconds': request_seconds - headers_seconds, + 'network_seconds': network_seconds, + 'total_seconds': time.monotonic() - started}, + 'outcome': 'success', + } + retry_after = response.headers.get('Retry-After') + location = response.headers.get('Location') + self.rate_limiter.record_response(origin, request_seconds, status >= 400) + if status == 429: + self.stats.rate_limit_hits += 1 + if status >= 400: + self.stats.errors_encountered += 1 + if retry_after: + self.rate_limiter.defer(origin, self._retry_after(retry_after, attempt)) + if status in self.retry_on_status and attempt < self.retry_attempts: + self.rate_limiter.defer(origin, self._retry_after(retry_after, attempt)) + continue + if status >= 400: + response_data.update(error=f'HTTP {status}', outcome='failed') + break + except asyncio.CancelledError: + raise + except (asyncio.TimeoutError, ClientError, OSError, ValueError) as exc: + network_seconds += time.monotonic() - request_started + self.stats.errors_encountered += 1 + self.rate_limiter.record_response(origin, 0, True) + certificate_error = isinstance(exc, (aiohttp.ClientConnectorCertificateError, + aiohttp.ClientConnectorSSLError)) + if attempt < self.retry_attempts and not certificate_error and not isinstance(exc, ValueError): + self.rate_limiter.defer(origin, self._retry_after(None, attempt)) + continue + message = 'Timeout' if isinstance(exc, asyncio.TimeoutError) else str(exc) + return self._failure( + requested_url, message, redirect_chain=chain, + timings={'headers_seconds': None, 'download_seconds': None, + 'network_seconds': network_seconds, + 'total_seconds': time.monotonic() - started}, + ) + if response_data is None: + return self._failure(requested_url, 'Retry budget exhausted', redirect_chain=chain) + status = response_data['status_code'] + if status in (301, 302, 303, 307, 308) and location: + if not self.follow_redirects: + response_data.update(error='Redirect not followed', outcome='skipped', skipped=True) + return response_data + if len(chain) >= self.max_redirects: + response_data.update(error='Maximum redirects exceeded', outcome='failed') + return response_data + target = resolve_url(location, response_data['url']) + if target is None: + response_data.update(error='Invalid redirect Location', outcome='failed') + return response_data + chain.append({'url': response_data['url'], 'status_code': status, 'location': target}) + self.stats.redirects_followed += 1 + current = target + continue + response_data['redirected_from'] = requested_url if chain else None + if response_data['truncated']: + response_data.update(error='Response exceeds max_page_size', outcome='failed') + self.limit_reasons.add('max_page_size') + return response_data + + async def _get_robots(self, url: str): + origin = self._origin(url) + robots_url = origin + '/robots.txt' + async with self._robots_locks[origin]: + cached = self.robots_cache.get(robots_url) + if cached and cached[1] > time.monotonic(): + return cached[0] + response = await self._request(robots_url, self._base_url or url, kind='robots', + max_bytes=min(self.max_content_length, 512000)) + rp = RobotFileParser() + status = response['status_code'] + if status == 200 and not response.get('error'): + rp.parse(response['content'].decode('utf-8-sig', errors='replace').splitlines()) + elif (status in (401, 403, 429) or 300 <= status < 400 or status >= 500 + or status == 0 or response.get('truncated')): + rp.disallow_all = True + else: + rp.allow_all = True + self._robots_sitemaps[origin] = rp.site_maps() or [] + delay = rp.crawl_delay(self.user_agent) + if delay is not None: + self.rate_limiter.set_minimum_delay(origin, delay * self.crawl_delay_factor) + rate = rp.request_rate(self.user_agent) + if rate and rate.requests: + self.rate_limiter.set_minimum_delay(origin, rate.seconds / rate.requests) + self.robots_cache[robots_url] = (rp, time.monotonic() + self.robots_cache_ttl) + return rp + async def check_robots_txt(self, url: str) -> bool: - """Enhanced robots.txt checking with caching and expiry.""" if not self.respect_robots: return True - - parsed = urlparse(url) - robots_url = f"{parsed.scheme}://{parsed.netloc}/robots.txt" - - # Check cache with expiry (1 hour) - if robots_url in self.robots_cache: - rp, expiry = self.robots_cache[robots_url] - if time.time() < expiry: - allowed = rp.can_fetch(self.user_agent, url) - if not allowed: - self.stats.robots_blocked += 1 - return allowed - - # Fetch and parse robots.txt - try: - async with self.session.get(robots_url, timeout=ClientTimeout(total=5)) as response: - if response.status == 200: - content = await response.text() - rp = RobotFileParser() - rp.parse(content.splitlines()) - - # Extract crawl delay if specified - for line in content.splitlines(): - if line.lower().startswith('crawl-delay:'): - try: - delay = float(line.split(':')[1].strip()) - self.rate_limiter.delay = max(self.rate_limiter.delay, delay) - except: - pass - - # Cache with 1-hour expiry - self.robots_cache[robots_url] = (rp, time.time() + 3600) - - allowed = rp.can_fetch(self.user_agent, url) - if not allowed: - self.stats.robots_blocked += 1 - return allowed - except: - pass - - return True # Allow if robots.txt not found - - async def fetch_page(self, url: str, retry_count: int = 0) -> Optional[Dict[str, Any]]: - """Enhanced page fetching with retries and better error handling.""" - normalized_url = self.normalize_url(url) - - # Check if already visited - if normalized_url in self.visited_urls: + rp = await self._get_robots(url) + allowed = rp.can_fetch(self.user_agent, url) + if not allowed: + self.stats.robots_blocked += 1 + return allowed + + async def fetch_page(self, url: str, retry_count: int = 0) -> Optional[FetchResult]: + base_url = self._base_url or url + if not self._valid_url(url, base_url): + result = self._failure(url, 'URL is invalid, excluded, or outside crawl scope', + outcome='skipped', skipped=True) + self.failed_urls[str(url)] = result['error'] + return normalize_fetch_result(result, '$.fetch') + normalized = self.normalize_url(url) + if normalized in self.visited_urls: return None - - self.visited_urls.add(normalized_url) - - # Rate limiting - domain = urlparse(url).netloc - if self.adaptive_throttle: - await self.rate_limiter.wait(domain) - - # Check robots.txt - if not await self.check_robots_txt(url): - return {'url': url, 'error': 'Blocked by robots.txt', 'status_code': 0} - + self.visited_urls.add(normalized) try: - start_time = time.time() - - # Add some randomization to headers - headers = self.headers.copy() - headers['User-Agent'] = self._randomize_user_agent() - - async with self.session.get( - url, - allow_redirects=self.follow_redirects, - max_redirects=self.max_redirects, - headers=headers, - ssl=False # Skip SSL verification for better compatibility - ) as response: - load_time = time.time() - start_time - - # Track redirects - if str(response.url) != url: - self.stats.redirects_followed += 1 - - # Check content type - content_type = response.headers.get('content-type', '').lower() - is_html = any(ct in content_type for ct in ['text/html', 'application/xhtml']) - - # Handle non-HTML content - if not is_html and 'application/xml' not in content_type and 'text/xml' not in content_type: - return { - 'url': str(response.url), - 'status_code': response.status, - 'content_type': content_type, - 'error': f'Non-HTML content: {content_type}', - 'load_time': load_time - } - - # Read content with size limit - content = b'' - chunk_size = 10240 # 10KB chunks - async for chunk in response.content.iter_chunked(chunk_size): - content += chunk - self.stats.bytes_downloaded += len(chunk) - if len(content) > self.max_content_length: - content = content[:self.max_content_length] - break - - # Detect encoding - encoding = response.get_encoding() - if not encoding: - # Try to detect from content - if b'charset=' in content[:1024]: - match = re.search(b'charset=([^"\'\\s>;]+)', content[:1024]) - if match: - encoding = match.group(1).decode('ascii', errors='ignore') - else: - encoding = 'utf-8' - - # Decode content + operation = self._request(url, base_url, retry_count=max(0, retry_count)) + if self._deadline is None: + result = await asyncio.wait_for(operation, self.max_crawl_time) + else: + result = await operation + except asyncio.TimeoutError: + result = self._failure(url, 'Crawl time limit exceeded') + self.limit_reasons.add('max_crawl_time') + except asyncio.CancelledError: + raise + content = result.pop('content', b'') + content_type = result.get('content_type', '') + if not result.get('error'): + if not any(kind in content_type for kind in ('text/html', 'application/xhtml+xml')): + result.update(error=f'Non-HTML content: {content_type or "unspecified"}', + outcome='skipped', skipped=True) + else: + charset = re.search(r'charset\s*=\s*["\']?([^;\s"\']+)', content_type, re.I) + encodings = [charset.group(1)] if charset else None + decoded = UnicodeDammit(content, encodings, is_html=True) + html = decoded.unicode_markup or '' try: - html = content.decode(encoding, errors='ignore') - except: - html = content.decode('utf-8', errors='ignore') - - # Parse HTML with appropriate parser - if PARSER == 'lxml' and is_html: - # Use lxml's HTML parser for better performance - try: - soup = BeautifulSoup(html, 'lxml') - except: - soup = BeautifulSoup(html, 'html.parser') - else: soup = BeautifulSoup(html, PARSER) - - # Detect if JavaScript rendering needed - js_indicators = [ - 'window.location', - 'document.write', - 'React', - 'Angular', - 'Vue', - '__NEXT_DATA__', - '_app.js' - ] - needs_js = any(indicator in html for indicator in js_indicators) - - # Build result - result = { - 'url': str(response.url), - 'status_code': response.status, - 'content_type': content_type, - 'load_time': load_time, - 'content_length': len(content), - 'headers': dict(response.headers), - 'soup': soup, - 'timestamp': time.time(), - 'redirected_from': url if str(response.url) != url else None, - 'encoding': encoding, - 'needs_javascript': needs_js - } - - # Optionally store HTML + except FeatureNotFound: + soup = BeautifulSoup(html, 'html.parser') + result.update(soup=soup, encoding=decoded.original_encoding or 'utf-8', + needs_javascript=any(indicator in html for indicator in + ('window.location', 'document.write', 'React', + 'Angular', 'Vue', '__NEXT_DATA__', '_app.js'))) if self.store_html: result['html'] = html - - # Record successful response - self.rate_limiter.record_response(domain, load_time) - - return result - - except asyncio.TimeoutError: - self.stats.errors_encountered += 1 - if retry_count < self.retry_attempts: - await asyncio.sleep(self.retry_delay * (retry_count + 1)) - return await self.fetch_page(url, retry_count + 1) - - self.failed_urls[normalized_url] = 'Timeout' - self.rate_limiter.record_response(domain, self.timeout, is_error=True) - return {'url': url, 'error': 'Timeout', 'status_code': 0} - - except ClientError as e: - self.stats.errors_encountered += 1 - error_msg = str(e) - - # Handle rate limiting - if hasattr(e, 'status') and e.status == 429: - self.stats.rate_limit_hits += 1 - if retry_count < self.retry_attempts: - # Exponential backoff for rate limits - wait_time = min(60, 2 ** retry_count * 5) - await asyncio.sleep(wait_time) - return await self.fetch_page(url, retry_count + 1) - - self.failed_urls[normalized_url] = error_msg - self.rate_limiter.record_response(domain, 0, is_error=True) - return {'url': url, 'error': error_msg, 'status_code': getattr(e, 'status', 0)} - - except Exception as e: - self.stats.errors_encountered += 1 - self.failed_urls[normalized_url] = str(e) - return {'url': url, 'error': str(e), 'status_code': 0} - + if result.get('error'): + self.failed_urls[normalized] = result['error'] + return normalize_fetch_result(result, '$.fetch') + def _randomize_user_agent(self) -> str: - """Add slight randomization to user agent to appear more natural.""" - agents = [ - self.user_agent, - 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', - 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' - ] - return random.choice(agents) if random.random() < 0.1 else self.user_agent - + """Compatibility shim: request identity remains stable for robots rules.""" + return self.user_agent + def extract_links(self, soup: BeautifulSoup, base_url: str) -> List[Tuple[str, int]]: - """Enhanced link extraction with priority scoring.""" - links_with_priority = [] - - for tag in soup.find_all(['a', 'link']): + document_base = soup.find('base', href=True) + resolved_base = (resolve_url(document_base['href'], base_url) + if document_base else None) or base_url + links = [] + seen = set() + for tag in soup.find_all(['a', 'link'], href=True): href = tag.get('href') - if not href: + if not isinstance(href, str) or not href: continue - - # Make absolute URL - absolute_url = urljoin(base_url, href) - + absolute_url = resolve_url(href, resolved_base) if not self.is_valid_url(absolute_url, base_url): continue - - # Priority scoring (lower is higher priority) - priority = 5 # Default - - # Prioritize certain patterns - if any(pattern in href.lower() for pattern in ['index', 'home', 'main']): + normalized = self.normalize_url(absolute_url) + if normalized in seen: + continue + seen.add(normalized) + lowered = href.lower() + priority = 5 + if any(word in lowered for word in ('index', 'home', 'main')): priority = 1 - elif any(pattern in href.lower() for pattern in ['product', 'service', 'about']): + elif any(word in lowered for word in ('product', 'service', 'about')): priority = 2 - elif any(pattern in href.lower() for pattern in ['contact', 'blog', 'news']): + elif any(word in lowered for word in ('contact', 'blog', 'news')): priority = 3 - elif any(pattern in href.lower() for pattern in ['privacy', 'terms', 'legal']): + elif any(word in lowered for word in ('privacy', 'terms', 'legal')): priority = 8 - - # Deprioritize pagination if re.search(r'[?&]page=\d+', href): priority = 9 - - links_with_priority.append((absolute_url, priority)) - - return links_with_priority - - async def crawl_site(self, start_url: str, max_pages: Optional[int] = None) -> List[Dict[str, Any]]: - """Enhanced website crawling with intelligent queue management.""" - max_pages = max_pages or self.max_pages - - # Initialize queue with start URL - self.url_queue.add(start_url, priority=0, depth=0) - - # Check for sitemap - if self.follow_sitemap: - sitemap_urls = await self._discover_sitemaps(start_url) - for url in sitemap_urls[:max_pages]: - self.url_queue.add(url, priority=1, depth=1) - - # Semaphore for concurrency control - semaphore = asyncio.Semaphore(self.max_concurrent) - - async def fetch_with_semaphore(url: str): - async with semaphore: - return await self.fetch_page(url) - - active_tasks = set() - - while (self.url_queue or active_tasks) and len(self.results) < max_pages: - # Start new tasks up to concurrency limit - while len(active_tasks) < self.max_concurrent and self.url_queue and len(self.results) < max_pages: - item = self.url_queue.get() - if item: - priority, depth, url = item - if depth <= self.max_depth: - task = asyncio.create_task(fetch_with_semaphore(url)) - active_tasks.add((task, url, depth)) - - if not active_tasks: - break - - # Wait for at least one task to complete - done, pending = await asyncio.wait( - [task for task, _, _ in active_tasks], - return_when=asyncio.FIRST_COMPLETED - ) - - # Process completed tasks - for task in done: - # Find the associated URL and depth - for task_tuple in active_tasks: - if task_tuple[0] == task: - _, url, depth = task_tuple - active_tasks.remove(task_tuple) + links.append((normalized, priority)) + return links + + @staticmethod + def _frontier_limit(max_pages): + return min(100000, max_pages * 10) + + def _enqueue(self, url, priority=5, depth=0, parent_url=None): + normalized = self.normalize_url(url) + if normalized in self.visited_urls or self.url_queue.has_url(normalized): + return + if not self.url_queue.add(normalized, priority, depth): + self.limit_reasons.add('frontier') + elif parent_url is not None: + self._parents[normalized] = parent_url + + async def _run_queue(self, max_pages, follow_links): + initial_count = len(self.results) + active = {} + try: + while self.url_queue or active: + while (self.url_queue and len(active) < self.max_concurrent and + len(self.results) - initial_count + len(active) < max_pages): + # Finish a breadth level before starting the next. Otherwise + # a slow shallow route can arrive after a deeper duplicate. + if active and self.url_queue.queue[0][0] > min(depth for _, depth in active.values()): break - - try: - result = await task - if result and 'error' not in result: - self.results.append(result) - - # Extract and queue new links - if 'soup' in result and result.get('status_code') == 200: - if depth < self.max_depth: - links = self.extract_links(result['soup'], url) - for link, priority in links: - self.url_queue.add(link, priority, depth + 1) - elif result: - self.results.append(result) - except Exception as e: - logger.error(f"Error processing {url}: {e}") - - # Cancel any remaining tasks - for task, _, _ in active_tasks: - task.cancel() - + _, depth, url = self.url_queue.get() + if depth > self.max_depth: + continue + task = asyncio.create_task(self.fetch_page(url)) + active[task] = (url, depth) + if not active: + break + done, _ = await asyncio.wait(active, return_when=asyncio.FIRST_COMPLETED) + for task in done: + url, depth = active.pop(task) + try: + result = task.result() + except Exception as exc: + result = self._failure(url, str(exc)) + self.failed_urls[url] = result['error'] + if result is None: + continue + result['depth'] = depth + if url in self._parents: + result['parent_url'] = self._parents[url] + if (follow_links and not result.get('error') and + result.get('status_code') == 200 and 'soup' in result): + links = self.extract_links(result['soup'], result['url']) + if depth < self.max_depth: + for link, priority in links: + self._enqueue(link, priority, depth + 1, parent_url=result['url']) + elif any(link not in self.visited_urls and not self.url_queue.has_url(link) + for link, _ in links): + self.limit_reasons.add('max_depth') + # Consumers may release soup/html as soon as this is visible. + self.results.append(result) + if len(self.results) - initial_count >= max_pages: + if self.url_queue: + self.limit_reasons.add('max_pages') + break + finally: + for task in active: + task.cancel() + if active: + await asyncio.gather(*active, return_exceptions=True) + if self._interrupted_fetches is not None: + # wait_for can cancel before a separately sampled clock reaches + # its deadline. The caller decides whether this was a timeout. + self._interrupted_fetches.extend( + (url, depth, self._parents.get(url)) for url, depth in active.values()) return self.results - - async def _discover_sitemaps(self, base_url: str) -> List[str]: - """Discover and parse sitemaps for a website.""" - urls = [] - parsed = urlparse(base_url) - base_domain = f"{parsed.scheme}://{parsed.netloc}" - - # Common sitemap locations - sitemap_urls = [ - f"{base_domain}/sitemap.xml", - f"{base_domain}/sitemap_index.xml", - f"{base_domain}/sitemap-index.xml", - f"{base_domain}/sitemaps/sitemap.xml" - ] - - # Check robots.txt for sitemap - robots_url = f"{base_domain}/robots.txt" + + async def _run_with_deadline(self, operation, seed): + previous = self._deadline + previous_interrupted = self._interrupted_fetches + interrupted = [] + self._interrupted_fetches = interrupted + self._deadline = time.monotonic() + self.max_crawl_time + initial_count = len(self.results) + try: + return await asyncio.wait_for(operation, self.max_crawl_time) + except asyncio.TimeoutError: + self.limit_reasons.add('max_crawl_time') + for url, depth, parent_url in interrupted: + result = self._failure(url, 'Crawl time limit exceeded', depth=depth) + if parent_url is not None: + result['parent_url'] = parent_url + self.failed_urls[url] = result['error'] + self.results.append(result) + if len(self.results) == initial_count: + result = self._failure(seed, 'Crawl time limit exceeded') + self.failed_urls[seed] = result['error'] + self.results.append(result) + return self.results + finally: + self._deadline = previous + self._interrupted_fetches = previous_interrupted + + async def crawl_site(self, start_url: str, max_pages: Optional[int] = None) -> List[Dict[str, Any]]: + limit = self.max_pages if max_pages is None else max_pages + if not isinstance(limit, int) or isinstance(limit, bool) or limit <= 0: + raise ValueError('max_pages must be a positive integer') + if not self._valid_url(start_url, start_url): + result = self._failure(start_url, 'URL is invalid, excluded, or outside crawl scope', + outcome='skipped', skipped=True) + self.failed_urls[str(start_url)] = result['error'] + self.results.append(result) + return self.results + previous_base = self._base_url + self._base_url = start_url + self.url_queue = URLQueue(self._frontier_limit(limit)) + self._parents = {} + self._enqueue(start_url, 0, 0) + + async def crawl(): + if self.follow_sitemap and self.discover_sitemaps and limit > 1 and self.max_depth > 0: + for url in await self.discover_sitemap_urls(start_url, limit - 1): + self._enqueue(url, 1, 1) + return await self._run_queue(limit, follow_links=True) try: - async with self.session.get(robots_url, timeout=ClientTimeout(total=5)) as response: - if response.status == 200: - content = await response.text() - for line in content.splitlines(): - if line.lower().startswith('sitemap:'): - sitemap_url = line.split(':', 1)[1].strip() - if sitemap_url not in sitemap_urls: - sitemap_urls.append(sitemap_url) - except: - pass - - # Try to fetch sitemaps - for sitemap_url in sitemap_urls: + return await self._run_with_deadline(crawl(), start_url) + finally: + self._base_url = previous_base + + def _discovery_error(self, url, error): + if len(self.discovery_errors) < 100: + self.discovery_errors.append({'url': url, 'error': str(error)}) + logger.debug('Sitemap discovery failed for %s: %s', url, error) + + async def _parse_sitemaps(self, candidates, base_url, max_urls, speculative_urls=()): + urls = [] + found = set() + visited = set() + queued = set() + queue = deque() + sitemap_budget = max(16, min(1000, max_urls)) + speculative = {self.normalize_url(url) for url in speculative_urls} + + def enqueue(url, depth): + normalized = self.normalize_url(url) + if normalized in queued: + return + if depth > 10 or len(queued) >= sitemap_budget: + self.limit_reasons.add('sitemap_discovery') + return + if not self._valid_url(url, base_url, page=False): + self._discovery_error(url, 'Sitemap is invalid, excluded, or outside crawl scope') + return + queued.add(normalized) + queue.append((url, depth)) + + for url in candidates: + enqueue(url, 0) + while queue and len(urls) < max_urls: + url, depth = queue.popleft() + normalized = self.normalize_url(url) + if normalized in visited: + continue + visited.add(normalized) + result = await self._request(url, base_url, kind='sitemap') + if result.get('error') or result['status_code'] != 200: + # Missing guessed locations are ordinary absence, not failed + # declared sitemap coverage. + if normalized in speculative and result['status_code'] in (404, 410): + continue + self._discovery_error(url, result.get('error', f'HTTP {result["status_code"]}')) + continue try: - urls.extend(await self._parse_sitemap(sitemap_url)) - if urls: - break # Use first successful sitemap - except: + parser = ElementTree.XMLParser(target=_SitemapTreeBuilder()) + root = ElementTree.fromstring(result['content'], parser=parser) + except (ElementTree.ParseError, ValueError) as exc: + self._discovery_error(url, exc) continue - - return urls - - async def _parse_sitemap(self, sitemap_url: str) -> List[str]: - """Parse a sitemap or sitemap index.""" - urls = [] - - try: - async with self.session.get(sitemap_url, timeout=ClientTimeout(total=10)) as response: - if response.status != 200: - return urls - - content = await response.text() - - # Check if it's a sitemap index - if '= max_urls: + self.limit_reasons.add('max_pages') + return urls + found.add(identity) + urls.append(identity) else: - # Parse regular sitemap - if PARSER == 'lxml': - try: - root = etree.fromstring(content.encode('utf-8')) - for url in root.xpath('//ns:url/ns:loc/text()', - namespaces={'ns': 'http://www.sitemaps.org/schemas/sitemap/0.9'}): - urls.append(url) - except: - pass - else: - soup = BeautifulSoup(content, 'xml') - for loc in soup.find_all('loc'): - if loc.parent.name == 'url': - urls.append(loc.text.strip()) - except Exception as e: - logger.debug(f"Error parsing sitemap {sitemap_url}: {e}") - + self._discovery_error(target, 'Page is invalid, excluded, or outside crawl scope') + if queue and len(urls) >= max_urls: + self.limit_reasons.add('max_pages') return urls - + + async def _bounded_discovery(self, operation, url): + remaining = (max(0, self._deadline - time.monotonic()) + if self._deadline is not None else self.max_crawl_time) + try: + return await asyncio.wait_for(operation, remaining) + except asyncio.TimeoutError: + self.limit_reasons.add('max_crawl_time') + self._discovery_error(url, 'Crawl time limit exceeded during sitemap discovery') + return [] + + async def discover_sitemap_urls(self, base_url: str, max_urls: Optional[int] = None) -> List[str]: + """Return eligible page URLs, sharing a bounded sitemap discovery budget.""" + limit = self.max_pages if max_urls is None else max_urls + if limit <= 0 or not self.follow_sitemap or not self.discover_sitemaps: + return [] + if not self._valid_url(base_url, base_url, page=False): + self._discovery_error(base_url, 'Invalid or out-of-scope base URL') + return [] + + async def discover(): + origin = self._origin(base_url) + await self._get_robots(base_url) + candidates = list(self._robots_sitemaps.get(origin, [])) + defaults = [origin + path for path in + ('/sitemap.xml', '/sitemap_index.xml', '/sitemap-index.xml', '/sitemaps/sitemap.xml')] + speculative = [url for url in defaults if url not in candidates] + candidates.extend(defaults) + return await self._parse_sitemaps(candidates, base_url, limit, speculative) + return await self._bounded_discovery(discover(), base_url) + + async def parse_sitemap(self, sitemap_url: str, max_urls: Optional[int] = None) -> List[str]: + """Parse a sitemap/index without optional XML dependencies or recursive requests.""" + limit = self.max_pages if max_urls is None else max_urls + if limit <= 0: + return [] + return await self._bounded_discovery( + self._parse_sitemaps([sitemap_url], self._base_url or sitemap_url, limit), sitemap_url) + + async def _discover_sitemaps(self, base_url: str) -> List[str]: + return await self.discover_sitemap_urls(base_url) + + async def _parse_sitemap(self, sitemap_url: str) -> List[str]: + return await self.parse_sitemap(sitemap_url) + async def crawl_urls(self, urls: List[str]) -> List[Dict[str, Any]]: - """Crawl a list of specific URLs with improved batching.""" - # Semaphore for concurrency control - semaphore = asyncio.Semaphore(self.max_concurrent) - - async def fetch_with_semaphore(url: str): - async with semaphore: - return await self.fetch_page(url) - - # Process all URLs concurrently with proper error handling - tasks = [] + self.url_queue = URLQueue(self._frontier_limit(self.max_pages)) + self._parents = {} for url in urls: - task = asyncio.create_task(fetch_with_semaphore(url)) - tasks.append((task, url)) - - # Gather results - for task, url in tasks: - try: - result = await task - if result: - self.results.append(result) - except Exception as e: - self.failed_urls[url] = str(e) - self.results.append({'url': url, 'error': str(e), 'status_code': 0}) - - return self.results - + # Keep malformed user seeds intact so fetch_page records their error. + identity = self.normalize_url(url) if self._valid_url(url, self._base_url or url) else url + if identity not in self.visited_urls: + self.url_queue.add(identity, depth=0) + if len(self.url_queue) >= self.max_pages: + break + return await self._run_with_deadline(self._run_queue(self.max_pages, follow_links=False), + urls[0] if urls else '') + async def crawl_sitemap(self, sitemap_url: str) -> List[Dict[str, Any]]: - """Crawl URLs from a sitemap with sitemap index support.""" - urls = await self._parse_sitemap(sitemap_url) - - if not urls: - return [] - - # Crawl discovered URLs - return await self.crawl_urls(urls[:self.max_pages]) - + previous_base = self._base_url + self._base_url = sitemap_url + + async def crawl(): + urls = await self.parse_sitemap(sitemap_url) + self.url_queue = URLQueue(self._frontier_limit(self.max_pages)) + self._parents = {} + for url in urls: + self._enqueue(url, depth=0) + return await self._run_queue(self.max_pages, follow_links=False) + try: + return await self._run_with_deadline(crawl(), sitemap_url) + finally: + self._base_url = previous_base + def get_statistics(self) -> Dict[str, Any]: - """Get comprehensive crawl statistics.""" - successful = [r for r in self.results if r.get('status_code', 0) >= 200 and r.get('status_code', 0) < 400] - failed = [r for r in self.results if r.get('status_code', 0) >= 400 or 'error' in r] - redirects = [r for r in self.results if 300 <= r.get('status_code', 0) < 400] - - total_load_time = sum(r.get('load_time', 0) for r in successful) - avg_load_time = total_load_time / len(successful) if successful else 0 - - # Status code distribution - status_distribution = defaultdict(int) - for r in self.results: - status_distribution[r.get('status_code', 0)] += 1 - + successful = [r for r in self.results if 200 <= r.get('status_code', 0) < 400 and not r.get('error')] + failed = [r for r in self.results if r.get('error') or r.get('status_code', 0) >= 400] + load_time = sum(r.get('load_time', 0) for r in successful) + distribution = defaultdict(int) + for result in self.results: + distribution[result.get('status_code', 0)] += 1 + stats = self.stats.get_summary() return { - 'total_pages': len(self.results), - 'successful_pages': len(successful), + 'total_pages': len(self.results), 'successful_pages': len(successful), 'failed_pages': len(failed), - 'redirected_pages': len(redirects), + 'redirected_pages': sum(bool(r.get('redirect_chain')) for r in self.results), 'unique_urls': len(self.visited_urls), - 'average_load_time': avg_load_time, - 'total_load_time': total_load_time, - 'pages_per_second': len(successful) / total_load_time if total_load_time > 0 else 0, - 'status_distribution': dict(status_distribution), - 'failed_urls': dict(list(self.failed_urls.items())[:10]), # Top 10 failed - 'stats': self.stats.get_summary(), + 'average_load_time': load_time / len(successful) if successful else 0, + 'total_load_time': load_time, + 'pages_per_second': len(successful) / stats['elapsed_seconds'] if stats['elapsed_seconds'] else 0, + 'status_distribution': dict(distribution), + 'failed_urls': dict(list(self.failed_urls.items())[:10]), 'stats': stats, 'queue_remaining': len(self.url_queue), - 'javascript_pages': sum(1 for r in self.results if r.get('needs_javascript', False)) + 'javascript_pages': sum(bool(r.get('needs_javascript')) for r in self.results), + 'limits_reached': sorted(self.limit_reasons), + 'discovery_errors': self.discovery_errors, } -# Backward compatibility - keep old class name as alias -Crawler = EnhancedCrawler \ No newline at end of file +Crawler = EnhancedCrawler diff --git a/tfq0seo/core/models.py b/tfq0seo/core/models.py new file mode 100644 index 0000000..87c3dae --- /dev/null +++ b/tfq0seo/core/models.py @@ -0,0 +1,508 @@ +"""Versioned dictionary contracts shared by analysis and report consumers. + +Dictionary payloads remain compatible with the public library API. Optional +scores represent unavailable results, never a measured zero. +""" + +import copy +import math +from collections.abc import Mapping +from datetime import date +from typing import Any, Dict, List, Optional, TypedDict, Union +from ..page_facts import PageFacts + +SCHEMA_VERSION = '1.0' +ANALYZER_NAMES = ('seo', 'content', 'technical', 'performance', 'links') +HeaderValue = Union[str, List[str]] + + +class RedirectHop(TypedDict): + url: str + status_code: int + location: str + + +class RuleCoverage(TypedDict): + total: int + counts: Dict[str, int] + assessed: int + ratio: Optional[float] + scope: str + + +class PageSummary(TypedDict, total=False): + url: str + score: Optional[float] + status: str + status_code: int + load_time: Optional[float] + issues: Dict[str, int] + priority: Optional[int] + depth: Optional[int] + + +class ReportPages(TypedDict): + summary: List[PageSummary] + detailed: List['PageResult'] + failed: List['PageResult'] + skipped: List['PageResult'] + + +class Issue(TypedDict, total=False): + rule_id: str + category: str + severity: str + message: str + source: str + status: str + details: Dict[str, Any] + evidence: Union[Dict[str, Any], List[Any]] + url: str + rule_version: str + owner: str + applicability: str + rule_applicability: str + references: List[str] + reviewed_on: str + confidence: str + penalty: int + reason: str + scope: str + title: str + fix: str + + +class _RuleEnvelope(TypedDict): + rule_id: str + rule_version: str + scope: str + title: str + owner: str + category: str + severity: str + message: str + status: str + applicability: str + rule_applicability: str + reason: str + evidence: Union[Dict[str, Any], List[Any]] + source: str + confidence: str + references: List[str] + reviewed_on: str + fix: str + penalty: int + + +class RuleResult(_RuleEnvelope, total=False): + """A complete outcome with optional aggregate provenance and presentation detail.""" + reported_by: List[str] + observations: List[Dict[str, Any]] + score_owner: Optional[str] + details: Any + url: str + + +class _FetchIdentity(TypedDict): + url: str + + +class FetchResult(_FetchIdentity, total=False): + requested_url: str + status_code: int + error: str + soup: Any + headers: Optional[Dict[str, HeaderValue]] + redirect_chain: List[RedirectHop] + load_time: Optional[float] + timings: Dict[str, Optional[float]] + content_length: int + truncated: bool + outcome: str + skipped: bool + reason: str + content_type: str + encoding: str + html: str + depth: int + parent_url: Optional[str] + timestamp: float + redirected_from: Optional[str] + needs_javascript: bool + + +class AnalyzerResult(TypedDict, total=False): + status: str + score: Optional[float] + issues: List[Issue] + data: Dict[str, Any] + error: str + rule_results: List[RuleResult] + rule_coverage: Dict[str, Any] + recommendations: List[str] + + +class SitePageObservation(TypedDict, total=False): + url: str + canonical_targets: List[str] + canonical_status: str + canonical_terminal: Optional[str] + canonical_hops: Optional[int] + canonical_cycle_id: Optional[int] + incoming_links: int + outgoing_links: Optional[int] + nofollow_links: Optional[int] + link_depth: Optional[int] + reachable: Optional[bool] + component: Optional[int] + facts_available: bool + content_complete: bool + canonical_headers_checked: bool + + +class SiteAnalysis(TypedDict, total=False): + version: str + scope: str + coverage: Dict[str, Any] + canonicals: Dict[str, Any] + links: Dict[str, Any] + pages: List[SitePageObservation] + findings: List[RuleResult] + + +class PageResult(TypedDict, total=False): + schema_version: str + url: str + requested_url: str + status_code: int + status: str + overall_score: Optional[float] + issues: List[Issue] + issue_counts: Dict[str, int] + coverage: Dict[str, Any] + analyzer_errors: Dict[str, str] + error: str + rule_results: List[RuleResult] + rule_coverage: Dict[str, Any] + scoring: Dict[str, Any] + page_facts: Dict[str, Any] + site_analysis: SitePageObservation + recommendations: List[Dict[str, Any]] + load_time: Optional[float] + timings: Dict[str, Optional[float]] + redirect_chain: List[RedirectHop] + content_length: int + truncated: bool + timestamp: float + skipped: bool + reason: str + context: Dict[str, Any] + content_hash: str + analysis_time: float + cached: bool + seo: AnalyzerResult + content: AnalyzerResult + technical: AnalyzerResult + performance: AnalyzerResult + links: AnalyzerResult + + +class SiteReport(TypedDict, total=False): + schema_version: str + status: str + summary: Dict[str, Any] + scores: Dict[str, Any] + issues: Dict[str, Any] + pages: ReportPages + recommendations: Dict[str, Any] + technical_health: Dict[str, Any] + performance_metrics: Dict[str, Any] + metadata: Dict[str, Any] + rule_coverage: Dict[str, Any] + scoring: Dict[str, Any] + site_analysis: SiteAnalysis + + +class ContractError(ValueError): + """Invalid boundary data, identified by its field path rather than its contents.""" + + def __init__(self, path: str, message: str): + self.path = path + super().__init__(f'{path}: {message}') + + +def validate_json_value(value, path='$', _parents=None): + """Reject nonportable objects, cycles, and non-finite numbers without coercion. + + Integer dictionary keys are retained for existing HTTP-status histograms; + JSON encoders represent those keys as strings. Unknown extension fields are + allowed, but their values must obey the same contract. + """ + if value is None or isinstance(value, (str, bool, int)): + return value + if isinstance(value, float): + if not math.isfinite(value): + raise ContractError(path, 'must be a finite number or null') + return value + if not isinstance(value, (dict, list)): + raise ContractError(path, 'must contain JSON values, not ' + type(value).__name__) + parents = set() if _parents is None else _parents + if id(value) in parents: + raise ContractError(path, 'must not contain a circular reference') + parents.add(id(value)) + try: + entries = value.items() if isinstance(value, dict) else enumerate(value) + for key, item in entries: + if isinstance(value, dict) and not (isinstance(key, str) or type(key) is int): + raise ContractError(path, 'object keys must be strings or integer status codes') + child = f'{path}[{key}]' if isinstance(value, list) else f'{path}.{key}' + validate_json_value(item, child, parents) + finally: + parents.remove(id(value)) + return value + + +def _mapping(value, path): + if not isinstance(value, dict): + raise ContractError(path, 'must be an object') + + +def _string(value, path, *, nonempty=False): + if not isinstance(value, str) or (nonempty and not value.strip()): + raise ContractError(path, 'must be a nonempty string' if nonempty else 'must be a string') + + +def _number(value, path, *, nullable=False, maximum=None, integer=False): + if value is None and nullable: + return + valid = type(value) is int if integer else type(value) in (int, float) + if not valid or value < 0 or (isinstance(value, float) and not math.isfinite(value)): + raise ContractError(path, 'must be a nonnegative finite ' + ('integer' if integer else 'number')) + if maximum is not None and value > maximum: + raise ContractError(path, f'must not exceed {maximum}') + + +def normalize_fetch_result(value, path='$') -> FetchResult: + """Validate fetch input and detach metadata while keeping the parsed DOM. + + Missing observations stay unavailable. Legacy partial dictionaries are + supported; malformed supplied fields are never silently coerced. + """ + if not isinstance(value, Mapping): + raise ContractError(path, 'fetch result must be an object') + _string(value.get('url'), path + '.url', nonempty=True) + for key in ('requested_url', 'error', 'reason', 'content_type', 'encoding', 'html', 'outcome'): + if key in value: + _string(value[key], path + '.' + key) + for key in ('parent_url', 'redirected_from'): + if value.get(key) is not None: + _string(value[key], path + '.' + key) + for key in ('load_time', 'timestamp'): + if key in value: + _number(value[key], path + '.' + key, nullable=(key == 'load_time')) + for key in ('content_length', 'depth'): + if key in value: + _number(value[key], path + '.' + key, integer=True) + if 'status_code' in value: + _number(value['status_code'], path + '.status_code', integer=True, maximum=599) + if 0 < value['status_code'] < 100: + raise ContractError(path + '.status_code', 'must be zero or an HTTP status from 100 to 599') + for key in ('truncated', 'skipped', 'needs_javascript'): + if key in value and type(value[key]) is not bool: + raise ContractError(path + '.' + key, 'must be a boolean') + timings = value.get('timings', {}) + _mapping(timings, path + '.timings') + for key, duration in timings.items(): + _string(key, path + '.timings key') + _number(duration, path + '.timings.' + key, nullable=True) + chain = value.get('redirect_chain', []) + if not isinstance(chain, list): + raise ContractError(path + '.redirect_chain', 'must be a list') + for index, hop in enumerate(chain): + hop_path = f'{path}.redirect_chain[{index}]' + _mapping(hop, hop_path) + _string(hop.get('url'), hop_path + '.url', nonempty=True) + _string(hop.get('location'), hop_path + '.location', nonempty=True) + _number(hop.get('status_code'), hop_path + '.status_code', integer=True, maximum=399) + if hop['status_code'] < 300: + raise ContractError(hop_path + '.status_code', 'must be an HTTP redirect status') + headers = value.get('headers') + if headers is not None: + if not isinstance(headers, Mapping): + raise ContractError(path + '.headers', 'must be a header mapping or null') + detached_headers = {} + for key in headers: + _string(key, path + '.headers key', nonempty=True) + header = headers.getall(key) if hasattr(headers, 'getall') else headers[key] + values = header if isinstance(header, (list, tuple)) else [header] + for part in values: + _string(part, path + '.headers.' + key) + detached_headers[str(key)] = list(values) if isinstance(header, (list, tuple)) else header + headers = detached_headers + soup = value.get('soup') + if soup is not None: + from bs4 import BeautifulSoup + if not isinstance(soup, BeautifulSoup): + raise ContractError(path + '.soup', 'must be a BeautifulSoup document or null') + result = {key: copy.deepcopy(item) for key, item in value.items() if key not in ('soup', 'headers')} + result['headers'] = headers + if 'soup' in value: + result['soup'] = soup + validate_json_value({key: item for key, item in result.items() if key != 'soup'}, path) + outcome = result.get('outcome') + if outcome is not None and outcome not in ('success', 'failed', 'skipped'): + raise ContractError(path + '.outcome', 'must be success, failed, or skipped') + if outcome == 'failed' and not result.get('error'): + result['error'] = 'Fetch failed without an error description' + if outcome == 'skipped': + result['skipped'] = True + result.setdefault('reason', result.get('error') or 'Fetch was skipped') + if outcome == 'success' and (result.get('error') or result.get('skipped')): + raise ContractError(path + '.outcome', 'success conflicts with error or skipped state') + if outcome == 'failed' and result.get('skipped'): + raise ContractError(path + '.outcome', 'failed conflicts with skipped state') + result.setdefault('requested_url', result.get('redirected_from') or result['url']) + result.setdefault('status_code', 0) + result.setdefault('load_time', None) + result.setdefault('timings', {}) + result.setdefault('redirect_chain', []) + result.setdefault('truncated', False) + return result + + +def validate_rule_result(value, path='$', *, registered=True): + """Validate a complete live rule outcome before merging or scoring it.""" + from ..rules import ANALYZERS, STATUSES, RULESET_VERSION, finding_penalty, get_rule + _mapping(value, path) + for key in ('rule_id', 'rule_version', 'scope', 'title', 'owner', 'category', 'severity', + 'message', 'status', 'applicability', 'rule_applicability', 'source', + 'confidence', 'reviewed_on', 'fix'): + _string(value.get(key), path + '.' + key, nonempty=True) + _string(value.get('reason'), path + '.reason') + if value['status'] not in STATUSES: + raise ContractError(path + '.status', 'unknown rule outcome') + if value['applicability'] not in ('applicable', 'unknown', 'not_applicable'): + raise ContractError(path + '.applicability', 'unknown applicability') + if value['confidence'] not in ('high', 'medium', 'low'): + raise ContractError(path + '.confidence', 'must be high, medium, or low') + if value['scope'] not in ('page', 'site'): + raise ContractError(path + '.scope', 'must be page or site') + if value['status'] in ('pass', 'fail', 'informational') and value['applicability'] != 'applicable': + raise ContractError(path + '.applicability', 'assessed outcomes must be applicable') + if (value['status'] == 'not_applicable') != (value['applicability'] == 'not_applicable'): + raise ContractError(path + '.applicability', 'not_applicable must match the outcome') + if value['status'] in ('unknown', 'not_applicable', 'error') and not value['reason'].strip(): + raise ContractError(path + '.reason', 'unavailable outcomes require an explanation') + if not isinstance(value.get('evidence'), (dict, list)): + raise ContractError(path + '.evidence', 'must be structured observations') + references = value.get('references') + if not isinstance(references, list) or not references: + raise ContractError(path + '.references', 'must be a nonempty list') + for index, reference in enumerate(references): + _string(reference, f'{path}.references[{index}]', nonempty=True) + try: + date.fromisoformat(value['reviewed_on']) + except ValueError: + raise ContractError(path + '.reviewed_on', 'must be an ISO calendar date') from None + _number(value.get('penalty'), path + '.penalty', integer=True) + if value['status'] != 'fail' and value['penalty'] != 0: + raise ContractError(path + '.penalty', 'only failed rules can have a deduction') + if registered: + try: + definition = get_rule(value['rule_id']) + except ValueError: + raise ContractError(path + '.rule_id', 'must identify a registered rule') from None + if value['owner'] != definition.owner or value['severity'] != definition.severity: + raise ContractError(path, 'owner and severity must match the registered rule') + expected = {'rule_version': RULESET_VERSION, 'fix': definition.recommendation, + 'references': list(definition.references), 'reviewed_on': definition.reviewed_on, + 'rule_applicability': definition.applicability} + for key, recorded in expected.items(): + if value[key] != recorded: + raise ContractError(path + '.' + key, 'must match the registered live rule') + if value['status'] == 'fail' and (not definition.scored or value['confidence'] == 'low'): + raise ContractError(path + '.status', 'advisory findings must be informational') + if value['penalty'] != finding_penalty(value): + raise ContractError(path + '.penalty', 'must match the rule scoring policy') + for key in ('reported_by',): + if key in value and (not isinstance(value[key], list) or + any(item not in ANALYZERS for item in value[key])): + raise ContractError(path + '.' + key, 'must list known analyzers') + if value.get('score_owner') is not None and value['score_owner'] not in ANALYZERS: + raise ContractError(path + '.score_owner', 'must identify an analyzer or be null') + if 'observations' in value: + if not isinstance(value['observations'], list): + raise ContractError(path + '.observations', 'must be a list') + for index, observation in enumerate(value['observations']): + observation_path = f'{path}.observations[{index}]' + _mapping(observation, observation_path) + if observation.get('status') not in STATUSES: + raise ContractError(observation_path + '.status', 'unknown observation outcome') + if not isinstance(observation.get('evidence'), (dict, list)): + raise ContractError(observation_path + '.evidence', 'must be structured observations') + if observation.get('applicability') not in ('applicable', 'unknown', 'not_applicable'): + raise ContractError(observation_path + '.applicability', 'unknown applicability') + if (observation['status'] in ('pass', 'fail', 'informational') and + observation['applicability'] != 'applicable'): + raise ContractError(observation_path + '.applicability', 'assessed outcomes must be applicable') + if (observation['status'] == 'not_applicable') != (observation['applicability'] == 'not_applicable'): + raise ContractError(observation_path + '.applicability', 'not_applicable must match the outcome') + reporters = observation.get('reported_by') + if reporters is not None and (not isinstance(reporters, list) or any(item not in ANALYZERS for item in reporters)): + raise ContractError(observation_path + '.reported_by', 'must list known analyzers or be null') + _string(observation.get('source'), observation_path + '.source', nonempty=True) + if observation['status'] in ('unknown', 'not_applicable', 'error'): + _string(observation.get('reason'), observation_path + '.reason', nonempty=True) + validate_json_value(value, path) + return value + + +def validate_analyzer_result(value, path='$') -> AnalyzerResult: + """Validate live analyzer output, including every nested issue and outcome.""" + _mapping(value, path) + if not isinstance(value.get('issues'), list): + raise ContractError(path + '.issues', 'must be a list') + if 'score' in value: + _number(value['score'], path + '.score', nullable=True, maximum=100) + if 'status' in value and value['status'] not in ('complete', 'partial', 'error'): + raise ContractError(path + '.status', 'must be complete, partial, or error') + if value.get('status') == 'error' and not value.get('error'): + raise ContractError(path + '.error', 'errored analyzers require an explanation') + if 'error' in value: + _string(value['error'], path + '.error') + if value.get('error'): + _string(value['error'], path + '.error', nonempty=True) + if value.get('score') is not None: + raise ContractError(path + '.score', 'errored analyzers must have an unavailable score') + if value.get('status') in ('complete', 'partial'): + raise ContractError(path + '.status', 'conflicts with the analyzer error') + if 'data' in value: + _mapping(value['data'], path + '.data') + for index, issue in enumerate(value['issues']): + issue_path = f'{path}.issues[{index}]' + _mapping(issue, issue_path) + if 'rule_version' in issue: + validate_rule_result(issue, issue_path) + else: + for key in ('message', 'category', 'severity'): + _string(issue.get(key), issue_path + '.' + key, nonempty=True) + if issue['severity'] not in ('critical', 'warning', 'notice'): + raise ContractError(issue_path + '.severity', 'unknown issue severity') + if 'rule_results' in value: + if not isinstance(value['rule_results'], list): + raise ContractError(path + '.rule_results', 'must be a list') + for index, result in enumerate(value['rule_results']): + validate_rule_result(result, f'{path}.rule_results[{index}]') + expected_issues = [result for result in value['rule_results'] + if result['status'] in ('fail', 'informational')] + if (len(value['issues']) != len(expected_issues) or + any(issue not in expected_issues for issue in value['issues']) or + any(issue not in value['issues'] for issue in expected_issues)): + raise ContractError(path + '.issues', 'must contain the failed and informational rule evaluations') + if 'recommendations' in value: + if not isinstance(value['recommendations'], list): + raise ContractError(path + '.recommendations', 'must be a list') + for index, recommendation in enumerate(value['recommendations']): + _string(recommendation, f'{path}.recommendations[{index}]') + validate_json_value(value, path) + return value diff --git a/tfq0seo/core/report_contracts.py b/tfq0seo/core/report_contracts.py new file mode 100644 index 0000000..380b188 --- /dev/null +++ b/tfq0seo/core/report_contracts.py @@ -0,0 +1,383 @@ +"""Validate report dictionaries without rewriting historical evidence or scores. + +Producer envelopes are stricter than imported archives. Unknown extension fields +remain intact, and archived rule identifiers are not checked against today's +registry. Presentation code must still escape strings and restrict link schemes. +""" + +from .models import ANALYZER_NAMES, ContractError, validate_json_value + + +def _mapping(value, path): + if not isinstance(value, dict): + raise ContractError(path, 'must be an object') + + +def _list(value, path): + if not isinstance(value, list): + raise ContractError(path, 'must be an array') + + +def _text(value, path, nullable=False): + if value is None and nullable: + return + if not isinstance(value, str): + raise ContractError(path, 'must be a string' + (' or null' if nullable else '')) + + +def _number(value, path, nullable=True): + if value is None and nullable: + return + if type(value) not in (int, float): + raise ContractError(path, 'must be a number' + (' or null' if nullable else '')) + + +def _score(value, path): + _number(value, path) + if value is not None and not 0 <= value <= 100: + raise ContractError(path, 'must be between 0 and 100 or null') + + +def _count(value, path): + if type(value) is not int or value < 0: + raise ContractError(path, 'must be a nonnegative integer') + + +def _fields(data, names, validator, path): + for name in names: + if name in data: + validator(data[name], path + '.' + name) + + +def _required(data, names, path): + for name in names: + if name not in data: + raise ContractError(path + '.' + name, 'is required') + + +def _records(value, path, validator): + _list(value, path) + for index, item in enumerate(value): + validator(item, f'{path}[{index}]') + + +def _counts(value, path): + _mapping(value, path) + for name, count in value.items(): + _text(name, path + '.') + _count(count, path + '.' + name) + + +def _scores(value, path): + _mapping(value, path) + for name, score in value.items(): + _text(name, path + '.') + _score(score, path + '.' + name) + + +def _issue(value, path): + _mapping(value, path) + _fields(value, ('rule_id', 'rule_version', 'category', 'severity', 'message', 'source', + 'status', 'fix', 'url', 'owner', 'applicability', 'rule_applicability', + 'reviewed_on', 'confidence', 'reason', 'title'), + lambda item, name: _text(item, name, nullable=True), path) + _fields(value, ('count', 'pages_affected'), _count, path) + _fields(value, ('observations', 'evidence_by_page'), lambda item, name: _records(item, name, _mapping), path) + _fields(value, ('references', 'reported_by', 'pages', 'example_pages'), + lambda item, name: _records(item, name, _text), path) + # Legacy detail/evidence structures may be arbitrary JSON values. Their + # portability is checked once at the public boundary, not reinterpreted here. + + +def _recommendation(value, path): + if isinstance(value, str): + return + _mapping(value, path) + _fields(value, ('recommendation', 'description', 'title', 'priority', 'category', 'effort', 'rule_id'), + lambda item, name: _text(item, name, nullable=True), path) + + +def _executive(value, path): + _mapping(value, path) + _fields(value, ('overview', 'key_metrics'), _mapping, path) + _fields(value, ('quick_wins', 'action_items'), lambda item, name: _records(item, name, _recommendation), path) + _fields(value, ('top_issues',), lambda item, name: _records(item, name, _issue), path) + + +def _recommendations(value, path): + if isinstance(value, dict): + _fields(value, ('specific',), lambda item, name: _records(item, name, _recommendation), path) + _fields(value, ('executive',), _executive, path) + else: + _records(value, path, _recommendation) + + +def _coverage(value, path): + _mapping(value, path) + _fields(value, ('counts',), _counts, path) + _fields(value, ('total', 'assessed'), _count, path) + _fields(value, ('ratio',), _number, path) + + +def _analyzer(value, path): + _mapping(value, path) + _fields(value, ('score',), _score, path) + _fields(value, ('error', 'status'), _text, path) + _fields(value, ('issues', 'rule_results'), lambda item, name: _records(item, name, _issue), path) + _fields(value, ('rule_coverage',), _coverage, path) + _fields(value, ('recommendations',), lambda item, name: _records(item, name, _recommendation), path) + if 'data' not in value: + return + data, data_path = value['data'], path + '.data' + _mapping(data, data_path) + _fields(data, ('metrics', 'readability', 'image_analysis', 'mobile', 'performance', + 'quality_assessment', 'scores', 'network_metrics', 'metric_sources', 'open_graph'), _mapping, data_path) + _fields(data, ('structured_data',), lambda item, name: _records(item, name, _mapping), data_path) + for container, container_path in ((data, data_path), (data.get('metrics', {}), data_path + '.metrics')): + _fields(container, ('word_count', 'image_count', 'total_resources'), + lambda item, name: None if item is None else _count(item, name), container_path) + _fields(container, ('html_fetch_time', 'content_size_mb', 'lcp', 'inp', 'fid', 'cls', 'fcp', 'tti', 'tbt', 'ttfb'), _number, container_path) + for key in ('title', 'description'): + if key in data: + if isinstance(data[key], dict): + _fields(data[key], ('text',), _text, data_path + '.' + key) + _fields(data[key], ('length',), _count, data_path + '.' + key) + else: + _text(data[key], data_path + '.' + key) + for key in ('internal_links', 'external_links', 'non_http_links'): + if key in data: + _records(data[key], data_path + '.' + key, _link) + _fields(data, ('recommendations',), lambda item, name: _records(item, name, _recommendation), data_path) + + +def _link(value, path): + _mapping(value, path) + _fields(value, ('url', 'href', 'text', 'anchor_text'), _text, path) + + +def _common(data, path): + _fields(data, ('schema_version', 'url', 'requested_url', 'status', 'error', 'reason'), _text, path) + _fields(data, ('overall_score', 'score'), _score, path) + _fields(data, ('issue_counts',), _counts, path) + _fields(data, ('category_scores',), _scores, path) + _fields(data, ('rule_results', 'aggregated_issues'), lambda item, name: _records(item, name, _issue), path) + _fields(data, ('rule_coverage',), _coverage, path) + _fields(data, ('coverage', 'scoring', 'aggregation_stats', 'summary', 'technical_health', 'metadata'), _mapping, path) + _fields(data, ('executive_summary',), _executive, path) + _fields(data, ('enhanced_recommendations',), lambda item, name: _records(item, name, _recommendation), path) + _fields(data, ('recommendations',), _recommendations, path) + if 'coverage' in data: + _fields(data['coverage'], ('rules',), _coverage, path + '.coverage') + if 'scores' in data: + scores = data['scores'] + _mapping(scores, path + '.scores') + _fields(scores, ('overall',), _score, path + '.scores') + _fields(scores, ('categories',), _scores, path + '.scores') + _fields(scores, ('scoring_versions',), lambda item, name: _records(item, name, _text), path + '.scores') + if 'aggregation_stats' in data: + _fields(data['aggregation_stats'], ('reduction_ratio',), _number, path + '.aggregation_stats') + if 'performance_metrics' in data: + metrics = data['performance_metrics'] + metrics_path = path + '.performance_metrics' + _mapping(metrics, metrics_path) + _fields(metrics, ('load_time_stats', 'score_stats', 'status_codes'), _mapping, metrics_path) + _fields(metrics, ('load_times', 'content_sizes', 'issues_per_page', 'scores_per_page', 'slowest_pages', 'lowest_scoring_pages'), + lambda item, name: _records(item, name, _mapping), metrics_path) + + +def _optional_count(value, path): + if value is not None: + _count(value, path) + + +def _boolean(value, path): + if type(value) is not bool: + raise ContractError(path, 'must be a boolean') + + +def _page_facts(value, path): + """Validate fields consumed during site aggregation, without inventing them.""" + _mapping(value, path) + _fields(value, ('facts_version', 'url', 'base_url'), _text, path) + if 'robots' in value: + _mapping(value['robots'], path + '.robots') + _fields(value['robots'], ('noindex', 'nofollow'), _boolean, path + '.robots') + if 'anchors' in value: + _records(value['anchors'], path + '.anchors', _mapping) + for index, anchor in enumerate(value['anchors']): + anchor_path = f'{path}.anchors[{index}]' + _required(anchor, ('url', 'attrs'), anchor_path) + _fields(anchor, ('url',), lambda item, name: _text(item, name, nullable=True), anchor_path) + if 'attrs' in anchor: + _mapping(anchor['attrs'], anchor_path + '.attrs') + if 'rel' in anchor['attrs']: + rel = anchor['attrs']['rel'] + if isinstance(rel, list): + _records(rel, anchor_path + '.attrs.rel', _text) + elif rel is not None: + _text(rel, anchor_path + '.attrs.rel') + if 'canonical' in value: + canonical_path = path + '.canonical' + canonical = value['canonical'] + _mapping(canonical, canonical_path) + _fields(canonical, ('headers_checked',), _boolean, canonical_path) + _fields(canonical, ('parse_errors',), _count, canonical_path) + if 'declarations' in canonical: + _records(canonical['declarations'], canonical_path + '.declarations', _mapping) + for index, declaration in enumerate(canonical['declarations']): + declaration_path = f'{canonical_path}.declarations[{index}]' + _required(declaration, ('url', 'eligible'), declaration_path) + _fields(declaration, ('url', 'href'), lambda item, name: _text(item, name, nullable=True), declaration_path) + _fields(declaration, ('eligible',), _boolean, declaration_path) + _fields(declaration, ('source', 'reason'), _text, declaration_path) + + +def _site_page(value, path): + _mapping(value, path) + _required(value, ('url', 'canonical_targets', 'canonical_status', 'canonical_terminal', 'canonical_hops', + 'incoming_links', 'outgoing_links', 'link_depth'), path) + _fields(value, ('url', 'canonical_status'), _text, path) + _fields(value, ('canonical_terminal',), lambda item, name: _text(item, name, nullable=True), path) + _fields(value, ('canonical_targets',), lambda item, name: _records(item, name, _text), path) + _fields(value, ('incoming_links',), _count, path) + _fields(value, ('canonical_hops', 'canonical_cycle_id', 'outgoing_links', 'nofollow_links', 'link_depth', 'component'), _optional_count, path) + _fields(value, ('facts_available', 'content_complete', 'canonical_headers_checked'), _boolean, path) + if value.get('reachable') is not None: + _boolean(value['reachable'], path + '.reachable') + + +def _site_analysis(value, path): + _mapping(value, path) + _required(value, ('version', 'scope', 'coverage', 'canonicals', 'links', 'pages', 'findings'), path) + _fields(value, ('version', 'scope'), _text, path) + _records(value['pages'], path + '.pages', _site_page) + _records(value['findings'], path + '.findings', _issue) + _mapping(value['coverage'], path + '.coverage') + _fields(value['coverage'], ('inventory_pages', 'pages_with_facts', 'complete_html_pages'), _count, path + '.coverage') + _fields(value['coverage'], ('crawl_complete',), _boolean, path + '.coverage') + _fields(value['coverage'], ('note',), _text, path + '.coverage') + _mapping(value['canonicals'], path + '.canonicals') + _fields(value['canonicals'], ('status_counts',), _counts, path + '.canonicals') + _fields(value['canonicals'], ('unchecked_targets',), lambda item, name: _records(item, name, _text), path + '.canonicals') + _mapping(value['links'], path + '.links') + links = value['links'] + _required(links, ('node_count', 'edge_count', 'roots', 'components', 'unfetched_targets', 'edges', 'depth_method'), path + '.links') + _fields(links, ('node_count', 'edge_count'), _count, path + '.links') + _fields(links, ('root_source', 'depth_method'), _text, path + '.links') + _fields(links, ('roots', 'unfetched_targets'), lambda item, name: _records(item, name, _text), path + '.links') + for collection, collection_path in ((links['components'], path + '.links.components'), + (value['canonicals'].get('cycles', []), path + '.canonicals.cycles')): + _records(collection, collection_path, _mapping) + for index, group in enumerate(collection): + group_path = f'{collection_path}[{index}]' + _required(group, ('id', 'urls'), group_path) + _count(group['id'], group_path + '.id') + _records(group['urls'], group_path + '.urls', _text) + _records(links['edges'], path + '.links.edges', _mapping) + for index, edge in enumerate(links['edges']): + edge_path = f'{path}.links.edges[{index}]' + _required(edge, ('source', 'target', 'nofollow', 'target_observed'), edge_path) + _fields(edge, ('source', 'target'), _text, edge_path) + _fields(edge, ('nofollow', 'target_observed'), _boolean, edge_path) + if links['edge_count'] != len(links['edges']) or links['node_count'] != len(value['pages']): + raise ContractError(path + '.links', 'node and edge counts must match the recorded graph') + + +def _page(data, path, strict=False): + _mapping(data, path) + if strict: + _required(data, ('schema_version', 'url', 'status', 'status_code', 'overall_score', 'issues', 'issue_counts', 'recommendations'), path) + if data['status'] not in ('complete', 'partial', 'error', 'skipped'): + raise ContractError(path + '.status', 'must be complete, partial, error, or skipped') + _common(data, path) + _fields(data, ('page_facts',), _page_facts, path) + _fields(data, ('site_analysis',), _site_page, path) + for key in ('status_code', 'content_length'): + if key in data and (strict or data[key] is not None): + _count(data[key], path + '.' + key) + _fields(data, ('load_time', 'analysis_time'), _number, path) + _fields(data, ('analyzer_errors', 'timings', 'context'), _mapping, path) + _fields(data, ('redirect_chain',), lambda item, name: _records(item, name, _mapping), path) + _fields(data, ANALYZER_NAMES, _analyzer, path) + if 'issues' in data: + issues = data['issues'] + if isinstance(issues, dict) and not strict: + # Historical site page summaries contain issue-count dictionaries. + _counts(issues, path + '.issues') + else: + _records(issues, path + '.issues', _issue) + if strict: + _list(data['recommendations'], path + '.recommendations') + if not data['url'].strip(): + raise ContractError(path + '.url', 'must not be empty') + if data['status'] in ('error', 'skipped') and data['overall_score'] is not None: + raise ContractError(path + '.overall_score', 'must be null for an error or skipped page') + if data['status'] == 'error' and not data.get('error', '').strip(): + raise ContractError(path + '.error', 'an error page requires an explanation') + if data.get('error') and data['status'] != 'error': + raise ContractError(path + '.status', 'must be error when the page has an error') + + +def _site(data, path, strict=False): + _mapping(data, path) + if strict: + _required(data, ('schema_version', 'status'), path) + if data['status'] not in ('complete', 'partial', 'error'): + raise ContractError(path + '.status', 'must be complete, partial, or error') + if not (data['status'] == 'error' and data.get('error') and 'pages' not in data): + _required(data, ('summary', 'scores', 'issues', 'pages', 'recommendations'), path) + for key, required in ( + ('summary', ('total_pages', 'successful_pages', 'partial_pages', 'failed_pages', 'skipped_pages')), + ('scores', ('overall', 'categories')), + ('issues', ('aggregated', 'stats', 'counts', 'top_issues')), + ('pages', ('summary', 'detailed', 'failed', 'skipped')), + ('recommendations', ('specific', 'executive')), + ): + _mapping(data[key], path + '.' + key) + _required(data[key], required, path + '.' + key) + _common(data, path) + _fields(data, ('site_analysis',), _site_analysis, path) + if 'summary' in data: + _fields(data['summary'], ('total_pages', 'successful_pages', 'partial_pages', 'failed_pages', 'skipped_pages'), _count, path + '.summary') + if 'issues' in data: + issues = data['issues'] + if isinstance(issues, dict): + _fields(issues, ('aggregated', 'top_issues'), lambda item, name: _records(item, name, _issue), path + '.issues') + _fields(issues, ('stats',), _mapping, path + '.issues') + if 'stats' in issues: + _fields(issues['stats'], ('reduction_ratio',), _number, path + '.issues.stats') + _fields(issues, ('counts',), _counts, path + '.issues') + else: + _records(issues, path + '.issues', _issue) + if 'pages' in data: + pages = data['pages'] + if isinstance(pages, dict): + for key in ('summary', 'detailed', 'failed', 'skipped'): + if key in pages: + _records(pages[key], path + '.pages.' + key, _page) + else: + _records(pages, path + '.pages', _page) + + +def validate_page_result(data, *, strict=False, path='$'): + """Validate a page or historical page summary and return the same object.""" + validate_json_value(data, path) + _page(data, path, strict) + return data + + +def validate_site_report(data, *, strict=False, path='$'): + """Validate a site envelope; archived nested pages keep compatible validation.""" + validate_json_value(data, path) + _site(data, path, strict) + return data + + +def validate_report(data, *, strict=False): + """Validate either report shape before any export writer opens a file.""" + _mapping(data, '$') + if any(key in data for key in ('pages', 'aggregated_issues')) or ('summary' in data and 'scores' in data): + return validate_site_report(data, strict=strict) + if data.get('status') == 'error' and 'url' not in data: + return validate_site_report(data, strict=strict) + return validate_page_result(data, strict=strict) diff --git a/tfq0seo/core/report_optimizer.py b/tfq0seo/core/report_optimizer.py index 4b5d164..18ec790 100644 --- a/tfq0seo/core/report_optimizer.py +++ b/tfq0seo/core/report_optimizer.py @@ -1,372 +1,116 @@ -"""Report optimization utilities for aggregating and enhancing report data.""" +"""Pure report aggregation over recorded evidence; no synthetic measurements.""" -from typing import Dict, List, Any, Tuple -from collections import Counter, defaultdict -import hashlib +import copy +import math +from collections import Counter, OrderedDict +from statistics import mean, median +from typing import Any, Dict, List, Tuple +from ..rules import RULESET_VERSION, get_rule -def aggregate_issues(issues: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]: - """ - Aggregate duplicate issues across multiple pages. - - Returns: - - Aggregated unique issues with occurrence counts - - Statistics about the aggregation - """ - # Create issue signatures for deduplication - issue_map = defaultdict(lambda: {'count': 0, 'pages': [], 'first_seen': None}) - +def aggregate_issues(issues: List[Dict[str, Any]]) -> Tuple[List[Dict], Dict]: + grouped = OrderedDict() for issue in issues: - # Create a unique signature for each issue type - signature = f"{issue.get('severity')}:{issue.get('category')}:{issue.get('message')}" - - issue_map[signature]['count'] += 1 - issue_map[signature]['severity'] = issue.get('severity') - issue_map[signature]['category'] = issue.get('category') - issue_map[signature]['message'] = issue.get('message') - - # Track which pages have this issue - if 'url' in issue: - issue_map[signature]['pages'].append(issue['url']) - - if not issue_map[signature]['first_seen']: - issue_map[signature]['first_seen'] = issue - if 'details' in issue: - issue_map[signature]['details'] = issue['details'] - - # Convert to list of aggregated issues - aggregated = [] - for signature, data in issue_map.items(): - aggregated_issue = { - 'severity': data['severity'], - 'category': data['category'], - 'message': data['message'], - 'count': data['count'], - 'pages_affected': len(set(data['pages'])), - 'example_pages': list(set(data['pages'][:5])), # First 5 unique pages - } - if 'details' in data: - aggregated_issue['details'] = data['details'] - aggregated.append(aggregated_issue) - - # Sort by severity and count - severity_order = {'critical': 0, 'warning': 1, 'notice': 2} - aggregated.sort(key=lambda x: (severity_order.get(x['severity'], 3), -x['count'])) - - # Calculate statistics - stats = { - 'total_issues': len(issues), - 'unique_issues': len(aggregated), - 'reduction_ratio': 1 - (len(aggregated) / len(issues)) if issues else 0, - 'most_common': aggregated[0] if aggregated else None, - 'pages_with_issues': len(set(issue.get('url', '') for issue in issues if 'url' in issue)) + key = ('rule', issue['rule_id'], issue.get('rule_version')) if issue.get('rule_id') else ( + 'legacy', issue.get('message'), issue.get('category'), issue.get('severity')) + if key not in grouped: + grouped[key] = {**copy.deepcopy(issue), 'count': 0, 'pages': [], 'evidence_by_page': []} + grouped[key].pop('url', None) + item = grouped[key] + item['count'] += 1 + if issue.get('url') and issue['url'] not in item['pages']: + item['pages'].append(issue['url']) + if issue.get('url') and 'evidence' in issue: + item['evidence_by_page'].append({field: copy.deepcopy(issue.get(field)) for field in + ('url', 'evidence', 'observations', 'status', 'applicability', 'score_owner')}) + aggregated = list(grouped.values()) + for item in aggregated: + item['pages_affected'] = len(item['pages']) + item['example_pages'] = item['pages'][:5] + order = {'critical': 0, 'warning': 1, 'notice': 2} + aggregated.sort(key=lambda item: (order.get(item.get('severity'), 3), -item['count'])) + return aggregated, { + 'total_issues': len(issues), 'unique_issues': len(aggregated), + 'reduction_ratio': 1 - len(aggregated) / len(issues) if issues else 0, + 'most_common': max(aggregated, key=lambda item: item['count']) if aggregated else None, + 'pages_with_issues': len({item['url'] for item in issues if item.get('url')}), } - - return aggregated, stats -def generate_specific_recommendations(report: Dict[str, Any]) -> List[Dict[str, Any]]: - """Generate specific, actionable recommendations based on the analysis.""" +def generate_specific_recommendations(report: Dict[str, Any]) -> List[Dict]: + raw = report.get('issues', {}) + issues = raw.get('aggregated', []) if isinstance(raw, dict) else raw + issues = report.get('aggregated_issues', issues) recommendations = [] - - # Analyze aggregated issues - if 'aggregated_issues' in report: - issues = report['aggregated_issues'] - else: - issues = report.get('issues', []) - - # Priority 1: Critical SEO issues - critical_seo = [i for i in issues if i.get('severity') == 'critical' and i.get('category') == 'SEO'] - - for issue in critical_seo[:3]: - if 'Missing page title' in issue.get('message', ''): - recommendations.append({ - 'priority': 'HIGH', - 'category': 'SEO', - 'title': 'Add Page Titles', - 'description': f"Add unique, descriptive title tags to {issue.get('count', 'multiple')} pages", - 'implementation': """ - Your Page Title - Brand Name - - Keep titles between 50-60 characters - - Include primary keywords naturally - - Make each page title unique - - Place important keywords near the beginning - """.strip(), - 'impact': 'Critical for search rankings and click-through rates', - 'effort': 'Low', - 'affected_pages': issue.get('count', 0) - }) - - elif 'Missing meta description' in issue.get('message', ''): - recommendations.append({ - 'priority': 'HIGH', - 'category': 'SEO', - 'title': 'Add Meta Descriptions', - 'description': f"Write compelling meta descriptions for {issue.get('count', 'multiple')} pages", - 'implementation': """ - - - Keep between 150-160 characters - - Include a call-to-action - - Use active voice - - Include target keywords naturally - """.strip(), - 'impact': 'Improves click-through rates from search results', - 'effort': 'Medium', - 'affected_pages': issue.get('count', 0) - }) - - elif 'Missing H1' in issue.get('message', ''): - recommendations.append({ - 'priority': 'HIGH', - 'category': 'Content', - 'title': 'Add H1 Headings', - 'description': f"Add single, descriptive H1 tags to {issue.get('count', 'multiple')} pages", - 'implementation': """ -

Main Page Heading

- - Use only one H1 per page - - Include primary keyword - - Make it descriptive and unique - - Keep it under 70 characters - """.strip(), - 'impact': 'Essential for content hierarchy and SEO', - 'effort': 'Low', - 'affected_pages': issue.get('count', 0) - }) - - # Priority 2: Mobile and Technical issues - technical_issues = [i for i in issues if i.get('category') == 'Technical'] - - for issue in technical_issues[:2]: - if 'viewport' in issue.get('message', '').lower(): - recommendations.append({ - 'priority': 'HIGH', - 'category': 'Technical', - 'title': 'Make Site Mobile-Friendly', - 'description': f"Add viewport meta tag to {issue.get('count', 'all')} pages", - 'implementation': """ - - - Add to the section of all pages - - Essential for mobile responsiveness - - Required for mobile-first indexing - """.strip(), - 'impact': 'Critical for mobile users and Google rankings', - 'effort': 'Low', - 'affected_pages': issue.get('count', 0) - }) - - elif 'HTTPS' in issue.get('message', ''): - recommendations.append({ - 'priority': 'HIGH', - 'category': 'Technical', - 'title': 'Enable HTTPS', - 'description': 'Secure your website with SSL certificate', - 'implementation': """ - 1. Obtain SSL certificate (Let's Encrypt for free) - 2. Install certificate on server - 3. Update all internal links to HTTPS - 4. Set up 301 redirects from HTTP to HTTPS - 5. Update sitemap and robots.txt - """.strip(), - 'impact': 'Required for security and SEO rankings', - 'effort': 'Medium', - 'affected_pages': issue.get('count', 0) - }) - - # Priority 3: Performance issues - if 'performance' in report: - perf_data = report['performance'] - if perf_data.get('average_load_time', 0) > 3: - recommendations.append({ - 'priority': 'MEDIUM', - 'category': 'Performance', - 'title': 'Improve Page Load Speed', - 'description': f"Average load time is {perf_data.get('average_load_time', 0):.1f}s (target <3s)", - 'implementation': """ - 1. Enable gzip compression - 2. Optimize and compress images - 3. Minify CSS and JavaScript - 4. Enable browser caching - 5. Use a Content Delivery Network (CDN) - 6. Implement lazy loading for images - """.strip(), - 'impact': 'Improves user experience and SEO rankings', - 'effort': 'High', - 'affected_pages': report.get('summary', {}).get('total_pages', 0) - }) - - # Priority 4: Structured Data - structured_data_missing = [i for i in issues if 'structured data' in i.get('message', '').lower()] - if structured_data_missing: - issue = structured_data_missing[0] - recommendations.append({ - 'priority': 'MEDIUM', - 'category': 'SEO', - 'title': 'Implement Structured Data', - 'description': f"Add JSON-LD structured data to {issue.get('count', 'multiple')} pages", - 'implementation': """ - - - Add appropriate schema types (Article, Product, etc.) - - Validate with Google's Rich Results Test - """.strip(), - 'impact': 'Enables rich snippets in search results', - 'effort': 'Medium', - 'affected_pages': issue.get('count', 0) - }) - - # Priority 5: Content improvements - content_issues = [i for i in issues if i.get('category') == 'Content'] - word_count_issues = [i for i in content_issues if 'word count' in i.get('message', '').lower()] - - if word_count_issues: - issue = word_count_issues[0] + for issue in issues: + recommendation = issue.get('fix') or issue.get('message', 'Review the recorded evidence.') + if issue.get('rule_version') == RULESET_VERSION: + try: + recommendation = get_rule(issue['rule_id']).recommendation + except ValueError: + pass # An imported archive may contain a rule unavailable in this installation. recommendations.append({ - 'priority': 'LOW', - 'category': 'Content', - 'title': 'Expand Thin Content', - 'description': f"Increase content length on {issue.get('count', 'multiple')} pages", - 'implementation': """ - - Target minimum 300 words per page - - Add valuable, relevant information - - Include related keywords naturally - - Break content into scannable sections - - Add supporting images and media - """.strip(), - 'impact': 'Improves content quality and rankings', - 'effort': 'High', - 'affected_pages': issue.get('count', 0) + 'rule_id': issue.get('rule_id'), + 'priority': {'critical': 'HIGH', 'warning': 'MEDIUM', 'notice': 'LOW'}.get(issue.get('severity'), 'LOW'), + 'category': issue.get('category', 'General'), 'title': issue.get('message', 'Review finding'), + 'description': recommendation, + 'implementation': recommendation, + 'references': issue.get('references', []), 'reviewed_on': issue.get('reviewed_on'), + 'applicability': issue.get('rule_applicability'), + 'effort': issue.get('effort', 'Unknown'), + 'impact': issue.get('impact', 'Review the evidence and applicability for your site.'), + 'affected_pages': issue.get('pages_affected', issue.get('count', 0)), + 'example_pages': issue.get('example_pages', []), }) - - # Sort by priority - priority_order = {'HIGH': 0, 'MEDIUM': 1, 'LOW': 2} - recommendations.sort(key=lambda x: priority_order.get(x.get('priority', 'LOW'), 3)) - - return recommendations[:10] # Return top 10 recommendations + return recommendations -def create_executive_summary(report: Dict[str, Any]) -> Dict[str, Any]: - """Create an executive summary for the report.""" - summary = { - 'overview': {}, - 'key_metrics': {}, - 'top_issues': [], - 'quick_wins': [], - 'action_items': [] - } - - # Overview - summary['overview'] = { - 'total_pages_analyzed': report.get('summary', {}).get('total_pages', 0), - 'successful_pages': report.get('summary', {}).get('successful_pages', 0), - 'failed_pages': report.get('summary', {}).get('failed_pages', 0), - 'overall_health': 'Good' if report.get('overall_score', 0) >= 80 else - 'Average' if report.get('overall_score', 0) >= 60 else 'Poor', - 'overall_score': report.get('overall_score', 0) +def create_executive_summary(report: Dict[str, Any]) -> Dict: + scores = report.get('scores', {}) + overall = scores.get('overall', report.get('overall_score')) + categories = scores.get('categories', report.get('category_scores', {})) + counts = report.get('issues', {}).get('counts', {}) if isinstance(report.get('issues'), dict) else report.get('issue_counts', {}) + summary = report.get('summary', {}) + specific = report.get('recommendations', {}).get('specific', []) + health = 'Unknown' if overall is None else 'Good' if overall >= 80 else 'Average' if overall >= 60 else 'Poor' + return { + 'overview': {'total_pages_analyzed': summary.get('total_pages', 0), + 'successful_pages': summary.get('successful_pages', 0), + 'partial_pages': summary.get('partial_pages', 0), + 'failed_pages': summary.get('failed_pages', 0), + 'overall_health': health, 'overall_score': overall, + 'assessment_source': 'static_rule_heuristics'}, + 'key_metrics': {**{name + '_score': categories.get(name) for name in + ('seo', 'content', 'technical', 'performance', 'links')}, + 'critical_issues': counts.get('critical', 0), 'total_issues': counts.get('total', 0)}, + 'top_issues': report.get('issues', {}).get('top_issues', []) if isinstance(report.get('issues'), dict) else [], + 'quick_wins': [item for item in specific if item.get('effort') == 'Low' and item['priority'] == 'HIGH'][:3], + 'action_items': [item['description'] for item in specific[:5]], } - - # Key metrics - summary['key_metrics'] = { - 'seo_score': report.get('category_scores', {}).get('seo', 0), - 'content_score': report.get('category_scores', {}).get('content', 0), - 'technical_score': report.get('category_scores', {}).get('technical', 0), - 'performance_score': report.get('category_scores', {}).get('performance', 0), - 'links_score': report.get('category_scores', {}).get('links', 0), - 'critical_issues': report.get('issue_counts', {}).get('critical', 0), - 'total_issues': report.get('issue_counts', {}).get('total', 0) - } - - # Top issues (from aggregated data) - if 'aggregated_issues' in report: - summary['top_issues'] = report['aggregated_issues'][:5] - elif 'top_issues' in report: - summary['top_issues'] = report['top_issues'][:5] - - # Quick wins (low effort, high impact) - if 'enhanced_recommendations' in report: - quick_wins = [r for r in report['enhanced_recommendations'] - if r.get('effort') == 'Low' and r.get('priority') == 'HIGH'] - summary['quick_wins'] = quick_wins[:3] - - # Action items - summary['action_items'] = [ - 'Fix all critical issues immediately', - 'Implement mobile-friendly design', - 'Add missing SEO elements (titles, descriptions, H1s)', - 'Improve page load speed', - 'Add structured data markup' - ] - - return summary -def generate_performance_metrics(pages: List[Dict[str, Any]]) -> Dict[str, Any]: - """Generate detailed performance metrics from page data.""" - metrics = { - 'load_times': [], - 'resource_counts': [], - 'status_codes': Counter(), - 'content_sizes': [], - 'issues_per_page': [], - 'scores_per_page': [] - } - +def _number(value): + return type(value) in (int, float) and math.isfinite(value) + + +def generate_performance_metrics(pages: List[Dict[str, Any]]) -> Dict: + metrics = {'load_times': [], 'status_codes': dict(Counter(page.get('status_code') or 0 for page in pages)), + 'content_sizes': [], 'issues_per_page': [], 'scores_per_page': [], + 'measurement_source': 'http_fetch', 'browser_metrics_status': 'not_measured'} for page in pages: - if 'error' not in page: - # Load times - if 'load_time' in page: - metrics['load_times'].append({ - 'url': page.get('url', ''), - 'time': page.get('load_time', 0) - }) - - # Status codes - metrics['status_codes'][page.get('status_code', 0)] += 1 - - # Scores - if 'overall_score' in page: - metrics['scores_per_page'].append({ - 'url': page.get('url', ''), - 'score': page.get('overall_score', 0) - }) - - # Issues - if 'issues' in page: - metrics['issues_per_page'].append({ - 'url': page.get('url', ''), - 'count': len(page['issues']) - }) - - # Calculate aggregates - if metrics['load_times']: - times = [t['time'] for t in metrics['load_times']] - metrics['load_time_stats'] = { - 'average': sum(times) / len(times), - 'min': min(times), - 'max': max(times), - 'median': sorted(times)[len(times)//2] - } - - if metrics['scores_per_page']: - scores = [s['score'] for s in metrics['scores_per_page']] - metrics['score_stats'] = { - 'average': sum(scores) / len(scores), - 'min': min(scores), - 'max': max(scores), - 'median': sorted(scores)[len(scores)//2] - } - - # Identify problem pages - metrics['slowest_pages'] = sorted(metrics['load_times'], - key=lambda x: x['time'], - reverse=True)[:10] - metrics['lowest_scoring_pages'] = sorted(metrics['scores_per_page'], - key=lambda x: x['score'])[:10] - + url = page.get('url', '') + if _number(page.get('load_time')): + metrics['load_times'].append({'url': url, 'time': page['load_time']}) + if _number(page.get('content_length')): + metrics['content_sizes'].append({'url': url, 'bytes': page['content_length']}) + if _number(page.get('overall_score')): + metrics['scores_per_page'].append({'url': url, 'score': page['overall_score']}) + if not page.get('error'): + metrics['issues_per_page'].append({'url': url, 'count': len(page.get('issues', []))}) + for source, field, target in (('load_times', 'time', 'load_time_stats'), ('scores_per_page', 'score', 'score_stats')): + values = [item[field] for item in metrics[source]] + if values: + metrics[target] = {'average': mean(values), 'median': median(values), 'min': min(values), 'max': max(values)} + metrics['slowest_pages'] = sorted(metrics['load_times'], key=lambda item: item['time'], reverse=True)[:10] + metrics['lowest_scoring_pages'] = sorted(metrics['scores_per_page'], key=lambda item: item['score'])[:10] return metrics diff --git a/tfq0seo/exporters/base.py b/tfq0seo/exporters/base.py index b08b895..e6a229e 100644 --- a/tfq0seo/exporters/base.py +++ b/tfq0seo/exporters/base.py @@ -1,565 +1,415 @@ -"""Export manager for various output formats - simple and direct implementation.""" +"""Export analysis results through a shared, presentation-only adapter.""" -import json import csv -import os -from pathlib import Path -from typing import Dict, List, Any, Optional +import json +import math +import re +from string import Formatter from datetime import datetime +from pathlib import Path +from typing import Any, Dict, List, Optional +from urllib.parse import urlsplit -try: - import pandas as pd - PANDAS_AVAILABLE = True -except ImportError: - PANDAS_AVAILABLE = False +from jinja2 import Environment, FileSystemLoader, TemplateNotFound, select_autoescape +from ..core.report_contracts import validate_report try: from openpyxl import Workbook - from openpyxl.styles import Font, PatternFill, Alignment + from openpyxl.styles import Font, PatternFill OPENPYXL_AVAILABLE = True except ImportError: OPENPYXL_AVAILABLE = False -from jinja2 import Template, FileSystemLoader, Environment - class ExportManager: - """Manages export of analysis results to various formats.""" - + """Manages JSON, CSV, Excel and HTML exports without changing source results.""" + + ANALYZERS = ('seo', 'content', 'technical', 'performance', 'links') + def __init__(self, config: Optional[Any] = None): - """Initialize export manager with configuration.""" - # Handle both dict and dataclass config objects - if hasattr(config, '__dict__'): - # It's a dataclass or object, convert to dict - self.config = config.__dict__ if config else {} - else: - # It's already a dict or None - self.config = config or {} - + self.config = dict(vars(config) if hasattr(config, '__dict__') else config or {}) self.output_dir = Path(self.config.get('output_directory', './reports')) self.output_dir.mkdir(parents=True, exist_ok=True) - - # Setup Jinja2 for HTML templates template_dir = Path(__file__).parent.parent / 'templates' - self.jinja_env = Environment(loader=FileSystemLoader(str(template_dir))) - + self.jinja_env = Environment( + loader=FileSystemLoader(str(template_dir)), + autoescape=select_autoescape(['html', 'xml'], default_for_string=True), + ) + self.jinja_env.filters.update(number=self._display_number, score_color=self._score_color, + safe_url=self._safe_url, json_text=self._json_text) + self.jinja_env.policies['json.dumps_kwargs'] = {'default': str, 'sort_keys': False} + + @staticmethod + def _number(value): + if isinstance(value, (int, float)) and not isinstance(value, bool): + try: + return value if math.isfinite(value) else None + except OverflowError: + pass + return None + + @classmethod + def _display_number(cls, value, digits=0, suffix=''): + number = cls._number(value) + if number is None: + return 'Not measured' + return (str(round(number)) if digits == 0 else f'{number:.{digits}f}') + suffix + + @classmethod + def _score_color(cls, value): + number = cls._number(value) + if number is None: + return 'var(--color-gray, #666)' + return 'var(--color-pass)' if number >= 80 else 'var(--color-average)' if number >= 50 else 'var(--color-fail)' + + @staticmethod + def _safe_url(value): + """Only allow complete HTTP(S) destinations in clickable report links.""" + if not isinstance(value, str) or any(ord(char) < 32 for char in value): + return '' + try: + parsed = urlsplit(value) + if parsed.scheme.lower() in ('http', 'https') and parsed.hostname: + return value + except ValueError: + pass + return '' + + @staticmethod + def _json_text(value): + """Return plain JSON text for autoescaped HTML evidence, never trusted markup.""" + return json.dumps(value, indent=2, ensure_ascii=False, default=str) + + @staticmethod + def _cell(value): + """Keep cells scalar and prevent untrusted strings becoming formulas.""" + if value is None or isinstance(value, (bool, int, float)): + return value + if not isinstance(value, str): + value = json.dumps(value, ensure_ascii=False, default=str) + value = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f]', '', value) + if value.lstrip().startswith(('=', '+', '-', '@')) or value.startswith(('\t', '\r', '\n')): + value = "'" + value + return value + + @staticmethod + def _records(value): + return [item for item in value if isinstance(item, dict)] if isinstance(value, list) else [] + + @classmethod + def _page_records(cls, data): + pages = data.get('pages') + if isinstance(pages, dict): + records = cls._records(pages.get('detailed')) or cls._records(pages.get('summary')) + return records + cls._records(pages.get('failed')) + cls._records(pages.get('skipped')) + if isinstance(pages, list): + return cls._records(pages) + return [data] + + @staticmethod + def _recommendation_text(rec): + if isinstance(rec, dict): + return str(rec.get('recommendation') or rec.get('description') or rec.get('title') or '') + return str(rec) + + @classmethod + def _recommendations(cls, data): + recs = data.get('recommendations', []) + if isinstance(recs, dict): + recs = recs.get('specific', []) + return recs if isinstance(recs, list) else [] + + @classmethod + def _scores(cls, data): + scores = data.get('scores', {}) + overall = cls._number(scores.get('overall', data.get('overall_score'))) + categories = scores.get('categories', data.get('category_scores')) + if not isinstance(categories, dict): + categories = {name: data.get(name, {}).get('score') for name in cls.ANALYZERS} + return overall, {name: cls._number(value) for name, value in categories.items()} + + @classmethod + def _issues(cls, data): + issues = data.get('issues', []) + if isinstance(issues, dict): + issues = issues.get('aggregated', issues.get('top_issues', [])) + issues = cls._records(issues) + return sorted(issues, key=lambda issue: {'critical': 0, 'warning': 1, 'notice': 2}.get(issue.get('severity'), 3)) + + @classmethod + def _issue_counts(cls, data, issues=None): + issues = cls._issues(data) if issues is None else issues + counts = {severity: sum(issue.get('severity') == severity for issue in issues) + for severity in ('critical', 'warning', 'notice')} + counts.update(total=len(issues), unique=len(issues)) + issue_data = data.get('issues') + supplied = issue_data.get('counts', {}) if isinstance(issue_data, dict) else data.get('issue_counts', {}) + counts.update({key: value for key, value in supplied.items() if cls._number(value) is not None}) + return counts + def export(self, data: Dict[str, Any], format: str, output_path: Optional[str] = None) -> str: - """Export data to specified format.""" + if format not in ('json', 'csv', 'xlsx', 'html'): + raise ValueError(f'Unsupported export format: {format}') + validate_report(data) + timestamp = datetime.now().strftime('%Y%m%d_%H%M%S_%f') if output_path: output_file = Path(output_path) else: - timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') - filename = f"seo_report_{timestamp}.{format}" + pattern = self.config.get('filename_pattern', '{domain}_{timestamp}_{format}') + for _, field, spec, conversion in Formatter().parse(pattern): + if field is not None and (field not in ('domain', 'timestamp', 'format') or spec or conversion): + raise ValueError('filename_pattern supports only {domain}, {timestamp}, and {format}') + records = self._page_records(data) + try: + domain = urlsplit(records[0].get('url', '')).hostname if records else None + except ValueError: + domain = None + domain = re.sub(r'[^A-Za-z0-9.-]', '_', domain or 'site')[:120] + filename = pattern.format(domain=domain, timestamp=timestamp, format=format) + device_name = filename.split('.')[0].rstrip(' ').upper() + reserved = device_name in {'CON', 'PRN', 'AUX', 'NUL', 'CONIN$', 'CONOUT$'} or re.fullmatch( + r'(?:COM|LPT)[1-9¹²³]', device_name) + if (not filename or filename in ('.', '..') or Path(filename).name != filename + or re.search(r'[<>:"/\\|?*\x00-\x1f]', filename) or reserved): + raise ValueError('filename_pattern must produce a portable filename without directories or reserved names') + if not filename.endswith('.' + format): + filename += '.' + format output_file = self.output_dir / filename - - # Ensure parent directory exists output_file.parent.mkdir(parents=True, exist_ok=True) - - if format == 'json': - return self.export_json(data, output_file) - elif format == 'csv': - return self.export_csv(data, output_file) - elif format == 'xlsx': - return self.export_xlsx(data, output_file) - elif format == 'html': - return self.export_html(data, output_file) - else: - raise ValueError(f"Unsupported export format: {format}") - + return getattr(self, f'export_{format}')(data, output_file) + def export_json(self, data: Dict[str, Any], output_file: Path) -> str: - """Export data as JSON.""" - with open(output_file, 'w', encoding='utf-8') as f: - json.dump(data, f, indent=2, default=str, ensure_ascii=False) + validate_report(data) + serialized = json.dumps(data, indent=2, default=str, ensure_ascii=False, allow_nan=False) + with open(output_file, 'w', encoding='utf-8') as stream: + stream.write(serialized) return str(output_file) - + def export_csv(self, data: Dict[str, Any], output_file: Path) -> str: - """Export data as CSV.""" - # Flatten the data for CSV export - rows = [] - - if 'pages' in data: - # Multi-page report - for page in data['pages']: - row = self._flatten_page_data(page) - rows.append(row) - else: - # Single page report - row = self._flatten_page_data(data) - rows.append(row) - - if not rows: - rows = [{'error': 'No data to export'}] - - # Write CSV - fieldnames = set() - for row in rows: - fieldnames.update(row.keys()) - fieldnames = sorted(list(fieldnames)) - - with open(output_file, 'w', newline='', encoding='utf-8') as f: - writer = csv.DictWriter(f, fieldnames=fieldnames) + validate_report(data) + rows = [self._flatten_page_data(page) for page in self._page_records(data)] + rows = rows or [{'error': 'No data to export'}] + fieldnames = sorted({key for row in rows for key in row}) + with open(output_file, 'w', newline='', encoding='utf-8') as stream: + writer = csv.DictWriter(stream, fieldnames=fieldnames) writer.writeheader() - writer.writerows(rows) - + writer.writerows({key: self._cell(value) for key, value in row.items()} for row in rows) return str(output_file) - + + def _flatten_page_data(self, page_data: Dict[str, Any]) -> Dict[str, Any]: + flat = {key: page_data.get(key) for key in ('url', 'status_code', 'load_time', 'error', 'status')} + flat['overall_score'] = self._number(page_data.get('overall_score', page_data.get('score'))) + for name in self.ANALYZERS: + analyzer = page_data.get(name, {}) + flat[f'{name}_score'] = self._number(analyzer.get('score')) + flat[f'{name}_error'] = analyzer.get('error') + counts = page_data.get('issue_counts', page_data.get('issues', {})) + if isinstance(counts, dict): + flat.update({f'issues_{key}': value for key, value in counts.items()}) + seo_data = page_data.get('seo', {}).get('data', {}) + for key in ('title', 'description'): + value = seo_data.get(key, '') + flat[key] = value.get('text', '') if isinstance(value, dict) else value + content = page_data.get('content', {}).get('data', {}) + flat['word_count'] = content.get('metrics', {}).get('word_count', content.get('word_count')) + flat['flesch_reading_ease'] = content.get('readability', {}).get('flesch_reading_ease', content.get('flesch_reading_ease')) + performance = page_data.get('performance', {}).get('data', {}) + for key in ('total_resources', 'content_size_mb'): + flat[key] = performance.get(key, performance.get('metrics', {}).get(key)) + site = page_data.get('site_analysis', {}) + for key in ('canonical_targets', 'canonical_status', 'canonical_terminal', 'canonical_hops', + 'canonical_cycle_id', 'incoming_links', 'outgoing_links', 'nofollow_links', + 'link_depth', 'reachable', 'component'): + if key in site: + flat[key] = site[key] + return flat + def export_xlsx(self, data: Dict[str, Any], output_file: Path) -> str: - """Export data as Excel file.""" + validate_report(data) if not OPENPYXL_AVAILABLE: - # Fallback to CSV if openpyxl not available - output_file = output_file.with_suffix('.csv') - return self.export_csv(data, output_file) - - wb = Workbook() - - # Summary sheet - summary_sheet = wb.active - summary_sheet.title = "Summary" - self._write_summary_sheet(summary_sheet, data) - - # Issues sheet - if 'issues' in data or ('pages' in data and data['pages']): - issues_sheet = wb.create_sheet("Issues") - self._write_issues_sheet(issues_sheet, data) - - # Pages sheet (if multi-page report) - if 'pages' in data: - pages_sheet = wb.create_sheet("Pages") - self._write_pages_sheet(pages_sheet, data['pages']) - - # Recommendations sheet - if 'recommendations' in data: - rec_sheet = wb.create_sheet("Recommendations") - self._write_recommendations_sheet(rec_sheet, data['recommendations']) - - wb.save(output_file) + return self.export_csv(data, output_file.with_suffix('.csv')) + workbook = Workbook() + summary = workbook.active + summary.title = 'Summary' + self._write_summary_sheet(summary, data) + self._write_issues_sheet(workbook.create_sheet('Issues'), data) + self._write_pages_sheet(workbook.create_sheet('Pages'), self._page_records(data)) + self._write_recommendations_sheet(workbook.create_sheet('Recommendations'), self._recommendations(data)) + workbook.save(output_file) return str(output_file) - + + def _append_row(self, sheet, values): + sheet.append([self._cell(value) for value in values]) + + @staticmethod + def _style_header(sheet): + for cell in sheet[1]: + cell.font = Font(bold=True) + cell.fill = PatternFill(start_color='CCCCCC', end_color='CCCCCC', fill_type='solid') + sheet.freeze_panes = 'A2' + + def _write_summary_sheet(self, sheet, data): + overall, categories = self._scores(data) + self._append_row(sheet, ['SEO Analysis Report']) + self._append_row(sheet, []) + self._append_row(sheet, ['Overall Score', overall if overall is not None else 'Not measured']) + self._append_row(sheet, ['Assessment', data.get('status', '')]) + for name, score in categories.items(): + self._append_row(sheet, [name.title(), score if score is not None else 'Not measured']) + counts = self._issue_counts(data) + for severity in ('critical', 'warning', 'notice', 'total'): + self._append_row(sheet, [severity.title() + ' Issues', counts[severity]]) + if data.get('error'): + self._append_row(sheet, ['Error', data['error']]) + self._style_header(sheet) + sheet.column_dimensions['A'].width = 24 + sheet.column_dimensions['B'].width = 30 + + def _write_issues_sheet(self, sheet, data): + self._append_row(sheet, ['Severity', 'Category', 'Message', 'URL', 'Occurrences', 'Affected Pages']) + issues = self._issues(data) + if not issues and 'pages' in data: + issues = [dict(issue, url=page.get('url')) for page in self._page_records(data) for issue in self._issues(page)] + for issue in issues: + self._append_row(sheet, [issue.get('severity'), issue.get('category'), issue.get('message'), + issue.get('url', data.get('url')), issue.get('count', 1), + issue.get('pages', issue.get('pages_affected'))]) + self._style_header(sheet) + + def _write_pages_sheet(self, sheet, pages: List[Dict[str, Any]]): + rows = [self._flatten_page_data(page) for page in pages] + keys = ['url', 'overall_score', 'status_code', 'load_time'] + keys += sorted({key for row in rows for key in row} - set(keys)) + self._append_row(sheet, [key.replace('_', ' ').title() for key in keys]) + for row in rows: + self._append_row(sheet, [row.get(key) for key in keys]) + self._style_header(sheet) + + def _write_recommendations_sheet(self, sheet, recommendations): + if isinstance(recommendations, dict): + recommendations = recommendations.get('specific', []) + self._append_row(sheet, ['Recommendation', 'Priority', 'Category', 'Impact', 'Effort']) + for rec in recommendations: + metadata = rec if isinstance(rec, dict) else {} + self._append_row(sheet, [self._recommendation_text(rec)] + [metadata.get(key) for key in ('priority', 'category', 'impact', 'effort')]) + self._style_header(sheet) + def export_html(self, data: Dict[str, Any], output_file: Path) -> str: - """Export data as HTML report.""" - # Select template based on data characteristics - template_name = 'report.html' - - # Use optimized template if we have aggregated data or multiple pages - if ('aggregated_issues' in data or 'executive_summary' in data or - 'enhanced_recommendations' in data or - (data.get('summary', {}).get('total_pages', 0) > 1)): - template_name = 'optimized_report.html' - elif self.config.get('html_template') == 'enhanced': - template_name = 'enhanced_report.html' - + validate_report(data) + requested = self.config.get('html_template') + template_names = {'report': 'report.html', 'enhanced': 'enhanced_report.html', 'optimized': 'optimized_report.html'} + if requested is not None and requested not in template_names: + raise ValueError(f'Unsupported HTML template: {requested}') + default = 'optimized' if 'pages' in data or 'aggregated_issues' in data else 'report' try: - template = self.jinja_env.get_template(template_name) - except: - # If template not found, try alternative or use basic + template = self.jinja_env.get_template(template_names[requested or default]) + except TemplateNotFound: try: template = self.jinja_env.get_template('report.html') - except: - template = Template(self._get_basic_html_template()) - - # Prepare data for template - template_data = self._prepare_html_data(data) - - # Render HTML - html_content = template.render(**template_data) - - # Write to file - with open(output_file, 'w', encoding='utf-8') as f: - f.write(html_content) - + except TemplateNotFound: + template = self.jinja_env.from_string(self._get_basic_html_template()) + html = template.render(**self._prepare_html_data(data)) + with open(output_file, 'w', encoding='utf-8') as stream: + stream.write(html) return str(output_file) - - def _flatten_page_data(self, page_data: Dict[str, Any]) -> Dict[str, Any]: - """Flatten nested page data for CSV export.""" - flat = { - 'url': page_data.get('url', ''), - 'overall_score': page_data.get('overall_score', 0), - 'status_code': page_data.get('status_code', 0), - 'load_time': page_data.get('load_time', 0), - } - - # Add scores from each analyzer - for analyzer in ['seo', 'content', 'technical', 'performance', 'links']: - if analyzer in page_data: - flat[f'{analyzer}_score'] = page_data[analyzer].get('score', 0) - - # Add issue counts - if 'issue_counts' in page_data: - flat.update({f'issues_{k}': v for k, v in page_data['issue_counts'].items()}) - - # Add some key data points - if 'seo' in page_data and 'data' in page_data['seo']: - seo_data = page_data['seo']['data'] - flat['title'] = seo_data.get('title', '')[:100] - flat['description'] = seo_data.get('description', '')[:160] - - if 'content' in page_data and 'data' in page_data['content']: - content_data = page_data['content']['data'] - flat['word_count'] = content_data.get('word_count', 0) - flat['flesch_reading_ease'] = content_data.get('flesch_reading_ease', 0) - - if 'performance' in page_data and 'data' in page_data['performance']: - perf_data = page_data['performance']['data'] - flat['total_resources'] = perf_data.get('total_resources', 0) - flat['content_size_mb'] = perf_data.get('content_size_mb', 0) - - return flat - - def _write_summary_sheet(self, sheet, data: Dict[str, Any]): - """Write summary data to Excel sheet.""" - # Title - sheet['A1'] = 'SEO Analysis Report' - sheet['A1'].font = Font(size=16, bold=True) - - row = 3 - - # Overall score - sheet[f'A{row}'] = 'Overall Score' - sheet[f'B{row}'] = data.get('overall_score', 0) - sheet[f'B{row}'].font = Font(bold=True, color='00FF00' if data.get('overall_score', 0) >= 80 else 'FF0000') - row += 1 - - # Category scores - if 'category_scores' in data: - sheet[f'A{row}'] = 'Category Scores' - sheet[f'A{row}'].font = Font(bold=True) - row += 1 - - for category, score in data['category_scores'].items(): - sheet[f'A{row}'] = category.title() - sheet[f'B{row}'] = score - row += 1 - - row += 1 - - # Issue counts - if 'issue_counts' in data: - sheet[f'A{row}'] = 'Issue Summary' - sheet[f'A{row}'].font = Font(bold=True) - row += 1 - - sheet[f'A{row}'] = 'Critical' - sheet[f'B{row}'] = data['issue_counts'].get('critical', 0) - sheet[f'B{row}'].font = Font(color='FF0000') - row += 1 - - sheet[f'A{row}'] = 'Warnings' - sheet[f'B{row}'] = data['issue_counts'].get('warning', 0) - sheet[f'B{row}'].font = Font(color='FFA500') - row += 1 - - sheet[f'A{row}'] = 'Notices' - sheet[f'B{row}'] = data['issue_counts'].get('notice', 0) - sheet[f'B{row}'].font = Font(color='0000FF') - row += 1 - - # Auto-adjust column widths - for column in sheet.columns: - max_length = 0 - column_letter = column[0].column_letter - for cell in column: - try: - if len(str(cell.value)) > max_length: - max_length = len(str(cell.value)) - except: - pass - adjusted_width = min(max_length + 2, 50) - sheet.column_dimensions[column_letter].width = adjusted_width - - def _write_issues_sheet(self, sheet, data: Dict[str, Any]): - """Write issues to Excel sheet.""" - # Headers - headers = ['Severity', 'Category', 'Message', 'URL'] - for col, header in enumerate(headers, 1): - cell = sheet.cell(row=1, column=col, value=header) - cell.font = Font(bold=True) - cell.fill = PatternFill(start_color='CCCCCC', end_color='CCCCCC', fill_type='solid') - - # Collect all issues - all_issues = [] - if 'issues' in data: - for issue in data['issues']: - all_issues.append({ - 'severity': issue.get('severity', ''), - 'category': issue.get('category', ''), - 'message': issue.get('message', ''), - 'url': data.get('url', '') - }) - elif 'pages' in data: - for page in data['pages']: - if 'issues' in page: - for issue in page['issues']: - all_issues.append({ - 'severity': issue.get('severity', ''), - 'category': issue.get('category', ''), - 'message': issue.get('message', ''), - 'url': page.get('url', '') - }) - - # Sort by severity - severity_order = {'critical': 0, 'warning': 1, 'notice': 2} - all_issues.sort(key=lambda x: severity_order.get(x['severity'], 3)) - - # Write issues - for row_num, issue in enumerate(all_issues, 2): - sheet.cell(row=row_num, column=1, value=issue['severity']) - sheet.cell(row=row_num, column=2, value=issue['category']) - sheet.cell(row=row_num, column=3, value=issue['message']) - sheet.cell(row=row_num, column=4, value=issue['url']) - - # Color code severity - severity_cell = sheet.cell(row=row_num, column=1) - if issue['severity'] == 'critical': - severity_cell.font = Font(color='FF0000') - elif issue['severity'] == 'warning': - severity_cell.font = Font(color='FFA500') - elif issue['severity'] == 'notice': - severity_cell.font = Font(color='0000FF') - - def _write_pages_sheet(self, sheet, pages: List[Dict[str, Any]]): - """Write pages data to Excel sheet.""" - if not pages: - return - - # Headers - headers = ['URL', 'Overall Score', 'Status', 'Load Time', 'SEO Score', - 'Content Score', 'Technical Score', 'Performance Score', 'Links Score', - 'Critical Issues', 'Warnings', 'Notices'] - - for col, header in enumerate(headers, 1): - cell = sheet.cell(row=1, column=col, value=header) - cell.font = Font(bold=True) - cell.fill = PatternFill(start_color='CCCCCC', end_color='CCCCCC', fill_type='solid') - - # Write page data - for row_num, page in enumerate(pages, 2): - sheet.cell(row=row_num, column=1, value=page.get('url', '')) - sheet.cell(row=row_num, column=2, value=page.get('overall_score', 0)) - sheet.cell(row=row_num, column=3, value=page.get('status_code', 0)) - sheet.cell(row=row_num, column=4, value=page.get('load_time', 0)) - - # Analyzer scores - col = 5 - for analyzer in ['seo', 'content', 'technical', 'performance', 'links']: - score = page.get(analyzer, {}).get('score', 0) if analyzer in page else 0 - sheet.cell(row=row_num, column=col, value=score) - col += 1 - - # Issue counts - issue_counts = page.get('issue_counts', {}) - sheet.cell(row=row_num, column=10, value=issue_counts.get('critical', 0)) - sheet.cell(row=row_num, column=11, value=issue_counts.get('warning', 0)) - sheet.cell(row=row_num, column=12, value=issue_counts.get('notice', 0)) - - def _write_recommendations_sheet(self, sheet, recommendations: List[str]): - """Write recommendations to Excel sheet.""" - sheet['A1'] = 'Recommendations' - sheet['A1'].font = Font(size=14, bold=True) - - for row_num, rec in enumerate(recommendations, 3): - sheet[f'A{row_num}'] = f'{row_num - 2}.' - sheet[f'B{row_num}'] = rec - + def _prepare_html_data(self, data: Dict[str, Any]) -> Dict[str, Any]: - """Prepare data for HTML template.""" - # Ensure all required fields exist - prepared = { - 'url': data.get('url', 'Multiple Pages'), - 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), - 'overall_score': data.get('overall_score', 0), - 'category_scores': data.get('category_scores', {}), - 'issues': data.get('issues', []), - 'issue_counts': data.get('issue_counts', {}), - 'recommendations': data.get('recommendations', []), - 'pages': data.get('pages', []), + overall, categories = self._scores(data) + issues = self._issues(data) + issue_data = data.get('issues', {}) if isinstance(data.get('issues'), dict) else {} + counts = self._issue_counts(data, issues) + recs = self._recommendations(data) + recommendations = data.get('recommendations', {}) if isinstance(data.get('recommendations'), dict) else {} + pages = self._page_records(data) + summaries = [] + for page in pages: + count_data = page.get('issue_counts', page.get('issues', {})) + issue_count = count_data.get('total', 0) if isinstance(count_data, dict) else len(count_data) + summaries.append({'url': str(page.get('url', '')), 'score': self._number(page.get('overall_score', page.get('score'))), + 'status_code': page.get('status_code'), 'load_time': self._number(page.get('load_time')), + 'issue_count': issue_count, 'error': page.get('error'), 'status': page.get('status')}) + summary = data.get('summary', {}) + executive_defaults = { + 'overview': {'total_pages_analyzed': summary.get('total_pages', len(pages)), + 'successful_pages': summary.get('successful_pages', sum(not page.get('error') for page in pages)), + 'overall_health': 'Not measured' if overall is None else 'Good' if overall >= 80 else 'Needs improvement'}, + 'key_metrics': {'critical_issues': counts['critical']}, 'quick_wins': [], } - - # Handle nested structures from new report format - # Check for scores nested structure - if 'scores' in data: - prepared['overall_score'] = data['scores'].get('overall', 0) - prepared['category_scores'] = data['scores'].get('categories', {}) - - # Check for issues nested structure - if 'issues' in data and isinstance(data['issues'], dict): - if 'counts' in data['issues']: - prepared['issue_counts'] = data['issues']['counts'] - - # Ensure scores exist - if not prepared['category_scores']: - prepared['category_scores'] = { - 'seo': 0, - 'content': 0, - 'technical': 0, - 'performance': 0, - 'links': 0 - } - - # Add new optimized data fields with defaults - if 'aggregated_issues' in data: - prepared['aggregated_issues'] = data['aggregated_issues'] - else: - prepared['aggregated_issues'] = [] - - if 'aggregation_stats' in data: - prepared['aggregation_stats'] = data['aggregation_stats'] - else: - prepared['aggregation_stats'] = {} - - # Handle recommendations - check for new format - if 'recommendations' in data and isinstance(data['recommendations'], dict): - if 'specific' in data['recommendations']: - prepared['enhanced_recommendations'] = data['recommendations']['specific'] - if 'executive' in data['recommendations']: - prepared['executive_summary'] = data['recommendations']['executive'] - else: - # Try direct fields - if 'enhanced_recommendations' in data: - prepared['enhanced_recommendations'] = data['enhanced_recommendations'] - else: - prepared['enhanced_recommendations'] = [] - - if 'executive_summary' in data: - prepared['executive_summary'] = data['executive_summary'] - else: - # Create a default executive summary - prepared['executive_summary'] = { - 'overview': { - 'total_pages_analyzed': data.get('summary', {}).get('total_pages', 1) if 'summary' in data else 1, - 'overall_health_score': data.get('overall_score', 0) - }, - 'key_metrics': { - 'average_score': data.get('overall_score', 0), - 'critical_issues': data.get('issue_counts', {}).get('critical', 0), - 'warnings': data.get('issue_counts', {}).get('warning', 0), - 'notices': data.get('issue_counts', {}).get('notice', 0) - }, - 'top_issues': [], - 'quick_wins': [] - } - - if 'performance_metrics' in data: - prepared['performance_metrics'] = data['performance_metrics'] - else: - prepared['performance_metrics'] = {} - - # Handle pages data - if 'pages' in data and isinstance(data['pages'], dict): - # New format with nested structure - if 'summary' in data['pages']: - prepared['pages_summary'] = data['pages']['summary'] - if 'detailed' in data['pages']: - prepared['pages'] = data['pages']['detailed'] - else: - # Old format compatibility - if 'pages_summary' in data: - prepared['pages_summary'] = data['pages_summary'] - else: - prepared['pages_summary'] = [] - - if 'pages_truncated' in data: - prepared['pages_truncated'] = data['pages_truncated'] - prepared['pages_truncated_count'] = data.get('pages_truncated_count', 0) - else: - prepared['pages_truncated'] = False - prepared['pages_truncated_count'] = 0 - - if 'top_issues' in data: - prepared['top_issues'] = data['top_issues'] - elif 'issues' in data and isinstance(data['issues'], dict) and 'top_issues' in data['issues']: - prepared['top_issues'] = data['issues']['top_issues'] - else: - prepared['top_issues'] = [] - - # Add performance data - if 'performance' in data: - prepared['performance_data'] = data['performance'] - - # Add summary if multi-page - if 'summary' in data: - prepared['summary'] = data['summary'] - - # Handle issues - check if it's a dict (new format) or list (old format) - severity_order = {'critical': 0, 'warning': 1, 'notice': 2} - - if isinstance(prepared['issues'], dict): - # New format: issues is a dict with 'aggregated' key - if 'aggregated' in prepared['issues']: - issue_list = prepared['issues']['aggregated'] - elif 'top_issues' in prepared['issues']: - issue_list = prepared['issues']['top_issues'] - else: - issue_list = [] - - # Update prepared['issues'] to be the list for template compatibility - prepared['issues'] = issue_list - else: - # Old format: issues is already a list - issue_list = prepared['issues'] - - # Sort issues by severity - if issue_list and isinstance(issue_list, list): - issue_list.sort(key=lambda x: severity_order.get(x.get('severity', 'notice'), 3)) - prepared['issues'] = issue_list - - # Group issues by severity - prepared['issues_by_severity'] = { - 'critical': [i for i in prepared['issues'] if i.get('severity') == 'critical'], - 'warning': [i for i in prepared['issues'] if i.get('severity') == 'warning'], - 'notice': [i for i in prepared['issues'] if i.get('severity') == 'notice'] + supplied_executive = recommendations.get('executive', data.get('executive_summary')) or {} + executive = {**executive_defaults, **supplied_executive} + for key in ('overview', 'key_metrics'): + executive[key] = {**executive_defaults[key], **supplied_executive.get(key, {})} + performance = dict(data.get('performance', {}).get('data', {})) + performance.update(performance.get('metrics', {})) + performance.setdefault('html_fetch_time', data.get('load_time')) + content = dict(data.get('content', {}).get('data', {})) + content.update(content.get('metrics', {})) + content.update(content.get('readability', {})) + content.setdefault('average_grade_level', content.get('consensus_grade')) + content.setdefault('image_count', content.get('image_analysis', {}).get('total_images')) + technical = dict(data.get('technical', {}).get('data', {})) + technical.setdefault('has_viewport', technical.get('mobile', {}).get('viewport_configured')) + technical.setdefault('compression', technical.get('performance', {}).get('compression')) + seo = dict(data.get('seo', {}).get('data', {})) + for key in ('title', 'description'): + if isinstance(seo.get(key), dict): + seo[key] = seo[key].get('text', '') + scoring = data.get('scoring') if isinstance(data.get('scoring'), dict) else {} + scoring_policies = [scoring] if scoring else [] + if not scoring_policies: + for page in pages: + policy = page.get('scoring') + if isinstance(policy, dict) and policy and policy not in scoring_policies: + scoring_policies.append(policy) + versions = data.get('scores', {}).get('scoring_versions', []) + scoring_versions = list(versions) if isinstance(versions, list) else [] + for policy in scoring_policies: + if policy.get('version') is not None and policy['version'] not in scoring_versions: + scoring_versions.append(policy['version']) + rule_coverage = data.get('rule_coverage') + if not isinstance(rule_coverage, dict): + coverage = data.get('coverage', {}) + rule_coverage = coverage.get('rules', {}) if isinstance(coverage, dict) else {} + if not isinstance(rule_coverage, dict): + rule_coverage = {} + enhanced_recommendations = recommendations.get('specific', data.get('enhanced_recommendations', [])) + enhanced_recommendations = [rec if isinstance(rec, dict) else {'title': rec, 'description': rec} + for rec in enhanced_recommendations] + aggregation_stats = issue_data.get('stats', data.get('aggregation_stats', {})) + if self._number(aggregation_stats.get('reduction_ratio')) is None: + aggregation_stats = {} + return { + 'data': data, + 'url': data.get('url', 'Multiple Pages'), 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), + 'error': data.get('error'), 'overall_score': overall, 'category_scores': categories, + 'report_status': data.get('status'), + 'scoring_policies': scoring_policies, 'scoring_versions': scoring_versions, + 'rule_coverage': rule_coverage, + 'score_source': data.get('scores', {}).get('source', data.get('coverage', {}).get('measurement_source')), + 'analysis_errors': [{'analyzer': name, 'error': data[name]['error']} for name in self.ANALYZERS + if isinstance(data.get(name), dict) and data[name].get('error')], + 'score_chart_values': [overall, 100 - overall] if overall is not None else [], + 'issues': issues, 'issue_counts': counts, + 'issues_by_severity': {severity: [issue for issue in issues if issue.get('severity') == severity] + for severity in ('critical', 'warning', 'notice')}, + 'recommendations': [self._recommendation_text(rec) for rec in recs], + 'enhanced_recommendations': enhanced_recommendations, + 'executive_summary': executive, + 'aggregated_issues': issue_data.get('aggregated', data.get('aggregated_issues', [])), + 'aggregation_stats': aggregation_stats, + 'performance_metrics': data.get('performance_metrics', {}), + 'pages': pages, 'pages_summary': summaries, 'pages_truncated': data.get('pages_truncated', False), + 'pages_truncated_count': data.get('pages_truncated_count', 0), 'summary': summary, + 'seo_data': seo, 'content_data': content, 'technical_data': technical, + 'performance_data': performance, } - - return prepared - + def _get_basic_html_template(self) -> str: - """Return a basic HTML template if template files are not available.""" - return ''' - - - - - SEO Analysis Report - - - -
-

SEO Analysis Report

-

URL: {{ url }}

-

Generated: {{ timestamp }}

- -

Overall Score

-
- {{ overall_score|round|int }}/100 -
- -

Issues ({{ issues|length }})

-
- {% for issue in issues %} -
- {{ issue.category }}: {{ issue.message }} -
- {% endfor %} -
- -

Recommendations

-
    - {% for rec in recommendations %} -
  1. {{ rec }}
  2. - {% endfor %} -
-
- -''' + return ''' +SEO Analysis Report

SEO Analysis Report

+

{{ url }}

Overall score: {{ overall_score|number }}

+{% if error %}

Analysis failed: {{ error }}

{% endif %} +{% for issue in issues %}

{{ issue.category }}: {{ issue.message }}

{% endfor %} +{% for rec in recommendations %}

{{ rec }}

{% endfor %} +{% for page in pages_summary %} +{% endfor %}
{{ page.url }}{{ page.score|number }}{{ page.error or '' }}
''' diff --git a/tfq0seo/page_facts.py b/tfq0seo/page_facts.py new file mode 100644 index 0000000..54e62ce --- /dev/null +++ b/tfq0seo/page_facts.py @@ -0,0 +1,298 @@ +"""Reusable snapshots of observed HTML, independent of scoring and transport.""" + +import hashlib +import math +import re +from dataclasses import dataclass, field +from types import MappingProxyType +from typing import Any, Dict, Mapping, Optional + +from bs4 import BeautifulSoup, Doctype + +FACTS_VERSION = '1.1' + + +def _freeze(value): + if isinstance(value, Mapping): + if any(not isinstance(key, str) for key in value): + raise TypeError('PageFacts mappings require string keys') + return MappingProxyType({key: _freeze(item) for key, item in value.items()}) + if isinstance(value, (list, tuple)): + return tuple(_freeze(item) for item in value) + if value is None or isinstance(value, (str, bool, int)): + return value + if isinstance(value, float) and math.isfinite(value): + return value + raise TypeError('PageFacts observations must contain finite JSON primitives') + + +def _thaw(value): + if isinstance(value, Mapping): + return {key: _thaw(item) for key, item in value.items()} + if isinstance(value, tuple): + return [_thaw(item) for item in value] + return value + + +def _headers_snapshot(headers): + if headers is None: + return None + if not isinstance(headers, Mapping): + raise TypeError('PageFacts headers must be a mapping or None') + result = {} + for name in headers: + if not isinstance(name, str): + raise TypeError('PageFacts header names must be strings') + values = headers.getall(name) if hasattr(headers, 'getall') else headers[name] + values = values if isinstance(values, (list, tuple)) else [values] + if any(not isinstance(value, str) for value in values): + raise TypeError('PageFacts header values must be strings or lists of strings') + key = name.lower() + if hasattr(headers, 'getall'): + result[key] = list(values) + else: + result.setdefault(key, []).extend(values) + return result + + +def extract_content_text(soup: BeautifulSoup, preserve_structure: bool = False, *, html: Optional[str] = None) -> str: + """Preserve the existing content extractor's exclusions without mutating input.""" + clean = BeautifulSoup(str(soup) if html is None else html, 'html.parser') + for element in clean(['script', 'style', 'noscript', 'iframe', 'svg']): + element.decompose() + for element in clean.find_all(style=re.compile(r'(display\s*:\s*none|visibility\s*:\s*hidden)', re.I)): + element.decompose() + for element in clean.find_all(attrs={'hidden': True}): + element.decompose() + if preserve_structure: + text = clean.get_text(separator='\n', strip=True) + else: + text = re.sub(r'\s+', ' ', clean.get_text(separator=' ')) + text = re.sub(r'[\r\n]+', '\n', text) + return re.sub(r'[^\S\n]+', ' ', text).strip() + + +@dataclass(frozen=True) +class PageFacts: + """A frozen snapshot; collection properties return independent JSON primitives. + + Construct snapshots with extract_page_facts. The source soup is never cached on or modified. Callers supplying this + snapshot must keep that soup unchanged while specialized DOM checks run. + """ + + url: str + base_url: str + html: str + text: str + content_text: str + language: Optional[str] + is_xml: bool + doctype: tuple + dom_size: int + user_agent: str + _source_id: int = field(repr=False) + _snapshot: Mapping[str, Any] = field(repr=False) + version: str = field(default=FACTS_VERSION, init=False) + + def __post_init__(self): + required = {'headers', 'robots', 'headings', 'meta', 'link_tags', 'images', + 'scripts', 'anchors', 'tag_counts', 'paragraphs', 'title', 'canonical'} + if not isinstance(self._snapshot, Mapping) or not required <= self._snapshot.keys(): + raise ValueError('PageFacts requires the complete snapshot produced by extract_page_facts') + if any(not isinstance(value, str) for value in + (self.url, self.base_url, self.html, self.text, self.content_text, self.user_agent)): + raise TypeError('PageFacts URL, text, and user agent fields must be strings') + if self.language is not None and not isinstance(self.language, str): + raise TypeError('PageFacts language must be a string or None') + if type(self.is_xml) is not bool or type(self.dom_size) is not int or self.dom_size < 0: + raise TypeError('PageFacts requires a parser flag and a nonnegative DOM element count') + if type(self._source_id) is not int or not isinstance(self.doctype, (list, tuple)) or any( + not isinstance(value, str) for value in self.doctype): + raise TypeError('PageFacts requires a source identity and string DOCTYPE observations') + object.__setattr__(self, 'doctype', tuple(self.doctype)) + object.__setattr__(self, '_snapshot', _freeze(self._snapshot)) + + def __deepcopy__(self, memo): + return self + + @property + def headers(self): + return _thaw(self._snapshot['headers']) + + @property + def robots(self): + return _thaw(self._snapshot['robots']) + + @property + def headings(self): + return _thaw(self._snapshot['headings']) + + @property + def meta(self): + return _thaw(self._snapshot['meta']) + + @property + def link_tags(self): + return _thaw(self._snapshot['link_tags']) + + @property + def canonical(self): + return _thaw(self._snapshot['canonical']) + + @property + def images(self): + return _thaw(self._snapshot['images']) + + @property + def scripts(self): + return _thaw(self._snapshot['scripts']) + + @property + def anchors(self): + return _thaw(self._snapshot['anchors']) + + @property + def tag_counts(self): + return _thaw(self._snapshot['tag_counts']) + + @property + def paragraphs(self): + return tuple(self._snapshot['paragraphs']) + + @property + def title(self): + return self._snapshot['title'] + + def to_dict(self, include_content: bool = False) -> Dict[str, Any]: + """Export provenance and structured observations; omit bulk text by default.""" + result = { + 'facts_version': self.version, 'url': self.url, 'base_url': self.base_url, + 'source': 'parsed_html_and_optional_response_headers', 'is_xml': self.is_xml, + 'language': self.language, 'doctype': list(self.doctype), 'dom_size': self.dom_size, + 'user_agent': self.user_agent, 'headers_observed': self._snapshot['headers'] is not None, + 'text_sha256': hashlib.sha256(self.text.encode('utf-8')).hexdigest(), + 'text_length': len(self.text), 'content_text_length': len(self.content_text), + 'html_length': len(self.html), 'content_text_method': 'markup_exclusions_and_inline_hidden_attributes', + **_thaw(self._snapshot), + } + result['header_names'] = list((result.pop('headers') or {}).keys()) + # Raw script bodies are intentionally excluded from the default report. + for script in result['scripts']: + script_text = script.pop('text') + script['text_length'] = len(script_text) + script['text_sha256'] = hashlib.sha256(script_text.encode('utf-8')).hexdigest() + result['paragraph_count'] = len(result.pop('paragraphs')) + if include_content: + result.update(html=self.html, text=self.text, content_text=self.content_text, + scripts=self.scripts, paragraphs=list(self.paragraphs)) + return result + + +def _attrs(element): + result = {} + for name, value in element.attrs.items(): + if not isinstance(name, str): + raise TypeError('HTML attribute names must be strings') + if isinstance(value, (list, tuple)) and all(isinstance(item, str) for item in value): + result[name] = list(value) + elif isinstance(value, str) or value is None: + result[name] = value + else: + raise TypeError(f'Unsupported parsed HTML attribute value at {element.name}[{name}]') + return result + + +def extract_page_facts(soup: BeautifulSoup, url: str, headers: Any = None, + user_agent: str = 'googlebot') -> PageFacts: + """Extract shared observations once per page; retain declaration order and absence.""" + from .analyzers.common import canonical_facts, document_base_url, heading_facts, parse_robots + from .urls import classify_url, resolve_url + + if not isinstance(soup, BeautifulSoup) or not isinstance(url, str) or not isinstance(user_agent, str): + raise TypeError('Page facts require BeautifulSoup and a URL string') + elements = soup.find_all(True) + attributes = [_attrs(element) for element in elements] + html = str(soup) + base_url = document_base_url(soup, url) + indexed_ids = {} + for element in elements: + if element.get('id') is not None: + indexed_ids.setdefault(str(element['id']), element) + label_text_cache, context_text_cache = {}, {} + + def label_text(identifier): + if identifier not in label_text_cache: + label_text_cache[identifier] = indexed_ids[identifier].get_text(' ', strip=True) + return label_text_cache[identifier] + + snapshot = {'headers': _headers_snapshot(headers), 'meta': [], 'link_tags': [], 'images': [], + 'scripts': [], 'anchors': [], 'tag_counts': {}, 'paragraphs': [], 'title': None} + language = None + for index, (element, attrs) in enumerate(zip(elements, attributes)): + tag = element.name + snapshot['tag_counts'][tag] = snapshot['tag_counts'].get(tag, 0) + 1 + if tag == 'html' and snapshot['tag_counts'][tag] == 1: + language = element.get('lang') + if tag == 'title' and snapshot['title'] is None: + snapshot['title'] = element.get_text().strip() + if tag == 'p': + snapshot['paragraphs'].append(element.get_text()) + if tag in ('meta', 'link', 'img', 'script'): + record = {'attrs': attrs, 'index': index} + if tag in ('meta', 'link', 'script'): + record['text'] = element.get_text() + if tag in ('script', 'link'): + record['in_head'] = element.find_parent('head') is not None + snapshot[{'meta': 'meta', 'link': 'link_tags', 'img': 'images', 'script': 'scripts'}[tag]].append(record) + if tag == 'a' and element.has_attr('href'): + text = element.get_text(' ', strip=True) + compact = element.get_text(strip=True) + labelled = ' '.join(label_text(identifier) + for identifier in str(element.get('aria-labelledby', '')).split() + if identifier in indexed_ids).strip() + parents = list(element.parents) + position = next((parent.name for parent in parents if parent.name in ('header', 'footer', 'nav', 'aside')), 'body') + context = '' + parent = element.parent + if parent and parent.name in ('p', 'div', 'li', 'td', 'article', 'section'): + if id(parent) not in context_text_cache: + context_text_cache[id(parent)] = parent.get_text(strip=True) + parent_text = context_text_cache[id(parent)] + if compact in parent_text: + start = max(0, parent_text.index(compact) - 50) + end = min(len(parent_text), parent_text.index(compact) + len(compact) + 50) + context = ('...' if start else '') + parent_text[start:end] + ('...' if end < len(parent_text) else '') + href = element.get('href', '') + snapshot['anchors'].append({ + 'attrs': attrs, 'index': index, 'text': text, 'text_compact': compact, + 'labelled_text': labelled, + 'image_alt_text': ' '.join(image.get('alt', '') for image in element.find_all('img')).strip(), + 'context': context, 'position': position, + 'parent_tags': [parent.name for parent in parents], + 'parent_roles': [parent.get('role') for parent in parents], + 'parent_classes': [str(parent.get('class', [])) for parent in parents], + 'url': resolve_url(href, base_url), 'url_kind': classify_url(href, url, base_url), + }) + snapshot['headings'] = heading_facts(soup) + snapshot['robots'] = parse_robots(soup, snapshot['headers'], user_agent) + snapshot['canonical'] = canonical_facts(snapshot['link_tags'], url, base_url, snapshot['headers']) + return PageFacts(url=url, base_url=base_url, html=html, text=soup.get_text(' ', strip=True), + content_text=extract_content_text(soup, html=html), language=language, + is_xml=bool(soup.is_xml), doctype=tuple(str(node) for node in soup.contents if isinstance(node, Doctype)), + dom_size=len(elements), user_agent=user_agent.lower(), _source_id=id(soup), _snapshot=snapshot) + + +def ensure_page_facts(soup: BeautifulSoup, url: str, headers: Any = None, + user_agent: Optional[str] = None, facts: Optional[PageFacts] = None) -> PageFacts: + """Reuse a matching snapshot or build one for a standalone analyzer call.""" + if facts is None: + return extract_page_facts(soup, url, headers, user_agent or 'googlebot') + if not isinstance(facts, PageFacts): + raise TypeError('facts must be a PageFacts snapshot') + if facts.url != url or facts._source_id != id(soup): + raise ValueError('PageFacts does not belong to this URL and soup') + if user_agent is not None and facts.user_agent != user_agent.lower(): + raise ValueError('PageFacts was extracted for a different user agent') + if headers is not None and _headers_snapshot(headers) != facts.headers: + raise ValueError('PageFacts was extracted with different response headers') + return facts diff --git a/tfq0seo/rules.py b/tfq0seo/rules.py new file mode 100644 index 0000000..2f7adb3 --- /dev/null +++ b/tfq0seo/rules.py @@ -0,0 +1,269 @@ +"""Reviewed rule definitions, explicit evaluations, and one scoring policy. + +Reference documents support observations and guidance, not the numeric weights. +Penalties are a versioned TFQ0SEO checklist policy, not search ranking factors. +""" + +import copy +import json +import re +from collections import Counter, OrderedDict +from dataclasses import dataclass +from datetime import date +from types import MappingProxyType +from typing import Any, Dict, Iterable, List, Optional, Tuple +from urllib.parse import urlsplit + + +RULESET_VERSION = '2026.09.21' +SCORING_VERSION = '2.0' +ANALYZERS = ('seo', 'content', 'technical', 'performance', 'links') +PENALTIES = MappingProxyType({'critical': 15, 'warning': 7, 'notice': 3}) +STATUSES = ('pass', 'fail', 'informational', 'unknown', 'not_applicable', 'error') + + +@dataclass(frozen=True) +class RuleDefinition: + rule_id: str + owner: str + severity: str + recommendation: str + applicability: str + references: Tuple[str, ...] + reviewed_on: str + scored: bool = True + title: str = '' + + def __post_init__(self): + if not re.fullmatch(r'[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)+', self.rule_id): + raise ValueError('Rule IDs must be stable dotted identifiers') + if self.owner not in ANALYZERS or self.severity not in PENALTIES: + raise ValueError('Unknown rule owner or severity') + if not self.recommendation.strip() or not self.applicability.strip(): + raise ValueError('Rules require a recommendation and applicability description') + if not isinstance(self.references, tuple) or not self.references: + raise ValueError('Rules require a tuple of reviewed reference URLs') + for reference in self.references: + parsed = urlsplit(reference) + if parsed.scheme != 'https' or not parsed.hostname: + raise ValueError('Rule references must be complete HTTPS URLs') + date.fromisoformat(self.reviewed_on) + if type(self.scored) is not bool: + raise ValueError('scored must be a boolean') + + +_RULES: Dict[str, RuleDefinition] = {} +RULES = MappingProxyType(_RULES) + + +def register_rules(definitions: Iterable[RuleDefinition]): + """Register module-owned definitions once; conflicting IDs are programming errors.""" + definitions = tuple(definitions) + proposed = dict(_RULES) + for definition in definitions: + if not isinstance(definition, RuleDefinition): + raise TypeError('Expected RuleDefinition') + previous = proposed.get(definition.rule_id) + if previous is not None and previous != definition: + raise ValueError('Conflicting rule definition: ' + definition.rule_id) + proposed[definition.rule_id] = definition + _RULES.update(proposed) + return MappingProxyType({item.rule_id: item for item in definitions}) + + +def get_rule(rule_id: str) -> RuleDefinition: + try: + return _RULES[rule_id] + except (KeyError, TypeError) as exc: + raise ValueError('Unregistered rule: ' + str(rule_id)) from exc + + +def rule_result(rule_id: str, evidence: Any, *, message: str = '', category: Optional[str] = None, + status: str = 'fail', applicable: Optional[bool] = True, reason: str = '', + source: str = 'html', confidence: str = 'high', details: Any = None) -> Dict: + definition = get_rule(rule_id) + if status not in STATUSES: + raise ValueError('Unknown rule status: ' + str(status)) + if applicable is not None and type(applicable) is not bool: + raise ValueError('applicable must be true, false, or None') + if not isinstance(evidence, (dict, list)): + raise ValueError('Rule evidence must be structured observations, including unavailable fields') + # Fail before emitting non-portable or non-finite evidence into JSON reports. + json.dumps(evidence, allow_nan=False, ensure_ascii=False) + if applicable is False: + status = 'not_applicable' + elif applicable is None and status != 'error': + status = 'unknown' + elif status == 'fail' and (not definition.scored or confidence == 'low'): + status = 'informational' + if status in ('unknown', 'not_applicable', 'error') and not reason: + raise ValueError('Unknown, inapplicable, and failed evaluations need an explanation') + result = { + 'rule_id': rule_id, 'rule_version': RULESET_VERSION, 'scope': 'page', + 'title': definition.title or rule_id, + 'owner': definition.owner, 'category': category or definition.owner.title(), + 'severity': definition.severity, 'message': message or definition.title or rule_id, + 'status': status, 'applicability': ('applicable' if applicable is True else + 'not_applicable' if applicable is False else 'unknown'), + 'rule_applicability': definition.applicability, 'reason': reason, + 'evidence': copy.deepcopy(evidence), 'source': source, 'confidence': confidence, + 'references': list(definition.references), 'reviewed_on': definition.reviewed_on, + 'fix': definition.recommendation, + 'penalty': PENALTIES[definition.severity] if status == 'fail' and definition.scored else 0, + **({'details': copy.deepcopy(details)} if details is not None else {}), + } + from .core.models import validate_rule_result + validate_rule_result(result) + return result + + +class RuleCollector: + def __init__(self, analyzer: str): + if analyzer not in ANALYZERS: + raise ValueError('Unknown analyzer') + self.analyzer = analyzer + self.results: List[Dict] = [] + + def check(self, rule_id: str, failed: Optional[bool], evidence: Any, *, message: str = '', + category: Optional[str] = None, applicable: Optional[bool] = True, reason: str = '', + source: str = 'html', confidence: str = 'high', status: Optional[str] = None) -> Dict: + if failed is not None and type(failed) is not bool: + raise ValueError('A check condition must be true, false, or None') + outcome = status or ('unknown' if failed is None else 'fail' if failed else 'pass') + result = rule_result(rule_id, evidence, message=message, category=category, status=outcome, + applicable=applicable, reason=reason, source=source, confidence=confidence) + result['reported_by'] = [self.analyzer] + self.results.append(result) + return result + + @property + def issues(self): + return [result for result in self.results if result['status'] in ('fail', 'informational')] + + @property + def coverage(self): + return rule_coverage(self.results) + + +def rule_coverage(results): + merged = merge_rule_results(results) + counts = Counter(result['status'] for result in merged) + has_errors = any(observation.get('status') == 'error' for result in merged + for observation in result.get('observations', [result])) + assessed = sum(counts[status] for status in ('pass', 'fail', 'informational')) + applicable = assessed + counts['unknown'] + counts['error'] + return {'total': sum(counts.values()), 'counts': {status: counts[status] for status in STATUSES}, + 'has_errors': has_errors, + 'assessed': assessed, 'ratio': assessed / applicable if applicable else None, + 'scope': 'Evaluations actually attempted; disabled rules and analyzers are not assumed to pass.'} + + +def merge_rule_results(results): + """Merge duplicate evaluations without discarding their evidence or observers.""" + from .core.models import validate_rule_result + merged = OrderedDict() + precedence = {'not_applicable': 0, 'pass': 1, 'informational': 2, 'unknown': 3, 'error': 4, 'fail': 5} + for original in results: + validate_rule_result(original) + rule_id = original.get('rule_id') + get_rule(rule_id) + result = copy.deepcopy(original) + if result.get('status') not in STATUSES: + raise ValueError('Invalid rule evaluation status') + observation = {key: copy.deepcopy(result.get(key)) for key in + ('status', 'applicability', 'evidence', 'source', 'reason', 'reported_by')} + if rule_id not in merged: + result['observations'] = result.get('observations') or [observation] + merged[rule_id] = result + continue + previous = merged[rule_id] + observations = previous['observations'] + (result.get('observations') or [observation]) + unique_observations = [] + for item in observations: + if item not in unique_observations: + unique_observations.append(item) + reporters = sorted(set(previous.get('reported_by', [])) | set(result.get('reported_by', []))) + if precedence[result['status']] > precedence[previous['status']]: + previous = result + merged[rule_id] = previous + previous['observations'] = unique_observations + previous['reported_by'] = reporters + return list(merged.values()) + + +def finding_penalty(result): + definition = get_rule(result.get('rule_id')) + if (result.get('status') != 'fail' or result.get('applicability') != 'applicable' + or result.get('confidence') == 'low' or not definition.scored): + return 0 + return PENALTIES[definition.severity] + + +def score_findings(issues, owner: Optional[str] = None): + penalties = {} + for issue in issues: + definition = get_rule(issue.get('rule_id')) + if owner is None or definition.owner == owner: + penalties[definition.rule_id] = max(penalties.get(definition.rule_id, 0), finding_penalty(issue)) + return max(0, 100 - sum(penalties.values())) + + +def recommendations_for(issues): + seen, recommendations = set(), [] + for issue in issues: + rule_id = issue.get('rule_id') + definition = get_rule(rule_id) + if issue.get('status') in ('fail', 'informational') and rule_id not in seen: + seen.add(rule_id) + recommendations.append(definition.recommendation) + return recommendations + + +# Shared facts have one owner even when several analyzers observe them. +_REVIEWED = '2026-09-14' +_ROBOTS = ('https://developers.google.com/search/docs/crawling-indexing/robots-meta-tag',) +_HEADINGS = ('https://www.w3.org/WAI/tutorials/page-structure/headings/',) +_VIEWPORT = ('https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/meta/name/viewport',) +register_rules([ + RuleDefinition('robots.noindex', 'seo', 'critical', + 'Confirm whether this page should appear in search. Remove noindex only if indexing is intended.', + 'Observed indexing directives; a restriction may be intentional.', _ROBOTS, _REVIEWED, scored=False), + RuleDefinition('robots.nofollow', 'seo', 'warning', + 'Review the page-wide nofollow directive against the intended link-following policy.', + 'Observed link-following directives; publisher intent is not inferred.', _ROBOTS, _REVIEWED, scored=False), + RuleDefinition('robots.nosnippet', 'seo', 'notice', + 'Confirm the snippet restriction is intentional before changing it.', + 'Observed snippet directives.', _ROBOTS, _REVIEWED, scored=False), + RuleDefinition('headings.missing_h1', 'content', 'warning', + 'Review whether a descriptive top-level heading would clarify the page structure.', + 'HTML documents; absence alone does not establish a ranking or accessibility failure.', + _HEADINGS, _REVIEWED, scored=False), + RuleDefinition('headings.empty', 'content', 'warning', + 'Give each heading meaningful text or remove the empty heading element.', + 'Observed HTML heading elements.', _HEADINGS, _REVIEWED), + RuleDefinition('headings.skipped_level', 'content', 'notice', + 'Review heading levels in document order so they communicate the intended hierarchy.', + 'Observed heading hierarchy; review the document context.', _HEADINGS, _REVIEWED, scored=False), + RuleDefinition('images.missing_alt', 'content', 'warning', + 'Provide an appropriate text alternative; use alt="" for a purely decorative image.', + 'HTML img elements without an alt attribute; content purpose determines its value.', + ('https://www.w3.org/WAI/tutorials/images/decorative/',), _REVIEWED), + RuleDefinition('images.missing_dimensions', 'performance', 'notice', + 'Check reserved image space in the rendered layout; use dimensions or an appropriate CSS aspect ratio.', + 'Image dimension attributes only; CSS and layout are not measured.', + ('https://web.dev/articles/optimize-cls',), _REVIEWED, scored=False), + RuleDefinition('mobile.viewport_missing', 'technical', 'warning', + 'Configure a viewport appropriate for the responsive layout, then test it in a browser.', + 'HTML documents intended for browser display.', _VIEWPORT, _REVIEWED), + RuleDefinition('mobile.viewport_zoom_disabled', 'technical', 'warning', + 'Remove viewport restrictions that prevent users from zooming the page.', + 'An observed viewport declaration restricting user zoom.', _VIEWPORT, _REVIEWED), + RuleDefinition('language.missing', 'technical', 'warning', + 'Declare the primary document language with an appropriate lang attribute.', + 'HTML documents with human-readable content.', + ('https://www.w3.org/WAI/WCAG22/Techniques/html/H57',), _REVIEWED), + RuleDefinition('security.https_missing', 'technical', 'critical', + 'Serve the page over HTTPS with a valid certificate and update navigation to the secure URL.', + 'Observed HTTP document URLs; local development may intentionally use HTTP.', + ('https://developer.mozilla.org/en-US/docs/Web/Security/Defenses/Transport_Layer_Security',), _REVIEWED), +]) diff --git a/tfq0seo/site_analysis.py b/tfq0seo/site_analysis.py new file mode 100644 index 0000000..2eda507 --- /dev/null +++ b/tfq0seo/site_analysis.py @@ -0,0 +1,288 @@ +"""Cross-page observations over fetched evidence, with no additional requests. + +Graph traversal is iterative and memoized. Canonical paths retain their next +hop and terminal instead of copying every suffix of a long chain into reports. +""" + +from collections import Counter, defaultdict, deque +from urllib.parse import urlsplit + +from .rules import RuleDefinition, register_rules, rule_result +from .urls import is_internal_url, resolve_url + + +SITE_ANALYSIS_VERSION = '1.0' +_CANONICAL_REFERENCE = 'https://developers.google.com/search/docs/crawling-indexing/consolidate-duplicate-urls' +_LINK_REFERENCE = 'https://developers.google.com/search/docs/crawling-indexing/links-crawlable' + +register_rules([ + RuleDefinition('site.canonical_' + name, 'seo', severity, recommendation, + 'Canonical declarations and target observations within the supplied page inventory.', + (_CANONICAL_REFERENCE,), '2026-09-21', scored=False, title=title) + for name, severity, title, recommendation in ( + ('conflict', 'warning', 'Conflicting canonical targets', + 'Reconcile the observed canonical declarations so they identify one intended representative URL.'), + ('cycle', 'warning', 'Canonical cycle', + 'Break the recorded cycle and point each duplicate directly to its intended representative URL.'), + ('chain', 'notice', 'Canonical chain', + 'Review the recorded chain and point directly to the intended terminal canonical URL.'), + ('target_error', 'warning', 'Canonical target returned an HTTP error', + 'Fix the observed target response or select an accessible canonical URL.'), + ('target_noindex', 'warning', 'Canonical target declares noindex', + 'Reconcile the canonical preference with the target page\'s observed noindex directive.'), + ('target_redirect', 'notice', 'Canonical target redirects', + 'Review the observed redirect and use the intended final canonical URL directly.'), + ) +]) +register_rules([ + RuleDefinition('site.links_' + name, 'links', 'notice', recommendation, + 'Observed internal HTML links; this is not a complete site inventory or a ranking metric.', + (_LINK_REFERENCE,), '2026-09-21', scored=False, title=title) + for name, title, recommendation in ( + ('no_incoming', 'No incoming links observed', + 'Check whether this page should be linked from relevant pages. Expand crawl coverage before calling it orphaned.'), + ('unreachable', 'No link path observed from the entry pages', + 'Review navigation from the recorded entry pages; unfetched pages may contain additional paths.'), + ) +]) + + +def url_identity(url): + """Reuse HTTP URL resolution, preserving queries and removing fragments.""" + resolved = resolve_url(url, url) + if not resolved or urlsplit(resolved).scheme not in ('http', 'https'): + return None + return resolved.split('#', 1)[0] + + +def _walk_canonicals(next_hops, endings): + """Resolve a functional graph in O(V + E), including redirect aliases.""" + resolved = dict(endings) + cycles = [] + for start in sorted(next_hops): + path, positions = [], {} + current = start + while current not in resolved and current not in positions: + positions[current] = len(path) + path.append(current) + if current not in next_hops: + resolved[current] = (current, 'unchecked', 0, None) + break + current = next_hops[current] + if current in positions and current not in resolved: + members = path[positions[current]:] + first = members.index(min(members)) + members = members[first:] + members[:first] + cycle_id = len(cycles) + cycles.append({'id': cycle_id, 'urls': members}) + for member in members: + resolved[member] = (None, 'cycle', None, cycle_id) + for node in reversed(path): + if node not in resolved: + terminal, status, hops, cycle_id = resolved[next_hops[node]] + resolved[node] = (terminal, status, hops + 1 if hops is not None else None, cycle_id) + return resolved, cycles + + +def analyze_site(pages, *, start_url=None, crawl_complete=False): + """Build additive, unscored site findings from validated page dictionaries. + + Missing facts and unfetched targets remain unknown. Self links do not count + as incoming links. Reachability uses observed hrefs, including nofollow + hints, and never claims to model a search engine's chosen crawl paths. + """ + groups = defaultdict(list) + for page in pages: + identity = url_identity(page.get('url')) + if identity: + groups[identity].append(page) + + aliases = defaultdict(set) + for url, records in groups.items(): + for page in records: + # A terminal HTTP error or skipped non-HTML response still proves + # its redirect destination. Network/loop/limit failures do not. + status = page.get('status_code') or 0 + if not (200 <= status < 300 or 400 <= status <= 599): + continue + sources = [page.get('requested_url')] + sources.extend(hop.get('url') for hop in page.get('redirect_chain', [])) + for source in sources: + alias = url_identity(source) + if alias and alias != url: + aliases[alias].add(url) + redirects = {alias: next(iter(targets)) for alias, targets in aliases.items() + if len(targets) == 1 and alias not in groups} + + facts_by_url, rows, endings, next_hops = {}, {}, {}, dict(redirects) + links_observed = {} + declarations = {} + noindex = set() + statuses = {} + complete_facts = set() + for url in sorted(groups): + records = groups[url] + status_codes = {page.get('status_code') or 0 for page in records} + statuses[url] = next(iter(status_codes)) if len(status_codes) == 1 else 0 + usable = [page for page in records if not page.get('error') and not page.get('skipped') + and 200 <= (page.get('status_code') or 0) < 300 and isinstance(page.get('page_facts'), dict)] + facts = [page['page_facts'] for page in usable] + facts_by_url[url] = facts + links_observed[url] = bool(facts) and all('anchors' in fact for fact in facts) + if (usable and all(not page.get('truncated') for page in records) and len(usable) == len(records) + and all({'anchors', 'robots', 'canonical'} <= fact.keys() and + {'declarations', 'headers_checked', 'parse_errors'} <= fact['canonical'].keys() and + {'noindex', 'nofollow'} <= fact['robots'].keys() for fact in facts)): + complete_facts.add(url) + if any(fact.get('robots', {}).get('noindex') is True for fact in facts): + noindex.add(url) + canonical = [fact.get('canonical') for fact in facts] + observed = bool(canonical) and all(isinstance(item, dict) and + {'declarations', 'headers_checked', 'parse_errors'} <= item.keys() + for item in canonical) + declarations[url] = [declaration for item in canonical if isinstance(item, dict) + for declaration in item.get('declarations', [])] + declarations[url].sort(key=lambda item: tuple(str(item.get(key, '')) for key in + ('url', 'href', 'source', 'eligible', 'reason'))) + targets = sorted({target for declaration in declarations[url] if declaration.get('eligible') + for target in [url_identity(declaration.get('url'))] if target}) + invalid = any(item.get('eligible') and not url_identity(item.get('url')) for item in declarations[url]) + uncertain = (not observed or url not in complete_facts or + any(item.get('parse_errors', 0) for item in canonical if isinstance(item, dict))) + headers_checked = observed and all(item.get('headers_checked') is True for item in canonical) + rows[url] = {'url': url, 'canonical_targets': targets, 'canonical_status': 'unknown', + 'canonical_terminal': None, 'canonical_hops': None, 'canonical_cycle_id': None, + 'incoming_links': 0, 'outgoing_links': 0 if facts else None, + 'nofollow_links': 0 if facts else None, 'link_depth': None, 'reachable': None, + 'component': None, 'facts_available': bool(facts), + 'content_complete': url in complete_facts, 'canonical_headers_checked': headers_checked} + status = ('http_error' if statuses[url] >= 400 else 'conflict' if len(targets) > 1 else + 'invalid' if invalid else 'unknown' if uncertain else + 'self' if targets == [url] else 'none' if not targets and headers_checked else + 'unknown' if not targets else None) + if status is not None: + endings[url] = (url, status, 0, None) + else: + next_hops[url] = targets[0] + + resolved, cycles = _walk_canonicals(next_hops, endings) + findings = [] + + def finding(rule_id, url, evidence): + result = rule_result(rule_id, evidence, source='fetched_site_inventory') + result.update(scope='site', url=url) + findings.append(result) + + for url, row in rows.items(): + terminal, status, hops, cycle_id = resolved[url] + row.update(canonical_terminal=terminal, canonical_hops=hops, canonical_cycle_id=cycle_id) + if hops and status in ('self', 'none'): + status = 'chain' if hops > 1 else 'resolved' + row['canonical_status'] = status + evidence = {key: row[key] for key in ('canonical_targets', 'canonical_terminal', 'canonical_hops', 'canonical_cycle_id')} + # Conflicts are attributed to their source; callers leading to one keep + # the terminal status without duplicating the target's conflict evidence. + if len(row['canonical_targets']) > 1: + finding('site.canonical_conflict', url, {'declarations': declarations[url], **evidence}) + if status == 'cycle': + finding('site.canonical_cycle', url, evidence) + if hops is not None and hops > 1: + finding('site.canonical_chain', url, evidence) + for target in row['canonical_targets']: + destination = redirects.get(target, target) + if target in redirects: + finding('site.canonical_target_redirect', url, {'target': target, 'destination': destination}) + elif statuses.get(target) in (301, 302, 303, 307, 308): + finding('site.canonical_target_redirect', url, {'target': target, 'destination': None, + 'status_code': statuses[target], + 'reason': 'The redirect destination was not observed.'}) + if statuses.get(destination, 0) >= 400: + finding('site.canonical_target_error', url, {'target': target, 'destination': destination, + 'status_code': statuses[destination]}) + if destination in noindex: + finding('site.canonical_target_noindex', url, {'target': target, 'destination': destination}) + + outgoing = {url: set() for url in rows} + incoming = {url: set() for url in rows} + edges, unknown_targets = [], set() + for url, facts in facts_by_url.items(): + links = {} + for fact in facts: + for anchor in fact.get('anchors', []): + target = url_identity(anchor.get('url')) + if not target or not is_internal_url(target, url): + continue + target = redirects.get(target, target) + rel = anchor.get('attrs', {}).get('rel', []) + rel = rel if isinstance(rel, list) else str(rel).split() + nofollow = fact.get('robots', {}).get('nofollow') is True or 'nofollow' in {str(item).lower() for item in rel} + # Any observed ordinary link makes the pair non-nofollow. + links[target] = links.get(target, True) and nofollow + for target, nofollow in sorted(links.items()): + edges.append({'source': url, 'target': target, 'nofollow': nofollow, 'target_observed': target in rows}) + outgoing[url].add(target) + if target in incoming and target != url: + incoming[target].add(url) + if target not in rows: + unknown_targets.add(target) + rows[url]['outgoing_links'] = len(links) if links_observed[url] else None + rows[url]['nofollow_links'] = sum(links.values()) if links_observed[url] else None + + root = url_identity(start_url) + root = redirects.get(root, root) + roots = [root] if root in rows else [] + root_source = 'crawl_start' if roots else 'unavailable' + if start_url is None: + roots = [url for url in rows if urlsplit(url).path == '/' and not urlsplit(url).query] + root_source = 'observed_homepages' if roots else 'unavailable' + depth = dict.fromkeys(roots, 0) + queue = deque(roots) + while queue: + source = queue.popleft() + for target in sorted(outgoing[source]): + if target in rows and target not in depth: + depth[target] = depth[source] + 1 + queue.append(target) + + components = [] + remaining = set(rows) + for start in rows: + if start not in remaining: + continue + component_id = len(components) + members, queue = [], deque([start]) + remaining.remove(start) + while queue: + current = queue.popleft() + members.append(current) + rows[current]['component'] = component_id + for neighbor in (outgoing[current] | incoming[current]) & remaining: + remaining.remove(neighbor) + queue.append(neighbor) + components.append({'id': component_id, 'urls': sorted(members)}) + for url, row in rows.items(): + row['incoming_links'] = len(incoming[url]) + row['link_depth'] = depth.get(url) + row['reachable'] = url in depth if roots else None + if facts_by_url[url] and url not in roots: + if not incoming[url]: + finding('site.links_no_incoming', url, {'incoming_links': 0, 'inventory_pages': len(rows), + 'interpretation': 'Candidate only; unobserved pages may link here.'}) + elif roots and url not in depth: + finding('site.links_unreachable', url, {'roots': roots, 'component': row['component'], + 'interpretation': 'No path in the observed graph.'}) + + return { + 'version': SITE_ANALYSIS_VERSION, + 'scope': 'Observed HTML links, canonical declarations and HTTP responses; no extra fetches or page-score deductions.', + 'coverage': {'inventory_pages': len(rows), 'pages_with_facts': sum(bool(facts) for facts in facts_by_url.values()), + 'complete_html_pages': len(complete_facts), 'crawl_complete': bool(crawl_complete), + 'note': 'A completed crawl still obeys its configured scope. Missing targets and paths remain unverified.'}, + 'canonicals': {'status_counts': dict(Counter(row['canonical_status'] for row in rows.values())), + 'cycles': cycles, 'unchecked_targets': sorted({terminal for terminal, status, _, _ in resolved.values() + if status == 'unchecked' and terminal is not None})}, + 'links': {'node_count': len(rows), 'edge_count': len(edges), 'roots': roots, 'root_source': root_source, + 'unfetched_targets': sorted(unknown_targets), 'components': components, 'edges': edges, + 'depth_method': 'Shortest observed href path, including nofollow hints; not search-engine crawl depth.'}, + 'pages': list(rows.values()), 'findings': findings, + } diff --git a/tfq0seo/templates/enhanced_report.html b/tfq0seo/templates/enhanced_report.html index f8e8a90..a857f7a 100644 --- a/tfq0seo/templates/enhanced_report.html +++ b/tfq0seo/templates/enhanced_report.html @@ -1,3 +1,4 @@ +{% from "rule_metadata.html" import finding as rule_finding, overview as rule_overview, styles as rule_styles %} @@ -442,15 +443,20 @@ } } + {{ rule_styles() }} + {% if report_status == "partial" %}
Analysis is partial. Review the reported errors and page status.
{% endif %} + {% if score_source in ("static_html", "static_rule_heuristics") %}

Scores summarize completed static HTML checks.

{% endif %} + {% if error %}
Analysis failed: {{ error }}
{% endif %} + {% for analyzer_error in analysis_errors %}
{{ analyzer_error.analyzer|title }}: {{ analyzer_error.error }}
{% endfor %}

🚀 TFQ0SEO Enhanced Analysis Report

- {{ url }} + {% if url|safe_url %}{{ url }}{% else %}{{ url }}{% endif %}
@@ -470,6 +476,8 @@

🚀 TFQ0SEO Enhanced Analysis Report

+ {{ rule_overview(scoring_policies, scoring_versions, rule_coverage) }} + {% include "site_analysis.html" %}
@@ -478,8 +486,8 @@

Overall Score

Weighted average of all category scores
-
- {{ overall_score|round|int }}/100 +
+ {{ overall_score|number(0, '/100') }}
@@ -491,10 +499,10 @@

Overall Score

{{ category|title }}

-
- {{ score|round|int }}/100 +
+ {{ score|number(0, '/100') }}
- + {% if score is number %}{% endif %}
{% endfor %}
@@ -549,22 +557,22 @@

Category Scores

📖
-
{% if content_data %}{{ content_data.word_count }}{% else %}0{% endif %}
+
{{ content_data.word_count|number }}
Word Count
📚
-
{% if content_data %}{{ content_data.flesch_reading_ease|round|int }}{% else %}N/A{% endif %}
+
{% if content_data %}{{ content_data.flesch_reading_ease|number }}{% else %}N/A{% endif %}
Readability
🎯
-
{% if content_data %}{{ content_data.average_grade_level|round|int }}{% else %}N/A{% endif %}
+
{% if content_data %}{{ content_data.average_grade_level|number }}{% else %}N/A{% endif %}
Grade Level
🖼️
-
{% if content_data %}{{ content_data.image_count }}{% else %}0{% endif %}
+
{{ content_data.image_count|number }}
Images
@@ -578,21 +586,21 @@

Category Scores

HTTPS Status

-

{% if technical_data.https %}✅ Secure{% else %}❌ Not Secure{% endif %}

+

{% if technical_data.https is sameas true %}HTTPS{% elif technical_data.https is sameas false %}HTTP{% else %}Not measured{% endif %}

-

Mobile Friendly

-

{% if technical_data.has_viewport %}✅ Yes{% else %}❌ No{% endif %}

+

Viewport configured

+

{% if technical_data.has_viewport is sameas true %}Yes{% elif technical_data.has_viewport is sameas false %}No{% else %}Not measured{% endif %}

Compression

-

{{ technical_data.compression|default('Not detected') }}

+

{{ technical_data.compression or 'Not measured' }}

{% endif %} @@ -605,23 +613,23 @@

Compression

{% if performance_data %}
⏱️
-
{{ performance_data.load_time|round(2) }}s
-
Load Time
+
{{ performance_data.html_fetch_time|number(2, 's') }}
+
HTML fetch time
📦
-
{{ performance_data.content_size_mb|round(2) }}MB
-
Page Size
+
{{ performance_data.content_size_mb|number(2, 'MB') }}
+
HTML size
🎨
-
{{ performance_data.lcp_estimate|round(2) }}s
-
LCP Estimate
+
{{ performance_data.lcp|number(2, 's') }}
+
Largest Contentful Paint
👆
-
{{ performance_data.fid_estimate }}ms
-
FID Estimate
+
{{ performance_data.inp|number(0, 'ms') }}
+
Interaction to Next Paint
{% endif %}
@@ -646,6 +654,7 @@

{{ severity|title }} Issues ({{ issues_list|length }})

{% for issue in issues_list %}
{{ issue.category }}: {{ issue.message }} + {{ rule_finding(issue) }}
{% endfor %}
@@ -666,6 +675,22 @@

{{ severity|title }} Issues ({{ issues_list|length }})

+ + {% if pages_summary|length > 1 or summary %} +
+

Pages ({{ pages_summary|length }})

+ + + {% for page in pages_summary %} + + + + + {% endfor %} +
URLScoreStatusLoad timeIssuesAnalysis status
{{ page.url }}{{ page.score|number }}{{ page.status_code if page.status_code is not none else 'Unavailable' }}{{ page.load_time|number(2, 's') }}{{ page.issue_count }}{{ page.error or page.status or '' }}
+
+ {% endif %} + diff --git a/tfq0seo/templates/report.html b/tfq0seo/templates/report.html index 9fb6fdf..b489876 100644 --- a/tfq0seo/templates/report.html +++ b/tfq0seo/templates/report.html @@ -1,3 +1,4 @@ +{% from "rule_metadata.html" import finding as rule_finding, overview as rule_overview, styles as rule_styles %} @@ -504,8 +505,13 @@ } } + {{ rule_styles() }} + {% if report_status == "partial" %}
Analysis is partial. Review the reported errors and page status.
{% endif %} + {% if score_source in ("static_html", "static_rule_heuristics") %}

Scores summarize completed static HTML checks.

{% endif %} + {% if error %}
Analysis failed: {{ error }}
{% endif %} + {% for analyzer_error in analysis_errors %}
{{ analyzer_error.analyzer|title }}: {{ analyzer_error.error }}
{% endfor %}
@@ -515,24 +521,26 @@

TFQ0SEO Analysis Report

- {{ url }} + {% if url|safe_url %}{{ url }}{% else %}{{ url }}{% endif %}
Generated: {{ timestamp }}
+ {{ rule_overview(scoring_policies, scoring_versions, rule_coverage) }} + {% include "site_analysis.html" %}
+ stroke-dashoffset="{{ 565.48 * (1 - overall_score / 100) if overall_score is number else 565.48 }}"> -
- {{ overall_score|round|int }} +
+ {{ overall_score|number }}
Overall Score
@@ -540,8 +548,8 @@

TFQ0SEO Analysis Report

{% for category, score in category_scores.items() %}
-
- {{ score|round|int }} +
+ {{ score|number }}
{{ category|title }}
@@ -589,6 +597,7 @@

Issues Found

{{ severity|upper }}
{{ issue.message }}
+ {{ rule_finding(issue) }} {% if issue.details %}
{{ issue.details|tojson(indent=2) }}
@@ -616,8 +625,24 @@

Recommendations

{% endif %} + + {% if pages_summary|length > 1 or summary %} +
+

Pages ({{ pages_summary|length }})

+ + + {% for page in pages_summary %} + + + + + {% endfor %} +
URLScoreStatusLoad timeIssuesAnalysis status
{{ page.url }}{{ page.score|number }}{{ page.status_code if page.status_code is not none else 'Unavailable' }}{{ page.load_time|number(2, 's') }}{{ page.issue_count }}{{ page.error or page.status or '' }}
+
+ {% endif %} +
-

Generated by TFQ0SEO v2.2.0 - Fast SEO Analysis Tool

+

Generated by TFQ0SEO - Fast SEO Analysis Tool

diff --git a/tfq0seo/templates/rule_metadata.html b/tfq0seo/templates/rule_metadata.html new file mode 100644 index 0000000..e0e6de5 --- /dev/null +++ b/tfq0seo/templates/rule_metadata.html @@ -0,0 +1,72 @@ +{# Shared presentation only: imported report fields remain autoescaped. #} +{% macro styles() -%} + +{%- endmacro %} + +{% macro finding(issue) -%} +{% if issue.get('rule_id') or issue.get('status') or issue.get('applicability') or issue.get('source') or issue.get('references') or issue.get('reviewed_on') or 'evidence' in issue %} + +{% endif %} +{%- endmacro %} + +{% macro overview(policies, versions, coverage) -%} +{% if policies or versions or coverage %} +
+

Scoring policy and rule coverage

+ {% if versions %}

Scoring versions: {{ versions|join(', ') }}

{% endif %} + {% for policy in policies %} + {% if policy.get('ruleset_version') %}

Ruleset: {{ policy.ruleset_version }}

{% endif %} + {% if policy.get('policy') %}

{{ policy.policy }}

{% endif %} + {% if policy.get('scope') %}

{{ policy.scope }}

{% endif %} + {% if policy.get('weights') %} +
Configured category weights
{{ policy.weights|json_text }}
+ {% endif %} + {% endfor %} + {% if policies or versions %}

Scores and weights are TFQ0SEO checklist policy, not search ranking factors or promises from the reference sources.

{% endif %} + {% if coverage %} +

Recorded rule evaluations: {{ coverage.get('total')|number }}. + Assessed: {{ coverage.get('assessed')|number }}.

+ {% if coverage.get('counts') is mapping %} +
    {% for outcome, count in coverage.counts.items() %}
  • {{ outcome }}: {{ count|number }}
  • {% endfor %}
+ {% endif %} + {% if coverage.get('scope') %}

{{ coverage.scope }}

{% endif %} +

Unknown, error, and not-applicable outcomes are not passed checks. Disabled or unattempted checks are not assumed to pass.

+ {% endif %} +
+{% endif %} +{%- endmacro %} diff --git a/tfq0seo/templates/site_analysis.html b/tfq0seo/templates/site_analysis.html new file mode 100644 index 0000000..895edbb --- /dev/null +++ b/tfq0seo/templates/site_analysis.html @@ -0,0 +1,34 @@ +{% if data.get('site_analysis', {}).get('version') %} +
+

Site-wide analysis

+ {% set site = data.site_analysis %} +

{{ site.scope }}

+

{{ site.coverage.pages_with_facts }} of {{ site.coverage.inventory_pages }} observed URLs have page facts. + {{ site.coverage.note }}

+

{{ site.links.edge_count }} distinct internal link pairs; + {{ site.links.unfetched_targets|length }} targets not in the fetched inventory; + {{ site.links.components|length }} connected groups in the observed graph.

+

{{ site.links.depth_method }}

+ {% if site.links.roots %}

Entry pages: {{ site.links.roots|join(', ') }} ({{ site.links.root_source }})

+ {% else %}

No entry page is known; reachability and depth are unavailable.

{% endif %} +
+ Canonical and internal-link observations for every URL +
+ + + + {% for page in site.pages %} + + + + {% for key in ['canonical_hops', 'incoming_links', 'outgoing_links', 'link_depth'] %} + {% endfor %} + {% endfor %} +
URLCanonical statusCanonical target(s)TerminalHopsIncomingOutgoingLink depth
{% if page.url|safe_url %}{{ page.url }}{% else %}{{ page.url }}{% endif %}{{ page.canonical_status }}{{ page.canonical_targets|join(', ') }}{{ page.canonical_terminal or 'Unverified' }}{{ page[key] if page[key] is not none else 'Unverified' }}
+
+
+ {% if site.canonicals.cycles %}
Canonical cycles + {% for cycle in site.canonicals.cycles %}

Cycle {{ cycle.id }}: {{ cycle.urls|join(' → ') }}

{% endfor %} +
{% endif %} +
+{% endif %} diff --git a/tfq0seo/urls.py b/tfq0seo/urls.py new file mode 100644 index 0000000..a6f2239 --- /dev/null +++ b/tfq0seo/urls.py @@ -0,0 +1,122 @@ +"""URL-reference resolution shared by discovery and static analysis.""" + +from typing import Optional +from urllib.parse import urlsplit, urlunsplit + + +def _remove_dot_segments(path: str) -> str: + """Remove literal dot segments without collapsing empty path segments.""" + segments = path.split('/') + result = [] + for index, segment in enumerate(segments): + if segment == '.': + if index == len(segments) - 1: + result.append('') + elif segment == '..': + if result and (len(result) > 1 or result[0] != ''): + result.pop() + if index == len(segments) - 1: + result.append('') + else: + result.append(segment) + return '/'.join(result) + + +def _authority(parsed) -> str: + hostname = parsed.hostname + if not hostname or any(character.isspace() or character in '/\\?#@' for character in hostname): + raise ValueError('Invalid HTTP hostname') + port = parsed.port # Validates port syntax and range. + if ':' in hostname: + host = '[' + hostname.lower() + ']' + else: + if '%' in hostname: + raise ValueError('Percent-encoded hostnames are not supported') + host = hostname.encode('idna').decode('ascii').lower() + userinfo = parsed.netloc.rsplit('@', 1)[0] + '@' if '@' in parsed.netloc else '' + default_port = 443 if parsed.scheme.lower() == 'https' else 80 + return userinfo + host + (f':{port}' if port is not None and port != default_port else '') + + +def resolve_url(href: str, base_url: str) -> Optional[str]: + """Resolve a URI reference, preserving duplicate slashes and query semantics. + + Only literal dot segments and HTTP authority case/default ports are + normalized. Empty query values, query ordering, and fragments are retained. + Invalid authorities are rejected without raising into a page analysis. + """ + if not isinstance(href, str) or not isinstance(base_url, str): + return None + reference = href.strip() + if any(ord(character) < 32 or ord(character) == 127 for character in reference): + return None + try: + ref = urlsplit(reference) + base = urlsplit(base_url) + has_query = '?' in reference.split('#', 1)[0] + if ref.scheme: + scheme, netloc, path, query = ref.scheme, ref.netloc, ref.path, ref.query + elif ref.netloc: + scheme, netloc, path, query = base.scheme, ref.netloc, ref.path, ref.query + else: + scheme, netloc = base.scheme, base.netloc + if not ref.path: + path = base.path + query = ref.query if has_query else base.query + has_query = has_query or '?' in base_url.split('#', 1)[0] + else: + if ref.path.startswith('/'): + path = ref.path + else: + directory = base.path.rsplit('/', 1)[0] + '/' if '/' in base.path else ('/' if netloc else '') + path = directory + ref.path + query = ref.query + scheme = scheme.lower() + if not scheme: + return None + if scheme in ('http', 'https'): + path = _remove_dot_segments(path) or '/' + parsed = urlsplit(urlunsplit((scheme, netloc, path, query, ref.fragment))) + netloc = _authority(parsed) + result = urlunsplit((scheme, netloc, path, query, ref.fragment)) + if has_query and not query: + head, separator, fragment = result.partition('#') + result = head + '?' + (separator + fragment if separator else '') + if '#' in reference and not ref.fragment: + result += '#' + return result + except (TypeError, ValueError, UnicodeError): + return None + + +def is_internal_url(href: str, page_url: str, base_url: Optional[str] = None) -> bool: + """Match the site hostname/port, allowing standard HTTP to HTTPS transitions.""" + resolved = resolve_url(href, base_url or page_url) + page_resolved = resolve_url(page_url, page_url) + if not resolved or not page_resolved: + return False + target, page = urlsplit(resolved), urlsplit(page_resolved) + if target.scheme not in ('http', 'https') or page.scheme not in ('http', 'https'): + return False + target_host = (target.hostname or '').lower().rstrip('.') + page_host = (page.hostname or '').lower().rstrip('.') + default_target = 443 if target.scheme == 'https' else 80 + default_page = 443 if page.scheme == 'https' else 80 + target_port = target.port if target.port is not None else default_target + page_port = page.port if page.port is not None else default_page + return target_host == page_host and ( + target_port == page_port or (target_port == default_target and page_port == default_page) + ) + + +def classify_url(href: str, page_url: str, base_url: Optional[str] = None) -> str: + resolved = resolve_url(href, base_url or page_url) + if not resolved: + return 'invalid' + scheme = urlsplit(resolved).scheme + if scheme in ('http', 'https'): + return 'internal' if is_internal_url(href, page_url, base_url) else 'external' + return { + 'mailto': 'email', 'tel': 'telephone', 'javascript': 'javascript', + 'data': 'data', + }.get(scheme, 'other')