Skip to content

The ctx object

Member Description
inputs The resolved input values (frozen).
previous The last committed state, or null.
store Per-item persistent key/value storage (below).
http HTTP client (below). Only available in run() and validate().
net TCP and TLS sockets (below). Only available in run() and validate().
crypto Hashes, HMAC, signatures and random values (below).
xml A forgiving XML parser (below).
html A forgiving HTML parser with CSS selectors (below).
encoding base64Encode(text), base64Decode(b64), queryString(params) (text is UTF-8), and decode(data, charset, { from }) for other charsets (below).
sleep(duration) Waits for up to 60 s. Accepts milliseconds or a duration string.
item { id, name } of the item being run.
trigger "foreground", "pull", "background", "manual", "server" or "test"; see Triggers.
now A Date holding the run’s start time. Prefer it over new Date(), because fixtures control it.

console.log, console.info, console.warn, console.error and console.debug write to the run log. The log is capped at 500 entries of up to 2,000 characters each.

get(key), set(key, value), delete(key), has(key) and keys(). Values are JSON; set(key, undefined) deletes the key. The store is limited to 256 KB in total. It is writable in run(), onNotify() and validate(), and read-only in summary(). Changes are committed together with the state, only when the run succeeds.

Use the store for data that outlives one run but doesn’t belong on the card: history arrays for sparklines, baselines, cursors and “already alerted” markers.

ctx.http.request({ url, method, headers, query, body | json | form, timeout, responseType }). It has shorthands get, post, put, patch, delete and head, each called as (url, options).

  • query values are percent-encoded and appended; null and undefined values are skipped, and arrays repeat the key.
  • json sends a JSON body; form sends application/x-www-form-urlencoded. body must be a string.
  • Responses have status, ok (2xx), headers (with lowercased names), url, text(), json() and base64(). Non-2xx responses do not throw. Check ok or status.
  • Network failures, blocked hosts and timeouts reject the promise. Rejections have name set to NetworkError, PermissionError or LimitError.
  • Limits:
    • 5 MB per response
    • 100 requests per run
    • a 30 s default per-request timeout; the run timeout still applies
  • There are no cookies or caches between requests or runs.
  • A default User-Agent: Rundown/1 is sent unless the script sets one.

A script can contact only the hosts listed in meta.permissions.hosts, over HTTP or sockets. For HTTP the rule is applied again on every redirect.

Pattern Allows
api.example.com That host, over HTTPS, on any port
*.example.com Any subdomain over HTTPS, but not example.com itself
* Any host over HTTPS; the import screen flags this pattern prominently
api.example.com:8443 That host on that port only
http://192.168.1.10 Plain HTTP as well. HTTP is never allowed implicitly.
imap.gmail.com:993 Sockets (TLS) to that port, as well as HTTPS to it
*:993 Sockets (TLS) to any host on port 993; flagged like *
tcp://192.168.1.10:143 Unencrypted sockets as well. Must include the port.

Sockets always need an entry with a port, so an HTTPS entry such as api.example.com never allows raw connections.

ctx.net.connect({ host, port, tls = true, timeout = "15s" }) opens a connection and resolves to a socket:

Method Returns
write(data, { encoding }) Sends text as UTF-8, or bytes given as base64 with encoding: "base64".
readLine(options) The next line without its \n or \r\n, or null once the server has closed the connection.
readUntil(delimiter, options) Everything before delimiter (which is consumed), or null at the end.
read(byteCount, options) Exactly that many bytes; fewer only if the connection ends first, null if it already has.
close() Closes the connection.
  • Read options are { timeout = "30s", encoding: "utf8" | "base64" }. A read that times out rejects with TimeoutError and closes the socket.
  • Await each read before starting the next; a second read while one is waiting rejects.
  • TLS verifies the server’s certificate against host, as HTTPS does. There is no way to accept an invalid certificate. STARTTLS (upgrading a plain connection) is not supported; use the TLS port (IMAP 993, SMTP 465).
  • Limits: 4 connections per run, 5 MB received per run, 1 MB per line or delimited read. Connections still open when the run ends are closed.
  • Errors reject with name set to PermissionError, NetworkError, TimeoutError or LimitError, and a readable message such as “Connection refused” or “TLS failed: …”.
  • The run log records connects and closes (with byte counts), never the data.

