# ArkAPI: backend for this HarmonyOS app

This project uses **ArkAPI**. The backend is TypeScript that runs on Bun, written in `*.api.ts` files next to the
ArkTS screens. Every exported function becomes an endpoint. ArkAPI generates a typed ArkTS client (`*.api.ets`) for
each file, and `bunx arkapi deploy` ships the backend to the ArkAPI host.

Human docs: https://arkapi.emincanozcan.com/docs. Agents: https://arkapi.emincanozcan.com/llms.txt, or any docs
page with `.md` appended. `/docs/guide.md` is this file.

## Where things are

| Path | What it is |
|---|---|
| `entry/src/main/ets/**/x.api.ts` | Backend code. Runs on Bun, never on the device. You write this. |
| `entry/src/main/ets/**/x.api.ets` | Generated client. **Never edit**; regenerate instead. Commit it. |
| `arkapi.config.ts` | Project config. `app` is filled in by the first deploy. |
| `libs/arkapi.har` | Client library (`AsyncValue`, `LiveValue`, `ApiError`, `FileRef`, `Listening`). Added by `arkapi init`. |
| `package.json` | Bun package with the `arkapi` CLI as a dev dependency. |
| `.idea/` | DevEco project view from `arkapi init`: generated stubs are hidden. Commit it. |

## Commands

Run them from the project root.

```sh
bunx arkapi login         # once per machine; create the account at the dashboard or with `bunx arkapi signup`
bunx arkapi deploy        # bundle *.api.ts, upload, point stubs at the cloud. The first run creates the app.
bunx arkapi watch         # local server on :3000; stubs point at this machine while it runs
bunx arkapi generate      # regenerate stubs only (cloud URL if deployed, else local)
bunx arkapi logs [-f]     # output of the deployed backend (console.log goes here)
bunx arkapi env set KEY=value   # secrets and config for the backend; read with process.env.KEY
bunx arkapi open          # dashboard: traffic, errors, data, deploys and rollback, logs, env
```

Build the app **after** `deploy` or `generate`: the backend URL is compiled into the stubs. From the command line:

```sh
ohpm install
hvigorw assembleHap --mode module -p product=default -p buildMode=debug --no-daemon
```

An unsigned HAP is enough to check that the code compiles. Running it needs signing and a device or emulator in
DevEco Studio. `watch` points stubs at `10.0.2.2`, the host machine as seen from the emulator. For a real phone on
the same network, set `deviceHost: "<your LAN IP>"` in `arkapi.config.ts`, or use `deploy`.

## Writing the backend (`x.api.ts`)

```ts
import { Database } from "bun:sqlite"
import { ApiError, caller } from "arkapi/server"

interface Todo {
  id: number
  title: string
  done: boolean
}

const db = new Database("app.db")
db.run("create table if not exists todos (id integer primary key, device_id text, title text, done integer)")

export function listTodos(): Todo[] {
  return db.query<{ id: number; title: string; done: number }, [string]>(
    "select id, title, done from todos where device_id = ? order by id",
  ).all(caller().deviceId).map((row) => ({ ...row, done: row.done === 1 }))
}

export function addTodo(title: string): number {
  if (title.trim() === "") throw new ApiError("BAD_REQUEST", "title is empty")
  return Number(db.run("insert into todos (device_id, title, done) values (?, ?, 0)", [caller().deviceId, title]).lastInsertRowid)
}
```

Rules:

- **Exported functions are endpoints.** Their id is `<path>.<name>` (`pages/todo.api.ts` → `pages.todo.listTodos`;
  `pages/profile/profile.api.ts` → `pages.profile.profile.getName`).
  Non-exported functions stay private. Reserved: `uploadFile` (see Files), `routes` (HTTP routes), and `onX`
  when the file exports an event `x` (its generated listener).
- **Types that cross the wire**: `string`, `number`, `boolean`, arrays, `interface`s, unions with `null`,
  `Record<string, T>`, and `void` as a return type. Not supported: `any`, `unknown`, `Date` (send epoch
  milliseconds), `Map`, classes, functions, rest parameters. Optional and default parameters must be trailing.
  Define interfaces in the same file or import them from another user file; the stub declares them for ArkTS.
