extract

package
v2.6.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 24 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package extract converts raw HTML and PDF payloads into clean GitHub-Flavored Markdown, plain text, resolved links, images, CSS branding signals, BM25 query-reranked passages, and `llms.txt` structured discovery metadata using only the Go standard library.

Extraction Pipeline

  1. Head metadata & branding signals (`<title>`, OpenGraph, canonical URL, favicon, CSS hex palette, fonts).
  2. Boilerplate & chrome removal (`<nav>`, `<footer>`, `<aside>`, `<script>`, `<style>`) with `<main>` / `<article>` focus when `OnlyMainContent` is enabled.
  3. Sentinel-protected `<pre><code>` and multi-backtick inline `<code>` conversion so generic type signatures (`Promise<void>`, `#include <stdio.h>`) survive HTML tag stripping intact.
  4. GFM table reconstruction, optional BM25 passage reranking (RerankPassages), and optional PII redaction (RedactPII).
  5. Streaming Poppler `pdftotext -layout` extraction with a pure-Go FlateDecode fallback (ExtractPDFText) for distroless Lite deployments.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func CandidateCompanionMarkdownURL

func CandidateCompanionMarkdownURL(pageURL string) string

CandidateCompanionMarkdownURL returns `<url>.md` when `pageURL` looks like a clean documentation/article path (e.g. `https://developers.cloudflare.com/workers/wrangler` -> `https://developers.cloudflare.com/workers/wrangler.md`).

func DetectRenderedChallenge

func DetectRenderedChallenge(rawHTML string) string

DetectRenderedChallenge checks whether an HTML payload (HTTP or headless browser) is gated by a bot/CAPTCHA challenge. Delegates to `classify.ClassifyWAF` (`R2` & `R3`) so all 4 anti-false-positive guardrails (visible word-count veto, Schema.org JSON-LD veto, `<pre>`/`<code>` immunity, and `<nav>` landmark veto) protect rendered pages too.

func ExtractPDFFileText

func ExtractPDFFileText(ctx context.Context, pdfPath string, maxPages int) (text string, usedPoppler bool, err error)

ExtractPDFFileText extracts UTF-8 text from an on-disk PDF file up to `maxPages` (default 60) using `pdftotext` (`poppler-utils`), falling back to a bounded pure-Go FlateDecode stream reader when `pdftotext` is absent. Reading from a seekable file path allows Poppler to seek directly to the PDF `xref` trailer at EOF without buffering large manuals in RAM.

func ExtractPDFText

func ExtractPDFText(ctx context.Context, pdfBytes []byte, maxPages int) (text string, usedPoppler bool, err error)

ExtractPDFText extracts UTF-8 text from `pdfBytes` up to `maxPages` (default 60). On Fat nodes (`edgefetch_fat`), it streams `pdfBytes` directly over stdin into `pdftotext -layout` (`poppler-utils`, zero temporary files on disk). On distroless Lite nodes without `pdftotext`, it falls back to a pure-Go FlateDecode content-stream text reader so PDF fetches remain functional everywhere.

func HasPDFToText

func HasPDFToText() bool

HasPDFToText reports whether `pdftotext` (`poppler-utils`, bundled in `edgefetch_fat`) is available in $PATH.

func IsPDFBytes

func IsPDFBytes(data []byte) bool

IsPDFBytes checks whether `data` starts with `%PDF-` within the first 1024 bytes (per PDF spec §7.5.2).

func NeedsBrowserRender

func NeedsBrowserRender(rawHTML string) bool

NeedsBrowserRender heuristics detect empty client-side SPA shells (`<div id="root"></div>` + script bundles with almost zero SSR body text) so `renderMode: "auto"` only launches Chromium when static HTTP/2 lacks content.

func ParseDeclarativeYAML added in v2.6.2

func ParseDeclarativeYAML(raw []byte) (any, error)

