# Gears

> How Gears (add-ons) are built - one module with a manifest that plugs into payments, the page head, routes, events and widget slots.

Gears are add-ons a site owner installs from the **Gear Shop** in the admin panel. A Gear plugs into fixed, safe places. It never replaces Vorjo's checkout, prices, stock or orders.

> **Building your own Gear?** This page describes the Gears built into Vorjo. Outside developers build hosted Gears that run on their own servers: see [Build a Gear (hosted apps)](/developers/gears-hosted).

## A Gear, start to finish

A Gear is one JavaScript module that calls `register()`. This is the whole idea of the Bank transfer Gear:

```js
import { register } from "./index.mjs";

register({
  id: "bank-transfer",              // unique and permanent: installs are stored under it
  name: "Bank transfer",
  category: "payments",             // payments, marketing, google, shipping, customers, content, email, chat, privacy, productivity
  icon: "M3 10l9-6 9 6M5 10v8M9 10v8M15 10v8M19 10v8M3 20h18", // one SVG path on a 24×24 grid
  tagline: "Customers pay into your bank account.",
  description: "Shows your bank details at checkout, on the order page and in the confirmation email.",
  access: [{ area: "Checkout", level: "Add a payment option", why: "Adds Bank transfer at checkout and shows your bank details." }],
  settings: [
    { key: "label", label: "Name at checkout", type: "text", default: "Bank transfer" },
    { key: "instructions", label: "Your bank details", type: "textarea", required: true },
  ],
  payment: { kind: "manual", label: "Bank transfer", note: (s) => s.instructions },
});
```

Add the file to `lib/gears/` and import it from its group file (`lib/gears/payments.mjs`, or a new group imported by `lib/commerce.mjs`). It appears in every Gear Shop straight away.

## Where a Gear can plug in

| Place | What it's for | Example |
| --- | --- | --- |
| `payment` | A way to pay at checkout | PayPal, bank transfer |
| `siteHead` / `siteBody` | Code in the `<head>` or at the start of `<body>` of the live site | Meta Pixel, Tag Manager |
| `routes` | Addresses at `/_vorjo/gears/<id>/<route>` on every site | A product feed, a payment webhook |
| `on` | Reacting to shop events | Send a purchase to an ads platform |
| `slot(ctx, name)` | A widget in `home`, `product`, `footer`, `checkout`, or an exact product place: `product.price.after`, `product.stock.after`, `product.cart.before`, `product.cart.after` | Trustpilot, any embed |
| `settings` | The form the owner fills in | API keys, account IDs |
| `check(settings)` | Refuse bad settings on save | "Stripe didn't accept that key" |
| `buttons` + `actions` | Buttons on the Gear's page | "Test connection" |
| `status(settings, activity)` | A one-line status | "Webhooks connected", "Last sync failed: …" |
| `gate(settings, otherGear)` | Hold other Gears' page code until the visitor consents | The Cookie consent banner |

## The manifest

| Field | Required | Notes |
| --- | --- | --- |
| `id` | yes | Never change it after release |
| `name`, `tagline`, `description` | yes | Plain words for owners who aren't technical |
| `category`, `icon` | yes | One stroked SVG path, 24×24. No emoji or images. |
| `settings` | no | Fields: `text`, `textarea`, `number`, `select`, `toggle`, `secret` (stored encrypted, never shown again). Also `heading`, `showIf` and `hidden`. |
| `access` | yes | What it can access, shown before install: see [Access](#access) |
| `price` | no | `{ type: "free" }` or `{ type: "paid", label: "$5 / month" }` |
| `validate(settings)` | no | Return an error message to refuse bad settings, or nothing |
| `onInstall(ctx)` | no | Runs once after install |
| `comingSoon`, `builtIn` | no | Listed but not installable, or set up elsewhere |
| `toggle` | no | Vorjo's own features only: a switch on one of Vorjo's settings (Install turns it on, Uninstall off), e.g. Vorjo AI Chat |
| `exclusive` | no | A group name (e.g. `"captcha"`): switching this Gear on switches the others in the group off, and the owner is told |

Settings fields are `{ key, label, type, required?, default?, placeholder?, help?, options? }`. A `secret` is stored encrypted and never shown again; leaving it empty on save keeps the saved one. `heading` adds a section title, `showIf: { otherKey: "value" }` shows a field only when another setting has that value, and `hidden: true` keeps a value the Gear manages itself (such as a webhook secret) out of the form.

A `hidden` field with `generate: () => "…"` gets its value once, when the Gear is installed (the Webhooks Gear makes its
signing secret this way; with `type: "secret"` it's stored encrypted). A `copy` field shows a read-only value with a Copy
button: `copy({ origin, project, settings })` returns it.

Every hook gets a `ctx` with `settings` (secrets decrypted), `project` (`{ id, name, slug }`), `log()`, `warn()` and
`note({ ok, message })`. `note` adds a line to the Gear's **Recent activity** on its page (the last 10 are kept, the last 5
shown), so the owner sees each sync or delivery and the provider's own words when one fails. Routes also get `test` (true on
the private preview), `origin` and `url`. `siteHead` and `siteBody` also get `page` (`"site"` or `"checkout"`) and
`enabledIds` (the other Gears switched on, e.g. to keep floating buttons from overlapping).

