Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

21.6 KB
Raw Blame
// Generates Open Graph (OG) / SEO social-preview metadata from the single
// source of truth in the frontend (tool ids, URL aliases, translated English
// strings) plus the actual images in public/og_images.
//
// Outputs:
//   src/editor/core/data/ogImageMap.json      - { toolId: imageBasename }  (imported by the client)
//   src/editor/core/data/urlSeoOverrides.json - { path: { title, description } } (client per-URL meta, English only)
//   public/og-metadata.json            - { default, byTool, byPath, canonicalByPath } (prerender input)
//   public/og-metadata.saas.json       - same shape, SaaS marketing copy/art (prerender input, --mode saas)
//
// Run: `node scripts/generate-og-metadata.mjs`        (writes files)
//      `node scripts/generate-og-metadata.mjs --check` (CI drift guard: fails if stale)
//
// Why a generator instead of hand-maintained JSON: tool ids, URL aliases and
// English copy already live in the codebase. Regenerating keeps OG metadata in
// lockstep with the tool registry and surfaces tools that have no art.

import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, "..");
const read = (p) => fs.readFileSync(path.join(ROOT, p), "utf8");

const SITE_NAME = "Stirling PDF";
// SITE_TITLE is the home page's own title/social headline; SITE_NAME is the
// suffix every other page carries, so the download count appears once.
const SITE_TITLE = "Stirling PDF - 30M+ Downloads";
const SITE_DESC =
  "A free, private PDF editor you can run on any infrastructure.";
const DEFAULT_IMAGE_BASENAME = "home";

// Keyword-targeted landing copy for the convert tool's URL aliases. Every
// /pdf-to-x and /x-to-pdf path routes to the single `convert` tool, so without
// this they would all share the generic "Convert - Stirling PDF" title and
// description - duplicate content that ranks for nothing. Each entry gets its
// own crawlable title/description (prerendered) and a client-side override so
// the SPA keeps the same title after hydration in English (other locales keep
// their translated copy). `name` is the keyword phrase; the app suffix
// (" - Stirling PDF" / the instance name) is added per surface.
const CONVERT_SEO_PAGES = {
  "/pdf-to-word": {
    name: "PDF to Word Converter",
    description:
      "Convert PDF files into editable Microsoft Word (DOCX) documents. Free, fast, and private - no signup or email required.",
  },
  "/pdf-to-xlsx": {
    name: "PDF to Excel Converter",
    description:
      "Convert PDF tables into editable Microsoft Excel (XLSX) spreadsheets. Free, fast, and private.",
  },
  "/pdf-to-csv": {
    name: "PDF to CSV Converter",
    description:
      "Extract tables from PDF files into CSV data. Free, fast, and private - no signup required.",
  },
  "/pdf-to-img": {
    name: "PDF to Image Converter",
    description:
      "Convert PDF pages into high-quality JPG or PNG images. Free and private, right in your browser.",
  },
  "/pdf-to-presentation": {
    name: "PDF to PowerPoint Converter",
    description:
      "Convert PDF files into editable PowerPoint (PPTX) presentations. Free, fast, and private.",
  },
  "/pdf-to-text": {
    name: "PDF to Text Converter",
    description:
      "Extract plain text from PDF documents. Free, fast, and private - no signup or email required.",
  },
  "/pdf-to-markdown": {
    name: "PDF to Markdown Converter",
    description:
      "Convert PDF documents into clean Markdown text. Free and private, right in your browser.",
  },
  "/pdf-to-html": {
    name: "PDF to HTML Converter",
    description:
      "Convert PDF documents into HTML web pages. Free and private, right in your browser.",
  },
  "/pdf-to-xml": {
    name: "PDF to XML Converter",
    description:
      "Convert PDF documents into structured XML. Free, fast, and private.",
  },
  "/pdf-to-pdfa": {
    name: "PDF to PDF/A Converter",
    description:
      "Convert PDFs to the PDF/A archival standard for long-term preservation. Free and private.",
  },
  "/img-to-pdf": {
    name: "Image to PDF Converter",
    description:
      "Convert JPG, PNG, and other images into a single PDF document. Free, fast, and private.",
  },
  "/html-to-pdf": {
    name: "HTML to PDF Converter",
    description:
      "Convert HTML files and web pages into PDF documents. Free, fast, and private.",
  },
  "/markdown-to-pdf": {
    name: "Markdown to PDF Converter",
    description:
      "Convert Markdown files into polished PDF documents. Free and private, right in your browser.",
  },
  "/eml-to-pdf": {
    name: "Email (EML) to PDF Converter",
    description:
      "Convert email (EML) files into PDF documents. Free, fast, and private - no signup required.",
  },
  "/file-to-pdf": {
    name: "File to PDF Converter",
    description:
      "Convert Word, Excel, PowerPoint, and more into PDF documents. Free, fast, and private.",
  },
  "/cbr-to-pdf": {
    name: "CBR to PDF Converter",
    description:
      "Convert CBR comic book archives into PDF documents. Free and private, right in your browser.",
  },
  "/pdf-to-cbr": {
    name: "PDF to CBR Converter",
    description:
      "Convert PDF documents into CBR comic book archives. Free and private.",
  },
  "/cbz-to-pdf": {
    name: "CBZ to PDF Converter",
    description:
      "Convert CBZ comic book archives into PDF documents. Free and private.",
  },
  "/pdf-to-cbz": {
    name: "PDF to CBZ Converter",
    description:
      "Convert PDF documents into CBZ comic book archives. Free and private.",
  },
};

