Site SEO Auditor
Run ID: 69cb69cd61b1021a29a88d622026-03-31SEO & Growth
PantheraHive BOS
BOS Dashboard

Site SEO Auditor: Step 2/5 - Database Diff Generation

This document details the execution and output of Step 2 in the "Site SEO Auditor" workflow: hive_db → diff. This crucial step is responsible for generating a comprehensive "before and after" comparison report by leveraging historical audit data stored in your dedicated MongoDB instance. This diff report highlights changes, improvements, and regressions in your site's SEO performance between consecutive audits.


1. Step Overview: hive_db → diff

The hive_db → diff step serves as the analytical core for tracking your website's SEO evolution. Upon completion of a new site crawl and audit (Step 1), the newly generated SiteAuditReport is stored in MongoDB. This step then intelligently retrieves the latest and the previous audit reports to perform a detailed, page-by-page and metric-by-metric comparison.

Key functionalities of this step include:

* The system queries your dedicated SiteAuditReport collection in MongoDB.

* It retrieves the most recently completed audit report (the "current" state).

* It identifies and retrieves the audit report immediately preceding the current one (the "previous" state).

* In cases where no previous audit exists (e.g., the very first audit), the diff report will simply indicate all findings as "new issues."

* The comparison is performed at a granular level, analyzing each audited page individually.

* For each page, every metric from the 12-point SEO checklist is compared between the current and previous reports.

* This includes:

* Meta Title & Description (uniqueness, presence, length)

* H1 Tag (presence, uniqueness)

* Image Alt Attributes (coverage)

* Internal Link Density

* Canonical Tags (presence, correctness)

* Open Graph Tags (presence, correctness)

* Core Web Vitals (LCP, CLS, FID scores and status)

* Structured Data (presence, validity)

* Mobile Viewport (presence, correctness)

* The comparison logic identifies specific changes:

New Issues: Problems found in the current audit that were not* present in the previous one.

Resolved Issues: Problems present in the previous audit that are no longer* found in the current one.

* Regressions: Metrics that have worsened (e.g., CWV scores decreased, alt tag coverage dropped).

* Improvements: Metrics that have improved (e.g., CWV scores increased, new canonical tags added).

* Unchanged Issues: Problems that persist across both audits.

* The output of this step is a structured JSON or similar data format representing the "diff."

* This report is designed for clarity and actionability, categorizing changes by page and by SEO metric.


2. Output: The Site Audit Diff Report

The generated diff report provides a clear, concise, and actionable overview of how your site's SEO health has changed since the last audit. It's designed to help you quickly identify what needs attention and celebrate what has been fixed.

2.1. Report Structure

The diff report is typically structured as follows:

* totalNewIssues: Count of new issues identified.

* totalResolvedIssues: Count of issues resolved.

* totalRegressions: Count of metrics that worsened.

* totalImprovements: Count of metrics that improved.

* pagesAffected: Count of unique pages with changes.

* url: The URL of the page being analyzed.

* status: Overall status for the page (e.g., "Improved", "Regressed", "Mixed Changes", "No Change").

* metricChanges: An array of objects detailing changes for each SEO metric on that page.

* metricName: e.g., "metaTitle", "h1Tag", "lcpScore", "imageAltCoverage".

* changeType: "New Issue", "Resolved", "Improved", "Regressed", "Unchanged Issue".

* previousValue: The value/status of the metric in the previous audit.

* currentValue: The value/status of the metric in the current audit.

* details: Specific information about the change (e.g., "Meta title too long (65 chars vs 58 chars previously)", "LCP score decreased by 0.5s").

* fixSuggestionId: (Optional) Reference to a potential fix suggestion generated by Gemini in a later step.

2.2. Example Diff Report Snippet (Conceptual)

json • 2,270 chars
{
  "auditIdCurrent": "65e23a6b01d4c2f3e4a5b6c7",
  "auditIdPrevious": "65d12b5a90c3b1e2d3f4a5b6",
  "auditDateCurrent": "2024-03-03T02:00:00Z",
  "auditDatePrevious": "2024-02-25T02:00:00Z",
  "summary": {
    "totalNewIssues": 5,
    "totalResolvedIssues": 3,
    "totalRegressions": 1,
    "totalImprovements": 2,
    "pagesAffected": 4
  },
  "pageChanges": [
    {
      "url": "https://www.example.com/product/new-item",
      "status": "New Issues",
      "metricChanges": [
        {
          "metricName": "h1Tag",
          "changeType": "New Issue",
          "previousValue": "Present & Unique",
          "currentValue": "Missing",
          "details": "H1 tag is now missing on this page.",
          "fixSuggestionId": "fix_h1_001"
        },
        {
          "metricName": "imageAltCoverage",
          "changeType": "New Issue",
          "previousValue": "100%",
          "currentValue": "75%",
          "details": "New images added without alt attributes, coverage dropped.",
          "fixSuggestionId": "fix_alt_002"
        }
      ]
    },
    {
      "url": "https://www.example.com/blog/old-post",
      "status": "Resolved Issues",
      "metricChanges": [
        {
          "metricName": "metaDescription",
          "changeType": "Resolved",
          "previousValue": "Too Short (<50 chars)",
          "currentValue": "Optimal (150 chars)",
          "details": "Meta description has been updated to optimal length.",
          "fixSuggestionId": null
        }
      ]
    },
    {
      "url": "https://www.example.com/category/widgets",
      "status": "Regressed",
      "metricChanges": [
        {
          "metricName": "lcpScore",
          "changeType": "Regressed",
          "previousValue": "2.1s (Good)",
          "currentValue": "3.5s (Needs Improvement)",
          "details": "Largest Contentful Paint (LCP) score significantly increased.",
          "fixSuggestionId": "fix_cwv_lcp_003"
        },
        {
          "metricName": "internalLinkDensity",
          "changeType": "Improved",
          "previousValue": "Low (2 links)",
          "currentValue": "Medium (8 links)",
          "details": "Number of internal links on page increased.",
          "fixSuggestionId": null
        }
      ]
    }
  ]
}
Sandboxed live preview

Workflow Step 1 of 5: Puppeteer Site Crawl Initiation

This document details the execution and outcomes of Step 1: puppeteer → crawl for your "Site SEO Auditor" workflow. This crucial initial phase involves systematically traversing your website to identify all accessible pages, laying the groundwork for the subsequent in-depth SEO audit.


1. Step Objective

The primary objective of this step is to perform a comprehensive, headless crawl of your target website. Using Puppeteer, we simulate a real user's browser experience to discover all unique, internal URLs, capture their raw HTML content, and record essential initial load metrics. This ensures that the SEO audit covers the entirety of your site's discoverable content, including pages rendered via JavaScript.


2. Mechanism: How the Crawl Works

