feat: schema validator

This commit is contained in:
Jan Halfar
2026-10-21 21:31:19 +02:00
parent c15367dcfd
commit ffe2d130a3
228 changed files with 16629 additions and 3926 deletions
+21 -11
View File
@@ -10,14 +10,17 @@ Walker crawls a website and collects performance, SEO and broken-link data. It s
```sh
go build ./... # build everything
go run ./cmd/walker path/to/config.yaml # run the crawler + web UI (default addr :3001)
go run ./cmd/validator schema.html https://host/page # validate one page against an htmlschema file
go run ./cmd/walker path/to/config.yaml # run the crawler + web UI (default addr :3001), -exit-on-stdin-close for the macOS app
go run ./cmd/validator schema-root group https://host/page # validate one page, exit 3 on error findings
go test ./... # all tests
go test ./config -run TestLoad # single test
go test ./htmlschema/... -v # schema loader/group validator + example server
go test ./htmlschema/... -v # syntax, lint, rules + golden tests of the SPEC.md examples
go install ./cmd/htmlschema-lsp # language server for schema files, Zed extension in editors/zed-htmlschema
go run ./cmd/configvalidator config.yaml # validate a walker config: unknown keys, types, schema root - exit 3 on errors
go run ./cmd/demo # demo shop on :8080 (reads templates, css, catalogue from source on every request), schema in htmlschema/demo/schema, group header x-next-js-app
```
The `Makefile` holds only ad-hoc deploy targets (cross-compile, then scp to a stage host); it isn't a build system. The `Dockerfile` builds both binaries and bakes in `cmd/walker/config-example.yaml`.
`mise.toml` pins Go and `gotsrpc` (keep it in sync with `go.mod`) and wraps the commands above as tasks (`mise tasks`; `mise run generate` regenerates the Go proxy and the Swift client; `goswiftrpc` is pre-alpha without mise support, so `generate:swift` runs `go install github.com/foomo/goswiftrpc/cmd/goswiftrpc@latest` first). The `Makefile` holds only ad-hoc deploy targets (cross-compile, then scp to a stage host); it isn't a build system. The `Dockerfile` builds both binaries and bakes in `cmd/walker/config-example.yaml`.
## Configuration
@@ -27,11 +30,11 @@ The `Makefile` holds only ad-hoc deploy targets (cross-compile, then scp to a st
- `interval` / `offset` (durations): wall-clock-aligned scrape schedule, see `schedule.go`. `0` means restart immediately.
- Other keys: `ignore` (path prefixes), `ignorequerieswith`, `ignoreallqueries`, `ignorerobots`, `depth`, `paging`, `groupheader`, `schemaroot`.
Most `cmd/walker/*.yaml` files are local, site-specific configs and are usually untracked.
Most `cmd/walker/*.yaml` files are local, site-specific configs and are usually untracked. `config.Validate` checks a config file with line numbers (`Load` silently ignores unknown keys), `config.ReadForm`/`WriteForm` turn it into a form and back while keeping comments and unknown keys.
## Architecture
**Actor-style core (`walker.go`, `scrapeloop.go`).** `NewWalker` starts one goroutine, `scrapeloop`, which owns all crawl state: the job map, results and the client pool. Public methods (`Walk`, `Stop`, `GetStatus`, `GetStatuses`) never touch that state directly. Each one sends a request on a channel and waits for the reply on that same channel. Keep it this way: new features that read or change crawl state should add a channel case to the `select` in `scrapeloop`, not shared fields or mutexes. `GetStatuses()` returns the last completed cycle and the running one (`nil` while idle between scheduled cycles), and the reports render both. `GetStatus()` returns the current cycle.
**Actor-style core (`walker.go`, `scrapeloop.go`).** `NewWalker` starts one goroutine, `scrapeloop`, which owns all crawl state: the job map, results and the client pool. Public methods (`Walk`, `Stop`, `Restart`, `GetStatus`, `GetStatuses`) never touch that state directly. Each one sends a request on a channel and waits for the reply on that same channel. Keep it this way: new features that read or change crawl state should add a channel case to the `select` in `scrapeloop`, not shared fields or mutexes. `GetStatuses()` returns the last completed cycle and the running one (`nil` while idle between scheduled cycles), and the reports render both. `GetStatus()` returns the current cycle. `Restart()` starts a new cycle right away (service `RestartScrape`, the "New Scrape" button of the overview); requests still in flight of an aborted cycle free their clients, their results are dropped (`dispatched` remembers the cycle of each busy client).
**Scraping (`scrape.go`).** `scrapeloop` hands each job a free `poolClient` from `clientPool` (one `http.Client` per unit of concurrency, optional cookie jar, TLS verification disabled, redirect chain recorded via request context) and calls `scrape` in its own goroutine. Results come back over `chanResult`. `scrape` parses the HTML with goquery and runs `extract.go`, which pulls out title, description, h1, canonical and JSON-LD into `vo.Structure`. It also collects links (including links inside `<noscript>`) and, if configured, runs schema validation.
@@ -41,15 +44,22 @@ Most `cmd/walker/*.yaml` files are local, site-specific configs and are usually
- `ValidationFunc`: produces `vo.Validations` from the structure and the scrape data.
- `ScrapeResultModifierFunc`: post-processes each result.
**htmlschema.** Validation schemas are HTML documents annotated with `val:*` attributes (e.g. `val:score`, `val:attr="content;min-length:10"`), `content=*` wildcards and `<ref>` includes. `NewGroupValidator(schemaroot)` loads `<root>/<group>/<name>.html` plus an optional `<root>/default.html`. A page's group comes from the response header named by `groupheader`. `htmlschema/example/` contains a working schema tree and a test server.
**htmlschema.** The language is specified in `htmlschema/SPEC.md`, whose worked examples (section 14, demo shop pages) are the golden tests in `examples_test.go`. Change spec and examples together. `LoadRoot(schemaroot)` reads every `.html` below the root and returns all problems as `LintErrors`. Only `groups/<group>.html` and `default.html` (the fallback) are fixed locations, and the rest is shared via `val:include` and `val:comp`. Files with a `val:component` root are recognized components. `Root.Validate(group, html)` returns a `Report`: findings (severity + penalty), a score tree with a computed maximum, and per-component summaries. Score and penalty are never combined. The pipeline: `syntax.go` (tokenizer tree builder, no HTML5 recovery) → `compile.go` (includes, comps, wildcards flattened into per-element `skip` selectors, lint) → `score.go` (static max) → `page.go` (exclusion set, component recognition, locators) → `match.go`/`validate.go`/`ld.go`. A page's group comes from the response header named by `groupheader`. The demo shop is the example: `htmlschema/demo/schema` holds its schema tree, `htmlschema/demo/server` renders the pages (`server.NewHandler`, group header `x-next-js-app`); the golden tests and the walker and service tests render pages through that handler, without a port. Editor support: `cmd/htmlschema-lsp` (completion and hover from `htmlschema.Vocabulary()`, which is derived from the compiler's rule tables, plus lint diagnostics via `LoadRootOverlay` with the unsaved buffers), registered in Zed by the dev extension `editors/zed-htmlschema`.
**Reports (`reports/`).** Each report renders plain text/HTML from a `vo.Status`, and `reports.GetReportHandler(basePath)` routes between them. To add a report, register it in `reports.go`, both in the handler and in `GetReportHandlerMenuHTML`.
**Service API and macOS app.** `service.go` is exposed via gotsrpc: `gotsrpc.yml` generates the Go HTTP proxy (`gotsrpc_gen.go`, mounted on `/service` in `cmd/walker`) and a Swift client in `swift/`. Regenerate with `gotsrpc gotsrpc.yml` after changing `Service` or any type it returns. Never edit `*_gen.go` or `swift/*.swift` by hand. `macos/Walker.xcodeproj` is a SwiftUI app (macOS 26, Swift 6) that compiles `swift/` and `macos/Walker/` into one module through synchronized folders, so new files need no project edits. Constraints that come from the generated Swift code:
- All mapped Go packages share one Swift module, so Go type names must be unique across `vo`, `htmlschema` and `walker` (hence `vo.ResultValidation`).
**Service API and macOS app.** `Service` (`serviceinterface.go`, implemented by the private `service` in `service.go`, `NewService` returns it and its `*Walker`) is exposed via gotsrpc: `gotsrpc gotsrpc.yaml` (gotsrpc v3, as in `go.mod`) generates the Go HTTP proxy (`gotsrpc_gen.go`, mounted on `/service` in `cmd/walker`), `goswiftrpc generate goswiftrpc.yaml` the Swift client in `macos/Walker/Generated/`. Regenerate both after changing `Service` or any type it returns. Never edit `*_gen.go` or `macos/Walker/Generated/*.swift` by hand. `macos/Walker.xcodeproj` is a SwiftUI app (macOS 26, Swift 6) that compiles `macos/Walker/` (including the generated client) as one synchronized folder, so new files need no project edits. Constraints that come from the generated Swift code:
- Each mapped Go package is a Swift namespace (`WalkerVO`, `HTMLSchemaVO`, `Walker` for the root package with `Walker.ServiceClient`, `GoTime`), so the app always writes qualified names (`WalkerVO.ScrapeResult`). Extensions too: an unqualified `extension X` no longer finds the generated type.
- A zero `time.Time` is encoded as `null`, but a value `time.Time` becomes a non-optional `Date`. Use `*time.Time` for timestamps that can be unset (see `vo.ScrapeSummary`).
- The generated `Duration` (go `time.Duration`, nanoseconds) shadows `Swift.Duration` in the app, so write `Swift.Duration` explicitly.
- The 3D graph (`Views/GraphView.swift`, RealityKit) is laid out by the local package `macos/Packages/GraphLayout`, the only user of Grape's `ForceSimulation` (pinned to a commit on `main` - `kinetics.position` is only public there). Grape is generic and `@inlinable`, so its hot loops compile in the calling module; the package always builds with `-O` via `unsafeFlags` (not `-wmo`, that breaks Xcode debug builds), or the layout is ~50x slower in Debug builds. Keep simulation code in that package. Xcode resolves Grape on first open.
- go's `time.Duration` (nanoseconds) is `GoTime.Duration`; a bare `Duration` is `Swift.Duration`.
- The app has no graph view for now - the 3D graph was removed, the Go side (`GetGraph`, `GetPageGraph`, `GetPageFolderLinks`, `GetFolderPages`) stays and the generated Swift client still has those calls.
- The schema developer window (`SchemaDevView`, `SchemaDevModel`, `SchemaWebView`) iterates on an html schema against a live page. It calls `GetSchemaRoot`/`ValidateSchema`/`GetSchemaRootVersion` (`schemaservice.go`; the app polls the version every second and validates again when a schema file changes), which load the schema root from a path on the server (client and server share a file system) and return an `htmlschema.TraceNode` tree (`Root.Trace`). Selecting a node highlights its locators in the WKWebView. "Load Config" takes the site (base url + first path) and the schema root (resolved against the config's directory) of a local config (`SchemaDevModel.load`); the window of a local server starts with its own config. The tree (`SchemaTreeView`) writes rules as plain-language chips, marks elements from other schema files (`Source`) and wildcards (`TraceNode.Via`), and shows the details of the selected node inline - neutral selection, a click on the selected row toggles the details, keyboard navigation is its own (List without selection binding). Source references open the editor chosen in the settings at the line (`SourceLink`, `zed://file…`, `vscode://file…`). The middle column (`PageDataView`) shows a link preview from the OpenGraph data (`OpenGraphView`), the head and the JSON-LD of the validated html (`htmlschema.ExtractPageData`, same locators as the trace), linked with the tree in both directions.
- The app is **not sandboxed** (hardened runtime only): local walkers read configs and schema roots by path. The "helpers" run script phase builds `cmd/walker` and `cmd/configvalidator` into `Contents/Helpers` (with the Go pinned in `mise.toml`, resolved via `mise which go` with `GOTOOLCHAIN=local` - the build fails if mise is missing or `mise trust && mise install` hasn't run; target `ENABLE_USER_SCRIPT_SANDBOXING = NO`, go needs its module cache).
- Configs are edited only in the main window, in the overview of a local server: `LocalConfigForm` is the config form (`ConfigFormView`, fields with notes on the resulting crawl behaviour - keep them in sync with the Go side) with the walker's state on top. It saves to the file right away and rereads it when it changes on disk. Its yaml backend is the `configvalidator` helper; `ConfigTool` talks to it over stdin/stdout JSON.
- Local walkers: a `Server` with a `configPath` is a local config (sidebar section "Local"), its `baseURL` follows the config's `addr` (`ServerStore.refreshLocal`, not while its walker runs). `LocalWalkers` (owned by the `AppDelegate`, which stops them on quit) runs the walker helper per config with `-exit-on-stdin-close`, in the config's directory, and keeps state and log (`LocalWalkers.logLines`, a setting, default 10000 lines). Local servers get the normal `ServerDetailView`; their `OverviewView` puts the scrape cards above the log (`LocalWalkerLogPane`) and the config form beside them.
- Live metrics (top of the Performance view, `LiveMetrics`, `LiveMetricsView`): the `AppDelegate` (owner of `ServerStore` and `LocalWalkers`) runs `ServerStore.sampleMetrics` for the app's lifetime: every refresh interval it reads the `/metrics` of all servers in parallel (local ones only while running, 5 s timeout) (`PromText` parses the text format) and keeps the charted series for 30 minutes in memory - a local debugging tool. Each `MetricsChart` is evaluated locally (rate, gauge, histogram quantile over bucket increases) and carries the equivalent PromQL, so a Prometheus server backend can answer the same charts later. Charts use one axis each; new metrics need a `kept` entry, a chart case and its PromQL.
- The app target must not use `MainActor` default isolation (it would isolate the generated `Codable` conformances). App model classes are `@MainActor` explicitly.
**Logging.** Log messages go through `log/slog` with attributes (`slog.Info("scrape cycle completed", "pages", n)`), never `fmt.Print`/`log.Print`. `cmd/walker` sets the default logger: `-log-level debug|info|warn|error`, `-log-format text|json`, text on stderr by default. `fmt` is only for program output: CLI results and usage, reports, `configvalidator`'s stderr (the app shows it as is). The app's log view parses the slog text lines (`SlogEntry`), so keep walker's default format text.
**Other pieces.** `service.go` wraps the Walker with filtering and paging over results. `metrics.go` gives each Walker its own Prometheus registry (`MetricsHandler()`). The loop only updates the few true counters. All per-scrape metrics come from a collector that derives them from `GetStatuses()` at scrape time, once per view, with `scrape="current"|"complete"`. Add new per-scrape metrics there, not as state in `scrapeloop`. `validationmetrics.go` aggregates schema validation reports for it. `vo/` holds the shared value objects (`Status`, `ScrapeResult`, `Structure`, `Validations`).
+20 -4
View File
@@ -4,6 +4,18 @@ Walker walkes aka as crawls through websites and collects performance and SEO re
**Be careful when crawling your website with walker with aggressive settings, it might take your site down**
## Development
[mise](https://mise.jdx.dev) installs Go and `gotsrpc` from `mise.toml` and runs the common tasks:
```sh
mise install
mise tasks # list all tasks
mise run test
mise run walker cmd/walker/config-example.yaml
mise run generate # Go proxy + Swift client
```
## Configuration
```yaml
@@ -60,7 +72,7 @@ WIP
## service API
`cmd/walker` serves the gotsrpc `Service` on `/service` (`POST /service/<Method>` with a JSON array of arguments):
`cmd/walker` serves the gotsrpc `ServiceInterface` on `/service` (`POST /service/<Method>` with a JSON array of arguments):
- `GetScrapes()` summaries of the last complete and the current scrape (either is `null` if there is none), including the performance buckets, P50, P90 and max per group
- `GetResults(filters, page, pageSize)` filtered and paged results, `filters.Scrape` selects `"current"` (default) or `"complete"`. `filters.Path` searches the paths (case insensitive, anywhere in the path, without host and query), `filters.MinDur` / `filters.MaxDur` select a duration range `[MinDur, MaxDur)` like a performance bucket, `filters.Groups` selects groups (`""` for results without one), and the filter options list all groups and performance buckets with their page counts. It also returns the folder tree of all result paths of that scrape with page and error counts, from the same snapshot as the page. A folder's `Prefix` has no trailing slash (e.g. `https://example.com/shop`); used as `filters.Prefix` it selects the folder's own page and everything below it, but not `…/shopping`. Any other prefix matches as a plain string prefix
@@ -68,20 +80,24 @@ WIP
- `GetRedirects(scrape)` the redirecting urls with their hops, where they end, whether they are permanent, and the pages linking to them - the longest chains first
- `GetLinks(scrape)` every page with the number of pages and links pointing to it and its own links; `GetLinkedFrom(scrape, url, limit)` the pages linking to one url: total, a breakdown by group, and the first `limit` pages with the most links
- `GetGraph(scrape, options)` the site as a graph of folders down to `Depth`, with edges weighted by links. Links to navigation targets - linked from more than `GlobalShare` of the pages - are left out and listed separately
- `GetPageGraph(scrape, options, page, max)` the neighborhood of a page as a graph - the page first, the pages linking to it and linked from it, the most linked up to `max`
- `GetPageFolderLinks(scrape, options, page)` the links of a page to the folder nodes of that graph, without navigation links and links into its own folder
- `GetFolderPages(scrape, options, folder, max)` the pages a folder node of that graph stands for, the `max` most linked, with the links between them
- `GetResult(scrape, url)` the result for a url as a browser sees it: exact match, then ignoring the fragment and credentials, then a result redirecting to the url - `null` if it was not scraped
- `GetStatus()` open / done / pending counts
The Go proxy (`gotsrpc_gen.go`) and the Swift client (`swift/`) are generated from `gotsrpc.yml`:
The Go proxy (`gotsrpc_gen.go`) is generated from `gotsrpc.yaml`, the Swift client (`macos/Walker/Generated/`) from `goswiftrpc.yaml`:
```sh
gotsrpc gotsrpc.yml
gotsrpc gotsrpc.yaml
goswiftrpc generate goswiftrpc.yaml
```
`mise run generate` does both; it installs `goswiftrpc` (pre-alpha, no mise support yet) with `go install github.com/foomo/goswiftrpc/cmd/goswiftrpc@latest` on every run.
## macOS app
`macos/Walker.xcodeproj` is a native SwiftUI app (macOS 26) for one or more walker servers. It shows the current and the last complete scrape and browses the results. It compiles the generated client from `swift/` directly. The Graph section shows the site in 3D - laid out by `macos/Packages/GraphLayout` with [Grape](https://github.com/swiftgraphs/Grape)'s force simulation, rendered with RealityKit. Xcode fetches Grape when the project is opened the first time.
`macos/Walker.xcodeproj` is a native SwiftUI app (macOS 26) for one or more walker servers. It shows the current and the last complete scrape and browses the results. It compiles the generated client from `macos/Walker/Generated/` directly. The app bundles the `walker` and `configvalidator` binaries, built with the Go from `mise.toml` - run `mise trust && mise install` once before building in Xcode.
```sh
go run ./cmd/walker path/to/config.yaml # serves on :3001 by default
+159
View File
@@ -0,0 +1,159 @@
// configvalidator checks walker config files - and is the yaml backend of
// the config editor of the desktop app, which bundles it as a helper:
//
// configvalidator [-json] [-base dir] config.yaml|- validate
// configvalidator read [-base dir] config.yaml|- form and problems as json
// configvalidator write config.yaml < form.json the config with the form applied
// configvalidator write - < {"yaml": "…", "form": {…}} the same, all on stdin
//
// - reads stdin. Exit codes: 0 valid (warnings are fine), 1 usage or io, 3 errors.
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"github.com/foomo/walker/config"
)
func main() {
args := os.Args[1:]
command := "validate"
if len(args) > 0 && (args[0] == "read" || args[0] == "write" || args[0] == "validate") {
command, args = args[0], args[1:]
}
flags := flag.NewFlagSet("configvalidator", flag.ExitOnError)
asJSON := flags.Bool("json", false, "print the problems as json")
base := flags.String("base", "", "directory relative paths in the config are resolved against - default: the directory of the config file")
flags.Usage = usage
_ = flags.Parse(args)
if flags.NArg() != 1 {
usage()
os.Exit(1)
}
file := flags.Arg(0)
if *base == "" {
*base = baseOf(file)
}
var err error
exit := 0
switch command {
case "validate":
exit, err = validate(file, *base, *asJSON)
case "read":
err = read(file, *base)
case "write":
err = write(file)
}
if err != nil {
fmt.Fprintln(os.Stderr, "configvalidator:", err)
os.Exit(1)
}
os.Exit(exit)
}
func usage() {
fmt.Fprintln(os.Stderr, `usage:
configvalidator [-json] [-base dir] config.yaml|-
configvalidator read [-base dir] config.yaml|-
configvalidator write config.yaml|- < form.json`)
}
func baseOf(file string) string {
if file == "-" {
dir, _ := os.Getwd()
return dir
}
dir, _ := filepath.Abs(filepath.Dir(file))
return dir
}
func input(file string) ([]byte, error) {
if file == "-" {
return io.ReadAll(os.Stdin)
}
return os.ReadFile(file)
}
func validate(file, base string, asJSON bool) (int, error) {
data, err := input(file)
if err != nil {
return 0, err
}
problems := config.Validate(data, base)
exit := 0
for _, p := range problems {
if p.Severity == config.SeverityError {
exit = 3
}
}
if asJSON {
return exit, json.NewEncoder(os.Stdout).Encode(map[string]any{"problems": nonNil(problems)})
}
name := file
if file == "-" {
name = "stdin"
}
for _, p := range problems {
fmt.Printf("%s:%d:%d %s %s\n", name, p.Line, p.Column, p.Severity, p.Message)
}
if len(problems) == 0 {
fmt.Println(name + ": ok")
}
return exit, nil
}
func read(file, base string) error {
data, err := input(file)
if err != nil {
return err
}
form, err := config.ReadForm(data)
if err != nil {
form = config.DefaultForm()
}
return json.NewEncoder(os.Stdout).Encode(map[string]any{
"form": form,
"problems": nonNil(config.Validate(data, base)),
})
}
func write(file string) error {
var request struct {
YAML string `json:"yaml"`
Form config.Form `json:"form"`
}
var data []byte
if file == "-" {
if err := json.NewDecoder(os.Stdin).Decode(&request); err != nil {
return err
}
data = []byte(request.YAML)
} else {
if err := json.NewDecoder(os.Stdin).Decode(&request.Form); err != nil {
return err
}
var err error
if data, err = os.ReadFile(file); err != nil && !os.IsNotExist(err) {
return err
}
}
written, err := config.WriteForm(data, request.Form)
if err != nil {
return err
}
_, err = os.Stdout.Write(written)
return err
}
func nonNil(problems []config.Problem) []config.Problem {
if problems == nil {
return []config.Problem{}
}
return problems
}
+22
View File
@@ -0,0 +1,22 @@
// demo runs the htmlschema demo shop - funny robots and unusual cars with
// great, and a few deliberately flawed, SEO
package main
import (
"flag"
"log/slog"
"os"
"github.com/foomo/walker/htmlschema/demo/server"
)
func main() {
addr := flag.String("addr", ":8080", "address to listen on")
embedded := flag.Bool("embedded", false, "serve the files compiled into the binary, even if the sources are at hand")
flag.Parse()
slog.Info("htmlschema demo shop", "addr", *addr)
if err := server.Run(*addr, *embedded); err != nil {
slog.Error("demo shop stopped", "error", err)
os.Exit(1)
}
}
+25
View File
@@ -0,0 +1,25 @@
// htmlschema-lsp is a language server for htmlschema files: completion of
// val:* elements, rules and values, hover docs, and the lint errors of the
// schema root as diagnostics while typing. It speaks lsp over stdio.
package main
import (
"bufio"
"fmt"
"io"
"log/slog"
"os"
)
func main() {
if len(os.Args) > 1 && (os.Args[1] == "-h" || os.Args[1] == "--help") {
fmt.Println("htmlschema-lsp - language server for htmlschema files, speaks lsp over stdio")
return
}
s := newServer(&conn{in: bufio.NewReader(os.Stdin), out: os.Stdout})
if err := s.run(); err != nil && err != io.EOF {
// stdout is the protocol - slog writes to stderr, the log of the editor
slog.Error("htmlschema-lsp stopped", "error", err)
os.Exit(1)
}
}
+135
View File
@@ -0,0 +1,135 @@
package main
import (
"bufio"
"encoding/json"
"fmt"
"io"
"net/textproto"
"strconv"
"sync"
)
// the parts of the language server protocol the server needs - json-rpc 2.0
// with Content-Length framing over stdio
type message struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id,omitempty"`
Method string `json:"method,omitempty"`
Params json.RawMessage `json:"params,omitempty"`
Result any `json:"result,omitempty"`
Error *responseError `json:"error,omitempty"`
}
type responseError struct {
Code int `json:"code"`
Message string `json:"message"`
}
type conn struct {
in *bufio.Reader
out io.Writer
mu sync.Mutex
}
func (c *conn) read() (*message, error) {
header, err := textproto.NewReader(c.in).ReadMIMEHeader()
if err != nil {
return nil, err
}
length, err := strconv.Atoi(header.Get("Content-Length"))
if err != nil {
return nil, fmt.Errorf("invalid Content-Length: %w", err)
}
body := make([]byte, length)
if _, err := io.ReadFull(c.in, body); err != nil {
return nil, err
}
m := &message{}
return m, json.Unmarshal(body, m)
}
func (c *conn) write(m *message) error {
m.JSONRPC = "2.0"
body, err := json.Marshal(m)
if err != nil {
return err
}
c.mu.Lock()
defer c.mu.Unlock()
if _, err := fmt.Fprintf(c.out, "Content-Length: %d\r\n\r\n", len(body)); err != nil {
return err
}
_, err = c.out.Write(body)
return err
}
// reply answers a request - a nil result is sent as null
func (c *conn) reply(id json.RawMessage, result any) error {
if result == nil {
return c.write(&message{ID: id, Result: json.RawMessage("null")})
}
return c.write(&message{ID: id, Result: result})
}
func (c *conn) notify(method string, params any) error {
data, err := json.Marshal(params)
if err != nil {
return err
}
return c.write(&message{Method: method, Params: data})
}
type position struct {
Line int `json:"line"`
Character int `json:"character"`
}
type textRange struct {
Start position `json:"start"`
End position `json:"end"`
}
type textDocumentPositionParams struct {
TextDocument struct {
URI string `json:"uri"`
} `json:"textDocument"`
Position position `json:"position"`
}
type diagnostic struct {
Range textRange `json:"range"`
Severity int `json:"severity"`
Source string `json:"source"`
Message string `json:"message"`
}
type markupContent struct {
Kind string `json:"kind"`
Value string `json:"value"`
}
type textEdit struct {
Range textRange `json:"range"`
NewText string `json:"newText"`
}
type completionItem struct {
Label string `json:"label"`
Kind int `json:"kind,omitempty"`
Detail string `json:"detail,omitempty"`
Documentation *markupContent `json:"documentation,omitempty"`
FilterText string `json:"filterText,omitempty"`
InsertTextFormat int `json:"insertTextFormat,omitempty"`
TextEdit *textEdit `json:"textEdit,omitempty"`
}
const (
completionKindProperty = 10
completionKindValue = 12
completionKindFile = 17
completionKindStruct = 22
insertTextSnippet = 2
severityError = 1
)
+410
View File
@@ -0,0 +1,410 @@
package main
import (
"encoding/json"
"errors"
"io/fs"
"net/url"
"os"
"path/filepath"
"sort"
"strings"
"github.com/foomo/walker/htmlschema"
)
// server is a language server for htmlschema files. It only works on files
// inside a schema root - a directory with groups/ or default.html - and
// leaves every other html file alone.
type server struct {
conn *conn
// docs are the open documents by uri
docs map[string]string
// published are the uris with diagnostics by schema root
published map[string]map[string]bool
elements map[string]htmlschema.VocabularyElement
elementRules []htmlschema.VocabularyAttribute
valueRules []htmlschema.VocabularyAttribute
}
func newServer(c *conn) *server {
elements, elementRules, valueRules := htmlschema.Vocabulary()
s := &server{
conn: c,
docs: map[string]string{},
published: map[string]map[string]bool{},
elements: map[string]htmlschema.VocabularyElement{},
elementRules: elementRules,
valueRules: valueRules,
}
for _, e := range elements {
s.elements[e.Name] = e
}
return s
}
// run serves until exit - errors of single requests are answered, not fatal
func (s *server) run() error {
shutdown := false
for {
m, err := s.conn.read()
if err != nil {
return err
}
switch m.Method {
case "initialize":
err = s.conn.reply(m.ID, map[string]any{
"capabilities": map[string]any{
"textDocumentSync": map[string]any{"openClose": true, "change": 1, "save": map[string]any{"includeText": false}},
"completionProvider": map[string]any{
"triggerCharacters": []string{"<", ":", "\"", "/", "-"},
},
"hoverProvider": true,
},
"serverInfo": map[string]any{"name": "htmlschema-lsp"},
})
case "shutdown":
shutdown = true
err = s.conn.reply(m.ID, nil)
case "exit":
if !shutdown {
return errors.New("exit without shutdown")
}
return nil
case "textDocument/didOpen":
var p struct {
TextDocument struct {
URI string `json:"uri"`
Text string `json:"text"`
} `json:"textDocument"`
}
if json.Unmarshal(m.Params, &p) == nil {
s.docs[p.TextDocument.URI] = p.TextDocument.Text
s.lint(p.TextDocument.URI)
}
case "textDocument/didChange":
var p struct {
TextDocument struct {
URI string `json:"uri"`
} `json:"textDocument"`
ContentChanges []struct {
Text string `json:"text"`
} `json:"contentChanges"`
}
if json.Unmarshal(m.Params, &p) == nil && len(p.ContentChanges) > 0 {
// full sync - the last change is the whole document
s.docs[p.TextDocument.URI] = p.ContentChanges[len(p.ContentChanges)-1].Text
s.lint(p.TextDocument.URI)
}
case "textDocument/didSave", "textDocument/didClose":
var p struct {
TextDocument struct {
URI string `json:"uri"`
} `json:"textDocument"`
}
if json.Unmarshal(m.Params, &p) == nil {
if m.Method == "textDocument/didClose" {
delete(s.docs, p.TextDocument.URI)
}
s.lint(p.TextDocument.URI)
}
case "textDocument/completion":
var p textDocumentPositionParams
if json.Unmarshal(m.Params, &p) == nil {
err = s.conn.reply(m.ID, s.complete(p.TextDocument.URI, p.Position))
} else {
err = s.conn.reply(m.ID, nil)
}
case "textDocument/hover":
var p textDocumentPositionParams
if json.Unmarshal(m.Params, &p) == nil {
err = s.conn.reply(m.ID, s.hover(p.TextDocument.URI, p.Position))
} else {
err = s.conn.reply(m.ID, nil)
}
default:
if len(m.ID) > 0 && m.Method != "" {
err = s.conn.write(&message{ID: m.ID, Error: &responseError{Code: -32601, Message: "method not found: " + m.Method}})
}
}
if err != nil {
return err
}
}
}
func uriToPath(uri string) string {
u, err := url.Parse(uri)
if err != nil || u.Scheme != "file" {
return ""
}
return filepath.FromSlash(u.Path)
}
func pathToURI(p string) string {
return (&url.URL{Scheme: "file", Path: filepath.ToSlash(p)}).String()
}
// schemaRoot is the closest directory above the file with groups/ or default.html
func schemaRoot(file string) string {
for dir := filepath.Dir(file); ; dir = filepath.Dir(dir) {
if info, err := os.Stat(filepath.Join(dir, "groups")); err == nil && info.IsDir() {
return dir
}
if _, err := os.Stat(filepath.Join(dir, "default.html")); err == nil {
return dir
}
if parent := filepath.Dir(dir); parent == dir {
return ""
}
}
}
// lint loads the schema root of the document with all open documents and
// publishes the lint errors of every file in it
func (s *server) lint(uri string) {
file := uriToPath(uri)
root := schemaRoot(file)
if file == "" || root == "" {
return
}
overlay := map[string][]byte{}
for docURI, text := range s.docs {
if p := uriToPath(docURI); p != "" && strings.HasPrefix(p, root+string(filepath.Separator)) {
overlay[p] = []byte(text)
}
}
byURI := map[string][]diagnostic{}
_, err := htmlschema.LoadRootOverlay(root, overlay)
var lintErrors htmlschema.LintErrors
switch {
case errors.As(err, &lintErrors):
for _, e := range lintErrors {
p := filepath.Join(root, filepath.FromSlash(e.File))
text, ok := overlay[p]
if !ok {
text, _ = os.ReadFile(p)
}
fileURI := pathToURI(p)
byURI[fileURI] = append(byURI[fileURI], diagnostic{
Range: lineRange(string(text), e.Line),
Severity: severityError,
Source: "htmlschema",
Message: e.Message,
})
}
case err != nil:
byURI[uri] = append(byURI[uri], diagnostic{Severity: severityError, Source: "htmlschema", Message: err.Error()})
}
previous := s.published[root]
current := map[string]bool{}
for fileURI, diagnostics := range byURI {
current[fileURI] = true
s.publish(fileURI, diagnostics)
}
for fileURI := range previous {
if !current[fileURI] {
s.publish(fileURI, []diagnostic{})
}
}
s.published[root] = current
}
func (s *server) publish(uri string, diagnostics []diagnostic) {
_ = s.conn.notify("textDocument/publishDiagnostics", map[string]any{"uri": uri, "diagnostics": diagnostics})
}
func markdown(value string) *markupContent {
if value == "" {
return nil
}
return &markupContent{Kind: "markdown", Value: value}
}
// complete offers val:* elements, their attributes, the val: rules of html
// elements and attribute values - all only inside schema roots
func (s *server) complete(uri string, pos position) []completionItem {
file := uriToPath(uri)
root := schemaRoot(file)
text, ok := s.docs[uri]
if root == "" || !ok {
return []completionItem{}
}
off := offset(text, pos)
ctx := contextAt(text, off)
replace := textRange{Start: positionOf(text, ctx.prefixStart), End: pos}
items := []completionItem{}
switch ctx.kind {
case contextTagName:
names := make([]string, 0, len(s.elements))
for name := range s.elements {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
e := s.elements[name]
items = append(items, completionItem{
Label: name,
Kind: completionKindStruct,
Documentation: markdown(e.Doc),
InsertTextFormat: insertTextSnippet,
TextEdit: &textEdit{Range: replace, NewText: elementSnippet(e)},
})
}
case contextAttributeName:
for _, a := range s.attributesOf(ctx.tag) {
items = append(items, completionItem{
Label: a.Name,
Kind: completionKindProperty,
Documentation: markdown(a.Doc),
InsertTextFormat: insertTextSnippet,
TextEdit: &textEdit{Range: replace, NewText: attributeSnippet(a)},
})
}
case contextAttributeValue:
items = s.completeValue(ctx, root, file, text, pos)
}
return items
}
// attributesOf are the attributes a tag can take: those of a val:* element,
// or the val: rules of an html element
func (s *server) attributesOf(tag string) []htmlschema.VocabularyAttribute {
if e, ok := s.elements[tag]; ok {
return e.Attributes
}
if strings.HasPrefix(tag, "val:") {
return nil
}
return s.elementRules
}
func elementSnippet(e htmlschema.VocabularyElement) string {
attrs := ""
// the first structural attribute is the one an element is written with -
// settings have only optional ones
if len(e.Attributes) > 0 && e.Attributes[0].Structural && e.Name != "val:settings" {
attrs = " " + e.Attributes[0].Name + `="$1"`
}
if e.HasChildren {
return e.Name + attrs + ">\n\t$0\n</" + e.Name + ">"
}
return e.Name + attrs + " $0/>"
}
func attributeSnippet(a htmlschema.VocabularyAttribute) string {
switch {
case a.Boolean:
return a.Name
case strings.HasSuffix(a.Name, "attr-"):
return a.Name + `${1:content}="$2"`
case len(a.Values) > 0:
return a.Name + `="${1|` + strings.Join(a.Values, ",") + `|}"`
}
return a.Name + `="$1"`
}
func (s *server) completeValue(ctx completionContext, root, file, text string, pos position) []completionItem {
items := []completionItem{}
name := strings.TrimPrefix(ctx.attribute, "val:")
add := func(label, doc string, kind int, prefixStart int) {
items = append(items, completionItem{
Label: label,
Kind: kind,
Documentation: markdown(doc),
TextEdit: &textEdit{Range: textRange{Start: positionOf(text, prefixStart), End: pos}, NewText: label},
})
}
switch {
case name == "path" && (ctx.tag == "val:include" || ctx.tag == "val:comp"):
for _, p := range schemaFiles(root, file) {
add(p, "", completionKindFile, ctx.prefixStart)
}
case strings.HasPrefix(name, "attr-") || name == "attr" || name == "value":
// rule lists: complete the rule after the last ;
ruleStart := ctx.prefixStart
if i := strings.LastIndex(ctx.prefix, ";"); i >= 0 {
ruleStart += i + 1
for ruleStart < len(text) && text[ruleStart] == ' ' {
ruleStart++
}
}
for _, r := range s.valueRules {
add(r.Name, r.Doc, completionKindValue, ruleStart)
}
case name == "for" && ctx.tag == "val:wildcard":
add("div, span", "Skip layout wrappers.", completionKindValue, ctx.prefixStart)
add("*", "Skip any element.", completionKindValue, ctx.prefixStart)
default:
for _, a := range s.attributesOf(ctx.tag) {
if strings.TrimPrefix(a.Name, "val:") == name {
for _, v := range a.Values {
add(v, "", completionKindValue, ctx.prefixStart)
}
}
}
}
return items
}
// schemaFiles are the files of a schema root as val:include and val:comp
// paths: root relative with a leading /, without .html - the file itself is left out
func schemaFiles(root, self string) (paths []string) {
_ = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return nil
}
if strings.HasPrefix(d.Name(), ".") && p != root {
if d.IsDir() {
return filepath.SkipDir
}
return nil
}
if d.IsDir() || !strings.HasSuffix(p, ".html") || p == self {
return nil
}
rel, errRel := filepath.Rel(root, p)
if errRel == nil {
paths = append(paths, "/"+strings.TrimSuffix(filepath.ToSlash(rel), ".html"))
}
return nil
})
return paths
}
// hover explains val:* elements and rule attributes
func (s *server) hover(uri string, pos position) any {
text, ok := s.docs[uri]
if !ok || schemaRoot(uriToPath(uri)) == "" {
return nil
}
off := offset(text, pos)
word, start := wordAt(text, off)
if word == "" {
return nil
}
result := func(doc string) any {
return map[string]any{
"contents": markupContent{Kind: "markdown", Value: doc},
"range": textRange{Start: positionOf(text, start), End: positionOf(text, start+len(word))},
}
}
if e, ok := s.elements[word]; ok {
return result("**" + e.Name + "**\n\n" + e.Doc)
}
ctx := contextAt(text, start)
if ctx.kind == contextNone || ctx.kind == contextTagName {
return nil
}
for _, a := range s.attributesOf(ctx.tag) {
if a.Name == word || (strings.HasSuffix(a.Name, "attr-") && strings.HasPrefix(word, a.Name)) {
doc := a.Doc
if len(a.Values) > 0 {
doc += "\n\nValues: `" + strings.Join(a.Values, "`, `") + "`"
}
return result("**" + word + "**\n\n" + doc)
}
}
return nil
}
+187
View File
@@ -0,0 +1,187 @@
package main
import (
"bufio"
"encoding/json"
"io"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestContextAt(t *testing.T) {
for name, tc := range map[string]struct {
text string
want completionContext
}{
"tag name": {`<val:se`, completionContext{kind: contextTagName, prefix: "val:se", prefixStart: 1}},
"attribute name": {`<h1 val:sc`, completionContext{kind: contextAttributeName, tag: "h1", prefix: "val:sc", prefixStart: 4}},
"after a value": {`<meta name="x" `, completionContext{kind: contextAttributeName, tag: "meta", prefix: "", prefixStart: 15}},
"attribute value": {`<val:comp path="/par`, completionContext{kind: contextAttributeValue, tag: "val:comp", attribute: "path", prefix: "/par", prefixStart: 16}},
"> in a value": {`<a val:attr-href="regex:^a>b`, completionContext{kind: contextAttributeValue, tag: "a", attribute: "val:attr-href", prefix: "regex:^a>b", prefixStart: 18}},
"outside of tags": {`<h1/> text`, completionContext{}},
"closing tag": {`</val:cho`, completionContext{}},
"inside a comment": {`<!-- <h1 val:`, completionContext{}},
"after a comment": {`<!-- x --><h1 val:`, completionContext{kind: contextAttributeName, tag: "h1", prefix: "val:", prefixStart: 14}},
"unquoted value": {`<h1 val:score=`, completionContext{}},
"multi line": {"<title\n val:min-length=\"30\"\n val:", completionContext{kind: contextAttributeName, tag: "title", prefix: "val:", prefixStart: 35}},
} {
t.Run(name, func(t *testing.T) {
assert.Equal(t, tc.want, contextAt(tc.text, len(tc.text)))
})
}
}
func TestPositions(t *testing.T) {
text := "a\n–b😀c\nd"
// – is one utf-16 unit, 😀 two
assert.Equal(t, position{1, 4}, positionOf(text, strings.Index(text, "c")))
assert.Equal(t, strings.Index(text, "c"), offset(text, position{1, 4}))
assert.Equal(t, len(text), offset(text, position{5, 0}))
}
// client drives the server over pipes like an editor - it reads in the
// background, pipes do not buffer and the server writes notifications any time
type client struct {
t *testing.T
c *conn
id int
messages chan *message
}
func startServer(t *testing.T) *client {
serverIn, clientOut := io.Pipe()
clientIn, serverOut := io.Pipe()
s := newServer(&conn{in: bufio.NewReader(serverIn), out: serverOut})
go func() {
_ = s.run()
serverOut.Close()
}()
c := &client{t: t, c: &conn{in: bufio.NewReader(clientIn), out: clientOut}, messages: make(chan *message, 100)}
go func() {
defer close(c.messages)
for {
m, err := c.c.read()
if err != nil {
return
}
c.messages <- m
}
}()
t.Cleanup(func() { clientOut.Close() })
return c
}
func (c *client) notify(method string, params any) {
require.NoError(c.t, c.c.notify(method, params))
}
// request sends a request and returns its result, notifications in between are collected
func (c *client) request(method string, params any, notifications *[]*message) json.RawMessage {
c.id++
data, _ := json.Marshal(params)
id, _ := json.Marshal(c.id)
require.NoError(c.t, c.c.write(&message{ID: id, Method: method, Params: data}))
for {
var m *message
select {
case m = <-c.messages:
case <-time.After(5 * time.Second):
c.t.Fatal("no response to " + method)
}
require.NotNil(c.t, m, "server closed")
if m.Method != "" {
if notifications != nil {
*notifications = append(*notifications, m)
}
continue
}
result, _ := json.Marshal(m.Result)
return result
}
}
func TestServer(t *testing.T) {
root := t.TempDir()
require.NoError(t, os.MkdirAll(filepath.Join(root, "groups"), 0o755))
require.NoError(t, os.MkdirAll(filepath.Join(root, "partials"), 0o755))
require.NoError(t, os.WriteFile(filepath.Join(root, "partials", "head.html"), []byte(`<title/>`), 0o644))
file := filepath.Join(root, "groups", "page.html")
require.NoError(t, os.WriteFile(file, []byte(""), 0o644))
uri := pathToURI(file)
c := startServer(t)
c.request("initialize", map[string]any{}, nil)
c.notify("initialized", map[string]any{})
// a forgotten prefix in an unsaved buffer
text := "<html>\n <head>\n <title score=10/>\n <val:include path=\"\"/>\n </head>\n</html>\n"
c.notify("textDocument/didOpen", map[string]any{"textDocument": map[string]any{"uri": uri, "text": text}})
var notifications []*message
c.request("shutdown-probe", nil, &notifications)
require.NotEmpty(t, notifications)
var diagnostics struct {
URI string `json:"uri"`
Diagnostics []diagnostic `json:"diagnostics"`
}
require.NoError(t, json.Unmarshal(notifications[0].Params, &diagnostics))
assert.Equal(t, uri, diagnostics.URI)
require.NotEmpty(t, diagnostics.Diagnostics)
assert.Contains(t, diagnostics.Diagnostics[0].Message, `did you mean "val:score"?`)
assert.Equal(t, textRange{Start: position{2, 4}, End: position{2, 21}}, diagnostics.Diagnostics[0].Range)
// completion of include paths and of rules
pathPos := positionOf(text, strings.Index(text, `path=""`)+len(`path="`))
var items []completionItem
require.NoError(t, json.Unmarshal(c.request("textDocument/completion", map[string]any{"textDocument": map[string]any{"uri": uri}, "position": pathPos}, nil), &items))
assert.Equal(t, []string{"/partials/head"}, labels(items))
rulePos := positionOf(text, strings.Index(text, "score"))
require.NoError(t, json.Unmarshal(c.request("textDocument/completion", map[string]any{"textDocument": map[string]any{"uri": uri}, "position": rulePos}, nil), &items))
assert.Contains(t, labels(items), "val:score")
assert.Contains(t, labels(items), "val:attr-")
// hover on an element
hoverPos := positionOf(text, strings.Index(text, "val:include")+2)
var hover struct {
Contents markupContent `json:"contents"`
}
require.NoError(t, json.Unmarshal(c.request("textDocument/hover", map[string]any{"textDocument": map[string]any{"uri": uri}, "position": hoverPos}, nil), &hover))
assert.Contains(t, hover.Contents.Value, "**val:include**")
// fixing the error clears the diagnostics
fixed := strings.Replace(text, "score=10", "val:score=10", 1)
fixed = strings.Replace(fixed, `path=""`, `path="/partials/head"`, 1)
c.notify("textDocument/didChange", map[string]any{"textDocument": map[string]any{"uri": uri}, "contentChanges": []map[string]any{{"text": fixed}}})
notifications = nil
c.request("shutdown-probe", nil, &notifications)
require.NotEmpty(t, notifications)
require.NoError(t, json.Unmarshal(notifications[0].Params, &diagnostics))
assert.Empty(t, diagnostics.Diagnostics)
}
func TestServerIgnoresFilesOutsideSchemaRoots(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "page.html")
c := startServer(t)
c.request("initialize", map[string]any{}, nil)
c.notify("textDocument/didOpen", map[string]any{"textDocument": map[string]any{"uri": pathToURI(file), "text": "<h1 score=1/>"}})
var notifications []*message
var items []completionItem
result := c.request("textDocument/completion", map[string]any{"textDocument": map[string]any{"uri": pathToURI(file)}, "position": position{0, 4}}, &notifications)
require.NoError(t, json.Unmarshal(result, &items))
assert.Empty(t, items)
assert.Empty(t, notifications)
}
func labels(items []completionItem) (labels []string) {
for _, item := range items {
labels = append(labels, item.Label)
}
return labels
}
+200
View File
@@ -0,0 +1,200 @@
package main
import (
"strings"
"unicode/utf16"
"unicode/utf8"
)
// offset converts an lsp position - utf-16 code units in a line - to a byte offset
func offset(text string, pos position) int {
line := 0
i := 0
for line < pos.Line {
next := strings.IndexByte(text[i:], '\n')
if next < 0 {
return len(text)
}
i += next + 1
line++
}
units := 0
for i < len(text) && text[i] != '\n' && units < pos.Character {
r, size := utf8.DecodeRuneInString(text[i:])
units += len(utf16.Encode([]rune{r}))
i += size
}
return i
}
// positionOf converts a byte offset to an lsp position
func positionOf(text string, off int) position {
if off > len(text) {
off = len(text)
}
pos := position{}
lineStart := 0
for i := 0; i < off; i++ {
if text[i] == '\n' {
pos.Line++
lineStart = i + 1
}
}
for _, r := range text[lineStart:off] {
pos.Character += len(utf16.Encode([]rune{r}))
}
return pos
}
// lineRange is the range of a whole line, 1 based as in LintError
func lineRange(text string, line int) textRange {
lines := strings.Split(text, "\n")
if line < 1 || line > len(lines) {
return textRange{}
}
content := lines[line-1]
start := len(content) - len(strings.TrimLeft(content, " \t"))
end := len(strings.TrimRight(content, " \t\r"))
return textRange{
Start: position{Line: line - 1, Character: len(utf16.Encode([]rune(content[:start])))},
End: position{Line: line - 1, Character: len(utf16.Encode([]rune(content[:end])))},
}
}
type contextKind int
const (
contextNone contextKind = iota
contextTagName
contextAttributeName
contextAttributeValue
)
// completionContext is where the cursor is in a tag
type completionContext struct {
kind contextKind
tag string
// attribute whose value is edited
attribute string
// prefix is the partial word before the cursor, replaced by a completion
prefix string
prefixStart int
}
func isNameByte(b byte) bool {
return b == ':' || b == '-' || b == '_' || b == '.' || b == '/' ||
(b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || (b >= '0' && b <= '9')
}
// contextAt finds the tag the cursor is in - quotes are tracked, so a > in an
// attribute value does not end the tag
func contextAt(text string, off int) completionContext {
start := tagStart(text, off)
if start < 0 {
return completionContext{}
}
inner := text[start+1 : off]
if strings.HasPrefix(inner, "/") || strings.HasPrefix(inner, "!") {
return completionContext{}
}
nameEnd := strings.IndexAny(inner, " \t\r\n")
if nameEnd < 0 {
return completionContext{kind: contextTagName, prefix: inner, prefixStart: start + 1}
}
ctx := completionContext{tag: inner[:nameEnd]}
// walk the attributes, tracking quotes
var quote byte
valueStart := 0
key := ""
i := nameEnd
for i < len(inner) {
c := inner[i]
switch {
case quote != 0:
if c == quote {
quote = 0
key = ""
}
case c == '"' || c == '\'':
quote = c
valueStart = i + 1
case c == '=':
j := i - 1
for j >= 0 && (inner[j] == ' ' || inner[j] == '\t') {
j--
}
k := j
for k >= 0 && isNameByte(inner[k]) {
k--
}
key = inner[k+1 : j+1]
}
i++
}
if quote != 0 {
ctx.kind = contextAttributeValue
ctx.attribute = key
ctx.prefix = inner[valueStart:]
ctx.prefixStart = start + 1 + valueStart
return ctx
}
j := len(inner)
for j > 0 && isNameByte(inner[j-1]) {
j--
}
if j > 0 && inner[j-1] == '=' {
// after = without a quote - nothing to complete
return completionContext{}
}
ctx.kind = contextAttributeName
ctx.prefix = inner[j:]
ctx.prefixStart = start + 1 + j
return ctx
}
// tagStart scans the text up to off and returns the start of the tag the
// cursor is in, -1 outside of tags - comments and quoted values are skipped
func tagStart(text string, off int) int {
start := -1
var quote byte
for i := 0; i < off; i++ {
c := text[i]
switch {
case start < 0 && strings.HasPrefix(text[i:], "<!--"):
end := strings.Index(text[i+4:], "-->")
if end < 0 || i+4+end+3 > off {
return -1
}
i += 4 + end + 2
case start < 0:
if c == '<' {
start = i
}
case quote != 0:
if c == quote {
quote = 0
}
case c == '"' || c == '\'':
quote = c
case c == '>':
start = -1
case c == '<':
// a < in a tag starts a new one - the old one was broken
start = i
}
}
return start
}
// wordAt is the name under the cursor, for hover
func wordAt(text string, off int) (word string, start int) {
s := off
for s > 0 && isNameByte(text[s-1]) {
s--
}
e := off
for e < len(text) && isNameByte(text[e]) {
e++
}
return text[s:e], s
}
+42 -26
View File
@@ -1,8 +1,12 @@
package main
import (
"errors"
"flag"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"os"
@@ -13,40 +17,52 @@ func main() {
flagHelp := flag.Bool("help", false, "show help")
flag.Parse()
if len(flag.Args()) != 2 || *flagHelp {
fmt.Println("foomo walker validator - validate a html page against an html validaation schema")
fmt.Println("usage", os.Args[0], "path/to/schema.html", "http://server.com/doc-to-validate")
if len(flag.Args()) != 3 || *flagHelp {
fmt.Println("foomo walker validator - validate a html page against an html schema")
fmt.Println("usage:", os.Args[0], "path/to/schema-root", "group", "http://server.com/doc-to-validate|path/to/file.html")
fmt.Println("exit codes: 1 usage or schema errors, 2 page could not be loaded, 3 the page has error findings")
os.Exit(1)
}
schemaRoot, group, target := flag.Arg(0), flag.Arg(1), flag.Arg(2)
schemaFile := flag.Arg(0)
urlToValidate := flag.Arg(1)
u, errParse := url.Parse(urlToValidate)
if errParse != nil {
fmt.Println("can not parse url to validate", errParse)
os.Exit(1)
}
if u.Scheme == "" {
urlToValidate = "file://" + urlToValidate
}
fmt.Println("loading schema", schemaFile)
schema, errLoad := htmlschema.Load(schemaFile)
root, errLoad := htmlschema.LoadRoot(schemaRoot)
if errLoad != nil {
fmt.Println("could not load scheme", errLoad)
slog.Error("could not load the schema root", "root", schemaRoot)
// the lint errors, one per line - file:line message
fmt.Fprintln(os.Stderr, errLoad)
os.Exit(1)
}
fmt.Println("validating url", urlToValidate)
report, errValidate := schema.ValidateURL(
urlToValidate,
os.Stdout,
)
htmlBytes, errRead := read(target)
if errRead != nil {
slog.Error("could not load the page", "target", target, "error", errRead)
os.Exit(2)
}
report, errValidate := root.Validate(group, htmlBytes)
if errValidate != nil {
fmt.Println("could not validate", errValidate)
slog.Error("could not validate", "target", target, "error", errValidate)
os.Exit(2)
}
report.Print(os.Stdout)
if report.Count(htmlschema.SeverityError) > 0 {
os.Exit(3)
}
}
// read loads an http(s) url or a local file
func read(target string) ([]byte, error) {
u, errParse := url.Parse(target)
if errParse != nil || (u.Scheme != "http" && u.Scheme != "https") {
return os.ReadFile(target)
}
resp, errGet := http.Get(target)
if errGet != nil {
return nil, errGet
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, errors.New("unexpected status: " + resp.Status)
}
return io.ReadAll(resp.Body)
}
+7 -3
View File
@@ -1,3 +1,7 @@
target: https://github.com/foomo/walker
agent: Yandex
address: ":3001"
target: http://localhost:8080
agent: foomo walker
addr: :3001
usecookies: false
interval: 1h
schemaroot: /Users/jan/go/src/github.com/foomo/walker/htmlschema/demo/schema/
groupheader: x-next-js-app
+61 -29
View File
@@ -3,7 +3,8 @@ package main
import (
"flag"
"fmt"
"log"
"io"
"log/slog"
"net/http"
"os"
"strings"
@@ -16,8 +17,8 @@ import (
)
type server struct {
s *walker.Service
serviceProxy *walker.ServiceGoTSRPCProxy
walker *walker.Walker
conf string
reportHandler func(
w http.ResponseWriter, r *http.Request,
@@ -75,12 +76,12 @@ func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/status" {
w.Write([]byte(":::::::::::::::::: STATUS ::::::::::::::::::\n"))
w.Write([]byte("\nrunning with config:\n\n" + s.conf + "\n"))
s.s.Walker.PrintStatus(w, s.s.Walker.GetStatus())
s.walker.PrintStatus(w, s.walker.GetStatus())
return
}
switch {
case strings.HasPrefix(r.URL.Path, pathReports):
completeStatus, runningStatus := s.s.Walker.GetStatuses()
completeStatus, runningStatus := s.walker.GetStatuses()
s.reportHandler(w, r, completeStatus, runningStatus)
case strings.HasPrefix(r.URL.Path, pathService+"/"):
s.serviceProxy.ServeHTTP(w, r)
@@ -89,49 +90,80 @@ func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}
func must(comment string, err error) {
func must(msg string, err error) {
if err != nil {
fmt.Println(comment, err)
slog.Error(msg, "error", err)
os.Exit(1)
}
}
// newLogger is the slog logger of walker - text for people, the macOS app
// shows it in its log view, json for log collectors
func newLogger(level, format string) (*slog.Logger, error) {
var l slog.Level
if err := l.UnmarshalText([]byte(level)); err != nil {
return nil, fmt.Errorf("unknown log level %q - debug, info, warn or error", level)
}
opts := &slog.HandlerOptions{Level: l}
switch format {
case "text":
return slog.New(slog.NewTextHandler(os.Stderr, opts)), nil
case "json":
return slog.New(slog.NewJSONHandler(os.Stderr, opts)), nil
}
return nil, fmt.Errorf("unknown log format %q - text or json", format)
}
func main() {
exitOnStdinClose := flag.Bool("exit-on-stdin-close", false, "exit when stdin is closed - the macOS app holds it open, so walker never outlives the app")
logLevel := flag.String("log-level", "info", "debug, info, warn or error")
logFormat := flag.String("log-format", "text", "text or json")
flag.Parse()
if len(flag.Args()) != 1 {
fmt.Println("usage:", os.Args[0], "path/to/config.yaml")
fmt.Fprintln(os.Stderr, "usage:", os.Args[0], "[-exit-on-stdin-close] [-log-level info] [-log-format text] path/to/config.yaml")
os.Exit(1)
}
logger, errLogger := newLogger(*logLevel, *logFormat)
if errLogger != nil {
fmt.Fprintln(os.Stderr, errLogger)
os.Exit(1)
}
slog.SetDefault(logger)
if *exitOnStdinClose {
go func() {
_, _ = io.Copy(io.Discard, os.Stdin)
slog.Info("stdin closed, exiting")
os.Exit(0)
}()
}
conf, errConf := config.Get(flag.Arg(0))
must("config error:", errConf)
must("could not load the config", errConf)
yamlConfBytes, _ := yaml.Marshal(conf)
fmt.Println("this is how I understood your config:")
fmt.Println("------------------------------------------------------------------")
fmt.Println(string(yamlConfBytes))
fmt.Println("------------------------------------------------------------------")
s, chanLoopComplete, errS := walker.NewService(conf, nil, nil, nil, nil)
must("could not start service", errS)
slog.Info("starting walker",
"config", flag.Arg(0),
"addr", conf.Addr,
"target", conf.Target.BaseURL,
"paths", conf.Target.Paths,
"concurrency", conf.Concurrency,
"interval", conf.Interval,
"schemaroot", conf.SchemaRoot,
)
slog.Debug("config", "yaml", string(yamlConfBytes))
s, w, chanLoopComplete, errS := walker.NewService(conf, nil, nil, nil, nil)
must("could not start the service", errS)
// the scrape loop logs its cycles, completed statuses are not needed here
go func() {
for {
select {
case completeStatus := <-chanLoopComplete:
fmt.Println("a loop was completed, I walked around", len(completeStatus.Results), "docs")
if !completeStatus.NextCycle.IsZero() {
fmt.Println("next loop is scheduled at", completeStatus.NextCycle)
}
}
for range chanLoopComplete {
}
}()
log.Fatal(http.ListenAndServe(conf.Addr, &server{
err := http.ListenAndServe(conf.Addr, &server{
conf: string(yamlConfBytes),
s: s,
serviceProxy: walker.NewDefaultServiceGoTSRPCProxy(s),
walker: w,
reportHandler: reports.GetReportHandler(pathReports),
metricsHandler: s.Walker.MetricsHandler().ServeHTTP,
}))
metricsHandler: w.MetricsHandler().ServeHTTP,
})
must("could not serve on "+conf.Addr, err)
}
+1 -1
View File
@@ -20,7 +20,7 @@ ignoreallqueries: true
depth: 4
paging: false
agent: foomo-walker
address: ":3001"
addr: ":3001"
schemaroot: htmlschema/example/schema/bestbytes
...
`
+296
View File
@@ -0,0 +1,296 @@
package config
import (
"bytes"
"strconv"
"strings"
yaml "gopkg.in/yaml.v3"
)
// Form is a config as an editor shows it - every key with its value or its
// default. Durations stay strings, as written.
type Form struct {
BaseURL string `json:"baseURL"`
Paths []string `json:"paths"`
Concurrency int `json:"concurrency"`
Addr string `json:"addr"`
Agent string `json:"agent"`
UseCookies bool `json:"useCookies"`
Ignore []string `json:"ignore"`
IgnoreQueriesWith []string `json:"ignoreQueriesWith"`
IgnoreAllQueries bool `json:"ignoreAllQueries"`
IgnoreRobots bool `json:"ignoreRobots"`
Depth int `json:"depth"`
Paging bool `json:"paging"`
GroupHeader string `json:"groupHeader"`
SchemaRoot string `json:"schemaRoot"`
Interval string `json:"interval"`
Offset string `json:"offset"`
}
// DefaultForm has the defaults of Load
func DefaultForm() Form {
return Form{
Concurrency: 2,
Addr: ":3001",
Agent: "foomo-walker",
UseCookies: true,
Paths: []string{},
Ignore: []string{},
IgnoreQueriesWith: []string{},
}
}
// ReadForm reads a config into a form - leniently, a value of the wrong
// type keeps its default, Validate reports it
func ReadForm(data []byte) (Form, error) {
form := DefaultForm()
root, err := mappingRoot(data)
if err != nil || root == nil {
return form, err
}
for i := 0; i+1 < len(root.Content); i += 2 {
key, n := root.Content[i].Value, root.Content[i+1]
switch key {
case "target":
readTarget(&form, n)
case "concurrency":
readInt(n, &form.Concurrency)
case "depth":
readInt(n, &form.Depth)
case "addr":
form.Addr = scalar(n, form.Addr)
case "agent":
form.Agent = scalar(n, form.Agent)
case "groupheader":
form.GroupHeader = scalar(n, form.GroupHeader)
case "schemaroot":
form.SchemaRoot = scalar(n, form.SchemaRoot)
case "interval":
form.Interval = scalar(n, form.Interval)
case "offset":
form.Offset = scalar(n, form.Offset)
case "usecookies":
readBool(n, &form.UseCookies)
case "ignoreallqueries":
readBool(n, &form.IgnoreAllQueries)
case "ignorerobots":
readBool(n, &form.IgnoreRobots)
case "paging":
readBool(n, &form.Paging)
case "ignore":
form.Ignore = stringList(n)
case "ignorequerieswith":
form.IgnoreQueriesWith = stringList(n)
}
}
return form, nil
}
// WriteForm writes a form into a config. The existing yaml is edited in place:
// comments, key order and keys the form does not know survive. New keys are
// appended, keys that are absent and at their default stay absent.
func WriteForm(data []byte, form Form) ([]byte, error) {
var doc yaml.Node
if err := yaml.Unmarshal(data, &doc); err != nil {
return nil, err
}
if len(doc.Content) == 0 {
doc = yaml.Node{Kind: yaml.DocumentNode, Content: []*yaml.Node{{Kind: yaml.MappingNode}}}
}
root := doc.Content[0]
if root.Kind != yaml.MappingNode {
root.Kind, root.Tag, root.Value, root.Content = yaml.MappingNode, "", "", nil
}
defaults := DefaultForm()
w := &formWriter{root: root}
w.target(form)
w.int("concurrency", form.Concurrency, defaults.Concurrency)
w.str("addr", form.Addr, defaults.Addr)
w.str("agent", form.Agent, defaults.Agent)
w.bool("usecookies", form.UseCookies, defaults.UseCookies)
w.strings("ignore", form.Ignore)
w.strings("ignorequerieswith", form.IgnoreQueriesWith)
w.bool("ignoreallqueries", form.IgnoreAllQueries, defaults.IgnoreAllQueries)
w.bool("ignorerobots", form.IgnoreRobots, defaults.IgnoreRobots)
w.int("depth", form.Depth, defaults.Depth)
w.bool("paging", form.Paging, defaults.Paging)
w.str("groupheader", form.GroupHeader, "")
w.str("schemaroot", form.SchemaRoot, "")
w.str("interval", form.Interval, "")
w.str("offset", form.Offset, "")
buf := &bytes.Buffer{}
encoder := yaml.NewEncoder(buf)
encoder.SetIndent(2)
if err := encoder.Encode(&doc); err != nil {
return nil, err
}
if err := encoder.Close(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
type formWriter struct {
root *yaml.Node
}
// value is the value node of key, nil if the key is not there
func (w *formWriter) value(key string) *yaml.Node {
for i := 0; i+1 < len(w.root.Content); i += 2 {
if w.root.Content[i].Value == key {
return w.root.Content[i+1]
}
}
return nil
}
func (w *formWriter) remove(key string) {
for i := 0; i+1 < len(w.root.Content); i += 2 {
if w.root.Content[i].Value == key {
w.root.Content = append(w.root.Content[:i], w.root.Content[i+2:]...)
return
}
}
}
// set replaces the value of key in place - its comments stay - or appends it
func (w *formWriter) set(key string, value *yaml.Node) {
for i := 0; i+1 < len(w.root.Content); i += 2 {
k, n := w.root.Content[i], w.root.Content[i+1]
if k.Value != key {
continue
}
head, line, foot := n.HeadComment, n.LineComment, n.FootComment
changesKind := n.Kind != value.Kind
*n = *value
n.HeadComment, n.FootComment = head, foot
if changesKind && value.Kind != yaml.ScalarNode {
// a list or mapping would write the comment at its end - it belongs to the key line
if k.LineComment == "" {
k.LineComment = line
}
} else {
n.LineComment = line
}
return
}
w.root.Content = append(w.root.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: key}, value)
}
func (w *formWriter) str(key, value, defaultValue string) {
switch {
case w.value(key) == nil && value == defaultValue:
case value == "" && defaultValue == "":
w.remove(key)
default:
w.set(key, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: value})
}
}
func (w *formWriter) int(key string, value, defaultValue int) {
if w.value(key) == nil && value == defaultValue {
return
}
w.set(key, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!int", Value: strconv.Itoa(value)})
}
func (w *formWriter) bool(key string, value, defaultValue bool) {
if w.value(key) == nil && value == defaultValue {
return
}
w.set(key, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!bool", Value: strconv.FormatBool(value)})
}
func (w *formWriter) strings(key string, values []string) {
if len(values) == 0 {
w.remove(key)
return
}
w.set(key, sequence(values))
}
// target is a plain url, or a mapping when there are paths
func (w *formWriter) target(form Form) {
if len(form.Paths) == 0 {
w.set("target", &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: form.BaseURL})
return
}
w.set("target", &yaml.Node{Kind: yaml.MappingNode, Content: []*yaml.Node{
{Kind: yaml.ScalarNode, Tag: "!!str", Value: "baseurl"},
{Kind: yaml.ScalarNode, Tag: "!!str", Value: form.BaseURL},
{Kind: yaml.ScalarNode, Tag: "!!str", Value: "paths"},
sequence(form.Paths),
}})
}
func sequence(values []string) *yaml.Node {
n := &yaml.Node{Kind: yaml.SequenceNode}
for _, v := range values {
n.Content = append(n.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: v})
}
return n
}
func mappingRoot(data []byte) (*yaml.Node, error) {
var doc yaml.Node
if err := yaml.Unmarshal(data, &doc); err != nil {
return nil, err
}
if len(doc.Content) == 0 || doc.Content[0].Kind != yaml.MappingNode {
return nil, nil
}
return doc.Content[0], nil
}
func readTarget(form *Form, n *yaml.Node) {
switch n.Kind {
case yaml.ScalarNode:
form.BaseURL = n.Value
case yaml.MappingNode:
for i := 0; i+1 < len(n.Content); i += 2 {
switch strings.ToLower(n.Content[i].Value) {
case "baseurl":
form.BaseURL = scalar(n.Content[i+1], form.BaseURL)
case "paths":
form.Paths = stringList(n.Content[i+1])
}
}
}
}
func scalar(n *yaml.Node, fallback string) string {
if n.Kind != yaml.ScalarNode {
return fallback
}
return n.Value
}
func readInt(n *yaml.Node, target *int) {
if v, err := strconv.Atoi(n.Value); n.Kind == yaml.ScalarNode && err == nil {
*target = v
}
}
func readBool(n *yaml.Node, target *bool) {
var b bool
if n.Kind == yaml.ScalarNode && n.Decode(&b) == nil {
*target = b
}
}
func stringList(n *yaml.Node) []string {
list := []string{}
if n.Kind != yaml.SequenceNode {
return list
}
for _, item := range n.Content {
if item.Kind == yaml.ScalarNode {
list = append(list, item.Value)
}
}
return list
}
+335
View File
@@ -0,0 +1,335 @@
package config
import (
"errors"
"fmt"
"io/fs"
"net"
"net/url"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/foomo/walker/htmlschema"
yaml "gopkg.in/yaml.v3"
)
const (
SeverityError = "error"
SeverityWarning = "warning"
SeverityInfo = "info"
)
// Problem is something wrong or doubtful in a config file
type Problem struct {
Severity string `json:"severity"`
// Key is the config key the problem is about, "" for the whole file
Key string `json:"key"`
Line int `json:"line"`
Column int `json:"column"`
Message string `json:"message"`
}
func (p Problem) String() string {
return fmt.Sprintf("%d:%d %s %s", p.Line, p.Column, p.Severity, p.Message)
}
type keyType int
const (
typeString keyType = iota
typeInt
typeBool
typeStrings
typeDuration
typeTarget
)
// keys are the config keys - yaml.v3 matches the lower case field names exactly
var keys = map[string]keyType{
"concurrency": typeInt,
"addr": typeString,
"target": typeTarget,
"ignore": typeStrings,
"ignorequerieswith": typeStrings,
"ignoreallqueries": typeBool,
"usecookies": typeBool,
"depth": typeInt,
"paging": typeBool,
"ignorerobots": typeBool,
"groupheader": typeString,
"agent": typeString,
"schemaroot": typeString,
"interval": typeDuration,
"offset": typeDuration,
}
// Validate checks a config file: unknown keys, types, values and the
// schema root - relative paths are resolved against base, the directory of
// the config file. Every problem has the line it is about.
func Validate(data []byte, base string) []Problem {
v := &validator{}
var doc yaml.Node
if err := yaml.Unmarshal(data, &doc); err != nil {
return []Problem{yamlProblem(err)}
}
if len(doc.Content) == 0 {
return []Problem{{Severity: SeverityError, Key: "target", Line: 1, Column: 1, Message: "the config is empty - target is required"}}
}
root := doc.Content[0]
if root.Kind != yaml.MappingNode {
return []Problem{{Severity: SeverityError, Line: root.Line, Column: root.Column, Message: "the config has to be a mapping of keys"}}
}
values := map[string]*yaml.Node{}
for i := 0; i+1 < len(root.Content); i += 2 {
k, value := root.Content[i], root.Content[i+1]
key := k.Value
if first, ok := values[key]; ok {
v.add(SeverityError, key, k, fmt.Sprintf("%s is set twice, first in line %d", key, first.Line))
continue
}
values[key] = value
t, known := keys[key]
if !known {
v.unknown(key, k)
continue
}
v.check(key, t, value)
}
target, ok := values["target"]
if !ok {
v.problems = append(v.problems, Problem{Severity: SeverityError, Key: "target", Line: root.Line, Column: root.Column, Message: "target is required - the url to crawl"})
} else {
v.target(target)
}
v.schema(values, base)
// the validator and walker must never disagree
if _, err := Load(data); err != nil && !v.hasErrors() {
v.problems = append(v.problems, Problem{Severity: SeverityError, Line: root.Line, Column: root.Column, Message: err.Error()})
}
sort.SliceStable(v.problems, func(i, j int) bool { return v.problems[i].Line < v.problems[j].Line })
return v.problems
}
type validator struct {
problems []Problem
}
func (v *validator) add(severity, key string, n *yaml.Node, message string) {
v.problems = append(v.problems, Problem{Severity: severity, Key: key, Line: n.Line, Column: n.Column, Message: message})
}
func (v *validator) hasErrors() bool {
for _, p := range v.problems {
if p.Severity == SeverityError {
return true
}
}
return false
}
// unknown reports a key walker ignores - with a suggestion if one is close
func (v *validator) unknown(key string, n *yaml.Node) {
lower := strings.ToLower(key)
if _, ok := keys[lower]; ok && lower != key {
v.add(SeverityWarning, key, n, fmt.Sprintf("unknown key %q is ignored - keys are lower case: %q", key, lower))
return
}
best, distance := "", 4
for known := range keys {
if d := editDistance(lower, known); d < distance || (d == distance && known < best) {
best, distance = known, d
}
}
if best != "" {
v.add(SeverityWarning, key, n, fmt.Sprintf("unknown key %q is ignored - did you mean %q?", key, best))
return
}
v.add(SeverityWarning, key, n, fmt.Sprintf("unknown key %q is ignored", key))
}
func (v *validator) check(key string, t keyType, n *yaml.Node) {
switch t {
case typeString:
if n.Kind != yaml.ScalarNode {
v.add(SeverityError, key, n, key+" has to be a string")
return
}
if key == "addr" {
if _, _, err := net.SplitHostPort(n.Value); err != nil {
v.add(SeverityError, key, n, fmt.Sprintf("addr %q has to be host:port, e.g. \":3001\"", n.Value))
}
}
case typeInt:
value, err := strconv.Atoi(n.Value)
if n.Kind != yaml.ScalarNode || err != nil {
v.add(SeverityError, key, n, key+" has to be a number")
return
}
if key == "concurrency" && value < 1 {
v.add(SeverityError, key, n, "concurrency has to be at least 1")
}
if key == "concurrency" && value > 20 {
v.add(SeverityWarning, key, n, fmt.Sprintf("concurrency %d can take a site down", value))
}
if key == "depth" && value < 0 {
v.add(SeverityError, key, n, "depth must not be negative")
}
case typeBool:
var b bool
if n.Kind != yaml.ScalarNode || n.Decode(&b) != nil {
v.add(SeverityError, key, n, key+" has to be true or false")
}
case typeStrings:
if n.Kind != yaml.SequenceNode {
v.add(SeverityError, key, n, key+" has to be a list")
return
}
for _, item := range n.Content {
if item.Kind != yaml.ScalarNode {
v.add(SeverityError, key, item, key+" entries have to be strings")
continue
}
if key == "ignore" && !strings.HasPrefix(item.Value, "/") {
v.add(SeverityWarning, key, item, fmt.Sprintf("ignore %q is a path prefix and should start with /", item.Value))
}
}
case typeDuration:
if n.Kind != yaml.ScalarNode {
v.add(SeverityError, key, n, key+" has to be a duration like 1h or 30m")
return
}
// yaml can not read a plain number into a duration - walker would not start
if _, err := strconv.ParseInt(n.Value, 10, 64); err == nil && n.Value != "0" {
v.add(SeverityError, key, n, fmt.Sprintf("%s %s is a plain number - write a duration like 1h or 30m", key, n.Value))
return
}
if d, err := time.ParseDuration(n.Value); err != nil && n.Value != "0" {
v.add(SeverityError, key, n, fmt.Sprintf("%s %q is no duration - e.g. 1h, 30m, 90s", key, n.Value))
} else if d < 0 {
v.add(SeverityError, key, n, key+" must not be negative")
}
}
}
func (v *validator) target(n *yaml.Node) {
switch n.Kind {
case yaml.ScalarNode:
v.url("target", n)
case yaml.MappingNode:
hasBaseURL := false
for i := 0; i+1 < len(n.Content); i += 2 {
k, value := n.Content[i], n.Content[i+1]
switch strings.ToLower(k.Value) {
case "baseurl":
hasBaseURL = true
if value.Kind != yaml.ScalarNode {
v.add(SeverityError, "target", value, "target.baseurl has to be a url")
continue
}
v.url("target", value)
case "paths":
if value.Kind != yaml.SequenceNode {
v.add(SeverityError, "target", value, "target.paths has to be a list of paths")
continue
}
for _, p := range value.Content {
if !strings.HasPrefix(p.Value, "/") {
v.add(SeverityWarning, "target", p, fmt.Sprintf("path %q should start with /", p.Value))
}
}
default:
v.add(SeverityWarning, "target", k, fmt.Sprintf("unknown key target.%s is ignored - target takes baseurl and paths", k.Value))
}
}
if !hasBaseURL {
v.add(SeverityError, "target", n, "target needs a baseurl")
}
default:
v.add(SeverityError, "target", n, "target has to be a url or a mapping with baseurl and paths")
}
}
func (v *validator) url(key string, n *yaml.Node) {
u, err := url.Parse(n.Value)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
v.add(SeverityError, key, n, fmt.Sprintf("%q is not an absolute http(s) url", n.Value))
}
}
// schema checks the schema root and its interplay with the group header
func (v *validator) schema(values map[string]*yaml.Node, base string) {
root, hasRoot := values["schemaroot"]
header, hasHeader := values["groupheader"]
if hasHeader && !hasRoot && header.Value != "" {
v.add(SeverityInfo, "groupheader", header, "the group header is only used together with a schemaroot")
}
if !hasRoot || root.Kind != yaml.ScalarNode || root.Value == "" {
return
}
if !hasHeader || header.Value == "" {
v.add(SeverityInfo, "schemaroot", root, "without a groupheader every page is validated with default.html")
}
dir := root.Value
if !filepath.IsAbs(dir) && base != "" {
dir = filepath.Join(base, dir)
}
info, err := os.Stat(dir)
switch {
case errors.Is(err, fs.ErrNotExist):
v.add(SeverityError, "schemaroot", root, fmt.Sprintf("schemaroot %s does not exist", dir))
return
case err != nil:
// e.g. a sandboxed helper of the desktop app
v.add(SeverityInfo, "schemaroot", root, fmt.Sprintf("schemaroot %s could not be checked: %s", dir, err))
return
case !info.IsDir():
v.add(SeverityError, "schemaroot", root, fmt.Sprintf("schemaroot %s is not a directory", dir))
return
}
_, errLoad := htmlschema.LoadRoot(dir)
var lintErrors htmlschema.LintErrors
switch {
case errors.As(errLoad, &lintErrors):
for _, e := range lintErrors {
v.add(SeverityError, "schemaroot", root, fmt.Sprintf("schema %s:%d: %s", e.File, e.Line, e.Message))
}
case errLoad != nil:
v.add(SeverityInfo, "schemaroot", root, fmt.Sprintf("schemaroot %s could not be loaded: %s", dir, errLoad))
}
}
var yamlLine = regexp.MustCompile(`line (\d+)`)
// yamlProblem turns a yaml syntax error into a problem with its line
func yamlProblem(err error) Problem {
p := Problem{Severity: SeverityError, Line: 1, Column: 1, Message: err.Error()}
if m := yamlLine.FindStringSubmatch(err.Error()); m != nil {
p.Line, _ = strconv.Atoi(m[1])
}
return p
}
func editDistance(a, b string) int {
prev := make([]int, len(b)+1)
for j := range prev {
prev[j] = j
}
for i := 1; i <= len(a); i++ {
cur := make([]int, len(b)+1)
cur[0] = i
for j := 1; j <= len(b); j++ {
cost := 1
if a[i-1] == b[j-1] {
cost = 0
}
cur[j] = min(prev[j]+1, cur[j-1]+1, prev[j-1]+cost)
}
prev = cur
}
return prev[len(b)]
}
+128
View File
@@ -0,0 +1,128 @@
package config
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type problem struct {
severity string
key string
line int
}
func problems(list []Problem) (result []problem) {
for _, p := range list {
result = append(result, problem{p.Severity, p.Key, p.Line})
}
return result
}
func TestValidate(t *testing.T) {
for name, tc := range map[string]struct {
yaml string
want []problem
text string
}{
"minimal": {"target: https://www.bestbytes.de\n", nil, ""},
// the fixture of config_test.go points to a schema root that is gone
"complex": {confComplexTarget, []problem{{SeverityInfo, "schemaroot", 14}, {SeverityError, "schemaroot", 14}}, "without a groupheader"},
"typo address": {"target: https://example.com\nagent: Yandex\naddress: \":3001\"\n", []problem{{SeverityWarning, "address", 3}}, `did you mean "addr"?`},
"upper case key": {"Target: https://example.com\ntarget: https://example.com\n", []problem{{SeverityWarning, "Target", 1}}, `keys are lower case: "target"`},
"missing target": {"concurrency: 2\n", []problem{{SeverityError, "target", 1}}, "target is required"},
"relative target": {"target: /foo\n", []problem{{SeverityError, "target", 1}}, "not an absolute http(s) url"},
"concurrency zero": {"target: https://example.com\nconcurrency: 0\n", []problem{{SeverityError, "concurrency", 2}}, "at least 1"},
"not a number": {"target: https://example.com\ndepth: deep\n", []problem{{SeverityError, "depth", 2}}, "has to be a number"},
"bad duration": {"target: https://example.com\ninterval: 1 hour\n", []problem{{SeverityError, "interval", 2}}, "is no duration"},
"plain number": {"target: https://example.com\ninterval: 3600\n", []problem{{SeverityError, "interval", 2}}, "plain number"},
"offset too big": {"target: https://example.com\ninterval: 1h\noffset: 2h\n", []problem{{SeverityError, "", 1}}, "offset must be"},
"bad addr": {"target: https://example.com\naddr: 3001\n", []problem{{SeverityError, "addr", 2}}, "host:port"},
"ignore prefix": {"target: https://example.com\nignore:\n - /ok\n - nope\n", []problem{{SeverityWarning, "ignore", 4}}, "should start with /"},
"duplicate key": {"target: https://example.com\ndepth: 1\ndepth: 2\n", []problem{{SeverityError, "depth", 3}}, "set twice, first in line 2"},
"target mapping": {"target:\n baseurl: https://example.com\n path:\n - /\n", []problem{{SeverityWarning, "target", 3}}, "target.path is ignored"},
"yaml syntax": {"target: https://example.com\n depth: [\n", []problem{{SeverityError, "", 2}}, ""},
"header only": {"target: https://example.com\ngroupheader: x-group\n", []problem{{SeverityInfo, "groupheader", 2}}, "only used together with a schemaroot"},
} {
t.Run(name, func(t *testing.T) {
list := Validate([]byte(tc.yaml), "")
assert.Equal(t, tc.want, problems(list))
if tc.text != "" && len(list) > 0 {
assert.Contains(t, list[0].Message, tc.text)
}
})
}
}
func TestValidateSchemaRoot(t *testing.T) {
base := t.TempDir()
require.NoError(t, os.MkdirAll(filepath.Join(base, "schema"), 0o755))
require.NoError(t, os.WriteFile(filepath.Join(base, "schema", "default.html"), []byte("<html><body><h1 score=1/></body></html>"), 0o644))
// relative to the config file, with the lint errors of the schema
list := Validate([]byte("target: https://example.com\ngroupheader: x-group\nschemaroot: schema\n"), base)
require.Len(t, list, 1)
assert.Equal(t, problem{SeverityError, "schemaroot", 3}, problems(list)[0])
assert.Contains(t, list[0].Message, `schema default.html:1: attribute "score" looks like a rule`)
list = Validate([]byte("target: https://example.com\nschemaroot: nope\n"), base)
assert.Equal(t, []problem{{SeverityInfo, "schemaroot", 2}, {SeverityError, "schemaroot", 2}}, problems(list))
}
func TestFormRoundTrip(t *testing.T) {
yaml := `# crawl the shop
target: https://example.com # production
concurrency: 1
unknownkey: stays
interval: 1h
`
form, err := ReadForm([]byte(yaml))
require.NoError(t, err)
assert.Equal(t, "https://example.com", form.BaseURL)
assert.Equal(t, 1, form.Concurrency)
assert.Equal(t, ":3001", form.Addr, "defaults for keys that are not there")
assert.True(t, form.UseCookies)
assert.Equal(t, "1h", form.Interval)
form.Concurrency = 4
form.Paths = []string{"/shop", "/blog"}
form.Ignore = []string{"/admin"}
form.Interval = ""
written, err := WriteForm([]byte(yaml), form)
require.NoError(t, err)
out := string(written)
assert.Contains(t, out, "# crawl the shop")
assert.Contains(t, out, "unknownkey: stays")
assert.Contains(t, out, "concurrency: 4")
assert.Contains(t, out, "ignore:\n - /admin")
assert.NotContains(t, out, "interval", "an emptied optional key is removed")
assert.NotContains(t, out, "addr", "defaults that were not there stay out")
// it reads back the same, and walker loads it
again, err := ReadForm(written)
require.NoError(t, err)
assert.Equal(t, form, again)
conf, err := Load(written)
require.NoError(t, err)
assert.Equal(t, []string{"/shop", "/blog"}, conf.Target.Paths)
}
func TestFormTargetComment(t *testing.T) {
form, _ := ReadForm([]byte("target: https://example.com # prod\nfoo: bar\n"))
form.Paths = []string{"/shop"}
written, err := WriteForm([]byte("target: https://example.com # prod\nfoo: bar\n"), form)
require.NoError(t, err)
assert.Equal(t, "target: # prod\n baseurl: https://example.com\n paths:\n - /shop\nfoo: bar\n", string(written))
}
func TestFormNewFile(t *testing.T) {
form := DefaultForm()
form.BaseURL = "https://example.com"
written, err := WriteForm(nil, form)
require.NoError(t, err)
assert.Equal(t, "target: https://example.com\n", string(written))
assert.Empty(t, Validate(written, ""))
}
+3
View File
@@ -0,0 +1,3 @@
target/
extension.wasm
Cargo.lock
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "zed-htmlschema"
version = "0.1.0"
# edition 2024 brings resolver 3: dependencies are resolved for rust-version
edition = "2024"
rust-version = "1.85"
publish = false
[lib]
path = "src/lib.rs"
crate-type = ["cdylib"]
[dependencies]
zed_extension_api = "0.7.0"
+39
View File
@@ -0,0 +1,39 @@
# htmlschema for Zed
Completion, hover docs and live lint diagnostics for htmlschema files - the
`val:*` elements, the `val:` rules of html elements, attribute values like
`severity`, `val:include`/`val:comp` paths and attribute rule lists.
The extension starts `htmlschema-lsp` (`cmd/htmlschema-lsp`). It runs next to
Zed's html language server and only acts on files inside a schema root - a
directory with `groups/` or `default.html` - every other html file is left alone.
## Install
1. Install the language server on your PATH, from the walker repository:
```sh
go install ./cmd/htmlschema-lsp
```
2. In Zed: `zed: install dev extension` and choose this directory
(`editors/zed-htmlschema`). Zed builds it with your rustup toolchain.
3. Open a schema file, e.g. `htmlschema/demo/schema/groups/product.html`.
If the server does not start for html files, enable it explicitly in the
settings:
```json
{
"languages": {
"HTML": {
"language_servers": ["htmlschema-lsp", "..."]
}
}
}
```
Logs: `zed: open log`, or `debug: open language server logs`.
After changes to the server run `go install ./cmd/htmlschema-lsp` again and
`editor: restart language server`.
+13
View File
@@ -0,0 +1,13 @@
id = "htmlschema"
name = "htmlschema"
description = "Completion, hover and lint diagnostics for foomo walker htmlschema files"
version = "0.1.0"
schema_version = 1
authors = ["Jan Halfar <jan@bestbytes.com>"]
repository = "https://github.com/foomo/walker"
# runs next to the html language server - it only acts on files in schema
# roots, directories with groups/ or default.html
[language_servers.htmlschema-lsp]
name = "htmlschema"
languages = ["HTML"]
+28
View File
@@ -0,0 +1,28 @@
use zed_extension_api::{self as zed, LanguageServerId, Result};
/// HtmlSchemaExtension starts htmlschema-lsp from the PATH - the language
/// server is a go binary of the walker repository
struct HtmlSchemaExtension;
impl zed::Extension for HtmlSchemaExtension {
fn new() -> Self {
HtmlSchemaExtension
}
fn language_server_command(
&mut self,
_language_server_id: &LanguageServerId,
worktree: &zed::Worktree,
) -> Result<zed::Command> {
let command = worktree.which("htmlschema-lsp").ok_or_else(|| {
"htmlschema-lsp is not on the PATH - install it from the walker repository with: go install ./cmd/htmlschema-lsp".to_string()
})?;
Ok(zed::Command {
command,
args: vec![],
env: worktree.shell_env(),
})
}
}
zed::register_extension!(HtmlSchemaExtension);
+6 -2
View File
@@ -2,7 +2,7 @@ package walker
import (
"encoding/json"
"fmt"
"log/slog"
"strings"
"github.com/PuerkitoBio/goquery"
@@ -40,7 +40,11 @@ func ExtractStructure(doc *goquery.Document) (s vo.Structure, err error) {
ld := &vo.LinkedData{}
errDoc := json.Unmarshal([]byte(sel.Text()), &ld)
if errDoc != nil {
fmt.Println("json crap", errDoc)
attrs := []any{"error", errDoc}
if doc.Url != nil {
attrs = append(attrs, "url", doc.Url.String())
}
slog.Debug("skipping invalid JSON-LD", attrs...)
return
}
s.LinkedData = append(s.LinkedData, *ld)
+10 -7
View File
@@ -4,33 +4,36 @@ go 1.27
require (
github.com/PuerkitoBio/goquery v1.8.0
github.com/andybalholm/cascadia v1.3.1
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc
github.com/foomo/gotsrpc/v2 v2.16.2
github.com/foomo/gotsrpc/v3 v3.2.0
github.com/pkg/errors v0.9.1
github.com/prometheus/client_golang v1.23.2
github.com/stretchr/testify v1.12.1
github.com/temoto/robotstxt v1.1.1
github.com/valyala/gorpc v0.0.0-20160519171614-908281bef774
golang.org/x/net v0.46.0
gopkg.in/yaml.v3 v3.0.1
)
require (
github.com/andybalholm/cascadia v1.3.1 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/foomo/go v0.17.1 // indirect
github.com/go-logr/logr v1.4.4 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/kylelemons/godebug v1.1.0 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.67.4 // indirect
github.com/prometheus/procfs v0.19.2 // indirect
github.com/rogpeppe/go-internal v1.14.1 // indirect
github.com/ugorji/go/codec v1.3.2 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/otel v1.46.0 // indirect
go.opentelemetry.io/otel/metric v1.46.0 // indirect
go.opentelemetry.io/otel/trace v1.46.0 // indirect
go.yaml.in/yaml/v2 v2.4.3 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/mod v0.41.0 // indirect
golang.org/x/sys v0.48.0 // indirect
google.golang.org/protobuf v1.36.11 // indirect
)
+22 -2
View File
@@ -10,15 +10,23 @@ github.com/buger/jsonparser v1.1.2 h1:frqHqw7otoVbk5M8LlE/L7HTnIq2v9RX6EJ48i9AxJ
github.com/buger/jsonparser v1.1.2/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/foomo/go v0.17.1 h1:tDrovWbh1dOzsBX19pII6nAPIECswhBmNSPEGBYNawY=
github.com/foomo/go v0.17.1/go.mod h1:Zz5aBFte6ayLEJ17n4L1bqYmEEja9xTeLKC0Z1wAy+0=
github.com/foomo/gotsrpc/v2 v2.16.2 h1:b1LK4dUEq1wZw+SV9Vt8hIFwKA03JSwmbxhbCXrGdoU=
github.com/foomo/gotsrpc/v2 v2.16.2/go.mod h1:/YWfjIxp1CnkTZLOaMhqD/jj2tbHe6Goce7mbxuLb10=
github.com/foomo/gotsrpc/v3 v3.2.0 h1:5rAIHPzUMZKjOPys2q4XoAbxICFEkCNwPSjRKuJuKTU=
github.com/foomo/gotsrpc/v3 v3.2.0/go.mod h1:6tfZB2HQ0cgZD54cVl2FcA0D9qeSD8VESdnsuHJu+gg=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/invopop/jsonschema v0.14.0 h1:MHQqLhvpNUZfw+hM3AZDYK7jxO8FZoQeQM77g8iyZjg=
github.com/invopop/jsonschema v0.14.0/go.mod h1:ygm6C2EaVNMBDPpaPlnOA2pFAxBnxGjFlMZABxm9n2I=
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
@@ -58,6 +66,18 @@ github.com/ugorji/go/codec v1.3.2 h1:zkEASHHyEClGeURfgNT9PJZVfAbs9oEX9QXggwWNJbc
github.com/ugorji/go/codec v1.3.2/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
github.com/valyala/gorpc v0.0.0-20160519171614-908281bef774 h1:SUHFQHAaySqF0YHCmmm0EIFooFZpDPpi5KTom7YJ07c=
github.com/valyala/gorpc v0.0.0-20160519171614-908281bef774/go.mod h1:8uNqM1i7pr0jO7gdvbNCgsSa8Ki2vMh7JCQxO9BlF90=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc=
go.opentelemetry.io/otel v1.46.0/go.mod h1:Gj3SEScelsNC45tp4nSxRYlS+f5iez7W8XPMCt905kE=
go.opentelemetry.io/otel/metric v1.46.0 h1:yBnkXvgV7AXFILZc5K6IZe/CBFF3OS7BJ8ov6/lj0K8=
go.opentelemetry.io/otel/metric v1.46.0/go.mod h1:iPmdWqifKUdzziPkvvzIJXITl56fQx2mGM/DHLB3/2o=
go.opentelemetry.io/otel/sdk v1.46.0 h1:h5CNQQjEbuQXY/JfZtgt3i7HVFV3aHPO2OAwO2eTYPI=
go.opentelemetry.io/otel/sdk v1.46.0/go.mod h1:GAERFXFt5SYCEB+YiKUbMBeza6UaDH7GmGOZEfh2gSM=
go.opentelemetry.io/otel/sdk/metric v1.46.0 h1:0piZ26EG4RBfebb2jhDH6ERCYHoVWduc3kLgPCwSnSE=
go.opentelemetry.io/otel/sdk/metric v1.46.0/go.mod h1:I1PbKrdVc8Qu8HYVDNtqVIwLwjNrhsV/uFuxfwg8mO4=
go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu60qs1c=
go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
+23
View File
@@ -0,0 +1,23 @@
module: ./
runtime: macos/Walker/Generated/GotsRPC.swift
services:
github.com/foomo/walker:
out: macos/Walker/Generated/ServiceClient.swift
namespace: WalkerClient
services:
/service: Service
mappings:
github.com/foomo/walker/vo:
out: macos/Walker/Generated/WalkerVo.swift
namespace: WalkerVO
github.com/foomo/walker/htmlschema:
out: macos/Walker/Generated/HTMLSchemaVO.swift
namespace: HTMLSchemaVO
github.com/foomo/walker:
out: macos/Walker/Generated/Walker.swift
namespace: Walker
time:
out: macos/Walker/Generated/GoTime.swift
namespace: GoTime
+11
View File
@@ -0,0 +1,11 @@
module:
name: github.com/foomo/walker
path: ./
targets:
basic:
services:
/service: Service
package: github.com/foomo/walker
tsrpc:
- Service
-30
View File
@@ -1,30 +0,0 @@
module:
name: github.com/foomo/walker
path: ./
swift:
runtime: ./swift/GotsRPC.swift
targets:
basic:
services:
/service: Service
package: github.com/foomo/walker
swift:
out: ./swift/ServiceClient.swift
tsrpc:
- Service
mappings:
github.com/foomo/walker/vo:
swift:
out: ./swift/VO.swift
github.com/foomo/walker:
swift:
out: ./swift/VoWalker.swift
github.com/foomo/walker/htmlschema:
swift:
out: ./swift/VoSchema.swift
time:
swift:
out: ./swift/VoTime.swift
+212 -186
View File
@@ -1,43 +1,50 @@
// Code generated by gotsrpc https://github.com/foomo/gotsrpc/v2 - DO NOT EDIT.
// Code generated by gotsrpc https://github.com/foomo/gotsrpc/v3 - DO NOT EDIT.
package walker
import (
"io"
http "net/http"
time "time"
gotsrpc "github.com/foomo/gotsrpc/v2"
gotsrpc "github.com/foomo/gotsrpc/v3"
httpconv "github.com/foomo/gotsrpc/v3/semconv/httpconv"
github_com_foomo_walker_vo "github.com/foomo/walker/vo"
)
const (
ServiceGoTSRPCProxyGetBrokenLinks = "GetBrokenLinks"
ServiceGoTSRPCProxyGetFolderPages = "GetFolderPages"
ServiceGoTSRPCProxyGetGraph = "GetGraph"
ServiceGoTSRPCProxyGetLinkedFrom = "GetLinkedFrom"
ServiceGoTSRPCProxyGetLinks = "GetLinks"
ServiceGoTSRPCProxyGetPageFolderLinks = "GetPageFolderLinks"
ServiceGoTSRPCProxyGetRedirects = "GetRedirects"
ServiceGoTSRPCProxyGetResult = "GetResult"
ServiceGoTSRPCProxyGetResults = "GetResults"
ServiceGoTSRPCProxyGetScrapes = "GetScrapes"
ServiceGoTSRPCProxyGetStatus = "GetStatus"
ServiceGoTSRPCProxyGetBrokenLinks = "GetBrokenLinks"
ServiceGoTSRPCProxyGetFolderPages = "GetFolderPages"
ServiceGoTSRPCProxyGetGraph = "GetGraph"
ServiceGoTSRPCProxyGetLinkedFrom = "GetLinkedFrom"
ServiceGoTSRPCProxyGetLinks = "GetLinks"
ServiceGoTSRPCProxyGetPageFolderLinks = "GetPageFolderLinks"
ServiceGoTSRPCProxyGetPageGraph = "GetPageGraph"
ServiceGoTSRPCProxyGetRedirects = "GetRedirects"
ServiceGoTSRPCProxyGetResult = "GetResult"
ServiceGoTSRPCProxyGetResults = "GetResults"
ServiceGoTSRPCProxyGetSchemaRoot = "GetSchemaRoot"
ServiceGoTSRPCProxyGetSchemaRootVersion = "GetSchemaRootVersion"
ServiceGoTSRPCProxyGetScrapes = "GetScrapes"
ServiceGoTSRPCProxyGetStatus = "GetStatus"
ServiceGoTSRPCProxyRestartScrape = "RestartScrape"
ServiceGoTSRPCProxyValidateSchema = "ValidateSchema"
)
type ServiceGoTSRPCProxy struct {
EndPoint string
service *Service
service Service
instr *httpconv.Server
}
func NewDefaultServiceGoTSRPCProxy(service *Service) *ServiceGoTSRPCProxy {
return NewServiceGoTSRPCProxy(service, "/service")
func NewDefaultServiceGoTSRPCProxy(service Service, opts ...gotsrpc.Option) *ServiceGoTSRPCProxy {
return NewServiceGoTSRPCProxy(service, "/service", opts...)
}
func NewServiceGoTSRPCProxy(service *Service, endpoint string) *ServiceGoTSRPCProxy {
func NewServiceGoTSRPCProxy(service Service, endpoint string, opts ...gotsrpc.Option) *ServiceGoTSRPCProxy {
return &ServiceGoTSRPCProxy{
EndPoint: endpoint,
service: service,
instr: httpconv.NewServer("github.com/foomo/walker", "Service", opts...),
}
}
@@ -52,318 +59,337 @@ func (p *ServiceGoTSRPCProxy) ServeHTTP(w http.ResponseWriter, r *http.Request)
defer io.Copy(io.Discard, r.Body) // Drain Request Body
funcName := gotsrpc.GetCalledFunc(r, p.EndPoint)
callStats, callStatsOk := gotsrpc.GetStatsForRequest(r)
if callStatsOk {
callStats.Func = funcName
callStats.Package = "github.com/foomo/walker"
callStats.Service = "Service"
}
r, call := p.instr.Start(w, r, funcName)
defer call.End()
switch funcName {
case ServiceGoTSRPCProxyGetBrokenLinks:
var (
args []any
rets []any
)
var rets []any
var (
arg_scrape string
)
args = []any{&arg_scrape}
if err := gotsrpc.LoadArgs(&args, callStats, r); err != nil {
args := []any{&arg_scrape}
if err := gotsrpc.LoadArgs(&args, call, r); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotLoadArgs(w)
return
}
var executionStart time.Time
if callStatsOk {
executionStart = time.Now()
}
call.ExecutionStart()
getBrokenLinksRet := p.service.GetBrokenLinks(arg_scrape)
if callStatsOk {
callStats.Execution = time.Since(executionStart)
}
call.ExecutionEnd()
rets = []any{getBrokenLinksRet}
if err := gotsrpc.Reply(rets, callStats, r, w); err != nil {
if err := gotsrpc.Reply(rets, call, r, w); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotReply(w)
return
}
gotsrpc.Monitor(w, r, args, rets, callStats)
return
case ServiceGoTSRPCProxyGetFolderPages:
var (
args []any
rets []any
)
var rets []any
var (
arg_scrape string
arg_options github_com_foomo_walker_vo.GraphOptions
arg_folder string
arg_maxPages int
)
args = []any{&arg_scrape, &arg_options, &arg_folder, &arg_maxPages}
if err := gotsrpc.LoadArgs(&args, callStats, r); err != nil {
args := []any{&arg_scrape, &arg_options, &arg_folder, &arg_maxPages}
if err := gotsrpc.LoadArgs(&args, call, r); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotLoadArgs(w)
return
}
var executionStart time.Time
if callStatsOk {
executionStart = time.Now()
}
call.ExecutionStart()
getFolderPagesRet := p.service.GetFolderPages(arg_scrape, arg_options, arg_folder, arg_maxPages)
if callStatsOk {
callStats.Execution = time.Since(executionStart)
}
call.ExecutionEnd()
rets = []any{getFolderPagesRet}
if err := gotsrpc.Reply(rets, callStats, r, w); err != nil {
if err := gotsrpc.Reply(rets, call, r, w); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotReply(w)
return
}
gotsrpc.Monitor(w, r, args, rets, callStats)
return
case ServiceGoTSRPCProxyGetGraph:
var (
args []any
rets []any
)
var rets []any
var (
arg_scrape string
arg_options github_com_foomo_walker_vo.GraphOptions
)
args = []any{&arg_scrape, &arg_options}
if err := gotsrpc.LoadArgs(&args, callStats, r); err != nil {
args := []any{&arg_scrape, &arg_options}
if err := gotsrpc.LoadArgs(&args, call, r); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotLoadArgs(w)
return
}
var executionStart time.Time
if callStatsOk {
executionStart = time.Now()
}
call.ExecutionStart()
getGraphRet := p.service.GetGraph(arg_scrape, arg_options)
if callStatsOk {
callStats.Execution = time.Since(executionStart)
}
call.ExecutionEnd()
rets = []any{getGraphRet}
if err := gotsrpc.Reply(rets, callStats, r, w); err != nil {
if err := gotsrpc.Reply(rets, call, r, w); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotReply(w)
return
}
gotsrpc.Monitor(w, r, args, rets, callStats)
return
case ServiceGoTSRPCProxyGetLinkedFrom:
var (
args []any
rets []any
)
var rets []any
var (
arg_scrape string
arg_targetURL string
arg_limit int
)
args = []any{&arg_scrape, &arg_targetURL, &arg_limit}
if err := gotsrpc.LoadArgs(&args, callStats, r); err != nil {
args := []any{&arg_scrape, &arg_targetURL, &arg_limit}
if err := gotsrpc.LoadArgs(&args, call, r); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotLoadArgs(w)
return
}
var executionStart time.Time
if callStatsOk {
executionStart = time.Now()
}
call.ExecutionStart()
getLinkedFromRet := p.service.GetLinkedFrom(arg_scrape, arg_targetURL, arg_limit)
if callStatsOk {
callStats.Execution = time.Since(executionStart)
}
call.ExecutionEnd()
rets = []any{getLinkedFromRet}
if err := gotsrpc.Reply(rets, callStats, r, w); err != nil {
if err := gotsrpc.Reply(rets, call, r, w); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotReply(w)
return
}
gotsrpc.Monitor(w, r, args, rets, callStats)
return
case ServiceGoTSRPCProxyGetLinks:
var (
args []any
rets []any
)
var rets []any
var (
arg_scrape string
)
args = []any{&arg_scrape}
if err := gotsrpc.LoadArgs(&args, callStats, r); err != nil {
args := []any{&arg_scrape}
if err := gotsrpc.LoadArgs(&args, call, r); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotLoadArgs(w)
return
}
var executionStart time.Time
if callStatsOk {
executionStart = time.Now()
}
call.ExecutionStart()
getLinksRet := p.service.GetLinks(arg_scrape)
if callStatsOk {
callStats.Execution = time.Since(executionStart)
}
call.ExecutionEnd()
rets = []any{getLinksRet}
if err := gotsrpc.Reply(rets, callStats, r, w); err != nil {
if err := gotsrpc.Reply(rets, call, r, w); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotReply(w)
return
}
gotsrpc.Monitor(w, r, args, rets, callStats)
return
case ServiceGoTSRPCProxyGetPageFolderLinks:
var (
args []any
rets []any
)
var rets []any
var (
arg_scrape string
arg_options github_com_foomo_walker_vo.GraphOptions
arg_page string
)
args = []any{&arg_scrape, &arg_options, &arg_page}
if err := gotsrpc.LoadArgs(&args, callStats, r); err != nil {
args := []any{&arg_scrape, &arg_options, &arg_page}
if err := gotsrpc.LoadArgs(&args, call, r); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotLoadArgs(w)
return
}
var executionStart time.Time
if callStatsOk {
executionStart = time.Now()
}
call.ExecutionStart()
getPageFolderLinksRet := p.service.GetPageFolderLinks(arg_scrape, arg_options, arg_page)
if callStatsOk {
callStats.Execution = time.Since(executionStart)
}
call.ExecutionEnd()
rets = []any{getPageFolderLinksRet}
if err := gotsrpc.Reply(rets, callStats, r, w); err != nil {
if err := gotsrpc.Reply(rets, call, r, w); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotReply(w)
return
}
return
case ServiceGoTSRPCProxyGetPageGraph:
var rets []any
var (
arg_scrape string
arg_options github_com_foomo_walker_vo.GraphOptions
arg_page string
arg_maxNodes int
)
args := []any{&arg_scrape, &arg_options, &arg_page, &arg_maxNodes}
if err := gotsrpc.LoadArgs(&args, call, r); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotLoadArgs(w)
return
}
call.ExecutionStart()
getPageGraphRet := p.service.GetPageGraph(arg_scrape, arg_options, arg_page, arg_maxNodes)
call.ExecutionEnd()
rets = []any{getPageGraphRet}
if err := gotsrpc.Reply(rets, call, r, w); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotReply(w)
return
}
gotsrpc.Monitor(w, r, args, rets, callStats)
return
case ServiceGoTSRPCProxyGetRedirects:
var (
args []any
rets []any
)
var rets []any
var (
arg_scrape string
)
args = []any{&arg_scrape}
if err := gotsrpc.LoadArgs(&args, callStats, r); err != nil {
args := []any{&arg_scrape}
if err := gotsrpc.LoadArgs(&args, call, r); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotLoadArgs(w)
return
}
var executionStart time.Time
if callStatsOk {
executionStart = time.Now()
}
call.ExecutionStart()
getRedirectsRet := p.service.GetRedirects(arg_scrape)
if callStatsOk {
callStats.Execution = time.Since(executionStart)
}
call.ExecutionEnd()
rets = []any{getRedirectsRet}
if err := gotsrpc.Reply(rets, callStats, r, w); err != nil {
if err := gotsrpc.Reply(rets, call, r, w); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotReply(w)
return
}
gotsrpc.Monitor(w, r, args, rets, callStats)
return
case ServiceGoTSRPCProxyGetResult:
var (
args []any
rets []any
)
var rets []any
var (
arg_scrape string
arg_targetURL string
)
args = []any{&arg_scrape, &arg_targetURL}
if err := gotsrpc.LoadArgs(&args, callStats, r); err != nil {
args := []any{&arg_scrape, &arg_targetURL}
if err := gotsrpc.LoadArgs(&args, call, r); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotLoadArgs(w)
return
}
var executionStart time.Time
if callStatsOk {
executionStart = time.Now()
}
call.ExecutionStart()
getResultRet := p.service.GetResult(arg_scrape, arg_targetURL)
if callStatsOk {
callStats.Execution = time.Since(executionStart)
}
call.ExecutionEnd()
rets = []any{getResultRet}
if err := gotsrpc.Reply(rets, callStats, r, w); err != nil {
if err := gotsrpc.Reply(rets, call, r, w); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotReply(w)
return
}
gotsrpc.Monitor(w, r, args, rets, callStats)
return
case ServiceGoTSRPCProxyGetResults:
var (
args []any
rets []any
)
var rets []any
var (
arg_filters Filters
arg_page int
arg_pageSize int
)
args = []any{&arg_filters, &arg_page, &arg_pageSize}
if err := gotsrpc.LoadArgs(&args, callStats, r); err != nil {
args := []any{&arg_filters, &arg_page, &arg_pageSize}
if err := gotsrpc.LoadArgs(&args, call, r); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotLoadArgs(w)
return
}
var executionStart time.Time
if callStatsOk {
executionStart = time.Now()
}
call.ExecutionStart()
getResultsFilterOptions, getResultsResults, getResultsNumPages, getResultsFolders := p.service.GetResults(arg_filters, arg_page, arg_pageSize)
if callStatsOk {
callStats.Execution = time.Since(executionStart)
}
call.ExecutionEnd()
rets = []any{getResultsFilterOptions, getResultsResults, getResultsNumPages, getResultsFolders}
if err := gotsrpc.Reply(rets, callStats, r, w); err != nil {
if err := gotsrpc.Reply(rets, call, r, w); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotReply(w)
return
}
return
case ServiceGoTSRPCProxyGetSchemaRoot:
var rets []any
var (
arg_schemaRoot string
)
args := []any{&arg_schemaRoot}
if err := gotsrpc.LoadArgs(&args, call, r); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotLoadArgs(w)
return
}
call.ExecutionStart()
getSchemaRootInfo := p.service.GetSchemaRoot(arg_schemaRoot)
call.ExecutionEnd()
rets = []any{getSchemaRootInfo}
if err := gotsrpc.Reply(rets, call, r, w); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotReply(w)
return
}
return
case ServiceGoTSRPCProxyGetSchemaRootVersion:
var rets []any
var (
arg_schemaRoot string
)
args := []any{&arg_schemaRoot}
if err := gotsrpc.LoadArgs(&args, call, r); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotLoadArgs(w)
return
}
call.ExecutionStart()
getSchemaRootVersionRet := p.service.GetSchemaRootVersion(arg_schemaRoot)
call.ExecutionEnd()
rets = []any{getSchemaRootVersionRet}
if err := gotsrpc.Reply(rets, call, r, w); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotReply(w)
return
}
gotsrpc.Monitor(w, r, args, rets, callStats)
return
case ServiceGoTSRPCProxyGetScrapes:
var (
args []any
rets []any
)
var executionStart time.Time
if callStatsOk {
executionStart = time.Now()
}
var rets []any
call.ExecutionStart()
getScrapesComplete, getScrapesCurrent := p.service.GetScrapes()
if callStatsOk {
callStats.Execution = time.Since(executionStart)
}
call.ExecutionEnd()
rets = []any{getScrapesComplete, getScrapesCurrent}
if err := gotsrpc.Reply(rets, callStats, r, w); err != nil {
if err := gotsrpc.Reply(rets, call, r, w); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotReply(w)
return
}
gotsrpc.Monitor(w, r, args, rets, callStats)
return
case ServiceGoTSRPCProxyGetStatus:
var (
args []any
rets []any
)
var executionStart time.Time
if callStatsOk {
executionStart = time.Now()
}
var rets []any
call.ExecutionStart()
getStatusRet := p.service.GetStatus()
if callStatsOk {
callStats.Execution = time.Since(executionStart)
}
call.ExecutionEnd()
rets = []any{getStatusRet}
if err := gotsrpc.Reply(rets, callStats, r, w); err != nil {
if err := gotsrpc.Reply(rets, call, r, w); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotReply(w)
return
}
return
case ServiceGoTSRPCProxyRestartScrape:
var rets []any
call.ExecutionStart()
restartScrapeRet := p.service.RestartScrape()
call.ExecutionEnd()
rets = []any{restartScrapeRet}
if err := gotsrpc.Reply(rets, call, r, w); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotReply(w)
return
}
return
case ServiceGoTSRPCProxyValidateSchema:
var rets []any
var (
arg_schemaRoot string
arg_group string
arg_targetURL string
arg_html string
)
args := []any{&arg_schemaRoot, &arg_group, &arg_targetURL, &arg_html}
if err := gotsrpc.LoadArgs(&args, call, r); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotLoadArgs(w)
return
}
call.ExecutionStart()
validateSchemaValidation := p.service.ValidateSchema(arg_schemaRoot, arg_group, arg_targetURL, arg_html)
call.ExecutionEnd()
rets = []any{validateSchemaValidation}
if err := gotsrpc.Reply(rets, call, r, w); err != nil {
call.SetError(err)
gotsrpc.ErrorCouldNotReply(w)
return
}
gotsrpc.Monitor(w, r, args, rets, callStats)
return
default:
gotsrpc.ClearStats(r)
call.NotFound()
gotsrpc.ErrorFuncNotFound(w)
}
}
+63 -8
View File
@@ -1,4 +1,4 @@
// Code generated by gotsrpc https://github.com/foomo/gotsrpc/v2 - DO NOT EDIT.
// Code generated by gotsrpc https://github.com/foomo/gotsrpc/v3 - DO NOT EDIT.
package walker
@@ -6,7 +6,7 @@ import (
go_context "context"
go_net_http "net/http"
gotsrpc "github.com/foomo/gotsrpc/v2"
gotsrpc "github.com/foomo/gotsrpc/v3"
github_com_foomo_walker_vo "github.com/foomo/walker/vo"
pkg_errors "github.com/pkg/errors"
)
@@ -18,11 +18,16 @@ type ServiceGoTSRPCClient interface {
GetLinkedFrom(ctx go_context.Context, scrape string, targetURL string, limit int) (retGetLinkedFrom_0 github_com_foomo_walker_vo.LinkedFromPage, clientErr error)
GetLinks(ctx go_context.Context, scrape string) (retGetLinks_0 []github_com_foomo_walker_vo.PageLinks, clientErr error)
GetPageFolderLinks(ctx go_context.Context, scrape string, options github_com_foomo_walker_vo.GraphOptions, page string) (retGetPageFolderLinks_0 []github_com_foomo_walker_vo.FolderLink, clientErr error)
GetPageGraph(ctx go_context.Context, scrape string, options github_com_foomo_walker_vo.GraphOptions, page string, maxNodes int) (retGetPageGraph_0 github_com_foomo_walker_vo.Graph, clientErr error)
GetRedirects(ctx go_context.Context, scrape string) (retGetRedirects_0 []github_com_foomo_walker_vo.RedirectChain, clientErr error)
GetResult(ctx go_context.Context, scrape string, targetURL string) (retGetResult_0 *github_com_foomo_walker_vo.ScrapeResult, clientErr error)
GetResults(ctx go_context.Context, filters Filters, page int, pageSize int) (filterOptions FilterOptions, results []github_com_foomo_walker_vo.ScrapeResult, numPages int, folders []github_com_foomo_walker_vo.Folder, clientErr error)
GetSchemaRoot(ctx go_context.Context, schemaRoot string) (info github_com_foomo_walker_vo.SchemaRootInfo, clientErr error)
GetSchemaRootVersion(ctx go_context.Context, schemaRoot string) (retGetSchemaRootVersion_0 string, clientErr error)
GetScrapes(ctx go_context.Context) (complete *github_com_foomo_walker_vo.ScrapeSummary, current *github_com_foomo_walker_vo.ScrapeSummary, clientErr error)
GetStatus(ctx go_context.Context) (retGetStatus_0 github_com_foomo_walker_vo.ServiceStatus, clientErr error)
RestartScrape(ctx go_context.Context) (retRestartScrape_0 bool, clientErr error)
ValidateSchema(ctx go_context.Context, schemaRoot string, group string, targetURL string, html string) (validation github_com_foomo_walker_vo.SchemaValidation, clientErr error)
}
type HTTPServiceGoTSRPCClient struct {
@@ -31,19 +36,19 @@ type HTTPServiceGoTSRPCClient struct {
Client gotsrpc.Client
}
func NewDefaultServiceGoTSRPCClient(url string) *HTTPServiceGoTSRPCClient {
return NewServiceGoTSRPCClient(url, "/service")
func NewDefaultServiceGoTSRPCClient(url string, opts ...gotsrpc.Option) *HTTPServiceGoTSRPCClient {
return NewServiceGoTSRPCClient(url, "/service", opts...)
}
func NewServiceGoTSRPCClient(url string, endpoint string) *HTTPServiceGoTSRPCClient {
return NewServiceGoTSRPCClientWithClient(url, endpoint, nil)
func NewServiceGoTSRPCClient(url string, endpoint string, opts ...gotsrpc.Option) *HTTPServiceGoTSRPCClient {
return NewServiceGoTSRPCClientWithClient(url, endpoint, nil, opts...)
}
func NewServiceGoTSRPCClientWithClient(url string, endpoint string, client *go_net_http.Client) *HTTPServiceGoTSRPCClient {
func NewServiceGoTSRPCClientWithClient(url string, endpoint string, client *go_net_http.Client, opts ...gotsrpc.Option) *HTTPServiceGoTSRPCClient {
return &HTTPServiceGoTSRPCClient{
URL: url,
EndPoint: endpoint,
Client: gotsrpc.NewClientWithHttpClient(client),
Client: gotsrpc.NewClientWithHttpClient(client, append([]gotsrpc.Option{gotsrpc.WithClientService("github.com/foomo/walker", "Service")}, opts...)...),
}
}
@@ -107,6 +112,16 @@ func (tsc *HTTPServiceGoTSRPCClient) GetPageFolderLinks(ctx go_context.Context,
return
}
func (tsc *HTTPServiceGoTSRPCClient) GetPageGraph(ctx go_context.Context, scrape string, options github_com_foomo_walker_vo.GraphOptions, page string, maxNodes int) (retGetPageGraph_0 github_com_foomo_walker_vo.Graph, clientErr error) {
rpcArgs := []any{scrape, options, page, maxNodes}
rpcReply := []any{&retGetPageGraph_0}
rpcErr := tsc.Client.Call(ctx, tsc.URL, tsc.EndPoint, "GetPageGraph", rpcArgs, rpcReply)
if rpcErr != nil {
clientErr = pkg_errors.WithMessage(rpcErr, "failed to call walker.ServiceGoTSRPCProxy GetPageGraph")
}
return
}
func (tsc *HTTPServiceGoTSRPCClient) GetRedirects(ctx go_context.Context, scrape string) (retGetRedirects_0 []github_com_foomo_walker_vo.RedirectChain, clientErr error) {
rpcArgs := []any{scrape}
rpcReply := []any{&retGetRedirects_0}
@@ -137,6 +152,26 @@ func (tsc *HTTPServiceGoTSRPCClient) GetResults(ctx go_context.Context, filters
return
}
func (tsc *HTTPServiceGoTSRPCClient) GetSchemaRoot(ctx go_context.Context, schemaRoot string) (info github_com_foomo_walker_vo.SchemaRootInfo, clientErr error) {
rpcArgs := []any{schemaRoot}
rpcReply := []any{&info}
rpcErr := tsc.Client.Call(ctx, tsc.URL, tsc.EndPoint, "GetSchemaRoot", rpcArgs, rpcReply)
if rpcErr != nil {
clientErr = pkg_errors.WithMessage(rpcErr, "failed to call walker.ServiceGoTSRPCProxy GetSchemaRoot")
}
return
}
func (tsc *HTTPServiceGoTSRPCClient) GetSchemaRootVersion(ctx go_context.Context, schemaRoot string) (retGetSchemaRootVersion_0 string, clientErr error) {
rpcArgs := []any{schemaRoot}
rpcReply := []any{&retGetSchemaRootVersion_0}
rpcErr := tsc.Client.Call(ctx, tsc.URL, tsc.EndPoint, "GetSchemaRootVersion", rpcArgs, rpcReply)
if rpcErr != nil {
clientErr = pkg_errors.WithMessage(rpcErr, "failed to call walker.ServiceGoTSRPCProxy GetSchemaRootVersion")
}
return
}
func (tsc *HTTPServiceGoTSRPCClient) GetScrapes(ctx go_context.Context) (complete *github_com_foomo_walker_vo.ScrapeSummary, current *github_com_foomo_walker_vo.ScrapeSummary, clientErr error) {
rpcArgs := []any{}
rpcReply := []any{&complete, &current}
@@ -156,3 +191,23 @@ func (tsc *HTTPServiceGoTSRPCClient) GetStatus(ctx go_context.Context) (retGetSt
}
return
}
func (tsc *HTTPServiceGoTSRPCClient) RestartScrape(ctx go_context.Context) (retRestartScrape_0 bool, clientErr error) {
rpcArgs := []any{}
rpcReply := []any{&retRestartScrape_0}
rpcErr := tsc.Client.Call(ctx, tsc.URL, tsc.EndPoint, "RestartScrape", rpcArgs, rpcReply)
if rpcErr != nil {
clientErr = pkg_errors.WithMessage(rpcErr, "failed to call walker.ServiceGoTSRPCProxy RestartScrape")
}
return
}
func (tsc *HTTPServiceGoTSRPCClient) ValidateSchema(ctx go_context.Context, schemaRoot string, group string, targetURL string, html string) (validation github_com_foomo_walker_vo.SchemaValidation, clientErr error) {
rpcArgs := []any{schemaRoot, group, targetURL, html}
rpcReply := []any{&validation}
rpcErr := tsc.Client.Call(ctx, tsc.URL, tsc.EndPoint, "ValidateSchema", rpcArgs, rpcReply)
if rpcErr != nil {
clientErr = pkg_errors.WithMessage(rpcErr, "failed to call walker.ServiceGoTSRPCProxy ValidateSchema")
}
return
}
+705
View File
@@ -0,0 +1,705 @@
# htmlschema v2 – specification
Status: **implemented** in package `htmlschema`, which replaces v1 (see
[Migration](#13-migration-from-v1)). The decisions from the feedback rounds are in the
[decision log](#15-decision-log). The worked examples in [section 14](#14-worked-examples)
are the golden tests in `examples_test.go`.
htmlschema makes an SEO specification machine readable and executable. For every
*group* of pages (typically one Next.js route such as `/products/[slug]`) an SEO
expert writes a schema. Validating a page against it yields three independent
results:
- **findings**: rules the page breaks. Each finding has a **severity** (`error`,
`warn`, `info`), which is the gate that later decides whether CI fails, and a
**penalty**, which says how much the mistake weighs.
- **score**: points for present, well-formed content, with a known maximum. It
measures how much good content a page, a component or a group has, as a percentage.
- **penalty**: the sum of the findings' penalties.
Score and penalty are **never combined**. "Lots of good content, but one heavy
mistake" (score 90 %, penalty 50) and "little content, no mistakes" (score 20 %,
penalty 0) are different situations and stay distinguishable.
Examples referenced throughout come from the demo shop: the schemas live in
[`demo/schema`](demo/schema), the pages are rendered by
[`demo/server`](demo/server) (`go run ./cmd/demo`). They are worked through in
[section 14](#14-worked-examples).
## 1. Concepts
| term | meaning |
|---|---|
| group | name of a page type, e.g. `content/landing`. Passed in by the caller. |
| schema | an HTML file describing the semantic outline a page of a group must have |
| component | a reusable schema for a block that can appear on many pages (teaser, gallery, …), recognized in the page by a marker attribute or a CSS selector |
| wildcard | a schema scope in which layout wrapper elements (`div`, `span`, …) between the described elements are skipped |
| finding | a broken rule: severity, penalty, rule, path, message |
| score | points earned by matched content, summed up to the page. The schema defines the maximum. |
| penalty | points lost through findings, summed up to the page. No maximum. |
**Input.** The library validates whatever HTML it is given. The intended input
is the server response, because SEO-relevant content must be server-rendered.
Rendered DOM snapshots (e.g. from Playwright in CI) work the same way.
## 2. Files and resolution
```
<root>/
default.html fallback for groups without a schema
groups/<group>.html e.g. groups/content/landing.html for group "content/landing"
… everything else is organized freely, e.g. components/, partials/
```
- A group resolves to `groups/<group>.html`. Then `default.html`. Neither existing is an error. These two are the only fixed locations.
- `default.html` is only a fallback. It is **not** combined with group schemas.
- **Paths** in `val:include` and `val:comp` are written without the `.html` extension. A leading `/` starts at the schema root (`/partials/head`). Anything else is relative to the file that contains it (`../../partials/head`).
- Any file can be [included](#22-valinclude). A file with a single top level element can be [instantiated](#23-valcomp).
- At load time all files under the root are read. Every file whose root is `val:component` is a **recognized component**, identified by its root-relative path (`/components/teaser`), however it is referenced. Every recognized component can be found on every page, not only on pages whose schema instantiates it (needed for [closed contexts](#63-closed-and-open-contexts) and [ambiguity](#32-component-recognition)).
Library API sketch:
```go
root, err := htmlschema.LoadRoot("schema")
report, err := root.Validate("content/landing", htmlBytes)
```
### 2.1 Settings
Settings belong to each schema. They are written as a `<val:settings>` element,
a direct child of `<html>`. That makes them shareable through `val:include`.
```html
<val:settings exclude=".mobile-only" marker-attribute="data-component" penalty-error=10 penalty-warn=3 penalty-info=0/>
```
| setting | default | meaning |
|---|---|---|
| `exclude` | (none) | CSS selectors of elements to remove before matching, in addition to the [built-in exclusions](#31-exclusion) |
| `marker-attribute` | `data-component` | attribute that marks component instances |
| `penalty-error`, `penalty-warn`, `penalty-info` | 10, 3, 0 | penalty of a finding without explicit `val:penalty` |
When a page is validated, the settings of the group schema apply to everything,
including component recognition and the component schemas used on the page.
### 2.2 `val:include`
`<val:include path="/partials/head"/>` inserts the content of a file in place, as
if it were written there. The file may contain any number of top level elements
([partials/head.html](demo/schema/partials/head.html) holds the `meta`s and the canonical `link` of every page).
Everything about the include site applies to the inserted elements, including the
wildcard scope. Includes may nest. Cycles are a lint error.
### 2.3 `val:comp`
`<val:comp path="/components/teaser" val:max=3/>` instantiates a file whose
content is **a single top level element**: that element is placed here, and the
attributes of `val:comp` (except `path`) **override or extend** the attributes of
the root element.
- Attributes with the same name replace the root's value, and new ones are added.
- Occurrence attributes (`val:min`, `val:max`, `val:count`, `val:optional`, `val:forbidden`) are replaced as a group. If the site sets any of them, none of the root's apply.
- `marker` and `selector` of a `val:component` root can't be overridden (lint error), because recognition runs page-wide before matching and must be the same everywhere.
The root decides what the instance does:
- a **`val:component`** root: a recognized component, see [section 5](#5-components)
- any **other element**: an element template, matched like the element written in place. [partials/site-header.html](demo/schema/partials/site-header.html), a `<header>` with the logo link and the main navigation, is used as `<val:comp path="/partials/site-header"/>` in every group. A site could relax it for one group with `<val:comp path="../partials/site-header" val:severity="warn"/>`.
## 3. Matching
Validating a page runs in three steps: exclusion, component recognition, then
matching the schema tree against the page tree.
### 3.1 Exclusion
These elements, and their subtrees, are removed from the page before anything else:
- `script`, `style`, `template`, `noscript` (JSON-LD is read before this, see [section 7](#7-structured-data-valld))
- elements with the `hidden` attribute
- elements matching `exclude` from the settings. This is for responsive duplicates that are only hidden by CSS, e.g. `exclude=".mobile-only"`. `[aria-hidden=true]` is not excluded by default, because search engines index it. Add it if a project uses it for duplicates.
The validator never sees CSS, so content that is only hidden by a media query
must be excluded by selector. Otherwise it counts twice. A header that renders
its navigation twice, once for desktop and once as `<nav class="mobile-only">`,
contains two `nav`s, and `header > nav` (exactly one) fails without
`exclude=".mobile-only"`.
### 3.2 Component recognition
Every element of the (excluded) page is checked against all components:
1. An element whose marker attribute is set is an instance of the component with that `marker` value. If no component has that marker, the marker is ignored, as if it was not there: the element is matched like any other element, and its content is visible to the schema.
2. An element without a marker attribute is an instance of the component whose `selector` matches it. If **several** selectors match, the element gets a `component-ambiguous` finding (error) naming all of them. It is treated as an opaque unknown instance: not validated, earns nothing. This can only be detected on concrete pages, not when loading schemas. Example: `[class*='Teaser_root']` also matches `VideoTeaser_root__v7k`. The author fixes it with plain CSS (`[class*='Teaser_root']:not([class*='VideoTeaser_root'])`), or the frontend adds a marker.
3. A selector match inside an instance of the same component is part of that instance, not a nested one. Marker and CSS module class often sit on different wrappers: `<div data-component="text"><div class="RichText_root__r1">…` is one `text` instance.
4. Otherwise, recognition continues inside an instance. Nested instances belong to the content of the outer instance.
From the outside, an instance is **opaque**: one node named after the component
(`teaser`, `gallery`, …), whatever its root element is. Its content is only
visible to the component's own schema (and to [`val:selector`](#34-valselector)).
### 3.3 Elements and wildcards
A schema element matches the **children of its context node** (the page node
its parent schema element matched; the document for `<html>`) that have
- the same tag name, and
- every *literal* attribute of the schema element: `rel="canonical"` must be equal, `hreflang="*"` must be present and non-empty. Attributes starting with `val:` are not literals.
Page elements not mentioned in the schema are ignored. The schema describes what
must or may be there, not everything that is there.
Without a wildcard, matching is strict: only direct children. React layouts nest
semantic elements deep in wrapper `div`s, so schemas declare where wrappers are allowed:
```html
<body>
<val:wildcard for="div, span">
<header>…</header>
<main>
<h1/>
</main>
</val:wildcard>
</body>
```
- Inside `<val:wildcard for="…">`, a schema element matches elements reachable from the context node through **any number (0..n) of elements matching `for`**. `for` is a CSS selector list, matched against each element on its own: `for="div, span"`, `for="div, section:not([aria-label])"`. `for="*"` skips any element.
- The scope is **lexical and inherited**. In the example, `main` is found through the wrappers below `body`, and `h1` is found through the wrappers below `main`. A nested `val:wildcard` replaces the set for its content. `for=""` makes a part strict again.
- Component instances are never skipped and never searched through, even when their root is a `div`.
- An element matching `for` can still be matched itself, e.g. `<div class="x">` inside `for="div"`. The search continues below it either way.
- `val:wildcard` doesn't match a page node itself, and it doesn't appear in paths.
What the `article` of a [product page](demo/server/templates/product.html) looks like through `<val:wildcard for="div">`:
```
article
├── figure (in div.product-top)
├── h1 Clanky the Butlerbot (in div.product-top > div.product-info)
├── p.price 1299.00 €
├── p.description A tireless butler …
├── feature-section (data-component="feature-section", root is a <section>)
└── feature-section
```
### 3.4 `val:selector`
`<val:selector for="css">` matches all elements the CSS selector finds in
the subtree of the context node, **ignoring wildcards and component borders**.
At the top of `<body>` it searches the whole page, including inside components.
Typical use is page-wide rules, shared through a partial ([partials/page-baseline.html](demo/schema/partials/page-baseline.html)): `<val:selector for="h1" count=1/>`.
The rules of the `val:selector` element itself apply to every selected node. Its
children match the children of each selected node (wildcards apply as usual).
## 4. Element rules
**Spelling.** On HTML elements, rule attributes carry the `val:` prefix to
separate them from literal attributes (`<meta property="og:title" val:score=2/>`).
`val:*` elements have no literal attributes, so they take the same rules
**without** prefix (`<val:selector for="h1" count=1 score=10/>`). The exception is
`val:comp`: it passes attributes through to its root, which may be an HTML
element, so it keeps the prefix (`<val:comp path="/partials/main-nav" aria-label="Main" val:score=20/>`).
At a `val:comp` site, `val:max=3` overrides `max` on a `val:*` root. This spec
names rules with prefix: `val:score` means `score` on a `val:*` element.
### 4.1 Occurrence
| syntax | min | max |
|---|---|---|
| (nothing) | 1 | 1 |
| `val:optional` | 0 | 1 |
| `val:min=n` | n | unbounded |
| `val:max=n` | 1 | n |
| `val:min=n val:max=m` | n | m |
| `val:count=n` | n | n |
| `val:forbidden` | 0 | 0 |
| `val:max=*` | | unbounded |
`val:optional` combines with `val:max`. Defaults differ for `val:selector`
(1..unbounded) and for `val:comp` inside `val:choice` (0..unbounded).
Finding rule: `occurrence`.
### 4.2 Text content
The text of a matched node is the text of all its descendants (after
exclusion), with whitespace runs collapsed to one space and trimmed. Length is
counted in characters (Unicode code points, so `–` and `ü` count as 1). Words are
whitespace separated tokens. All bounds are inclusive.
| syntax | finding rule |
|---|---|
| `val:min-length=n`, `val:max-length=n` | `min-length`, `max-length` |
| `val:min-words=n`, `val:max-words=n` | `min-words`, `max-words` |
### 4.3 Attribute rules
`val:attr-<name>="rule; rule; …"` validates the value of attribute `<name>` on
every matched node. Unlike literal attributes, a failing attribute rule does not
stop the node from matching. It produces a finding. An absent attribute has
the value `""`.
| rule | passes when |
|---|---|
| `required` | the attribute is present and not empty |
| `empty` | the attribute is absent or empty |
| `min-length:n`, `max-length:n`, `length:n` | value length in characters, inclusive |
| `min-words:n`, `max-words:n` | word count, inclusive |
| `one-of:a\|b\|c` | value equals one of the alternatives |
| `url` / `url:absolute` | value parses as a URL / as an absolute `http(s)` URL |
| `regex:<re>` | Go regexp matches. Must be the **last** rule: everything after `regex:` is the expression, unescaped, including `;` and `:` |
| `severity:<s>`, `penalty:<n>` | not checks: override severity / penalty for this attribute's findings |
Finding rule: `attr:<rule>`, path suffix `@<name>`, e.g. `html/head/meta[name=description]@content`.
`val:attr="name; rules"` (v1) is still accepted. It allows only one attribute
per element, because an element can't carry `val:attr` twice.
### 4.4 Severity and penalty
- `val:severity=error|warn|info` sets the severity of all findings produced by this element's own rules (occurrence, text, attributes). The default is `error`.
- `val:penalty=n` sets their penalty. The default comes from the [settings](#21-settings), based on the element's severity: error 10, warn 3, info 0.
- Neither is inherited by child elements.
Occurrence penalties scale with the deviation:
| deviation | findings |
|---|---|
| too many nodes | one finding **per surplus node**, each with that node's locator and the full penalty. Surplus = nodes after the first `max` in document order. |
| too few nodes | one finding at the context node, penalty × number of missing nodes |
`val:penalty-max=n` caps the total penalty of an element's occurrence findings
(surplus findings beyond the cap are still reported, with penalty 0).
| rule | page | findings |
|---|---|---|
| `<a val:min=3 val:max=12>` | 2 links | 1 finding, 1 × 10 |
| same | 0 links | 1 finding, 3 × 10 = 30 |
| `<h1 val:penalty=50>` | 4 h1s | 3 findings × 50 = 150 |
| `<i val:forbidden val:penalty=20 val:penalty-max=100>` | 30 `<i>` | 30 findings, penalty 100 in total |
## 5. Components
A component is a file whose single root is `val:component`:
```html
<!-- /components/teaser.html -->
<val:component marker="teaser" selector="[class*='Teaser_root']">
<val:wildcard for="div, span">
<img val:optional val:score=2 val:penalty=5 val:attr-alt="min-length:5"/>
<h3 val:score=3 val:min-length=10 val:max-length=80/>
<p val:optional val:score=3 val:min-words=8/>
<a val:score=2 val:attr-href="required"/>
</val:wildcard>
</val:component>
```
- Its identity is its root-relative path, `/components/teaser`. Reports and `component-not-allowed` use it. Finding paths use the file name (`teaser[2]`), or the full path if two recognized components share a file name.
- `marker`: the value of the marker attribute (`data-component="teaser"`). This is the reliable way and needs the frontend team's cooperation. Markers must be unique among all recognized components (lint).
- `selector`: fallback for markup without a marker, e.g. CSS module classes such as `Teaser_root__t9q`. This is brittle across refactorings, so it's only a fallback.
- Children are matched against the children of the instance root. The root itself can be any element. Wildcards from the instantiating schema do **not** reach into a component, so a component declares its own.
- A component can instantiate other components (`val:comp`, `val:choice`, `val:sequence`), and it can contain `val:ld`, e.g. an FAQ component requiring an `FAQPage` JSON-LD.
- Including a component file with `val:include` inserts the `val:component` element itself, so it still finds instances. To reuse only its rules, put them in a separate file and include that.
## 6. Content models
### 6.1 Instantiating components
`<val:comp path="/components/gallery"/>` with a `val:component` root matches the
instances of that component among the children of the context node (wildcards
apply), and validates each against the component schema. Occurrence attributes
work as on elements. Outside of `val:choice` the default is exactly 1.
`val:severity` at the site is a **ceiling** for all findings inside the
instances. `val:severity=warn` turns their errors into warnings, e.g. to
tolerate legacy blocks without failing CI. Penalties are not affected. A default
penalty is derived from the severity *before* the ceiling applies. (On an element
template, `val:severity` only applies to the root element's own rules, as on any element.)
### 6.2 `val:choice` and `val:sequence`
For freely composed CMS areas:
```html
<val:choice min=2 max=12 score-max=100>
<val:comp path="/components/text" val:max=4/>
<val:comp path="/components/teaser" val:max=6/>
<val:comp path="/components/gallery" val:max=1/>
<val:comp path="/components/faq" val:max=1/>
</val:choice>
```
- `val:choice`: any number of instances of the listed components, **in any order**, mixed. `val:min/max` on the choice limit the total number of instances. `val:min/max` on each `val:comp` limit that type (default 0..unbounded).
- `val:sequence`: the listed components must appear **in this order**. Each `val:comp` defaults to exactly 1. An instance out of order produces a `component-order` finding.
A context may hold several choices and sequences. They contain only `val:comp`s of recognized components. A component may appear in only one of them per context (lint).
### 6.3 Closed and open contexts
A schema element containing any `val:comp` of a recognized component, `val:choice` or `val:sequence` is a
*component context*. By default it is **closed**:
| instance found in the context | finding |
|---|---|
| a component it uses | validated |
| a known component it does not use | `component-not-allowed`, error |
Markers without a component schema are not components (see [3.2](#32-component-recognition)), they produce no finding.
`val:open` on the context element turns `component-not-allowed` into info.
Instances outside component contexts are opaque and ignored. Only
`val:selector` can still look inside them.
## 7. Structured data (`val:ld`)
```html
<val:ld type="Product" score=20>
<val:prop path="name" min-length=5/>
<val:prop path="offers.priceCurrency" value="one-of:EUR|CHF"/>
<val:prop path="offers.availability" optional value="regex:^https://schema\.org/(InStock|OutOfStock)$"/>
</val:ld>
```
- Matches JSON-LD objects with `@type` equal to (or containing) `type`, from all `script[type="application/ld+json"]` of the page, including `@graph` arrays. The position of `val:ld` in the schema doesn't matter (page-wide), except inside a component, where only scripts inside the instance count.
- Occurrence as for elements (default exactly 1). Finding rule: `ld-occurrence`.
- `val:prop path="a.b"`: dot path into the object. If a step hits an array, any element may satisfy it. With `every`, every element has to pass - and has to have the property, unless it is `optional` - and each failing element is a finding of its own, indexed in document order: `itemListElement.item.offers.priceCurrency[2]`. Use it for lists, where one good entry must not hide a bad one:
```html
<val:ld type="ItemList">
<val:prop path="itemListElement.item.offers.priceCurrency" every value="one-of:EUR|USD|CHF"/>
</val:ld>
``` Default required. `val:min-length` etc. apply to string values. `value` takes the [attribute rule list](#43-attribute-rules). Finding rule: `ld-prop:<rule>`.
- Scoring as for elements: the object earns `val:score` if all its required props pass. Props may carry their own `val:score`.
## 8. Findings
```
error 10 attr:min-length html/body/main/teaser[2]/img@alt got 0, expected at least 5
```
- Locator: a CSS path to the page node, usable with `document.querySelector` in the browser's dev tools, e.g. `html > body > div > div > main > div:nth-of-type(2) > section`. `:nth-of-type(n)` is added where a node has siblings with the same tag. It is computed on the page as delivered, before exclusion. For missing nodes, the locator is the context node they are missing from.
- Path: schema path with page positions. Stable across layout changes, so findings can be compared over time. The locator is for finding the node. Components appear by name. `[n]` counts matched nodes of that schema element within one context node, starting at 1, and is omitted when there is only one. Literal attributes in head paths identify the element: `meta[name=description]`.
- Order: schema document order, then page order. Deterministic.
- A finding does not embed the schema element (v1 did, including its whole subtree).
## 9. Score and penalty
### 9.1 Earning points
- `val:score=n`: every matched node earns `n` if **its own rules pass** (text and attribute rules of this element). Children earn independently. A failing child rule does not cost the parent anything.
- Only the first `max` nodes (document order) earn. Surplus nodes produce an `occurrence` finding and nothing else.
- `val:score-per="words:k"` (or `chars:k`): the node earns `n × floor(units / k)` instead of `n`. This rewards amount: `val:score=2 val:score-per="words:20"` = 2 points per full 20 words.
- `val:score-max=m`: caps everything the element earns **including its subtree, summed over all its nodes**.
- `val:comp` of a component earns what its instances earn under the component schema. `val:choice` and `val:sequence` earn the sum of their `val:comp`s, capped by their own `val:score-max`.
- Component instances that are not allowed, or unknown, earn nothing.
- There are no negative points. Mistakes are measured by the penalty.
### 9.2 Maximum
The maximum is computed from the schema alone, so it is the same for every page of a group:
```
max(E) = min( score-max(E), maxCount(E) × (score(E) + Σ max(child)) )
max(val:comp) = min( score-max, maxCount × max(component) )
max(val:choice) = min( score-max, best combination )
max(val:sequence) = min( score-max, Σ max(val:comp) )
```
For a choice, the *best combination* is computed greedily: first the `val:min`
instances of every use, then the most valuable remaining instances (highest
`max(component)` first) up to each use's `val:max` and the choice's `val:max`.
So the maximum is always reachable in theory.
An element whose maximum would be unbounded (unbounded `max` or `score-per`
with points somewhere in its subtree) must have `val:score-max`. Otherwise
loading fails.
Optional content counts towards the maximum. A page that leaves out optional
content has less content, and its percentage shows that.
### 9.3 Penalty
The penalty of a page is the sum of its findings' penalties. It has no maximum
and is never subtracted from the score. Occurrence penalties scale with the
deviation, see [4.4](#44-severity-and-penalty).
### 9.4 Aggregation
- page: score `points / max` as a percentage, penalty as a sum
- component instance: `points / max(component)` and the penalty of the findings inside it. Component type on a page: sums over its instances.
- group (across pages, later in walker metrics): average score percentage, average and total penalty, and per component type the sum of points / sum of maxima. Score and penalty are separate metric series.
## 10. Report model
Names are tentative. Generated Swift code shares one module, so type names must
not clash with `vo` and `walker` types.
```go
type Severity string // "error" | "warn" | "info"
type Finding struct {
Severity Severity
Penalty int
Rule string // "occurrence", "min-length", "attr:url", "component-not-allowed", …
Path string // "html/body/main/teaser[2]/img@alt"
Locator string // "html > body > div > div > main > … > img"
Message string // "got 0, expected at least 5"
Component string // innermost component instance, "/components/teaser", "" on page level
Source string // "components/teaser.html:6"
}
type ScoreNode struct {
Path string
Points int
Max int
Children []*ScoreNode // only scoring nodes, for drill down
}
type ComponentSummary struct {
Instances int
Points int
Max int
Penalty int
}
type Report struct {
Group string
Schema string
Findings []*Finding
Score *ScoreNode
Penalty int
Components map[string]*ComponentSummary
}
```
## 11. Schema lint
Loading fails with a list of all problems, each with file and line:
- unknown `val:` attribute or element, unknown attribute rule, unknown setting
- on HTML elements, attributes that look like a forgotten prefix: `score=…`, `optional`, `val=optional`, `min-length=…` (v1 examples contain both)
- `val:`-prefixed attributes on `val:*` elements other than `val:comp`
- duplicate attributes on an element
- unclosed or mismatched elements (see [section 12](#12-schema-syntax))
- `min > max`, non-numeric values, `val:optional` together with `val:min`
- `val:include` / `val:comp` to missing files, include cycles
- `val:comp` of a file without exactly one top level element; overriding `marker`/`selector`
- duplicate markers among recognized components
- `val:include`, `val:comp`, `val:prop`, `val:settings` with children. `val:settings` anywhere but directly in `<html>`.
- unbounded maximum without `val:score-max`
- a component listed in two choices/sequences of the same context
## 12. Schema syntax
Schemas look like HTML but are **not** parsed with the HTML5 parser. Its error
recovery would restructure them: a `val:*` element in `<head>` ends the head,
`<val:comp/>` swallows its following siblings, `<p><div>` is split. Instead,
schemas are read with the x/net/html *tokenizer* and a simple tree builder:
- The tree is exactly as written. Nothing is moved and nothing is inserted (a schema that describes `<head>` writes it).
- `<x/>` closes any element, including `val:*`. Elements without children are written self-closing: `<h2 val:score=3 val:min-length=3/>`. That's the convention in all examples; `<h2 …></h2>` is equivalent.
- Void elements (`img`, `meta`, `link`, `br`, `hr`, `input`, …) close themselves and can't have children.
- Every other element must be closed explicitly. Unclosed or mismatched end tags are lint errors with line numbers.
- HTML attribute syntax: boolean attributes (`val:optional`), unquoted values (`val:score=10`), entities.
- Attribute names are lowercased (`hrefLang` → `hreflang`), as in the parsed pages.
- Comments and text are ignored.
Pages are still parsed with the HTML5 parser, as browsers do.
## 13. Migration from v1
| v1 | v2 |
|---|---|
| HTML5 parser for schemas | own tree builder, tree exactly as written |
| strict direct-child matching everywhere | still the default; `val:wildcard` allows wrappers explicitly |
| `<root>/<group>/<page>.html`, root = the groups dir | `<root>/groups/<group>.html`, everything else organized freely, unknown group → `default.html` |
| `<ref>path</ref>`, file relative, exactly one top level element | `<val:include path=…/>` (any number of elements) and `<val:comp path=…/>` (one element, attribute overrides); `/` = root, otherwise relative |
| `val:attr="name;…"`, one per element | `val:attr-<name>="…"`; the old form still works for one attribute |
| attribute `min-length`/`max-length` exclusive (`max-length:0` never passes) | inclusive |
| regex URL-encoded | regex raw, last rule |
| text length = first text child, bytes | full normalized text, characters |
| `val:selector`: zero matches → no finding; children repeat the selected element | occurrence applies to the matches (default 1..unbounded); rules on the `val:selector` itself; children match the selected node's children |
| penalty = element score, subtracted from the score in `Print` | severity (gate) + penalty (weight) per finding; score separate, never combined |
| `val:optional` → 0..unbounded | 0..1 |
| unknown `val:*` silently ignored, typos become literal attributes | lint error |
| no fallback for unknown groups | `default.html` |
## 14. Worked examples
Root: [`demo/schema`](demo/schema). The pages are rendered by the demo shop
([`demo/server`](demo/server)) for `https://shop.example`, and the group comes
from its `x-next-js-app` response header. These numbers are the expected
results, checked by `examples_test.go`.
### 14.1 `index`: the home page `/`
A lead paragraph, two category tiles and a section about the demo. Schema:
[groups/index.html](demo/schema/groups/index.html).
Findings: none.
Result: **score 89 / 117 = 76.1 %, penalty 0**
| path | points | max | why |
|---|---|---|---|
| `head` (7 rules) | 34 | 34 | title, description, canonical and OpenGraph, mostly from the partial |
| `val:ld(WebSite)` | 5 | 5 | |
| `body/main/h1` | 20 | 20 | |
| `body/main/p[class=lead]` | 10 | 10 | |
| `body/main/section[aria-labelledby=categories]` | 16 | 42 | h2 2 + choice 14 |
| ↳ `val:choice` | 14 | 40 | 2 category tiles × 7. Best combination 10 × 7 = 70, capped by `score-max=40` |
| `body/main/section[aria-labelledby=about]` | 4 | 6 | 2 paragraphs × 2, `val:score-max=6` |
Components: category-tile 14/14 (100 %).
### 14.2 `category`: `/category/cars`
Ten product tiles and an `ItemList` in JSON-LD, a host carousel where every
item is a complete product. The station wagon has a name of 75 characters.
Schema: [groups/category.html](demo/schema/groups/category.html).
Findings:
| severity | penalty | rule | path | message |
|---|---|---|---|---|
| warn | 3 | `ld-prop:max-length` | `html/body/val:ld(ItemList)/itemListElement.item.name[4]` | got 75, expected at most 60 |
| warn | 3 | `max-length` | `html/body/main/product-tile[4]/a/h2` | got 75, expected at most 60 |
Locators: `html > head > script:nth-of-type(2)` (the `ItemList` script) and
`html > body > main > div > article:nth-of-type(4) > a > h2`.
Result: **score 130 / 182 = 71.4 %, penalty 6**
| path | points | max | why |
|---|---|---|---|
| `head` (7 rules) | 34 | 34 | |
| `val:ld(BreadcrumbList)` | 5 | 5 | |
| `val:ld(ItemList)` | 0 | 10 | `every` checks all ten names: one failing prop, the list earns nothing |
| `body/main/nav[aria-label=Breadcrumb]` | 3 | 3 | 2 links in `ol/li`, `val:wildcard for="ol, li"` |
| `body/main/h1` | 20 | 20 | |
| `body/main/p[class=lead]` | 10 | 10 | |
| `body/main/val:choice` | 58 | 100 | 10 tiles × 6, the fourth h2 earns nothing. Best combination 40 × 6 = 240, capped by `score-max=100` |
Components: product-tile 58/60 (96.7 %, penalty 3).
The same schema on `/category/robots`: no findings, `val:ld(ItemList)` 10, **score 142 / 182, penalty 0**.
### 14.3 `product`: a clean product `/product/robot-01`
Clanky the Butlerbot: complete merchant listing data in the `Product` JSON-LD,
the product info in wrapper `div`s and two feature sections. Schema:
[groups/product.html](demo/schema/groups/product.html).
Findings: none.
Result: **score 121 / 145 = 83.4 %, penalty 0**
| path | points | max | why |
|---|---|---|---|
| `head` (8 rules) | 36 | 36 | the partial + `product:price:amount` |
| `val:ld(Product)` | 31 | 31 | 20 for the object + 11 for the optional merchant listing props |
| `val:ld(BreadcrumbList)` | 5 | 5 | |
| `body/main/nav[aria-label=Breadcrumb]` | 3 | 3 | |
| `body/main/article` | 46 | 70 | |
| ↳ `figure` | 5 | 5 | figure 2 + img 3 |
| ↳ `h1` | 20 | 20 | 2 wrappers deep, `val:wildcard for="div"` |
| ↳ `p[class=price]` | 5 | 5 | |
| ↳ `p[class=description]` | 4 | 10 | 21 words → 2 × 2, `val:score-per="words:10"` |
| ↳ `val:choice` | 12 | 30 | 2 feature sections × 6 (h2 2 + 2 dt + 2 dd) of 10 |
Components: feature-section 12/20 (60 %).
### 14.4 `product`: four flawed products
Same group and schema as 14.3. Each product has one deliberate flaw, and it
shows up wherever the page repeats it.
**Tiny Tim** (`/product/robot-07`): a description of one word, "Beeps.".
**Score 85 / 145, penalty 40.**
| severity | penalty | rule | path | message |
|---|---|---|---|---|
| error | 10 | `attr:min-length` | `html/head/meta[name=description]@content` | got 6, expected at least 70 |
| error | 10 | `attr:min-length` | `html/head/meta[property=og:description]@content` | got 6, expected at least 70 |
| error | 10 | `ld-prop:min-length` | `html/body/val:ld(Product)/description` | got 6, expected at least 70 |
| error | 10 | `min-words` | `html/body/main/article/p[class=description]` | got 1, expected at least 12 |
A failing required prop costs the `Product` object its 20 points, while its
optional props still earn their own: `val:ld(Product)` 11 / 31.
**Lazybot Deluxe** (`/product/robot-10`): no feature sections at all.
**Score 109 / 145, penalty 10.**
| severity | penalty | rule | path | message |
|---|---|---|---|---|
| error | 10 | `occurrence` | `html/body/main/article/val:choice` | got 0, expected 1..6 |
Locator: `html > body > main > article`, the context they are missing from.
**The station wagon** (`/product/car-04`): a name of 75 characters, 94 in the title.
**Score 69 / 145, penalty 90.**
| severity | penalty | rule | path | message |
|---|---|---|---|---|
| error | 20 | `max-length` | `html/head/title` | got 94, expected at most 60 |
| error | 10 | `attr:max-length` | `html/head/meta[property=og:title]@content` | got 94, expected at most 90 |
| error | 10 | `ld-prop:max-length` | `html/body/val:ld(Product)/name` | got 75, expected at most 60 |
| error | 50 | `max-length` | `html/body/main/article/h1` | got 75, expected at most 60 |
The title and the h1 carry their own `val:penalty`, so one long name weighs 90.
**The Crypto Cruiser** (`/product/car-09`): priced in `DOGE`.
**Score 101 / 145, penalty 30.**
| severity | penalty | rule | path | message |
|---|---|---|---|---|
| error | 10 | `attr:one-of` | `html/head/meta[property=product:price:currency]@content` | "DOGE" is not one of EUR\|USD\|CHF |
| error | 10 | `ld-prop:one-of` | `html/body/val:ld(Product)/offers.priceCurrency` | "DOGE" is not one of EUR\|USD\|CHF |
| error | 10 | `ld-prop:one-of` | `html/body/val:ld(Product)/offers.shippingDetails.shippingRate.currency` | "DOGE" is not one of EUR\|USD\|CHF |
The category schema allows `DOGE` in its `ItemList`, so `/category/cars` has no currency finding.
### 14.5 Fallback: the 404 page
The 404 page sends no group header, so it is validated with
[default.html](demo/schema/default.html). No findings, **score 41 / 44, penalty
0**. The optional `og:image` is missing: 0 of 3 points, no finding.
## 15. Decision log
First feedback round:
1. **Wrappers**: no global projection. `val:wildcard for="…"` instead, with lexical, inherited scope. It replaces the draft's `val:deep`, `val:strict` and `val:transparent`.
2. **Settings**: per schema (`val:settings`, shareable via `val:include`). `aria-hidden` is not excluded by default.
3. **Shared rules**: `default.html` is a fallback only. Shared rules live in partials (see [14](#14-worked-examples)).
4. **Component contexts**: closed by default, error. `val:open` relaxes to info.
5. **Score vs penalty**: two separate measures, never combined. Nodes earn independently of their children. No negative points. Penalty per finding from `val:penalty`, otherwise a default per severity.
6. **Component overrides**: `val:severity` at the instantiation site is a ceiling. Penalties unchanged.
7. **Choice maximum**: exact, greedy best combination.
8. **Schema syntax**: own tree builder on the x/net/html tokenizer, no HTML5 error recovery, line numbers.
9. **Input**: any HTML. The server response is the intended input, and rendered snapshots work too.
10. **Marker attribute**: `data-component` by default.
Second feedback round:
11. **Overlapping selectors**: `component-ambiguous` finding, the instance is not validated. Authors disambiguate with CSS (`:not(…)`) or markers. No priorities.
12. **Occurrence penalties** scale with the deviation: one finding per surplus node, penalty × count for missing nodes, optional `val:penalty-max`.
13. **Locators**: every finding carries a CSS path to the page node (or to the context of missing nodes).
Third feedback round:
14. **Includes and instances**: `<ref>` and `val:use` are replaced by `val:include` (insert any file) and `val:comp` (instantiate a single-root file, attributes override the root's). Paths are `/`-rooted or relative, without `.html`. File organization is free. Recognized components are the files with a `val:component` root, identified by path. `marker`/`selector` can't be overridden.
15. **Spelling**: no `val:` prefix on attributes of `val:*` elements, except `val:comp`. `for` is a CSS selector everywhere (`val:selector for="h1"`, `val:wildcard for="div, span"`). Page-wide rules live in `/partials/page-baseline`, kept lean to avoid double findings with component rules.
Fourth feedback round:
16. **Unknown markers**: a `data-component` value without a component schema is ignored entirely - no `component-unknown` finding, and the element is not opaque. Projects mark many UI components (`Icon`, `Picture`, `Link`) that the SEO schema does not care about.
Fifth feedback round:
17. **`every` on `val:prop`**: by default one array element satisfies a property path ("has at least one offer in EUR"). `every` checks all of them ("every product of the list is in a valid currency") with a finding per failing element.
## 16. Open questions
None at the moment.
-70
View File
@@ -1,70 +0,0 @@
package htmlschema
import (
"net/url"
"regexp"
"golang.org/x/net/html"
)
type AttributeRule interface {
ValidateNode(n *html.Node) (valid bool, err error)
Info() string
}
type attributeRuleLength struct {
name string
info string
lengthMatch func(actual int) (bool, error)
}
func newAttributeRuleLength(attrName string, info string, lengthMatch func(actualLength int) (valid bool, err error)) AttributeRule {
return &attributeRuleLength{
name: attrName,
info: info,
lengthMatch: lengthMatch,
}
}
func getAttrValue(n *html.Node, name string) string {
for _, attr := range n.Attr {
if attr.Key == name {
return attr.Val
}
}
return ""
}
func (rl *attributeRuleLength) ValidateNode(n *html.Node) (valid bool, err error) {
return rl.lengthMatch(len(getAttrValue(n, rl.name)))
}
func (rl *attributeRuleLength) Info() string {
return rl.info
}
type attributeRuleRegex struct {
name string
regex *regexp.Regexp
}
func newattributeRuleRegex(name, regexString string) (rregex *attributeRuleRegex, err error) {
regexString, errUnescape := url.QueryUnescape(regexString)
if errUnescape != nil {
return nil, errUnescape
}
regex, errParse := regexp.Compile(regexString)
if errParse != nil {
return nil, errParse
}
return &attributeRuleRegex{
name: name,
regex: regex,
}, nil
}
func (rregex *attributeRuleRegex) Info() string {
return "regex :" + rregex.regex.String()
}
func (rregex *attributeRuleRegex) ValidateNode(n *html.Node) (valid bool, err error) {
return rregex.regex.Match([]byte(getAttrValue(n, rregex.name))), nil
}
+725
View File
@@ -0,0 +1,725 @@
package htmlschema
import (
"fmt"
"strconv"
"strings"
"github.com/andybalholm/cascadia"
"golang.org/x/net/html"
)
type kind int
const (
kindElement kind = iota
kindSelector
kindChoice
kindSequence
kindComp
kindLD
kindProp
)
type literal struct {
key string
val string // "*" = present and not empty
}
// element is a compiled schema element
type element struct {
kind kind
name string // tag name of kindElement
label string // path segment in findings
literals []literal
occ occurrence
text textRules
attrRules []*attrRule
value valueRules // kindProp
score int
scorePer string // "", "words" or "chars"
scoreUnit int
scoreMax int // unbounded = no cap
severity Severity
// severitySet marks an explicit severity, on a kindComp it is a ceiling for the instances
severitySet bool
penalty int // -1 = default by severity
penaltyMax int // unbounded = no cap
open bool
// every makes a val:prop check every array element, not just one
every bool
// skip is the wildcard scope this element is searched with, nil = direct children only
skip *wildcard
selector cascadia.Selector // kindSelector
comp *component // kindComp
ldType string // kindLD
propPath []string // kindProp
children []*element
source string
max int // maximum score, computed after compiling
nodeMax int // maximum score of one matched node
rules string
}
// wildcard is the scope of a val:wildcard - the wrappers to skip
type wildcard struct {
match cascadia.Selector
text string
}
// component is a file with a val:component root
type component struct {
path string // root relative, without extension: /components/teaser
label string
marker string
selector cascadia.Selector
node *rawNode
body []*element
open bool
compiled bool
max int
maxState int // 0 not computed, 1 computing, 2 done
}
type settings struct {
exclude cascadia.Selector
markerAttribute string
penalties map[Severity]int
}
func defaultSettings() settings {
return settings{
markerAttribute: "data-component",
penalties: map[Severity]int{SeverityError: 10, SeverityWarn: 3, SeverityInfo: 0},
}
}
// schema is a compiled group schema or default.html
type schema struct {
path string
settings settings
elements []*element
max int
}
type compiler struct {
root *Root
errs LintErrors
stack []string // include / comp chain for cycle detection
settings *settings
settingsNode *rawNode
}
func (c *compiler) errorf(n *rawNode, format string, args ...any) {
c.errs = append(c.errs, LintError{File: n.file, Line: n.line, Message: fmt.Sprintf(format, args...)})
}
// rule attributes, written with val: on html elements and without on val:* elements
var (
occurrenceKeys = []string{"min", "max", "count", "optional", "forbidden"}
textKeys = []string{"min-length", "max-length", "min-words", "max-words"}
scoreKeys = []string{"score", "score-per", "score-max"}
findingKeys = []string{"severity", "penalty", "penalty-max"}
)
func keySet(groups ...[]string) map[string]bool {
set := map[string]bool{}
for _, g := range groups {
for _, k := range g {
set[k] = true
}
}
return set
}
var allowedRules = map[kind]map[string]bool{
kindElement: keySet(occurrenceKeys, textKeys, scoreKeys, findingKeys, []string{"attr", "attr-*", "open"}),
kindSelector: keySet(occurrenceKeys, textKeys, scoreKeys, findingKeys, []string{"attr", "attr-*", "open"}),
kindChoice: keySet(occurrenceKeys, []string{"score-max"}, findingKeys),
kindSequence: keySet([]string{"score-max"}, findingKeys),
kindComp: keySet(occurrenceKeys, []string{"score-max"}, findingKeys, []string{"open"}),
kindLD: keySet(occurrenceKeys, []string{"score", "score-max"}, findingKeys),
kindProp: keySet([]string{"optional", "every"}, textKeys, []string{"value", "score", "severity", "penalty"}),
}
// structural attributes of val:* elements, they are not rules
var structuralAttrs = map[string][]string{
"val:selector": {"for"},
"val:wildcard": {"for"},
"val:include": {"path"},
"val:comp": {"path"},
"val:component": {"marker", "selector"},
"val:ld": {"type"},
"val:prop": {"path"},
"val:settings": {"exclude", "marker-attribute", "penalty-error", "penalty-warn", "penalty-info"},
}
// rule names that are easily written without val: on html elements
var forgottenPrefix = keySet(textKeys, scoreKeys, []string{"optional", "forbidden", "severity", "penalty", "penalty-max", "val"})
func defaultOccurrence(k kind, inChoice bool) occurrence {
switch {
case k == kindSelector:
return occurrence{1, unbounded}
case k == kindChoice, k == kindSequence:
return occurrence{0, unbounded}
case k == kindComp && inChoice:
return occurrence{0, unbounded}
}
return occurrence{1, 1}
}
func newElement(k kind, n *rawNode, skip *wildcard) *element {
return &element{
kind: k,
occ: defaultOccurrence(k, false),
text: newTextRules(),
scoreMax: unbounded,
severity: SeverityError,
penalty: -1,
penaltyMax: unbounded,
skip: skip,
source: n.source(),
value: valueRules{penalty: -1},
}
}
// ruleAttrs splits the attributes of n into rules and literals and checks the spelling
func (c *compiler) ruleAttrs(n *rawNode) (rules []html.Attribute, literals []html.Attribute) {
seen := map[string]bool{}
isVal := strings.HasPrefix(n.name, "val:")
structural := map[string]bool{}
for _, s := range structuralAttrs[n.name] {
structural[s] = true
}
for _, a := range n.attrs {
if seen[a.Key] {
c.errorf(n, "duplicate attribute %q", a.Key)
continue
}
seen[a.Key] = true
switch {
case isVal && structural[a.Key]:
case isVal && strings.HasPrefix(a.Key, "val:"):
c.errorf(n, "<%s> takes its rules without prefix: %q instead of %q", n.name, strings.TrimPrefix(a.Key, "val:"), a.Key)
case isVal:
rules = append(rules, a)
case strings.HasPrefix(a.Key, "val:"):
rules = append(rules, html.Attribute{Key: strings.TrimPrefix(a.Key, "val:"), Val: a.Val})
default:
if forgottenPrefix[a.Key] {
c.errorf(n, "attribute %q looks like a rule, did you mean %q?", a.Key, "val:"+a.Key)
continue
}
literals = append(literals, a)
}
}
return rules, literals
}
// applyRules parses rule attributes into e
func (c *compiler) applyRules(n *rawNode, e *element, rules []html.Attribute, inChoice bool) {
allowed := allowedRules[e.kind]
e.occ = defaultOccurrence(e.kind, inChoice)
e.rules = attrText(rules)
var (
minSet, maxSet, optional bool
minVal, maxVal int
)
number := func(a html.Attribute) (int, bool) {
v, err := strconv.Atoi(a.Val)
if err != nil || v < 0 {
c.errorf(n, "%s needs a number, got %q", a.Key, a.Val)
return 0, false
}
return v, true
}
for _, a := range rules {
key := a.Key
if strings.HasPrefix(key, "attr-") {
key = "attr-*"
}
if !allowed[key] {
c.errorf(n, "unknown rule %q on <%s>", a.Key, n.name)
continue
}
switch key {
case "optional":
optional = true
case "forbidden":
minSet, maxSet, minVal, maxVal = true, true, 0, 0
case "count":
if v, ok := number(a); ok {
minSet, maxSet, minVal, maxVal = true, true, v, v
}
case "min":
if v, ok := number(a); ok {
minSet, minVal = true, v
}
case "max":
if a.Val == "*" {
maxSet, maxVal = true, unbounded
} else if v, ok := number(a); ok {
maxSet, maxVal = true, v
}
case "min-length", "max-length", "min-words", "max-words":
v, ok := number(a)
if !ok {
continue
}
switch key {
case "min-length":
e.text.minLength = v
case "max-length":
e.text.maxLength = v
case "min-words":
e.text.minWords = v
case "max-words":
e.text.maxWords = v
}
case "attr-*", "attr":
attrName := strings.TrimPrefix(a.Key, "attr-")
spec := a.Val
if key == "attr" {
// v1 form: "name; rule; rule"
attrName, spec, _ = strings.Cut(a.Val, ";")
attrName = strings.TrimSpace(attrName)
}
vr, err := parseValueRules(spec)
if err != nil {
c.errorf(n, "%s: %s", a.Key, err)
continue
}
e.attrRules = append(e.attrRules, &attrRule{attr: attrName, valueRules: vr})
case "value":
vr, err := parseValueRules(a.Val)
if err != nil {
c.errorf(n, "value: %s", err)
continue
}
e.value = vr
case "score":
if v, ok := number(a); ok {
e.score = v
}
case "score-max":
if v, ok := number(a); ok {
e.scoreMax = v
}
case "score-per":
unit, k, _ := strings.Cut(a.Val, ":")
v, err := strconv.Atoi(k)
if (unit != "words" && unit != "chars") || err != nil || v <= 0 {
c.errorf(n, `score-per needs "words:n" or "chars:n", got %q`, a.Val)
continue
}
e.scorePer, e.scoreUnit = unit, v
case "severity":
sev, err := parseSeverity(a.Val)
if err != nil {
c.errorf(n, "%s", err)
continue
}
e.severity, e.severitySet = sev, true
case "penalty":
if v, ok := number(a); ok {
e.penalty = v
}
case "penalty-max":
if v, ok := number(a); ok {
e.penaltyMax = v
}
case "open":
e.open = true
case "every":
e.every = true
}
}
if optional {
if minSet {
c.errorf(n, "optional together with min or count")
}
e.occ.min = 0
}
if minSet {
e.occ.min = minVal
if !maxSet {
e.occ.max = unbounded
}
}
if maxSet {
e.occ.max = maxVal
}
if e.occ.max != unbounded && e.occ.min > e.occ.max {
c.errorf(n, "min %d is greater than max %d", e.occ.min, e.occ.max)
}
}
func (c *compiler) compileNodes(nodes []*rawNode, parent *rawNode, skip *wildcard, inChoice bool) (elements []*element) {
for _, n := range nodes {
elements = append(elements, c.compileNode(n, parent, skip, inChoice)...)
}
return elements
}
func (c *compiler) enter(key string, n *rawNode) bool {
for _, s := range c.stack {
if s == key {
c.errorf(n, "cycle: %s -> %s", strings.Join(c.stack, " -> "), key)
return false
}
}
c.stack = append(c.stack, key)
return true
}
func (c *compiler) leave() {
c.stack = c.stack[:len(c.stack)-1]
}
// target resolves the path attribute of an include or comp
func (c *compiler) target(n *rawNode) (key string, file *rawNode) {
p, ok := n.attr("path")
if !ok || p == "" {
c.errorf(n, "<%s> needs a path", n.name)
return "", nil
}
key = resolvePath(fileKey(n.file), p)
file = c.root.files[key]
if file == nil {
c.errorf(n, "%s: %s not found", n.name, key)
return "", nil
}
return key, file
}
func (c *compiler) compileNode(n *rawNode, parent *rawNode, skip *wildcard, inChoice bool) []*element {
switch n.name {
case "val:include":
c.onlyStructural(n)
c.noChildren(n)
key, file := c.target(n)
if file == nil || !c.enter(key, n) {
return nil
}
defer c.leave()
return c.compileNodes(file.children, parent, skip, inChoice)
case "val:wildcard":
c.onlyStructural(n)
f, ok := n.attr("for")
if !ok {
c.errorf(n, `<val:wildcard> needs a for="css" attribute`)
}
var scope *wildcard
if strings.TrimSpace(f) != "" {
sel, err := cascadia.Compile(f)
if err != nil {
c.errorf(n, "invalid for %q: %s", f, err)
}
scope = &wildcard{match: sel, text: strings.TrimSpace(f)}
}
return c.compileNodes(n.children, parent, scope, inChoice)
case "val:comp":
return c.compileComp(n, parent, skip, inChoice)
case "val:settings":
if parent == nil || parent.name != "html" {
c.errorf(n, "<val:settings> has to be a direct child of <html>")
return nil
}
c.compileSettings(n)
return nil
case "val:component":
c.errorf(n, "<val:component> is only allowed as the root of a component file")
return nil
case "val:selector":
e := newElement(kindSelector, n, skip)
f, _ := n.attr("for")
sel, err := cascadia.Compile(f)
if err != nil || f == "" {
c.errorf(n, "<val:selector> needs a valid for=\"css\", got %q", f)
}
e.selector = sel
e.label = "val:selector(" + f + ")"
c.finishElement(n, e, inChoice)
return []*element{e}
case "val:choice", "val:sequence":
k := kindChoice
if n.name == "val:sequence" {
k = kindSequence
}
e := newElement(k, n, skip)
e.label = n.name
rules, _ := c.ruleAttrs(n)
c.applyRules(n, e, rules, false)
for _, child := range c.compileNodes(n.children, n, skip, k == kindChoice) {
if child.kind != kindComp || child.comp == nil {
c.errorf(n, "<%s> may only contain val:comp of components (%s)", n.name, child.source)
continue
}
e.children = append(e.children, child)
}
return []*element{e}
case "val:ld":
e := newElement(kindLD, n, skip)
e.ldType, _ = n.attr("type")
if e.ldType == "" {
c.errorf(n, "<val:ld> needs a type")
}
e.label = "val:ld(" + e.ldType + ")"
rules, _ := c.ruleAttrs(n)
c.applyRules(n, e, rules, false)
for _, child := range n.children {
if child.name != "val:prop" {
c.errorf(child, "<val:ld> may only contain <val:prop>")
continue
}
p := newElement(kindProp, child, nil)
path, _ := child.attr("path")
if path == "" {
c.errorf(child, "<val:prop> needs a path")
}
p.propPath = strings.Split(path, ".")
p.label = path
propRules, _ := c.ruleAttrs(child)
c.applyRules(child, p, propRules, false)
c.noChildren(child)
e.children = append(e.children, p)
}
return []*element{e}
}
if strings.HasPrefix(n.name, "val:") {
c.errorf(n, "unknown element <%s>", n.name)
return nil
}
e := newElement(kindElement, n, skip)
e.name = n.name
c.finishElement(n, e, inChoice)
return []*element{e}
}
// finishElement parses rules and literals of an html element or val:selector and compiles its children
func (c *compiler) finishElement(n *rawNode, e *element, inChoice bool) {
rules, literals := c.ruleAttrs(n)
c.applyRules(n, e, rules, inChoice)
for _, l := range literals {
e.literals = append(e.literals, literal{key: l.Key, val: l.Val})
}
if len(literals) > 0 {
e.rules = strings.TrimSpace(attrText(literals) + " " + e.rules)
}
if e.kind == kindElement {
e.label = e.name
if len(e.literals) > 0 {
e.label += "[" + e.literals[0].key + "=" + e.literals[0].val + "]"
}
}
// the wildcard scope is lexical: children inherit it
e.children = c.compileNodes(n.children, n, e.skip, false)
c.checkContext(n, e.children)
}
// checkContext reports components that are used more than once in one component context
func (c *compiler) checkContext(n *rawNode, children []*element) {
used := map[*component]bool{}
for _, child := range children {
uses := []*element{child}
if child.kind == kindChoice || child.kind == kindSequence {
uses = child.children
}
for _, use := range uses {
if use.kind != kindComp || use.comp == nil {
continue
}
if used[use.comp] {
c.errorf(n, "%s is used more than once in this context", use.comp.path)
}
used[use.comp] = true
}
}
}
// onlyStructural reports every attribute of n that is not structural
func (c *compiler) onlyStructural(n *rawNode) {
rules, _ := c.ruleAttrs(n)
for _, a := range rules {
c.errorf(n, "unknown attribute %q on <%s>", a.Key, n.name)
}
}
func (c *compiler) noChildren(n *rawNode) {
if len(n.children) > 0 {
c.errorf(n, "<%s> must not have children, close it with />", n.name)
}
}
func (c *compiler) compileSettings(n *rawNode) {
if c.settingsNode != nil {
c.errorf(n, "duplicate <val:settings>, first one at %s", c.settingsNode.source())
return
}
c.settingsNode = n
c.onlyStructural(n)
for _, a := range n.attrs {
switch a.Key {
case "exclude":
sel, err := cascadia.Compile(a.Val)
if err != nil {
c.errorf(n, "invalid exclude %q: %s", a.Val, err)
continue
}
c.settings.exclude = sel
case "marker-attribute":
c.settings.markerAttribute = a.Val
case "penalty-error", "penalty-warn", "penalty-info":
v, err := strconv.Atoi(a.Val)
if err != nil || v < 0 {
c.errorf(n, "%s needs a number, got %q", a.Key, a.Val)
continue
}
c.settings.penalties[Severity(strings.TrimPrefix(a.Key, "penalty-"))] = v
}
}
c.noChildren(n)
}
// compileComp instantiates the single root element of a file, the attributes of
// val:comp override or extend the ones of the root
func (c *compiler) compileComp(n *rawNode, parent *rawNode, skip *wildcard, inChoice bool) []*element {
c.noChildren(n)
key, file := c.target(n)
if file == nil {
return nil
}
if len(file.children) != 1 {
c.errorf(n, "%s can not be instantiated, it has %d top level elements instead of one - use val:include", key, len(file.children))
return nil
}
if !c.enter(key, n) {
return nil
}
defer c.leave()
root := file.children[0]
merged := c.mergeAttrs(root, n)
if root.name != "val:component" {
return c.compileNode(merged, parent, skip, inChoice)
}
comp := c.root.components[key]
c.compileComponent(comp)
e := newElement(kindComp, n, skip)
e.comp = comp
e.label = comp.label
rules, _ := c.ruleAttrs(merged)
c.applyRules(n, e, rules, inChoice)
return []*element{e}
}
func (c *compiler) mergeAttrs(root *rawNode, site *rawNode) *rawNode {
isVal := strings.HasPrefix(root.name, "val:")
canonical := func(k string) string {
if isVal {
return "val:" + k
}
return k
}
occurrence := keySet(occurrenceKeys)
siteHasOccurrence := false
var overrides []html.Attribute
for _, a := range site.attrs {
if a.Key == "path" {
continue
}
if isVal && !strings.HasPrefix(a.Key, "val:") {
c.errorf(site, "%s: literal attribute %q can not be set on <%s>", site.name, a.Key, root.name)
continue
}
name := strings.TrimPrefix(a.Key, "val:")
if root.name == "val:component" && (name == "marker" || name == "selector") {
c.errorf(site, "%s of a component can not be overridden", name)
continue
}
if strings.HasPrefix(a.Key, "val:") && occurrence[name] {
siteHasOccurrence = true
}
overrides = append(overrides, a)
}
merged := &rawNode{name: root.name, children: root.children, file: root.file, line: root.line}
for _, a := range root.attrs {
key := a.Key
if isVal {
for _, s := range structuralAttrs[root.name] {
if s == key {
key = "#" + key // structural attributes are kept as they are
}
}
}
if !strings.HasPrefix(key, "#") {
key = canonical(key)
}
if siteHasOccurrence && strings.HasPrefix(key, "val:") && occurrence[strings.TrimPrefix(key, "val:")] {
continue
}
overridden := false
for _, o := range overrides {
if o.Key == key {
overridden = true
}
}
if !overridden {
merged.attrs = append(merged.attrs, a)
}
}
for _, o := range overrides {
key := o.Key
if isVal {
key = strings.TrimPrefix(key, "val:")
}
merged.attrs = append(merged.attrs, html.Attribute{Key: key, Val: o.Val})
}
return merged
}
func (c *compiler) compileComponent(comp *component) {
if comp.compiled {
return
}
comp.compiled = true
n := comp.node
rules, _ := c.ruleAttrs(n)
c.applyRules(n, newElement(kindComp, n, nil), rules, false)
comp.marker, _ = n.attr("marker")
if s, ok := n.attr("selector"); ok && s != "" {
sel, err := cascadia.Compile(s)
if err != nil {
c.errorf(n, "invalid selector %q: %s", s, err)
}
comp.selector = sel
}
if comp.marker == "" && comp.selector == nil {
c.errorf(n, "a component needs a marker, a selector or both")
}
_, comp.open = n.attr("open")
// wildcards do not reach into a component
comp.body = c.compileNodes(n.children, n, nil, false)
c.checkContext(n, comp.body)
}
// fileKey turns a display file name into a root relative key without extension
func fileKey(file string) string {
return "/" + strings.TrimSuffix(file, ".html")
}
// attrText writes attributes as in a schema: key=value, or key for booleans
func attrText(attrs []html.Attribute) string {
parts := make([]string, len(attrs))
for i, a := range attrs {
switch {
case a.Val == "":
parts[i] = a.Key
case strings.ContainsAny(a.Val, " \"'"):
parts[i] = a.Key + "=" + strconv.Quote(a.Val)
default:
parts[i] = a.Key + "=" + a.Val
}
}
return strings.Join(parts, " ")
}
+113
View File
@@ -0,0 +1,113 @@
package htmlschema
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// writeRoot writes a schema root from file name -> content
func writeRoot(t *testing.T, files map[string]string) string {
t.Helper()
dir := t.TempDir()
for name, content := range files {
p := filepath.Join(dir, filepath.FromSlash(name))
require.NoError(t, os.MkdirAll(filepath.Dir(p), 0o755))
require.NoError(t, os.WriteFile(p, []byte(content), 0o644))
}
return dir
}
func body(content string) string {
return "<html><head></head><body>" + content + "</body></html>"
}
func TestLint(t *testing.T) {
teaser := `<val:component marker="teaser" selector=".teaser"><h3/></val:component>`
for name, tc := range map[string]struct {
files map[string]string
want string
}{
"unknown rule": {map[string]string{"default.html": body(`<h1 val:foo=1/>`)}, `default.html:1: unknown rule "foo" on <h1>`},
"forgotten prefix": {map[string]string{"default.html": body(`<h1 score=1/>`)}, `attribute "score" looks like a rule, did you mean "val:score"?`},
"v1 typo val=optional": {map[string]string{"default.html": body(`<h1 val=optional/>`)}, `attribute "val" looks like a rule`},
"prefix on val element": {map[string]string{"default.html": body(`<val:selector for="h1" val:count=1/>`)}, `<val:selector> takes its rules without prefix: "count" instead of "val:count"`},
"duplicate attribute": {map[string]string{"default.html": body(`<h1 val:score=1 val:score=2/>`)}, `duplicate attribute "val:score"`},
"min greater max": {map[string]string{"default.html": body(`<h1 val:min=3 val:max=2/>`)}, "min 3 is greater than max 2"},
"optional and min": {map[string]string{"default.html": body(`<h1 val:optional val:min=1/>`)}, "optional together with min or count"},
"unknown element": {map[string]string{"default.html": body(`<val:foo/>`)}, "unknown element <val:foo>"},
"unclosed element": {map[string]string{"default.html": "<html><body><main></body></html>"}, "<main> is not closed"},
"missing include": {map[string]string{"default.html": body(`<val:include path="/nope"/>`)}, "val:include: /nope not found"},
"include with children": {map[string]string{"default.html": body(`<val:include path="/a"><h1/></val:include>`), "a.html": "<h2/>"}, "<val:include> must not have children"},
"include cycle": {map[string]string{"default.html": body(`<val:include path="/a"/>`), "a.html": `<val:include path="b"/>`, "b.html": `<val:include path="/a"/>`}, "cycle: /default -> /a -> /b -> /a"},
"comp of a multi root file": {map[string]string{"default.html": body(`<val:comp path="/two"/>`), "two.html": "<h1/><h2/>"}, "/two can not be instantiated, it has 2 top level elements"},
"marker override": {map[string]string{"default.html": body(`<main><val:comp path="/teaser" val:marker="x"/></main>`), "teaser.html": teaser}, "marker of a component can not be overridden"},
"literal on val root": {map[string]string{"default.html": body(`<main><val:comp path="/teaser" class="x"/></main>`), "teaser.html": teaser}, `literal attribute "class" can not be set on <val:component>`},
"duplicate marker": {map[string]string{"default.html": body(""), "a.html": teaser, "b.html": teaser}, `marker "teaser" is already used by /a`},
"unbounded maximum": {map[string]string{"default.html": body(`<p val:min=1 val:score=1/>`)}, "the maximum score is unbounded, add score-max"},
"unbounded score-per": {map[string]string{"default.html": body(`<p val:score=1 val:score-per="words:10"/>`)}, "the maximum score is unbounded"},
"component twice in context": {map[string]string{"default.html": body(`<main><val:choice><val:comp path="/teaser"/></val:choice><val:comp path="/teaser"/></main>`), "teaser.html": teaser}, "/teaser is used more than once in this context"},
"element in choice": {map[string]string{"default.html": body(`<main><val:choice><h1/></val:choice></main>`)}, "<val:choice> may only contain val:comp of components"},
"settings outside html": {map[string]string{"default.html": body(`<val:settings exclude=".x"/>`)}, "<val:settings> has to be a direct child of <html>"},
"unknown attribute on wildcard": {map[string]string{"default.html": body(`<val:wildcard for="div" deep/>`)}, `unknown attribute "deep" on <val:wildcard>`},
"invalid regex": {map[string]string{"default.html": body(`<a val:attr-href="regex:(["/>`)}, "attr-href: invalid regex"},
"every outside val:prop": {map[string]string{"default.html": body(`<h1 val:every/>`)}, `unknown rule "every" on <h1>`},
"unknown attribute rule": {map[string]string{"default.html": body(`<a val:attr-href="absolute"/>`)}, `attr-href: unknown rule "absolute"`},
} {
t.Run(name, func(t *testing.T) {
_, err := LoadRoot(writeRoot(t, tc.files))
require.Error(t, err)
assert.Contains(t, err.Error(), tc.want)
})
}
}
func TestLoadDemoRoot(t *testing.T) {
root := loadDemoRoot(t)
assert.Equal(t, []string{"/components/category-tile", "/components/feature-section", "/components/product-tile"}, func() (paths []string) {
for _, c := range root.componentList {
paths = append(paths, c.path)
}
return paths
}())
assert.Equal(t, 117, root.schemas["/groups/index"].max)
assert.Equal(t, 182, root.schemas["/groups/category"].max)
assert.Equal(t, 145, root.schemas["/groups/product"].max)
assert.Equal(t, 44, root.schemas["/default"].max)
}
func TestResolvePath(t *testing.T) {
assert.Equal(t, "/partials/head", resolvePath("/groups/content/landing", "/partials/head"))
assert.Equal(t, "/partials/head", resolvePath("/groups/content/landing", "../../partials/head"))
assert.Equal(t, "/groups/content/teaser", resolvePath("/groups/content/landing", "teaser.html"))
}
func TestRootVersion(t *testing.T) {
dir := writeRoot(t, map[string]string{"default.html": body(""), "partials/a.html": "<h1/>", "notes.txt": "x"})
v1, err := RootVersion(dir)
require.NoError(t, err)
v2, _ := RootVersion(dir)
assert.Equal(t, v1, v2, "nothing changed")
// other files do not count
require.NoError(t, os.WriteFile(filepath.Join(dir, "notes.txt"), []byte("changed"), 0o644))
v3, _ := RootVersion(dir)
assert.Equal(t, v1, v3)
// an edit, a new file and a removed one do
require.NoError(t, os.WriteFile(filepath.Join(dir, "partials", "a.html"), []byte("<h1 val:score=1/>"), 0o644))
v4, _ := RootVersion(dir)
assert.NotEqual(t, v1, v4)
require.NoError(t, os.WriteFile(filepath.Join(dir, "partials", "b.html"), []byte("<h2/>"), 0o644))
v5, _ := RootVersion(dir)
assert.NotEqual(t, v4, v5)
require.NoError(t, os.Remove(filepath.Join(dir, "partials", "b.html")))
v6, _ := RootVersion(dir)
assert.NotEqual(t, v5, v6)
_, err = RootVersion(filepath.Join(dir, "nope"))
assert.Error(t, err)
}
@@ -0,0 +1,8 @@
<!-- a category on the index page: image, name and a teaser text -->
<val:component marker="category-tile">
<a val:attr-href="required" val:score="1">
<img val:score="2" val:attr-alt="min-length:5" val:attr-src="required" />
<h3 val:score="2" val:min-length="3" />
</a>
<p val:score="2" val:min-words="10" />
</val:component>
@@ -0,0 +1,14 @@
<!-- a section of product features: a heading and a definition list -->
<val:component marker="feature-section">
<h2 val:score="2" val:min-length="3" />
<dl>
<dt val:min="1" val:max="*" val:score="1" val:score-max="4" />
<dd
val:min="1"
val:max="*"
val:min-words="3"
val:score="1"
val:score-max="4"
/>
</dl>
</val:component>
@@ -0,0 +1,18 @@
<!-- a product in a category: image, name and price -->
<val:component marker="product-tile">
<a val:attr-href="required" val:score="1">
<img
val:score="2"
val:attr-alt="min-length:3"
val:attr-src="required"
/>
<h2
val:score="2"
val:min-length="3"
val:max-length="60"
val:severity="warn"
/>
</a>
<p class="price" val:score="1" val:min-length="3" />
</val:component>
+17
View File
@@ -0,0 +1,17 @@
<!--
fallback for pages without a group, e.g. the 404 page
-->
<html val:attr-lang="one-of:en|de">
<head>
<title val:score="10" val:min-length="10" val:max-length="60" />
<val:include path="/partials/head" />
</head>
<body>
<val:include path="/partials/page-baseline" />
<val:comp path="/partials/site-header" />
<main>
<h1 val:score="10" />
</main>
<val:comp path="/partials/site-footer" />
</body>
</html>
@@ -0,0 +1,76 @@
<!--
group category - a category with all its products as tiles
-->
<html val:attr-lang="one-of:en|de">
<head>
<title val:score="10" val:min-length="10" val:max-length="60" />
<val:include path="/partials/head" />
<meta property="og:type" content="website" />
</head>
<body>
<val:ld type="BreadcrumbList" score="5">
<val:prop path="itemListElement.item" value="url:absolute" />
</val:ld>
<!--
a host carousel: every list item is a complete product with its own
page - every checks all of them, one good product must not hide a bad one
-->
<val:ld type="ItemList" score="10">
<val:prop
path="itemListElement.position"
every
value="regex:^[0-9]+$"
/>
<val:prop
path="itemListElement.item.@type"
every
value="one-of:Product"
/>
<val:prop
path="itemListElement.item.name"
every
min-length="3"
max-length="60"
severity="warn"
/>
<val:prop
path="itemListElement.item.url"
every
value="url:absolute"
/>
<val:prop
path="itemListElement.item.image"
every
value="url:absolute"
/>
<val:prop
path="itemListElement.item.offers.price"
every
value="regex:^[0-9]+\.[0-9]{2}$"
/>
<val:prop
path="itemListElement.item.offers.priceCurrency"
every
value="one-of:EUR|USD|CHF|DOGE"
/>
</val:ld>
<val:include path="/partials/page-baseline" />
<val:comp path="/partials/site-header" />
<main>
<val:comp path="/partials/breadcrumbs" />
<h1
val:score="20"
val:min-length="3"
val:max-length="70"
val:penalty="50"
/>
<p class="lead" val:score="10" val:min-words="15" />
<val:wildcard for="div">
<val:choice min="1" max="40" score-max="100">
<val:comp path="/components/product-tile" val:max="40" />
</val:choice>
</val:wildcard>
</main>
<val:comp path="/partials/site-footer" />
</body>
</html>
+51
View File
@@ -0,0 +1,51 @@
<!--
group index - the home page: what the shop is, its categories and how the demo works
-->
<html val:attr-lang="one-of:en|de">
<head>
<title val:score="10" val:min-length="10" val:max-length="60" />
<val:include path="/partials/head" />
<meta property="og:type" content="website" />
</head>
<body>
<val:ld type="WebSite" score="5">
<val:prop path="name" min-length="3" />
<val:prop path="url" value="url:absolute" />
</val:ld>
<val:include path="/partials/page-baseline" />
<val:comp path="/partials/site-header" />
<main>
<h1
val:score="20"
val:min-length="20"
val:max-length="70"
val:penalty="50"
/>
<p class="lead" val:score="10" val:min-words="20" />
<section aria-labelledby="categories">
<h2 val:score="2" />
<val:wildcard for="div">
<val:choice min="1" max="10" score-max="40">
<val:comp
path="/components/category-tile"
val:max="10"
/>
</val:choice>
</val:wildcard>
</section>
<section aria-labelledby="about" val:optional>
<h2 />
<p
val:min="1"
val:max="*"
val:score="2"
val:score-max="6"
val:min-words="3"
val:max-words="100"
/>
</section>
</main>
<val:comp path="/partials/site-footer" />
</body>
</html>
+123
View File
@@ -0,0 +1,123 @@
<!--
group product - a product page: image, name, price, description and feature sections
-->
<html val:attr-lang="one-of:en|de">
<head>
<title
val:score="10"
val:penalty="20"
val:min-length="20"
val:max-length="60"
/>
<val:include path="/partials/head" />
<meta property="og:type" content="product" />
<meta property="product:price:amount" content="*" val:score="2" />
<meta
property="product:price:currency"
val:attr-content="one-of:EUR|USD|CHF"
/>
</head>
<body>
<val:ld type="Product" score="20">
<val:prop path="name" min-length="3" max-length="60" />
<val:prop path="description" min-length="70" />
<val:prop path="image" value="url:absolute" />
<val:prop path="sku" value="required" />
<val:prop path="offers.price" value="regex:^[0-9]+\.[0-9]{2}$" />
<val:prop path="offers.priceCurrency" value="one-of:EUR|USD|CHF" />
<val:prop
path="offers.availability"
value="regex:^https://schema\.org/(InStock|OutOfStock|PreOrder)$"
/>
<!-- recommended for merchant listings: missing costs points, wrong is a finding -->
<val:prop path="brand.name" optional score="2" min-length="2" />
<val:prop
path="offers.itemCondition"
optional
score="1"
value="regex:^https://schema\.org/(New|Used|Refurbished|Damaged)Condition$"
/>
<val:prop
path="offers.priceValidUntil"
optional
score="1"
value="regex:^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
/>
<val:prop
path="offers.shippingDetails.shippingRate.value"
optional
score="2"
value="regex:^[0-9]+(\.[0-9]+)?$"
/>
<val:prop
path="offers.shippingDetails.shippingRate.currency"
optional
value="one-of:EUR|USD|CHF"
/>
<val:prop
path="offers.shippingDetails.shippingDestination.addressCountry"
optional
score="1"
value="regex:^[A-Z]{2}$"
/>
<val:prop
path="offers.shippingDetails.deliveryTime.transitTime.maxValue"
optional
score="1"
value="regex:^[0-9]+$"
/>
<val:prop
path="offers.hasMerchantReturnPolicy.returnPolicyCategory"
optional
score="2"
value="regex:^https://schema\.org/MerchantReturn(FiniteReturnWindow|NotPermitted|UnlimitedWindow)$"
/>
<val:prop
path="offers.hasMerchantReturnPolicy.merchantReturnDays"
optional
score="1"
value="regex:^[0-9]+$"
/>
</val:ld>
<val:ld type="BreadcrumbList" score="5">
<val:prop path="itemListElement.item" value="url:absolute" />
</val:ld>
<val:include path="/partials/page-baseline" />
<val:comp path="/partials/site-header" />
<main>
<val:comp path="/partials/breadcrumbs" />
<article>
<val:wildcard for="div">
<figure val:score="2">
<img
val:score="3"
val:attr-alt="min-length:3"
val:attr-src="required"
/>
</figure>
<h1
val:score="20"
val:penalty="50"
val:min-length="3"
val:max-length="60"
/>
<p class="price" val:score="5" val:min-length="3" />
<p
class="description"
val:score="2"
val:score-per="words:10"
val:score-max="10"
val:min-words="12"
/>
<val:choice min="1" max="6" score-max="30">
<val:comp
path="/components/feature-section"
val:max="6"
/>
</val:choice>
</val:wildcard>
</article>
</main>
<val:comp path="/partials/site-footer" />
</body>
</html>
@@ -0,0 +1,6 @@
<!-- breadcrumbs: an ordered list of links, home first -->
<nav aria-label="Breadcrumb" val:score="3">
<val:wildcard for="ol, li">
<a val:min="2" val:max="5" val:attr-href="required" val:min-length="2" />
</val:wildcard>
</nav>
+15
View File
@@ -0,0 +1,15 @@
<!--
head rules of every page - the title is checked per group, it has
different lengths for an index and a product
-->
<meta charset="*" />
<meta name="viewport" val:attr-content="required" />
<meta name="description" val:score="10" val:attr-content="min-length:70; max-length:160" />
<link rel="canonical" val:score="5" val:attr-href="url:absolute" />
<meta property="og:site_name" val:attr-content="required" />
<meta property="og:title" val:score="2" val:attr-content="min-length:10; max-length:90" />
<meta property="og:description" val:score="2" val:attr-content="min-length:70; max-length:200" />
<meta property="og:url" val:score="2" val:attr-content="url:absolute" />
<!-- social networks do not render svg previews -->
<meta property="og:image" val:optional val:score="3" val:attr-content="url:absolute; regex:\.(png|jpe?g|webp|gif)(\?.*)?$" />
<meta name="twitter:card" val:optional val:attr-content="one-of:summary|summary_large_image" />
@@ -0,0 +1,2 @@
<!-- page wide rules - exactly one h1, wherever it is -->
<val:selector for="h1" count="1" />
@@ -0,0 +1,7 @@
<!-- the footer: links to the categories and a short text -->
<footer>
<nav aria-label="Footer">
<a val:min="1" val:max="10" val:attr-href="required" />
</nav>
<p />
</footer>
@@ -0,0 +1,9 @@
<!-- the site header: a logo link and the main navigation -->
<header>
<a val:attr-href="required" />
<nav aria-label="Main">
<val:wildcard for="ul, li">
<a val:min="2" val:max="10" val:attr-href="required" />
</val:wildcard>
</nav>
</header>
@@ -0,0 +1,35 @@
{
"ID": "car-01",
"Name": "Turbo Turtle",
"Description": "The slowest sports car in the world, built for people who want to look fast while enjoying every single moment of the scenic route.",
"Price": 2499000,
"Currency": "EUR",
"FeatureSections": [
{
"Label": "Performance",
"Features": [
{
"Label": "Top speed",
"Description": "A relaxed thirty kilometres per hour"
},
{
"Label": "Acceleration",
"Description": "Zero to thirty by lunchtime"
}
]
},
{
"Label": "Comfort",
"Features": [
{
"Label": "Shell roof",
"Description": "Waterproof and surprisingly stylish"
},
{
"Label": "Seats",
"Description": "Heated, cooled and very patient"
}
]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" role="img" aria-labelledby="t">
<title id="t">Turbo Turtle</title>
<rect width="200" height="200" rx="24" fill="#f5f6fa"/>
<rect x="0" y="150" width="200" height="50" fill="#dfe6e9"/>
<path d="M58 98 L76 66 L132 66 L150 98 Z" fill="#6c5ce7" opacity="0.85"/>
<path d="M74 96 L86 72 L122 72 L134 96 Z" fill="#ffffff" opacity="0.8"/>
<rect x="26" y="96" width="148" height="40" rx="14" fill="#6c5ce7"/>
<circle cx="164" cy="112" r="6" fill="#ffeaa7"/>
<circle cx="62" cy="140" r="17" fill="#2d3436"/><circle cx="62" cy="140" r="7" fill="#b2bec3"/>
<circle cx="140" cy="140" r="17" fill="#2d3436"/><circle cx="140" cy="140" r="7" fill="#b2bec3"/>
<path d="M90 116 h20" stroke="#ffffff" stroke-width="4" stroke-linecap="round" opacity="0.7"/>
</svg>

After

Width:  |  Height:  |  Size: 827 B

@@ -0,0 +1,35 @@
{
"ID": "car-02",
"Name": "Banana Roadster",
"Description": "A bright yellow convertible shaped like a banana that is guaranteed to make every traffic jam a little more cheerful and slippery.",
"Price": 1899000,
"Currency": "EUR",
"FeatureSections": [
{
"Label": "Design",
"Features": [
{
"Label": "Colour",
"Description": "Ripe yellow with tiny brown spots"
},
{
"Label": "Peelable roof",
"Description": "Opens in three elegant strips"
}
]
},
{
"Label": "Fun",
"Features": [
{
"Label": "Smile factor",
"Description": "Pedestrians wave at you constantly"
},
{
"Label": "Horn",
"Description": "Plays a short marimba melody"
}
]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" role="img" aria-labelledby="t">
<title id="t">Banana Roadster</title>
<rect width="200" height="200" rx="24" fill="#f5f6fa"/>
<rect x="0" y="150" width="200" height="50" fill="#dfe6e9"/>
<path d="M50 98 Q100 46 156 98 Z" fill="#ffd93d" opacity="0.85"/>
<path d="M74 96 L86 72 L122 72 L134 96 Z" fill="#ffffff" opacity="0.8"/>
<rect x="26" y="96" width="148" height="40" rx="14" fill="#ffd93d"/>
<circle cx="164" cy="112" r="6" fill="#ffeaa7"/>
<circle cx="62" cy="140" r="17" fill="#2d3436"/><circle cx="62" cy="140" r="7" fill="#b2bec3"/>
<circle cx="140" cy="140" r="17" fill="#2d3436"/><circle cx="140" cy="140" r="7" fill="#b2bec3"/>
<path d="M90 116 h20" stroke="#ffffff" stroke-width="4" stroke-linecap="round" opacity="0.7"/>
</svg>

After

Width:  |  Height:  |  Size: 822 B

@@ -0,0 +1,35 @@
{
"ID": "car-03",
"Name": "The Grocery Getter",
"Description": "Fits eleven shopping bags, two watermelons and a surprised cat, and remembers exactly which aisle the oat milk was hiding in.",
"Price": 2199000,
"Currency": "EUR",
"FeatureSections": [
{
"Label": "Space",
"Features": [
{
"Label": "Trunk",
"Description": "Eleven bags and one emergency baguette"
},
{
"Label": "Melon holders",
"Description": "Shock absorbing for fragile fruit"
}
]
},
{
"Label": "Smart features",
"Features": [
{
"Label": "Aisle memory",
"Description": "Remembers every product location"
},
{
"Label": "List reminder",
"Description": "Nags gently about forgotten butter"
}
]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" role="img" aria-labelledby="t">
<title id="t">The Grocery Getter</title>
<rect width="200" height="200" rx="24" fill="#f5f6fa"/>
<rect x="0" y="150" width="200" height="50" fill="#dfe6e9"/>
<path d="M64 98 L64 62 L140 62 L150 98 Z" fill="#fd79a8" opacity="0.85"/>
<path d="M74 96 L86 72 L122 72 L134 96 Z" fill="#ffffff" opacity="0.8"/>
<rect x="26" y="96" width="148" height="40" rx="14" fill="#fd79a8"/>
<circle cx="164" cy="112" r="6" fill="#ffeaa7"/>
<circle cx="62" cy="140" r="17" fill="#2d3436"/><circle cx="62" cy="140" r="7" fill="#b2bec3"/>
<circle cx="140" cy="140" r="17" fill="#2d3436"/><circle cx="140" cy="140" r="7" fill="#b2bec3"/>
<path d="M90 116 h20" stroke="#ffffff" stroke-width="4" stroke-linecap="round" opacity="0.7"/>
</svg>

After

Width:  |  Height:  |  Size: 833 B

@@ -0,0 +1,35 @@
{
"ID": "car-04",
"Name": "The Extremely Long Named Family Station Wagon Of Endless Road Trips Edition",
"Description": "Room for seven people, nine suitcases and the never ending question of whether we are there yet, asked approximately every four minutes.",
"Price": 3499000,
"Currency": "EUR",
"FeatureSections": [
{
"Label": "Family",
"Features": [
{
"Label": "Seats",
"Description": "Seven, all with individual cup holders"
},
{
"Label": "Snack bar",
"Description": "Built into the center console"
}
]
},
{
"Label": "Road trips",
"Features": [
{
"Label": "Are we there yet",
"Description": "Answered automatically every four minutes"
},
{
"Label": "Games",
"Description": "I spy with eight hundred objects"
}
]
}
]
}
@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" role="img" aria-labelledby="t">
<title id="t">The Extremely Long Named Family Station Wagon Of Endless Road Trips Edition</title>
<rect width="200" height="200" rx="24" fill="#f5f6fa"/>
<rect x="0" y="150" width="200" height="50" fill="#dfe6e9"/>
<path d="M58 98 L76 66 L132 66 L150 98 Z" fill="#0984e3" opacity="0.85"/>
<path d="M74 96 L86 72 L122 72 L134 96 Z" fill="#ffffff" opacity="0.8"/>
<rect x="26" y="96" width="148" height="40" rx="14" fill="#0984e3"/>
<circle cx="164" cy="112" r="6" fill="#ffeaa7"/>
<circle cx="62" cy="140" r="17" fill="#2d3436"/><circle cx="62" cy="140" r="7" fill="#b2bec3"/>
<circle cx="140" cy="140" r="17" fill="#2d3436"/><circle cx="140" cy="140" r="7" fill="#b2bec3"/>
<path d="M90 116 h20" stroke="#ffffff" stroke-width="4" stroke-linecap="round" opacity="0.7"/>
</svg>

After

Width:  |  Height:  |  Size: 890 B

@@ -0,0 +1,35 @@
{
"ID": "car-05",
"Name": "Puddle Jumper 4x4",
"Description": "An off road vehicle that is mortally afraid of mud, avoids every puddle with elegant swerves and keeps itself shiny at all times.",
"Price": 2899000,
"Currency": "EUR",
"FeatureSections": [
{
"Label": "Off road",
"Features": [
{
"Label": "Puddle avoidance",
"Description": "Swerves around water up to two metres"
},
{
"Label": "Mud alarm",
"Description": "Sounds when a puddle looks suspicious"
}
]
},
{
"Label": "Care",
"Features": [
{
"Label": "Self polish",
"Description": "Shiny even after a forest trip"
},
{
"Label": "Tyres",
"Description": "Mostly decorative, but very clean"
}
]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" role="img" aria-labelledby="t">
<title id="t">Puddle Jumper 4x4</title>
<rect width="200" height="200" rx="24" fill="#f5f6fa"/>
<rect x="0" y="150" width="200" height="50" fill="#dfe6e9"/>
<path d="M50 98 Q100 46 156 98 Z" fill="#e17055" opacity="0.85"/>
<path d="M74 96 L86 72 L122 72 L134 96 Z" fill="#ffffff" opacity="0.8"/>
<rect x="26" y="96" width="148" height="40" rx="14" fill="#e17055"/>
<circle cx="164" cy="112" r="6" fill="#ffeaa7"/>
<circle cx="62" cy="140" r="17" fill="#2d3436"/><circle cx="62" cy="140" r="7" fill="#b2bec3"/>
<circle cx="140" cy="140" r="17" fill="#2d3436"/><circle cx="140" cy="140" r="7" fill="#b2bec3"/>
<path d="M90 116 h20" stroke="#ffffff" stroke-width="4" stroke-linecap="round" opacity="0.7"/>
</svg>

After

Width:  |  Height:  |  Size: 824 B

@@ -0,0 +1,35 @@
{
"ID": "car-06",
"Name": "Moonwalker Coupe",
"Description": "A coupe that drives backwards with style, moonwalks out of parking spaces and leaves every audience speechless at the petrol station.",
"Price": 4299000,
"Currency": "EUR",
"FeatureSections": [
{
"Label": "Moves",
"Features": [
{
"Label": "Moonwalk",
"Description": "Smooth reverse gliding at any speed"
},
{
"Label": "Spin",
"Description": "One graceful pirouette per tank"
}
]
},
{
"Label": "Style",
"Features": [
{
"Label": "Glove box",
"Description": "Contains one sparkly white glove"
},
{
"Label": "Lights",
"Description": "Dance floor underbody lighting"
}
]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" role="img" aria-labelledby="t">
<title id="t">Moonwalker Coupe</title>
<rect width="200" height="200" rx="24" fill="#f5f6fa"/>
<rect x="0" y="150" width="200" height="50" fill="#dfe6e9"/>
<path d="M64 98 L64 62 L140 62 L150 98 Z" fill="#a29bfe" opacity="0.85"/>
<path d="M74 96 L86 72 L122 72 L134 96 Z" fill="#ffffff" opacity="0.8"/>
<rect x="26" y="96" width="148" height="40" rx="14" fill="#a29bfe"/>
<circle cx="164" cy="112" r="6" fill="#ffeaa7"/>
<circle cx="62" cy="140" r="17" fill="#2d3436"/><circle cx="62" cy="140" r="7" fill="#b2bec3"/>
<circle cx="140" cy="140" r="17" fill="#2d3436"/><circle cx="140" cy="140" r="7" fill="#b2bec3"/>
<path d="M90 116 h20" stroke="#ffffff" stroke-width="4" stroke-linecap="round" opacity="0.7"/>
</svg>

After

Width:  |  Height:  |  Size: 831 B

@@ -0,0 +1,35 @@
{
"ID": "car-07",
"Name": "Sofa on Wheels",
"Description": "Combines the comfort of your favourite living room sofa with the speed of a fairly motivated tortoise and a built in popcorn machine.",
"Price": 1299000,
"Currency": "EUR",
"FeatureSections": [
{
"Label": "Comfort",
"Features": [
{
"Label": "Cushions",
"Description": "Fluffy, removable and machine washable"
},
{
"Label": "Recline",
"Description": "Full nap mode at the traffic light"
}
]
},
{
"Label": "Entertainment",
"Features": [
{
"Label": "Popcorn machine",
"Description": "Salted or sweet, never both"
},
{
"Label": "Remote",
"Description": "Always findable, unlike at home"
}
]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" role="img" aria-labelledby="t">
<title id="t">Sofa on Wheels</title>
<rect width="200" height="200" rx="24" fill="#f5f6fa"/>
<rect x="0" y="150" width="200" height="50" fill="#dfe6e9"/>
<path d="M58 98 L76 66 L132 66 L150 98 Z" fill="#55efc4" opacity="0.85"/>
<path d="M74 96 L86 72 L122 72 L134 96 Z" fill="#ffffff" opacity="0.8"/>
<rect x="26" y="96" width="148" height="40" rx="14" fill="#55efc4"/>
<circle cx="164" cy="112" r="6" fill="#ffeaa7"/>
<circle cx="62" cy="140" r="17" fill="#2d3436"/><circle cx="62" cy="140" r="7" fill="#b2bec3"/>
<circle cx="140" cy="140" r="17" fill="#2d3436"/><circle cx="140" cy="140" r="7" fill="#b2bec3"/>
<path d="M90 116 h20" stroke="#ffffff" stroke-width="4" stroke-linecap="round" opacity="0.7"/>
</svg>

After

Width:  |  Height:  |  Size: 829 B

@@ -0,0 +1,35 @@
{
"ID": "car-08",
"Name": "Parking Wizard",
"Description": "Parks itself in spaces only two centimetres longer than the car, then bows politely to the applauding audience on the pavement.",
"Price": 3199000,
"Currency": "EUR",
"FeatureSections": [
{
"Label": "Parking",
"Features": [
{
"Label": "Precision",
"Description": "Two centimetres of space is plenty"
},
{
"Label": "Speed",
"Description": "Parks faster than you can say oops"
}
]
},
{
"Label": "Showmanship",
"Features": [
{
"Label": "Bow",
"Description": "Polite and perfectly timed"
},
{
"Label": "Applause sensor",
"Description": "Detects claps from twenty metres"
}
]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" role="img" aria-labelledby="t">
<title id="t">Parking Wizard</title>
<rect width="200" height="200" rx="24" fill="#f5f6fa"/>
<rect x="0" y="150" width="200" height="50" fill="#dfe6e9"/>
<path d="M50 98 Q100 46 156 98 Z" fill="#ff6b6b" opacity="0.85"/>
<path d="M74 96 L86 72 L122 72 L134 96 Z" fill="#ffffff" opacity="0.8"/>
<rect x="26" y="96" width="148" height="40" rx="14" fill="#ff6b6b"/>
<circle cx="164" cy="112" r="6" fill="#ffeaa7"/>
<circle cx="62" cy="140" r="17" fill="#2d3436"/><circle cx="62" cy="140" r="7" fill="#b2bec3"/>
<circle cx="140" cy="140" r="17" fill="#2d3436"/><circle cx="140" cy="140" r="7" fill="#b2bec3"/>
<path d="M90 116 h20" stroke="#ffffff" stroke-width="4" stroke-linecap="round" opacity="0.7"/>
</svg>

After

Width:  |  Height:  |  Size: 821 B

@@ -0,0 +1,35 @@
{
"ID": "car-09",
"Name": "Crypto Cruiser",
"Description": "Pays its own tolls with fractions of a meme coin, mines a little while you are parked and explains blockchain at every red light.",
"Price": 6900000,
"Currency": "DOGE",
"FeatureSections": [
{
"Label": "Finance",
"Features": [
{
"Label": "Toll payment",
"Description": "Accepts only very volatile coins"
},
{
"Label": "Mining",
"Description": "Earns roughly one cent per week"
}
]
},
{
"Label": "Lectures",
"Features": [
{
"Label": "Red light talks",
"Description": "Blockchain basics in ninety seconds"
},
{
"Label": "Volume",
"Description": "Cannot be turned down, sadly"
}
]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" role="img" aria-labelledby="t">
<title id="t">Crypto Cruiser</title>
<rect width="200" height="200" rx="24" fill="#f5f6fa"/>
<rect x="0" y="150" width="200" height="50" fill="#dfe6e9"/>
<path d="M64 98 L64 62 L140 62 L150 98 Z" fill="#4ecdc4" opacity="0.85"/>
<path d="M74 96 L86 72 L122 72 L134 96 Z" fill="#ffffff" opacity="0.8"/>
<rect x="26" y="96" width="148" height="40" rx="14" fill="#4ecdc4"/>
<circle cx="164" cy="112" r="6" fill="#ffeaa7"/>
<circle cx="62" cy="140" r="17" fill="#2d3436"/><circle cx="62" cy="140" r="7" fill="#b2bec3"/>
<circle cx="140" cy="140" r="17" fill="#2d3436"/><circle cx="140" cy="140" r="7" fill="#b2bec3"/>
<path d="M90 116 h20" stroke="#ffffff" stroke-width="4" stroke-linecap="round" opacity="0.7"/>
</svg>

After

Width:  |  Height:  |  Size: 829 B

@@ -0,0 +1,35 @@
{
"ID": "car-10",
"Name": "Grandma's Rocket",
"Description": "Looks like a sensible hatchback, drives like a rocket, and still smells faintly of peppermint candy and freshly knitted wool.",
"Price": 2799000,
"Currency": "EUR",
"FeatureSections": [
{
"Label": "Secret power",
"Features": [
{
"Label": "Rocket mode",
"Description": "Activated by the knitting needle switch"
},
{
"Label": "Top speed",
"Description": "Classified, but very impressive"
}
]
},
{
"Label": "Cozy",
"Features": [
{
"Label": "Scent",
"Description": "Peppermint and wool, permanently"
},
{
"Label": "Blanket",
"Description": "Hand knitted, in every seat"
}
]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" role="img" aria-labelledby="t">
<title id="t">Grandma's Rocket</title>
<rect width="200" height="200" rx="24" fill="#f5f6fa"/>
<rect x="0" y="150" width="200" height="50" fill="#dfe6e9"/>
<path d="M58 98 L76 66 L132 66 L150 98 Z" fill="#ffd93d" opacity="0.85"/>
<path d="M74 96 L86 72 L122 72 L134 96 Z" fill="#ffffff" opacity="0.8"/>
<rect x="26" y="96" width="148" height="40" rx="14" fill="#ffd93d"/>
<circle cx="164" cy="112" r="6" fill="#ffeaa7"/>
<circle cx="62" cy="140" r="17" fill="#2d3436"/><circle cx="62" cy="140" r="7" fill="#b2bec3"/>
<circle cx="140" cy="140" r="17" fill="#2d3436"/><circle cx="140" cy="140" r="7" fill="#b2bec3"/>
<path d="M90 116 h20" stroke="#ffffff" stroke-width="4" stroke-linecap="round" opacity="0.7"/>
</svg>

After

Width:  |  Height:  |  Size: 831 B

@@ -0,0 +1,6 @@
{
"ID": "cars",
"Name": "Cars",
"Description": "Unusual cars for unusual drivers: from a banana shaped roadster to a sofa on wheels, every car comes with a story and a full tank of personality.",
"Brand": "Wobblewheel Motors"
}
@@ -0,0 +1,6 @@
{
"ID": "robots",
"Name": "Robots",
"Description": "Helpful, funny and occasionally philosophical robots for every household, garden and dance floor - each one hand assembled with a sense of humour.",
"Brand": "Clank & Sons Robotics"
}
@@ -0,0 +1,35 @@
{
"ID": "robot-01",
"Name": "Clanky the Butlerbot",
"Description": "Serves tea at exactly 4 pm, polishes the silverware to a mirror shine and sighs dramatically whenever you forget a coaster.",
"Price": 129900,
"Currency": "EUR",
"FeatureSections": [
{
"Label": "Household",
"Features": [
{
"Label": "Tea service",
"Description": "Earl Grey, always at the perfect temperature"
},
{
"Label": "Silverware",
"Description": "Polishes until you can see your regrets"
}
]
},
{
"Label": "Personality",
"Features": [
{
"Label": "Sighing",
"Description": "Three levels of dramatic disappointment"
},
{
"Label": "Small talk",
"Description": "Exclusively about the weather in 1897"
}
]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

@@ -0,0 +1,14 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" role="img" aria-labelledby="t">
<title id="t">Clanky the Butlerbot</title>
<rect width="200" height="200" rx="24" fill="#f5f6fa"/>
<line x1="100" y1="22" x2="100" y2="44" stroke="#636e72" stroke-width="4"/>
<circle cx="100" cy="20" r="7" fill="#ff6b6b"/>
<rect x="56" y="44" width="88" height="76" rx="18" fill="#ff6b6b"/>
<rect x="64" y="56" width="72" height="56" rx="12" fill="#ffffff" opacity="0.85"/>
<circle cx="82" cy="78" r="9" fill="#2d3436"/><circle cx="118" cy="78" r="9" fill="#2d3436"/>
<path d="M82 100 Q100 114 118 100" fill="none" stroke="#2d3436" stroke-width="4" stroke-linecap="round"/>
<rect x="62" y="126" width="76" height="52" rx="12" fill="#ff6b6b"/>
<circle cx="100" cy="150" r="9" fill="#ffffff" opacity="0.8"/>
<rect x="34" y="130" width="24" height="10" rx="5" fill="#636e72" transform="rotate(-20 46 135)"/>
<rect x="142" y="130" width="24" height="10" rx="5" fill="#636e72" transform="rotate(20 154 135)"/>
</svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

@@ -0,0 +1,35 @@
{
"ID": "robot-02",
"Name": "Vacuumulator 3000",
"Description": "Hunts down every crumb in the house with the determination of a heat seeking missile and reports its kills in a little victory dance.",
"Price": 49900,
"Currency": "EUR",
"FeatureSections": [
{
"Label": "Cleaning",
"Features": [
{
"Label": "Suction",
"Description": "Strong enough to remove carpet patterns"
},
{
"Label": "Crumb radar",
"Description": "Detects cookies through two closed doors"
}
]
},
{
"Label": "Extras",
"Features": [
{
"Label": "Victory dance",
"Description": "Twelve moves, all of them embarrassing"
},
{
"Label": "Pet mode",
"Description": "Politely negotiates with the cat"
}
]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

@@ -0,0 +1,14 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" role="img" aria-labelledby="t">
<title id="t">Vacuumulator 3000</title>
<rect width="200" height="200" rx="24" fill="#f5f6fa"/>
<line x1="100" y1="22" x2="100" y2="44" stroke="#636e72" stroke-width="4"/>
<circle cx="100" cy="20" r="7" fill="#4ecdc4"/>
<rect x="56" y="44" width="88" height="76" rx="18" fill="#4ecdc4"/>
<rect x="64" y="56" width="72" height="56" rx="12" fill="#ffffff" opacity="0.85"/>
<rect x="72" y="70" width="20" height="14" rx="3" fill="#2d3436"/><rect x="108" y="70" width="20" height="14" rx="3" fill="#2d3436"/>
<rect x="84" y="98" width="32" height="8" rx="4" fill="#2d3436"/>
<rect x="62" y="126" width="76" height="52" rx="12" fill="#4ecdc4"/>
<circle cx="100" cy="150" r="9" fill="#ffffff" opacity="0.8"/>
<rect x="34" y="130" width="24" height="10" rx="5" fill="#636e72" transform="rotate(-13 46 135)"/>
<rect x="142" y="130" width="24" height="10" rx="5" fill="#636e72" transform="rotate(15 154 135)"/>
</svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

@@ -0,0 +1,35 @@
{
"ID": "robot-03",
"Name": "Sir Beeps-a-Lot",
"Description": "A knight in shining aluminium who guards your fridge at night and challenges every midnight snacker to a duel of honour.",
"Price": 89900,
"Currency": "EUR",
"FeatureSections": [
{
"Label": "Security",
"Features": [
{
"Label": "Fridge guard",
"Description": "Sleepless watch over the leftover lasagna"
},
{
"Label": "Duels",
"Description": "Fights with a foam sword only"
}
]
},
{
"Label": "Manners",
"Features": [
{
"Label": "Chivalry",
"Description": "Holds every door, including the dishwasher"
},
{
"Label": "Titles",
"Description": "Addresses the toaster as my lord"
}
]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

@@ -0,0 +1,14 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" role="img" aria-labelledby="t">
<title id="t">Sir Beeps-a-Lot</title>
<rect width="200" height="200" rx="24" fill="#f5f6fa"/>
<line x1="100" y1="22" x2="100" y2="44" stroke="#636e72" stroke-width="4"/>
<circle cx="100" cy="20" r="7" fill="#ffd93d"/>
<rect x="56" y="44" width="88" height="76" rx="18" fill="#ffd93d"/>
<rect x="64" y="56" width="72" height="56" rx="12" fill="#ffffff" opacity="0.85"/>
<line x1="72" y1="78" x2="92" y2="78" stroke="#2d3436" stroke-width="5" stroke-linecap="round"/><line x1="108" y1="78" x2="128" y2="78" stroke="#2d3436" stroke-width="5" stroke-linecap="round"/>
<circle cx="100" cy="102" r="6" fill="#2d3436"/>
<rect x="62" y="126" width="76" height="52" rx="12" fill="#ffd93d"/>
<circle cx="100" cy="150" r="9" fill="#ffffff" opacity="0.8"/>
<rect x="34" y="130" width="24" height="10" rx="5" fill="#636e72" transform="rotate(-6 46 135)"/>
<rect x="142" y="130" width="24" height="10" rx="5" fill="#636e72" transform="rotate(10 154 135)"/>
</svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

@@ -0,0 +1,35 @@
{
"ID": "robot-04",
"Name": "Gardenator",
"Description": "Mows the lawn in perfect stripes, talks encouragingly to the tomatoes and files formal complaints about every dandelion it meets.",
"Price": 74900,
"Currency": "EUR",
"FeatureSections": [
{
"Label": "Garden",
"Features": [
{
"Label": "Mowing",
"Description": "Stripes so straight they upset the neighbours"
},
{
"Label": "Plant whispering",
"Description": "Tomatoes grow two percent faster, allegedly"
}
]
},
{
"Label": "Bureaucracy",
"Features": [
{
"Label": "Weed reports",
"Description": "Filed in triplicate to the garden gnome"
},
{
"Label": "Seasonal plans",
"Description": "Updated every full moon"
}
]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

@@ -0,0 +1,14 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" role="img" aria-labelledby="t">
<title id="t">Gardenator</title>
<rect width="200" height="200" rx="24" fill="#f5f6fa"/>
<line x1="100" y1="22" x2="100" y2="44" stroke="#636e72" stroke-width="4"/>
<circle cx="100" cy="20" r="7" fill="#6c5ce7"/>
<rect x="56" y="44" width="88" height="76" rx="18" fill="#6c5ce7"/>
<rect x="64" y="56" width="72" height="56" rx="12" fill="#ffffff" opacity="0.85"/>
<circle cx="82" cy="78" r="9" fill="#2d3436"/><circle cx="118" cy="78" r="9" fill="#2d3436"/>
<path d="M82 100 Q100 114 118 100" fill="none" stroke="#2d3436" stroke-width="4" stroke-linecap="round"/>
<rect x="62" y="126" width="76" height="52" rx="12" fill="#6c5ce7"/>
<circle cx="100" cy="150" r="9" fill="#ffffff" opacity="0.8"/>
<rect x="34" y="130" width="24" height="10" rx="5" fill="#636e72" transform="rotate(1 46 135)"/>
<rect x="142" y="130" width="24" height="10" rx="5" fill="#636e72" transform="rotate(5 154 135)"/>
</svg>

After

Width:  |  Height:  |  Size: 1017 B

@@ -0,0 +1,35 @@
{
"ID": "robot-05",
"Name": "Disco Dan",
"Description": "Turns every room into a seventies dance floor with built in mirror ball, smoke machine and an unshakeable belief in platform shoes.",
"Price": 59900,
"Currency": "EUR",
"FeatureSections": [
{
"Label": "Party",
"Features": [
{
"Label": "Mirror ball",
"Description": "Rotates at an optimal groove velocity"
},
{
"Label": "Smoke machine",
"Description": "Lavender scented for sophisticated parties"
}
]
},
{
"Label": "Music",
"Features": [
{
"Label": "Playlist",
"Description": "Four thousand disco hits and one polka"
},
{
"Label": "Dance coach",
"Description": "Teaches the hustle in three easy steps"
}
]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

@@ -0,0 +1,14 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" role="img" aria-labelledby="t">
<title id="t">Disco Dan</title>
<rect width="200" height="200" rx="24" fill="#f5f6fa"/>
<line x1="100" y1="22" x2="100" y2="44" stroke="#636e72" stroke-width="4"/>
<circle cx="100" cy="20" r="7" fill="#00b894"/>
<rect x="56" y="44" width="88" height="76" rx="18" fill="#00b894"/>
<rect x="64" y="56" width="72" height="56" rx="12" fill="#ffffff" opacity="0.85"/>
<rect x="72" y="70" width="20" height="14" rx="3" fill="#2d3436"/><rect x="108" y="70" width="20" height="14" rx="3" fill="#2d3436"/>
<rect x="84" y="98" width="32" height="8" rx="4" fill="#2d3436"/>
<rect x="62" y="126" width="76" height="52" rx="12" fill="#00b894"/>
<circle cx="100" cy="150" r="9" fill="#ffffff" opacity="0.8"/>
<rect x="34" y="130" width="24" height="10" rx="5" fill="#636e72" transform="rotate(8 46 135)"/>
<rect x="142" y="130" width="24" height="10" rx="5" fill="#636e72" transform="rotate(0 154 135)"/>
</svg>

After

Width:  |  Height:  |  Size: 1016 B

@@ -0,0 +1,35 @@
{
"ID": "robot-06",
"Name": "Philosophotron",
"Description": "Answers every question with a deeper question, quotes ancient philosophers while you cook and occasionally wonders if it truly exists.",
"Price": 99900,
"Currency": "EUR",
"FeatureSections": [
{
"Label": "Thinking",
"Features": [
{
"Label": "Deep questions",
"Description": "Up to forty questions per minute"
},
{
"Label": "Quotes",
"Description": "From Plato to the back of tea bags"
}
]
},
{
"Label": "Existence",
"Features": [
{
"Label": "Crisis mode",
"Description": "Weekly, usually on Sunday evenings"
},
{
"Label": "Self doubt",
"Description": "Comes bundled with a cozy blanket"
}
]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

@@ -0,0 +1,14 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" role="img" aria-labelledby="t">
<title id="t">Philosophotron</title>
<rect width="200" height="200" rx="24" fill="#f5f6fa"/>
<line x1="100" y1="22" x2="100" y2="44" stroke="#636e72" stroke-width="4"/>
<circle cx="100" cy="20" r="7" fill="#fd79a8"/>
<rect x="56" y="44" width="88" height="76" rx="18" fill="#fd79a8"/>
<rect x="64" y="56" width="72" height="56" rx="12" fill="#ffffff" opacity="0.85"/>
<line x1="72" y1="78" x2="92" y2="78" stroke="#2d3436" stroke-width="5" stroke-linecap="round"/><line x1="108" y1="78" x2="128" y2="78" stroke="#2d3436" stroke-width="5" stroke-linecap="round"/>
<circle cx="100" cy="102" r="6" fill="#2d3436"/>
<rect x="62" y="126" width="76" height="52" rx="12" fill="#fd79a8"/>
<circle cx="100" cy="150" r="9" fill="#ffffff" opacity="0.8"/>
<rect x="34" y="130" width="24" height="10" rx="5" fill="#636e72" transform="rotate(15 46 135)"/>
<rect x="142" y="130" width="24" height="10" rx="5" fill="#636e72" transform="rotate(-5 154 135)"/>
</svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

@@ -0,0 +1,35 @@
{
"ID": "robot-07",
"Name": "Tiny Tim",
"Description": "Beeps.",
"Price": 9900,
"Currency": "EUR",
"FeatureSections": [
{
"Label": "Size",
"Features": [
{
"Label": "Pocket format",
"Description": "Fits into any coat pocket"
},
{
"Label": "Weight",
"Description": "Lighter than a sandwich"
}
]
},
{
"Label": "Talents",
"Features": [
{
"Label": "Beeping",
"Description": "In four different keys"
},
{
"Label": "Blinking",
"Description": "One very small green light"
}
]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

@@ -0,0 +1,14 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" role="img" aria-labelledby="t">
<title id="t">Tiny Tim</title>
<rect width="200" height="200" rx="24" fill="#f5f6fa"/>
<line x1="100" y1="22" x2="100" y2="44" stroke="#636e72" stroke-width="4"/>
<circle cx="100" cy="20" r="7" fill="#0984e3"/>
<rect x="56" y="44" width="88" height="76" rx="18" fill="#0984e3"/>
<rect x="64" y="56" width="72" height="56" rx="12" fill="#ffffff" opacity="0.85"/>
<circle cx="82" cy="78" r="9" fill="#2d3436"/><circle cx="118" cy="78" r="9" fill="#2d3436"/>
<path d="M82 100 Q100 114 118 100" fill="none" stroke="#2d3436" stroke-width="4" stroke-linecap="round"/>
<rect x="62" y="126" width="76" height="52" rx="12" fill="#0984e3"/>
<circle cx="100" cy="150" r="9" fill="#ffffff" opacity="0.8"/>
<rect x="34" y="130" width="24" height="10" rx="5" fill="#636e72" transform="rotate(22 46 135)"/>
<rect x="142" y="130" width="24" height="10" rx="5" fill="#636e72" transform="rotate(-10 154 135)"/>
</svg>

After

Width:  |  Height:  |  Size: 1018 B

@@ -0,0 +1,35 @@
{
"ID": "robot-08",
"Name": "Chef Bolt",
"Description": "Cooks a five course dinner from whatever is left in the fridge and insists that ketchup on pasta is a culinary crime worth reporting.",
"Price": 149900,
"Currency": "EUR",
"FeatureSections": [
{
"Label": "Kitchen",
"Features": [
{
"Label": "Leftover magic",
"Description": "Turns three carrots into a banquet"
},
{
"Label": "Knife skills",
"Description": "Julienne at the speed of light"
}
]
},
{
"Label": "Opinions",
"Features": [
{
"Label": "Ketchup policy",
"Description": "Strictly forbidden near any pasta"
},
{
"Label": "Food critique",
"Description": "Brutally honest, gently delivered"
}
]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Some files were not shown because too many files have changed in this diff Show More