# kanif-kumbhar/pdf-analyzer architecture

> Architecture diagram of the GitHub repository kanif-kumbhar/pdf-analyzer, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-07-10). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/kanif-kumbhar/pdf-analyzer
- Repository: https://github.com/kanif-kumbhar/pdf-analyzer

## Overview

1. **Overall shape**
   - This is a **single Next.js monolith**: UI, server route handlers, security checks, caching, and AI orchestration all live in one deployable app.
   - The main architectural boundary is **browser vs. server**. The client submits a URL or PDF file, but all fetching, validation, caching, and Gemini access happen server-side.

2. **Presentation layer**
   - The app shell is in `app/layout.tsx`, `app/page.tsx`, and `app/globals.css`.
   - The analyzer UI is split into reusable components under `components/analyzer`, including the URL form, drag-and-drop upload zone, loading skeleton, error state, and structured result cards/lists.
   - The UI is designed to consume a single structured analysis result object and render metadata, topics, takeaways, and key points.

3. **API surface**
   - The primary entrypoint is `POST /api/analyze` for analyzing a PDF from a public URL.
   - `POST /api/analyze/upload` handles direct file uploads.
   - `GET/POST /api/analyze/cached` appears to support cache retrieval or cache-backed analysis lookup.
   - `GET /api/history` exposes prior analyses, and `GET /api/limit` likely exposes rate-limit status for the client.

4. **Request orchestration pipeline**
   - Requests first pass through **schema validation** (`lib/validation/analyze-request.ts`).
   - URLs are normalized/transformed (`lib/url/transform-url.ts`), then validated for safety.
   - The server either returns a cached result or fetches and analyzes the PDF.
   - The pipeline is intentionally synchronous: one request can perform fetch, validation, AI analysis, persistence, and response assembly end-to-end.

5. **Document ingestion and PDF handling**
   - URL-based ingestion uses `lib/pdf/fetch-pdf.ts` to stream the remote document.
   - Upload-based ingestion uses `lib/pdf/validate-upload.ts` to enforce file safety and size limits.
   - `lib/pdf/metadata.ts` and `lib/analysis/reading-time.ts` compute deterministic document metadata such as page count and estimated reading time.
   - A PDF signature check and incremental byte-size enforcement are part of the trust boundary before any AI work begins.

6. **Security boundary**
   - SSRF protection is a core subsystem: `lib/security/validate-url.ts` and `lib/security/ip-policy.ts` enforce protocol restrictions, block credentials in URLs, and reject private/reserved IP ranges.
   - Redirects are audited rather than blindly followed.
   - This means the server never trusts the user-supplied URL as-is, and the browser never directly contacts external PDF hosts.

7. **Caching and persistence**
   - Supabase PostgreSQL is the persistence layer (`lib/db/supabase.ts`).
   - There are two cache layers:
     - **L1 URL cache** in `lib/db/analysis-cache.ts`, keyed by normalized URL hash.
     - **L2 content cache** keyed by SHA-256 of the PDF bytes.
   - `lib/db/search-history.ts` stores past analyses for history retrieval.
   - Cached results are part of the main request path, not a separate background system.

8. **AI analysis boundary**
   - Gemini integration lives in `lib/providers/gemini.ts`.
   - Prompt construction is isolated in `lib/analysis/prompt.ts`.
   - The model is expected to return a **strict structured schema** defined in `lib/analysis/schema.ts`, and that response is validated before being accepted.
   - The PDF content is treated as untrusted data; the prompt design is meant to reduce prompt injection risk.

9. **Validation and error handling**
   - The app uses `lib/errors/app-error.ts` and `lib/errors/error-response.ts` to translate internal failures into public-facing error codes/messages.
   - This creates a consistent contract for invalid URLs, unsafe hosts, oversized files, timeouts, rate-limit violations, and model/schema failures.
   - The result is a controlled error surface rather than leaking raw exceptions to the client.

10. **Rate limiting**
   - `lib/security/rate-limit.ts` implements a two-tier quota system.
   - The repository indicates separate limits for general request traffic and expensive analysis calls.
   - Limits are persisted in the database and keyed via hashed client identifiers to avoid storing raw IPs.

11. **Observability**
   - `lib/observability/logger.ts` provides server-side logging for analysis and failure paths.
   - This is a supporting subsystem rather than a user-facing feature, but it matters for tracing request execution across validation, fetch, cache, and model stages.

12. **Architecture decision record trail**
   - The `docs/decisions` folder documents the key design choices: monolith structure, SSRF protection, caching strategy, rate limiting, and Gemini schema enforcement.
   - These ADRs reinforce the repo’s core shape: a security-heavy server-side document analysis pipeline with strong validation and cache reuse.

Main entry points: [`app/api/analyze/route.ts`](https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/app/api/analyze/route.ts) (Analyze API), [`components/analyzer`](https://github.com/kanif-kumbhar/pdf-analyzer/tree/master/components/analyzer) (Analyzer UI), [`app/api/analyze/upload/route.ts`](https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/app/api/analyze/upload/route.ts) (Upload API), [`docs/decisions`](https://github.com/kanif-kumbhar/pdf-analyzer/tree/master/docs/decisions) (ADRs)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_ui["UI"]
  node_app_shell["App shell<br/>next app<br/>[layout.tsx]"]
  node_analyzer_ui["Analyzer UI<br/>client components"]
end

subgraph group_api["API"]
  node_api_analyze["Analyze API<br/>route handler<br/>[route.ts]"]
  node_api_upload["Upload API<br/>route handler<br/>[route.ts]"]
  node_api_cached["Cached API<br/>route handler<br/>[route.ts]"]
  node_api_history["History API<br/>route handler<br/>[route.ts]"]
  node_api_limit["Limit API<br/>route handler<br/>[route.ts]"]
end

subgraph group_core["Core pipeline"]
  node_request_validation["Request validation<br/>schema guard<br/>[analyze-request.ts]"]
  node_url_transform["URL transform<br/>url normalization<br/>[transform-url.ts]"]
  node_url_security["URL safety<br/>ssrf defense<br/>[validate-url.ts]"]
  node_ip_policy["IP policy<br/>network policy<br/>[ip-policy.ts]"]
  node_pdf_fetch["PDF fetch<br/>remote ingestion<br/>[fetch-pdf.ts]"]
  node_upload_validate["Upload safety<br/>file guard<br/>[validate-upload.ts]"]
  node_pdf_metadata["PDF metadata<br/>document metrics<br/>[metadata.ts]"]
  node_reading_time["Reading time<br/>estimate<br/>[reading-time.ts]"]
  node_analysis_prompt["Prompt builder<br/>prompt assembly<br/>[prompt.ts]"]
  node_analysis_schema["Analysis schema<br/>structured output<br/>[schema.ts]"]
  node_rate_limit["Rate limiting<br/>quota control<br/>[rate-limit.ts]"]
  node_app_error["App errors<br/>error mapping<br/>[app-error.ts]"]
  node_error_response["Error response<br/>api formatter<br/>[error-response.ts]"]
end

subgraph group_infra["Infra"]
  node_analysis_cache[("Analysis cache<br/>cache layer<br/>[analysis-cache.ts]")]
  node_search_history[("Search history<br/>persistence<br/>[search-history.ts]")]
  node_supabase[("Supabase DB<br/>postgres backend<br/>[supabase.ts]")]
  node_gemini["Gemini provider<br/>llm integration<br/>[gemini.ts]"]
  node_logger["Logger<br/>observability<br/>[logger.ts]"]
end

subgraph group_docs["Docs"]
  node_decisions["ADRs<br/>design docs"]
end

node_app_shell -->|"renders"| node_analyzer_ui
node_analyzer_ui -->|"submits URL"| node_api_analyze
node_analyzer_ui -->|"uploads file"| node_api_upload
node_analyzer_ui -->|"checks cache"| node_api_cached
node_analyzer_ui -->|"loads history"| node_api_history
node_analyzer_ui -->|"reads quota"| node_api_limit
node_api_analyze -->|"validates"| node_request_validation
node_api_analyze -->|"normalizes"| node_url_transform
node_url_transform -->|"guards"| node_url_security
node_url_security -->|"resolves IPs"| node_ip_policy
node_api_analyze -->|"throttles"| node_rate_limit
node_api_analyze -->|"looks up"| node_analysis_cache
node_analysis_cache -->|"reads/writes"| node_supabase
node_api_analyze -->|"fetches PDF"| node_pdf_fetch
node_api_upload -->|"validates upload"| node_upload_validate
node_api_upload -->|"throttles"| node_rate_limit
node_pdf_fetch -->|"extracts metadata"| node_pdf_metadata
node_upload_validate -->|"extracts metadata"| node_pdf_metadata
node_pdf_metadata -->|"estimates"| node_reading_time
node_api_analyze -->|"builds prompt"| node_analysis_prompt
node_api_upload -->|"builds prompt"| node_analysis_prompt
node_analysis_prompt -->|"expects"| node_analysis_schema
node_analysis_prompt -->|"calls"| node_gemini
node_gemini -->|"returns"| node_analysis_schema
node_api_analyze -->|"stores history"| node_search_history
node_search_history -->|"reads/writes"| node_supabase
node_api_history -->|"reads"| node_search_history
node_api_limit -->|"reports"| node_rate_limit
node_api_analyze -->|"maps failures"| node_app_error
node_app_error -->|"formats"| node_error_response
node_api_analyze -->|"logs"| node_logger
node_api_upload -->|"logs"| node_logger
node_decisions -.->|"documents"| node_analysis_cache
node_decisions -.->|"documents"| node_url_security
node_decisions -.->|"documents"| node_rate_limit
node_decisions -.->|"documents"| node_analysis_schema

click node_app_shell "https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/app/layout.tsx"
click node_analyzer_ui "https://github.com/kanif-kumbhar/pdf-analyzer/tree/master/components/analyzer"
click node_api_analyze "https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/app/api/analyze/route.ts"
click node_api_upload "https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/app/api/analyze/upload/route.ts"
click node_api_cached "https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/app/api/analyze/cached/route.ts"
click node_api_history "https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/app/api/history/route.ts"
click node_api_limit "https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/app/api/limit/route.ts"
click node_request_validation "https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/validation/analyze-request.ts"
click node_url_transform "https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/url/transform-url.ts"
click node_url_security "https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/security/validate-url.ts"
click node_ip_policy "https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/security/ip-policy.ts"
click node_pdf_fetch "https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/pdf/fetch-pdf.ts"
click node_upload_validate "https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/pdf/validate-upload.ts"
click node_pdf_metadata "https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/pdf/metadata.ts"
click node_reading_time "https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/analysis/reading-time.ts"
click node_analysis_prompt "https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/analysis/prompt.ts"
click node_analysis_schema "https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/analysis/schema.ts"
click node_analysis_cache "https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/db/analysis-cache.ts"
click node_search_history "https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/db/search-history.ts"
click node_supabase "https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/db/supabase.ts"
click node_rate_limit "https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/security/rate-limit.ts"
click node_gemini "https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/providers/gemini.ts"
click node_app_error "https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/errors/app-error.ts"
click node_error_response "https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/errors/error-response.ts"
click node_logger "https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/observability/logger.ts"
click node_decisions "https://github.com/kanif-kumbhar/pdf-analyzer/tree/master/docs/decisions"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_app_shell,node_analyzer_ui toneBlue
class node_api_analyze,node_api_upload,node_api_cached,node_api_history,node_api_limit toneAmber
class node_request_validation,node_url_transform,node_url_security,node_ip_policy,node_pdf_fetch,node_upload_validate,node_pdf_metadata,node_reading_time,node_analysis_prompt,node_analysis_schema,node_rate_limit,node_app_error,node_error_response toneMint
class node_analysis_cache,node_search_history,node_supabase,node_gemini,node_logger toneRose
class node_decisions toneIndigo
```

## Components

### UI

Next.js client-side presentation and interaction layer

- [App shell](https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/app/layout.tsx): next app · Root layout, page, and global styles for the monolith UI · `app/layout.tsx`
- [Analyzer UI](https://github.com/kanif-kumbhar/pdf-analyzer/tree/master/components/analyzer): client components · Form, drop zone, skeleton, errors, and result rendering for document analysis · `components/analyzer`

### API

Route handlers that expose the analysis service

- [Analyze API](https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/app/api/analyze/route.ts): route handler · Primary endpoint for URL-based PDF analysis · `app/api/analyze/route.ts`
- [Upload API](https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/app/api/analyze/upload/route.ts): route handler · Direct file upload analysis endpoint · `app/api/analyze/upload/route.ts`
- [Cached API](https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/app/api/analyze/cached/route.ts): route handler · Cache retrieval or cache-backed analysis lookup · `app/api/analyze/cached/route.ts`
- [History API](https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/app/api/history/route.ts): route handler · Returns prior analyses for the client · `app/api/history/route.ts`
- [Limit API](https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/app/api/limit/route.ts): route handler · Exposes rate-limit status to the client · `app/api/limit/route.ts`

### Core pipeline

Server-side validation, ingestion, analysis, caching, and errors

- [Request validation](https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/validation/analyze-request.ts): schema guard · Validates analyze request shape before any work begins · `lib/validation/analyze-request.ts`
- [URL transform](https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/url/transform-url.ts): url normalization · Normalizes and prepares submitted URLs for validation and hashing · `lib/url/transform-url.ts`
- [URL safety](https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/security/validate-url.ts): ssrf defense · Blocks unsafe protocols, credentials, and reserved/private hosts · `lib/security/validate-url.ts`
- [IP policy](https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/security/ip-policy.ts): network policy · Resolves and rejects disallowed IP ranges during URL checks · `lib/security/ip-policy.ts`
- [PDF fetch](https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/pdf/fetch-pdf.ts): remote ingestion · Streams remote PDFs from trusted URLs on the server · `lib/pdf/fetch-pdf.ts`
- [Upload safety](https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/pdf/validate-upload.ts): file guard · Validates uploaded PDF size, signature, and trust boundary · `lib/pdf/validate-upload.ts`
- [PDF metadata](https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/pdf/metadata.ts): document metrics · Derives page count and document metadata · `lib/pdf/metadata.ts`
- [Reading time](https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/analysis/reading-time.ts): estimate · Computes estimated reading duration from document characteristics · `lib/analysis/reading-time.ts`
- [Prompt builder](https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/analysis/prompt.ts): prompt assembly · Constructs the Gemini prompt around untrusted PDF content · `lib/analysis/prompt.ts`
- [Analysis schema](https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/analysis/schema.ts): structured output · Strict response schema required from the model · `lib/analysis/schema.ts`
- [Rate limiting](https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/security/rate-limit.ts): quota control · Two-tier request and analysis throttling keyed by hashed client identity · `lib/security/rate-limit.ts`
- [App errors](https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/errors/app-error.ts): error mapping · Converts internal failures into controlled public errors · `lib/errors/app-error.ts`
- [Error response](https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/errors/error-response.ts): api formatter · Formats safe client-facing error payloads · `lib/errors/error-response.ts`

### Infra

Persistence, observability, and external service integration

- [Analysis cache](https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/db/analysis-cache.ts): cache layer · URL-keyed and content-keyed cached analysis lookup · `lib/db/analysis-cache.ts`
- [Search history](https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/db/search-history.ts): persistence · Stores prior analyses for history retrieval · `lib/db/search-history.ts`
- [Supabase DB](https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/db/supabase.ts): postgres backend · Shared persistence layer for cache, history, and quota state · `lib/db/supabase.ts`
- [Gemini provider](https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/providers/gemini.ts): llm integration · Server-side model access for document analysis · `lib/providers/gemini.ts`
- [Logger](https://github.com/kanif-kumbhar/pdf-analyzer/blob/master/lib/observability/logger.ts): observability · Server-side logging across validation, fetch, cache, and model paths · `lib/observability/logger.ts`

### Docs

Architecture decision records and design notes

- [ADRs](https://github.com/kanif-kumbhar/pdf-analyzer/tree/master/docs/decisions): design docs · Architecture decision records for monolith, SSRF, caching, rate limits, and schema enforcement · `docs/decisions`

## Connections

- App shell → Analyzer UI: renders · The page shell hosts the analyzer components
- Analyzer UI → Analyze API: submits URL · Client sends URL analysis requests to the main API
- Analyzer UI → Upload API: uploads file · Client sends direct PDF uploads to the upload endpoint
- Analyzer UI → Cached API: checks cache · Client can query cache-backed analysis state
- Analyzer UI → History API: loads history · Client requests prior analyses
- Analyzer UI → Limit API: reads quota · Client checks current rate-limit status
- Analyze API → Request validation: validates · Analyze requests are schema-checked first
- Analyze API → URL transform: normalizes · Submitted URLs are normalized before policy checks
- URL transform → URL safety: guards · Transformed URLs are checked for SSRF and trust issues
- URL safety → IP policy: resolves IPs · Disallowed network ranges are rejected
- Analyze API → Rate limiting: throttles · Request traffic is rate-limited before expensive work
- Analyze API → Analysis cache: looks up · Main analysis path consults cached results first
- Analysis cache → Supabase DB: reads/writes · Cache records are persisted in Postgres
- Analyze API → PDF fetch: fetches PDF · Server streams the remote document after validation
- Upload API → Upload safety: validates upload · Upload endpoint enforces size and PDF signature rules
- Upload API → Rate limiting: throttles · Upload analysis is also quota-controlled
- PDF fetch → PDF metadata: extracts metadata · Fetched documents are summarized with deterministic metadata
- Upload safety → PDF metadata: extracts metadata · Validated uploads flow into metadata extraction
- PDF metadata → Reading time: estimates · Metadata feeds reading-time estimation
- Analyze API → Prompt builder: builds prompt · Analysis pipeline constructs a model prompt from document content
- Upload API → Prompt builder: builds prompt · Upload pipeline also constructs the analysis prompt
- Prompt builder → Analysis schema: expects · Prompt is paired with a strict structured response contract
- Prompt builder → Gemini provider: calls · Prompt is sent to the Gemini provider
- Gemini provider → Analysis schema: returns · Model output is validated against the schema before acceptance
- Analyze API → Search history: stores history · Successful analyses are persisted for later retrieval
- Search history → Supabase DB: reads/writes · History records are stored in the database
- History API → Search history: reads · History endpoint serves prior analyses from storage
- Limit API → Rate limiting: reports · Limit endpoint exposes current quota state
- Analyze API → App errors: maps failures · Internal failures are normalized into app errors
- App errors → Error response: formats · Errors are turned into safe API responses
- Analyze API → Logger: logs · Request execution and failures are logged
- Upload API → Logger: logs · Upload path emits server-side logs
- ADRs → Analysis cache: documents · ADR trail captures the caching strategy
- ADRs → URL safety: documents · ADR trail captures SSRF protections
- ADRs → Rate limiting: documents · ADR trail captures rate limiting
- ADRs → Analysis schema: documents · ADR trail captures structured Gemini responses