## Access

Before an owner installs a Gear, they see what it can access, like an app store's install screen: one row per area of their
site, with a level and one short sentence on what the Gear does with it.

```js
access: [
  { area: "Orders", level: "Read", why: "Reads each order's number and total to create its payment." },
  { area: "Payments", level: "Read and write", why: "Creates PayPal payments, confirms each one with PayPal, and receives payment updates (webhooks)." },
  { area: "Refunds", level: "Write", why: "Refunds the payment through PayPal when you refund an order." },
],
```

| Area | Levels |
| --- | --- |
| Orders, Products, Inventory, Customers, Discounts, Payments, Refunds, Shipping, Site content, Analytics | `Read`, `Write`, `Read and write` |
| Live pages (code or widgets on the site) | `Add code`, `Add tracking code`, `Add a widget` |
| Checkout | `Add a payment option` |

The rules:

- **List only what the code really uses.** Reads the order's total to create a payment? `Orders: Read`. Never sends the buyer's details? No `Customers` row.
- **Say when a row depends on a setting**, in the `why`: "…only if you turn on Enhanced conversions". A tracking Gear that only adds its tag has one row, `Live pages: Add tracking code`.
- **Webhooks aren't an area.** Mention them in the `why` of the row they belong to (usually Payments).
- **One row per area**, in the order that matters most to the owner. `why` is one plain sentence ending with a full stop.

`register()` refuses a Gear without `access`, or with an area or level that isn't in the table (`ACCESS` in
`lib/gears/index.mjs`). `permissions` (plain sentences for older screens) is made from the `why` of each row. Hosted Gears
get their rows from their scopes: see [Permissions (scopes)](/developers/gears-hosted#permissions-scopes).

## Payment Gears

```js
payment: {
  kind: "redirect",                 // or "manual" (pay later)
  label: "PayPal",
  currencies: ["USD", "EUR"],       // only offered in these store currencies
  async start(ctx, order, { returnUrl, cancelUrl }) {
    return { redirect: "https://provider.example/pay/…", ref: "provider-payment-id" };
  },
  async verify(ctx, order) {        // ask the provider, never the browser
    return { paid: true, ref: "capture-id", text: "Paid with PayPal" };
  },
}
```

**Rules for payment Gears:** check the amount and currency in `verify`, never trust the return address alone, support the provider's test (sandbox) mode as a setting, and test end to end with a real test merchant account before shops can use it.

Vorjo creates the order with its own prices, calls `start`, and marks the order paid only when `verify` says so, after checking the amount and currency. Manual methods reserve stock at once and wait for the owner to press **Mark as paid**. Payment Gears get "only for orders between" limits with `...limitFields()` and can refund with `payment.refund(ctx, order, amount)`.

`verify` can also return `url`: a link to the payment in the provider's dashboard, shown on bookings and invoice payments.
`order.number` is the shop order's number, `bk-<id>` for a booking or `inv-<id>` for an invoice: send it to the provider as
your reference, and route webhooks back with it. A payment Gear with `currencies` that doesn't take the site's currency is
hidden at checkout, and its page and **Settings › Payments** row say why.

The Paddle Gear is a worked example of a provider whose checkout runs in the browser (Paddle.js): `start` creates a Paddle
transaction for the exact amount (`tax_mode: "internal"`, since Paddle is the merchant of record and takes tax out of the
price) and redirects to the Gear's own `pay` route on the site, which opens Paddle's overlay and sends the shopper to
`returnUrl` when it completes. Only addresses on the same site are accepted as the way back.

## Site scripts

```js
siteHead: (ctx) => `<script async src="https://example.com/tag.js?id=${escape(ctx.settings.pixelId)}"></script>`,
```

Added to the **live** site only, never the preview. Escape everything that comes from settings, and keep it small and asynchronous.
Load a third-party widget after the page (on the first scroll or tap, or a few seconds after `load`), as the live chat Gears do.

### Cookie consent

When the Cookie consent banner is on, its `gate(settings, gear)` names a category for each other Gear: `analytics` (Google
Analytics, Clarity), `marketing` (Tag Manager, Google Ads, Meta, TikTok, Pinterest, LinkedIn) or nothing. That Gear's code is
then rewritten before it's sent: each `<script>` becomes `type="text/plain" data-vorjo-consent="<category>"`, iframes and
images keep their address in `data-vorjo-src`, and `<noscript>` parts are dropped. The banner's script runs them once the
visitor accepts that category (`window.VorjoConsent.get()`, `.open()`, `.set({ analytics, marketing })`, and a
`vorjo:consent` event). A new tracking Gear sets `consent: "analytics"` or `consent: "marketing"` in its manifest to be held
back the same way.

### Captchas and the spam shield

Every live page and Vorjo's checkout carry `window.__vorjoStamp`, a signed note of when the page was served. The site
toolkit, the checkout and the chat send it back as `_vt`, and plain forms get it as a hidden field when they're sent. With
the hidden `_hp` field and the content checks it feeds Vorjo's spam shield (`lib/spam.mjs`). A captcha Gear (Turnstile,
reCAPTCHA, hCaptcha: `exclusive: "captcha"`) defines `window.VorjoCaptcha = { token(), fresh(), reset() }`; the token is sent
as `_captcha` and verified on the server. On Vorjo's checkout pages a captcha goes only into forms marked
`data-vorjo-captcha="on"`; `data-vorjo-captcha="off"` keeps it out of any form.

