From ecb9faaf9d5f648428685848d749f6ec72c5d2bb Mon Sep 17 00:00:00 2001
From: Talal Alqahs <153442159+TFQ0@users.noreply.github.com>
Date: Wed, 9 Sep 2026 18:54:43 +0300
Subject: [PATCH 1/5] Update README.md
---
README.md | 3 +++
1 file changed, 3 insertions(+)
diff --git a/README.md b/README.md
index cf70e29..8bb24d3 100644
--- a/README.md
+++ b/README.md
@@ -44,3 +44,6 @@ tfq0seo crawl https://example.com --depth 5 --max-pages 500 --concurrent 20 --fo
4. **Performance**
5. **Link Analysis**
+
+
+
From 7675604c2802de47b7440f9dbf8dde2bf7ca1f8f Mon Sep 17 00:00:00 2001
From: Talal Alqahs <153442159+TFQ0@users.noreply.github.com>
Date: Tue, 15 Sep 2026 01:24:06 +0300
Subject: [PATCH 2/5] update 3.0.0
---
.github/workflows/tests.yml | 54 +
.github/workflows/tfq0seo-publish.yml | 79 +-
.gitignore | 2 +
MANIFEST.in | 1 +
README.md | 371 ++++-
pyproject.toml | 15 +-
requirements.txt | 20 +-
setup.py | 52 +-
tests/conftest.py | 66 +
tests/test_analyzers.py | 327 ++++
tests/test_app.py | 271 ++++
tests/test_app_edges.py | 178 ++
tests/test_benchmark.py | 147 ++
tests/test_cli.py | 119 ++
tests/test_config.py | 160 ++
tests/test_content_performance_link_rules.py | 250 +++
tests/test_crawler.py | 590 +++++++
tests/test_crawler_deadline_contract.py | 114 ++
tests/test_exporters.py | 274 ++++
tests/test_model_contracts.py | 299 ++++
tests/test_page_facts.py | 231 +++
tests/test_report_contracts.py | 209 +++
tests/test_rule_reports.py | 128 ++
tests/test_rules.py | 289 ++++
tests/test_seo_rules.py | 200 +++
tests/test_shared_fact_analyzers.py | 162 ++
tests/test_technical_rules.py | 297 ++++
tests/wheel_smoke.py | 66 +
tfq0seo/analyzers/common.py | 174 ++
tfq0seo/analyzers/content.py | 617 +++----
tfq0seo/analyzers/links.py | 852 +++-------
tfq0seo/analyzers/performance.py | 1086 +++++--------
tfq0seo/analyzers/seo.py | 1303 +++++----------
tfq0seo/analyzers/technical.py | 1176 +++++++-------
tfq0seo/benchmark.py | 487 +++---
tfq0seo/cli.py | 606 ++-----
tfq0seo/core/app.py | 1517 +++++++++--------
tfq0seo/core/config.py | 746 ++++-----
tfq0seo/core/crawler.py | 1531 ++++++++++--------
tfq0seo/core/models.py | 478 ++++++
tfq0seo/core/report_contracts.py | 282 ++++
tfq0seo/core/report_optimizer.py | 454 ++----
tfq0seo/exporters/base.py | 894 +++++-----
tfq0seo/page_facts.py | 293 ++++
tfq0seo/rules.py | 269 +++
tfq0seo/templates/enhanced_report.html | 76 +-
tfq0seo/templates/optimized_report.html | 93 +-
tfq0seo/templates/report.html | 40 +-
tfq0seo/templates/rule_metadata.html | 72 +
tfq0seo/urls.py | 122 ++
50 files changed, 11327 insertions(+), 6812 deletions(-)
create mode 100644 .github/workflows/tests.yml
create mode 100644 tests/conftest.py
create mode 100644 tests/test_analyzers.py
create mode 100644 tests/test_app.py
create mode 100644 tests/test_app_edges.py
create mode 100644 tests/test_benchmark.py
create mode 100644 tests/test_cli.py
create mode 100644 tests/test_config.py
create mode 100644 tests/test_content_performance_link_rules.py
create mode 100644 tests/test_crawler.py
create mode 100644 tests/test_crawler_deadline_contract.py
create mode 100644 tests/test_exporters.py
create mode 100644 tests/test_model_contracts.py
create mode 100644 tests/test_page_facts.py
create mode 100644 tests/test_report_contracts.py
create mode 100644 tests/test_rule_reports.py
create mode 100644 tests/test_rules.py
create mode 100644 tests/test_seo_rules.py
create mode 100644 tests/test_shared_fact_analyzers.py
create mode 100644 tests/test_technical_rules.py
create mode 100644 tests/wheel_smoke.py
create mode 100644 tfq0seo/analyzers/common.py
create mode 100644 tfq0seo/core/models.py
create mode 100644 tfq0seo/core/report_contracts.py
create mode 100644 tfq0seo/page_facts.py
create mode 100644 tfq0seo/rules.py
create mode 100644 tfq0seo/templates/rule_metadata.html
create mode 100644 tfq0seo/urls.py
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..9b953eb 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -4,6 +4,7 @@ include requirements.txt
include pyproject.toml
recursive-include tfq0seo/templates *.html
recursive-include tfq0seo *.py
+recursive-include tests *.py
global-exclude __pycache__
global-exclude *.py[co]
global-exclude .DS_Store
diff --git a/README.md b/README.md
index 8bb24d3..3e22dcc 100644
--- a/README.md
+++ b/README.md
@@ -1,49 +1,368 @@
-# TFQ0SEO - SEO Analysis Tool
+# TFQ0SEO
-[](https://pypi.org/project/tfq0seo/)
-[](https://github.com/tfq0/tfq0seo/blob/main/LICENSE)
-[](https://pypi.org/project/tfq0seo/)
-[](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](tfq0seo/core/config.py).
+
+Unknown keys, invalid types, conflicting aliases, and unsupported non-default
+legacy settings fail validation. Legacy dataclass fields remain readable for
+compatibility; their presence does not imply an implemented feature. JavaScript
+execution, HTTP/2 selection, background monitoring, webhooks, email delivery,
+PDF export, and `dry_run` are not implemented. Remove unused legacy overrides
+instead of relying on settings that previously had no effect.
+
+## 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](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.
+
+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.
+
+## 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](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](tfq0seo/core/report_contracts.py).
+
+## Rules, applicability, and scoring
+
+The rule registry in [rules.py](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
```
-## 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. 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, `v2.3.3`). 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/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.
',
+ '
',
+ '
Hidden
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
Secret
')
+ 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('