ParseDeclarativeYAML parses a safe YAML 1.2 Core Schema subset into standard Go JSON-compatible values (`map[string]any`, `[]any`, `string`, `bool`, `json.Number`, `nil`). Explicitly rejects YAML anchors (`&`), aliases (`*`), merge keys (`<<`), custom tags (`!`), and tab indentation.

func PlainText

func PlainText(rawHTML string) string

PlainText strips scripts/styles/tags from HTML and collapses whitespace.

func RedactPII

func RedactPII(s string) string

RedactPII replaces email addresses, SSNs, phone numbers, and Luhn-valid payment card numbers with `[REDACTED_*]`.

func RerankPassages

func RerankPassages(doc, query string, maxChars int) string

RerankPassages splits long Markdown or PDF text into semantic paragraphs/sections and selects the top chunks matching `query` via BM25-style term scoring + exact-phrase boost while preserving original document reading order.

func YAMLToJSON added in v2.6.2

func YAMLToJSON(raw []byte) ([]byte, error)

YAMLToJSON converts a safe YAML document into canonical UTF-8 JSON bytes.

Types

type BrandingProfile

type BrandingProfile struct {
	Title        string   `json:"title,omitempty"`
	Description  string   `json:"description,omitempty"`
	CanonicalURL string   `json:"canonicalUrl,omitempty"`
	Favicon      string   `json:"favicon,omitempty"`
	OGImage      string   `json:"ogImage,omitempty"`
	ThemeColor   string   `json:"themeColor,omitempty"`
	Colors       []string `json:"colors,omitempty"`
	Fonts        []string `json:"fonts,omitempty"`
}

BrandingProfile summarizes visual brand identity signals extracted from HTML/CSS (`formats: ["branding"]`).

type DeclarativeAdapterManifest added in v2.6.2

type DeclarativeAdapterManifest struct {
	ID          string                  `json:"id"`
	Name        string                  `json:"name"`
	Category    string                  `json:"category"`
	Description string                  `json:"description"`
	Domains     []string                `json:"domains"`
	ExampleURLs []string                `json:"exampleUrls"`
	Match       *DeclarativeMatchSpec   `json:"match,omitempty"`
	Twin        *DeclarativeTwinSpec    `json:"twin,omitempty"`
	Extract     *DeclarativeExtractSpec `json:"extract,omitempty"`
	Routes      []DeclarativeRouteSpec  `json:"routes,omitempty"`
}

DeclarativeAdapterManifest is the canonical shared Go + TypeScript declarative JSON adapter contract.

func ParseDeclarativeManifest added in v2.6.2

func ParseDeclarativeManifest(raw []byte) (*DeclarativeAdapterManifest, error)

ParseDeclarativeManifest parses and validates a single declarative JSON manifest.

func ParseDeclarativeYAMLManifest added in v2.6.2

func ParseDeclarativeYAMLManifest(raw []byte) (*DeclarativeAdapterManifest, error)

ParseDeclarativeYAMLManifest parses and validates a declarative YAML manifest (explicitly rejecting anchors, aliases, and merge keys).

type DeclarativeAdapterSummary added in v2.6.2

type DeclarativeAdapterSummary struct {
	ID              string   `json:"id"`
	Name            string   `json:"name"`
	Category        string   `json:"category"`
	Description     string   `json:"description"`
	Modes           []string `json:"modes"`
	Domains         []string `json:"domains"`
	UniversalEngine bool     `json:"universalEngine"`
	ExampleURLs     []string `json:"exampleUrls"`
}

DeclarativeAdapterSummary describes an embedded declarative site adapter in `GET /v1/extractors` and MCP `find_extractors`.

func FindDeclarativeAdapters added in v2.6.2

func FindDeclarativeAdapters(query, category string, limit int) []DeclarativeAdapterSummary

FindDeclarativeAdapters filters and ranks embedded declarative site adapters by optional query and category.

func ListDeclarativeAdapters added in v2.6.2

func ListDeclarativeAdapters() []DeclarativeAdapterSummary

ListDeclarativeAdapters returns metadata summaries for all embedded declarative site adapters.

type DeclarativeBulletSpec added in v2.6.2

