### Install and Run LinkPeek Server Source: https://github.com/thegruber/linkpeek/blob/main/examples/bun-server/README.md Installs the linkpeek package and starts the server using Bun. ```bash bun add linkpeek bun run index.ts ``` -------------------------------- ### Install Dependencies and Run Locally Source: https://github.com/thegruber/linkpeek/blob/main/examples/playground/README.md Installs the necessary packages and starts the local development server for the linkpeek playground. ```bash npm install linkpeek wrangler npx wrangler dev ``` -------------------------------- ### Reproduce Install Footprint Benchmark Source: https://github.com/thegruber/linkpeek/blob/main/docs/comparison.md This bash script can be used to reproduce the install footprint measurements for various packages. It initializes a new npm project, installs a specified package, and then reports the number of installed packages and the size of the node_modules directory. ```bash mkdir -p /tmp/cmp && cd /tmp/cmp && npm init -y npm install --ignore-scripts --no-fund --no-audit node -e "const l=require('./package-lock.json');console.log(Object.keys(l.packages).filter(Boolean).length)" du -sk node_modules ``` -------------------------------- ### Install and Develop Cloudflare Worker Source: https://github.com/thegruber/linkpeek/blob/main/examples/cloudflare-worker/README.md Install the necessary package and start the local development server for the Cloudflare Worker. ```bash npm install linkpeek npx wrangler dev ``` -------------------------------- ### Install linkpeek Source: https://github.com/thegruber/linkpeek/blob/main/examples/nextjs-app-router/README.md Install the linkpeek package using npm. ```bash npm install linkpeek ``` -------------------------------- ### Install Dependencies and Run Server Source: https://github.com/thegruber/linkpeek/blob/main/examples/express-api/README.md Installs necessary packages (express, linkpeek, tsx) and then runs the Express server using tsx. ```bash npm install express linkpeek tsx npx tsx index.ts ``` -------------------------------- ### Fetch Link Preview Metadata Source: https://github.com/thegruber/linkpeek/blob/main/examples/supabase-edge-function/README.md Example of how to call the deployed Edge Function to get link preview metadata for a specific URL. ```bash curl "https://.supabase.co/functions/v1/preview?url=https://github.com" ``` -------------------------------- ### Install Dependencies and Run Quality Checks Source: https://github.com/thegruber/linkpeek/blob/main/docs/release.md Installs project dependencies using npm ci and then runs the quality assurance checks. ```bash npm ci npm run quality ``` -------------------------------- ### Run Benchmark Commands Source: https://github.com/thegruber/linkpeek/blob/main/benchmarks/competitive/README.md Commands to build the project, install dependencies, and run the benchmark. Ensure you are in the project root for the build command. ```bash (cd ../.. && npm run build) npm install npm run bench ``` -------------------------------- ### Install Dependencies Source: https://github.com/thegruber/linkpeek/blob/main/CONTRIBUTING.md Installs project dependencies using npm ci, ensuring consistency with the committed lockfile. ```bash npm ci ``` -------------------------------- ### Development Commands for Linkpeek Source: https://github.com/thegruber/linkpeek/blob/main/README.md Standard npm commands for installing dependencies, linting, testing, building, and auditing the Linkpeek project. ```bash npm ci npm run lint npm run typecheck npm run test npm run build npm audit npm run package:check npm run benchmark ``` -------------------------------- ### Example Commit Docs Source: https://github.com/thegruber/linkpeek/blob/main/CONTRIBUTING.md An example of a commit message following the conventional commit format for documentation changes. ```git docs: add benchmark usage notes ``` -------------------------------- ### Query Link Preview Metadata Source: https://github.com/thegruber/linkpeek/blob/main/examples/bun-server/README.md Example of how to use curl to request link preview metadata from the running Bun server. ```bash curl "http://localhost:3000?url=https://github.com" ``` -------------------------------- ### Example Commit Performance Source: https://github.com/thegruber/linkpeek/blob/main/CONTRIBUTING.md An example of a commit message following the conventional commit format for a performance improvement. ```git perf: stop parse once head closes ``` -------------------------------- ### Request Link Preview Source: https://github.com/thegruber/linkpeek/blob/main/examples/express-api/README.md Demonstrates how to make a curl request to the /api/preview endpoint with a URL to get a link preview. ```bash curl "http://localhost:3000/api/preview?url=https://github.com" ``` -------------------------------- ### Example Commit Fix Source: https://github.com/thegruber/linkpeek/blob/main/CONTRIBUTING.md An example of a commit message following the conventional commit format for a bug fix. ```git fix: improve og:image fallback resolution ``` -------------------------------- ### Use Link Preview Worker API Source: https://github.com/thegruber/linkpeek/blob/main/examples/cloudflare-worker/README.md Example of how to use the deployed link preview worker by making a curl request to its URL with a target URL parameter. ```bash curl "https://link-preview-worker..workers.dev/?url=https://github.com" ``` -------------------------------- ### Linkpeek Presets for Preview Generation Source: https://github.com/thegruber/linkpeek/blob/main/README.md Demonstrates how to use predefined presets (fast, quality) and custom configurations for generating link previews. The default preset is optimized for speed, while the quality preset offers richer data at the cost of more bandwidth. ```typescript import { preview, presets } from "linkpeek"; // Default: fast (30 KB limit, head only, no meta-refresh) const fast = await preview(url); // Quality: body JSON-LD + image fallback + meta-refresh const quality = await preview(url, presets.quality); // Custom: spread a preset and override const custom = await preview(url, { ...presets.quality, timeout: 3000 }); ``` -------------------------------- ### Build Project Source: https://github.com/thegruber/linkpeek/blob/main/CLAUDE.md Build the project using tsup. The output is placed in the 'dist/' directory. ```bash npm run build ``` -------------------------------- ### Run Live Benchmarks Source: https://github.com/thegruber/linkpeek/blob/main/CLAUDE.md Execute live benchmarks, likely involving network requests or external services. ```bash npm run benchmark:live ``` -------------------------------- ### Run Benchmarks Source: https://github.com/thegruber/linkpeek/blob/main/CLAUDE.md Execute project benchmarks to measure performance. ```bash npm run benchmark ``` -------------------------------- ### preview(url, options?) Source: https://github.com/thegruber/linkpeek/blob/main/README.md Fetches a URL and extracts link preview metadata. Returns a Promise that resolves with a PreviewResult object. ```APIDOC ## `preview(url, options?)` ### Description Fetches a URL and extracts link preview metadata. Returns `Promise`. ### Parameters #### Path Parameters None #### Query Parameters None #### Options - **`url`** (string) - Required - The URL to fetch and preview. - **`options`** (object) - Optional - Configuration options for the preview request. - **`timeout`** (number) - Optional - Request timeout in milliseconds. Defaults to `8000`. Throws `LinkpeekError` code `TIMEOUT`. - **`maxBytes`** (number) - Optional - Maximum bytes to stream. Defaults to `30000`. - **`userAgent`** (string) - Optional - User-Agent sent with requests. Defaults to `"Twitterbot/1.0"`. - **`followRedirects`** (boolean) - Optional - Follow HTTP redirects after validating each target. Defaults to `true`. - **`maxRedirects`** (number) - Optional - Maximum HTTP redirects to follow. Defaults to `10`. - **`headers`** (Record) - Optional - Extra non-sensitive request headers. Common credential-bearing headers are rejected; custom headers are not forwarded on cross-origin redirects. - **`allowPrivateIPs`** (boolean) - Optional - Allow private/internal IP targets. Defaults to `false`. - **`signal`** (AbortSignal) - Optional - Cancel the request from the caller side. - **`fetch`** (typeof fetch) - Optional - Custom fetch implementation (proxies, caching, testing). Defaults to `globalThis.fetch`. - **`followMetaRefresh`** (boolean) - Optional - Follow one `` redirect with a delay of 10s or less. Defaults to `false`. - **`includeBodyContent`** (boolean) - Optional - Continue scanning `` for JSON-LD and image fallbacks. Defaults to `false`. ### Result Fields - **`url`** (string) - Final fetched URL. - **`statusCode`** (number) - HTTP status code. `parseHTML()` returns `0`. - **`title`** (string | null) - `og:title` -> `twitter:title` -> JSON-LD -> Dublin Core -> ``. - **`description`** (string | null) - `og:description` -> `twitter:description` -> `meta[name=description]` -> JSON-LD. - **`image`** (string | null) - Preview image URL. - **`imageAlt`** (string | null) - Image alt text. - **`imageWidth`** (number | null) - `og:image:width`. - **`imageHeight`** (number | null) - `og:image:height`. - **`siteName`** (string) - `og:site_name` -> JSON-LD publisher -> hostname. - **`favicon`** (string | null) - Favicon URL. - **`mediaType`** (string) - `og:type`, defaults to `"website"`. - **`canonicalUrl`** (string) - Canonical URL, `og:url`, or fetched URL. - **`author`** (string | null) - JSON-LD author, author meta, or Dublin Core creator. - **`locale`** (string | null) - `og:locale`. - **`lang`** (string | null) - HTML language, content-language, or locale prefix. - **`publishedDate`** (string | null) - Article, JSON-LD, or Dublin Core date. - **`keywords`** (string[] | null) - `meta[name=keywords]`. - **`video`** (string | null) - Safe `og:video` URL. - **`audio`** (string | null) - Safe `og:audio` URL. - **`twitterCard`** (string | null) - Twitter card type. - **`twitterSite`** (string | null) - Twitter site handle. - **`twitterCreator`** (string | null) - Twitter creator handle. - **`themeColor`** (string | null) - Theme color. - **`oEmbedUrl`** (string | null) - Discovered oEmbed endpoint URL. Not fetched. ``` -------------------------------- ### Run Tests Source: https://github.com/thegruber/linkpeek/blob/main/CLAUDE.md Execute project tests using vitest. By default, only fixture and mock tests are run. ```bash npm run test ``` -------------------------------- ### Run Live URL Tests Source: https://github.com/thegruber/linkpeek/blob/main/CONTRIBUTING.md Enables and runs live URL tests, intended for verifying network extraction quality. This is opt-in and should not be part of the standard CI process. ```bash LINKPEEK_LIVE_TESTS=1 npm run test ``` -------------------------------- ### Verify Build Output Files Source: https://github.com/thegruber/linkpeek/blob/main/docs/release.md Checks for the existence of the expected module formats and declaration files in the dist directory. ```bash test -f dist/index.js test -f dist/index.cjs test -f dist/index.d.ts test -f dist/index.d.cts ``` -------------------------------- ### Deploy Supabase Edge Function Source: https://github.com/thegruber/linkpeek/blob/main/examples/supabase-edge-function/README.md Deploys the 'preview' Edge Function to your Supabase project. ```bash supabase functions deploy preview ``` -------------------------------- ### Deploy Cloudflare Worker Source: https://github.com/thegruber/linkpeek/blob/main/examples/playground/README.md Deploys the linkpeek playground to the Cloudflare Workers environment. ```bash npx wrangler deploy ``` -------------------------------- ### Lint Code Source: https://github.com/thegruber/linkpeek/blob/main/CLAUDE.md Run the linter using Biome to check for code style and potential issues. ```bash npm run lint ``` -------------------------------- ### Fetch Link Preview Metadata Source: https://github.com/thegruber/linkpeek/blob/main/examples/nextjs-app-router/README.md Fetch link preview metadata from the API route on the frontend. The URL parameter should be encoded. ```typescript const res = await fetch(`/api/preview?url=${encodeURIComponent("https://github.com")}`); const data = await res.json(); // { title, description, image, siteName, ... } ``` -------------------------------- ### Extract URL Preview Metadata Source: https://github.com/thegruber/linkpeek/blob/main/README.md Use the `preview` function to fetch and extract metadata like title, image, site name, and description from a given URL. This is the primary function for obtaining link previews. ```typescript import { preview } from "linkpeek"; const result = await preview("https://www.youtube.com/watch?v=dQw4w9WgXcQ"); result.title; // "Rick Astley - Never Gonna Give You Up" result.image; // "https://i.ytimg.com/vi/dQw4w9WgXcQ/maxresdefault.jpg" result.siteName; // "YouTube" result.favicon; // "https://www.youtube.com/favicon.ico" result.description; // "The official video for \"Never Gonna Give You Up\"..." ``` -------------------------------- ### Run Full Quality Gate Source: https://github.com/thegruber/linkpeek/blob/main/CONTRIBUTING.md Executes the complete quality assurance process, including linting, type checking, testing, auditing, building, and package checks. ```bash npm run quality ``` -------------------------------- ### Handle Linkpeek Errors Source: https://github.com/thegruber/linkpeek/blob/main/README.md Import `LinkpeekError` and `preview` to catch and branch on specific error codes for invalid input, blocked targets, or timeouts. ```typescript import { LinkpeekError, preview } from "linkpeek"; try { const result = await preview(url); } catch (err) { if (err instanceof LinkpeekError) { switch (err.code) { case "INVALID_URL": // not a parseable URL case "UNSUPPORTED_PROTOCOL": // not http/https case "PRIVATE_NETWORK_BLOCKED": // SSRF protection triggered case "SENSITIVE_HEADER": // credential-bearing custom header case "TOO_MANY_REDIRECTS": case "TIMEOUT": case "INVALID_OPTIONS": break; } } // Aborts via your own `signal` are rethrown as-is (AbortError), // and network failures propagate from fetch unchanged. } ``` -------------------------------- ### Basic LinkPreview Component Usage Source: https://github.com/thegruber/linkpeek/blob/main/examples/react-preview-card/README.md Import and use the LinkPreview component in your React application, providing the URL for which to generate a preview. ```tsx import { LinkPreview } from "./LinkPreview"; export default function Page() { return <LinkPreview url="https://github.com" />; } ``` -------------------------------- ### parseHTML(html, baseUrl, options?) Source: https://github.com/thegruber/linkpeek/blob/main/README.md Parses an HTML string directly to extract link preview metadata. Use this when you already have the HTML content. ```APIDOC ## `parseHTML(html, baseUrl, options?)` ### Description Parses an HTML string directly. Use this when you already have the HTML. Pass `{ includeBodyContent: true }` to continue into `<body>` for JSON-LD and image fallbacks; by default it keeps the same head-first behavior as `preview()`. ### Parameters #### Path Parameters None #### Query Parameters None #### Arguments - **`html`** (string) - Required - The HTML string to parse. - **`baseUrl`** (string) - Required - The base URL for resolving relative links. - **`options`** (object) - Optional - Configuration options for parsing. - **`includeBodyContent`** (boolean) - Optional - Continue scanning `<body>` for JSON-LD and image fallbacks. Defaults to `false`. ### Result Fields (Same as `preview()` result fields, except `url` will be the `baseUrl` if no other URL is found, and `statusCode` will be `0`.) ``` -------------------------------- ### Check Package Integrity Source: https://github.com/thegruber/linkpeek/blob/main/CLAUDE.md Run package integrity checks, including publint, Are The Types Wrong, and npm dry-run pack. ```bash npm run package:check ``` -------------------------------- ### Fix Linting Issues Source: https://github.com/thegruber/linkpeek/blob/main/CLAUDE.md Automatically fix linting issues in the code. ```bash npm run lint:fix ``` -------------------------------- ### Cloudflare Workers Fetch Handler for Link Previews Source: https://github.com/thegruber/linkpeek/blob/main/README.md A Cloudflare Worker's fetch handler that processes incoming requests for link previews. It extracts the 'url' from search parameters, generates the preview, and sets appropriate Cache-Control headers based on the success of the preview generation. ```typescript import { preview } from "linkpeek"; export default { async fetch(request: Request): Promise<Response> { const url = new URL(request.url).searchParams.get("url"); if (!url) return Response.json({ error: "Missing url" }, { status: 400 }); try { const result = await preview(url); // Only cache successful previews — 4xx/5xx return a result, not an error const cacheControl = result.statusCode >= 200 && result.statusCode < 300 ? "public, max-age=3600" : "no-store"; return Response.json(result, { headers: { "Cache-Control": cacheControl }, }); } catch (err) { return Response.json( { error: err instanceof Error ? err.message : "Preview failed" }, { status: 422 }, ); } }, }; ``` -------------------------------- ### Express.js API Endpoint for Link Previews Source: https://github.com/thegruber/linkpeek/blob/main/README.md An Express.js route handler for the '/api/preview' endpoint that takes a 'url' query parameter to generate a link preview. It handles missing URLs and errors during the preview generation process. ```typescript import express from "express"; import { preview } from "linkpeek"; const app = express(); app.get("/api/preview", async (req, res) => { const url = typeof req.query.url === "string" ? req.query.url : ""; if (!url) return res.status(400).json({ error: "Missing url" }); try { res.json(await preview(url)); } catch (err) { res.status(422).json({ error: err instanceof Error ? err.message : "Preview failed", }); } }); ``` -------------------------------- ### Next.js App Router API Route for Link Previews Source: https://github.com/thegruber/linkpeek/blob/main/README.md An API route for Next.js App Router that accepts a 'url' query parameter and returns a link preview. It includes basic error handling for missing URLs and preview generation failures. ```typescript //app/api/preview/route.ts import { preview } from "linkpeek"; import { type NextRequest, NextResponse } from "next/server"; export async function GET(req: NextRequest) { const url = req.nextUrl.searchParams.get("url"); if (!url) return NextResponse.json({ error: "Missing url" }, { status: 400 }); try { return NextResponse.json(await preview(url)); } catch (err) { return NextResponse.json( { error: err instanceof Error ? err.message : "Preview failed" }, { status: 422 }, ); } } ``` -------------------------------- ### Validate URL with Linkpeek Source: https://github.com/thegruber/linkpeek/blob/main/README.md Use `validateUrl` to check if a URL is valid and does not point to a private network. It throws an error for invalid or blocked URLs. ```typescript import { validateUrl } from "linkpeek"; validateUrl("http://169.254.169.254/"); // throws PRIVATE_NETWORK_BLOCKED ``` -------------------------------- ### Typecheck Code Source: https://github.com/thegruber/linkpeek/blob/main/CLAUDE.md Perform type checking on the project's TypeScript code. ```bash npm run typecheck ``` -------------------------------- ### Parse HTML Directly Source: https://github.com/thegruber/linkpeek/blob/main/README.md Use the `parseHTML` function when you already have the HTML content. Provide the HTML string and a base URL for resolving relative links. ```typescript import { parseHTML } from "linkpeek"; const result = parseHTML( "<html><head><title>Hello", "https://example.com", ); console.log(result.title); // "Hello" ``` -------------------------------- ### Check HTTP Status Code Source: https://github.com/thegruber/linkpeek/blob/main/README.md Check the `statusCode` property of the result to handle non-throwing HTTP errors like 404 or 500 before caching or rendering. ```typescript const result = await preview(url); if (result.statusCode >= 400) { // render a broken-link card, skip caching } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.