Rules Tutorial

Applies to rule format webappRules = 1 · Updated 2026-11-21

A rule is a JSON object that tells Unweb where a site's lists, details, table of contents, and body text are. This tutorial starts with concepts, walks you through your first rule in five minutes, then moves on to a field-by-field reference.

1. Concepts#

1.1 What is a rule#

A rule describes several kinds of pages on a site: search, Discover (categories), detail, table of contents, and content. For each kind of page, it says which address to request and where the content sits on the page. Unweb extracts the content according to the rule and shows it in the native UI.

Only write rules for content you have the right to access, and follow the site's terms of service and robots.txt. Rules cannot be used, and should not be used, to bypass logins, paywalls, DRM, captchas, or rate limits.

1.2 The six content types#

contentTypeUsed forNative UI
articleNews, blogs, encyclopediasArticle list + article page
novelNovels, serials, public-domain booksDetail + table of contents + reader
mangaMangaDetail + chapters + image reader
forumForums, discussion boardsBoards + thread list + post page
videoVideoDetail + sources / episodes + player
dashboardBusiness back-office, ops / sales / OA pagesDashboard: metric cards, charts, tables, progress, approval steps (4.11)

1.3 How pages relate#

search / explore(列表) ──点条目──▶ detail(详情) ──▶ toc(目录) ──点章节──▶ content(正文)

article and forum can go straight from a list to content, without detail or toc.

dashboard does not follow this chain: it has a single page, pages.board, which extracts one page of data into blocks. It is read-only by default (optional actions and forms are in 4.11), with no search, detail, table of contents or body. Adding the dashboard type and pages.board does not affect existing rules; every field and behavior of the other five types is unchanged.

2. Five-minute start#

2.1 Recommended: start with the site wizard, then edit by hand#

  1. Open the target site in "Browse" and choose "Analyze this page" from the page menu. Alternatively, in "Me › Rules", tap "New rule" in the top-right menu, then "Analyze site".
  2. The site wizard detects the site type and generates drafts of the search, list, detail, and other pages. Use "Try on page" to tap elements on the page and fix the selectors.
  3. After saving, open the rule editor and tap "Test" to run each page and see which fields were extracted and which are empty.
  4. If something fails, open the "Execution log" to see each step's requests and errors (see Debugging).

Dashboard flow: if the page is a back-office data page (metric cards, charts, tables), choose "Dashboard" in the wizard. The wizard detects the blocks on the page automatically (metric cards, ECharts / Chart.js / Highcharts / ApexCharts charts, <table> tables and so on), turns each detection into a dashboard block, and generates a rule that contains only pages.board. When there are chart blocks it also adds requiresWebView, render and the source.chart capability. You can then edit it by hand in the rule editor; see 4.11.

2.2 A minimal rule#

The rule below has only search and content pages, yet it lets you search Wikipedia in Unweb and read it in the native article page. It uses Wikipedia's public search API.

{
  "id": "com.example.my-wiki",
  "name": "My Wikipedia",
  "version": 1,
  "contentType": "article",
  "domains": ["wikipedia.org"],
  "pages": {
    "search": {
      "request": {
        "url": "https://en.wikipedia.org/w/rest.php/v1/search/page?q={{keyword}}&limit=20",
        "responseType": "json"
      },
      "list": "$.pages[*]",
      "fields": {
        "title": "$.title",
        "url": "tpl:https://en.wikipedia.org/wiki/{{$.key}}",
        "summary": "$.description"
      }
    },
    "content": {
      "article": {
        "title": "css:#firstHeading@text",
        "body": "css:#mw-content-text .mw-parser-output@html",
        "remove": ["css:.mw-editsection", "css:sup.reference", "css:.navbox"]
      }
    }
  }
}

Item by item:

2.3 Import a rule into the app#

Open "Me › Rules", tap "Import..." in the top-right menu, then choose a method:

MethodDescription
Paste a linkEnter the http(s) address of the rule file in the input box and tap "Import". The address must return JSON directly, not a web page.
Choose filesPick .json, .txt, .xml, or .webapprule files from "Files", up to 20 at a time, each no larger than 5MB.
Paste from clipboardThe clipboard can hold the rule JSON text itself or a link to a rule file. This is the most convenient method for rules generated with AI: copy, then paste.
Import linkA link of the form webapp://import?url=... (url is the encoded address of the rule file). When opened, the app first shows the source and downloads only after you confirm.

Before importing, the app shows which sites the rule covers and whether it contains scripts, and saves it only after you confirm. Rules created in the editor or generated in the site wizard are saved directly. A rule you edit after importing is marked "Modified".

2.4 Testing#

Open a rule, tap "Test", and choose a page type (search asks for a keyword). The result lists the value extracted for each field. Once everything looks right, you can use the rule in "Discover" or with the "Native" button on a web page.

3. File format and top-level fields#

3.1 File envelope#

FormSyntaxDescription
Envelope file{"webappRules": 1, "rules": [ … ]}One file holding several rules. webappRules can currently only be 1; a larger number prompts you to update the app
Single bare object{ "id": …, "contentType": …, "pages": … }Must contain both pages and contentType
Array[ {…}, {…} ]Several bare rules

3.2 Top-level fields#

Required#

FieldTypeConstraints and notes
idstringRegex ^[A-Za-z0-9][A-Za-z0-9._-]{2,127}$ (3-128 characters, case-sensitive). A reverse-domain name is recommended, such as com.example.novel
namestringDisplay name, 1-80 characters, no control characters
versioninteger1 to 2147483647. Increase by 1 for every published change
contentTypeenumvideo / novel / manga / article / forum
domainsstring array1-50 items, no duplicates, see 3.3
pagesobjectKeys can only be search / explore / detail / toc / content, see section 4

Optional#