type DeclarativeBulletSpec struct {
	Label    string `json:"label"`
	Template string `json:"template"`
	WhenVar  string `json:"whenVar,omitempty"`
}

DeclarativeBulletSpec renders `- **<Label>**: <Template>` (or `**<Label>**: <Template>` in metaLine).

type DeclarativeDynamicKeyPath added in v2.6.2

type DeclarativeDynamicKeyPath struct {
	Base    string `json:"base"`
	KeyVar  string `json:"keyVar"`
	SubPath string `json:"subPath,omitempty"`
}

DeclarativeDynamicKeyPath looks up root[Base][vars[KeyVar]][SubPath].

type DeclarativeExtractSpec added in v2.6.2

type DeclarativeExtractSpec struct {
	TextMode                string                        `json:"textMode,omitempty"`
	PathParam               string                        `json:"pathParam,omitempty"`
	UnwrapFirstArrayElement bool                          `json:"unwrapFirstArrayElement,omitempty"`
	RootPath                string                        `json:"rootPath,omitempty"`
	FindInArray             *DeclarativeFindInArray       `json:"findInArray,omitempty"`
	RequireFields           []string                      `json:"requireFields,omitempty"`
	RequireAnyFields        []string                      `json:"requireAnyFields,omitempty"`
	RequireVars             []string                      `json:"requireVars,omitempty"`
	Vars                    map[string]DeclarativeVarSpec `json:"vars,omitempty"`
	TitleTemplate           string                        `json:"titleTemplate"`
	TitleWhenVar            string                        `json:"titleWhenVar,omitempty"`
	TitleFallbackTemplate   string                        `json:"titleFallbackTemplate,omitempty"`
	DescriptionVar          string                        `json:"descriptionVar,omitempty"`
	AuthorVar               string                        `json:"authorVar,omitempty"`
	PublishedTimeVar        string                        `json:"publishedTimeVar,omitempty"`
	MetaLine                []DeclarativeBulletSpec       `json:"metaLine,omitempty"`
	IntroVar                string                        `json:"introVar,omitempty"`
	Bullets                 []DeclarativeBulletSpec       `json:"bullets,omitempty"`
	ObjectLinksPath         string                        `json:"objectLinksPath,omitempty"`
	BodyVar                 string                        `json:"bodyVar,omitempty"`
	Sections                []DeclarativeSectionSpec      `json:"sections,omitempty"`
	LinksVars               []string                      `json:"linksVars,omitempty"`
}

DeclarativeExtractSpec defines how a JSON or text twin payload is converted into Markdown and metadata.

type DeclarativeFindInArray added in v2.6.2

type DeclarativeFindInArray struct {
	ArrayPath     string `json:"arrayPath"`
	MatchField    string `json:"matchField"`
	MatchTemplate string `json:"matchTemplate"`
	IgnoreCase    bool   `json:"ignoreCase,omitempty"`
}

DeclarativeFindInArray selects a matching element from a JSON array to serve as the active root object.

type DeclarativeFormattedDoc added in v2.6.2

type DeclarativeFormattedDoc struct {
	Title         string   `json:"title"`
	Description   string   `json:"description,omitempty"`
	Author        string   `json:"author,omitempty"`
	PublishedTime string   `json:"publishedTime,omitempty"`
	Markdown      string   `json:"markdown"`
	Links         []string `json:"links,omitempty"`
}

DeclarativeFormattedDoc holds the structured Markdown and metadata produced from a declarative twin payload.

type DeclarativeMatchSpec added in v2.6.2

type DeclarativeMatchSpec struct {
	ExactSegments *bool                       `json:"exactSegments,omitempty"`
	PathSegments  []DeclarativeSegmentSpec    `json:"pathSegments,omitempty"`
	QueryParams   []DeclarativeQueryParamSpec `json:"queryParams,omitempty"`
	Defaults      map[string]string           `json:"defaults,omitempty"`
	AnyOf         []DeclarativeMatchSpec      `json:"anyOf,omitempty"`
}

