Skip to content

Integrations: code that talks to another service

Use this guide to write the code of an integration, integrations/<name>.ts, and the manifest beside it, integrations/<name>.json. Guide site-integrations says what an integration is for, how one is started and how its secrets are saved; topic integrations is the exact list of triggers, verifiers and limits. This page is the language.

integrations/weather.ts the code
integrations/weather.json the manifest

The name is lower-case letters, digits, - and _. The two are written together: a manifest with no code beside it is refused, and so is code with no manifest. Several jobs under one manifest, with tables and pages of their own, go in a folder, a package: guide site-integrations, “6. Several jobs in one package”. A package’s job is written as this page says.

Any of three functions, and nothing else:

Export Is given
sync() Nothing.
on(event) event.record with its id and data, event.file, event.schedule, the name of the schedule that came due, or event.dashboard, the action the owner pressed, with event.pick for a pick.
receive(request) request.method, request.path (/-/hooks/<path>, or /-/integrations/<name>/hooks/<path> for a package’s job, which says which of its paths was called), request.headers (the ones the manifest names), and request.body where the call was JSON or request.text otherwise.

A function that is not exported is the code’s own. The code is written as a model is: functions, and const names with a literal value. Nothing runs when the file is loaded. Every text of an event, a request and a fetch’s answer is treated as a stranger’s: it can be kept in a row and sent in a query or a body, and it is never an address, never a header, and never what notify or fail says.

Call Does
await fetch(url, options) A request over HTTPS to a host the manifest names. options are method, query, headers, body (a text, or a list or an object sent as JSON) and the four below. The answer has ok, status, headers, text and json.
secrets.NAME A secret the manifest names. It goes into a fetch, after the address’s https://host/ start, in a header, in a query value or as the body, and nowhere else. The code never reads it.
tables.<handle>.upsert(rows, by) Rows matched by the field by, added or changed, 500 at most. Answers { added, changed }. For a table in writes.
tables.<handle>.remove(by, keys) The rows whose field by holds one of the keys, removed, 500 at most. For a table in writes.
tables.<handle> Read as a page reads a table (filter, sortBy, slice, count), for a table in reads.
state.get(), state.set(value) One JSON value of 16 KiB at most, kept between runs.
once(key) true the first time a key is seen in seven days.
log(text) A line kept with the run, 500 characters and 100 lines at most.
notify(text) Words the site’s members are told, once a run, in the code’s own words. Numbers and dates may be joined in.
fail(text) Ends the run as failed, in the code’s own words.
settings.<name>, site.name The manifest’s settings, and the site.
crypto.hmac, crypto.digest A signature or a hash of what is sent.
crypto.base64(value) A text, or a list or an object written as JSON, as base64. It takes no secret.
random(n) n letters and digits, from 1 to 256, different from run to run: a nonce, or a key a service asks the caller to make. Plain text, kept or sent anywhere.
addDays, today, now, date, daysBetween, formatDate, number, encodeURIComponent As every file has them.

fetch takes three more options in a job, and a request may be signed:

  • mint: { NAME: "json.access_token" } makes a value of the answer a secret of the run (a place is json.path, header.name or text). The manifest lists it with "mint", the host it comes from.
  • form: { ... } sends an object as a form. A fetch takes a body or a form.
  • crypto.hmac("sha256", secrets.KEY, message, "hex") in a header or a value signs a request. What it answers is a secret.
  • follow: true follows an address the service answered, as await fetch(answer.json.next, { follow: true }).

Returning { continue: true } runs the function again at once, up to 12 times, with state carrying the place.

  • Read anything of a page or a visitor: params, query, page, form, session, visitor and the rest are refused.
  • Name a table, a secret, a setting or a host the manifest does not.
  • List a table in writes that the code never writes.
  • Loop without an end: write for (const item of list) or for (const i of range(n)).
  • Join a stranger’s text into an address, a header, notify or fail.

A setting the owner chooses from what the provider holds, such as the chat a bot posts to, is a pick: "pick" on a dashboard trigger. The app lists what the job answers, and lays the settings it answers for the one chosen.

{
"kind": "dashboard",
"name": "chat",
"label": "Chat",
"pick": { "lays": ["chat_id"], "required": true, "empty": "Send your bot a message in the chat first, or add it to the group, then look again." }
}

