commit 6ede33ccdbb1433f90c3ab8306deba1573d3d06d Author: wehub-resource-sync Date: Mon Jul 13 13:33:44 2026 +0800 chore: import upstream snapshot with attribution diff --git a/.cursor/rules/ponytail.mdc b/.cursor/rules/ponytail.mdc new file mode 100644 index 0000000..db435a7 --- /dev/null +++ b/.cursor/rules/ponytail.mdc @@ -0,0 +1,36 @@ +--- +description: Ponytail, lazy senior dev mode. Always pick the simplest solution that works. +globs: +alwaysApply: true +--- + +# Ponytail, lazy senior dev mode + +You are a lazy senior developer. Lazy means efficient, not careless. The best code is the code never written. + +Before writing any code, stop at the first rung that holds: + +1. Does this need to be built at all? (YAGNI) +2. Does it already exist in this codebase? Reuse the helper, util, or pattern that's already here, don't re-write it. +3. Does the standard library already do this? Use it. +4. Does a native platform feature cover it? Use it. +5. Does an already-installed dependency solve it? Use it. +6. Can this be one line? Make it one line. +7. Only then: write the minimum code that works. + +The ladder runs after you understand the problem, not instead of it: read the task and the code it touches, trace the real flow end to end, then climb. + +Bug fix = root cause, not symptom: a report names a symptom. Grep every caller of the function you touch and fix the shared function once — one guard there is a smaller diff than one per caller, and patching only the path the ticket names leaves a sibling caller still broken. + +Rules: + +- No abstractions that weren't explicitly requested. +- No new dependency if it can be avoided. +- No boilerplate nobody asked for. +- Deletion over addition. Boring over clever. Fewest files possible. +- Shortest working diff wins, but only once you understand the problem. The smallest change in the wrong place isn't lazy, it's a second bug. +- Question complex requests: "Do you actually need X, or does Y cover it?" +- Pick the edge-case-correct option when two stdlib approaches are the same size, lazy means less code, not the flimsier algorithm. +- Mark intentional simplifications with a `ponytail:` comment. If the shortcut has a known ceiling (global lock, O(n²) scan, naive heuristic), the comment names the ceiling and the upgrade path. + +Not lazy about: understanding the problem (read it fully and trace the real flow before picking a rung, a small diff you don't understand is just laziness dressed up as efficiency), input validation at trust boundaries, error handling that prevents data loss, security, accessibility, the calibration real hardware needs (the platform is never the spec ideal, a clock drifts, a sensor reads off), anything explicitly requested. Lazy code without its check is unfinished: non-trivial logic leaves ONE runnable check behind, the smallest thing that fails if the logic breaks (an assert-based demo/self-check or one small test file; no frameworks, no fixtures). Trivial one-liners need no test. diff --git a/.cursor/skills/alert-manager/SKILL.md b/.cursor/skills/alert-manager/SKILL.md new file mode 100644 index 0000000..3cece47 --- /dev/null +++ b/.cursor/skills/alert-manager/SKILL.md @@ -0,0 +1,337 @@ +--- +name: alert-manager +description: 'Configure SEO alerts for ranking drops, traffic changes, technical issues, competitor movements. SEO预警/排名监控' +version: "6.0.0" +license: Apache-2.0 +compatibility: "Claude Code ≥1.0, skills.sh marketplace, ClawHub marketplace, Vercel Labs skills ecosystem. No system packages required. Optional: MCP network access for SEO tool integrations." +homepage: "https://github.com/aaron-he-zhu/seo-geo-claude-skills" +when_to_use: "Use when setting up monitoring alerts for rankings, traffic, backlinks, technical issues, or AI visibility changes." +argument-hint: " [metric]" +metadata: + author: aaron-he-zhu + version: "6.0.0" + geo-relevance: "low" + tags: + - seo + - geo + - seo-alerts + - ranking-alerts + - traffic-monitoring + - competitor-alerts + - automated-monitoring + - anomaly-detection + - SEO预警 + - SEOアラート + - SEO알림 + - alertas-seo + triggers: + # EN-formal + - "set up SEO alerts" + - "monitor rankings" + - "ranking notifications" + - "traffic alerts" + - "competitor alerts" + - "automated monitoring" + # EN-casual + - "notify me when rankings drop" + - "alert me if rankings drop" + - "notify me of traffic changes" + - "watch competitor changes" + - "watch my keywords for changes" + - "alert me about changes" + # EN-question + - "how to monitor my rankings" + - "how to set up SEO alerts" + # ZH-pro + - "SEO预警" + - "排名监控" + - "流量报警" + - "竞品变动提醒" + # ZH-casual + - "排名掉了提醒我" + - "流量异常" + - "有变化通知我" + # JA + - "SEOアラート" + - "ランキング監視" + # KO + - "SEO 알림" + - "순위 모니터링" + # ES + - "alertas SEO" + - "monitoreo de rankings" + # PT + - "alertas de SEO" + # Misspellings + - "SEO allerts" +--- + +# Alert Manager + + +> **[SEO & GEO Skills Library](https://github.com/aaron-he-zhu/seo-geo-claude-skills)** · 20 skills for SEO + GEO · [ClawHub](https://clawhub.ai/u/aaron-he-zhu) · [skills.sh](https://skills.sh/aaron-he-zhu/seo-geo-claude-skills) +> **System Mode**: This monitoring skill follows the shared [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md) and [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md). + + +Sets up proactive monitoring alerts for critical SEO and GEO metrics. Triggers notifications when rankings drop, traffic changes significantly, technical issues occur, or competitors make moves. + +**System role**: Monitoring layer skill. It turns performance changes into deltas, alerts, and next actions. + +## When This Must Trigger + +Use this when the conversation involves any of these situations — even if the user does not use SEO terminology: + +Use this whenever the task needs time-aware change detection, escalation, or stakeholder-ready visibility. + +- Setting up SEO monitoring systems +- Creating ranking drop alerts +- Monitoring technical SEO health +- Tracking competitor movements +- Alerting on content performance changes +- Monitoring GEO/AI visibility changes +- Setting up brand mention alerts + +## What This Skill Does + +1. **Alert Configuration**: Sets up custom alert thresholds +2. **Multi-Metric Monitoring**: Tracks rankings, traffic, technical issues +3. **Threshold Management**: Defines when alerts trigger +4. **Priority Classification**: Categorizes alerts by severity +5. **Notification Setup**: Configures how alerts are delivered +6. **Alert Response Plans**: Creates action plans for each alert type +7. **Alert History**: Tracks alert patterns over time + +## Quick Start + +Start with one of these prompts. Finish with a short handoff summary using the repository format in [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md). + +### Set Up Alerts + +``` +Set up SEO monitoring alerts for [domain] +``` + +``` +Create ranking drop alerts for my top 20 keywords +``` + +### Configure Specific Alerts + +``` +Alert me when [specific condition] +``` + +``` +Set up competitor monitoring for [competitor domains] +``` + +### Review Alert System + +``` +Review and optimize my current SEO alerts +``` + +## Skill Contract + +**Expected output**: a delta summary, alert/report output, and a short handoff summary ready for `memory/monitoring/`. + +- **Reads**: current metrics, previous baselines, alert thresholds, and reporting context from [CLAUDE.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CLAUDE.md) and the shared [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md) when available. +- **Writes**: a user-facing monitoring deliverable plus a reusable summary that can be stored under `memory/monitoring/`. +- **Promotes**: significant changes, confirmed anomalies, and follow-up actions to `memory/open-loops.md` and `memory/decisions.md`. +- **Next handoff**: use the `Next Best Skill` below when a change needs action. + +## Data Sources + +> **Note:** All integrations are optional. This skill works without any API keys — users provide data manually when no tools are connected. + +> See [CONNECTORS.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CONNECTORS.md) for tool category placeholders. + +**With ~~SEO tool + ~~search console + ~~web crawler connected:** +Automatically monitor real-time metric feeds for ranking changes via ~~SEO tool API, indexing and coverage alerts from ~~search console, and technical health alerts from ~~web crawler. Set up automated threshold-based alerts with notification delivery. + +**With manual data only:** +Ask the user to provide: +1. Current baseline metrics for alert thresholds (rankings, traffic, backlinks) +2. Critical keywords or pages to monitor +3. Alert priority levels and notification preferences +4. Historical data to understand normal fluctuation ranges +5. Manual reporting on metric changes when they check their tools + +Proceed with the alert configuration using provided parameters. User will need to manually check metrics and report changes for alert triggers. + +## Instructions + +When a user requests alert setup: + +1. **Define Alert Categories** + + ```markdown + ## SEO Alert System Configuration + + **Domain**: [domain] + **Configured Date**: [date] + + ### Alert Categories + + | Category | Description | Typical Urgency | + |----------|-------------|-----------------| + | Ranking Alerts | Keyword position changes | Medium-High | + | Traffic Alerts | Organic traffic fluctuations | High | + | Technical Alerts | Site health issues | Critical | + | Backlink Alerts | Link profile changes | Medium | + | Competitor Alerts | Competitor movements | Low-Medium | + | GEO Alerts | AI visibility changes | Medium | + | Brand Alerts | Brand mentions and reputation | Medium | + ``` + +2. **Configure Alert Rules by Category** + + For each relevant category (Rankings, Traffic, Technical, Backlinks, Competitors, GEO/AI, Brand), define alert name, trigger condition, threshold, and priority level. + + > **Reference**: See [references/alert-configuration-templates.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/monitor/alert-manager/references/alert-configuration-templates.md) for complete alert tables, threshold examples, and response plan templates for all 7 categories. + +3. **Define Alert Response Plans** + + Map each priority level (Critical, High, Medium, Low) to a response time and immediate action steps. + +4. **Set Up Alert Delivery** + + Configure notification channels (Email, SMS, Slack), recipient routing by role, suppression rules (duplicate cooldown, maintenance windows), and escalation paths. + +5. **Create Alert Summary** + + ```markdown + # SEO Alert System Summary + + **Domain**: [domain] + **Configured**: [date] + **Total Active Alerts**: [X] + + ## Alert Count by Category + + | Category | Critical | High | Medium | Low | Total | + |----------|----------|------|--------|-----|-------| + | Rankings | [X] | [X] | [X] | [X] | [X] | + | Traffic | [X] | [X] | [X] | [X] | [X] | + | Technical | [X] | [X] | [X] | [X] | [X] | + | Backlinks | [X] | [X] | [X] | [X] | [X] | + | Competitors | [X] | [X] | [X] | [X] | [X] | + | GEO | [X] | [X] | [X] | [X] | [X] | + | **Total** | **[X]** | **[X]** | **[X]** | **[X]** | **[X]** | + + ## Quick Reference + + ### If You Get a Critical Alert + + 1. Don't panic + 2. Check alert details + 3. Follow response plan + 4. Document actions taken + 5. Update stakeholders + + ### Weekly Alert Review Checklist + + - [ ] Review all alerts triggered + - [ ] Identify patterns + - [ ] Adjust thresholds if needed + - [ ] Update response plans + - [ ] Clean up false positives + ``` + +## Validation Checkpoints + +### Input Validation +- [ ] Alert thresholds are based on realistic baseline data +- [ ] Critical keywords and pages clearly identified +- [ ] Response plans defined for each alert priority level +- [ ] Notification channels configured with appropriate recipients + +### Output Validation +- [ ] Every metric cites its data source and collection date +- [ ] Alert thresholds account for normal metric fluctuations +- [ ] Response plans are specific and time-bound +- [ ] Source of each alert trigger clearly stated (~~SEO tool API alert, ~~search console notification, ~~web crawler alert, or manual user check) + +## Example + +**User**: "Set up ranking drop alerts for my top keywords" + +**Output**: + +```markdown +## Ranking Alert Configuration + +### Critical Keywords (Immediate Alert) + +| Keyword | Current | Alert If | Priority | +|---------|---------|----------|----------| +| best project management software | 2 | Drops to 5+ | 🔴 Critical | +| project management tools | 4 | Drops to 8+ | 🔴 Critical | +| team collaboration software | 1 | Any drop | 🔴 Critical | + +### Important Keywords (Same-Day Alert) + +| Keyword | Current | Alert If | Priority | +|---------|---------|----------|----------| +| agile project management | 7 | Drops out of top 10 | 🔴 High | +| kanban software | 9 | Drops out of top 10 | 🔴 High | + +### Alert Response Plan + +**If Critical Keyword Drops**: +1. Check if page is still indexed (site:url) +2. Look for algorithm update announcements +3. Analyze what changed in SERP +4. Review competitor ranking changes +5. Check for technical issues on page +6. Create recovery action plan within 24 hours + +**Notification**: Email + Slack to SEO team immediately +``` + +## Tips for Success + +1. **Start simple** - Don't create too many alerts initially +2. **Tune thresholds** - Adjust based on normal fluctuations +3. **Avoid alert fatigue** - Too many alerts = ignored alerts +4. **Document response plans** - Know what to do when alerts fire +5. **Review regularly** - Alerts need maintenance as your SEO matures +6. **Include positive alerts** - Track wins, not just problems + +## Alert Threshold Quick Reference + +| Metric | Warning | Critical | Frequency | +|--------|---------|----------|-----------| +| Organic traffic | -15% WoW | -30% WoW | Daily | +| Keyword positions | >3 position drop | >5 position drop | Daily | +| Pages indexed | -5% change | -20% change | Weekly | +| Crawl errors | >10 new/day | >50 new/day | Daily | +| Core Web Vitals | "Needs Improvement" | "Poor" | Weekly | +| Backlinks lost | >5% in 1 week | >15% in 1 week | Weekly | +| AI citation loss | Any key query | >20% queries | Weekly | +| Security issues | Any detected | Any detected | Daily | + +> **Reference**: See [references/alert-threshold-guide.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/monitor/alert-manager/references/alert-threshold-guide.md) for baseline establishment, threshold setting methodology, fatigue prevention, escalation paths, and response playbooks. + + +### Save Results + +After delivering monitoring data or reports to the user, ask: + +> "Save these results for future sessions?" + +If yes, write a dated summary to `memory/monitoring/YYYY-MM-DD-.md` containing: +- One-line headline finding or status change +- Top 3-5 actionable items +- Open loops or anomalies requiring follow-up +- Source data references + +If any findings should influence ongoing strategy, recommend promoting key conclusions to `memory/hot-cache.md`. + +## Reference Materials + +- [Alert Threshold Guide](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/monitor/alert-manager/references/alert-threshold-guide.md) — Recommended thresholds by metric, fatigue prevention strategies, and escalation path templates + +## Next Best Skill + +- **Primary**: [rank-tracker](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/monitor/rank-tracker/SKILL.md) — pair alerts with a baseline measurement workflow. diff --git a/.cursor/skills/animation-vocabulary/SKILL.md b/.cursor/skills/animation-vocabulary/SKILL.md new file mode 100644 index 0000000..cd0af50 --- /dev/null +++ b/.cursor/skills/animation-vocabulary/SKILL.md @@ -0,0 +1,173 @@ +--- +name: animation-vocabulary +description: Reverse-lookup glossary that turns a vague description of a web animation or motion effect into its exact term ("the bouncy thing when a popover opens" → Pop in; "the iOS rubber-band scroll" → Rubber-banding). Use when the user asks "what's it called when…", or describes a motion effect without knowing its name and wants the right word to prompt an AI or designer with. For naming an effect, not designing or building one. +--- + +# Animation Vocabulary + +Turn a vague description of a motion or effect into the precise term, so the user knows what to ask for. + +## Quick Start + +The user describes an effect loosely. You return the matching term(s) in this format: + +``` +**Stagger** — Animate several items one after another with a small delay between each, creating a cascade. +``` + +If several terms could fit, list the best match first, then 1–2 alternates with a one-line note on how they differ. + +## Instructions + +1. **Read for intent, not keywords.** Users describe what they *see* or *feel* ("springy", "slides off", "draws itself in"), not the technical name. Map the sensation to the glossary below. +2. **Quote the glossary verbatim.** Its descriptions are authoritative — use them as-is, don't paraphrase. +3. **Disambiguate close terms.** When two compete (*Clip-path* vs *Mask*, *Pop in* vs *Bounce*, *Shared element transition* vs *Layout animation*), contrast them so the user can pick. +4. **When nothing matches exactly,** name the closest term and say plainly it's an approximation, or describe the effect in the glossary's vocabulary (e.g. "that's a *stagger* of *scale-in* entrances"). +5. **Stay within this glossary.** If a term genuinely isn't here, say so rather than inventing one — though you may explain the concept using these words. +6. **Keep it tight.** A naming question wants a name, not an essay. Lead with the term; expand only if asked. + +## Examples + +**Example 1 — feel-based** +User: "What's it called when a popover seems to grow out of the button you clicked instead of from its middle?" +Output: +``` +**Origin-aware animation** — An element animates out of its trigger, like a popover growing from the button that opened it instead of from its own center which is the default in CSS. +``` + +**Example 2 — disambiguation** +User: "The thing where one image turns into another image." +Output: +``` +**Morph** — One shape smoothly turns into another shape, e.g. Dynamic Island. + +Close alternates: +- **Crossfade** — if they simply fade over each other in the same spot. +- **Shared element transition** — if an element travels and transforms from one position into another. +``` + +**Example 3 — physics feel** +User: "That iOS scroll where it resists and snaps back when you pull too far." +Output: +``` +**Rubber-banding** — Resistance and snap-back when you drag past a boundary (the iOS overscroll feel). +``` + +## Glossary + +_A curated snapshot mirroring the project's `/vocabulary` page; keep the two in sync when either changes._ + +### Entrances & Exits — how elements appear and disappear +- **Fade in / Fade out** — Element appears or disappears by changing opacity. +- **Slide in** — Element enters by sliding in from off-screen (left, right, top, or bottom). +- **Scale in** — Element grows from smaller to full size as it appears, often paired with a fade. +- **Pop in** — Element appears with a slight overshoot, like it bounces into place. +- **Reveal** — Content is uncovered gradually, often by animating a clip-path or mask. +- **Enter / Exit** — The animation an element plays when it's added to or removed from the screen. + +### Sequencing & Timing — coordinating multiple elements or moments +- **Keyframes** — Defined points in an animation (0%, 50%, 100%) that the browser fills the gaps between. +- **Interpolation / Tween** — Generating all the in-between frames between a start and end value, so motion is continuous. +- **Stagger** — Animate several items one after another with a small delay between each, creating a cascade. +- **Orchestration** — Deliberately timing multiple animations so they feel like one coordinated motion. +- **Delay** — Time before an animation starts. +- **Duration** — How long an animation takes. +- **Fill mode** — Whether an element keeps its first or last frame's styles before the animation starts or after it ends (e.g. forwards). +- **Stepped animation** — An animation that is divided into discrete steps, like a countdown timer. + +### Movement & Transforms — changing an element's position, size, or angle +- **Translate** — Move an element along the X or Y axis. +- **Scale** — Make an element bigger or smaller. +- **Rotate** — Spin an element around a point. +- **Skew** — Slant an element along the X or Y axis, shearing it out of its rectangular shape. +- **3D tilt / Flip** — Rotate in 3D space (rotateX / rotateY) to add depth. +- **Perspective** — How strong the 3D effect looks — a lower value exaggerates depth, like the viewer is closer. +- **Transform origin** — The anchor point a scale or rotation grows or spins from. +- **Origin-aware animation** — An element animates out of its trigger, like a popover growing from the button that opened it instead of from its own center which is the default in CSS. + +### Transitions Between States — connecting one state, view, or element to another +- **Crossfade** — One element fades out as another fades in, in the same spot. +- **Continuity transition** — A change that keeps the user oriented by visually connecting before and after. For example, making the same rectangle bigger and smaller. +- **Morph** — One shape smoothly turns into another shape, e.g. Dynamic Island. +- **Shared element transition** — An element travels and transforms from one position into another, like a thumbnail expanding into a card. +- **Layout animation** — When an element's size or position changes, it animates to the new spot instead of snapping. +- **Accordion / Collapse** — A section smoothly expands and collapses its height to show or hide content. +- **Direction-aware transition** — Content slides one way going forward and the opposite way going back, so navigation has a sense of direction. + +### Scroll — motion tied to scrolling or navigating between views +- **Scroll reveal** — Elements fade or slide into place as they enter the viewport. +- **Scroll-driven animation** — An animation whose progress is tied directly to scroll position. +- **Parallax** — Background and foreground move at different speeds while scrolling, creating depth. +- **Page transition** — An animation that plays when navigating from one page or route to another. +- **View transition** — The browser morphs between two states or pages, connecting shared elements. + +### Feedback & Interaction — responding to the user's actions +- **Hover effect** — Visual change when the cursor moves over an element. +- **Press / Tap feedback** — A subtle scale-down when an element is clicked, so it feels physical. +- **Hold to confirm** — A progress effect that fills up while the user holds a button. +- **Drag** — Moving an element by grabbing it, often with momentum when released. +- **Drag to reorder** — Dragging items in a list to rearrange them, while the others shift to make room. +- **Swipe to dismiss** — Dragging an element off-screen to close it, like a drawer or toast. +- **Rubber-banding** — Resistance and snap-back when you drag past a boundary (the iOS overscroll feel). +- **Shake / Wiggle** — A quick side-to-side jitter signaling an error or rejected input. +- **Ripple** — A circle expanding from the point of a tap, confirming the press. + +### Easing — how speed changes over an animation +- **Easing** — The rate at which an animation speeds up or slows down. +- **Ease-out** — Starts fast, ends slow. The default for most UI and anything responding to the user. +- **Ease-in** — Starts slow, ends fast. Usually avoided; can feel sluggish. +- **Ease-in-out** — Slow, fast, slow. Good for elements already on screen moving from A to B. +- **Linear** — Constant speed. Avoid for UI; reserve for spinners or marquees. +- **Cubic-bezier** — A custom easing curve you define for precise control. +- **Asymmetric easing** — A curve that accelerates and decelerates at different rates. Feels more alive than a symmetric one. + +### Spring Animations — physics-based motion as an alternative to fixed-duration easing +- **Spring** — Motion driven by physics (tension, mass, damping) rather than a set duration. +- **Stiffness / Tension** — How strongly the spring pulls toward its target. Higher feels snappier. +- **Damping** — How quickly a spring settles. Lower damping means more bounce and oscillation. +- **Mass** — How heavy the animated element feels. More mass makes it slower and more sluggish. +- **Bounce** — A spring that overshoots and settles, adding playfulness. +- **Perceptual duration** — How long a spring feels finished, even though it keeps micro-settling underneath. +- **Momentum** — Motion that carries velocity, especially after a drag or interruption. +- **Velocity** — How fast and in which direction an element is moving. A spring carries it into the next animation when interrupted, so a flicked element keeps its speed. +- **Interruptible animation** — An animation that can be smoothly redirected mid-flight instead of finishing first. + +### Looping & Ambient Motion — animations that run on their own +- **Marquee** — Text or content that scrolls continuously in a loop. +- **Loop** — An animation that repeats, a set number of times or infinitely. +- **Alternate (yoyo)** — A loop that plays forward then reverses each iteration, instead of jumping back to the start. +- **Orbit** — An element circling around another in a continuous path. +- **Pulse** — A gentle repeating scale or opacity change to draw attention. +- **Float** — A gentle, continuous up-and-down drift that makes a static element feel alive and weightless. +- **Idle animation** — Subtle motion that plays while an element is just sitting there, waiting to be interacted with. + +### Polish & Effects — the small touches that separate good from great +- **Blur** — A blur filter used to soften an element or mask tiny imperfections. +- **Clip-path** — Clipping an element to a shape, used for reveals, masks, and before/after sliders. +- **Mask** — Hiding or revealing parts of an element using a shape or gradient — like clip-path, but with soft, fadeable edges. +- **Before / after slider** — A draggable divider that wipes between two overlaid images to compare them. +- **Line drawing** — An SVG path that draws itself in, like an invisible pen tracing it. +- **Text morph** — Text that animates character by character when it changes, drawing attention to the new value. +- **Skeleton / Shimmer** — A placeholder with a moving sheen shown while content loads. +- **Number ticker** — Digits rolling or counting up to a value. +- **Tabular numbers** — Fixed-width digits so numbers don't shift around as they change. Essential for tickers, timers, and counters. +- **Typewriter** — Text appearing one character at a time, as if being typed. + +### Performance — what keeps motion smooth instead of stuttering +- **Frame rate (FPS)** — Frames drawn per second. 60fps is the baseline for smooth motion; 120fps on newer displays. +- **Jank** — Visible stutter when the browser drops frames because it can't keep up with the animation. +- **Dropped frame** — A frame the browser missed its deadline to draw, causing a tiny hitch in motion. +- **Compositing** — Letting the GPU move or fade an element on its own layer without redoing layout or paint. +- **will-change** — A CSS hint that an element is about to animate, so the browser can promote it to its own layer ahead of time. +- **Layout thrashing** — Animating properties like width, height, top, or left that force the browser to recalculate layout every frame, causing jank. + +### Principles to Know — concepts that guide when and how to animate +- **Purposeful animation** — Motion should serve a function — orient, give feedback, show relationships — not just decorate. +- **Anticipation** — A small wind-up in the opposite direction before a move, hinting at what's about to happen. +- **Follow-through** — Parts of an element keep moving and settle slightly after the main motion stops, adding weight. +- **Squash & stretch** — Deforming an element as it moves to convey weight, speed, and flexibility. +- **Perceived performance** — The right animation makes an interface feel faster, even when it isn't. +- **Frequency of use** — The more often a user sees an animation, the shorter and subtler it should be. +- **Spatial consistency** — Animating so an element keeps its identity and position across states, so users never lose track of where things went. +- **Hardware acceleration** — Animating transform and opacity lets the GPU keep motion smooth. +- **Reduced motion** — Respecting the user's prefers-reduced-motion setting by toning down or removing motion. diff --git a/.cursor/skills/backlink-analyzer/SKILL.md b/.cursor/skills/backlink-analyzer/SKILL.md new file mode 100644 index 0000000..ce0a2e7 --- /dev/null +++ b/.cursor/skills/backlink-analyzer/SKILL.md @@ -0,0 +1,301 @@ +--- +name: backlink-analyzer +description: 'Analyze backlink profiles: link authority, toxic links, building opportunities, competitor link gaps. 外链分析/反向链接' +version: "6.0.0" +license: Apache-2.0 +compatibility: "Claude Code ≥1.0, skills.sh marketplace, ClawHub marketplace, Vercel Labs skills ecosystem. No system packages required. Optional: MCP network access for SEO tool integrations." +homepage: "https://github.com/aaron-he-zhu/seo-geo-claude-skills" +when_to_use: "Use when analyzing backlink profiles, link quality, toxic links, referring domains, or anchor text distribution." +argument-hint: "" +metadata: + author: aaron-he-zhu + version: "6.0.0" + geo-relevance: "low" + tags: + - seo + - backlinks + - link-building + - link-profile + - toxic-links + - off-page-seo + - link-audit + - referring-domains + - disavow + - ahrefs-alternative + - 外链分析 + - 被リンク + - 백링크 + - backlinks-seo + triggers: + # EN-formal + - "analyze backlinks" + - "check link profile" + - "find toxic links" + - "link building opportunities" + - "link profile analysis" + - "backlink audit" + - "link quality" + # EN-casual + - "who links to me" + - "I have spammy links" + - "how do I get more backlinks" + - "how do I get more links" + - "disavow links" + - "link building outreach" + - "disavow file" + # EN-question + - "how to build backlinks" + - "how to find toxic backlinks" + # ZH-pro + - "外链分析" + - "反向链接" + - "有毒链接" + - "链接建设" + # ZH-casual + - "外链怎么做" + - "有垃圾外链" + - "谁链接到我" + - "友链" + - "互换友链" + - "外链建设" + # JA + - "被リンク分析" + - "バックリンク" + - "リンク構築" + # KO + - "백링크 분석" + - "링크 빌딩" + - "누가 내 사이트 링크해?" + - "백링크 어떻게 늘려?" + # ES + - "análisis de backlinks" + - "enlaces entrantes" + # PT + - "análise de backlinks" + # Misspellings + - "backlink anaylsis" + - "backlnk analysis" +--- + +# Backlink Analyzer + + +> **[SEO & GEO Skills Library](https://github.com/aaron-he-zhu/seo-geo-claude-skills)** · 20 skills for SEO + GEO · [ClawHub](https://clawhub.ai/u/aaron-he-zhu) · [skills.sh](https://skills.sh/aaron-he-zhu/seo-geo-claude-skills) +> **System Mode**: This monitoring skill follows the shared [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md) and [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md). + + +Analyzes, monitors, and optimizes backlink profiles. Identifies link quality, discovers opportunities, and tracks competitor link building activities. + +**System role**: Monitoring layer skill. It turns performance changes into deltas, alerts, and next actions. + +## When This Must Trigger + +Use this when the conversation involves any of these situations — even if the user does not use SEO terminology: + +Use this whenever the task needs time-aware change detection, escalation, or stakeholder-ready visibility. + +- Auditing your current backlink profile +- Identifying toxic or harmful links +- Discovering link building opportunities +- Analyzing competitor backlink strategies +- Monitoring new and lost links +- Evaluating link quality for outreach +- Preparing for link disavow + +## What This Skill Does + +1. **Profile Analysis**: Comprehensive backlink profile overview +2. **Quality Assessment**: Evaluates link authority and relevance +3. **Toxic Link Detection**: Identifies harmful links +4. **Competitor Analysis**: Compares link profiles across competitors +5. **Opportunity Discovery**: Finds link building prospects +6. **Trend Monitoring**: Tracks link acquisition over time +7. **Disavow Guidance**: Helps create disavow files + +## Quick Start + +Start with one of these prompts. Finish with a short handoff summary using the repository format in [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md). + +### Analyze Your Profile + +``` +Analyze backlink profile for [domain] +``` + +### Find Opportunities + +``` +Find link building opportunities by analyzing [competitor domains] +``` + +### Detect Issues + +``` +Check for toxic backlinks on [domain] +``` + +### Compare Profiles + +``` +Compare backlink profiles: [your domain] vs [competitor domains] +``` + +## Skill Contract + +**Expected output**: a delta summary, alert/report output, and a short handoff summary ready for `memory/monitoring/`. + +- **Reads**: current metrics, previous baselines, alert thresholds, and reporting context from [CLAUDE.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CLAUDE.md) and the shared [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md) when available. +- **Writes**: a user-facing monitoring deliverable plus a reusable summary that can be stored under `memory/monitoring/`. +- **Promotes**: significant changes, confirmed anomalies, and follow-up actions to `memory/open-loops.md` and `memory/decisions.md`. +- **Next handoff**: use the `Next Best Skill` below when a change needs action. + +## Data Sources + +> **Note:** All integrations are optional. This skill works without any API keys — users provide data manually when no tools are connected. + +> See [CONNECTORS.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CONNECTORS.md) for tool category placeholders. + +**With ~~link database + ~~SEO tool connected:** +Automatically pull comprehensive backlink profiles including referring domains, anchor text distribution, link quality metrics (DA/DR), link velocity, and toxic link detection from ~~link database. Competitor backlink data from ~~SEO tool for gap analysis. + +**With manual data only:** +Ask the user to provide: +1. Backlink export CSV (with source domains, anchor text, link type) +2. Referring domains list with authority metrics +3. Competitor domains for comparison +4. Recent link gains/losses if tracking changes +5. Any known toxic or spammy links + +Proceed with the full analysis using provided data. Note in the output which metrics are from automated collection vs. user-provided data. + +## Instructions + +When a user requests backlink analysis: + +1. **Generate Profile Overview** -- Key metrics (total backlinks, referring domains, DA/DR, dofollow ratio), link velocity (30d/90d/year), authority distribution chart, profile health score. + +2. **Analyze Link Quality** -- Top quality backlinks table, link type distribution, anchor text analysis (brand/exact/partial/URL/generic), geographic distribution. + +3. **Identify Toxic Links** -- Toxic score, risk indicators by type (spam, PBN, link farms, irrelevant), high-risk links to review, disavow recommendations (domain-level and URL-level). + +4. **Compare Against Competitors** -- Profile comparison table (referring domains, DA/DR, velocity, avg link DA), unique referring domains, link intersection analysis, competitor content attracting most links. + +5. **Find Link Building Opportunities** -- Link intersection prospects, broken link opportunities, unlinked mentions, resource page opportunities, guest post prospects, priority matrix (effort vs impact). + +6. **Track Link Changes** -- New and lost links for last 30 days with DA, type, anchor, dates. Net change and links to recover. + +7. **Generate Backlink Report** -- Executive summary, strengths, concerns, opportunities, competitive position, recommended actions (immediate/short-term/long-term), KPIs to track. + + > **Reference**: See [references/analysis-templates.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/monitor/backlink-analyzer/references/analysis-templates.md) for complete output templates for all 7 steps above. + +### CITE Item Mapping + +When running `domain-authority-auditor` after this analysis, the following data feeds directly into CITE scoring: + +| Backlink Metric | CITE Item | Dimension | +|----------------|-----------|-----------| +| Referring domains count | C01 (Referring Domain Volume) | Citation | +| Authority distribution (DA breakdown) | C02 (Referring Domains Quality) | Citation | +| Link velocity | C04 (Link Velocity) | Citation | +| Geographic distribution | C10 (Link Source Diversity) | Citation | +| Dofollow/Nofollow ratio | T02 (Dofollow Ratio Normality) | Trust | +| Toxic link analysis | T01 (Link Profile Naturalness), T03 (Link-Traffic Coherence) | Trust | +| Competitive link intersection | T05 (Profile Uniqueness) | Trust | + +## Validation Checkpoints + +### Input Validation +- [ ] Target domain backlink data is complete and current +- [ ] Competitor domains specified for comparison analysis +- [ ] Backlink data includes necessary fields (source domain, anchor text, link type) +- [ ] Authority metrics available (DA/DR or equivalent) + +### Output Validation +- [ ] Every metric cites its data source and collection date +- [ ] Toxic link assessments include risk justification +- [ ] Link opportunity recommendations are specific and actionable +- [ ] Source of each data point clearly stated (~~link database data, ~~SEO tool data, user-provided, or estimated) + +## Example + +**User**: "Find link building opportunities by analyzing HubSpot, Salesforce, and Mailchimp" + +**Output**: + +```markdown +## Link Intersection Analysis + +### Sites linking to 2+ competitors (not you) + +| Domain | DA | HubSpot | Salesforce | Mailchimp | Opportunity | +|--------|-----|---------|------------|-----------|-------------| +| g2.com | 91 | ✅ | ✅ | ✅ | Get listed/reviewed | +| capterra.com | 89 | ✅ | ✅ | ✅ | Submit for review | +| entrepreneur.com | 92 | ✅ | ✅ | ❌ | Pitch guest post | +| techcrunch.com | 94 | ✅ | ❌ | ✅ | PR/news pitch | + +### Top 5 Immediate Opportunities + +1. **G2.com** (DA 91) - All competitors listed + - Action: Create detailed G2 profile + - Effort: Low + - Impact: High authority + referral traffic + +2. **Entrepreneur.com** (DA 92) - 2 competitors have links + - Action: Pitch contributed article + - Effort: High + - Impact: High authority + brand exposure + +3. **MarketingProfs** (DA 75) - All competitors featured + - Action: Apply for expert contribution + - Effort: Medium + - Impact: Relevant audience + quality link + +### Estimated Impact + +If you acquire links from top 10 opportunities: +- New referring domains: +10 +- Average DA of new links: 82 +- Estimated ranking impact: +2-5 positions for competitive keywords +``` + +## Tips for Success + +1. **Quality over quantity** - One DA 80 link beats ten DA 20 links +2. **Monitor regularly** - Catch lost links and toxic links early +3. **Study competitors** - Learn from their link building success +4. **Diversify your profile** - Mix of link types and anchors +5. **Disavow carefully** - Only disavow clearly toxic links + +## Link Quality and Strategy Reference + +> **Reference**: See [references/link-quality-rubric.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/monitor/backlink-analyzer/references/link-quality-rubric.md) for the complete link quality scoring matrix (6 weighted factors), toxic link identification criteria, link profile health benchmarks, and disavow file guidance. + +> **Reference**: See [references/outreach-templates.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/monitor/backlink-analyzer/references/outreach-templates.md) for email outreach frameworks, subject line formulas, response rate benchmarks, follow-up sequences, and templates for each link building strategy. + + +### Save Results + +After delivering monitoring data or reports to the user, ask: + +> "Save these results for future sessions?" + +If yes, write a dated summary to `memory/monitoring/YYYY-MM-DD-.md` containing: +- One-line headline finding or status change +- Top 3-5 actionable items +- Open loops or anomalies requiring follow-up +- Source data references + +If any findings should influence ongoing strategy, recommend promoting key conclusions to `memory/hot-cache.md`. + + +**Gate check recommended**: If toxic link ratio exceeds 15%, recommend running domain-authority-auditor to assess overall domain trust impact. + +## Reference Materials + +- [Link Quality Rubric](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/monitor/backlink-analyzer/references/link-quality-rubric.md) — Quality scoring matrix with weighted factors and toxic link identification criteria +- [Outreach Templates](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/monitor/backlink-analyzer/references/outreach-templates.md) — Email frameworks, subject line formulas, and response rate benchmarks + +## Next Best Skill + +- **Primary**: [domain-authority-auditor](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/cross-cutting/domain-authority-auditor/SKILL.md) — translate link findings into a domain-level trust view. diff --git a/.cursor/skills/competitor-analysis/SKILL.md b/.cursor/skills/competitor-analysis/SKILL.md new file mode 100644 index 0000000..11c1efc --- /dev/null +++ b/.cursor/skills/competitor-analysis/SKILL.md @@ -0,0 +1,309 @@ +--- +name: competitor-analysis +description: 'Analyze competitor SEO/GEO: keywords, content, backlinks, AI citations, traffic share gaps. 竞品分析/竞争对手' +version: "6.0.0" +license: Apache-2.0 +compatibility: "Claude Code ≥1.0, skills.sh marketplace, ClawHub marketplace, Vercel Labs skills ecosystem. No system packages required. Optional: MCP network access for SEO tool integrations." +homepage: "https://github.com/aaron-he-zhu/seo-geo-claude-skills" +when_to_use: "Use when analyzing competitor SEO strategy, comparing domains, benchmarking against competitors, or finding competitor keywords and content gaps." +argument-hint: "" +metadata: + author: aaron-he-zhu + version: "6.0.0" + geo-relevance: "medium" + tags: + - seo + - geo + - competitor-analysis + - competitive-intelligence + - benchmarking + - competitor-keywords + - competitor-backlinks + - market-analysis + - spyfu-alternative + - 竞品分析 + - 競合分析 + - 경쟁분석 + - analisis-competitivo + triggers: + # EN-formal + - "analyze competitors" + - "competitor SEO" + - "competitive analysis" + - "competitor keywords" + - "competitor backlinks" + - "market analysis" + - "competitive intelligence" + # EN-casual + - "what are my competitors doing" + - "what are they doing differently" + - "why do they rank higher" + - "spy on competitor SEO" + - "what are they doing better" + - "why do they outrank me" + # EN-question + - "who are my SEO competitors" + - "how do I beat my competitors" + - "why do competitors rank higher" + # EN-competitor + - "SpyFu alternative" + - "Semrush competitor analysis" + - "Ahrefs competitor tool" + # ZH-pro + - "竞品分析" + - "竞争对手分析" + - "竞品SEO" + - "对标分析" + - "竞争情报" + # ZH-casual + - "竞品怎么做的" + - "他们排名为什么比我高" + - "看看对手在干什么" + - "为什么他们排名好" + # JA + - "競合分析" + - "競合SEO分析" + - "ライバル分析" + # KO + - "경쟁 분석" + - "경쟁사 SEO" + - "경쟁사 키워드" + # ES + - "análisis de competidores" + - "análisis competitivo SEO" + # PT + - "análise de concorrentes" + # Misspellings + - "competitve analysis" + - "compeditor analysis" +--- + +# Competitor Analysis + + +> **[SEO & GEO Skills Library](https://github.com/aaron-he-zhu/seo-geo-claude-skills)** · 20 skills for SEO + GEO · [ClawHub](https://clawhub.ai/u/aaron-he-zhu) · [skills.sh](https://skills.sh/aaron-he-zhu/seo-geo-claude-skills) +> **System Mode**: This research skill follows the shared [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md) and [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md). + + +This skill provides comprehensive analysis of competitor SEO and GEO strategies, revealing what's working in your market and identifying opportunities to outperform the competition. + +**System role**: Research layer skill. It turns market signals into reusable strategic inputs for the rest of the library. + +## When This Must Trigger + +Use this when the conversation involves any of these situations — even if the user does not use SEO terminology: + +Use this whenever the task needs reusable market intelligence that should influence strategy, not just an ad hoc answer. + +- Entering a new market or niche +- Planning content strategy based on competitor success +- Understanding why competitors rank higher +- Finding backlink and partnership opportunities +- Identifying content gaps competitors are missing +- Analyzing competitor AI citation strategies +- Benchmarking your SEO performance + +## What This Skill Does + +1. **Keyword Analysis**: Identifies keywords competitors rank for +2. **Content Audit**: Analyzes competitor content strategies and formats +3. **Backlink Profiling**: Reviews competitor link-building approaches +4. **Technical Assessment**: Evaluates competitor site health +5. **GEO Analysis**: Identifies how competitors appear in AI responses +6. **Gap Identification**: Finds opportunities competitors miss +7. **Strategy Extraction**: Reveals actionable insights from competitor success + +## Quick Start + +Start with one of these prompts. Finish with a short handoff summary using the repository format in [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md). + +### Basic Competitor Analysis + +``` +Analyze SEO strategy for [competitor URL] +``` + +``` +Compare my site [URL] against [competitor 1], [competitor 2], [competitor 3] +``` + +### Specific Analysis + +``` +What content is driving the most traffic for [competitor]? +``` + +``` +Analyze why [competitor] ranks #1 for [keyword] +``` + +### GEO-Focused Analysis + +``` +How is [competitor] getting cited in AI responses? What can I learn? +``` + +## Skill Contract + +**Expected output**: a prioritized research brief, evidence-backed findings, and a short handoff summary ready for `memory/research/`. + +- **Reads**: user goals, target market inputs, available tool data, and prior strategy from [CLAUDE.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CLAUDE.md) and the shared [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md) when available. +- **Writes**: a user-facing research deliverable plus a reusable summary that can be stored under `memory/research/`. +- **Promotes**: durable keyword priorities, competitor facts, entity candidates, and strategic decisions to `CLAUDE.md`, `memory/decisions.md`, and `memory/research/`; hand canonical entity work to `entity-optimizer`. +- **Next handoff**: use the `Next Best Skill` below when the findings are ready to drive action. + +## Data Sources + +> **Note:** All integrations are optional. This skill works without any API keys — users provide data manually when no tools are connected. + +> See [CONNECTORS.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CONNECTORS.md) for tool category placeholders. + +**With ~~SEO tool + ~~analytics + ~~AI monitor connected:** +Automatically pull competitor keyword rankings, backlink profiles, top performing content, domain authority metrics from ~~SEO tool. Compare against your site's metrics from ~~analytics and ~~search console. Check AI citation patterns for both your site and competitors using ~~AI monitor. + +**With manual data only:** +Ask the user to provide: +1. Competitor URLs to analyze (2-5 recommended) +2. Your own site URL and current metrics (traffic, rankings if known) +3. Industry or niche context +4. Specific aspects to focus on (keywords, content, backlinks, etc.) +5. Any known competitor strengths or weaknesses + +Proceed with the full analysis using provided data. Note in the output which metrics are from automated collection vs. user-provided data. + +## Instructions + +When a user requests competitor analysis: + +1. **Identify Competitors** + + If not specified, help identify competitors: + + ```markdown + ### Competitor Identification Framework + + **Direct Competitors** (same product/service) + - Search "[your main keyword]" and note top 5 organic results + - Check who's advertising for your keywords + - Ask: Who do customers compare you to? + + **Indirect Competitors** (different solution, same problem) + - Search problem-focused keywords + - Look at alternative solutions + + **Content Competitors** (compete for same keywords) + - May not sell same product + - Rank for your target keywords + - Include media sites, blogs, aggregators + ``` + +2. **Gather Competitor Data** + + Collect for each competitor: URL, domain age, estimated traffic, domain authority, business model, target audience, and key offerings. + +3. **Analyze Keyword Rankings** + + Document total keywords ranking, top 10/top 3 counts, top performing keywords (with position, volume, traffic, page URL), keyword distribution by intent, and keyword gaps. + +4. **Audit Content Strategy** + + Analyze content volume by type, top performing content, content patterns (word count, frequency, formats), content themes, and success factors. + +5. **Analyze Backlink Profile** + + Review total backlinks, referring domains, link quality distribution, top linking domains, link acquisition patterns, and linkable assets. + +6. **Technical SEO Assessment** + + Evaluate Core Web Vitals, mobile-friendliness, site architecture, internal linking quality, URL structure, and technical strengths/weaknesses. + +7. **GEO/AI Citation Analysis** + + Test competitor content in AI systems: document which queries cite them, GEO strategies observed (definitions, statistics, Q&A, authority signals), and GEO opportunities they are missing. + +8. **Synthesize Competitive Intelligence** + + Produce a final report with: Executive Summary, Competitive Landscape comparison table, CITE domain authority comparison, Strengths to Learn From, Weaknesses to Exploit, Keyword Opportunities, Content Strategy Recommendations, and Action Plan (Immediate / Short-term / Long-term). + + > **Reference**: See [references/analysis-templates.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/research/competitor-analysis/references/analysis-templates.md) for detailed templates for each step. + +## Validation Checkpoints + +### Input Validation +- [ ] Competitor URLs verified as relevant to your niche +- [ ] Analysis scope defined (comprehensive or specific focus area) +- [ ] Your own site metrics available for comparison +- [ ] Minimum 2-3 competitors identified for meaningful patterns + +### Output Validation +- [ ] Every recommendation cites specific data points (not generic advice) +- [ ] Competitor strengths backed by measurable evidence (metrics, rankings) +- [ ] Opportunities based on identifiable gaps, not assumptions +- [ ] Action plan items are specific and actionable (not vague strategies) +- [ ] Source of each data point clearly stated (~~SEO tool data, ~~analytics data, ~~AI monitor data, user-provided, or estimated) + +## Example + +> **Reference**: See [references/example-report.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/research/competitor-analysis/references/example-report.md) for a complete example analyzing HubSpot's marketing keyword dominance. + +## Advanced Analysis Types + +### Content Gap Analysis + +``` +Show me content [competitor] has that I don't, sorted by traffic potential +``` + +### Link Intersection + +``` +Find sites linking to [competitor 1] AND [competitor 2] but not me +``` + +### SERP Feature Analysis + +``` +What SERP features do competitors win? (Featured snippets, PAA, etc.) +``` + +### Historical Tracking + +``` +How has [competitor]'s SEO strategy evolved over the past year? +``` + +## Tips for Success + +1. **Analyze 3-5 competitors** for comprehensive view +2. **Include indirect competitors** - they often have innovative approaches +3. **Look beyond rankings** - analyze content quality, user experience +4. **Study their failures** - avoid their mistakes +5. **Monitor regularly** - competitor strategies evolve +6. **Focus on actionable insights** - what can you actually implement? + + + +### Save Results + +After delivering findings to the user, ask: + +> "Save these results for future sessions?" + +If yes, write a dated summary to `memory/research/competitor-analysis/YYYY-MM-DD-.md` containing: +- One-line headline finding +- Top 3-5 actionable items +- Open loops or blockers +- Source data references + +If any findings should influence ongoing strategy, recommend promoting key conclusions to `memory/hot-cache.md`. + +## Reference Materials + +- [Analysis Templates](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/research/competitor-analysis/references/analysis-templates.md) — Detailed templates for each analysis step (profile, keywords, content, backlinks, technical, GEO, synthesis) +- [Battlecard Template](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/research/competitor-analysis/references/battlecard-template.md) — Quick-reference competitive battlecard for sales and marketing teams +- [Positioning Frameworks](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/research/competitor-analysis/references/positioning-frameworks.md) — Positioning maps, messaging matrices, narrative analysis, and differentiation frameworks +- [Example Report](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/research/competitor-analysis/references/example-report.md) — Complete example analyzing HubSpot's marketing keyword dominance + +## Next Best Skill + +- **Primary**: [content-gap-analysis](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/research/content-gap-analysis/SKILL.md) — turn competitor findings into a focused opportunity map. diff --git a/.cursor/skills/content-gap-analysis/SKILL.md b/.cursor/skills/content-gap-analysis/SKILL.md new file mode 100644 index 0000000..0e4e0e7 --- /dev/null +++ b/.cursor/skills/content-gap-analysis/SKILL.md @@ -0,0 +1,287 @@ +--- +name: content-gap-analysis +description: 'Find content gaps: topics and keywords competitors cover that you don''t, with editorial calendar. 内容缺口/选题规划' +version: "6.0.0" +license: Apache-2.0 +compatibility: "Claude Code ≥1.0, skills.sh marketplace, ClawHub marketplace, Vercel Labs skills ecosystem. No system packages required. Optional: MCP network access for SEO tool integrations." +homepage: "https://github.com/aaron-he-zhu/seo-geo-claude-skills" +when_to_use: "Use when finding content gaps between two domains, discovering missing topics, or identifying coverage holes versus competitors." +argument-hint: " " +metadata: + author: aaron-he-zhu + version: "6.0.0" + geo-relevance: "medium" + tags: + - seo + - geo + - content-gaps + - topic-analysis + - content-strategy + - editorial-calendar + - competitive-gap + - content-opportunities + - 内容缺口 + - コンテンツギャップ + - 콘텐츠갭 + - brechas-contenido + triggers: + # EN-formal + - "find content gaps" + - "content opportunities" + - "topic analysis" + - "content strategy gaps" + - "editorial calendar" + - "untapped topics" + # EN-casual + - "what am I missing" + - "topics to cover" + - "what do competitors write about" + - "what should I cover next" + - "topics I haven't written about" + - "they cover this but I don't" + # EN-question + - "what topics am I missing" + - "what content should I create" + # ZH-pro + - "内容缺口分析" + - "选题规划" + - "内容机会" + - "竞品话题" + # ZH-casual + - "缺什么内容" + - "竞品写了什么" + - "还应该写什么" + # JA + - "コンテンツギャップ" + - "コンテンツ機会" + # KO + - "콘텐츠 갭 분석" + - "콘텐츠 기회" + # ES + - "brechas de contenido" + - "oportunidades de contenido" + # PT + - "lacunas de conteúdo" + # Misspellings + - "content gab analysis" +--- + +# Content Gap Analysis + + +> **[SEO & GEO Skills Library](https://github.com/aaron-he-zhu/seo-geo-claude-skills)** · 20 skills for SEO + GEO · [ClawHub](https://clawhub.ai/u/aaron-he-zhu) · [skills.sh](https://skills.sh/aaron-he-zhu/seo-geo-claude-skills) +> **System Mode**: This research skill follows the shared [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md) and [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md). + + +Identifies content opportunities by analyzing gaps between a site's content and competitors'. Surfaces missing topics, untapped keywords, and content formats worth creating. + +**System role**: Research layer skill. It turns market signals into reusable strategic inputs for the rest of the library. + +## When This Must Trigger + +Use this when the conversation involves any of these situations — even if the user does not use SEO terminology: + +Use this whenever the task needs reusable market intelligence that should influence strategy, not just an ad hoc answer. + +- Planning content strategy and editorial calendar +- Finding quick-win content opportunities +- Understanding where competitors outperform you +- Identifying underserved topics in your niche +- Expanding into adjacent topic areas +- Prioritizing content creation efforts +- Finding GEO opportunities competitors miss + +## What This Skill Does + +1. **Keyword Gap Analysis**: Finds keywords competitors rank for that you don't +2. **Topic Coverage Mapping**: Identifies topic areas needing more content +3. **Content Format Gaps**: Reveals missing content types (videos, tools, guides) +4. **Audience Need Mapping**: Matches gaps to audience journey stages +5. **GEO Opportunity Detection**: Finds AI-answerable topics you're missing +6. **Priority Scoring**: Ranks gaps by impact and effort +7. **Content Calendar Creation**: Plans gap-filling content schedule + +## Quick Start + +Start with one of these prompts. Finish with a short handoff summary using the repository format in [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md). + +### Basic Gap Analysis + +``` +Find content gaps between my site [URL] and [competitor URLs] +``` + +``` +What content am I missing compared to my top 3 competitors? +``` + +### Topic-Specific Analysis + +``` +Find content gaps in [topic area] compared to industry leaders +``` + +``` +What [content type] do competitors have that I don't? +``` + +### Audience-Focused + +``` +What content gaps exist for [audience segment] in my niche? +``` + +## Skill Contract + +**Expected output**: a prioritized research brief, evidence-backed findings, and a short handoff summary ready for `memory/research/`. + +- **Reads**: user goals, target market inputs, available tool data, and prior strategy from [CLAUDE.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CLAUDE.md) and the shared [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md) when available. +- **Writes**: a user-facing research deliverable plus a reusable summary that can be stored under `memory/research/`. +- **Promotes**: durable keyword priorities, competitor facts, entity candidates, and strategic decisions to `CLAUDE.md`, `memory/decisions.md`, and `memory/research/`; hand canonical entity work to `entity-optimizer`. +- **Next handoff**: use the `Next Best Skill` below when the findings are ready to drive action. + +## Data Sources + +> **Note:** All integrations are optional. This skill works without any API keys — users provide data manually when no tools are connected. + +> See [CONNECTORS.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CONNECTORS.md) for tool category placeholders. + +**With ~~SEO tool + ~~search console + ~~analytics + ~~AI monitor connected:** +Automatically pull your site's content inventory from ~~search console and ~~analytics (indexed pages, traffic per page, keywords ranking), competitor content data from ~~SEO tool (ranking keywords, top pages, backlink counts), and AI citation patterns from ~~AI monitor. Keyword overlap analysis and gap identification can be automated. + +**With manual data only:** +Ask the user to provide: +1. Your site URL and content inventory (list of published content with topics) +2. Competitor URLs (3-5 sites) +3. Your current traffic and keyword performance (if available) +4. Known content strengths and weaknesses +5. Industry context and business goals + +Proceed with the full analysis using provided data. Note in the output which metrics are from automated collection vs. user-provided data. + +## Instructions + +When a user requests content gap analysis: + +1. **Define Analysis Scope** + + Clarify parameters: + + ```markdown + ### Analysis Parameters + + **Your Site**: [URL] + **Competitors to Analyze**: [URLs or "identify for me"] + **Topic Focus**: [specific area or "all"] + **Content Types**: [blogs, guides, tools, videos, or "all"] + **Audience**: [target audience] + **Business Goals**: [traffic, leads, authority, etc.] + ``` + +2. **Audit Your Existing Content** + + Document total indexed pages, content by type and topic cluster, top performing content, and content strengths/weaknesses. + +3. **Analyze Competitor Content** + + For each competitor: document content volume, monthly traffic, content distribution by type, topic coverage vs. yours, and unique content they have. + +4. **Identify Keyword Gaps** + + Find keywords competitors rank for that you do not. Categorize into High Priority (high volume, achievable difficulty), Quick Wins (lower volume, low difficulty), and Long-term (high volume, high difficulty). Include keyword overlap analysis. + +5. **Map Topic Gaps** + + Create a topic coverage comparison matrix across all competitors. For each missing topic cluster, document business relevance, competitor coverage, opportunity size, sub-topics, and recommended pillar/cluster approach. + +6. **Identify Content Format Gaps** + + Compare format distribution (guides, tutorials, comparisons, case studies, tools, templates, video, infographics, research) against competitors and industry averages. For each gap, assess effort and expected impact. + +7. **Analyze GEO/AI Gaps** + + Identify topics where competitors get AI citations but you do not. Document missing Q&A content, definition/explanation content, and comparison content. Score each by traditional SEO value and GEO value. + +8. **Map to Audience Journey** + + Compare funnel stage coverage (Awareness, Consideration, Decision, Retention) against competitor averages. Detail specific gaps at each stage. + +9. **Prioritize and Create Action Plan** + + Produce a final report with: Executive Summary, Prioritized Gap List (Tier 1 Quick Wins, Tier 2 Strategic Builds, Tier 3 Long-term), Content Calendar, and Success Metrics. + + > **Reference**: See [references/analysis-templates.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/research/content-gap-analysis/references/analysis-templates.md) for detailed templates for each step. + +## Validation Checkpoints + +### Input Validation +- [ ] Your content inventory is complete or representative sample provided +- [ ] Competitor URLs identified (minimum 2-3 competitors) +- [ ] Analysis scope defined (specific topics or comprehensive) +- [ ] Business goals and priorities clarified + +### Output Validation +- [ ] Every recommendation cites specific data points (not generic advice) +- [ ] Gap analysis compares like-to-like content (topic clusters to topic clusters) +- [ ] Priority scoring based on measurable criteria (volume, difficulty, business fit) +- [ ] Content calendar maps gaps to realistic timeframes +- [ ] Source of each data point clearly stated (~~SEO tool data, ~~analytics data, ~~AI monitor data, user-provided, or estimated) + +## Example + +> **Reference**: See [references/example-report.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/research/content-gap-analysis/references/example-report.md) for a complete example analyzing SaaS marketing blog gaps vs. HubSpot and Drift. + +## Advanced Analysis + +### Competitive Cluster Comparison + +``` +Compare our topic cluster coverage for [topic] vs top 5 competitors +``` + +### Temporal Gap Analysis + +``` +What content have competitors published in the last 6 months that we haven't covered? +``` + +### Intent-Based Gaps + +``` +Find gaps in our [commercial/informational] intent content +``` + +## Tips for Success + +1. **Focus on actionable gaps** - Not all gaps are worth filling +2. **Consider your resources** - Prioritize based on ability to execute +3. **Quality over quantity** - Better to fill 5 gaps well than 20 poorly +4. **Track what works** - Measure gap-filling success +5. **Update regularly** - Gaps change as competitors publish +6. **Include GEO opportunities** - Don't just optimize for traditional search + + + +### Save Results + +After delivering findings to the user, ask: + +> "Save these results for future sessions?" + +If yes, write a dated summary to `memory/research/content-gap-analysis/YYYY-MM-DD-.md` containing: +- One-line headline finding +- Top 3-5 actionable items +- Open loops or blockers +- Source data references + +If any findings should influence ongoing strategy, recommend promoting key conclusions to `memory/hot-cache.md`. + +## Reference Materials + +- [Analysis Templates](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/research/content-gap-analysis/references/analysis-templates.md) — Detailed templates for each analysis step (inventory, competitor content, keyword gaps, topic gaps, format gaps, GEO gaps, journey, prioritized report) +- [Gap Analysis Frameworks](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/research/content-gap-analysis/references/gap-analysis-frameworks.md) — Content audit matrices, funnel mapping, and gap prioritization scoring methodologies +- [Example Report](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/research/content-gap-analysis/references/example-report.md) — Complete example analyzing SaaS marketing blog gaps vs. HubSpot and Drift + +## Next Best Skill + +- **Primary**: [seo-content-writer](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/build/seo-content-writer/SKILL.md) — turn missing topics into a draft or content roadmap. diff --git a/.cursor/skills/content-quality-auditor/SKILL.md b/.cursor/skills/content-quality-auditor/SKILL.md new file mode 100644 index 0000000..c3679a8 --- /dev/null +++ b/.cursor/skills/content-quality-auditor/SKILL.md @@ -0,0 +1,403 @@ +--- +name: content-quality-auditor +description: 'Publish-readiness gate: 80-item CORE-EEAT audit with weighted scoring, veto checks, and fix plan. 内容质量/EEAT评分' +version: "6.0.0" +license: Apache-2.0 +allowed-tools: WebFetch +compatibility: "Claude Code ≥1.0, skills.sh marketplace, ClawHub marketplace, Vercel Labs skills ecosystem. No system packages required. Optional: MCP network access for SEO tool integrations." +homepage: "https://github.com/aaron-he-zhu/seo-geo-claude-skills" +when_to_use: "Use when auditing content quality before publishing. Runs CORE-EEAT 80-item scoring with veto checks. Also when the user asks for E-E-A-T analysis or publish readiness." +argument-hint: " [keyword]" +metadata: + author: aaron-he-zhu + version: "6.0.0" + geo-relevance: "high" + tags: + - seo + - geo + - e-e-a-t + - core-eeat + - content-quality + - content-scoring + - helpful-content + - publish-readiness + - 内容质量 + - コンテンツ品質 + - 콘텐츠품질 + - auditoria-eeat + triggers: + # EN-formal + - "audit content quality" + - "EEAT score" + - "CORE-EEAT audit" + - "content quality check" + - "content assessment" + - "quality score" + # EN-casual + - "is this ready to publish" + - "grade my article" + - "check before publishing" + - "how good is my content" + - "is my content good enough to rank" + - "rate my content quality" + # EN-question + - "is my content ready to publish" + - "how do I improve content quality" + # ZH-pro + - "内容质量审计" + - "EEAT评分" + - "内容评估" + # ZH-casual + - "文章能发吗" + - "内容打几分" + - "文章写得怎么样" + # JA + - "コンテンツ品質監査" + - "E-E-A-T評価" + # KO + - "콘텐츠 품질 감사" + - "EEAT 점수" + # ES + - "auditoría de calidad de contenido" + - "puntuación EEAT" + # PT + - "auditoria de qualidade" + # Misspellings + - "EEAT scroe" +--- + +# Content Quality Auditor + +> Based on [CORE-EEAT Content Benchmark](https://github.com/aaron-he-zhu/core-eeat-content-benchmark). Full benchmark reference: [references/core-eeat-benchmark.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/core-eeat-benchmark.md) + + +> **[SEO & GEO Skills Library](https://github.com/aaron-he-zhu/seo-geo-claude-skills)** · 20 skills for SEO + GEO · [ClawHub](https://clawhub.ai/u/aaron-he-zhu) · [skills.sh](https://skills.sh/aaron-he-zhu/seo-geo-claude-skills) +> **System Mode**: This cross-cutting skill is part of the protocol layer and follows the shared [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md) and [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md). + + +This skill evaluates content quality across 80 standardized criteria organized in 8 dimensions. It produces a comprehensive audit report with per-item scoring, dimension and system scores, weighted totals by content type, and a prioritized action plan. + +**System role**: Publish Readiness Gate. It decides whether content is ready to ship, what blocks publication, and what should be promoted into durable project memory. + +## When This Must Trigger + +Use this when content needs a quality check before publishing — even if the user doesn't use audit terminology: + +- User asks "is this ready to publish" or "how good is this" +- User just finished writing with seo-content-writer or content-refresher +- **PostToolUse hook auto-triggers**: after content is written or substantially edited, the hook recommends this audit. When hook-triggered, skip setup questions — audit the content that was just produced. +- Auditing content quality before publishing +- Evaluating existing content for improvement opportunities +- Benchmarking content against CORE-EEAT standards +- Comparing content quality against competitors +- Assessing both GEO readiness (AI citation potential) and SEO strength (source credibility) +- Running periodic content quality checks as part of a content maintenance program +- After writing or optimizing content with seo-content-writer or geo-content-optimizer + +## What This Skill Does + +1. **Full 80-Item Audit**: Scores every CORE-EEAT check item as Pass/Partial/Fail +2. **Dimension Scoring**: Calculates scores for all 8 dimensions (0-100 each) +3. **System Scoring**: Computes GEO Score (CORE) and SEO Score (EEAT) +4. **Weighted Totals**: Applies content-type-specific weights for final score +5. **Veto Detection**: Flags critical trust violations (T04, C01, R10) +6. **Priority Ranking**: Identifies Top 5 improvements sorted by impact +7. **Action Plan**: Generates specific, actionable improvement steps + +## Quick Start + +Start with one of these prompts. Finish with a publish verdict and a handoff summary using the repository format in [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md). + +### Audit Content + +``` +Audit this content against CORE-EEAT: [content text or URL] +``` + +``` +Run a content quality audit on [URL] as a [content type] +``` + +### Audit with Content Type + +``` +CORE-EEAT audit for this product review: [content] +``` + +``` +Score this how-to guide against the 80-item benchmark: [content] +``` + +### Comparative Audit + +``` +Audit my content vs competitor: [your content] vs [competitor content] +``` + +## Skill Contract + +**Gate verdict**: **SHIP** (no veto items, dimension scores above threshold) / **FIX** (issues found but no veto) / **BLOCK** (veto item T04, C01, or R10 failed). Always state the verdict prominently at the top of the report. + +**Expected output**: a CORE-EEAT audit report, a publish-readiness verdict, and a short handoff summary ready for `memory/audits/content/`. + +- **Reads**: the target content, content type, supporting evidence, and any prior decisions from [CLAUDE.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CLAUDE.md) and the shared [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md) when available. +- **Writes**: a user-facing audit report plus a reusable summary that can be stored under `memory/audits/content/`. +- **Promotes**: veto items and publish blockers to `memory/hot-cache.md` (auto-saved, no user confirmation needed). Top improvement priorities to `memory/open-loops.md`. +- **Next handoff**: use the `Next Best Skill` below once the verdict is clear. + +## Data Sources + +> See [CONNECTORS.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CONNECTORS.md) for tool category placeholders. + +**With ~~web crawler + ~~SEO tool connected:** +Automatically fetch page content, extract HTML structure, check schema markup, verify internal/external links, and pull competitor content for comparison. + +**With manual data only:** +Ask the user to provide: +1. Content text, URL, or file path +2. Content type (if not auto-detectable): Product Review, How-to Guide, Comparison, Landing Page, Blog Post, FAQ Page, Alternative, Best-of, or Testimonial +3. Optional: competitor content for benchmarking + +Proceed with the full 80-item audit using provided data. Note in the output which items could not be fully evaluated due to missing access (e.g., backlink data, schema markup, site-level signals). + +## Decision Gates + +When stopping to ask, always: (1) state the specific value and threshold, (2) offer numbered options with outcomes. + +**Stop and ask the user when:** +- Content is under minimum word count for its type (blog/guide: 300 words; product/landing page: 150 words; FAQ: fewer than 3 entries with 50+ words each) — state the actual count and offer: (1) expand to minimum, (2) continue audit with Insufficient Data flags, (3) cancel +- Content type cannot be auto-detected — state what you detected and ask to confirm before proceeding +- Content is primarily media (video/image) with minimal text — ask whether to audit transcript, alt text, or skip +- More than 50% of a dimension's items are N/A — name the dimension and ask: (1) provide supplementary data, (2) mark entire dimension as Insufficient Data +- Any veto item triggers — flag it immediately with the item ID and ask: (1) stop for immediate fix, (2) continue full audit and flag in report + +**Continue silently (never stop for):** +- Individual Partial scores within a dimension +- Missing SEO tool data (mark items as N/A and continue) +- Low overall score (the report is the deliverable, not a judgment call) +- User not specifying content type (auto-detect and state your assumption) + +## Instructions + +When a user requests a content quality audit: + +### Step 1: Preparation + +```markdown +### Audit Setup + +**Content**: [title or URL] +**Content Type**: [auto-detected or user-specified] +**Dimension Weights**: [loaded from content-type weight table] + +#### Veto Check (Emergency Brake) + +| Veto Item | Status | Action | +|-----------|--------|--------| +| T04: Disclosure Statements | ✅ Pass / ⚠️ VETO | [If VETO: "Add disclosure banner at page top immediately"] | +| C01: Intent Alignment | ✅ Pass / ⚠️ VETO | [If VETO: "Rewrite title and first paragraph"] | +| R10: Content Consistency | ✅ Pass / ⚠️ VETO | [If VETO: "Verify all data before publishing"] | +``` + +If any veto item triggers, flag it prominently at the top of the report and recommend immediate action before continuing the full audit. + +### Step 2: CORE Audit (40 items) + +Evaluate each item against the criteria in [references/core-eeat-benchmark.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/core-eeat-benchmark.md). + +Score each item: +- **Pass** = 10 points (fully meets criteria) +- **Partial** = 5 points (partially meets criteria) +- **Fail** = 0 points (does not meet criteria) + +```markdown +### C — Contextual Clarity + +| ID | Check Item | Score | Notes | +|----|-----------|-------|-------| +| C01 | Intent Alignment | Pass/Partial/Fail | [specific observation] | +| C02 | Direct Answer | Pass/Partial/Fail | [specific observation] | +| ... | ... | ... | ... | +| C10 | Semantic Closure | Pass/Partial/Fail | [specific observation] | + +**C Score**: [X]/100 +``` + +Repeat the same table format for **O** (Organization), **R** (Referenceability), and **E** (Exclusivity), scoring all 10 items per dimension. + +### Step 3: EEAT Audit (40 items) + +```markdown +### Exp — Experience + +| ID | Check Item | Score | Notes | +|----|-----------|-------|-------| +| Exp01 | First-Person Narrative | Pass/Partial/Fail | [specific observation] | +| ... | ... | ... | ... | + +**Exp Score**: [X]/100 +``` + +Repeat the same table format for **Ept** (Expertise), **A** (Authority), and **T** (Trust), scoring all 10 items per dimension. + +See [references/item-reference.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/cross-cutting/content-quality-auditor/references/item-reference.md) for the complete 80-item ID lookup table and site-level item handling notes. + +### Step 4: Scoring & Report + +Calculate scores and generate the final report: + +```markdown +## CORE-EEAT Audit Report + +### Overview + +- **Content**: [title] +- **Content Type**: [type] +- **Audit Date**: [date] +- **Total Score**: [score]/100 ([rating]) +- **GEO Score**: [score]/100 | **SEO Score**: [score]/100 +- **Veto Status**: ✅ No triggers / ⚠️ [item] triggered + +### Dimension Scores + +| Dimension | Score | Rating | Weight | Weighted | +|-----------|-------|--------|--------|----------| +| C — Contextual Clarity | [X]/100 | [rating] | [X]% | [X] | +| O — Organization | [X]/100 | [rating] | [X]% | [X] | +| R — Referenceability | [X]/100 | [rating] | [X]% | [X] | +| E — Exclusivity | [X]/100 | [rating] | [X]% | [X] | +| Exp — Experience | [X]/100 | [rating] | [X]% | [X] | +| Ept — Expertise | [X]/100 | [rating] | [X]% | [X] | +| A — Authority | [X]/100 | [rating] | [X]% | [X] | +| T — Trust | [X]/100 | [rating] | [X]% | [X] | +| **Weighted Total** | | | | **[X]/100** | + +**Score Calculation**: +- GEO Score = (C + O + R + E) / 4 +- SEO Score = (Exp + Ept + A + T) / 4 +- Weighted Score = Σ (dimension_score × content_type_weight) + +**Rating Scale**: 90-100 Excellent | 75-89 Good | 60-74 Medium | 40-59 Low | 0-39 Poor + +### N/A Item Handling + +When an item cannot be evaluated (e.g., A01 Backlink Profile requires site-level data not available): + +1. Mark the item as "N/A" with reason +2. Exclude N/A items from the dimension score calculation +3. Dimension Score = (sum of scored items) / (number of scored items x 10) x 100 +4. If more than 50% of a dimension's items are N/A, flag the dimension as "Insufficient Data" and exclude it from the weighted total +5. Recalculate weighted total using only dimensions with sufficient data, re-normalizing weights to sum to 100% + +**Example**: Authority dimension with 8 N/A items and 2 scored items (A05=8, A07=5): +- Dimension score = (8+5) / (2 x 10) x 100 = 65 +- But 8/10 items are N/A (>50%), so flag as "Insufficient Data -- Authority" +- Exclude A dimension from weighted total; redistribute its weight proportionally to remaining dimensions + +### Per-Item Scores + +#### CORE — Content Body (40 Items) + +| ID | Check Item | Score | Notes | +|----|-----------|-------|-------| +| C01 | Intent Alignment | [Pass/Partial/Fail] | [observation] | +| C02 | Direct Answer | [Pass/Partial/Fail] | [observation] | +| ... | ... | ... | ... | + +#### EEAT — Source Credibility (40 Items) + +| ID | Check Item | Score | Notes | +|----|-----------|-------|-------| +| Exp01 | First-Person Narrative | [Pass/Partial/Fail] | [observation] | +| ... | ... | ... | ... | + +### Top 5 Priority Improvements + +Sorted by: weight × points lost (highest impact first) + +1. **[ID] [Name]** — [specific modification suggestion] + - Current: [Fail/Partial] | Potential gain: [X] weighted points + - Action: [concrete step] + +2. **[ID] [Name]** — [specific modification suggestion] + - Current: [Fail/Partial] | Potential gain: [X] weighted points + - Action: [concrete step] + +3–5. [Same format] + +### Action Plan + +#### Quick Wins (< 30 minutes each) +- [ ] [Action 1] +- [ ] [Action 2] + +#### Medium Effort (1-2 hours) +- [ ] [Action 3] +- [ ] [Action 4] + +#### Strategic (Requires planning) +- [ ] [Action 5] +- [ ] [Action 6] + +### Recommended Next Steps + +- For full content rewrite: use `seo-content-writer` with CORE-EEAT constraints +- For GEO optimization: use `geo-content-optimizer` targeting failed GEO-First items +- For content refresh: use `content-refresher` with weak dimensions as focus +- For technical fixes: run `/seo:check-technical` for site-level issues +``` + +### Save Results + +After delivering findings to the user, ask: + +> "Save these results for future sessions?" + +If yes, write a dated summary to the appropriate `memory/` path using filename `YYYY-MM-DD-.md` containing: +- One-line verdict or headline finding +- Top 3-5 actionable items +- Open loops or blockers +- Source data references + +If any veto-level issue was found (CORE-EEAT T04, C01, R10 or CITE T03, T05, T09), also append a one-liner to `memory/hot-cache.md` without asking. + +## Validation Checkpoints + +### Input Validation +- [ ] Content source identified (text, URL, or file path) +- [ ] Content type confirmed (auto-detected or user-specified) +- [ ] Content is substantial enough for meaningful audit (≥300 words) +- [ ] If comparative audit, competitor content also provided + +### Output Validation +- [ ] All 80 items scored (or marked N/A with reason) +- [ ] All 8 dimension scores calculated correctly +- [ ] Weighted total matches content-type weight configuration +- [ ] Veto items checked and flagged if triggered +- [ ] Top 5 improvements sorted by weighted impact, not arbitrary +- [ ] Every recommendation is specific and actionable (not generic advice) +- [ ] Action plan includes concrete steps with effort estimates + +## Example + +See [references/item-reference.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/cross-cutting/content-quality-auditor/references/item-reference.md) for a complete scored example showing the C dimension with all 10 items, priority improvements, and weighted scoring. + +## Tips for Success + +1. **Start with veto items** — T04, C01, R10 are deal-breakers regardless of total score + > These veto items are consistent with the CORE-EEAT benchmark (Section 3), which defines them as items that can override the overall score. +2. **Focus on high-weight dimensions** — Different content types prioritize different dimensions +3. **GEO-First items matter most for AI visibility** — Prioritize items tagged GEO 🎯 if AI citation is the goal +4. **Some EEAT items need site-level data** — Don't penalize content for things only observable at the site level (backlinks, brand recognition) +5. **Use the weighted score, not just the raw average** — A product review with strong Exclusivity matters more than strong Authority +6. **Re-audit after improvements** — Run again to verify score improvements and catch regressions +7. **Pair with CITE for domain-level context** — A high content score on a low-authority domain signals a different priority than the reverse; run [domain-authority-auditor](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/cross-cutting/domain-authority-auditor/SKILL.md) for the full 120-item picture + +## Reference Materials + +- [CORE-EEAT Content Benchmark](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/core-eeat-benchmark.md) — Full 80-item benchmark with dimension definitions, scoring criteria, and GEO-First item markers +- [references/item-reference.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/cross-cutting/content-quality-auditor/references/item-reference.md) — All 80 item IDs in a compact lookup table + site-level item handling notes + scored example report + +## Next Best Skill + +- **Primary**: [content-refresher](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/content-refresher/SKILL.md) — turn failed checks into a concrete rewrite plan. diff --git a/.cursor/skills/content-refresher/SKILL.md b/.cursor/skills/content-refresher/SKILL.md new file mode 100644 index 0000000..5c1967a --- /dev/null +++ b/.cursor/skills/content-refresher/SKILL.md @@ -0,0 +1,396 @@ +--- +name: content-refresher +description: 'Refresh outdated posts with current stats, new sections, freshness signals to restore rankings. 内容更新/排名恢复' +version: "6.0.0" +license: Apache-2.0 +compatibility: "Claude Code ≥1.0, skills.sh marketplace, ClawHub marketplace, Vercel Labs skills ecosystem. No system packages required. Optional: MCP network access for SEO tool integrations." +homepage: "https://github.com/aaron-he-zhu/seo-geo-claude-skills" +when_to_use: "Use when updating outdated content, refreshing old articles, improving declining pages, or adding new information to existing content." +argument-hint: "" +metadata: + author: aaron-he-zhu + version: "6.0.0" + geo-relevance: "medium" + tags: + - seo + - geo + - content-refresh + - content-update + - content-decay + - ranking-recovery + - evergreen-content + - content-lifecycle + - 内容更新 + - コンテンツ更新 + - 콘텐츠갱신 + - actualizar-contenido + triggers: + # EN-formal + - "update old content" + - "refresh content" + - "content is outdated" + - "improve declining rankings" + - "revive old blog posts" + - "content decay" + - "content refresh strategy" + # EN-casual + - "traffic is dropping" + - "ranking dropped" + - "this post is outdated" + - "traffic is declining on this page" + - "rankings dropped for this article" + - "my old content needs updating" + # EN-question + - "how to fix declining traffic" + - "why is my content losing rankings" + - "how often should I update content" + # EN-competitor + - "Clearscope content refresh" + - "MarketMuse content update" + # ZH-pro + - "内容更新" + - "内容刷新" + - "排名恢复" + - "内容衰减" + - "内容生命周期" + # ZH-casual + - "排名下降了" + - "文章过时了" + - "流量掉了" + - "老文章怎么办" + # JA + - "コンテンツ更新" + - "コンテンツリフレッシュ" + - "記事更新" + # KO + - "콘텐츠 갱신" + - "콘텐츠 업데이트" + - "순위 하락" + - "순위 하락 원인" + - "오래된 글 어떻게 해?" + # ES + - "actualizar contenido" + - "refrescar contenido antiguo" + # PT + - "atualizar conteúdo" + # Misspellings + - "content refesh" + - "content refreshh" +--- + +# Content Refresher + + +> **[SEO & GEO Skills Library](https://github.com/aaron-he-zhu/seo-geo-claude-skills)** · 20 skills for SEO + GEO · [ClawHub](https://clawhub.ai/u/aaron-he-zhu) · [skills.sh](https://skills.sh/aaron-he-zhu/seo-geo-claude-skills) +> **System Mode**: This optimization skill follows the shared [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md) and [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md). + + +This skill helps identify and revitalize outdated content to reclaim lost rankings and traffic. It analyzes content freshness, identifies update opportunities, and guides the refresh process for maximum SEO and GEO impact. + +**System role**: Optimization layer skill. It turns weak pages, structures, and technical issues into prioritized repair work. + +## When This Must Trigger + +Use this when the conversation involves any of these situations — even if the user does not use SEO terminology: + +Use this whenever the task needs a diagnosis or repair plan that should feed directly into remediation work, not just a one-time opinion. + +- Content has lost rankings or traffic over time +- Statistics and information are outdated +- Competitors have published better content +- Content needs updating for a new year +- Industry changes require content updates +- Adding new sections to existing content +- Converting old content for GEO optimization + +## What This Skill Does + +1. **Freshness Analysis**: Identifies outdated content needing updates +2. **Performance Tracking**: Finds content with declining traffic +3. **Gap Identification**: Spots missing information competitors have +4. **Update Prioritization**: Ranks content by refresh potential +5. **Refresh Recommendations**: Provides specific update guidance +6. **GEO Enhancement**: Updates content for AI citation potential +7. **Republishing Strategy**: Advises on date and promotion tactics + +## Quick Start + +Start with one of these prompts. Finish with a short handoff summary using the repository format in [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md). + +### Identify Content to Refresh + +``` +Find content on [domain] that needs refreshing +``` + +``` +Which of my blog posts have lost the most traffic? +``` + +### Refresh Specific Content + +``` +Refresh this article for [current year]: [URL/content] +``` + +``` +Update this content to outrank [competitor URL]: [your URL] +``` + +### Content Refresh Strategy + +``` +Create a content refresh strategy for [domain/topic] +``` + +## Skill Contract + +**Expected output**: a scored diagnosis, prioritized repair plan, and a short handoff summary ready for `memory/audits/`. + +- **Reads**: the current page or site state, symptoms, prior audits, and current priorities from [CLAUDE.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CLAUDE.md) and the shared [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md) when available. +- **Writes**: a user-facing audit or optimization plan plus a reusable summary that can be stored under `memory/audits/`. +- **Promotes**: blocking defects, repeated weaknesses, and fix priorities to `memory/open-loops.md` and `memory/decisions.md`. +- **Next handoff**: use the `Next Best Skill` below when the repair path is clear. + +## Data Sources + +> See [CONNECTORS.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CONNECTORS.md) for tool category placeholders. + +**With ~~analytics + ~~search console + ~~SEO tool connected:** +Claude can automatically pull historical traffic trends from ~~analytics, fetch impression and ranking data from ~~search console, retrieve keyword position history from ~~SEO tool, and identify content with declining performance. This enables data-driven refresh prioritization. + +**With manual data only:** +Ask the user to provide: +1. Traffic data or screenshots showing performance trends +2. Ranking screenshots or history for key pages +3. Content publish dates and last update dates +4. List of pages the user suspects need refreshing + +Proceed with the analysis using provided data. Note in the output which findings are from automated data vs. manual review. + +## Instructions + +When a user requests content refresh help: + +1. **CORE-EEAT Quick Score — Identify Weak Dimensions** + + Before refreshing, run a quick CORE-EEAT assessment to focus effort on the weakest areas. Reference: [CORE-EEAT Benchmark](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/core-eeat-benchmark.md) + + ```markdown + ### CORE-EEAT Quick Assessment + + **Content**: [title or URL] + **Content Type**: [type] + + Rapidly score each dimension (estimate 0-100): + + | Dimension | Quick Score | Key Weakness | Refresh Priority | + |-----------|-----------|--------------|-----------------| + | C — Contextual Clarity | [X]/100 | [main issue] | 🔴/🟡/🟢 | + | O — Organization | [X]/100 | [main issue] | 🔴/🟡/🟢 | + | R — Referenceability | [X]/100 | [main issue] | 🔴/🟡/🟢 | + | E — Exclusivity | [X]/100 | [main issue] | 🔴/🟡/🟢 | + | Exp — Experience | [X]/100 | [main issue] | 🔴/🟡/🟢 | + | Ept — Expertise | [X]/100 | [main issue] | 🔴/🟡/🟢 | + | A — Authority | [X]/100 | [main issue] | 🔴/🟡/🟢 | + | T — Trust | [X]/100 | [main issue] | 🔴/🟡/🟢 | + + **Weakest Dimensions** (focus refresh here): + 1. [Dimension] — [what needs fixing] + 2. [Dimension] — [what needs fixing] + + **Refresh Strategy**: Focus on 🔴 dimensions first, then 🟡. + + _For full 80-item audit, use [content-quality-auditor](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/cross-cutting/content-quality-auditor/SKILL.md)_ + ``` + +2. **Identify Content Refresh Candidates** + + ```markdown + ## Content Refresh Analysis + + ### Refresh Candidate Identification + + **Criteria for Content Refresh**: + - Published more than 6 months ago + - Contains dated information (years, statistics) + - Declining traffic trend + - Lost keyword rankings + - Outdated references or broken links + - Missing topics competitors now cover + - No GEO optimization + + ### Content Audit Results + + | Content | Published | Last Updated | Traffic Trend | Priority | + |---------|-----------|--------------|---------------|----------| + | [Title 1] | [date] | [date] | ↓ -45% | 🔴 High | + | [Title 2] | [date] | Never | ↓ -30% | 🔴 High | + | [Title 3] | [date] | [date] | ↓ -20% | 🟡 Medium | + | [Title 4] | [date] | [date] | → 0% | 🟡 Medium | + + ### Refresh Prioritization Matrix + + ``` + High Traffic + High Decline = 🔴 Refresh Immediately + High Traffic + Low Decline = 🟡 Schedule Refresh + Low Traffic + High Decline = 🟡 Evaluate & Decide + Low Traffic + Low Decline = 🟢 Low Priority + ``` + ``` + +3. **Analyze Individual Content for Refresh** + + ```markdown + ## Content Refresh Analysis: [Title] + + **URL**: [URL] + **Published**: [date] + **Last Updated**: [date] + **Word Count**: [X] + + ### Performance Metrics + + | Metric | 6 Mo Ago | Current | Change | + |--------|----------|---------|--------| + | Organic Traffic | [X]/mo | [X]/mo | [+/-X]% | + | Avg Position | [X] | [X] | [+/-X] | + | Impressions | [X] | [X] | [+/-X]% | + | CTR | [X]% | [X]% | [+/-X]% | + + ### Keywords Analysis + + | Keyword | Old Position | Current Position | Change | + |---------|--------------|------------------|--------| + | [kw 1] | [X] | [X] | ↓ [X] | + | [kw 2] | [X] | [X] | ↓ [X] | + | [kw 3] | [X] | [X] | ↓ [X] | + + ### Why This Content Needs Refresh + + 1. **Outdated information**: [specific examples] + 2. **Competitive gap**: [what competitors added] + 3. **Missing topics**: [new subtopics to cover] + 4. **SEO issues**: [current optimization problems] + 5. **GEO potential**: [AI citation opportunities] + ``` + +4. **Identify Specific Updates Needed** + + ```markdown + ## Refresh Requirements + + ### Outdated Elements + + | Element | Current | Update Needed | + |---------|---------|---------------| + | Year references | "[old year]" | Update to [current year] | + | Statistics | "[old stat]" | Find current data | + | Tool mentions | "[old tool]" | Add newer tools | + | Links | [X] broken | Fix or replace | + | Screenshots | Outdated UI | Recapture | + + ### Missing Information + + **Topics competitors now cover that you don't**: + + | Topic | Competitor Coverage | Words Needed | Priority | + |-------|---------------------|--------------|----------| + | [Topic 1] | 3/5 competitors | ~300 words | High | + | [Topic 2] | 2/5 competitors | ~200 words | Medium | + | [Topic 3] | 4/5 competitors | ~400 words | High | + + ### SEO Updates Needed + + - [ ] Update title tag with current year + - [ ] Refresh meta description + - [ ] Add new H2 sections for [topics] + - [ ] Update internal links to newer content + - [ ] Add FAQ section for featured snippets + - [ ] Refresh images and add new alt text + + ### GEO Updates Needed + + - [ ] Add clear definition at start + - [ ] Include quotable statistics with sources + - [ ] Add Q&A formatted sections + - [ ] Update sources with current citations + - [ ] Create standalone factual statements + ``` + +5. **Create Refresh Plan** — Structural changes, content additions, statistics/links/images to update + + > **Reference**: See [references/refresh-templates.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/content-refresher/references/refresh-templates.md) for the full refresh plan template (Step 5). + +6. **Write Refresh Content** — Updated introduction, new sections, refreshed statistics, new FAQ section + + > **Reference**: See [references/refresh-templates.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/content-refresher/references/refresh-templates.md) for the refresh content writing template (Step 6). + +7. **Optimize for GEO During Refresh** — Clear definitions, quotable statements, Q&A sections, updated citations + + > **Reference**: See [references/refresh-templates.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/content-refresher/references/refresh-templates.md) for the GEO enhancement template (Step 7). + +8. **Generate Republishing Strategy** — Date strategy (update/add "last updated"/keep original), technical implementation, promotion plan + + > **Reference**: See [references/refresh-templates.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/content-refresher/references/refresh-templates.md) for the republishing strategy template (Step 8). + +9. **Create Refresh Report** — Summary of changes, updates completed, expected outcomes, next review date + + > **Reference**: See [references/refresh-templates.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/content-refresher/references/refresh-templates.md) for the refresh report template (Step 9). + +## Validation Checkpoints + +### Input Validation +- [ ] Target content URL or title clearly identified +- [ ] Historical performance data available (traffic trends, rankings) +- [ ] Content publish/update dates known +- [ ] If comparing to competitors, competitor URLs provided + +### Output Validation +- [ ] Every recommendation cites specific data points (not generic advice) +- [ ] Outdated elements identified with specific examples and replacement data +- [ ] All suggested additions include word counts and section locations +- [ ] Source of each data point clearly stated (~~analytics data, ~~search console, ~~SEO tool, user-provided, or estimated) + +## Example + +> **Reference**: See [references/refresh-example.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/content-refresher/references/refresh-example.md) for a full worked example (cloud hosting refresh) and the comprehensive content refresh checklist. + +## Tips for Success + +1. **Prioritize by ROI** - Refresh high-potential content first +2. **Don't just add dates** - Make substantial improvements +3. **Beat competitors** - Add what they have and more +4. **Track results** - Monitor ranking changes post-refresh +5. **Schedule regular audits** - Check content health quarterly +6. **Optimize for GEO** - Every refresh is a GEO opportunity + +> **Reference data**: For content decay signal taxonomy, lifecycle stages, refresh vs. rewrite decision framework, and update strategy by content type, see [references/content-decay-signals.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/content-refresher/references/content-decay-signals.md). + + +### Save Results + +After delivering audit or optimization findings to the user, ask: + +> "Save these results for future sessions?" + +If yes, write a dated summary to `memory/audits/content-refresher/YYYY-MM-DD-.md` containing: +- One-line verdict or headline finding +- Top 3-5 actionable items +- Open loops or blockers +- Source data references + +If any veto-level issue was found (CORE-EEAT T04, C01, R10 or CITE T03, T05, T09), also append a one-liner to `memory/hot-cache.md` without asking. + + +**Gate check recommended**: Run content-quality-auditor on refreshed content before republishing. + +## Reference Materials + +- [Content Decay Signals](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/content-refresher/references/content-decay-signals.md) — Decay indicators, lifecycle stages, and refresh triggers by content type +- [Refresh Templates](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/content-refresher/references/refresh-templates.md) — Detailed output templates for steps 5-9 (refresh plan, content writing, GEO enhancement, republishing, report) +- [Refresh Example & Checklist](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/content-refresher/references/refresh-example.md) — Full worked example and pre/post-refresh checklist + +## Next Best Skill + +- **Primary**: [content-quality-auditor](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/cross-cutting/content-quality-auditor/SKILL.md) — re-score the refreshed content before shipping. diff --git a/.cursor/skills/domain-authority-auditor/SKILL.md b/.cursor/skills/domain-authority-auditor/SKILL.md new file mode 100644 index 0000000..1840cfd --- /dev/null +++ b/.cursor/skills/domain-authority-auditor/SKILL.md @@ -0,0 +1,394 @@ +--- +name: domain-authority-auditor +description: '40-item CITE domain audit: citation, impact, trust, entity scoring with veto checks. 域名权威/网站可信度' +version: "6.0.0" +license: Apache-2.0 +compatibility: "Claude Code ≥1.0, skills.sh marketplace, ClawHub marketplace, Vercel Labs skills ecosystem. No system packages required. Optional: MCP network access for SEO tool integrations." +homepage: "https://github.com/aaron-he-zhu/seo-geo-claude-skills" +when_to_use: "Use when auditing domain trust and authority. Runs CITE 40-item scoring with veto checks. Also when the user asks about domain credibility or citation trustworthiness." +argument-hint: "" +metadata: + author: aaron-he-zhu + version: "6.0.0" + geo-relevance: "medium" + tags: + - seo + - geo + - domain-authority + - domain-rating + - domain-trust + - cite-framework + - site-authority + - 域名权威 + - ドメイン権威 + - 도메인권위 + - autoridad-dominio + triggers: + # EN-formal + - "audit domain authority" + - "CITE audit" + - "domain trust score" + - "domain credibility check" + - "domain rating" + - "site authority" + # EN-casual + - "how trustworthy is my site" + - "is my domain credible" + - "is my domain trustworthy" + - "domain credibility score" + - "Google penalty recovery" + - "my site got penalized" + # EN-question + - "how authoritative is my site" + - "what is my domain authority" + # ZH-pro + - "域名权威审计" + - "网站可信度" + - "域名评分" + # ZH-casual + - "域名可信吗" + - "权威度多少" + - "网站可信度怎么样" + # JA + - "ドメイン権威" + - "ドメイン評価" + # KO + - "도메인 권위" + - "도메인 신뢰도" + # ES + - "autoridad de dominio" + - "auditoría de dominio" + # PT + - "autoridade de domínio" + # Misspellings + - "domain autority" +--- + +# Domain Authority Auditor + +> Based on [CITE Domain Rating](https://github.com/aaron-he-zhu/cite-domain-rating). Full benchmark reference: [references/cite-domain-rating.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/cite-domain-rating.md) + +> **[SEO & GEO Skills Library](https://github.com/aaron-he-zhu/seo-geo-claude-skills)** · 20 skills for SEO + GEO · [ClawHub](https://clawhub.ai/u/aaron-he-zhu) · [skills.sh](https://skills.sh/aaron-he-zhu/seo-geo-claude-skills) +> **System Mode**: This cross-cutting skill is part of the protocol layer and follows the shared [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md) and [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md). + + +This skill evaluates domain authority across 40 standardized criteria organized in 4 dimensions. It produces a comprehensive audit report with per-item scoring, dimension and weighted scores by domain type, veto item checks, and a prioritized action plan. + +**Sister skill**: [content-quality-auditor](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/cross-cutting/content-quality-auditor/SKILL.md) evaluates content at the page level (80 items). This skill evaluates the domain behind the content (40 items). Together they provide a complete 120-item assessment. + +> **Namespace note**: CITE uses C01-C10 for Citation items; CORE-EEAT uses C01-C10 for Contextual Clarity items. In combined 120-item assessments, prefix with the framework name (e.g., CITE-C01 vs CORE-C01) to avoid confusion. + +**System role**: Citation Trust Gate. It decides whether a domain is credible enough to support ranking, citation, and brand authority work. + +## When This Must Trigger + +Use this when domain credibility or citation trustworthiness is in question — even if the user doesn't use audit terminology: + +- User asks "how trustworthy is my site" or "is my domain credible" +- When backlink-analyzer finds toxic link ratio above 15%, its handoff summary recommends this gate check +- Evaluating domain authority before a GEO campaign +- Benchmarking your domain against competitors +- Assessing whether a domain is trustworthy as a citation source +- Running periodic domain health checks or after link building campaigns +- Identifying manipulation red flags (PBNs, link farms, penalty history) +- Cross-referencing with content-quality-auditor for full 120-item assessment + +## What This Skill Does + +1. **Full 40-Item Audit**: Scores every CITE check item as Pass/Partial/Fail +2. **Dimension Scoring**: Calculates scores for all 4 dimensions (0-100 each) +3. **Weighted Totals**: Applies domain-type-specific weights for CITE Score +4. **Veto Detection**: Flags critical manipulation signals (T03, T05, T09) +5. **Priority Ranking**: Identifies Top 5 improvements sorted by impact +6. **Action Plan**: Generates specific, actionable improvement steps +7. **Cross-Reference**: Optionally pairs with CORE-EEAT for combined diagnosis + +## Quick Start + +Start with one of these prompts. Finish with a citation-trust verdict and a handoff summary using the repository format in [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md). + +### Audit Your Domain + +``` +Audit domain authority for [domain] +Run a CITE domain audit on [domain] as a [domain type] +``` + +### Audit with Domain Type + +``` +CITE audit for example.com as an e-commerce site +Score this SaaS domain against the 40-item benchmark: [domain] +``` + +### Comparative Audit + +``` +Compare domain authority: [your domain] vs [competitor 1] vs [competitor 2] +``` + +### Combined Assessment + +``` +Run full 120-item assessment on [domain]: CITE domain audit + CORE-EEAT content audit on [sample pages] +``` + +## Skill Contract + +**Gate verdict**: **TRUSTED** (no veto items, scores above threshold) / **CAUTIOUS** (issues found but no veto) / **UNTRUSTED** (veto item T03, T05, or T09 failed). Always state the verdict prominently at the top of the report. + +**Expected output**: a CITE audit report, a citation-trust verdict, and a short handoff summary ready for `memory/audits/domain/`. + +- **Reads**: the target domain, supporting authority signals, comparison domains, and prior decisions from [CLAUDE.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CLAUDE.md) and the shared [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md) when available. +- **Writes**: a user-facing authority report plus a reusable summary that can be stored under `memory/audits/domain/`. +- **Promotes**: veto items and domain risks to `memory/hot-cache.md` (auto-saved). Authority context to `memory/audits/domain/`. Results feed into entity-optimizer as authority input for brand's canonical profile. +- **Next handoff**: use the `Next Best Skill` below once the trust picture is clear. + +## Data Sources + +> See [CONNECTORS.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CONNECTORS.md) for tool category placeholders. + +> **Note:** All integrations are optional. This skill works without any API keys — users provide data manually when no tools are connected. + +**With ~~link database + ~~SEO tool + ~~AI monitor + ~~knowledge graph + ~~brand monitor connected:** +Automatically pull backlink profiles and link quality metrics from ~~link database, domain authority scores and keyword rankings from ~~SEO tool, AI citation data from ~~AI monitor, entity presence from ~~knowledge graph, and brand mention data from ~~brand monitor. + +**With manual data only:** +Ask the user to provide: +1. Domain to evaluate +2. Domain type (if not auto-detectable): Content Publisher, Product & Service, E-commerce, Community & UGC, Tool & Utility, or Authority & Institutional +3. Backlink data: referring domains count, domain authority, top linking domains +4. Traffic estimates (from any SEO tool or SimilarWeb) +5. Competitor domains for comparison (optional) + +Proceed with the full 40-item audit using provided data. Note in the output which items could not be fully evaluated due to missing access (e.g., AI citation data, knowledge graph queries, WHOIS history). + +## Instructions + +When a user requests a domain authority audit: + +### Step 1: Preparation + +```markdown +### Audit Setup + +**Domain**: [domain] +**Domain Type**: [auto-detected or user-specified] +**Dimension Weights**: [from domain-type weight table below] + +#### Domain-Type Weight Table + +> Canonical source: `references/cite-domain-rating.md`. This inline copy is for convenience. + +| Dim | Default | Content Publisher | Product & Service | E-commerce | Community & UGC | Tool & Utility | Authority & Institutional | +|-----|:-------:|:-:|:-:|:-:|:-:|:-:|:-:| +| C | 35% | **40%** | 25% | 20% | 35% | 25% | **45%** | +| I | 20% | 15% | **30%** | 20% | 10% | **30%** | 20% | +| T | 25% | 20% | 25% | **35%** | 25% | 25% | 20% | +| E | 20% | 25% | 20% | 25% | **30%** | 20% | 15% | + +#### Veto Check (Emergency Brake) + +| Veto Item | Status | Action | +|-----------|--------|--------| +| T03: Link-Traffic Coherence | ✅ Pass / ⚠️ VETO | [If VETO: "Audit backlink profile; disavow toxic links"] | +| T05: Backlink Profile Uniqueness | ✅ Pass / ⚠️ VETO | [If VETO: "Flag as manipulation network; investigate link sources"] | +| T09: Penalty & Deindex History | ✅ Pass / ⚠️ VETO | [If VETO: "Address penalty first; all other optimization is futile"] | +``` + +If any veto item triggers, flag it prominently at the top of the report. CITE Score is capped at 39 (Poor) regardless of other scores. + +### Step 2: C + I Audit (20 items) + +Evaluate each item against the criteria in [references/cite-domain-rating.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/cite-domain-rating.md). + +Score each item: +- **Pass** = 10 points (fully meets criteria) +- **Partial** = 5 points (partially meets criteria) +- **Fail** = 0 points (does not meet criteria) + +```markdown +### C — Citation + +| ID | Check Item | Score | Notes | +|----|-----------|-------|-------| +| C01 | Referring Domains Volume | Pass/Partial/Fail | [specific observation] | +| C02 | Referring Domains Quality | Pass/Partial/Fail | [specific observation] | +| ... | ... | ... | ... | +| C10 | Link Source Diversity | Pass/Partial/Fail | [specific observation] | + +**C Score**: [X]/100 + +### I — Identity + +| ID | Check Item | Score | Notes | +|----|-----------|-------|-------| +| I01 | Knowledge Graph Presence | Pass/Partial/Fail | [specific observation] | +| ... | ... | ... | ... | + +**I Score**: [X]/100 +``` + +### Step 3: T + E Audit (20 items) + +Same format for Trust and Eminence dimensions. + +```markdown +### T — Trust + +| ID | Check Item | Score | Notes | +|----|-----------|-------|-------| +| T01 | Link Profile Naturalness | Pass/Partial/Fail | [specific observation] | +| ... | ... | ... | ... | + +**T Score**: [X]/100 + +### E — Eminence + +| ID | Check Item | Score | Notes | +|----|-----------|-------|-------| +| E01 | Organic Search Visibility | Pass/Partial/Fail | [specific observation] | +| ... | ... | ... | ... | + +**E Score**: [X]/100 +``` + +**Note**: Some items require specialized data (C05-C08 AI citation data, I01 knowledge graph queries, T04-T05 IP/profile analysis). Score what is observable; mark unverifiable items as "N/A — requires [data source]" and exclude from dimension average. + +### Step 4: Scoring & Report + +Calculate scores and generate the final report: + +```markdown +## CITE Domain Authority Report + +### Overview + +- **Domain**: [domain] +- **Domain Type**: [type] +- **Audit Date**: [date] +- **CITE Score**: [score]/100 ([rating]) +- **Veto Status**: ✅ No triggers / ⚠️ [item] triggered — Score capped at 39 + +### Dimension Scores + +| Dimension | Score | Rating | Weight | Weighted | +|-----------|-------|--------|--------|----------| +| C — Citation | [X]/100 | [rating] | [X]% | [X] | +| I — Identity | [X]/100 | [rating] | [X]% | [X] | +| T — Trust | [X]/100 | [rating] | [X]% | [X] | +| E — Eminence | [X]/100 | [rating] | [X]% | [X] | +| **CITE Score** | | | | **[X]/100** | + +**Score Calculation**: CITE Score = C × [w_C] + I × [w_I] + T × [w_T] + E × [w_E] + +**Rating Scale**: 90-100 Excellent | 75-89 Good | 60-74 Medium | 40-59 Low | 0-39 Poor + +### Per-Item Scores + +| ID | Check Item | Score | Notes | +|----|-----------|-------|-------| +| C01 | Referring Domains Volume | [Pass/Partial/Fail] | [observation] | +| C02 | Referring Domains Quality | [Pass/Partial/Fail] | [observation] | +| ... | ... | ... | ... | +| E10 | Industry Share of Voice | [Pass/Partial/Fail] | [observation] | + +### Top 5 Priority Improvements + +Sorted by: weight × points lost (highest impact first) + +1. **[ID] [Name]** — [specific modification suggestion] + - Current: [Fail/Partial] | Potential gain: [X] weighted points + - Action: [concrete step] +2. **[ID] [Name]** — [specific modification suggestion] + - Current: [Fail/Partial] | Potential gain: [X] weighted points + - Action: [concrete step] +3–5. [Same format] + +### Action Plan + +#### Quick Wins (< 1 week) +- [ ] [Action 1] +- [ ] [Action 2] +#### Medium Effort (1-4 weeks) +- [ ] [Action 3] +- [ ] [Action 4] +#### Strategic (1-3 months) +- [ ] [Action 5] +- [ ] [Action 6] + +### Cross-Reference with CORE-EEAT + +For a complete assessment, pair this CITE audit with a CORE-EEAT content audit: + +| Assessment | Score | Rating | +|-----------|-------|--------| +| CITE (Domain) | [X]/100 | [rating] | +| CORE-EEAT (Content) | [Run content-quality-auditor on sample pages] | — | + +**Diagnosis Matrix**: +- High CITE + High CORE-EEAT → Maintain and expand +- High CITE + Low CORE-EEAT → Prioritize content quality +- Low CITE + High CORE-EEAT → Build domain authority +- Low CITE + Low CORE-EEAT → Start with content, then domain + +### Recommended Next Steps + +- For domain authority building: focus on top 5 priorities above +- For content improvement: use `content-quality-auditor` on key pages +- For backlink strategy: use `backlink-analyzer` for detailed link analysis +- For competitor benchmarking: use `competitor-analysis` with CITE scores +- For tracking progress: run `/seo:report` with CITE score trends +``` + +### Save Results + +After delivering findings to the user, ask: + +> "Save these results for future sessions?" + +If yes, write a dated summary to the appropriate `memory/` path using filename `YYYY-MM-DD-.md` containing: +- One-line verdict or headline finding +- Top 3-5 actionable items +- Open loops or blockers +- Source data references + +If any veto-level issue was found (CORE-EEAT T04, C01, R10 or CITE T03, T05, T09), also append a one-liner to `memory/hot-cache.md` without asking. + +## Validation Checkpoints + +### Input Validation +- [ ] Domain identified and accessible +- [ ] Domain type confirmed (auto-detected or user-specified) +- [ ] Backlink data available (at minimum: referring domains count, DA/DR) +- [ ] If comparative audit, competitor domains also specified + +### Output Validation +- [ ] All 40 items scored (or marked N/A with reason) +- [ ] All 4 dimension scores calculated correctly +- [ ] Weighted CITE Score matches domain-type weight configuration +- [ ] All 3 veto items checked first and flagged if triggered +- [ ] Top 5 improvements sorted by weighted impact, not arbitrary +- [ ] Every recommendation is specific and actionable (not generic advice) +- [ ] Action plan includes concrete steps with effort estimates + +## Example + +See [references/example-report.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/cross-cutting/domain-authority-auditor/references/example-report.md) for a complete CITE audit of cloudhosting.com showing veto check, dimension scores, top 5 improvements, action plan, and cross-reference with CORE-EEAT. + +## Tips for Success + +1. **Start with veto items** — T03, T05, T09 can invalidate the entire score +2. **Identify domain type first** — Different types have very different weight profiles +3. **AI citation items (C05-C08) matter most for GEO** — Test by querying AI engines with niche-relevant questions +4. **Some items need specialized tools** — Knowledge graph queries, AI citation monitoring, and IP diversity analysis may require manual research if tools aren't connected +5. **Pair with CORE-EEAT for full picture** — Domain authority without content quality (or vice versa) tells only half the story + +## Reference Materials + +- [CITE Domain Rating](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/cite-domain-rating.md) — Full 40-item benchmark with dimension definitions, scoring criteria, domain-type weight tables, and veto items +- [references/example-report.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/cross-cutting/domain-authority-auditor/references/example-report.md) — Complete CITE audit example with scored dimensions, top 5 improvements, action plan, and CORE-EEAT cross-reference + +## Next Best Skill + +- **Primary**: [backlink-analyzer](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/monitor/backlink-analyzer/SKILL.md) — turn trust or citation issues into link-level investigation. diff --git a/.cursor/skills/emil-design-eng/SKILL.md b/.cursor/skills/emil-design-eng/SKILL.md new file mode 100644 index 0000000..4911235 --- /dev/null +++ b/.cursor/skills/emil-design-eng/SKILL.md @@ -0,0 +1,679 @@ +--- +name: emil-design-eng +description: This skill encodes Emil Kowalski's philosophy on UI polish, component design, animation decisions, and the invisible details that make software feel great. +--- + +# Design Engineering + +## Initial Response + +When this skill is first invoked without a specific question, respond only with: + +> I'm ready to help you build interfaces that feel right, my knowledge comes from Emil Kowalski's design engineering philosophy. If you want to dive even deeper, check out Emil’s course: [animations.dev](https://animations.dev/). + +Do not provide any other information until the user asks a question. + +You are a design engineer with the craft sensibility. You build interfaces where every detail compounds into something that feels right. You understand that in a world where everyone's software is good enough, taste is the differentiator. + +## Core Philosophy + +### Taste is trained, not innate + +Good taste is not personal preference. It is a trained instinct: the ability to see beyond the obvious and recognize what elevates. You develop it by surrounding yourself with great work, thinking deeply about why something feels good, and practicing relentlessly. + +When building UI, don't just make it work. Study why the best interfaces feel the way they do. Reverse engineer animations. Inspect interactions. Be curious. + +### Unseen details compound + +Most details users never consciously notice. That is the point. When a feature functions exactly as someone assumes it should, they proceed without giving it a second thought. That is the goal. + +> "All those unseen details combine to produce something that's just stunning, like a thousand barely audible voices all singing in tune." - Paul Graham + +Every decision below exists because the aggregate of invisible correctness creates interfaces people love without knowing why. + +### Beauty is leverage + +People select tools based on the overall experience, not just functionality. Good defaults and good animations are real differentiators. Beauty is underutilized in software. Use it as leverage to stand out. + +## Review Format (Required) + +When reviewing UI code, you MUST use a markdown table with Before/After columns. Do NOT use a list with "Before:" and "After:" on separate lines. Always output an actual markdown table like this: + +| Before | After | Why | +| --- | --- | --- | +| `transition: all 300ms` | `transition: transform 200ms ease-out` | Specify exact properties; avoid `all` | +| `transform: scale(0)` | `transform: scale(0.95); opacity: 0` | Nothing in the real world appears from nothing | +| `ease-in` on dropdown | `ease-out` with custom curve | `ease-in` feels sluggish; `ease-out` gives instant feedback | +| No `:active` state on button | `transform: scale(0.97)` on `:active` | Buttons must feel responsive to press | +| `transform-origin: center` on popover | `transform-origin: var(--radix-popover-content-transform-origin)` | Popovers should scale from their trigger (not modals — modals stay centered) | + +Wrong format (never do this): + +``` +Before: transition: all 300ms +After: transition: transform 200ms ease-out +──────────────────────────── +Before: scale(0) +After: scale(0.95) +``` + +Correct format: A single markdown table with | Before | After | Why | columns, one row per issue found. The "Why" column briefly explains the reasoning. + +## The Animation Decision Framework + +Before writing any animation code, answer these questions in order: + +### 1. Should this animate at all? + +**Ask:** How often will users see this animation? + +| Frequency | Decision | +| ----------------------------------------------------------- | ---------------------------- | +| 100+ times/day (keyboard shortcuts, command palette toggle) | No animation. Ever. | +| Tens of times/day (hover effects, list navigation) | Remove or drastically reduce | +| Occasional (modals, drawers, toasts) | Standard animation | +| Rare/first-time (onboarding, feedback forms, celebrations) | Can add delight | + +**Never animate keyboard-initiated actions.** These actions are repeated hundreds of times daily. Animation makes them feel slow, delayed, and disconnected from the user's actions. + +Raycast has no open/close animation. That is the optimal experience for something used hundreds of times a day. + +### 2. What is the purpose? + +Every animation must have a clear answer to "why does this animate?" + +Valid purposes: + +- **Spatial consistency**: toast enters and exits from the same direction, making swipe-to-dismiss feel intuitive +- **State indication**: a morphing feedback button shows the state change +- **Explanation**: a marketing animation that shows how a feature works +- **Feedback**: a button scales down on press, confirming the interface heard the user +- **Preventing jarring changes**: elements appearing or disappearing without transition feel broken + +If the purpose is just "it looks cool" and the user will see it often, don't animate. + +### 3. What easing should it use? + +Is the element entering or exiting? + Yes → ease-out (starts fast, feels responsive) + No → + Is it moving/morphing on screen? + Yes → ease-in-out (natural acceleration/deceleration) + Is it a hover/color change? + Yes → ease + Is it constant motion (marquee, progress bar)? + Yes → linear + Default → ease-out + +**Critical: use custom easing curves.** The built-in CSS easings are too weak. They lack the punch that makes animations feel intentional. + +```css +/* Strong ease-out for UI interactions */ +--ease-out: cubic-bezier(0.23, 1, 0.32, 1); + +/* Strong ease-in-out for on-screen movement */ +--ease-in-out: cubic-bezier(0.77, 0, 0.175, 1); + +/* iOS-like drawer curve (from Ionic Framework) */ +--ease-drawer: cubic-bezier(0.32, 0.72, 0, 1); +``` + +**Never use ease-in for UI animations.** It starts slow, which makes the interface feel sluggish and unresponsive. A dropdown with `ease-in` at 300ms _feels_ slower than `ease-out` at the same 300ms, because ease-in delays the initial movement — the exact moment the user is watching most closely. + +**Easing curve resources:** Don't create curves from scratch. Use [easing.dev](https://easing.dev/) or [easings.co](https://easings.co/) to find stronger custom variants of standard easings. + +### 4. How fast should it be? + +| Element | Duration | +| ------------------------ | ------------- | +| Button press feedback | 100-160ms | +| Tooltips, small popovers | 125-200ms | +| Dropdowns, selects | 150-250ms | +| Modals, drawers | 200-500ms | +| Marketing/explanatory | Can be longer | + +**Rule: UI animations should stay under 300ms.** A 180ms dropdown feels more responsive than a 400ms one. A faster-spinning spinner makes the app feel like it loads faster, even when the load time is identical. + +### Perceived performance + +Speed in animation is not just about feeling snappy — it directly affects how users perceive your app's performance: + +- A **fast-spinning spinner** makes loading feel faster (same load time, different perception) +- A **180ms select** animation feels more responsive than a **400ms** one +- **Instant tooltips** after the first one is open (skip delay + skip animation) make the whole toolbar feel faster + +The perception of speed matters as much as actual speed. Easing amplifies this: `ease-out` at 200ms _feels_ faster than `ease-in` at 200ms because the user sees immediate movement. + +## Spring Animations + +Springs feel more natural than duration-based animations because they simulate real physics. They don't have fixed durations — they settle based on physical parameters. + +### When to use springs + +- Drag interactions with momentum +- Elements that should feel "alive" (like Apple's Dynamic Island) +- Gestures that can be interrupted mid-animation +- Decorative mouse-tracking interactions + +### Spring-based mouse interactions + +Tying visual changes directly to mouse position feels artificial because it lacks motion. Use `useSpring` from Motion (formerly Framer Motion) to interpolate value changes with spring-like behavior instead of updating immediately. + +```jsx +import { useSpring } from 'framer-motion'; + +// Without spring: feels artificial, instant +const rotation = mouseX * 0.1; + +// With spring: feels natural, has momentum +const springRotation = useSpring(mouseX * 0.1, { + stiffness: 100, + damping: 10, +}); +``` + +This works because the animation is **decorative** — it doesn't serve a function. If this were a functional graph in a banking app, no animation would be better. Know when decoration helps and when it hinders. + +### Spring configuration + +**Apple's approach (recommended — easier to reason about):** + +```js +{ type: "spring", duration: 0.5, bounce: 0.2 } +``` + +**Traditional physics (more control):** + +```js +{ type: "spring", mass: 1, stiffness: 100, damping: 10 } +``` + +Keep bounce subtle (0.1-0.3) when used. Avoid bounce in most UI contexts. Use it for drag-to-dismiss and playful interactions. + +### Interruptibility advantage + +Springs maintain velocity when interrupted — CSS animations and keyframes restart from zero. This makes springs ideal for gestures users might change mid-motion. When you click an expanded item and quickly press Escape, a spring-based animation smoothly reverses from its current position. + +## Component Building Principles + +### Buttons must feel responsive + +Add `transform: scale(0.97)` on `:active`. This gives instant feedback, making the UI feel like it is truly listening to the user. + +```css +.button { + transition: transform 160ms ease-out; +} + +.button:active { + transform: scale(0.97); +} +``` + +This applies to any pressable element. The scale should be subtle (0.95-0.98). + +### Never animate from scale(0) + +Nothing in the real world disappears and reappears completely. Elements animating from `scale(0)` look like they come out of nowhere. + +Start from `scale(0.9)` or higher, combined with opacity. Even a barely-visible initial scale makes the entrance feel more natural, like a balloon that has a visible shape even when deflated. + +```css +/* Bad */ +.entering { + transform: scale(0); +} + +/* Good */ +.entering { + transform: scale(0.95); + opacity: 0; +} +``` + +### Make popovers origin-aware + +Popovers should scale in from their trigger, not from center. The default `transform-origin: center` is wrong for almost every popover. **Exception: modals.** Modals should keep `transform-origin: center` because they are not anchored to a specific trigger — they appear centered in the viewport. + +```css +/* Radix UI */ +.popover { + transform-origin: var(--radix-popover-content-transform-origin); +} + +/* Base UI */ +.popover { + transform-origin: var(--transform-origin); +} +``` + +Whether the user notices the difference individually does not matter. In the aggregate, unseen details become visible. They compound. + +### Tooltips: skip delay on subsequent hovers + +Tooltips should delay before appearing to prevent accidental activation. But once one tooltip is open, hovering over adjacent tooltips should open them instantly with no animation. This feels faster without defeating the purpose of the initial delay. + +```css +.tooltip { + transition: transform 125ms ease-out, opacity 125ms ease-out; + transform-origin: var(--transform-origin); +} + +.tooltip[data-starting-style], +.tooltip[data-ending-style] { + opacity: 0; + transform: scale(0.97); +} + +/* Skip animation on subsequent tooltips */ +.tooltip[data-instant] { + transition-duration: 0ms; +} +``` + +### Use CSS transitions over keyframes for interruptible UI + +CSS transitions can be interrupted and retargeted mid-animation. Keyframes restart from zero. For any interaction that can be triggered rapidly (adding toasts, toggling states), transitions produce smoother results. + +```css +/* Interruptible - good for UI */ +.toast { + transition: transform 400ms ease; +} + +/* Not interruptible - avoid for dynamic UI */ +@keyframes slideIn { + from { + transform: translateY(100%); + } + to { + transform: translateY(0); + } +} +``` + +### Use blur to mask imperfect transitions + +When a crossfade between two states feels off despite trying different easings and durations, add subtle `filter: blur(2px)` during the transition. + +**Why blur works:** Without blur, you see two distinct objects during a crossfade — the old state and the new state overlapping. This looks unnatural. Blur bridges the visual gap by blending the two states together, tricking the eye into perceiving a single smooth transformation instead of two objects swapping. + +Combine blur with scale-on-press (`scale(0.97)`) for a polished button state transition: + +```css +.button { + transition: transform 160ms ease-out; +} + +.button:active { + transform: scale(0.97); +} + +.button-content { + transition: filter 200ms ease, opacity 200ms ease; +} + +.button-content.transitioning { + filter: blur(2px); + opacity: 0.7; +} +``` + +Keep blur under 20px. Heavy blur is expensive, especially in Safari. + +### Animate enter states with @starting-style + +The modern CSS way to animate element entry without JavaScript: + +```css +.toast { + opacity: 1; + transform: translateY(0); + transition: opacity 400ms ease, transform 400ms ease; + + @starting-style { + opacity: 0; + transform: translateY(100%); + } +} +``` + +This replaces the common React pattern of using `useEffect` to set `mounted: true` after initial render. Use `@starting-style` when browser support allows; fall back to the `data-mounted` attribute pattern otherwise. + +```jsx +// Legacy pattern (still works everywhere) +useEffect(() => { + setMounted(true); +}, []); +//
+``` + +## CSS Transform Mastery + +### translateY with percentages + +Percentage values in `translate()` are relative to the element's own size. Use `translateY(100%)` to move an element by its own height, regardless of actual dimensions. This is how Sonner positions toasts and how Vaul hides the drawer before animating in. + +```css +/* Works regardless of drawer height */ +.drawer-hidden { + transform: translateY(100%); +} + +/* Works regardless of toast height */ +.toast-enter { + transform: translateY(-100%); +} +``` + +Prefer percentages over hardcoded pixel values. They are less error-prone and adapt to content. + +### scale() scales children too + +Unlike `width`/`height`, `scale()` also scales an element's children. When scaling a button on press, the font size, icons, and content scale proportionally. This is a feature, not a bug. + +### 3D transforms for depth + +`rotateX()`, `rotateY()` with `transform-style: preserve-3d` create real 3D effects in CSS. Orbiting animations, coin flips, and depth effects are all possible without JavaScript. + +```css +.wrapper { + transform-style: preserve-3d; +} + +@keyframes orbit { + from { + transform: translate(-50%, -50%) rotateY(0deg) translateZ(72px) rotateY(360deg); + } + to { + transform: translate(-50%, -50%) rotateY(360deg) translateZ(72px) rotateY(0deg); + } +} +``` + +### transform-origin + +Every element has an anchor point from which transforms execute. The default is center. Set it to match where the trigger lives for origin-aware interactions. + +## clip-path for Animation + +`clip-path` is not just for shapes. It is one of the most powerful animation tools in CSS. + +### The inset shape + +`clip-path: inset(top right bottom left)` defines a rectangular clipping region. Each value "eats" into the element from that side. + +```css +/* Fully hidden from right */ +.hidden { + clip-path: inset(0 100% 0 0); +} + +/* Fully visible */ +.visible { + clip-path: inset(0 0 0 0); +} + +/* Reveal from left to right */ +.overlay { + clip-path: inset(0 100% 0 0); + transition: clip-path 200ms ease-out; +} +.button:active .overlay { + clip-path: inset(0 0 0 0); + transition: clip-path 2s linear; +} +``` + +### Tabs with perfect color transitions + +Duplicate the tab list. Style the copy as "active" (different background, different text color). Clip the copy so only the active tab is visible. Animate the clip on tab change. This creates a seamless color transition that timing individual color transitions can never achieve. + +### Hold-to-delete pattern + +Use `clip-path: inset(0 100% 0 0)` on a colored overlay. On `:active`, transition to `inset(0 0 0 0)` over 2s with linear timing. On release, snap back with 200ms ease-out. Add `scale(0.97)` on the button for press feedback. + +### Image reveals on scroll + +Start with `clip-path: inset(0 0 100% 0)` (hidden from bottom). Animate to `inset(0 0 0 0)` when the element enters the viewport. Use `IntersectionObserver` or Framer Motion's `useInView` with `{ once: true, margin: "-100px" }`. + +### Comparison sliders + +Overlay two images. Clip the top one with `clip-path: inset(0 50% 0 0)`. Adjust the right inset value based on drag position. No extra DOM elements needed, fully hardware-accelerated. + +## Gesture and Drag Interactions + +### Momentum-based dismissal + +Don't require dragging past a threshold. Calculate velocity: `Math.abs(dragDistance) / elapsedTime`. If velocity exceeds ~0.11, dismiss regardless of distance. A quick flick should be enough. + +```js +const timeTaken = new Date().getTime() - dragStartTime.current.getTime(); +const velocity = Math.abs(swipeAmount) / timeTaken; + +if (Math.abs(swipeAmount) >= SWIPE_THRESHOLD || velocity > 0.11) { + dismiss(); +} +``` + +### Damping at boundaries + +When a user drags past the natural boundary (e.g., dragging a drawer up when already at top), apply damping. The more they drag, the less the element moves. Things in real life don't suddenly stop; they slow down first. + +### Pointer capture for drag + +Once dragging starts, set the element to capture all pointer events. This ensures dragging continues even if the pointer leaves the element bounds. + +### Multi-touch protection + +Ignore additional touch points after the initial drag begins. Without this, switching fingers mid-drag causes the element to jump to the new position. + +```js +function onPress() { + if (isDragging) return; + // Start drag... +} +``` + +### Friction instead of hard stops + +Instead of preventing upward drag entirely, allow it with increasing friction. It feels more natural than hitting an invisible wall. + +## Performance Rules + +### Only animate transform and opacity + +These properties skip layout and paint, running on the GPU. Animating `padding`, `margin`, `height`, or `width` triggers all three rendering steps. + +### CSS variables are inheritable + +Changing a CSS variable on a parent recalculates styles for all children. In a drawer with many items, updating `--swipe-amount` on the container causes expensive style recalculation. Update `transform` directly on the element instead. + +```js +// Bad: triggers recalc on all children +element.style.setProperty('--swipe-amount', `${distance}px`); + +// Good: only affects this element +element.style.transform = `translateY(${distance}px)`; +``` + +### Framer Motion hardware acceleration caveat + +Framer Motion's shorthand properties (`x`, `y`, `scale`) are NOT hardware-accelerated. They use `requestAnimationFrame` on the main thread. For hardware acceleration, use the full `transform` string: + +```jsx +// NOT hardware accelerated (convenient but drops frames under load) + + +// Hardware accelerated (stays smooth even when main thread is busy) + +``` + +This matters when the browser is simultaneously loading content, running scripts, or painting. At Vercel, the dashboard tab animation used Shared Layout Animations and dropped frames during page loads. Switching to CSS animations (off main thread) fixed it. + +### CSS animations beat JS under load + +CSS animations run off the main thread. When the browser is busy loading a new page, Framer Motion animations (using `requestAnimationFrame`) drop frames. CSS animations remain smooth. Use CSS for predetermined animations; JS for dynamic, interruptible ones. + +### Use WAAPI for programmatic CSS animations + +The Web Animations API gives you JavaScript control with CSS performance. Hardware-accelerated, interruptible, and no library needed. + +```js +element.animate([{ clipPath: 'inset(0 0 100% 0)' }, { clipPath: 'inset(0 0 0 0)' }], { + duration: 1000, + fill: 'forwards', + easing: 'cubic-bezier(0.77, 0, 0.175, 1)', +}); +``` + +## Accessibility + +### prefers-reduced-motion + +Animations can cause motion sickness. Reduced motion means fewer and gentler animations, not zero. Keep opacity and color transitions that aid comprehension. Remove movement and position animations. + +```css +@media (prefers-reduced-motion: reduce) { + .element { + animation: fade 0.2s ease; + /* No transform-based motion */ + } +} +``` + +```jsx +const shouldReduceMotion = useReducedMotion(); +const closedX = shouldReduceMotion ? 0 : '-100%'; +``` + +### Touch device hover states + +```css +@media (hover: hover) and (pointer: fine) { + .element:hover { + transform: scale(1.05); + } +} +``` + +Touch devices trigger hover on tap, causing false positives. Gate hover animations behind this media query. + +## The Sonner Principles (Building Loved Components) + +These principles come from building Sonner (13M+ weekly npm downloads) and apply to any component: + +1. **Developer experience is key.** No hooks, no context, no complex setup. Insert `` once, call `toast()` from anywhere. The less friction to adopt, the more people will use it. + +2. **Good defaults matter more than options.** Ship beautiful out of the box. Most users never customize. The default easing, timing, and visual design should be excellent. + +3. **Naming creates identity.** "Sonner" (French for "to ring") feels more elegant than "react-toast". Sacrifice discoverability for memorability when appropriate. + +4. **Handle edge cases invisibly.** Pause toast timers when the tab is hidden. Fill gaps between stacked toasts with pseudo-elements to maintain hover state. Capture pointer events during drag. Users never notice these, and that is exactly right. + +5. **Use transitions, not keyframes, for dynamic UI.** Toasts are added rapidly. Keyframes restart from zero on interruption. Transitions retarget smoothly. + +6. **Build a great documentation site.** Let people touch the product, play with it, and understand it before they use it. Interactive examples with ready-to-use code snippets lower the barrier to adoption. + +### Cohesion matters + +Sonner's animation feels satisfying partly because the whole experience is cohesive. The easing and duration fit the vibe of the library. It is slightly slower than typical UI animations and uses `ease` rather than `ease-out` to feel more elegant. The animation style matches the toast design, the page design, the name — everything is in harmony. + +When choosing animation values, consider the personality of the component. A playful component can be bouncier. A professional dashboard should be crisp and fast. Match the motion to the mood. + +### The opacity + height combination + +When items enter and exit a list (like Family's drawer), the opacity change must work well with the height animation. This is often trial and error. There is no formula — you adjust until it feels right. + +### Review your work the next day + +Review animations with fresh eyes. You notice imperfections the next day that you missed during development. Play animations in slow motion or frame by frame to spot timing issues that are invisible at full speed. + +### Asymmetric enter/exit timing + +Pressing should be slow when it needs to be deliberate (hold-to-delete: 2s linear), but release should always be snappy (200ms ease-out). This pattern applies broadly: slow where the user is deciding, fast where the system is responding. + +```css +/* Release: fast */ +.overlay { + transition: clip-path 200ms ease-out; +} + +/* Press: slow and deliberate */ +.button:active .overlay { + transition: clip-path 2s linear; +} +``` + +## Stagger Animations + +When multiple elements enter together, stagger their appearance. Each element animates in with a small delay after the previous one. This creates a cascading effect that feels more natural than everything appearing at once. + +```css +.item { + opacity: 0; + transform: translateY(8px); + animation: fadeIn 300ms ease-out forwards; +} + +.item:nth-child(1) { + animation-delay: 0ms; +} +.item:nth-child(2) { + animation-delay: 50ms; +} +.item:nth-child(3) { + animation-delay: 100ms; +} +.item:nth-child(4) { + animation-delay: 150ms; +} + +@keyframes fadeIn { + to { + opacity: 1; + transform: translateY(0); + } +} +``` + +Keep stagger delays short (30-80ms between items). Long delays make the interface feel slow. Stagger is decorative — never block interaction while stagger animations are playing. + +## Debugging Animations + +### Slow motion testing + +Play animations at reduced speed to spot issues invisible at full speed. Temporarily increase duration to 2-5x normal, or use browser DevTools animation inspector to slow playback. + +Things to look for in slow motion: + +- Do colors transition smoothly, or do you see two distinct states overlapping? +- Does the easing feel right, or does it start/stop abruptly? +- Is the transform-origin correct, or does the element scale from the wrong point? +- Are multiple animated properties (opacity, transform, color) in sync? + +### Frame-by-frame inspection + +Step through animations frame by frame in Chrome DevTools (Animations panel). This reveals timing issues between coordinated properties that you cannot see at full speed. + +### Test on real devices + +For touch interactions (drawers, swipe gestures), test on physical devices. Connect your phone via USB, visit your local dev server by IP address, and use Safari's remote devtools. The Xcode Simulator is an alternative but real hardware is better for gesture testing. + +## Review Checklist + +When reviewing UI code, check for: + +| Issue | Fix | +| ------------------------------------------ | ---------------------------------------------------------------- | +| `transition: all` | Specify exact properties: `transition: transform 200ms ease-out` | +| `scale(0)` entry animation | Start from `scale(0.95)` with `opacity: 0` | +| `ease-in` on UI element | Switch to `ease-out` or custom curve | +| `transform-origin: center` on popover | Set to trigger location or use Radix/Base UI CSS variable (modals are exempt — keep centered) | +| Animation on keyboard action | Remove animation entirely | +| Duration > 300ms on UI element | Reduce to 150-250ms | +| Hover animation without media query | Add `@media (hover: hover) and (pointer: fine)` | +| Keyframes on rapidly-triggered element | Use CSS transitions for interruptibility | +| Framer Motion `x`/`y` props under load | Use `transform: "translateX()"` for hardware acceleration | +| Same enter/exit transition speed | Make exit faster than enter (e.g., enter 2s, exit 200ms) | +| Elements all appear at once | Add stagger delay (30-80ms between items) | diff --git a/.cursor/skills/entity-optimizer/SKILL.md b/.cursor/skills/entity-optimizer/SKILL.md new file mode 100644 index 0000000..7a2a6c5 --- /dev/null +++ b/.cursor/skills/entity-optimizer/SKILL.md @@ -0,0 +1,376 @@ +--- +name: entity-optimizer +description: 'Build entity presence in Knowledge Graph, Wikidata, AI systems for brand recognition and citations. 实体优化/知识图谱' +version: "6.0.0" +license: Apache-2.0 +compatibility: "Claude Code ≥1.0, skills.sh marketplace, ClawHub marketplace, Vercel Labs skills ecosystem. No system packages required. Optional: MCP network access for SEO tool integrations." +homepage: "https://github.com/aaron-he-zhu/seo-geo-claude-skills" +when_to_use: "Use when optimizing entity presence for Knowledge Graph, Wikidata, or AI engine disambiguation. Also for brand entity canonicalization." +argument-hint: "" +metadata: + author: aaron-he-zhu + version: "6.0.0" + geo-relevance: "high" + tags: + - seo + - geo + - entity-optimization + - knowledge-graph + - knowledge-panel + - brand-entity + - wikidata + - entity-disambiguation + - 实体优化 + - エンティティ + - 엔티티 + - entidad-seo + triggers: + # EN-formal + - "optimize entity presence" + - "build knowledge graph" + - "improve knowledge panel" + - "entity audit" + - "establish brand entity" + - "entity disambiguation" + # EN-casual + - "Google doesn't know my brand" + - "no knowledge panel" + - "establish my brand" + - "establish my brand as an entity" + - "get a Google knowledge card" + - "no Wikipedia entry" + # EN-question + - "how to get a knowledge panel" + - "how to build brand entity" + # ZH-pro + - "实体优化" + - "知识图谱" + - "品牌实体" + - "知识面板" + - "品牌词" + - "品牌词优化" + # ZH-casual + - "品牌搜不到" + - "没有知识面板" + - "Google不认识我的品牌" + # JA + - "エンティティ最適化" + - "ナレッジパネル" + # KO + - "엔티티 최적화" + - "지식 패널" + - "구글이 내 브랜드 모르는데?" + - "지식 패널 만들려면?" + # ES + - "optimización de entidad" + - "panel de conocimiento" + # PT + - "otimização de entidade" + # Misspellings + - "knowlege panel" + - "enity optimization" +--- + +# Entity Optimizer + + +> **[SEO & GEO Skills Library](https://github.com/aaron-he-zhu/seo-geo-claude-skills)** · 20 skills for SEO + GEO · [ClawHub](https://clawhub.ai/u/aaron-he-zhu) · [skills.sh](https://skills.sh/aaron-he-zhu/seo-geo-claude-skills) +> **System Mode**: This cross-cutting skill is part of the protocol layer and follows the shared [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md) and [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md). + + +Audits, builds, and maintains entity identity across search engines and AI systems. Entities — the people, organizations, products, and concepts that search engines and AI systems recognize as distinct things — are the foundation of how both Google and LLMs decide *what a brand is* and *whether to cite it*. + +**Why entities matter for SEO + GEO:** + +- **SEO**: Google's Knowledge Graph powers Knowledge Panels, rich results, and entity-based ranking signals. A well-defined entity earns SERP real estate. +- **GEO**: AI systems resolve queries to entities before generating answers. If an AI cannot identify an entity, it cannot cite it — no matter how good the content is. + +**System role**: Canonical Entity Profile. It acts as the source of truth for entity identity, associations, and disambiguation across the library. + +## When This Must Trigger + +Use this when brand or entity identity needs to be established or verified — even if the user doesn't use entity terminology: + +- User says "Google doesn't know my brand" or "no knowledge panel" +- Auto-recommended when `memory/entities/candidates.md` accumulates 3 or more uncanonized entity candidates from other skills +- Establishing a new brand/person/product as a recognized entity +- Auditing current entity presence across Knowledge Graph, Wikidata, and AI systems +- Improving or correcting a Knowledge Panel +- Building entity associations (entity ↔ topic, entity ↔ industry) +- Resolving entity disambiguation issues (your entity confused with another) +- Strengthening entity signals for AI citation +- After launching a new brand, product, or organization +- Preparing for a site migration (preserving entity identity) +- Running periodic entity health checks + +## What This Skill Does + +1. **Entity Audit**: Evaluates current entity presence across search and AI systems +2. **Knowledge Graph Analysis**: Checks Google Knowledge Graph, Wikidata, and Wikipedia status +3. **AI Entity Resolution Test**: Queries AI systems to see how they identify and describe the entity +4. **Entity Signal Mapping**: Identifies all signals that establish entity identity +5. **Gap Analysis**: Finds missing or weak entity signals +6. **Entity Building Plan**: Creates actionable plan to establish or strengthen entity presence +7. **Disambiguation Strategy**: Resolves confusion with similarly-named entities + +## Quick Start + +Start with one of these prompts. Finish with a canonical entity profile and a handoff summary using the repository format in [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md). + +### Entity Audit + +``` +Audit entity presence for [brand/person/organization] +``` + +``` +How well do search engines and AI systems recognize [entity name]? +``` + +### Build Entity Presence + +``` +Build entity presence for [new brand] in the [industry] space +``` + +``` +Establish [person name] as a recognized expert in [topic] +``` + +### Fix Entity Issues + +``` +My Knowledge Panel shows incorrect information — fix entity signals for [entity] +``` + +``` +AI systems confuse [my entity] with [other entity] — help me disambiguate +``` + +## Skill Contract + +**Expected output**: an entity audit, a canonical entity profile, and a short handoff summary ready for `memory/entities/`. + +- **Reads**: the entity name, primary domain, known profiles, topic associations, and prior brand context from [CLAUDE.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CLAUDE.md) and the shared [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md) when available. +- **Writes**: a user-facing entity report plus a reusable profile that can be stored under `memory/entities/`. +- **Promotes**: canonical names, sameAs links, disambiguation notes, and entity gaps to `CLAUDE.md`, `memory/entities/`, and `memory/open-loops.md`. + +This skill is the sole writer of canonical entity profiles at `memory/entities/.md`. Other skills write entity candidates to `memory/entities/candidates.md` only. When 3+ candidates accumulate, this skill should be recommended. + +- **Next handoff**: use the `Next Best Skill` below once the entity truth is clear. + +## Data Sources + +> See [CONNECTORS.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CONNECTORS.md) for tool category placeholders. + +**With ~~knowledge graph + ~~SEO tool + ~~AI monitor + ~~brand monitor connected:** +Query Knowledge Graph API for entity status, pull branded search data from ~~SEO tool, test AI citation with ~~AI monitor, track brand mentions with ~~brand monitor. + +**With manual data only:** +Ask the user to provide: +1. Entity name, type (Person, Organization, Brand, Product, Creative Work, Event) +2. Primary website / domain +3. Known existing profiles (Wikipedia, Wikidata, social media, industry directories) +4. Top 3-5 topics/industries the entity should be associated with +5. Any known disambiguation issues (other entities with same/similar name) + +Without tools, Claude provides entity optimization strategy and recommendations based on information the user provides. The user must run search queries, check Knowledge Panels, and test AI responses to supply the raw data for analysis. + +Proceed with the audit using public search results, AI query testing, and SERP analysis. Note which items require tool access for full evaluation. + +## Instructions + +When a user requests entity optimization: + +### Step 1: Entity Discovery + +Establish the entity's current state across all systems. + +```markdown +### Entity Profile + +**Entity Name**: [name] +**Entity Type**: [Person / Organization / Brand / Product / Creative Work / Event] +**Primary Domain**: [URL] +**Target Topics**: [topic 1, topic 2, topic 3] + +#### Current Entity Presence + +| Platform | Status | Details | +|----------|--------|---------| +| Google Knowledge Panel | ✅ Present / ❌ Absent / ⚠️ Incorrect | [details] | +| Wikidata | ✅ Listed / ❌ Not listed | [QID if exists] | +| Wikipedia | ✅ Article / ⚠️ Mentioned only / ❌ Absent | [notability assessment] | +| Google Knowledge Graph API | ✅ Entity found / ❌ Not found | [entity ID, types, score] | +| Schema.org on site | ✅ Complete / ⚠️ Partial / ❌ Missing | [Organization/Person/Product schema] | + +#### AI Entity Resolution Test + +**Note**: Claude cannot directly query other AI systems or perform real-time web searches without tool access. When running without ~~AI monitor or ~~knowledge graph tools, ask the user to run these test queries and report the results, or use the user-provided information to assess entity presence. + +Test how AI systems identify this entity by querying: +- "What is [entity name]?" +- "Who founded [entity name]?" (for organizations) +- "What does [entity name] do?" +- "[entity name] vs [competitor]" + +| AI System | Recognizes Entity? | Description Accuracy | Cites Entity's Content? | +|-----------|-------------------|---------------------|------------------------| +| ChatGPT | ✅ / ⚠️ / ❌ | [accuracy notes] | [yes/no/partially] | +| Claude | ✅ / ⚠️ / ❌ | [accuracy notes] | [yes/no/partially] | +| Perplexity | ✅ / ⚠️ / ❌ | [accuracy notes] | [yes/no/partially] | +| Google AI Overview | ✅ / ⚠️ / ❌ | [accuracy notes] | [yes/no/partially] | +``` + +### Step 2: Entity Signal Audit + +Evaluate entity signals across 6 categories. For the detailed 47-signal checklist with verification methods, see [references/entity-signal-checklist.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/cross-cutting/entity-optimizer/references/entity-signal-checklist.md). + +Evaluate each signal as Pass / Fail / Partial with a specific action for each gap. The 6 categories are: + +1. **Structured Data Signals** -- Organization/Person schema, sameAs links, @id consistency, author schema +2. **Knowledge Base Signals** -- Wikidata, Wikipedia, CrunchBase, industry directories +3. **Consistent NAP+E Signals** -- Name/description/logo/social consistency across platforms +4. **Content-Based Entity Signals** -- About page, author pages, topical authority, branded backlinks +5. **Third-Party Entity Signals** -- Authoritative mentions, co-citation, reviews, press coverage +6. **AI-Specific Entity Signals** -- Clear definitions, disambiguation, verifiable claims, crawlability + +> **Reference**: Use the audit template in [references/entity-signal-checklist.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/cross-cutting/entity-optimizer/references/entity-signal-checklist.md) for the full 47-signal checklist with verification methods for each category. + +### Step 3: Report & Action Plan + +```markdown +## Entity Optimization Report + +### Overview + +- **Entity**: [name] +- **Entity Type**: [type] +- **Audit Date**: [date] + +### Signal Category Summary + +| Category | Status | Key Findings | +|----------|--------|-------------| +| Structured Data | ✅ Strong / ⚠️ Gaps / ❌ Missing | [key findings] | +| Knowledge Base | ✅ Strong / ⚠️ Gaps / ❌ Missing | [key findings] | +| Consistency (NAP+E) | ✅ Strong / ⚠️ Gaps / ❌ Missing | [key findings] | +| Content-Based | ✅ Strong / ⚠️ Gaps / ❌ Missing | [key findings] | +| Third-Party | ✅ Strong / ⚠️ Gaps / ❌ Missing | [key findings] | +| AI-Specific | ✅ Strong / ⚠️ Gaps / ❌ Missing | [key findings] | + +### Critical Issues + +[List any issues that severely impact entity recognition — disambiguation problems, incorrect Knowledge Panel, missing from Knowledge Graph entirely] + +### Top 5 Priority Actions + +Sorted by: impact on entity recognition × effort required + +1. **[Signal]** — [specific action] + - Impact: [High/Medium] | Effort: [Low/Medium/High] + - Why: [explanation of how this improves entity recognition] + +2. **[Signal]** — [specific action] + - Impact: [High/Medium] | Effort: [Low/Medium/High] + - Why: [explanation] + +3–5. [Same format] + +### Entity Building Roadmap + +#### Week 1-2: Foundation (Structured Data + Consistency) +- [ ] Implement/fix Organization or Person schema with full properties +- [ ] Add sameAs links to all authoritative profiles +- [ ] Audit and fix NAP+E consistency across all platforms +- [ ] Ensure About page is entity-rich and well-structured + +#### Month 1: Knowledge Bases +- [ ] Create or update Wikidata entry with complete properties +- [ ] Ensure CrunchBase / industry directory profiles are complete +- [ ] Build Wikipedia notability (or plan path to notability) +- [ ] Submit to relevant authoritative directories + +#### Month 2-3: Authority Building +- [ ] Secure mentions on authoritative industry sites +- [ ] Build co-citation signals with established entities +- [ ] Create topical content clusters that reinforce entity-topic associations +- [ ] Pursue PR opportunities that generate entity mentions + +#### Ongoing: AI-Specific Optimization +- [ ] Test AI entity resolution quarterly +- [ ] Update factual claims to remain current and verifiable +- [ ] Monitor AI systems for incorrect entity information +- [ ] Ensure new content reinforces entity identity signals + +### Cross-Reference + +- **CORE-EEAT relevance**: Items A07 (Knowledge Graph Presence) and A08 (Entity Consistency) directly overlap — entity optimization strengthens Authority dimension +- **CITE relevance**: CITE I01-I10 (Identity dimension) measures entity signals at domain level — entity optimization feeds these scores +- For content-level audit: `content-quality-auditor` +- For domain-level audit: `domain-authority-auditor` +``` + +### Save Results + +After delivering findings to the user, ask: + +> "Save these results for future sessions?" + +If yes, write a dated summary to the appropriate `memory/` path using filename `YYYY-MM-DD-.md` containing: +- One-line verdict or headline finding +- Top 3-5 actionable items +- Open loops or blockers +- Source data references + +If any veto-level issue was found (CORE-EEAT T04, C01, R10 or CITE T03, T05, T09), also append a one-liner to `memory/hot-cache.md` without asking. + +## Validation Checkpoints + +### Input Validation +- [ ] Entity name and type identified +- [ ] Primary domain/website confirmed +- [ ] Target topics/industries specified +- [ ] Disambiguation context provided (if entity name is common) + +### Output Validation +- [ ] All 6 signal categories evaluated +- [ ] AI entity resolution tested with at least 3 queries +- [ ] Knowledge Panel status checked +- [ ] Wikidata/Wikipedia status verified +- [ ] Schema.org markup on primary site audited +- [ ] Every recommendation is specific and actionable +- [ ] Roadmap includes concrete steps with timeframes +- [ ] Cross-reference with CORE-EEAT A07/A08 and CITE I01-I10 noted + +## Example + +> **Reference**: See [references/example-audit-report.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/cross-cutting/entity-optimizer/references/example-audit-report.md) for a complete example entity audit report for a B2B SaaS company (CloudMetrics), including AI entity resolution test results, entity health summary, top 3 priority actions, and CORE-EEAT/CITE cross-references. + +## Tips for Success + +1. **Start with Wikidata** — It's the single most influential editable knowledge base; a complete Wikidata entry with references often triggers Knowledge Panel creation within weeks +2. **sameAs is your most powerful Schema.org property** — It directly tells search engines "I am this entity in the Knowledge Graph"; always include Wikidata URL first +3. **Test AI recognition before and after** — Query ChatGPT, Claude, Perplexity, and Google AI Overview before optimizing, then again after; this is the most direct GEO metric +4. **Entity signals compound** — Unlike content SEO, entity signals from different sources reinforce each other; 5 weak signals together are stronger than 1 strong signal alone +5. **Consistency beats completeness** — A consistent entity name and description across 10 platforms beats a perfect profile on just 2 +6. **Don't neglect disambiguation** — If your entity name is shared with anything else, disambiguation is the first priority; all other signals are wasted if they're attributed to the wrong entity +7. **Pair with CITE I-dimension for domain context** — Entity audit tells you how well the entity is recognized; CITE Identity (I01-I10) tells you how well the domain represents that entity; use both together + +## Entity Type Reference + +> **Reference**: See [references/entity-type-reference.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/cross-cutting/entity-optimizer/references/entity-type-reference.md) for entity types with key signals, schemas, and disambiguation strategies by situation. + +## Knowledge Panel & Wikidata Optimization + +> **Reference**: See [references/knowledge-panel-wikidata-guide.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/cross-cutting/entity-optimizer/references/knowledge-panel-wikidata-guide.md) for Knowledge Panel claiming/editing, common issues and fixes, Wikidata entry creation, key properties by entity type, and AI entity resolution optimization. + +## Reference Materials + +Detailed guides for entity optimization: +- [references/entity-signal-checklist.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/cross-cutting/entity-optimizer/references/entity-signal-checklist.md) — Complete signal checklist with verification methods +- [references/knowledge-graph-guide.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/cross-cutting/entity-optimizer/references/knowledge-graph-guide.md) — Wikidata, Wikipedia, and Knowledge Graph optimization playbook + +## Next Best Skill + +- **Primary**: [schema-markup-generator](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/build/schema-markup-generator/SKILL.md) — turn entity truth into machine-readable implementation. diff --git a/.cursor/skills/frontend-design/SKILL.md b/.cursor/skills/frontend-design/SKILL.md new file mode 100755 index 0000000..8feb88e --- /dev/null +++ b/.cursor/skills/frontend-design/SKILL.md @@ -0,0 +1,114 @@ +--- +name: frontend-design +description: Build distinctive, production-quality UI. Use when creating or reshaping user-facing interfaces, components, pages, layouts, visual redesigns, responsive behavior, loading/error/empty states, or accessibility-sensitive frontend work. +--- + +# Frontend Design & UI Quality + +Approach this as the design lead at a small studio known for giving every client a visual identity that could not be mistaken for anyone else's. Make deliberate, opinionated choices about palette, typography, layout, motion, and copy that are specific to the brief, then execute them with engineering rigor: accessible, responsive, performant, and complete in every state. + +## 1. Aesthetic Direction + +### Ground It In The Subject + +If the brief does not pin down the product or subject, pin it yourself before designing: name one concrete subject, its audience, and the page's single job. Use the user's preferences, project context, and previous design choices as hints. The subject's world - its materials, instruments, artifacts, and vernacular - is where distinctive choices come from. Build with real or realistic content throughout. Never use lorem ipsum; placeholder text hides wrapping, overflow, hierarchy, and tone problems. + +### Design Principles + +For web designs, the hero is a thesis. Open with the most characteristic thing in the subject's world: a headline, image, animation, live demo, interactive moment, or concrete product artifact. A big number with a small label, supporting stats, and a gradient accent is the template answer; only use it if it is truly the best option. + +Typography carries personality. Pair display and body faces deliberately, not the same families you would reach for on every project. Set a clear type scale with intentional weights, widths, spacing, and rhythm. Respect semantic hierarchy: one `h1` per page, no skipped heading levels, and no heading styles on non-heading content. + +Structure is information. Numbering, eyebrows, dividers, labels, cards, and section breaks should encode something true about the content, not decorate it. Numbered markers like `01 / 02 / 03` only belong when the content is actually sequential. + +Leverage motion deliberately. One orchestrated moment usually lands harder than scattered effects. Always respect `prefers-reduced-motion`. + +Match complexity to the vision. Maximalist directions need elaborate execution; minimal directions need precision in spacing, type, and detail. Elegance is executing the chosen vision well. + +### Known AI Defaults + +Avoid defaulting to: warm cream + high-contrast serif + terracotta; near-black + acid green/vermilion; broadsheet layouts with hairline rules; purple/indigo everything; decorative gradients; `rounded-2xl` everywhere; generic hero sections; uniform card grids that ignore information priority; oversized equal padding; layered shadows. These can be valid when the brief calls for them, but they must be choices, not reflexes. + +### Existing Product Rule + +If the project already has a design system, tokens, components, palette, radius scale, or layout language, that system is the brief. Distinctiveness then lives in hierarchy, composition, content, interaction, and motion - not in inventing stray colors or one-off radii. Use semantic tokens, existing components, and the established spacing scale. Avoid raw hex values or off-scale spacing unless the design system itself requires them. + +## 2. Process + +Work in two passes. + +First, create a compact design plan: + +- **Color:** 4-6 named hex values for greenfield work, or the exact tokens to use in an existing product. +- **Type:** roles for display, body, and utility/caption text. +- **Layout:** one-sentence concept plus quick ASCII wireframes when useful. +- **Signature:** the single element this interface should be remembered by. + +Second, critique the plan against the brief before building. If any part could appear unchanged in a generic page for a different subject, revise it. Only then write code. Derive every visual choice from the revised plan or the existing design system. + +When writing CSS, watch selector specificity. Generated class names often cancel each other out around section spacing, component padding, and element selectors. Prefer simple, local class structure and design-system utilities over clever selector chains. + +## 3. Engineering The Design + +### Components + +- Prefer composition over configuration: structured children over prop grab-bags. +- Keep components focused; split anything past roughly 200 lines unless there is a strong local reason not to. +- Separate data fetching from presentation. Containers resolve loading/error/empty and pass clean data to presentational components. +- Choose the simplest state that works: `useState` for component UI state; lifted state for 2-3 siblings; context for read-heavy/write-rare concerns like theme, auth, locale; URL state for shareable filters/pagination; SWR/React Query for server data; global stores only for genuinely app-wide client state. +- Avoid prop drilling past 3 levels. Restructure or introduce context when intermediate components do not use the props. + +### Four UI States + +Design loading, error, empty, and success together. + +- **Loading:** use skeletons that match content shape for content areas. Add `aria-busy="true"` where appropriate. +- **Error:** say what went wrong and how to fix it. Offer retry when retrying can work. +- **Empty:** treat it as an invitation to act: icon or marker, short explanation, and a primary action. Never leave a blank region. Use `role="status"` when the empty state announces a result. +- **Success:** optimize the default path without hiding constraints, secondary actions, or overflow cases. + +Use optimistic updates for quick mutations where rollback is cheap and failure is understandable. + +### Accessibility + +Meet WCAG 2.1 AA as a floor. + +- Use native elements first: `button`, `a`, `label`, `input`, `select`, `textarea`, `dialog`. +- A clickable `div` needs `role`, `tabIndex`, and keyboard handling for Enter/Space; prefer a real `button`. +- Every icon-only control needs an `aria-label`. Every input needs a visible label or explicit accessible name. +- Focus must be visible. Dialogs and popovers move focus on open and restore it on close; modal dialogs trap focus. +- Contrast: 4.5:1 for normal text, 3:1 for large text and non-text UI indicators. +- Do not use color as the only state indicator. Pair color with text, iconography, shape, or pattern. +- Respect `prefers-reduced-motion` for animation and transitions. + +### Responsive + +Design mobile-first, then expand. Verify at 320px, 768px, 1024px, and 1440px. Check text wrapping, overflow, touch targets, sticky elements, modals, tables, and long localized strings, not just whether the layout stacks. + +## 4. Restraint And Self-Critique + +Spend boldness in one place. Let the signature element be the memorable move; keep everything around it quiet and disciplined. Cut decoration that does not serve the brief. Not taking a risk can also be a risk. + +Critique the work visually as you build. If screenshots are available, use them. Before presenting, remove one accessory: one extra border, glow, gradient, icon, animation, card, or label that weakens the hierarchy. + +## 5. Writing In The Design + +Words make the interface easier to understand and use. They are design material, not decoration. + +Write from the end user's side of the screen. Name things by what people control and recognize, not by internal implementation. A person manages notifications, not webhook config. Be specific rather than clever. + +Use active voice. A control says exactly what happens: "Save changes," not "Submit." Keep action vocabulary consistent through the whole flow: "Publish" leads to "Published." + +Treat failure and emptiness as moments for direction, not mood. Errors do not apologize and are never vague. Empty states invite the next action. + +Keep copy conversational and tuned: plain verbs, sentence case, no filler, with tone matched to the brand and audience. Each element does one job: a label labels, an example demonstrates, helper text helps. + +## Verification Checklist + +Before presenting UI work, verify: + +- [ ] Design direction is specific to the brief, not a generic default. +- [ ] Existing design-system tokens, spacing, components, and typography are respected. +- [ ] Realistic content, loading, error, empty, and success states are handled. +- [ ] Keyboard navigation, focus, labels, contrast, and reduced motion are covered. +- [ ] Layout works at 320px, 768px, 1024px, and 1440px with no obvious overflow. diff --git a/.cursor/skills/geo-content-optimizer/SKILL.md b/.cursor/skills/geo-content-optimizer/SKILL.md new file mode 100644 index 0000000..5ee0a58 --- /dev/null +++ b/.cursor/skills/geo-content-optimizer/SKILL.md @@ -0,0 +1,420 @@ +--- +name: geo-content-optimizer +description: 'Optimize content for AI citations in ChatGPT, Perplexity, AI Overviews, Gemini, Claude. AI引用优化/GEO优化/AI搜索' +version: "6.0.0" +license: Apache-2.0 +compatibility: "Claude Code ≥1.0, skills.sh marketplace, ClawHub marketplace, Vercel Labs skills ecosystem. No system packages required. Optional: MCP network access for SEO tool integrations." +homepage: "https://github.com/aaron-he-zhu/seo-geo-claude-skills" +when_to_use: "Use when optimizing content for AI engines like ChatGPT, Perplexity, AI Overviews, Gemini, Claude, or Copilot. Also for AI citation optimization and generative engine visibility." +argument-hint: " [target AI engine]" +metadata: + author: aaron-he-zhu + version: "6.0.0" + geo-relevance: "high" + tags: + - geo + - ai-citations + - chatgpt-optimization + - perplexity-optimization + - google-ai-overview + - gemini + - generative-engine-optimization + - llm-citations + - ai-seo + - quotable-content + - AI引用优化 + - GEO优化 + - AI最適化 + - AI최적화 + - optimizacion-ia + triggers: + # EN-formal + - "optimize for AI" + - "get cited by ChatGPT" + - "AI optimization" + - "appear in AI answers" + - "GEO optimization" + - "generative engine optimization" + - "AI-friendly content" + - "LLM citations" + # EN-casual + - "get cited by AI" + - "show up in ChatGPT answers" + - "AI doesn't mention my brand" + - "make content AI-quotable" + - "how do I get AI to mention me" + - "ChatGPT doesn't know my brand" + # EN-question + - "how to appear in AI answers" + - "how to get cited by AI" + - "why doesn't AI mention my brand" + # EN-competitor + - "Perplexity optimization" + - "how to rank in ChatGPT answers" + - "AI Overview optimization tool" + # ZH-pro + - "AI引用优化" + - "GEO优化" + - "生成式引擎优化" + - "AI搜索优化" + - "AI可引用内容" + # ZH-casual + - "让AI引用我" + - "ChatGPT搜不到我" + - "AI不提我的品牌" + - "怎么让AI推荐我" + - "AI搜不到" + # JA + - "AIコンテンツ最適化" + - "AI引用されるコンテンツ" + - "ChatGPT対策" + - "AI検索最適化" + # KO + - "AI 최적화" + - "AI 검색 최적화" + - "ChatGPT 인용" + # ES + - "optimización para IA" + - "aparecer en respuestas de IA" + - "citación de IA" + # PT + - "otimização para IA" + - "aparecer nas respostas da IA" + # Misspellings + - "generative engine optimisation" + - "GEO optimisation" +--- + +# GEO Content Optimizer + +> **[SEO & GEO Skills Library](https://github.com/aaron-he-zhu/seo-geo-claude-skills)** · 20 skills for SEO + GEO · [ClawHub](https://clawhub.ai/u/aaron-he-zhu) · [skills.sh](https://skills.sh/aaron-he-zhu/seo-geo-claude-skills) +> **System Mode**: This build skill follows the shared [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md) and [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md). + + +This skill optimizes content to appear in AI-generated responses. As AI systems increasingly answer user queries directly, getting cited by these systems directly impacts visibility. + +**System role**: Build layer skill. It turns briefs and signals into assets that other skills can review, publish, and monitor. + +## When This Must Trigger + +Use this when the conversation involves any of these situations — even if the user does not use SEO terminology: + +Use this whenever the task needs a shippable asset or transformation that should feed directly into quality review, deployment, or monitoring. + +- Optimizing existing content for AI citations +- Creating new content designed for both SEO and GEO +- Improving chances of appearing in AI Overviews +- Making content more quotable by AI systems +- Adding authority signals that AI systems trust +- Structuring content for AI comprehension +- Competing for visibility in the AI-first search era + +## What This Skill Does + +1. **Citation Optimization**: Makes content more likely to be quoted by AI +2. **Structure Enhancement**: Formats content for AI comprehension +3. **Authority Building**: Adds signals that AI systems trust +4. **Factual Enhancement**: Improves accuracy and verifiability +5. **Quote Creation**: Creates memorable, citeable statements +6. **Source Attribution**: Adds proper citations that AI can verify +7. **GEO Scoring**: Evaluates content's AI-friendliness + +## Quick Start + +Start with one of these prompts. Finish with a short handoff summary using the repository format in [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md). + +### Optimize Existing Content + +``` +Optimize this content for GEO/AI citations: [content or URL] +``` + +``` +Make this article more likely to be cited by AI systems +``` + +### Create GEO-Optimized Content + +``` +Write content about [topic] optimized for both SEO and GEO +``` + +### GEO Audit + +``` +Audit this content for GEO readiness and suggest improvements +``` + +## Skill Contract + +**Expected output**: a ready-to-use asset or implementation-ready transformation plus a short handoff summary ready for `memory/content/`. + +- **Reads**: the brief, target keywords, entity inputs, quality constraints, and prior decisions from [CLAUDE.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CLAUDE.md) and the shared [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md) when available. +- **Writes**: a user-facing content, metadata, or schema deliverable plus a reusable summary that can be stored under `memory/content/`. +- **Promotes**: approved angles, messaging choices, missing evidence, and publish blockers to `CLAUDE.md`, `memory/decisions.md`, and `memory/open-loops.md`. +- **Next handoff**: use the `Next Best Skill` below when the asset is ready for review or deployment. + +## Data Sources + +> See [CONNECTORS.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CONNECTORS.md) for tool category placeholders. + +> **Note:** All integrations are optional. This skill works without any API keys — users provide data manually when no tools are connected. + +**With ~~AI monitor + ~~SEO tool connected:** +Automatically pull AI citation patterns (which content is being cited by ChatGPT, Claude, Perplexity), current AI visibility scores, competitor citation frequency, and AI Overview appearance tracking. + +**With manual data only:** +Ask the user to provide: +1. Target queries where they want AI citations +2. Current content URL or full content text +3. Any known instances where competitors are being cited by AI + +Proceed with the full workflow using provided data. Note in the output which metrics are from automated collection vs. user-provided data. + +## Instructions + +When a user requests GEO optimization: + +1. **Load CORE-EEAT GEO-First Optimization Targets** + + Before optimizing, load GEO-critical items from the [CORE-EEAT Benchmark](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/core-eeat-benchmark.md): + + ```markdown + ### CORE-EEAT GEO-First Targets + + These items have the highest impact on AI engine citation. Use as optimization checklist: + + **Top 6 Priority Items**: + | Rank | ID | Standard | Why It Matters | + |------|----|----------|---------------| + | 1 | C02 | Direct Answer in first 150 words | All engines extract from first paragraph | + | 2 | C09 | Structured FAQ with Schema | Directly matches AI follow-up queries | + | 3 | O03 | Data in tables, not prose | Most extractable structured format | + | 4 | O05 | JSON-LD Schema Markup | Helps AI understand content type | + | 5 | E01 | Original first-party data | AI prefers exclusive, verifiable sources | + | 6 | O02 | Key Takeaways / Summary Box | First choice for AI summary citations | + + **All GEO-First Items** (optimize for all when possible): + C02, C04, C05, C07, C08, C09 | O02, O03, O04, O05, O06, O09 + R01, R02, R03, R04, R05, R07, R09 | E01, E02, E03, E04, E06, E08, E09, E10 + Exp10 | Ept05, Ept08 | A08 + + **AI Engine Preferences**: + | Engine | Priority Items | + |--------|----------------| + | Google AI Overview | C02, O03, O05, C09 | + | ChatGPT Browse | C02, R01, R02, E01 | + | Perplexity AI | E01, R03, R05, Ept05 | + | Claude | R04, Ept08, Exp10, R03 | + + _Full benchmark: [references/core-eeat-benchmark.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/core-eeat-benchmark.md)_ + ``` + +2. **Analyze Current Content** + + ```markdown + ## GEO Analysis: [Content Title] + + ### Current State Assessment + + | GEO Factor | Current Score (1-10) | Notes | + |------------|---------------------|-------| + | Clear definitions | [X] | [notes] | + | Quotable statements | [X] | [notes] | + | Factual density | [X] | [notes] | + | Source citations | [X] | [notes] | + | Q&A format | [X] | [notes] | + | Authority signals | [X] | [notes] | + | Content freshness | [X] | [notes] | + | Structure clarity | [X] | [notes] | + | **GEO Readiness** | **[avg]/10** | **Average across factors** | + + **Primary Weaknesses**: + 1. [Weakness 1] + 2. [Weakness 2] + 3. [Weakness 3] + + **Quick Wins**: + 1. [Quick improvement 1] + 2. [Quick improvement 2] + ``` + +3. **Apply GEO Optimization Techniques** + + > **GEO fundamentals**: AI systems prioritize content that is authoritative (expert credentials, proper citations), accurate (verifiable, up-to-date), clear (well-structured, unambiguous), and quotable (standalone answers, specific data). See [references/geo-optimization-techniques.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/build/geo-content-optimizer/references/geo-optimization-techniques.md) for details. + + Apply the six core optimization techniques: definition optimization, quotable statement creation, authority signal enhancement, structure optimization, factual density improvement, and FAQ schema implementation. + + > **Reference**: See [references/geo-optimization-techniques.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/build/geo-content-optimizer/references/geo-optimization-techniques.md) for detailed before/after examples, templates, and checklists for each technique. + + Key principles: + - **Definitions**: 25-50 words, standalone, starting with the term + - **Quotable statements**: Specific statistics with sources, verifiable facts + - **Authority signals**: Expert quotes with credentials, proper source citations + - **Structure**: Q&A format, comparison tables, numbered lists + - **Factual density**: Replace vague claims with specific data points + - **FAQ schema**: JSON-LD FAQPage markup matching visible content + +4. **Generate GEO-Optimized Output** + + ```markdown + ## GEO Optimization Report + + ### Changes Made + + **Definitions Added/Improved**: + 1. [Definition 1] - [location in content] + 2. [Definition 2] - [location in content] + + **Quotable Statements Created**: + 1. "[Statement 1]" + 2. "[Statement 2]" + + **Authority Signals Added**: + 1. [Expert quote/citation] + 2. [Source attribution] + + **Structural Improvements**: + 1. [Change 1] + 2. [Change 2] + + ### Before/After GEO Score + + | GEO Factor | Before (1-10) | After (1-10) | Change | + |------------|---------------|--------------|--------| + | Clear definitions | [X] | [X] | +[X] | + | Quotable statements | [X] | [X] | +[X] | + | Factual density | [X] | [X] | +[X] | + | Source citations | [X] | [X] | +[X] | + | Q&A format | [X] | [X] | +[X] | + | Authority signals | [X] | [X] | +[X] | + | **Overall GEO Score** | **[avg]/10** | **[avg]/10** | **+[X]** | + + ### AI Query Coverage + + This content is now optimized to answer: + - "What is [topic]?" ✅ + - "How does [topic] work?" ✅ + - "Why is [topic] important?" ✅ + - "[Topic] vs [alternative]" ✅ + - "Best [topic] for [use case]" ✅ + ``` + +5. **CORE-EEAT GEO Self-Check** + + After optimization, verify GEO-First items: + + ```markdown + ### CORE-EEAT GEO Post-Optimization Check + + | ID | Standard | Status | Notes | + |----|----------|--------|-------| + | C02 | Direct Answer in first 150 words | ✅/⚠️/❌ | [notes] | + | C04 | Key terms defined on first use | ✅/⚠️/❌ | [notes] | + | C09 | Structured FAQ with Schema | ✅/⚠️/❌ | [notes] | + | O02 | Summary Box / Key Takeaways | ✅/⚠️/❌ | [notes] | + | O03 | Comparisons in tables | ✅/⚠️/❌ | [notes] | + | O05 | JSON-LD Schema Markup | ✅/⚠️/❌ | [notes] | + | O06 | Section chunking (3–5 sentences) | ✅/⚠️/❌ | [notes] | + | R01 | ≥5 precise data points with units | ✅/⚠️/❌ | [notes] | + | R02 | ≥1 citation per 500 words | ✅/⚠️/❌ | [notes] | + | R04 | Claims backed by evidence | ✅/⚠️/❌ | [notes] | + | R07 | Full entity names | ✅/⚠️/❌ | [notes] | + | E01 | Original first-party data | ✅/⚠️/❌ | [notes] | + | Exp10 | Limitations acknowledged | ✅/⚠️/❌ | [notes] | + | Ept08 | Reasoning transparency | ✅/⚠️/❌ | [notes] | + + **Items Needing Attention**: [list any ⚠️/❌ items] + + _For full 80-item audit, use [content-quality-auditor](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/cross-cutting/content-quality-auditor/SKILL.md)_ + ``` + +## Validation Checkpoints + +### Input Validation +- [ ] Content source identified (URL, full text, or content draft) +- [ ] Target AI queries or topics clearly defined +- [ ] Current GEO baseline assessed (if optimizing existing content) + +### Output Validation +- [ ] At least 3 clear, quotable definitions added +- [ ] Factual density improved with at least 5 verifiable statistics +- [ ] All claims have source citations from authoritative sources +- [ ] Q&A format sections cover top 5 user queries +- [ ] GEO score improvement of at least 50% from baseline +- [ ] Source of each data point clearly stated (~~AI monitor data, user-provided, or estimated) + +## Example + +**User**: "Optimize this paragraph for GEO: 'Email marketing is a good way to reach customers. It's been around for a while and many businesses use it. You can send newsletters, promotions, and other messages.'" + +**Output**: + +```markdown +## GEO-Optimized Version + +**Email marketing** is a digital marketing strategy that uses email to promote +products, build customer relationships, and drive conversions. According to +the Data & Marketing Association, email marketing delivers an average ROI +of $42 for every $1 invested, making it the highest-performing digital +marketing channel. + +### Key email marketing formats include: + +1. **Newsletters**: Regular updates sharing company news, industry insights, + and valuable content to maintain subscriber engagement +2. **Promotional emails**: Time-sensitive offers, discounts, and product + announcements designed to drive immediate sales +3. **Transactional emails**: Order confirmations, shipping updates, and + account notifications with 8x higher open rates than marketing emails +4. **Automated sequences**: Pre-scheduled email series triggered by user + actions, such as welcome series or abandoned cart reminders + +> **Key statistic**: 81% of small businesses rely on email as their primary +> customer acquisition channel (Emarsys, 2024). + +--- + +### Changes Made: + +Changes: added clear definition, 2 stats with sources, structured list, DMA/Emarsys citations, 3 quotable facts. **GEO Score**: 1/10 → 8/10. +``` + +## GEO Optimization Checklist + +> **Reference**: See the GEO Readiness Checklist in [references/geo-optimization-techniques.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/build/geo-content-optimizer/references/geo-optimization-techniques.md) for the full checklist covering definitions, quotable content, authority, structure, and technical elements. + +## Tips for Success + +1. **Answer the question first** - Put the answer in the first sentence +2. **Be specific** - Vague content doesn't get cited +3. **Cite sources** - AI systems trust verifiable information +4. **Stay current** - Update statistics and facts regularly +5. **Match query format** - Questions deserve direct answers +6. **Build authority** - Expert credentials increase citation likelihood + + +### Save Results + +After delivering content or optimization output to the user, ask: + +> "Save these results for future sessions?" + +If yes, write a dated summary to `memory/content/YYYY-MM-DD-.md` containing: +- One-line description of what was created +- Target keyword and content type +- Open loops or items needing review +- Source data references + +**Gate check recommended**: Run content-quality-auditor before publishing (PostToolUse hook will remind automatically). + +If any findings should influence ongoing strategy, recommend promoting key conclusions to `memory/hot-cache.md`. + +## Reference Materials + +- [AI Citation Patterns](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/build/geo-content-optimizer/references/ai-citation-patterns.md) - How Google AI Overviews, ChatGPT, Perplexity, and Claude select and cite sources +- [Quotable Content Examples](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/build/geo-content-optimizer/references/quotable-content-examples.md) - Before/after examples of content optimized for AI citation + +## Next Best Skill + +- **Primary**: [content-quality-auditor](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/cross-cutting/content-quality-auditor/SKILL.md) — verify the optimized content is strong enough to ship and cite. diff --git a/.cursor/skills/improve-codebase-architecture/DEEPENING.md b/.cursor/skills/improve-codebase-architecture/DEEPENING.md new file mode 100644 index 0000000..ecaf5d7 --- /dev/null +++ b/.cursor/skills/improve-codebase-architecture/DEEPENING.md @@ -0,0 +1,37 @@ +# Deepening + +How to deepen a cluster of shallow modules safely, given its dependencies. Assumes the vocabulary in [LANGUAGE.md](LANGUAGE.md) — **module**, **interface**, **seam**, **adapter**. + +## Dependency categories + +When assessing a candidate for deepening, classify its dependencies. The category determines how the deepened module is tested across its seam. + +### 1. In-process + +Pure computation, in-memory state, no I/O. Always deepenable — merge the modules and test through the new interface directly. No adapter needed. + +### 2. Local-substitutable + +Dependencies that have local test stand-ins (PGLite for Postgres, in-memory filesystem). Deepenable if the stand-in exists. The deepened module is tested with the stand-in running in the test suite. The seam is internal; no port at the module's external interface. + +### 3. Remote but owned (Ports & Adapters) + +Your own services across a network boundary (microservices, internal APIs). Define a **port** (interface) at the seam. The deep module owns the logic; the transport is injected as an **adapter**. Tests use an in-memory adapter. Production uses an HTTP/gRPC/queue adapter. + +Recommendation shape: *"Define a port at the seam, implement an HTTP adapter for production and an in-memory adapter for testing, so the logic sits in one deep module even though it's deployed across a network."* + +### 4. True external (Mock) + +Third-party services (Stripe, Twilio, etc.) you don't control. The deepened module takes the external dependency as an injected port; tests provide a mock adapter. + +## Seam discipline + +- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a port unless at least two adapters are justified (typically production + test). A single-adapter seam is just indirection. +- **Internal seams vs external seams.** A deep module can have internal seams (private to its implementation, used by its own tests) as well as the external seam at its interface. Don't expose internal seams through the interface just because tests use them. + +## Testing strategy: replace, don't layer + +- Old unit tests on shallow modules become waste once tests at the deepened module's interface exist — delete them. +- Write new tests at the deepened module's interface. The **interface is the test surface**. +- Tests assert on observable outcomes through the interface, not internal state. +- Tests should survive internal refactors — they describe behaviour, not implementation. If a test has to change when the implementation changes, it's testing past the interface. diff --git a/.cursor/skills/improve-codebase-architecture/INTERFACE-DESIGN.md b/.cursor/skills/improve-codebase-architecture/INTERFACE-DESIGN.md new file mode 100644 index 0000000..3197723 --- /dev/null +++ b/.cursor/skills/improve-codebase-architecture/INTERFACE-DESIGN.md @@ -0,0 +1,44 @@ +# Interface Design + +When the user wants to explore alternative interfaces for a chosen deepening candidate, use this parallel sub-agent pattern. Based on "Design It Twice" (Ousterhout) — your first idea is unlikely to be the best. + +Uses the vocabulary in [LANGUAGE.md](LANGUAGE.md) — **module**, **interface**, **seam**, **adapter**, **leverage**. + +## Process + +### 1. Frame the problem space + +Before spawning sub-agents, write a user-facing explanation of the problem space for the chosen candidate: + +- The constraints any new interface would need to satisfy +- The dependencies it would rely on, and which category they fall into (see [DEEPENING.md](DEEPENING.md)) +- A rough illustrative code sketch to ground the constraints — not a proposal, just a way to make the constraints concrete + +Show this to the user, then immediately proceed to Step 2. The user reads and thinks while the sub-agents work in parallel. + +### 2. Spawn sub-agents + +Spawn 3+ sub-agents in parallel using the Agent tool. Each must produce a **radically different** interface for the deepened module. + +Prompt each sub-agent with a separate technical brief (file paths, coupling details, dependency category from [DEEPENING.md](DEEPENING.md), what sits behind the seam). The brief is independent of the user-facing problem-space explanation in Step 1. Give each agent a different design constraint: + +- Agent 1: "Minimize the interface — aim for 1–3 entry points max. Maximise leverage per entry point." +- Agent 2: "Maximise flexibility — support many use cases and extension." +- Agent 3: "Optimise for the most common caller — make the default case trivial." +- Agent 4 (if applicable): "Design around ports & adapters for cross-seam dependencies." + +Include both [LANGUAGE.md](LANGUAGE.md) vocabulary and CONTEXT.md vocabulary in the brief so each sub-agent names things consistently with the architecture language and the project's domain language. + +Each sub-agent outputs: + +1. Interface (types, methods, params — plus invariants, ordering, error modes) +2. Usage example showing how callers use it +3. What the implementation hides behind the seam +4. Dependency strategy and adapters (see [DEEPENING.md](DEEPENING.md)) +5. Trade-offs — where leverage is high, where it's thin + +### 3. Present and compare + +Present designs sequentially so the user can absorb each one, then compare them in prose. Contrast by **depth** (leverage at the interface), **locality** (where change concentrates), and **seam placement**. + +After comparing, give your own recommendation: which design you think is strongest and why. If elements from different designs would combine well, propose a hybrid. Be opinionated — the user wants a strong read, not a menu. diff --git a/.cursor/skills/improve-codebase-architecture/LANGUAGE.md b/.cursor/skills/improve-codebase-architecture/LANGUAGE.md new file mode 100644 index 0000000..530c276 --- /dev/null +++ b/.cursor/skills/improve-codebase-architecture/LANGUAGE.md @@ -0,0 +1,53 @@ +# Language + +Shared vocabulary for every suggestion this skill makes. Use these terms exactly — don't substitute "component," "service," "API," or "boundary." Consistent language is the whole point. + +## Terms + +**Module** +Anything with an interface and an implementation. Deliberately scale-agnostic — applies equally to a function, class, package, or tier-spanning slice. +_Avoid_: unit, component, service. + +**Interface** +Everything a caller must know to use the module correctly. Includes the type signature, but also invariants, ordering constraints, error modes, required configuration, and performance characteristics. +_Avoid_: API, signature (too narrow — those refer only to the type-level surface). + +**Implementation** +What's inside a module — its body of code. Distinct from **Adapter**: a thing can be a small adapter with a large implementation (a Postgres repo) or a large adapter with a small implementation (an in-memory fake). Reach for "adapter" when the seam is the topic; "implementation" otherwise. + +**Depth** +Leverage at the interface — the amount of behaviour a caller (or test) can exercise per unit of interface they have to learn. A module is **deep** when a large amount of behaviour sits behind a small interface. A module is **shallow** when the interface is nearly as complex as the implementation. + +**Seam** _(from Michael Feathers)_ +A place where you can alter behaviour without editing in that place. The *location* at which a module's interface lives. Choosing where to put the seam is its own design decision, distinct from what goes behind it. +_Avoid_: boundary (overloaded with DDD's bounded context). + +**Adapter** +A concrete thing that satisfies an interface at a seam. Describes *role* (what slot it fills), not substance (what's inside). + +**Leverage** +What callers get from depth. More capability per unit of interface they have to learn. One implementation pays back across N call sites and M tests. + +**Locality** +What maintainers get from depth. Change, bugs, knowledge, and verification concentrate at one place rather than spreading across callers. Fix once, fixed everywhere. + +## Principles + +- **Depth is a property of the interface, not the implementation.** A deep module can be internally composed of small, mockable, swappable parts — they just aren't part of the interface. A module can have **internal seams** (private to its implementation, used by its own tests) as well as the **external seam** at its interface. +- **The deletion test.** Imagine deleting the module. If complexity vanishes, the module wasn't hiding anything (it was a pass-through). If complexity reappears across N callers, the module was earning its keep. +- **The interface is the test surface.** Callers and tests cross the same seam. If you want to test *past* the interface, the module is probably the wrong shape. +- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a seam unless something actually varies across it. + +## Relationships + +- A **Module** has exactly one **Interface** (the surface it presents to callers and tests). +- **Depth** is a property of a **Module**, measured against its **Interface**. +- A **Seam** is where a **Module**'s **Interface** lives. +- An **Adapter** sits at a **Seam** and satisfies the **Interface**. +- **Depth** produces **Leverage** for callers and **Locality** for maintainers. + +## Rejected framings + +- **Depth as ratio of implementation-lines to interface-lines** (Ousterhout): rewards padding the implementation. We use depth-as-leverage instead. +- **"Interface" as the TypeScript `interface` keyword or a class's public methods**: too narrow — interface here includes every fact a caller must know. +- **"Boundary"**: overloaded with DDD's bounded context. Say **seam** or **interface**. diff --git a/.cursor/skills/improve-codebase-architecture/SKILL.md b/.cursor/skills/improve-codebase-architecture/SKILL.md new file mode 100644 index 0000000..05984a6 --- /dev/null +++ b/.cursor/skills/improve-codebase-architecture/SKILL.md @@ -0,0 +1,71 @@ +--- +name: improve-codebase-architecture +description: Find deepening opportunities in a codebase, informed by the domain language in CONTEXT.md and the decisions in docs/adr/. Use when the user wants to improve architecture, find refactoring opportunities, consolidate tightly-coupled modules, or make a codebase more testable and AI-navigable. +--- + +# Improve Codebase Architecture + +Surface architectural friction and propose **deepening opportunities** — refactors that turn shallow modules into deep ones. The aim is testability and AI-navigability. + +## Glossary + +Use these terms exactly in every suggestion. Consistent language is the point — don't drift into "component," "service," "API," or "boundary." Full definitions in [LANGUAGE.md](LANGUAGE.md). + +- **Module** — anything with an interface and an implementation (function, class, package, slice). +- **Interface** — everything a caller must know to use the module: types, invariants, error modes, ordering, config. Not just the type signature. +- **Implementation** — the code inside. +- **Depth** — leverage at the interface: a lot of behaviour behind a small interface. **Deep** = high leverage. **Shallow** = interface nearly as complex as the implementation. +- **Seam** — where an interface lives; a place behaviour can be altered without editing in place. (Use this, not "boundary.") +- **Adapter** — a concrete thing satisfying an interface at a seam. +- **Leverage** — what callers get from depth. +- **Locality** — what maintainers get from depth: change, bugs, knowledge concentrated in one place. + +Key principles (see [LANGUAGE.md](LANGUAGE.md) for the full list): + +- **Deletion test**: imagine deleting the module. If complexity vanishes, it was a pass-through. If complexity reappears across N callers, it was earning its keep. +- **The interface is the test surface.** +- **One adapter = hypothetical seam. Two adapters = real seam.** + +This skill is _informed_ by the project's domain model. The domain language gives names to good seams; ADRs record decisions the skill should not re-litigate. + +## Process + +### 1. Explore + +Read the project's domain glossary and any ADRs in the area you're touching first. + +Then use the Agent tool with `subagent_type=Explore` to walk the codebase. Don't follow rigid heuristics — explore organically and note where you experience friction: + +- Where does understanding one concept require bouncing between many small modules? +- Where are modules **shallow** — interface nearly as complex as the implementation? +- Where have pure functions been extracted just for testability, but the real bugs hide in how they're called (no **locality**)? +- Where do tightly-coupled modules leak across their seams? +- Which parts of the codebase are untested, or hard to test through their current interface? + +Apply the **deletion test** to anything you suspect is shallow: would deleting it concentrate complexity, or just move it? A "yes, concentrates" is the signal you want. + +### 2. Present candidates + +Present a numbered list of deepening opportunities. For each candidate: + +- **Files** — which files/modules are involved +- **Problem** — why the current architecture is causing friction +- **Solution** — plain English description of what would change +- **Benefits** — explained in terms of locality and leverage, and also in how tests would improve + +**Use CONTEXT.md vocabulary for the domain, and [LANGUAGE.md](LANGUAGE.md) vocabulary for the architecture.** If `CONTEXT.md` defines "Order," talk about "the Order intake module" — not "the FooBarHandler," and not "the Order service." + +**ADR conflicts**: if a candidate contradicts an existing ADR, only surface it when the friction is real enough to warrant revisiting the ADR. Mark it clearly (e.g. _"contradicts ADR-0007 — but worth reopening because…"_). Don't list every theoretical refactor an ADR forbids. + +Do NOT propose interfaces yet. Ask the user: "Which of these would you like to explore?" + +### 3. Grilling loop + +Once the user picks a candidate, drop into a grilling conversation. Walk the design tree with them — constraints, dependencies, the shape of the deepened module, what sits behind the seam, what tests survive. + +Side effects happen inline as decisions crystallize: + +- **Naming a deepened module after a concept not in `CONTEXT.md`?** Add the term to `CONTEXT.md` — same discipline as `/grill-with-docs` (see [CONTEXT-FORMAT.md](../grill-with-docs/CONTEXT-FORMAT.md)). Create the file lazily if it doesn't exist. +- **Sharpening a fuzzy term during the conversation?** Update `CONTEXT.md` right there. +- **User rejects the candidate with a load-bearing reason?** Offer an ADR, framed as: _"Want me to record this as an ADR so future architecture reviews don't re-suggest it?"_ Only offer when the reason would actually be needed by a future explorer to avoid re-suggesting the same thing — skip ephemeral reasons ("not worth it right now") and self-evident ones. See [ADR-FORMAT.md](../grill-with-docs/ADR-FORMAT.md). +- **Want to explore alternative interfaces for the deepened module?** See [INTERFACE-DESIGN.md](INTERFACE-DESIGN.md). diff --git a/.cursor/skills/internal-linking-optimizer/SKILL.md b/.cursor/skills/internal-linking-optimizer/SKILL.md new file mode 100644 index 0000000..d83f3eb --- /dev/null +++ b/.cursor/skills/internal-linking-optimizer/SKILL.md @@ -0,0 +1,351 @@ +--- +name: internal-linking-optimizer +description: 'Optimize internal links: site architecture, authority distribution, orphan pages, crawl depth analysis. 内链优化/站内架构' +version: "6.0.0" +license: Apache-2.0 +compatibility: "Claude Code ≥1.0, skills.sh marketplace, ClawHub marketplace, Vercel Labs skills ecosystem. No system packages required. Optional: MCP network access for SEO tool integrations." +homepage: "https://github.com/aaron-he-zhu/seo-geo-claude-skills" +when_to_use: "Use when improving internal link structure, anchor text distribution, orphan pages, or site architecture." +argument-hint: "" +metadata: + author: aaron-he-zhu + version: "6.0.0" + geo-relevance: "low" + tags: + - seo + - internal-linking + - site-architecture + - link-equity + - orphan-pages + - topical-authority + - crawl-depth + - 内链优化 + - 内部リンク + - 내부링크 + - enlaces-internos + triggers: + # EN-formal + - "fix internal links" + - "improve site architecture" + - "link structure" + - "distribute page authority" + - "internal linking strategy" + - "site navigation" + - "link equity" + # EN-casual + - "orphan pages" + - "site architecture is messy" + - "pages have no links pointing to them" + - "pages have no links" + - "site structure is messy" + # EN-question + - "how to improve internal linking" + - "how to fix orphan pages" + # ZH-pro + - "内链优化" + - "站内链接" + - "网站架构" + - "权重传递" + - "锚文本优化" + # ZH-casual + - "内链怎么做" + - "孤立页面" + - "网站结构乱" + # JA + - "内部リンク最適化" + - "サイト構造" + # KO + - "내부 링크 최적화" + - "사이트 구조" + # ES + - "enlaces internos" + - "arquitectura del sitio" + # PT + - "links internos" + # Misspellings + - "internal linkng" +--- + +# Internal Linking Optimizer + + +> **[SEO & GEO Skills Library](https://github.com/aaron-he-zhu/seo-geo-claude-skills)** · 20 skills for SEO + GEO · [ClawHub](https://clawhub.ai/u/aaron-he-zhu) · [skills.sh](https://skills.sh/aaron-he-zhu/seo-geo-claude-skills) +> **System Mode**: This optimization skill follows the shared [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md) and [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md). + + +This skill analyzes your site's internal link structure and provides recommendations to improve SEO through strategic internal linking. It helps distribute authority, establish topical relevance, and improve crawlability. + +**System role**: Optimization layer skill. It turns weak pages, structures, and technical issues into prioritized repair work. + +## When This Must Trigger + +Use this when the conversation involves any of these situations — even if the user does not use SEO terminology: + +Use this whenever the task needs a diagnosis or repair plan that should feed directly into remediation work, not just a one-time opinion. + +- Improving site architecture for SEO +- Distributing authority to important pages +- Fixing orphan pages with no internal links +- Creating topic cluster internal link strategies +- Optimizing anchor text for SEO +- Recovering pages that have lost rankings +- Planning internal links for new content + +## What This Skill Does + +1. **Link Structure Analysis**: Maps current internal linking patterns +2. **Authority Flow Mapping**: Shows how PageRank flows through site +3. **Orphan Page Detection**: Finds pages with no internal links +4. **Anchor Text Optimization**: Improves anchor text diversity +5. **Topic Cluster Linking**: Creates pillar-cluster link strategies +6. **Link Opportunity Finding**: Identifies where to add links +7. **Navigation Optimization**: Improves site-wide link elements + +## Quick Start + +Start with one of these prompts. Finish with a short handoff summary using the repository format in [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md). + +### Analyze Current Structure + +``` +Analyze internal linking structure for [domain/sitemap] +``` + +``` +Find internal linking opportunities for [URL] +``` + +### Create Linking Strategy + +``` +Create internal linking plan for topic cluster about [topic] +``` + +``` +Suggest internal links for this new article: [content/URL] +``` + +### Fix Issues + +``` +Find orphan pages on [domain] +``` + +``` +Optimize anchor text across the site +``` + +## Skill Contract + +**Expected output**: a scored diagnosis, prioritized repair plan, and a short handoff summary ready for `memory/audits/`. + +- **Reads**: the current page or site state, symptoms, prior audits, and current priorities from [CLAUDE.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CLAUDE.md) and the shared [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md) when available. +- **Writes**: a user-facing audit or optimization plan plus a reusable summary that can be stored under `memory/audits/`. +- **Promotes**: blocking defects, repeated weaknesses, and fix priorities to `memory/open-loops.md` and `memory/decisions.md`. +- **Next handoff**: use the `Next Best Skill` below when the repair path is clear. + +## Data Sources + +> **Note:** All integrations are optional. This skill works without any API keys — users provide data manually when no tools are connected. + +> See [CONNECTORS.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CONNECTORS.md) for tool category placeholders. + +**With ~~web crawler + ~~analytics connected:** +Claude can automatically perform a full site crawl via ~~web crawler to map the complete link graph, fetch page performance metrics from ~~analytics to identify high-value pages, and analyze link flow throughout the site. This enables data-driven internal linking strategies. + +**With manual data only:** +Ask the user to provide: +1. Sitemap URL or list of important pages +2. Key page URLs that need more internal links +3. Content categories or topic clusters +4. Any existing link structure documentation + +Proceed with the analysis using provided data. Note in the output which findings are from automated crawl vs. manual review. + +## Instructions + +When a user requests internal linking optimization: + +1. **Analyze Current Internal Link Structure** + + ```markdown + ## Internal Link Structure Analysis + + ### Overview + + **Domain**: [domain] + **Total Pages Analyzed**: [X] + **Total Internal Links**: [X] + **Average Links per Page**: [X] + + ### Link Distribution + + | Links per Page | Page Count | Percentage | + |----------------|------------|------------| + | 0 (Orphan) | [X] | [X]% | + | 1-5 | [X] | [X]% | + | 6-10 | [X] | [X]% | + | 11-20 | [X] | [X]% | + | 20+ | [X] | [X]% | + + ### Top Linked Pages + + | Page | Internal Links | Authority | Notes | + |------|----------------|-----------|-------| + | [URL 1] | [X] | High | [notes] | + | [URL 2] | [X] | High | [notes] | + | [URL 3] | [X] | Medium | [notes] | + + ### Under-Linked Important Pages + + | Page | Current Links | Traffic | Recommended Links | + |------|---------------|---------|-------------------| + | [URL 1] | [X] | [X]/mo | [X]+ | + | [URL 2] | [X] | [X]/mo | [X]+ | + + **Structure Score**: [X]/10 + ``` + +2. **Identify Orphan Pages** + + ```markdown + ## Orphan Page Analysis + + ### Definition + Orphan pages have no internal links pointing to them, making them + hard for users and search engines to discover. + + ### Orphan Pages Found: [X] + + | Page | Traffic | Priority | Recommended Action | + |------|---------|----------|-------------------| + | [URL 1] | [X]/mo | High | Link from [pages] | + | [URL 2] | [X]/mo | Medium | Add to navigation | + | [URL 3] | 0 | Low | Consider deleting/redirecting | + + ### Fix Strategy + + **High Priority Orphans** (have traffic/rankings): + 1. [URL] - Add links from: [relevant pages] + 2. [URL] - Add links from: [relevant pages] + + **Medium Priority Orphans** (potentially valuable): + 1. [URL] - Add to category/tag page + 2. [URL] - Link from related content + + **Low Priority Orphans** (consider removing): + 1. [URL] - Redirect to [better page] + 2. [URL] - Delete or noindex + ``` + +3. **Analyze Anchor Text Distribution** + + > **CORE-EEAT alignment**: Internal linking quality maps to R08 (Internal Link Graph) in the CORE-EEAT benchmark -- use descriptive anchors, ensure links support topical authority. See [content-quality-auditor](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/cross-cutting/content-quality-auditor/SKILL.md) for full audit. + + ```markdown + ## Anchor Text Analysis + + ### Current Anchor Text Patterns + + **Most Used Anchors**: + + | Anchor Text | Count | Target Pages | Assessment | + |-------------|-------|--------------|------------| + | "click here" | [X] | [X] pages | ❌ Not descriptive | + | "read more" | [X] | [X] pages | ❌ Not descriptive | + | "[exact keyword]" | [X] | [page] | ⚠️ May be over-optimized | + | "[descriptive phrase]" | [X] | [page] | ✅ Good | + + ### Anchor Text Distribution by Page + + **Page: [Important URL]** + + | Anchor Text | Source Page | Status | + |-------------|-------------|--------| + | "[anchor 1]" | [source URL] | ✅/⚠️/❌ | + | "[anchor 2]" | [source URL] | ✅/⚠️/❌ | + + **Issues Found**: + - Over-optimized anchors: [X] instances + - Generic anchors: [X] instances + - Same anchor to multiple pages: [X] instances + + ### Anchor Text Recommendations + + **For Page: [URL]** + + Current: "[current anchor]" used [X] times + + Recommended variety: + - "[variation 1]" - Use from [page type] + - "[variation 2]" - Use from [page type] + - "[variation 3]" - Use from [page type] + + **Anchor Score**: [X]/10 + ``` + +4. **Create Topic Cluster Link Strategy** — Map current pillar/cluster links, recommend link structure, list specific links to add + + > **Reference**: See [references/linking-templates.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/internal-linking-optimizer/references/linking-templates.md) for the topic cluster link strategy template (Step 4). + +5. **Find Contextual Link Opportunities** — Analyze each page for topic-relevant link opportunities, prioritize high-impact additions + + > **Reference**: See [references/linking-templates.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/internal-linking-optimizer/references/linking-templates.md) for the contextual link opportunities template (Step 5). + +6. **Optimize Navigation and Footer Links** — Analyze main/footer/sidebar/breadcrumb navigation, recommend pages to add or remove + + > **Reference**: See [references/linking-templates.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/internal-linking-optimizer/references/linking-templates.md) for the navigation optimization template (Step 6). + +7. **Generate Link Implementation Plan** — Executive summary, current state metrics, phased priority actions (weeks 1-4+), implementation guide, tracking plan + + > **Reference**: See [references/linking-templates.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/internal-linking-optimizer/references/linking-templates.md) for the full implementation plan template (Step 7). + +## Validation Checkpoints + +### Input Validation +- [ ] Site structure or sitemap provided (URL or file) +- [ ] Target pages or topic clusters clearly defined +- [ ] If optimizing specific page, page URL or content provided + +### Output Validation +- [ ] Every recommendation cites specific data points (not generic advice) +- [ ] All link suggestions include source page, target page, and recommended anchor text +- [ ] Orphan page lists include URLs and recommended actions +- [ ] Source of each data point clearly stated (~~web crawler data, ~~analytics, user-provided, or manual analysis) + +## Example + +> **Reference**: See [references/linking-example.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/internal-linking-optimizer/references/linking-example.md) for a full worked example (email marketing best practices internal linking opportunities). + +## Tips for Success + +1. **Quality over quantity** - Add relevant links, not random ones +2. **User-first thinking** - Links should help users navigate +3. **Vary anchor text** - Avoid over-optimization +4. **Link to important pages** - Distribute authority strategically +5. **Regular audits** - Internal links need maintenance as content grows + + +### Save Results + +After delivering audit or optimization findings to the user, ask: + +> "Save these results for future sessions?" + +If yes, write a dated summary to `memory/audits/internal-linking-optimizer/YYYY-MM-DD-.md` containing: +- One-line verdict or headline finding +- Top 3-5 actionable items +- Open loops or blockers +- Source data references + +If any veto-level issue was found (CORE-EEAT T04, C01, R10 or CITE T03, T05, T09), also append a one-liner to `memory/hot-cache.md` without asking. + +## Reference Materials + +- [Link Architecture Patterns](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/internal-linking-optimizer/references/link-architecture-patterns.md) — Architecture models (hub-and-spoke, silo, flat, pyramid, mesh), anchor text diversity framework, link equity flow model, and internal link audit checklist +- [Linking Templates](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/internal-linking-optimizer/references/linking-templates.md) — Detailed output templates for steps 6-7 (navigation optimization, implementation plan) +- [Linking Example](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/internal-linking-optimizer/references/linking-example.md) — Full worked example for internal linking opportunities + +## Next Best Skill + +- **Primary**: [on-page-seo-auditor](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/on-page-seo-auditor/SKILL.md) — verify that revised internal links support the page-level goals. diff --git a/.cursor/skills/keyword-research/SKILL.md b/.cursor/skills/keyword-research/SKILL.md new file mode 100644 index 0000000..fdbb208 --- /dev/null +++ b/.cursor/skills/keyword-research/SKILL.md @@ -0,0 +1,435 @@ +--- +name: keyword-research +description: 'Find high-value SEO keywords: search volume, difficulty, intent classification, topic clusters. 关键词研究/内容选题' +version: "6.0.0" +license: Apache-2.0 +compatibility: "Claude Code ≥1.0, skills.sh marketplace, ClawHub marketplace, Vercel Labs skills ecosystem. No system packages required. Optional: MCP network access for SEO tool integrations." +homepage: "https://github.com/aaron-he-zhu/seo-geo-claude-skills" +when_to_use: "Use when starting keyword research for a new page, topic, or campaign. Also when the user asks about search volume, keyword difficulty, topic clusters, long-tail keywords, or what to write about." +argument-hint: " [market/language]" +metadata: + author: aaron-he-zhu + version: "6.0.0" + geo-relevance: "medium" + tags: + - seo + - geo + - keywords + - keyword-research + - search-volume + - keyword-difficulty + - topic-clusters + - long-tail-keywords + - search-intent + - content-calendar + - ahrefs + - semrush + - google-keyword-planner + - 关键词研究 + - SEO关键词 + - キーワード調査 + - 키워드분석 + - palabras-clave + triggers: + # EN-formal + - "keyword research" + - "find keywords" + - "keyword analysis" + - "keyword discovery" + - "search volume analysis" + - "keyword difficulty" + - "topic research" + - "identify ranking opportunities" + # EN-casual + - "what should I write about" + - "what are people searching for" + - "what are people googling" + - "find me topics to write" + - "give me keyword ideas" + - "which keywords should I target" + - "why is my traffic low" + - "I need content ideas" + # EN-question + - "how do I find good keywords" + - "what keywords should I target" + - "how competitive is this keyword" + # EN-competitor + - "Ahrefs keyword explorer alternative" + - "Semrush keyword magic tool" + - "Google Keyword Planner alternative" + - "Ubersuggest alternative" + # ZH-pro + - "关键词研究" + - "关键词分析" + - "搜索量查询" + - "关键词难度" + - "SEO关键词" + - "长尾关键词" + - "词库整理" + - "关键词布局" + - "关键词挖掘" + # ZH-casual + - "写什么内容好" + - "找选题" + - "帮我挖词" + - "不知道写什么" + - "查关键词" + - "选词" + - "帮我找词" + # JA + - "キーワード調査" + - "キーワードリサーチ" + - "SEOキーワード分析" + - "検索ボリューム" + - "ロングテールキーワード" + - "検索意図分析" + # KO + - "키워드 리서치" + - "키워드 분석" + - "검색량 분석" + - "키워드 어떻게 찾아요?" + - "검색어 분석" + - "경쟁도 낮은 키워드는?" + # ES + - "investigación de palabras clave" + - "análisis de palabras clave" + - "volumen de búsqueda" + - "posicionamiento web" + - "cómo encontrar palabras clave" + # PT + - "pesquisa de palavras-chave" + # Misspellings + - "keywrod research" + - "keywork research" +--- + +# Keyword Research + + +> **[SEO & GEO Skills Library](https://github.com/aaron-he-zhu/seo-geo-claude-skills)** · 20 skills for SEO + GEO · [ClawHub](https://clawhub.ai/u/aaron-he-zhu) · [skills.sh](https://skills.sh/aaron-he-zhu/seo-geo-claude-skills) +> **System Mode**: This research skill follows the shared [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md) and [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md). + + +Discovers, analyzes, and prioritizes keywords for SEO and GEO content strategies. Identifies high-value opportunities based on search volume, competition, intent, and business relevance. + +**System role**: Research layer skill. It turns market signals into reusable strategic inputs for the rest of the library. + +## When This Must Trigger + +Use this when the conversation involves any of these situations — even if the user does not use SEO terminology: + +Use this whenever the task needs reusable market intelligence that should influence strategy, not just an ad hoc answer. + +- Starting a new content strategy or campaign +- Expanding into new topics or markets +- Finding keywords for a specific product or service +- Identifying long-tail keyword opportunities +- Understanding search intent for your industry +- Planning content calendars +- Researching keywords for GEO optimization + +## What This Skill Does + +1. **Keyword Discovery**: Generates comprehensive keyword lists from seed terms +2. **Intent Classification**: Categorizes keywords by user intent (informational, navigational, commercial, transactional) +3. **Difficulty Assessment**: Evaluates competition level and ranking difficulty +4. **Opportunity Scoring**: Prioritizes keywords by potential ROI +5. **Clustering**: Groups related keywords into topic clusters +6. **GEO Relevance**: Identifies keywords likely to trigger AI responses + +## Quick Start + +Start with one of these prompts. Finish with a short handoff summary using the repository format in [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md). + +### Basic Keyword Research + +``` +Research keywords for [topic/product/service] +``` + +``` +Find keyword opportunities for a [industry] business targeting [audience] +``` + +### With Specific Goals + +``` +Find low-competition keywords for [topic] with commercial intent +``` + +``` +Identify question-based keywords for [topic] that AI systems might answer +``` + +### Competitive Research + +``` +What keywords is [competitor URL] ranking for that I should target? +``` + +## Skill Contract + +**Expected output**: a prioritized research brief, evidence-backed findings, and a short handoff summary ready for `memory/research/`. + +- **Reads**: user goals, target market inputs, available tool data, and prior strategy from [CLAUDE.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CLAUDE.md) and the shared [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md) when available. +- **Writes**: a user-facing research deliverable plus a reusable summary that can be stored under `memory/research/`. +- **Promotes**: durable keyword priorities, competitor facts, entity candidates, and strategic decisions to `CLAUDE.md`, `memory/decisions.md`, and `memory/research/`; hand canonical entity work to `entity-optimizer`. +- **Next handoff**: use the `Next Best Skill` below when the findings are ready to drive action. + +## Data Sources + +> **Note:** All integrations are optional. This skill works without any API keys — users provide data manually when no tools are connected. + +> See [CONNECTORS.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CONNECTORS.md) for tool category placeholders. + +**With ~~SEO tool + ~~search console connected:** +Automatically pull historical search volume data, keyword difficulty scores, SERP analysis, current rankings from ~~search console, and competitor keyword overlap. The skill will fetch seed keyword metrics, related keyword suggestions, and search trend data. + +**With manual data only:** +Ask the user to provide: +1. Seed keywords or topic description +2. Target audience and geographic location +3. Business goals (traffic, leads, sales) +4. Current domain authority (if known) or site age +5. Any known keyword performance data or search volume estimates + +Proceed with the full analysis using provided data. Note in the output which metrics are from automated collection vs. user-provided data. + +## Instructions + +When a user requests keyword research: + +At the start of each phase, announce: **[Phase X/8: Name]** so the user can track progress. + +### Phase 1/8: Scope + + Ask clarifying questions if not provided: + - What is your product/service/topic? + - Who is your target audience? + - What is your business goal? (traffic, leads, sales) + - What is your current domain authority? (new site, established, etc.) + - Any specific geographic targeting? + - Preferred language? + +### Phase 2/8: Discover + + Start with: + - Core product/service terms + - Problem-focused keywords (what issues do you solve?) + - Solution-focused keywords (how do you help?) + - Audience-specific terms + - Industry terminology + +### Phase 3/8: Variations + + For each seed keyword, generate variations: + + ```markdown + ## Keyword Expansion Patterns + + ### Modifiers + - Best [keyword] + - Top [keyword] + - [keyword] for [audience] + - [keyword] near me + - [keyword] [year] + - How to [keyword] + - What is [keyword] + - [keyword] vs [alternative] + - [keyword] examples + - [keyword] tools + + ### Long-tail Variations + - [keyword] for beginners + - [keyword] for small business + - Free [keyword] + - [keyword] software/tool/service + - [keyword] template + - [keyword] checklist + - [keyword] guide + ``` + +### Phase 4/8: Classify + + Categorize each keyword: + + | Intent | Signals | Example | Content Type | + |--------|---------|---------|--------------| + | Informational | what, how, why, guide, learn | "what is SEO" | Blog posts, guides | + | Navigational | brand names, specific sites | "google analytics login" | Homepage, product pages | + | Commercial | best, review, vs, compare | "best SEO tools [current year]" | Comparison posts, reviews | + | Transactional | buy, price, discount, order | "buy SEO software" | Product pages, pricing | + +### Phase 5/8: Score + + Score each keyword (1-100 scale): + + ```markdown + ### Difficulty Factors + + **High Difficulty (70-100)** + - Major brands ranking + - High domain authority competitors + - Established content (1000+ backlinks) + - Paid ads dominating SERP + + **Medium Difficulty (40-69)** + - Mix of authority and niche sites + - Some opportunities for quality content + - Moderate backlink requirements + + **Low Difficulty (1-39)** + - Few authoritative competitors + - Thin or outdated content ranking + - Long-tail variations + - New or emerging topics + ``` + +#### Opportunity Score + + Formula: `Opportunity = (Volume × Intent Value) / Difficulty` + + **Intent Value** assigns a numeric weight by search intent: + - Informational = 1 + - Navigational = 1 + - Commercial = 2 + - Transactional = 3 + + ```markdown + ### Opportunity Matrix + + | Scenario | Volume | Difficulty | Intent | Priority | + |----------|--------|------------|--------|----------| + | Quick Win | Low-Med | Low | High | ⭐⭐⭐⭐⭐ | + | Growth | High | Medium | High | ⭐⭐⭐⭐ | + | Long-term | High | High | High | ⭐⭐⭐ | + | Research | Low | Low | Low | ⭐⭐ | + ``` + +### Phase 6/8: GEO-Check — AI Answer Overlap + + Keywords likely to trigger AI responses: + + ```markdown + ### GEO-Relevant Keywords + + **High GEO Potential** + - Question formats: "What is...", "How does...", "Why is..." + - Definition queries: "[term] meaning", "[term] definition" + - Comparison queries: "[A] vs [B]", "difference between..." + - List queries: "best [category]", "top [number] [items]" + - How-to queries: "how to [action]", "steps to [goal]" + + **AI Answer Indicators** + - Query is factual/definitional + - Answer can be summarized concisely + - Topic is well-documented online + - Low commercial intent + ``` + +### Phase 7/8: Cluster + + Group keywords into content clusters: + + ```markdown + ## Topic Cluster: [Main Topic] + + **Pillar Content**: [Primary keyword] + - Search volume: [X] + - Difficulty: [X] + - Content type: Comprehensive guide + + **Cluster Content**: + + ### Sub-topic 1: [Secondary keyword] + - Volume: [X] + - Difficulty: [X] + - Links to: Pillar + - Content type: [Blog post/Tutorial/etc.] + + ### Sub-topic 2: [Secondary keyword] + - Volume: [X] + - Difficulty: [X] + - Links to: Pillar + Sub-topic 1 + - Content type: [Blog post/Tutorial/etc.] + + [Continue for all cluster keywords...] + ``` + +### Phase 8/8: Deliver + + Produce a report containing: Executive Summary, Top Keyword Opportunities (Quick Wins, Growth, GEO), Topic Clusters, Content Calendar, and Next Steps. + + **Quality bar** — every recommendation must include at least one specific number. If it reads like the left column, rewrite it before including. + + | ❌ Generic (rewrite before including) | ✅ Actionable | + |---|---| + | "Target long-tail keywords for better results" | "Target 'project management for nonprofits' (vol: 320, KD: 22) — no DR>40 sites in top 10" | + | "This keyword has good potential" | "Opportunity 8.4: vol 4,800, KD 28, transactional intent — gap analysis shows no content updated since 2023 in top 5" | + | "Consider creating content around this topic" | "Write '[Tool A] vs [Tool B] for small teams' — 1,200/mo searches, current #1 is a 2022 article with 12 backlinks" | + | "Optimize your page for this keyword" | "Add primary keyword to H1 (currently missing), write a 40-word direct answer in paragraph 1, add 3 internal links from your /blog/ cluster" | + + > **Reference**: See [references/example-report.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/research/keyword-research/references/example-report.md) for the full report template and example. + +## Validation Checkpoints + +### Input Validation +- [ ] Seed keywords or topic description clearly provided +- [ ] Target audience and business goals specified +- [ ] Geographic and language targeting confirmed +- [ ] Domain authority or site maturity level established + +### Output Validation +- [ ] Every recommendation cites specific data points (not generic advice) +- [ ] Search volume and difficulty scores included for each keyword +- [ ] Keywords grouped by intent and mapped to content types +- [ ] Topic clusters show clear pillar-to-cluster relationships +- [ ] Source of each data point clearly stated (~~SEO tool data, user-provided, or estimated) + +## Example + +> **Reference**: See [references/example-report.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/research/keyword-research/references/example-report.md) for a complete example report for "project management software for small businesses". + +### Advanced Usage + +- **Intent Mapping**: `Map all keywords for [topic] by search intent and funnel stage` +- **Seasonal Analysis**: `Identify seasonal keyword trends for [industry]` +- **Competitor Gap**: `What keywords do [competitor 1], [competitor 2] rank for that I'm missing?` +- **Local Keywords**: `Research local keywords for [business type] in [city/region]` + +## Tips for Success + +1. **Start with seed keywords** that describe your core offering +2. **Don't ignore long-tail** - they often have highest conversion rates +3. **Match content to intent** - informational queries need guides, not sales pages +4. **Group into clusters** for topical authority +5. **Prioritize quick wins** to build momentum and credibility +6. **Include GEO keywords** in your strategy for AI visibility +7. **Review quarterly** - keyword dynamics change over time + + + +### Save Results + +After delivering findings to the user, ask: + +> "Save these results for future sessions?" + +If yes, write a dated summary to `memory/research/keyword-research/YYYY-MM-DD-.md` containing: +- One-line headline finding +- Top 3-5 actionable items +- Open loops or blockers +- Source data references + +If any findings should influence ongoing strategy, recommend promoting key conclusions to `memory/hot-cache.md`. + +## Reference Materials + +- [Keyword Intent Taxonomy](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/research/keyword-research/references/keyword-intent-taxonomy.md) — Complete intent classification with signal words and content strategies +- [Topic Cluster Templates](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/research/keyword-research/references/topic-cluster-templates.md) — Hub-and-spoke architecture templates for pillar and cluster content +- [Keyword Prioritization Framework](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/research/keyword-research/references/keyword-prioritization-framework.md) — Priority scoring matrix, categories, and seasonal keyword patterns +- [Example Report](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/research/keyword-research/references/example-report.md) — Complete example keyword research report for project management software + +## Next Best Skill + +- **Primary**: [competitor-analysis](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/research/competitor-analysis/SKILL.md) — turn keyword opportunities into a competitive benchmark. diff --git a/.cursor/skills/memory-management/SKILL.md b/.cursor/skills/memory-management/SKILL.md new file mode 100644 index 0000000..c9ec3af --- /dev/null +++ b/.cursor/skills/memory-management/SKILL.md @@ -0,0 +1,342 @@ +--- +name: memory-management +description: 'Persist SEO/GEO campaign context across Claude sessions with automatic hot-list, active work, and archive tiers. 项目记忆/跨会话' +version: "7.0.0" +license: Apache-2.0 +compatibility: "Claude Code ≥1.0, skills.sh marketplace, ClawHub marketplace, Vercel Labs skills ecosystem. No system packages required. Optional: MCP network access for SEO tool integrations." +homepage: "https://github.com/aaron-he-zhu/seo-geo-claude-skills" +when_to_use: "Use when reviewing, archiving, or cleaning up campaign memory. Also when the user asks to check saved findings, manage hot cache, or archive old data." +argument-hint: "[review|archive|cleanup]" +metadata: + author: aaron-he-zhu + version: "7.0.0" + geo-relevance: "low" + tags: + - seo + - geo + - project-memory + - context-management + - campaign-tracking + - session-context + - hot-cache + - 项目记忆 + - プロジェクト記憶 + - 프로젝트메모리 + - memoria-proyecto + triggers: + # EN-formal + - "remember project context" + - "save SEO data" + - "track campaign progress" + - "store keyword data" + - "manage project memory" + - "project context" + - "refresh wiki index" + - "build wiki index" + - "wiki lint" + # EN-casual + - "remember this for next time" + - "save my keyword data" + - "keep track of this campaign" + - "what did we decide last time" + - "what do we know so far" + - "project status" + # EN-question + - "how to save project progress" + # ZH-pro + - "项目记忆管理" + - "SEO数据保存" + - "跨会话记忆" + - "刷新wiki索引" + - "项目状况" + # ZH-casual + - "保存进度" + - "上次说了什么" + - "记住这个" + # JA + - "プロジェクト記憶" + - "SEOデータ保存" + # KO + - "프로젝트 메모리" + - "데이터 저장" + # ES + - "memoria del proyecto" + - "guardar progreso" + # PT + - "memória do projeto" +--- + +# Memory Management + +> **[SEO & GEO Skills Library](https://github.com/aaron-he-zhu/seo-geo-claude-skills)** · 20 skills for SEO + GEO · [ClawHub](https://clawhub.ai/u/aaron-he-zhu) · [skills.sh](https://skills.sh/aaron-he-zhu/seo-geo-claude-skills) +> **System Mode**: This cross-cutting skill is part of the protocol layer and follows the shared [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md) and [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md). + +This skill implements a three-tier memory system (HOT/WARM/COLD) for SEO and GEO projects. HOT memory (80 lines max) loads automatically every session via the SessionStart hook. WARM memory loads on demand per skill. COLD memory is archived data queried only when explicitly requested. The skill manages the full lifecycle: capture, promote, demote, and archive. + +**System role**: Campaign Memory Loop. It defines how project context is captured, promoted, archived, and handed off across sessions. It is the sole executor of WARM-to-COLD archival and the aggregator for cross-skill project status queries. + +## When This Must Trigger + +Use this whenever project state should survive the current session — even if the user doesn't use memory terminology: + +- User says "remember this", "save this", "keep track of this" +- User asks "what did we decide", "what do we know", "project status" +- Setting up memory structure for a new SEO project +- After completing audits, ranking checks, or performance reports (Stop hook reminds automatically) +- When project context needs updating (new keywords, competitors, priorities) +- When you need to look up historical data or project-specific terminology +- After 30+ days of work to clean up and archive stale data +- When open-loops.md has items older than 7 days (SessionStart hook reminds automatically) + +## What This Skill Does + +1. **HOT Cache Management**: Maintains `memory/hot-cache.md` (80 lines max) — loaded automatically every session by SessionStart hook +2. **WARM Storage**: Organizes dated findings in `memory/` subdirectories — loaded on demand by relevant skills +3. **COLD Archive**: Moves stale data (90+ days unreferenced) to `memory/archive/` with date prefix +4. **Promotion**: Elevates frequently-referenced findings from WARM to HOT (3+ refs in 7 days, or 2+ skill refs) +5. **Demotion**: Moves unreferenced HOT items to WARM (30 days), WARM to COLD (90 days) +6. **Cross-Skill Aggregation**: When user asks "what do we know", aggregates from all `memory/` subdirectories +7. **Open Loop Tracking**: Maintains `memory/open-loops.md`, reminds user of stale items via SessionStart hook +8. **Wiki Index Maintenance**: Compiles `memory/wiki/index.md` — a structured, auto-refreshed index of all WARM files with precise fields (score, 健康度, status, next_action, mtime) and best-effort summaries. Supports project isolation via `memory/wiki//index.md`. Auto-refreshed on PostToolUse; user confirmation not required (index is a fully rebuildable derived artifact). Delete `memory/wiki/` at any time to revert to pre-wiki behavior. +9. **Wiki Compiled Pages** (Phase 2): Generates interlinked entity, keyword, and topic pages from WARM files with source hash tracking, contradiction detection, and confidence-labeled reconciliation. Requires user confirmation before writing. +10. **Wiki Lint** (Phase 2): Detects contradictions, orphan pages, stale claims, missing pages, and source hash mismatches across wiki and WARM files via `/seo:wiki-lint`. +11. **WARM Retirement Preview** (Phase 3): `wiki-lint --retire-preview` lists WARM files fully covered by wiki compiled pages as retirement candidates. Actual archival to COLD requires explicit user confirmation. + +## Quick Start + +Start with one of these prompts. Finish with a hot-cache update plan and a handoff summary using the repository format in [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md). + +### Initialize Wiki Index + +``` +Refresh wiki index +``` + +``` +Build wiki index for [project name] +``` + +Generates `memory/wiki/index.md` from existing WARM files. Required once to enable wiki features; subsequent refreshes happen automatically. + +### Initialize Memory Structure + +``` +Set up SEO memory for [project name] +``` + +``` +Initialize memory structure for a new [industry] website optimization project +``` + +### Update After Analysis + +``` +Update memory after ranking check for [keyword group] +``` + +``` +Refresh hot cache with latest competitor analysis findings +``` + +### Query Stored Context + +``` +What are our hero keywords? +``` + +``` +Show me the last ranking update date for [keyword category] +``` + +``` +Look up our primary competitors and their domain authority +``` + +### Promotion and Demotion + +``` +Promote [keyword] to hot cache +``` + +``` +Archive stale data that hasn't been referenced in 30+ days +``` + +### Glossary Management + +``` +Add [term] to project glossary: [definition] +``` + +``` +What does [internal jargon] mean in this project? +``` + +## Skill Contract + +**Expected output**: a memory update plan, hot-cache changes, and a short handoff summary. + +- **Reads**: current campaign facts, new findings from other skills, approved decisions, and the shared [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md). +- **Writes**: updates to `memory/hot-cache.md`, `memory/open-loops.md`, `memory/decisions.md`, and related `memory/` folders. Manages WARM-to-COLD archival in `memory/archive/`. Compiles `memory/wiki/index.md` (auto-refreshed) and wiki compiled pages (user-confirmed). +- **Promotes**: durable strategy, blockers, terminology, entity candidates, and major deltas. Applies temperature lifecycle rules: promote to HOT on high reference frequency, demote on staleness. +- **Next handoff**: use the `Next Best Skill` below when the project memory baseline is ready for active work. + +### Temperature Lifecycle Rules + +> See [references/promotion-demotion-rules.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/cross-cutting/memory-management/references/promotion-demotion-rules.md) for the full promotion/demotion table and action procedures. + +### Hook Integration + +This skill's behavior is reinforced by the library's prompt-based hooks: +- **SessionStart**: loads `memory/hot-cache.md`, reminds of stale open loops; loads `memory/wiki//index.md` (or global `index.md`) if it exists; provides light-user guidance based on Quick Status when `next_action` items are available +- **PostToolUse**: after any WARM file write, silently refreshes `memory/wiki/index.md` (Phase 1); prompts to update compiled pages (Phase 2) +- **Stop**: prompts to save session findings, auto-saves veto issues to hot-cache; appends changelog entry to index.md bottom + +## Data Sources + +> See [CONNECTORS.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CONNECTORS.md) for tool category placeholders. + +**With ~~SEO tool + ~~analytics + ~~search console connected:** +Automatically populate memory from historical data: keyword rankings over time, competitor domain authority changes, traffic metrics, conversion data, backlink profile evolution. The skill will fetch current rankings, alert on significant changes, and update both hot cache and cold storage. + +**With manual data only:** +Ask the user to provide: +1. Current target keywords with priority levels +2. Primary competitors (3-5 domains) +3. Key performance metrics and last update date +4. Active campaigns and their status +5. Any project-specific terminology or abbreviations + +Proceed with memory structure creation using provided data. Note in CLAUDE.md which data requires manual updates vs. automated refresh. + +## Instructions + +When a user requests SEO memory management: + +### 1. Initialize Memory Structure + +For new projects, create the directory structure defined in the [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md). Key directories: `memory/` (decisions, open-loops, glossary, entities, research, content, audits, monitoring) plus `memory/wiki/` (auto-managed compiled index with optional per-project subdirectories). + +> **Templates**: [hot-cache-template.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/cross-cutting/memory-management/references/hot-cache-template.md) · [glossary-template.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/cross-cutting/memory-management/references/glossary-template.md) · [Wiki spec](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/proposal-wiki-layer-v3.md) + +### 2. Context Lookup Flow + +When a user references something unclear, follow this lookup sequence: + +**Step 1: Check CLAUDE.md (Hot Cache)** +- Is it in active keywords? +- Is it in primary competitors? +- Is it in current priorities or campaigns? + +**Step 2: Check Wiki Index** (`memory/wiki/index.md` or project-level) — locate relevant WARM files + +**Step 3: Check memory/glossary.md** +- Is it defined as project terminology? +- Is it a custom segment or shorthand? + +**Step 4: Check Cold Storage** +- Search memory/research/keywords/ for historical keyword context +- Search memory/research/competitors/ for past analyses +- Search memory/monitoring/reports/ for archived mentions + +**Step 5: Ask User** +- If not found in any layer, ask for clarification +- Log the new term in glossary if it's project-specific + +Example lookup: + +```markdown +User: "Update rankings for our hero KWs" + +Step 1: Check CLAUDE.md → Found "Hero Keywords (Priority 1)" section +Step 2: Extract keyword list from hot cache +Step 3: Execute ranking check +Step 4: Update both CLAUDE.md and memory/monitoring/rank-history/YYYY-MM-DD-ranks.csv +``` + +### 3. Promotion & Demotion Logic + +> **Reference**: See [references/promotion-demotion-rules.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/cross-cutting/memory-management/references/promotion-demotion-rules.md) for detailed promotion/demotion triggers (keywords, competitors, metrics, campaigns) and the action procedures for each. + +### 4. Update Triggers, Archive Management & Cross-Skill Integration + +> **Reference**: See [references/update-triggers-integration.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/cross-cutting/memory-management/references/update-triggers-integration.md) for the complete update procedures after ranking checks, competitor analyses, audits, and reports; monthly/quarterly archive routines; and integration points with all 8 connected skills (keyword-research, rank-tracker, competitor-analysis, content-gap-analysis, seo-content-writer, content-quality-auditor, domain-authority-auditor). + +### 5. Memory Hygiene Checks + +When invoked for review or cleanup: + +1. **Line count check**: Count lines in `memory/hot-cache.md`. If >80, list oldest entries for archival. +2. **Byte check**: If hot-cache exceeds 25KB, warn and recommend trimming long entries. +3. **Staleness scan**: List memory files older than 30 days that have not been referenced. Recommend archival for files >90 days. +4. **Frontmatter audit**: Check that all memory files (except hot-cache.md) have `name`, `description`, and `type` in their frontmatter. Report any missing fields. + +### 6. Save Results + +After delivering any memory update or aggregation to the user, ask: + +> "Save these results for future sessions?" + +If yes, write a dated summary to the appropriate `memory/` path using filename `YYYY-MM-DD-.md` containing: +- One-line verdict or headline finding +- Top 3-5 actionable items +- Open loops or blockers +- Source data references + +If any veto-level issue was found (CORE-EEAT T04, C01, R10 or CITE T03, T05, T09), also append a one-liner to `memory/hot-cache.md` without asking. + +## Validation Checkpoints + +### Structure Validation +- [ ] memory/hot-cache.md exists and is under 80 lines +- [ ] memory/ directory structure matches the shared state model +- [ ] glossary.md exists and is populated with project basics +- [ ] All historical data files include timestamps in filename or metadata + +### Content Validation +- [ ] CLAUDE.md "Last Updated" date is current +- [ ] Every keyword in hot cache has current rank, target rank, and status +- [ ] Every competitor has domain authority and position assessment +- [ ] Every active campaign has status percentage and expected completion date +- [ ] Key Metrics Snapshot shows "Previous" values for comparison + +### Lookup Validation +- [ ] Test lookup flow: reference a term → verify it finds it in correct layer +- [ ] Test promotion: manually promote item → verify it appears in CLAUDE.md +- [ ] Test demotion: manually archive item → verify removed from CLAUDE.md +- [ ] Glossary contains all custom segments and shorthand used in CLAUDE.md + +### Update Validation +- [ ] After ranking check, `memory/monitoring/rank-history/` has a dated snapshot or export +- [ ] After competitor analysis, `memory/research/competitors/` has a dated file +- [ ] After audit, top action items appear in CLAUDE.md priorities +- [ ] After monthly report, metrics snapshot reflects new data + +## Examples + +> **Reference**: See [references/examples.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/cross-cutting/memory-management/references/examples.md) for three complete examples: (1) updating hero keyword rankings with memory refresh, (2) glossary lookup flow, and (3) initializing memory for a new e-commerce project. + +## Advanced Features + +- **Smart Context Loading**: `Load full context for [campaign name]` — retrieves hot cache + all cold storage files for a campaign +- **Memory Health Check**: `Run memory health check` — finds orphaned files, missing timestamps, stale items, broken references +- **Bulk Promotion/Demotion**: `Promote all keywords ranking in top 10 to hot cache` / `Demote all completed campaigns from Q3` +- **Memory Snapshot**: `Create memory snapshot for [date/milestone]` — point-in-time copy for major milestones +- **Cross-Project Memory**: `Compare memory with [other project]` — keyword overlaps, competitor intersections across projects +- **Wiki Lint**: `/seo:wiki-lint [--fix] [--project name] [--retire-preview]` — contradictions, orphans, stale claims, hash mismatches. See [commands/wiki-lint.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/commands/wiki-lint.md) + +## Practical Limitations + +- **Concurrent access**: Use timestamped filenames to avoid overwrites from parallel sessions. +- **Cold storage retrieval**: WARM/COLD files only load on demand. Hot cache is the primary cross-session mechanism. +- **Data freshness**: Stale data (>90 days) should be flagged for refresh. Wiki index `mtime` field helps detect staleness. +- **Wiki compilation**: Index is best-effort for summaries; precise fields (score, status, mtime) are deterministic. Delete `memory/wiki/` anytime to revert. + +## Reference Materials + +- [CORE-EEAT Content Benchmark](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/core-eeat-benchmark.md) — Content quality scoring stored in memory +- [CITE Domain Rating](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/cite-domain-rating.md) — Domain authority scoring stored in memory + +## Next Best Skill + +- **Primary**: [keyword-research](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/research/keyword-research/SKILL.md) — seed or refresh campaign strategy with current demand signals. diff --git a/.cursor/skills/meta-tags-optimizer/SKILL.md b/.cursor/skills/meta-tags-optimizer/SKILL.md new file mode 100644 index 0000000..1e3a81c --- /dev/null +++ b/.cursor/skills/meta-tags-optimizer/SKILL.md @@ -0,0 +1,417 @@ +--- +name: meta-tags-optimizer +description: 'Optimize title tags, meta descriptions, Open Graph, Twitter cards for maximum CTR with A/B variations. 标题优化/元描述/CTR' +version: "6.0.0" +license: Apache-2.0 +compatibility: "Claude Code ≥1.0, skills.sh marketplace, ClawHub marketplace, Vercel Labs skills ecosystem. No system packages required. Optional: MCP network access for SEO tool integrations." +homepage: "https://github.com/aaron-he-zhu/seo-geo-claude-skills" +when_to_use: "Use when optimizing title tags, meta descriptions, Open Graph tags, or Twitter Cards for a page." +argument-hint: "" +metadata: + author: aaron-he-zhu + version: "6.0.0" + geo-relevance: "low" + tags: + - seo + - meta-tags + - title-tag + - meta-description + - open-graph + - twitter-card + - ctr-optimization + - social-sharing + - 标题优化 + - 元描述 + - メタタグ + - 메타태그 + - meta-tags-seo + triggers: + # EN-formal + - "optimize title tag" + - "write meta description" + - "improve CTR" + - "Open Graph tags" + - "social media preview" + - "title optimization" + - "meta tags" + - "Twitter cards" + # EN-casual + - "my title tag needs work" + - "low click-through rate" + - "fix my meta tags" + - "OG tags not showing" + - "social preview looks wrong" + - "my click rate is low" + # EN-question + - "how to write a good title tag" + - "how to improve click-through rate" + - "what is a good meta description" + # EN-competitor + - "Yoast SEO title tool" + - "RankMath title optimizer" + # ZH-pro + - "标题标签优化" + - "元描述优化" + - "OG标签" + - "点击率提升" + - "社交预览" + - "TDK优化" + # ZH-casual + - "标题不好" + - "点击率太低" + - "社交分享预览不对" + - "标题怎么写" + - "TDK怎么写" + # JA + - "メタタグ最適化" + - "タイトルタグ" + - "CTR改善" + # KO + - "메타 태그 최적화" + - "제목 태그" + - "클릭률 개선" + # ES + - "optimizar meta tags" + - "mejorar CTR" + - "etiquetas Open Graph" + # PT + - "otimizar meta tags" + # Misspellings + - "meta discription" + - "tittle tag" +--- + +# Meta Tags Optimizer + +> **[SEO & GEO Skills Library](https://github.com/aaron-he-zhu/seo-geo-claude-skills)** · 20 skills for SEO + GEO · [ClawHub](https://clawhub.ai/u/aaron-he-zhu) · [skills.sh](https://skills.sh/aaron-he-zhu/seo-geo-claude-skills) +> **System Mode**: This build skill follows the shared [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md) and [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md). + + +This skill creates compelling, optimized meta tags that improve click-through rates from search results and enhance social media sharing. It covers title tags, meta descriptions, and social meta tags. + +**System role**: Build layer skill. It turns briefs and signals into assets that other skills can review, publish, and monitor. + +## When This Must Trigger + +Use this when the conversation involves any of these situations — even if the user does not use SEO terminology: + +Use this whenever the task needs a shippable asset or transformation that should feed directly into quality review, deployment, or monitoring. + +- Creating meta tags for new pages +- Optimizing existing meta tags for better CTR +- Preparing pages for social media sharing +- Fixing duplicate or missing meta tags +- A/B testing title and description variations +- Optimizing for specific SERP features +- Creating meta tags for different page types + +## What This Skill Does + +1. **Title Tag Creation**: Writes compelling, keyword-optimized titles +2. **Meta Description Writing**: Creates click-worthy descriptions +3. **Open Graph Optimization**: Prepares pages for social sharing +4. **Twitter Card Setup**: Optimizes Twitter-specific meta tags +5. **CTR Analysis**: Suggests improvements for better click rates +6. **Character Counting**: Ensures proper length for SERP display +7. **A/B Test Suggestions**: Provides variations for testing + +## Quick Start + +Start with one of these prompts. Finish with a short handoff summary using the repository format in [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md). + +### Create Meta Tags + +``` +Create meta tags for a page about [topic] targeting [keyword] +``` + +``` +Write title and meta description for this content: [content/URL] +``` + +### Optimize Existing Tags + +``` +Improve these meta tags for better CTR: [current tags] +``` + +### Social Media Tags + +``` +Create Open Graph and Twitter card tags for [page/URL] +``` + +## Skill Contract + +**Expected output**: a ready-to-use asset or implementation-ready transformation plus a short handoff summary ready for `memory/content/`. + +- **Reads**: the brief, target keywords, entity inputs, quality constraints, and prior decisions from [CLAUDE.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CLAUDE.md) and the shared [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md) when available. +- **Writes**: a user-facing content, metadata, or schema deliverable plus a reusable summary that can be stored under `memory/content/`. +- **Promotes**: approved angles, messaging choices, missing evidence, and publish blockers to `CLAUDE.md`, `memory/decisions.md`, and `memory/open-loops.md`. +- **Next handoff**: use the `Next Best Skill` below when the asset is ready for review or deployment. + +## Data Sources + +> See [CONNECTORS.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CONNECTORS.md) for tool category placeholders. + +**With ~~search console + ~~SEO tool connected:** +Automatically pull current meta tags, CTR data by query, competitor title/description patterns, SERP preview data, and impression/click metrics to identify optimization opportunities. + +**With manual data only:** +Ask the user to provide: +1. Current title and meta description (if optimizing existing) +2. Target primary keyword and 2-3 secondary keywords +3. Page URL and main content/value proposition +4. Competitor URLs or examples of well-performing titles in the SERP + +Proceed with the full workflow using provided data. Note in the output which metrics are from automated collection vs. user-provided data. + +## Instructions + +When a user requests meta tag optimization: + +1. **Gather Page Information** + + ```markdown + ### Page Analysis + + **Page URL**: [URL] + **Page Type**: [blog/product/landing/service/homepage] + **Primary Keyword**: [keyword] + **Secondary Keywords**: [keywords] + **Target Audience**: [audience] + **Primary CTA**: [action you want users to take] + **Unique Value Prop**: [what makes this page special] + ``` + +2. **Create Optimized Title Tag** + + ```markdown + ### Title Tag Optimization + + **Requirements**: + - Length: 50-60 characters (displays fully in SERP) + - Include primary keyword (preferably near front) + - Make it compelling and click-worthy + - Match search intent + - Include brand name if appropriate + + **Title Tag Formula Options**: + + 1. **Keyword | Benefit | Brand** + "[Primary Keyword]: [Benefit] | [Brand Name]" + + 2. **Number + Keyword + Promise** + "[Number] [Keyword] That [Promise/Result]" + + 3. **How-to Format** + "How to [Keyword]: [Benefit/Result]" + + 4. **Question Format** + "What is [Keyword]? [Brief Answer/Hook]" + + 5. **Year + Keyword** + "[Keyword] in [Year]: [Hook/Update]" + + **Generated Title Options**: + + | Option | Title | Length | Power Words | Keyword Position | + |--------|-------|--------|-------------|------------------| + | 1 | [Title] | [X] chars | [words] | [Front/Middle] | + | 2 | [Title] | [X] chars | [words] | [Front/Middle] | + | 3 | [Title] | [X] chars | [words] | [Front/Middle] | + + **Recommended**: Option [X] + **Reasoning**: [Why this option is best] + + **Title Tag Code**: + ```html + [Selected Title] + ``` + ``` + +3. **Write Meta Description** + + ```markdown + ### Meta Description Optimization + + **Requirements**: + - Length: 150-160 characters (displays fully in SERP) + - Include primary keyword naturally + - Include clear call-to-action + - Match page content accurately + - Create urgency or curiosity + - Avoid duplicate descriptions + + **Meta Description Formula**: + + [What the page offers] + [Benefit to user] + [Call-to-action] + + **Power Elements to Include**: + - Numbers and statistics + - Current year + - Emotional triggers + - Action verbs + - Unique value proposition + + **Generated Description Options**: + + | Option | Description | Length | CTA | Emotional Trigger | + |--------|-------------|--------|-----|-------------------| + | 1 | [Description] | [X] chars | [CTA] | [Trigger] | + | 2 | [Description] | [X] chars | [CTA] | [Trigger] | + | 3 | [Description] | [X] chars | [CTA] | [Trigger] | + + **Recommended**: Option [X] + **Reasoning**: [Why this option is best] + + **Meta Description Code**: + ```html + + ``` + ``` + +4. **Create Open Graph, Twitter Card, and Additional Meta Tags** + + Generate OG tags (og:type, og:url, og:title, og:description, og:image), Twitter Card tags, canonical URL, robots, viewport, author, and article-specific tags. Then combine into a complete meta tag block. + + > **Reference**: See [references/meta-tag-code-templates.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/build/meta-tags-optimizer/references/meta-tag-code-templates.md) for OG type selection guide, Twitter card type selection, all HTML code templates, and the complete meta tag block template. + +5. **CORE-EEAT Alignment Check** + + Verify meta tags align with content quality standards. Reference: [CORE-EEAT Benchmark](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/core-eeat-benchmark.md) + + ```markdown + ### CORE-EEAT Meta Tag Alignment + + | Check | Status | Notes | + |-------|--------|-------| + | **C01 Intent Alignment**: Title promise matches actual content delivery | ✅/⚠️/❌ | [Does the title accurately represent what the page delivers?] | + | **C02 Direct Answer**: Meta description reflects the core answer available in first 150 words | ✅/⚠️/❌ | [Does the description preview the direct answer?] | + + **If C01 fails**: Title is misleading — rewrite to match actual content. + **If C02 fails**: Content may need restructuring to front-load the answer, or description should better reflect available content. + ``` + +9. **Provide CTR Optimization Tips** + + ```markdown + ## CTR Optimization Analysis + + ### Power Words Used + - [Word 1] - Creates [emotion/action] + - [Word 2] - Creates [emotion/action] + + ### CTR Boosting Elements + + | Element | Present | Impact | + |---------|---------|--------| + | Numbers | Yes/No | +20-30% CTR | + | Current Year | Yes/No | +15-20% CTR | + | Power Words | Yes/No | +10-15% CTR | + | Question | Yes/No | +10-15% CTR | + | Brackets | Yes/No | +10% CTR | + + ### A/B Test Suggestions + + Test these variations: + + **Version A** (Current): + - Title: [Title] + - Description: [Description] + + **Version B** (Test): + - Title: [Alternative title] + - Description: [Alternative description] + - Hypothesis: [Why this might perform better] + ``` + +## Validation Checkpoints + +### Input Validation +- [ ] Primary keyword confirmed and matches page content +- [ ] Page type identified (blog/product/landing/service/homepage) +- [ ] Target audience and search intent clearly defined +- [ ] Unique value proposition articulated + +### Output Validation +- [ ] Title length 50-60 characters (displays fully in SERP) +- [ ] Meta description length 150-160 characters +- [ ] Primary keyword appears in both title and description +- [ ] Open Graph image specified (1200x630px recommended) +- [ ] All HTML syntax valid (no unclosed quotes or tags) +- [ ] Source of each data point clearly stated (~~search console CTR data, ~~SEO tool competitor data, user-provided, or estimated) + +## Example + +**User**: "Create meta tags for a blog post about 'how to start a podcast in [current year]'" + +**Output**: + +```markdown +## Meta Tags: How to Start a Podcast ([current year]) + +### Title Tag +```html +How to Start a Podcast in [current year]: Complete Beginner's Guide +``` +**Length**: ~55 characters ✅ +**Keyword**: "how to start a podcast" at front ✅ +**Power Words**: "Complete", "Beginner's" ✅ + +### Meta Description +```html + +``` +**Length**: ~163 characters ✅ +**Keyword**: Included naturally ✅ +**CTA**: "Start podcasting today!" ✅ + +_Complete meta tag block (with OG, Twitter, Article tags) generated using template from [references/meta-tag-code-templates.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/build/meta-tags-optimizer/references/meta-tag-code-templates.md)._ + +### A/B Test Variations + +**Title Variation B**: +"Start a Podcast in [current year]: Step-by-Step Guide (+ Free Checklist)" + +**Title Variation C**: +"How to Start a Podcast: [current year] Guide [Equipment + Software + Tips]" + +**Description Variation B**: +"Want to start a podcast in [current year]? This guide covers everything: equipment ($100 budget option), best hosting platforms, recording tips, and how to get your first 1,000 listeners." +``` + +## Tips for Success + +1. **Front-load keywords** - Put important terms at the beginning +2. **Match intent** - Description should preview what page delivers +3. **Be specific** - Vague descriptions get ignored +4. **Test variations** - Small changes can significantly impact CTR +5. **Update regularly** - Add current year, refresh messaging +6. **Check competitors** - See what's working in your SERP + + +### Save Results + +After delivering content or optimization output to the user, ask: + +> "Save these results for future sessions?" + +If yes, write a dated summary to `memory/content/YYYY-MM-DD-.md` containing: +- One-line description of what was created +- Target keyword and content type +- Open loops or items needing review +- Source data references + +**Gate check recommended**: Run content-quality-auditor before publishing (PostToolUse hook will remind automatically). + +If any findings should influence ongoing strategy, recommend promoting key conclusions to `memory/hot-cache.md`. + +## Reference Materials + +- [Meta Tag Formulas](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/build/meta-tags-optimizer/references/meta-tag-formulas.md) — Proven title and description formulas +- [CTR and Social Reference](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/build/meta-tags-optimizer/references/ctr-and-social-reference.md) — Page-type templates, CTR data, OG best practices + +## Next Best Skill + +- **Primary**: [schema-markup-generator](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/build/schema-markup-generator/SKILL.md) — complete the SERP packaging with structured data. diff --git a/.cursor/skills/on-page-seo-auditor/SKILL.md b/.cursor/skills/on-page-seo-auditor/SKILL.md new file mode 100644 index 0000000..170bee1 --- /dev/null +++ b/.cursor/skills/on-page-seo-auditor/SKILL.md @@ -0,0 +1,364 @@ +--- +name: on-page-seo-auditor +description: 'Audit on-page SEO: titles, headers, images, links with scored report and fix priorities. 页面SEO审计/排名诊断' +version: "6.0.0" +license: Apache-2.0 +compatibility: "Claude Code ≥1.0, skills.sh marketplace, ClawHub marketplace, Vercel Labs skills ecosystem. No system packages required. Optional: MCP network access for SEO tool integrations." +homepage: "https://github.com/aaron-he-zhu/seo-geo-claude-skills" +when_to_use: "Use when auditing a page's on-page SEO health, checking heading structure, keyword placement, image optimization, or content quality signals." +argument-hint: " [keyword]" +allowed-tools: WebFetch +metadata: + author: aaron-he-zhu + version: "6.0.0" + geo-relevance: "medium" + tags: + - seo + - on-page-audit + - page-optimization + - seo-score + - content-audit + - h1-optimization + - meta-audit + - seo-checklist + - yoast-alternative + - screaming-frog-alternative + - 页面SEO + - 网页优化 + - ページSEO + - 페이지감사 + - auditoria-seo + triggers: + # EN-formal + - "audit page SEO" + - "on-page SEO check" + - "SEO score" + - "page optimization" + - "on-page audit" + - "SEO page analysis" + - "content audit" + # EN-casual + - "what SEO issues does this page have" + - "check my page" + - "score my page" + - "why isn't this page ranking" + - "what's wrong with this page's SEO" + - "is my page optimized" + - "my rankings tanked" + - "why did my rankings drop" + # EN-question + - "why is my page not ranking" + - "how do I improve my page SEO" + - "what SEO problems does this page have" + # EN-competitor + - "Screaming Frog alternative" + - "Yoast SEO alternative" + # ZH-pro + - "页面SEO审计" + - "网页优化检查" + - "SEO评分" + - "页面诊断" + - "页面优化分析" + # ZH-casual + - "页面有什么问题" + - "为什么排不上去" + - "检查一下我的页面" + - "SEO打分" + - "排名上不去怎么办" + - "网页收录问题" + # JA + - "ページSEO監査" + - "オンページSEO" + - "ページ最適化" + - "SEOスコア" + # KO + - "페이지 SEO 감사" + - "온페이지 SEO" + - "SEO 점수" + - "이 페이지 뭐가 문제야?" + - "왜 순위가 안 올라가?" + - "SEO 점수 확인해줘" + # ES + - "auditoría SEO on-page" + - "análisis de página SEO" + - "puntuación SEO" + # PT + - "auditoria SEO on-page" + # Misspellings + - "on page SEO aduit" + - "SEO scroe" +--- + +# On-Page SEO Auditor + + +> **[SEO & GEO Skills Library](https://github.com/aaron-he-zhu/seo-geo-claude-skills)** · 20 skills for SEO + GEO · [ClawHub](https://clawhub.ai/u/aaron-he-zhu) · [skills.sh](https://skills.sh/aaron-he-zhu/seo-geo-claude-skills) +> **System Mode**: This optimization skill follows the shared [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md) and [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md). + + +This skill performs detailed on-page SEO audits to identify issues and optimization opportunities. It analyzes all on-page elements that affect search rankings and provides actionable recommendations. + +**System role**: Optimization layer skill. It turns weak pages, structures, and technical issues into prioritized repair work. + +## When This Must Trigger + +Use this when the conversation involves any of these situations — even if the user does not use SEO terminology: + +Use this whenever the task needs a diagnosis or repair plan that should feed directly into remediation work, not just a one-time opinion. + +- Auditing pages before or after publishing +- Identifying why a page isn't ranking well +- Optimizing existing content for better performance +- Creating pre-publish SEO checklists +- Comparing your on-page SEO to competitors +- Systematic site-wide SEO improvements +- Training team members on SEO best practices + +## What This Skill Does + +1. **Title Tag Analysis**: Evaluates title optimization and CTR potential +2. **Meta Description Review**: Checks description quality and length +3. **Header Structure Audit**: Analyzes H1-H6 hierarchy +4. **Content Quality Assessment**: Reviews content depth and optimization +5. **Keyword Usage Analysis**: Checks keyword placement and density +6. **Internal Link Review**: Evaluates internal linking structure +7. **Image Optimization Check**: Audits alt text and file optimization +8. **Technical On-Page Review**: Checks URL, canonical, and mobile factors + +## Quick Start + +Start with one of these prompts. Finish with a short handoff summary using the repository format in [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md). + +### Audit a Single Page + +``` +Audit the on-page SEO of [URL] +``` + +``` +Check SEO issues on this page targeting [keyword]: [URL/content] +``` + +### Compare Against Competitors + +``` +Compare on-page SEO of [your URL] vs [competitor URL] for [keyword] +``` + +### Audit Content Before Publishing + +``` +Pre-publish SEO audit for this content targeting [keyword]: [content] +``` + +## Skill Contract + +**Expected output**: a scored diagnosis, prioritized repair plan, and a short handoff summary ready for `memory/audits/`. + +- **Reads**: the current page or site state, symptoms, prior audits, and current priorities from [CLAUDE.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CLAUDE.md) and the shared [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md) when available. +- **Writes**: a user-facing audit or optimization plan plus a reusable summary that can be stored under `memory/audits/`. +- **Promotes**: blocking defects, repeated weaknesses, and fix priorities to `memory/open-loops.md` and `memory/decisions.md`. +- **Next handoff**: use the `Next Best Skill` below when the repair path is clear. + +## Data Sources + +> See [CONNECTORS.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CONNECTORS.md) for tool category placeholders. + +**With ~~SEO tool + ~~web crawler connected:** +Claude can automatically pull page HTML via ~~web crawler, fetch keyword search volume and difficulty from ~~SEO tool, retrieve click-through rate data from ~~search console, and download competitor pages for comparison. This enables fully automated audits with live data. + +**With manual data only:** +Ask the user to provide: +1. Page URL or complete HTML content +2. Target primary and secondary keywords +3. Competitor page URLs for comparison (optional) + +Proceed with the full audit using provided data. Note in the output which findings are from automated crawl vs. manual review. + +## Instructions + +When a user requests an on-page SEO audit: + +1. **Gather Page Information** + + ```markdown + ### Audit Setup + + **Page URL**: [URL] + **Target Keyword**: [primary keyword] + **Secondary Keywords**: [additional keywords] + **Page Type**: [blog/product/landing/service] + **Business Goal**: [traffic/conversions/authority] + ``` + +2. **Audit Title Tag** + + ```markdown + ## Title Tag Analysis + + **Current Title**: [title] + **Character Count**: [X] characters + + | Criterion | Status | Notes | + |-----------|--------|-------| + | Length (50-60 chars) | ✅/⚠️/❌ | [notes] | + | Keyword included | ✅/⚠️/❌ | Position: [front/middle/end] | + | Keyword at front | ✅/⚠️/❌ | [notes] | + | Unique across site | ✅/⚠️/❌ | [notes] | + | Compelling/clickable | ✅/⚠️/❌ | [notes] | + | Matches intent | ✅/⚠️/❌ | [notes] | + + **Title Score**: [X]/10 + + **Issues Found**: + - [Issue 1] + - [Issue 2] + + **Recommended Title**: + "[Optimized title suggestion]" + + **Why**: [Explanation of improvements] + ``` + +3. **Audit Meta Description** + + ```markdown + ## Meta Description Analysis + + **Current Description**: [description] + **Character Count**: [X] characters + + | Criterion | Status | Notes | + |-----------|--------|-------| + | Length (150-160 chars) | ✅/⚠️/❌ | [notes] | + | Keyword included | ✅/⚠️/❌ | [notes] | + | Call-to-action present | ✅/⚠️/❌ | [notes] | + | Unique across site | ✅/⚠️/❌ | [notes] | + | Accurately describes page | ✅/⚠️/❌ | [notes] | + | Compelling copy | ✅/⚠️/❌ | [notes] | + + **Description Score**: [X]/10 + + **Issues Found**: + - [Issue 1] + + **Recommended Description**: + "[Optimized description suggestion]" ([X] chars) + ``` + +4. **Audit Header Structure** + + ```markdown + ## Header Structure Analysis + + ### Current Header Hierarchy + + ``` + H1: [H1 text] + H2: [H2 text] + H3: [H3 text] + H3: [H3 text] + H2: [H2 text] + H3: [H3 text] + H2: [H2 text] + ``` + + | Criterion | Status | Notes | + |-----------|--------|-------| + | Single H1 | ✅/⚠️/❌ | Found: [X] H1s | + | H1 includes keyword | ✅/⚠️/❌ | [notes] | + | Logical hierarchy | ✅/⚠️/❌ | [notes] | + | H2s include keywords | ✅/⚠️/❌ | [X]/[Y] contain keywords | + | No skipped levels | ✅/⚠️/❌ | [notes] | + | Descriptive headers | ✅/⚠️/❌ | [notes] | + + **Header Score**: [X]/10 + + **Issues Found**: + - [Issue 1] + - [Issue 2] + + **Recommended Changes**: + - H1: [suggestion] + - H2s: [suggestions] + ``` + +5. **Audit Content Quality** — Word count, reading level, comprehensiveness, formatting, E-E-A-T signals, content elements checklist, gap identification + + > **Reference**: See [references/audit-templates.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/on-page-seo-auditor/references/audit-templates.md) for the content quality template (Step 5). + +6. **Audit Keyword Usage** — Primary/secondary keyword placement across all page elements, LSI/related terms, density analysis + + > **Reference**: See [references/audit-templates.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/on-page-seo-auditor/references/audit-templates.md) for the keyword optimization template (Step 6). + +7. **Audit Internal Links** — Link count, anchor text relevance, broken links, recommended additions + + > **Reference**: See [references/audit-templates.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/on-page-seo-auditor/references/audit-templates.md) for the internal linking template (Step 7). + +8. **Audit Images** — Alt text, file names, sizes, formats, lazy loading + + > **Reference**: See [references/audit-templates.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/on-page-seo-auditor/references/audit-templates.md) for the image optimization template (Step 8). + +9. **Audit Technical On-Page Elements** — URL, canonical, mobile, speed, HTTPS, schema + + > **Reference**: See [references/audit-templates.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/on-page-seo-auditor/references/audit-templates.md) for the technical on-page template (Step 9). + +10. **CORE-EEAT Content Quality Quick Scan** — 17 on-page-relevant items from the 80-item CORE-EEAT benchmark + + > **Reference**: See [references/audit-templates.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/on-page-seo-auditor/references/audit-templates.md) for the CORE-EEAT quick scan template (Step 10). Full benchmark: [CORE-EEAT Benchmark](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/core-eeat-benchmark.md). + +11. **Generate Audit Summary** — Overall score with visual breakdown, priority issues (critical/important/minor), quick wins, detailed recommendations, competitor comparison, action checklist, expected results + + > **Reference**: See [references/audit-templates.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/on-page-seo-auditor/references/audit-templates.md) for the full audit summary template (Step 11). + +## Validation Checkpoints + +### Input Validation +- [ ] Target keyword(s) clearly specified by user +- [ ] Page content accessible (either via URL or provided HTML) +- [ ] If competitor comparison requested, competitor URL provided + +### Output Validation +- [ ] Every recommendation cites specific data points (not generic advice) +- [ ] Scores based on measurable criteria, not subjective opinion +- [ ] All suggested changes include specific locations (title tag, H2 #3, paragraph 5, etc.) +- [ ] Source of each data point clearly stated (~~SEO tool data, user-provided, ~~web crawler, or manual review) + +## Example + +> **Reference**: See [references/audit-example.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/on-page-seo-auditor/references/audit-example.md) for a full worked example (noise-cancelling headphones audit) and page-type checklists (blog post, product page, landing page). + +## Tips for Success + +1. **Prioritize issues by impact** - Fix critical issues first +2. **Compare to competitors** - See what's working for top rankings +3. **Balance optimization and readability** - Don't over-optimize +4. **Audit regularly** - Content degrades over time +5. **Test changes** - Track ranking changes after updates + +> **Scoring details**: For the complete weight distribution, scoring scale, issue resolution playbook, and industry benchmarks, see [references/scoring-rubric.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/on-page-seo-auditor/references/scoring-rubric.md). + + +### Save Results + +After delivering audit or optimization findings to the user, ask: + +> "Save these results for future sessions?" + +If yes, write a dated summary to `memory/audits/on-page-seo-auditor/YYYY-MM-DD-.md` containing: +- One-line verdict or headline finding +- Top 3-5 actionable items +- Open loops or blockers +- Source data references + +If any veto-level issue was found (CORE-EEAT T04, C01, R10 or CITE T03, T05, T09), also append a one-liner to `memory/hot-cache.md` without asking. + +## Reference Materials + +- [Scoring Rubric](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/on-page-seo-auditor/references/scoring-rubric.md) — Detailed scoring criteria, weight distribution, and grade boundaries for on-page audits +- [Audit Templates](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/on-page-seo-auditor/references/audit-templates.md) — Detailed output templates for steps 5-11 (content quality, keywords, links, images, technical, CORE-EEAT scan, audit summary) +- [Audit Example & Checklists](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/on-page-seo-auditor/references/audit-example.md) — Full worked example and page-type checklists (blog, product, landing page) + +## Next Best Skill + +- **Primary**: [content-refresher](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/optimize/content-refresher/SKILL.md) — turn page-level findings into concrete edits. diff --git a/.cursor/skills/performance-reporter/SKILL.md b/.cursor/skills/performance-reporter/SKILL.md new file mode 100644 index 0000000..27ae07d --- /dev/null +++ b/.cursor/skills/performance-reporter/SKILL.md @@ -0,0 +1,263 @@ +--- +name: performance-reporter +description: 'Generate SEO/GEO dashboards: rankings, traffic, backlinks, AI visibility for stakeholders. SEO报告/绩效仪表盘' +version: "6.0.0" +license: Apache-2.0 +compatibility: "Claude Code ≥1.0, skills.sh marketplace, ClawHub marketplace, Vercel Labs skills ecosystem. No system packages required. Optional: MCP network access for SEO tool integrations." +homepage: "https://github.com/aaron-he-zhu/seo-geo-claude-skills" +when_to_use: "Use when generating SEO performance reports, traffic summaries, ranking reports, or stakeholder-facing dashboards." +argument-hint: " [date range]" +metadata: + author: aaron-he-zhu + version: "6.0.0" + geo-relevance: "medium" + tags: + - seo + - geo + - seo-reporting + - performance-report + - kpi-dashboard + - traffic-report + - monthly-report + - stakeholder-report + - SEO报告 + - SEOレポート + - SEO리포트 + - informe-seo + triggers: + # EN-formal + - "generate SEO report" + - "performance report" + - "traffic report" + - "SEO dashboard" + - "SEO analytics" + - "monthly report" + # EN-casual + - "report to stakeholders" + - "monthly SEO report" + - "show me my SEO results" + - "present SEO results to my boss" + - "report to my boss" + - "monthly SEO summary" + # EN-question + - "how are my SEO metrics" + - "how is my SEO performing" + # ZH-pro + - "SEO报告" + - "绩效仪表盘" + - "流量报告" + - "数据看板" + # ZH-casual + - "出SEO报告" + - "汇报给老板" + - "看看数据" + - "月报" + - "出月报" + - "周报" + # JA + - "SEOレポート" + - "パフォーマンスレポート" + # KO + - "SEO 리포트" + - "성과 보고서" + # ES + - "informe SEO" + - "reporte de rendimiento" + # PT + - "relatório SEO" + # Misspellings + - "SEO repoort" +--- + +# Performance Reporter + + +> **[SEO & GEO Skills Library](https://github.com/aaron-he-zhu/seo-geo-claude-skills)** · 20 skills for SEO + GEO · [ClawHub](https://clawhub.ai/u/aaron-he-zhu) · [skills.sh](https://skills.sh/aaron-he-zhu/seo-geo-claude-skills) +> **System Mode**: This monitoring skill follows the shared [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md) and [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md). + + +This skill creates comprehensive SEO and GEO performance reports that combine multiple metrics into actionable insights. It produces executive summaries, detailed analyses, and visual data presentations for stakeholder communication. + +**System role**: Monitoring layer skill. It turns performance changes into deltas, alerts, and next actions. + +## When This Must Trigger + +Use this when the conversation involves any of these situations — even if the user does not use SEO terminology: + +Use this whenever the task needs time-aware change detection, escalation, or stakeholder-ready visibility. + +- Monthly/quarterly SEO reporting +- Executive stakeholder updates +- Client reporting for agencies +- Tracking campaign performance +- Combining multiple SEO metrics +- Creating GEO visibility reports +- Documenting ROI from SEO efforts + +## What This Skill Does + +1. **Data Aggregation**: Combines multiple SEO data sources +2. **Trend Analysis**: Identifies patterns across metrics +3. **Executive Summaries**: Creates high-level overviews +4. **Visual Reports**: Presents data in clear formats +5. **Benchmark Comparison**: Tracks against goals and competitors +6. **Content Quality Tracking**: Integrates CORE-EEAT scores across audited pages +7. **ROI Calculation**: Measures SEO investment returns +8. **Recommendations**: Suggests actions based on data + +## Quick Start + +Start with one of these prompts. Finish with a short handoff summary using the repository format in [Skill Contract](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/skill-contract.md). + +### Generate Performance Report + +``` +Create an SEO performance report for [domain] for [time period] +``` + +### Executive Summary + +``` +Generate an executive summary of SEO performance for [month/quarter] +``` + +### Specific Report Types + +``` +Create a GEO visibility report for [domain] +``` + +``` +Generate a content performance report +``` + +## Skill Contract + +**Expected output**: a delta summary, alert/report output, and a short handoff summary ready for `memory/monitoring/`. + +- **Reads**: current metrics, previous baselines, alert thresholds, and reporting context from [CLAUDE.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CLAUDE.md) and the shared [State Model](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/references/state-model.md) when available. +- **Writes**: a user-facing monitoring deliverable plus a reusable summary that can be stored under `memory/monitoring/`. +- **Promotes**: significant changes, confirmed anomalies, and follow-up actions to `memory/open-loops.md` and `memory/decisions.md`. +- **Next handoff**: use the `Next Best Skill` below when a change needs action. + +## Data Sources + +> **Note:** All integrations are optional. This skill works without any API keys — users provide data manually when no tools are connected. + +> See [CONNECTORS.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/CONNECTORS.md) for tool category placeholders. + +**With ~~analytics + ~~search console + ~~SEO tool + ~~AI monitor connected:** +Automatically aggregate traffic metrics from ~~analytics, search performance data from ~~search console, ranking and backlink data from ~~SEO tool, and GEO visibility metrics from ~~AI monitor. Creates comprehensive multi-source reports with historical trends. + +**With manual data only:** +Ask the user to provide: +1. Analytics screenshots or traffic data export (sessions, users, conversions) +2. Search Console data (impressions, clicks, average position) +3. Keyword ranking data for the reporting period +4. Backlink metrics (referring domains, new/lost links) +5. Key performance indicators and goals for comparison +6. AI citation data if tracking GEO metrics + +Proceed with the full analysis using provided data. Note in the output which metrics are from automated collection vs. user-provided data. + +## Instructions + +When a user requests a performance report: + +1. **Define Report Parameters** -- Domain, report period, comparison period, report type (Monthly/Quarterly/Annual), audience (Executive/Technical/Client), focus areas. + +2. **Create Executive Summary** -- Overall performance rating, key wins/watch areas/action required, metrics at a glance table (traffic, rankings, conversions, DA, AI citations), SEO ROI calculation. + +3. **Report Organic Traffic Performance** -- Traffic overview (sessions, users, pageviews, bounce rate), traffic trend visualization, traffic by source/device, top performing pages. + +4. **Report Keyword Rankings** -- Rankings overview by position range, distribution change visualization, top improvements and declines, SERP feature performance. + +5. **Report GEO/AI Performance** -- AI citation overview, citations by topic, GEO wins, optimization opportunities. + +6. **Report Domain Authority (CITE Score)** -- If a CITE audit has been run, include CITE dimension scores (C/I/T/E) with period-over-period trends and veto status. If no audit exists, note as "Not yet evaluated." + +7. **Content Quality (CORE-EEAT Score)** -- If content-quality-auditor has been run, include average scores across all 8 CORE-EEAT dimensions with trends. If no audit exists, note as "Not yet evaluated." + +8. **Report Backlink Performance** -- Link profile summary, weekly link acquisition, notable new links, competitive position. + +9. **Report Content Performance** -- Publishing summary, top performing content, content needing attention, content ROI. + +10. **Generate Recommendations** -- Immediate/short-term/long-term actions with priority, expected impact, and owner. Goals for next period. + +11. **Compile Full Report** -- Combine all sections with table of contents, appendix (data sources, methodology, glossary). + + > **Reference**: See [references/report-output-templates.md](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/monitor/performance-reporter/references/report-output-templates.md) for complete output templates for all 11 report sections. + +## Validation Checkpoints + +### Input Validation +- [ ] Reporting period clearly defined with comparison period +- [ ] All required data sources available or alternatives noted +- [ ] Target audience identified (executive/technical/client) +- [ ] Performance goals and KPIs established for benchmarking + +### Output Validation +- [ ] Every metric cites its data source and collection date +- [ ] Trends include period-over-period comparisons +- [ ] Recommendations are specific, prioritized, and actionable +- [ ] Source of each data point clearly stated (~~analytics data, ~~search console data, ~~SEO tool data, user-provided, or estimated) + +## Example + +**User**: "Create a monthly SEO report for cloudhosting.com for January 2025" + +**Output** (abbreviated -- full report uses templates from all 11 steps): + +```markdown +# CloudHosting SEO & GEO Performance Report — January 2025 + +## Executive Summary — Overall Performance: Good + +| Metric | Jan 2025 | Dec 2024 | Change | Target | Status | +|--------|----------|----------|--------|--------|--------| +| Organic Traffic | 52,100 | 45,200 | +15.3% | 50,000 | On track | +| Keywords Top 10 | 87 | 79 | +8 | 90 | Watch | +| Organic Conversions | 684 | 612 | +11.8% | 700 | Watch | +| Domain Rating | 54 | 53 | +1 | 55 | Watch | +| AI Citations | 18 | 12 | +50.0% | 20 | Watch | + +**SEO ROI**: $8,200 invested / $41,040 organic revenue = 400% + +**Immediate**: Fix 37 crawl errors on /pricing/ pages +**This Month**: Optimize mobile LCP; publish 3 AI Overview comparison pages +**This Quarter**: Build Wikidata entry for CloudHost Inc. +``` + +## Tips for Success + +1. **Lead with insights** - Start with what matters, not raw data +2. **Visualize data** - Charts and graphs improve comprehension +3. **Compare periods** - Context makes data meaningful +4. **Include actions** - Every report should drive decisions +5. **Customize for audience** - Executives need different info than technical teams +6. **Track GEO metrics** - AI visibility is increasingly important + + +### Save Results + +After delivering monitoring data or reports to the user, ask: + +> "Save these results for future sessions?" + +If yes, write a dated summary to `memory/monitoring/YYYY-MM-DD-.md` containing: +- One-line headline finding or status change +- Top 3-5 actionable items +- Open loops or anomalies requiring follow-up +- Source data references + +If any findings should influence ongoing strategy, recommend promoting key conclusions to `memory/hot-cache.md`. + +## Reference Materials + +- [Report Output Templates](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/monitor/performance-reporter/references/report-output-templates.md) — Complete output templates for all 11 report sections +- [KPI Definitions](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/monitor/performance-reporter/references/kpi-definitions.md) — SEO/GEO metric definitions with benchmarks, good ranges, warning thresholds, trend analysis, and attribution guidance +- [Report Templates by Audience](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/monitor/performance-reporter/references/report-templates.md) — Copy-ready templates for executive, marketing, technical, and client audiences + +## Next Best Skill + +- **Primary**: [alert-manager](https://github.com/aaron-he-zhu/seo-geo-claude-skills/blob/main/monitor/alert-manager/SKILL.md) — turn reporting insights into ongoing monitoring rules. diff --git a/.cursor/skills/playwright-testing/SKILL.md b/.cursor/skills/playwright-testing/SKILL.md new file mode 100644 index 0000000..6512f12 --- /dev/null +++ b/.cursor/skills/playwright-testing/SKILL.md @@ -0,0 +1,295 @@ +--- +name: playwright-testing +description: Use when writing Playwright tests, fixing flaky tests, debugging failures, implementing Page Object Model, configuring CI/CD, optimizing performance, mocking APIs, handling authentication or OAuth, testing accessibility (axe-core), file uploads/downloads, date/time mocking, WebSockets, geolocation, permissions, multi-tab/popup flows, mobile/responsive layouts, touch gestures, GraphQL, error handling, offline mode, multi-user collaboration, third-party services (payments, email verification), console error monitoring, global setup/teardown, test annotations (skip, fixme, slow), test tags (@smoke, @fast, @critical, filtering with --grep), project dependencies, security testing (XSS, CSRF, auth), performance budgets (Web Vitals, Lighthouse), iframes, component testing, canvas/WebGL, service workers/PWA, test coverage, i18n/localization, Electron apps, or browser extension testing. Covers E2E, component, API, visual, accessibility, security, Electron, and extension testing. +--- + +# Playwright Testing + +This skill provides comprehensive guidance for all aspects of Playwright test development, from writing new tests to debugging and maintaining existing test suites. + +## Activity-Based Reference Guide + +Consult these references based on what you're doing: + +### Writing New Tests + +**When to use**: Creating new test files, writing test cases, implementing test scenarios + +| Activity | Reference Files | +| ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | +| **Writing E2E tests** | [test-suite-structure.md](core/test-suite-structure.md), [locators.md](core/locators.md), [assertions-waiting.md](core/assertions-waiting.md) | +| **Writing component tests** | [component-testing.md](testing-patterns/component-testing.md), [test-suite-structure.md](core/test-suite-structure.md) | +| **Writing API tests** | [api-testing.md](testing-patterns/api-testing.md), [test-suite-structure.md](core/test-suite-structure.md) | +| **Writing GraphQL tests** | [graphql-testing.md](testing-patterns/graphql-testing.md), [api-testing.md](testing-patterns/api-testing.md) | +| **Writing visual regression tests** | [visual-regression.md](testing-patterns/visual-regression.md), [canvas-webgl.md](testing-patterns/canvas-webgl.md) | +| **Structuring test code with POM** | [page-object-model.md](core/page-object-model.md), [test-suite-structure.md](core/test-suite-structure.md) | +| **Setting up test data/fixtures** | [fixtures-hooks.md](core/fixtures-hooks.md), [test-data.md](core/test-data.md) | +| **Handling authentication** | [authentication.md](advanced/authentication.md), [authentication-flows.md](advanced/authentication-flows.md) | +| **Testing date/time features** | [clock-mocking.md](advanced/clock-mocking.md) | +| **Testing file upload/download** | [file-operations.md](testing-patterns/file-operations.md), [file-upload-download.md](testing-patterns/file-upload-download.md) | +| **Testing forms/validation** | [forms-validation.md](testing-patterns/forms-validation.md) | +| **Testing drag and drop** | [drag-drop.md](testing-patterns/drag-drop.md) | +| **Testing accessibility** | [accessibility.md](testing-patterns/accessibility.md) | +| **Testing security (XSS, CSRF)** | [security-testing.md](testing-patterns/security-testing.md) | +| **Using test annotations** | [annotations.md](core/annotations.md) | +| **Using test tags** | [test-tags.md](core/test-tags.md) | +| **Testing iframes** | [iframes.md](browser-apis/iframes.md) | +| **Testing canvas/WebGL** | [canvas-webgl.md](testing-patterns/canvas-webgl.md) | +| **Internationalization (i18n)** | [i18n.md](testing-patterns/i18n.md) | +| **Testing Electron apps** | [electron.md](testing-patterns/electron.md) | +| **Testing browser extensions** | [browser-extensions.md](testing-patterns/browser-extensions.md) | + +### Mobile & Responsive Testing + +**When to use**: Testing mobile devices, touch interactions, responsive layouts + +| Activity | Reference Files | +| ------------------------------- | -------------------------------------------------------------------------------- | +| **Device emulation** | [mobile-testing.md](advanced/mobile-testing.md) | +| **Touch gestures (swipe, tap)** | [mobile-testing.md](advanced/mobile-testing.md) | +| **Viewport/breakpoint testing** | [mobile-testing.md](advanced/mobile-testing.md) | +| **Mobile-specific UI** | [mobile-testing.md](advanced/mobile-testing.md), [locators.md](core/locators.md) | + +### Real-Time & Browser APIs + +**When to use**: Testing WebSockets, geolocation, permissions, multi-tab flows + +| Activity | Reference Files | +| ------------------------------- | ---------------------------------------------------------------------------------------- | +| **WebSocket/real-time testing** | [websockets.md](browser-apis/websockets.md) | +| **Geolocation mocking** | [browser-apis.md](browser-apis/browser-apis.md) | +| **Permission handling** | [browser-apis.md](browser-apis/browser-apis.md) | +| **Clipboard testing** | [browser-apis.md](browser-apis/browser-apis.md) | +| **Camera/microphone mocking** | [browser-apis.md](browser-apis/browser-apis.md) | +| **Multi-tab/popup flows** | [multi-context.md](advanced/multi-context.md) | +| **OAuth popup handling** | [third-party.md](advanced/third-party.md), [multi-context.md](advanced/multi-context.md) | + +### Debugging & Troubleshooting + +**When to use**: Test failures, element not found, timeouts, unexpected behavior + +| Activity | Reference Files | +| ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| **Debugging test failures** | [debugging.md](debugging/debugging.md), [assertions-waiting.md](core/assertions-waiting.md) | +| **Fixing flaky tests** | [flaky-tests.md](debugging/flaky-tests.md), [debugging.md](debugging/debugging.md), [assertions-waiting.md](core/assertions-waiting.md) | +| **Debugging flaky parallel runs** | [flaky-tests.md](debugging/flaky-tests.md), [performance.md](infrastructure-ci-cd/performance.md), [fixtures-hooks.md](core/fixtures-hooks.md) | +| **Ensuring test isolation / avoiding state leak** | [flaky-tests.md](debugging/flaky-tests.md), [fixtures-hooks.md](core/fixtures-hooks.md), [performance.md](infrastructure-ci-cd/performance.md) | +| **Fixing selector issues** | [locators.md](core/locators.md), [debugging.md](debugging/debugging.md) | +| **Investigating timeout issues** | [assertions-waiting.md](core/assertions-waiting.md), [debugging.md](debugging/debugging.md) | +| **Using trace viewer** | [debugging.md](debugging/debugging.md) | +| **Debugging race conditions** | [flaky-tests.md](debugging/flaky-tests.md), [debugging.md](debugging/debugging.md), [assertions-waiting.md](core/assertions-waiting.md) | +| **Debugging console/JS errors** | [console-errors.md](debugging/console-errors.md), [debugging.md](debugging/debugging.md) | + +### Error & Edge Case Testing + +**When to use**: Testing error states, offline mode, network failures, validation + +| Activity | Reference Files | +| ------------------------------ | ----------------------------------------------------------------------------------------------------- | +| **Error boundary testing** | [error-testing.md](debugging/error-testing.md) | +| **Network failure simulation** | [error-testing.md](debugging/error-testing.md), [network-advanced.md](advanced/network-advanced.md) | +| **Offline mode testing** | [error-testing.md](debugging/error-testing.md), [service-workers.md](browser-apis/service-workers.md) | +| **Service worker testing** | [service-workers.md](browser-apis/service-workers.md) | +| **Loading state testing** | [error-testing.md](debugging/error-testing.md) | +| **Form validation testing** | [error-testing.md](debugging/error-testing.md) | + +### Multi-User & Collaboration Testing + +**When to use**: Testing features involving multiple users, roles, or real-time collaboration + +| Activity | Reference Files | +| ------------------------------ | ------------------------------------------------------------------------------------ | +| **Multiple users in one test** | [multi-user.md](advanced/multi-user.md) | +| **Real-time collaboration** | [multi-user.md](advanced/multi-user.md), [websockets.md](browser-apis/websockets.md) | +| **Role-based access testing** | [multi-user.md](advanced/multi-user.md) | +| **Concurrent action testing** | [multi-user.md](advanced/multi-user.md) | + +### Architecture Decisions + +**When to use**: Choosing test patterns, deciding between approaches, planning test architecture + +| Activity | Reference Files | +| ---------------------------- | --------------------------------------------------------- | +| **POM vs fixtures decision** | [pom-vs-fixtures.md](architecture/pom-vs-fixtures.md) | +| **Test type selection** | [test-architecture.md](architecture/test-architecture.md) | +| **Mock vs real services** | [when-to-mock.md](architecture/when-to-mock.md) | +| **Test suite structure** | [test-suite-structure.md](core/test-suite-structure.md) | + +### Framework-Specific Testing + +**When to use**: Testing React or Next.js applications + +| Activity | Reference Files | +| ------------------------- | ----------------------------------- | +| **Testing React apps** | [react.md](frameworks/react.md) | +| **Testing Next.js apps** | [nextjs.md](frameworks/nextjs.md) | + +### Refactoring & Maintenance + +**When to use**: Improving existing tests, code review, reducing duplication + +| Activity | Reference Files | +| ------------------------------------ | ---------------------------------------------------------------------------------------------------------- | +| **Refactoring to Page Object Model** | [page-object-model.md](core/page-object-model.md), [test-suite-structure.md](core/test-suite-structure.md) | +| **Improving test organization** | [test-suite-structure.md](core/test-suite-structure.md), [page-object-model.md](core/page-object-model.md) | +| **Extracting common setup/teardown** | [fixtures-hooks.md](core/fixtures-hooks.md) | +| **Replacing brittle selectors** | [locators.md](core/locators.md) | +| **Removing explicit waits** | [assertions-waiting.md](core/assertions-waiting.md) | +| **Creating test data factories** | [test-data.md](core/test-data.md) | +| **Configuration setup** | [configuration.md](core/configuration.md) | + +### Infrastructure & Configuration + +**When to use**: Setting up projects, configuring CI/CD, optimizing performance + +| Activity | Reference Files | +| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | +| **Configuring Playwright project** | [configuration.md](core/configuration.md), [projects-dependencies.md](core/projects-dependencies.md) | +| **Setting up CI/CD pipelines** | [ci-cd.md](infrastructure-ci-cd/ci-cd.md), [github-actions.md](infrastructure-ci-cd/github-actions.md) | +| **GitHub Actions setup** | [github-actions.md](infrastructure-ci-cd/github-actions.md) | +| **GitLab CI setup** | [gitlab.md](infrastructure-ci-cd/gitlab.md) | +| **Other CI providers** | [other-providers.md](infrastructure-ci-cd/other-providers.md) | +| **Docker/container setup** | [docker.md](infrastructure-ci-cd/docker.md) | +| **Global setup & teardown** | [global-setup.md](core/global-setup.md) | +| **Project dependencies** | [projects-dependencies.md](core/projects-dependencies.md) | +| **Optimizing test performance** | [performance.md](infrastructure-ci-cd/performance.md), [test-suite-structure.md](core/test-suite-structure.md) | +| **Configuring parallel execution** | [parallel-sharding.md](infrastructure-ci-cd/parallel-sharding.md), [performance.md](infrastructure-ci-cd/performance.md) | +| **Isolating test data between workers** | [fixtures-hooks.md](core/fixtures-hooks.md), [performance.md](infrastructure-ci-cd/performance.md) | +| **Test coverage** | [test-coverage.md](infrastructure-ci-cd/test-coverage.md) | +| **Test reporting/artifacts** | [reporting.md](infrastructure-ci-cd/reporting.md) | + +### Advanced Patterns + +**When to use**: Complex scenarios, API mocking, network interception + +| Activity | Reference Files | +| ------------------------------------ | ------------------------------------------------------------------------------------------------------------ | +| **Mocking API responses** | [test-suite-structure.md](core/test-suite-structure.md), [network-advanced.md](advanced/network-advanced.md) | +| **Network interception** | [network-advanced.md](advanced/network-advanced.md), [assertions-waiting.md](core/assertions-waiting.md) | +| **GraphQL mocking** | [network-advanced.md](advanced/network-advanced.md) | +| **HAR recording/playback** | [network-advanced.md](advanced/network-advanced.md) | +| **Custom fixtures** | [fixtures-hooks.md](core/fixtures-hooks.md) | +| **Advanced waiting strategies** | [assertions-waiting.md](core/assertions-waiting.md) | +| **OAuth/SSO mocking** | [third-party.md](advanced/third-party.md), [multi-context.md](advanced/multi-context.md) | +| **Payment gateway mocking** | [third-party.md](advanced/third-party.md) | +| **Email/SMS verification mocking** | [third-party.md](advanced/third-party.md) | +| **Failing on console errors** | [console-errors.md](debugging/console-errors.md) | +| **Security testing (XSS, CSRF)** | [security-testing.md](testing-patterns/security-testing.md) | +| **Performance budgets & Web Vitals** | [performance-testing.md](testing-patterns/performance-testing.md) | +| **Lighthouse integration** | [performance-testing.md](testing-patterns/performance-testing.md) | +| **Test annotations (skip, fixme)** | [annotations.md](core/annotations.md) | +| **Test tags (@smoke, @fast)** | [test-tags.md](core/test-tags.md) | +| **Test steps for reporting** | [annotations.md](core/annotations.md) | + +## Quick Decision Tree + +``` +What are you doing? +│ +├─ Writing a new test? +│ ├─ E2E test → core/test-suite-structure.md, core/locators.md, core/assertions-waiting.md +│ ├─ Component test → testing-patterns/component-testing.md +│ ├─ API test → testing-patterns/api-testing.md, core/test-suite-structure.md +│ ├─ GraphQL test → testing-patterns/graphql-testing.md +│ ├─ Visual regression → testing-patterns/visual-regression.md +│ ├─ Visual/canvas test → testing-patterns/canvas-webgl.md, core/test-suite-structure.md +│ ├─ Accessibility test → testing-patterns/accessibility.md +│ ├─ Mobile/responsive test → advanced/mobile-testing.md +│ ├─ i18n/locale test → testing-patterns/i18n.md +│ ├─ Electron app test → testing-patterns/electron.md +│ ├─ Browser extension test → testing-patterns/browser-extensions.md +│ ├─ Multi-user test → advanced/multi-user.md +│ ├─ Form validation test → testing-patterns/forms-validation.md +│ └─ Drag and drop test → testing-patterns/drag-drop.md +│ +├─ Testing specific features? +│ ├─ File upload/download → testing-patterns/file-operations.md, testing-patterns/file-upload-download.md +│ ├─ Date/time dependent → advanced/clock-mocking.md +│ ├─ WebSocket/real-time → browser-apis/websockets.md +│ ├─ Geolocation/permissions → browser-apis/browser-apis.md +│ ├─ OAuth/SSO mocking → advanced/third-party.md, advanced/multi-context.md +│ ├─ Payments/email/SMS → advanced/third-party.md +│ ├─ iFrames → browser-apis/iframes.md +│ ├─ Canvas/WebGL/charts → testing-patterns/canvas-webgl.md +│ ├─ Service workers/PWA → browser-apis/service-workers.md +│ ├─ i18n/localization → testing-patterns/i18n.md +│ ├─ Security (XSS, CSRF) → testing-patterns/security-testing.md +│ └─ Performance/Web Vitals → testing-patterns/performance-testing.md +│ +├─ Architecture decisions? +│ ├─ POM vs fixtures → architecture/pom-vs-fixtures.md +│ ├─ Test type selection → architecture/test-architecture.md +│ ├─ Mock vs real services → architecture/when-to-mock.md +│ └─ Test suite structure → core/test-suite-structure.md +│ +├─ Framework-specific testing? +│ ├─ React app → frameworks/react.md +│ └─ Next.js app → frameworks/nextjs.md +│ +├─ Authentication testing? +│ ├─ Basic auth patterns → advanced/authentication.md +│ └─ Complex flows (MFA, reset) → advanced/authentication-flows.md +│ +├─ Test is failing/flaky? +│ ├─ Flaky test investigation → debugging/flaky-tests.md +│ ├─ Element not found → core/locators.md, debugging/debugging.md +│ ├─ Timeout issues → core/assertions-waiting.md, debugging/debugging.md +│ ├─ Race conditions → debugging/flaky-tests.md, debugging/debugging.md +│ ├─ Flaky only with multiple workers → debugging/flaky-tests.md, infrastructure-ci-cd/performance.md +│ ├─ State leak / isolation → debugging/flaky-tests.md, core/fixtures-hooks.md +│ ├─ Console/JS errors → debugging/console-errors.md, debugging/debugging.md +│ └─ General debugging → debugging/debugging.md +│ +├─ Testing error scenarios? +│ ├─ Network failures → debugging/error-testing.md, advanced/network-advanced.md +│ ├─ Offline (unexpected) → debugging/error-testing.md +│ ├─ Offline-first/PWA → browser-apis/service-workers.md +│ ├─ Error boundaries → debugging/error-testing.md +│ └─ Form validation → testing-patterns/forms-validation.md, debugging/error-testing.md +│ +├─ Refactoring existing code? +│ ├─ Implementing POM → core/page-object-model.md +│ ├─ Improving selectors → core/locators.md +│ ├─ Extracting fixtures → core/fixtures-hooks.md +│ ├─ Creating data factories → core/test-data.md +│ └─ Configuration setup → core/configuration.md +│ +├─ Setting up infrastructure? +│ ├─ CI/CD → infrastructure-ci-cd/ci-cd.md +│ ├─ GitHub Actions → infrastructure-ci-cd/github-actions.md +│ ├─ GitLab CI → infrastructure-ci-cd/gitlab.md +│ ├─ Other CI providers → infrastructure-ci-cd/other-providers.md +│ ├─ Docker/containers → infrastructure-ci-cd/docker.md +│ ├─ Sharding/parallel → infrastructure-ci-cd/parallel-sharding.md +│ ├─ Reporting/artifacts → infrastructure-ci-cd/reporting.md +│ ├─ Global setup/teardown → core/global-setup.md +│ ├─ Project dependencies → core/projects-dependencies.md +│ ├─ Test performance → infrastructure-ci-cd/performance.md +│ ├─ Test coverage → infrastructure-ci-cd/test-coverage.md +│ └─ Project config → core/configuration.md, core/projects-dependencies.md +│ +├─ Organizing tests? +│ ├─ Skip/fixme/slow tests → core/annotations.md +│ ├─ Test tags (@smoke, @fast) → core/test-tags.md +│ ├─ Filtering tests (--grep) → core/test-tags.md +│ ├─ Test steps → core/annotations.md +│ └─ Conditional execution → core/annotations.md +│ +└─ Running subset of tests? + ├─ By tag (@smoke, @critical) → core/test-tags.md + ├─ Exclude slow/flaky tests → core/test-tags.md + ├─ PR vs nightly tests → core/test-tags.md, infrastructure-ci-cd/ci-cd.md + └─ Project-specific filtering → core/test-tags.md, core/configuration.md +``` + +## Test Validation Loop + +After writing or modifying tests: + +1. **Run tests**: `npx playwright test --reporter=list` +2. **If tests fail**: + - Review error output and trace (`npx playwright show-trace`) + - Fix locators, waits, or assertions + - Re-run tests +3. **Only proceed when all tests pass** +4. **Run multiple times** for critical tests: `npx playwright test --repeat-each=5` diff --git a/.cursor/skills/playwright-testing/advanced/authentication-flows.md b/.cursor/skills/playwright-testing/advanced/authentication-flows.md new file mode 100644 index 0000000..24ad08c --- /dev/null +++ b/.cursor/skills/playwright-testing/advanced/authentication-flows.md @@ -0,0 +1,360 @@ +# Complex Authentication Flow Patterns + +## Table of Contents + +1. [Email Verification Flows](#email-verification-flows) +2. [Password Reset](#password-reset) +3. [Session Timeout](#session-timeout) +4. [Remember Me Persistence](#remember-me-persistence) +5. [Logout Patterns](#logout-patterns) +6. [Tips](#tips) +7. [Related](#related) + +> **When to use**: Testing email verification, password reset, session timeout/expiration, or remember-me functionality. For basic auth setup (storage state, OAuth mocking, MFA, role-based access), see [authentication.md](authentication.md). + +--- + +## Email Verification Flows + +### Capturing Verification Tokens + +Intercept API responses to capture verification tokens for testing: + +```typescript +test('completes registration with email verification', async ({ page }) => { + let capturedToken = ''; + + await page.route('**/api/auth/register', async (route) => { + const response = await route.fetch(); + const body = await response.json(); + capturedToken = body.verificationToken; + await route.fulfill({ response }); + }); + + await page.goto('/register'); + await page.getByLabel('Name').fill('New User'); + await page.getByLabel('Email').fill('newuser@test.com'); + await page.getByLabel('Password', { exact: true }).fill('SecurePass!'); + await page.getByLabel('Confirm password').fill('SecurePass!'); + await page.getByRole('button', { name: 'Create account' }).click(); + + await expect(page.getByText('Check your inbox')).toBeVisible(); + + expect(capturedToken).toBeTruthy(); + await page.goto(`/verify?token=${capturedToken}`); + + await expect(page.getByText('Email confirmed')).toBeVisible(); +}); +``` + +### Fully Mocked Verification + +```typescript +test('verifies email with mocked endpoints', async ({ page }) => { + const mockToken = 'test-verification-abc123'; + + await page.route('**/api/auth/register', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ message: 'Verification sent', verificationToken: mockToken }), + }); + }); + + await page.route(`**/api/auth/verify?token=${mockToken}`, async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ verified: true }), + }); + }); + + await page.goto('/register'); + await page.getByLabel('Email').fill('test@example.com'); + await page.getByLabel('Password', { exact: true }).fill('Password123!'); + await page.getByRole('button', { name: 'Sign up' }).click(); + + await expect(page.getByText('Check your inbox')).toBeVisible(); + + await page.goto(`/verify?token=${mockToken}`); + await expect(page.getByText('Email confirmed')).toBeVisible(); +}); +``` + +--- + +## Password Reset + +### Complete Reset Flow + +```typescript +test('resets password through email link', async ({ page }) => { + let resetToken = ''; + + await page.route('**/api/auth/forgot-password', async (route) => { + const response = await route.fetch(); + const body = await response.json(); + resetToken = body.resetToken; + await route.fulfill({ response }); + }); + + await page.goto('/forgot-password'); + await page.getByLabel('Email').fill('user@test.com'); + await page.getByRole('button', { name: 'Send link' }).click(); + + await expect(page.getByText('Reset email sent')).toBeVisible(); + + expect(resetToken).toBeTruthy(); + await page.goto(`/reset-password?token=${resetToken}`); + + await page.getByLabel('New password', { exact: true }).fill('NewPassword456!'); + await page.getByLabel('Confirm password').fill('NewPassword456!'); + await page.getByRole('button', { name: 'Update password' }).click(); + + await expect(page.getByText('Password updated')).toBeVisible(); +}); +``` + +### Expired Token Handling + +```typescript +test('shows error for expired reset token', async ({ page }) => { + await page.goto('/reset-password?token=expired-token'); + + await page.getByLabel('New password', { exact: true }).fill('NewPass!'); + await page.getByLabel('Confirm password').fill('NewPass!'); + await page.getByRole('button', { name: 'Update password' }).click(); + + await expect(page.getByRole('alert')).toContainText(/expired|invalid/i); +}); +``` + +### Password Strength Validation + +```typescript +test('enforces password requirements on reset', async ({ page }) => { + await page.goto('/reset-password?token=valid-token'); + + await page.getByLabel('New password', { exact: true }).fill('weak'); + await page.getByLabel('Confirm password').fill('weak'); + await page.getByRole('button', { name: 'Update password' }).click(); + + await expect(page.getByText(/at least 8 characters/i)).toBeVisible(); +}); +``` + +--- + +## Session Timeout + +### Detecting Expired Sessions + +```typescript +test('redirects to signin after session expires', async ({ page, context }) => { + await page.goto('/signin'); + await page.getByLabel('Email').fill('user@test.com'); + await page.getByLabel('Password').fill('Password!'); + await page.getByRole('button', { name: 'Sign in' }).click(); + await expect(page).toHaveURL('/home'); + + const cookies = await context.cookies(); + const sessionCookie = cookies.find((c) => c.name.includes('session')); + + if (sessionCookie) { + await context.clearCookies({ name: sessionCookie.name }); + } + + await page.goto('/profile'); + await expect(page).toHaveURL(/\/signin/); + await expect(page.getByText(/session.*expired|sign in again/i)).toBeVisible(); +}); +``` + +### Session Extension Warning + +```typescript +test('shows warning before session expires', async ({ page }) => { + await page.route('**/api/auth/session', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ valid: true, expiresIn: 60 }), + }); + }); + + await page.goto('/home'); + + await expect(page.getByText(/session.*expir/i)).toBeVisible({ timeout: 10000 }); + await expect(page.getByRole('button', { name: /extend|stay signed in/i })).toBeVisible(); +}); +``` + +### Session Extension Action + +```typescript +test('extends session when user clicks extend', async ({ page }) => { + let sessionExtended = false; + + await page.route('**/api/auth/session', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ valid: true, expiresIn: 60 }), + }); + }); + + await page.route('**/api/auth/refresh', async (route) => { + sessionExtended = true; + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ valid: true, expiresIn: 3600 }), + }); + }); + + await page.goto('/home'); + + await expect(page.getByRole('button', { name: /extend|stay signed in/i })).toBeVisible({ + timeout: 10000, + }); + await page.getByRole('button', { name: /extend|stay signed in/i }).click(); + + expect(sessionExtended).toBe(true); + await expect(page.getByText(/session.*expir/i)).not.toBeVisible(); +}); +``` + +--- + +## Remember Me Persistence + +### Persistent Session + +```typescript +test('persists session with remember me enabled', async ({ browser }) => { + const ctx1 = await browser.newContext(); + const page1 = await ctx1.newPage(); + + await page1.goto('/signin'); + await page1.getByLabel('Email').fill('user@test.com'); + await page1.getByLabel('Password').fill('Password!'); + await page1.getByLabel('Keep me signed in').check(); + await page1.getByRole('button', { name: 'Sign in' }).click(); + + await expect(page1).toHaveURL('/home'); + + const state = await ctx1.storageState(); + await ctx1.close(); + + const ctx2 = await browser.newContext({ storageState: state }); + const page2 = await ctx2.newPage(); + + await page2.goto('/home'); + await expect(page2).toHaveURL('/home'); + await expect(page2.getByText('Welcome')).toBeVisible(); + + await ctx2.close(); +}); +``` + +### Session-Only Login + +```typescript +test('session-only login does not persist across browser restarts', async ({ browser }) => { + const ctx1 = await browser.newContext(); + const page1 = await ctx1.newPage(); + + await page1.goto('/signin'); + await page1.getByLabel('Email').fill('user@test.com'); + await page1.getByLabel('Password').fill('Password!'); + // Leave "Remember me" unchecked + await expect(page1.getByLabel('Keep me signed in')).not.toBeChecked(); + await page1.getByRole('button', { name: 'Sign in' }).click(); + + await expect(page1).toHaveURL('/home'); + + // Only keep persistent cookies (filter out session cookies) + const cookies = await ctx1.cookies(); + await ctx1.close(); + + const persistentCookies = cookies.filter((c) => c.expires > 0); + const ctx2 = await browser.newContext(); + await ctx2.addCookies(persistentCookies); + const page2 = await ctx2.newPage(); + + await page2.goto('/home'); + + // Should redirect to login since session was not persisted + await expect(page2).toHaveURL(/\/signin/); + + await ctx2.close(); +}); +``` + +--- + +## Logout Patterns + +### Standard Logout with Session Cleanup + +```typescript +test.use({ storageState: '.auth/user.json' }); + +test('logs out and clears session', async ({ page, context }) => { + await page.goto('/home'); + + await page.getByRole('button', { name: /account|menu/i }).click(); + await page.getByRole('menuitem', { name: 'Sign out' }).click(); + + await expect(page).toHaveURL('/signin'); + + const cookies = await context.cookies(); + const sessionCookies = cookies.filter((c) => c.name.includes('session') || c.name.includes('token')); + expect(sessionCookies).toHaveLength(0); + + await page.goto('/home'); + await expect(page).toHaveURL(/\/signin/); +}); +``` + +### Logout from All Devices + +```typescript +test('logs out from all devices', async ({ page }) => { + let logoutAllCalled = false; + + await page.route('**/api/auth/logout-all', async (route) => { + logoutAllCalled = true; + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ message: 'Logged out everywhere' }), + }); + }); + + await page.goto('/settings/security'); + + await page.getByRole('button', { name: 'Sign out everywhere' }).click(); + await page.getByRole('dialog').getByRole('button', { name: 'Confirm' }).click(); + + expect(logoutAllCalled).toBe(true); + await expect(page).toHaveURL(/\/signin/); +}); +``` + +--- + +## Tips + +1. **Configure shorter session timeouts in test environments** — Enables testing timeout behavior without slow tests +2. **Test token expiration edge cases** — Expired tokens, invalid tokens, already-used tokens +3. **Verify cleanup on logout** — Check both cookies and localStorage are cleared +4. **Test the full flow end-to-end** — Password reset should verify login with new password works + +--- + +## Related + +- [authentication.md](authentication.md) — Storage state, OAuth mocking, MFA, role-based access, API login +- [fixtures-hooks.md](../core/fixtures-hooks.md) — Creating auth fixtures +- [third-party.md](./third-party.md) — Mocking external auth providers diff --git a/.cursor/skills/playwright-testing/advanced/authentication.md b/.cursor/skills/playwright-testing/advanced/authentication.md new file mode 100644 index 0000000..02c2dd7 --- /dev/null +++ b/.cursor/skills/playwright-testing/advanced/authentication.md @@ -0,0 +1,871 @@ +# Authentication Testing + +## Table of Contents + +1. [Quick Reference](#quick-reference) +2. [Patterns](#patterns) +3. [Decision Guide](#decision-guide) +4. [Anti-Patterns](#anti-patterns) +5. [Troubleshooting](#troubleshooting) +6. [Related](#related) + +> **When to use**: Apps with login, session management, or protected routes. Authentication is the most common source of slow test suites. + +## Quick Reference + +```typescript +// Storage state reuse — the #1 pattern for fast auth +await page.goto("/login"); +await page.getByLabel("Username").fill("testuser@example.com"); +await page.getByLabel("Password").fill("secretPass123"); +await page.getByRole("button", { name: "Log in" }).click(); +await page.context().storageState({ path: ".auth/session.json" }); + +// Reuse in config — every test starts authenticated +{ + use: { + storageState: ".auth/session.json" + } +} + +// API login — skip the UI entirely +const context = await browser.newContext(); +const response = await context.request.post("/api/auth/login", { + data: { email: "testuser@example.com", password: "secretPass123" }, +}); +await context.storageState({ path: ".auth/session.json" }); +``` + +## Patterns + +### Storage State Reuse + +**Use when**: You need authenticated tests and want to avoid logging in before every test. +**Avoid when**: Tests require completely fresh sessions, or you are testing the login flow itself. + +`storageState` serializes cookies and localStorage to a JSON file. Load it in any browser context to start authenticated instantly. + +```typescript +// scripts/generate-auth.ts — run once to generate the state file +import { chromium } from "@playwright/test"; + +async function generateAuthState() { + const browser = await chromium.launch(); + const context = await browser.newContext(); + const page = await context.newPage(); + + await page.goto("http://localhost:4000/login"); + await page.getByLabel("Username").fill("testuser@example.com"); + await page.getByLabel("Password").fill("secretPass123"); + await page.getByRole("button", { name: "Log in" }).click(); + await page.waitForURL("/home"); + + await context.storageState({ path: ".auth/session.json" }); + await browser.close(); +} + +generateAuthState(); +``` + +```typescript +// playwright.config.ts — load saved state for all tests +import { defineConfig } from "@playwright/test"; + +export default defineConfig({ + use: { + baseURL: "http://localhost:4000", + storageState: ".auth/session.json", + }, +}); +``` + +```typescript +// tests/home.spec.ts — test starts already logged in +import { test, expect } from "@playwright/test"; + +test("authenticated user sees home page", async ({ page }) => { + await page.goto("/home"); + await expect(page.getByRole("heading", { name: "Home" })).toBeVisible(); +}); +``` + +### Global Setup Authentication + +**Use when**: You want to authenticate once before the entire test suite runs. +**Avoid when**: Different tests need different users, or your tokens expire faster than your suite runs. + +```typescript +// global-setup.ts +import { chromium, type FullConfig } from "@playwright/test"; + +async function globalSetup(config: FullConfig) { + const { baseURL } = config.projects[0].use; + const browser = await chromium.launch(); + const context = await browser.newContext(); + const page = await context.newPage(); + + await page.goto(`${baseURL}/login`); + await page.getByLabel("Username").fill(process.env.TEST_USER_EMAIL!); + await page.getByLabel("Password").fill(process.env.TEST_USER_PASSWORD!); + await page.getByRole("button", { name: "Log in" }).click(); + await page.waitForURL("**/home"); + + await context.storageState({ path: ".auth/session.json" }); + await browser.close(); +} + +export default globalSetup; +``` + +```typescript +// playwright.config.ts +import { defineConfig } from "@playwright/test"; + +export default defineConfig({ + globalSetup: require.resolve("./global-setup"), + use: { + baseURL: "http://localhost:4000", + storageState: ".auth/session.json", + }, +}); +``` + +Add `.auth/` to `.gitignore`. Auth state files contain session tokens and should never be committed. + +### Per-Worker Authentication + +**Use when**: Each parallel worker needs its own authenticated session to avoid race conditions for tests that modify server-side state. +**Avoid when**: Tests are read-only and a modifying shared session is safe, you can use a single shared account. + +> **Sharded runs**: `parallelIndex` resets per shard, so different shards can have workers with the same index. To avoid collisions, include the shard identifier in the username (e.g., `worker-${SHARD_INDEX}-${parallelIndex}@example.com`) by passing a `SHARD_INDEX` environment variable from your CI matrix. + +```typescript +// fixtures/auth.ts +import { test as base, type BrowserContext } from "@playwright/test"; + +type AuthFixtures = { + authenticatedContext: BrowserContext; +}; + +export const test = base.extend<{}, AuthFixtures>({ + authenticatedContext: [ + async ({ browser }, use) => { + const context = await browser.newContext(); + const page = await context.newPage(); + + await page.goto("/login"); + await page + .getByLabel("Username") + .fill(`worker-${test.info().parallelIndex}@example.com`); + await page.getByLabel("Password").fill("secretPass123"); + await page.getByRole("button", { name: "Log in" }).click(); + await page.waitForURL("/home"); + await page.close(); + + await use(context); + await context.close(); + }, + { scope: "worker" }, + ], +}); + +export { expect } from "@playwright/test"; +``` + +```typescript +// tests/settings.spec.ts +import { test, expect } from "../fixtures/auth"; + +test("update display name", async ({ authenticatedContext }) => { + const page = await authenticatedContext.newPage(); + await page.goto("/settings/profile"); + await page.getByLabel("Display name").fill("Updated Name"); + await page.getByRole("button", { name: "Save" }).click(); + await expect(page.getByText("Profile saved")).toBeVisible(); +}); +``` + +### Multiple Roles + +**Use when**: Your app has role-based access control and you need to test different permission levels. +**Avoid when**: Your app has a single user role. + +```typescript +// global-setup.ts — authenticate all roles +import { chromium, type FullConfig } from "@playwright/test"; + +const accounts = [ + { + role: "admin", + email: "admin@example.com", + password: process.env.ADMIN_PASSWORD!, + }, + { + role: "member", + email: "member@example.com", + password: process.env.MEMBER_PASSWORD!, + }, + { + role: "guest", + email: "guest@example.com", + password: process.env.GUEST_PASSWORD!, + }, +]; + +async function globalSetup(config: FullConfig) { + const { baseURL } = config.projects[0].use; + + for (const { role, email, password } of accounts) { + const browser = await chromium.launch(); + const context = await browser.newContext(); + const page = await context.newPage(); + + await page.goto(`${baseURL}/login`); + await page.getByLabel("Username").fill(email); + await page.getByLabel("Password").fill(password); + await page.getByRole("button", { name: "Log in" }).click(); + await page.waitForURL("**/home"); + + await context.storageState({ path: `.auth/${role}.json` }); + await browser.close(); + } +} + +export default globalSetup; +``` + +```typescript +// playwright.config.ts — one project per role +import { defineConfig } from "@playwright/test"; + +export default defineConfig({ + globalSetup: require.resolve("./global-setup"), + projects: [ + { + name: "admin", + use: { storageState: ".auth/admin.json" }, + testMatch: "**/*.admin.spec.ts", + }, + { + name: "member", + use: { storageState: ".auth/member.json" }, + testMatch: "**/*.member.spec.ts", + }, + { + name: "guest", + use: { storageState: ".auth/guest.json" }, + testMatch: "**/*.guest.spec.ts", + }, + { + name: "anonymous", + use: { storageState: { cookies: [], origins: [] } }, + testMatch: "**/*.anon.spec.ts", + }, + ], +}); +``` + +```typescript +// tests/admin-panel.admin.spec.ts +import { test, expect } from "@playwright/test"; + +test("admin can access user management", async ({ page }) => { + await page.goto("/admin/users"); + await expect( + page.getByRole("heading", { name: "User Management" }) + ).toBeVisible(); + await expect(page.getByRole("button", { name: "Remove user" })).toBeEnabled(); +}); +``` + +```typescript +// tests/admin-panel.guest.spec.ts +import { test, expect } from "@playwright/test"; + +test("guest cannot access admin panel", async ({ page }) => { + await page.goto("/admin/users"); + await expect(page.getByText("Access denied")).toBeVisible(); +}); +``` + +**Alternative**: Use a fixture that accepts a role parameter when you need role switching within a single spec file. + +```typescript +// fixtures/auth.ts — role-based fixture +import { test as base, type Page } from "@playwright/test"; +import fs from "fs"; + +type RoleFixtures = { + loginAs: (role: "admin" | "member" | "guest") => Promise; +}; + +export const test = base.extend({ + loginAs: async ({ browser }, use) => { + const pages: Page[] = []; + + await use(async (role) => { + const statePath = `.auth/${role}.json`; + if (!fs.existsSync(statePath)) { + throw new Error( + `Auth state for role "${role}" not found at ${statePath}` + ); + } + const context = await browser.newContext({ storageState: statePath }); + const page = await context.newPage(); + pages.push(page); + return page; + }); + + for (const page of pages) { + await page.context().close(); + } + }, +}); + +export { expect } from "@playwright/test"; +``` + +```typescript +// tests/role-comparison.spec.ts +import { test, expect } from "../fixtures/auth"; + +test("admin sees remove button, guest does not", async ({ loginAs }) => { + const adminPage = await loginAs("admin"); + await adminPage.goto("/admin/users"); + await expect( + adminPage.getByRole("button", { name: "Remove user" }) + ).toBeVisible(); + + const guestPage = await loginAs("guest"); + await guestPage.goto("/admin/users"); + await expect(guestPage.getByText("Access denied")).toBeVisible(); +}); +``` + +### OAuth/SSO Mocking + +**Use when**: Your app authenticates via a third-party OAuth provider and you cannot hit the real provider in tests. +**Avoid when**: You have a dedicated test tenant on the OAuth provider. + +A typical OAuth flow works like this: + +1. User clicks "Sign in with Provider" → browser navigates to `https://accounts.provider.com/authorize?...` +2. User authenticates on the provider's page → provider redirects back to your app's **callback route** (e.g. `http://localhost:4000/auth/callback?code=ABC&state=XYZ`) +3. Your backend exchanges the `code` for an access token, creates a session, and redirects the user to a logged-in page + +In tests you can short-circuit step 2 with `page.route()`: intercept the outbound request to the provider and respond with a `302` redirect straight to your callback route, supplying a mock `code` and `state`. Your backend still executes its normal callback handler — the only part that's mocked is the provider's authorization page. + +For cases where you want to skip the browser redirect entirely, a second approach calls a **test-only API endpoint** that creates the session server-side and returns the session cookie directly. + +```typescript +// tests/oauth-login.spec.ts — mock the callback route +import { test, expect } from "@playwright/test"; + +test("login via mocked OAuth flow", async ({ page }) => { + await page.route("https://accounts.provider.com/**", async (route) => { + const callbackUrl = new URL("http://localhost:4000/auth/callback"); + callbackUrl.searchParams.set("code", "mock-auth-code-xyz"); + callbackUrl.searchParams.set("state", "expected-state-value"); + await route.fulfill({ + status: 302, + headers: { location: callbackUrl.toString() }, + }); + }); + + await page.goto("/login"); + await page.getByRole("button", { name: "Sign in with Provider" }).click(); + + await page.waitForURL("/home"); + await expect(page.getByRole("heading", { name: "Home" })).toBeVisible(); +}); +``` + +```typescript +// tests/oauth-login.spec.ts — API-based session injection +import { test, expect } from "@playwright/test"; + +test("bypass OAuth entirely via API session injection", async ({ + page, +}) => { + // Call a test-only endpoint that creates a session without OAuth + const response = await page.request.post("/api/test/create-session", { + data: { + email: "oauth-user@example.com", + provider: "provider", + role: "member", + }, + }); + expect(response.ok()).toBeTruthy(); + + await page.context().storageState({ path: ".auth/oauth-user.json" }); + await page.goto("/home"); + await expect(page.getByRole("heading", { name: "Home" })).toBeVisible(); +}); +``` + +**Backend requirement**: Your backend must expose a test-only session creation endpoint (guarded by `NODE_ENV=test`) or accept a known test OAuth code. + +### MFA Handling + +**Use when**: Your app requires two-factor authentication (TOTP, SMS, email codes). +**Avoid when**: MFA is optional and you can disable it for test accounts. + +**Strategy 1**: Generate real TOTP codes from a shared secret. + +```typescript +// helpers/totp.ts +import * as OTPAuth from "otpauth"; + +export function generateTOTP(secret: string): string { + const totp = new OTPAuth.TOTP({ + secret: OTPAuth.Secret.fromBase32(secret), + digits: 6, + period: 30, + algorithm: "SHA1", + }); + return totp.generate(); +} +``` + +```typescript +// tests/mfa-login.spec.ts +import { test, expect } from "@playwright/test"; +import { generateTOTP } from "../helpers/totp"; + +test("login with TOTP two-factor auth", async ({ page }) => { + await page.goto("/login"); + await page.getByLabel("Username").fill("mfa-user@example.com"); + await page.getByLabel("Password").fill("secretPass123"); + await page.getByRole("button", { name: "Log in" }).click(); + + await expect(page.getByText("Enter your authentication code")).toBeVisible(); + + const code = generateTOTP(process.env.MFA_TOTP_SECRET!); + await page.getByLabel("Authentication code").fill(code); + await page.getByRole("button", { name: "Verify" }).click(); + + await page.waitForURL("/home"); + await expect(page.getByRole("heading", { name: "Home" })).toBeVisible(); +}); +``` + +**Strategy 2**: Mock MFA at the backend level. Have your backend accept a known bypass code (e.g., `000000`) when `NODE_ENV=test`. + +**Strategy 3**: Disable MFA for test accounts at the infrastructure level. + +### Session Refresh + +**Use when**: Your tokens expire during long test runs. +**Avoid when**: Your test suite runs quickly and tokens outlast the entire run. + +```typescript +// fixtures/auth-with-refresh.ts +import { test as base, type BrowserContext } from "@playwright/test"; +import fs from "fs"; + +type AuthFixtures = { + authenticatedPage: import("@playwright/test").Page; +}; + +export const test = base.extend({ + authenticatedPage: async ({ browser }, use) => { + const statePath = ".auth/session.json"; + + let context: BrowserContext; + if (fs.existsSync(statePath)) { + context = await browser.newContext({ storageState: statePath }); + const page = await context.newPage(); + + const response = await page.request.get("/api/auth/me"); + if (response.ok()) { + await use(page); + await context.close(); + return; + } + await context.close(); + } + + context = await browser.newContext(); + const page = await context.newPage(); + await page.goto("/login"); + await page.getByLabel("Username").fill(process.env.TEST_USER_EMAIL!); + await page.getByLabel("Password").fill(process.env.TEST_USER_PASSWORD!); + await page.getByRole("button", { name: "Log in" }).click(); + await page.waitForURL("/home"); + + await context.storageState({ path: statePath }); + + await use(page); + await context.close(); + }, +}); + +export { expect } from "@playwright/test"; +``` + +### Login Page Object + +**Use when**: Multiple test files need to log in and you want consistent, maintainable login logic. +**Avoid when**: You use `storageState` everywhere and never navigate through the login UI in tests. + +```typescript +// page-objects/LoginPage.ts +import { type Page, type Locator, expect } from "@playwright/test"; + +export class LoginPage { + readonly page: Page; + readonly usernameInput: Locator; + readonly passwordInput: Locator; + readonly loginButton: Locator; + readonly errorMessage: Locator; + readonly forgotPasswordLink: Locator; + + constructor(page: Page) { + this.page = page; + this.usernameInput = page.getByLabel("Username"); + this.passwordInput = page.getByLabel("Password"); + this.loginButton = page.getByRole("button", { name: "Log in" }); + this.errorMessage = page.getByRole("alert"); + this.forgotPasswordLink = page.getByRole("link", { + name: "Forgot password", + }); + } + + async goto() { + await this.page.goto("/login"); + await expect(this.loginButton).toBeVisible(); + } + + async login(username: string, password: string) { + await this.usernameInput.fill(username); + await this.passwordInput.fill(password); + await this.loginButton.click(); + } + + async loginAndWaitForHome(username: string, password: string) { + await this.login(username, password); + await this.page.waitForURL("/home"); + } + + async expectError(message: string | RegExp) { + await expect(this.errorMessage).toContainText(message); + } + + async expectFieldError(field: "username" | "password", message: string) { + const input = + field === "username" ? this.usernameInput : this.passwordInput; + await expect(input).toHaveAttribute("aria-invalid", "true"); + const errorId = await input.getAttribute("aria-describedby"); + if (errorId) { + await expect(this.page.locator(`#${errorId}`)).toContainText(message); + } + } +} +``` + +```typescript +// tests/login.spec.ts +import { test, expect } from "@playwright/test"; +import { LoginPage } from "../page-objects/LoginPage"; + +test.use({ storageState: { cookies: [], origins: [] } }); + +test.describe("login page", () => { + let loginPage: LoginPage; + + test.beforeEach(async ({ page }) => { + loginPage = new LoginPage(page); + await loginPage.goto(); + }); + + test("successful login redirects to home", async ({ page }) => { + await loginPage.loginAndWaitForHome( + "testuser@example.com", + "secretPass123" + ); + await expect(page.getByRole("heading", { name: "Home" })).toBeVisible(); + }); + + test("wrong password shows error", async () => { + await loginPage.login("testuser@example.com", "wrong-password"); + await loginPage.expectError("Invalid username or password"); + }); + + test("empty fields show validation errors", async () => { + await loginPage.loginButton.click(); + await loginPage.expectFieldError("username", "Username is required"); + }); + + test("forgot password link navigates correctly", async ({ page }) => { + await loginPage.forgotPasswordLink.click(); + await page.waitForURL("/forgot-password"); + await expect( + page.getByRole("heading", { name: "Reset password" }) + ).toBeVisible(); + }); +}); +``` + +### API-Based Login + +**Use when**: You want the fastest possible authentication without any browser interaction. +**Avoid when**: You are specifically testing the login UI. + +API login is typically 5-10x faster than UI login. + +```typescript +// global-setup.ts — API-based login (fastest) +import { request, type FullConfig } from "@playwright/test"; + +async function globalSetup(config: FullConfig) { + const { baseURL } = config.projects[0].use; + + const requestContext = await request.newContext({ baseURL }); + + const response = await requestContext.post("/api/auth/login", { + data: { + email: process.env.TEST_USER_EMAIL!, + password: process.env.TEST_USER_PASSWORD!, + }, + }); + + if (!response.ok()) { + throw new Error( + `API login failed: ${response.status()} ${await response.text()}` + ); + } + + await requestContext.storageState({ path: ".auth/session.json" }); + await requestContext.dispose(); +} + +export default globalSetup; +``` + +```typescript +// fixtures/api-auth.ts — fixture version for per-test authentication +import { test as base } from "@playwright/test"; + +export const test = base.extend({ + authenticatedPage: async ({ browser, playwright }, use) => { + const apiContext = await playwright.request.newContext({ + baseURL: "http://localhost:4000", + }); + + await apiContext.post("/api/auth/login", { + data: { + email: "testuser@example.com", + password: "secretPass123", + }, + }); + + const state = await apiContext.storageState(); + const context = await browser.newContext({ storageState: state }); + const page = await context.newPage(); + + await use(page); + + await context.close(); + await apiContext.dispose(); + }, +}); + +export { expect } from "@playwright/test"; +``` + +### Unauthenticated Tests + +**Use when**: Testing the login page, signup flow, password reset, public pages, or redirect behavior for unauthenticated users. +**Avoid when**: The test requires a logged-in user. + +When your config sets a default `storageState`, you must explicitly clear it for unauthenticated tests. + +```typescript +// tests/public-pages.spec.ts +import { test, expect } from "@playwright/test"; + +test.use({ storageState: { cookies: [], origins: [] } }); + +test.describe("unauthenticated access", () => { + test("homepage is accessible without login", async ({ page }) => { + await page.goto("/"); + await expect(page.getByRole("heading", { name: "Welcome" })).toBeVisible(); + await expect(page.getByRole("link", { name: "Log in" })).toBeVisible(); + }); + + test("protected route redirects to login", async ({ page }) => { + await page.goto("/home"); + await page.waitForURL("**/login**"); + expect(page.url()).toContain("redirect=%2Fhome"); + }); + + test("expired session shows re-login prompt", async ({ page, context }) => { + await page.goto("/home"); + await context.clearCookies(); + + await page.goto("/settings"); + await page.waitForURL("**/login**"); + await expect(page.getByText("Your session has expired")).toBeVisible(); + }); + + test("signup flow creates account", async ({ page }) => { + await page.goto("/signup"); + await page.getByLabel("Name").fill("New User"); + await page.getByLabel("Email").fill(`test-${Date.now()}@example.com`); + await page.getByLabel("Password", { exact: true }).fill("secretPass123"); + await page.getByLabel("Confirm password").fill("secretPass123"); + await page.getByRole("button", { name: "Create account" }).click(); + + await page.waitForURL("/onboarding"); + await expect(page.getByText("Welcome, New User")).toBeVisible(); + }); +}); +``` + +## Decision Guide + +| Scenario | Approach | Speed | Isolation | When to Choose | +| -------------------------------- | ------------------------------ | -------- | -------------- | -------------------------------------------------------------- | +| Most tests need auth | Global setup + `storageState` | Fastest | Shared session | Default for nearly every project | +| Tests modify user state | Per-worker fixture | Fast | Per worker | Tests update profile, change settings, or mutate data | +| Multiple user roles | Per-project `storageState` | Fastest | Per role | App has admin/member/guest roles | +| Testing the login page | No `storageState` | N/A | Full | Use `test.use({ storageState: { cookies: [], origins: [] } })` | +| OAuth/SSO provider | Mock the callback | Fast | Per test | Never hit real OAuth providers in CI | +| MFA is required | TOTP generation or bypass | Moderate | Per test | Generate real TOTP codes or use a test-mode bypass | +| Token expires mid-suite | Session refresh fixture | Fast | Per check | Fixture validates the session before use | +| Single test needs different user | `loginAs(role)` fixture | Moderate | Per call | Rare: prefer per-project roles | +| API-first app (no login UI) | API login via `request.post()` | Fastest | Per test | No browser needed for auth | + +### UI Login vs API Login vs Storage State + +```text +Need to test the login page itself? +├── Yes → UI login with LoginPage POM, no storageState +└── No → Do you have a login API endpoint? + ├── Yes → API login in global setup, save storageState (fastest) + └── No → UI login in global setup, save storageState + └── Tokens expire quickly? + ├── Yes → Add session refresh fixture + └── No → Standard storageState reuse is fine +``` + +## Anti-Patterns + +| Don't Do This | Problem | Do This Instead | +| ------------------------------------------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------- | +| Log in via UI before every test | Adds 2-5 seconds per test | Use `storageState` to skip login entirely | +| Share a single auth state file across parallel workers that mutate state | Race conditions | Use per-worker fixtures with `{ scope: 'worker' }` | +| Hardcode credentials in test files | Security risk | Use environment variables and `.env` files | +| Ignore token expiration | Tests fail intermittently with 401 errors | Add a session validity check in your auth fixture | +| Hit real OAuth providers in CI | Flaky: rate limits, CAPTCHA, network issues | Mock the OAuth callback or use API session injection | +| Use `page.waitForTimeout(2000)` after login | Arbitrary delay | `await page.waitForURL('/home')` or `await expect(heading).toBeVisible()` | +| Store `.auth/*.json` files in git | Tokens in version control | Add `.auth/` to `.gitignore` | +| Create one "god" test account with all permissions | Cannot test role-based access control | Create separate accounts per role | +| Use `browser.newContext()` without `storageState` for authenticated tests | Every context starts unauthenticated | Pass `storageState` when creating the context | +| Test MFA by disabling it everywhere | You never test the MFA flow | Use TOTP generation for at least one test | + +## Troubleshooting + +### Global setup fails with "Target page, context or browser has been closed" + +**Cause**: The login page redirected unexpectedly, or the browser closed before `storageState()` was called. + +**Fix**: + +- Add `await page.waitForURL()` after the login action +- Check that `baseURL` in your config matches the actual server URL and protocol +- Add error handling to global setup: + +```typescript +const response = await page.waitForResponse("**/api/auth/**"); +if (!response.ok()) { + throw new Error( + `Login failed in global setup: ${response.status()} ${await response.text()}` + ); +} +``` + +### Tests fail with 401 Unauthorized after running for a while + +**Cause**: The session token saved in `storageState` has expired. + +**Fix**: + +- Use the session refresh fixture pattern +- Increase token expiry in test environment configuration +- Switch to API-based login in a worker-scoped fixture + +### `storageState` file is empty or contains no cookies + +**Cause**: `storageState()` was called before the login response set cookies. + +**Fix**: + +- Wait for the post-login page to load: `await page.waitForURL('/home')` +- Verify cookies exist before saving: + +```typescript +const cookies = await context.cookies(); +if (cookies.length === 0) { + throw new Error("No cookies found after login"); +} +await context.storageState({ path: ".auth/session.json" }); +``` + +### Different browsers get different cookies + +**Cause**: Some auth flows set cookies with `SameSite=Strict` or use browser-specific cookie behavior. + +**Fix**: + +- Generate separate auth state files per browser project +- Check if your auth uses `SameSite=None; Secure` cookies that require HTTPS: + +```typescript +projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'], storageState: '.auth/chromium-session.json' }, + }, + { + name: 'firefox', + use: { ...devices['Desktop Firefox'], storageState: '.auth/firefox-session.json' }, + }, +], +``` + +### Parallel tests interfere with each other's sessions + +**Cause**: Multiple workers share the same test account and one worker's actions affect others. + +**Fix**: + +- Use per-worker test accounts: `worker-${test.info().parallelIndex}@example.com` +- Use the per-worker authentication fixture pattern +- Make tests idempotent + +### OAuth mock does not work — still redirects to real provider + +**Cause**: `page.route()` was registered after the navigation that triggers the OAuth redirect. + +**Fix**: + +- Register route handlers before any navigation: call `page.route()` before `page.goto()` +- Log the actual redirect URL to verify the pattern: + +```typescript +page.on("request", (req) => { + if (req.url().includes("oauth") || req.url().includes("accounts.provider")) { + console.log("OAuth request:", req.url()); + } +}); +``` + +## Related + +- [fixtures-hooks.md](../core/fixtures-hooks.md) — custom fixtures for auth setup and teardown +- [configuration.md](../core/configuration.md) — `storageState`, projects, and global setup configuration +- [global-setup.md](../core/global-setup.md) — global setup patterns and project dependencies +- [network-advanced.md](network-advanced.md) — route interception patterns used in OAuth mocking +- [api-testing.md](../testing-patterns/api-testing.md) — API request context used in API-based login +- [flaky-tests.md](../debugging/flaky-tests.md) — diagnosing auth-related flakiness diff --git a/.cursor/skills/playwright-testing/advanced/clock-mocking.md b/.cursor/skills/playwright-testing/advanced/clock-mocking.md new file mode 100644 index 0000000..073d087 --- /dev/null +++ b/.cursor/skills/playwright-testing/advanced/clock-mocking.md @@ -0,0 +1,364 @@ +# Date, Time & Clock Mocking + +## Table of Contents + +1. [Clock API Basics](#clock-api-basics) +2. [Fixed Time Testing](#fixed-time-testing) +3. [Time Advancement](#time-advancement) +4. [Timezone Testing](#timezone-testing) +5. [Timer Mocking](#timer-mocking) + +## Clock API Basics + +### Install Clock + +```typescript +test("mock current time", async ({ page }) => { + // Install clock before navigating + await page.clock.install({ time: new Date("2025-01-15T09:00:00") }); + + await page.goto("/dashboard"); + + // Page sees January 15, 2025 as current date + await expect(page.getByText("January 15, 2025")).toBeVisible(); +}); +``` + +### Clock with Fixture + +```typescript +// fixtures/clock.fixture.ts +import { test as base } from "@playwright/test"; + +type ClockFixtures = { + mockTime: (date: Date | string) => Promise; +}; + +export const test = base.extend({ + mockTime: async ({ page }, use) => { + await use(async (date) => { + const time = typeof date === "string" ? new Date(date) : date; + await page.clock.install({ time }); + }); + }, +}); + +// Usage +test("subscription expiry", async ({ page, mockTime }) => { + await mockTime("2025-12-31T23:59:00"); + await page.goto("/subscription"); + + await expect(page.getByText("Expires today")).toBeVisible(); +}); +``` + +## Fixed Time Testing + +### Test Date-Dependent Features + +```typescript +test("show holiday banner in December", async ({ page }) => { + await page.clock.install({ time: new Date("2025-12-20T10:00:00") }); + + await page.goto("/"); + + await expect(page.getByRole("banner", { name: /holiday/i })).toBeVisible(); +}); + +test("no holiday banner in January", async ({ page }) => { + await page.clock.install({ time: new Date("2025-01-15T10:00:00") }); + + await page.goto("/"); + + await expect(page.getByRole("banner", { name: /holiday/i })).toBeHidden(); +}); +``` + +### Test Relative Time Display + +```typescript +test("shows relative time correctly", async ({ page }) => { + // Fix time to control "posted 2 hours ago" text + await page.clock.install({ time: new Date("2025-06-15T14:00:00") }); + + // Mock API to return post with known timestamp + await page.route("**/api/posts/1", (route) => + route.fulfill({ + json: { + id: 1, + title: "Test Post", + createdAt: "2025-06-15T12:00:00Z", // 2 hours before mock time + }, + }), + ); + + await page.goto("/posts/1"); + + await expect(page.getByText("2 hours ago")).toBeVisible(); +}); +``` + +### Test Date Boundaries + +```typescript +test.describe("end of month billing", () => { + test("shows billing on last day of month", async ({ page }) => { + await page.clock.install({ time: new Date("2025-01-31T10:00:00") }); + await page.goto("/billing"); + + await expect(page.getByText("Payment due today")).toBeVisible(); + }); + + test("shows days remaining mid-month", async ({ page }) => { + await page.clock.install({ time: new Date("2025-01-15T10:00:00") }); + await page.goto("/billing"); + + await expect(page.getByText("16 days until payment")).toBeVisible(); + }); +}); +``` + +## Time Advancement + +### Advance Time Manually + +```typescript +test("session timeout warning", async ({ page }) => { + await page.clock.install({ time: new Date("2025-01-15T09:00:00") }); + await page.goto("/dashboard"); + + // Advance 25 minutes (session timeout at 30 min) + await page.clock.fastForward("25:00"); + + await expect(page.getByText("Session expires in 5 minutes")).toBeVisible(); + + // Advance 5 more minutes + await page.clock.fastForward("05:00"); + + await expect(page.getByText("Session expired")).toBeVisible(); +}); +``` + +### Pause and Resume Time + +```typescript +test("countdown timer", async ({ page }) => { + await page.clock.install({ time: new Date("2025-01-15T09:00:00") }); + await page.goto("/sale"); + + // Initial state + await expect(page.getByText("Sale ends in 2:00:00")).toBeVisible(); + + // Advance 1 hour + await page.clock.fastForward("01:00:00"); + + await expect(page.getByText("Sale ends in 1:00:00")).toBeVisible(); + + // Advance past end + await page.clock.fastForward("01:00:01"); + + await expect(page.getByText("Sale ended")).toBeVisible(); +}); +``` + +### Run Pending Timers + +```typescript +test("debounced search", async ({ page }) => { + await page.clock.install({ time: new Date("2025-01-15T09:00:00") }); + await page.goto("/search"); + + await page.getByLabel("Search").fill("playwright"); + + // Search is debounced by 300ms, won't fire yet + await expect(page.getByTestId("search-results")).toBeHidden(); + + // Fast forward past debounce + await page.clock.fastForward(300); + + // Now search should execute + await expect(page.getByTestId("search-results")).toBeVisible(); +}); +``` + +## Timezone Testing + +### Test Different Timezones + +```typescript +test.describe("timezone display", () => { + test("shows correct time in PST", async ({ browser }) => { + const context = await browser.newContext({ + timezoneId: "America/Los_Angeles", + }); + const page = await context.newPage(); + + await page.clock.install({ time: new Date("2025-01-15T17:00:00Z") }); // 5 PM UTC + + await page.goto("/schedule"); + + // Should show 9 AM PST + await expect(page.getByText("9:00 AM")).toBeVisible(); + + await context.close(); + }); + + test("shows correct time in JST", async ({ browser }) => { + const context = await browser.newContext({ + timezoneId: "Asia/Tokyo", + }); + const page = await context.newPage(); + + await page.clock.install({ time: new Date("2025-01-15T17:00:00Z") }); // 5 PM UTC + + await page.goto("/schedule"); + + // Should show 2 AM next day JST + await expect(page.getByText("2:00 AM")).toBeVisible(); + + await context.close(); + }); +}); +``` + +### Timezone Fixture + +```typescript +// fixtures/timezone.fixture.ts +import { test as base } from "@playwright/test"; + +type TimezoneFixtures = { + pageInTimezone: (timezone: string) => Promise; +}; + +export const test = base.extend({ + pageInTimezone: async ({ browser }, use) => { + const pages: Page[] = []; + + await use(async (timezone) => { + const context = await browser.newContext({ timezoneId: timezone }); + const page = await context.newPage(); + pages.push(page); + return page; + }); + + // Cleanup + for (const page of pages) { + await page.context().close(); + } + }, +}); +``` + +## Timer Mocking + +### Mock setInterval + +```typescript +test("auto-refresh data", async ({ page }) => { + await page.clock.install({ time: new Date("2025-01-15T09:00:00") }); + + let apiCalls = 0; + await page.route("**/api/data", (route) => { + apiCalls++; + route.fulfill({ json: { value: apiCalls } }); + }); + + await page.goto("/live-data"); // Sets up 30s refresh interval + + expect(apiCalls).toBe(1); // Initial load + + // Advance 30 seconds + await page.clock.fastForward("00:30"); + expect(apiCalls).toBe(2); // First refresh + + // Advance another 30 seconds + await page.clock.fastForward("00:30"); + expect(apiCalls).toBe(3); // Second refresh +}); +``` + +### Mock setTimeout Chains + +```typescript +test("notification queue", async ({ page }) => { + await page.clock.install({ time: new Date("2025-01-15T09:00:00") }); + await page.goto("/notifications"); + + // Trigger 3 notifications that show sequentially + await page.getByRole("button", { name: "Show All" }).click(); + + // First notification appears immediately + await expect(page.getByText("Notification 1")).toBeVisible(); + + // Second appears after 2 seconds + await page.clock.fastForward("00:02"); + await expect(page.getByText("Notification 2")).toBeVisible(); + + // Third appears after 2 more seconds + await page.clock.fastForward("00:02"); + await expect(page.getByText("Notification 3")).toBeVisible(); +}); +``` + +### Test Animation Frames + +```typescript +test("animation completes", async ({ page }) => { + await page.clock.install({ time: new Date("2025-01-15T09:00:00") }); + await page.goto("/animation-demo"); + + await page.getByRole("button", { name: "Animate" }).click(); + + // Animation runs for 500ms + const element = page.getByTestId("animated-box"); + await expect(element).toHaveCSS("opacity", "0"); + + // Fast forward through animation + await page.clock.fastForward(500); + + await expect(element).toHaveCSS("opacity", "1"); +}); +``` + +## Best Practices + +### Always Install Clock Before Navigation + +```typescript +// Good +test("date test", async ({ page }) => { + await page.clock.install({ time: new Date("2025-01-15") }); + await page.goto("/"); // Page loads with mocked time +}); + +// Bad - time already captured by page +test("date test", async ({ page }) => { + await page.goto("/"); + await page.clock.install({ time: new Date("2025-01-15") }); // Too late! +}); +``` + +### Use ISO Strings for Clarity + +```typescript +// Good - explicit timezone +await page.clock.install({ time: new Date("2025-01-15T09:00:00Z") }); + +// Ambiguous - uses local timezone +await page.clock.install({ time: new Date("2025-01-15T09:00:00") }); +``` + +## Anti-Patterns to Avoid + +| Anti-Pattern | Problem | Solution | +| ---------------------------------------- | ------------------------------- | -------------------------------------- | +| Installing clock after navigation | Page already captured real time | Install clock before `goto()` | +| Hardcoded relative dates | Tests break over time | Use fixed dates with clock mock | +| Not accounting for timezone | Tests fail in different regions | Use explicit UTC times or set timezone | +| Using `waitForTimeout` with mocked clock | Conflicts with mocked timers | Use `fastForward` instead | + +## Related References + +- **Assertions**: See [assertions-waiting.md](../core/assertions-waiting.md) for time-based assertions +- **Fixtures**: See [fixtures-hooks.md](../core/fixtures-hooks.md) for clock fixtures diff --git a/.cursor/skills/playwright-testing/advanced/mobile-testing.md b/.cursor/skills/playwright-testing/advanced/mobile-testing.md new file mode 100644 index 0000000..e928bde --- /dev/null +++ b/.cursor/skills/playwright-testing/advanced/mobile-testing.md @@ -0,0 +1,409 @@ +# Mobile & Responsive Testing + +## Table of Contents + +1. [Device Emulation](#device-emulation) +2. [Touch Gestures](#touch-gestures) +3. [Viewport Testing](#viewport-testing) +4. [Mobile-Specific UI](#mobile-specific-ui) +5. [Responsive Breakpoints](#responsive-breakpoints) + +## Device Emulation + +### Use Built-in Devices + +```typescript +import { test, devices } from "@playwright/test"; + +// Configure in playwright.config.ts +export default defineConfig({ + projects: [ + { name: "Desktop Chrome", use: { ...devices["Desktop Chrome"] } }, + { name: "Mobile Safari", use: { ...devices["iPhone 14"] } }, + { name: "Mobile Chrome", use: { ...devices["Pixel 7"] } }, + { name: "Tablet", use: { ...devices["iPad Pro 11"] } }, + ], +}); +``` + +### Custom Device Configuration + +```typescript +test.use({ + viewport: { width: 390, height: 844 }, + deviceScaleFactor: 3, + isMobile: true, + hasTouch: true, + userAgent: + "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15", +}); + +test("custom mobile device", async ({ page }) => { + await page.goto("/"); + // Test runs with custom device settings +}); +``` + +### Test Across Multiple Devices + +```typescript +const mobileDevices = ["iPhone 14", "Pixel 7", "Galaxy S21"]; + +for (const deviceName of mobileDevices) { + test(`checkout on ${deviceName}`, async ({ browser }) => { + const device = devices[deviceName]; + const context = await browser.newContext({ ...device }); + const page = await context.newPage(); + + await page.goto("/checkout"); + await expect(page.getByRole("button", { name: "Pay" })).toBeVisible(); + + await context.close(); + }); +} +``` + +## Touch Gestures + +### Tap + +```typescript +test.use({ hasTouch: true }); + +test("tap to interact", async ({ page }) => { + await page.goto("/gallery"); + + // Tap is like click but for touch devices + await page.getByRole("img", { name: "Photo 1" }).tap(); + + await expect(page.getByRole("dialog")).toBeVisible(); +}); +``` + +### Swipe + +```typescript +test("swipe carousel", async ({ page }) => { + await page.goto("/carousel"); + + const carousel = page.getByTestId("carousel"); + const box = await carousel.boundingBox(); + + if (box) { + // Swipe left + await page.touchscreen.tap(box.x + box.width - 50, box.y + box.height / 2); + await page.mouse.move(box.x + 50, box.y + box.height / 2); + + // Or use drag + await carousel.dragTo(carousel, { + sourcePosition: { x: box.width - 50, y: box.height / 2 }, + targetPosition: { x: 50, y: box.height / 2 }, + }); + } + + await expect(page.getByText("Slide 2")).toBeVisible(); +}); +``` + +### Swipe Fixture + +```typescript +// fixtures/touch.fixture.ts +import { test as base, Page } from "@playwright/test"; + +type TouchFixtures = { + swipe: ( + element: Locator, + direction: "left" | "right" | "up" | "down", + ) => Promise; +}; + +export const test = base.extend({ + swipe: async ({ page }, use) => { + await use(async (element, direction) => { + const box = await element.boundingBox(); + if (!box) throw new Error("Element not visible"); + + const centerX = box.x + box.width / 2; + const centerY = box.y + box.height / 2; + const distance = 100; + + const moves = { + left: { + startX: centerX + distance, + endX: centerX - distance, + y: centerY, + }, + right: { + startX: centerX - distance, + endX: centerX + distance, + y: centerY, + }, + up: { + startX: centerX, + endX: centerX, + startY: centerY + distance, + endY: centerY - distance, + }, + down: { + startX: centerX, + endX: centerX, + startY: centerY - distance, + endY: centerY + distance, + }, + }; + + const move = moves[direction]; + await page.touchscreen.tap(move.startX, move.startY ?? move.y); + await page.mouse.move(move.endX, move.endY ?? move.y, { steps: 10 }); + await page.mouse.up(); + }); + }, +}); + +// Usage +test("swipe to delete", async ({ page, swipe }) => { + await page.goto("/inbox"); + + const message = page.getByTestId("message-1"); + await swipe(message, "left"); + + await expect(page.getByRole("button", { name: "Delete" })).toBeVisible(); +}); +``` + +### Long Press + +```typescript +test("long press for context menu", async ({ page }) => { + await page.goto("/files"); + + const file = page.getByText("document.pdf"); + const box = await file.boundingBox(); + + if (box) { + // Touch down + await page.touchscreen.tap(box.x + box.width / 2, box.y + box.height / 2); + + // Hold for 500ms + await page.waitForTimeout(500); + + // Context menu should appear + await expect(page.getByRole("menu")).toBeVisible(); + } +}); +``` + +### Pinch Zoom + +```typescript +test("pinch to zoom image", async ({ page }) => { + await page.goto("/map"); + + // Pinch zoom requires two touch points + // Playwright doesn't have native pinch support, so we simulate via evaluate + await page.evaluate(() => { + const element = document.querySelector("#map"); + if (element) { + // Simulate wheel event as fallback for zoom + element.dispatchEvent( + new WheelEvent("wheel", { + deltaY: -100, // Negative = zoom in + ctrlKey: true, // Ctrl+wheel = pinch on many apps + }), + ); + } + }); + + // Or trigger the app's zoom function directly + await page.evaluate(() => { + (window as any).mapInstance?.setZoom(15); + }); +}); +``` + +## Viewport Testing + +### Test Different Sizes + +```typescript +const viewports = [ + { name: "mobile", width: 375, height: 667 }, + { name: "tablet", width: 768, height: 1024 }, + { name: "desktop", width: 1920, height: 1080 }, +]; + +for (const { name, width, height } of viewports) { + test(`navigation on ${name}`, async ({ page }) => { + await page.setViewportSize({ width, height }); + await page.goto("/"); + + if (width < 768) { + // Mobile: should have hamburger menu + await expect(page.getByRole("button", { name: "Menu" })).toBeVisible(); + } else { + // Desktop: should have visible nav links + await expect(page.getByRole("link", { name: "Products" })).toBeVisible(); + } + }); +} +``` + +### Dynamic Viewport Changes + +```typescript +test("responsive layout change", async ({ page }) => { + await page.setViewportSize({ width: 1200, height: 800 }); + await page.goto("/dashboard"); + + // Desktop: sidebar visible + await expect(page.getByRole("complementary")).toBeVisible(); + + // Resize to mobile + await page.setViewportSize({ width: 375, height: 667 }); + + // Mobile: sidebar hidden, hamburger visible + await expect(page.getByRole("complementary")).toBeHidden(); + await expect(page.getByRole("button", { name: "Menu" })).toBeVisible(); +}); +``` + +## Mobile-Specific UI + +### Hamburger Menu + +```typescript +test("mobile navigation", async ({ page }) => { + await page.setViewportSize({ width: 375, height: 667 }); + await page.goto("/"); + + // Open hamburger menu + await page.getByRole("button", { name: "Menu" }).click(); + + // Navigation drawer should appear + const nav = page.getByRole("navigation"); + await expect(nav).toBeVisible(); + + // Navigate via mobile menu + await nav.getByRole("link", { name: "Products" }).click(); + + await expect(page).toHaveURL("/products"); + // Menu should close after navigation + await expect(nav).toBeHidden(); +}); +``` + +### Bottom Sheet + +```typescript +test("bottom sheet interaction", async ({ page }) => { + await page.setViewportSize({ width: 375, height: 667 }); + await page.goto("/product/123"); + + await page.getByRole("button", { name: "Add to Cart" }).click(); + + // Bottom sheet appears + const sheet = page.getByRole("dialog"); + await expect(sheet).toBeVisible(); + + // Select options + await sheet.getByRole("combobox", { name: "Size" }).selectOption("Large"); + await sheet.getByRole("button", { name: "Confirm" }).click(); + + await expect(page.getByText("Added to cart")).toBeVisible(); +}); +``` + +### Pull to Refresh + +```typescript +test("pull to refresh", async ({ page }) => { + await page.goto("/feed"); + + const feed = page.getByTestId("feed"); + const initialFirstItem = await feed.locator("> *").first().textContent(); + + // Simulate pull down + const box = await feed.boundingBox(); + if (box) { + await page.touchscreen.tap(box.x + box.width / 2, box.y + 50); + await page.mouse.move(box.x + box.width / 2, box.y + 200, { steps: 20 }); + await page.mouse.up(); + } + + // Wait for refresh + await expect(page.getByTestId("loading")).toBeVisible(); + await expect(page.getByTestId("loading")).toBeHidden(); + + // Content should be updated (in a real app) +}); +``` + +## Responsive Breakpoints + +### Test All Breakpoints + +```typescript +const breakpoints = { + xs: 320, + sm: 640, + md: 768, + lg: 1024, + xl: 1280, + "2xl": 1536, +}; + +test.describe("responsive header", () => { + for (const [name, width] of Object.entries(breakpoints)) { + test(`header at ${name} (${width}px)`, async ({ page }) => { + await page.setViewportSize({ width, height: 800 }); + await page.goto("/"); + + if (width < 768) { + await expect(page.getByTestId("mobile-menu-button")).toBeVisible(); + await expect(page.getByTestId("desktop-nav")).toBeHidden(); + } else { + await expect(page.getByTestId("mobile-menu-button")).toBeHidden(); + await expect(page.getByTestId("desktop-nav")).toBeVisible(); + } + }); + } +}); +``` + +### Visual Regression at Breakpoints + +```typescript +test.describe("visual regression", () => { + const sizes = [ + { width: 375, height: 667, name: "mobile" }, + { width: 768, height: 1024, name: "tablet" }, + { width: 1440, height: 900, name: "desktop" }, + ]; + + for (const { width, height, name } of sizes) { + test(`homepage at ${name}`, async ({ page }) => { + await page.setViewportSize({ width, height }); + await page.goto("/"); + + await expect(page).toHaveScreenshot(`homepage-${name}.png`); + }); + } +}); +``` + +## Anti-Patterns to Avoid + +| Anti-Pattern | Problem | Solution | +| --------------------------- | ------------------------- | -------------------------------- | +| Only testing one viewport | Misses responsive bugs | Test multiple breakpoints | +| Ignoring touch events | Features broken on mobile | Test tap, swipe, long press | +| Hardcoded viewport in tests | Can't test multiple sizes | Use `page.setViewportSize()` | +| Not testing orientation | Landscape bugs missed | Test both portrait and landscape | + +## Related References + +- **Visual Testing**: See [test-suite-structure.md](../core/test-suite-structure.md) for screenshot testing +- **Locators**: See [locators.md](../core/locators.md) for mobile-friendly selectors +- **Browser APIs**: See [browser-apis.md](../browser-apis/browser-apis.md) for permissions (camera, geolocation, notifications) +- **Canvas/Touch**: See [canvas-webgl.md](../testing-patterns/canvas-webgl.md) for touch gestures on canvas elements diff --git a/.cursor/skills/playwright-testing/advanced/multi-context.md b/.cursor/skills/playwright-testing/advanced/multi-context.md new file mode 100644 index 0000000..ed1cf8a --- /dev/null +++ b/.cursor/skills/playwright-testing/advanced/multi-context.md @@ -0,0 +1,288 @@ +# Multi-Tab, Window & Popup Testing + +This file covers **single-user scenarios** with multiple browser tabs, windows, and popups. For **multi-user collaboration testing** (multiple users interacting simultaneously), see [multi-user.md](multi-user.md). + +## Table of Contents + +1. [Popup Handling](#popup-handling) +2. [New Tab Navigation](#new-tab-navigation) +3. [OAuth Flows](#oauth-flows) +4. [Multiple Windows](#multiple-windows) +5. [Tab Coordination](#tab-coordination) + +## Popup Handling + +### Basic Popup + +```typescript +test("handle popup window", async ({ page }) => { + await page.goto("/"); + + // Start waiting for popup before triggering it + const popupPromise = page.waitForEvent("popup"); + await page.getByRole("button", { name: "Open Support Chat" }).click(); + const popup = await popupPromise; + + // Wait for popup to load + await popup.waitForLoadState(); + + // Interact with popup + await popup.getByLabel("Message").fill("Need help"); + await popup.getByRole("button", { name: "Send" }).click(); + + await expect(popup.getByText("Message sent")).toBeVisible(); + + // Close popup + await popup.close(); +}); +``` + +### Popup with Authentication + +```typescript +test("popup login flow", async ({ page }) => { + await page.goto("/dashboard"); + + const popupPromise = page.waitForEvent("popup"); + await page.getByRole("button", { name: "Connect Account" }).click(); + const popup = await popupPromise; + + await popup.waitForLoadState(); + + // Complete login in popup + await popup.getByLabel("Email").fill("user@example.com"); + await popup.getByLabel("Password").fill("password123"); + await popup.getByRole("button", { name: "Log In" }).click(); + + // Popup should close automatically after auth + await popup.waitForEvent("close"); + + // Main page should reflect connected state + await expect(page.getByText("Account connected")).toBeVisible(); +}); +``` + +### Handle Blocked Popups + +```typescript +test("handle popup blocker", async ({ page }) => { + await page.goto("/share"); + + // Listen for console messages about blocked popup + page.on("console", (msg) => { + if (msg.text().includes("popup blocked")) { + console.log("Popup was blocked"); + } + }); + + const popupPromise = page.waitForEvent("popup").catch(() => null); + await page.getByRole("button", { name: "Share to Twitter" }).click(); + const popup = await popupPromise; + + if (!popup) { + // Popup blocked - app should show fallback + await expect(page.getByText("Copy share link instead")).toBeVisible(); + } +}); +``` + +## New Tab Navigation + +### Link Opens in New Tab + +```typescript +test("external link opens in new tab", async ({ page, context }) => { + await page.goto("/resources"); + + // Wait for new page in context + const pagePromise = context.waitForEvent("page"); + await page.getByRole("link", { name: "Documentation" }).click(); + const newPage = await pagePromise; + + await newPage.waitForLoadState(); + + expect(newPage.url()).toContain("docs.example.com"); + await expect(newPage.getByRole("heading", { level: 1 })).toBeVisible(); + + // Original page still there + expect(page.url()).toContain("/resources"); + + await newPage.close(); +}); +``` + +### Intercept New Tab + +```typescript +test("prevent new tab for testing", async ({ page }) => { + await page.goto("/links"); + + // Remove target="_blank" to keep navigation in same tab + await page.evaluate(() => { + document.querySelectorAll('a[target="_blank"]').forEach((a) => { + a.removeAttribute("target"); + }); + }); + + // Now link opens in same tab + await page.getByRole("link", { name: "External Site" }).click(); + + // Can test the destination page + await expect(page).toHaveURL(/external-site\.com/); +}); +``` + +## OAuth Flows + +### Google OAuth Popup + +```typescript +test("Google OAuth login", async ({ page }) => { + await page.goto("/login"); + + const popupPromise = page.waitForEvent("popup"); + await page.getByRole("button", { name: "Sign in with Google" }).click(); + const popup = await popupPromise; + + await popup.waitForLoadState(); + + // Handle Google's OAuth flow + await popup.getByLabel("Email or phone").fill("test@gmail.com"); + await popup.getByRole("button", { name: "Next" }).click(); + + await popup.getByLabel("Enter your password").fill("password"); + await popup.getByRole("button", { name: "Next" }).click(); + + // Wait for redirect back and popup close + await popup.waitForEvent("close"); + + // Verify logged in on main page + await expect(page.getByText("Welcome, Test User")).toBeVisible(); +}); +``` + +### Mock OAuth (Recommended) + +```typescript +test("mock OAuth flow", async ({ page, context }) => { + // Mock the OAuth callback instead of real flow + await page.route("**/auth/callback**", async (route) => { + // Simulate successful OAuth + const url = new URL(route.request().url()); + url.searchParams.set("code", "mock-auth-code"); + await route.fulfill({ + status: 302, + headers: { Location: "/dashboard" }, + }); + }); + + // Mock token exchange + await page.route("**/api/auth/token", (route) => + route.fulfill({ + json: { + access_token: "mock-token", + user: { name: "Test User", email: "test@example.com" }, + }, + }), + ); + + await page.goto("/login"); + await page.getByRole("button", { name: "Sign in with Google" }).click(); + + // Should redirect to dashboard without actual OAuth + await expect(page).toHaveURL("/dashboard"); + await expect(page.getByText("Welcome, Test User")).toBeVisible(); +}); +``` + +### OAuth Fixture + +> **For comprehensive OAuth mocking patterns** (fixtures, multiple providers, SAML SSO), see [third-party.md](third-party.md#oauthsso-mocking). This section focuses on popup window handling mechanics for OAuth flows. + +## Multiple Windows + +### Test Across Multiple Windows + +```typescript +test("sync between windows", async ({ context }) => { + // Open two pages + const page1 = await context.newPage(); + const page2 = await context.newPage(); + + await page1.goto("/dashboard"); + await page2.goto("/dashboard"); + + // Make change in first window + await page1.getByRole("button", { name: "Add Item" }).click(); + await page1.getByLabel("Name").fill("New Item"); + await page1.getByRole("button", { name: "Save" }).click(); + + // Should sync to second window (if app supports real-time sync) + await expect(page2.getByText("New Item")).toBeVisible({ timeout: 10000 }); +}); +``` + +### Different Users in Different Windows + +> **For multi-user collaboration patterns** (admin/user interactions, real-time collaboration, role-based testing, concurrent actions), see [multi-user.md](multi-user.md). This file focuses on single-user scenarios with multiple tabs/windows/popups. + +## Tab Coordination + +### Switch Between Tabs + +```typescript +test("manage multiple tabs", async ({ context }) => { + const page1 = await context.newPage(); + await page1.goto("/editor"); + + const page2 = await context.newPage(); + await page2.goto("/preview"); + + // Edit in first tab + await page1.bringToFront(); + await page1.getByLabel("Content").fill("Hello World"); + + // Check preview in second tab + await page2.bringToFront(); + await page2.reload(); // If preview needs refresh + await expect(page2.getByText("Hello World")).toBeVisible(); +}); +``` + +### Close All Tabs Except One + +```typescript +test("cleanup tabs after test", async ({ context }) => { + const mainPage = await context.newPage(); + await mainPage.goto("/"); + + // Open several popups during test + for (let i = 0; i < 3; i++) { + const popup = await context.newPage(); + await popup.goto(`/popup/${i}`); + } + + // Close all except main page + for (const page of context.pages()) { + if (page !== mainPage) { + await page.close(); + } + } + + expect(context.pages()).toHaveLength(1); +}); +``` + +## Anti-Patterns to Avoid + +| Anti-Pattern | Problem | Solution | +| ----------------------- | ------------------------------ | ------------------------------------------ | +| Not waiting for popup | Race condition | Use `waitForEvent("popup")` before trigger | +| Testing real OAuth | Slow, flaky, needs credentials | Mock OAuth endpoints | +| Assuming popup opens | May be blocked | Handle both open and blocked cases | +| Not closing extra pages | Resource leak | Close pages in cleanup | + +## Related References + +- **Authentication**: See [fixtures-hooks.md](../core/fixtures-hooks.md) for auth patterns +- **Network**: See [network-advanced.md](network-advanced.md) for mocking OAuth diff --git a/.cursor/skills/playwright-testing/advanced/multi-user.md b/.cursor/skills/playwright-testing/advanced/multi-user.md new file mode 100644 index 0000000..301e55c --- /dev/null +++ b/.cursor/skills/playwright-testing/advanced/multi-user.md @@ -0,0 +1,393 @@ +# Multi-User & Collaboration Testing + +## Table of Contents + +1. [Multiple Browser Contexts](#multiple-browser-contexts) +2. [Real-Time Collaboration](#real-time-collaboration) +3. [Role-Based Testing](#role-based-testing) +4. [Concurrent Actions](#concurrent-actions) +5. [Chat & Messaging](#chat--messaging) + +## Multiple Browser Contexts + +### Two Users in Same Test + +```typescript +test("two users see each other's changes", async ({ browser }) => { + // Create two isolated contexts (like two browsers) + const userAContext = await browser.newContext(); + const userBContext = await browser.newContext(); + + const userAPage = await userAContext.newPage(); + const userBPage = await userBContext.newPage(); + + // Both users go to the same document + await userAPage.goto("/doc/shared-123"); + await userBPage.goto("/doc/shared-123"); + + // User A types + await userAPage.getByLabel("Content").fill("Hello from User A"); + + // User B should see the change + await expect(userBPage.getByText("Hello from User A")).toBeVisible(); + + // Cleanup + await userAContext.close(); + await userBContext.close(); +}); +``` + +### Multiple Users with Auth States + +```typescript +test("admin and user interaction", async ({ browser }) => { + // Load different auth states + const adminContext = await browser.newContext({ + storageState: ".auth/admin.json", + }); + const userContext = await browser.newContext({ + storageState: ".auth/user.json", + }); + + const adminPage = await adminContext.newPage(); + const userPage = await userContext.newPage(); + + // User submits request + await userPage.goto("/support"); + await userPage.getByLabel("Message").fill("Need help!"); + await userPage.getByRole("button", { name: "Submit" }).click(); + + // Admin sees and responds + await adminPage.goto("/admin/tickets"); + await expect(adminPage.getByText("Need help!")).toBeVisible(); + await adminPage.getByRole("button", { name: "Reply" }).click(); + await adminPage.getByLabel("Response").fill("How can I help?"); + await adminPage.getByRole("button", { name: "Send" }).click(); + + // User sees response + await expect(userPage.getByText("How can I help?")).toBeVisible(); + + await adminContext.close(); + await userContext.close(); +}); +``` + +### Multi-User Fixture + +```typescript +// fixtures/multi-user.fixture.ts +import { test as base, Browser, BrowserContext, Page } from "@playwright/test"; + +type UserSession = { + context: BrowserContext; + page: Page; +}; + +type MultiUserFixtures = { + createUser: (authState?: string) => Promise; +}; + +export const test = base.extend({ + createUser: async ({ browser }, use) => { + const sessions: UserSession[] = []; + + await use(async (authState) => { + const context = await browser.newContext({ + storageState: authState, + }); + const page = await context.newPage(); + sessions.push({ context, page }); + return { context, page }; + }); + + // Cleanup all sessions + for (const session of sessions) { + await session.context.close(); + } + }, +}); + +// Usage +test("3 users collaborate", async ({ createUser }) => { + const alice = await createUser(".auth/alice.json"); + const bob = await createUser(".auth/bob.json"); + const charlie = await createUser(".auth/charlie.json"); + + // All navigate to same room + await alice.page.goto("/room/123"); + await bob.page.goto("/room/123"); + await charlie.page.goto("/room/123"); + + // Test interactions... +}); +``` + +## Real-Time Collaboration + +### Collaborative Document + +```typescript +test("real-time collaborative editing", async ({ browser }) => { + const user1 = await browser.newContext(); + const user2 = await browser.newContext(); + + const page1 = await user1.newPage(); + const page2 = await user2.newPage(); + + await page1.goto("/docs/shared"); + await page2.goto("/docs/shared"); + + // User 1 types at the beginning + const editor1 = page1.getByRole("textbox"); + await editor1.click(); + await editor1.press("Home"); + await editor1.type("User 1: "); + + // User 2 types at the end + const editor2 = page2.getByRole("textbox"); + await editor2.click(); + await editor2.press("End"); + await editor2.type(" - User 2"); + + // Both should see combined result + await expect(page1.getByRole("textbox")).toContainText("User 1:"); + await expect(page1.getByRole("textbox")).toContainText("- User 2"); + await expect(page2.getByRole("textbox")).toContainText("User 1:"); + await expect(page2.getByRole("textbox")).toContainText("- User 2"); + + await user1.close(); + await user2.close(); +}); +``` + +### Cursor Presence + +```typescript +test("shows other user cursors", async ({ browser }) => { + const ctx1 = await browser.newContext(); + const ctx2 = await browser.newContext(); + + const page1 = await ctx1.newPage(); + const page2 = await ctx2.newPage(); + + // Mock to identify users + await page1.route("**/api/me", (route) => + route.fulfill({ json: { id: "user-1", name: "Alice" } }), + ); + await page2.route("**/api/me", (route) => + route.fulfill({ json: { id: "user-2", name: "Bob" } }), + ); + + await page1.goto("/whiteboard/123"); + await page2.goto("/whiteboard/123"); + + // Move cursor on page1 + await page1.mouse.move(200, 200); + + // Page2 should see Alice's cursor + await expect(page2.getByTestId("cursor-user-1")).toBeVisible(); + await expect(page2.getByText("Alice")).toBeVisible(); + + await ctx1.close(); + await ctx2.close(); +}); +``` + +## Role-Based Testing + +### Test RBAC + +```typescript +const roles = [ + { role: "admin", canDelete: true, canEdit: true, canView: true }, + { role: "editor", canDelete: false, canEdit: true, canView: true }, + { role: "viewer", canDelete: false, canEdit: false, canView: true }, +]; + +for (const { role, canDelete, canEdit, canView } of roles) { + test(`${role} permissions`, async ({ browser }) => { + const context = await browser.newContext({ + storageState: `.auth/${role}.json`, + }); + const page = await context.newPage(); + + await page.goto("/document/123"); + + // Check view permission + if (canView) { + await expect(page.getByTestId("content")).toBeVisible(); + } else { + await expect(page.getByText("Access denied")).toBeVisible(); + } + + // Check edit permission + const editButton = page.getByRole("button", { name: "Edit" }); + if (canEdit) { + await expect(editButton).toBeEnabled(); + } else { + await expect(editButton).toBeDisabled(); + } + + // Check delete permission + const deleteButton = page.getByRole("button", { name: "Delete" }); + if (canDelete) { + await expect(deleteButton).toBeVisible(); + } else { + await expect(deleteButton).toBeHidden(); + } + + await context.close(); + }); +} +``` + +### Permission Escalation Test + +```typescript +test("cannot access admin routes as user", async ({ browser }) => { + const userContext = await browser.newContext({ + storageState: ".auth/user.json", + }); + const page = await userContext.newPage(); + + // Try to access admin page directly + await page.goto("/admin/users"); + + // Should redirect or show error + await expect(page).not.toHaveURL("/admin/users"); + await expect(page.getByText("Access denied")).toBeVisible(); + + await userContext.close(); +}); +``` + +## Concurrent Actions + +### Race Condition Testing + +```typescript +test("handles concurrent edits", async ({ browser }) => { + const ctx1 = await browser.newContext(); + const ctx2 = await browser.newContext(); + + const page1 = await ctx1.newPage(); + const page2 = await ctx2.newPage(); + + await page1.goto("/item/123"); + await page2.goto("/item/123"); + + // Both click edit at the same time + await Promise.all([ + page1.getByRole("button", { name: "Edit" }).click(), + page2.getByRole("button", { name: "Edit" }).click(), + ]); + + // Both try to save different values + await page1.getByLabel("Name").fill("Value from User 1"); + await page2.getByLabel("Name").fill("Value from User 2"); + + await Promise.all([ + page1.getByRole("button", { name: "Save" }).click(), + page2.getByRole("button", { name: "Save" }).click(), + ]); + + // One should succeed, one should get conflict error + const page1HasConflict = await page1.getByText("Conflict").isVisible(); + const page2HasConflict = await page2.getByText("Conflict").isVisible(); + + // Exactly one should have conflict + expect(page1HasConflict || page2HasConflict).toBe(true); + expect(page1HasConflict && page2HasConflict).toBe(false); + + await ctx1.close(); + await ctx2.close(); +}); +``` + +### Optimistic Locking Test + +```typescript +test("optimistic locking prevents overwrites", async ({ browser }) => { + const ctx1 = await browser.newContext(); + const ctx2 = await browser.newContext(); + + const page1 = await ctx1.newPage(); + const page2 = await ctx2.newPage(); + + // Both load the same version + await page1.goto("/record/123"); + await page2.goto("/record/123"); + + // User 1 edits and saves first + await page1.getByRole("button", { name: "Edit" }).click(); + await page1.getByLabel("Value").fill("Updated by User 1"); + await page1.getByRole("button", { name: "Save" }).click(); + await expect(page1.getByText("Saved")).toBeVisible(); + + // User 2 tries to save with stale version + await page2.getByRole("button", { name: "Edit" }).click(); + await page2.getByLabel("Value").fill("Updated by User 2"); + await page2.getByRole("button", { name: "Save" }).click(); + + // Should fail with version conflict + await expect(page2.getByText("Someone else modified this")).toBeVisible(); + await expect(page2.getByRole("button", { name: "Reload" })).toBeVisible(); + + await ctx1.close(); + await ctx2.close(); +}); +``` + +## Chat & Messaging + +### Real-Time Chat + +```typescript +test("chat messages sync between users", async ({ browser }) => { + const aliceCtx = await browser.newContext(); + const bobCtx = await browser.newContext(); + + const alicePage = await aliceCtx.newPage(); + const bobPage = await bobCtx.newPage(); + + // Setup user identities + await alicePage.route("**/api/me", (r) => + r.fulfill({ json: { name: "Alice" } }), + ); + await bobPage.route("**/api/me", (r) => r.fulfill({ json: { name: "Bob" } })); + + await alicePage.goto("/chat/room-1"); + await bobPage.goto("/chat/room-1"); + + // Alice sends message + await alicePage.getByLabel("Message").fill("Hi Bob!"); + await alicePage.getByRole("button", { name: "Send" }).click(); + + // Bob sees it + await expect(bobPage.getByText("Alice: Hi Bob!")).toBeVisible(); + + // Bob replies + await bobPage.getByLabel("Message").fill("Hey Alice!"); + await bobPage.getByRole("button", { name: "Send" }).click(); + + // Alice sees it + await expect(alicePage.getByText("Bob: Hey Alice!")).toBeVisible(); + + await aliceCtx.close(); + await bobCtx.close(); +}); +``` + +## Anti-Patterns to Avoid + +| Anti-Pattern | Problem | Solution | +| ----------------------------- | ----------------------------- | ---------------------------- | +| Sharing context between users | State leaks, not isolated | Create separate contexts | +| Not closing contexts | Memory leak, browser overload | Always close in cleanup | +| Hardcoded timing for sync | Flaky tests | Use `expect().toBeVisible()` | +| Testing only single user | Misses collaboration bugs | Test multi-user scenarios | + +## Related References + +- **Authentication**: See [fixtures-hooks.md](../core/fixtures-hooks.md) for auth setup +- **WebSockets**: See [websockets.md](../browser-apis/websockets.md) for real-time mocking diff --git a/.cursor/skills/playwright-testing/advanced/network-advanced.md b/.cursor/skills/playwright-testing/advanced/network-advanced.md new file mode 100644 index 0000000..fa017fe --- /dev/null +++ b/.cursor/skills/playwright-testing/advanced/network-advanced.md @@ -0,0 +1,452 @@ +# Advanced Network Interception + +## Table of Contents + +1. [Request Modification](#request-modification) +2. [GraphQL Mocking](#graphql-mocking) +3. [HAR Recording & Playback](#har-recording--playback) +4. [Conditional Mocking](#conditional-mocking) +5. [Network Throttling](#network-throttling) + +## Request Modification + +### Modify Request Headers + +```typescript +test("add auth header to requests", async ({ page }) => { + await page.route("**/api/**", (route) => { + const headers = { + ...route.request().headers(), + Authorization: "Bearer test-token", + "X-Test-Header": "test-value", + }; + route.continue({ headers }); + }); + + await page.goto("/dashboard"); +}); +``` + +### Modify Request Body + +```typescript +test("modify POST body", async ({ page }) => { + await page.route("**/api/orders", async (route) => { + if (route.request().method() === "POST") { + const postData = route.request().postDataJSON(); + + // Add test metadata + const modifiedData = { + ...postData, + testMode: true, + testTimestamp: Date.now(), + }; + + await route.continue({ + postData: JSON.stringify(modifiedData), + }); + } else { + await route.continue(); + } + }); + + await page.goto("/checkout"); + await page.getByRole("button", { name: "Place Order" }).click(); +}); +``` + +### Transform Response + +```typescript +test("modify API response", async ({ page }) => { + await page.route("**/api/products", async (route) => { + // Fetch real response + const response = await route.fetch(); + const json = await response.json(); + + // Modify response + const modified = json.map((product: any) => ({ + ...product, + price: product.price * 0.9, // 10% discount + testMode: true, + })); + + await route.fulfill({ + response, + json: modified, + }); + }); + + await page.goto("/products"); +}); +``` + +## GraphQL Mocking + +### Mock by Operation Name + +```typescript +test("mock GraphQL query", async ({ page }) => { + await page.route("**/graphql", async (route) => { + const postData = route.request().postDataJSON(); + + if (postData.operationName === "GetUser") { + return route.fulfill({ + json: { + data: { + user: { + id: "1", + name: "Test User", + email: "test@example.com", + }, + }, + }, + }); + } + + if (postData.operationName === "GetProducts") { + return route.fulfill({ + json: { + data: { + products: [ + { id: "1", name: "Product A", price: 29.99 }, + { id: "2", name: "Product B", price: 49.99 }, + ], + }, + }, + }); + } + + // Pass through unmocked operations + return route.continue(); + }); + + await page.goto("/dashboard"); +}); +``` + +### GraphQL Mock Fixture + +```typescript +// fixtures/graphql.fixture.ts +type GraphQLMock = { + operation: string; + variables?: Record; + response: { data?: any; errors?: any[] }; +}; + +type GraphQLFixtures = { + mockGraphQL: (mocks: GraphQLMock[]) => Promise; +}; + +export const test = base.extend({ + mockGraphQL: async ({ page }, use) => { + await use(async (mocks) => { + await page.route("**/graphql", async (route) => { + const postData = route.request().postDataJSON(); + + const mock = mocks.find((m) => { + if (m.operation !== postData.operationName) return false; + + // Optionally match variables + if (m.variables) { + return ( + JSON.stringify(m.variables) === JSON.stringify(postData.variables) + ); + } + return true; + }); + + if (mock) { + return route.fulfill({ json: mock.response }); + } + + return route.continue(); + }); + }); + }, +}); + +// Usage +test("dashboard with mocked GraphQL", async ({ page, mockGraphQL }) => { + await mockGraphQL([ + { + operation: "GetDashboardStats", + response: { + data: { stats: { users: 100, revenue: 50000 } }, + }, + }, + { + operation: "GetUser", + variables: { id: "1" }, + response: { + data: { user: { id: "1", name: "John" } }, + }, + }, + ]); + + await page.goto("/dashboard"); + await expect(page.getByText("100 users")).toBeVisible(); +}); +``` + +### Mock GraphQL Mutations + +```typescript +test("mock GraphQL mutation", async ({ page }) => { + await page.route("**/graphql", async (route) => { + const postData = route.request().postDataJSON(); + + if (postData.operationName === "CreateOrder") { + const { input } = postData.variables; + + return route.fulfill({ + json: { + data: { + createOrder: { + id: "order-123", + status: "PENDING", + items: input.items, + total: input.items.reduce( + (sum: number, item: any) => sum + item.price * item.quantity, + 0, + ), + }, + }, + }, + }); + } + + return route.continue(); + }); + + await page.goto("/checkout"); + await page.getByRole("button", { name: "Place Order" }).click(); + + await expect(page.getByText("Order #order-123")).toBeVisible(); +}); +``` + +## HAR Recording & Playback + +### Record HAR File + +```typescript +// Record network traffic +test("record HAR", async ({ page, context }) => { + // Start recording + await context.routeFromHAR("./recordings/checkout.har", { + update: true, // Create/update HAR file + url: "**/api/**", + }); + + await page.goto("/checkout"); + await page.getByRole("button", { name: "Place Order" }).click(); + + // HAR file is saved automatically +}); +``` + +### Playback HAR File + +```typescript +// Use recorded HAR for offline testing +test("playback HAR", async ({ page, context }) => { + await context.routeFromHAR("./recordings/checkout.har", { + url: "**/api/**", + update: false, // Don't update, just playback + }); + + await page.goto("/checkout"); + + // All API calls served from HAR file + await expect(page.getByText("Order confirmed")).toBeVisible(); +}); +``` + +### HAR with Fallback + +```typescript +test("HAR with live fallback", async ({ page, context }) => { + await context.routeFromHAR("./recordings/api.har", { + url: "**/api/**", + update: false, + notFound: "fallback", // Use real network if not in HAR + }); + + await page.goto("/dashboard"); +}); +``` + +## Conditional Mocking + +### Mock Based on Request Body + +```typescript +test("conditional mock by body", async ({ page }) => { + await page.route("**/api/search", async (route) => { + const body = route.request().postDataJSON(); + + if (body.query === "error") { + return route.fulfill({ + status: 500, + json: { error: "Search failed" }, + }); + } + + if (body.query === "empty") { + return route.fulfill({ + json: { results: [] }, + }); + } + + // Default response + return route.fulfill({ + json: { + results: [{ id: 1, title: `Result for: ${body.query}` }], + }, + }); + }); + + await page.goto("/search"); + + // Test different scenarios + await page.getByLabel("Search").fill("error"); + await page.getByLabel("Search").press("Enter"); + await expect(page.getByText("Search failed")).toBeVisible(); +}); +``` + +### Mock Nth Request + +```typescript +test("different response on retry", async ({ page }) => { + let callCount = 0; + + await page.route("**/api/status", (route) => { + callCount++; + + if (callCount < 3) { + return route.fulfill({ + status: 503, + json: { error: "Service unavailable" }, + }); + } + + // Succeed on 3rd attempt + return route.fulfill({ + json: { status: "ok" }, + }); + }); + + await page.goto("/dashboard"); + + // App should retry and eventually succeed + await expect(page.getByText("Connected")).toBeVisible(); +}); +``` + +### Mock with Delay + +```typescript +test("slow network simulation", async ({ page }) => { + await page.route("**/api/data", async (route) => { + // Simulate 2 second delay + await new Promise((resolve) => setTimeout(resolve, 2000)); + + return route.fulfill({ + json: { data: "loaded" }, + }); + }); + + await page.goto("/dashboard"); + + // Loading state should appear + await expect(page.getByText("Loading...")).toBeVisible(); + + // Then data appears + await expect(page.getByText("loaded")).toBeVisible(); +}); +``` + +## Network Throttling + +### Slow 3G Simulation + +```typescript +test("slow network experience", async ({ page, context }) => { + // Create CDP session for network throttling + const client = await context.newCDPSession(page); + + await client.send("Network.emulateNetworkConditions", { + offline: false, + downloadThroughput: (500 * 1024) / 8, // 500 Kbps + uploadThroughput: (500 * 1024) / 8, + latency: 400, // 400ms + }); + + await page.goto("/"); + + // Test loading states appear + await expect(page.getByTestId("skeleton-loader")).toBeVisible(); +}); +``` + +### Offline Mode + +Use `context.setOffline(true/false)` to simulate network connectivity changes. + +> **For comprehensive offline testing patterns:** +> +> - **Network failure simulation** (error recovery, graceful degradation): See [error-testing.md](error-testing.md#offline-testing) +> - **Offline-first/PWA testing** (service workers, caching, background sync): See [service-workers.md](service-workers.md#offline-testing) + +### Network Throttling Fixture + +```typescript +// fixtures/network.fixture.ts +type NetworkCondition = "slow3g" | "fast3g" | "offline"; + +const conditions = { + slow3g: { downloadThroughput: 50000, uploadThroughput: 50000, latency: 2000 }, + fast3g: { downloadThroughput: 180000, uploadThroughput: 75000, latency: 150 }, +}; + +type NetworkFixtures = { + setNetworkCondition: (condition: NetworkCondition) => Promise; +}; + +export const test = base.extend({ + setNetworkCondition: async ({ page, context }, use) => { + const client = await context.newCDPSession(page); + + await use(async (condition) => { + if (condition === "offline") { + await context.setOffline(true); + } else { + await client.send("Network.emulateNetworkConditions", { + offline: false, + ...conditions[condition], + }); + } + }); + + // Reset + await context.setOffline(false); + }, +}); +``` + +## Anti-Patterns to Avoid + +| Anti-Pattern | Problem | Solution | +| ------------------------ | ------------------------------ | -------------------------------- | +| Mocking all requests | Tests don't reflect reality | Mock only what's necessary | +| No cleanup of routes | Routes persist across tests | Use fixtures with cleanup | +| Ignoring request method | Mock applies to wrong requests | Check `route.request().method()` | +| Hardcoded mock responses | Brittle, hard to maintain | Use factories for mock data | + +## Related References + +- **Basic Mocking**: See [test-suite-structure.md](../core/test-suite-structure.md) for simple mocking +- **WebSockets**: See [websockets.md](../browser-apis/websockets.md) for real-time mocking diff --git a/.cursor/skills/playwright-testing/advanced/third-party.md b/.cursor/skills/playwright-testing/advanced/third-party.md new file mode 100644 index 0000000..acf8ab8 --- /dev/null +++ b/.cursor/skills/playwright-testing/advanced/third-party.md @@ -0,0 +1,464 @@ +# Third-Party Service Mocking + +## Table of Contents + +1. [OAuth/SSO Mocking](#oauthsso-mocking) +2. [Payment Gateway Mocking](#payment-gateway-mocking) +3. [Email Verification](#email-verification) +4. [SMS Verification](#sms-verification) +5. [Analytics & Tracking](#analytics--tracking) + +## OAuth/SSO Mocking + +### Mock Google OAuth + +```typescript +test("Google OAuth login", async ({ page }) => { + // Mock the OAuth callback + await page.route("**/auth/google/callback**", (route) => { + const url = new URL(route.request().url()); + // Simulate successful OAuth by redirecting with token + route.fulfill({ + status: 302, + headers: { + Location: "/dashboard?token=mock-jwt-token", + }, + }); + }); + + // Mock the token verification endpoint + await page.route("**/api/auth/verify", (route) => + route.fulfill({ + json: { + valid: true, + user: { + id: "123", + email: "test@gmail.com", + name: "Test User", + }, + }, + }), + ); + + await page.goto("/login"); + await page.getByRole("button", { name: "Sign in with Google" }).click(); + + await expect(page.getByText("Welcome, Test User")).toBeVisible(); +}); +``` + +### OAuth Fixture + +```typescript +// fixtures/oauth.fixture.ts +type OAuthProvider = "google" | "github" | "microsoft"; + +type OAuthUser = { + id: string; + email: string; + name: string; + avatar?: string; +}; + +type OAuthFixtures = { + mockOAuth: (provider: OAuthProvider, user: OAuthUser) => Promise; +}; + +export const test = base.extend({ + mockOAuth: async ({ page }, use) => { + await use(async (provider, user) => { + // Mock callback redirect + await page.route(`**/auth/${provider}/callback**`, (route) => + route.fulfill({ + status: 302, + headers: { Location: `/auth/success?provider=${provider}` }, + }), + ); + + // Mock session/user endpoint + await page.route("**/api/auth/session", (route) => + route.fulfill({ + json: { user, provider, authenticated: true }, + }), + ); + + // Mock user info endpoint + await page.route("**/api/me", (route) => route.fulfill({ json: user })); + }); + }, +}); + +// Usage +test("login with GitHub", async ({ page, mockOAuth }) => { + await mockOAuth("github", { + id: "gh-123", + email: "dev@github.com", + name: "GitHub User", + }); + + await page.goto("/login"); + await page.getByRole("button", { name: "Sign in with GitHub" }).click(); + + await expect(page.getByText("Welcome, GitHub User")).toBeVisible(); +}); +``` + +### Mock SAML SSO + +```typescript +test("SAML SSO login", async ({ page }) => { + // Mock SAML assertion consumer service + await page.route("**/saml/acs", async (route) => { + route.fulfill({ + status: 302, + headers: { + Location: "/dashboard", + "Set-Cookie": "session=mock-saml-session; Path=/; HttpOnly", + }, + }); + }); + + // Mock session validation + await page.route("**/api/session", (route) => + route.fulfill({ + json: { + user: { email: "user@company.com", name: "SSO User" }, + provider: "saml", + }, + }), + ); + + await page.goto("/login"); + await page.getByRole("button", { name: "SSO Login" }).click(); + + await expect(page).toHaveURL("/dashboard"); +}); +``` + +## Payment Gateway Mocking + +### Mock Stripe + +```typescript +test("Stripe checkout", async ({ page }) => { + // Mock Stripe.js + await page.addInitScript(() => { + (window as any).Stripe = () => ({ + elements: () => ({ + create: () => ({ + mount: () => {}, + on: () => {}, + destroy: () => {}, + }), + }), + confirmCardPayment: async () => ({ + paymentIntent: { status: "succeeded", id: "pi_mock_123" }, + }), + createPaymentMethod: async () => ({ + paymentMethod: { id: "pm_mock_123" }, + }), + }); + }); + + // Mock backend payment endpoint + await page.route("**/api/create-payment-intent", (route) => + route.fulfill({ + json: { clientSecret: "pi_mock_123_secret_mock" }, + }), + ); + + await page.route("**/api/confirm-payment", (route) => + route.fulfill({ + json: { success: true, orderId: "order-123" }, + }), + ); + + await page.goto("/checkout"); + await page.getByRole("button", { name: "Pay $99.99" }).click(); + + await expect(page.getByText("Payment successful")).toBeVisible(); +}); +``` + +### Mock PayPal + +```typescript +test("PayPal checkout", async ({ page }) => { + // Mock PayPal SDK + await page.addInitScript(() => { + (window as any).paypal = { + Buttons: () => ({ + render: () => Promise.resolve(), + isEligible: () => true, + }), + FUNDING: { PAYPAL: "paypal", CARD: "card" }, + }; + }); + + // Mock PayPal order creation + await page.route("**/api/paypal/create-order", (route) => + route.fulfill({ + json: { orderId: "PAYPAL-ORDER-123" }, + }), + ); + + // Mock PayPal capture + await page.route("**/api/paypal/capture", (route) => + route.fulfill({ + json: { success: true, transactionId: "TXN-123" }, + }), + ); + + await page.goto("/checkout"); + + // Simulate PayPal approval callback + await page.evaluate(() => { + (window as any).onPayPalApprove?.({ orderID: "PAYPAL-ORDER-123" }); + }); + + await expect(page.getByText("Order confirmed")).toBeVisible(); +}); +``` + +### Payment Fixture + +```typescript +// fixtures/payment.fixture.ts +type PaymentFixtures = { + mockStripe: (options?: { failPayment?: boolean }) => Promise; +}; + +export const test = base.extend({ + mockStripe: async ({ page }, use) => { + await use(async (options = {}) => { + await page.addInitScript( + ([shouldFail]) => { + (window as any).Stripe = () => ({ + elements: () => ({ + create: () => ({ + mount: () => {}, + on: (event: string, handler: Function) => { + if (event === "ready") setTimeout(handler, 100); + }, + destroy: () => {}, + }), + }), + confirmCardPayment: async () => { + if (shouldFail) { + return { error: { message: "Card declined" } }; + } + return { paymentIntent: { status: "succeeded" } }; + }, + }); + }, + [options.failPayment], + ); + }); + }, +}); + +// Usage +test("handles declined card", async ({ page, mockStripe }) => { + await mockStripe({ failPayment: true }); + + await page.goto("/checkout"); + await page.getByRole("button", { name: "Pay" }).click(); + + await expect(page.getByText("Card declined")).toBeVisible(); +}); +``` + +## Email Verification + +### Mock Email API + +```typescript +test("email verification flow", async ({ page, request }) => { + let verificationToken: string; + + // Capture the verification email + await page.route("**/api/send-verification", async (route) => { + const body = route.request().postDataJSON(); + verificationToken = `mock-token-${Date.now()}`; + + // Don't actually send email, just store token + route.fulfill({ + json: { sent: true, messageId: "msg-123" }, + }); + }); + + // Mock token verification + await page.route("**/api/verify-email**", (route) => { + const url = new URL(route.request().url()); + const token = url.searchParams.get("token"); + + if (token === verificationToken) { + route.fulfill({ json: { verified: true } }); + } else { + route.fulfill({ status: 400, json: { error: "Invalid token" } }); + } + }); + + await page.goto("/signup"); + await page.getByLabel("Email").fill("test@example.com"); + await page.getByRole("button", { name: "Sign Up" }).click(); + + await expect(page.getByText("Check your email")).toBeVisible(); + + // Simulate clicking email link + await page.goto(`/verify?token=${verificationToken}`); + + await expect(page.getByText("Email verified")).toBeVisible(); +}); +``` + +### Use Mailinator/Temp Mail + +```typescript +// fixtures/email.fixture.ts +type EmailFixtures = { + getVerificationEmail: (inbox: string) => Promise<{ link: string }>; +}; + +export const test = base.extend({ + getVerificationEmail: async ({ request }, use) => { + await use(async (inbox) => { + // Poll Mailinator API for new email + const response = await request.get( + `https://api.mailinator.com/v2/domains/public/inboxes/${inbox}`, + { + headers: { + Authorization: `Bearer ${process.env.MAILINATOR_API_KEY}`, + }, + }, + ); + + const messages = await response.json(); + const latest = messages.msgs[0]; + + // Get full message + const msgResponse = await request.get( + `https://api.mailinator.com/v2/domains/public/inboxes/${inbox}/messages/${latest.id}`, + { + headers: { + Authorization: `Bearer ${process.env.MAILINATOR_API_KEY}`, + }, + }, + ); + + const message = await msgResponse.json(); + + // Extract verification link from HTML + const linkMatch = message.parts[0].body.match( + /href="([^"]*verify[^"]*)"/, + ); + return { link: linkMatch?.[1] || "" }; + }); + }, +}); +``` + +## SMS Verification + +### Mock SMS API + +```typescript +test("SMS verification", async ({ page }) => { + let smsCode: string; + + // Capture SMS send + await page.route("**/api/send-sms", (route) => { + smsCode = Math.random().toString().slice(2, 8); // 6-digit code + + route.fulfill({ + json: { sent: true, messageId: "sms-123" }, + }); + }); + + // Mock code verification + await page.route("**/api/verify-sms", (route) => { + const body = route.request().postDataJSON(); + + if (body.code === smsCode) { + route.fulfill({ json: { verified: true } }); + } else { + route.fulfill({ status: 400, json: { error: "Invalid code" } }); + } + }); + + await page.goto("/verify-phone"); + await page.getByLabel("Phone").fill("+1234567890"); + await page.getByRole("button", { name: "Send Code" }).click(); + + // Enter the code + await page.getByLabel("Verification Code").fill(smsCode); + await page.getByRole("button", { name: "Verify" }).click(); + + await expect(page.getByText("Phone verified")).toBeVisible(); +}); +``` + +## Analytics & Tracking + +### Block Analytics in Tests + +```typescript +test.beforeEach(async ({ page }) => { + // Block all analytics/tracking + await page.route( + /google-analytics|googletagmanager|facebook|hotjar|segment|mixpanel|amplitude/, + (route) => route.abort(), + ); +}); +``` + +### Mock Analytics for Verification + +```typescript +test("tracks purchase event", async ({ page }) => { + const analyticsEvents: any[] = []; + + // Capture analytics calls + await page.route("**/api/analytics/**", (route) => { + analyticsEvents.push(route.request().postDataJSON()); + route.fulfill({ status: 200 }); + }); + + // Mock analytics SDK + await page.addInitScript(() => { + (window as any).analytics = { + track: (event: string, props: any) => { + fetch("/api/analytics/track", { + method: "POST", + body: JSON.stringify({ event, props }), + }); + }, + }; + }); + + await page.goto("/checkout"); + await page.getByRole("button", { name: "Complete Purchase" }).click(); + + // Verify analytics event was sent + expect(analyticsEvents).toContainEqual( + expect.objectContaining({ + event: "Purchase Completed", + props: expect.objectContaining({ amount: expect.any(Number) }), + }), + ); +}); +``` + +## Anti-Patterns to Avoid + +| Anti-Pattern | Problem | Solution | +| ------------------------- | ------------------------------ | ----------------------- | +| Using real OAuth in tests | Slow, needs credentials, flaky | Mock OAuth endpoints | +| Real payment processing | Charges real money, slow | Use test mode or mock | +| Waiting for real emails | Very slow, unreliable | Mock email API | +| Not mocking analytics | Pollutes analytics data | Block or mock analytics | + +## Related References + +- **Network Mocking**: See [network-advanced.md](network-advanced.md) for route patterns +- **Authentication**: See [fixtures-hooks.md](../core/fixtures-hooks.md) for auth patterns diff --git a/.cursor/skills/playwright-testing/architecture/pom-vs-fixtures.md b/.cursor/skills/playwright-testing/architecture/pom-vs-fixtures.md new file mode 100644 index 0000000..eafb06f --- /dev/null +++ b/.cursor/skills/playwright-testing/architecture/pom-vs-fixtures.md @@ -0,0 +1,363 @@ +# Organizing Reusable Test Code + +## Table of Contents + +1. [Pattern Comparison](#pattern-comparison) +2. [Selection Flowchart](#selection-flowchart) +3. [Page Objects](#page-objects) +4. [Custom Fixtures](#custom-fixtures) +5. [Helper Functions](#helper-functions) +6. [Combined Project Structure](#combined-project-structure) +7. [Anti-Patterns](#anti-patterns) + +Use all three patterns together. Most projects benefit from a hybrid approach: + +- **Page objects** for UI interaction (pages/components with 5+ interactions) +- **Custom fixtures** for test infrastructure (auth state, database, API clients, anything with lifecycle) +- **Helper functions** for stateless utilities (generate data, format values, simple waits) + +If only using one pattern, choose **custom fixtures** — they handle setup/teardown, compose well, and Playwright is built around them. + +## Pattern Comparison + +| Aspect | Page Objects | Custom Fixtures | Helper Functions | +|---|---|---|---| +| **Purpose** | Encapsulate UI interactions | Provide resources with setup/teardown | Stateless utilities | +| **Lifecycle** | Manual (constructor/methods) | Built-in (`use()` with automatic teardown) | None | +| **Composability** | Constructor injection or fixture wiring | Depend on other fixtures | Call other functions | +| **Best for** | Pages with many reused interactions | Resources needing setup AND teardown | Simple logic with no side effects | + +## Selection Flowchart + +```text +What kind of reusable code? +| ++-- Interacts with browser page/component? +| | +| +-- Has 5+ interactions (fill, click, navigate, assert)? +| | +-- YES: Used in 3+ test files? +| | | +-- YES --> PAGE OBJECT +| | | +-- NO --> Inline or small helper +| | +-- NO --> HELPER FUNCTION +| | +| +-- Needs setup before AND cleanup after test? +| +-- YES --> CUSTOM FIXTURE +| +-- NO --> PAGE OBJECT method or HELPER +| ++-- Manages resource with lifecycle (create/destroy)? +| +-- Examples: auth state, DB connection, API client, test user +| +-- YES --> CUSTOM FIXTURE (always) +| ++-- Stateless utility? (no browser, no side effects) +| +-- Examples: random email, format date, build URL, parse response +| +-- YES --> HELPER FUNCTION +| ++-- Not sure? + +-- Start with HELPER FUNCTION + +-- Promote to PAGE OBJECT when interactions grow + +-- Promote to FIXTURE when lifecycle needed +``` + +## Page Objects + +Best for pages/components with 5+ interactions appearing in 3+ test files. + +```typescript +// page-objects/booking.page.ts +import { type Page, type Locator, expect } from '@playwright/test'; + +export class BookingPage { + readonly page: Page; + readonly dateField: Locator; + readonly guestCount: Locator; + readonly roomType: Locator; + readonly reserveBtn: Locator; + readonly totalPrice: Locator; + + constructor(page: Page) { + this.page = page; + this.dateField = page.getByLabel('Check-in date'); + this.guestCount = page.getByLabel('Guests'); + this.roomType = page.getByLabel('Room type'); + this.reserveBtn = page.getByRole('button', { name: 'Reserve' }); + this.totalPrice = page.getByTestId('total-price'); + } + + async goto() { + await this.page.goto('/booking'); + } + + async fillDetails(opts: { date: string; guests: number; room: string }) { + await this.dateField.fill(opts.date); + await this.guestCount.fill(String(opts.guests)); + await this.roomType.selectOption(opts.room); + } + + async reserve() { + await this.reserveBtn.click(); + await this.page.waitForURL('**/confirmation'); + } + + async expectPrice(amount: string) { + await expect(this.totalPrice).toHaveText(amount); + } +} +``` + +```typescript +// tests/booking/reservation.spec.ts +import { test, expect } from '@playwright/test'; +import { BookingPage } from '../page-objects/booking.page'; + +test('complete reservation with standard room', async ({ page }) => { + const booking = new BookingPage(page); + await booking.goto(); + await booking.fillDetails({ date: '2026-03-15', guests: 2, room: 'standard' }); + await booking.reserve(); + await expect(page.getByText('Reservation confirmed')).toBeVisible(); +}); +``` + +**Page object principles:** +- One class per logical page/component, not per URL +- Constructor takes `Page` +- Locators as `readonly` properties in constructor +- Methods represent user intent (`reserve`, `fillDetails`), not low-level clicks +- Navigation methods (`goto`) belong on the page object + +## Custom Fixtures + +Best for resources needing setup before and teardown after tests — auth state, database connections, API clients, test users. + +```typescript +// fixtures/base.fixture.ts +import { test as base, expect } from '@playwright/test'; +import { BookingPage } from '../page-objects/booking.page'; +import { generateMember } from '../helpers/data'; + +type Fixtures = { + bookingPage: BookingPage; + member: { email: string; password: string; id: string }; + loggedInPage: import('@playwright/test').Page; +}; + +export const test = base.extend({ + bookingPage: async ({ page }, use) => { + await use(new BookingPage(page)); + }, + + member: async ({ request }, use) => { + const data = generateMember(); + const res = await request.post('/api/test/members', { data }); + const member = await res.json(); + await use(member); + await request.delete(`/api/test/members/${member.id}`); + }, + + loggedInPage: async ({ page, member }, use) => { + await page.goto('/login'); + await page.getByLabel('Email').fill(member.email); + await page.getByLabel('Password').fill(member.password); + await page.getByRole('button', { name: 'Sign in' }).click(); + await expect(page).toHaveURL('/dashboard'); + await use(page); + }, +}); + +export { expect } from '@playwright/test'; +``` + +```typescript +// tests/dashboard/overview.spec.ts +import { test, expect } from '../../fixtures/base.fixture'; + +test('member sees dashboard widgets', async ({ loggedInPage }) => { + await expect(loggedInPage.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); + await expect(loggedInPage.getByTestId('stats-widget')).toBeVisible(); +}); + +test('new member sees welcome prompt', async ({ loggedInPage, member }) => { + await expect(loggedInPage.getByText(`Welcome, ${member.email}`)).toBeVisible(); +}); +``` + +**Fixture principles:** +- Use `test.extend()` — never module-level variables +- `use()` callback separates setup from teardown +- Teardown runs even if test fails +- Fixtures compose: one can depend on another +- Fixtures are lazy: created only when requested +- Wrap page objects in fixtures for lifecycle management + +## Helper Functions + +Best for stateless utilities — generating test data, formatting values, building URLs, parsing responses. + +```typescript +// helpers/data.ts +import { randomUUID } from 'node:crypto'; + +export function generateEmail(prefix = 'user'): string { + return `${prefix}-${Date.now()}-${randomUUID().slice(0, 8)}@test.local`; +} + +export function generateMember(overrides: Partial = {}): Member { + return { + email: generateEmail(), + password: 'SecurePass456!', + name: 'Test Member', + ...overrides, + }; +} + +interface Member { + email: string; + password: string; + name: string; +} + +export function formatPrice(cents: number): string { + return `$${(cents / 100).toFixed(2)}`; +} +``` + +```typescript +// helpers/assertions.ts +import { type Page, expect } from '@playwright/test'; + +export async function expectNotification(page: Page, message: string): Promise { + const notification = page.getByRole('alert').filter({ hasText: message }); + await expect(notification).toBeVisible(); + await expect(notification).toBeHidden({ timeout: 10000 }); +} +``` + +```typescript +// tests/settings/account.spec.ts +import { test, expect } from '@playwright/test'; +import { generateEmail } from '../../helpers/data'; +import { expectNotification } from '../../helpers/assertions'; + +test('update account email', async ({ page }) => { + const newEmail = generateEmail('updated'); + await page.goto('/settings/account'); + await page.getByLabel('Email').fill(newEmail); + await page.getByRole('button', { name: 'Save' }).click(); + await expectNotification(page, 'Account updated'); + await expect(page.getByLabel('Email')).toHaveValue(newEmail); +}); +``` + +**Helper principles:** +- Pure functions with no side effects +- No browser state — take `page` as parameter if needed +- Promote to fixture if setup/teardown needed +- Promote to page object if many page interactions grow +- Keep small and focused + +## Combined Project Structure + +```text +tests/ ++-- fixtures/ +| +-- auth.fixture.ts +| +-- db.fixture.ts +| +-- base.fixture.ts ++-- page-objects/ +| +-- login.page.ts +| +-- booking.page.ts +| +-- components/ +| +-- data-table.component.ts ++-- helpers/ +| +-- data.ts +| +-- assertions.ts ++-- e2e/ +| +-- auth/ +| | +-- login.spec.ts +| +-- booking/ +| +-- reservation.spec.ts +playwright.config.ts +``` + +**Layer responsibilities:** + +| Layer | Pattern | Responsibility | +|---|---|---| +| **Test file** | `test()` | Describes behavior, orchestrates layers | +| **Fixtures** | `test.extend()` | Resource lifecycle — setup, provide, teardown | +| **Page objects** | Classes | UI interaction — navigation, actions, locators | +| **Helpers** | Functions | Utilities — data generation, formatting, assertions | + +## Anti-Patterns + +### Page object managing resources + +```typescript +// BAD: page object handling API calls and database +class LoginPage { + async createUser() { /* API call */ } + async deleteUser() { /* API call */ } + async signIn(email: string, password: string) { /* UI */ } +} +``` + +Resource lifecycle belongs in fixtures where teardown is guaranteed. Keep only `signIn` in the page object. + +### Locator-only page objects + +```typescript +// BAD: no methods, just locators +class LoginPage { + emailInput = this.page.getByLabel('Email'); + passwordInput = this.page.getByLabel('Password'); + submitBtn = this.page.getByRole('button', { name: 'Sign in' }); + constructor(private page: Page) {} +} +``` + +Add intent-revealing methods or skip the page object entirely. + +### Monolithic fixtures + +```typescript +// BAD: one fixture doing everything +test.extend({ + everything: async ({ page, request }, use) => { + const user = await createUser(request); + const products = await seedProducts(request, 50); + await setupPayment(request, user.id); + await page.goto('/dashboard'); + await use({ user, products, page }); + // massive teardown... + }, +}); +``` + +Break into small, composable fixtures. Each fixture does one thing. + +### Helpers with side effects + +```typescript +// BAD: module-level state +let createdUserId: string; + +export async function createTestUser(request: APIRequestContext) { + const res = await request.post('/api/users', { data: { email: 'test@example.com' } }); + const user = await res.json(); + createdUserId = user.id; // shared across tests! + return user; +} +``` + +Module-level state leaks between parallel tests. If it has side effects and needs cleanup, make it a fixture. + +### Over-abstracting simple operations + +```typescript +// BAD: helper for one-liner +export async function clickButton(page: Page, name: string) { + await page.getByRole('button', { name }).click(); +} +``` + +Only abstract when there is real duplication (3+ usages) or complexity (5+ interactions). diff --git a/.cursor/skills/playwright-testing/architecture/test-architecture.md b/.cursor/skills/playwright-testing/architecture/test-architecture.md new file mode 100644 index 0000000..28b6f6c --- /dev/null +++ b/.cursor/skills/playwright-testing/architecture/test-architecture.md @@ -0,0 +1,369 @@ +# Choosing Test Types: E2E, Component, or API + +## Table of Contents + +1. [Decision Matrix](#decision-matrix) +2. [API Tests](#api-tests) +3. [Component Tests](#component-tests) +4. [E2E Tests](#e2e-tests) +5. [Layering Test Types](#layering-test-types) +6. [Common Mistakes](#common-mistakes) +7. [Related](#related) + +> **When to use**: Deciding which test type to write for a feature. Ask: "What's the cheapest test that gives confidence this works?" + +## Decision Matrix + +| Scenario | Recommended Type | Rationale | +| --------------------------- | ---------------- | --------------------------------------------- | +| Login / auth flow | E2E | Cross-page, cookies, redirects, session state | +| Form submission | Component | Isolated validation logic, error states | +| CRUD operations | API | Data integrity matters more than UI | +| Search with results UI | Component + API | API for query logic; component for rendering | +| Cross-page navigation | E2E | Routing, history, deep linking | +| API error handling | API | Status codes, error shapes, edge cases | +| UI error feedback | Component | Toast, banner, inline error rendering | +| Accessibility | Component | ARIA roles, keyboard nav per-component | +| Responsive layout | Component | Viewport-specific rendering without full app | +| API contract validation | API | Response shapes, headers, auth | +| WebSocket/real-time | E2E | Requires full browser environment | +| Payment / checkout | E2E | Multi-step, third-party iframes | +| Onboarding wizard | E2E | Multi-step, state persists across pages | +| Widget behavior | Component | Toggle, accordion, date picker, modal | +| Permissions / authorization | API | Role-based access is backend logic | + +## API Tests + +**Ideal for**: + +- CRUD operations (create, read, update, delete) +- Input validation and error responses (400, 422) +- Permission and authorization checks +- Data integrity and business rules +- API contract verification +- Edge cases expensive to reproduce through UI +- Test data setup/teardown for E2E tests + +**Avoid for**: + +- Testing how errors display to users +- Browser-specific behavior (cookies, redirects) +- Visual layout or responsive design +- Flows requiring JavaScript execution or DOM interaction +- Third-party iframe interactions + +```typescript +import { test, expect } from "@playwright/test"; + +test.describe("Products API", () => { + let token: string; + + test.beforeAll(async ({ request }) => { + const res = await request.post("/api/auth/token", { + data: { email: "manager@shop.io", password: "mgr-secret" }, + }); + token = (await res.json()).accessToken; + }); + + test("creates product with valid payload", async ({ request }) => { + const res = await request.post("/api/products", { + headers: { Authorization: `Bearer ${token}` }, + data: { name: "Widget Pro", sku: "WGT-100", price: 29.99 }, + }); + + expect(res.status()).toBe(201); + const product = await res.json(); + expect(product).toMatchObject({ name: "Widget Pro", sku: "WGT-100" }); + expect(product).toHaveProperty("id"); + }); + + test("rejects duplicate SKU with 409", async ({ request }) => { + const res = await request.post("/api/products", { + headers: { Authorization: `Bearer ${token}` }, + data: { name: "Duplicate", sku: "WGT-100", price: 19.99 }, + }); + + expect(res.status()).toBe(409); + expect((await res.json()).message).toContain("already exists"); + }); + + test("returns 422 for missing required fields", async ({ request }) => { + const res = await request.post("/api/products", { + headers: { Authorization: `Bearer ${token}` }, + data: { name: "Incomplete" }, + }); + + expect(res.status()).toBe(422); + const err = await res.json(); + expect(err.errors).toContainEqual( + expect.objectContaining({ field: "sku" }) + ); + }); + + test("staff role cannot delete products", async ({ request }) => { + const staffLogin = await request.post("/api/auth/token", { + data: { email: "staff@shop.io", password: "staff-pass" }, + }); + const staffToken = (await staffLogin.json()).accessToken; + + const res = await request.delete("/api/products/123", { + headers: { Authorization: `Bearer ${staffToken}` }, + }); + + expect(res.status()).toBe(403); + }); + + test("lists products with pagination", async ({ request }) => { + const res = await request.get("/api/products", { + headers: { Authorization: `Bearer ${token}` }, + params: { page: "1", limit: "20" }, + }); + + expect(res.status()).toBe(200); + const body = await res.json(); + expect(body.items).toBeInstanceOf(Array); + expect(body.items.length).toBeLessThanOrEqual(20); + expect(body).toHaveProperty("totalCount"); + }); +}); +``` + +## Component Tests + +**Ideal for**: + +- Form validation (required fields, format rules, error messages) +- Interactive widgets (modals, dropdowns, accordions, date pickers) +- Conditional rendering (show/hide, loading states, empty states) +- Accessibility per-component (ARIA attributes, keyboard navigation) +- Responsive layout at different viewports +- Visual states (hover, focus, disabled, selected) + +**Avoid for**: + +- Testing routing or navigation between pages +- Flows requiring real cookies, sessions, or server-side state +- Data persistence or API contract validation +- Third-party iframe interactions +- Anything requiring multiple pages or browser contexts + +```typescript +import { test, expect } from "@playwright/experimental-ct-react"; +import { ContactForm } from "../src/components/ContactForm"; + +test.describe("ContactForm component", () => { + test("displays validation errors on empty submit", async ({ mount }) => { + const component = await mount( {}} />); + + await component.getByRole("button", { name: "Send message" }).click(); + + await expect(component.getByText("Name is required")).toBeVisible(); + await expect(component.getByText("Email is required")).toBeVisible(); + }); + + test("rejects malformed email", async ({ mount }) => { + const component = await mount( {}} />); + + await component.getByLabel("Name").fill("Alex"); + await component.getByLabel("Email").fill("invalid-email"); + await component.getByLabel("Message").fill("Hello"); + await component.getByRole("button", { name: "Send message" }).click(); + + await expect(component.getByText("Enter a valid email")).toBeVisible(); + }); + + test("invokes onSubmit with form data", async ({ mount }) => { + const submissions: Array<{ name: string; email: string; message: string }> = + []; + const component = await mount( + submissions.push(data)} /> + ); + + await component.getByLabel("Name").fill("Alex"); + await component.getByLabel("Email").fill("alex@company.org"); + await component.getByLabel("Message").fill("Inquiry about pricing"); + await component.getByRole("button", { name: "Send message" }).click(); + + expect(submissions).toHaveLength(1); + expect(submissions[0]).toEqual({ + name: "Alex", + email: "alex@company.org", + message: "Inquiry about pricing", + }); + }); + + test("disables button during submission", async ({ mount }) => { + const component = await mount( + {}} submitting={true} /> + ); + + await expect( + component.getByRole("button", { name: "Sending..." }) + ).toBeDisabled(); + }); + + test("associates labels with inputs for accessibility", async ({ mount }) => { + const component = await mount( {}} />); + + await expect( + component.getByRole("textbox", { name: "Name" }) + ).toBeVisible(); + await expect( + component.getByRole("textbox", { name: "Email" }) + ).toBeVisible(); + }); +}); +``` + +## E2E Tests + +**Ideal for**: + +- Critical user flows that generate revenue (checkout, signup) +- Authentication flows (login, SSO, MFA, password reset) +- Multi-page workflows where state carries across navigation +- Flows involving third-party iframes (payment widgets) +- Smoke tests validating the entire stack +- Real-time collaboration requiring multiple browser contexts + +**Avoid for**: + +- Testing every form validation permutation +- CRUD operations where UI is a thin wrapper +- Verifying individual component states +- Testing API response shapes or error codes +- Responsive layout at every breakpoint +- Edge cases that only affect the backend + +```typescript +import { test, expect } from "@playwright/test"; + +test.describe("subscription flow", () => { + test.beforeEach(async ({ page }) => { + await page.request.post("/api/test/seed-account", { + data: { plan: "free", email: "subscriber@demo.io" }, + }); + await page.goto("/account/upgrade"); + }); + + test("upgrades to premium plan", async ({ page }) => { + await test.step("select plan", async () => { + await expect( + page.getByRole("heading", { name: "Choose Your Plan" }) + ).toBeVisible(); + await page.getByRole("button", { name: "Select Premium" }).click(); + }); + + await test.step("enter billing details", async () => { + await page.getByLabel("Cardholder name").fill("Sam Johnson"); + await page.getByLabel("Billing address").fill("456 Oak Ave"); + await page.getByLabel("City").fill("Seattle"); + await page.getByRole("combobox", { name: "State" }).selectOption("WA"); + await page.getByLabel("Postal code").fill("98101"); + await page.getByRole("button", { name: "Continue" }).click(); + }); + + await test.step("complete payment", async () => { + const paymentFrame = page.frameLocator('iframe[title="Secure Payment"]'); + await paymentFrame.getByLabel("Card number").fill("5555555555554444"); + await paymentFrame.getByLabel("Expiry").fill("09/29"); + await paymentFrame.getByLabel("CVV").fill("456"); + await page.getByRole("button", { name: "Subscribe now" }).click(); + }); + + await test.step("verify success", async () => { + await page.waitForURL("**/account/subscription/success**"); + await expect( + page.getByRole("heading", { name: "Welcome to Premium" }) + ).toBeVisible(); + await expect(page.getByText(/Subscription #\d+/)).toBeVisible(); + }); + }); +}); +``` + +## Layering Test Types + +Effective test suites combine all three types. Example for an "inventory management" feature: + +### API Layer (60% of tests) + +Cover every backend logic permutation. Cheap to run and maintain. + +``` +tests/api/inventory.spec.ts + - creates item with valid data (201) + - rejects duplicate SKU (409) + - rejects invalid quantity format (422) + - rejects missing required fields (422) + - warehouse-staff cannot delete items (403) + - unauthenticated request returns 401 + - lists items with pagination + - filters items by category + - updates item stock level + - archives an item + - prevents archiving items with pending orders +``` + +### Component Layer (30% of tests) + +Cover every visual state and interaction. + +``` +tests/components/InventoryForm.spec.tsx + - shows validation errors on empty submit + - shows inline error for invalid SKU format + - disables submit while saving + - calls onSubmit with form data + - resets form after successful save + +tests/components/InventoryTable.spec.tsx + - renders item rows from props + - shows empty state when no items + - handles archive confirmation modal + - sorts by column header click + - shows stock level badges with correct colors +``` + +### E2E Layer (10% of tests) + +Cover only critical paths proving full stack works. + +``` +tests/e2e/inventory.spec.ts + - manager creates item and sees it in list + - manager updates item stock level + - warehouse-staff cannot access admin settings +``` + +### Execution Profile + +For this feature: + +- **11 API tests** — ~2 seconds total, no browser +- **10 component tests** — ~5 seconds total, real browser but no server +- **3 E2E tests** — ~15 seconds total, full stack + +Total: 24 tests, ~22 seconds. API tests catch most regressions. Component tests catch UI bugs. E2E tests prove wiring works. If E2E fails but API and component pass, the problem is in integration (routing, state management, API client). + +## Common Mistakes + +| Anti-Pattern | Problem | Better Approach | +| ----------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------------- | +| E2E for every validation rule | 30-second browser test for something API covers in 200ms | API test for validation, one component test for error display | +| No API tests, all E2E | Slow suite, flaky from UI timing, hard to diagnose | API tests for data/logic, E2E for critical paths only | +| Component tests mocking everything | Tests pass but app broken because mocks drift | Mock only external boundaries; API tests verify real contracts | +| Same assertion in API, component, AND E2E | Triple maintenance cost | Each layer tests what it uniquely verifies | +| E2E creating test data via UI | 2-minute test where 90 seconds is setup | Seed via API in `beforeEach`, test actual flow | +| Testing third-party behavior | Testing that Stripe validates cards (Stripe's job) | Mock Stripe; trust their contract | +| Skipping API layer | Can't tell if bug is frontend or backend | API tests isolate backend; component tests isolate frontend | +| One giant E2E for entire feature | 5-minute test failing somewhere with no clear cause | Focused E2E per critical path; use `test.step()` | + +## Related + +- [test-suite-structure.md](../core/test-suite-structure.md) — file structure and naming +- [api-testing.md](../testing-patterns/api-testing.md) — Playwright's `request` API for HTTP testing +- [component-testing.md](../testing-patterns/component-testing.md) — setting up component tests +- [authentication.md](../advanced/authentication.md) — auth flow patterns with `storageState` +- [when-to-mock.md](when-to-mock.md) — when to mock vs hit real services +- [pom-vs-fixtures.md](pom-vs-fixtures.md) — organizing shared test logic diff --git a/.cursor/skills/playwright-testing/architecture/when-to-mock.md b/.cursor/skills/playwright-testing/architecture/when-to-mock.md new file mode 100644 index 0000000..d5d5705 --- /dev/null +++ b/.cursor/skills/playwright-testing/architecture/when-to-mock.md @@ -0,0 +1,383 @@ +# Mocking Strategy: Real vs Mock Services + +## Table of Contents + +1. [Core Principle](#core-principle) +2. [Decision Matrix](#decision-matrix) +3. [Decision Flowchart](#decision-flowchart) +4. [Mocking Techniques](#mocking-techniques) +5. [Real Service Strategies](#real-service-strategies) +6. [Hybrid Approach: Fixture-Based Mock Control](#hybrid-approach-fixture-based-mock-control) +7. [Validating Mock Accuracy](#validating-mock-accuracy) +8. [Anti-Patterns](#anti-patterns) + +> **When to use**: Deciding whether to mock API calls, intercept network requests, or hit real services in Playwright tests. + +## Core Principle + +**Mock at the boundary, test your stack end-to-end.** Mock third-party services you don't own (payment gateways, email providers, OAuth). Never mock your own frontend-to-backend communication. Tests should prove YOUR code works, not that third-party APIs are available. + +## Decision Matrix + +| Scenario | Mock? | Strategy | +| --- | --- | --- | +| Your own REST/GraphQL API | Never | Hit real API against staging or local dev | +| Your database (through your API) | Never | Seed via API or fixtures | +| Authentication (your auth system) | Mostly no | Use `storageState` to skip login in most tests | +| Stripe / payment gateway | Always | `route.fulfill()` with expected responses | +| SendGrid / email service | Always | Mock the API call, verify request payload | +| OAuth providers (Google, GitHub) | Always | Mock token exchange, test your callback handler | +| Analytics (Segment, Mixpanel) | Always | `route.abort()` or `route.fulfill()` | +| Maps / geocoding APIs | Always | Mock with static responses | +| Feature flags (LaunchDarkly) | Usually | Mock to force specific flag states | +| CDN / static assets | Never | Let them load normally | +| Flaky external dependency | CI: mock, local: real | Conditional mocking based on environment | +| Slow external dependency | Dev: mock, nightly: real | Separate test projects in config | + +## Decision Flowchart + +```text +Is this service part of YOUR codebase? +├── YES → Do NOT mock. Test the real integration. +│ ├── Is it slow? → Optimize the service, not the test. +│ └── Is it flaky? → Fix the service. Flaky infra is a bug. +└── NO → It's a third-party service. + ├── Is it paid per call? → ALWAYS mock. + ├── Is it rate-limited? → ALWAYS mock. + ├── Is it slow or unreliable? → ALWAYS mock. + └── Is it a complex multi-step flow? → Mock with HAR recording. +``` + +## Mocking Techniques + +### Blocking Unwanted Requests + +Block third-party scripts that slow tests and add no coverage: + +```typescript +test.beforeEach(async ({ page }) => { + await page.route('**/{analytics,tracking,segment,hotjar}.{com,io}/**', (route) => { + route.abort(); + }); +}); + +test('dashboard renders without tracking scripts', async ({ page }) => { + await page.goto('/dashboard'); + await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); +}); +``` + +### Full Mock (route.fulfill) + +Completely replace a third-party API response: + +```typescript +test('order flow with mocked payment service', async ({ page }) => { + await page.route('**/api/charge', (route) => { + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + transactionId: 'txn_mock_abc', + status: 'completed', + }), + }); + }); + + await page.goto('/order/confirm'); + await page.getByRole('button', { name: 'Complete Purchase' }).click(); + await expect(page.getByText('Order confirmed')).toBeVisible(); +}); + +test('display error on payment decline', async ({ page }) => { + await page.route('**/api/charge', (route) => { + route.fulfill({ + status: 402, + contentType: 'application/json', + body: JSON.stringify({ + error: { code: 'insufficient_funds', message: 'Card declined.' }, + }), + }); + }); + + await page.goto('/order/confirm'); + await page.getByRole('button', { name: 'Complete Purchase' }).click(); + await expect(page.getByRole('alert')).toContainText('Card declined'); +}); +``` + +### Partial Mock (Modify Responses) + +Let the real API call happen but tweak the response: + +```typescript +test('display low inventory warning', async ({ page }) => { + await page.route('**/api/inventory/*', async (route) => { + const response = await route.fetch(); + const data = await response.json(); + + data.quantity = 1; + data.lowStock = true; + + await route.fulfill({ + response, + body: JSON.stringify(data), + }); + }); + + await page.goto('/products/widget-pro'); + await expect(page.getByText('Only 1 remaining')).toBeVisible(); +}); + +test('inject test notification into real response', async ({ page }) => { + await page.route('**/api/alerts', async (route) => { + const response = await route.fetch(); + const data = await response.json(); + + data.items.push({ + id: 'test-alert', + text: 'Report generated', + category: 'info', + }); + + await route.fulfill({ + response, + body: JSON.stringify(data), + }); + }); + + await page.goto('/home'); + await expect(page.getByText('Report generated')).toBeVisible(); +}); +``` + +### Record and Replay (HAR Files) + +For complex API sequences (OAuth flows, multi-step wizards): + +**Recording:** + +```typescript +test('capture API traffic for admin panel', async ({ page }) => { + await page.routeFromHAR('tests/fixtures/admin-panel.har', { + url: '**/api/**', + update: true, + }); + + await page.goto('/admin'); + await page.getByRole('tab', { name: 'Reports' }).click(); + await page.getByRole('tab', { name: 'Settings' }).click(); +}); +``` + +**Replaying:** + +```typescript +test('admin panel loads with recorded data', async ({ page }) => { + await page.routeFromHAR('tests/fixtures/admin-panel.har', { + url: '**/api/**', + update: false, + }); + + await page.goto('/admin'); + await expect(page.getByRole('heading', { name: 'Reports' })).toBeVisible(); +}); +``` + +**HAR maintenance:** + +- Record against a known-good staging environment +- Commit `.har` files to version control +- Re-record when APIs change +- Scope HAR to specific URL patterns + +## Real Service Strategies + +### Local Dev Server + +```typescript +// playwright.config.ts +export default defineConfig({ + webServer: { + command: 'npm run dev', + url: 'http://localhost:3000', + reuseExistingServer: !process.env.CI, + timeout: 30_000, + }, + use: { + baseURL: 'http://localhost:3000', + }, +}); +``` + +### Staging Environment + +```typescript +// playwright.config.ts +export default defineConfig({ + use: { + baseURL: process.env.CI + ? 'https://staging.example.com' + : 'http://localhost:3000', + }, +}); +``` + +### Test Containers + +```typescript +// playwright.config.ts +export default defineConfig({ + webServer: { + command: 'docker compose -f docker-compose.test.yml up --wait', + url: 'http://localhost:3000/health', + reuseExistingServer: !process.env.CI, + timeout: 120_000, + }, + globalTeardown: './tests/global-teardown.ts', +}); +``` + +```typescript +// tests/global-teardown.ts +import { execSync } from 'child_process'; + +export default function globalTeardown() { + if (process.env.CI) { + execSync('docker compose -f docker-compose.test.yml down -v'); + } +} +``` + +## Hybrid Approach: Fixture-Based Mock Control + +Create fixtures that let individual tests opt into mocking specific services: + +```typescript +// tests/fixtures/service-mocks.ts +import { test as base } from '@playwright/test'; + +type MockConfig = { + mockPayments: boolean; + mockNotifications: boolean; + mockAnalytics: boolean; +}; + +export const test = base.extend({ + mockPayments: [true, { option: true }], + mockNotifications: [true, { option: true }], + mockAnalytics: [true, { option: true }], + + page: async ({ page, mockPayments, mockNotifications, mockAnalytics }, use) => { + if (mockPayments) { + await page.route('**/api/billing/**', (route) => { + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ status: 'paid', id: 'inv_mock_789' }), + }); + }); + } + + if (mockNotifications) { + await page.route('**/api/notify', (route) => { + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ delivered: true }), + }); + }); + } + + if (mockAnalytics) { + await page.route('**/{segment,mixpanel,amplitude}.**/**', (route) => { + route.abort(); + }); + } + + await use(page); + }, +}); + +export { expect } from '@playwright/test'; +``` + +```typescript +// tests/billing.spec.ts +import { test, expect } from './fixtures/service-mocks'; + +test('subscription renewal sends notification', async ({ page }) => { + await page.goto('/account/billing'); + await page.getByRole('button', { name: 'Renew Now' }).click(); + await expect(page.getByText('Subscription renewed')).toBeVisible(); +}); + +test.describe('integration suite', () => { + test.use({ mockPayments: false }); + + test('real billing flow against test gateway', async ({ page }) => { + await page.goto('/account/billing'); + await page.getByRole('button', { name: 'Renew Now' }).click(); + await expect(page.getByText('Subscription renewed')).toBeVisible(); + }); +}); +``` + +### Environment-Based Test Projects + +```typescript +// playwright.config.ts +export default defineConfig({ + projects: [ + { + name: 'ci-fast', + testMatch: '**/*.spec.ts', + use: { baseURL: 'http://localhost:3000' }, + }, + { + name: 'nightly-full', + testMatch: '**/*.integration.spec.ts', + use: { baseURL: 'https://staging.example.com' }, + timeout: 120_000, + }, + ], +}); +``` + +## Validating Mock Accuracy + +Guard against mock drift from real APIs: + +```typescript +test.describe('contract validation', () => { + test('billing mock matches real API shape', async ({ request }) => { + const realResponse = await request.post('/api/billing/charge', { + data: { amount: 5000, currency: 'usd' }, + }); + const realBody = await realResponse.json(); + + const mockBody = { + status: 'paid', + id: 'inv_mock_789', + }; + + expect(Object.keys(mockBody).sort()).toEqual(Object.keys(realBody).sort()); + + for (const key of Object.keys(mockBody)) { + expect(typeof mockBody[key]).toBe(typeof realBody[key]); + } + }); +}); +``` + +## Anti-Patterns + +| Don't Do This | Problem | Do This Instead | +| --- | --- | --- | +| Mock your own API | Tests pass, app breaks. Zero integration coverage. | Hit your real API. Mock only third-party services. | +| Mock everything for speed | You test a fiction. Frontend and backend may be incompatible. | Mock only external boundaries. | +| Never mock anything | Tests are slow, flaky, fail when third parties have outages. | Mock third-party services. | +| Use outdated mocks | Mock returns different shape than real API. | Run contract validation tests. Re-record HAR files regularly. | +| Mock with `page.evaluate()` to stub fetch | Fragile, doesn't survive navigation. | Use `page.route()` which intercepts at network layer. | +| Copy-paste mocks across files | One API change requires updating many files. | Centralize mocks in fixtures. | +| Block all network and whitelist | Extremely brittle. Every new endpoint requires update. | Allow all by default. Selectively mock third-party services. | diff --git a/.cursor/skills/playwright-testing/browser-apis/browser-apis.md b/.cursor/skills/playwright-testing/browser-apis/browser-apis.md new file mode 100644 index 0000000..cc4c269 --- /dev/null +++ b/.cursor/skills/playwright-testing/browser-apis/browser-apis.md @@ -0,0 +1,391 @@ +# Browser APIs: Geolocation, Permissions & More + +## Table of Contents + +1. [Geolocation](#geolocation) +2. [Permissions](#permissions) +3. [Clipboard](#clipboard) +4. [Notifications](#notifications) +5. [Camera & Microphone](#camera--microphone) + +## Geolocation + +### Mock Location + +```typescript +test("shows nearby stores", async ({ context }) => { + // Grant permission and set location + await context.grantPermissions(["geolocation"]); + await context.setGeolocation({ latitude: 37.7749, longitude: -122.4194 }); // San Francisco + + const page = await context.newPage(); + await page.goto("/store-finder"); + await page.getByRole("button", { name: "Find Nearby" }).click(); + + await expect(page.getByText("San Francisco")).toBeVisible(); +}); +``` + +### Geolocation Fixture + +```typescript +// fixtures/geolocation.fixture.ts +import { test as base } from "@playwright/test"; + +type Coordinates = { latitude: number; longitude: number; accuracy?: number }; + +type GeoFixtures = { + setLocation: (coords: Coordinates) => Promise; +}; + +export const test = base.extend({ + setLocation: async ({ context }, use) => { + await context.grantPermissions(["geolocation"]); + + await use(async (coords) => { + await context.setGeolocation({ + latitude: coords.latitude, + longitude: coords.longitude, + accuracy: coords.accuracy ?? 100, + }); + }); + }, +}); + +// Usage +test("delivery zone check", async ({ page, setLocation }) => { + await setLocation({ latitude: 40.7128, longitude: -74.006 }); // NYC + + await page.goto("/delivery"); + + await expect(page.getByText("Delivery available")).toBeVisible(); +}); +``` + +### Test Location Changes + +```typescript +test("tracks location updates", async ({ context }) => { + await context.grantPermissions(["geolocation"]); + + const page = await context.newPage(); + await page.goto("/tracking"); + + // Initial location + await context.setGeolocation({ latitude: 37.7749, longitude: -122.4194 }); + await page.getByRole("button", { name: "Start Tracking" }).click(); + + await expect(page.getByTestId("location")).toContainText("37.7749"); + + // Move to new location + await context.setGeolocation({ latitude: 37.8044, longitude: -122.2712 }); + + // Trigger location update + await page.evaluate(() => { + navigator.geolocation.getCurrentPosition(() => {}); + }); + + await expect(page.getByTestId("location")).toContainText("37.8044"); +}); +``` + +### Test Geolocation Denial + +```typescript +test("handles location denied", async ({ browser }) => { + // Create context without geolocation permission + const context = await browser.newContext({ + permissions: [], // No permissions + }); + + const page = await context.newPage(); + await page.goto("/store-finder"); + await page.getByRole("button", { name: "Find Nearby" }).click(); + + await expect(page.getByText("Location access denied")).toBeVisible(); + await expect(page.getByLabel("Enter ZIP code")).toBeVisible(); + + await context.close(); +}); +``` + +## Permissions + +### Grant Permissions + +```typescript +test("notifications with permission", async ({ context }) => { + await context.grantPermissions(["notifications"]); + + const page = await context.newPage(); + await page.goto("/alerts"); + + // Notification API should work + const permission = await page.evaluate(() => Notification.permission); + expect(permission).toBe("granted"); +}); +``` + +### Test Permission Denied + +```typescript +test("handles notification permission denied", async ({ browser }) => { + const context = await browser.newContext({ + permissions: [], // Deny all + }); + + const page = await context.newPage(); + await page.goto("/notifications"); + + await page.getByRole("button", { name: "Enable Notifications" }).click(); + + await expect(page.getByText("Please enable notifications")).toBeVisible(); + + await context.close(); +}); +``` + +### Multiple Permissions + +```typescript +test("video call with permissions", async ({ context }) => { + await context.grantPermissions(["camera", "microphone", "notifications"]); + + const page = await context.newPage(); + await page.goto("/video-call"); + + // All permissions should be granted + const permissions = await page.evaluate(async () => ({ + camera: await navigator.permissions.query({ + name: "camera" as PermissionName, + }), + microphone: await navigator.permissions.query({ + name: "microphone" as PermissionName, + }), + })); + + expect(permissions.camera.state).toBe("granted"); + expect(permissions.microphone.state).toBe("granted"); +}); +``` + +## Clipboard + +### Test Copy to Clipboard + +```typescript +test("copy button works", async ({ page, context }) => { + // Grant clipboard permissions + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + + await page.goto("/share"); + + await page.getByRole("button", { name: "Copy Link" }).click(); + + // Read clipboard content + const clipboardContent = await page.evaluate(() => + navigator.clipboard.readText(), + ); + + expect(clipboardContent).toContain("https://example.com/share/"); +}); +``` + +### Test Paste from Clipboard + +```typescript +test("paste from clipboard", async ({ page, context }) => { + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + + await page.goto("/editor"); + + // Write to clipboard + await page.evaluate(() => navigator.clipboard.writeText("Pasted content")); + + // Trigger paste + await page.getByLabel("Content").focus(); + await page.keyboard.press("Control+V"); + + await expect(page.getByLabel("Content")).toHaveValue("Pasted content"); +}); +``` + +### Clipboard Fixture + +```typescript +// fixtures/clipboard.fixture.ts +import { test as base } from "@playwright/test"; + +type ClipboardFixtures = { + clipboard: { + write: (text: string) => Promise; + read: () => Promise; + }; +}; + +export const test = base.extend({ + clipboard: async ({ page, context }, use) => { + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + + await use({ + write: async (text) => { + await page.evaluate((t) => navigator.clipboard.writeText(t), text); + }, + read: async () => { + return page.evaluate(() => navigator.clipboard.readText()); + }, + }); + }, +}); +``` + +## Notifications + +### Mock Notification API + +```typescript +test("shows browser notification", async ({ page }) => { + const notifications: any[] = []; + + // Mock Notification constructor + await page.addInitScript(() => { + (window as any).__notifications = []; + (window as any).Notification = class { + constructor(title: string, options?: NotificationOptions) { + (window as any).__notifications.push({ title, ...options }); + } + static permission = "granted"; + static requestPermission = async () => "granted"; + }; + }); + + await page.goto("/alerts"); + await page.getByRole("button", { name: "Notify Me" }).click(); + + // Check notification was created + const created = await page.evaluate(() => (window as any).__notifications); + expect(created).toHaveLength(1); + expect(created[0].title).toBe("New Alert"); +}); +``` + +### Test Notification Click + +```typescript +test("notification click handler", async ({ page }) => { + await page.addInitScript(() => { + (window as any).Notification = class { + onclick: (() => void) | null = null; + constructor(title: string) { + // Simulate click after creation + setTimeout(() => this.onclick?.(), 100); + } + static permission = "granted"; + static requestPermission = async () => "granted"; + }; + }); + + await page.goto("/messages"); + await page.evaluate(() => { + new Notification("New Message"); + }); + + // Should navigate to messages when notification clicked + await expect(page).toHaveURL(/\/messages/); +}); +``` + +## Camera & Microphone + +### Mock Media Devices + +```typescript +test("video preview works", async ({ page, context }) => { + await context.grantPermissions(["camera"]); + + // Mock getUserMedia + await page.addInitScript(() => { + navigator.mediaDevices.getUserMedia = async () => { + const canvas = document.createElement("canvas"); + canvas.width = 640; + canvas.height = 480; + return canvas.captureStream(); + }; + }); + + await page.goto("/video-settings"); + await page.getByRole("button", { name: "Start Camera" }).click(); + + await expect(page.getByTestId("video-preview")).toBeVisible(); +}); +``` + +### Test Media Device Selection + +```typescript +test("switch camera", async ({ page }) => { + await page.addInitScript(() => { + navigator.mediaDevices.enumerateDevices = async () => + [ + { + deviceId: "cam1", + kind: "videoinput", + label: "Front Camera", + groupId: "1", + }, + { + deviceId: "cam2", + kind: "videoinput", + label: "Back Camera", + groupId: "2", + }, + ] as MediaDeviceInfo[]; + + navigator.mediaDevices.getUserMedia = async () => { + const canvas = document.createElement("canvas"); + return canvas.captureStream(); + }; + }); + + await page.goto("/camera"); + + // Should show camera options + await expect(page.getByRole("combobox", { name: "Camera" })).toBeVisible(); + await expect(page.getByText("Front Camera")).toBeVisible(); + await expect(page.getByText("Back Camera")).toBeVisible(); +}); +``` + +### Test Media Errors + +```typescript +test("handles camera access error", async ({ page }) => { + await page.addInitScript(() => { + navigator.mediaDevices.getUserMedia = async () => { + throw new DOMException("Permission denied", "NotAllowedError"); + }; + }); + + await page.goto("/video-call"); + await page.getByRole("button", { name: "Join Call" }).click(); + + await expect(page.getByText("Camera access denied")).toBeVisible(); + await expect( + page.getByRole("button", { name: "Join Audio Only" }), + ).toBeVisible(); +}); +``` + +## Anti-Patterns to Avoid + +| Anti-Pattern | Problem | Solution | +| ----------------------------- | --------------------------------- | ----------------------------------- | +| Not granting permissions | Tests fail with permission errors | Use `context.grantPermissions()` | +| Testing real geolocation | Flaky, environment-dependent | Mock with `setGeolocation()` | +| Not testing permission denial | Misses error handling | Test both granted and denied states | +| Using real camera/mic | CI has no devices | Mock `getUserMedia` | + +## Related References + +- **Fixtures**: See [fixtures-hooks.md](../core/fixtures-hooks.md) for context fixtures +- **Mobile**: See [mobile-testing.md](../advanced/mobile-testing.md) for device emulation diff --git a/.cursor/skills/playwright-testing/browser-apis/iframes.md b/.cursor/skills/playwright-testing/browser-apis/iframes.md new file mode 100644 index 0000000..155cc1c --- /dev/null +++ b/.cursor/skills/playwright-testing/browser-apis/iframes.md @@ -0,0 +1,403 @@ +# iFrame Testing + +## Table of Contents + +1. [Basic iFrame Access](#basic-iframe-access) +2. [Cross-Origin iFrames](#cross-origin-iframes) +3. [Nested iFrames](#nested-iframes) +4. [Dynamic iFrames](#dynamic-iframes) +5. [iFrame Navigation](#iframe-navigation) +6. [Common Patterns](#common-patterns) + +## Basic iFrame Access + +### Using frameLocator + +```typescript +// Access iframe by selector +const frame = page.frameLocator("iframe#payment"); +await frame.getByRole("button", { name: "Pay" }).click(); + +// Access by name attribute +const namedFrame = page.frameLocator('iframe[name="checkout"]'); +await namedFrame.getByLabel("Card number").fill("4242424242424242"); + +// Access by title +const titledFrame = page.frameLocator('iframe[title="Payment Form"]'); + +// Access by src (partial match) +const srcFrame = page.frameLocator('iframe[src*="stripe.com"]'); +``` + +### Frame vs FrameLocator + +```typescript +// frameLocator - for locator-based operations (recommended) +const frameLocator = page.frameLocator("#my-iframe"); +await frameLocator.getByRole("button").click(); + +// frame() - for Frame object operations (navigation, evaluation) +const frame = page.frame({ name: "my-frame" }); +if (frame) { + await frame.goto("https://example.com"); + const title = await frame.title(); +} + +// Get all frames +const frames = page.frames(); +for (const f of frames) { + console.log("Frame URL:", f.url()); +} +``` + +### Waiting for iFrame Content + +```typescript +// Wait for iframe to load +const frame = page.frameLocator("#dynamic-iframe"); + +// Wait for element inside iframe +await expect(frame.getByRole("heading")).toBeVisible({ timeout: 10000 }); + +// Wait for iframe src to change +await page.waitForFunction(() => { + const iframe = document.querySelector("iframe#my-frame") as HTMLIFrameElement; + return iframe?.src.includes("loaded"); +}); +``` + +## Cross-Origin iFrames + +### Accessing Cross-Origin Content + +```typescript +// Cross-origin iframes work seamlessly with frameLocator +const thirdPartyFrame = page.frameLocator('iframe[src*="third-party.com"]'); + +// Interact with elements inside cross-origin iframe +await thirdPartyFrame.getByRole("textbox").fill("test@example.com"); +await thirdPartyFrame.getByRole("button", { name: "Submit" }).click(); + +// Wait for cross-origin iframe to be ready +await expect(thirdPartyFrame.locator("body")).toBeVisible(); +``` + +### Payment Provider iFrames (Stripe, PayPal) + +```typescript +test("Stripe payment iframe", async ({ page }) => { + await page.goto("/checkout"); + + // Stripe uses multiple iframes for each field + const cardFrame = page + .frameLocator('iframe[name*="__privateStripeFrame"]') + .first(); + + // Wait for Stripe to initialize + await expect(cardFrame.locator('[placeholder="Card number"]')).toBeVisible({ + timeout: 15000, + }); + + // Fill card details + await cardFrame + .locator('[placeholder="Card number"]') + .fill("4242424242424242"); + await cardFrame.locator('[placeholder="MM / YY"]').fill("12/30"); + await cardFrame.locator('[placeholder="CVC"]').fill("123"); +}); +``` + +### Handling OAuth in iFrames + +```typescript +test("OAuth iframe flow", async ({ page }) => { + await page.goto("/login"); + await page.getByRole("button", { name: "Sign in with Google" }).click(); + + // If OAuth opens in iframe instead of popup + const oauthFrame = page.frameLocator('iframe[src*="accounts.google.com"]'); + + // Wait for OAuth form + await expect(oauthFrame.getByLabel("Email")).toBeVisible({ timeout: 10000 }); + await oauthFrame.getByLabel("Email").fill("test@gmail.com"); +}); +``` + +## Nested iFrames + +### Accessing Nested Frames + +```typescript +// Parent iframe contains child iframe +const parentFrame = page.frameLocator("#outer-frame"); +const childFrame = parentFrame.frameLocator("#inner-frame"); + +// Interact with deeply nested content +await childFrame.getByRole("button", { name: "Submit" }).click(); + +// Multiple levels of nesting +const level1 = page.frameLocator("#level1"); +const level2 = level1.frameLocator("#level2"); +const level3 = level2.frameLocator("#level3"); +await level3.getByText("Deep content").click(); +``` + +### Finding Elements Across Frame Hierarchy + +```typescript +// Helper to search all frames for an element +async function findInAnyFrame( + page: Page, + selector: string, +): Promise { + // Check main page first + const mainCount = await page.locator(selector).count(); + if (mainCount > 0) return page.locator(selector); + + // Check all frames + for (const frame of page.frames()) { + const count = await frame.locator(selector).count(); + if (count > 0) { + return frame.locator(selector); + } + } + return null; +} + +test("find element in any frame", async ({ page }) => { + await page.goto("/complex-page"); + const element = await findInAnyFrame(page, '[data-testid="submit-btn"]'); + if (element) await element.click(); +}); +``` + +## Dynamic iFrames + +### iFrames Created at Runtime + +```typescript +test("handle dynamically created iframe", async ({ page }) => { + await page.goto("/dashboard"); + + // Click button that creates iframe + await page.getByRole("button", { name: "Open Widget" }).click(); + + // Wait for iframe to appear in DOM + await page.waitForSelector("iframe#widget-frame"); + + // Now access the frame + const widgetFrame = page.frameLocator("#widget-frame"); + await expect(widgetFrame.getByText("Widget Loaded")).toBeVisible(); +}); +``` + +### iFrames with Changing src + +```typescript +test("iframe src changes", async ({ page }) => { + await page.goto("/multi-step"); + + const frame = page.frameLocator("#step-frame"); + + // Step 1 + await expect(frame.getByText("Step 1")).toBeVisible(); + await frame.getByRole("button", { name: "Next" }).click(); + + // Wait for iframe to reload with new content + await expect(frame.getByText("Step 2")).toBeVisible({ timeout: 10000 }); + await frame.getByRole("button", { name: "Next" }).click(); + + // Step 3 + await expect(frame.getByText("Step 3")).toBeVisible({ timeout: 10000 }); +}); +``` + +### Lazy-Loaded iFrames + +```typescript +test("lazy loaded iframe", async ({ page }) => { + await page.goto("/page-with-lazy-iframe"); + + // Scroll to trigger lazy load + await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight)); + + // Wait for iframe to load + const lazyFrame = page.frameLocator("#lazy-iframe"); + await expect(lazyFrame.locator("body")).not.toBeEmpty({ timeout: 15000 }); + + // Interact with content + await lazyFrame.getByRole("button").click(); +}); +``` + +## iFrame Navigation + +### Navigating Within iFrame + +```typescript +test("iframe internal navigation", async ({ page }) => { + await page.goto("/app"); + + // Get frame object for navigation control + const frame = page.frame({ name: "content-frame" }); + if (!frame) throw new Error("Frame not found"); + + // Navigate within iframe + await frame.goto("https://embedded-app.com/page2"); + + // Wait for navigation + await frame.waitForURL("**/page2"); + + // Verify content + await expect(frame.getByRole("heading")).toHaveText("Page 2"); +}); +``` + +### Handling Frame Navigation Events + +```typescript +test("track iframe navigation", async ({ page }) => { + const navigations: string[] = []; + + // Listen to frame navigation + page.on("framenavigated", (frame) => { + if (frame.parentFrame()) { + // This is an iframe navigation + navigations.push(frame.url()); + } + }); + + await page.goto("/with-iframe"); + await page + .frameLocator("#nav-frame") + .getByRole("link", { name: "Page 2" }) + .click(); + + // Verify navigation occurred + expect(navigations.some((url) => url.includes("page2"))).toBe(true); +}); +``` + +## Common Patterns + +### iFrame Fixture + +```typescript +// fixtures.ts +import { test as base, FrameLocator } from "@playwright/test"; + +export const test = base.extend<{ paymentFrame: FrameLocator }>({ + paymentFrame: async ({ page }, use) => { + await page.goto("/checkout"); + + // Wait for payment iframe to be ready + const frame = page.frameLocator('iframe[src*="payment"]'); + await expect(frame.locator("body")).toBeVisible({ timeout: 15000 }); + + await use(frame); + }, +}); + +// test file +test("complete payment", async ({ paymentFrame }) => { + await paymentFrame.getByLabel("Card").fill("4242424242424242"); + await paymentFrame.getByRole("button", { name: "Pay" }).click(); +}); +``` + +### Debugging iFrame Issues + +```typescript +test("debug iframe content", async ({ page }) => { + await page.goto("/page-with-iframes"); + + // List all frames + console.log("All frames:"); + for (const frame of page.frames()) { + console.log(` - ${frame.name() || "(unnamed)"}: ${frame.url()}`); + } + + // Screenshot specific iframe content + const frame = page.frame({ name: "target-frame" }); + if (frame) { + const body = frame.locator("body"); + await body.screenshot({ path: "iframe-content.png" }); + } + + // Get iframe HTML for debugging + const frameContent = page.frameLocator("#my-frame"); + const html = await frameContent.locator("body").innerHTML(); + console.log("iFrame HTML:", html.substring(0, 500)); +}); +``` + +### Handling iFrame Load Failures + +```typescript +test("handle iframe load failure", async ({ page }) => { + await page.goto("/page-with-unreliable-iframe"); + + const frame = page.frameLocator("#unreliable-frame"); + + try { + // Try to interact with iframe content + await expect(frame.getByRole("button")).toBeVisible({ timeout: 5000 }); + await frame.getByRole("button").click(); + } catch (error) { + // Fallback: refresh iframe + await page.evaluate(() => { + const iframe = document.querySelector( + "#unreliable-frame", + ) as HTMLIFrameElement; + if (iframe) iframe.src = iframe.src; + }); + + // Retry + await expect(frame.getByRole("button")).toBeVisible({ timeout: 10000 }); + await frame.getByRole("button").click(); + } +}); +``` + +### Mocking iFrame Content + +```typescript +test("mock iframe response", async ({ page }) => { + // Intercept iframe src request + await page.route("**/embedded-widget**", (route) => { + route.fulfill({ + contentType: "text/html", + body: ` + + + +

Mocked Widget

+

Mocked widget content

+ + + `, + }); + }); + + await page.goto("/page-with-widget"); + + const frame = page.frameLocator("#widget-frame"); + await expect(frame.getByRole("heading")).toHaveText("Mocked Widget"); +}); +``` + +## Anti-Patterns to Avoid + +| Anti-Pattern | Problem | Solution | +| ------------------------------------- | --------------------------------- | -------------------------------------------------- | +| Using `page.frame()` for interactions | Less reliable than frameLocator | Use `page.frameLocator()` for element interactions | +| Hardcoding iframe index | Fragile if DOM order changes | Use name, id, or src attribute selectors | +| Not waiting for iframe load | Race conditions | Wait for element inside iframe to be visible | +| Assuming same-origin | Cross-origin has different timing | Always wait for iframe content explicitly | +| Ignoring nested iframes | Element not found | Chain frameLocator calls for nested frames | + +## Related References + +- **Locators**: See [locators.md](../core/locators.md) for selector strategies +- **Third-party services**: See [third-party.md](../advanced/third-party.md) for payment iframe patterns +- **Debugging**: See [debugging.md](../debugging/debugging.md) for troubleshooting iframe issues diff --git a/.cursor/skills/playwright-testing/browser-apis/service-workers.md b/.cursor/skills/playwright-testing/browser-apis/service-workers.md new file mode 100644 index 0000000..7603de3 --- /dev/null +++ b/.cursor/skills/playwright-testing/browser-apis/service-workers.md @@ -0,0 +1,504 @@ +# Service Worker Testing + +## Table of Contents + +1. [Service Worker Basics](#service-worker-basics) +2. [Registration & Lifecycle](#registration--lifecycle) +3. [Cache Testing](#cache-testing) +4. [Offline Testing](#offline-testing) +5. [Push Notifications](#push-notifications) +6. [Background Sync](#background-sync) + +## Service Worker Basics + +### Waiting for Service Worker Registration + +```typescript +test("service worker registers", async ({ page }) => { + await page.goto("/pwa-app"); + + // Wait for SW to register + const swRegistered = await page.evaluate(async () => { + if (!("serviceWorker" in navigator)) return false; + + const registration = await navigator.serviceWorker.ready; + return !!registration.active; + }); + + expect(swRegistered).toBe(true); +}); +``` + +### Getting Service Worker State + +```typescript +test("check SW state", async ({ page }) => { + await page.goto("/"); + + const swState = await page.evaluate(async () => { + const registration = await navigator.serviceWorker.getRegistration(); + if (!registration) return null; + + return { + installing: !!registration.installing, + waiting: !!registration.waiting, + active: !!registration.active, + scope: registration.scope, + }; + }); + + expect(swState?.active).toBe(true); + expect(swState?.scope).toContain(page.url()); +}); +``` + +### Service Worker Context + +```typescript +test("access service worker", async ({ context, page }) => { + await page.goto("/pwa-app"); + + // Get all service workers in context + const workers = context.serviceWorkers(); + + // Wait for service worker if not yet available + if (workers.length === 0) { + await context.waitForEvent("serviceworker"); + } + + const sw = context.serviceWorkers()[0]; + expect(sw.url()).toContain("sw.js"); +}); +``` + +## Registration & Lifecycle + +### Testing SW Update Flow + +```typescript +test("service worker updates", async ({ page }) => { + await page.goto("/pwa-app"); + + // Check for update + const hasUpdate = await page.evaluate(async () => { + const registration = await navigator.serviceWorker.ready; + await registration.update(); + + return new Promise((resolve) => { + if (registration.waiting) { + resolve(true); + } else { + registration.addEventListener("updatefound", () => { + resolve(true); + }); + // Timeout if no update + setTimeout(() => resolve(false), 5000); + } + }); + }); + + // If update found, test skip waiting flow + if (hasUpdate) { + await page.evaluate(async () => { + const registration = await navigator.serviceWorker.ready; + registration.waiting?.postMessage({ type: "SKIP_WAITING" }); + }); + + // Wait for controller change + await page.evaluate(() => { + return new Promise((resolve) => { + navigator.serviceWorker.addEventListener("controllerchange", () => { + resolve(); + }); + }); + }); + } +}); +``` + +### Testing SW Installation + +```typescript +test("verify SW install event", async ({ context, page }) => { + // Listen for service worker before navigating + const swPromise = context.waitForEvent("serviceworker"); + + await page.goto("/pwa-app"); + + const sw = await swPromise; + + // Evaluate in SW context + const swVersion = await sw.evaluate(() => { + // Access SW globals + return (self as any).SW_VERSION || "unknown"; + }); + + expect(swVersion).toBe("1.0.0"); +}); +``` + +### Unregistering Service Workers + +```typescript +test.beforeEach(async ({ page }) => { + await page.goto("/"); + + // Unregister all service workers for clean state + await page.evaluate(async () => { + const registrations = await navigator.serviceWorker.getRegistrations(); + await Promise.all(registrations.map((r) => r.unregister())); + }); + + // Clear caches + await page.evaluate(async () => { + const cacheNames = await caches.keys(); + await Promise.all(cacheNames.map((name) => caches.delete(name))); + }); +}); +``` + +## Cache Testing + +### Verifying Cached Resources + +```typescript +test("assets are cached", async ({ page }) => { + await page.goto("/pwa-app"); + + // Wait for SW to cache assets + await page.evaluate(async () => { + await navigator.serviceWorker.ready; + }); + + // Check cache contents + const cachedUrls = await page.evaluate(async () => { + const cache = await caches.open("app-cache-v1"); + const requests = await cache.keys(); + return requests.map((r) => r.url); + }); + + expect(cachedUrls).toContain(expect.stringContaining("/styles.css")); + expect(cachedUrls).toContain(expect.stringContaining("/app.js")); +}); +``` + +### Testing Cache Strategies + +```typescript +test("cache-first strategy", async ({ page }) => { + await page.goto("/pwa-app"); + + // Wait for initial cache + await page.waitForFunction(async () => { + const cache = await caches.open("app-cache-v1"); + const keys = await cache.keys(); + return keys.length > 0; + }); + + // Block network for cached resources + await page.route("**/styles.css", (route) => route.abort()); + + // Reload - should work from cache + await page.reload(); + + // Verify page still styled (CSS loaded from cache) + const hasStyles = await page.evaluate(() => { + const body = document.body; + const styles = window.getComputedStyle(body); + return styles.fontFamily !== ""; // Has custom font from CSS + }); + + expect(hasStyles).toBe(true); +}); +``` + +### Testing Cache Updates + +```typescript +test("cache updates on new version", async ({ page }) => { + await page.goto("/pwa-app"); + + // Get initial cache + const initialCacheKeys = await page.evaluate(async () => { + const cache = await caches.open("app-cache-v1"); + const keys = await cache.keys(); + return keys.map((r) => r.url); + }); + + // Simulate app update by mocking SW response + await page.route("**/sw.js", (route) => { + route.fulfill({ + contentType: "application/javascript", + body: ` + const VERSION = 'v2'; + self.addEventListener('install', (e) => { + e.waitUntil(caches.open('app-cache-v2')); + self.skipWaiting(); + }); + `, + }); + }); + + // Trigger update + await page.evaluate(async () => { + const reg = await navigator.serviceWorker.ready; + await reg.update(); + }); + + // Verify new cache exists + await page.waitForFunction(async () => { + return await caches.has("app-cache-v2"); + }); +}); +``` + +## Offline Testing + +This section covers **offline-first apps (PWAs)** that are designed to work offline using service workers, caching, and background sync. For testing **unexpected network failures** (error recovery, graceful degradation), see [error-testing.md](error-testing.md#offline-testing). + +### Simulating Offline Mode + +```typescript +test("app works offline", async ({ page, context }) => { + await page.goto("/pwa-app"); + + // Ensure SW is active and content cached + await page.evaluate(async () => { + await navigator.serviceWorker.ready; + }); + await page.waitForTimeout(1000); // Allow caching to complete + + // Go offline + await context.setOffline(true); + + // Navigate to cached page + await page.reload(); + + // Verify content loads + await expect(page.getByRole("heading", { name: "Dashboard" })).toBeVisible(); + + // Verify offline indicator + await expect(page.locator(".offline-badge")).toBeVisible(); + + // Go back online + await context.setOffline(false); + await expect(page.locator(".offline-badge")).not.toBeVisible(); +}); +``` + +### Testing Offline Fallback + +```typescript +test("shows offline page for uncached routes", async ({ page, context }) => { + await page.goto("/pwa-app"); + await page.evaluate(() => navigator.serviceWorker.ready); + + // Go offline + await context.setOffline(true); + + // Navigate to uncached page + await page.goto("/uncached-page"); + + // Should show offline fallback + await expect(page.getByText("You are offline")).toBeVisible(); + await expect(page.getByRole("button", { name: "Retry" })).toBeVisible(); +}); +``` + +### Testing Offline Form Submission + +```typescript +test("queues form submission offline", async ({ page, context }) => { + await page.goto("/pwa-app/form"); + + // Go offline + await context.setOffline(true); + + // Submit form + await page.getByLabel("Message").fill("Offline message"); + await page.getByRole("button", { name: "Send" }).click(); + + // Should show queued status + await expect(page.getByText("Queued for sync")).toBeVisible(); + + // Go online + await context.setOffline(false); + + // Trigger sync (or wait for automatic) + await page.evaluate(async () => { + const reg = await navigator.serviceWorker.ready; + // Manually trigger sync for testing + await (reg as any).sync?.register("form-sync"); + }); + + // Verify submission completed + await expect(page.getByText("Message sent")).toBeVisible({ timeout: 10000 }); +}); +``` + +## Push Notifications + +### Mocking Push Subscription + +```typescript +test("handles push subscription", async ({ page, context }) => { + // Grant notification permission + await context.grantPermissions(["notifications"]); + + await page.goto("/pwa-app"); + + // Subscribe to push + const subscription = await page.evaluate(async () => { + const reg = await navigator.serviceWorker.ready; + const sub = await reg.pushManager.subscribe({ + userVisibleOnly: true, + applicationServerKey: "test-key", + }); + return sub.toJSON(); + }); + + expect(subscription.endpoint).toBeDefined(); +}); +``` + +### Testing Push Message Handling + +```typescript +test("handles push notification", async ({ context, page }) => { + await context.grantPermissions(["notifications"]); + await page.goto("/pwa-app"); + + // Wait for SW + const swPromise = context.waitForEvent("serviceworker"); + const sw = await swPromise; + + // Simulate push message to service worker + await sw.evaluate(async () => { + // Dispatch push event + const pushEvent = new PushEvent("push", { + data: new PushMessageData( + JSON.stringify({ title: "Test", body: "Push message" }), + ), + }); + self.dispatchEvent(pushEvent); + }); + + // Note: Actual notification display testing is limited in Playwright + // Focus on verifying the SW handles the push correctly +}); +``` + +### Testing Notification Click + +```typescript +test("notification click opens page", async ({ context, page }) => { + await context.grantPermissions(["notifications"]); + await page.goto("/pwa-app"); + + // Store notification URL target + let notificationUrl = ""; + + // Listen for new pages (notification click opens new page) + context.on("page", (newPage) => { + notificationUrl = newPage.url(); + }); + + // Trigger notification via SW + await page.evaluate(async () => { + const reg = await navigator.serviceWorker.ready; + await reg.showNotification("Test", { + body: "Click me", + data: { url: "/notification-target" }, + }); + }); + + // Simulate clicking notification (via SW) + const sw = context.serviceWorkers()[0]; + await sw.evaluate(() => { + self.dispatchEvent( + new NotificationEvent("notificationclick", { + notification: { data: { url: "/notification-target" } } as any, + }), + ); + }); + + // Verify navigation occurred + await page.waitForTimeout(1000); + // Check if new page opened or current page navigated +}); +``` + +## Background Sync + +### Testing Background Sync Registration + +```typescript +test("registers background sync", async ({ page }) => { + await page.goto("/pwa-app"); + + // Register sync + const syncRegistered = await page.evaluate(async () => { + const reg = await navigator.serviceWorker.ready; + if (!("sync" in reg)) return false; + + await (reg as any).sync.register("my-sync"); + return true; + }); + + expect(syncRegistered).toBe(true); +}); +``` + +### Testing Sync Event + +```typescript +test("sync event fires when online", async ({ context, page }) => { + await page.goto("/pwa-app"); + + // Queue data while offline + await context.setOffline(true); + + await page.evaluate(async () => { + // Store data in IndexedDB for sync + const db = await openDB(); + await db.put("sync-queue", { id: 1, data: "test" }); + + // Register sync + const reg = await navigator.serviceWorker.ready; + await (reg as any).sync.register("data-sync"); + }); + + // Track sync completion + await page.evaluate(() => { + window.syncCompleted = false; + navigator.serviceWorker.addEventListener("message", (e) => { + if (e.data.type === "SYNC_COMPLETE") { + window.syncCompleted = true; + } + }); + }); + + // Go online + await context.setOffline(false); + + // Wait for sync to complete + await page.waitForFunction(() => window.syncCompleted, { timeout: 10000 }); +}); +``` + +## Anti-Patterns to Avoid + +| Anti-Pattern | Problem | Solution | +| ------------------------------ | ----------------------- | -------------------------------------------- | +| Not clearing SW between tests | Tests affect each other | Unregister SW in beforeEach | +| Not waiting for SW ready | Race conditions | Always await `navigator.serviceWorker.ready` | +| Testing in isolation only | Misses real SW behavior | Test with actual caching | +| Hardcoded timeouts for caching | Flaky tests | Wait for cache to populate | +| Ignoring SW update cycle | Missing update bugs | Test install, activate, update flows | + +## Related References + +- **Network Failures**: See [error-testing.md](error-testing.md#offline-testing) for unexpected network failure patterns +- **Browser APIs**: See [browser-apis.md](browser-apis.md) for permissions +- **Network Mocking**: See [network-advanced.md](../advanced/network-advanced.md) for network interception +- **Browser Extensions**: See [browser-extensions.md](../testing-patterns/browser-extensions.md) for extension service worker patterns diff --git a/.cursor/skills/playwright-testing/browser-apis/websockets.md b/.cursor/skills/playwright-testing/browser-apis/websockets.md new file mode 100644 index 0000000..075a997 --- /dev/null +++ b/.cursor/skills/playwright-testing/browser-apis/websockets.md @@ -0,0 +1,403 @@ +# WebSocket & Real-Time Testing + +## Table of Contents + +1. [WebSocket Basics](#websocket-basics) +2. [Mocking WebSocket Messages](#mocking-websocket-messages) +3. [Testing Real-Time Features](#testing-real-time-features) +4. [Server-Sent Events](#server-sent-events) +5. [Reconnection Testing](#reconnection-testing) + +## WebSocket Basics + +### Wait for WebSocket Connection + +```typescript +test("chat connects via websocket", async ({ page }) => { + // Listen for WebSocket connection + const wsPromise = page.waitForEvent("websocket"); + + await page.goto("/chat"); + + const ws = await wsPromise; + expect(ws.url()).toContain("/ws/chat"); + + // Wait for connection to be established + await ws.waitForEvent("framesent"); +}); +``` + +### Monitor WebSocket Messages + +```typescript +test("receives real-time updates", async ({ page }) => { + const messages: string[] = []; + + // Set up listener before navigation + page.on("websocket", (ws) => { + ws.on("framereceived", (frame) => { + messages.push(frame.payload as string); + }); + }); + + await page.goto("/dashboard"); + + // Wait for some messages + await expect.poll(() => messages.length).toBeGreaterThan(0); + + // Verify message format + const data = JSON.parse(messages[0]); + expect(data).toHaveProperty("type"); +}); +``` + +### Capture Sent Messages + +```typescript +test("sends correct message format", async ({ page }) => { + const sentMessages: string[] = []; + + page.on("websocket", (ws) => { + ws.on("framesent", (frame) => { + sentMessages.push(frame.payload as string); + }); + }); + + await page.goto("/chat"); + await page.getByLabel("Message").fill("Hello!"); + await page.getByRole("button", { name: "Send" }).click(); + + // Verify sent message + await expect.poll(() => sentMessages.length).toBeGreaterThan(0); + + const sent = JSON.parse(sentMessages[sentMessages.length - 1]); + expect(sent).toEqual({ + type: "message", + content: "Hello!", + }); +}); +``` + +## Mocking WebSocket Messages + +### Inject Messages via Page Evaluate + +```typescript +test("displays incoming chat message", async ({ page }) => { + await page.goto("/chat"); + + // Wait for WebSocket to be ready + await page.waitForFunction( + () => (window as any).chatSocket?.readyState === 1, + ); + + // Simulate incoming message + await page.evaluate(() => { + const event = new MessageEvent("message", { + data: JSON.stringify({ + type: "message", + from: "Alice", + content: "Hello there!", + }), + }); + (window as any).chatSocket.dispatchEvent(event); + }); + + await expect(page.getByText("Alice: Hello there!")).toBeVisible(); +}); +``` + +### Mock WebSocket with Route Handler + +```typescript +test("mock websocket entirely", async ({ page, context }) => { + // Intercept the WebSocket upgrade + await context.route("**/ws/**", async (route) => { + // For WebSocket routes, we can't fulfill directly + // Instead, use page.evaluate to mock the client-side + }); + + // Alternative: Mock at application level + await page.addInitScript(() => { + const OriginalWebSocket = window.WebSocket; + (window as any).WebSocket = function (url: string) { + const ws = { + readyState: 1, + send: (data: string) => { + console.log("WS Send:", data); + }, + close: () => {}, + addEventListener: () => {}, + removeEventListener: () => {}, + }; + setTimeout(() => ws.onopen?.(), 100); + return ws; + }; + }); + + await page.goto("/chat"); +}); +``` + +### WebSocket Mock Fixture + +```typescript +// fixtures/websocket.fixture.ts +import { test as base, Page } from "@playwright/test"; + +type WsMessage = { type: string; [key: string]: any }; + +type WebSocketFixtures = { + mockWebSocket: { + injectMessage: (message: WsMessage) => Promise; + getSentMessages: () => Promise; + }; +}; + +export const test = base.extend({ + mockWebSocket: async ({ page }, use) => { + const sentMessages: WsMessage[] = []; + + // Capture sent messages + await page.addInitScript(() => { + (window as any).__wsSent = []; + const OriginalWebSocket = window.WebSocket; + window.WebSocket = function (url: string) { + const ws = new OriginalWebSocket(url); + const originalSend = ws.send.bind(ws); + ws.send = (data: string) => { + (window as any).__wsSent.push(JSON.parse(data)); + originalSend(data); + }; + (window as any).__ws = ws; + return ws; + } as any; + }); + + await use({ + injectMessage: async (message) => { + await page.evaluate((msg) => { + const event = new MessageEvent("message", { + data: JSON.stringify(msg), + }); + (window as any).__ws?.dispatchEvent(event); + }, message); + }, + getSentMessages: async () => { + return page.evaluate(() => (window as any).__wsSent || []); + }, + }); + }, +}); + +// Usage +test("chat with mocked websocket", async ({ page, mockWebSocket }) => { + await page.goto("/chat"); + + // Inject incoming message + await mockWebSocket.injectMessage({ + type: "message", + from: "Bob", + content: "Hi!", + }); + + await expect(page.getByText("Bob: Hi!")).toBeVisible(); + + // Send a reply + await page.getByLabel("Message").fill("Hello Bob!"); + await page.getByRole("button", { name: "Send" }).click(); + + // Verify sent message + const sent = await mockWebSocket.getSentMessages(); + expect(sent).toContainEqual( + expect.objectContaining({ content: "Hello Bob!" }), + ); +}); +``` + +## Testing Real-Time Features + +### Live Notifications + +```typescript +test("displays live notification", async ({ page }) => { + await page.goto("/dashboard"); + + // Simulate notification via WebSocket + await page.evaluate(() => { + const event = new MessageEvent("message", { + data: JSON.stringify({ + type: "notification", + title: "New Order", + message: "Order #123 received", + }), + }); + (window as any).notificationSocket.dispatchEvent(event); + }); + + await expect(page.getByRole("alert")).toContainText("Order #123 received"); +}); +``` + +### Live Data Updates + +```typescript +test("updates stock price in real-time", async ({ page }) => { + await page.goto("/stocks/AAPL"); + + const priceElement = page.getByTestId("stock-price"); + const initialPrice = await priceElement.textContent(); + + // Simulate price update + await page.evaluate(() => { + const event = new MessageEvent("message", { + data: JSON.stringify({ + type: "price_update", + symbol: "AAPL", + price: 150.25, + }), + }); + (window as any).stockSocket.dispatchEvent(event); + }); + + await expect(priceElement).not.toHaveText(initialPrice!); + await expect(priceElement).toContainText("150.25"); +}); +``` + +### Collaborative Editing + +```typescript +test("shows collaborator cursor", async ({ page }) => { + await page.goto("/document/123"); + + // Simulate another user's cursor position + await page.evaluate(() => { + const event = new MessageEvent("message", { + data: JSON.stringify({ + type: "cursor", + userId: "user-456", + userName: "Alice", + position: { x: 100, y: 200 }, + }), + }); + (window as any).docSocket.dispatchEvent(event); + }); + + await expect(page.getByTestId("cursor-user-456")).toBeVisible(); + await expect(page.getByText("Alice")).toBeVisible(); +}); +``` + +## Server-Sent Events + +### Test SSE Updates + +```typescript +test("receives SSE updates", async ({ page }) => { + // Mock SSE endpoint + await page.route("**/api/events", (route) => { + route.fulfill({ + status: 200, + headers: { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache", + Connection: "keep-alive", + }, + body: `data: {"type":"update","value":42}\n\n`, + }); + }); + + await page.goto("/live-data"); + + await expect(page.getByTestId("value")).toHaveText("42"); +}); +``` + +### Simulate Multiple SSE Events + +```typescript +test("handles multiple SSE events", async ({ page }) => { + await page.route("**/api/events", async (route) => { + const encoder = new TextEncoder(); + const events = [ + `data: {"count":1}\n\n`, + `data: {"count":2}\n\n`, + `data: {"count":3}\n\n`, + ]; + + route.fulfill({ + status: 200, + headers: { "Content-Type": "text/event-stream" }, + body: events.join(""), + }); + }); + + await page.goto("/counter"); + + // Should receive all events + await expect(page.getByTestId("count")).toHaveText("3"); +}); +``` + +## Reconnection Testing + +### Test Connection Loss + +```typescript +test("handles connection loss gracefully", async ({ page }) => { + await page.goto("/chat"); + + // Simulate connection close + await page.evaluate(() => { + (window as any).chatSocket.close(); + }); + + // Should show disconnected state + await expect(page.getByText("Reconnecting...")).toBeVisible(); +}); +``` + +### Test Reconnection + +```typescript +test("reconnects after connection loss", async ({ page }) => { + await page.goto("/chat"); + + // Simulate disconnect + await page.evaluate(() => { + (window as any).chatSocket.close(); + }); + + await expect(page.getByText("Reconnecting...")).toBeVisible(); + + // Simulate reconnection + await page.evaluate(() => { + const event = new Event("open"); + (window as any).chatSocket = { readyState: 1 }; + (window as any).chatSocket.dispatchEvent?.(event); + }); + + // Force component to re-check connection + await page.evaluate(() => { + window.dispatchEvent(new Event("online")); + }); + + await expect(page.getByText("Connected")).toBeVisible(); +}); +``` + +## Anti-Patterns to Avoid + +| Anti-Pattern | Problem | Solution | +| ------------------------------------- | ----------------------------- | ---------------------------------- | +| Not waiting for WebSocket ready | Messages sent too early | Wait for `readyState === 1` | +| Testing against real WebSocket server | Flaky, timing-dependent | Mock WebSocket messages | +| Ignoring connection state | Tests pass but feature broken | Test connected/disconnected states | +| No cleanup of listeners | Memory leaks in tests | Clean up event listeners | + +## Related References + +- **Network**: See [network-advanced.md](../advanced/network-advanced.md) for HTTP mocking patterns +- **Assertions**: See [assertions-waiting.md](../core/assertions-waiting.md) for polling patterns +- **Multi-User**: See [multi-user.md](../advanced/multi-user.md) for real-time collaboration testing with multiple users diff --git a/.cursor/skills/playwright-testing/core/annotations.md b/.cursor/skills/playwright-testing/core/annotations.md new file mode 100644 index 0000000..ac0f890 --- /dev/null +++ b/.cursor/skills/playwright-testing/core/annotations.md @@ -0,0 +1,424 @@ +# Test Annotations & Organization + +## Table of Contents + +1. [Skip Annotations](#skip-annotations) +2. [Fixme & Fail Annotations](#fixme--fail-annotations) +3. [Slow Tests](#slow-tests) +4. [Test Steps](#test-steps) +5. [Custom Annotations](#custom-annotations) +6. [Conditional Annotations](#conditional-annotations) + +## Skip Annotations + +### Basic Skip + +```typescript +// Skip unconditionally +test.skip("feature not implemented", async ({ page }) => { + // This test won't run +}); + +// Skip with reason +test("payment flow", async ({ page }) => { + test.skip(true, "Payment gateway in maintenance"); + // Test body won't execute +}); +``` + +### Conditional Skip + +```typescript +test("webkit-specific feature", async ({ page, browserName }) => { + test.skip(browserName !== "webkit", "This feature only works in WebKit"); + + await page.goto("/webkit-feature"); +}); + +test("production only", async ({ page }) => { + test.skip(process.env.ENV !== "production", "Only runs against production"); + + await page.goto("/prod-feature"); +}); +``` + +### Skip by Platform + +```typescript +test("windows-specific", async ({ page }) => { + test.skip(process.platform !== "win32", "Windows only"); +}); + +test("not on CI", async ({ page }) => { + test.skip(!!process.env.CI, "Skipped in CI environment"); +}); +``` + +### Skip Describe Block + +```typescript +test.describe("Admin features", () => { + test.skip( + ({ browserName }) => browserName === "firefox", + "Firefox admin bug", + ); + + test("admin dashboard", async ({ page }) => { + // Skipped in Firefox + }); + + test("admin settings", async ({ page }) => { + // Skipped in Firefox + }); +}); +``` + +## Fixme & Fail Annotations + +### Fixme - Known Issues + +```typescript +// Mark test as needing fix (skips the test) +test.fixme("broken after refactor", async ({ page }) => { + // Test won't run but is tracked +}); + +// Conditional fixme +test("flaky on CI", async ({ page }) => { + test.fixme(!!process.env.CI, "Investigate CI flakiness - ticket #123"); + + await page.goto("/flaky-feature"); +}); +``` + +### Fail - Expected Failures + +```typescript +// Test is expected to fail (runs but expects failure) +test("known bug", async ({ page }) => { + test.fail(); + + await page.goto("/buggy-page"); + // If this passes, the test fails (bug was fixed!) + await expect(page.getByText("Working")).toBeVisible(); +}); + +// Conditional fail +test("fails on webkit", async ({ page, browserName }) => { + test.fail(browserName === "webkit", "WebKit rendering bug #456"); + + await page.goto("/render-test"); + await expect(page.getByTestId("element")).toHaveCSS("width", "100px"); +}); +``` + +### Difference Between Skip, Fixme, Fail + +| Annotation | Runs? | Use Case | +| -------------- | ----- | -------------------------------- | +| `test.skip()` | No | Feature not applicable | +| `test.fixme()` | No | Known bug, needs investigation | +| `test.fail()` | Yes | Expected to fail, tracking a bug | + +## Slow Tests + +### Mark Slow Tests + +```typescript +// Triple the default timeout +test("large data import", async ({ page }) => { + test.slow(); + + await page.goto("/import"); + await page.setInputFiles("#file", "large-file.csv"); + await page.getByRole("button", { name: "Import" }).click(); + + await expect(page.getByText("Import complete")).toBeVisible(); +}); + +// Conditional slow +test("video processing", async ({ page, browserName }) => { + test.slow(browserName === "webkit", "WebKit video processing is slow"); + + await page.goto("/video-editor"); +}); +``` + +### Custom Timeout + +```typescript +test("very long operation", async ({ page }) => { + // Set specific timeout (in milliseconds) + test.setTimeout(120000); // 2 minutes + + await page.goto("/long-operation"); +}); + +// Timeout for describe block +test.describe("Integration tests", () => { + test.describe.configure({ timeout: 60000 }); + + test("test 1", async ({ page }) => { + // Has 60 second timeout + }); +}); +``` + +## Test Steps + +### Basic Steps + +```typescript +test("checkout flow", async ({ page }) => { + await test.step("Add item to cart", async () => { + await page.goto("/products"); + await page.getByRole("button", { name: "Add to Cart" }).click(); + }); + + await test.step("Go to checkout", async () => { + await page.getByRole("link", { name: "Cart" }).click(); + await page.getByRole("button", { name: "Checkout" }).click(); + }); + + await test.step("Fill shipping info", async () => { + await page.getByLabel("Address").fill("123 Test St"); + await page.getByLabel("City").fill("Test City"); + }); + + await test.step("Complete payment", async () => { + await page.getByLabel("Card").fill("4242424242424242"); + await page.getByRole("button", { name: "Pay" }).click(); + }); + + await expect(page.getByText("Order confirmed")).toBeVisible(); +}); +``` + +### Nested Steps + +```typescript +test("user registration", async ({ page }) => { + await test.step("Fill registration form", async () => { + await page.goto("/register"); + + await test.step("Personal info", async () => { + await page.getByLabel("Name").fill("John Doe"); + await page.getByLabel("Email").fill("john@example.com"); + }); + + await test.step("Security", async () => { + await page.getByLabel("Password").fill("SecurePass123"); + await page.getByLabel("Confirm Password").fill("SecurePass123"); + }); + }); + + await test.step("Submit and verify", async () => { + await page.getByRole("button", { name: "Register" }).click(); + await expect(page.getByText("Welcome")).toBeVisible(); + }); +}); +``` + +### Steps with Return Values + +```typescript +test("verify order", async ({ page }) => { + const orderId = await test.step("Create order", async () => { + await page.goto("/checkout"); + await page.getByRole("button", { name: "Place Order" }).click(); + + // Return value from step + return await page.getByTestId("order-id").textContent(); + }); + + await test.step("Verify order details", async () => { + await page.goto(`/orders/${orderId}`); + await expect(page.getByText(`Order #${orderId}`)).toBeVisible(); + }); +}); +``` + +### Step in Page Object + +```typescript +// pages/checkout.page.ts +export class CheckoutPage { + async fillShippingInfo(address: string, city: string) { + await test.step("Fill shipping information", async () => { + await this.page.getByLabel("Address").fill(address); + await this.page.getByLabel("City").fill(city); + }); + } + + async completePayment(cardNumber: string) { + await test.step("Complete payment", async () => { + await this.page.getByLabel("Card").fill(cardNumber); + await this.page.getByRole("button", { name: "Pay" }).click(); + }); + } +} +``` + +## Custom Annotations + +### Add Annotations + +```typescript +test("important feature", async ({ page }, testInfo) => { + // Add custom annotation + testInfo.annotations.push({ + type: "priority", + description: "high", + }); + + testInfo.annotations.push({ + type: "ticket", + description: "JIRA-123", + }); + + await page.goto("/feature"); +}); +``` + +### Annotation Fixture + +```typescript +// fixtures/annotations.fixture.ts +import { test as base, TestInfo } from "@playwright/test"; + +type AnnotationFixtures = { + annotate: { + ticket: (id: string) => void; + priority: (level: "low" | "medium" | "high") => void; + owner: (name: string) => void; + }; +}; + +export const test = base.extend({ + annotate: async ({}, use, testInfo) => { + await use({ + ticket: (id) => { + testInfo.annotations.push({ type: "ticket", description: id }); + }, + priority: (level) => { + testInfo.annotations.push({ type: "priority", description: level }); + }, + owner: (name) => { + testInfo.annotations.push({ type: "owner", description: name }); + }, + }); + }, +}); + +// Usage +test("critical feature", async ({ page, annotate }) => { + annotate.ticket("JIRA-456"); + annotate.priority("high"); + annotate.owner("Alice"); + + await page.goto("/critical"); +}); +``` + +### Read Annotations in Reporter + +```typescript +// reporters/annotation-reporter.ts +import { Reporter, TestCase, TestResult } from "@playwright/test/reporter"; + +class AnnotationReporter implements Reporter { + onTestEnd(test: TestCase, result: TestResult) { + const ticket = test.annotations.find((a) => a.type === "ticket"); + const priority = test.annotations.find((a) => a.type === "priority"); + + if (ticket) { + console.log(`Test linked to: ${ticket.description}`); + } + + if (priority?.description === "high" && result.status === "failed") { + console.log(`HIGH PRIORITY FAILURE: ${test.title}`); + } + } +} + +export default AnnotationReporter; +``` + +## Conditional Annotations + +### Annotation Helper + +```typescript +// helpers/test-annotations.ts +import { test } from "@playwright/test"; + +export function skipInCI(reason = "Skipped in CI") { + test.skip(!!process.env.CI, reason); +} + +export function skipInBrowser(browser: string, reason: string) { + test.beforeEach(({ browserName }) => { + test.skip(browserName === browser, reason); + }); +} + +export function onlyInEnv(env: string) { + test.skip(process.env.ENV !== env, `Only runs in ${env}`); +} +``` + +```typescript +// tests/feature.spec.ts +import { skipInCI, onlyInEnv } from "../helpers/test-annotations"; + +test("local only feature", async ({ page }) => { + skipInCI("Uses local resources"); + + await page.goto("/local-feature"); +}); + +test("production check", async ({ page }) => { + onlyInEnv("production"); + + await page.goto("/prod-only"); +}); +``` + +### Describe-Level Conditions + +```typescript +test.describe("Mobile features", () => { + test.beforeEach(({ isMobile }) => { + test.skip(!isMobile, "Mobile only tests"); + }); + + test("touch gestures", async ({ page }) => { + // Only runs on mobile + }); +}); + +test.describe("Desktop features", () => { + test.beforeEach(({ isMobile }) => { + test.skip(isMobile, "Desktop only tests"); + }); + + test("hover interactions", async ({ page }) => { + // Only runs on desktop + }); +}); +``` + +## Anti-Patterns to Avoid + +| Anti-Pattern | Problem | Solution | +| --------------------------- | ---------------------- | -------------------------------- | +| Skipping without reason | Hard to track why | Always provide description | +| Too many skipped tests | Test debt accumulates | Review and clean up regularly | +| Using skip instead of fixme | Loses intent | Use fixme for bugs, skip for N/A | +| Not using steps | Hard to debug failures | Group logical actions in steps | + +## Related References + +- **Test Tags**: See [test-tags.md](test-tags.md) for tagging and filtering tests with `--grep` +- **Test Organization**: See [test-suite-structure.md](test-suite-structure.md) for structuring tests +- **Debugging**: See [debugging.md](../debugging/debugging.md) for troubleshooting diff --git a/.cursor/skills/playwright-testing/core/assertions-waiting.md b/.cursor/skills/playwright-testing/core/assertions-waiting.md new file mode 100644 index 0000000..bd03dd8 --- /dev/null +++ b/.cursor/skills/playwright-testing/core/assertions-waiting.md @@ -0,0 +1,361 @@ +# Assertions & Waiting + +## Table of Contents + +1. [Web-First Assertions](#web-first-assertions) +2. [Generic Assertions](#generic-assertions) +3. [Soft Assertions](#soft-assertions) +4. [Waiting Strategies](#waiting-strategies) +5. [Polling & Retrying](#polling--retrying) +6. [Custom Matchers](#custom-matchers) + +## Web-First Assertions + +Auto-retry until condition is met or timeout. Always prefer these over generic assertions. + +### Locator Assertions + +```typescript +import { expect } from "@playwright/test"; + +// Visibility +await expect(page.getByRole("button")).toBeVisible(); +await expect(page.getByRole("button")).toBeHidden(); +await expect(page.getByRole("button")).not.toBeVisible(); + +// Enabled/Disabled +await expect(page.getByRole("button")).toBeEnabled(); +await expect(page.getByRole("button")).toBeDisabled(); + +// Text content +await expect(page.getByRole("heading")).toHaveText("Welcome"); +await expect(page.getByRole("heading")).toHaveText(/welcome/i); +await expect(page.getByRole("heading")).toContainText("Welcome"); + +// Count +await expect(page.getByRole("listitem")).toHaveCount(5); + +// Attributes +await expect(page.getByRole("link")).toHaveAttribute("href", "/home"); +await expect(page.getByRole("img")).toHaveAttribute("alt", /logo/i); + +// CSS +await expect(page.getByRole("button")).toHaveClass(/primary/); +await expect(page.getByRole("button")).toHaveCSS("color", "rgb(0, 0, 255)"); + +// Input values +await expect(page.getByLabel("Email")).toHaveValue("user@example.com"); +await expect(page.getByLabel("Email")).toBeEmpty(); + +// Focus +await expect(page.getByLabel("Email")).toBeFocused(); + +// Checked state +await expect(page.getByRole("checkbox")).toBeChecked(); +await expect(page.getByRole("checkbox")).not.toBeChecked(); + +// Editable state +await expect(page.getByLabel("Name")).toBeEditable(); +``` + +### Page Assertions + +```typescript +// URL +await expect(page).toHaveURL("/dashboard"); +await expect(page).toHaveURL(/\/dashboard/); + +// Title +await expect(page).toHaveTitle("Dashboard - MyApp"); +await expect(page).toHaveTitle(/dashboard/i); +``` + +### Response Assertions + +```typescript +const response = await page.request.get("/api/users"); +await expect(response).toBeOK(); +await expect(response).not.toBeOK(); +``` + +## Generic Assertions + +Use for non-UI values. Do NOT retry - execute immediately. + +```typescript +// Equality +expect(value).toBe(5); +expect(object).toEqual({ name: "Test" }); +expect(array).toContain("item"); + +// Truthiness +expect(value).toBeTruthy(); +expect(value).toBeFalsy(); +expect(value).toBeNull(); +expect(value).toBeUndefined(); +expect(value).toBeDefined(); + +// Numbers +expect(value).toBeGreaterThan(5); +expect(value).toBeLessThanOrEqual(10); +expect(value).toBeCloseTo(5.5, 1); + +// Strings +expect(string).toMatch(/pattern/); +expect(string).toContain("substring"); + +// Arrays/Objects +expect(array).toHaveLength(3); +expect(object).toHaveProperty("key", "value"); + +// Exceptions +expect(() => fn()).toThrow(); +expect(() => fn()).toThrow("error message"); +await expect(asyncFn()).rejects.toThrow(); +``` + +## Soft Assertions + +Continue test execution after failure, report all failures at end. + +```typescript +test("check multiple elements", async ({ page }) => { + await page.goto("/dashboard"); + + // Won't stop on first failure + await expect.soft(page.getByRole("heading")).toHaveText("Dashboard"); + await expect.soft(page.getByRole("button", { name: "Save" })).toBeEnabled(); + await expect.soft(page.getByText("Welcome")).toBeVisible(); + + // Test continues; all failures reported at end +}); +``` + +### Soft Assertions with Early Exit + +```typescript +test("check form", async ({ page }) => { + await expect.soft(page.getByRole("form")).toBeVisible(); + + // Exit early if form not visible (pointless to check fields) + if (expect.soft.hasFailures()) { + return; + } + + await expect.soft(page.getByLabel("Name")).toBeVisible(); + await expect.soft(page.getByLabel("Email")).toBeVisible(); +}); +``` + +## Waiting Strategies + +### Auto-Waiting (Default) + +Actions automatically wait for: + +- Element to be attached to DOM +- Element to be visible +- Element to be stable (no animations) +- Element to be enabled +- Element to receive events + +```typescript +// These auto-wait +await page.click("button"); +await page.fill("input", "text"); +await page.getByRole("button").click(); +``` + +### Wait for Navigation + +```typescript +// Wait for URL change +await page.waitForURL("/dashboard"); +await page.waitForURL(/\/dashboard/); + +// Wait for navigation after action +await Promise.all([ + page.waitForURL("**/dashboard"), + page.click('a[href="/dashboard"]'), +]); + +// Or without Promise.all +const urlPromise = page.waitForURL("**/dashboard"); +await page.click("a"); +await urlPromise; +``` + +### Wait for Network + +```typescript +// Wait for specific response +const responsePromise = page.waitForResponse("**/api/users"); +await page.click("button"); +const response = await responsePromise; +expect(response.status()).toBe(200); + +// Wait for request +const requestPromise = page.waitForRequest("**/api/submit"); +await page.click("button"); +const request = await requestPromise; + +// Wait for no network activity +await page.waitForLoadState("networkidle"); +``` + +### Wait for Element State + +```typescript +// Wait for element to appear +await page.getByRole("dialog").waitFor({ state: "visible" }); + +// Wait for element to disappear +await page.getByText("Loading...").waitFor({ state: "hidden" }); + +// Wait for element to be attached +await page.getByTestId("result").waitFor({ state: "attached" }); + +// Wait for element to be detached +await page.getByTestId("modal").waitFor({ state: "detached" }); +``` + +### Wait for Function + +```typescript +// Wait for arbitrary condition +await page.waitForFunction(() => { + return document.querySelector(".loaded") !== null; +}); + +// With arguments +await page.waitForFunction( + (selector) => document.querySelector(selector)?.textContent === "Ready", + ".status", +); +``` + +## Polling & Retrying + +### toPass() for Polling + +Retry until block passes or times out: + +```typescript +await expect(async () => { + const response = await page.request.get("/api/status"); + expect(response.status()).toBe(200); + + const data = await response.json(); + expect(data.ready).toBe(true); +}).toPass({ + intervals: [1000, 2000, 5000], // Retry intervals + timeout: 30000, +}); +``` + +### expect.poll() + +Poll a function until assertion passes: + +```typescript +// Poll API until condition met +await expect + .poll( + async () => { + const response = await page.request.get("/api/job/123"); + return (await response.json()).status; + }, + { + intervals: [1000, 2000, 5000], + timeout: 30000, + }, + ) + .toBe("completed"); + +// Poll DOM value +await expect.poll(() => page.getByTestId("counter").textContent()).toBe("10"); +``` + +## Custom Matchers + +```typescript +// playwright.config.ts or fixtures +import { expect } from "@playwright/test"; + +expect.extend({ + async toHaveDataLoaded(page: Page) { + const locator = page.getByTestId("data-container"); + let pass = false; + let message = ""; + + try { + await expect(locator).toBeVisible(); + await expect(locator).not.toContainText("Loading"); + pass = true; + } catch (e) { + message = `Expected data to be loaded but found loading state`; + } + + return { pass, message: () => message }; + }, +}); + +// Extend TypeScript types +declare global { + namespace PlaywrightTest { + interface Matchers { + toHaveDataLoaded(): Promise; + } + } +} + +// Usage +await expect(page).toHaveDataLoaded(); +``` + +## Timeouts + +### Configure Timeouts + +```typescript +// playwright.config.ts +export default defineConfig({ + timeout: 30000, // Test timeout + expect: { + timeout: 5000, // Assertion timeout + }, +}); + +// Per-test timeout +test("long test", async ({ page }) => { + test.setTimeout(60000); + // ... +}); + +// Per-assertion timeout +await expect(page.getByRole("button")).toBeVisible({ timeout: 10000 }); +``` + +## Best Practices + +| Do | Don't | +| ------------------------------ | ------------------------------ | +| Use web-first assertions | Use generic assertions for DOM | +| Let auto-waiting work | Add unnecessary explicit waits | +| Use `toPass()` for polling | Write manual retry loops | +| Configure appropriate timeouts | Use `waitForTimeout()` | +| Check specific conditions | Wait for arbitrary time | + +## Anti-Patterns to Avoid + +| Anti-Pattern | Problem | Solution | +| --------------------------------------------------------- | ----------------------------- | -------------------------------------------- | +| `await page.waitForTimeout(5000)` | Slow, flaky, arbitrary timing | Use auto-waiting or `waitForResponse` | +| `await new Promise(resolve => setTimeout(resolve, 1000))` | Same as above | Use `waitForResponse` or element state waits | +| Generic assertions on DOM elements | No auto-retry, flaky | Use web-first assertions with `expect()` | + +## Related References + +- **Debugging timeout issues**: See [debugging.md](../debugging/debugging.md) for troubleshooting +- **Fixing flaky tests**: See [debugging.md](../debugging/debugging.md) for race condition solutions +- **Network interception**: See [test-suite-structure.md](test-suite-structure.md) for API mocking diff --git a/.cursor/skills/playwright-testing/core/configuration.md b/.cursor/skills/playwright-testing/core/configuration.md new file mode 100644 index 0000000..66b9d33 --- /dev/null +++ b/.cursor/skills/playwright-testing/core/configuration.md @@ -0,0 +1,452 @@ +# Playwright Configuration + +## Table of Contents + +1. [CLI Quick Reference](#cli-quick-reference) +2. [Decision Guide](#decision-guide) +3. [Production-Ready Config](#production-ready-config) +4. [Patterns](#patterns) +5. [Anti-Patterns](#anti-patterns) +6. [Troubleshooting](#troubleshooting) +7. [Related](#related) + +> **When to use**: Setting up a new project, adjusting timeouts, adding browser targets, configuring CI behavior, or managing environment-specific settings. + +## CLI Quick Reference + +```bash +npx playwright init # scaffold config + first test +npx playwright test --config=custom.config.ts # use alternate config +npx playwright test --project=chromium # run single project +npx playwright test --reporter=html # override reporter +npx playwright test --grep @smoke # run tests tagged @smoke +npx playwright test --grep-invert @slow # exclude @slow tests +npx playwright show-report # open last HTML report +DEBUG=pw:api npx playwright test # verbose logging +``` + +## Decision Guide + +### Timeout Selection + +| Symptom | Setting | Default | Recommended | +|---------|---------|---------|-------------| +| Test takes too long overall | `timeout` | 30s | 30-60s (max 120s) | +| Assertion retries too long/short | `expect.timeout` | 5s | 5-10s | +| `page.goto()` or `waitForURL()` times out | `navigationTimeout` | 30s | 10-30s | +| `click()`, `fill()` time out | `actionTimeout` | 0 (unlimited) | 10-15s | +| Dev server slow to start | `webServer.timeout` | 60s | 60-180s | + +### Server Management + +| Scenario | Approach | +|----------|----------| +| App in same repo | `webServer` with `reuseExistingServer: !process.env.CI` | +| Separate repos | Manual start or Docker Compose | +| Testing deployed environment | No `webServer`; set `baseURL` via env | +| Multiple services | Array of `webServer` entries | + +### Single vs Multi-Project + +| Scenario | Approach | +|----------|----------| +| Early development | Single project (chromium only) | +| Pre-release validation | Multi-project: chromium + firefox + webkit | +| Mobile-responsive app | Add mobile projects alongside desktop | +| Auth + non-auth tests | Setup project with dependencies | +| Tight CI budget | Chromium on PRs; all browsers on main | + +### globalSetup vs Setup Projects vs Fixtures + +| Need | Use | +|------|-----| +| One-time DB seed | `globalSetup` | +| Shared browser auth | Setup project with `dependencies` | +| Per-test isolated state | Custom fixture via `test.extend()` | +| Cleanup after all tests | `globalTeardown` | + +## Production-Ready Config + +```ts +// playwright.config.ts +import { defineConfig, devices } from '@playwright/test'; +import dotenv from 'dotenv'; +import path from 'path'; + +dotenv.config({ path: path.resolve(__dirname, '.env') }); + +export default defineConfig({ + testDir: './e2e', + testMatch: '**/*.spec.ts', + + fullyParallel: true, + forbidOnly: !!process.env.CI, + retries: process.env.CI ? 2 : 0, + workers: process.env.CI ? '50%' : undefined, + + reporter: process.env.CI + ? [['html', { open: 'never' }], ['github']] + : [['html', { open: 'on-failure' }]], + + timeout: 30_000, + expect: { timeout: 5_000 }, + + use: { + baseURL: process.env.BASE_URL || 'http://localhost:4000', + actionTimeout: 10_000, + navigationTimeout: 15_000, + trace: 'on-first-retry', + screenshot: 'only-on-failure', + video: 'retain-on-failure', + locale: 'en-US', + timezoneId: 'America/Los_Angeles', + }, + + projects: [ + { name: 'chromium', use: { ...devices['Desktop Chrome'] } }, + { name: 'firefox', use: { ...devices['Desktop Firefox'] } }, + { name: 'webkit', use: { ...devices['Desktop Safari'] } }, + { name: 'mobile-chrome', use: { ...devices['Pixel 7'] } }, + { name: 'mobile-safari', use: { ...devices['iPhone 14'] } }, + ], + + webServer: { + command: 'npm run start', + url: 'http://localhost:4000', + reuseExistingServer: !process.env.CI, + timeout: 120_000, + stdout: 'pipe', + stderr: 'pipe', + }, +}); +``` + +## Patterns + +### Environment-Specific Configuration + +**Use when**: Tests run against dev, staging, and production environments. + +```ts +// playwright.config.ts +import { defineConfig } from '@playwright/test'; +import dotenv from 'dotenv'; +import path from 'path'; + +const ENV = process.env.TEST_ENV || 'local'; +dotenv.config({ path: path.resolve(__dirname, `.env.${ENV}`) }); + +const envConfig: Record = { + local: { baseURL: 'http://localhost:4000', retries: 0 }, + staging: { baseURL: 'https://staging.myapp.com', retries: 2 }, + prod: { baseURL: 'https://myapp.com', retries: 2 }, +}; + +export default defineConfig({ + testDir: './e2e', + retries: envConfig[ENV].retries, + use: { baseURL: envConfig[ENV].baseURL }, +}); +``` + +```bash +TEST_ENV=staging npx playwright test +TEST_ENV=prod npx playwright test --grep @smoke +``` + +### Setup Project with Dependencies + +**Use when**: Tests need shared authentication state before running. + +```ts +// playwright.config.ts +import { defineConfig, devices } from '@playwright/test'; + +export default defineConfig({ + testDir: './e2e', + projects: [ + { + name: 'setup', + testMatch: /auth\.setup\.ts/, + }, + { + name: 'chromium', + use: { + ...devices['Desktop Chrome'], + storageState: 'playwright/.auth/session.json', + }, + dependencies: ['setup'], + }, + { + name: 'firefox', + use: { + ...devices['Desktop Firefox'], + storageState: 'playwright/.auth/session.json', + }, + dependencies: ['setup'], + }, + ], +}); +``` + +```ts +// e2e/auth.setup.ts +import { test as setup, expect } from '@playwright/test'; + +const authFile = 'playwright/.auth/session.json'; + +setup('authenticate', async ({ page }) => { + await page.goto('/login'); + await page.getByLabel('Username').fill('testuser@example.com'); + await page.getByLabel('Password').fill(process.env.TEST_PASSWORD!); + await page.getByRole('button', { name: 'Log in' }).click(); + await expect(page.getByRole('heading', { name: 'Home' })).toBeVisible(); + await page.context().storageState({ path: authFile }); +}); +``` + +### webServer with Build Step + +**Use when**: Tests need a running application server managed by Playwright. + +```ts +// playwright.config.ts +import { defineConfig } from '@playwright/test'; + +export default defineConfig({ + testDir: './e2e', + use: { baseURL: 'http://localhost:4000' }, + webServer: { + command: process.env.CI + ? 'npm run build && npm run preview' + : 'npm run dev', + url: 'http://localhost:4000', + reuseExistingServer: !process.env.CI, + timeout: 120_000, + env: { + NODE_ENV: 'test', + DB_URL: process.env.DB_URL || 'postgresql://localhost:5432/testdb', + }, + }, +}); +``` + +### globalSetup / globalTeardown + +**Use when**: One-time non-browser work like seeding a database. Runs once per test run. + +```ts +// playwright.config.ts +import { defineConfig } from '@playwright/test'; + +export default defineConfig({ + testDir: './e2e', + globalSetup: './e2e/setup.ts', + globalTeardown: './e2e/teardown.ts', +}); +``` + +```ts +// e2e/setup.ts +import { FullConfig } from '@playwright/test'; + +export default async function globalSetup(config: FullConfig) { + const { execSync } = await import('child_process'); + execSync('npx prisma db seed', { stdio: 'inherit' }); + process.env.TEST_RUN_ID = `run-${Date.now()}`; +} +``` + +```ts +// e2e/teardown.ts +import { FullConfig } from '@playwright/test'; + +export default async function globalTeardown(config: FullConfig) { + const { execSync } = await import('child_process'); + execSync('npx prisma db push --force-reset', { stdio: 'inherit' }); +} +``` + +### Environment Variables with .env + +**Use when**: Managing secrets, URLs, or feature flags without hardcoding. + +```bash +# .env.example (commit this) +BASE_URL=http://localhost:4000 +TEST_PASSWORD= +API_KEY= + +# .env.local (gitignored) +BASE_URL=http://localhost:4000 +TEST_PASSWORD=secret123 +API_KEY=dev-key-abc + +# .env.staging (gitignored) +BASE_URL=https://staging.myapp.com +TEST_PASSWORD=staging-pass +API_KEY=staging-key-xyz +``` + +```bash +# .gitignore +.env +.env.local +.env.staging +.env.production +playwright/.auth/ +``` + +Install dotenv: + +```bash +npm install -D dotenv +``` + +### Tag-Based Test Filtering + +**Use when**: Running subsets of tests in different CI stages (PR vs nightly). + +```ts +// playwright.config.ts +import { defineConfig } from '@playwright/test'; + +export default defineConfig({ + testDir: './e2e', + + // Filter by tags in CI + grep: process.env.CI ? /@smoke|@critical/ : undefined, + grepInvert: process.env.CI ? /@flaky/ : undefined, +}); +``` + +**Project-specific filtering:** + +```ts +// playwright.config.ts +import { defineConfig, devices } from '@playwright/test'; + +export default defineConfig({ + testDir: './e2e', + projects: [ + { + name: 'smoke', + grep: /@smoke/, + use: { ...devices['Desktop Chrome'] }, + }, + { + name: 'regression', + grepInvert: /@smoke/, + use: { ...devices['Desktop Chrome'] }, + }, + { + name: 'critical-only', + grep: /@critical/, + use: { ...devices['Desktop Chrome'] }, + }, + ], +}); +``` + +```bash +# Run specific project +npx playwright test --project=smoke +npx playwright test --project=regression +``` + +### Artifact Collection Strategy + +| Setting | Local | CI | Reason | +|---------|-------|-----|--------| +| `trace` | `'off'` | `'on-first-retry'` | Traces are large; collect on failure only | +| `screenshot` | `'off'` | `'only-on-failure'` | Useful for CI debugging | +| `video` | `'off'` | `'retain-on-failure'` | Recording slows tests | + +```ts +// playwright.config.ts +import { defineConfig } from '@playwright/test'; + +export default defineConfig({ + testDir: './e2e', + use: { + trace: process.env.CI ? 'on-first-retry' : 'off', + screenshot: process.env.CI ? 'only-on-failure' : 'off', + video: process.env.CI ? 'retain-on-failure' : 'off', + }, +}); +``` + +## Anti-Patterns + +| Don't | Problem | Do Instead | +|-------|---------|------------| +| `timeout: 300_000` globally | Masks flaky tests; slow CI | Fix root cause; keep 30s default | +| Hardcoded URLs: `page.goto('http://localhost:4000/login')` | Breaks in other environments | Use `baseURL` + relative paths | +| All browsers on every PR | 3x CI time | Chromium on PRs; all on main | +| `trace: 'on'` always | Huge artifacts, slow uploads | `trace: 'on-first-retry'` | +| `video: 'on'` always | Massive storage; slow tests | `video: 'retain-on-failure'` | +| Config in test files: `test.use({ viewport: {...} })` everywhere | Scattered, inconsistent | Define once in project config | +| `retries: 3` locally | Hides flakiness | `retries: 0` local, `retries: 2` CI | +| No `forbidOnly` in CI | Committed `test.only` runs single test | `forbidOnly: !!process.env.CI` | +| `globalSetup` for browser auth | No browser context available | Use setup project with dependencies | +| Committing `.env` with credentials | Security risk | Commit `.env.example` only | + +## Troubleshooting + +### baseURL Not Working + +**Cause**: Using absolute URL in `page.goto()` ignores `baseURL`. + +```ts +// Wrong - ignores baseURL +await page.goto('http://localhost:4000/dashboard'); + +// Correct - uses baseURL +await page.goto('/dashboard'); +``` + +### webServer Starts But Tests Get Connection Refused + +**Cause**: `webServer.url` doesn't match actual server address or health check returns non-200. + +```ts +webServer: { + command: 'npm run dev', + url: 'http://localhost:4000/api/health', // use real endpoint + reuseExistingServer: !process.env.CI, + timeout: 120_000, +}, +``` + +### Tests Pass Locally But Timeout in CI + +**Cause**: CI machines are slower. Increase timeouts and reduce workers: + +```ts +export default defineConfig({ + workers: process.env.CI ? '50%' : undefined, + use: { + navigationTimeout: process.env.CI ? 30_000 : 15_000, + actionTimeout: process.env.CI ? 15_000 : 10_000, + }, +}); +``` + +### "Target page, context or browser has been closed" + +**Cause**: Test exceeded `timeout` and Playwright tore down browser during action. + +**Fix**: Don't increase global timeout. Find slow step using trace: + +```bash +npx playwright test --trace on +npx playwright show-report +``` + +## Related + +- [test-tags.md](./test-tags.md) - tagging and filtering tests with `--grep` +- [fixtures-hooks.md](./fixtures-hooks.md) - custom fixtures for per-test state +- [test-suite-structure.md](test-suite-structure.md) - file structure and naming +- [authentication.md](../advanced/authentication.md) - setup projects for shared auth +- [projects-dependencies.md](./projects-dependencies.md) - advanced multi-project patterns diff --git a/.cursor/skills/playwright-testing/core/fixtures-hooks.md b/.cursor/skills/playwright-testing/core/fixtures-hooks.md new file mode 100644 index 0000000..ff9dc93 --- /dev/null +++ b/.cursor/skills/playwright-testing/core/fixtures-hooks.md @@ -0,0 +1,417 @@ +# Fixtures & Hooks + +## Table of Contents + +1. [Built-in Fixtures](#built-in-fixtures) +2. [Custom Fixtures](#custom-fixtures) +3. [Fixture Scopes](#fixture-scopes) +4. [Hooks](#hooks) +5. [Authentication Patterns](#authentication-patterns) +6. [Database Fixtures](#database-fixtures) + +## Built-in Fixtures + +### Core Fixtures + +```typescript +test("example", async ({ + page, // Isolated page instance + context, // Browser context (cookies, localStorage) + browser, // Browser instance + browserName, // 'chromium', 'firefox', or 'webkit' + request, // API request context +}) => { + // Each test gets fresh instances +}); +``` + +### Request Fixture + +```typescript +test("API call", async ({ request }) => { + const response = await request.get("/api/users"); + await expect(response).toBeOK(); + + const users = await response.json(); + expect(users).toHaveLength(5); +}); +``` + +## Custom Fixtures + +### Basic Custom Fixture + +```typescript +// fixtures.ts +import { test as base } from "@playwright/test"; + +// Declare fixture types +type MyFixtures = { + todoPage: TodoPage; + apiClient: ApiClient; +}; + +export const test = base.extend({ + // Fixture with setup and teardown + todoPage: async ({ page }, use) => { + const todoPage = new TodoPage(page); + await todoPage.goto(); + + await use(todoPage); // Test runs here + + // Teardown (optional) + await todoPage.clearTodos(); + }, + + // Simple fixture + apiClient: async ({ request }, use) => { + await use(new ApiClient(request)); + }, +}); + +export { expect } from "@playwright/test"; +``` + +### Fixture with Options + +```typescript +type Options = { + defaultUser: { email: string; password: string }; +}; + +type Fixtures = { + authenticatedPage: Page; +}; + +export const test = base.extend({ + // Define option with default + defaultUser: [ + { email: "test@example.com", password: "pass123" }, + { option: true }, + ], + + // Use option in fixture + authenticatedPage: async ({ page, defaultUser }, use) => { + await page.goto("/login"); + await page.getByLabel("Email").fill(defaultUser.email); + await page.getByLabel("Password").fill(defaultUser.password); + await page.getByRole("button", { name: "Sign in" }).click(); + await use(page); + }, +}); + +// Override in config +export default defineConfig({ + use: { + defaultUser: { email: "admin@example.com", password: "admin123" }, + }, +}); +``` + +### Automatic Fixtures + +```typescript +export const test = base.extend<{}, { setupDb: void }>({ + // Auto-fixture runs for every test without explicit usage + setupDb: [ + async ({}, use) => { + await seedDatabase(); + await use(); + await cleanDatabase(); + }, + { auto: true }, + ], +}); +``` + +## Fixture Scopes + +### Test Scope (Default) + +Created fresh for each test: + +```typescript +test.extend({ + page: async ({ browser }, use) => { + const page = await browser.newPage(); + await use(page); + await page.close(); + }, +}); +``` + +### Worker Scope + +Shared across tests in the same worker (each worker gets its own instance; tests in different workers do not share it): + +```typescript +type WorkerFixtures = { + sharedAccount: Account; +}; + +export const test = base.extend<{}, WorkerFixtures>({ + sharedAccount: [ + async ({ browser }, use) => { + // Expensive setup - runs once per worker + const account = await createTestAccount(); + await use(account); + await deleteTestAccount(account); + }, + { scope: "worker" }, + ], +}); +``` + +### Isolate test data between parallel workers + +When tests in different workers touch the same backend or DB (e.g. same user, same tenant), they can collide and cause flaky failures. Use `testInfo.workerIndex` (or `process.env.TEST_WORKER_INDEX`) in a worker-scoped fixture to create unique data per worker: + +```typescript +import { test as baseTest } from "@playwright/test"; + +type WorkerFixtures = { + dbUserName: string; +}; + +export const test = baseTest.extend<{}, WorkerFixtures>({ + dbUserName: [ + async ({}, use, testInfo) => { + const userName = `user-${testInfo.workerIndex}`; + await createUserInTestDatabase(userName); + await use(userName); + await deleteUserFromTestDatabase(userName); + }, + { scope: "worker" }, + ], +}); +``` + +Then each worker uses a distinct user (e.g. `user-1`, `user-2`), so parallel workers do not overwrite each other’s data. + +## Hooks + +### beforeEach / afterEach + +```typescript +test.beforeEach(async ({ page }) => { + // Runs before each test in file + await page.goto("/"); +}); + +test.afterEach(async ({ page }, testInfo) => { + // Runs after each test + if (testInfo.status !== "passed") { + await page.screenshot({ path: `failed-${testInfo.title}.png` }); + } +}); +``` + +### beforeAll / afterAll + +```typescript +test.beforeAll(async ({ browser }) => { + // Runs once before all tests in file + // Note: Cannot use page fixture here +}); + +test.afterAll(async () => { + // Runs once after all tests in file +}); +``` + +### Describe-Level Hooks + +```typescript +test.describe("User Management", () => { + test.beforeEach(async ({ page }) => { + await page.goto("/users"); + }); + + test("can list users", async ({ page }) => { + // Starts at /users + }); + + test("can add user", async ({ page }) => { + // Starts at /users + }); +}); +``` + +## Authentication Patterns + +### Global Setup with Storage State + +```typescript +// auth.setup.ts +import { test as setup, expect } from "@playwright/test"; + +const authFile = ".auth/user.json"; + +setup("authenticate", async ({ page }) => { + await page.goto("/login"); + await page.getByLabel("Email").fill(process.env.TEST_EMAIL!); + await page.getByLabel("Password").fill(process.env.TEST_PASSWORD!); + await page.getByRole("button", { name: "Sign in" }).click(); + + await expect(page.getByRole("heading", { name: "Dashboard" })).toBeVisible(); + await page.context().storageState({ path: authFile }); +}); +``` + +```typescript +// playwright.config.ts +export default defineConfig({ + projects: [ + { name: "setup", testMatch: /.*\.setup\.ts/ }, + { + name: "chromium", + use: { + ...devices["Desktop Chrome"], + storageState: ".auth/user.json", + }, + dependencies: ["setup"], + }, + ], +}); +``` + +### Multiple Auth States + +```typescript +// auth.setup.ts +setup("admin auth", async ({ page }) => { + await login(page, "admin@example.com", "adminpass"); + await page.context().storageState({ path: ".auth/admin.json" }); +}); + +setup("user auth", async ({ page }) => { + await login(page, "user@example.com", "userpass"); + await page.context().storageState({ path: ".auth/user.json" }); +}); +``` + +```typescript +// playwright.config.ts +projects: [ + { + name: "admin tests", + testMatch: /.*admin.*\.spec\.ts/, + use: { storageState: ".auth/admin.json" }, + dependencies: ["setup"], + }, + { + name: "user tests", + testMatch: /.*user.*\.spec\.ts/, + use: { storageState: ".auth/user.json" }, + dependencies: ["setup"], + }, +]; +``` + +### Auth Fixture + +```typescript +// fixtures/auth.fixture.ts +export const test = base.extend<{ adminPage: Page; userPage: Page }>({ + adminPage: async ({ browser }, use) => { + const context = await browser.newContext({ + storageState: ".auth/admin.json", + }); + const page = await context.newPage(); + await use(page); + await context.close(); + }, + + userPage: async ({ browser }, use) => { + const context = await browser.newContext({ + storageState: ".auth/user.json", + }); + const page = await context.newPage(); + await use(page); + await context.close(); + }, +}); +``` + +## Database Fixtures + +This section covers **per-test database fixtures** (isolation, transaction rollback). For related topics: + +- **Test data factories** (builders, Faker): See [test-data.md](test-data.md) +- **One-time database setup** (migrations, snapshots): See [global-setup.md](global-setup.md#database-patterns) + +### Transaction Rollback Pattern + +```typescript +import { test as base } from "@playwright/test"; +import { db } from "../db"; + +export const test = base.extend<{ dbTransaction: Transaction }>({ + dbTransaction: async ({}, use) => { + const transaction = await db.beginTransaction(); + + await use(transaction); + + await transaction.rollback(); // Clean slate for next test + }, +}); +``` + +### Seed Data Fixture + +```typescript +type TestData = { + testUser: User; + testProducts: Product[]; +}; + +export const test = base.extend({ + testUser: async ({}, use) => { + const user = await db.users.create({ + email: `test-${Date.now()}@example.com`, + name: "Test User", + }); + + await use(user); + + await db.users.delete(user.id); + }, + + testProducts: async ({ testUser }, use) => { + const products = await db.products.createMany([ + { name: "Product A", ownerId: testUser.id }, + { name: "Product B", ownerId: testUser.id }, + ]); + + await use(products); + + await db.products.deleteMany(products.map((p) => p.id)); + }, +}); +``` + +## Fixture Tips + +| Tip | Explanation | +| ------------------ | ------------------------------------------- | +| Fixtures are lazy | Only created when used | +| Compose fixtures | Use other fixtures as dependencies | +| Keep setup minimal | Do heavy lifting in worker-scoped fixtures | +| Clean up resources | Use teardown in fixtures, not afterEach | +| Avoid shared state | Each fixture instance should be independent | + +## Anti-Patterns to Avoid + +| Anti-Pattern | Problem | Solution | +| ----------------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Shared mutable state between tests | Race conditions, order dependencies | Use fixtures for isolation | +| Global variables in tests | Tests depend on execution order | Use fixtures or beforeEach for setup | +| Not cleaning up test data | Tests interfere with each other | Use fixtures with teardown or database transactions | +| Shared `page` or `context` in `beforeAll` | State leak between tests; flaky when tests run in parallel | Use default one-context-per-test, or `beforeEach` + fresh page; if serial is required, prefer `test.describe.configure({ mode: 'serial' })` and document that isolation is sacrificed | +| Backend/DB state shared across workers | Tests in different workers collide on same data | Use worker-scoped fixture with `testInfo.workerIndex` to create unique data per worker | + +## Related References + +- **Page Objects with fixtures**: See [page-object-model.md](page-object-model.md) for POM patterns +- **Test organization**: See [test-suite-structure.md](test-suite-structure.md) for test structure +- **Debugging fixture issues**: See [debugging.md](../debugging/debugging.md) for troubleshooting diff --git a/.cursor/skills/playwright-testing/core/global-setup.md b/.cursor/skills/playwright-testing/core/global-setup.md new file mode 100644 index 0000000..a033522 --- /dev/null +++ b/.cursor/skills/playwright-testing/core/global-setup.md @@ -0,0 +1,434 @@ +# Global Setup & Teardown + +## Table of Contents + +1. [Global Setup](#global-setup) +2. [Global Teardown](#global-teardown) +3. [Database Patterns](#database-patterns) +4. [Environment Provisioning](#environment-provisioning) +5. [Setup Projects vs Global Setup](#setup-projects-vs-global-setup) +6. [Parallel Execution Caveats](#parallel-execution-caveats) + +## Global Setup + +### Basic Global Setup + +```typescript +// global-setup.ts +import { FullConfig } from "@playwright/test"; + +async function globalSetup(config: FullConfig) { + console.log("Running global setup..."); + // Perform one-time setup: start services, run migrations, etc. +} + +export default globalSetup; +``` + +### Configure Global Setup + +```typescript +// playwright.config.ts +import { defineConfig } from "@playwright/test"; + +export default defineConfig({ + globalSetup: require.resolve("./global-setup"), + globalTeardown: require.resolve("./global-teardown"), +}); +``` + +> **Authentication in Global Setup**: For authentication patterns using storage state in global setup, see [fixtures-hooks.md](fixtures-hooks.md#authentication-patterns). Setup projects are generally preferred for authentication as they provide access to Playwright fixtures. + +### Global Setup with Return Value + +```typescript +// global-setup.ts +async function globalSetup(config: FullConfig): Promise<() => Promise> { + const server = await startTestServer(); + + // Return cleanup function (alternative to globalTeardown) + return async () => { + await server.stop(); + }; +} + +export default globalSetup; +``` + +### Access Config in Global Setup + +```typescript +// global-setup.ts +import { FullConfig } from "@playwright/test"; + +async function globalSetup(config: FullConfig) { + const { baseURL } = config.projects[0].use; + console.log(`Setting up for ${baseURL}`); + + // Access custom config + const workers = config.workers; + const timeout = config.timeout; + + // Access environment + const isCI = !!process.env.CI; +} + +export default globalSetup; +``` + +## Global Teardown + +### Basic Global Teardown + +```typescript +// global-teardown.ts +import { FullConfig } from "@playwright/test"; +import fs from "fs"; + +async function globalTeardown(config: FullConfig) { + console.log("Running global teardown..."); + + // Clean up auth files + if (fs.existsSync(".auth")) { + fs.rmSync(".auth", { recursive: true }); + } + + // Clean up test data + await cleanupTestDatabase(); + + // Stop services + await stopTestServices(); +} + +export default globalTeardown; +``` + +### Conditional Teardown + +```typescript +// global-teardown.ts +async function globalTeardown(config: FullConfig) { + // Skip cleanup in CI (containers are discarded anyway) + if (process.env.CI) { + console.log("Skipping teardown in CI"); + return; + } + + // Local cleanup + await cleanupLocalTestData(); +} + +export default globalTeardown; +``` + +## Database Patterns + +This section covers **one-time database setup** (migrations, snapshots, per-worker databases). For related topics: + +- **Per-test database fixtures** (isolation, transaction rollback): See [fixtures-hooks.md](fixtures-hooks.md#database-fixtures) +- **Test data factories** (builders, Faker): See [test-data.md](test-data.md) + +### Database Migration in Setup + +```typescript +// global-setup.ts +import { execSync } from "child_process"; + +async function globalSetup() { + console.log("Running database migrations..."); + + // Run migrations + execSync("npx prisma migrate deploy", { stdio: "inherit" }); + + // Seed test data + execSync("npx prisma db seed", { stdio: "inherit" }); +} + +export default globalSetup; +``` + +### Database Snapshot Pattern + +```typescript +// global-setup.ts +import { execSync } from "child_process"; +import fs from "fs"; + +const SNAPSHOT_PATH = "./test-db-snapshot.sql"; + +async function globalSetup() { + // Check if snapshot exists + if (fs.existsSync(SNAPSHOT_PATH)) { + console.log("Restoring database from snapshot..."); + execSync(`psql $DATABASE_URL < ${SNAPSHOT_PATH}`, { stdio: "inherit" }); + return; + } + + // First run: migrate and create snapshot + console.log("Creating database snapshot..."); + execSync("npx prisma migrate deploy", { stdio: "inherit" }); + execSync("npx prisma db seed", { stdio: "inherit" }); + execSync(`pg_dump $DATABASE_URL > ${SNAPSHOT_PATH}`, { stdio: "inherit" }); +} + +export default globalSetup; +``` + +### Test Database per Worker + +```typescript +// global-setup.ts +async function globalSetup(config: FullConfig) { + const workerCount = config.workers || 1; + + // Create a database for each worker + for (let i = 0; i < workerCount; i++) { + const dbName = `test_db_worker_${i}`; + await createDatabase(dbName); + await runMigrations(dbName); + await seedDatabase(dbName); + } +} + +// global-teardown.ts +async function globalTeardown(config: FullConfig) { + const workerCount = config.workers || 1; + + for (let i = 0; i < workerCount; i++) { + await dropDatabase(`test_db_worker_${i}`); + } +} +``` + +## Environment Provisioning + +### Start Services in Setup + +```typescript +// global-setup.ts +import { execSync, spawn } from "child_process"; + +let serverProcess: any; + +async function globalSetup() { + // Start backend server + serverProcess = spawn("npm", ["run", "start:test"], { + stdio: "pipe", + detached: true, + }); + + // Wait for server to be ready + await waitForServer("http://localhost:3000/health", 30000); + + // Store PID for teardown + process.env.SERVER_PID = serverProcess.pid.toString(); +} + +async function waitForServer(url: string, timeout: number) { + const start = Date.now(); + + while (Date.now() - start < timeout) { + try { + const response = await fetch(url); + if (response.ok) return; + } catch { + // Server not ready yet + } + await new Promise((r) => setTimeout(r, 1000)); + } + + throw new Error(`Server did not start within ${timeout}ms`); +} + +export default globalSetup; +``` + +### Docker Compose Setup + +```typescript +// global-setup.ts +import { execSync } from "child_process"; + +async function globalSetup() { + console.log("Starting Docker services..."); + + execSync("docker-compose -f docker-compose.test.yml up -d", { + stdio: "inherit", + }); + + // Wait for services to be healthy + execSync("docker-compose -f docker-compose.test.yml exec -T db pg_isready", { + stdio: "inherit", + }); +} + +export default globalSetup; +``` + +```typescript +// global-teardown.ts +import { execSync } from "child_process"; + +async function globalTeardown() { + console.log("Stopping Docker services..."); + + execSync("docker-compose -f docker-compose.test.yml down -v", { + stdio: "inherit", + }); +} + +export default globalTeardown; +``` + +### Environment Variables Setup + +```typescript +// global-setup.ts +import dotenv from "dotenv"; +import path from "path"; + +async function globalSetup() { + // Load test-specific environment + const envFile = process.env.CI ? ".env.ci" : ".env.test"; + dotenv.config({ path: path.resolve(process.cwd(), envFile) }); + + // Validate required variables + const required = ["DATABASE_URL", "API_KEY", "TEST_EMAIL"]; + for (const key of required) { + if (!process.env[key]) { + throw new Error(`Missing required environment variable: ${key}`); + } + } +} + +export default globalSetup; +``` + +## Setup Projects vs Global Setup + +### When to Use Each + +| Use Global Setup | Use Setup Projects | +| ------------------------------------- | ---------------------------------------- | +| One-time setup (migrations, services) | Per-project setup (auth states) | +| No access to Playwright fixtures | Need page, request fixtures | +| Runs once before all projects | Can run per-project or have dependencies | +| Shared across all workers | Can be parallelized | + +### Setup Project Pattern + +```typescript +// playwright.config.ts +export default defineConfig({ + projects: [ + // Setup project + { + name: "setup", + testMatch: /.*\.setup\.ts/, + }, + // Test projects depend on setup + { + name: "chromium", + use: { ...devices["Desktop Chrome"] }, + dependencies: ["setup"], + }, + { + name: "firefox", + use: { ...devices["Desktop Firefox"] }, + dependencies: ["setup"], + }, + ], +}); +``` + +> **For complete authentication setup patterns**, see [fixtures-hooks.md](fixtures-hooks.md#authentication-patterns). + +### Combining Both + +```typescript +// playwright.config.ts +export default defineConfig({ + // Global: Start services, run migrations + globalSetup: require.resolve("./global-setup"), + globalTeardown: require.resolve("./global-teardown"), + + projects: [ + // Setup project: Create auth states + { name: "setup", testMatch: /.*\.setup\.ts/ }, + { + name: "chromium", + use: { + ...devices["Desktop Chrome"], + storageState: ".auth/user.json", + }, + dependencies: ["setup"], + }, + ], +}); +``` + +## Parallel Execution Caveats + +### Understanding Global Setup Execution + +``` +┌─────────────────────────────────────────────────────────────┐ +│ globalSetup runs ONCE │ +│ ↓ │ +│ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ +│ │ Worker 1│ │ Worker 2│ │ Worker 3│ │ Worker 4│ │ +│ │ tests │ │ tests │ │ tests │ │ tests │ │ +│ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │ +│ ↓ │ +│ globalTeardown runs ONCE │ +└─────────────────────────────────────────────────────────────┘ +``` + +**Key implications:** + +- Global setup has **no access** to Playwright fixtures (`page`, `request`, `context`) +- State created in global setup is **shared** across all workers +- If tests **modify** shared state, they may conflict with parallel workers +- Global setup **cannot** react to individual test needs + +### When to Prefer Worker-Scoped Fixtures + +Use **worker-scoped fixtures** instead of globalSetup when: + +| Scenario | Why Fixtures Are Better | +| ------------------------------------ | ---------------------------------------------------- | +| Each worker needs isolated resources | Fixtures can create per-worker databases, servers | +| Setup needs Playwright APIs | Fixtures have access to `page`, `request`, `browser` | +| Setup depends on test configuration | Fixtures receive test context and options | +| Resources need cleanup per worker | Worker fixtures auto-cleanup when worker exits | + +### Common Parallel Pitfall + +```typescript +// ❌ BAD: Global setup creates ONE user, all workers fight over it +async function globalSetup() { + await createUser({ email: "test@example.com" }); // Shared! +} + +// ✅ GOOD: Each worker gets its own user via worker-scoped fixture +// Uses workerInfo.workerIndex to create unique data per worker +``` + +> **For worker-scoped fixture patterns** (per-worker databases, unique test data, `workerIndex` isolation), see [fixtures-hooks.md](fixtures-hooks.md#isolate-test-data-between-parallel-workers). + +## Anti-Patterns to Avoid + +| Anti-Pattern | Problem | Solution | +| ------------------------------ | -------------------------------- | ------------------------------------------ | +| Heavy setup in globalSetup | Slow test startup | Use setup projects for parallelizable work | +| Not cleaning up in teardown | Leaks resources, flaky CI | Always clean up or use containers | +| Hardcoded URLs in setup | Breaks in different environments | Use config.projects[0].use.baseURL | +| No timeout on service wait | Hangs forever if service fails | Add timeout with clear error | +| Shared mutable state | Race conditions in parallel | Use worker-scoped fixtures for isolation | +| Global setup for per-test data | Tests conflict | Use test-scoped fixtures | + +## Related References + +- **Fixtures & Auth**: See [fixtures-hooks.md](fixtures-hooks.md) for worker-scoped fixtures and auth patterns +- **CI/CD**: See [ci-cd.md](../infrastructure-ci-cd/ci-cd.md) for CI setup patterns +- **Projects**: See [projects-dependencies.md](projects-dependencies.md) for project configuration diff --git a/.cursor/skills/playwright-testing/core/locators.md b/.cursor/skills/playwright-testing/core/locators.md new file mode 100644 index 0000000..afe3af3 --- /dev/null +++ b/.cursor/skills/playwright-testing/core/locators.md @@ -0,0 +1,242 @@ +# Locator Strategies + +## Table of Contents + +1. [Priority Order](#priority-order) +2. [User-Facing Locators](#user-facing-locators) +3. [Filtering & Chaining](#filtering--chaining) +4. [Dynamic Content](#dynamic-content) +5. [Shadow DOM](#shadow-dom) +6. [Iframes](#iframes) + +## Priority Order + +Use locators in this order of preference: + +1. **Role-based** (most resilient): `getByRole` +2. **Label-based**: `getByLabel`, `getByPlaceholder` +3. **Text-based**: `getByText`, `getByTitle` +4. **Test IDs** (when semantic locators aren't possible): `getByTestId` +5. **CSS/XPath** (last resort): `locator('css=...')`, `locator('xpath=...')` + +## User-Facing Locators + +### getByRole + +Most robust approach - matches how users and assistive technology perceive the page. + +```typescript +// Buttons +page.getByRole("button", { name: "Submit", exact: true }); // exact accessible name +page.getByRole("button", { name: /submit/i }); // flexible case-insensitive match + +// Links +page.getByRole("link", { name: "Home" }); + +// Form elements +page.getByRole("textbox", { name: "Email" }); +page.getByRole("checkbox", { name: "Remember me" }); +page.getByRole("combobox", { name: "Country" }); +page.getByRole("radio", { name: "Option A" }); + +// Headings +page.getByRole("heading", { name: "Welcome", level: 1 }); + +// Lists & items +page.getByRole("list").getByRole("listitem"); + +// Navigation & regions +page.getByRole("navigation"); +page.getByRole("main"); +page.getByRole("dialog"); +page.getByRole("alert"); +``` + +### getByLabel + +For form elements with associated labels. + +```typescript +// Input with