DeclarativeMatchSpec matches incoming HTTPS URLs without regular-expression backtracking.

type DeclarativeParamSegment added in v2.6.2

type DeclarativeParamSegment struct {
	Param       string   `json:"param"`
	Charset     string   `json:"charset,omitempty"`
	AllowValues []string `json:"allowValues,omitempty"`
	Reserved    []string `json:"reserved,omitempty"`
	StripSuffix string   `json:"stripSuffix,omitempty"`
	MinLen      int      `json:"minLen,omitempty"`
	MaxLen      int      `json:"maxLen,omitempty"`
	Greedy      bool     `json:"greedy,omitempty"`
}

DeclarativeParamSegment defines a strictly validated URL path segment capture.

type DeclarativeQueryParamSpec added in v2.6.2

type DeclarativeQueryParamSpec struct {
	Name    string `json:"name"`
	Param   string `json:"param"`
	Charset string `json:"charset,omitempty"`
	MinLen  int    `json:"minLen,omitempty"`
	MaxLen  int    `json:"maxLen,omitempty"`
}

DeclarativeQueryParamSpec defines an optional query parameter capture and validation rule.

type DeclarativeRouteSpec added in v2.6.2

type DeclarativeRouteSpec struct {
	Match   DeclarativeMatchSpec   `json:"match"`
	Twin    DeclarativeTwinSpec    `json:"twin"`
	Extract DeclarativeExtractSpec `json:"extract"`
}

DeclarativeRouteSpec pairs a URL match specification with its twin fetch and extraction contract.

type DeclarativeSectionSpec added in v2.6.2

type DeclarativeSectionSpec struct {
	Heading        string                        `json:"heading"`
	TextVar        string                        `json:"textVar,omitempty"`
	ArrayPath      string                        `json:"arrayPath,omitempty"`
	Columns        []DeclarativeTableColumn      `json:"columns,omitempty"`
	ListArrayPath  string                        `json:"listArrayPath,omitempty"`
	Limit          int                           `json:"limit,omitempty"`
	IndentField    string                        `json:"indentField,omitempty"`
	IndentOffset   int                           `json:"indentOffset,omitempty"`
	MaxIndent      int                           `json:"maxIndent,omitempty"`
	ItemTemplate   string                        `json:"itemTemplate,omitempty"`
	RequireItemVar string                        `json:"requireItemVar,omitempty"`
	ItemVars       map[string]DeclarativeVarSpec `json:"itemVars,omitempty"`
}

DeclarativeSectionSpec renders a `## <Heading>` prose, GFM table, or nested bullet list section.

type DeclarativeSegmentSpec added in v2.6.2

type DeclarativeSegmentSpec struct {
	IsLiteral bool
	Literal   string
	ParamSpec DeclarativeParamSegment
}

DeclarativeSegmentSpec represents either a literal path segment ("gems") or a DeclarativeParamSegment.

func (*DeclarativeSegmentSpec) UnmarshalJSON added in v2.6.2

func (s *DeclarativeSegmentSpec) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a string literal segment or an object parameter segment.

type DeclarativeSubFieldsJoin added in v2.6.2

type DeclarativeSubFieldsJoin struct {
	Fields        []string `json:"fields"`
	Sep           string   `json:"sep"`
	FallbackField string   `json:"fallbackField,omitempty"`
}

DeclarativeSubFieldsJoin joins subfields from objects inside an array (e.g. Crossref given + family).

type DeclarativeTableColumn added in v2.6.2

type DeclarativeTableColumn struct {
	Header          string   `json:"header"`
	Paths           []string `json:"paths,omitempty"`
	FallbackVar     string   `json:"fallbackVar,omitempty"`
	Format          string   `json:"format,omitempty"`
	OutcomesField   string   `json:"outcomesField,omitempty"`
	PricesField     string   `json:"pricesField,omitempty"`
	DefaultOutcomes []string `json:"defaultOutcomes,omitempty"`
	Code            bool     `json:"code,omitempty"`
	SliceMax        int      `json:"sliceMax,omitempty"`
}