// Keyword titles for base tools. The in-app label ("Compress") is the UI name,
// not the phrase people search ("Compress PDF"). Keyed by tool id; overrides the
// prerendered <title>, the crawlable H1, and the nav-hub label, and is fed to the
// running SPA (per alias) so the hydrated title matches. The in-app UI name is
// unaffected - it comes from the translation registry, not this file. The tool's
// own description is kept. Convert aliases are handled by CONVERT_SEO_PAGES.
const TOOL_SEO_TITLES = {
  compress: "Compress PDF",
  merge: "Merge PDF",
  split: "Split PDF",
  rotate: "Rotate PDF",
  convert: "PDF Converter",
  ocr: "OCR PDF",
  watermark: "Add Watermark to PDF",
  sign: "Sign PDF",
  certSign: "Sign PDF with a Certificate",
  redact: "Redact PDF",
  crop: "Crop PDF",
  flatten: "Flatten PDF",
  repair: "Repair PDF",
  compare: "Compare PDF Files",
  sanitize: "Sanitize PDF",
  addPassword: "Password Protect PDF",
  removePassword: "Remove PDF Password",
  changePermissions: "Change PDF Permissions",
  addPageNumbers: "Add Page Numbers to PDF",
  addText: "Add Text to PDF",
  addImage: "Add Image to PDF",
  addStamp: "Add Stamp to PDF",
  addAttachments: "Manage PDF Attachments",
  extractPages: "Extract PDF Pages",
  removePages: "Delete Pages from PDF",
  removeBlanks: "Remove Blank Pages from PDF",
  removeImage: "Remove Images from PDF",
  removeAnnotations: "Remove Annotations from PDF",
  reorganizePages: "Organize PDF Pages",
  extractImages: "Extract Images from PDF",
  pageLayout: "PDF Multi-Page Layout",
  scalePages: "Resize PDF Pages",
  pdfToSinglePage: "Combine PDF into a Single Page",
  adjustContrast: "Adjust PDF Colors and Contrast",
  replaceColor: "Replace and Invert PDF Colors",
  changeMetadata: "Edit PDF Metadata",
  getPdfInfo: "PDF Info and Metadata Viewer",
  overlayPdfs: "Overlay PDFs",
  editTableOfContents: "Edit PDF Bookmarks",
  pdfTextEditor: "Edit PDF Text",
  formFill: "Fill PDF Forms",
  multiTool: "PDF Page Editor",
  read: "PDF Viewer",
  annotate: "Annotate PDF",
  automate: "PDF Workflow Automation",
  scannerImageSplit: "Split Scanned Photos",
  autoRename: "Auto Rename PDF Files",
  bookletImposition: "Create a PDF Booklet",
  unlockPDFForms: "Unlock PDF Forms",
  removeCertSign: "Remove PDF Certificate Signature",
  validateSignature: "Validate PDF Signature",
  timestampPdf: "Timestamp PDF",
  showJS: "Show JavaScript in PDF",
};

