Files
webb/PROJECT_REQUIREMENT_DOCUMENTATION.md
T

74 KiB

PRD: Dynamic, JSON-Driven Photo Tools Website

Version: 1.1 | Date: 03 Nov 2026 | Status: ready for design and build Purpose: one SEO-first website that showcases all photo tools, lets visitors try them free, and sends them to the right mobile app. Every page, text, layout, theme, tool and backend endpoint is controlled by JSON files, so features can be added, changed or removed later without rewriting code. Change from v1.0: the backend layer now consumes the owner's real API Catalogue JSON (format documented in Section 7) as a replaceable input file, instead of a hand-written manifest.


0. How to use this document in a prompt (for humans and AI assistants)

0.1 Referencing

  • Cite sections as PRD §7.4 and requirements by ID, e.g. CFG-04, API-09, TRY-05, SEO-14.
  • Priority words: Must (launch blocker), Should (planned, can slip), Could (nice to have).
  • File names in code style are real files in the repository (see §16).

0.2 Source-of-truth order (when instructions conflict)

  1. The user's explicit instruction in the current prompt.
  2. Must requirements in this PRD.
  3. Schemas in content/schemas/ (validation rules).
  4. Conventions in §16.
  5. Should / Could requirements.

0.3 Rules an AI assistant must follow when building from this PRD

  1. Never hard-code copy, URLs, API paths, parameter names, colours, limits or app/store links. They come from JSON (§5, §7).
  2. Never expose secrets. API secret keys, backend URLs and raw catalogue data stay on the server. The browser calls only the site's own routes (/api/try/...).
  3. Treat the API Catalogue as an external, changeable input. Endpoints may be added, removed or edited at any time. Code must tolerate that (§7.4, §7.10).
  4. Validate everything (JSON files, user uploads, backend responses). Invalid content must degrade gracefully, never crash the site.
  5. Use the section registry to render pages (§6). Do not build one-off page components for content that can be a section.
  6. TypeScript strict, tests included for every module (unit tests for config/binding/catalogue normalisation; Playwright for flows).
  7. If a decision depends on an item in §7.13 Open questions, make the choice configurable and state the assumption in code comments and the PR description.
  8. Keep output small and modular. One responsibility per file.

0.4 Prompt templates

Ready-to-paste prompts are in Appendix E.

0.5 Key file names (glossary)