DeclarativeTableColumn defines a column in a GFM Markdown table section.

type DeclarativeTwinMatch added in v2.6.2

type DeclarativeTwinMatch struct {
	ID        string
	AdapterID string
	FetchURL  string
	Kind      classify.Kind
	Accept    string
	// contains filtered or unexported fields
}

DeclarativeTwinMatch represents a resolved 1-hop declarative twin upgrade ready to fetch and format.

func ResolveDeclarativeTwin added in v2.6.2

func ResolveDeclarativeTwin(rawURL string) (*DeclarativeTwinMatch, bool)

ResolveDeclarativeTwin checks if `rawURL` matches any embedded declarative adapter and returns its 1-hop twin descriptor.

func (*DeclarativeTwinMatch) Format added in v2.6.2

Format transforms a fetched JSON or text twin body into clean GitHub-Flavored Markdown and structured metadata. Returns `(nil, false)` on malformed, HTML soft-404, or schema-mismatched payloads so callers safely fall back to HTML scraping.

type DeclarativeTwinSpec added in v2.6.2

type DeclarativeTwinSpec struct {
	ID            string   `json:"id,omitempty"`
	FetchURL      string   `json:"fetchUrl"`
	RawPathParams []string `json:"rawPathParams,omitempty"`
	Kind          string   `json:"kind"`
	Accept        string   `json:"accept"`
}

DeclarativeTwinSpec describes the 1-hop HTTPS JSON/text endpoint upgrade.

type DeclarativeVarSpec added in v2.6.2

type DeclarativeVarSpec struct {
	Paths               []string                   `json:"paths,omitempty"`
	DynamicKeyPath      *DeclarativeDynamicKeyPath `json:"dynamicKeyPath,omitempty"`
	Template            string                     `json:"template,omitempty"`
	WhenVars            []string                   `json:"whenVars,omitempty"`
	FallbackVar         string                     `json:"fallbackVar,omitempty"`
	FirstNonMatchingKey string                     `json:"firstNonMatchingKey,omitempty"`
	SubField            string                     `json:"subField,omitempty"`
	SubFieldsJoin       *DeclarativeSubFieldsJoin  `json:"subFieldsJoin,omitempty"`
	ItemWrap            string                     `json:"itemWrap,omitempty"`
	Join                string                     `json:"join,omitempty"`
	Limit               int                        `json:"limit,omitempty"`
	Format              string                     `json:"format,omitempty"`
	TrueValue           string                     `json:"trueValue,omitempty"`
	FalseValue          string                     `json:"falseValue,omitempty"`
	StripFrontmatter    bool                       `json:"stripFrontmatter,omitempty"`
	Trim                bool                       `json:"trim,omitempty"`
	RequireHTTPS        bool                       `json:"requireHttps,omitempty"`
	SliceMax            int                        `json:"sliceMax,omitempty"`
	Default             string                     `json:"default,omitempty"`
	FallbackTemplate    string                     `json:"fallbackTemplate,omitempty"`
}

DeclarativeVarSpec extracts and formats a named string variable from JSON.

type ExtractOptions

type ExtractOptions struct {
	BaseURL         string
	OnlyMainContent bool
	IncludeLinks    bool
	IncludeImages   bool
	IncludeBranding bool
	RedactPII       bool
	Query           string
	MaxChars        int
}

ExtractOptions configures HTML extraction.

type ImageInfo

type ImageInfo struct {
	URL string `json:"url"`
	Alt string `json:"alt,omitempty"`
}

ImageInfo describes an image discovered on a page.

type LlmsDiscovery

type LlmsDiscovery struct {
	Found           bool       `json:"found"`
	LlmsTxtURL      string     `json:"llmsTxtUrl,omitempty"`
	LlmsFullTxtURL  string     `json:"llmsFullTxtUrl,omitempty"`
	CompanionMdURL  string     `json:"companionMdUrl,omitempty"`
	UsedCompanionMd bool       `json:"usedCompanionMd,omitempty"`
	SiteTitle       string     `json:"siteTitle,omitempty"`
	SiteSummary     string     `json:"siteSummary,omitempty"`
	MatchedEntry    *LlmsLink  `json:"matchedEntry,omitempty"`
	RelatedLinks    []LlmsLink `json:"relatedLinks,omitempty"`
}