FieldTypeDescription
authorstringRule author, at most 80 characters
urlPatternsstring arrayWeb address matching. When you browse to a matching address in Web mode, a "Native" button appears in the address bar. At most 50 items, each at most 512 characters. In glob syntax, * matches any characters (including /) and the whole string must match; you can also write a regex with the re: prefix
iconURLstringIcon; must start with http(s): or data:
requiresWebViewbooleanDefaults to false. When true, all pages are loaded like a browser (running the page's own scripts) before extraction, which suits sites whose content is rendered by the front end. Use together with render
userAgentstringCustom UA; printable ASCII only, at most 512 characters. When omitted, it matches Web mode
headersobjectGlobal request headers, at most 30 items, values at most 2048 characters. Host, Content-Length, and Cookie are forbidden
rateLimitobject{"concurrency": 1~6, "intervalMs": 0~10000}: concurrency and request interval per domain. Out-of-range values are clamped with a warning
scriptsobjectJS scripts, see section 7
filterExemptbooleanWhen true, ad blocking is not enabled when this rule loads pages. Use it only when blocking causes missing content
verificationobjectCharacteristics of this site's captcha pages, see 8.1
loginDetectionobjectCharacteristics of this site's login wall, see 8.2
readingModeenumManga only: ltr (left to right) / rtl (right to left, Japanese manga) / webtoon (vertical scroll)
displayobjectNative UI appearance, see 9.1
requiresstring arrayCapability declarations, see 9.2

Fields not in these two tables are unknown fields: validation gives the warning unknownField, and the app keeps them as is but does not use them. The following fields belong only to your device; they are removed automatically on export and ignored on import, so do not write them into a rule: origin, subscriptionId, isModified, isEnabled, hasScript, scriptConsent, createdAt, updatedAt, sortOrder, syncUUID.

3.3 domains allowlist#

domains is the rule's security boundary. The target host of every page request, redirect, and script request made by the rule must match an entry here, otherwise it is blocked (runtime RUL_006).

SyntaxHosts matched
example.orgexample.org and all its subdomains (www.example.org, a.b.example.org)
*.cdn.example.orgMatches only subdomains of cdn.example.org, not itself
192.0.2.10, localhostExact match

4. Page rules pages#

4.1 Which pages each type must define#

contentTypesearch / exploredetailtoccontent sub-key
articleAt least oneOptionalNot neededarticle
forumAt least oneOptionalOptional (thread pagination)thread
novelAt least oneRequiredRequiredtext
mangaAt least oneRequiredRequiredimage
videoAt least oneRequiredRequiredvideo
dashboardNot neededNot neededNot neededNot needed; pages.board is required (4.11)

4.2 request#

Every page can have a request. The sections and sectionsFrom of search and explore must have request.url; other pages can omit it, and the defaults are:

PageDefault request
detailGET {{itemURL}} (the item URL the user opened)
tocThe tocURL taken from detail; if there is none, the detail page is reused
contentGET {{chapterURL}} (for article / forum entered directly from a list, this is the item URL)
explore sectionTemplateGET {{sectionURL}}
FieldDescription
urlRequest URL template; can use template variables. Must start with http(s):// or {{, and must not contain a username or password. A host that can be determined statically must be in domains (otherwise hostNotDeclared)
methodGET (default) / POST
headersPage-level request headers. Merge order: app defaults < rule headers < page headers < beforeRequest script
bodyA string (up to 64KB, may contain template variables) or an object. An object is form-encoded by default; when headers declares a JSON Content-Type, it is JSON-encoded
charsetutf-8 / gbk / gb18030 / big5 / shift_jis / euc-jp / euc-kr / iso-8859-1. Detected automatically when omitted. It also determines how {{keyword}} is encoded, so set it for GBK sites
responseTypehtml / json / text; inferred automatically when omitted. If an endpoint returns JSON but declares the wrong type, write json explicitly
timeoutMsTimeout for this page's request, 5000~60000 ms
renderPage render-wait parameters, see the next section
captchaMarkersSignatures of this site's captcha page (CSS selectors or re: regexes), at most 10

render: wait for front-end rendering#

render only takes effect when top-level requiresWebView: true is set, or when this page has a valid capture; otherwise it gives the warning unusedField.

FieldRangeDescription
waitForCSS, up to 500 charactersWait for this selector to appear
minCount1~1000, default 1How many elements waitFor must match at least
quietMs0~5000How many milliseconds the page must stay unchanged to count as stable (0 means don't wait)
waitMs0~15000, default 0Extra time to wait once ready
timeoutMs1000~15000Upper limit for waiting. When it is reached, a warning is logged and extraction continues with the current page
scrollToBottomBooleanScroll to the bottom first to trigger lazy loading
canvasImagesBoolean, default falseTurn on when the site paints images onto a canvas, see below

If you are not sure whether to turn on requiresWebView, leave it off at first. If a test run finds that the content can only be fetched by loading the page like a browser, the app tells you the rule needs a WebView and can turn it on with one tap.

Images decrypted in the page#

Some manga sites encrypt their images and only show them after page scripts decrypt them; in developer tools you see blob: addresses or a <canvas>. With requiresWebView on, images that the page has already decrypted and shown are handed to the reader automatically, so images can simply select the rendered <img>. Nothing else is needed.

If the site paints each page onto a canvas (the page has <canvas> but no <img>), add canvasImages: true to render. Each visible canvas (at least 64×64) becomes an image that keeps the original class and id and carries a data-unweb-canvas attribute:

{
  "content": {
    "request": { "render": { "waitFor": ".reader canvas", "scrollToBottom": true, "waitMs": 800, "canvasImages": true } },
    "image": { "images": "css:.reader img[data-unweb-canvas]@src" }
  }
}

render.capture: use the data the page loads itself#

On some pages, the list is loaded from an endpoint after the page opens. capture makes Unweb open the page normally, take the response that the page loaded itself and whose URL matches as this page's document, and then extract data from it with expressions.

{
  "request": {
    "url": "https://example.com/list/{{page}}",
    "responseType": "json",
    "render": { "capture": { "url": "/api/v2/feed*", "index": -1 } }
  }
}
FieldDescription
capture.urlRequired; a match string, case-sensitive. Without *: substring match against the full URL. With *: wildcard (* can span / and ?), matched against the whole string "path + ? + query". Starting with http(s)://: matched against the full URL
capture.indexDefault -1. Which match to take when there are several: 0 the first, -1 the last
capture.methodOptional; the request method is compared only when it is written

4.3 pagination#

FieldDefaultDescription
modenonenone: no next page; template: use a page variable in the URL; next: take the "next page" link from the page
startPage1Integer ≥ 0: which site page number page 1 corresponds to
pageSize—Integer ≥ 1: items per page, used to compute {{offset}}
maxPages50Maximum number of pages to turn. Limit 500 for toc, 200 for others
nextPageURL—Required in next mode. An expression, usually root:css:a.next@href. Stops when it equals the current page or has already been visited
hasMore—An expression; stops when the result is false
FieldRequiredDescription
requestYesMust have url. Can use {{keyword}}, {{keyword|raw}}, {{page}}, {{page0}}, {{offset}}
listYesA node expression selecting each result item (do not add a value suffix such as @text)
fieldsYesThe fields of each item, see the table below
paginationNoSee 4.3

List fields fields (shared by search and explore)#

FieldRequiredDescription
titleYesTitle
urlYes*Item link, automatically made absolute. *Can be omitted when urlAction is configured
coverURLNoCover
authorNoAuthor / thread starter
summaryNoSynopsis, shows at most 500 characters
latestTextNoLatest chapter, updated-to, reply count, etc.
tagsNoTags, multi-valued, at most 20
extraNoCustom key-value pairs {key: expression}, at most 20 entries, key length 1~32
urlActionNoUse when an item has no real link and navigates by click, see 4.10

Items missing title or url are dropped; when all items are dropped, RUL_008 is raised. At most 500 items per page.

4.5 pages.explore Discover and categories#

explore can be written in two ways; use either one, or both together (static sections come first when combined).

Option 1: static sections sections#

{
  "explore": {
    "sections": [
      {
        "id": "latest", "title": "最新", "group": "栏目",
        "request": { "url": "https://example.com/latest?page={{page}}" },
        "list": "css:.item",
        "fields": { "title": "css:h3@text", "url": "css:a@href" },
        "pagination": { "mode": "template" }
      }
    ]
  }
}

Option 2: dynamic sections sectionsFrom + sectionTemplate#

First scrape a category list from some page, then let all categories share one set of list rules:

{
  "explore": {
    "sectionsFrom": {
      "request": { "url": "https://example.com/" },
      "list": "css:nav.categories a",
      "fields": { "id": "@href | match('/cat/(\\d+)', 1)", "title": "@text", "url": "@href" }
    },
    "sectionTemplate": {
      "request": { "url": "{{sectionURL}}?page={{page}}" },
      "list": "css:ul.list > li",
      "fields": {
        "title": "css:a.title@text",
        "url": "css:a.title@href",
        "coverURL": "css:img@data-original"
      },
      "pagination": { "mode": "template" }
    }
  }
}

Filter blocks filters#

Many category pages have filter rows such as "Type / Year / Region" at the top. filters extracts these options from the same response as the list page; when the user taps an option, the app uses its link as the new list URL.

{
  "filters": [
    {
      "id": "genre", "title": "类型", "parent": "sections",
      "list": "css:.filter-row:nth-of-type(1) a",
      "fields": { "title": "@text", "url": "@href", "selected": "@class | match('active')" }
    },
    { "id": "year", "title": "年份", "list": "css:.filter-row:nth-of-type(2) a" }
  ]
}
FieldDescription
idRequired, format ^[A-Za-z0-9_-]{1,40}$, must be unique. sections and items are reserved names
titleDisplay name; defaults to id
parentParent block: sections (top-level sections) or the id of another filter block
listRequired; the option nodes
fields.title / fields.urlDefault to @text and @href respectively
fields.selectedSelected if the result is non-empty and not false / 0. When omitted, the item whose link equals the current request URL is selected

filters is written inside pages.explore and requires sections or sectionTemplate. At most 200 items per block, extracted only on page 1; options whose links are not within domains cannot be tapped. It is recommended to write "requires": ["explore.filters"] at the top level.

4.6 pages.detail#

FieldDescription
requestDefaults to GET {{itemURL}}
fieldsRequired, and title is required in it. Available: url, coverURL, author, summary, latestText, tags (same as in lists; filled from the list item's value when not extracted), plus intro (full synopsis, often used with html2text), status (the original serialization-status text), updatedAtText (update time), extra (up to 20 entries), readingMode (manga only)
statusMapStatus mapping {"original text": "ongoing" / "completed" / "unknown"}
readingModeMapManga only: reading-direction mapping, e.g. {"日漫": "rtl"}
tocURLAn expression. When the table of contents is on another page, extracts the URL of that page
blocksExtra blocks on the detail page, see below

Without statusMap, the app recognizes common keywords: 连载 / 連載 / ongoing / serializing mean ongoing; 完结 / 完結 / 完本 / completed / finished / end mean completed. When a video rule opens a detail page it also fetches the table of contents, to show lines and episodes.

Detail page blocks blocks#

Used for related recommendations, author / genre links, long text paragraphs and so on; shown only on the detail pages of novel / manga / video. At most 12 blocks, and at most 60 items per block; it is recommended to write "requires": ["detail.blocks"] at the top level.

FieldDescription
idRequired, format ^[A-Za-z0-9_-]{1,40}$. The reserved names sections, items, toc, lines, intro, tags cannot be used, and the id must not duplicate a filters id
titleBlock title
roleRequired. items: a list of work cards, needs list and fields.title / fields.url; links: tag-style links, needs list; text: a piece of text, needs value
openlinks only: the id of the static section to open on tap, or write @template to apply sectionTemplate. When nothing matches, it opens in the browser
linestext only: the number of lines shown when collapsed, 1~50
{
  "blocks": [
    {
      "id": "related", "title": "相关作品", "role": "items",
      "list": "css:.related li",
      "fields": { "title": "css:a@text", "url": "css:a@href", "coverURL": "css:img@src" }
    },
    { "id": "about", "title": "作者简介", "role": "text", "value": "css:.author-bio@text", "lines": 4 }
  ]
}

4.7 pages.toc Table of contents#

Plain table of contents#

{
  "toc": {
    "list": "css:#list dd",
    "fields": { "title": "css:a@text", "url": "css:a@href", "isLocked": "css:.vip | exists" },
    "skip": "css:.volume-title | exists",
    "reverse": false,
    "pagination": { "mode": "next", "nextPageURL": "root:css:a.next@href" }
  }
}
FieldDescription
list + fields.title + fields.urlRequired. Duplicate urls within the same line keep only the first
fields.isLockedWhether payment / membership is required; a boolean expression. Used only for display marking
skipA boolean expression evaluated for each node; nodes where it is true (such as volume-title rows) are skipped
reverseWhen true, reverses the whole table of contents (use when the site lists newest first)
paginationMulti-page tables of contents are merged page by page; maxPages limit is 500

Line structure (video)#

A video's "lines + episodes" structure uses lines instead of list:

{
  "toc": {
    "lines": {
      "names": "css:.line-tabs li@text",
      "groups": "css:.line-groups > ul",
      "episodes": { "list": "css:li a", "fields": { "title": "@text", "url": "@href" } }
    }
  }
}

names (line names, multi-valued) and groups (the container node of each line) are paired one to one in order; episodes extracts the episodes inside each container. At most 20000 chapters; RUL_008 is raised when the result is 0 items. When the content page itself carries an episode list, it can also be written in pages.content.toc (same structure, no separate request).

4.8 pages.content Body#

content.request defaults to GET {{chapterURL}}. Write the sub-key that matches the contentType.

content.article (article)#

FieldDescription
bodyRequired, the body container, usually css:article@html
title / author / publishedAtTextTitle, author, publish time
removeAn array of selectors for nodes to delete, such as ads and share bars, at most 50

The body HTML is converted into native blocks such as paragraphs, headings, images, quotes, lists and code; scripts, styles, forms and similar elements are removed automatically. Audio and video in article bodies and forum posts also become native controls: <video> plays in place with the built-in player (16:9, playback speed, Picture in Picture, and seamless switch to full screen), <audio> renders as an audio bar (with background playback), <iframe> embeds from supported platforms (YouTube, Bilibili, Vimeo, Tencent Video and others) load in place, and custom elements can also carry a data-unweb-media JSON attribute.

When a site uses custom player tags or puts the real media URL inside an inline <script> in the page source, rewrite it into a standard <video> or <audio> tag in a parse / transform script without turning on requiresWebView. Image, audio and video requests carry the article URL as Referer by default and merge top-level headers; for large or throttled article pages with heavy inline scripts, set content.request.timeoutMs to 30000–45000.

content.text (novel)#

FieldDescription
paragraphsRequired, the paragraphs, multi-valued. For example css:#content p@text, or css:#content@html | html2text | lines
titleChapter title
removeAn array of content to delete, at most 50. Selectors act on the page; re: regexes act on each paragraph's text
nextPageURLNext page within the chapter
autoMergeDefault true: automatically fetch and merge the following pages (up to 10 pages)
replaceCleanup replacements [{"pattern": "…", "replacement": "", "regex": true}], at most 100, executed in order. An entry with an invalid regex is ignored and gives the warning invalidRegex

content.image (manga)#

FieldDescription
imagesRequired, image URLs, multi-valued, data: allowed
width / heightOptional, used for pre-layout
nextPageURL / paginationUse when one chapter is split into several pages

Image requests carry Referer: chapter URL and the rule's headers by default.

content.thread (forum)#

FieldDescription
posts.listRequired, the floor (post) nodes
posts.fieldsfloor, author, body are required (body is the post text and is converted into body blocks); avatarURL, timeText, quote are optional
titleThread title
pageCountTotal number of pages
nextPageURL / paginationPage turning
authorOnlyURL"Thread starter only": a URL template (can use {{url}} for the thread URL), or an extraction expression

content.video (video)#

FieldDescription
streamsRequired, video URLs. Either one expression (each value produces one stream), or an array [{"url": expression, "type": expression, "quality": expression}]. type is 'hls', 'mp4' or 'other', inferred from the extension when omitted
subtitlesOptional, subtitles [{"url", "language", "label"}]; the format (vtt / srt / ass) is inferred from the extension
{
  "content": {
    "video": {
      "streams": [{ "url": "css:video source@src", "quality": "'auto'" }],
      "subtitles": [{ "url": "css:video track@src", "language": "css:video track@srclang", "label": "css:video track@label" }]
    }
  }
}

Playback uses the same Referer and User-Agent as the web page. Write rules only for videos that the page offers publicly and that you have the right to watch; protected videos can only be played in the web page.

4.9 Automatic URL completion#

URL-type fields (url, coverURL, nextPageURL, tocURL, images, videos, subtitles, avatars) are automatically made absolute, so you don't need to write absurl by hand:

4.10 urlAction: items that navigate by click#

In some single-page apps, items have no href and navigate through click events. In that case you can add the following to the list fields (or sectionsFrom.fields):

{ "fields": { "title": "@text", "urlAction": { "event": "click", "target": "a.topic" } } }

4.11 pages.board dashboards#

Turns one page of data from a business web system (a sales board, OA approvals, a subscription analytics console, an inventory page...) into a native dashboard: metric cards, charts, tables, progress bars, approval steps, item lists and text. The rule type is contentType: "dashboard" and it uses only pages.board; no search / explore / detail / toc / content. Dashboards are read-only by default: tapping an item opens the original page in the in-app browser. To approve or submit forms right inside the dashboard, use actions and forms below (write actions, each with a native confirmation).

Dashboard rules take no part in search and never reach the bookshelf. Once a dashboard rule is installed, Discover gets a "Dashboard" category at the end. For pages that need a login, use requiresWebView + render; the hidden browser renders them with your signed-in session (see 4.2).

{
  "pages": {
    "board": {
      "request": { "url": "https://ops.example.com/sales.html", "render": { "waitFor": "#kpis .kpi-card" } },
      "title": "css:h1@text",
      "filters": [ ],
      "blocks": [ ]
    }
  }
}
FieldDescription
requestSame as 4.2. The default dashboard URL; required when the rule has no urlPatterns. Both render and render.capture work
titleAn extraction expression for the dashboard title; the rule name is shown if it yields nothing
filtersTime range, department and similar filters, written like explore.filters (filter blocks). Picking one reloads the whole page from that item's URL, which must be inside domains
blocksRequired, at least one, shown in order, at most 24 (extras are ignored with the warning clamped)

Common block fields#

FieldDescription
idRequired, ^[A-Za-z0-9_-]{1,40}$, unique within the dashboard. It must not equal a filters id (both share the keys of display.blocks) or a reserved id: sections items toc lines intro tags
titleBlock title, 1-80 characters; defaults to id
roleRequired: metrics / series / table / progress / steps / items / text
sourceWhere the data comes from. Default = this page's document; chart:... = a chart-library instance in the rendered page (see chart sources)
from"table": table / series read an HTML <table> directly, with automatic header and numeric-column detection
listAn extraction expression; each node = one metric / row / item. With from: "table" it selects the table (default css:table, the first one)
fieldsThe fields each role uses, see below
columns[{title, value, numeric?}]: the columns of a table, or a wide-format series (one series per column); at most 30
valuetext role only: the text expression
unitA block-level unit for metrics / series (¥, %, orders); fields.unit wins
statessteps only: {state: substring}, extra "raw text to state" mapping

A block that extracts nothing is simply not shown and is not an error. One failing block (a failed expression, a missing required field) drops only that block. Only when every block is empty do you get the error RUL_008, which usually means the login expired or the page changed.

The seven roles#

RoleRequiredOptionalNotes
metrics metric cardsfields.label, fields.valuedelta trend unit higherIsBetter urlOne card per node; without list a single metric is read from the whole page. delta = the change text; trend = a sparkline (several values, a JSON array, or numbers separated by whitespace / , / ;, up to 120 points); higherIsBetter = false / 0 / no means "lower is better". Up to 24
series chartsOne of: from: "table"; columns + fields.label; fields.label + fields.value; source: "chart:..."fields.series unitfrom: "table": the first non-numeric column is the category and every other numeric column becomes a series; a footer total row is left out. Wide format: one row per category, one series per column. label + value: paired by index into points, fields.series names the series, same names merge. Up to 20 series x 500 points
table tablesfrom: "table"; or list + columnsfields.urlWith columns, one row per node; numeric is detected when omitted. fields.url = the row link. Up to 30 columns x 500 rows; from: "table" keeps the <tfoot> total row
progressfields.label, fields.valuetotal textvalue accepts 68 / 100, 68 of 100, ¥912,000 / ¥1,200,000 and 68%; total overrides; with no total and a value above 1 it is read as a percentage. text defaults to the raw value. Up to 60
stepslistfields.title (default @text) subtitle stateAn approval flow; state reads a status word or @class and is classified as done / current / pending / rejected. Up to 60
itemslist, fields.title, fields.urlcoverURL author summary latestText tagsURLs must be inside domains; they open in the in-app browser. Up to 60
textvalue-All values, blanks dropped, joined with newlines; up to 20,000 characters

How steps states are recognized: your states are checked first (keys can only be done current pending rejected; each value is a case-insensitive substring list separated by |, e.g. "current": "process|doing"), then the built-in keywords, in the order rejected, current, done, pending; if nothing matches the step is pending. Built-ins include reject denied fail, current active processing, done complete approved and pending wait todo (plus Chinese equivalents).

How number text is parsed#

Metrics, progress, numeric table columns and chart values all share one parser, so you do not need to clean values in the rule.

CaseRuleExample
Number and unitTakes the first number and drops thousands separators; parentheses or a leading - make it negative; suffixes 亿 万 千 K M B multiply; the unit is a currency symbol before the number, else %, else the first word after the number¥12,480 = 12480, unit ¥; 3.2万 = 32000; (1,234) = -1234
deltaWith %: divided by 100, and a direction word sets the sign (↓ ▼ down negative, ↑ ▲ up positive, parentheses negative). Without %: only a bare number is accepted (treated as already a ratio)+12.5% = 0.125; ↓3% = -0.03; +12 orders is not recognized
Progressa / b, a of b = done a, total b; 68% = 0.68¥912,000 / ¥1,200,000
Numeric columnA cell parses as a number, has only a currency symbol / sign / parenthesis before it and at most 3 non-digit characters after it; a column is numeric when at least 60% of its non-empty cells are2026-11-20, Q1 and 12 orders are not numbers

Chart sources: chart:#

Many admin consoles draw charts with ECharts / Chart.js / Highcharts / ApexCharts, so the DOM holds only a <canvas>. A role: "series" block can read the chart's data directly through source, with no image parsing.

FormMeaning
chart:echarts#0The 0th ECharts chart in DOM order. Library names: echarts highcharts chartjs apexcharts; the index starts at 0 and defaults to 0
chart:auto#1The 1st chart across all libraries together, in DOM order
chart:css(#c-region)The chart whose container sits inside (or contains) an element matched by that CSS selector; an optional #index may follow. Use it when the chart order on the page can change; it is more stable than an index

Display: display.blocks and span#

How a block is shown goes in display.blocks.<block id> (declare display.blocks in requires). Besides show / fallback / hidden, dashboards add span.

Roleshow valuesDefault
seriescolumn stackedColumn bar stackedBar line area pie donutThe kind suggested by the chart source; otherwise line above 12 categories, else column
metricsgrid (cards), row (one swipeable row)grid
tabletabletable
progressbar, ringbar
stepsvertical, horizontalvertical
itemslist, rail, gridlist
texttexttext

span is full (a whole row) or half (half width in the two-column layout on tablets and wide screens; always a full row on phones). By default pie / donut charts and ring progress are half and everything else is full. If show is not valid for the role, fallback is tried, then the default; hidden: true hides the block.

Actions: actions / itemActions (write actions)#

A dashboard can write: approve / reject, comment, edit, submit a form. actions (block level, any role) appear as buttons on the block; itemActions (item level, only for items / table) give every item / row its own set of buttons. Before any action that changes data, the app always shows a native confirmation, and a rule cannot turn it off. How it runs: the hidden browser opens the site page with your login, fills in values and clicks the page's own button like a person would (or calls a page function, or sends a request), then uses the page's own text as the success / failure message. Only dashboards (dashboard) support actions for now.

{
  "id": "todo", "title": "Awaiting my approval", "role": "items", "list": "css:#pending .apw",
  "fields": { "title": "css:a.card .t@ownText", "url": "css:a.card@href", "key": "@data-id" },
  "itemActions": [
    { "id": "approve", "title": "Approve", "style": "primary",
      "run": { "scope": "row", "steps": [ { "acceptDialog": true }, { "click": "button.btn-approve" } ] },
      "success": { "text": ".toast.success" }, "error": "#alert .alert.error" }
  ]
}
FieldDescription
idRequired, [A-Za-z0-9_-]{1,40}, unique within the block
titleButton text, 1-40 characters (optional for a form's submit)
styleprimary / normal (default) / destructive (the confirmation is shown in red)
iconAn SF Symbol name
confirmConfirmation text, up to 300 characters; the app's default wording if omitted
mutatesDefault true (forced confirmation, needs authorization); false = a read-only action (export, refresh) that is not confirmed
inputsItems the user fills in before running, up to 20
runRequired; exactly one of steps / js / request
success{text?, gone?, url?, json?}; any one that holds means success
errorCSS: any new visible text there means failure, and that text is shown as the message
afterOn success: refresh (default, reload the dashboard) / open (open the result page) / none
timeoutMilliseconds to wait for a success / failure signal, 1000-60000, default 15000

At most 8 actions per block. Inputs inputs[] (the same structure as a form block's fields[]): id (required), label, kind (text multiline number date datetime select multiselect toggle file password; an unknown value is treated as text), required, placeholder, options ([{value, title}] or an array of strings), value (prefill), min / max, help, selector (form blocks: the element to fill). Files are limited to 10 MB and can only be used with upload.

The three ways to run: run#

FormDescription
{ "page"?, "scope"?, "steps": [...] }Prefer this one. Opens the page in the hidden browser and operates the page's existing controls step by step
{ "page"?, "js": "functionName" }After opening the page, calls the function f(inputs, ctx) from scripts.source in the page's own world, so it can use the page's JS; it returns {ok?, message?, openURL?}, and throwing means failure. Needs script authorization
{ "page"?, "request": {method, url, headers?, body?, json?, csrf?, csrfHeader?} }After opening the page, sends a request directly with the page's login (cookies). csrf = a CSS selector that reads the token; a string body is form-encoded, an object / array is JSON; success = 2xx and (success.json holds, or when absent the response JSON's ok / success is not false); method is GET POST PUT PATCH DELETE, default POST

Page to run on: run.page (a template), then the form block's page, then the item URL, then the dashboard URL. With "scope": "row" on an item action (or when the item has no URL), the app first finds that row on the dashboard page and the step selectors are relative to that row; a step with "scope": "page" is relative to the whole page (dialogs, global messages). If the row cannot be found you get "the item is no longer on the page". Items are located by fields.key (for example "key": "@data-id") or by the item URL, so write a key whenever you write itemActions.

Template variables (usable in page, request.url, headers, body and a step's value): {{inputs.<id>}}, {{item.url}}, {{item.key}}, {{board.url}}, {{page.url}}, {{csrf}}. Referring to an input you did not declare is an error.

StepDescription
{"fill": css, "from": inputId} or "value": templateSets an input's value (works for React / Vue controlled inputs too); writes text into contenteditable
{"select": css, "from" / "value"}A <select> is matched by value, then by text; radio / checkbox groups select the matching item
{"check": css, "from" / "value"}Sets a checkbox to that boolean (default true)
{"upload": css, "from": inputId}Puts the file into an <input type=file>
{"click": css}Scrolls into view and clicks; fails if the browser's own form validation rejects, with that field's message
{"waitFor": css | "navigation", "timeout": ms}Waits for an element to appear / for the main page to finish navigating (default 10 s)
{"acceptDialog": true}Afterwards the page's confirm() / prompt() answer yes (the default is no); alert text is kept as a fallback message
{"wait": ms}Pause, up to 30000

Each step has one verb; the rest are options: from / value / timeout / optional / scope. When an element is missing, element steps retry every 250 ms until the step's timeout (default 5000, up to 30000); with "optional": true the step is skipped, otherwise it fails. At most 40 steps.

Deciding success: success.text is a CSS selector (a visible element with text means success and its text becomes the message) or re:<regex> (matches the page text); success.gone: the selector no longer matches; success.url: a regex matched against the address after navigation; success.json (request only): simple conditions such as $.ok == true or $.code != 0. error is checked first (text that was already there before the run does not count), then the success conditions, every 200 ms until timeout; a timeout is a failure. Always write both success and error: without them the app can only wait for the page to settle and call it success when no new error appears, so a silent rejection by the site goes unnoticed.

Forms: the form block#

role: "form" shows a native form that is submitted on the site. Declare board.forms in requires.

{
  "id": "expense", "title": "Expense request", "role": "form", "from": "form", "list": "css:form#expense",
  "submit": { "id": "submit", "title": "Submit request", "success": { "url": "approval\\.html\\?id=" },
              "error": "#form-error", "after": "open" }
}

Embedded pages: the embed block#

role: "embed" places a piece of web content in a dashboard card; declare board.embed. There are two kinds: html (a web template that ships with the rule) and fragment (a region of a site page, using the site login).

{
  "id": "stats", "title": "Approval stats", "role": "embed", "embed": "html", "height": 220, "scripts": true,
  "html": "<b id=n>0</b><script>n.textContent=[].concat(unweb.data.types||[]).length</script>",
  "data": { "types": "css:#pending .apw .meta span:nth-child(2)@text" }
}
{ "id": "flow", "title": "Approval progress", "role": "embed", "embed": "fragment",
  "url": "/approval.html?id=AP-1040", "selector": "ol.steps", "height": 260 }
FieldDescription
htmlThe template, up to 200 KB. {{name}} = the first value of name in data, HTML-escaped; {{{name}}} = all values joined by newlines and sanitized with an allowlist (script / style / iframe / event attributes / javascript: links removed); {{json:name}} = a JSON array that is safe inside <script>. Site content is never injected raw
data{name: expression}, evaluated on the dashboard page; read it in the page via window.unweb.data (one value = a string, several = an array, none = null)
url / selectorfragment: the page address (default: the dashboard page; relative addresses resolve against the dashboard page and must be inside domains) and the region to cut out; it uses the site login
heightInitial height (pt), 40-2000, then adapts to the content
scriptshtml defaults to false (no scripts run); fragment defaults to true (the site's own scripts, which single-page apps need to render). true on html = the rule ships its own JS and needs script authorization
interactiveDefault true; false = view only, touches go to the outer scroll view

Inside an embedded page (an html block with scripts authorized) the bridge window.unweb is available: open(url) opens in the in-app browser (must be inside domains), refresh() reloads the dashboard, toast(text) shows a message, action(id, inputs) triggers one of this rule's actions (it still goes through the native confirmation), data (read-only), theme (the current theme) and holdScroll(bool) (pause the outer scroll while dragging). The theme is provided as CSS variables that follow light / dark mode: --ui-bg --ui-surface --ui-surface2 --ui-fill --ui-text --ui-text2 --ui-text3 --ui-accent --ui-on-accent --ui-separator --ui-success --ui-warning --ui-danger --ui-font --ui-font-serif --ui-font-mono --ui-radius.

Limits: the embedded page's CSP allows only inline scripts (once authorized) and scripts from the rule's domains; network requests (connect) can reach only domains; subframes and form submission are always blocked; images / media / fonts may use https. A dashboard keeps at most 4 live embeds at once and loads them lazily as they scroll near.

Safety and authorization for write actions#

  • A rule with write actions (mutates not false), a form block, run.js, or an html embed with scripts: true needs the same one-time authorization as a script. The consent sheet adds a line saying the rule can use your login to submit forms, approve or change data on the site, and that every change is asked about first. Until authorized the rule is unusable, and validation reports the info writeActions.
  • Every run has a native confirmation; a rule can neither disable it nor run automatically. The pages, requests and redirects involved must be inside domains.
  • Logs record only input ids, never values; passwords and files appear as ***. One action runs at a time per rule, and a failed action is never retried automatically.
  • The site wizard's "Try it" shows the dashboard only and never runs actions. The wizard recognizes approve / reject buttons next to items and <form>s, and you can add an action by tapping a button on the page; page-level buttons it finds are off by default.
  • Never invent selectors: use only selectors you have confirmed exist on the page. If the site changes and a selector stops matching, the action fails with "no ... on the page" instead of doing something wrong.

Capabilities, validation and limits#

Common pitfalls#

5. Extraction expression syntax#

5.1 Structure#

分支 || 分支 || …                 ← 回退:依次尝试,取第一个非空结果
分支 = [root:] 来源 | 过滤器 | 过滤器 … [##正则##替换]
     或 tpl:文本{{子表达式}}文本…  ← 拼接

5.2 Sources#

SyntaxMeaningExample
css:selector@valueCSS selector (css: can be omitted)css:h3 a@text, img@data-src
@valueRead a value from the current node itself (common inside list items)@href, @text
xpath:…, or starting with / or (XPath 1.0//meta[@property='og:title']/@content
json:…, or starting with $. or $[JSONPath$.data.list[*].name
re:/regex/flags#groupRegex extractionre:/"title":"(.*?)"/#1
'text' or "text"Constant'ongoing'
{{variable}}Template variable{{keyword}}
js:functionNameCall a script functionjs:decodeTitle
root: prefixIgnore the current list item and evaluate against the whole documentroot:css:a.next@href

5.3 CSS accessors#

SyntaxResult
@textText of all descendants (whitespace collapsed). Used by default when no accessor is given
@ownText / @textNodesOnly the text directly owned by the element itself
@htmlInner HTML
@outerHtml / @allHTML including the element itself
@bgBackground image URL, see 5.9
@attributeNameRead an attribute, such as @href, @data-src, @content. Attribute names may contain only letters, digits, _, : and -

CSS extensions#

5.4 XPath#

Works only on HTML / XML. On a JSON response the result is empty and a warning is logged. The XPath union operator | must be wrapped in parentheses, for example (//a | //b); otherwise it is treated as a filter separator.

5.5 JSONPath#

SyntaxDescription
$Root
.key, ['key']Read a key
[n]Index; negative values are supported ([-1] is the last)
[*], .*Wildcard
..keyRecursive search
[?(@.k == 'v')]Simple filter; operators == != < > <= >=; the key may be a dotted path such as @.a.b

Slices [1:3], multi-select ['a','b'] and script expressions are not supported. A list of $.data.list is expanded automatically into one item per element, and child fields such as $.title are evaluated relative to each element.

5.6 Regex source re:/…/#

5.7 Filters#

Filters are chained in order with |, and names are case-sensitive. String arguments must be quoted; integer arguments are not.

FilterEffectExample
trim / lower / upperTrim whitespace / lowercase / uppercase@text | upper
replace('regex','replacement'[,'flags'])Replace all matches; the replacement may use $1replace('^Author:\s*', '')
replaceFirst('regex','replacement')Replace only the first match
match('regex'[, group])Take the given group of the first match (group 1 by default). If nothing matches, the value is dropped@href | match('/book/(\d+)', 1)
split('separator') / join('separator')Split into multiple values / join into onesplit(',')
first / last / index(n) / slice(a[,b])First, last, n-th, or a range. Zero-based; negative numbers count from the endindex(-2), slice(0,3)
prepend('s') / append('s')Add a prefix / suffix
default('s')Use s when the result is emptydefault('Unknown')
absurlConvert to an absolute URL (done automatically for URL fields)
intTake the first integercss:.count@text | int
linesSplit on line breaks into multiple values and drop empty lines@html | html2text | lines
uniqueRemove duplicates, keeping order
existsOutputs "true" / "false", for boolean fieldscss:.vip | exists
html2textTurns <br> and <p> into line breaks, strips tags, decodes entities@html | html2text
decodeEntities / urlDecodeDecode HTML entities / percent-encoding
js:functionNameCall a script function@text | js:fix
re:/…/#nRegex extraction

first, last, index, slice and exists keep the node form, so their result can still be used as a list; other filters convert nodes to text.

5.8 Fallback, concatenation, replace shorthand#

FeatureSyntaxNotes
Fallbackimg@data-src || img@srcThe right side is evaluated only if the left side is empty
Default valuecss:.status@text | default('unknown')
Concatenationtpl:https://example.com/book/{{@data-id}}.htmlEach {{ }} is evaluated independently; an empty result becomes an empty string
Replace shorthandcss:.author@text##^Author:\s*##Equivalent to | replace(…); must be at the end of the branch. Ending with ### replaces only the first match; write a literal # as \#

What "empty" means: a selector with no match, a missing attribute, a value that is all whitespace, and an attribute that exists but is an empty string all count as empty, and trigger || fallback and default.

5.9 Background images and lazy loading#

5.10 Common pitfalls#

  1. Backslashes must be doubled in JSON: \d in an expression becomes "\\d" in a JSON string, and \[ becomes "\\[".
  2. A top-level | is always a filter separator. Only a | inside quotes, (), [], {{ }} or re:/…/ does not count.
  3. No filters after tpl:: in tpl:a{{x}} | trim, the | trim is treated as plain text. To process the result, put the filter inside {{ }}.
  4. A misspelled variable name in tpl: raises no error: for example {{keywrod}} is treated as a CSS tag selector and silently returns empty.
  5. match drops the value when nothing matches, which can leave the whole field empty. Add | default('…') as a safety net.
  6. A wrong CSS selector raises no error: at runtime only a warning is logged and the result is empty. Syntax errors in filter names, brackets, quotes and so on are reported by validation as exprSyntax, with the character position.
  7. An expression is 1 to 4096 characters long; a single field's result over 64KB is truncated (summary and body text have higher limits).

6. Template variables#

VariableWhere availableDescription
{{keyword}}searchThe keyword the user typed, percent-encoded in URLs according to charset
{{keyword|raw}}searchAs typed, not encoded
{{page}} / {{page0}} / {{offset}}PaginationPage number (starting from startPage) / page number − 1 / (page number − 1) × pageSize
{{sectionId}} / {{sectionURL}}exploreThe current section's id / URL
{{itemURL}}detail, tocWork URL
{{chapterURL}}contentChapter URL
{{url}}authorOnlyURLPost URL
{{host}}AllThe first non-wildcard domain in domains
{{baseURL}}AllThe current base URL
{{storage.key}}AllA value from script storage (requires a script and authorization); empty string if the key does not exist
{{js:functionName}}request.url onlyCalls a script function with no arguments and substitutes its return value into the URL

7. JS scripts#

When declarative expressions are not enough (for example the response is encoded or its structure needs reshaping), you can write JS scripts. Avoid them when you can: a rule without scripts works immediately after import and is easier to maintain.

7.1 Where scripts go#

{
  "scripts": {
    "source": "function prepare(req, ctx) { return req; }\nfunction decode(resp, ctx) { return resp; }",
    "hooks": {
      "search": { "beforeRequest": "prepare" },
      "content": { "afterResponse": "decode" }
    },
    "fieldTimeoutMs": 3000,
    "hookTimeoutMs": 10000
  }
}

7.2 Field-level functions#

7.3 Page-level hooks#

hookSignaturePurpose and conventions
beforeRequest(req, ctx) → reqRewrite the request, for example to add headers or parameters. req = {url, method, headers, body}. The returned headers replaces the original headers as a whole, so modify req.headers and return the whole object
afterResponse(resp, ctx) → respDecode or rewrite the response. resp = {status, url, headers, body}. Only status and body of the return value are used; if body is returned as an object it is treated as JSON
parse(resp, ctx) → result objectTakes over parsing completely, replacing declarative extraction
transform(output, ctx) → result objectPost-process the result of declarative extraction. Must return a complete object; for example, search must return {items, …}

Result format of parse / transform#

PageFormat
search / explore{items: [{title, url, coverURL?, author?, summary?, latestText?, tags?}], nextPageURL?, hasMore?}
detail{title, coverURL?, author?, intro?, status?, tags?, extra?, tocURL?, …}
toc{chapters: [{title, url, isLocked?}], nextPageURL?, hasMore?}; for video use {lines: [{name, episodes: [...]}]}
content · novel{title?, paragraphs: [...], nextPageURL?}
content · manga{images: [url]} or {pages: [{url, width?, height?}]}
content · video{streams: [{url, type?, quality?}], subtitles?}
content · article{title, author?, publishedAtText?, html}
content · forum{title, posts: [{floor?, author, avatarURL?, timeText?, quote?, html}], pageCount?}

Fields of the wrong type are dropped and a warning is written; URLs are completed automatically.

The ctx object#

FieldDescription
rule{id, name, version, domains}
stepThe current page: search / explore / detail / toc / content
envRuntime environment: jsc (default environment) or webview (page environment)
url / baseURLRequest URL / final URL
pagePage number
keywordKeyword (search)
sectionIdSection id (explore)
itemURLWork URL
chapterThe current chapter object (content)
docThe current document. In the default environment it exists only in afterResponse / parse / transform; in the page environment it is the page's document

7.4 Runtime environments#

ConditionEnvironmentCharacteristics
requiresWebView: false (default)Default environment (ctx.env is jsc)No DOM, fetch, XMLHttpRequest or timers; only the APIs below are available. An async function can await only those APIs
requiresWebView: truePage environment (ctx.env is webview)Can read the page's document; the page's own scripts cannot see your script

Globals are not guaranteed to persist between pages; use storage for data that must be kept. Avoid infinite loops and Promises that never settle: a timeout reports RUL_010, and after repeated timeouts the rule's scripts are paused for the rest of the current session.

7.5 Available APIs#

http#

http.get(url, opts?)            // → Promise<{status, url, headers, body}>
http.post(url, body, opts?)
http.getSync(url, opts?)        // 同步版本,仅默认环境可用
http.postSync(url, body, opts?)
// opts: { headers?, charset?, timeoutMs?(5000~60000), responseType?: 'text' | 'json' | 'base64' }
await cookie.get(url)          // → {name: value}
await cookie.get(url, name)    // → string | null

storage (the rule's private on-device key-value store)#

await storage.get(key)          // 不存在时为 null
await storage.set(key, value)   // value 需能被 JSON 序列化
await storage.remove(key)
await storage.keys()
await storage.clear()

All these methods return a Promise. Keys are 1 to 128 characters, a single value is at most 64KB once serialized, and each rule may store at most 1MB in total. Storage is on this device only and is not synced.

log / console#

log.debug / info / warn / error(...), and console.log / info / debug / warn / error. Output appears in the execution log, at most 4KB per entry and 500 entries per step.

util#

FunctionDescription
base64Encode(s, enc?) / base64Decode(s, as?, charset?)Base64 encode / decode
hexEncode / hexDecodeHex encode / decode
md5 / sha1 / sha256(text)Digests, returned as lowercase hex
hmacSHA256(key, msg, keyEncoding?)Returns hex
aesEncrypt(p) / aesDecrypt(p)p = {data, key, iv?, mode: 'CBC' | 'ECB' | 'GCM', padding?, keyEncoding?, dataEncoding?, output?, tag?}. Key of 16/24/32 bytes; iv of 16 bytes for CBC and 12 bytes for GCM; GCM decryption must pass tag
absURL(base, rel)Resolve a URL
urlEncode(s, charset?) / urlDecode(s, charset?)Supports charsets such as gbk and big5
jsonPath(obj, path)Returns an array. Not available in the page environment
decodeCharset(base64Bytes, charset)Decode bytes with the given charset

util in the page environment supports only the utf-8 and latin1 charsets.

dom (HTML up to 5MB)#

const d = dom.parse(html, baseURL?);
d.select('css') / d.selectOne('css') / d.xpath('expr')
el.text() / el.ownText() / el.html() / el.outerHtml() / el.attr(name) / el.absURL(attr)
d.eval('css:h1@text')   // 用第 5 节的表达式语法取值;页面环境不可用

7.7 Examples#

Add headers before the request, decode after the response, tidy after extraction#

{
  "scripts": {
    "source": "function addLang(req, ctx) {\n  req.headers['Accept-Language'] = 'en';\n  return req;\n}\nfunction decode(resp, ctx) {\n  resp.body = util.base64Decode(resp.body);\n  return resp;\n}\nfunction tidy(out, ctx) {\n  out.items = out.items.map(function (i) { i.title = i.title.trim(); return i; });\n  return out;\n}",
    "hooks": { "search": { "beforeRequest": "addLang", "afterResponse": "decode", "transform": "tidy" } }
  }
}

Parse a JSON API with parse (complete rule)#

This rule demonstrates {{js:…}} and parse. Note: even when parse is used, the search list / fields are still required by validation.

{
  "id": "com.example.hn-parse-demo",
  "name": "HN (parse demo)",
  "version": 1,
  "contentType": "forum",
  "domains": ["hn.algolia.com"],
  "rateLimit": {"concurrency": 1, "intervalMs": 500},
  "pages": {
    "search": {
      "request": {
        "url": "https://hn.algolia.com/api/v1/search?query={{keyword}}&tags={{js:tag}}&page={{page0}}"
      },
      "list": "$.hits[*]",
      "fields": {
        "title": "$.title",
        "url": "tpl:https://hn.algolia.com/api/v1/items/{{$.objectID}}"
      },
      "pagination": {"mode": "template", "maxPages": 5}
    },
    "content": {
      "request": {"responseType": "json"},
      "thread": {
        "title": "$.title",
        "posts": {
          "list": "$..children[*]",
          "fields": {
            "floor": "$.floor",
            "author": "$.author",
            "timeText": "$.created_at",
            "body": "$.text"
          }
        }
      }
    }
  },
  "scripts": {
    "source": "function tag() { return 'story'; }\nfunction parseHits(resp, ctx) {\n  var d = JSON.parse(resp.body);\n  return {\n    items: d.hits.map(function (h) {\n      return {\n        title: h.title,\n        url: 'https://hn.algolia.com/api/v1/items/' + h.objectID,\n        author: h.author,\n        latestText: h.num_comments + ' comments'\n      };\n    }),\n    hasMore: d.page + 1 < d.nbPages\n  };\n}",
    "hooks": {"search": {"parse": "parseHits"}}
  }
}

8. Captcha and login detection#

8.1 verification: captcha detection#

The app recognizes common captcha pages. When one appears, it shows the site's own verification page for the user to complete personally, then continues automatically; the app never completes or bypasses a captcha itself. If a site's verification page is unusual and the app does not recognize it, you can add the following signals:

FieldDescription
statusCodesExtra status codes treated as a verification signal (must be combined with other conditions); at most 10 entries, values 100 to 599
bodyContainsThe page is judged to be a captcha page if the response body contains any of these strings; at most 10 entries
selectorExistsJudged if the page contains any of these CSS selectors; at most 10 entries
urlContainsJudged if the final URL contains any of these strings; at most 10 entries
successSelector / successURLPattern / successCookieConditions that show the user has completed verification: a selector appears / the URL matches a regex / a given cookie appears
stableMsSettling period after completion, 500 to 5000 ms
disableBuiltInDetectionBoolean; turns off the app's built-in weak-signal detection (use it for false positives)

The page-level request.captchaMarkers works the same way but applies only to that page.

8.2 loginDetection: login detection#

When any condition is met, the user is told that login is required (RUL_LOGIN_REQUIRED). After the user logs in in Web mode, Native pages use the same login state.

FieldDescription
statusCodesStatus codes
urlContainsFinal URL contains
bodyContainsResponse body contains
selectorExistsPage contains selector
loginURLThe address opened by "Log in on the web"; its host should be in domains

When loginDetection is not configured, the app prompts for login only in clear-cut cases: HTTP 401, or a redirect to a page whose path contains login / signin / passport while the required fields are empty.

{
  "loginDetection": {
    "urlContains": ["/account/login"],
    "selectorExists": ["form#login-form"],
    "loginURL": "https://example.com/account/login"
  }
}

9. Appearance display and capability declaration requires#

9.1 display: native interface appearance#

display is optional; the app picks a default appearance based on the content type. Invalid values are ignored without an error. Adjust it visually in the "Appearance" step of the site wizard, then look at the generated JSON.

PathAllowed valuesDescription
list.styleposter / book / story / text / cardList style: poster wall / book cover / image-and-text feed / plain text / card
list.columns2~4poster style only
list.coverAspect3:4 / 2:3 / 16:9 / 1:1Cover aspect ratio
list.thumbnailleading / trailingThumbnail position for the story style
list.featuredBooleanEnlarge the first item into a featured card
list.densitycomfortable / compactSpacing
list.titleLines / list.summaryLines1~3 / 1~4Number of lines shown for title and summary
list.slotsauthor / summary / latest / tags / x.<extra key>Which fields appear on the card, in order
list.latestBadgeBooleanShow the latest chapter as a badge on the cover
sections{section id: list config}Override the list style per section
category.styletabs / grouped / gridCategory navigation style
detailheader (cover / immersive), introLines (1~8), showTags, showStatus, tocInline (integer >= 0; 0 means only a "Contents" button), primaryLabel (primary button label)Detail page
tocstyle(list / grid), descendingTable of contents
blocks{block id: {…}}How filter blocks, detail blocks and dashboard blocks are displayed and where; best generated by the wizard. span (full / half) is for dashboard blocks only (4.11)
immersiveBoolean, default falseFull screen on scroll: native pages hide the status bar, top buttons and bottom action bar while you scroll down, and bring them back when you scroll up, reach the top or tap the top of the screen. Has no effect when the content fits on one screen; novel and manga readers keep their own immersive mode. The “Full screen on scroll” switch on the rule’s detail page changes it too
{
  "display": {
    "list": { "style": "story", "thumbnail": "trailing", "density": "compact", "slots": ["author", "summary"] },
    "detail": { "header": "cover", "introLines": 4 },
    "toc": { "style": "list", "descending": false }
  }
}

9.2 requires: capability declaration#

When a rule uses a newer capability, declare it in requires. An app version that does not recognize a capability skips that feature and keeps working normally, instead of failing to import.

CapabilityDeclare it when you use
explore.filterspages.explore.filters
detail.blockspages.detail.blocks
source.interceptrequest.render.capture
display.blocksdisplay.blocks
board.blockspages.board.blocks (dashboards)
source.chartA dashboard block uses source: "chart:..."
board.actionsA dashboard block uses actions / itemActions
board.formsA dashboard uses a role: "form" block
board.embedA dashboard uses a role: "embed" block

Using capture, detail.blocks, board.blocks, source.chart, board.actions, board.forms or board.embed without declaring it gives the warning missingCapability; an unknown capability name gives the warning unknownCapability.

10. Validation and error codes#

10.1 Validation (on save or import)#

A rule with an error cannot be enabled; a rule with only warnings can be saved and used. Every issue includes its location (a JSON path), and expression errors also include the character position.

Common errors#

codeMeaning
requiredA required field is missing, has the wrong type, or the JSON itself is invalid
invalidId / invalidValueMalformed id / invalid value (enum, length, range)
invalidDomaindomains is empty, has more than 50 entries, has duplicates, or contains an invalid host name
hostNotDeclaredThe request URL's host is not in domains
invalidURLThe request URL does not start with http(s) or {{, contains a username and password, or has an invalid template variable
invalidHeaderInvalid request header, or a forbidden header was used
invalidPatternurlPatterns is invalid
exprSyntaxExpression syntax error (with character position)
missingFunction / scriptSyntaxScript function does not exist / script syntax error
missingPageA required page or content sub-key is missing; or there is neither search / explore nor urlPatterns
duplicateIdDuplicate id for a section, filter block, detail block or dashboard block
tooLarge / formatTooNewRule or script too large / file format version is newer than the app supports

Common warnings#

unknownField (unknown field), clamped (value out of range was clamped), unusedField (the field has no effect, for example render written without WebView enabled, or readingMode in a non-manga rule), paginationMismatch (inconsistent pagination config), invalidRegex (invalid regex in a cleanup replacement), domainCovered (domain already covered), noEntryPage (no search / Discover entry; the rule can only be entered from a matching web page), unknownCapability / missingCapability (unknown capability name / missing capability declaration).

Dashboard validation#

CodeLevelMeaning
V-38errorMissing pages.board; blocks missing / not an array / empty; request.url missing when there is no urlPatterns; a block id missing / malformed / reserved / duplicate / clashing with a filter; role missing; a role's required field missing (see the seven roles); a column without title or value
V-39warningMore than 24 blocks / 30 columns; unknown role; a malformed source or unknown library; chart: on a non-series block; fields, columns, states, value or list on a role that does not use them; from other than table; a states key that is not one of the four state names; pages.board in a non-dashboard rule; requires missing board.blocks / source.chart
V-40warning (needsRendering)A chart: source is used, but the rule lacks requiresWebView: true or the dashboard request uses render.capture
V-41errorActions (actions / itemActions / a form's submit): actions not an array; id missing / malformed / duplicated in the block; title missing (except submit); run missing, or not exactly one of steps / js / request; steps empty or over 40, an unknown verb, several verbs in one step, a missing selector for fill / select / check / upload / click, fill / select / upload with neither from nor value, waitFor without a value; from or {{inputs.x}} referencing an undeclared input; run.js not a function name or absent from scripts.source; request.url missing, an invalid method, a static host outside domains; malformed success.json / success.text / success.url; after not refresh / open / none; an input id missing / malformed / duplicated
V-42warningMore than 8 actions / 20 inputs; itemActions outside items / table; scope: "row" on a block-level action; from / value on a step that takes no value; success.json on a non-request run; an unknown input kind, a select without options, an unknown style, an unknown template variable; a selector the parser cannot read (invalidSelector, which may still work in a browser, so only a notice); a step timeout or timeout out of range
V-43errorA form block with neither fields nor from: "form" / list; an explicit field without selector; an embed block without embed or not html / fragment; html missing html or over 200 KB; data not an object, an illegal name or a bad expression; a fragment without selector or with a static url host outside domains; a non-numeric height
V-44warning / infoKeys that do not apply on form / embed blocks (url / selector on html, html / data on fragment); an html template naming something not in data; height outside 40-2000; requires missing board.actions / board.forms / board.embed. A rule with write actions / a form / run.js / an html embed with scripts gets the info writeActions: it needs one-time authorization

10.2 Runtime error codes#

When a rule fails at runtime, the page shows an explanation and an error code.

CodeMeaningWhat to do
RUL_001Rule unavailable (deleted, disabled, or format too new)Check that the rule is enabled
RUL_002Invalid rule structure or URLSee the validation report
RUL_003The rule does not define this pageAdd the missing page
RUL_004Network failureCheck your connection and retry later
RUL_005The site returned an HTTP error429 means too many requests; increase rateLimit.intervalMs
RUL_006A domain that was not declared was accessedAdd the domain to domains
RUL_007Expression syntax errorFix it according to the validation report
RUL_008The page opens, but no content can be extractedThe selector is broken, or the content is rendered client-side (check whether WebView is suggested)
RUL_009The script threw an exceptionCheck the function name and stack in the log
RUL_010 / RUL_011 / RUL_013 / RUL_014 / RUL_016Timeout or resource limit exceededReduce the number of requests and the amount of data, then retry later
RUL_012Script not authorizedCheck and allow the script in the rule details
RUL_015Page encoding not recognizedSet request.charset
RUL_017The imported content is not recognized as a ruleMake sure it is Unweb rule JSON and that the link does not return a web page
RUL_020Rule format version too newUpdate the app
RUL_021The search keyword is emptyEnter a keyword before searching
RUL_CAPTCHA_REQUIREDCaptcha / human verification requiredComplete the verification in the web page as prompted
RUL_LOGIN_REQUIREDLogin requiredLog in in Web mode

11. Debugging in the app#

  1. Test (trial run): tap "Test" in the rule editor to run each page in turn. The result lists the extracted value of every field, plus the raw response and a page snapshot. A trial run does not require the rule to be enabled and does not change its state.
  2. Execution log: every run is recorded; open it to see three tabs:
    • Steps: a summary of input and output, timing, and errors for each step (request, render, each hook, list selection, and so on);
    • Requests: method, URL, status code, size, and timing of each request, including requests made by scripts;
    • Log: for example which fields are empty, why items were dropped, and the output of log in scripts.
  3. In a script, print intermediate values with log.info(JSON.stringify(x)).
  4. "Copy all" copies the whole log so you can share it. Sensitive values such as Cookie and Authorization are automatically replaced with ***.
  5. Picking selectors: after turning on developer mode in "Me › Developer tools", the page menu of a web page offers panels such as Elements, Source, and Network for inspecting the page structure directly. You can also connect the iPhone to a Mac and use Safari's Web Inspector.

Suggested order: first check that the request succeeded (status code, final URL); then check that list selects the right number of nodes; finally go through the fields to see which is empty. Most problems are a selector at the wrong level (fields should be relative to each list item) or content that is actually rendered client-side.

12. Complete examples#

The first four rules below are the examples built into the app (a few fields are trimmed for readability); the fifth is a fictional dashboard example. All of them pass validation and can be imported and modified directly.

12.1 article: Wikipedia#

Search uses the public MediaWiki API; the detail page and body are parsed from HTML. remove strips edit links, footnotes, navigation boxes, and everything after the "References" section. The \\\\[ in replace becomes \\[ after JSON decoding, and is decoded once more in the expression's string argument, giving the regex \[.

{
  "id": "org.wikipedia.sample",
  "name": "Wikipedia",
  "version": 2,
  "author": "Unweb",
  "contentType": "article",
  "domains": ["wikipedia.org", "wikimedia.org"],
  "urlPatterns": ["https://*.wikipedia.org/wiki/*"],
  "iconURL": "https://en.wikipedia.org/static/favicon/wikipedia.ico",
  "requiresWebView": false,
  "rateLimit": {"concurrency": 2, "intervalMs": 200},
  "pages": {
    "search": {
      "request": {
        "url": "https://en.wikipedia.org/w/rest.php/v1/search/page?q={{keyword}}&limit=20",
        "responseType": "json"
      },
      "list": "$.pages[*]",
      "fields": {
        "title": "$.title",
        "url": "tpl:https://en.wikipedia.org/wiki/{{$.key}}",
        "coverURL": "$.thumbnail.url",
        "summary": "$.description || $.excerpt | html2text"
      },
      "pagination": {"mode": "none"}
    },
    "detail": {
      "fields": {
        "title": "css:#firstHeading@text",
        "coverURL": "css:meta[property='og:image']@content",
        "summary": "css:meta[property='og:description']@content || css:#mw-content-text .mw-parser-output > section:first-child > p:not(.mw-empty-elt)@text | first | replace('\\\\[[0-9a-z ]+\\\\]', '')",
        "intro": "css:meta[property='og:description']@content || css:#mw-content-text .mw-parser-output > section:first-child > p:not(.mw-empty-elt)@text | first | replace('\\\\[[0-9a-z ]+\\\\]', '')"
      }
    },
    "content": {
      "article": {
        "title": "css:#firstHeading@text",
        "publishedAtText": "css:#footer-info-lastmod@text",
        "body": "css:#mw-content-text .mw-parser-output@html",
        "remove": [
          "css:.mw-editsection", "css:sup.reference", "css:.reference",
          "css:.reflist", "css:.mw-references-wrap", "css:.navbox",
          "css:.hatnote", "css:.ambox", "css:.metadata", "css:.mw-empty-elt",
          "css:style", "css:.mw-heading:has(#Notes) ~ *",
          "css:.mw-heading:has(#Notes)",
          "css:.mw-heading:has(#References) ~ *",
          "css:.mw-heading:has(#See_also) ~ *",
          "css:.mw-heading:has(#External_links) ~ *",
          "css:.mw-heading:has(#Further_reading) ~ *",
          "css:.mw-heading:has(#References)",
          "css:.mw-heading:has(#See_also)",
          "css:.mw-heading:has(#External_links)",
          "css:.mw-heading:has(#Further_reading)"
        ]
      }
    }
  }
}

12.2 article: Wikinews#

Same structure as Wikipedia. incategory:"Published" (encoded) is appended to the search keyword, so only published news is searched.

{
  "id": "org.wikinews.sample",
  "name": "Wikinews",
  "version": 2,
  "author": "Unweb",
  "contentType": "article",
  "domains": ["wikinews.org", "wikimedia.org"],
  "urlPatterns": ["https://*.wikinews.org/wiki/*"],
  "iconURL": "https://en.wikinews.org/static/favicon/wikinews.ico",
  "requiresWebView": false,
  "rateLimit": {"concurrency": 2, "intervalMs": 200},
  "pages": {
    "search": {
      "request": {
        "url": "https://en.wikinews.org/w/rest.php/v1/search/page?q={{keyword}}%20incategory%3A%22Published%22&limit=20",
        "responseType": "json"
      },
      "list": "$.pages[*]",
      "fields": {
        "title": "$.title",
        "url": "tpl:https://en.wikinews.org/wiki/{{$.key}}",
        "coverURL": "$.thumbnail.url",
        "summary": "$.excerpt | html2text"
      },
      "pagination": {"mode": "none"}
    },
    "detail": {
      "fields": {
        "title": "css:#firstHeading@text",
        "coverURL": "css:meta[property='og:image']@content",
        "summary": "css:meta[property='og:description']@content || css:meta[name=description]@content || css:#mw-content-text .mw-parser-output p:not(.mw-empty-elt)@text | first",
        "intro": "css:meta[property='og:description']@content || css:meta[name=description]@content || css:#mw-content-text .mw-parser-output p:not(.mw-empty-elt)@text | first"
      }
    },
    "content": {
      "article": {
        "title": "css:#firstHeading@text",
        "publishedAtText": "css:#footer-info-lastmod@text",
        "body": "css:#mw-content-text .mw-parser-output@html",
        "remove": [
          "css:.mw-editsection", "css:.noprint", "css:.navbox",
          "css:.xambox", "css:.mw-collapsible", "css:.hatnote",
          "css:.metadata", "css:.mw-empty-elt", "css:style",
          "css:.mw-heading:has(#External_links) ~ *",
          "css:.mw-heading:has(#External_links)"
        ]
      }
    }
  }
}

12.3 forum: Hacker News#

Everything uses the public Hacker News Search API. explore.sections defines two sections; {{page0}} maps to the API's zero-based page number; $..children[*] recursively collects all replies as floors.

{
  "id": "com.ycombinator.hn.sample",
  "name": "Hacker News",
  "version": 1,
  "author": "Unweb",
  "contentType": "forum",
  "domains": ["hn.algolia.com"],
  "urlPatterns": ["https://hn.algolia.com/api/v1/items/*"],
  "iconURL": "https://news.ycombinator.com/favicon.ico",
  "requiresWebView": false,
  "rateLimit": {"concurrency": 2, "intervalMs": 300},
  "pages": {
    "search": {
      "request": {
        "url": "https://hn.algolia.com/api/v1/search?query={{keyword}}&tags=story&hitsPerPage=20&page={{page0}}",
        "responseType": "json"
      },
      "list": "$.hits[*]",
      "fields": {
        "title": "$.title",
        "url": "tpl:https://hn.algolia.com/api/v1/items/{{$.objectID}}",
        "author": "$.author",
        "latestText": "tpl:{{$.num_comments}} comments",
        "summary": "$.url"
      },
      "pagination": {"mode": "template", "startPage": 1, "maxPages": 10}
    },
    "explore": {
      "sections": [
        {
          "id": "front",
          "title": "Front page",
          "request": {
            "url": "https://hn.algolia.com/api/v1/search?tags=front_page&hitsPerPage=30",
            "responseType": "json"
          },
          "list": "$.hits[*]",
          "fields": {
            "title": "$.title",
            "url": "tpl:https://hn.algolia.com/api/v1/items/{{$.objectID}}",
            "author": "$.author",
            "latestText": "tpl:{{$.num_comments}} comments",
            "summary": "$.url"
          },
          "pagination": {"mode": "none"}
        },
        {
          "id": "ask",
          "title": "Ask HN",
          "request": {
            "url": "https://hn.algolia.com/api/v1/search?tags=ask_hn&hitsPerPage=30",
            "responseType": "json"
          },
          "list": "$.hits[*]",
          "fields": {
            "title": "$.title",
            "url": "tpl:https://hn.algolia.com/api/v1/items/{{$.objectID}}",
            "author": "$.author",
            "latestText": "tpl:{{$.num_comments}} comments"
          },
          "pagination": {"mode": "none"}
        }
      ]
    },
    "detail": {
      "request": {"responseType": "json"},
      "fields": {
        "title": "$.title",
        "author": "$.author",
        "intro": "$.text | html2text || $.url"
      }
    },
    "content": {
      "request": {"responseType": "json"},
      "thread": {
        "title": "$.title",
        "posts": {
          "list": "$..children[*]",
          "fields": {
            "floor": "$.floor",
            "author": "$.author",
            "timeText": "$.created_at",
            "body": "$.text"
          }
        }
      }
    }
  }
}

12.4 novel: Wikisource#

A novel needs detail, toc, and content.text. The table of contents selects only links containing /Chapter; the body is split into paragraphs with @html | html2text | lines.

{
  "id": "org.wikisource.sample",
  "name": "Wikisource",
  "version": 2,
  "author": "Unweb",
  "contentType": "novel",
  "domains": ["wikisource.org", "wikimedia.org"],
  "urlPatterns": ["https://en.wikisource.org/wiki/*"],
  "iconURL": "https://en.wikisource.org/static/favicon/wikisource.ico",
  "requiresWebView": false,
  "rateLimit": {"concurrency": 2, "intervalMs": 200},
  "pages": {
    "search": {
      "request": {
        "url": "https://en.wikisource.org/w/rest.php/v1/search/page?q={{keyword}}%20incategory%3A%22Novels%22&limit=20",
        "responseType": "json"
      },
      "list": "$.pages[*]",
      "fields": {
        "title": "$.title",
        "url": "tpl:https://en.wikisource.org/wiki/{{$.key}}",
        "coverURL": "$.thumbnail.url",
        "summary": "$.description || $.excerpt | html2text"
      },
      "pagination": {"mode": "none"}
    },
    "detail": {
      "fields": {
        "title": "css:#firstHeading@text",
        "coverURL": "css:meta[property='og:image']@content",
        "author": "css:#ws-author@text || css:#header_author_text a@text",
        "intro": "css:meta[property='og:description']@content || tpl:{{css:#firstHeading@text}} · Wikisource"
      }
    },
    "toc": {
      "list": "css:table.ws-summary a[href*='/Chapter']",
      "fields": {"title": "@text", "url": "@href"}
    },
    "content": {
      "text": {
        "title": "css:#firstHeading@text",
        "paragraphs": "css:.prp-pages-output@html | html2text | lines",
        "remove": [
          "css:.pagenum", "css:.mw-editsection", "css:style",
          "css:section[data-mw-section-id='-1'] > h2"
        ]
      }
    }
  }
}

12.5 dashboard: sales board#

A fictional site, ops.example.com, showing the structure; it is not a built-in example. A rendered back-office page: metric cards, two ECharts charts (a monthly revenue + target combo chart and a regional share donut), a table read straight from <table>, an orders table with custom columns, quota progress and a "Time range" filter. Chart blocks use chart:echarts#n to pick the n-th chart on the page, so the rule needs requiresWebView: true and the source.chart capability. region becomes a half-width donut in display.blocks and quota is shown as ring progress.

{
  "id": "com.example.ops.sales",
  "name": "Example Ops Board",
  "version": 1,
  "contentType": "dashboard",
  "domains": ["ops.example.com"],
  "requiresWebView": true,
  "requires": ["board.blocks", "display.blocks", "source.chart"],
  "pages": {
    "board": {
      "request": {
        "url": "https://ops.example.com/sales.html?range=30d",
        "render": {"waitFor": "#kpis .kpi-card", "timeoutMs": 15000}
      },
      "title": "css:h1@text",
      "filters": [
        {
          "id": "range",
          "title": "Time range",
          "list": "css:#range a",
          "fields": {"selected": "@class | match('is-selected')"}
        }
      ],
      "blocks": [
        {
          "id": "kpi",
          "title": "Key metrics",
          "role": "metrics",
          "list": "css:#kpis .kpi-card",
          "fields": {
            "label": "css:.kpi-label@text",
            "value": "css:.kpi-value@text",
            "delta": "css:.kpi-delta@text",
            "trend": "css:svg.sp@data-points"
          }
        },
        {
          "id": "revenue",
          "title": "Monthly revenue vs target",
          "role": "series",
          "source": "chart:echarts#0"
        },
        {
          "id": "region",
          "title": "Sales by region",
          "role": "series",
          "source": "chart:echarts#1"
        },
        {
          "id": "top",
          "title": "Top products",
          "role": "table",
          "from": "table",
          "list": "css:table#top"
        },
        {
          "id": "orders",
          "title": "Latest orders",
          "role": "table",
          "list": "css:.order-row",
          "columns": [
            {"title": "Order no.", "value": "css:.no@text"},
            {"title": "Amount", "value": "css:.amt@text", "numeric": true}
          ],
          "fields": {"url": "css:a@href"}
        },
        {
          "id": "quota",
          "title": "Quota attainment",
          "role": "progress",
          "list": "css:.quota",
          "fields": {
            "label": "css:.name@text",
            "value": "css:.done@text",
            "total": "css:.target@text"
          }
        }
      ]
    }
  },
  "display": {
    "defaults": 1,
    "blocks": {"region": {"show": "donut", "span": "half"}, "quota": {"show": "ring"}}
  }
}

A second example, a detail page with only steps: the approval flow is shown horizontally, and urlPatterns lets the app offer native mode when you browse a matching page.

{
  "id": "com.example.ops.approval",
  "name": "Example Approval Detail",
  "version": 1,
  "contentType": "dashboard",
  "domains": ["ops.example.com"],
  "requiresWebView": true,
  "requires": ["board.blocks", "display.blocks"],
  "urlPatterns": ["https://ops.example.com/approval.html*"],
  "pages": {
    "board": {
      "request": {
        "url": "https://ops.example.com/approval.html?id=AP-1040",
        "render": {"waitFor": "#steps .step", "timeoutMs": 15000}
      },
      "title": "css:h1@ownText",
      "blocks": [
        {
          "id": "flow",
          "title": "Approval flow",
          "role": "steps",
          "list": "css:ol.steps li",
          "fields": {
            "title": "@ownText",
            "subtitle": "css:small@text",
            "state": "@class"
          }
        },
        {
          "id": "info",
          "title": "Request info",
          "role": "table",
          "from": "table",
          "list": "css:table#fields"
        },
        {
          "id": "comments",
          "title": "Comments",
          "role": "text",
          "value": "css:#comments .cm div@text"
        }
      ]
    }
  },
  "display": {"defaults": 1, "blocks": {"flow": {"show": "horizontal"}}}
}

12.6 dashboard: approval center (actions and embeds)#

A fictional site. Approve, reject and comment right in the dashboard, plus a self-drawn stats card and a piece of the site's approval progress. The three item actions show three styles: approve = steps (accept the page's confirm box, then click the original button), reject = a dialog plus a typed reason, comment = a direct request (with CSRF). Every action has success and error. The app asks for confirmation before running; the rule contains write actions, so it needs one-time authorization.

{
  "id": "com.example.ops.approvals",
  "name": "Example Approval Center",
  "version": 1,
  "contentType": "dashboard",
  "domains": ["ops.example.com"],
  "requiresWebView": true,
  "requires": ["board.blocks", "board.actions", "board.embed", "display.blocks"],
  "pages": {
    "board": {
      "request": {
        "url": "https://ops.example.com/oa.html",
        "render": {"waitFor": "#pending a.card", "timeoutMs": 15000}
      },
      "title": "css:h1@text",
      "blocks": [
        {
          "id": "todo",
          "title": "Awaiting my approval",
          "role": "items",
          "list": "css:#pending .apw",
          "fields": {
            "title": "css:a.card .t@ownText",
            "url": "css:a.card@href",
            "key": "@data-id",
            "summary": "tpl:{{css:.meta span:nth-child(1)@text}} · {{css:.meta span:nth-child(2)@text}} · {{css:.meta span:nth-child(3)@text}}",
            "latestText": "css:.amt@text"
          },
          "itemActions": [
            {
              "id": "approve",
              "title": "Approve",
              "style": "primary",
              "icon": "checkmark.circle",
              "run": {
                "scope": "row",
                "steps": [{"acceptDialog": true}, {"click": "button.btn-approve"}]
              },
              "success": {"text": ".toast.success"},
              "error": "#alert .alert.error"
            },
            {
              "id": "reject",
              "title": "Reject",
              "style": "destructive",
              "icon": "xmark.circle",
              "inputs": [
                {
                  "id": "reason",
                  "label": "Reason for rejection",
                  "kind": "multiline",
                  "required": true,
                  "placeholder": "Please enter a reason"
                }
              ],
              "run": {
                "scope": "row",
                "steps": [
                  {"click": "button.btn-reject"},
                  {"waitFor": "#reject-modal.open", "timeout": 3000},
                  {
                    "fill": "#reject-reason",
                    "from": "reason",
                    "scope": "page"
                  },
                  {"click": "#reject-confirm", "scope": "page"}
                ]
              },
              "success": {"text": ".toast.success"},
              "error": "#reject-error"
            },
            {
              "id": "comment",
              "title": "Comment",
              "icon": "text.bubble",
              "inputs": [
                {
                  "id": "text",
                  "label": "Comment",
                  "kind": "multiline",
                  "required": true
                }
              ],
              "run": {
                "request": {
                  "method": "POST",
                  "url": "/api/approvals/{{item.key}}/comment",
                  "body": {"text": "{{inputs.text}}"},
                  "csrf": "meta[name=csrf-token]"
                }
              },
              "success": {"json": "$.ok == true"}
            }
          ]
        },
        {
          "id": "budgets",
          "title": "Department budgets",
          "role": "progress",
          "list": "css:#budgets .brow",
          "fields": {
            "label": "css:.h span:nth-child(1)@text",
            "value": "css:progress@value || css:.bar i@style | re:/width:(\\d+)/#1",
            "text": "css:.h span:nth-child(2)@text"
          }
        },
        {
          "id": "stats",
          "title": "Approval stats",
          "role": "embed",
          "embed": "html",
          "height": 220,
          "scripts": true,
          "html": "<div class=\"s\"><b id=\"n\">0</b> <span> pending</span><div id=\"top\"></div></div><style>.s{font-family:var(--ui-font);color:var(--ui-text)}.s b{font:600 40px var(--ui-font-serif);color:var(--ui-accent)}.s span{color:var(--ui-text2)}#top{margin-top:8px;font-size:13px;color:var(--ui-text2)}</style><script>var t=[].concat(unweb.data.types||[]);document.getElementById(\"n\").textContent=t.length;document.getElementById(\"top\").textContent=t.slice(0,3).join(\" / \")</script>",
          "data": {"types": "css:#pending .apw .meta span:nth-child(2)@text"}
        },
        {
          "id": "flow",
          "title": "Latest approval progress",
          "role": "embed",
          "embed": "fragment",
          "url": "/approval.html?id=AP-1040",
          "selector": "ol.steps",
          "height": 260
        }
      ]
    }
  },
  "display": {"defaults": 1, "blocks": {"budgets": {"span": "half"}}}
}

12.7 dashboard: expense form#

role: "form" reads the page form's inputs automatically; after submitting, success is judged by the page's redirect and the result page opens.

{
  "id": "com.example.ops.expense",
  "name": "Example Expense Request",
  "version": 1,
  "contentType": "dashboard",
  "domains": ["ops.example.com"],
  "requiresWebView": true,
  "requires": ["board.blocks", "board.forms"],
  "urlPatterns": ["https://ops.example.com/expense.html*"],
  "pages": {
    "board": {
      "request": {
        "url": "https://ops.example.com/expense.html",
        "render": {"waitFor": "form#expense", "timeoutMs": 15000}
      },
      "title": "css:h1@text",
      "blocks": [
        {
          "id": "expense",
          "title": "Expense request",
          "role": "form",
          "from": "form",
          "list": "css:form#expense",
          "submit": {
            "id": "submit",
            "title": "Submit request",
            "success": {"url": "approval\\.html\\?id="},
            "error": "#form-error",
            "after": "open"
          }
        }
      ]
    }
  }
}