Native hashing and signing (CryptoKit in the apps, node:crypto on the server), so large inputs stay fast. Available in every phase.

  • digest(algorithm, data, options), and the shorthands md5, sha1, sha256, sha384, sha512. algorithm is one of those names.
  • hmac(algorithm, key, data, options).
  • sign("es256", privateKey, data, options): an ECDSA P-256 / SHA-256 signature as r ‖ s (64 bytes), the form JWS uses. privateKey is PEM, PKCS#8 (PRIVATE KEY, as in a .p8 file from Apple) or SEC1 (EC PRIVATE KEY). Line breaks inside it may be missing, and the base64 body alone is read as PKCS#8, so a key pasted into a secret field works. ECDSA signatures are randomized: signing the same data twice gives different, equally valid results.
  • randomBytes(count, { encoding }) (up to 65,536 bytes) and randomUUID().

options.encoding is the output: "hex" (default), "base64" or "base64url" (unpadded). options.inputEncoding says how data is given: "utf8" (default), "base64" or "hex". hmac also takes keyEncoding, so signing chains work, for example AWS Signature V4:

const kDate = ctx.crypto.hmac("sha256", "AWS4" + secret, date);
const kRegion = ctx.crypto.hmac("sha256", kDate, region, { keyEncoding: "hex" });

A JWT for APIs that take ES256 developer tokens (WeatherKit, App Store Connect, APNs):

const part = (value) => ctx.encoding.base64Encode(JSON.stringify(value)).replace(/=+$/, "").replace(/\+/g, "-").replace(/\//g, "_");
const unsigned = `${part({ alg: "ES256", kid: keyId })}.${part({ iss: teamId, iat, exp })}`;
const token = `${unsigned}.${ctx.crypto.sign("es256", ctx.inputs.privateKey, unsigned, { encoding: "base64url" })}`;

ctx.xml.parse(text) returns the root element. Elements have:

  • name: the tag as written, including any prefix ("item", "atom:link").
  • attributes: an object of strings.
  • children: elements and text in document order. Text between elements that is only whitespace is dropped. CDATA sections become text; entities are decoded.
  • elements: the child elements without text.
  • text: all text inside the element, including descendants, trimmed.
  • attr(name): an attribute, or undefined.
  • find(path), findAll(path) and textOf(path): by a path of names relative to the element ("channel/item"). * matches any name, and a leading // searches at any depth ("//entry").

The parser is forgiving because feeds often aren’t valid XML: unknown entities (other than common HTML ones like &nbsp;) stay as written, a stray < is text, a closing tag without a matching opening tag is ignored, and elements still open at the end are closed. Text without any element throws a SyntaxError.

Elements serialize to { name, attributes, children }, so they can be kept in state or the store. The parser is part of the shared prelude, so every host builds exactly the same tree.

ctx.html.parse(text) returns the document (an element named "#document"). Elements have:

  • name: the tag in lowercase ("div", "td").
  • attributes: an object of strings, with lowercase names and decoded entities. attr(name) reads one, whatever its case.
  • children, elements and parent, as in the DOM.
  • text: what a reader sees. Scripts, styles and templates are left out, blocks, table cells, line breaks and form controls are kept apart by a space, and whitespace (non-breaking spaces too) is collapsed and trimmed. <p>In stock</p><p>Ships&nbsp;today</p> gives "In stock Ships today". A script, style, textarea or title gives its content as written, so JSON a page embeds is one call away: JSON.parse(doc.querySelector('script[type="application/ld+json"]').text).
  • querySelector(selector) (the first match or null) and querySelectorAll(selector) (every match, in document order), looking inside the element.

Selectors can use types, *, #id, .class (escape special characters: .md\:flex), attributes ([attr], =, ~=, |=, ^=, $=, *=, with an i flag), the combinators , >, + and ~, lists with ,, and :first-child, :last-child, :only-child, :nth-child(), :nth-last-child(), the -of-type forms, :empty, :root, :not(), :is(), :where() and :has(). One addition from jQuery is not standard CSS: :contains("text") matches elements whose text contains the text, which finds a value by its label: td:contains("Price") + td. Anything else, such as pseudo-elements or :hover, throws a SyntaxError.

The parser follows what a browser does with scripting off, simplified: end tags HTML lets authors leave out (</p>, </li>, </td>, </tr>, </option>) are implied, void elements (br, img, input, meta, …) have no content, /> closes any element (for inline SVG), and end tags without a matching open element are ignored. Scripts don’t run, so content a page builds with JavaScript isn’t in the document; look for the JSON it embeds instead, or the API it calls.

Elements serialize to { name, attributes, children }. The parser is part of the shared prelude, so every host builds exactly the same tree.

ctx.encoding.decode(data, charset = "utf-8", { from = "base64" }) decodes bytes (base64, or hex with from: "hex") in any IANA charset, such as "iso-8859-1", "windows-1252" or "shift_jis". Unknown charsets and invalid bytes throw a TypeError. It is what email headers need (RFC 2047 encoded words); see imap-inbox.js.