LlmsDiscovery reports `llms.txt` / companion `.md` enrichment attached to a crawled page Result.

type LlmsDocument

type LlmsDocument struct {
	SourceURL  string     `json:"sourceUrl"`
	Title      string     `json:"title,omitempty"`
	Summary    string     `json:"summary,omitempty"`
	FullTxtURL string     `json:"fullTxtUrl,omitempty"`
	Links      []LlmsLink `json:"links,omitempty"`
	RawPreview string     `json:"rawPreview,omitempty"`
}

LlmsDocument represents a parsed `/llms.txt` index per https://llmstxt.org/.

func ParseLlmsTxt

func ParseLlmsTxt(raw, sourceURL string) (*LlmsDocument, bool)

ParseLlmsTxt parses an `llms.txt` Markdown file, rejecting HTML 200 soft-404 pages masquerading as `/llms.txt`.

Example
package main

import (
	"fmt"

	"github.com/bartrumb/edgefetch/v2/internal/extract"
)

func main() {
	raw := `# EdgeFetch Docs
> Distributed edge web crawler for AI agents.

## Guides
- [Quickstart](/docs/quickstart.md): Deploy Hub + Go Worker in 60 seconds
`
	doc, ok := extract.ParseLlmsTxt(raw, "https://docs.example.com/llms.txt")
	fmt.Println("valid:", ok, "| title:", doc.Title, "| firstUrl:", doc.Links[0].URL)
}
Output:
valid: true | title: EdgeFetch Docs | firstUrl: https://docs.example.com/docs/quickstart.md

func (*LlmsDocument) MatchPage

func (doc *LlmsDocument) MatchPage(pageURL string) (matched *LlmsLink, companionMdURL string, related []LlmsLink)

MatchPage finds any exact orcompanion `.md` entry in `doc` corresponding to `pageURL`, plus up to 8 same-section related links.

type LlmsLink struct {
	Section string `json:"section,omitempty"`
	Title   string `json:"title"`
	URL     string `json:"url"`
	Notes   string `json:"notes,omitempty"`
}

LlmsLink represents a single `- [Title](URL): Notes` entry inside `/llms.txt`.

type PageExtraction

type PageExtraction struct {
	Title       string           `json:"title,omitempty"`
	Description string           `json:"description,omitempty"`
	Favicon     string           `json:"favicon,omitempty"`
	Markdown    string           `json:"markdown,omitempty"`
	Text        string           `json:"text,omitempty"`
	Links       []string         `json:"links,omitempty"`
	Images      []ImageInfo      `json:"images,omitempty"`
	Branding    *BrandingProfile `json:"branding,omitempty"`
}

PageExtraction holds the structured outputs extracted from an HTML document.

func ExtractHTML

func ExtractHTML(rawHTML string, opts ExtractOptions) PageExtraction

ExtractHTML parses rawHTML into clean Markdown, plain text, links, images, and optional branding profile.

Example
package main

import (
	"fmt"

	"github.com/bartrumb/edgefetch/v2/internal/extract"
)

func main() {
	rawHTML := `<!doctype html>
<html>
  <head><title>Async Runtime</title></head>
  <body>
    <nav><a href="/home">Home</a></nav>
    <main>
      <h1>Async Runtime</h1>
      <p>Returns <code>Promise&lt;void&gt;</code> when complete.</p>
    </main>
  </body>
</html>`
	page := extract.ExtractHTML(rawHTML, extract.ExtractOptions{
		BaseURL:         "https://docs.example.com/guide",
		OnlyMainContent: true,
	})
	fmt.Println(page.Markdown)
}
Output:
# Async Runtime

Returns `Promise<void>` when complete.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL