dsl

package
v2.8.44 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 18 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 dsl implements EdgeFetch's Cross-Compatible Bounded Adapter DSL v2 (`dsl: 2`).

Architecture (`docs/adapters/DSL-V2-RFC.md`)

Every `dsl: 2` route executes through a single 3-stage bounded pipeline:

  1. Stage 1 — Bounded Source Readers (`readers_*.go`): Reads JSON (`4 MiB` max), HTML DOM / `<table>` / `<dl>` / `<meta>` / JSON-LD (`2 MiB` max), SSR hydration JSON (`#__NEXT_DATA__` or brace-balanced JS assignments, `512 KiB` max), namespaced XML / RSS / Atom / JATS (`1,000` items max), or RFC 4180 CSV / TSV (`2 MiB`, `1,000` rows max), with multi-shape `variants` dispatch (`<= 8` branches) into normalized Go values (`nil | bool | json.Number | float64 | string | []any | map[string]any`).

  2. Stage 2 — Shared Pure Value & Collection Pipeline (`ops_*.go`): Evaluates prefilter & negative-shell / JSON-error guards, bounded `parseJson` (`<= 256 KiB`, depth `<= 16`, keys `<= 4,096`), zero-regex `O(n)` scalar text pipelines (`<= 16` steps, `<= 64 KiB` output), declarative `coalesce` / `lookup` (`<= 256` entries) / `when` switches, deterministic locale-independent typed formatters (`formatDate`, `formatCurrency`, `formatNumber`, `formatBytes`, `formatDuration`, `formatUnit`), and bounded collection operators (`filter`, `preferWhere`, `dedupeBy`, `sort`, `limit`, `groupBy`, `count`, `sum`, capped at `2,000` items and `50` groups).

  3. Stage 3 — Unconditionally Sanitized Shared Emitter (`emitter.go`): Renders GFM Markdown (`Title`, `MetaLine`, `Blockquote`, `Intro`, `Bullets`, `KVTable`, `Body`, `Sections`, `Subsections`, `TreeComments`, `FooterItalic`), structured `Records[]`, `Links[]`, and `PaginationMeta`. Stage 3 is the sole output exit of the package and unconditionally sanitizes all metadata fields, GFM table cells, raw HTML outside fenced code blocks, and dangerous URL schemes (`javascript:`, `vbscript:`, `data:`, `file:`, `blob:`).

WASM & Bulkhead Guarantees

  • Zero `crypto` or `crypto/*` imports (safe for `GOOS=wasip1 GOARCH=wasm` without Go 1.26 FIPS DRBG BSS).
  • Zero backtracking regular expressions; all text ops use pure `strings` primitives and any date/number helper regexes use lazy `sync.OnceValue` RE2 automata.

Index

Constants

View Source
const (
	MaxJSONBytes         = 4 << 20   // 4 MiB max JSON source payload
	MaxJSONDepth         = 32        // Max nesting depth for JSON source payloads
	MaxHTMLBytes         = 2 << 20   // 2 MiB max HTML source payload
	MaxSelectAllItems    = 500       // Max elements returned by HTML selectAll
	MaxTableRows         = 500       // Max rows extracted from HTML <table> or <dl>
	MaxTableCols         = 32        // Max columns per row in HTML <table>
	MaxHydrationBytes    = 512 << 10 // 512 KiB max SSR hydration JSON slice
	MaxHydrationDepth    = 24        // Max brace/bracket depth in SSR hydration JSON
	MaxXMLItems          = 1000      // Max items extracted by xmlFeed
	MaxDelimitedBytes    = 2 << 20   // 2 MiB max CSV/TSV input
	MaxDelimitedRows     = 1000      // Max data rows extracted from CSV/TSV
	MaxDelimitedCols     = 64        // Max columns per CSV/TSV row
	MaxVariants          = 8         // Max multi-shape dispatch branches
	MaxParseJSONBytes    = 256 << 10 // 256 KiB max embedded JSON string for parseJson
	MaxParseJSONDepth    = 16        // Max nesting depth for parseJson
	MaxParseJSONKeys     = 4096      // Max object keys decoded by parseJson
	MaxPipelineSteps     = 16        // Max chained Stage 2 steps per variable
	MaxScalarOutputBytes = 64 << 10  // 64 KiB max scalar string output per variable
	MaxLookupEntries     = 256       // Max entries in a lookup table
	MaxCollectionItems   = 2000      // Max items processed by Stage 2 collection operators
	MaxGroups            = 50        // Max distinct groups emitted by groupBy
	MaxEmittedLinks      = 2000      // Max deduplicated public HTTPS links emitted
)

Hard resource ceilings enforced across all Stage 1 readers, Stage 2 operators, and Stage 3 emitters.

View Source
const Version2 = 2

Version2 identifies Cross-Compatible Bounded Adapter DSL v2 specs.

Variables

This section is empty.

Functions

func ApplyDedupeBy

func ApplyDedupeBy(items []map[string]any, dd *DedupeSpec) []map[string]any

ApplyDedupeBy deduplicates and merges items by `KeyPaths` (`#7`, `maxItems <= 2000`).

func ApplyFilter

func ApplyFilter(items []map[string]any, flt *FilterSpec, params map[string]string, varLookup func(string) string) []map[string]any

ApplyFilter filters bounded `[]map[string]any` items in O(n) (`#13`).

func ApplySort

func ApplySort(items []map[string]any, keys []SortKeySpec) []map[string]any

ApplySort stably sorts up to `MaxCollectionItems` (`2,000`) items in O(n log n) (`#19`).

func CheckNegativeHTMLShell

func CheckNegativeHTMLShell(rawHTML, rawURL string, genericTitles, extraNotFound, pathExemptions []string) bool

CheckNegativeHTMLShell inspects URL soft-404/auth paths, `<title>` / `<h1>` error/WAF/maintenance/generic shell markers, adapter-scoped `genericTitles`, and empty CSR mount shells (`<div id="root"></div>`) in O(n) bounded time with zero regular expressions.

func CheckNegativeJSONError

func CheckNegativeJSONError(rootObj map[string]any) bool

CheckNegativeJSONError detects standard REST/GraphQL JSON error envelopes (`status >= 400`, `success == false`, `ok == false`, or non-empty `error`/`errors`/`fault`/`exception` without payload data).

func CheckRequireAnyProbe

func CheckRequireAnyProbe(rawBody string, needles []string) bool

CheckRequireAnyProbe runs a 64 KiB ASCII-lowercase substring prefilter in O(n) time.

func EvalCondition

func EvalCondition(cond ConditionSpec, currentVal any, activeObj map[string]any, varLookup func(string) string) bool

EvalCondition evaluates a typed comparison predicate on `target` (or `activeObj[cond.Field]` / `varLookup(cond.Var)`).

func EvalCount

func EvalCount(raw any) int

EvalCount returns the bounded length of an array (`<= 2000`).

func EvalLookup

func EvalLookup(rawKey string, table map[string]string, fallback string, ignoreCase bool) string

EvalLookup maps `rawKey` through a bounded lookup table (`<= MaxLookupEntries = 256` entries).

func EvalSum

func EvalSum(raw any, fieldPath string) (float64, bool)

EvalSum sums numeric scalars (or `fieldPath` inside objects) across up to `MaxCollectionItems` (`2,000`) items.

func FormatBytesValue

func FormatBytesValue(raw any, spec *BytesFormatSpec) string