// SaaS (stirling.com) link-preview cards. Only the SaaS build (`--mode saas`)
// uses og-metadata.saas.json; every other flavour keeps the tool-registry copy
// above. `ogTitle` is the punchy social headline; `title` is the SEO <title>.
// `home` overrides the site default (served at `/app`); the rest are extra
// marketing landing routes prerendered so their links unfurl with bespoke art.
const SAAS_DEFAULT = {
  image: "/og_images/saas/app.png",
  title: "Stirling - Edit any PDF. Govern every PDF.",
  ogTitle: "Edit any PDF. Govern every PDF.",
  description:
    "The free, open-source PDF Editor, plus a Processor that governs every PDF your organization touches. 1¢ per PDF.",
};
const SAAS_ROUTE_OVERRIDES = {
  "/processor": {
    image: "/og_images/saas/app-processor.png",
    title: "Stirling Processor - Govern every PDF your organization touches",
    ogTitle: "Govern every PDF your organization touches",
    description:
      "Redaction, retention, and encryption policies enforced everywhere PDFs enter your org. Distribute the free Editor anywhere. 1¢ per PDF.",
    // Metered product - a price-0 Offer would contradict the page copy.
    noOffer: true,
  },
  "/editor": {
    image: "/og_images/saas/app-editor.png",
    title: "Stirling - The world's most secure PDF editor",
    ogTitle: "The world's most secure PDF editor",
    description:
      "Edit, sign, redact, and convert PDFs in your browser. Free forever, open source, and self-hostable.",
  },
};

// Tools whose art exists under a legacy v1 filename that does not match the
// tool id or any current URL slug. Verified against public/og_images contents.
const LEGACY_IMAGE_OVERRIDES = {
  merge: "mergePdfs",
  crop: "cropPdf",
  getPdfInfo: "get-all-info-on-pdf",
  validateSignature: "validate-pdf-signature",
  replaceColor: "replace-and-invert-color",
  scalePages: "adjust-page-size-scale",
  adjustContrast: "adjust-colors-contrast",
  autoRename: "auto-rename-pdf-file",
  removeBlanks: "remove-blank-pages",
  removePages: "remove",
  scannerImageSplit: "detect-split-scanned-photos",
};

// --- parse tool ids ---------------------------------------------------------
const idSrc = read("src/editor/core/types/toolId.ts");
function idArray(name) {
  const m = idSrc.match(
    new RegExp("export const " + name + " = \\[([\\s\\S]*?)\\] as const"),
  );
  return m ? [...m[1].matchAll(/"([^"]+)"/g)].map((x) => x[1]) : [];
}
const regularIds = idArray("CORE_REGULAR_TOOL_IDS");
const superIds = idArray("CORE_SUPER_TOOL_IDS");
const linkIds = idArray("CORE_LINK_TOOL_IDS");
const allIds = [...regularIds, ...superIds, ...linkIds];

// --- parse URL aliases ------------------------------------------------------
const mapSrc = read("src/editor/core/utils/urlMapping.ts");
const urlToTool = {};
for (const m of mapSrc.matchAll(/"([^"]+)":\s*"([^"]+)"/g))
  urlToTool[m[1]] = m[2];

// --- parse English title/description fallbacks ------------------------------
const regSrc = read("src/editor/core/data/useTranslatedToolRegistry.tsx");
const titleById = {};
const descById = {};
const STR = '"((?:[^"\\\\]|\\\\.)*)"';
for (const m of regSrc.matchAll(
  new RegExp('t\\(\\s*"home\\.([A-Za-z0-9_]+)\\.title"\\s*,\\s*' + STR, "g"),
))
  titleById[m[1]] = m[2];