File / folder Meaning
content/site.config.json Brand, theme tokens, navigation, feature flags, SEO defaults, analytics
content/pages/*.json Static pages as ordered lists of sections
content/templates/*.json Section lists for collection pages (tool page, app page, ...)
content/collections/{tools,apps,categories,useCases,faqs,testimonials}/*.json Reusable records
content/api.catalog.json Owner-supplied API Catalogue (replaceable at any time; format in §7.2)
content/api.overlay.json Site-specific settings for endpoints (limits, variants, secrets mapping, enable/disable)
content/redirects.json Old URL to new URL rules
content/locales/{lang}.json Translated system strings and content overrides
content/schemas/* Schemas used to validate all of the above

1. Overview

1.1 Product

A single, structured, professional website for a portfolio of photo-editing apps (Android and iOS). The website is a marketing and try-it engine: it earns organic search traffic, lets visitors try tools free without signing up, and sends each visitor to the home app that contains the tool. Purchases and credits stay inside each app.

1.2 Decisions already made

  • One website for the whole portfolio (shared SEO strength, one design, one codebase).
  • Each tool has exactly one home app. Buttons read "Open {tool} in {app}".
  • Apps have separate store accounts and separate in-app purchases. The site must never imply a shared wallet. Standard line: "Credits and purchases are specific to this app."
  • Backend already exists and is described by the owner's API Catalogue JSON, which can change at any time.
  • Web login, wallet and payments are out of scope for v1 (feature flags exist, default off).

1.3 Goals

# Goal Measured by
G1 Rank in Google for tool-related searches Impressions, clicks, indexed pages
G2 Visitors get a result in seconds without signing up Try completion rate; time to first result
G3 Drive installs of the correct app App-button taps, attributed installs, first edit in app
G4 Everything editable without code Add a tool or change a page in under 1 hour by editing JSON
G5 Fast, accessible, professional UI Core Web Vitals, accessibility audit
G6 Free-try cost under control Cost per processed photo; daily budget never exceeded
G7 Backend changes need no UI code change Add/remove/edit an endpoint by editing the catalogue/overlay only

1.4 Non-goals (v1)

  • Website login, wallet, credit purchase, subscriptions.
  • A full layered photo editor. Each tool has a focused try-it widget.
  • User-generated content, comments, marketplace.
  • A custom admin UI (Phase 2, §14). In v1, editing is by JSON with validation and preview.

1.5 Personas

Persona Needs Site must
Shop seller Clean product photos fast Land on the right tool, try it, open the product app
Creator Cutouts, effects, quick content Instant try, shareable results, creator app
Casual user Fix or restore a family photo Simple, trustworthy, no sign-up, clear privacy
Site owner Add tools, change copy, test layouts Edit JSON, preview, publish, see reports

1.6 Assumptions and dependencies

  • Backend endpoints are reachable over HTTPS from the site's server (not necessarily from browsers).
  • Endpoints currently return binary images (e.g. image/png) synchronously (see §7.3). Job-style (asynchronous) APIs may appear later and must be supported by configuration (§7.8).
  • App store listings, package names, App Store IDs and a deep-link provider are available before launch.
  • Brand assets, real before/after examples and legal text are supplied by the owner.

2. Principles and scope

2.1 Principles

Principle Meaning
Config over code Anything a non-engineer may change lives in JSON
Content is data, UI is a library Pages are lists of typed sections; sections are reusable components
SEO first Public pages arrive as complete server-rendered HTML
Safe by default JSON cannot run code; secrets stay server-side; bad config never takes the site down
Honest conversion The free try is genuinely useful; app buttons only point to apps that contain the tool
Fast and accessible Performance budgets and WCAG 2.2 AA are requirements
Extend, do not fork New tools, sections, languages, endpoints are added through playbooks (§15)
External catalogue is a moving target The site adapts to the catalogue; it does not copy it into code

2.2 Phases

Phase In scope Result
v1 (launch) Core pages, tool pages with try-it, app pages, app handoff, SEO engine, JSON config system, catalogue-driven API layer, analytics and consent, localisation framework (English first), CI checks Public launch
v1.1 More tools and use-case pages, second language, A/B tests, site search Growth
v2 Admin UI or CMS integration, catalogue upload with diff view, scheduled publishing, roles, version history Easy editing for non-developers
v3 (optional) Web login, shared account across apps, web wallet (behind flags), partner API Only if data justifies it

3. Information architecture and page inventory

Route Template Source Indexable Priority
/ Home pages/home.json Yes Must
/tools Tools index (search, categories) tools collection Yes Must
/tools/{slug} Tool page with try-it collections/tools/{slug}.json + templates/tool.json Yes Must
/categories/{slug} Category hub categories collection Yes Should
/use-cases/{slug} Use-case page (opens a tool with a preset) useCases collection Yes Should
/apps Apps index apps collection Yes Must
/apps/{slug} App page collections/apps/{slug}.json + templates/app.json Yes Must
/pricing Explainer: per-app pricing pages/pricing.json Yes Must
/learn, /guides/{slug} Guides guides (markdown) Yes Should
/trust, /privacy, /terms Trust and legal pages/*.json Yes Must
/about, /contact, /help Company, support pages/*.json Yes Should
/go/{tool}/{app} Tracked smart redirect to the app computed No Must
/api/try/{toolId} Try-it server route (§8) computed No Must
404 / 500 Friendly error pages pages/404.json No Must
/sitemap.xml, /robots.txt Generated from JSON computed n/a Must

3.1 URL rules

  • Lowercase, hyphenated, short slugs. Slugs are stable; changing one requires an entry in redirects.json.
  • No IDs or query strings in indexable URLs. Filters/sorting use noindex or canonical to the clean URL.
  • One trailing-slash policy, enforced by redirect.

3.2 Navigation

  • Header: logo, Tools (menu from categories), Use cases, Apps, Pricing, Learn, primary button "Get the app". All defined in site.config.json.
  • Footer: tools, apps, company, legal, language switcher, store badges.
  • Breadcrumbs on all sub-pages with matching structured data.
  • Mobile: simple menu sheet; slim "Open in app" bar only on tool and app pages (§9).

4. System architecture

 Visitor browser
      |
      v
 NEXT.JS WEBSITE (one deployment)
   - Renderer: JSON -> validated model -> sections -> HTML (static/ISR)
   - Try-it widget (client, lazy)
   - Server routes:  /api/try/{toolId}   /go/{tool}/{app}   /api/revalidate
      |                         |
      | read + validate         | server-side calls only (secrets here)
      v                         v
 CONTENT STORE             BACKEND APIs (owner)
  site.config.json          described by api.catalog.json
  pages/ templates/         + api.overlay.json (site settings)
  collections/ locales/
  api.catalog.json (replaceable)
  api.overlay.json

4.1 Technology decisions

Layer Decision Reason
Framework Next.js (App Router) + React + TypeScript (strict) Static/server rendering for SEO plus interactive widgets
Styling Tailwind CSS with tokens from JSON; accessible headless primitives (Radix or equivalent) Fast, consistent, themeable
Validation Zod (or JSON Schema) for every JSON file and backend response Safe config, typed models
Client data TanStack Query for try-it state; native fetch elsewhere Retries, cancellation
Localisation next-intl (or equivalent) with locale JSON Routing and translations
Images Framework image optimisation, AVIF/WebP, CDN Performance and SEO
Testing Vitest, Playwright, Storybook, Lighthouse CI, axe Quality gates
Hosting Any Node-capable host with CDN; the try-it route needs a request timeout long enough for image processing (target 60 s) Avoid vendor lock-in; do not use hosting whose function limit is shorter than backend processing time

4.2 Rendering strategy

Content Strategy Freshness
Home, tools, apps, guides, legal Static generation + incremental regeneration On-demand revalidation on publish; fallback timer (e.g. 10 min)
Try-it widget Client component, lazy loaded after main content Real time
/api/try/*, /go/* Server runtime Real time
Sitemap, robots Generated from JSON Same as pages

4.3 Page rendering pipeline

  1. Load JSON (local or remote) -> 2. Validate against schema -> 3. Resolve bindings and locale -> 4. Apply visibility rules -> 5. Map section type to component via registry -> 6. Emit HTML with SEO metadata, structured data and links.

4.4 Environments

  • Local: JSON from files; mock backend generated from the catalogue.
  • Preview: per-change preview URL (noindex, token protected) using draft JSON.
  • Staging: production-like, real test endpoints, search engines blocked.
  • Production: published JSON only, monitoring on.

4.5 Environment variables (never stored in JSON files)

Variable Purpose
CONTENT_SOURCE local or remote
CONTENT_BASE_URL, CONTENT_TOKEN Remote JSON location and read token
CATALOG_SOURCE file or url for api.catalog.json
CATALOG_PATH / CATALOG_URL, CATALOG_TOKEN Where the catalogue is read from
CATALOG_REFRESH_SECONDS Polling interval for remote catalogue (0 = webhook only)
API_SECRET_DEFAULT, API_SECRET_{GROUP} Backend secret keys referenced from api.overlay.json as env:NAME
REVALIDATE_SECRET Protects publish/reload webhooks
BOT_CHECK_SITE_KEY, BOT_CHECK_SECRET Bot protection for try-it
ANALYTICS_ID, SENTRY_DSN Analytics and error tracking
SITE_URL Canonical base URL

5. Configuration and content system

Everything an owner may want to change later is stored as JSON. The website reads it, validates it against a schema, and renders pages from it. Examples: Appendix A.

5.1 The JSON files

File / collection Controls Example change
site.config.json Brand, languages, theme tokens, navigation, footer, feature flags, SEO defaults, analytics, consent Colours, menu items, turn a feature on/off
pages/*.json Static pages: ordered sections with props, SEO fields, visibility rules Reorder home sections, change hero text
templates/*.json Section lists for collection pages using bindings Add an FAQ block to all tool pages
collections/tools/*.json One file per tool: names, summary, home app, try-it settings, endpoint reference, examples, FAQs, SEO Add a tool, change free-try limits
collections/apps/*.json One file per app: store links, deep-link settings, tools inside, screenshots, ratings New app, new store URL
`collections/categories useCases faqs
guides/*.md Long-form articles (safe markdown) Publish a guide
locales/{lang}.json Translated system strings and content overrides Add Hindi
api.catalog.json Owner's API Catalogue (external input, §7) Add/remove/edit endpoints
api.overlay.json Site-specific endpoint settings (§7.6) Enable/disable an endpoint, set limits
redirects.json Old URL to new URL Rename a slug safely

5.2 Core ideas

  • Pages are lists of sections. A section has id, type, optional variant, props, optional visibleWhen.
  • Collections hold reusable data. A tool page template pulls everything from one tool file, so adding a tool = adding one JSON file.
  • Bindings insert data: {{tool.name}}, {{tool.homeApp.name}}, {{site.brand.name}}. Lookup with optional default {{tool.name|Tool}}. No scripting.
  • References link records by id (homeApp, alsoIn, related, faqs, endpointRef). Broken references fail validation.
  • Localised fields are objects keyed by language ({"en": "...", "hi": "..."}); missing languages fall back to the default.
  • Visibility rules are declarative: device (mobile/desktop), locale, date range, flag, country (optional), A/B variant. No custom code.

5.3 Requirements

ID Requirement Priority Acceptance
CFG-01 All visible copy, nav, section order, theme tokens, CTA targets, SEO fields and limits come from JSON. Only system/error strings live in locale files. Must Change a JSON value, publish, site updates with no code change
CFG-02 Every JSON file is validated against a versioned schema at build and on every remote fetch. Must Invalid file: build fails (local) or last-good snapshot used + alert (remote)
CFG-03 Content source switchable between local files and remote JSON by one env variable. Must Same code runs both
CFG-04 A publish webhook triggers on-demand revalidation of affected pages. Must Page updates within 60 s of publish
CFG-05 Unknown section type or invalid props skips only that section, logs a warning, page still renders. Must Test with a deliberately broken section
CFG-06 Collection items have status: draft, published, archived. Only published items are public, in sitemap and nav. Must Draft returns 404 and is absent from sitemap
CFG-07 Reference integrity: ids in homeApp, alsoIn, related, faqs, nav, endpointRef must exist. Must Validation error lists file, field, bad id
CFG-08 Bindings support nested paths and defaults; a missing value never prints a raw placeholder. Must Unit tests
CFG-09 Visibility rules evaluated server-side where possible to avoid layout flicker. Should No visible shift
CFG-10 Preview mode shows drafts behind a secret token, always noindex. Should Preview not in sitemap, returns noindex
CFG-11 Schema versioning with migration scripts for old JSON. Should Old fixture migrates and validates
CFG-12 JSON never executes code. Rich text allows a safe markdown subset; embeds only from an allowlist (e.g. YouTube). Must Script/iframe injection test fails safely
CFG-13 Config is cached with a last-good snapshot so a content-store outage does not break the site. Must Simulated outage keeps site up

5.4 Publishing flow

  1. Edit JSON (repo in v1; admin/CMS in v2).
  2. Validate automatically: schema, references, SEO rules (title/description length, one H1, image alt), links, duplicate slugs, catalogue references.
  3. Preview on a preview URL with draft content.
  4. Publish (merge/press publish); content store updates; webhook revalidates pages and sitemap.
  5. Roll back by reverting to the previous version.

6. Section library

The renderer has a section registry: a table mapping a section type to a React component and its schema. New section types are added by registering a component. All sections support shared props: id, anchor, spacing, background (token), width, visibleWhen, analyticsName.

Section type Purpose Main props Used on
hero Headline, subtext, CTAs, optional try-it or media title, subtitle, ctas[], media, variant (tryit, split, centered) Home, tool, app
toolGrid Grid or tabs of tools source (collection/query), limit, columns, showCategory Home, tools, category
tryItWidget Upload and run a tool (§8) toolRef, options override, limits override Tool, use case, home
beforeAfter Comparison slider items[] (before, after, alt, caption) Tool, use case, guide
appCards Cards for apps with store badges source, apps[], layout, showRating Home, apps, footer
appHandoff Panel/bottom sheet opening a tool in its app toolRef, appRef, copy, bonus, qr, triggers Tool, result
availability "Available on Web / App A / App B" toolRef Tool
appPicker 3-question quiz recommending an app questions[], rules[] Home, apps
steps Numbered how-it-works items[] Tool, app
featureList Feature points with icons items[], columns App, home
screenshots Screenshot/video carousel items[] App
faq Expandable questions, optional FAQ markup faqRefs[] or items[], schema Tool, app, pricing
testimonials / ratings Real reviews and ratings items[], source Home, app
stats Key numbers (only if true) items[] Home
comparisonTable Compare apps or modes columns[], rows[] Apps, pricing
pricingExplainer Per-app pricing explanation with store links apps[], notes Pricing
relatedTools Auto/manual related tools toolRef, mode (auto/manual), limit Tool
richText Safe markdown markdown, toc Guides, legal
ctaBanner Call-to-action strip title, text, cta Any
notice Dismissible announcement text, level, expires Any
breadcrumbs Trail + structured data auto Sub-pages
gallery / logoCloud Image grids items[] Home, guides

6.1 Requirements

ID Requirement Priority Acceptance
SEC-01 Every section has a documented schema, defaults and a Storybook story for all variants. Must Story per type in CI
SEC-02 Sections are server-rendered where possible; interactive parts hydrate lazily. Must Page works without JS except the widget
SEC-03 Sections never hard-code colours, spacing or copy; they use tokens and props. Must Theme change updates all sections
SEC-04 Sections can be reordered, added, removed per page in JSON. Must Owner reorders home without code
SEC-05 Variants and spacing options give layout flexibility without custom CSS in JSON. Should At least 2 variants for hero, appCards, toolGrid
SEC-06 A new section type needs only a component, schema and registry entry. Must Playbook in §15

7. Backend API layer (catalogue-driven)

7.1 Two-layer model

The owner maintains the backend API documentation as a JSON file that can be changed at any time (endpoints added, removed or edited). The website must adapt automatically. Therefore the API layer has two inputs and one internal model:

Layer File Owned by Contains Changes how often
1. API Catalogue content/api.catalog.json Backend owner URLs, methods, parameters, response types, sub-endpoints, descriptions Any time
2. API Overlay content/api.overlay.json Website owner Which tools use which endpoint, enable/disable, limits, timeouts, variant labels, secrets mapping, parameter sources When site behaviour changes
3. Normalised model in memory (EndpointSpec[]) Code Catalogue + overlay merged and validated On every reload

Rules:

  • The catalogue is never edited by code and never copied into source files. It is read, normalised and cached.
  • Tools in collections/tools/*.json reference endpoints by catalogue id (and optionally a sub-endpoint), e.g. api-blemish-remover.
  • If an endpoint disappears from the catalogue, every tool using it is automatically marked unavailable (graceful message, app CTA still shown) and the build/validation report lists the affected tools.
  • The browser never receives the catalogue. It receives only a sanitised public view (tool options, limits, labels).

7.2 Catalogue format (as supplied by the owner)

The catalogue is a list of API groups. Each group has endpoints[]. The owner's sample is partial, so the loader must be tolerant (see §7.4). Observed fields:

Group level

Field Meaning (observed / assumed)
title, desc Group display name and description
api_key Group identifier such as Eye_Redness_Remover (appears to be a name, not a secret; see §7.13)
api_ip_link Group base URL, e.g. https://apigp0006.creinnovations.in/apis/mlm/eye_redness_remover/
chips Tags (empty in sample)
curl Example curl command (empty in sample)
endpoints[] Callable endpoints

Endpoint level

Field Meaning
id Stable unique id, e.g. api-blemish-remover, ml-eye-redness-remover (the id tools reference)
title, summary, desc Display text (note \u0026 is the & character; parse as normal JSON)
full_url Complete public URL to call (keep the trailing slash exactly)
path Path portion, e.g. /blemish_remover/image/
subpath Path relative to the group link (e.g. image/)
port Internal port (e.g. 8000); informational only, never used to build requests
method POST, or MULTI meaning "the real callable operations are listed in subs"
params[] Request parameters (below)
resp Response content type, e.g. image/png (binary image, not JSON)
subs[] Sub-endpoints (variants): d description, m method, p path
chips, curl As above

Parameter fields (params[])

Field Meaning (observed / assumed)
n Parameter name; this is the exact field name sent to the backend (e.g. image, secretKey)
ty Type text, e.g. file (binary), string
rq Required (boolean)
df Default value as text; "None" / empty means no default
ds Description
lc Location / encoding, e.g. multipart/form-data (assumed: where/how it is sent)
al Alias such as image0 (assumed informational; not used as the request field name)

7.3 Sample (sanitised excerpt of the owner's catalogue)

{
  "title": "Blemish_Remover",
  "endpoints": [
    {
      "id": "api-blemish-remover",
      "title": "Blemish_Remover",
      "summary": "AI acne, mole, wrinkle, and eye defect removal preserving natural skin pore texture.",
      "full_url": "https://apigp0006.creinnovations.in/apis/mlm/blemish_remover/image/",
      "path": "/blemish_remover/image/",
      "port": "8000",
      "method": "MULTI",
      "resp": "image/png",
      "params": [
        { "n": "image", "ty": "file (binary)", "rq": true, "df": "None", "al": "image0",
          "lc": "multipart/form-data", "ds": "Portrait photograph displaying blemishes or eye flaws." },
        { "n": "secretKey", "ty": "string", "rq": true, "df": "None", "al": "",
          "lc": "multipart/form-data", "ds": "Authentication: required authentication key." }
      ],
      "subs": [
        { "d": "Primary acne and blemish removal", "m": "POST", "p": "/blemish_remover/image/" },
        { "d": "Eye defect, iris clarity, and sclera correction", "m": "POST", "p": "/blemish_remover/eye_fix/" },
        { "d": "Full skin texture smoothening and pore tone balancing", "m": "POST", "p": "/blemish_remover/improver/" }
      ]
    }
  ]
}

Derived values (the loader must compute these):

Value Rule Example
baseUrl full_url with the trailing path removed (if full_url does not end with path, report a catalogue warning and skip the endpoint) https://apigp0006.creinnovations.in/apis/mlm
Callable URL (no variants) full_url .../apis/mlm/eye_redness_remover/image/
Callable URL (variant) baseUrl + sub.p .../apis/mlm/blemish_remover/eye_fix/
Variant id last non-empty segment of sub.p image, eye_fix, improver
Param kind from ty: contains file -> file; int -> integer; float/number/double -> number; bool -> boolean; json/object/array -> json; else string file (binary) -> file
Param location from lc: contains multipart or form-data -> multipart; x-www-form-urlencoded -> form; json -> json body; query -> query; header -> header; path -> path; unknown -> multipart multipart/form-data -> multipart
Default df unless None, null or empty none
Secret flag n matches secret, key, token, password, auth (case-insensitive) or ds mentions authentication secretKey -> secret

7.4 Loader requirements and algorithm

Algorithm (normaliseCatalog):

  1. Read the file or URL (CATALOG_SOURCE). Parse JSON.
  2. Find groups tolerantly: accept (a) an array of groups, (b) an object with a list under any key (e.g. apis, groups, data), (c) a single group, (d) a bare list of endpoints. Any object containing an endpoints array is a group.
  3. For each endpoint: sanitise text (strip control characters such as \u0007, trim, collapse whitespace), skip entries without id or full_url (log warning), check HTTPS, check full_url host against the allowlist (§7.11).
  4. Resolve derived values (table above), build variants from subs, build params list.
  5. Detect duplicate ids; the first wins, duplicates are reported.
  6. Merge with api.overlay.json (§7.6). Apply defaults.
  7. Compute a content hash. If the hash differs from the previous snapshot, store a diff report (added, removed, changed endpoints and which tools are affected).
  8. Save as the active snapshot and keep the previous last-good snapshot.
ID Requirement Priority Acceptance
CAT-01 The catalogue is loaded from CATALOG_SOURCE and is replaceable without a code change or redeploy (remote mode) or with a restart/revalidate (file mode). Must Replace file, endpoints change
CAT-02 Loader accepts the shapes in step 2 and ignores unknown fields. Must Fixture tests with 4 shapes
CAT-03 Invalid endpoints are skipped with a warning; one bad endpoint never breaks others. Must Corrupt one entry, others still work
CAT-04 A completely invalid catalogue keeps the last-good snapshot and raises an alert. Must Fault test
CAT-05 A diff report is produced on every change and shown in CI/admin. Should Report lists added/removed/changed ids
CAT-06 Tools referencing a missing endpoint or sub-endpoint are marked unavailable automatically and listed in the report. Must Remove endpoint, tool shows unavailable
CAT-07 New endpoints are usable by tools immediately after reload (no code). Must Add endpoint, reference it from a tool JSON, it works
CAT-08 Text from the catalogue (titles, summaries, descriptions) may be used as default tool copy but is overridable in tool JSON; it is escaped before display. Should Override works
CAT-09 Catalogue refresh by polling (CATALOG_REFRESH_SECONDS) and by a protected reload route (/api/admin/catalog/reload). Should Both work

7.5 Normalised internal model

interface ParamSpec {
  name: string;            // from n  (exact request field name)
  alias?: string;          // from al (informational)
  description?: string;    // from ds (never shown if isSecret)
  required: boolean;       // from rq
  kind: 'file'|'string'|'integer'|'number'|'boolean'|'json'|'unknown';
  rawType: string;         // original ty
  default?: string;        // from df unless None/empty
  location: 'multipart'|'form'|'json'|'query'|'header'|'path';
  isSecret: boolean;
  source: 'user.file'|'secret'|{ option: string }|{ constant: string }; // from overlay or inferred
}
interface VariantSpec { id: string; method: string; path: string; url: string; description?: string; label?: Localised }
interface EndpointSpec {
  id: string;              // catalogue id, the key tools reference
  groupKey?: string; groupTitle?: string;
  title: string; summary?: string; description?: string;
  method: 'GET'|'POST'|'PUT'|'DELETE'|'MULTI';
  url: string;             // full_url
  baseUrl: string;         // derived
  path: string;
  responseType: string;    // resp, e.g. image/png
  params: ParamSpec[];
  variants: VariantSpec[]; // empty if none
  enabled: boolean; publicTry: boolean;   // from overlay
  limits: { timeoutMs: number; retries: number; maxUploadMB: number; allowedMime: string[]; rateLimit: string };
  response: { kind: 'binary-image'|'json'|'job'; delivery: 'stream'|'signed-url' };
  hash: string;            // for change detection
}

7.6 API Overlay (api.overlay.json)

The catalogue describes what the backend offers. The overlay describes how this website uses it. It exists so that the backend owner's file stays untouched and everything site-specific is configurable.

Overlay key Meaning
defaults Default timeout, retries, max upload size, allowed mime types, rate-limit policy, response delivery
secrets Where secret values come from: default and byGroup / byEndpoint, always as env:NAME (never the real value)
allowedHosts Extra hosts allowed besides hosts found in the catalogue (usually empty)
rateLimits Named policies: per visitor per day, per IP per hour, daily total budget (calls)
endpoints.{id}.enabled Switch an endpoint off without touching the catalogue
endpoints.{id}.publicTry Whether visitors may try it on the website (some endpoints may be app-only or internal)
endpoints.{id}.response kind (binary-image, json, job) and delivery (stream or signed-url)
endpoints.{id}.paramSources For each parameter name: user.file, secret, option:<optionId>, constant:<value>, or hidden
endpoints.{id}.variants Friendly ids and labels for subs (shown as modes/options), plus optional per-variant parameter overrides
endpoints.{id}.limits Overrides for timeout, upload size, mime types, rate-limit policy
endpoints.{id}.errorMap Map backend status codes/messages to friendly message keys

Inference defaults (used when the overlay is silent):

  • A file param becomes user.file.
  • A secret param becomes secret and is read from secrets.
  • Other params with a default become constant:<df>; required params without a source cause the endpoint to be flagged misconfigured (not publicly usable) and listed in the report.
  • Sub-endpoints are assumed to accept the same params as the parent unless the overlay overrides them (see open question Q4).

7.7 Tool JSON references an endpoint

{
  "tryIt": {
    "enabled": true,
    "endpointRef": { "id": "api-blemish-remover", "defaultVariant": "image" },
    "variantControl": { "type": "radio", "label": { "en": "What should we fix?" } }
  }
}
  • If the endpoint has variants, the widget shows a variant control (radio, tabs or select) built from the overlay labels (fallback: sub d text).
  • If a variant is removed from the catalogue, it disappears from the control. If none remain, the tool becomes unavailable.

7.8 Request and response handling

Request building (server only):

  1. Pick endpoint + variant -> callable URL.
  2. For each param by location: multipart fields are appended with the exact name; secret params are filled from the environment; option: params from validated user options; constant: from config.
  3. Send with the endpoint timeoutMs; retries only when the overlay allows and the method is safe.

Response kinds:

resp / overlay kind Handling
image/* (binary) Verify Content-Type starts with image/, verify size cap, then deliver by stream (default: bytes go straight back to the browser, nothing stored) or signed-url (stored privately, expiring link)
application/json Parse, validate with the mapping in the overlay, return normalised TryItJob
Job style (future) Persist job id, poll or receive callback according to overlay, return normalised states

Normalised result shape returned to the browser:

type TryItResult =
  | { state: 'succeeded'; delivery: 'stream'|'signed-url'; resultUrl?: string; info?: { width?: number; height?: number; type: string } }
  | { state: 'failed'; error: { code: string; messageKey: string; retryable: boolean } }
  | { state: 'limit'; messageKey: string }
  | { state: 'unavailable'; messageKey: string };

7.9 Example overlay for the two sample endpoints

{
  "schemaVersion": "1.0",
  "defaults": { "timeoutMs": 60000, "retries": 0, "maxUploadMB": 10,
                "allowedMime": ["image/jpeg", "image/png", "image/webp"],
                "rateLimit": "tryit-default",
                "response": { "kind": "binary-image", "delivery": "stream" } },
  "secrets": { "default": "env:API_SECRET_DEFAULT" },
  "rateLimits": { "tryit-default": { "perVisitorPerDay": 3, "perIpPerHour": 20, "dailyBudgetCalls": 5000 } },
  "endpoints": {
    "api-blemish-remover": {
      "enabled": true, "publicTry": true,
      "paramSources": { "image": "user.file", "secretKey": "secret" },
      "variants": [
        { "id": "image",   "label": { "en": "Remove acne and blemishes" } },
        { "id": "eye_fix", "label": { "en": "Fix eye defects" } },
        { "id": "improver","label": { "en": "Smooth skin texture" } }
      ]
    },
    "ml-eye-redness-remover": {
      "enabled": true, "publicTry": true,
      "paramSources": { "image": "user.file", "secretKey": "secret" }
    }
  }
}

7.10 What happens when the catalogue changes

Change in api.catalog.json Effect on the website
New endpoint added Appears in the report as "unused"; usable by any tool via endpointRef; no code change
Endpoint removed Tools using it become unavailable automatically; app CTA stays; alert and report
URL or path changed New URL used after reload; no tool change
Parameter added (optional) Ignored unless overlay maps it; no break
Parameter added (required, no source) Endpoint flagged misconfigured and not publicly usable until overlay maps it
Parameter renamed Overlay paramSources must be updated; until then flagged misconfigured
Sub-endpoint added/removed Variant control updates automatically
Response type changed Handling follows resp; unsupported types flagged
Secret rotated Change the environment variable only; no JSON change

7.11 Security rules for the API layer

  • Secrets never leave the server. Not in the browser, bundles, logs, error messages, JSON files, analytics or the public catalogue view.
  • The ds text of a secret parameter can contain a key or key hint. It must be removed during sanitisation and never rendered (see §7.13 Q1).
  • Host allowlist (SSRF protection): only hosts that appear in the catalogue (HTTPS) or in overlay.allowedHosts may be called. User input is never used to build a URL.
  • Reject catalogue URLs that are not HTTPS, point to private/internal IP ranges, or use unexpected ports.
  • Enforce file type by content (signature), size and pixel limits before calling the backend; strip metadata when returning results if configured.
  • Rate limits and a daily total budget are enforced before every backend call; when the budget is exhausted, the tool shows the limit state and the app invitation.
  • Add a bot check (Turnstile or equivalent) token to every try-it submission.
  • Log request id, endpoint id, variant, status, duration; never log images, secrets or full multipart bodies.

7.12 API requirements

ID Requirement Priority Acceptance
API-01 All backend calls go through the server route /api/try/{toolId}; browsers never call backend URLs or hold secrets. Must Network inspection shows only the site domain; secrets absent from bundles
API-02 Endpoint behaviour is derived from catalogue + overlay; adding/changing an endpoint needs no UI code edit. Must Demonstrate with a new dummy endpoint
API-03 Incoming values are validated against ParamSpec (type, required, allowed values, file limits) before any backend call. Must Contract tests
API-04 Supports multipart (files and fields), form, JSON, query, path and header parameters; secrets via env reference. Must Test matrix
API-05 Supports synchronous binary-image responses (current), JSON responses and (optional) job-style polling/callback. Must E2E on a mock server for each kind
API-06 Variants (subs) are exposed as selectable modes; per-variant overrides supported. Must Blemish remover shows 3 modes
API-07 Timeouts, limited safe retries and a circuit breaker that marks a failing endpoint temporarily unavailable. Must Failure-injection test
API-08 Rate limits and a daily budget enforced server-side per visitor, IP and endpoint. Must Load test; budget breaker trips
API-09 SSRF protection via host allowlist. Must Security test
API-10 Request ids logged; no photo content or secrets in logs. Must Log review
API-11 A mock server is generated from the catalogue for local dev and CI. Should CI runs without the real backend
API-12 Endpoint health checks; failing endpoints flagged unavailable and alerted. Should Alert fires
API-13 Misconfigured endpoints (required param without source) are blocked from public use and listed in reports. Must Test
API-14 Response Content-Type and size are verified; unexpected content is rejected with a safe error. Must Fuzz test

7.13 Open questions (confirm with the backend owner; code must keep these configurable)

# Question Assumption used until answered
Q1 What is secretKey? Is it one key shared by all endpoints or per group? The description text in the sample appears to contain a key or key hint; if it is a real key, rotate it and keep it only in environment variables. One default secret, overridable per group/endpoint
Q2 Is api_key (e.g. Eye_Redness_Remover) only a group identifier? Yes, an identifier, not a secret
Q3 What does method: "MULTI" mean exactly, and does the parent full_url also work, or only subs? Only subs are callable when MULTI; the parent full_url equals the first/primary variant
Q4 Do all subs accept the same parameters as the parent? Yes
Q5 Meaning of lc and al? lc = encoding/location; al informational
Q6 Top-level shape of the catalogue file (array, object, key name)? Tolerant loader handles all
Q7 Error format (HTTP codes, JSON error body, rate-limit headers)? HTTP status based; unknown -> generic error
Q8 Max input size/pixels, supported formats, typical processing time, cost per call? 10 MB, jpg/png/webp, timeout 60 s
Q9 Which endpoints may be exposed to anonymous visitors? Only those with publicTry: true in the overlay
Q10 Does the backend keep uploaded images? For how long? Unknown; privacy page text must be confirmed
Q11 Are image/png responses always the final image (no async job)? Yes

8. Try-it experience (free tool widget)

The widget is the main conversion tool of each tool page. It must feel instant, safe and clear. It is generated from the tool JSON (options, limits, copy) and the endpoint resolved from the catalogue/overlay (§7).

8.1 Flow (current backend: synchronous, returns an image)

  1. Browser POST /api/try/{toolId} with multipart/form-data: image, variant, options, bot-check token.
  2. Server validates: file signature, size, pixels, bot token, rate limits, daily budget.
  3. Server resolves endpoint + variant from catalogue/overlay and builds the backend request (secret added server-side).
  4. Backend returns image bytes (e.g. image/png).
  5. Server verifies content type and size, then returns the result by stream (default) or signed-url.
  6. Browser shows before/after, download (standard quality) and the app invitation.

8.2 States

State User sees Notes
Idle Drop zone, sample photos, allowed formats and size Samples allow trying without upload
Selected Thumbnail, variant/options (generated), Run button Client validation
Uploading / Processing Progress with estimated time range, Cancel Synchronous calls show indeterminate progress
Success Before/after slider, Download, app button Remaining free tries shown
Limit reached Friendly message + app invitation with welcome bonus Counts enforced server-side
Error Plain message, Try again, help link Retryable errors offer one-tap retry
Unavailable "Temporarily unavailable" + app or other tool From circuit breaker, flag or missing endpoint

8.3 Requirements

ID Requirement Priority Acceptance
TRY-01 Controls (variant, select, toggle, slider, text) are generated from tool options and endpoint variants. Must New option appears after JSON edit only
TRY-02 Upload by drag and drop, file picker, paste; on phones, gallery and camera. Must Tests on iOS and Android
TRY-03 Client checks type, size and pixel limits from JSON; server re-checks by content. Must Bad files rejected clearly
TRY-04 HEIC/HEIF and EXIF orientation handled (convert or clear message). Should iPhone photos work
TRY-05 No sign-in. Visitor token + bot check + server limits prevent abuse. Must Bots blocked; limits hold in common cases
TRY-06 Limits (per day, per tool, resolution, daily budget) come from JSON; counters and messages from the server. Must Limit change needs no deploy
TRY-07 Result shows before/after, standard-quality download and result CTA to the home app. Must CTA visible without scrolling on common screens
TRY-08 Accessibility: keyboard use, focus management, aria-live state announcements, alt text. Must axe + manual screen-reader pass
TRY-09 Privacy notice near upload: what happens to the photo and retention (text from JSON). Must Notice present, editable
TRY-10 Widget code is lazy-loaded and does not delay first paint. Must LCP/INP budgets met
TRY-11 Default delivery is stream (no storage of results). If signed-url is used, links are unguessable and expire quickly. Must Access test after expiry
TRY-12 Analytics events for each state; no photo content. Must Event test
TRY-13 Optional watermark / size / quality limits per tool from JSON. Could Setting changes output
TRY-14 For face/portrait tools: consent reminder, abuse-report link, and the ability to switch a tool off instantly (kill switch). Must Switch works without deploy

9. App handoff and conversion

9.1 Requirements

ID Requirement Priority Acceptance
APP-01 Each tool has exactly one homeApp; alsoIn lists other apps that really contain it. Buttons: "Open {tool} in {app}". Must Validation fails if missing or app lacks the tool
APP-02 Store links, package names, App Store IDs and deep-link settings come from app JSON. Must Editing app JSON updates every button
APP-03 /go/{tool}/{app} detects platform: Android deep link or Play listing; iPhone universal link or App Store; desktop -> app page with QR. Must Real-device tests
APP-04 Deep links open the app on the specific tool and carry source, campaign and bonus parameters; deferred deep links via the chosen link provider. Must Install then open lands on the tool
APP-05 Desktop: QR code, plus optional "send me the link" (email/SMS/WhatsApp, consent required). Should QR opens correct app
APP-06 Result panel shows the app invitation after a result; at limit, shows the limit message with the app button. Must Right states
APP-07 Mobile web: slim bottom bar/sheet, dismissible, remembered for the session. No full-screen pop-up on arrival. Must No intrusive interstitial
APP-08 Optional iPhone smart banner / Android equivalent per page via JSON. Could Flag works
APP-09 Welcome bonus: link adds a bonus code; copy and amount editable in JSON; the app honours it. Reward installs/first use only, never ratings or reviews. Should Install with code credits user in app
APP-10 App pages show screenshots, tool list (linking to tool pages), real ratings, reviews and "Credits and purchases are specific to this app." Must Present on all app pages
APP-11 Pricing page explains per-app pricing and links to each store listing; no web prices. Must No web checkout in v1
APP-12 App picker quiz recommends an app from JSON rules. Could Quiz maps answers to apps
APP-13 Ratings and review counts come from real data with a source field; never invented. Must Source required
Visitor Goes to Fallback
Android, app installed Deep link to the tool Play listing with campaign tags
iPhone, app installed Universal link to the tool App Store / custom product page
Mobile, not installed Store listing, then deferred deep link after install Web app page
Desktop App page with QR, badges, send-link Store listing in a new tab

10. SEO requirements

ID Requirement Priority Acceptance
SEO-01 All public pages return complete HTML (title, H1, text, links, images, metadata) without JavaScript. Must View-source and fetch-as-Google test
SEO-02 Every page has seo.title, seo.description, canonical, Open Graph and Twitter tags from JSON, with fallbacks from site defaults/templates. Must Validator confirms presence and uniqueness
SEO-03 Title about 50-60 characters, description about 140-155; warn outside range, error if missing or duplicate. Must CI lint
SEO-04 Exactly one H1 per page; logical heading order. Must CI lint
SEO-05 XML sitemaps (split by type) from published, indexable JSON items with lastmod; robots.txt generated. Must Only canonical indexable URLs
SEO-06 Canonical on every page; filters, search, preview URLs are noindex/canonicalised. Must Crawl test
SEO-07 Structured data per type: Organization + WebSite (home), BreadcrumbList (sub-pages), WebApplication/SoftwareApplication (tool, app), Article (guides). FAQ markup optional. Must describe visible, accurate content; ratings only from real sources. Must Rich result test, no errors
SEO-08 Internal linking engine: related tools, parent category, home app and guides linked automatically from JSON relationships; crawlable menu/footer. Must No orphan pages
SEO-09 Images: next-gen formats, width/height, lazy loading below the fold, mandatory alt text (validated). Must CI lint, Lighthouse
SEO-10 hreflang and localised URLs only for pages with real translations; x-default set. Should Alternates validate
SEO-11 301 redirects from redirects.json; no chains; 404 page returns 404. Must Crawl test
SEO-12 Core Web Vitals budgets met on mobile (§13). Must Lighthouse CI + RUM
SEO-13 Dynamic Open Graph images per tool and app. Should Share preview check
SEO-14 Quality gate: a page cannot be indexable unless it has unique title and description, at least one real example image, and FAQ or how-it-works content (minimum fields configurable). Must Publishing blocked otherwise
SEO-15 Staging/preview blocked by noindex and authentication; Search Console and analytics verification via config. Must Staging not indexed
SEO-16 Pages for tools whose endpoint is unavailable stay indexable with an "unavailable" notice and app CTA (avoid dropping rankings); a long-term removal uses 301 or 410 via redirects.json. Should Behaviour test

Tool page SEO template: Title {tool.name} Free Online | {brand}; description = what it does + free try + app mention; H1 = plain promise using the search phrase; URL /tools/{slug}; structured data WebApplication + BreadcrumbList; 3-5 related-tool links, home-app link, 1-2 guides; 3 real before/after examples with alt text.


11. UI/UX and design system

11.1 Direction

  • Professional, clean, trustworthy; generous white space; the photo results are the hero.
  • One system of colours, type, spacing, radius, shadow and motion defined as design tokens in site.config.json.
  • Light and dark mode (dark can be switched off by flag). Respect reduced-motion.
  • Mobile-first: thumb-friendly controls, no hover-only actions.

11.2 Tokens controlled by JSON

Group Examples
Colour primary, accent, background, surface, text, muted, success, warning, error, dark-mode values
Typography font families (system fallback), size scale, weights, line-height
Spacing and layout spacing scale, max width, section rhythm, grid columns
Shape radius, border width, shadows
Motion durations, easing, enable/disable
Component variants button, card, badge styles

11.3 Tool page layout (each block is a JSON section)

1 hero (breadcrumb, H1, one-line promise)
2 tryItWidget (upload, variants/options, run)
3 beforeAfter (real examples)
4 appHandoff (result panel: "Get full quality in the app")
5 steps (how it works)
6 availability (Web | App A | App B, home app first)
7 faq (+ honest limits)
8 relatedTools + ctaBanner

11.4 Key screens

Screen Layout notes
Home Hero with headline and try-it box; popular job tiles; app strip; examples; app picker; trust; FAQ
Tools index Search, category filters, grid of tool cards (image, name, one line, app badges)
Tool page As above; on phones the result panel is a bottom sheet with one main button
App page Screenshots, store badges, QR; best-at points; tools inside; reviews; FAQ; credits line
Pricing Plain explanation; one card per app linking to its listing
Guide Readable layout with table of contents, inline CTA, related guides

11.5 Requirements

ID Requirement Priority Acceptance
UI-01 Responsive 320-1920 px; breakpoints in tokens. Must Visual tests at 5 widths
UI-02 WCAG 2.2 AA: contrast, focus, keyboard, target sizes, labels, errors, skip link, landmarks. Must axe + manual audit
UI-03 Consistent loading (skeleton), empty and error states for every dynamic block. Must Story coverage
UI-04 No layout shift: reserve space for images, widgets and banners. Must CLS under 0.1
UI-05 Microcopy: plain words, consistent button labels, honest cost and limit messages; copy lives in JSON. Must Copy review
UI-06 Compact, accessible consent banner that does not block content. Must Manual test
UI-07 Dark mode and token changes apply across all components without code edits. Should Theme switch test
UI-08 One icon set (SVG sprites). Should Review

ID Requirement Priority Acceptance
AN-01 Consent management before non-essential tracking, with regional settings from config (e.g. India DPDP, EU/UK GDPR). Must No tracking before consent where required
AN-02 One tracking helper implements the event list (Appendix B) with toolId, appId, pageType, locale, device and campaign. Must Events visible in analytics debug
AN-03 UTM/campaign parameters captured on landing and passed to /go links and deep links. Must End-to-end test
AN-04 No photo content, signed URLs, tokens, secrets or personal data in analytics events. Must Payload review
AN-05 Funnel dashboard: visit, try start, try success, app button, store view, install, first edit in app. Should Dashboard available
AN-06 A/B hooks: section variants chosen by an experiment id in JSON. Could One test runs
AN-07 Privacy pages editable from JSON; retention period for try-it photos stated and enforced (default: not stored on the website; confirm backend retention, Q10). Must Policy matches behaviour

13. Non-functional requirements

Area Requirement
Performance (mobile, p75) LCP at or under 2.5 s (target 2.0 s), INP under 200 ms, CLS under 0.1. Initial JavaScript on public pages as small as possible (target under 100 KB compressed excluding the lazy try-it widget)
Lighthouse (CI) Performance, Accessibility, Best Practices at least 90; SEO at least 95 on all templates
Availability Static pages served from CDN even if the backend, content store or catalogue source is down; hosting target 99.9%
Security HTTPS only, HSTS, strict CSP, secure headers, dependency scanning, secrets in environment only, input validation, file-signature checks, rate limits, bot protection, SSRF protection, no sensitive data in logs
Privacy Try-it photos private; results streamed (not stored) by default; clear notice; no training use without consent
Scalability CDN caching absorbs spikes; try-it limited by budget and rate limits, not by web servers
Reliability If an endpoint fails the tool shows "temporarily unavailable" and offers the app; last-good config and catalogue snapshots
Browser support Current evergreen browsers, iOS Safari and Android Chrome from the last few major versions
Maintainability TypeScript strict, lint, documented schemas, stories, conventional commits
Observability Error tracking, uptime checks, real-user performance, endpoint health and call-volume dashboards, alerting on catalogue diffs and budget breaches
Localisation RTL-ready layout; dates, numbers via locale formatting

14. Content management and admin (Phase 2)

In v1, the owner edits JSON files in a repository with automatic validation and preview. Phase 2 adds a friendlier editor without changing the JSON format.

ID Requirement Priority Acceptance
ADM-01 Admin UI or headless CMS reading/writing the same schemas, with forms generated from schemas. Should Edit a tool in forms; JSON validates
ADM-02 Roles: owner, editor, SEO, translator, viewer. Should Permissions tested
ADM-03 Draft, preview, schedule, publish; version history; one-click rollback. Should Rollback works
ADM-04 Image upload with optimisation and required alt text. Should Upload test
ADM-05 Live SEO checker in the editor. Could Warnings visible
ADM-06 Audit log of changes. Should Log exists
ADM-07 Catalogue manager: upload a new api.catalog.json, see the diff (added/removed/changed, affected tools), test an endpoint with a sample image, then apply. Should Upload, diff, apply, rollback
ADM-08 Overlay editor with validation (unmapped params, unused endpoints, unavailable tools). Should Warnings shown

15. Extensibility playbooks (acceptance tests for the architecture)

Task Steps Code change?
Add a new tool 1) Ensure the endpoint exists in api.catalog.json. 2) Add collections/tools/{slug}.json with endpointRef. 3) Add example images. 4) Set homeApp. 5) Add overlay entry if defaults are not enough. 6) Validate, preview, publish No
Add an endpoint Add it to api.catalog.json (or replace the file); reload; reference it from a tool No
Remove an endpoint Remove from catalogue; review the report; tools show unavailable; update or archive them No
Change a backend URL/param Edit the catalogue; fix overlay.paramSources if a name changed No
Rotate a secret Change the environment variable No
Add a new app collections/apps/{slug}.json with store IDs and deep-link settings; list its tools No
Change layout or text Edit section order, variants or text in page JSON No
Change look and feel Edit theme tokens in site.config.json No
Add a language Add locale in site.config.json, locales/{lang}.json and translated fields No (check RTL)
Add a page pages/{name}.json + navigation entry No
Add a new section type Create component, schema, story; register in the section registry Yes (small)
Turn on a feature (e.g. web login later) Switch the flag; feature module exists behind the flag only when built Only when built
Run an A/B test Two variants + experiment id in page JSON No

16. Repository structure and conventions

site/
  app/                       routes: [locale]/..., api/try/[toolId], go/[tool]/[app], api/admin/*
  components/sections/       hero, toolGrid, tryItWidget, faq, ... (one folder per section)
  components/ui/             buttons, cards, dialog, tabs, form controls
  lib/config/                loaders (local/remote), schemas, binding engine, rules engine
  lib/catalog/               loader, tolerant parser, normaliser, overlay merge, diff, snapshots
  lib/api/                   request builder, response handlers, rate limits, budget, circuit breaker, mock generator
  lib/seo/                   metadata, sitemap, structured data, validators
  lib/analytics/             consent, tracker, events
  content/
    site.config.json  api.catalog.json  api.overlay.json  redirects.json
    pages/  templates/  collections/{tools,apps,categories,useCases,faqs,testimonials}/
    guides/  locales/  schemas/
  scripts/                   validate-content, catalog-diff, generate-mock-api, check-seo, link-check
  tests/                     unit, contract, e2e, accessibility, performance
  docs/                      playbooks, runbooks
  • Schemas are the single source of truth for validation and (later) editor forms.
  • Every pull request runs: type check, lint, unit tests, content validation, catalogue validation and diff, SEO lint, link check, contract tests on the mock API, accessibility tests, Lighthouse.
  • Naming: stable ids (api-blemish-remover, img.background.remove), slugs for URLs, camelCase JSON keys in site-owned files (the catalogue keeps its own key style).

17. Quality assurance and acceptance

Area Tests Pass condition
Config system Schema, reference, binding, rules, fallback, broken-section tests Invalid content never crashes the site
Catalogue Fixtures for each accepted shape; corrupt entry; duplicate ids; removed endpoint; renamed param; new endpoint Behaviour matches §7.10
Playbooks Perform every task in §15 on a clean checkout Done by a non-author within the stated steps
API route Contract tests per endpoint (mock), failure injection (timeout, 500, wrong content type), rate and budget tests Safe errors; no secret leakage
Try-it E2E on Chrome, Safari, Firefox; iOS and Android; big and small images; HEIC; cancel; limit reached; variants Matches §8
App handoff Real-device tests: installed, not installed, desktop QR Lands on correct tool
SEO Crawl, sitemap, canonical, structured data validation, view-source, Search Console after launch No errors; all public pages indexable
Accessibility Automated + manual keyboard and screen reader No serious issues
Performance Lighthouse CI + real-user monitoring Budgets in §13
Security Dependency scan, header check, SSRF and upload tests, review of secret handling No high issues
Content Copy, examples, legal, translations reviewed Owner sign-off

Definition of done (launch):

  • All Must requirements pass their acceptance criteria.
  • At least 5 launch tools live with real examples and a working try-it.
  • Every app has an app page and working deep links for its tools.
  • Sitemap submitted; staging blocked; analytics and consent verified.
  • Runbooks exist: publish, rollback, catalogue change, API outage, budget breaker, tool kill switch, secret rotation.
  • The owner has performed the playbooks (add tool, change text, change catalogue/overlay) without developer help.

18. Milestones, risks and inputs

Milestone Duration Deliverables
M0 Discovery 1 week Answers to §7.13, sample catalogue + test credentials, tool/app inventory, home-app list, brand assets, keyword list
M1 Foundation 2 weeks Repo, tokens and UI kit, config loader and schemas, renderer, section registry, core sections, home and tools index
M2 Tools and API 2 weeks Catalogue loader/normaliser/diff, overlay, /api/try, mock server, try-it widget, first 2-3 real endpoints, rate limits, bot check
M3 Apps and SEO 2 weeks App pages, /go redirects, deep links, tracking, sitemap, structured data, redirects, localisation framework
M4 Hardening and launch 1-2 weeks Remaining tools, accessibility, performance, security review, content QA, launch checklist
M5 Growth ongoing More tools and use-case pages, A/B tests, second language, admin/CMS (Phase 2)

Indicative team: 1 product owner, 2 frontend/full-stack engineers, 1 backend/integration engineer (part-time), 1 designer, 1 SEO/content person, QA support.

18.1 Risks

Risk Mitigation
Catalogue changes break tools Tolerant loader, diff report, last-good snapshot, automatic "unavailable" state, contract tests on every change
Secret leaks Env-only secrets, sanitisation of secret descriptions, log redaction, security review, rotate if exposed
Free tries cost too much Limits and daily budget, bot check, circuit breaker
Too much flexibility makes config messy Strict schemas, validators, limited section catalogue, documentation
Thin or duplicate SEO pages Quality gate blocks indexing until requirements are met
Users disappointed after app handoff Home-app rule, honest labels, validation of app-tool relationships
Hosting timeouts on slow image processing Choose Node hosting with long enough request time; timeouts in overlay
Photo privacy or misuse (face tools) Stream-only results, consent reminder, abuse reporting, kill switch
Store rule issues for bonuses Reward installs/first use only; expert review

18.2 Inputs needed before M1

  • Brand name, logo, colours, fonts, tone of voice.
  • Tools and apps list with the home app for each tool.
  • The full api.catalog.json, answers to §7.13, test secret key and a staging backend.
  • Store URLs, package names, App Store IDs, deep-link provider account.
  • Analytics and Search Console accounts, hosting and domain.
  • Launch languages; privacy policy, terms, photo retention policy.
  • Real before/after example images (with permission) and app screenshots.

Appendix A. JSON examples

Field names are the recommended standard; the schema files in content/schemas/ are the final authority.

A.1 site.config.json (excerpt)

{
  "schemaVersion": "1.0",
  "brand": { "name": "StudioName", "logo": "/brand/logo.svg",
             "tagline": { "en": "Edit photos in seconds" } },
  "locales": { "default": "en", "supported": ["en", "hi"] },
  "theme": {
    "colors": { "primary": "#2563EB", "accent": "#0E9F9A", "background": "#FFFFFF", "text": "#0F1F3D",
                "dark": { "background": "#0B1220", "text": "#E5E9F2" } },
    "font": { "heading": "Inter, system-ui, sans-serif", "body": "Inter, system-ui, sans-serif" },
    "radius": "12px", "maxWidth": "1200px", "motion": true
  },
  "nav": {
    "header": [
      { "label": { "en": "Tools" }, "href": "/tools", "children": "collection:categories" },
      { "label": { "en": "Apps" }, "href": "/apps" },
      { "label": { "en": "Pricing" }, "href": "/pricing" },
      { "label": { "en": "Learn" }, "href": "/learn" }
    ],
    "cta": { "label": { "en": "Get the app" }, "href": "/apps" }
  },
  "features": { "tryIt": true, "appPicker": true, "darkMode": true, "webAccounts": false, "webWallet": false },
  "seo": { "titleTemplate": "%s | StudioName", "defaultOgImage": "/og/default.png" },
  "analytics": { "provider": "ga4", "id": "env:ANALYTICS_ID", "consent": "required" }
}

A.2 pages/home.json (excerpt)

{
  "id": "home", "route": "/", "status": "published",
  "seo": { "title": { "en": "Free Online Photo Tools | StudioName" },
           "description": { "en": "Remove blemishes, backgrounds and more. Try free now, get full quality in the app." },
           "indexable": true },
  "sections": [
    { "id": "hero", "type": "hero", "variant": "tryit",
      "props": { "title": { "en": "Edit photos in seconds" },
                 "subtitle": { "en": "Try free. Get full quality in our apps." },
                 "tryIt": { "toolRef": "face.blemish.remove" } } },
    { "id": "popular", "type": "toolGrid", "props": { "source": "featured", "limit": 8, "columns": 4 } },
    { "id": "apps", "type": "appCards", "props": { "source": "all", "showRating": true } },
    { "id": "quizHint", "type": "notice", "visibleWhen": { "device": "mobile", "flag": "appPicker" },
      "props": { "text": { "en": "Not sure which app? Take the 30-second quiz." } } }
  ]
}

A.3 collections/tools/blemish-remover.json

{
  "id": "face.blemish.remove", "slug": "blemish-remover", "status": "published",
  "category": "portrait-retouch",
  "name": { "en": "Blemish Remover" },
  "summary": { "en": "Remove acne, marks and eye defects while keeping natural skin texture." },
  "homeApp": "portrait-app", "alsoIn": [],
  "tryIt": {
    "enabled": true,
    "endpointRef": { "id": "api-blemish-remover", "defaultVariant": "image" },
    "variantControl": { "type": "radio", "label": { "en": "What should we fix?" } },
    "limits": { "perDay": 3, "maxMB": 10, "maxPixels": 16000000, "formats": ["jpg", "png", "webp", "heic"] },
    "result": { "quality": "standard", "showAppCta": true }
  },
  "content": {
    "steps": [ { "en": "Upload a portrait" }, { "en": "Choose what to fix" }, { "en": "Download or open in the app" } ],
    "faqs": ["faq.blemish.free", "faq.blemish.privacy", "faq.blemish.app"],
    "examples": [ { "before": "/ex/blemish-before.jpg", "after": "/ex/blemish-after.png",
                    "alt": { "en": "Portrait before and after blemish removal" } } ]
  },
  "related": ["face.eyeredness.remove"],
  "seo": { "title": { "en": "Remove Blemishes from Photo Free | StudioName" },
           "description": { "en": "Remove acne and blemishes from portraits in seconds. Try free, then get full quality in the app." } }
}

A.4 collections/apps/portrait-app.json

{
  "id": "portrait-app", "slug": "portrait-app", "status": "published",
  "name": { "en": "Portrait App" },
  "tagline": { "en": "Natural portrait retouching" },
  "stores": {
    "android": { "packageId": "com.example.portrait", "url": "https://play.google.com/store/apps/details?id=com.example.portrait" },
    "ios": { "appId": "1234567890", "url": "https://apps.apple.com/app/id1234567890" }
  },
  "deepLink": { "base": "https://link.example.com/portrait", "toolParam": "tool", "sourceParam": "src", "bonusParam": "promo" },
  "tools": ["face.blemish.remove", "face.eyeredness.remove"],
  "rating": { "value": 4.6, "count": 1200, "source": "store-data" },
  "creditsNote": { "en": "Credits and purchases are specific to this app." }
}

A.5 Example normalised EndpointSpec (result of the loader for the sample)

{
  "id": "ml-eye-redness-remover",
  "groupKey": "Eye_Redness_Remover",
  "title": "Eye Redness & Flash Sclera Corrector",
  "method": "POST",
  "url": "https://apigp0006.creinnovations.in/apis/mlm/eye_redness_remover/image/",
  "baseUrl": "https://apigp0006.creinnovations.in/apis/mlm",
  "path": "/eye_redness_remover/image/",
  "responseType": "image/png",
  "params": [
    { "name": "image", "required": true, "kind": "file", "location": "multipart", "isSecret": false, "source": "user.file" },
    { "name": "secretKey", "required": true, "kind": "string", "location": "multipart", "isSecret": true, "source": "secret" }
  ],
  "variants": [],
  "enabled": true, "publicTry": true,
  "limits": { "timeoutMs": 60000, "retries": 0, "maxUploadMB": 10,
              "allowedMime": ["image/jpeg", "image/png", "image/webp"], "rateLimit": "tryit-default" },
  "response": { "kind": "binary-image", "delivery": "stream" }
}

Appendix B. Analytics events

Event When Key properties
page_view Every page pageType, locale, device, campaign, referrer
tool_viewed Tool page loaded toolId, homeApp
tryit_started File selected toolId, fileType, sizeBucket
tryit_submitted Run pressed toolId, variant, non-sensitive options
tryit_succeeded / tryit_failed Result or error toolId, durationMs, errorCode
tryit_limit_reached Limit shown toolId
result_downloaded Download clicked toolId
app_cta_shown / app_cta_clicked Invitation shown/tapped toolId, appId, placement, platform
store_redirect /go served toolId, appId, platform, campaign
qr_shown / sendlink_submitted Desktop handoff toolId, appId
app_picker_completed Quiz finished recommendedAppId
related_tool_clicked Related link fromToolId, toToolId
consent_updated Consent changed categories
catalog_changed (server) Catalogue reload with changes added, removed, changed counts

Appendix C. Per-page SEO and launch checklist

  • Unique title (50-60 chars) and description (140-155 chars)
  • One H1 with the main search phrase; logical headings
  • Server-rendered content visible in view-source
  • Canonical correct; indexable flag correct
  • 3+ internal links in and out; breadcrumb present
  • Real example images with alt text, dimensions, next-gen format
  • Structured data valid and matches visible content
  • Try-it works from upload to result; app button correct for the tool
  • Mobile layout and speed checked; no intrusive pop-ups
  • In sitemap; not blocked by robots; no redirect chain
  • Analytics events firing; consent respected

Appendix D. Glossary

Term Meaning
PRD Product Requirements Document
JSON Text format for structured data read by the site
Schema Rules describing what a JSON file may contain
Section Reusable page block controlled by JSON
Collection Group of similar records (tools, apps)
Binding Placeholder such as {{tool.name}} replaced by data
API Catalogue Owner's JSON describing backend endpoints (api.catalog.json)
API Overlay Site-specific settings for endpoints (api.overlay.json)
Variant A sub-endpoint (subs) of a MULTI endpoint shown as a mode
Normalised model Internal merged form of catalogue + overlay (EndpointSpec)
Home app The one app a tool sends people to
Deep link Link opening a specific screen in an app
Circuit breaker Safety switch pausing calls to a failing service
ISR Pre-built pages refreshed when content changes

Appendix E. Prompt templates (copy and paste)

E.1 Build the foundation

Read the attached PRD (PRD_Dynamic_JSON_Driven_Photo_Tools_Website.md). Implement Milestone M1:
repo setup (Next.js App Router, TypeScript strict, Tailwind), config loader (local+remote),
Zod schemas for site.config, pages, templates, collections, the binding engine, visibility rules,
the section registry with these sections: hero, toolGrid, appCards, steps, faq, richText, ctaBanner,
breadcrumbs, and the home + tools index pages. Follow PRD §0.3 rules, CFG-01..13, SEC-01..06.
Include unit tests and a README. Do not hard-code any copy. Ask before deviating from the PRD.

E.2 Implement the catalogue-driven API layer

Using PRD §7 and Appendix A.5: implement lib/catalog (tolerant loader for api.catalog.json, normaliser to
EndpointSpec, overlay merge, diff report, last-good snapshot) and the server route /api/try/[toolId]
(multipart upload, validation, rate limits, daily budget, bot check, backend call, binary image
response by stream). Secrets only from env via overlay. Requirements: CAT-01..09, API-01..14, TRY-03,05,06,11.
Provide a mock server generated from the catalogue and tests for: added/removed endpoint, renamed param,
corrupt entry, wrong content type. Use the sample catalogue in §7.3 as a fixture.

E.3 Add a tool

Follow PRD §15 "Add a new tool". Endpoint id: <id>. Tool slug: <slug>. Home app: <appId>.
Create collections/tools/<slug>.json, any overlay entry needed, and show the validation output.
Do not change source code.

E.4 Review the catalogue change

Here is the new api.catalog.json. Compare it with the previous version using the diff rules in PRD §7.4 and §7.10.
List added/removed/changed endpoints, affected tools, misconfigured endpoints and required overlay changes.