- Functions may be `async`. Arguments are positional. Return plain JSON data; `void` arrives as `null`.
- **Queries and mutations**: a name that starts with `get`, `list`, `find`, `search`, `count`, `has`, `is` or
  `load`, followed by an uppercase letter or the end, is a query (`getMessages`, `isOnline`). Everything else is a
  mutation (`sendMessage`, `getaway`). Keep queries free of side effects. Only queries can back a `LiveValue`.
- **Validation**: the server checks arguments against the signature before running the function. Wrong types,
  missing or extra arguments and extra object fields fail with 400 `BAD_REQUEST`, for example
  `args[0].title: expected string, got number`. Return values are not checked.
- **Errors**: `throw new ApiError(code, message)`. Codes: `BAD_REQUEST` (400), `UNAUTHORIZED` (401),
  `FORBIDDEN` (403), `NOT_FOUND` (404), `CONFLICT` (409), `RATE_LIMITED` (429), `INTERNAL` (500). Any other thrown
  error is `INTERNAL`. On the device the same `code` arrives, plus `NETWORK` for transport failures.
- **Who is calling**: `caller().deviceId` is a stable id of the calling device, sent by the client library. Use it
  as the user key. It identifies a device; it does not authenticate a person.
- **Who is connected**: `online()` returns the device ids that have a live connection open right now.
- **Events**: for moments that are not stored state ("Ayse is typing", a reaction), export
  `event<Payload>()` and call `.send(deviceIds, payload)`. Only those devices get it, and only if their app is
  open (see Events).
- **State**: keep it in SQLite (`new Database("app.db")`). The file survives deploys and restarts. Module-level
  variables reset on every deploy and crash.
- Bun APIs, `fetch` and npm packages work; packages in `package.json` are bundled on deploy.

## Calling it from ArkTS

Import the generated functions and types from the stub, by the same name as the `.api.ts` file:

```ts
import { AsyncValue, LiveValue } from 'arkapi'
import { addTodo, listTodos, Todo } from './todo.api'

@Entry
@Component
struct TodoPage {
  @State todos: LiveValue<Todo[]> = new LiveValue(listTodos)
  @State added: AsyncValue<number> = new AsyncValue()
  @State draft: string = ''

  build() {
    Column({ space: 8 }) {
      ForEach(this.todos.data ?? [], (todo: Todo) => {
        Text(todo.title).fontColor('#FFFFFF')
      }, (todo: Todo) => `${todo.id}`)
      TextInput({ text: $$this.draft })
      Button('Add')
        .enabled(!this.added.loading)
        .onClick(() => { this.added.run(addTodo(this.draft)) })
      Text(this.todos.error ?? this.added.error ?? '').fontColor('#E06C6C')
    }
  }
}
```

- **Plain call**: every stub function returns a `Promise`. A failed call rejects with `ApiError` (from `arkapi`)
  carrying `code` and `message`.
- **`AsyncValue<R>`** for actions: `run(promise)` sets `loading`, then `data` or `error` and `errorCode`.
  Check codes, not message text: `if (this.added.errorCode === 'CONFLICT') { ... }`.
- **`LiveValue<R>`** for data on screen: `new LiveValue(listTodos)` or `new LiveValue(() => getTodo(id))`.
  Fields: `data` (null until the first value), `loaded` (true once the first answer, data or error, arrived;
  tells "not loaded yet" apart from a query that returned null), `error`, `errorCode`, `connected`.
  - The server re-runs live queries after every mutation, HTTP route, upload and job, and sends only changed
    results. After `addTodo` there is nothing to refresh by hand: every screen showing `listTodos` updates.
  - Nothing re-runs just because time passes. For text that depends on the clock ("5 minutes ago", an expiry),
    return the timestamp and compute the text on the device.
  - The function must call exactly one query; its arguments are fixed. For other arguments, create a new LiveValue.
  - It reconnects by itself and keeps the last data; `connected` turns false after about 3 s without a connection.
  - `stop()` ends the subscription; the last data stays readable. Call it in `aboutToDisappear` for a LiveValue
    created by a screen that goes away. Do not recreate LiveValues on every render.