for (const m of regSrc.matchAll(
  new RegExp('t\\(\\s*"home\\.([A-Za-z0-9_]+)\\.desc"\\s*,\\s*' + STR, "g"),
))
  descById[m[1]] = m[2];

// --- available images -------------------------------------------------------
const imageDir = "public/og_images";
const images = new Set(
  fs
    .readdirSync(path.join(ROOT, imageDir))
    .filter((f) => f.endsWith(".png"))
    .map((f) => f.replace(/\.png$/, "")),
);

const canonicalPath = (id) => "/" + id.replace(/([A-Z])/g, "-$1").toLowerCase();
const aliasesByTool = {};
for (const [p, id] of Object.entries(urlToTool))
  (aliasesByTool[id] ??= []).push(p);

function resolveImage(id) {
  const override = LEGACY_IMAGE_OVERRIDES[id];
  if (override) return images.has(override) ? override : null;
  const candidates = [
    id,
    canonicalPath(id).slice(1),
    ...(aliasesByTool[id] || []).map((a) => a.slice(1)),
  ];
  for (const c of candidates) if (images.has(c)) return c;
  return null;
}

const humanize = (id) =>
  id
    .replace(/([A-Z]+)/g, " $1")
    .replace(/^./, (c) => c.toUpperCase())
    .replace(/\s+/g, " ")
    .trim();
const titleFor = (id) => `${titleById[id] || humanize(id)} - ${SITE_NAME}`;
const descFor = (id) => descById[id] || SITE_DESC;

// --- build outputs ----------------------------------------------------------
const ogImageMap = {}; // toolId -> basename (only tools with art)
const byTool = {};
const missing = [];
for (const id of allIds) {
  const img = resolveImage(id);
  if (img) ogImageMap[id] = img;
  else missing.push(id);
  byTool[id] = {
    image: `/og_images/${img || DEFAULT_IMAGE_BASENAME}.png`,
    title: titleFor(id),
    description: descFor(id),
    // Link tools are external redirects with no component, not landing pages.
    ...(linkIds.includes(id) ? { noindex: true } : {}),
  };
}

// Upgrade base-tool titles to their search phrases (see TOOL_SEO_TITLES).
for (const id of Object.keys(TOOL_SEO_TITLES)) {
  if (!byTool[id]) {
    console.warn(`[og] TOOL_SEO_TITLES: unknown tool id "${id}" - skipped`);
    continue;
  }
  byTool[id].title = `${TOOL_SEO_TITLES[id]} - ${SITE_NAME}`;
}

// path -> toolId for every canonical path and every alias
const byPath = {};
for (const id of allIds) byPath[canonicalPath(id)] = id;
for (const [p, id] of Object.entries(urlToTool)) byPath[p] = id;