FormatBytesValue formats byte counts into IEC (`KiB`/`MiB`/`GiB`), SI (`KB`/`MB`/`GB`), or legacy human strings.

func FormatCase

func FormatCase(s, mode string) string

FormatCase transforms `s` to `"lower"`, `"upper"`, or `"title"` without regular expressions.

func FormatCurrencyValue

func FormatCurrencyValue(raw any, spec *CurrencyFormatSpec, activeObj map[string]any, varLookup func(string) string) string

FormatCurrencyValue formats numeric/price scalars deterministically (`$1,299.00` or `1,299.00 USD`).

func FormatDateValue

func FormatDateValue(raw any, spec *DateFormatSpec) string

FormatDateValue formats `raw` according to `spec`.

func FormatDurationValue

func FormatDurationValue(raw any, spec *DurationFormatSpec) string

FormatDurationValue formats seconds/milliseconds/minutes or ISO-8601 `PT1H2M3S` into `"1h 2m 3s"` or `"1:02:03"`.

func FormatNumberValue

func FormatNumberValue(raw any, spec *NumberFormatSpec) string

FormatNumberValue formats numeric scalars deterministically (`decimals`, `thousandsSep`, `scale`, `compact`).

func FormatUnitValue

func FormatUnitValue(raw any, spec *UnitFormatSpec, activeObj map[string]any, varLookup func(string) string) string

FormatUnitValue formats a numeric value with a measurement unit (`50 Nm`, `360 Wh`).

func GetByDotPath

func GetByDotPath(root any, dotPath string) any

GetByDotPath navigates nested `map[string]any` and `[]any` values using dot-separated segments AND bracket indices (both `items.0.title` and `items[0].title` or `[0].title` are supported in O(pathLen)). Keys containing literal `.` (e.g. `"01. symbol"`) are resolved via direct map lookup when the remaining suffix matches an existing property on the current object.

func IsTruthy

func IsTruthy(v any) bool

IsTruthy evaluates JavaScript/JSON-like truthiness on normalized DSL values.

func ParseEmbeddedJSON

func ParseEmbeddedJSON(raw string, maxBytes, maxDepth int) any

ParseEmbeddedJSON decodes JSON stored inside a scalar string with strict byte, depth, and key caps. Malformed or over-budget JSON returns `nil` cleanly without error panics.

func ParseNormalizedDate

func ParseNormalizedDate(raw any, inputLayouts []string, epochUnit string) (time.Time, bool)

ParseNormalizedDate parses epoch numbers, `[YYYY, M, D]` arrays, ISO-8601, RFC3339, RFC1123, US slash, human English dates, compact `YYYYMMDD`, or explicit `inputLayouts` into a UTC `time.Time`.

func ReplaceLiteralBounded

func ReplaceLiteralBounded(s, from, to string) string

ReplaceLiteralBounded performs a zero-regex literal replacement while capping output at `MaxScalarOutputBytes` (`64 KiB`) so pathological expansion (`From: "a"`, `To: 1000*"b"`) cannot blow up memory.

func ScalarToString

func ScalarToString(v any) string

ScalarToString converts a normalized JSON/DSL scalar (`string`, `json.Number`, `float64`, `int`, `int64`, `bool`) to string.

func SelectPreferWhere

func SelectPreferWhere(arr []any, pw *PreferWhereSpec) any

SelectPreferWhere narrows an array value to the best matching element (`#13`).

func SlugToTitle

func SlugToTitle(s string) string

SlugToTitle converts URL/identifier slugs (`"e-bike-battery-guide_v2"` -> `"E Bike Battery Guide V2"`) in a single linear pass with zero regular expressions.

func SplitLinear

func SplitLinear(s, sep string, limit int) []any

SplitLinear splits `s` by `sep` in O(n) with zero regular expressions, capped at `limit` parts (`<= 2000`).

func TrimPrefixOp

func TrimPrefixOp(s, prefix string, ignoreCase bool) string

TrimPrefixOp strips `prefix` (optionally case-insensitively) on UTF-8 rune boundaries.

func TrimSuffixOp

func TrimSuffixOp(s, suffix string, ignoreCase bool) string

TrimSuffixOp strips `suffix` (optionally case-insensitively) on UTF-8 rune boundaries.

func TruncateRunesUTF8

func TruncateRunesUTF8(s string, maxChars int, ellipsis string) string

TruncateRunesUTF8 truncates `s` to at most `maxChars` UTF-8 runes, appending `ellipsis` when truncated.

func ValueToFloat

func ValueToFloat(v any) (float64, bool)

ValueToFloat parses numeric scalars (`json.Number`, `float64`, `int`, `int64`, or numeric strings) to `float64`.

Types

type AppendCurrentMdDeltaSpec

type AppendCurrentMdDeltaSpec struct {
	BaseVar       string `json:"baseVar,omitempty"`
	MinExtraChars int    `json:"minExtraChars"`
}

AppendCurrentMdDeltaSpec appends generic Readability Markdown when it is substantially richer than BaseVar.

type ArrayFieldGate

type ArrayFieldGate struct {
	ArrayPath string `json:"arrayPath"`
	Field     string `json:"field"`
}

ArrayFieldGate requires `ArrayPath` to be an array and (if non-empty) its first element's `Field` to be truthy.

type BulletSpec

type BulletSpec struct {
	Label           string `json:"label,omitempty"`
	Template        string `json:"template"`
	WhenVar         string `json:"whenVar,omitempty"`
	UnlessVar       string `json:"unlessVar,omitempty"`
	ColonInsideBold bool   `json:"colonInsideBold,omitempty"`
}

BulletSpec renders `- **<Label>**: <Template>` in Bullets or `**<Label>**: <Template>` in MetaLine.

type BytesFormatSpec

type BytesFormatSpec struct {
	Base      int    `json:"base,omitempty"`      // 1024 (`KiB`/`MiB`/`GiB`, default) | 1000 (`KB`/`MB`/`GB`)
	Style     string `json:"style,omitempty"`     // "" | "iec" (KiB/MiB) | "si" (KB/MB base 1000) | "legacy_kb_mb" (v1 bytes_human parity)
	Decimals  *int   `json:"decimals,omitempty"`  // defaults to 1 (0 for B)
	OnInvalid string `json:"onInvalid,omitempty"` // "keep" | "empty" | "dash"
}

BytesFormatSpec configures byte-size formatting (`#16`).

type CSSAllTextSpec

type CSSAllTextSpec struct {
	Selector string `json:"selector"`
	Limit    int    `json:"limit,omitempty"`
	Dedupe   *bool  `json:"dedupe,omitempty"`
	Join     string `json:"join,omitempty"`
}

CSSAllTextSpec extracts text from all matching nodes and joins them.

type CSSAttrSpec

type CSSAttrSpec struct {
	Selector string `json:"selector,omitempty"`
	Attr     string `json:"attr"`
}

CSSAttrSpec extracts an attribute from the first matching selector.

type CodeByPathSpec

type CodeByPathSpec struct {
	SourceVar     string `json:"sourceVar"`
	PathParam     string `json:"pathParam"`
	RawIfMarkdown bool   `json:"rawIfMarkdown,omitempty"`
}

CodeByPathSpec formats a code/markdown variable using the file extension from a path parameter.

type CollectionPipelineSpec