Our headless crawler leverages Google's Puppeteer library to interact with your website as a full-fledged browser would. This provides several key advantages over traditional static crawlers:

  • Headless Browser Emulation: A Chromium browser instance runs in the background, capable of executing JavaScript, rendering dynamic content, and accurately reflecting the user's view of your pages.
  • Dynamic Content Discovery: Unlike basic HTTP request crawlers, Puppeteer waits for pages to fully load and JavaScript to execute, ensuring that links injected or modified by client-side scripts are discovered and followed.
  • User-Agent Simulation: The crawler can be configured to mimic specific user agents (e.g., Googlebot, desktop browser, mobile browser) to observe site behavior under different conditions.
  • Link Extraction: Once a page is fully loaded, all internal <a> tags with href attributes are identified and added to a queue for subsequent crawling. External links are noted but not followed to maintain crawl scope.
  • Page Content Capture: For each successfully crawled URL, the complete rendered HTML content (DOM snapshot) is captured.
  • Resource Handling: The crawler can optionally block certain resource types (e.g., images, fonts, CSS) to optimize crawl speed, although for a full SEO audit, these are typically allowed to ensure accurate page rendering and performance metrics.
  • Error Handling: Robust mechanisms are in place to handle network errors, timeouts, HTTP status codes (e.g., 404, 500), and redirect chains, ensuring a resilient crawl.
  • Crawl Depth Management: The crawler respects a configurable crawl depth to prevent infinite loops and manage resource consumption.

3. Inputs for the Crawl