## Ask Vorjo

A Gear can add its own actions and data questions to Ask Vorjo. They're offered only on sites where the Gear is installed
and set up, and only to people with the permission they declare.

```js
ask: {
  actions: [{
    id: "label_buy", label: "Buy a shipping label", about: "buy a label for one order",
    effect: "spend",                                  // "change" | "spend" | "send"
    perm: [["shipping-labels", "0", "buy"], "POST"],  // the Admin Panel route whose permission it needs
    params: { order: { type: "text", max: 40, required: true, about: "the order number or customer name" } },
    examples: ["Buy a label for order #1042"],
    confirm: async (ctx, p) => ({ card: { title: "Buy a shipping label", confirm: "Buy a USPS label for order #1042: $7.90?", cta: "Buy label", data: { … } } }),
    run: async (ctx, card) => ({ message: "Label bought.", links: [{ label: "Print label", href: url }] }),
  }],
  tools: [{ id: "rates", label: "Shipping prices", about: "…", perms: ["orders"], params: { … }, examples: ["…"],
    run: async (ctx, p) => ({ title, sentence, view: "table", columns, rows }) }],
}
```

- **Actions** always show the owner a card with `confirm`, one sentence with the exact effect. `confirm` writes nothing;
  `run` only runs after the button is pressed, with the stored card (never the AI's words). Optional `undo(ctx, card, result)`.
- **Tools** are read-only questions; they run straight away.
- `ctx` has `project`, `site`, `actor`, `settings` (secrets opened), `call(method, parts, body)` for Admin Panel routes with the
  person's permissions, and `kit` (find an order or a person on this site only).
- Throw `new Error("plain sentence")` for something the owner can fix; other errors show a generic message.
- Every run is limited per site and noted in the Gear's **Recent activity**. `register()` refuses a declaration without
  `confirm`, `effect` or `perm`. See `lib/gears/ask-decl.mjs` and `lib/gear-ask.mjs`.

## Routes (feeds and webhooks)

```js
routes: {
  "feed.xml": async (ctx, req, res) => {
    res.writeHead(200, { "content-type": "application/xml" });
    res.end(await buildFeed(ctx));
  },
},
```

A route is served at `https://<site>/_vorjo/gears/<id>/<route>`, only while the Gear is installed and switched on.

Events are covered in [Events and webhooks](/developers/webhooks-and-events).