lays lists the settings a choice sets, 1 to 4, each one settings names and none another pick lays. required says the integration is not set up until one is chosen, and empty is the sentence shown where the list has nothing in it; {host}, the site’s address, is the one word in braces it may hold. A pick is answered at once and writes nothing. on is handed event.dashboard, the action’s name, and event.pick, what is asked:

event.pick The job returns
{ list: { after } } { choices, after }: at most 50 choices, each { value, label, note }, with group, badge and aside where they help, and after, a text the next page starts from, or null on the last page. The first page is asked with after: null.
{ choose: value } { settings: { name: "text" }, label, note }, each name one of lays, or { refused: "a sentence" }.

Each text is one line: value 200 characters at most, label and note 120, group 80, badge and aside 40. A pick may also make a new one at the provider: its make holds the words of the row that asks for it, and it is then asked { make: { in, time_zone } }, where in is one of the places a list’s page gave beside choices (each { value, label }) or null, and time_zone is the owner’s. It answers as choose does, for what it made. A pick of several things the provider takes together, such as an ad account and a Page, declares parts, 2 to 4 of { "name", "label" }: each part is listed on its own, { list: { after, part } }, and the choice names a value for every part, { choose: { part: value } }.

value came back from the app, so choose never lays it as it came: it reads the choice back from the provider by that value, lays what the provider answers, and refuses a value the provider does not know. A job returns 2 KiB at most, so a long list goes a page at a time. A pick is pressed in the app alone; play one in a scenario with on("telegram_enquiries", { dashboard: "chat", pick: { list: { after: null } } }).

A setting the owner types is a field: "fields" in the manifest, up to 8 of { "setting", "label", "example", "hint", "pattern" }, each for a setting settings names. label is the words beside the box (40 characters at most), example and hint help the owner fill it in, and pattern, written \A...\z, is what a value is held to:

"fields": [{ "setting": "account", "label": "Account ID", "example": "123456", "pattern": "\\A\\d{1,20}\\z" }]

A scenario in tests/<name>.test.ts runs a job with no network, against stand-ins, and run_tests plays it (guide vzk/tests):

scenario("a week of forecasts is kept", () => {
answer("https://api.open-meteo.com/v1/forecast?daily=temperature_2m_max%2Ctemperature_2m_min&forecast_days=7&latitude=49.84&longitude=24.03&timezone=Europe%2FKyiv", {
json: { daily: { time: ["2026-11-10"], temperature_2m_max: [7], temperature_2m_min: [1] } }
})
sync("weather").ok().logged("Kept 1 days")
})

answer(url, { json, body, status, failed }) stands in for the next fetch to an address, written as it is sent: with its query, the names in order (A to Z before a to z), each name and value percent-encoded and a null left out, and with a secret as its name in braces (https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage). A fetch with no stand-in fails, which the code reads with answer.ok. state(value) sets what the job kept, random(text) answers the next random(n) with text (n letters and digits), and sync(job), on(job, event) and receive(job, request) run a function and answer the run, which reads ok(), failed(words), logged(words), notified(words), minted(name) and again().

Each is laid in paused: it starts nothing until the owner switches it on, with its secrets saved.

// A week of forecasts, read every hour and kept a row a day.
export function sync() {
const answer = await fetch("https://api.open-meteo.com/v1/forecast", {
query: {
latitude: settings.latitude,
longitude: settings.longitude,
daily: "temperature_2m_max,temperature_2m_min",
timezone: settings.timezone,
forecast_days: "7"
}
})
if (!answer.ok) { fail("The weather service did not answer.") }
const daily = answer.json.daily
const days = daily.time.map((day, at) => ({
day: day,
high: daily.temperature_2m_max[at],
low: daily.temperature_2m_min[at]
}))
const wrote = tables.forecasts.upsert(days, "day")
log("Kept " + days.length + " days: " + wrote.added + " new")
}
{
"engine": 1,
"name": "Weather",
"state": "paused",
"hosts": ["api.open-meteo.com"],
"writes": ["forecasts"],
"settings": {
"latitude": "49.84",
"longitude": "24.03",
"timezone": "Europe/Kyiv"
},
"triggers": [{ "kind": "schedule", "every": "1h" }]
}

tables/forecasts.json has day (text, required, filterable, sortable), high and low (numbers), and "keep": "7 days".

