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:
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`).
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).
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
- func ApplyDedupeBy(items []map[string]any, dd *DedupeSpec) []map[string]any
- func ApplyFilter(items []map[string]any, flt *FilterSpec, params map[string]string, ...) []map[string]any
- func ApplySort(items []map[string]any, keys []SortKeySpec) []map[string]any
- func CheckNegativeHTMLShell(rawHTML, rawURL string, genericTitles, extraNotFound, pathExemptions []string) bool
- func CheckNegativeJSONError(rootObj map[string]any) bool
- func CheckRequireAnyProbe(rawBody string, needles []string) bool
- func CollectionDependencies(name string, cols map[string]CollectionPipelineSpec) []string
- func CompareParsedVersions(a, b ParsedVersion) int
- func CompareVersions(a, b string) int
- func EachConflictKeys() []string
- func EachPageScopedKeys() []string
- func EachRawStepOps() []string
- func EachValueFormats() []string
- func EvalCondition(cond ConditionSpec, currentVal any, activeObj map[string]any, ...) bool
- func EvalCount(raw any) int
- func EvalLookup(rawKey string, table map[string]string, fallback string, ignoreCase bool) string
- func EvalSum(raw any, fieldPath string) (float64, bool)
- func FirstNonEmptyPathValue(v any) any
- func FormatBytesValue(raw any, spec *BytesFormatSpec) string
- func FormatCase(s, mode string) string
- func FormatCurrencyValue(raw any, spec *CurrencyFormatSpec, activeObj map[string]any, ...) string
- func FormatDateValue(raw any, spec *DateFormatSpec) string
- func FormatDurationValue(raw any, spec *DurationFormatSpec) string
- func FormatNumberValue(raw any, spec *NumberFormatSpec) string
- func FormatUnitValue(raw any, spec *UnitFormatSpec, activeObj map[string]any, ...) string
- func GetByDotPath(root any, dotPath string) any
- func IsNeverGuard(g *GuardSpec) bool
- func IsPrereleaseVersion(s string) bool
- func IsTruthy(v any) bool
- func ParseEmbeddedJSON(raw string, maxBytes, maxDepth int) any
- func ParseNormalizedDate(raw any, inputLayouts []string, epochUnit string) (time.Time, bool)
- func PathHasFanOut(p string) bool
- func ReplaceLiteralBounded(s, from, to string) string
- func ResolveSpecDefaultsJSON(b []byte) ([]byte, error)
- func ScalarToString(v any) string
- func SelectPreferWhere(arr []any, pw *PreferWhereSpec) any
- func SlugToTitle(s string) string
- func SplitLinear(s, sep string, limit int) []any
- func TrimPrefixOp(s, prefix string, ignoreCase bool) string
- func TrimSuffixOp(s, suffix string, ignoreCase bool) string
- func TruncateRunesUTF8(s string, maxChars int, ellipsis string) string
- func ValidCheckDigitScheme(s string) bool
- func ValidConditionOp(op string) bool
- func ValidRecordType(t string) bool
- func ValidSortType(t string) bool
- func ValidateCollections(cols map[string]CollectionPipelineSpec) string
- func ValidateConditionTree(c ConditionSpec, allowVars bool) error
- func ValidateEachSpec(v VarSpec, depth int) string
- func ValidateHTMLFragments(frags []HTMLFragmentSpec) string
- func ValidateLineReaderSource(src SourceSpec) string
- func ValidateNeverGuard(spec Spec) string
- func ValidatePagination(pg *PaginationSpec) string
- func ValidatePathExpr(p string) error
- func ValidateScalarStep(st StepSpec) error
- func ValidateSectionAutoColumns(sec SectionSpec) string
- func ValidateSectionEmptyRecord(sec SectionSpec) string
- func ValidateSectionRecordLimit(sec SectionSpec) string
- func ValidateSortKeys(keys []SortKeySpec) string
- func ValidateXMLTree(xs *XMLFeedSpec) string
- func ValueToFloat(v any) (float64, bool)
- type AppendCurrentMdDeltaSpec
- type ArrayFieldGate
- type AutoColumnsExclude
- type AutoColumnsKeySource
- type AutoColumnsRecordsSpec
- type AutoColumnsSpec
- type BulletSpec
- type BytesFormatSpec
- type CSSAllTextSpec
- type CSSAttrSpec
- type CodeByPathSpec
- type CollectionPipelineSpec
- type ConditionSpec
- type CurrencyFormatSpec
- type DateFormatSpec
- type DedupeSpec
- type DefaultsSpec
- type DelimitedSpec
- type Document
- type DurationFormatSpec
- type DynamicKeyPathSpec
- type EachDedupe
- type EmitSpec
- type ExecuteOptions
- type FieldPrefixFilterSpec
- type FieldSuffixesFilterSpec
- type FilterSpec
- type FindInArraySpec
- type FindLangSpec
- type GroupBySpec
- type GroupedItems
- type GuardSpec
- type HTMLDLKvSpec
- type HTMLFieldReadSpec
- type HTMLFragmentSpec
- type HTMLSelectAllSpec
- type HTMLSourceSpec
- type HTMLTableSpec
- type HTMLToMarkdownFunc
- type HydrationSourceSpec
- type Input
- type JSONSourceSpec
- type KVTableSpec
- type LineBlockSpec
- type LinePrefixField
- type LineReaderSpec
- type NestedSubValuesSpec
- type NumberFormatSpec
- type ObjectEntriesSpec
- type PaginationSpec
- type ParallelArraysSpec
- type ParsedVersion
- type PathEq
- type PreferWhereSpec
- type PriorityFilterAfterSpec
- type RecordTypeSpec
- type RegexExtractSpec
- type SanitizerHooks
- type SectionSpec
- type ShapePredicate
- type SortKeySpec
- type SourceSpec
- type Spec
- type StepSpec
- type SubFieldsJoinSpec
- type TableColumnSpec
- type TagFilterParamSpec
- type TextSourceSpec
- type TreeCommentsSpec
- type UnitFormatSpec
- type UnnestSpec
- type VarSpec
- type VariantSpec
- type XMLFeedSpec
- type XMLFieldSpec
- type XMLTreeSelectSpec
- type XMLTreeSpec
Constants ¶
const ( // MaxAutoColumns caps `maxCols` (and the column count of any autoColumns table). MaxAutoColumns = 32 // DefaultAutoColumns is the column cap when `maxCols` is unset. DefaultAutoColumns = 8 // MaxAutoColumnsFirstN caps the rows scanned by `from: unionKeysFirstN`. MaxAutoColumnsFirstN = 50 // DefaultAutoColumnsFirstN is the scan depth of `unionKeysFirstN` when `firstN` is unset. DefaultAutoColumnsFirstN = 5 // MaxAutoColumnsListEntries caps `pinFirst`, `exclude.prefixes` and `exclude.keys`. MaxAutoColumnsListEntries = 16 // MaxAutoColumnsChars caps `headerMaxChars`, `cellMaxChars` and `records.maxChars`. MaxAutoColumnsChars = 1000 // MaxAutoColumnsRecordFields caps `records.maxFields`. MaxAutoColumnsRecordFields = 32 // MaxAutoColumnsRowKeys caps the keys read from one row (key collection stays bounded on wide rows). MaxAutoColumnsRowKeys = 512 )
PRIMITIVES-RFC P7 `autoColumns` bounds. The hub compiler mirrors them in DSL_V2_AUTO_COLUMNS_LIMITS (hub/scripts/adapter-schema-and-docs.mjs); hub/test/adapter-dsl-auto-columns.test.ts keeps the two in sync.
const ( AutoColumnsFromFirstRowKeys = "firstRowKeys" AutoColumnsFromUnionKeysFirstN = "unionKeysFirstN" AutoColumnsFromLabels = "labels" )
Key sources of `autoColumns.from`.
const ( MaxConditionDepth = 3 // nesting levels of all/any groups below the root condition MaxConditionLeaves = 16 // comparison leaves per condition tree MaxConditionRegexBytes = 512 // `matches` pattern length MaxConditionMatchInput = 64 << 10 // `matches` subject bytes considered )
PRIMITIVES-RFC P3 bounds for structured conditions.
const ( // MaxEachDepth is the deepest `each` nesting allowed (an `each` inside an `each`). MaxEachDepth = 2 // MaxEachEvaluations caps element evaluations per top-level var, across all nesting levels. MaxEachEvaluations = 4000 // MaxEachItems caps the joined results of one `each` (the existing array join cap). MaxEachItems = 500 // EachScalarKey is the element-scope name a scalar (non-object) element is exposed under. EachScalarKey = "_value" )
P4 per-element mapping (`VarSpec.Each`) bounds.
const ( // MaxHTMLFragments caps the entries in `source.json.htmlFragments`. MaxHTMLFragments = 4 // DefaultHTMLFragmentBytes is the fragment prefix parsed when `maxBytes` is unset (512 KiB). DefaultHTMLFragmentBytes = 512 << 10 // MaxHTMLFragmentBytes caps `maxBytes`, and also the bytes parsed across all fragments of one spec. MaxHTMLFragmentBytes = MaxHTMLBytes // MaxHTMLFragmentOutputs caps the named outputs (`selectAll` + `tables` + `dlKv`) of one fragment. MaxHTMLFragmentOutputs = 16 // MaxHTMLFragmentNameLen caps an output name. MaxHTMLFragmentNameLen = 64 // MaxHTMLFragmentPathLen caps `path`. MaxHTMLFragmentPathLen = 256 )
HTML selection over a JSON string field (`source.json.htmlFragments`).
Some JSON APIs return their real content as an HTML fragment inside a string field (review widgets such as `{"html": "<div class='jdgm-rev'>..."}`). A fragment entry parses that string with the same bounded DOM the HTML source uses (parseHTMLDoc: NUL/zero-entity strip, node, depth and visit budgets) and runs the same `selectAll`, `tables` and `dlKv` readers on it. Each result is written into the root object under its own name, so the rest of the spec treats it like any JSON field. Every value still leaves only through the Stage 3 emitter and its sanitizer.
const ( // MaxTextLines caps the physical lines a `lines` / `keyValue` reader visits. MaxTextLines = 5000 // MaxTextLineRows caps the rows (lines or entries) kept for Stage 2 (= MaxCollectionItems). MaxTextLineRows = MaxCollectionItems // MaxTextLineBlocks caps the `keyValue` blocks kept. MaxTextLineBlocks = 1000 // MaxTextLineValuesPerKey caps the values kept per key in `fields` (the typed-array element cap). MaxTextLineValuesPerKey = 256 // MaxLineReaderListEntries caps prefix lists, header lists and `newBlockOnRepeat`. MaxLineReaderListEntries = 16 // MaxLineReaderPrefixBytes caps every prefix, block marker and separator. MaxLineReaderPrefixBytes = 64 // MaxLineReaderSkipBlocks caps `skipBlocks`. MaxLineReaderSkipBlocks = 8 // MaxLineReaderFields caps `set` and `sticky`. MaxLineReaderFields = 8 // MaxLineReaderAllowKeys caps `allowKeys`. MaxLineReaderAllowKeys = 64 // MaxLineReaderLineBytes caps `maxLineBytes`. MaxLineReaderLineBytes = 64 << 10 // MaxLineReaderRejectChars caps `rejectChars`. MaxLineReaderRejectChars = 32 // MaxDelimitedSkipRows caps `delimited.skipRows`. MaxDelimitedSkipRows = 16 // MaxDelimitedScanRows caps the records a delimited reader visits, kept or only counted. MaxDelimitedScanRows = 100000 )
P11 bounds.
const ( NeverGuardErrOtherKeys = "guard.never: excludes every other guard key" NeverGuardErrBranches = "guard.never: a spec that never emits cannot have variants or fallback" NeverGuardErrDefaults = "guard.never: not allowed in defaults (set it on the branch)" )
NeverGuardErrOtherKeys and NeverGuardErrBranches are the validation messages shared with the JS manifest compiler (hub/scripts/adapter-schema-and-docs.mjs) and the case table testdata/never_guard_validation_cases.json.
const ( MaxRegexPatternBytes = 512 MaxRegexInputBytes = 64 << 10 MaxRegexReplacements = 4096 // replace mode rewrites at most this many matches MaxRegexToBytes = 256 MaxMathArgs = 8 MaxMathDecimals = 6 MaxJoinNonEmptyValues = 16 MaxScalarArgBytes = 256 // per `args` / `values` template MaxScalarSepBytes = 16 )
PRIMITIVES-RFC P2 scalar step family: `regex`, `math`, `joinNonEmpty`, `urlEncode` / `urlDecode`.
All four are pure strings / strconv / net/url / RE2 (linear time, no backtracking). None loops over its own output, and the 16-step pipeline cap and the 64 KiB scalar output cap still apply.
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 = 2000 // Max data rows kept from CSV/TSV (= MaxCollectionItems, PRIMITIVES-RFC P11) 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 // P6 collection sources: MaxCollectionArrayPaths = 8 // Max candidate paths in `arrayPaths` MaxUnnestStages = 2 // Max `unnest` stages per collection MaxUnnestParentFields = 16 // Max `parentFields` per `unnest` stage MaxConcatSources = 8 // Max collections appended by `concat` MaxEmptyRecordFields = 32 // Max keys in a section's `emptyRecordFields` )
Hard resource ceilings enforced across all Stage 1 readers, Stage 2 operators, and Stage 3 emitters.
const ( // MaxPathFanOuts caps the number of `[*]` fan-outs in one path. MaxPathFanOuts = 2 // MaxPathFanOutResults caps the flattened result list of a fan-out path. MaxPathFanOutResults = MaxCollectionItems )
PRIMITIVES-RFC P5 path bounds.
const ( MaxVersionBytes = 256 // trimmed input; longer values do not parse MaxVersionSegments = 16 // numeric core segments MaxVersionSegmentBytes = 64 // digits per core segment MaxVersionTagParts = 16 // tag identifiers after the letter/digit split MaxSortKeys = 8 // keys in one `sort` list )
PRIMITIVES-RFC P9 bounds. hub/test/adapter-dsl-version-order.test.ts pins the hub copies.
const ( // DefaultXMLTreeBytes is the body size accepted when `maxBytes` is unset. DefaultXMLTreeBytes = 2 << 20 // MaxXMLTreeBytes caps `maxBytes`. MaxXMLTreeBytes = MaxJSONBytes // DefaultXMLTreeDepth / MaxXMLTreeDepth bound element nesting (the document element is depth 1). DefaultXMLTreeDepth = 24 MaxXMLTreeDepth = 32 // DefaultXMLTreeNodes / MaxXMLTreeNodes bound the elements read. DefaultXMLTreeNodes = 20000 MaxXMLTreeNodes = 50000 // DefaultXMLTreeAttrs / MaxXMLTreeAttrs bound the attributes kept per element. DefaultXMLTreeAttrs = 32 MaxXMLTreeAttrs = 64 // MaxXMLTreeNameLen caps element and attribute local names (bytes). MaxXMLTreeNameLen = 128 // MaxXMLTreeNames caps the entries of `alwaysArray`, `mixedText` and each `select.tags`. MaxXMLTreeNames = 64 // MaxXMLTreeNamespaces caps `namespaces`. MaxXMLTreeNamespaces = 16 // MaxXMLTreeSelects caps the `select` outputs. MaxXMLTreeSelects = 8 // DefaultXMLTreeSelectItems is a select's item cap when `maxItems` is unset; MaxXMLItems caps it. DefaultXMLTreeSelectItems = 500 // MaxXMLTreeSepLen caps a `mixedText` separator. MaxXMLTreeSepLen = 8 )
XML tree source (`source.xml.mode: tree`, PRIMITIVES-RFC P12).
The tree reader turns an XML document (RSS, Atom, OAI-PMH, sitemaps, SPL, DBLP, SOAP-style replies) into the same normalized values the JSON source produces (`map[string]any`, `[]any`, `string`), so every existing path, `each`, collection, condition and emitter feature applies unchanged. Mapping:
- The document element is written into the root object under its own key: `<rss>` -> `rss`.
- An element's key is its local name. When `namespaces` binds a prefix to the element's namespace URI the key is `prefix:local` (so `atom:link` and `link` stay apart); unbound namespaces use the local name. `foldCase` lower-cases every element and attribute key.
- A leaf element without attributes is a string: its character data, entity-decoded, untrimmed ("" if empty).
- An element with attributes or child elements is an object. Attributes are `@name` keys; xmlns declarations are dropped. Direct character data, when not whitespace-only, is `#text`. Child elements are keys.
- Repeated sibling keys become an array in document order; a single child stays a single value unless its key is listed in `alwaysArray`.
- Elements named in `mixedText` are flattened: all descendant character data, in document order, joined with the configured separator. Their child elements are not represented. With attributes they are an object whose `#text` holds the flattened text.
- `keyAttr` keys an element by one of its attributes instead of its name, for name/value vocabularies such as `<content name="title">` or Solr `<str name="id">`: with `keyAttr: {content: name}` that element is written as `title` and the `name` attribute is dropped. The value is trimmed (and folded under `foldCase`); a value that is not a valid element key (empty, with a dot, ...) keeps the element name and the attribute. `mixedText` and `select.tags` match the element name; `alwaysArray` matches the resulting key.
- `select` collects the outermost descendants whose key is in `tags`, in document order, as objects carrying `#tag` (a string leaf becomes `{"#tag": k, "#text": s}`). It flattens polymorphic records (DBLP `article` / `inproceedings`, SPL `section`) into one list that sections read with `arrayPath`.
Safety and bounds:
- encoding/xml with a nil Entity map: only the five predefined entities and character references decode. Undeclared references stay literal text (`&foo;`). DTDs are never read: a DOCTYPE, or any other `<!...>` declaration, rejects the whole document, so there is no external entity resolution (XXE) and no entity expansion (billion laughs).
- A non-UTF-8 encoding declaration stops the parse (no CharsetReader), like the legacy decoders.
- The body is rejected above `maxBytes`. Elements deeper than `maxDepth`, or whose name is longer than MaxXMLTreeNameLen, are skipped with their subtree; attributes past `maxAttrs` or with over-long names are dropped. Parsing stops after `maxNodes` elements. A syntax error also stops the parse: what was read before it is kept, with open elements closed, as the legacy token loops did.
- Conversion is iterative over a depth-bounded tree; select results are capped at `maxItems`.
const MaxCheckDigitChars = 18
PRIMITIVES-RFC P8: `checkDigit` validates a published identifier checksum. Spaces and hyphens are stripped; any other character that is not a digit (or the ISBN-10 / ISSN trailing `X`) rejects the value. A valid value is returned compact (digits, upper-case `X`); `normalize: gtin14` left-pads a valid GTIN to 14 digits. An invalid or over-long value yields "".
const MaxDefaultsExpandedBytes = 1 << 20
MaxDefaultsExpandedBytes caps the JSON size of one spec after its `defaults` block has been merged into its branches. Merging copies the shared block into up to MaxVariants branches, so the cap keeps a small spec from expanding into a very large one.
const MaxRecordArrayItems = 256
MaxRecordArrayItems caps the elements of a single `type: array` record value.
const MaxSectionRecordLimit = 500
MaxSectionRecordLimit bounds SectionSpec.RecordLimit (the emitter's section row cap).
const TableSeparatorCompact = "compact"
TableSeparatorCompact renders the header separator row as `|---|---|` instead of the default `| --- | --- |`.
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 ¶
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 ¶
CheckRequireAnyProbe runs a 64 KiB ASCII-lowercase substring prefilter in O(n) time.
func CollectionDependencies ¶ added in v2.8.46
func CollectionDependencies(name string, cols map[string]CollectionPipelineSpec) []string
CollectionDependencies lists the other collections that `name` reads: its `concat` entries plus any `arrayPath` / `arrayPaths` whose first segment names another collection. Sorted and de-duplicated.
func CompareParsedVersions ¶ added in v2.8.46
func CompareParsedVersions(a, b ParsedVersion) int
CompareParsedVersions orders two parsed versions (see the package comment above); both must be OK.
func CompareVersions ¶ added in v2.8.46
CompareVersions orders two strings by P9 precedence. Values that parse sort above values that do not; two values that do not parse compare equal.
func EachConflictKeys ¶ added in v2.8.46
func EachConflictKeys() []string
EachConflictKeys exposes eachConflictKeyNames for the compiler-agreement test.
func EachPageScopedKeys ¶ added in v2.8.46
func EachPageScopedKeys() []string
func EachRawStepOps ¶ added in v2.8.46
func EachRawStepOps() []string
func EachValueFormats ¶ added in v2.8.46
func EachValueFormats() []string
EachValueFormats, EachRawStepOps and EachPageScopedKeys expose the rule lists so the compiler-agreement test can compare them with the hub schema generator.
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)`), including `all` / `any` groups and `not` (PRIMITIVES-RFC P3).
func EvalLookup ¶
EvalLookup maps `rawKey` through a bounded lookup table (`<= MaxLookupEntries = 256` entries).
func EvalSum ¶
EvalSum sums numeric scalars (or `fieldPath` inside objects) across up to `MaxCollectionItems` (`2,000`) items.
func FirstNonEmptyPathValue ¶ added in v2.8.46
FirstNonEmptyPathValue returns v unchanged unless it is a fan-out list, in which case it returns the first element that is a non-blank scalar or a non-empty object/array (PRIMITIVES-RFC P5 `paths` rule).
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 ¶
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 ¶
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.
PRIMITIVES-RFC P5 extensions:
- `[-1]` / `.-1`: negative indices count from the end.
- `[*]`: fans out over every array element, resolves the rest of the path per element, and flattens one level (an element result that is itself an array contributes its elements). Nil results are dropped; the list is capped at MaxPathFanOutResults; an empty fan-out yields nil. At most MaxPathFanOuts fan-outs are honoured per path (deeper ones yield nil).
- `*` as a map segment: the value of the first key in sorted order (a literal `"*"` key wins).
func IsNeverGuard ¶ added in v2.8.46
IsNeverGuard reports whether g declares a route that never emits.
func IsPrereleaseVersion ¶ added in v2.8.46
IsPrereleaseVersion reports whether s parses as a P9 version with a pre-release tag. Values that do not parse are not pre-releases.
func ParseEmbeddedJSON ¶
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 ¶
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 PathHasFanOut ¶ added in v2.8.46
PathHasFanOut reports whether p contains a `[*]` fan-out (PRIMITIVES-RFC P5).
func ReplaceLiteralBounded ¶
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 ResolveSpecDefaultsJSON ¶ added in v2.8.46
ResolveSpecDefaultsJSON merges the top-level `defaults` block of a JSON spec into the spec's own body, each `variants[].extract` and the `fallback`, and returns the spec without `defaults`. A nested spec that declares its own `defaults` receives the parent's block merged under its own and resolves it when it is decoded.
func ScalarToString ¶
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 ¶
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 ¶
SplitLinear splits `s` by `sep` in O(n) with zero regular expressions, capped at `limit` parts (`<= 2000`).
func TrimPrefixOp ¶
TrimPrefixOp strips `prefix` (optionally case-insensitively) on UTF-8 rune boundaries.
func TrimSuffixOp ¶
TrimSuffixOp strips `suffix` (optionally case-insensitively) on UTF-8 rune boundaries.
func TruncateRunesUTF8 ¶
TruncateRunesUTF8 truncates `s` to at most `maxChars` UTF-8 runes, appending `ellipsis` when truncated.
func ValidCheckDigitScheme ¶ added in v2.8.46
ValidCheckDigitScheme reports whether s is a supported `checkDigit` scheme.
func ValidConditionOp ¶ added in v2.8.46
ValidConditionOp reports whether op is a supported leaf comparison.
func ValidRecordType ¶ added in v2.8.46
ValidRecordType reports whether t is a supported `recordTypes[*].type`.
func ValidSortType ¶ added in v2.8.46
ValidSortType reports whether t is a supported `sort[].type` ("" means str).
func ValidateCollections ¶ added in v2.8.46
func ValidateCollections(cols map[string]CollectionPipelineSpec) string
ValidateCollections checks the P6 bounds shared with the hub compiler (`validateCollectionsV2`) and returns "" when valid, else a message for the first problem found (collections in sorted order).
func ValidateConditionTree ¶ added in v2.8.46
func ValidateConditionTree(c ConditionSpec, allowVars bool) error
ValidateConditionTree enforces the P3 compile-time bounds. allowVars=false (guards, variants) rejects `var` / `valueVar`, which cannot resolve before Stage 2.
func ValidateEachSpec ¶ added in v2.8.46
ValidateEachSpec checks the compile-time rules for a var that uses `each` (or `dedupe`). depth is the number of enclosing `each` scopes (0 for a top-level var). It returns a short reason, or "" when the var is valid. Shared by the Go compiler check and the tests; the hub compiler (adapter-schema-and-docs.mjs) mirrors the same rules.
func ValidateHTMLFragments ¶ added in v2.8.46
func ValidateHTMLFragments(frags []HTMLFragmentSpec) string
ValidateHTMLFragments checks `source.json.htmlFragments` and returns "" or the first problem, as a message relative to the spec (e.g. `source.json.htmlFragments[0].path is required`). The hub compiler (validateJsonHtmlFragmentsV2) returns the same messages; both run testdata/html_fragments_validation_cases.json.
func ValidateLineReaderSource ¶ added in v2.8.46
func ValidateLineReaderSource(src SourceSpec) string
ValidateLineReaderSource checks the P11 options of `source.delimited` and `source.text`. It returns "" when they are valid or unused, else a message relative to the spec. The hub compiler (validateLineReaderSourceV2) returns the same messages from the shared case table testdata/line_readers_validation_cases.json.
func ValidateNeverGuard ¶ added in v2.8.46
ValidateNeverGuard checks the `guard.never` rules for one spec level (not its variants or fallback, which are validated as specs of their own). It returns "" when the spec has no `never` guard or obeys the rules.
func ValidatePagination ¶ added in v2.8.46
func ValidatePagination(pg *PaginationSpec) string
ValidatePagination checks the P11 `truncatedVar` bound and the P9 `totalOnly` option ("" when valid or unused). It mirrors validatePaginationV2 in hub/scripts/adapter-schema-and-docs.mjs.
func ValidatePathExpr ¶ added in v2.8.46
ValidatePathExpr checks the PRIMITIVES-RFC P5 bounds of one path expression: at most MaxPathFanOuts `[*]` fan-outs, and at most one `[*]` per segment chain (`[*][*]` is rejected). It mirrors validateDslV2PathExpr in hub/scripts/adapter-schema-and-docs.mjs.
func ValidateScalarStep ¶ added in v2.8.46
ValidateScalarStep checks the compile-time bounds of a P2 / P8 step. Other ops return nil. It is shared by the Go manifest validator; hub/scripts/adapter-schema-and-docs.mjs mirrors it.
func ValidateSectionAutoColumns ¶ added in v2.8.46
func ValidateSectionAutoColumns(sec SectionSpec) string
ValidateSectionAutoColumns checks a section's `autoColumns` (PRIMITIVES-RFC P7). It returns "" when the section has no autoColumns or they are valid, else a message relative to the section. The hub compiler (validateSectionAutoColumnsV2) returns the same messages from the shared case table testdata/auto_columns_validation_cases.json.
func ValidateSectionEmptyRecord ¶ added in v2.8.46
func ValidateSectionEmptyRecord(sec SectionSpec) string
ValidateSectionEmptyRecord checks a section's P6 `emptyRecordFields` ("" when valid or unused).
func ValidateSectionRecordLimit ¶ added in v2.8.46
func ValidateSectionRecordLimit(sec SectionSpec) string
ValidateSectionRecordLimit checks the P11 section `recordLimit` and returns an empty message when it is valid or unset. The hub mirror is validateSectionRecordLimitV2 in hub/scripts/adapter-schema-and-docs.mjs.
func ValidateSortKeys ¶ added in v2.8.46
func ValidateSortKeys(keys []SortKeySpec) string
ValidateSortKeys checks a `sort` list ("" when valid). It mirrors validateSortKeysV2 in hub/scripts/adapter-schema-and-docs.mjs; version_validation_cases.json pins both, down to the message.
func ValidateXMLTree ¶ added in v2.8.46
func ValidateXMLTree(xs *XMLFeedSpec) string
ValidateXMLTree checks `source.xml` when `mode` is `tree` (and that `tree` is not set for other modes). It returns "" or the first problem relative to the spec. The hub compiler (validateXmlTreeV2) returns the same messages; both run testdata/xml_tree_validation_cases.json.
func ValueToFloat ¶
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 ¶
ArrayFieldGate requires `ArrayPath` to be an array and (if non-empty) its first element's `Field` to be truthy.
type AutoColumnsExclude ¶ added in v2.8.46
type AutoColumnsExclude struct {
Prefixes []string `json:"prefixes,omitempty"`
Keys []string `json:"keys,omitempty"`
}
AutoColumnsExclude drops candidate keys before they become columns or row-mode record fields.
type AutoColumnsKeySource ¶ added in v2.8.46
type AutoColumnsKeySource struct {
From string `json:"from"`
FirstN int `json:"firstN,omitempty"`
Exclude *AutoColumnsExclude `json:"exclude,omitempty"`
PinFirst []string `json:"pinFirst,omitempty"`
}
AutoColumnsKeySource is the `autoColumns.fallback` key source, tried when the primary source yields no keys.
type AutoColumnsRecordsSpec ¶ added in v2.8.46
type AutoColumnsRecordsSpec struct {
// Keys is "columns" (default: the column keys) or "row" (every row key, sorted, after `exclude`).
Keys string `json:"keys,omitempty"`
// MaxFields caps the non-empty fields one record takes in `keys: row` mode (default and max MaxAutoColumnsRecordFields).
MaxFields int `json:"maxFields,omitempty"`
// MaxChars truncates each value (default 160).
MaxChars int `json:"maxChars,omitempty"`
}
AutoColumnsRecordsSpec emits each rendered row as a record keyed by data keys (PRIMITIVES-RFC P7).
type AutoColumnsSpec ¶ added in v2.8.46
type AutoColumnsSpec struct {
From string `json:"from"`
FirstN int `json:"firstN,omitempty"`
Exclude *AutoColumnsExclude `json:"exclude,omitempty"`
PinFirst []string `json:"pinFirst,omitempty"`
Fallback *AutoColumnsKeySource `json:"fallback,omitempty"`
// LabelsPath is a root-relative path to a `{ key: label }` map. It feeds `from: labels` and header labels.
LabelsPath string `json:"labelsPath,omitempty"`
MaxCols int `json:"maxCols,omitempty"`
HeaderMaxChars int `json:"headerMaxChars,omitempty"`
CellMaxChars int `json:"cellMaxChars,omitempty"`
EmptyValue *string `json:"emptyValue,omitempty"`
Records *AutoColumnsRecordsSpec `json:"records,omitempty"`
}
AutoColumnsSpec derives a section's table columns from the data instead of a fixed `columns` list (PRIMITIVES-RFC P7). Candidate keys come from `from`; `exclude` drops keys; keys are ordered (see resolveAutoColumnKeys), `pinFirst` keys move to the front, and the list is cut to `maxCols`. When the primary source yields no keys, `fallback` (one level, no nesting) is tried. Headers come from the `labelsPath` map when it labels the key, else the key itself. Cells are plain text. `records` emits each rendered row as a record keyed by the same data keys.
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 ¶
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"`
// ArrayPaths tries each dot-path in order; the first one that yields at least one object row wins
// (`<= MaxCollectionArrayPaths`). A path may name an earlier collection.
ArrayPaths []string `json:"arrayPaths,omitempty"`
// AsArray turns a non-empty object found at `arrayPath`/`arrayPaths` into a single row.
AsArray bool `json:"asArray,omitempty"`
// ScalarRows (PRIMITIVES-RFC P9) turns string, number and bool elements of the source array, or a lone
// scalar at the path, into rows `{"_value": el}` (the P4 `each` scalar key), so string lists such as
// version arrays can be filtered, sorted and limited. Object elements stay rows; null and nested
// arrays are skipped.
ScalarRows bool `json:"scalarRows,omitempty"`
// Unnest flattens `parent[].child[]` into child rows that carry selected parent fields
// (`<= MaxUnnestStages` stages, depth 1 per stage).
Unnest []UnnestSpec `json:"unnest,omitempty"`
// Concat appends the rows of other (acyclic, compile-time checked) collections after the source rows.
Concat []string `json:"concat,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.
P6 collection sources (PRIMITIVES-RFC) compose in a fixed order: source (`arrayPath` | `arrayPaths` [+ `asArray`] | `objectEntries` | `parallelArrays`) -> `unnest` -> `concat` -> `filter` -> `dedupeBy` -> `sort` -> `limit`. Every stage keeps `MaxCollectionItems`.
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,omitempty"` // see ValidConditionOp
Value string `json:"value,omitempty"` // literal right-hand side (RE2 pattern for `matches`)
ValueVar string `json:"valueVar,omitempty"` // right-hand side read from a variable instead of `value`
Values []string `json:"values,omitempty"`
Num *float64 `json:"num,omitempty"`
IgnoreCase bool `json:"ignoreCase,omitempty"`
Not bool `json:"not,omitempty"`
All []ConditionSpec `json:"all,omitempty"`
Any []ConditionSpec `json:"any,omitempty"`
}
ConditionSpec defines a typed comparison predicate for `when`, `filter`, guards and variants (PRIMITIVES-RFC P3).
A leaf compares one target against `value` / `values` / `num` / `valueVar`. A group sets `all` and/or `any` (and no `op`): every `all` child must hold and, when `any` is set, at least one `any` child. `not` negates either form. Groups nest at most MaxConditionDepth deep with at most MaxConditionLeaves leaves.
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 DefaultsSpec ¶ added in v2.8.46
type DefaultsSpec struct {
Guard *GuardSpec `json:"guard,omitempty"`
Source *SourceSpec `json:"source,omitempty"`
Collections map[string]CollectionPipelineSpec `json:"collections,omitempty"`
Vars map[string]VarSpec `json:"vars,omitempty"`
Emit *EmitSpec `json:"emit,omitempty"`
Section *SectionSpec `json:"section,omitempty"`
}
DefaultsSpec is a spec-level block of shared definitions (`defaults`, PRIMITIVES-RFC P10).
It is resolved when the spec is decoded, so the runtime never sees it. Every branch the spec can run inherits it: each `variants[].extract`, the `fallback`, and the spec's own body. `Section` is merged into every `emit.sections[]` entry of those branches.
Precedence (the branch always wins; the merge is one level deep):
- `guard`, `source`, `emit` and `section` merge key by key. A key the branch sets replaces the inherited key, including false, 0 and "". Anything below that key is replaced whole (for example `source.json` or `emit.pagination`).
- Named-entry maps merge by entry name: `collections`, `vars`, `emit.recordFields`, `emit.recordTypes`, and a section's `itemVars`, `recordFields` and `recordTypes`. A branch entry replaces the inherited entry with the same name; it is never merged field by field.
- Lists (`bullets`, `sections`, `columns`, `linksVars`, ...) are never concatenated: a branch list replaces the inherited list.
- A nested spec's own `defaults` beats its parent's.
- A branch cannot delete an inherited key; it overrides it with its own value instead.
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"
// P11 options (line_readers.go):
HeaderCase string `json:"headerCase,omitempty"` // "" (as written, trimmed) | "lower"
RequireHeaders []string `json:"requireHeaders,omitempty"` // every name must be a header key
RequireAnyHeaders []string `json:"requireAnyHeaders,omitempty"` // at least one name must be a header key
MinColumns int `json:"minColumns,omitempty"` // the header row needs at least this many fields
Comment string `json:"comment,omitempty"` // one character; lines starting with it are skipped
SkipRows int `json:"skipRows,omitempty"` // data rows dropped right after the header
StrictQuotes bool `json:"strictQuotes,omitempty"` // a malformed quote ends the read (default: lazy quotes)
FixedFields bool `json:"fixedFields,omitempty"` // a row whose field count differs from the first record ends the read
Where *ConditionSpec `json:"where,omitempty"` // row filter (fields only): failing rows are neither kept nor counted
DropPartialLastLine bool `json:"dropPartialLastLine,omitempty"` // drop an unterminated last line (Range-cut bodies)
}
DelimitedSpec configures the bounded RFC 4180 CSV / TSV reader (`maxBytes <= 2 MiB`, `maxRows <= 2000`).
PRIMITIVES-RFC P11 adds header projection and row selection (line_readers.go): header key normalization and required headers, comment lines, skipped descriptor rows, a strict field-count mode, a per-row `where` filter counted over the whole bounded input, and Range-cut partial last line handling.
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 EachDedupe ¶ added in v2.8.46
type EachDedupe struct {
IgnoreCase bool `json:"ignoreCase,omitempty"`
}
EachDedupe drops repeated per-element results produced by `VarSpec.Each`. Its presence enables dedupe; IgnoreCase compares the strings.ToLower forms. The first spelling seen wins.
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"`
// BulletsAsBlocks separates bullet lines with a blank line ("\n\n") instead of "\n", for legacy formatters that
// emitted each bullet as its own Markdown block.
BulletsAsBlocks bool `json:"bulletsAsBlocks,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"`
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"`
RecordTypes map[string]RecordTypeSpec `json:"recordTypes,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
// contains filtered or unexported fields
}
ExecuteOptions configures optional host callbacks for Execute.
type FieldPrefixFilterSpec ¶
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 ¶
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 {
// Never marks a route that never emits (`guard: { never: true }`, never_guard.go): Execute returns (nil, false)
// before reading the body, so the page falls through to the next route or extractor. It excludes every other
// guard key, and the spec it sits in cannot have variants or a fallback (ValidateNeverGuard).
Never bool `json:"never,omitempty"`
// 64 KiB ASCII-lowercase probe substring prefilter (at least one needle must appear if non-empty).
RequireAnyProbe []string `json:"requireAnyProbe,omitempty"`
// PRIMITIVES-RFC P11: the same 64 KiB ASCII-lowercase probe, rejecting when any needle appears (e.g. an HTML
// shell or WAF page served where a plain-text file is expected).
RejectAnyProbe []string `json:"rejectAnyProbe,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"`
// Structured post-parse conditions on the parsed root (PRIMITIVES-RFC P3). Vars are not resolved yet,
// so `var` / `valueVar` are rejected by the compiler here.
RejectWhen []ConditionSpec `json:"rejectWhen,omitempty"` // reject when any condition holds
RequireWhen []ConditionSpec `json:"requireWhen,omitempty"` // reject unless every condition holds
}
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 HTMLFragmentSpec ¶ added in v2.8.46
type HTMLFragmentSpec struct {
Path string `json:"path"`
MaxBytes int `json:"maxBytes,omitempty"` // fragment bytes parsed; default DefaultHTMLFragmentBytes
SelectAll map[string]HTMLSelectAllSpec `json:"selectAll,omitempty"`
Tables map[string]HTMLTableSpec `json:"tables,omitempty"`
DLKv map[string]HTMLDLKvSpec `json:"dlKv,omitempty"`
}
HTMLFragmentSpec selects from an HTML fragment held in the JSON string at Path: the reverse of `embeddedFrom`, which pulls JSON out of HTML. Each `selectAll` / `tables` / `dlKv` entry behaves exactly as under `source.html` and is written into the root object under its own name, so sections read it with `arrayPath` and vars with `paths`. ValidateHTMLFragments holds the bounds.
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 ¶
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
// HTMLFragments runs the HTML source's bounded selectors (`selectAll`, `tables`, `dlKv`) over HTML markup
// stored in a JSON string field, and writes each named result into the root object (html_fragments.go).
HTMLFragments []HTMLFragmentSpec `json:"htmlFragments,omitempty"`
}
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 LineBlockSpec ¶ added in v2.8.46
LineBlockSpec is a skipped region: it opens on a line starting with Start and closes on a line starting with End, or on the next blank line when End is empty. Both marker lines are skipped.
type LinePrefixField ¶ added in v2.8.46
LinePrefixField maps a literal line prefix to a field name.
type LineReaderSpec ¶ added in v2.8.46
type LineReaderSpec struct {
MaxLines int `json:"maxLines,omitempty"` // physical lines read (<= MaxTextLines; default MaxTextLines)
CommentPrefixes []string `json:"commentPrefixes,omitempty"` // lines starting with any of these are skipped
StripPrefixes []string `json:"stripPrefixes,omitempty"` // the first matching prefix is removed once, then the line is re-trimmed
SkipBlocks []LineBlockSpec `json:"skipBlocks,omitempty"` // regions dropped whole (start line through end line)
RejectChars string `json:"rejectChars,omitempty"` // lines containing any of these bytes are dropped
MaxLineBytes int `json:"maxLineBytes,omitempty"` // longer lines are dropped (0 = no limit beyond the input cap)
// `lines` mode:
Set []LinePrefixField `json:"set,omitempty"` // a line starting with prefix sets a root field to the rest of the line (last wins)
Sticky []LinePrefixField `json:"sticky,omitempty"` // a line starting with prefix sets a field copied onto every later row
// `keyValue` mode:
Sep string `json:"sep,omitempty"` // separator, split at its first occurrence (default ":")
KeyCase string `json:"keyCase,omitempty"` // "" (as written) | "lower"
AllowKeys []string `json:"allowKeys,omitempty"` // keep only these keys (compared after keyCase)
Blocks string `json:"blocks,omitempty"` // "" | "blank": a blank line ends the open block
NewBlockOnRepeat []string `json:"newBlockOnRepeat,omitempty"` // a listed key already in the open block starts a new block
IntoField string `json:"intoField,omitempty"` // rows field: "lines" (lines mode) or "entries" (keyValue mode)
}
LineReaderSpec configures `text.mode: lines` and `text.mode: keyValue` (PRIMITIVES-RFC P11).
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"` // numeric field, or an array whose length is the total
TotalVar string `json:"totalVar,omitempty"` // P2: integer total from a computed var (e.g. math max of meta total and lenOf)
ReturnedVar string `json:"returnedVar,omitempty"` // P7: integer returned count from a computed var instead of the emitted row count
TruncatedVar string `json:"truncatedVar,omitempty"` // P11: a non-empty var forces truncated=true (e.g. a Range-cut body) even when total <= returned
TotalOnly bool `json:"totalOnly,omitempty"` // P9: Total alone; Returned, Truncated and the derived cursor stay unset (NextCursorPath still applies)
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 ParsedVersion ¶ added in v2.8.46
type ParsedVersion struct {
OK bool
// contains filtered or unexported fields
}
ParsedVersion is a parsed P9 version. The zero value (OK false) is a value that does not parse.
func ParseVersion ¶ added in v2.8.46
func ParseVersion(s string) ParsedVersion
ParseVersion parses s by the P9 grammar in linear time.
func (ParsedVersion) Prerelease ¶ added in v2.8.46
func (v ParsedVersion) Prerelease() bool
Prerelease reports whether v parsed and carries a pre-release tag.
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 RecordTypeSpec ¶ added in v2.8.46
type RecordTypeSpec struct {
// Type is one of "string" (default), "int", "number", "bool", "array".
Type string `json:"type,omitempty"`
// Path reads the raw value at a dot-path on the row / active object instead of the template.
Path string `json:"path,omitempty"`
// Sep splits a string source into array elements (array type only); "" keeps one element.
Sep string `json:"sep,omitempty"`
// KeepEmpty emits JSON null for this field when it has no valid value (instead of omitting it).
KeepEmpty bool `json:"keepEmpty,omitempty"`
// OmitEmpty drops this field when it has no valid value even under scope-wide `keepEmptyRecordFields`
// (PRIMITIVES-RFC P6: legacy records that keep some empty strings but omit other empty fields).
// It cannot be combined with KeepEmpty.
OmitEmpty bool `json:"omitEmpty,omitempty"`
}
RecordTypeSpec types one Stage 3 record field (`recordTypes`, PRIMITIVES-RFC P1).
By default the field's value is its `recordFields` template result (a string), coerced to Type. When Path is set, the raw value at Path on the current row (sections) or active root object (emit) is coerced instead, so JSON arrays, numbers, and bools survive without a string round trip.
YAML shorthand: `recordTypes: { price: number }` is `{ price: { type: number } }`.
func (*RecordTypeSpec) UnmarshalJSON ¶ added in v2.8.46
func (r *RecordTypeSpec) UnmarshalJSON(b []byte) error
UnmarshalJSON accepts either a bare type string or a full object.
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"`
AutoColumns *AutoColumnsSpec `json:"autoColumns,omitempty"` // P7: data-driven columns (auto_columns.go)
TableSeparator string `json:"tableSeparator,omitempty"` // "" (default `| --- |`) | "compact" (`|---|`)
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"`
RecordTypes map[string]RecordTypeSpec `json:"recordTypes,omitempty"`
KeepEmptyRecordFields bool `json:"keepEmptyRecordFields,omitempty"`
// RecordLimit (P11) caps the records a `columns` table section emits while its rows keep rendering up to
// `limit` (e.g. a 50-row index table with 25 records); 0 means one record per rendered row.
RecordLimit int `json:"recordLimit,omitempty"`
// EmptyRecordFields (P6) emits exactly one fallback record, expanded against top-level vars, when the
// section's source yields no rows (`<= MaxEmptyRecordFields` keys).
EmptyRecordFields map[string]string `json:"emptyRecordFields,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"`
// Condition is a structured predicate on the parsed JSON root (PRIMITIVES-RFC P3); ANDed with the fields above.
Condition *ConditionSpec `json:"condition,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" | "version" (PRIMITIVES-RFC P9, version.go)
}
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"`
// Defaults holds shared definitions every branch of this spec inherits (PRIMITIVES-RFC P10).
// It is merged into the branches by Spec.UnmarshalJSON and is always nil on a decoded spec.
Defaults *DefaultsSpec `json:"defaults,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.
func (*Spec) UnmarshalJSON ¶ added in v2.8.46
UnmarshalJSON decodes a Spec and resolves its `defaults` block (PRIMITIVES-RFC P10) into its branches.
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",
// "regex", "math", "joinNonEmpty", "urlEncode", "urlDecode" (PRIMITIVES-RFC P2, ops_scalar.go),
// "checkDigit" (PRIMITIVES-RFC P8, ops_scalar.go)
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"`
// PRIMITIVES-RFC P2 scalar ops (regex, math, joinNonEmpty, urlEncode/urlDecode); see ops_scalar.go.
Pattern string `json:"pattern,omitempty"` // regex: RE2, <= MaxRegexPatternBytes
Mode string `json:"mode,omitempty"` // regex: match|capture|replace; urlEncode/urlDecode: query|path
Group int `json:"group,omitempty"` // regex capture group (0 = whole match)
Fn string `json:"fn,omitempty"` // math: max|min|add|sub|mul|div|round|abs
Args []string `json:"args,omitempty"` // math operands: templates, or "." for the current value
Decimals *int `json:"decimals,omitempty"` // math: fixed output decimals 0..6
// PRIMITIVES-RFC P8 checkDigit (ops_scalar.go).
Scheme string `json:"scheme,omitempty"` // gtin | isbn10 | isbn13 | issn | luhn
Normalize string `json:"normalize,omitempty"` // gtin14: left-pad a valid GTIN to 14 digits
// 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" | "lines" | "keyValue"
PathParam string `json:"pathParam,omitempty"`
RejectHTMLSoft404 *bool `json:"rejectHtmlSoft404,omitempty"`
// BlankLineBeforeFences inserts a blank line before a fenced code block that directly follows a non-blank line
// in Markdown bodies (plain mode, yaml_frontmatter_card, and Markdown paths of code_or_markdown_by_path). The
// fail-closed sanitizer trusts a fence only after a blank line, so without this a CommonMark-valid fence that
// interrupts a paragraph is escaped as text. Opt-in; code bodies are never changed.
BlankLineBeforeFences bool `json:"blankLineBeforeFences,omitempty"`
// Lines configures `mode: lines` and `mode: keyValue` (PRIMITIVES-RFC P11, line_readers.go).
Lines *LineReaderSpec `json:"lines,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 UnnestSpec ¶ added in v2.8.46
type UnnestSpec struct {
ChildPath string `json:"childPath"`
ParentFields map[string]string `json:"parentFields,omitempty"`
KeyField string `json:"keyField,omitempty"`
}
UnnestSpec is one P6 `unnest` stage: every row's `ChildPath` value becomes child rows.
- An array yields one row per object element.
- An object yields one row, unless `KeyField` is set: then it is read as a map of arrays (`{"2024-01": [...], ...}`), walked in sorted key order, and each child row gets the map key in `KeyField`.
Each child row is a shallow copy of the child object plus `ParentFields` (output key -> parent dot-path), which are written last and therefore win over same-named child keys.
type VarSpec ¶
type VarSpec struct {
// Value selectors (work across JSON, Hydration, XML, CSV, and HTML Embedded/JSON-LD):
Paths []string `json:"paths,omitempty"`
LenOf string `json:"lenOf,omitempty"` // P2: element count of an array / key count of an object at this path
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"`
// Per-element mapping (P4). When set, the value selected by `paths` / `embeddedPaths` /
// `jsonLdPaths` is treated as a list (a lone value is a one-element list) and `Each` is
// evaluated once per element with that element as the active object. Empty results are
// dropped, then `Dedupe`, `Limit`, `ItemWrap` and `Join` apply. ValidateEachSpec (each.go)
// holds the compile-time rules and bounds.
Each *VarSpec `json:"each,omitempty"`
Dedupe *EachDedupe `json:"dedupe,omitempty"`
// Marks variable output as pre-composed Markdown (e.g. html_to_md, cssHtmlToMd, inline code wrap).
MarkdownFormatted bool `json:"markdownFormatted,omitempty"`
// CollectLinks emits the hyperlinks found while converting this var's HTML to Markdown (`format: html_to_md`
// or an `htmlToMd` step) into doc.Links, using the same HTML extractor as the legacy Go formatters. Links pass
// the emitter's link gate (absolute https only, no whitespace, deduped, capped at MaxEmittedLinks) and come
// before linksVars / linkTemplates. Top-level vars only.
CollectLinks bool `json:"collectLinks,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" | "tree"
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"
// Tree configures `mode: tree` (PRIMITIVES-RFC P12): the document becomes a bounded JSON-like tree
// (`@attr`, `#text`, repeated elements as arrays) that paths, collections and conditions read (xml_tree.go).
Tree *XMLTreeSpec `json:"tree,omitempty"`
}
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`).
type XMLTreeSelectSpec ¶ added in v2.8.46
type XMLTreeSelectSpec struct {
Tags []string `json:"tags"`
MaxItems int `json:"maxItems,omitempty"`
}
XMLTreeSelectSpec collects the outermost descendants whose key is in Tags, in document order.
type XMLTreeSpec ¶ added in v2.8.46
type XMLTreeSpec struct {
MaxBytes int `json:"maxBytes,omitempty"`
MaxDepth int `json:"maxDepth,omitempty"`
MaxNodes int `json:"maxNodes,omitempty"`
MaxAttrs int `json:"maxAttrs,omitempty"`
FoldCase bool `json:"foldCase,omitempty"`
Namespaces map[string]string `json:"namespaces,omitempty"` // prefix -> namespace URI
AlwaysArray []string `json:"alwaysArray,omitempty"` // element keys that are always arrays
MixedText map[string]string `json:"mixedText,omitempty"` // element key -> separator between text runs
KeyAttr map[string]string `json:"keyAttr,omitempty"` // element key -> attribute whose value becomes the key
Select map[string]XMLTreeSelectSpec `json:"select,omitempty"` // output name -> outermost descendants
}
XMLTreeSpec configures `source.xml.mode: tree`. ValidateXMLTree holds the bounds.
Source Files
¶
- auto_columns.go
- collections.go
- conditions.go
- defaults.go
- doc.go
- each.go
- emitter.go
- html_fragments.go
- line_readers.go
- never_guard.go
- ops_format_collections.go
- ops_guards_text.go
- ops_scalar.go
- readers_html.go
- readers_hydration_xml_csv.go
- readers_json.go
- readers_text_fences.go
- records_typed.go
- types.go
- version.go
- xml_tree.go