type CollectionPipelineSpec struct {
	ArrayPath      string              `json:"arrayPath,omitempty"`
	ObjectEntries  *ObjectEntriesSpec  `json:"objectEntries,omitempty"`
	ParallelArrays *ParallelArraysSpec `json:"parallelArrays,omitempty"`
	Filter         *FilterSpec         `json:"filter,omitempty"`
	DedupeBy       *DedupeSpec         `json:"dedupeBy,omitempty"`
	Sort           []SortKeySpec       `json:"sort,omitempty"`
	Limit          int                 `json:"limit,omitempty"`
}

CollectionPipelineSpec transforms a source array into a filtered/deduped/sorted/sliced collection or aggregate.

type ConditionSpec

type ConditionSpec struct {
	Field      string   `json:"field,omitempty"` // dot-path on item/object; empty tests current value
	Var        string   `json:"var,omitempty"`   // variable name to test instead of current value
	Op         string   `json:"op"`              // "equals", "notEquals", "in", "notIn", "contains", "prefix", "notPrefix", "suffix", "notSuffix", "gt", "gte", "lt", "lte", "exists", "truthy"
	Value      string   `json:"value,omitempty"`
	Values     []string `json:"values,omitempty"`
	Num        *float64 `json:"num,omitempty"`
	IgnoreCase bool     `json:"ignoreCase,omitempty"`
}

ConditionSpec defines a typed comparison predicate for `when` and `filter`.

type CurrencyFormatSpec

type CurrencyFormatSpec struct {
	Currency     string  `json:"currency,omitempty"`     // literal ISO-4217 code or symbol (e.g. "USD", "$")
	CurrencyPath string  `json:"currencyPath,omitempty"` // dot-path on active object
	CurrencyVar  string  `json:"currencyVar,omitempty"`  // variable name holding currency code
	Scale        float64 `json:"scale,omitempty"`        // e.g. 0.01 for minor units / cents
	Decimals     *int    `json:"decimals,omitempty"`     // defaults to 2 (0 for JPY/KRW when omitted)
	Style        string  `json:"style,omitempty"`        // "symbol" (default: $1,299.00) | "iso" (1,299.00 USD) | "compact" ($1.25M) | "free_or_iso"
	ThousandsSep *string `json:"thousandsSep,omitempty"` // defaults to ","
	OnInvalid    string  `json:"onInvalid,omitempty"`    // "keep" | "empty"
}

CurrencyFormatSpec configures deterministic currency formatting (`#5`).

type DateFormatSpec

type DateFormatSpec struct {
	InputLayouts []string `json:"inputLayouts,omitempty"` // optional explicit Go or YYYY-MM-DD layouts
	Output       string   `json:"output,omitempty"`       // "isoDate" (default: 2006-01-02) | "isoDateTime" | "humanDate" (Jan 2, 2006) | "monthYear" (Jan 2006) | custom Go layout
	EpochUnit    string   `json:"epochUnit,omitempty"`    // "" (auto) | "s" | "ms"
	OnInvalid    string   `json:"onInvalid,omitempty"`    // "keep" | "empty" (default "empty")
}

DateFormatSpec configures deterministic locale-independent date formatting (`#2`).

type DedupeSpec

type DedupeSpec struct {
	KeyPaths          []string `json:"keyPaths"`
	MergeTextPaths    []string `json:"mergeTextPaths,omitempty"`
	MergeTargetField  string   `json:"mergeTargetField,omitempty"`
	MergeSep          string   `json:"mergeSep,omitempty"`
	MergeLimit        int      `json:"mergeLimit,omitempty"`
	OrBoolPaths       []string `json:"orBoolPaths,omitempty"`
	OrBoolTargetField string   `json:"orBoolTargetField,omitempty"`
}

DedupeSpec deduplicates and merges array items by key (`#7`).

type DelimitedSpec

type DelimitedSpec struct {
	Sep       string   `json:"sep,omitempty"`    // "," (default) or "\t" or ";" or "|"
	Header    *bool    `json:"header,omitempty"` // defaults to true
	Columns   []string `json:"columns,omitempty"`
	MaxRows   int      `json:"maxRows,omitempty"`
	MaxBytes  int      `json:"maxBytes,omitempty"`
	IntoField string   `json:"intoField,omitempty"` // defaults to "rows"
}

DelimitedSpec configures RFC 4180 streaming CSV / TSV reading (`maxBytes <= 2 MiB`, `maxRows <= 1000`).

type Document

type Document 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"`
	Records       []map[string]any `json:"records,omitempty"`
	ReplaceLinks  bool             `json:"-"`
	Total         *int             `json:"total,omitempty"`
	Returned      *int             `json:"returned,omitempty"`
	Truncated     *bool            `json:"truncated,omitempty"`
	NextCursor    string           `json:"nextCursor,omitempty"`
}

Document is the unconditionally sanitized Stage 3 output of Execute.

func Execute

func Execute(spec Spec, input Input, opts ExecuteOptions) (*Document, bool)

Execute runs the complete 3-stage bounded `dsl: 2` pipeline (`Stage 1 Readers -> Stage 2 Ops -> Stage 3 Sanitized Emitter`) and returns the unconditionally sanitized `*Document` and `true` when extraction succeeds, or `(nil, false)` otherwise.

type DurationFormatSpec

type DurationFormatSpec struct {
	InputUnit string `json:"inputUnit,omitempty"` // "s" (default) | "ms" | "m" | "iso"
	Style     string `json:"style,omitempty"`     // "human" (default: "1h 2m 3s") | "clock" ("1:02:03" / "02:03")
	OnInvalid string `json:"onInvalid,omitempty"` // "keep" | "empty"
}

DurationFormatSpec configures duration formatting (`#16`).

type DynamicKeyPathSpec

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

DynamicKeyPathSpec looks up `activeObj[Base][vars[KeyVar]][SubPath]`.

type EmitSpec