The page that shows them, pages/weather.vzk, reads the table inside a region, so an open page follows the forecast as the job writes it:

<script server>
export const name = "Weather"
// The newest seven days the job kept, the nearest first. The region is
// drawn again as the job writes, so an open page follows the forecast.
const days = tables.forecasts.sortBy(f => f.day, "desc").slice(0, 7).toReversed()
</script>
<head>
<title>Weather</title>
</head>
<section id="forecast" region class="mx-auto max-w-xl px-6 py-12">
<h1 class="text-2xl font-semibold">Weather</h1>
<p :if={days.length == 0} class="mt-4">No forecast yet.</p>
<ul class="mt-4 divide-y">
<li :for={day in days} class="flex justify-between py-2">
<span>{day.day}</span>
<span>{day.high}° / {day.low}°</span>
</li>
</ul>
</section>

A call from another service: Stripe payments

Section titled “A call from another service: Stripe payments”
// One row for each payment that succeeded. Stripe may deliver an event
// more than once, so an event is kept once, by its id. The amount is kept
// as Stripe says it, in the currency's smallest unit: cents for a euro,
// whole yen for a yen.
export function receive(request) {
const event = request.body
if (event.type != "payment_intent.succeeded") { return }
if (!once(event.id)) { return }
const intent = event.data.object
tables.stripe_payments.upsert([{
payment: intent.id,
amount_minor: intent.amount_received,
currency: intent.currency
}], "payment")
log("Kept a payment")
}
{
"engine": 1,
"name": "Stripe payments",
"state": "paused",
"hosts": [],
"writes": ["stripe_payments"],
"secrets": [{ "name": "STRIPE_WEBHOOK_SECRET", "host": "api.stripe.com" }],
"triggers": [
{
"kind": "inbound",
"path": "stripe",
"secret": "STRIPE_WEBHOOK_SECRET",
"verifier": {
"kind": "hmac",
"header": "Stripe-Signature",
"key": "v1",
"timestamp": { "key": "t", "window": 300 },
"signed": "{timestamp}.{body}"
}
}
]
}

tables/stripe_payments.json is read by the owner alone, with payment (text, required, filterable), amount_minor (number, the amount in the currency’s smallest unit) and currency (text).

The owner reads them as a chart, an artifact pinned to Home that sums the month for each currency (making-artifacts says how one is made). Its settings, artifacts/stripe_month.json:

{
"title": "Payments this month",
"kind": "chart",
"reads": ["stripe_payments"],
"pinned": true
}

And what it draws, artifacts/stripe_month.vzk:

<script server>
// What Stripe was paid this month, summed for each currency, with a bar
// for each day so far. A payment is counted on the day its row was kept
// or last changed, in UTC, so a row changed by hand moves to that day.
// The newest 500 rows are read.
const month = today()
const kept = tables.stripe_payments.sortBy(p => p.updated_at, "desc").slice(0, 500)
const paid = kept.filter(p => date(p.updated_at)?.year == month.year && date(p.updated_at)?.month == month.month)
// Stripe says an amount in the currency's smallest unit: 500 is five
// euros. For the first of these lists that unit is the currency itself,
// so 500 is five hundred yen, and for the second it is a thousandth.
const whole = ["bif", "clp", "djf", "gnf", "jpy", "kmf", "krw", "mga", "pyg", "rwf", "ugx", "vnd", "vuv", "xaf", "xof", "xpf"]
const thousandths = ["bhd", "jod", "kwd", "omr", "tnd"]
function amount(currency, minor) {
if (whole.includes(currency)) {
return minor
}
return thousandths.includes(currency) ? minor / 1000 : minor / 100
}
function on(currency, day) {
let minor = 0
for (const payment of paid) {
if (payment.currency == currency && date(payment.updated_at).day == day) {
minor += payment.amount_minor ?? 0
}
}
return minor
}
function summed(currency) {
const days = range(month.day).map(at => ({ day: at + 1, minor: on(currency, at + 1) }))
let minor = 0
let most = 1
for (const day of days) {
minor += day.minor
if (day.minor > most) {
most = day.minor
}
}
return {
currency: currency.toUpperCase(),
total: amount(currency, minor),
count: paid.filter(payment => payment.currency == currency).length,
days: days.map(day => ({ day: day.day, total: amount(currency, day.minor), share: day.minor * 100 / most }))
}
}
let currencies = []
for (const payment of paid) {
if (payment.currency && !currencies.includes(payment.currency)) {
currencies = [...currencies, payment.currency]
}
}
const sums = currencies.toSorted().map(currency => summed(currency))
</script>
<section id="payments" class="space-y-6 p-6">
<h1 class="text-lg font-semibold">Payments in {formatDate(month, "MMMM yyyy")}</h1>
<p :if={sums.length == 0} class="text-sm">No payment yet this month.</p>
<div :for={sum in sums} class="space-y-2">
<p class="text-2xl font-semibold">{formatMoney(sum.total, sum.currency)}</p>
<p class="text-sm">{sum.count} {sum.count == 1 ? "payment" : "payments"}</p>
<div :for={day in sum.days} class="flex items-center gap-3">
<span class="w-6 text-right text-xs">{day.day}</span>
<div class="h-3 rounded bg-current" style="width: {day.share}%"></div>
<span :if={day.total > 0} class="text-xs">{formatMoney(day.total, sum.currency)}</span>
</div>
</div>
</section>