The following parameters were utilized to initiate and control the website crawl:

  • Target Website URL: [Your Website URL] (e.g., https://www.yourdomain.com)
  • Crawl Depth: [Default/Configured Depth] (e.g., 3 – meaning it will follow links up to 3 levels deep from the starting URL)
  • User Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 (Simulating a standard desktop browser for initial comprehensive discovery)
  • Page Load Timeout: 60000 ms (60 seconds per page before timing out)
  • Request Concurrency: [Configured Concurrency] (e.g., 5 simultaneous page requests to balance speed and server load)
  • Exclusion Patterns (Optional): Any specified URL patterns (e.g., /admin/, /private-area/) were excluded from the crawl.

4. Outputs Generated by the Crawl

Upon successful completion, the crawl step generates the following critical data points for each discovered unique URL:

  • Discovered URL: The full URL of the page.
  • HTTP Status Code: The final HTTP status code received (e.g., 200 OK, 301 Redirect, 404 Not Found).
  • Final URL (after redirects): If redirects occurred, the ultimate destination URL.
  • Raw HTML Content: The complete, rendered HTML source code of the page at the time of crawl. This is essential for parsing all SEO-critical elements.
  • Initial Load Performance Metrics: Basic timing metrics such as DNS lookup time, TCP connection time, TTFB (Time To First Byte), and DOMContentLoaded event time. These provide an early indicator for Core Web Vitals.
  • Internal Links Found: A list of all unique internal links discovered on the page, which are then queued for further crawling (if within depth limits).
  • External Links Found: A list of all unique external links discovered on the page.
  • Crawl Timestamp: The exact time the page was crawled.
  • Crawl Errors/Warnings: Any specific issues encountered during the crawl of that particular page (e.g., timeout, navigation error).

5. Deliverables for the Customer (After Step 1 Completion)

Upon the successful conclusion of the crawling phase, you will receive:

  • Crawl Summary Report: A high-level overview including:

* Total number of unique URLs discovered.

* Number of unique URLs successfully crawled (HTTP 200).

* Number of URLs resulting in redirects (HTTP 3xx).

* Number of URLs resulting in client errors (HTTP 4xx, e.g., 404 Not Found).

* Number of URLs resulting in server errors (HTTP 5xx).

* Total crawl duration.

  • Raw URL List: A comprehensive list of all unique URLs identified on your website during this crawl.
  • Initial Status Check: Notification of any critical issues encountered during the crawl that might indicate site-wide problems (e.g., the site being unreachable, excessive redirects on the homepage).

6. Actionable Insights & Next Steps

With the crawl data successfully gathered, the system is now ready to proceed to the next stage of the Site SEO Auditor workflow:

  • Data Handover to Step 2: The collected HTML content, URL lists, and initial metrics are securely passed to Step 2: gemini → seo_audit.
  • Initiation of SEO Audit: The subsequent step will begin processing each discovered page against the 12-point SEO checklist, analyzing the captured HTML for meta tags, H1s, image alts, structured data, and more.
  • Performance Deep Dive: The initial load metrics will be used as a foundation for a more detailed Core Web Vitals assessment in later stages.

This completes the foundational crawling step, ensuring that our auditor has a complete and accurate map of your website before commencing the detailed SEO analysis.


3. Actionable Insights & Next Steps

This detailed diff report is a critical deliverable, providing immediate insights into the impact of recent website changes on your SEO performance.

  • Prioritization: Quickly identify new critical issues or regressions that require immediate attention.
  • Validation: Confirm that previous SEO fixes have been successfully implemented and resolved.
  • Trend Analysis: Over time, these diff reports build a history, allowing you to observe long-term trends in your site's SEO health.
  • Development Feedback: Pinpoint specific development changes that might have inadvertently affected SEO (e.g., new templates missing H1s, image uploads without alt text).

The output of this hive_db → diff step will now be passed to the subsequent stages of the workflow, particularly for generating specific fixes for identified broken elements using Gemini.

gemini Output

Step 3 of 5: AI-Powered Fix Generation (Gemini)

This crucial step leverages Google's advanced Gemini AI to not only identify SEO issues but also to generate precise, actionable fixes for them. Instead of merely presenting a list of problems, the Site SEO Auditor provides you with direct, implementable solutions, significantly streamlining your optimization efforts.


Process Overview: From Issue Detection to AI-Generated Fix

  1. Issue Identification: Following the comprehensive crawl (Step 2), our system flags all elements on your site that do not meet the 12-point SEO checklist criteria. This includes missing tags, duplicate content, accessibility gaps, and structural inconsistencies.
  2. Contextual Data Extraction: For each identified issue, the system extracts relevant contextual information. This includes the specific page URL, the surrounding HTML code, existing content, image attributes, and any other data points necessary for Gemini to understand the problem fully.
  3. Gemini Analysis & Fix Generation: The extracted data for each "broken element" is fed into Gemini. Gemini then analyzes the issue within its context and generates an exact, code-level fix or a highly specific recommendation designed to resolve the problem efficiently and effectively.

Gemini's Role in Generating Exact Fixes

Gemini acts as your intelligent SEO developer, providing solutions that are often ready for direct implementation. Here's how it addresses various common SEO issues:

  • Meta Title & Description Uniqueness:

* Issue: Duplicate, missing, or overly short/long meta titles and descriptions.

* Gemini Fix: Generates unique, compelling, and keyword-optimized meta titles and descriptions tailored to the page's content, ensuring they meet character limits and encourage click-throughs.

* Example: For a product page with a generic meta description, Gemini might suggest: <meta name="description" content="Shop the [Product Name] – [Key Feature 1] & [Key Feature 2]. Fast shipping & 5-star reviews. Discover yours today!">

  • H1 Tag Presence & Uniqueness:

* Issue: Missing H1 tags, multiple H1s, or non-descriptive H1s.

* Gemini Fix: Suggests a single, clear, and keyword-rich H1 tag that accurately reflects the primary topic of the page, or recommends which existing H1 to retain/modify if multiple are present.

* Example: For a blog post missing an H1, Gemini might suggest: <h1>[Blog Post Title Extracted from Content]</h1>

  • Image Alt Text Coverage:

* Issue: Images missing alt attributes or having non-descriptive alt text.

* Gemini Fix: Analyzes image filenames, surrounding text, and page context to generate descriptive and SEO-friendly alt text for each image, improving accessibility and search engine understanding.

* Example: For an image named product-xyz-blue.jpg within a product description, Gemini might suggest: <img src="product-xyz-blue.jpg" alt="Blue [Product Name] with [Specific Detail]">

  • Internal Link Density:

* Issue: Pages with insufficient internal links pointing to them, or missed opportunities for internal linking.

* Gemini Fix: Identifies relevant anchor text within existing page content and suggests adding internal links to other high-priority pages on your site, improving site structure and link equity flow.

* Example: For a page discussing "eco-friendly practices," Gemini might suggest: "Learn more about our commitment to <a href="/sustainability">sustainability initiatives</a>."

  • Canonical Tags:

* Issue: Missing or incorrect canonical tags, leading to potential duplicate content issues.

* Gemini Fix: Generates the correct <link rel="canonical"> tag, pointing to the preferred version of the page, based on the site's structure and content.

* Example: For a URL like example.com/product?color=blue, Gemini might suggest: <link rel="canonical" href="https://www.example.com/product/blue-product-name">

  • Open Graph (OG) Tags:

* Issue: Missing or incomplete Open Graph tags, hindering social media sharing previews.

* Gemini Fix: Generates all essential OG tags (e.g., og:title, og:description, og:image, og:url, og:type) based on the page's content, ensuring optimal display when shared on platforms like Facebook, X (Twitter), and LinkedIn.

* Example: <meta property="og:title" content="[Page Title]"> <meta property="og:description" content="[Page Meta Description]"> <meta property="og:image" content="[Primary Page Image URL]">

  • Core Web Vitals (LCP/CLS/FID) - Optimization Recommendations:

* Issue: Pages with poor performance metrics (e.g., slow Largest Contentful Paint, high Cumulative Layout Shift).

* Gemini Fix: While not direct code insertions, Gemini provides highly specific, code-level recommendations for optimizing performance. This might include suggestions for:

* Lazy loading images and videos.

* Preloading critical resources (fonts, CSS).

* Specifying image and video dimensions to prevent CLS.

* Minimizing render-blocking resources.

* Optimizing server response times.

* Example: "Implement loading='lazy' for all off-screen images. Consider preloading <link rel="preload" href="/fonts/myfont.woff2" as="font" type="font/woff2" crossorigin> for your primary headline font."

  • Structured Data Presence:

* Issue: Missing or incomplete Schema.org structured data, limiting rich snippet potential.

* Gemini Fix: Based on the page's content type (e.g., Article, Product, Recipe, LocalBusiness), Gemini generates the appropriate JSON-LD schema markup, ready to be embedded in the page's <head> or <body>.

* Example: For a product page, Gemini might generate:


        <script type="application/ld+json">
        {
          "@context": "https://schema.org/",
          "@type": "Product",
          "name": "[Product Name]",
          "image": "[Product Image URL]",
          "description": "[Product Description]",
          "sku": "[Product SKU]",
          "offers": {
            "@type": "Offer",
            "url": "[Page URL]",
            "priceCurrency": "USD",
            "price": "[Product Price]",
            "itemCondition": "https://schema.org/NewCondition",
            "availability": "https://schema.org/InStock"
          }
        }
        </script>
  • Mobile Viewport Configuration:

* Issue: Missing or incorrect <meta name="viewport"> tag, leading to poor mobile responsiveness.

* Gemini Fix: Provides the standard and recommended viewport meta tag for optimal mobile display.

* Example: <meta name="viewport" content="width=device-width, initial-scale=1">


Output & Deliverable

The output from this step is a comprehensive list of identified issues, each paired with its specific Gemini-generated fix. These fixes are presented in a clear, actionable format, often as direct code snippets or explicit instructions, ready for your development team to implement.

This detailed "before" (identified issue) and "after" (proposed fix) information will be a core component of your final Site Audit Report, providing a clear roadmap for improving your site's SEO performance.

hive_db Output

Step 4 of 5: hive_db → Upsert - Storing Your Site Audit Report

This crucial step finalizes the "Site SEO Auditor" workflow by systematically storing all generated audit data and recommended fixes into your dedicated MongoDB instance (hive_db). This ensures that your site's SEO performance is meticulously tracked, providing a comprehensive historical record and actionable insights.


Step Overview: Data Persistence with hive_db Upsert

Once the headless crawler (Puppeteer) has completed its audit, Gemini has generated specific fixes for identified issues, and Core Web Vitals have been measured, all this rich data is compiled into a structured SiteAuditReport. The hive_db upsert operation then intelligently handles the storage:

  1. Intelligent Insertion/Update: An "upsert" operation means that if an audit report for your site already exists (e.g., from a previous scheduled scan), it will be updated with the latest findings. If no prior report exists, a new one will be created.
  2. Comprehensive Data Storage: Every detail from the 12-point SEO checklist, Core Web Vitals, and Gemini's generated fixes are meticulously organized and stored.
  3. Historical Tracking: By updating existing records or creating new ones with timestamps, we build a continuous history of your site's SEO performance, enabling "before and after" comparisons over time.
  4. Before/After Diff Generation: As part of the upsert process, the system compares the newly generated audit report against the most recent previous report. A high-level summary of significant changes, improvements, or new issues ("before/after diff") is then calculated and stored within the new report, providing immediate context on your site's SEO evolution.

SiteAuditReport Document Structure in MongoDB

The audit results will be stored as a SiteAuditReport document in a dedicated collection within your hive_db. Below is the detailed structure, outlining the key information captured:


{
  "_id": ObjectId("..."),           // Unique identifier for this audit report
  "siteUrl": "https://www.yourwebsite.com", // The URL of the audited site
  "auditTimestamp": ISODate("2023-10-27T02:00:00.000Z"), // Timestamp of when the audit was completed
  "auditType": "Scheduled",         // "Scheduled" or "On-Demand"
  "overallStatus": "Completed with Issues", // Overall status: "Completed", "Completed with Issues", "Failed"
  "totalPagesCrawled": 150,         // Total number of unique pages successfully crawled
  "issuesFoundCount": 45,           // Total number of unique issues identified across all pages
  "pagesWithFixesCount": 20,        // Number of pages for which Gemini generated fixes

  "summaryMetrics": {
    "averageLCP": "2.5s",
    "averageCLS": "0.05",
    "averageFID": "50ms",
    "metaTitleIssues": 10,
    "metaDescriptionIssues": 8,
    "h1MissingIssues": 5,
    "imageAltMissingIssues": 12,
    "canonicalTagIssues": 3,
    "openGraphTagIssues": 7,
    "structuredDataMissingIssues": 4,
    "mobileViewportIssues": 1
    // ... other aggregated metrics
  },

  "beforeAfterDiff": {
    "lastAuditTimestamp": ISODate("2023-10-20T02:00:00.000Z"), // Timestamp of the previous audit
    "summary": "Overall SEO score improved by 5%. Reduced meta title duplicates by 3, but 2 new broken image links were detected.",
    "changes": [
      {
        "metric": "metaTitleUniqueness",
        "previousValue": "70% unique",
        "currentValue": "80% unique",
        "status": "Improved"
      },
      {
        "metric": "totalBrokenLinks",
        "previousValue": 5,
        "currentValue": 7,
        "status": "Degraded"
      }
      // ... more detailed diff for key metrics
    ]
  },

  "pageAudits": [ // Array containing detailed audit results for each crawled page
    {
      "pageUrl": "https://www.yourwebsite.com/product-page-1",
      "crawlStatus": "Success", // "Success", "Redirected", "Error"
      "statusCode": 200,
      "pageLCP": "2.1s",
      "pageCLS": "0.03",
      "pageFID": "45ms",
      "findings": [ // Specific findings for this page
        {
          "check": "metaTitle",
          "status": "Pass",
          "value": "Product Page 1 - Best Gadget Ever",
          "isUnique": true
        },
        {
          "check": "metaDescription",
          "status": "Fail",
          "value": "A generic description.",
          "issueDetails": "Meta description too short and not unique.",
          "geminiFix": {
            "prompt": "Generate a unique, compelling meta description for a product page selling 'Best Gadget Ever'.",
            "fixGenerated": "Discover the 'Best Gadget Ever' – your ultimate solution for [benefit 1] and [benefit 2]. Shop now and revolutionize your experience!",
            "confidence": "High"
          }
        },
        {
          "check": "h1Presence",
          "status": "Pass",
          "value": "<h1>The Best Gadget Ever</h1>"
        },
        {
          "check": "imageAltCoverage",
          "status": "Fail",
          "issueDetails": "Missing alt text for 2 images.",
          "brokenElements": [
            {
              "type": "img",
              "selector": "img.product-image-main",
              "attribute": "alt",
              "currentValue": "",
              "issue": "Missing alt text",
              "geminiFix": {
                "prompt": "Generate descriptive alt text for an image of 'Best Gadget Ever' on a product page.",
                "fixGenerated": "A close-up view of the 'Best Gadget Ever' in its sleek silver casing.",
                "confidence": "High"
              }
            }
          ]
        },
        {
          "check": "internalLinkDensity",
          "status": "Pass",
          "count": 15
        },
        {
          "check": "canonicalTag",
          "status": "Pass",
          "value": "https://www.yourwebsite.com/product-page-1"
        },
        {
          "check": "openGraphTags",
          "status": "Fail",
          "issueDetails": "Missing og:image and og:description.",
          "geminiFix": { /* ... fix details ... */ }
        },
        {
          "check": "structuredDataPresence",
          "status": "Pass",
          "schemaType": "Product"
        },
        {
          "check": "mobileViewport",
          "status": "Pass",
          "value": "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
        }
      ]
    }
    // ... more page audit objects
  ],

  "geminiFixesAggregate": [ // An aggregate list of all fixes generated for this audit
    {
      "pageUrl": "https://www.yourwebsite.com/product-page-1",
      "check": "metaDescription",
      "issueDetails": "Meta description too short and not unique.",
      "fix": "Discover the 'Best Gadget Ever' – your ultimate solution for [benefit 1] and [benefit 2]. Shop now and revolutionize your experience!"
    },
    {
      "pageUrl": "https://www.yourwebsite.com/product-page-1",
      "check": "imageAltCoverage",
      "issueDetails": "Missing alt text for image.product-image-main",
      "fix": "A close-up view of the 'Best Gadget Ever' in its sleek silver casing."
    }
    // ... more aggregated fixes
  ]
}

Key Benefits of Persistent Data Storage

Storing your SiteAuditReport in MongoDB provides significant advantages:

  • Historical Performance Tracking: Effortlessly monitor your site's SEO health and Core Web Vitals over time. Track improvements, regressions, and the long-term impact of your SEO efforts.
  • Actionable & Centralized Insights: All identified issues and Gemini-generated fixes are consolidated in one place, making it easy for your team to prioritize and implement changes.
  • "Before and After" Analysis: The beforeAfterDiff field gives you an immediate summary of how your site's SEO posture has changed since the last audit, highlighting progress or new areas of concern.
  • Robust Reporting & Analytics: The structured data enables the generation of custom reports, dashboards, and in-depth analysis of specific SEO metrics across your entire site or individual pages.
  • Accountability & Transparency: Maintain a clear, auditable record of your site's SEO status and the actions taken, fostering transparency within your team and with stakeholders.
  • Foundation for Automation: This data forms the bedrock for future automated actions, such as triggering notifications for critical issues or integrating with project management tools.

Next Steps

With your SiteAuditReport securely stored in hive_db, the system is now ready for the final step: generating a comprehensive, customer-facing report. This report will leverage the data stored in this step to present a clear overview of your site's SEO performance, identified issues, recommended fixes, and the crucial "before/after" comparison.

hive_db Output

Step 5 of 5: hive_dbconditional_update - Site SEO Auditor

This final step in the "Site SEO Auditor" workflow is critical for persisting all collected audit data, generating a valuable "before/after" comparison, and making the insights accessible. The hive_db component within PantheraHive is responsible for securely storing your comprehensive SiteAuditReport in our MongoDB database.

1. Step Description: Data Persistence and Diff Generation

The hive_db → conditional_update operation performs the following key functions:

  • Receives Finalized Audit Report: It ingests the complete, processed audit data from the previous steps, including all page-level SEO checks, Core Web Vitals, identified issues, and Gemini-generated fix recommendations.
  • Retrieves Previous Audit Data: The system queries the database for the most recent SiteAuditReport pertaining to your specific site. This is foundational for providing comparative analysis.
  • Generates "Before/After" Diff: A sophisticated comparison engine analyzes the newly generated report against the previously stored report. This process meticulously identifies:

* New Issues: SEO violations or performance degradations that were not present or detected in the previous audit.

* Resolved Issues: Issues that were identified in a prior audit but are no longer present, indicating successful remediation.

* Metric Changes: Significant fluctuations in Core Web Vitals (LCP, CLS, FID) or other quantifiable metrics.

* Content Changes: Detection of new pages, removed pages, or substantial shifts in page structure impacting SEO elements.

  • Conditional Database Operation:

* If this is the first audit for your site, a new SiteAuditReport document is created and inserted into the MongoDB database.

For subsequent audits, a new SiteAuditReport document is also inserted, preserving a historical record. This new document includes a reference to the _id of the previous* report and contains the generated "before/after" diff. This strategy ensures a complete audit history is maintained.

  • Workflow Completion: Marks the current audit run as successfully completed within the PantheraHive system.

2. Expected SiteAuditReport Structure in MongoDB

Each audit run results in a detailed SiteAuditReport document stored in MongoDB, structured to provide maximum insight and historical context:


{
  "_id": ObjectId("..."),
  "siteUrl": "https://www.yourwebsite.com",
  "auditTimestamp": ISODate("2023-10-29T02:00:00.000Z"),
  "auditType": "scheduled", // or "on_demand"
  "overallStatus": "issues_found", // or "success", "critical_issues"
  "pagesAudited": 150,
  "overallScore": 85, // Aggregate score based on all checks
  "reportDetails": [
    {
      "pageUrl": "https://www.yourwebsite.com/",
      "seoMetrics": {
        "metaTitle": { "status": "pass", "value": "Your Homepage Title | Company Name" },
        "metaDescription": { "status": "fail", "issue": "Duplicate description", "value": "..." },
        "h1Presence": { "status": "pass", "value": "Welcome to Our Site" },
        "imageAltCoverage": { "status": "fail", "issue": "3 images missing alt text" },
        "internalLinkDensity": { "status": "pass", "count": 25 },
        "canonicalTag": { "status": "pass", "value": "https://www.yourwebsite.com/" },
        "openGraphTags": { "status": "pass", "missing": [] },
        "structuredData": { "status": "pass", "schemaTypes": ["Organization", "WebSite"] },
        "mobileViewport": { "status": "pass" }
      },
      "coreWebVitals": {
        "LCP": { "score": 2.2, "status": "good" }, // Seconds
        "CLS": { "score": 0.05, "status": "good" },
        "FID": { "score": 30, "status": "good" } // Milliseconds
      },
      "issuesFound": [
        {
          "check": "Meta Description Uniqueness",
          "description": "Meta description is a duplicate of /products/item-a",
          "severity": "medium",
          "recommendedFix": "Gemini: Update the meta description for this page to be unique and keyword-rich, focusing on 'homepage specific content'. Example: '<meta name=\"description\" content=\"Discover our full range of innovative solutions and services tailored for [target audience]. Explore our mission and values.\">'"
        },
        {
          "check": "Image Alt Text",
          "description": "Image 'logo.png' is missing an alt attribute.",
          "severity": "low",
          "recommendedFix": "Gemini: Add descriptive alt text to the image 'logo.png'. Example: '<img src=\"logo.png\" alt=\"Company Name Logo\">'"
        }
      ]
    }
    // ... more pages
  ],
  "beforeAfterDiff": {
    "summary": "Significant improvements in Core Web Vitals. New duplicate H1 detected on one page.",
    "newIssues": [
      { "check": "H1 Presence", "pageUrl": "/blog/latest-post", "description": "Duplicate H1 tag found." }
    ],
    "resolvedIssues": [
      { "check": "Meta Description Uniqueness", "pageUrl": "/products/old-item", "description": "Previously duplicate, now unique." }
    ],
    "metricChanges": {
      "LCP": { "previous": 3.5, "current": 2.2, "change": -1.3, "unit": "s" },
      "CLS": { "previous": 0.15, "current": 0.05, "change": -0.10, "unit": "" }
    },
    "pagesAdded": ["/new-service-page"],
    "pagesRemoved": ["/old-promo"]
  },
  "previousReportId": ObjectId("...") // Reference to the _id of the previous audit report
}

3. Customer Deliverables and Value

Upon completion of this step, you will gain access to:

  • Comprehensive Site Audit Reports: Each audit run generates a complete, timestamped report detailing the SEO health of every page on your site.
  • Actionable "Before/After" Diff: This is a key feature. Instead of just a new report, you'll immediately see a concise summary of what has changed since the last audit. This allows you to:

* Measure Impact: Quickly assess the effectiveness of recent SEO optimizations or development changes.

* Prioritize New Issues: Immediately identify and address new problems that have emerged.

* Track Progress: Monitor the resolution of previously identified issues.

  • Historical Performance Tracking: The storage of individual audit reports over time provides a robust historical record, enabling trend analysis and long-term performance monitoring.
  • Direct Access to Fixes: All Gemini-generated fix recommendations are stored directly within the audit report, ensuring that actionable advice is always coupled with the identified issue.
  • Dashboard Integration: The structured data from these reports will feed directly into your PantheraHive SEO dashboard, providing intuitive visualizations, detailed drill-downs, and custom reporting capabilities.

4. Availability and Next Steps

Your latest SiteAuditReport, complete with the "before/after" diff, is now securely stored in your dedicated PantheraHive database.

  • Access: You can access this report and all historical audit data via your PantheraHive dashboard, typically under the "SEO Auditor" or "Site Performance" section.
  • Notifications: Depending on your configuration, you may receive an email or dashboard notification confirming the completion of the audit and summarizing key findings.
  • Next Audit: The system is configured to run automatically every Sunday at 2 AM UTC, ensuring continuous monitoring of your site's SEO health. You can also trigger an on-demand audit at any time through your dashboard.

This final step ensures that all the power of the Site SEO Auditor workflow is translated into persistent, actionable insights readily available to you.

site_seo_auditor.txt
Download source file
Copy all content
Full output as text
Download ZIP
IDE-ready project ZIP
Copy share link
Permanent URL for this run
Get Embed Code
Embed this result on any website
Print / Save PDF
Use browser print dialog
\n ```\n\n* **Mobile Viewport Configuration**:\n * **Issue**: Missing or incorrect `` tag, leading to poor mobile responsiveness.\n * **Gemini Fix**: Provides the standard and recommended viewport meta tag for optimal mobile display.\n * **Example**: ``\n\n---\n\n### Output & Deliverable\n\nThe output from this step is a comprehensive list of identified issues, each paired with its specific Gemini-generated fix. These fixes are presented in a clear, actionable format, often as direct code snippets or explicit instructions, ready for your development team to implement.\n\nThis detailed \"before\" (identified issue) and \"after\" (proposed fix) information will be a core component of your final Site Audit Report, providing a clear roadmap for improving your site's SEO performance.\n\n## Step 4 of 5: `hive_db` → Upsert - Storing Your Site Audit Report\n\nThis crucial step finalizes the \"Site SEO Auditor\" workflow by systematically storing all generated audit data and recommended fixes into your dedicated MongoDB instance (`hive_db`). This ensures that your site's SEO performance is meticulously tracked, providing a comprehensive historical record and actionable insights.\n\n---\n\n### Step Overview: Data Persistence with `hive_db` Upsert\n\nOnce the headless crawler (Puppeteer) has completed its audit, Gemini has generated specific fixes for identified issues, and Core Web Vitals have been measured, all this rich data is compiled into a structured `SiteAuditReport`. The `hive_db` upsert operation then intelligently handles the storage:\n\n1. **Intelligent Insertion/Update**: An \"upsert\" operation means that if an audit report for your site already exists (e.g., from a previous scheduled scan), it will be updated with the latest findings. If no prior report exists, a new one will be created.\n2. **Comprehensive Data Storage**: Every detail from the 12-point SEO checklist, Core Web Vitals, and Gemini's generated fixes are meticulously organized and stored.\n3. **Historical Tracking**: By updating existing records or creating new ones with timestamps, we build a continuous history of your site's SEO performance, enabling \"before and after\" comparisons over time.\n4. **Before/After Diff Generation**: As part of the upsert process, the system compares the newly generated audit report against the most recent previous report. A high-level summary of significant changes, improvements, or new issues (\"before/after diff\") is then calculated and stored within the new report, providing immediate context on your site's SEO evolution.\n\n---\n\n### `SiteAuditReport` Document Structure in MongoDB\n\nThe audit results will be stored as a `SiteAuditReport` document in a dedicated collection within your `hive_db`. Below is the detailed structure, outlining the key information captured:\n\n```json\n{\n \"_id\": ObjectId(\"...\"), // Unique identifier for this audit report\n \"siteUrl\": \"https://www.yourwebsite.com\", // The URL of the audited site\n \"auditTimestamp\": ISODate(\"2023-10-27T02:00:00.000Z\"), // Timestamp of when the audit was completed\n \"auditType\": \"Scheduled\", // \"Scheduled\" or \"On-Demand\"\n \"overallStatus\": \"Completed with Issues\", // Overall status: \"Completed\", \"Completed with Issues\", \"Failed\"\n \"totalPagesCrawled\": 150, // Total number of unique pages successfully crawled\n \"issuesFoundCount\": 45, // Total number of unique issues identified across all pages\n \"pagesWithFixesCount\": 20, // Number of pages for which Gemini generated fixes\n\n \"summaryMetrics\": {\n \"averageLCP\": \"2.5s\",\n \"averageCLS\": \"0.05\",\n \"averageFID\": \"50ms\",\n \"metaTitleIssues\": 10,\n \"metaDescriptionIssues\": 8,\n \"h1MissingIssues\": 5,\n \"imageAltMissingIssues\": 12,\n \"canonicalTagIssues\": 3,\n \"openGraphTagIssues\": 7,\n \"structuredDataMissingIssues\": 4,\n \"mobileViewportIssues\": 1\n // ... other aggregated metrics\n },\n\n \"beforeAfterDiff\": {\n \"lastAuditTimestamp\": ISODate(\"2023-10-20T02:00:00.000Z\"), // Timestamp of the previous audit\n \"summary\": \"Overall SEO score improved by 5%. Reduced meta title duplicates by 3, but 2 new broken image links were detected.\",\n \"changes\": [\n {\n \"metric\": \"metaTitleUniqueness\",\n \"previousValue\": \"70% unique\",\n \"currentValue\": \"80% unique\",\n \"status\": \"Improved\"\n },\n {\n \"metric\": \"totalBrokenLinks\",\n \"previousValue\": 5,\n \"currentValue\": 7,\n \"status\": \"Degraded\"\n }\n // ... more detailed diff for key metrics\n ]\n },\n\n \"pageAudits\": [ // Array containing detailed audit results for each crawled page\n {\n \"pageUrl\": \"https://www.yourwebsite.com/product-page-1\",\n \"crawlStatus\": \"Success\", // \"Success\", \"Redirected\", \"Error\"\n \"statusCode\": 200,\n \"pageLCP\": \"2.1s\",\n \"pageCLS\": \"0.03\",\n \"pageFID\": \"45ms\",\n \"findings\": [ // Specific findings for this page\n {\n \"check\": \"metaTitle\",\n \"status\": \"Pass\",\n \"value\": \"Product Page 1 - Best Gadget Ever\",\n \"isUnique\": true\n },\n {\n \"check\": \"metaDescription\",\n \"status\": \"Fail\",\n \"value\": \"A generic description.\",\n \"issueDetails\": \"Meta description too short and not unique.\",\n \"geminiFix\": {\n \"prompt\": \"Generate a unique, compelling meta description for a product page selling 'Best Gadget Ever'.\",\n \"fixGenerated\": \"Discover the 'Best Gadget Ever' – your ultimate solution for [benefit 1] and [benefit 2]. Shop now and revolutionize your experience!\",\n \"confidence\": \"High\"\n }\n },\n {\n \"check\": \"h1Presence\",\n \"status\": \"Pass\",\n \"value\": \"

The Best Gadget Ever

\"\n },\n {\n \"check\": \"imageAltCoverage\",\n \"status\": \"Fail\",\n \"issueDetails\": \"Missing alt text for 2 images.\",\n \"brokenElements\": [\n {\n \"type\": \"img\",\n \"selector\": \"img.product-image-main\",\n \"attribute\": \"alt\",\n \"currentValue\": \"\",\n \"issue\": \"Missing alt text\",\n \"geminiFix\": {\n \"prompt\": \"Generate descriptive alt text for an image of 'Best Gadget Ever' on a product page.\",\n \"fixGenerated\": \"A close-up view of the 'Best Gadget Ever' in its sleek silver casing.\",\n \"confidence\": \"High\"\n }\n }\n ]\n },\n {\n \"check\": \"internalLinkDensity\",\n \"status\": \"Pass\",\n \"count\": 15\n },\n {\n \"check\": \"canonicalTag\",\n \"status\": \"Pass\",\n \"value\": \"https://www.yourwebsite.com/product-page-1\"\n },\n {\n \"check\": \"openGraphTags\",\n \"status\": \"Fail\",\n \"issueDetails\": \"Missing og:image and og:description.\",\n \"geminiFix\": { /* ... fix details ... */ }\n },\n {\n \"check\": \"structuredDataPresence\",\n \"status\": \"Pass\",\n \"schemaType\": \"Product\"\n },\n {\n \"check\": \"mobileViewport\",\n \"status\": \"Pass\",\n \"value\": \"\"\n }\n ]\n }\n // ... more page audit objects\n ],\n\n \"geminiFixesAggregate\": [ // An aggregate list of all fixes generated for this audit\n {\n \"pageUrl\": \"https://www.yourwebsite.com/product-page-1\",\n \"check\": \"metaDescription\",\n \"issueDetails\": \"Meta description too short and not unique.\",\n \"fix\": \"Discover the 'Best Gadget Ever' – your ultimate solution for [benefit 1] and [benefit 2]. Shop now and revolutionize your experience!\"\n },\n {\n \"pageUrl\": \"https://www.yourwebsite.com/product-page-1\",\n \"check\": \"imageAltCoverage\",\n \"issueDetails\": \"Missing alt text for image.product-image-main\",\n \"fix\": \"A close-up view of the 'Best Gadget Ever' in its sleek silver casing.\"\n }\n // ... more aggregated fixes\n ]\n}\n```\n\n---\n\n### Key Benefits of Persistent Data Storage\n\nStoring your `SiteAuditReport` in MongoDB provides significant advantages:\n\n* **Historical Performance Tracking**: Effortlessly monitor your site's SEO health and Core Web Vitals over time. Track improvements, regressions, and the long-term impact of your SEO efforts.\n* **Actionable & Centralized Insights**: All identified issues and Gemini-generated fixes are consolidated in one place, making it easy for your team to prioritize and implement changes.\n* **\"Before and After\" Analysis**: The `beforeAfterDiff` field gives you an immediate summary of how your site's SEO posture has changed since the last audit, highlighting progress or new areas of concern.\n* **Robust Reporting & Analytics**: The structured data enables the generation of custom reports, dashboards, and in-depth analysis of specific SEO metrics across your entire site or individual pages.\n* **Accountability & Transparency**: Maintain a clear, auditable record of your site's SEO status and the actions taken, fostering transparency within your team and with stakeholders.\n* **Foundation for Automation**: This data forms the bedrock for future automated actions, such as triggering notifications for critical issues or integrating with project management tools.\n\n---\n\n### Next Steps\n\nWith your `SiteAuditReport` securely stored in `hive_db`, the system is now ready for the final step: generating a comprehensive, customer-facing report. This report will leverage the data stored in this step to present a clear overview of your site's SEO performance, identified issues, recommended fixes, and the crucial \"before/after\" comparison.\n\n## Step 5 of 5: `hive_db` → `conditional_update` - Site SEO Auditor\n\nThis final step in the \"Site SEO Auditor\" workflow is critical for persisting all collected audit data, generating a valuable \"before/after\" comparison, and making the insights accessible. The `hive_db` component within PantheraHive is responsible for securely storing your comprehensive `SiteAuditReport` in our MongoDB database.\n\n### 1. Step Description: Data Persistence and Diff Generation\n\nThe `hive_db → conditional_update` operation performs the following key functions:\n\n* **Receives Finalized Audit Report**: It ingests the complete, processed audit data from the previous steps, including all page-level SEO checks, Core Web Vitals, identified issues, and Gemini-generated fix recommendations.\n* **Retrieves Previous Audit Data**: The system queries the database for the most recent `SiteAuditReport` pertaining to your specific site. This is foundational for providing comparative analysis.\n* **Generates \"Before/After\" Diff**: A sophisticated comparison engine analyzes the newly generated report against the previously stored report. This process meticulously identifies:\n * **New Issues**: SEO violations or performance degradations that were not present or detected in the previous audit.\n * **Resolved Issues**: Issues that were identified in a prior audit but are no longer present, indicating successful remediation.\n * **Metric Changes**: Significant fluctuations in Core Web Vitals (LCP, CLS, FID) or other quantifiable metrics.\n * **Content Changes**: Detection of new pages, removed pages, or substantial shifts in page structure impacting SEO elements.\n* **Conditional Database Operation**:\n * If this is the **first audit** for your site, a new `SiteAuditReport` document is created and inserted into the MongoDB database.\n * For **subsequent audits**, a *new* `SiteAuditReport` document is also inserted, preserving a historical record. This new document includes a reference to the `_id` of the *previous* report and contains the generated \"before/after\" diff. This strategy ensures a complete audit history is maintained.\n* **Workflow Completion**: Marks the current audit run as successfully completed within the PantheraHive system.\n\n### 2. Expected `SiteAuditReport` Structure in MongoDB\n\nEach audit run results in a detailed `SiteAuditReport` document stored in MongoDB, structured to provide maximum insight and historical context:\n\n```json\n{\n \"_id\": ObjectId(\"...\"),\n \"siteUrl\": \"https://www.yourwebsite.com\",\n \"auditTimestamp\": ISODate(\"2023-10-29T02:00:00.000Z\"),\n \"auditType\": \"scheduled\", // or \"on_demand\"\n \"overallStatus\": \"issues_found\", // or \"success\", \"critical_issues\"\n \"pagesAudited\": 150,\n \"overallScore\": 85, // Aggregate score based on all checks\n \"reportDetails\": [\n {\n \"pageUrl\": \"https://www.yourwebsite.com/\",\n \"seoMetrics\": {\n \"metaTitle\": { \"status\": \"pass\", \"value\": \"Your Homepage Title | Company Name\" },\n \"metaDescription\": { \"status\": \"fail\", \"issue\": \"Duplicate description\", \"value\": \"...\" },\n \"h1Presence\": { \"status\": \"pass\", \"value\": \"Welcome to Our Site\" },\n \"imageAltCoverage\": { \"status\": \"fail\", \"issue\": \"3 images missing alt text\" },\n \"internalLinkDensity\": { \"status\": \"pass\", \"count\": 25 },\n \"canonicalTag\": { \"status\": \"pass\", \"value\": \"https://www.yourwebsite.com/\" },\n \"openGraphTags\": { \"status\": \"pass\", \"missing\": [] },\n \"structuredData\": { \"status\": \"pass\", \"schemaTypes\": [\"Organization\", \"WebSite\"] },\n \"mobileViewport\": { \"status\": \"pass\" }\n },\n \"coreWebVitals\": {\n \"LCP\": { \"score\": 2.2, \"status\": \"good\" }, // Seconds\n \"CLS\": { \"score\": 0.05, \"status\": \"good\" },\n \"FID\": { \"score\": 30, \"status\": \"good\" } // Milliseconds\n },\n \"issuesFound\": [\n {\n \"check\": \"Meta Description Uniqueness\",\n \"description\": \"Meta description is a duplicate of /products/item-a\",\n \"severity\": \"medium\",\n \"recommendedFix\": \"Gemini: Update the meta description for this page to be unique and keyword-rich, focusing on 'homepage specific content'. Example: ''\"\n },\n {\n \"check\": \"Image Alt Text\",\n \"description\": \"Image 'logo.png' is missing an alt attribute.\",\n \"severity\": \"low\",\n \"recommendedFix\": \"Gemini: Add descriptive alt text to the image 'logo.png'. Example: '\\\"Company'\"\n }\n ]\n }\n // ... more pages\n ],\n \"beforeAfterDiff\": {\n \"summary\": \"Significant improvements in Core Web Vitals. New duplicate H1 detected on one page.\",\n \"newIssues\": [\n { \"check\": \"H1 Presence\", \"pageUrl\": \"/blog/latest-post\", \"description\": \"Duplicate H1 tag found.\" }\n ],\n \"resolvedIssues\": [\n { \"check\": \"Meta Description Uniqueness\", \"pageUrl\": \"/products/old-item\", \"description\": \"Previously duplicate, now unique.\" }\n ],\n \"metricChanges\": {\n \"LCP\": { \"previous\": 3.5, \"current\": 2.2, \"change\": -1.3, \"unit\": \"s\" },\n \"CLS\": { \"previous\": 0.15, \"current\": 0.05, \"change\": -0.10, \"unit\": \"\" }\n },\n \"pagesAdded\": [\"/new-service-page\"],\n \"pagesRemoved\": [\"/old-promo\"]\n },\n \"previousReportId\": ObjectId(\"...\") // Reference to the _id of the previous audit report\n}\n```\n\n### 3. Customer Deliverables and Value\n\nUpon completion of this step, you will gain access to:\n\n* **Comprehensive Site Audit Reports**: Each audit run generates a complete, timestamped report detailing the SEO health of every page on your site.\n* **Actionable \"Before/After\" Diff**: This is a key feature. Instead of just a new report, you'll immediately see a concise summary of what has changed since the last audit. This allows you to:\n * **Measure Impact**: Quickly assess the effectiveness of recent SEO optimizations or development changes.\n * **Prioritize New Issues**: Immediately identify and address new problems that have emerged.\n * **Track Progress**: Monitor the resolution of previously identified issues.\n* **Historical Performance Tracking**: The storage of individual audit reports over time provides a robust historical record, enabling trend analysis and long-term performance monitoring.\n* **Direct Access to Fixes**: All Gemini-generated fix recommendations are stored directly within the audit report, ensuring that actionable advice is always coupled with the identified issue.\n* **Dashboard Integration**: The structured data from these reports will feed directly into your PantheraHive SEO dashboard, providing intuitive visualizations, detailed drill-downs, and custom reporting capabilities.\n\n### 4. Availability and Next Steps\n\nYour latest `SiteAuditReport`, complete with the \"before/after\" diff, is now securely stored in your dedicated PantheraHive database.\n\n* **Access**: You can access this report and all historical audit data via your PantheraHive dashboard, typically under the \"SEO Auditor\" or \"Site Performance\" section.\n* **Notifications**: Depending on your configuration, you may receive an email or dashboard notification confirming the completion of the audit and summarizing key findings.\n* **Next Audit**: The system is configured to run automatically every Sunday at 2 AM UTC, ensuring continuous monitoring of your site's SEO health. You can also trigger an on-demand audit at any time through your dashboard.\n\nThis final step ensures that all the power of the Site SEO Auditor workflow is translated into persistent, actionable insights readily available to you.";function phTab(btn,name){document.querySelectorAll(".ph-panel").forEach(function(el){el.classList.remove("active");});document.querySelectorAll(".ph-tab").forEach(function(el){el.classList.remove("active");el.classList.add("inactive");});var p=document.getElementById("panel-"+name);if(p)p.classList.add("active");btn.classList.remove("inactive");btn.classList.add("active");if(name==="preview"){var fr=document.getElementById("ph-preview-frame");if(fr&&!fr.dataset.loaded){if(_phIsHtml){fr.srcdoc=_phCode;}else{var vc=document.getElementById("panel-content");fr.srcdoc=vc?""+vc.innerHTML+"":"

No content

";}fr.dataset.loaded="1";}}}function phCopyCode(){navigator.clipboard.writeText(_phCode).then(function(){var b=document.getElementById("tab-code");if(b){var o=b.innerHTML;b.innerHTML=' Copied!';setTimeout(function(){b.innerHTML=o;},2000);}});}function phCopyAll(){navigator.clipboard.writeText(_phAll).then(function(){alert("Content copied to clipboard!");});}function phDownload(){var content=_phCode||_phAll;if(!content){alert("No content to download.");return;}var fn=_phFname;if(!_phCode&&fn.endsWith(".txt"))fn=fn.replace(/\.txt$/,".md");var a=document.createElement("a");a.href="data:text/plain;charset=utf-8,"+encodeURIComponent(content);a.download=fn;a.click();}function phDownloadZip(){ var lbl=document.getElementById("ph-zip-lbl"); if(lbl)lbl.textContent="Preparing\u2026"; /* ===== HELPERS ===== */ function cc(s){ return s.replace(/[_\-\s]+([a-z])/g,function(m,c){return c.toUpperCase();}) .replace(/^[a-z]/,function(m){return m.toUpperCase();}); } function pkgName(app){ return app.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"my_app"; } function slugTitle(app){ return app.replace(/_/g," "); } /* Generic code block extractor. Finds marker comments like: // lib/main.dart or # lib/main.dart or ## lib/main.dart and collects lines until the next marker. Also strips markdown fences (\`\`\`lang ... \`\`\`) from each block. */ function extractFiles(txt, pathRe){ var files={}, cur=null, buf=[]; function flush(){ if(cur&&buf.length){ files[cur]=buf.join("\n").trim(); } } txt.split("\n").forEach(function(line){ var m=line.trim().match(pathRe); if(m){ flush(); cur=m[1]; buf=[]; return; } if(cur) buf.push(line); }); flush(); // Strip \`\`\`...\`\`\` fences from each file Object.keys(files).forEach(function(k){ files[k]=files[k].replace(/^\`\`\`[a-z]*\n?/,"").replace(/\n?\`\`\`$/,"").trim(); }); return files; } /* General path extractor that covers most languages */ function extractCode(txt){ var re=/^(?:\/\/|#|##)\s*((?:lib|src|test|tests|Sources?|app|components?|screens?|views?|hooks?|routes?|store|services?|models?|pages?)\/[\w\/\-\.]+\.\w+|pubspec\.yaml|Package\.swift|angular\.json|babel\.config\.(?:js|ts)|vite\.config\.(?:js|ts)|tsconfig\.(?:json|app\.json)|app\.json|App\.(?:tsx|jsx|vue|kt|swift)|MainActivity(?:\.kt)?|ContentView\.swift)/i; return extractFiles(txt, re); } /* Detect language from combined code+panel text */ function detectLang(code, panel){ var t=(code+" "+panel).toLowerCase(); if(t.indexOf("import 'package:flutter")>=0||t.indexOf('import "package:flutter')>=0) return "flutter"; if(t.indexOf("statelesswidget")>=0||t.indexOf("statefulwidget")>=0) return "flutter"; if((t.indexOf(".dart")>=0)&&(t.indexOf("pubspec")>=0||t.indexOf("flutter:")>=0)) return "flutter"; if(t.indexOf("react-native")>=0||t.indexOf("react_native")>=0) return "react-native"; if(t.indexOf("stylesheet.create")>=0||t.indexOf("view, text, touchableopacity")>=0) return "react-native"; if(t.indexOf("expo(")>=0||t.indexOf("\"expo\":")>=0||t.indexOf("from 'expo")>=0) return "react-native"; if(t.indexOf("import swiftui")>=0||t.indexOf("import uikit")>=0) return "swift"; if(t.indexOf(".swift")>=0&&(t.indexOf("func body")>=0||t.indexOf("@main")>=0||t.indexOf("var body: some view")>=0)) return "swift"; if(t.indexOf("import android.")>=0||t.indexOf("package com.example")>=0) return "kotlin"; if(t.indexOf("@composable")>=0||t.indexOf("fun mainactivity")>=0||(t.indexOf(".kt")>=0&&t.indexOf("androidx")>=0)) return "kotlin"; if(t.indexOf("@ngmodule")>=0||t.indexOf("@component")>=0) return "angular"; if(t.indexOf("angular.json")>=0||t.indexOf("from '@angular")>=0) return "angular"; if(t.indexOf(".vue")>=0||t.indexOf("