type EmitSpec struct {
	TitleTemplate         string `json:"titleTemplate,omitempty"`
	TitleWhenVar          string `json:"titleWhenVar,omitempty"`
	TitleFallbackTemplate string `json:"titleFallbackTemplate,omitempty"`
	AllowEmptyTitle       bool   `json:"allowEmptyTitle,omitempty"` // true for DOM HTML routes that omit title when body starts with H1

	DescriptionVar      string `json:"descriptionVar,omitempty"`
	DescriptionTemplate string `json:"descriptionTemplate,omitempty"`
	AuthorVar           string `json:"authorVar,omitempty"`
	AuthorTemplate      string `json:"authorTemplate,omitempty"`
	PublishedTimeVar    string `json:"publishedTimeVar,omitempty"`

	// TemplateMode selects subtle inline escaping parity ("safe_md" default vs "dom_bullet" for v1 DOM HTML routes).
	TemplateMode string `json:"templateMode,omitempty"`
	// BlockOrder selects block ordering ("standard" default: Title, MetaLine, Blockquote, Intro, Bullets, KVTable, Body, FooterItalic, Sections
	// vs "dom": Title/Blockquote, MetaItalic, Intro, Bullets, KVTable, Body, Sections, AppendCurrentMdDelta).
	BlockOrder string `json:"blockOrder,omitempty"`

	MetaLine             []BulletSpec  `json:"metaLine,omitempty"`
	MetaLineItalic       bool          `json:"metaLineItalic,omitempty"`
	MetaItalicTemplate   string        `json:"metaItalicTemplate,omitempty"`
	MetaItalicWhenVar    string        `json:"metaItalicWhenVar,omitempty"`
	BlockquoteTemplate   string        `json:"blockquoteTemplate,omitempty"`
	BlockquoteWhenVar    string        `json:"blockquoteWhenVar,omitempty"`
	IntroVar             string        `json:"introVar,omitempty"`
	Bullets              []BulletSpec  `json:"bullets,omitempty"`
	ObjectLinksPath      string        `json:"objectLinksPath,omitempty"`
	KVTables             []KVTableSpec `json:"kvTables,omitempty"`
	BodyVar              string        `json:"bodyVar,omitempty"`
	BodyFallbackHeading  string        `json:"bodyFallbackHeading,omitempty"`
	FooterItalicTemplate string        `json:"footerItalicTemplate,omitempty"`
	FooterItalicWhenVar  string        `json:"footerItalicWhenVar,omitempty"`

	Sections             []SectionSpec             `json:"sections,omitempty"`
	AppendCurrentMdDelta *AppendCurrentMdDeltaSpec `json:"appendCurrentMdDelta,omitempty"`
	CodeByPath           *CodeByPathSpec           `json:"codeByPath,omitempty"`

	LinksVars                []string          `json:"linksVars,omitempty"`
	LinkTemplates            []string          `json:"linkTemplates,omitempty"`
	PreserveBodyLinksFromVar string            `json:"preserveBodyLinksFromVar,omitempty"`
	RecordFields             map[string]string `json:"recordFields,omitempty"`
	KeepEmptyRecordFields    bool              `json:"keepEmptyRecordFields,omitempty"`
	Pagination               *PaginationSpec   `json:"pagination,omitempty"`
}

EmitSpec configures Stage 3 presentation blocks, records, links, and pagination.

type ExecuteOptions

type ExecuteOptions struct {
	HTMLToMarkdown HTMLToMarkdownFunc
	Sanitizer      *SanitizerHooks
}

ExecuteOptions configures optional host callbacks for Execute.

type FieldPrefixFilterSpec

type FieldPrefixFilterSpec struct {
	Field  string `json:"field"`
	Prefix string `json:"prefix"`
}

FieldPrefixFilterSpec excludes items whose Field starts with Prefix.

type FieldSuffixesFilterSpec

type FieldSuffixesFilterSpec struct {
	Field    string   `json:"field"`
	Suffixes []string `json:"suffixes"`
}

FieldSuffixesFilterSpec excludes items whose Field is empty or ends with any suffix in Suffixes.

type FilterSpec

type FilterSpec struct {
	// Composable v2 predicates (all conditions must hold when All is set; at least one when Any is set):
	All []ConditionSpec `json:"all,omitempty"`
	Any []ConditionSpec `json:"any,omitempty"`

	// Direct v1-compatible field filters:
	RequireField         string                   `json:"requireField,omitempty"`
	ExcludeFieldPrefix   *FieldPrefixFilterSpec   `json:"excludeFieldPrefix,omitempty"`
	ExcludeFieldSuffixes *FieldSuffixesFilterSpec `json:"excludeFieldSuffixes,omitempty"`
	TagFilterParam       *TagFilterParamSpec      `json:"tagFilterParam,omitempty"`
}

FilterSpec filters array elements in O(n) bounded time (`#13`).

type FindInArraySpec

type FindInArraySpec struct {
	ArrayPath        string   `json:"arrayPath"`
	MatchField       string   `json:"matchField,omitempty"`
	MatchFields      []string `json:"matchFields,omitempty"`
	EndsWithField    string   `json:"endsWithField,omitempty"`
	MatchTemplate    string   `json:"matchTemplate"`
	EndsWithTemplate string   `json:"endsWithTemplate,omitempty"`
	IgnoreCase       bool     `json:"ignoreCase,omitempty"`
}

FindInArraySpec locates a single object inside an array to serve as the active root object.

type FindLangSpec

type FindLangSpec struct {
	ArrayPath  string `json:"arrayPath"`
	LangField  string `json:"langField"`
	LangValue  string `json:"langValue"`
	ValueField string `json:"valueField"`
}

FindLangSpec selects a localized string from an array of `{ lang, value }` objects.

type GroupBySpec

type GroupBySpec struct {
	Field           string `json:"field"`
	DefaultGroup    string `json:"defaultGroup,omitempty"`
	MaxGroups       int    `json:"maxGroups,omitempty"`
	HeadingTemplate string `json:"headingTemplate,omitempty"` // defaults to "{group} ({count})"
}

GroupBySpec partitions rows into ordered `###` groups (`#20`, `maxGroups <= 50`).

type GroupedItems

type GroupedItems struct {
	Group string
	Items []map[string]any
}

GroupedItems holds one ordered partition produced by `ApplyGroupBy`.

func ApplyGroupBy

func ApplyGroupBy(items []map[string]any, gb *GroupBySpec) []GroupedItems

ApplyGroupBy partitions items into ordered groups (`#20`, `maxGroups <= 50`).

type GuardSpec

type GuardSpec struct {
	// 64 KiB ASCII-lowercase probe substring prefilter (at least one needle must appear if non-empty).
	RequireAnyProbe []string `json:"requireAnyProbe,omitempty"`

	// Negative HTML shell guard (`#3`: 404/403/410/429/5xx/WAF/maintenance/login/empty-CSR + adapter-scoped genericTitles).
	RejectNegativeShell     bool     `json:"rejectNegativeShell,omitempty"`
	GenericTitles           []string `json:"genericTitles,omitempty"`
	ExtraNotFoundSubstrings []string `json:"extraNotFoundSubstrings,omitempty"`
	PathExemptions          []string `json:"pathExemptions,omitempty"`

	// Negative JSON error-envelope guard (`status >= 400`, `success == false`, `{ error, errors, fault }`).
	RejectJSONError        bool            `json:"rejectJsonError,omitempty"`
	RejectIfFieldTruthy    string          `json:"rejectIfFieldTruthy,omitempty"`
	RejectIfAnyFieldTruthy []string        `json:"rejectIfAnyFieldTruthy,omitempty"`
	RequireFieldEquals     *PathEq         `json:"requireFieldEquals,omitempty"`
	RequireArrayItemField  *ArrayFieldGate `json:"requireArrayItemField,omitempty"`
	RequireFields          []string        `json:"requireFields,omitempty"`
	RequireAnyFields       []string        `json:"requireAnyFields,omitempty"`
	RequireVars            []string        `json:"requireVars,omitempty"`
	RequireBulletsOrVars   []string        `json:"requireBulletsOrVars,omitempty"`
}

GuardSpec configures pre-parse and post-parse validation guards.

type HTMLDLKvSpec

type HTMLDLKvSpec struct {
	CSS           string `json:"css,omitempty"` // defaults to "dl"
	NormalizeKeys *bool  `json:"normalizeKeys,omitempty"`
}

HTMLDLKvSpec parses `<dl>/<dt>/<dd>` definition lists into a key-value map (`maxRows <= 500`).

type HTMLFieldReadSpec

type HTMLFieldReadSpec struct {
	CSSText     []string        `json:"cssText,omitempty"` // "" or ":scope" reads the matched element itself
	CSSAttr     *CSSAttrSpec    `json:"cssAttr,omitempty"` // Selector "" or ":scope" reads attr on matched element itself
	CSSAllText  *CSSAllTextSpec `json:"cssAllText,omitempty"`
	CSSHTMLToMd []string        `json:"cssHtmlToMd,omitempty"`
	StripTags   bool            `json:"stripTags,omitempty"`
}