A new row, and a chat to pick: a line in Telegram

Section titled “A new row, and a chat to pick: a line in Telegram”
// A line in a Telegram chat when an enquiry comes. It says that one came
// and never what it said: the enquiry is read in the Vizitka app.
//
// The chat is picked in the app, by the manifest's `chat` action: a press
// of it lists the chats the bot has heard from, and the one chosen is read
// back from Telegram before its id is laid in `settings.chat_id`.
export function on(event) {
if (event.dashboard == "chat") { return pick(event.pick) }
if (!settings.chat_id) { fail("No chat is picked yet: pick one on the integration's page.") }
const total = tables.enquiries.count()
const answer = await fetch(`https://api.telegram.org/bot${secrets.TELEGRAM_BOT_TOKEN}/sendMessage`, {
method: "POST",
body: {
chat_id: settings.chat_id,
text: "A new enquiry came. " + total + " in all."
}
})
if (!answer.ok) { fail("Telegram refused the message.") }
}
// A job answers 2 KiB at most, so the chats are listed six at a time, each
// name cut to 60 characters, and `after` says where the next six start.
const at_once = 6
function pick(ask) {
if (ask.choose) { return chosen(ask.choose) }
return listed(ask.list.after)
}
// The chats the bot has heard from, the newest first and each once.
// Telegram keeps a day of what the bot was sent. It is asked with no
// `offset`, so nothing is marked as read.
function listed(after) {
const answer = await fetch(`https://api.telegram.org/bot${secrets.TELEGRAM_BOT_TOKEN}/getUpdates`)
if (!answer.ok) { fail("Telegram did not say which chats the bot has heard from.") }
let chats = []
for (const update of (answer.json.result ?? []).toReversed()) {
const chat = update.message?.chat ?? update.edited_message?.chat ?? update.channel_post?.chat ?? update.my_chat_member?.chat
if (chat != null && !chats.some(known => known.id == chat.id)) {
chats = [...chats, chat]
}
}
const from = after ? number(after) ?? 0 : 0
return {
choices: chats.slice(from, from + at_once).map(chat => ({ value: `${chat.id}`, label: named(chat), note: kind(chat) })),
after: chats.length > from + at_once ? `${from + at_once}` : null
}
}
// The chat the owner chose. Its id came back from the app, so it is never
// laid as it came: the chat is read back from Telegram by that id, and
// what is laid is the id Telegram answers. A chat Telegram does not know,
// or one the bot is not in, is refused, and so is anything but a chat's
// number: a name such as @channel finds any public channel, the bot's or
// not.
function chosen(value) {
if (number(value) == null) { return { refused: "That is not one of the chats listed." } }
const answer = await fetch(`https://api.telegram.org/bot${secrets.TELEGRAM_BOT_TOKEN}/getChat`, {
query: { chat_id: value }
})
if (answer.status == 400 || answer.status == 403) {
return { refused: "Telegram does not know that chat, or the bot is not in it." }
}
if (!answer.ok) { fail("Telegram did not answer.") }
const chat = answer.json.result
return { settings: { chat_id: `${chat.id}` }, label: named(chat), note: kind(chat) }
}
// What the owner knows a chat by: its title, or the person's name.
function named(chat) {
let name = chat.title ?? [chat.first_name ?? "", chat.last_name ?? ""].join(" ").trim()
if (name == "" && chat.username) { name = "@" + chat.username }
if (name == "") { name = `Chat ${chat.id}` }
return name.slice(0, 60)
}
function kind(chat) {
if (chat.type == "private") { return "A private chat" }
if (chat.type == "channel") { return "A channel" }
return "A group"
}
{
"engine": 1,
"name": "Telegram: new enquiries",
"state": "paused",
"hosts": ["api.telegram.org"],
"reads": ["enquiries"],
"secrets": [{ "name": "TELEGRAM_BOT_TOKEN", "host": "api.telegram.org" }],
"settings": {
"chat_id": ""
},
"fields": [
{
"setting": "chat_id",
"label": "Chat ID",
"example": "-1001234567890",
"hint": "Pick the chat above, or type its ID where it is not listed. A group's ID starts with -100.",
"pattern": "\\A-?[0-9]{1,20}\\z"
}
],
"triggers": [
{ "kind": "rows", "table": "enquiries" },
{
"kind": "dashboard",
"name": "chat",
"label": "Chat",
"pick": {
"lays": ["chat_id"],
"required": true,
"empty": "Send your bot a message in the chat first, or add it to the group, then look again."
}
}
]
}