- Hold both in `@State`. The library declares the INTERNET permission itself.
- On a wearable (round screen, about 233 vp), keep content narrow and away from the top and bottom edges.

## Calling it without the app (curl, tests)

Every endpoint is `POST <base>/api/<id>` with the arguments as a JSON array. After a deploy, `<base>` is the `BASE`
constant at the top of the generated stub. Under `watch`, use `http://localhost:<port>` from this machine (`BASE`
then holds the address the emulator or phone uses, like `http://10.0.2.2:3000`).

```sh
curl -X POST https://arkapi.emincanozcan.com/apps/<app>/api/pages.todo.addTodo \
  -H 'X-ArkAPI-Device: test-device-1' -d '{"args": ["buy milk"]}'
# 200 → the JSON result · errors → {"error": "...", "code": "..."} with the matching HTTP status
```

Live queries use a WebSocket at `<base>/live`:

```ts
const socket = new WebSocket('ws://localhost:3000/live', { headers: { 'X-ArkAPI-Device': 'test-device-1' } })
socket.onopen = () => socket.send(JSON.stringify({ id: 1, name: 'pages.todo.listTodos', args: [] }))
socket.onmessage = (event) => console.log(JSON.parse(String(event.data)))
```

Messages are `{id, data}` for a full result, `{id, error, code}` for a failure, or `{id, drop, append}` for a list
update: the new list is `previous.slice(drop).concat(append)`. Events arrive as `{event, data}`, for example
`{"event": "pages.chat.typing", "data": {...}}`. `{"id": 1, "stop": true}` ends one subscription; closing the
socket ends all of them.

## Events

A LiveValue shows state. An event is a moment the backend pushes to chosen devices: someone is typing, a
reaction, "your order is here". Export it from an api file; the payload follows the same type rules as
arguments.

```ts
import { caller, event, online } from 'arkapi/server'

export interface Typing { name: string }
export const typing = event<Typing>()

export function setTyping(name: string): void {
  const me = caller().deviceId
  typing.send(online().filter((device) => device !== me), { name })
}
```

The stub gets a typed listener named `on` + the event name. Start it in `aboutToAppear` and stop it in
`aboutToDisappear`:

```ts
import { Listening } from 'arkapi'
import { onTyping, Typing } from './chat.api'

private listening: Listening | null = null
aboutToAppear(): void { this.listening = onTyping((event: Typing) => { this.typist = event.name }) }
aboutToDisappear(): void { this.listening?.stop() }
```

Events are not stored: a device whose app is closed or offline when it is sent never gets it. Anything a device
must see later belongs in the database and a LiveValue. Decide on the device how long to show an event.

## Files and photos

Every stub exports `uploadFile(uri: string): Promise<FileRef>`. Pass a local file URI, for example from the photo
picker. `FileRef` has `id` and `url`.

```ts
import { photoAccessHelper } from '@kit.MediaLibraryKit'
import { sendPhoto, uploadFile } from './chat.api'

async function pickAndSend(): Promise<void> {
  const options = new photoAccessHelper.PhotoSelectOptions()
  options.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE // images only
  options.maxSelectNumber = 1
  try {
    const selected = await new photoAccessHelper.PhotoViewPicker().select(options)
    if (selected.photoUris.length === 0) return // the user cancelled
    const photo = await uploadFile(selected.photoUris[0]) // bytes go to file storage; photo = { id, url }
    await sendPhoto(photo.id) // your endpoint stores the id; show it with Image(photo.url)
  } catch (e) {
    console.error(`Photo not sent: ${e}`)
  }
}
```

On the backend:

```ts
import { files } from 'arkapi/server'

const id = await files.write('hello', 'text/plain') // ArrayBuffer or string; returns an id
const url = files.url(id)                           // public download URL
const data = await files.read(id)                   // ArrayBuffer; NOT_FOUND if absent
const all = files.list()                            // { id, size }[]
files.remove(id)
```