HTMLFieldReadSpec reads a child field from a matched DOM node (or document root).

type HTMLSelectAllSpec

type HTMLSelectAllSpec struct {
	CSS      string                       `json:"css"`
	MaxItems int                          `json:"maxItems,omitempty"`
	Fields   map[string]HTMLFieldReadSpec `json:"fields"`
}

HTMLSelectAllSpec extracts up to `MaxSelectAllItems` (`500`) repeated elements as `[]map[string]any`.

type HTMLSourceSpec

type HTMLSourceSpec struct {
	JSONLdTypes         []string                     `json:"jsonLdTypes,omitempty"`
	EmbeddedBalancedKey string                       `json:"embeddedBalancedKey,omitempty"`
	SelectAll           map[string]HTMLSelectAllSpec `json:"selectAll,omitempty"`
	Tables              map[string]HTMLTableSpec     `json:"tables,omitempty"`
	DLKv                map[string]HTMLDLKvSpec      `json:"dlKv,omitempty"`
	CleanPreset         string                       `json:"cleanPreset,omitempty"` // "ietf_rfc", "jsr_io", "mediawiki"
}

HTMLSourceSpec configures Stage 1 bounded HTML DOM, table, `<dl>`, `<meta>`, and JSON-LD reading (`<= 2 MiB`).

type HTMLTableSpec

type HTMLTableSpec struct {
	CSS           string   `json:"css,omitempty"`  // selector for <table> (defaults to "table")
	Mode          string   `json:"mode,omitempty"` // "rows" (default: []map[string]any) | "kv" (map[string]any + ordered pairs)
	Headers       []string `json:"headers,omitempty"`
	HasHeader     *bool    `json:"hasHeader,omitempty"`
	MaxRows       int      `json:"maxRows,omitempty"`
	MaxCols       int      `json:"maxCols,omitempty"`
	NormalizeKeys bool     `json:"normalizeKeys,omitempty"`
}

HTMLTableSpec parses an HTML `<table>` linearly (`maxRows <= 500`, `maxCols <= 32`) with zero regexes.

type HTMLToMarkdownFunc

type HTMLToMarkdownFunc func(htmlFragment, baseURL string) (markdown string, links []string)

HTMLToMarkdownFunc converts an HTML fragment into GFM Markdown and extracted href URLs.

type HydrationSourceSpec

type HydrationSourceSpec struct {
	ScriptID        string   `json:"scriptId,omitempty"`
	AssignPrefixes  []string `json:"assignPrefixes,omitempty"` // e.g. ["window.__INITIAL_STATE__", "__PRELOADED_STATE__"]
	BalancedKey     string   `json:"balancedKey,omitempty"`    // e.g. `"protocolSection"`
	MaxBytes        int      `json:"maxBytes,omitempty"`
	MaxDepth        int      `json:"maxDepth,omitempty"`
	RootPath        string   `json:"rootPath,omitempty"`
	WrapRootArrayAs string   `json:"wrapRootArrayAs,omitempty"`
}

HydrationSourceSpec extracts `#__NEXT_DATA__`, script JSON, or brace-balanced JS state assignments (`<= 512 KiB`, depth `<= 24`).

type Input

type Input struct {
	// Body is the raw response payload (JSON, HTML, XML, CSV/TSV, or plain text).
	Body string
	// URL is the canonical request / page URL.
	URL string
	// Params holds validated URL/query parameters captured by route matching (plus host, etc.).
	Params map[string]string
	// CurrentMarkdown optionally supplies pre-computed generic HTML-to-Markdown output (or GetCurrentMarkdown lazily).
	CurrentMarkdown string
	// GetCurrentMarkdown lazily computes CurrentMarkdown only if a preset or delta block requests it.
	GetCurrentMarkdown func() string
}

Input provides the fetched payload, URL context, and route parameters to Execute.

type JSONSourceSpec

type JSONSourceSpec struct {
	// EmbeddedFrom extracts JSON from an HTML wrapper before decoding: "" (raw JSON), "inertia_data_page", "script_id", or "data_attr".
	EmbeddedFrom            string              `json:"embeddedFrom,omitempty"`
	ScriptID                string              `json:"scriptId,omitempty"`
	DataAttr                string              `json:"dataAttr,omitempty"`
	WrapRootArrayAs         string              `json:"wrapRootArrayAs,omitempty"`
	UnwrapFirstArrayElement bool                `json:"unwrapFirstArrayElement,omitempty"`
	RootPath                string              `json:"rootPath,omitempty"`
	FindInArray             *FindInArraySpec    `json:"findInArray,omitempty"`
	ParallelArrays          *ParallelArraysSpec `json:"parallelArrays,omitempty"`
	IntoField               string              `json:"intoField,omitempty"` // target field for top-level ParallelArrays
}

JSONSourceSpec configures Stage 1 bounded JSON reading (`<= 4 MiB`).

type KVTableSpec

type KVTableSpec struct {
	Heading     string            `json:"heading,omitempty"`
	Path        string            `json:"path,omitempty"` // dot-path to map[string]any ("" means root object)
	KeyHeader   string            `json:"keyHeader,omitempty"`
	ValueHeader string            `json:"valueHeader,omitempty"`
	AllowKeys   []string          `json:"allowKeys,omitempty"`   // explicit ordered allowlist of keys
	Labels      map[string]string `json:"labels,omitempty"`      // key -> display label
	IncludeRest bool              `json:"includeRest,omitempty"` // append remaining non-empty scalar keys after AllowKeys
	BoldKeys    bool              `json:"boldKeys,omitempty"`
	WhenVar     string            `json:"whenVar,omitempty"`
}

KVTableSpec renders an object or `<dl>`/`<table>` KV map as a 2-column GFM table (`#14`).

type NestedSubValuesSpec

type NestedSubValuesSpec struct {
	ArrayPath     string   `json:"arrayPath"`
	SubArrayField string   `json:"subArrayField"`
	ValueField    string   `json:"valueField"`
	ExcludeValues []string `json:"excludeValues,omitempty"`
	Limit         int      `json:"limit,omitempty"`
	Join          string   `json:"join,omitempty"`
}

NestedSubValuesSpec collects unique values across nested sub-arrays.

type NumberFormatSpec

type NumberFormatSpec struct {
	Decimals     *int    `json:"decimals,omitempty"`
	ThousandsSep string  `json:"thousandsSep,omitempty"` // e.g. ","
	Scale        float64 `json:"scale,omitempty"`        // multiplier (0 means 1.0)
	Prefix       string  `json:"prefix,omitempty"`
	Suffix       string  `json:"suffix,omitempty"`
	Compact      bool    `json:"compact,omitempty"`   // K / M / B suffix
	OnInvalid    string  `json:"onInvalid,omitempty"` // "keep" | "empty"
}

NumberFormatSpec configures deterministic numeric formatting (`#11`).

type ObjectEntriesSpec

type ObjectEntriesSpec struct {
	Paths    []string `json:"paths"`
	KeyField string   `json:"keyField,omitempty"` // defaults to "key"
}

ObjectEntriesSpec iterates sorted keys of the first non-empty object map at `Paths` (`<= MaxCollectionItems`), cloning each `map[string]any` entry with `KeyField` set to its map key.