// --- non-tool application routes --------------------------------------------
// Every other URL the SPA serves also gets OG: auth, the file manager, the
// mobile scanner, and each settings section. These have no bespoke art (default
// image) but carry a page-specific title so shared links are labelled correctly.
// Keyed by path (tool ids never start with "/", so there is no collision).
const navKeys = (
  read("src/editor/core/components/shared/config/types.ts")
    .match(/export const VALID_NAV_KEYS = \[([\s\S]*?)\] as const/)?.[1]
    .match(/"([^"]+)"/g) || []
).map((s) => s.replace(/"/g, ""));

const humanizeLabel = (s) =>
  s
    .replace(/[-_]/g, " ")
    .replace(/([a-z])([A-Z])/g, "$1 $2")
    .replace(/\s+/g, " ")
    .trim()
    .replace(/\b\w/g, (c) => c.toUpperCase());

const pageTitles = {
  // The editor's own URL ("/" only routes, by role).
  "/editor": "Editor",
  "/login": "Sign In",
  "/mobile-scanner": "Mobile Scanner",
  "/files": "Files",
  "/settings": "Settings",
  "/docs": "Documentation",
  // Processor views per portal/ViewRouter. Its redirect-only paths
  // (/processor/users and friends, now settings) render nothing to label.
  "/processor": "Processor",
  "/processor/pipelines": "Pipelines",
  "/processor/sources": "Sources",
  "/processor/integrations": "Integrations",
  "/processor/documents": "Documents",
  "/processor/review": "Review",
};

// Routes only the SaaS build serves - self-hosted redirects /signup to /login.
const SAAS_ONLY_PAGE_TITLES = { "/signup": "Sign Up" };

// Nav keys humanizeLabel gets wrong: it title-cases acronyms, and one key is an
// initialism rather than words.
const NAV_KEY_LABELS = {
  "api-keys": "API Keys",
  adminMcp: "Admin MCP",
  adminAi: "Admin AI",
  adminAiGeneral: "Admin AI General",
  adminAiModels: "Admin AI Models",
  adminAiDocuments: "Admin AI Documents",
  adminAiLimits: "Admin AI Limits",
  payg: "Pay As You Go",
};
for (const key of navKeys)
  pageTitles[`/settings/${key}`] =
    `${NAV_KEY_LABELS[key] ?? humanizeLabel(key)} Settings`;

// App surfaces, not landing pages: noindex keeps them out of the index and the
// sitemap. Docs and processor render client-side, so a shell would be thin.
for (const [routePath, label] of Object.entries(pageTitles)) {
  byTool[routePath] = {
    image: `/og_images/${DEFAULT_IMAGE_BASENAME}.png`,
    title: `${label} - ${SITE_NAME}`,
    description: SITE_DESC,
    noindex: true,
  };
  byPath[routePath] = routePath;
}

// --- convert-alias SEO landing pages -----------------------------------------
// Give each convert alias its own keyword title/description instead of the
// generic "Convert" entry. Self-key in byPath so the prerender treats it as a
// distinct (self-canonical) page. `urlSeoOverrides` feeds the same copy to the
// running SPA so the hydrated title matches what crawlers first see.
const convertImage =
  byTool.convert?.image ?? `/og_images/${DEFAULT_IMAGE_BASENAME}.png`;
const urlSeoOverrides = {};
for (const [routePath, seo] of Object.entries(CONVERT_SEO_PAGES)) {
  byTool[routePath] = {
    image: convertImage,
    title: `${seo.name} - ${SITE_NAME}`,
    description: seo.description,
  };
  byPath[routePath] = routePath;
  urlSeoOverrides[routePath] = {
    title: seo.name,
    description: seo.description,
  };
}

// Base-tool keyword copy for the running SPA, on every alias of the tool, so the
// hydrated English <title> matches the prerendered one. Convert pages set above
// win (they have more specific per-alias keywords), hence the guard.
for (const [id, name] of Object.entries(TOOL_SEO_TITLES)) {
  if (!byTool[id]) continue;
  for (const p of [canonicalPath(id), ...(aliasesByTool[id] || [])])
    if (!(p in urlSeoOverrides))
      urlSeoOverrides[p] = { title: name, description: descFor(id) };
}

// First alias per tool, guaranteed routable by parseToolRoute.
const primaryPathByTool = {};
for (const [p, id] of Object.entries(urlToTool))
  if (!(id in primaryPathByTool)) primaryPathByTool[id] = p;

// --- alias canonicalisation --------------------------------------------------
// Many paths route to the same tool (/compress-pdf and /compress). Indexing them
// all is duplicate content, so every alias canonicalises to the tool's primary
// path, and the prerender leaves aliases out of the sitemap. Paths
// keyed to themselves in byPath are landing pages with their own copy, so they
// stay primary.
const canonicalByPath = {};
for (const [p, id] of Object.entries(byPath)) {
  if (p === id) continue;
  const primary = primaryPathByTool[id] || canonicalPath(id);
  if (p !== primary) canonicalByPath[p] = primary;
}

const manifest = {
  default: {
    image: `/og_images/${DEFAULT_IMAGE_BASENAME}.png`,
    title: SITE_TITLE,
    description: SITE_DESC,
  },
  byTool,
  byPath,
  canonicalByPath,
};

// SaaS manifest: same tool pages as above, but the home default and two extra
// marketing routes carry the stirling.com cards. Keeps all per-tool OG intact.
const saasManifest = {
  default: SAAS_DEFAULT,
  byTool: { ...byTool },
  byPath: { ...byPath },
  canonicalByPath: { ...canonicalByPath },
};
// Same app-surface rule as the pageTitles loop above: noindex, never a landing page.
for (const [routePath, label] of Object.entries(SAAS_ONLY_PAGE_TITLES)) {
  saasManifest.byTool[routePath] = {
    image: `/og_images/${DEFAULT_IMAGE_BASENAME}.png`,
    title: `${label} - ${SITE_NAME}`,
    description: SITE_DESC,
    noindex: true,
  };
  saasManifest.byPath[routePath] = routePath;
}
for (const [routePath, entry] of Object.entries(SAAS_ROUTE_OVERRIDES)) {
  saasManifest.byTool[routePath] = entry;
  saasManifest.byPath[routePath] = routePath;
}
// SaaS card art lives in the saas/ subdir (outside the root images scan), so
// check the files on disk directly.
const missingSaasImages = [SAAS_DEFAULT, ...Object.values(SAAS_ROUTE_OVERRIDES)]
  .map((e) => e.image)
  .filter((img) => !fs.existsSync(path.join(ROOT, "public" + img)));
if (missingSaasImages.length)
  console.warn(
    `\nWARNING: SaaS OG cards reference missing images: ${missingSaasImages.join(", ")}`,
  );

const mapJson = JSON.stringify(ogImageMap, null, 2) + "\n";
const manifestJson = JSON.stringify(manifest, null, 2) + "\n";
const saasManifestJson = JSON.stringify(saasManifest, null, 2) + "\n";
const seoOverridesJson = JSON.stringify(urlSeoOverrides, null, 2) + "\n";
const mapPath = "src/editor/core/data/ogImageMap.json";
const manifestPath = "public/og-metadata.json";
const saasManifestPath = "public/og-metadata.saas.json";
const seoOverridesPath = "src/editor/core/data/urlSeoOverrides.json";

const outputs = [
  [mapPath, mapJson],
  [manifestPath, manifestJson],
  [saasManifestPath, saasManifestJson],
  [seoOverridesPath, seoOverridesJson],
];

const check = process.argv.includes("--check");
if (check) {
  const stale = outputs
    .filter(
      ([p, content]) =>
        !fs.existsSync(path.join(ROOT, p)) || read(p) !== content,
    )
    .map(([p]) => p);
  if (stale.length) {
    console.error(
      "OG metadata is stale. Run `node scripts/generate-og-metadata.mjs`:\n  " +
        stale.join("\n  "),
    );
    process.exit(1);
  }
  console.log("OG metadata is up to date.");
} else {
  for (const [p, content] of outputs)
    fs.writeFileSync(path.join(ROOT, p), content);
  console.log(
    `Wrote ${mapPath} (${Object.keys(ogImageMap).length} tools with art)`,
  );
  console.log(
    `Wrote ${saasManifestPath} (${Object.keys(saasManifest.byPath).length} paths, SaaS)`,
  );
  console.log(`Wrote ${manifestPath} (${Object.keys(byPath).length} paths)`);
  console.log(
    `Wrote ${seoOverridesPath} (${Object.keys(urlSeoOverrides).length} SEO landing pages)`,
  );
}

// --- report -----------------------------------------------------------------
console.log(
  `\nTools with OG image: ${allIds.length - missing.length}/${allIds.length}`,
);
console.log(
  `Tools using the DEFAULT image (${DEFAULT_IMAGE_BASENAME}.png) - no bespoke art: ${missing.length}`,
);
for (const id of missing) {
  const kind = superIds.includes(id)
    ? "super"
    : linkIds.includes(id)
      ? "link"
      : "regular";
  console.log(`  ${kind.padEnd(8)} ${id.padEnd(20)} ${canonicalPath(id)}`);
}
const used = new Set(Object.values(ogImageMap));
const orphans = [...images]
  .filter((i) => !used.has(i) && i !== DEFAULT_IMAGE_BASENAME)
  .sort();
console.log(
  `\nUnused images in ${imageDir} (${orphans.length}): ${orphans.join(", ")}`,
);