The SDK
Extensions reach Aperture through one SDK with two transports: @aperture/sdk in a backend and window.aperture in a UI panel. This page lists everything both offer, with signatures and examples. The backend module is deploy/aperture-sdk/mod.ts; the panel runtime is injected by internal/api/ext_static.go.
Two transports
Section titled “Two transports”| Backend | UI panel | |
|---|---|---|
| How you get it | import { aperture } from "@aperture/sdk"; |
window.aperture, injected into every HTML panel |
| How a call travels | HTTP to the Aperture API with the extension’s own token | A message to the Aperture page, which relays it through the broker |
| Whose rights | The extension’s scopes and camera grant | The extension’s scopes and grant, intersected with the viewer’s |
| Errors | Throws ApertureError with status and body |
Rejects with an Error whose message is the server’s |
Common calls look the same in both:
const cams = await aperture.cameras.list();const cam = await aperture.request("GET", "/cameras/front_door");Not everything exists in both:
| Member | Backend | Panel |
|---|---|---|
request(method, path, body?) |
yes | yes |
cameras.list(), cameras.get(id) |
yes | yes |
events.list(query?) |
yes, query is an object | yes, query is a string |
events.get(id) |
yes | no; use request |
coverage(cameraId, range?) |
yes | no; use request |
automations.list() |
yes | no; use request |
alarm.arm(armed) |
yes | no; use request |
storage.get/set/delete/keys |
yes, secrets readable | yes, administrators only, secrets read as null |
settings.get(key), settings.all() |
no; use storage.get |
yes, non-secret values; a viewer gets camera values only for cameras they may see |
on(type, handler, opts?) |
yes | no |
http.fetch(input, init?) |
yes | no |
net.fetch(url, init?) |
no | yes |
cameraId |
no | yes |
resize(height, width?) |
no | yes |
Backends: @aperture/sdk
Section titled “Backends: @aperture/sdk”Importing
Section titled “Importing”Import the bare specifier. The module has a named export and a default export:
import { aperture, ApertureError, type Camera, type FeedMessage } from "@aperture/sdk";// or: import aperture from "@aperture/sdk";@aperture/sdk is not downloaded. Each time it starts a backend, Aperture writes an import map, .import-map.json in the extension’s folder, that points the specifier at the SDK file installed with Aperture (/usr/lib/aperture/sdk/mod.ts, set by APERTURE_EXT_SDK), and runs Deno with --import-map and read access to that file. The SDK always matches the server it ships with.
No remote code
Section titled “No remote code”A backend runs with --deny-import, so Deno refuses to load any module from a URL. Import only @aperture/sdk and relative paths to files in your own bundle (./lib/onvif.ts). Vendor any third-party code into the bundle.
Aperture also scans the bundle at install and rejects it with “remote imports are not allowed: …” when a .ts, .js, .mjs, .tsx or .jsx file has a from "…" or import("…") whose target starts with http://, https:// or file:, or is an absolute path. That turns a runtime permission error into a clear install message. The scan cannot see a specifier built at runtime; --deny-import still blocks it.
Environment
Section titled “Environment”A backend’s environment is replaced entirely. It holds:
| Variable | Value | Readable by your code |
|---|---|---|
APERTURE_TOKEN |
This extension’s API token (apt_…), new on every start |
Yes |
APERTURE_API |
The API base, from APERTURE_URL in Aperture’s environment, for example http://127.0.0.1:8971 |
Yes |
APERTURE_EXT_ID |
This extension’s id, which addresses its private storage | Yes |
HOME |
The extension’s folder | No |
DENO_DIR |
.deno inside the extension’s folder |
No |
NO_COLOR |
1 |
No |
Deno’s --allow-env names exactly the first three, so Deno.env.get on anything else throws. The SDK reads them for you; you rarely need them. If APERTURE_API or APERTURE_TOKEN is missing, every SDK call throws ApertureError with status 0 and the message “SDK not initialised: APERTURE_API/APERTURE_TOKEN missing”.
Lifecycle
Section titled “Lifecycle”- The backend starts when the extension is installed, enabled, or when Aperture starts with it enabled. It starts even before anyone has filled in its settings, so handle missing values.
- It restarts when its settings are saved, when its cameras are changed, when a file is saved in Edit files, and when it is updated or reverted. Each start gets a new token and revokes the previous one, so a running backend never holds a revoked token.
- Standard output and standard error appear under Logs on its row.
- To stop it, Aperture sends SIGTERM to its process group and SIGKILL 5 seconds later.
- If it exits on its own, Aperture restarts it with a growing delay and gives up after five quick crashes; see When a backend keeps crashing.
- An unhandled promise rejection ends a Deno process. Catch errors inside
asynchandlers.
The working directory is the extension’s own folder, which it may read and write; see Extension security.
aperture.request
Section titled “aperture.request”request<T = unknown>(method: string, path: string, body?: unknown): Promise<T>Calls any API route the extension’s scopes allow. path is relative to /api/v1 ("/cameras" becomes /api/v1/cameras); a path that already starts with /api/ is used as it is, and a missing leading slash is added. A body is sent as JSON. The response is parsed as JSON when it can be, returned as text when it cannot, and undefined when empty. Any status outside 200 to 299 throws ApertureError.
const site = await aperture.request<{ timezone: string }>("GET", "/system/site"); // needs data.site: "read"The SDK returns only the response body, so response headers such as X-Next-Cursor are not available. Page through long lists with time ranges instead. See the API and the API reference for routes.
aperture.cameras
Section titled “aperture.cameras”cameras.list(): Promise<Camera[]> // GET /cameras, needs cameras:readcameras.get(id: string): Promise<Camera> // GET /cameras/{id}, needs cameras:readlist returns only the cameras in the extension’s grant. get for a camera outside it throws with status 403.
aperture.events
Section titled “aperture.events”events.list(query?: Record<string, string | number>): Promise<ApertureEvent[]> // GET /eventsevents.get(id: string): Promise<ApertureEvent> // GET /events/{id}Both need events:read. events.list takes query parameters as an object:
| Parameter | Meaning |
|---|---|
limit |
Page size; default 200, at most 1000 |
from, to |
Time range in Unix milliseconds; default the last 24 hours |
cursor |
Continue a previous page (the cursor comes from a response header the SDK does not expose) |
const lastHour = await aperture.events.list({ from: Date.now() - 3_600_000, limit: 50 });Events come newest first and carry, among others, id, seq, cameraId, type, startTs, endTsMs (null while the event is still going), ongoing, score, reviewed and saved.
aperture.coverage
Section titled “aperture.coverage”coverage(cameraId: string, range?: { from?: number | string; to?: number | string }): Promise<CoverageRange[]>Recorded time for one camera, as an array of CoverageRange ({ start, end }, Unix milliseconds), with gaps under 2 seconds merged. Needs coverage:read. from and to are Unix milliseconds; from defaults to 24 hours ago and to to now. A string is still accepted, but it must be a number: a value the server cannot read as one, such as an ISO date, is ignored and the default used.
const now = Date.now();const ranges = await aperture.coverage("front_door", { from: now - 6 * 3_600_000, to: now });aperture.automations
Section titled “aperture.automations”automations.list(): Promise<unknown> // GET /automationsNeeds automation:read and an administrator as the token’s owner, which an installed extension normally has.
aperture.alarm
Section titled “aperture.alarm”alarm.arm(armed: boolean): Promise<{ armed: boolean }> // PUT /alarmArms (true) or disarms (false) the alarm. Needs alarm: "arm". The change is written to the audit log and announced on the change feed as alarm.state.
aperture.storage
Section titled “aperture.storage”storage.get(key: string): Promise<string | null>storage.set(key: string, value: string): Promise<void>storage.delete(key: string): Promise<void>storage.keys(): Promise<string[]>The extension’s private key-value store. Needs storage: true or a settings block. Values are strings; encode structured data with JSON.stringify. get resolves to null for a missing key. A backend reads every key, secrets included, and this is how it reads its settings:
const url = await aperture.storage.get("webhook_url");const token = await aperture.storage.get("auth_token"); // a secret settingconst rows = JSON.parse((await aperture.storage.get("lights")) ?? "[]"); // a group settingQuotas and rate limits are on Settings and storage.
aperture.on
Section titled “aperture.on”on(type: string, handler: (msg: FeedMessage) => void, opts?: { cameras?: string[] }): () => voidSubscribes to the change feed (GET /api/v1/feed, Server-Sent Events) for one message type and returns a function that unsubscribes. Needs events:read.
typeis matched exactly; there are no wildcards. Callononce per type.opts.camerasnarrows the feed to those camera ids. The server already leaves out cameras outside the grant.- On a dropped connection it reconnects after 1 second, doubling to at most 30 seconds, and back to 1 second once connected.
- On every connect the server first sends the current state (the latest
camera.statefor each camera, for example), then live messages. - The SDK does not resume from the last message it saw, so durable messages sent while it was disconnected are not replayed. If you must not miss an event, read
events.listwith a time range after reconnecting. - A handler that throws is ignored and the subscription continues. A rejected promise from an
asynchandler is not caught; catch it yourself.
const off = aperture.on("camera.state", (msg) => { const { state } = msg.data as { state: "online" | "offline" }; console.log(`${msg.camera} is ${state}`);}, { cameras: ["front_door", "garage"] });// later: off();| Type | camera |
data |
Notes |
|---|---|---|---|
event.created |
yes | { eventId, eventType, score } |
Durable |
event.closed |
yes | { eventId, endTsMs } |
Durable |
detection.created |
yes | { eventId } |
Objects were attached to an event |
camera.state |
yes | { state: "online" | "offline" } |
|
alarm.state |
no | { armed } |
|
config.updated |
no | { domain }, such as "site" or "detection" |
|
storage.updated |
no | none | |
automation.updated |
no | none | |
export.progress |
no | { exportId, progress } |
The feed is best-effort: a subscriber that falls behind loses messages rather than slowing Aperture down. The API describes the feed in full.
aperture.http.fetch
Section titled “aperture.http.fetch”http.fetch(input: string | URL, init?: RequestInit): Promise<Response>Deno’s own fetch, for hosts in the extension’s network permission. Any other host throws Deno’s NotCapable error. This is the only way a backend reaches the outside world, and it can send your data there. Unlike a panel’s net.fetch, there is no {{secret:…}} substitution: a backend reads its secrets with storage.get and uses them directly.
const token = await aperture.storage.get("auth_token");await aperture.http.fetch("https://hooks.example.com/notify", { method: "POST", headers: { "Content-Type": "application/json", ...(token ? { Authorization: `Bearer ${token}` } : {}) }, body: JSON.stringify({ text: "Garage door camera went offline" }),});interface Camera { id: string; name: string; enabled?: boolean; [k: string]: unknown }interface ApertureEvent { id: string; type?: string; cameraId?: string; startTs?: number; endTs?: number; endTsMs?: number | null; ongoing?: boolean; seq?: number; score?: number; reviewed?: boolean; saved?: boolean; topLabel?: string; objectSummary?: string; /** @deprecated */ camera?: string; /** @deprecated */ startedAt?: string; [k: string]: unknown;}interface CoverageRange { start: number; end: number }interface FeedMessage { id: number; type: string; ts: number; camera?: string; data?: unknown }These are deliberately partial, with an index signature so every field the API returns is still there. ApertureEvent names the fields the API sends: times are Unix milliseconds, endTsMs is null and ongoing is true while the event is still going (endTs then reads the current time), and topLabel and objectSummary are present when object recognition named something. camera and startedAt are never sent; they stay in the type, marked deprecated, so older code still compiles. Read cameraId and startTs instead. FeedMessage.ts is Unix milliseconds.
ApertureError
Section titled “ApertureError”class ApertureError extends Error { readonly status: number; // HTTP status; 0 when the SDK is not initialised readonly body: unknown; // the parsed error response}The message is the API’s error text, or HTTP <status> when there is none.
try { await aperture.cameras.get("garage");} catch (e) { if (e instanceof ApertureError && e.status === 403) { console.log("not granted:", e.message); } else { throw e; }}| Status | Typical cause |
|---|---|
| 403 | Missing scope (“missing required scope: …”), camera outside the grant, administrator-only route, or a session-only route (“not available to API tokens”) |
| 404 | Unknown id, or a storage key that does not exist (storage.get turns this into null) |
| 413 | JSON body over 1 MiB |
| 429 | Rate limit; see below |
| 507 | Storage quota exceeded |
Limits
Section titled “Limits”| Limit | Value |
|---|---|
| API requests | 20 per second with bursts of 40, shared by every token of the same owner; the reply is 429 with Retry-After: 1 |
| JSON request body | 1 MiB |
| Storage | See Settings and storage |
| JavaScript heap | 256 MB (--max-old-space-size=256) |
| Open files | 256 |
| Processes and threads | 64, counted for the extension’s own user |
UI panels: window.aperture
Section titled “UI panels: window.aperture”The runtime is inserted at the end of <head>, so window.aperture exists for every script in <body>. A script placed in <head> runs before it; put your scripts in the body. Each method sends a message to the Aperture page; see the host bridge.
| Member | Signature | Notes |
|---|---|---|
cameraId |
string | null |
The camera this panel is shown for, in camera slots; otherwise null |
request |
(method, path, body?) => Promise<T> |
Any API route, through the broker. path is relative to /api/v1 and must start with / |
cameras.list |
() => Promise<T> |
GET /cameras: cameras both the viewer and the extension may see |
cameras.get |
(id) => Promise<T> |
GET /cameras/{id} |
events.list |
(query?: string) => Promise<T> |
GET /events?<query>; pass a query string without the ?, such as "limit=20" |
storage.get |
(key) => Promise<string | null> |
Administrators only; secrets read as null |
storage.set |
(key, value) => Promise<void> |
Administrators only; the value is stored as a string |
storage.delete |
(key) => Promise<void> |
Administrators only |
storage.keys |
() => Promise<string[]> |
Administrators only |
settings.get |
(key) => Promise<string | object[] | null> |
A non-secret setting: a string for a scalar, an array of row objects for a group, null when unset or secret |
settings.all |
() => Promise<object> |
All non-secret settings; secrets are absent |
net.fetch |
(url, { method?, headers?, body? }) => Promise<{ status, ok, body?, error?, detail? }> |
Server-side request to a declared host; see below |
resize |
(height: number, width?: number) => void |
Ask for a frame size; see Sizing |
A rejected call carries the server’s message, for example “missing required scope: events:read”. The panel does not get the HTTP status.
net.fetch
Section titled “net.fetch”net.fetch(url: string, init?: { method?: string; headers?: Record<string, string>; body?: string }) : Promise<{ status: number; ok: boolean; body?: string; error?: string; detail?: string }>Aperture’s server makes the request to a host in the extension’s network permission. {{secret:key}} in a header value or the body is replaced on the server with the extension’s own secret setting, so the secret never reaches the browser. body must be a string; the response body is text, at most 256 KiB.
- Any answer from the host resolves, with
status,ok(true for 200 to 299) andbody. Redirects are returned, not followed. - A connection failure resolves with
status: 0,ok: false,error(a sentence naming the host and the problem) anddetail(the raw error). - Aperture’s own refusals reject: host not allowed, an address setting not configured, an undeclared or unset secret, or the outbound rate limit.
The checks are listed under Permissions › Panels.
Types for authoring
Section titled “Types for authoring”Panels are served as written, with no build step. If you write panel code in TypeScript and compile it into your HTML, the interface in web/src/ext-sdk/index.ts types window.aperture. It declares resize(height) only; the runtime also accepts the optional width.