type PaginationSpec

type PaginationSpec struct {
	TotalPath           string `json:"totalPath,omitempty"`
	TotalFromCollection bool   `json:"totalFromCollection,omitempty"`
	DefaultTotal        *int   `json:"defaultTotal,omitempty"`
	OmitFalseTruncated  bool   `json:"omitFalseTruncated,omitempty"`
	NextCursorPath      string `json:"nextCursorPath,omitempty"`
	CursorMode          string `json:"cursorMode,omitempty"` // "" | "id" | "offset" | "path"
	IDField             string `json:"idField,omitempty"`
}

PaginationSpec populates Document.Total, Returned, Truncated, and NextCursor.

type ParallelArraysSpec

type ParallelArraysSpec struct {
	BasePath            string                   `json:"basePath,omitempty"`
	Fields              map[string]string        `json:"fields"`
	MaxItems            int                      `json:"maxItems,omitempty"`
	PriorityFilterAfter *PriorityFilterAfterSpec `json:"priorityFilterAfter,omitempty"`
}

ParallelArraysSpec zips parallel column arrays into `[]map[string]any` row objects (`maxItems <= 2000`).

type PathEq

type PathEq struct {
	Path  string `json:"path"`
	Value string `json:"value"`
}

PathEq pairs a path or key with an expected string value.

type PreferWhereSpec

type PreferWhereSpec struct {
	Path           string `json:"path"`
	Equals         string `json:"equals"`
	FallbackEquals string `json:"fallbackEquals,omitempty"`
	FallbackLast   bool   `json:"fallbackLast,omitempty"`
}

PreferWhereSpec narrows an array value to the preferred matching element.

type PriorityFilterAfterSpec

type PriorityFilterAfterSpec struct {
	Index       int      `json:"index"`
	Field       string   `json:"field"`
	AllowValues []string `json:"allowValues"`
}

PriorityFilterAfterSpec restricts zipped rows beyond Index to an allowed set of Field values.

type RegexExtractSpec

type RegexExtractSpec struct {
	Source    string `json:"source,omitempty"` // "" (clean HTML <= 200KB) | "doc_text_and_img_alts"
	Pattern   string `json:"pattern"`
	Group     int    `json:"group,omitempty"`
	Transform string `json:"transform,omitempty"` // "" | "upper" | "lower"
}

RegexExtractSpec runs a bounded RE2 linear regex capture on HTML or clean text.

type SanitizerHooks

type SanitizerHooks struct {
	// SanitizeMeta cleans single-line metadata fields (Title, Description, Author, PublishedTime).
	SanitizeMeta func(s string) string
	// SanitizeMarkdown cleans emitted Markdown outside fenced code blocks.
	SanitizeMarkdown func(md string) string
	// IsSafePublicHTTPSURL validates candidate URLs for `Links[]` and public feed URL checks.
	IsSafePublicHTTPSURL func(rawURL string) bool
}

SanitizerHooks allows `package extract` to wire its canonical metadata, Markdown, and public-HTTPS URL validators while `internal/extract/dsl` ALWAYS runs its own fail-closed standalone sanitizer guarantees.

type SectionSpec

type SectionSpec struct {
	Heading         string `json:"heading,omitempty"`
	HeadingTemplate string `json:"headingTemplate,omitempty"`
	WhenVar         string `json:"whenVar,omitempty"`
	UnlessVar       string `json:"unlessVar,omitempty"`

	// Prose section:
	TextVar string `json:"textVar,omitempty"`

	// Tree comments section:
	TreeComments *TreeCommentsSpec `json:"treeComments,omitempty"`

	// KV table section:
	KVTable *KVTableSpec `json:"kvTable,omitempty"`

	// Collection source & inline Stage 2 operators:
	ArrayPath            string              `json:"arrayPath,omitempty"`
	SingleObjectPath     string              `json:"singleObjectPath,omitempty"`
	ObjectEntries        *ObjectEntriesSpec  `json:"objectEntries,omitempty"`
	ParallelArrays       *ParallelArraysSpec `json:"parallelArrays,omitempty"`
	ListArrayPath        string              `json:"listArrayPath,omitempty"`
	SubsectionsArrayPath string              `json:"subsectionsArrayPath,omitempty"`
	Filter               *FilterSpec         `json:"filter,omitempty"`
	DedupeBy             *DedupeSpec         `json:"dedupeBy,omitempty"`
	Sort                 []SortKeySpec       `json:"sort,omitempty"`
	GroupBy              *GroupBySpec        `json:"groupBy,omitempty"`
	MinItems             int                 `json:"minItems,omitempty"`
	Limit                int                 `json:"limit,omitempty"`
	EmptyText            string              `json:"emptyText,omitempty"`
	FailIfEmptyRows      bool                `json:"failIfEmptyRows,omitempty"` // v1 XML items_table parity when rows == 0

	// Row variables & output formats:
	ItemVars              map[string]VarSpec `json:"itemVars,omitempty"`
	RequireItemVar        string             `json:"requireItemVar,omitempty"`
	Columns               []TableColumnSpec  `json:"columns,omitempty"`
	ItemTemplate          string             `json:"itemTemplate,omitempty"`
	ItemBlockTemplate     string             `json:"itemBlockTemplate,omitempty"`
	IndentField           string             `json:"indentField,omitempty"`
	IndentOffset          int                `json:"indentOffset,omitempty"`
	MaxIndent             int                `json:"maxIndent,omitempty"`
	CollectLinkVars       []string           `json:"collectLinkVars,omitempty"`
	RecordFields          map[string]string  `json:"recordFields,omitempty"`
	KeepEmptyRecordFields bool               `json:"keepEmptyRecordFields,omitempty"`

	// Subsections rendering:
	SubsectionHeadingTemplate    string   `json:"subsectionHeadingTemplate,omitempty"`
	SubsectionAltHeadingTemplate string   `json:"subsectionAltHeadingTemplate,omitempty"`
	SubsectionAltWhenVar         string   `json:"subsectionAltWhenVar,omitempty"`
	SubsectionBodyVar            string   `json:"subsectionBodyVar,omitempty"`
	SubsectionSubkeys            []string `json:"subsectionSubkeys,omitempty"`
}

SectionSpec renders a `## <Heading>` prose, GFM table, grouped `###` sub-sections, subsection array, or bullet list.

type ShapePredicate

type ShapePredicate struct {
	HasPath             string   `json:"hasPath,omitempty"`
	HasAnyPath          []string `json:"hasAnyPath,omitempty"`
	NonEmptyObjectPaths []string `json:"nonEmptyObjectPaths,omitempty"`
	PathEquals          *PathEq  `json:"pathEquals,omitempty"`
	IsArray             string   `json:"isArray,omitempty"`        // "" checks root, non-empty checks dot-path
	CheckRootArray      bool     `json:"checkRootArray,omitempty"` // true when IsArray == "" should test root array
	NonEmptyArray       string   `json:"nonEmptyArray,omitempty"`
	JSONLdType          string   `json:"jsonLdType,omitempty"`
	CSSExists           string   `json:"cssExists,omitempty"`
	ProbeContains       []string `json:"probeContains,omitempty"` // case-insensitive match within 64 KiB prefix
	URLPathPrefix       string   `json:"urlPathPrefix,omitempty"`
	URLContains         string   `json:"urlContains,omitempty"`
	ParamEquals         *PathEq  `json:"paramEquals,omitempty"`
}