Files are at most 10 MB (413 otherwise), survive deploys, and are public to anyone with the URL. Uploading and
using a file are separate calls: store ids in your database and check ownership before `files.remove`.

## HTTP routes

For callers that need plain HTTP, such as webhooks, export `routes` from any api file. Keys are `METHOD /path`;
handlers get the `Request` and the path parameters and return a `Response`.

```ts
import { ApiError, type Routes } from 'arkapi/server'

export const routes: Routes = {
  'POST /announce': async (req) => {
    if (req.headers.get('Authorization') !== `Bearer ${process.env.ANNOUNCE_TOKEN}`) {
      throw new ApiError('UNAUTHORIZED', 'Invalid token')
    }
    return Response.json({ accepted: await req.text() })
  },
  'PUT /items/:id': async (req, params) => Response.json({ id: params.id }),
}
```

The URLs are `<base>/http/announce` and `<base>/http/items/123`. A route refreshes live queries like a
mutation. Cookies are not forwarded; use the `Authorization` header for credentials.

## Scheduled jobs

Register jobs at the top level of an api file. Intervals are milliseconds or strings such as `'30s'`, `'5m'`,
`'1h'`; `daily` takes `HH:MM` in UTC.

```ts
import { every, daily } from 'arkapi/server'

every('1h', function cleanup() { /* ... */ })
daily('02:30', async function nightlyDigest() { /* ... */ })
```

A run is skipped while the previous one is still running. Each run logs `job <name> ok 12ms` or its error, then
refreshes live queries. Jobs have no calling device, so `caller()` does not work in them. Runs missed while the
app was down are not repeated. To test job logic, put it in a plain module outside the `*.api.ts` glob and call it
from a Bun test; exporting it from an api file would make it an endpoint.

## Hosted limits

3 apps per account · 600 requests per minute per app · 50 open connections per app · 100 MB disk per app ·
5 MB bundle · 30 deploys per hour · 0.5 CPU core and 256 MiB RAM per app. A request is one call or one new
LiveValue; pushed updates and events do not count. Over a limit the call fails with 429 (413 or 507 on deploy).
A call whose response has not started after 5 s fails with 504.

## When something is off

- Build fails after generating → `ohpm install`, then build again. DevEco still runs an old stub → Build → Clean
  Project. `does not provide an export name` at runtime is the same stale build.
- `unsupported type ...` from generate → change the signature to wire types (see the rules above).
- `BAD_REQUEST` with an `args[...]` path → the argument at that path does not match the signature.
- `this app was built against a different version of the backend; rebuild it` → `bunx arkapi generate`, then
  rebuild and reinstall the app.
- `unknown endpoint` → the backend was not deployed after adding the function: `bunx arkapi deploy`.
- `LiveValue needs a query (get…, list…)` → back the LiveValue with a query; run mutations with `AsyncValue`.
- `errorCode === 'NETWORK'` → check connectivity and the `BASE` URL in the stub.
- `ArkAPI: not logged in` → `bunx arkapi login`.
- `watch` cannot bind its port → another process is listening on it, or the sandbox blocks local sockets.
- A route returns 404 → call `<base>/http/<path>` with the method declared in `routes`, after a deploy.
- A job does not run → `bunx arkapi logs`; check its interval or UTC time.
- Backend crashes → `bunx arkapi logs`. The host restarts it. The dashboard's **Recent errors** lists the last
  failures with endpoint, code and message.
- `bun:sqlite`, `process` or `arkapi/server` red in DevEco → run `bunx arkapi init`, then reopen the project.
  `unsupported ohpm layout` → run `ohpm install` from the project root.
- A hidden stub is needed in DevEco → Project view ⚙ → **Show Excluded Files**. To jump from a call straight to
  its backend function, install `node_modules/arkapi/cli/assets/arkapi-navigation.zip` (Settings → Plugins → ⚙ →
  Install Plugin from Disk).