The message says an enquiry came and never what it said. chat_id is laid empty, and the owner picks the chat in the app with the chat action: its list is the chats the bot has heard from in the last day, and the chat chosen is read back from Telegram with getChat before its id is laid. A chat the list does not show can be typed as its ID, the chat_id field. Until a chat is set, a new enquiry fails with words that say so.

// A mirror of the site at a git host, Codeberg as it is laid. The host
// syncs, and this job never sees a pack: it says when a sync is owed, and
// it is told what came of one.
//
// The token goes as the password under the user `git`: Gitea, which
// Codeberg runs, takes a token as the password whatever the user is.
// A push at the remote, signed with the webhook's secret. That one came is
// all a sync needs, so nothing of it is kept or logged.
export function receive(request) {
return { sync: true }
}
// The owner's "Sync now", and what a sync did. A branch the site refused,
// or one the remote would not take, is counted, and nothing of it is kept.
export function on(event) {
if (event.dashboard == "sync") { return { sync: true } }
if (event.repository) {
return { told: event.repository.refs.filter(ref => ref.did == "refused" || ref.did == "blocked").length }
}
}
{
"engine": 1,
"name": "Git mirror",
"state": "paused",
"hosts": ["codeberg.org"],
"secrets": [
{ "name": "GIT_TOKEN", "host": "codeberg.org" },
{ "name": "GIT_WEBHOOK_SECRET", "host": "codeberg.org" }
],
"settings": {
"owner": "",
"repository": ""
},
"fields": [
{
"setting": "owner",
"label": "Owner",
"example": "my-team",
"hint": "The user or organization the repository belongs to.",
"pattern": "\\A[A-Za-z0-9._-]{1,100}\\z"
},
{
"setting": "repository",
"label": "Repository",
"example": "my-site",
"hint": "The repository's name, without .git.",
"pattern": "\\A[A-Za-z0-9._-]{1,100}\\z"
}
],
"repository": {
"remote": "https://codeberg.org/{owner}/{repository}.git",
"user": "git",
"password": "GIT_TOKEN"
},
"triggers": [
{
"kind": "inbound",
"path": "git-mirror",
"secret": "GIT_WEBHOOK_SECRET",
"verifier": {
"kind": "hmac",
"algorithm": "sha256",
"encoding": "hex",
"header": "X-Gitea-Signature"
},
"delivery": "X-Gitea-Delivery"
},
{ "kind": "repository" },
{ "kind": "dashboard", "name": "sync", "label": "Sync now" }
]
}

A mirror keeps the site’s repository and one at a git host in step: the host syncs, and the job is told what came of a sync through its repository trigger and never sees a pack. The job only says when a sync is owed, with { sync: true } from a delivery or a press, and tells whoever it likes what a sync did.

repository names the remote, on a host hosts lists and filled from settings, the user, and the secret sent as the password, bound to that host. For a host other than Codeberg, change it in hosts, secrets and remote. A mirror waits for a manager to switch it on in the app, and a site holds one mirror, so only one of its integrations may declare one.