ShapePredicate tests payload or URL shape in O(1) / linear bounded time (`multi-shape-dispatch`).

type SortKeySpec

type SortKeySpec struct {
	Field string `json:"field"`
	Dir   string `json:"dir,omitempty"`  // "asc" (default) | "desc"
	Type  string `json:"type,omitempty"` // "str" (default) | "num" | "date" | "bool"
}

SortKeySpec defines a deterministic sort key (`#19`).

type SourceSpec

type SourceSpec struct {
	// Kind is one of: "json", "html", "hydration", "xml", "delimited", "text".
	Kind string `json:"kind"`

	JSON      *JSONSourceSpec      `json:"json,omitempty"`
	HTML      *HTMLSourceSpec      `json:"html,omitempty"`
	Hydration *HydrationSourceSpec `json:"hydration,omitempty"`
	XML       *XMLFeedSpec         `json:"xml,omitempty"`
	Delimited *DelimitedSpec       `json:"delimited,omitempty"`
	Text      *TextSourceSpec      `json:"text,omitempty"`
}

SourceSpec configures Stage 1 bounded source reading.

type Spec

type Spec struct {
	DSL int `json:"dsl,omitempty"`

	// Guard runs prefilter probes and negative HTML/JSON shell checks before or right after Stage 1 parsing.
	Guard *GuardSpec `json:"guard,omitempty"`

	// Variants evaluates up to 8 ordered shape predicates (`multi-shape-dispatch`) and dispatches to the first matching branch.
	Variants []VariantSpec `json:"variants,omitempty"`

	// Source selects and configures the Stage 1 bounded reader.
	Source SourceSpec `json:"source"`

	// Collections defines optional named Stage 2 collection pipelines producing `[]map[string]any` (or scalar `count`/`sum`)
	// into the root data map for Stage 2 vars and Stage 3 sections.
	Collections map[string]CollectionPipelineSpec `json:"collections,omitempty"`

	// Vars defines named Stage 2 scalar/value variables evaluated lazily with cycle protection.
	Vars map[string]VarSpec `json:"vars,omitempty"`

	// Emit configures the Stage 3 Markdown, Record, Link, and Pagination emitter.
	Emit EmitSpec `json:"emit"`

	// Fallback defines an optional fallback Spec if `FindInArray` or primary guards do not match.
	Fallback *Spec `json:"fallback,omitempty"`
}

Spec defines a complete `dsl: 2` extraction specification across Stages 1, 2, and 3.

type StepSpec

type StepSpec struct {
	// Op is one of:
	//   "parseJson", "path", "resolveUrl",
	//   "split", "join", "replaceLiteral", "trimPrefix", "trimSuffix", "stripFrontmatter",
	//   "truncate", "case", "slugToTitle", "trim", "stripTags", "stripLeadingH1", "demoteH1", "htmlToMd",
	//   "coalesce", "lookup", "when", "boolMap",
	//   "formatDate", "formatCurrency", "formatNumber", "formatBytes", "formatDuration", "formatUnit",
	//   "count", "sum"
	Op string `json:"op"`

	// Path / parseJson options:
	Path     string `json:"path,omitempty"`
	MaxBytes int    `json:"maxBytes,omitempty"`
	MaxDepth int    `json:"maxDepth,omitempty"`

	// Text op options (zero-regex):
	Sep        string `json:"sep,omitempty"`
	Index      *int   `json:"index,omitempty"` // optional part index after split (supports negative from end)
	Limit      int    `json:"limit,omitempty"`
	From       string `json:"from,omitempty"`
	To         string `json:"to,omitempty"`
	Prefix     string `json:"prefix,omitempty"`
	Suffix     string `json:"suffix,omitempty"`
	IgnoreCase bool   `json:"ignoreCase,omitempty"`
	MaxChars   int    `json:"maxChars,omitempty"`
	Ellipsis   string `json:"ellipsis,omitempty"`
	CaseMode   string `json:"case,omitempty"` // "lower" | "upper" | "title"

	// Coalesce / Lookup / BoolMap / When options:
	Values     []string          `json:"values,omitempty"` // literal or `{var}` templates for coalesce / `in`
	Map        map[string]string `json:"map,omitempty"`    // <= 256 entries for lookup
	Default    string            `json:"default,omitempty"`
	TrueValue  string            `json:"trueValue,omitempty"`
	FalseValue string            `json:"falseValue,omitempty"`
	When       *ConditionSpec    `json:"when,omitempty"`
	Then       string            `json:"then,omitempty"`
	Else       string            `json:"else,omitempty"`

	// Typed formatter options:
	Date     *DateFormatSpec     `json:"date,omitempty"`
	Currency *CurrencyFormatSpec `json:"currency,omitempty"`
	Number   *NumberFormatSpec   `json:"number,omitempty"`
	Bytes    *BytesFormatSpec    `json:"bytes,omitempty"`
	Duration *DurationFormatSpec `json:"duration,omitempty"`
	Unit     *UnitFormatSpec     `json:"unit,omitempty"`
}

StepSpec represents one composable Stage 2 transformation step (`max 16` per pipeline).

type SubFieldsJoinSpec

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

SubFieldsJoinSpec joins subfields from objects inside an array.

type TableColumnSpec

type TableColumnSpec struct {
	Header          string   `json:"header"`
	Paths           []string `json:"paths,omitempty"`
	Template        string   `json:"template,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"`
	StripPrefix     string   `json:"stripPrefix,omitempty"`
	Code            bool     `json:"code,omitempty"`
	SliceMax        int      `json:"sliceMax,omitempty"`
	StrictHTTPSLink bool     `json:"strictHttpsLink,omitempty"` // v1 XML items_table `[{label}]({url})` parity
	EmptyValue      *string  `json:"emptyValue,omitempty"`
}

TableColumnSpec defines a GFM table column in Stage 3 Sections.

type TagFilterParamSpec

type TagFilterParamSpec struct {
	Param        string `json:"param"`
	SkipIfEquals string `json:"skipIfEquals,omitempty"`
	TagsField    string `json:"tagsField"`
}

TagFilterParamSpec narrows items when a query/path parameter is present and matches an entry in TagsField.

type TextSourceSpec

type TextSourceSpec struct {
	Mode              string `json:"mode,omitempty"` // "plain" (default) | "yaml_frontmatter_card" | "code_or_markdown_by_path"
	PathParam         string `json:"pathParam,omitempty"`
	RejectHTMLSoft404 *bool  `json:"rejectHtmlSoft404,omitempty"`
}

TextSourceSpec configures plain-text / frontmatter / code-by-path twins.

type TreeCommentsSpec

type TreeCommentsSpec struct {
	ChildrenPath string `json:"childrenPath"`
	AuthorPath   string `json:"authorPath"`
	HTMLTextPath string `json:"htmlTextPath"`
	MaxDepth     int    `json:"maxDepth,omitempty"`
	MaxItems     int    `json:"maxItems,omitempty"`
}

TreeCommentsSpec renders bounded nested comment trees.

type UnitFormatSpec

type UnitFormatSpec struct {
	Unit      string  `json:"unit,omitempty"`
	UnitPath  string  `json:"unitPath,omitempty"`
	UnitVar   string  `json:"unitVar,omitempty"`
	Decimals  *int    `json:"decimals,omitempty"`
	Scale     float64 `json:"scale,omitempty"`
	Thousands string  `json:"thousandsSep,omitempty"`
	Sep       *string `json:"sep,omitempty"` // defaults to " "
	OnInvalid string  `json:"onInvalid,omitempty"`
}

UnitFormatSpec formats a numeric scalar with a physical/measurement unit (`#16`).

type VarSpec

type VarSpec struct {
	// Value selectors (work across JSON, Hydration, XML, CSV, and HTML Embedded/JSON-LD):
	Paths                  []string             `json:"paths,omitempty"`
	CoalesceVars           []string             `json:"coalesceVars,omitempty"`
	Literal                string               `json:"literal,omitempty"`
	QueryParams            []string             `json:"queryParams,omitempty"`
	URLPathSegment         *int                 `json:"urlPathSegment,omitempty"`
	FirstMatchingObjectKey []string             `json:"firstMatchingObjectKey,omitempty"`
	DynamicKeyPath         *DynamicKeyPathSpec  `json:"dynamicKeyPath,omitempty"`
	NestedSubValues        *NestedSubValuesSpec `json:"nestedSubValues,omitempty"`
	TocHeading             string               `json:"tocHeading,omitempty"`
	FindInArrayLang        *FindLangSpec        `json:"findInArrayLang,omitempty"`
	PreferWhere            *PreferWhereSpec     `json:"preferWhere,omitempty"`
	FirstNonMatchingKey    string               `json:"firstNonMatchingKey,omitempty"`

	// HTML DOM / Meta / JSON-LD selectors (when Source.Kind == "html"):
	EmbeddedPaths    []string          `json:"embeddedPaths,omitempty"`
	JSONLdPaths      []string          `json:"jsonLdPaths,omitempty"`
	AllMetaKey       string            `json:"allMetaKey,omitempty"`
	MetaKeys         []string          `json:"metaKeys,omitempty"`
	StripRegexSuffix string            `json:"stripRegexSuffix,omitempty"`
	CSSText          []string          `json:"cssText,omitempty"`
	CSSAttr          *CSSAttrSpec      `json:"cssAttr,omitempty"`
	CSSAllText       *CSSAllTextSpec   `json:"cssAllText,omitempty"`
	CSSHTMLToMd      []string          `json:"cssHtmlToMd,omitempty"`
	RegexExtract     *RegexExtractSpec `json:"regexExtract,omitempty"`

	// Template / Conditional composition:
	Template         string   `json:"template,omitempty"`
	SafeMarkdownTpl  bool     `json:"safeMarkdownTpl,omitempty"` // force safe Markdown template escaping
	WhenVars         []string `json:"whenVars,omitempty"`
	WhenAnyVars      []string `json:"whenAnyVars,omitempty"`
	FallbackVar      string   `json:"fallbackVar,omitempty"`
	FallbackTemplate string   `json:"fallbackTemplate,omitempty"`
	Default          string   `json:"default,omitempty"`

	// Array projection & scalar extraction options:
	SubField         string             `json:"subField,omitempty"`
	SubFieldsJoin    *SubFieldsJoinSpec `json:"subFieldsJoin,omitempty"`
	ItemWrap         string             `json:"itemWrap,omitempty"`
	Join             string             `json:"join,omitempty"`
	Limit            int                `json:"limit,omitempty"`
	DefaultArrayJoin string             `json:"defaultArrayJoin,omitempty"` // e.g. ", " for HTML DOM arrays
	DomObjectScalar  bool               `json:"domObjectScalar,omitempty"`  // extract m["name"] / m["value"] on object elements

	// Path-level match filters:
	ExcludeEquals string `json:"excludeEquals,omitempty"`
	EqualsVar     string `json:"equalsVar,omitempty"`

	// Format & boolean mapping shortcuts (100% compatible with v1 + v2):
	Format            string `json:"format,omitempty"`
	CurrencyVar       string `json:"currencyVar,omitempty"`
	TrueValue         string `json:"trueValue,omitempty"`
	FalseValue        string `json:"falseValue,omitempty"`
	StripFrontmatter  bool   `json:"stripFrontmatter,omitempty"`
	StripPrefix       string `json:"stripPrefix,omitempty"`
	StripSuffix       string `json:"stripSuffix,omitempty"`
	StripIgnoreCase   bool   `json:"stripIgnoreCase,omitempty"`
	ReplaceFrom       string `json:"replaceFrom,omitempty"`
	ReplaceTo         string `json:"replaceTo,omitempty"`
	HasReplace        bool   `json:"hasReplace,omitempty"`
	Trim              bool   `json:"trim,omitempty"`
	Upper             bool   `json:"upper,omitempty"`
	Lower             bool   `json:"lower,omitempty"`
	RequireHTTPS      bool   `json:"requireHttps,omitempty"`
	RequireHTTPPrefix bool   `json:"requireHttpPrefix,omitempty"`
	MinLen            int    `json:"minLen,omitempty"`
	SliceMax          int    `json:"sliceMax,omitempty"` // UTF-16 code unit safe truncation (v1 parity)

	// Chained Stage 2 pipeline steps (`<= 16` steps, `<= 64 KiB` scalar cap):
	Steps []StepSpec `json:"steps,omitempty"`

	// Marks variable output as pre-composed Markdown (e.g. html_to_md, cssHtmlToMd, inline code wrap).
	MarkdownFormatted bool `json:"markdownFormatted,omitempty"`
}

VarSpec extracts and transforms a Stage 2 variable across ANY Stage 1 source.

type VariantSpec

type VariantSpec struct {
	When ShapePredicate `json:"when"`
	Spec Spec           `json:"extract"`
}

VariantSpec pairs a ShapePredicate with the Spec branch to run when it matches.

type XMLFeedSpec

type XMLFeedSpec struct {
	Mode                      string                  `json:"mode,omitempty"` // "items" (default) | "items_table" | "jats_article"
	RequireAnyTags            []string                `json:"requireAnyTags,omitempty"`
	ItemTags                  []string                `json:"itemTags,omitempty"` // e.g. ["item", "entry"]
	MaxItems                  int                     `json:"maxItems,omitempty"`
	Namespaces                map[string]string       `json:"namespaces,omitempty"`
	ChannelTitleFallbackParam string                  `json:"channelTitleFallbackParam,omitempty"`
	FirstItemVars             map[string][]string     `json:"firstItemVars,omitempty"`
	Fields                    map[string]XMLFieldSpec `json:"fields,omitempty"`
	IntoField                 string                  `json:"intoField,omitempty"` // defaults to "items"
}

XMLFeedSpec configures namespaced XML / RSS / Atom / JATS extraction (`maxItems <= 1000`).

type XMLFieldSpec

type XMLFieldSpec struct {
	Tags           []string `json:"tags"` // e.g. ["dc:creator", "author>name", "atom:link[rel=alternate]@href", "link@href", "link"]
	All            bool     `json:"all,omitempty"`
	Join           string   `json:"join,omitempty"`
	SplitColonPart *int     `json:"splitColonPart,omitempty"`
	SliceMax       int      `json:"sliceMax,omitempty"`
	StripTags      *bool    `json:"stripTags,omitempty"`
	Default        string   `json:"default,omitempty"`
}

XMLFieldSpec extracts tag text or attribute values (including `ns:tag` and `ns:tag@attr` or `tag[rel=alternate]@href`).

Jump to

Keyboard shortcuts

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