# ArkAPI: complete documentation # Meet ArkAPI Source: https://arkapi.emincanozcan.com/docs/overview.md ArkAPI lets you build a HarmonyOS feature from end to end in one project. You write the backend as TypeScript functions in a `*.api.ts` file next to the ArkTS screen. The screen imports those functions and calls them. `bunx arkapi deploy` puts the backend online. ## A function is your API ```ts // greeting.api.ts: runs on the server export function greet(name: string): string { return `Hello, ${name}` } ``` ```ts // Greeting.ets: runs on the device import { greet } from './greeting.api' async function hello(): Promise { const message: string = await greet('Ada') } ``` ArkAPI reads the function signature and generates `greeting.api.ets`, a typed client for the screen. There is no URL, request body or JSON parsing to write. If you change the backend signature and forget the screen, the app does not compile. ## What is included - **Typed calls**: functions, interfaces and errors carry through to ArkTS. The server checks every argument. - **Live data**: a screen that shows a query updates by itself when another device changes the data. - **Storage**: SQLite and file uploads, kept across deploys. - **HTTP routes and jobs**: webhooks for other services, and work that runs every hour or every night. - **Hosting**: one-command deploys, a dashboard with traffic, errors, logs and data, environment variables and rollback. ## Pick your path - [Your first feature](/docs/quickstart.md): a shared list, from install to the screen. - [Build a chat app](/docs/tutorial.md): every feature in one small app, step by step. - [Build with your agent](/docs/agents.md): give a coding agent the same guide you read. - Already building? Go to [server functions](/docs/functions.md) or [calling from ArkTS](/docs/client.md). ## What you need A HarmonyOS project, [Bun](https://bun.sh) and DevEco Studio. The hosted service is a development service; check the [limits](/docs/limits.md) before you depend on it. --- # Your first feature Source: https://arkapi.emincanozcan.com/docs/quickstart.md Start in an existing HarmonyOS project, or in an empty folder: `init --create` makes a blank phone project first. You need [Bun](https://bun.sh), DevEco Studio and access to the ArkAPI GitHub repository. The current install uses your GitHub SSH key. ## 1. Add ArkAPI Run these commands in the project root: ```sh bun add -d git+ssh://git@github.com/emincanozcan/arkapi.git bunx arkapi init bunx arkapi signup --email you@example.com ``` Already have an account? Run `bunx arkapi login --email you@example.com` instead of signup. The CLI prompts for your password. `init` adds the client HAR, `arkapi.config.ts`, a small example and `AGENTS.md`. The guide is also there for your coding agent. In an empty folder, run `bunx arkapi init --create` instead. The project is named after the folder. ## 2. Write the backend Create `entry/src/main/ets/pages/todos.api.ts` beside your screen: ```ts import { Database } from 'bun:sqlite' import { ApiError } from 'arkapi/server' interface Todo { id: number title: string } const db = new Database('app.db') db.run('create table if not exists todos (id integer primary key, title text)') export function listTodos(): Todo[] { return db.query('select id, title from todos order by id').all() } export function addTodo(title: string): number { if (!title.trim()) throw new ApiError('BAD_REQUEST', 'Add a title') return Number(db.run('insert into todos (title) values (?)', [title.trim()]).lastInsertRowid) } ``` The data is shared by everyone using this app. It survives deploys because `app.db` lives in the app's working directory. This example has no user authentication; [device identity](/docs/functions.md) can help partition anonymous data but is not a trusted login. ## 3. Deploy the functions ```sh bunx arkapi deploy ``` The first deploy creates your hosted app and writes its ID to `arkapi.config.ts`. It also generates `todos.api.ets` with typed client functions and the hosted URL. Later deploys activate a new version after it answers its readiness probe. ## 4. Connect your screen Use this as a page, or copy its state and UI into an existing page: ```ts import { AsyncValue, LiveValue } from 'arkapi' import { addTodo, listTodos, Todo } from './todos.api' @Entry @Component struct TodosPage { @State todos: LiveValue = new LiveValue(listTodos) @State added: AsyncValue = new AsyncValue() @State draft: string = '' build() { Column({ space: 12 }) { if (!this.todos.connected) { LoadingProgress().width(20) } ForEach(this.todos.data ?? [], (todo: Todo) => { Text(todo.title) }, (todo: Todo) => `${todo.id}`) TextInput({ text: $$this.draft, placeholder: 'What are we building?' }) Button('Add') .enabled(!this.added.loading) .onClick(() => { this.added.run(addTodo(this.draft)) }) Text(this.todos.error ?? this.added.error ?? '') } .padding(24) .width('100%') } } ``` `addTodo` is a mutation. After it runs, ArkAPI re-runs `listTodos` and sends changed results to subscribed screens. You do not need a manual refresh call. See [ArkTS and live data](/docs/client.md) for connection and error states. ## 5. Build and run the client ```sh ohpm install hvigorw assembleHap --mode module -p product=default -p buildMode=debug --no-daemon ``` Use DevEco Studio to configure signing and run on a device or emulator. Build and install after deploy: the backend URL and client types are compiled into the app. Compilation checks the code; running it on a device checks networking and rendering. ## Keep building For local iteration, run `bunx arkapi watch`. It regenerates stubs and restarts the local server when backend files change. Emulator stubs use `10.0.2.2`; for a phone on your LAN, set `deviceHost` in `arkapi.config.ts`. Deploy again before building a client that should use the hosted URL. Open `bunx arkapi open` to inspect traffic, logs, environment variables and stored data. Next, add [photos and files](/docs/files.md), [HTTP routes](/docs/http.md) or [scheduled jobs](/docs/jobs.md). --- # Build with your agent Source: https://arkapi.emincanozcan.com/docs/agents.md The screen and its backend live in the same project, so a coding agent can build a whole feature in one go. `arkapi init` writes `AGENTS.md`, plus a `CLAUDE.md` that points to it. Claude Code, Codex and similar agents read it when they open the project. ## Give the agent an outcome ```text Read AGENTS.md. Build a shared photo wall for this HarmonyOS app: photo uploads, captions, a live feed, and likes per device. Use ArkAPI for the backend. Generate the client and check the build. ``` The guide covers the commands, the wire types, live data, files, HTTP routes, jobs, build checks and common errors. Because the client is generated from the backend, a mismatch between the two is a compile error the agent sees and fixes, not a bug that shows up later on a device. ## Context for agents on the web - [Documentation index](/llms.txt): the list of pages with Markdown URLs. - [Project guide](/docs/guide.md): the exact `AGENTS.md` that `init` writes. - [All documentation](/llms-full.txt): every page in one response. Every page also has a `.md` URL, and page URLs return Markdown to requests with `Accept: text/markdown`. ```sh curl https://arkapi.emincanozcan.com/docs/files.md ``` ## Keep a human in the loop Describe who may see or change data. Device ids identify devices but do not authenticate people. A successful build does not replace trying the app on a device. --- # Build a chat app Source: https://arkapi.emincanozcan.com/docs/tutorial.md In this tutorial you build a group chat for HarmonyOS. People pick a name, send messages and photos, and see who is typing. A script outside the app can post announcements, and old messages clean themselves up. At the end it runs on the hosted service. The backend is one file of about 100 lines. The screen is one ArkTS page. Along the way you use everything ArkAPI has: | You will use | For | |---|---| | `caller()`, `online()` | who is calling, who is connected | | `ApiError` | errors the screen can react to | | `LiveValue`, `AsyncValue` | data that updates by itself, buttons with loading and error state | | `event()` | "Ada is typing…" | | `files`, `uploadFile` | photos | | `routes` | announcements from a script | | `every()` | hourly cleanup | | `watch`, `deploy`, `open`, `logs`, `env` | the CLI | That table is the whole API. There is nothing else to learn. ## How ArkAPI works You write the backend as TypeScript functions in a file that ends in `.api.ts`, next to your screen. ArkAPI reads the function signatures and generates a typed ArkTS client with the same name and `.api.ets`. Your screen imports from it as if the functions were local: ```ets import { setName } from './chat.api' ``` A call runs on the server, never on the device. You do not write URLs, request bodies or JSON parsing, and if the backend and the screen disagree on a type, the app does not compile. ## Set up the project You need [Bun](https://bun.sh) and DevEco Studio. In DevEco Studio, create a new project with the **Empty Ability** template. Then, in the project root: ```sh bun add -d git+ssh://git@github.com/emincanozcan/arkapi.git bunx arkapi init ``` No project yet? In an empty folder, `bunx arkapi init --create` makes a blank phone project first. `init` adds the client library, `arkapi.config.ts` and an `AGENTS.md` guide for coding agents. It also adds an example, `entry/src/main/ets/pages/hello.api.ts`. Delete it and its generated `hello.api.ets`; you will write your own. ## Run the backend on your computer ```sh bunx arkapi watch ``` `watch` runs the backend on port 3000 and regenerates the client whenever you save an `.api.ts` file. Keep it running for the whole tutorial. The data goes to `app.db`, a SQLite file in the project root. Run the app on the emulator from DevEco Studio. The emulator reaches your computer at `10.0.2.2`, which is where the generated client points while `watch` runs. To use a phone on your network instead, set `deviceHost` in `arkapi.config.ts` to your computer's address. Next: [pick a name](/docs/tutorial-names.md). --- # 1. Pick a name Source: https://arkapi.emincanozcan.com/docs/tutorial-names.md The chat starts with a name. There are no accounts: each device picks a name, and the backend remembers it by device. ## The backend Create `entry/src/main/ets/pages/chat.api.ts`: ```ts import { Database } from 'bun:sqlite' import { ApiError, caller } from 'arkapi/server' const db = new Database('app.db') db.run('create table if not exists people (device text primary key, name text not null unique collate nocase)') export function getName(): string { return nameOf(caller().deviceId) ?? '' } export function setName(name: string): string { const clean = name.trim() if (clean === '' || clean.length > 20) throw new ApiError('BAD_REQUEST', 'Use 1 to 20 characters') const { deviceId } = caller() if (db.query('select 1 from people where name = ? and device != ?').get(clean, deviceId)) { throw new ApiError('CONFLICT', `${clean} is taken`) } db.run('insert into people (device, name) values (?, ?) on conflict (device) do update set name = excluded.name', [deviceId, clean]) return clean } function nameOf(device: string): string | undefined { return db.query<{ name: string }, [string]>('select name from people where device = ?').get(device)?.name } ``` What is going on: - **Exported functions are endpoints.** `getName` and `setName` can be called from the app; `nameOf` is not exported, so it stays private to the server. - **Queries and mutations.** A function whose name starts with `get`, `list`, `find`, `search`, `count`, `has`, `is` or `load`, followed by an uppercase letter or the end of the name (`getMessages`, `isOnline`; not `getaway`), is a query: it only reads. Everything else is a mutation. The difference matters in a minute. - **`caller().deviceId`** is the id of the device that made the call. The app sends it with every request. It tells devices apart, but it is not a login: do not use it to protect anything valuable. - **`ApiError`** carries a code the screen can check. `CONFLICT` becomes HTTP 409, `BAD_REQUEST` becomes 400. Any other thrown error becomes `INTERNAL`, and its stack goes to the logs. - **SQLite** comes with Bun. `app.db` survives restarts and deploys; a variable at the top of the file does not. Save the file. `watch` prints the generated client: `chat.api.ets (getName, setName)`. ## The screen Replace `entry/src/main/ets/pages/Index.ets`: ```ets import { AsyncValue, LiveValue } from 'arkapi' import { getName, setName } from './chat.api' @Entry @Component struct Index { @State name: LiveValue = new LiveValue(getName) @State saving: AsyncValue = new AsyncValue() @State nameDraft: string = '' build() { Column({ space: 12 }) { if (this.name.data === null) { LoadingProgress().width(32).color('#8A8A99') } else if (this.name.data === '') { this.namePicker() } else { this.chat(this.name.data) } } .width('100%') .height('100%') .padding(16) .justifyContent(FlexAlign.Center) .backgroundColor('#101014') } @Builder namePicker() { Text('Pick a name').fontSize(22).fontColor('#FFFFFF') TextInput({ text: $$this.nameDraft, placeholder: 'Ada' }) .fontColor('#FFFFFF') .placeholderColor('#77778A') .backgroundColor('#22222A') Button('Join') .width('100%') .fontColor('#FFFFFF') .backgroundColor('#4F6BF5') .enabled(!this.saving.loading) .onClick(() => { this.saving.run(setName(this.nameDraft)) }) Text(this.nameError()).fontColor('#FF7B7B') } nameError(): string { if (this.saving.errorCode === 'CONFLICT') { return 'Someone already has that name' } if (this.saving.errorCode === 'BAD_REQUEST') { return 'Use 1 to 20 characters' } return this.saving.error ?? '' } @Builder chat(name: string) { Text(`Hi, ${name}`).fontSize(22).fontColor('#FFFFFF') } } ``` The two wrappers are the whole client API: - **`LiveValue`** keeps a query's result on screen. `data` is `null` until the first answer arrives, so the screen shows a spinner, then the name picker (empty name) or the chat. - **`AsyncValue`** runs one call for a button. `run(promise)` sets `loading` while the call is in flight, then either `data` or `error` and `errorCode`. Notice what is missing: after `setName` succeeds, nothing tells the screen to reload the name. ArkAPI re-runs live queries after every mutation and sends the results that changed. `getName` now returns the new name, so the screen switches to the chat by itself. Check `errorCode`, not the message text. `error` is the full message, handy in logs; `NETWORK` means the device could not reach the backend. ## Try it Run the app, pick a name, and you see "Hi, Ada". Now be a second device from the terminal. Every endpoint is a `POST` with the arguments as a JSON array: ```sh curl -X POST http://localhost:3000/api/pages.chat.setName \ -H 'X-ArkAPI-Device: laptop' -d '{"args": ["ada"]}' ``` The answer is `409` with `{"error": "ada is taken", "code": "CONFLICT"}`. The name column ignores case, so `ada` and `Ada` are the same name. Try `{"args": [42]}` too: the server checks the arguments against the signature and answers `400` before `setName` runs. Next: [live messages](/docs/tutorial-messages.md). --- # 2. Live messages Source: https://arkapi.emincanozcan.com/docs/tutorial-messages.md Now the chat itself: a list of messages that stays up to date on every device, without polling or refresh buttons. ## The backend Make four additions to `chat.api.ts`. Add `online` to the import: ```ts import { ApiError, caller, online } from 'arkapi/server' ``` Add the message types below the imports: ```ts export interface Message { id: number name: string text: string mine: boolean } interface MessageRow { id: number name: string text: string mine: number } ``` Create a `messages` table below the `people` table: ```ts db.run('create table if not exists messages (id integer primary key, device text not null, text text not null, photo text, at integer not null)') ``` Add the new functions below `setName`: ```ts export function getMessages(): Message[] { const rows = db.query(` select m.id, coalesce(p.name, 'Announcement') as name, m.text, m.device = ? as mine from messages m left join people p on p.device = m.device order by m.id desc limit 100`).all(caller().deviceId) return rows.reverse().map((row) => ({ id: row.id, name: row.name, text: row.text, mine: row.mine === 1 })) } export function sendMessage(text: string): void { const clean = text.trim() if (clean === '') throw new ApiError('BAD_REQUEST', 'Write something first') save(me(), clean, null) } export function countOnline(): number { return online().length } function me(): string { const { deviceId } = caller() if (!nameOf(deviceId)) throw new ApiError('UNAUTHORIZED', 'Pick a name first') return deviceId } function save(device: string, text: string, photo: string | null): void { db.run('insert into messages (device, text, photo, at) values (?, ?, ?, ?)', [device, text, photo, Date.now()]) } ``` - **`Message` crosses the wire.** Interfaces used by endpoints appear in the generated client under the same name, so the screen imports `Message` too. Plain types work: strings, numbers, booleans, arrays, interfaces, `null` unions and records. Send times as numbers, not `Date`. - **`mine`** depends on who asks, so each device gets its own answer. ArkAPI notices that `getMessages` reads `caller()` and runs it once per device; queries that do not, like `countOnline`, run once and are shared. - **`online()`** lists the devices that have the app open right now, so `countOnline` changes when someone opens or closes the app. - The `photo` column and the `'Announcement'` name are for later chapters; they cost nothing now. ## The screen Replace `Index.ets`. The name picker is the same as before; what is new are the imports, three pieces of state, the `chat` builder, `bubble` and `send`: ```ets import { AsyncValue, LiveValue } from 'arkapi' import { countOnline, getMessages, getName, Message, sendMessage, setName } from './chat.api' @Entry @Component struct Index { @State name: LiveValue = new LiveValue(getName) @State saving: AsyncValue = new AsyncValue() @State nameDraft: string = '' @State messages: LiveValue = new LiveValue(getMessages) @State online: LiveValue = new LiveValue(countOnline) @State sending: AsyncValue = new AsyncValue() @State draft: string = '' build() { Column({ space: 12 }) { if (this.name.data === null) { LoadingProgress().width(32).color('#8A8A99') } else if (this.name.data === '') { this.namePicker() } else { this.chat(this.name.data) } } .width('100%') .height('100%') .padding(16) .justifyContent(FlexAlign.Center) .backgroundColor('#101014') } @Builder namePicker() { Text('Pick a name').fontSize(22).fontColor('#FFFFFF') TextInput({ text: $$this.nameDraft, placeholder: 'Ada' }) .fontColor('#FFFFFF') .placeholderColor('#77778A') .backgroundColor('#22222A') Button('Join') .width('100%') .fontColor('#FFFFFF') .backgroundColor('#4F6BF5') .enabled(!this.saving.loading) .onClick(() => { this.saving.run(setName(this.nameDraft)) }) Text(this.nameError()).fontColor('#FF7B7B') } nameError(): string { if (this.saving.errorCode === 'CONFLICT') { return 'Someone already has that name' } if (this.saving.errorCode === 'BAD_REQUEST') { return 'Use 1 to 20 characters' } return this.saving.error ?? '' } @Builder chat(name: string) { Text(`${name} · ${this.online.data ?? 0} online`).fontSize(12).fontColor('#8A8A99') List({ space: 8 }) { ForEach(this.messages.data ?? [], (message: Message) => { ListItem() { this.bubble(message) } }, (message: Message) => `${message.id}`) } .width('100%') .layoutWeight(1) .stackFromEnd(true) Row({ space: 8 }) { TextInput({ text: $$this.draft, placeholder: 'Message' }) .layoutWeight(1) .fontColor('#FFFFFF') .placeholderColor('#77778A') .backgroundColor('#22222A') .onSubmit(() => this.send()) Button('Send') .fontColor('#FFFFFF') .backgroundColor('#4F6BF5') .enabled(!this.sending.loading) .onClick(() => this.send()) } } @Builder bubble(message: Message) { Column({ space: 2 }) { Text(message.name).fontSize(11).fontColor('#8A8A99') Text(message.text) .fontSize(15) .fontColor('#FFFFFF') .padding({ left: 12, right: 12, top: 8, bottom: 8 }) .borderRadius(14) .backgroundColor(message.mine ? '#4F6BF5' : '#2A2A33') } .width('100%') .alignItems(message.mine ? HorizontalAlign.End : HorizontalAlign.Start) } send(): void { this.sending.run(sendMessage(this.draft)).then(() => { if (this.sending.error === null) { this.draft = '' } }) } } ``` ## What happens when you press Send 1. `sendMessage` runs on the server and inserts a row. 2. Because it is a mutation, ArkAPI re-runs every live query that a screen is showing: `getMessages` for each device, `countOnline` once. 3. Results that changed go down each device's socket. For a list that only grew, only the new items are sent. 4. `this.messages.data` changes and ArkUI redraws the list. All `LiveValue`s in the app share one socket. If it drops, it reconnects by itself and keeps the last data; `connected` turns false after a few seconds, if you want to show it. ## Try it Send a message from the app. Then give the terminal a name and talk to yourself: ```sh curl -X POST http://localhost:3000/api/pages.chat.setName \ -H 'X-ArkAPI-Device: laptop' -d '{"args": ["Lin"]}' curl -X POST http://localhost:3000/api/pages.chat.sendMessage \ -H 'X-ArkAPI-Device: laptop' -d '{"args": ["Hello from the terminal"]}' ``` Lin's message appears on the left, in grey, the moment the second command returns. Skip the `setName` with a new device id and `sendMessage` answers `401` with `Pick a name first`. Next: [someone is typing](/docs/tutorial-typing.md). --- # 3. Someone is typing Source: https://arkapi.emincanozcan.com/docs/tutorial-typing.md "Lin is typing…" is not data you store. It is a moment: it matters now, to the people who are looking, and then it is gone. For that, ArkAPI has events. | | `LiveValue` | Event | |---|---|---| | What | state, the result of a query | a moment | | Who gets it | every screen showing the query | the device ids you choose | | Stored | in your database | never; offline devices miss it | | Example | the message list | someone is typing | ## The backend Add `event` to the import, and this below `countOnline`: ```ts import { ApiError, caller, event, online } from 'arkapi/server' ``` ```ts export interface Typing { name: string } export const typing = event() export function setTyping(): void { const device = me() typing.send(online().filter((other) => other !== device), { name: nameOf(device)! }) } ``` `event()` declares an event with its payload type. Export it, or the app cannot listen to it. `send` takes a list of device ids and the payload. Here it goes to every device that is online, except the one typing. ## The screen Save, and the generated client has a new function, `onTyping`: `on` plus the event name, with a typed listener. Add `Listening`, `onTyping`, `setTyping` and `Typing` to the imports: ```ets import { AsyncValue, Listening, LiveValue } from 'arkapi' import { countOnline, getMessages, getName, Message, onTyping, sendMessage, setName, setTyping, Typing } from './chat.api' ``` Add this below the `draft` state. The listener starts when the screen appears and stops when it goes away: ```ets @State typist: string = '' private typing: Listening | null = null private typedAt: number = 0 private typistAt: number = 0 aboutToAppear(): void { this.typing = onTyping((event: Typing) => { this.typist = event.name this.typistAt = Date.now() setTimeout(() => { if (Date.now() - this.typistAt >= 3000) { this.typist = '' } }, 3000) }) } aboutToDisappear(): void { this.typing?.stop() } ``` The name disappears three seconds after the last event. In the `chat` builder, show it between the list and the input row: ```ets .stackFromEnd(true) Text(this.typist === '' ? '' : `${this.typist} is typing…`).fontSize(11).fontColor('#8A8A99') ``` Then tell the others while you type. Add `.onChange` to the message `TextInput`, and the `typed` method above `send`: ```ets .backgroundColor('#22222A') .onChange(() => this.typed()) .onSubmit(() => this.send()) ``` ```ets typed(): void { if (Date.now() - this.typedAt > 2000) { this.typedAt = Date.now() setTyping().catch(() => {}) } } ``` `typed` sends at most one event every two seconds, and the receiver keeps the name for three, so the indicator stays steady while someone types. `catch(() => {})` because a lost typing notice is not worth an error on screen. ## Try it You need a second listener, so open a socket from the terminal. `/live` is the same socket the app uses: ```sh bun -e "const ws = new WebSocket('ws://localhost:3000/live', { headers: { 'X-ArkAPI-Device': 'laptop' } }); ws.onmessage = (e) => console.log(String(e.data))" ``` Type in the app, and the terminal prints `{"event":"pages.chat.typing","data":{"name":"Ada"}}`. The app, the one typing, gets nothing. Next: [photos](/docs/tutorial-photos.md). --- # 4. Photos Source: https://arkapi.emincanozcan.com/docs/tutorial-photos.md A photo is two calls: upload the file, then send a message that points to it. Every generated client has `uploadFile(uri)` for the first; you write the second. ## The backend Add `files` to the import. `Message` gets a `photoUrl`, and `MessageRow` the `photo` column: ```ts import { ApiError, caller, event, files, online } from 'arkapi/server' export interface Message { id: number name: string text: string photoUrl: string | null mine: boolean } interface MessageRow { id: number name: string text: string photo: string | null mine: number } ``` Select the photo in `getMessages` and turn its id into a URL: ```ts export function getMessages(): Message[] { const rows = db.query(` select m.id, coalesce(p.name, 'Announcement') as name, m.text, m.photo, m.device = ? as mine from messages m left join people p on p.device = m.device order by m.id desc limit 100`).all(caller().deviceId) return rows.reverse().map((row) => ({ id: row.id, name: row.name, text: row.text, mine: row.mine === 1, photoUrl: row.photo === null ? null : files.url(row.photo), })) } ``` And add `sendPhoto` below `sendMessage`: ```ts export function sendPhoto(fileId: string): void { if (!files.list().some((file) => file.id === fileId)) throw new ApiError('NOT_FOUND', 'Upload the photo first') save(me(), '', fileId) } ``` Store the file id in your database, not the URL: `files.url` builds the URL for wherever the backend runs, on your computer now and on the hosted service later. Files are at most 10 MB, survive deploys, and anyone with the URL can open them. ## The screen Import the photo picker, and add `sendPhoto` and `uploadFile` to the client imports: ```ets import { AsyncValue, Listening, LiveValue } from 'arkapi' import { photoAccessHelper } from '@kit.MediaLibraryKit' import { countOnline, getMessages, getName, Message, onTyping, sendMessage, sendPhoto, setName, setTyping, Typing, uploadFile } from './chat.api' ``` Add a `+` button at the start of the input row: ```ets Row({ space: 8 }) { Button('+') .fontColor('#FFFFFF') .backgroundColor('#2A2A33') .enabled(!this.sending.loading) .onClick(() => { this.sending.run(this.pickPhoto()) }) ``` And the method that picks, uploads and sends, above `send`: ```ets async pickPhoto(): Promise { try { const options = new photoAccessHelper.PhotoSelectOptions() options.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE options.maxSelectNumber = 1 const picked = await new photoAccessHelper.PhotoViewPicker().select(options) if (picked.photoUris.length > 0) { const photo = await uploadFile(picked.photoUris[0]) await sendPhoto(photo.id) } } catch (error) { throw error as Error } } ``` The `try` that only rethrows is there for the ArkTS compiler, which warns about picker calls outside one. The error still reaches `this.sending`. `pickPhoto` returns a promise like any call, so the same `AsyncValue` that drives Send also disables both buttons during the upload. Finally, in `bubble`, show the photo instead of the text bubble when there is one: ```ets Text(message.name).fontSize(11).fontColor('#8A8A99') if (message.photoUrl !== null) { Image(message.photoUrl).width(180).borderRadius(14) } else { Text(message.text) .fontSize(15) .fontColor('#FFFFFF') .padding({ left: 12, right: 12, top: 8, bottom: 8 }) .borderRadius(14) .backgroundColor(message.mine ? '#4F6BF5' : '#2A2A33') } ``` ## Try it Send a photo with `+`. `sendPhoto` is a mutation, so the photo reaches every screen the same way a text message does. Next: [announcements from outside](/docs/tutorial-announce.md). --- # 5. Announcements from outside Source: https://arkapi.emincanozcan.com/docs/tutorial-announce.md Not every caller is your app. A script, a CI job or a payment provider speaks plain HTTP. In this chapter, anyone with a token can post an announcement into the chat with `curl`. ## The backend Add `type Routes` to the import, and export `routes` below `setTyping`: ```ts import { ApiError, caller, event, files, online, type Routes } from 'arkapi/server' ``` ```ts export const routes: Routes = { 'POST /announce': async (req) => { const token = process.env.ANNOUNCE_TOKEN if (!token || req.headers.get('Authorization') !== `Bearer ${token}`) { throw new ApiError('UNAUTHORIZED', 'Wrong token') } save('announcement', await req.text(), null) return new Response('ok') }, } ``` - Keys are `METHOD /path`; a path like `/items/:id` passes `id` in a second `params` argument. The handler gets a standard `Request` and returns a `Response`. - The URL is the backend's address plus `/http`, so this one is `http://localhost:3000/http/announce` for now. - The message is saved with the device `announcement`, which has no row in `people`. That is why `getMessages` falls back to the name `Announcement`. - A route refreshes live queries like a mutation, so the announcement appears on every screen. ## Try it The token comes from an environment variable. Stop `watch`, and start it again with one: ```sh ANNOUNCE_TOKEN=pizza bunx arkapi watch ``` ```sh curl -X POST http://localhost:3000/http/announce \ -H 'Authorization: Bearer pizza' -d 'Pizza in the kitchen' ``` The app shows the announcement from "Announcement". With a wrong token the answer is `401` and nothing is saved. On the hosted service you set the token with `bunx arkapi env set`, in the last chapter. Next: [clean up every hour](/docs/tutorial-cleanup.md). --- # 6. Clean up every hour Source: https://arkapi.emincanozcan.com/docs/tutorial-cleanup.md The chat keeps a week of history. Older messages, and their photos, should go away without anyone calling anything. That is a job. ## The backend Add `every` to the import, and register the job below `routes`: ```ts import { ApiError, caller, event, every, files, online, type Routes } from 'arkapi/server' ``` ```ts every('1h', function cleanup() { const weekAgo = Date.now() - 7 * 24 * 60 * 60 * 1000 const old = db.query<{ photo: string }, [number]>('select photo from messages where at < ? and photo is not null').all(weekAgo) db.run('delete from messages where at < ?', [weekAgo]) old.forEach((row) => files.remove(row.photo)) }) ``` - `every` takes milliseconds or `'30s'`, `'5m'`, `'1h'`. For a time of day, `daily('03:00', fn)` runs once a day, in UTC. - Runs line up with the clock: an hourly job runs at the start of each hour, not an hour after the last deploy. - Each run writes `job cleanup ok 3ms`, or its error, to the logs, and refreshes live queries, so open screens drop the old messages right away. - A run is skipped while the previous one is still going, and only the active version runs jobs, so a deploy never runs one twice. - A job has no calling device: `caller()` does not work inside it. This is the whole backend. Everything from here is about shipping it. Next: [ship it](/docs/tutorial-ship.md). --- # 7. Ship it Source: https://arkapi.emincanozcan.com/docs/tutorial-ship.md The app works on your computer. Now put the backend online, so people can chat from anywhere. ## Deploy Create an account once per machine, then deploy: ```sh bunx arkapi signup --email you@example.com bunx arkapi deploy ``` Already have an account? Use `bunx arkapi login --email you@example.com` instead of signup. The first deploy creates your app and writes its id to `arkapi.config.ts`. Every deploy bundles the backend, uploads it, and regenerates the client so it points to the hosted URL. The host starts the new version next to the old one and switches only when it answers; open sockets move over. `app.db` and uploaded files stay where they are. Give the hosted backend its announcement token. Setting a variable restarts the backend: ```sh bunx arkapi env set ANNOUNCE_TOKEN=pick-a-long-random-token ``` ## Rebuild the app The backend URL and the types are compiled into the app, so build and install it again after a deploy, from DevEco Studio. Your local `app.db` stays on your computer: on the hosted service everyone starts without a name. The deploy prints the app's URL. Announcements now go there: ```sh curl -X POST https://arkapi.emincanozcan.com/apps//http/announce \ -H 'Authorization: Bearer pick-a-long-random-token' -d 'We are live' ``` ## Watch it run ```sh bunx arkapi open ``` The dashboard shows requests and errors per minute, every endpoint with its call count and timing, recent errors with their code and message, the tables in `app.db`, the logs, and the environment variables. To follow the logs in the terminal, including each `job cleanup ok` line: ```sh bunx arkapi logs -f ``` Every deploy is listed in the dashboard. If one goes wrong, **Roll back** switches to an earlier version. ## Keep going `bunx arkapi watch` points the client at your computer again; run `deploy` before you build an app for the hosted backend. When you change a function's signature, the app you built earlier still works for the calls that match, and the rest fail with a message to rebuild. You have used all of ArkAPI. The other chapters cover each part in more detail: [server functions](/docs/functions.md), [calling from ArkTS](/docs/client.md), [errors](/docs/errors.md), [files](/docs/files.md), [HTTP routes](/docs/http.md), [jobs](/docs/jobs.md), and [the hosted service's limits](/docs/limits.md). ## The whole app `entry/src/main/ets/pages/chat.api.ts`: ```ts import { Database } from 'bun:sqlite' import { ApiError, caller, event, every, files, online, type Routes } from 'arkapi/server' export interface Message { id: number name: string text: string photoUrl: string | null mine: boolean } interface MessageRow { id: number name: string text: string photo: string | null mine: number } const db = new Database('app.db') db.run('create table if not exists people (device text primary key, name text not null unique collate nocase)') db.run('create table if not exists messages (id integer primary key, device text not null, text text not null, photo text, at integer not null)') export function getName(): string { return nameOf(caller().deviceId) ?? '' } export function setName(name: string): string { const clean = name.trim() if (clean === '' || clean.length > 20) throw new ApiError('BAD_REQUEST', 'Use 1 to 20 characters') const { deviceId } = caller() if (db.query('select 1 from people where name = ? and device != ?').get(clean, deviceId)) { throw new ApiError('CONFLICT', `${clean} is taken`) } db.run('insert into people (device, name) values (?, ?) on conflict (device) do update set name = excluded.name', [deviceId, clean]) return clean } export function getMessages(): Message[] { const rows = db.query(` select m.id, coalesce(p.name, 'Announcement') as name, m.text, m.photo, m.device = ? as mine from messages m left join people p on p.device = m.device order by m.id desc limit 100`).all(caller().deviceId) return rows.reverse().map((row) => ({ id: row.id, name: row.name, text: row.text, mine: row.mine === 1, photoUrl: row.photo === null ? null : files.url(row.photo), })) } export function sendMessage(text: string): void { const clean = text.trim() if (clean === '') throw new ApiError('BAD_REQUEST', 'Write something first') save(me(), clean, null) } export function sendPhoto(fileId: string): void { if (!files.list().some((file) => file.id === fileId)) throw new ApiError('NOT_FOUND', 'Upload the photo first') save(me(), '', fileId) } export function countOnline(): number { return online().length } export interface Typing { name: string } export const typing = event() export function setTyping(): void { const device = me() typing.send(online().filter((other) => other !== device), { name: nameOf(device)! }) } export const routes: Routes = { 'POST /announce': async (req) => { const token = process.env.ANNOUNCE_TOKEN if (!token || req.headers.get('Authorization') !== `Bearer ${token}`) { throw new ApiError('UNAUTHORIZED', 'Wrong token') } save('announcement', await req.text(), null) return new Response('ok') }, } every('1h', function cleanup() { const weekAgo = Date.now() - 7 * 24 * 60 * 60 * 1000 const old = db.query<{ photo: string }, [number]>('select photo from messages where at < ? and photo is not null').all(weekAgo) db.run('delete from messages where at < ?', [weekAgo]) old.forEach((row) => files.remove(row.photo)) }) function me(): string { const { deviceId } = caller() if (!nameOf(deviceId)) throw new ApiError('UNAUTHORIZED', 'Pick a name first') return deviceId } function save(device: string, text: string, photo: string | null): void { db.run('insert into messages (device, text, photo, at) values (?, ?, ?, ?)', [device, text, photo, Date.now()]) } function nameOf(device: string): string | undefined { return db.query<{ name: string }, [string]>('select name from people where device = ?').get(device)?.name } ``` `entry/src/main/ets/pages/Index.ets`: ```ets import { AsyncValue, Listening, LiveValue } from 'arkapi' import { photoAccessHelper } from '@kit.MediaLibraryKit' import { countOnline, getMessages, getName, Message, onTyping, sendMessage, sendPhoto, setName, setTyping, Typing, uploadFile } from './chat.api' @Entry @Component struct Index { @State name: LiveValue = new LiveValue(getName) @State saving: AsyncValue = new AsyncValue() @State nameDraft: string = '' @State messages: LiveValue = new LiveValue(getMessages) @State online: LiveValue = new LiveValue(countOnline) @State sending: AsyncValue = new AsyncValue() @State draft: string = '' @State typist: string = '' private typing: Listening | null = null private typedAt: number = 0 private typistAt: number = 0 aboutToAppear(): void { this.typing = onTyping((event: Typing) => { this.typist = event.name this.typistAt = Date.now() setTimeout(() => { if (Date.now() - this.typistAt >= 3000) { this.typist = '' } }, 3000) }) } aboutToDisappear(): void { this.typing?.stop() } build() { Column({ space: 12 }) { if (this.name.data === null) { LoadingProgress().width(32).color('#8A8A99') } else if (this.name.data === '') { this.namePicker() } else { this.chat(this.name.data) } } .width('100%') .height('100%') .padding(16) .justifyContent(FlexAlign.Center) .backgroundColor('#101014') } @Builder namePicker() { Text('Pick a name').fontSize(22).fontColor('#FFFFFF') TextInput({ text: $$this.nameDraft, placeholder: 'Ada' }) .fontColor('#FFFFFF') .placeholderColor('#77778A') .backgroundColor('#22222A') Button('Join') .width('100%') .fontColor('#FFFFFF') .backgroundColor('#4F6BF5') .enabled(!this.saving.loading) .onClick(() => { this.saving.run(setName(this.nameDraft)) }) Text(this.nameError()).fontColor('#FF7B7B') } nameError(): string { if (this.saving.errorCode === 'CONFLICT') { return 'Someone already has that name' } if (this.saving.errorCode === 'BAD_REQUEST') { return 'Use 1 to 20 characters' } return this.saving.error ?? '' } @Builder chat(name: string) { Text(`${name} · ${this.online.data ?? 0} online`).fontSize(12).fontColor('#8A8A99') List({ space: 8 }) { ForEach(this.messages.data ?? [], (message: Message) => { ListItem() { this.bubble(message) } }, (message: Message) => `${message.id}`) } .width('100%') .layoutWeight(1) .stackFromEnd(true) Text(this.typist === '' ? '' : `${this.typist} is typing…`).fontSize(11).fontColor('#8A8A99') Row({ space: 8 }) { Button('+') .fontColor('#FFFFFF') .backgroundColor('#2A2A33') .enabled(!this.sending.loading) .onClick(() => { this.sending.run(this.pickPhoto()) }) TextInput({ text: $$this.draft, placeholder: 'Message' }) .layoutWeight(1) .fontColor('#FFFFFF') .placeholderColor('#77778A') .backgroundColor('#22222A') .onChange(() => this.typed()) .onSubmit(() => this.send()) Button('Send') .fontColor('#FFFFFF') .backgroundColor('#4F6BF5') .enabled(!this.sending.loading) .onClick(() => this.send()) } } @Builder bubble(message: Message) { Column({ space: 2 }) { Text(message.name).fontSize(11).fontColor('#8A8A99') if (message.photoUrl !== null) { Image(message.photoUrl).width(180).borderRadius(14) } else { Text(message.text) .fontSize(15) .fontColor('#FFFFFF') .padding({ left: 12, right: 12, top: 8, bottom: 8 }) .borderRadius(14) .backgroundColor(message.mine ? '#4F6BF5' : '#2A2A33') } } .width('100%') .alignItems(message.mine ? HorizontalAlign.End : HorizontalAlign.Start) } typed(): void { if (Date.now() - this.typedAt > 2000) { this.typedAt = Date.now() setTyping().catch(() => {}) } } async pickPhoto(): Promise { try { const options = new photoAccessHelper.PhotoSelectOptions() options.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE options.maxSelectNumber = 1 const picked = await new photoAccessHelper.PhotoViewPicker().select(options) if (picked.photoUris.length > 0) { const photo = await uploadFile(picked.photoUris[0]) await sendPhoto(photo.id) } } catch (error) { throw error as Error } } send(): void { this.sending.run(sendMessage(this.draft)).then(() => { if (this.sending.error === null) { this.draft = '' } }) } } ``` --- # Server functions Source: https://arkapi.emincanozcan.com/docs/functions.md Every exported function in a `*.api.ts` file is an endpoint. It runs on Bun, on the server, never on the device. ```ts import { Database } from 'bun:sqlite' import { ApiError, caller } from 'arkapi/server' interface Todo { id: number title: string } const db = new Database('app.db') db.run('create table if not exists todos (id integer primary key, device_id text, title text)') export function listTodos(): Todo[] { return db.query('select id, title from todos where device_id = ?').all(caller().deviceId) } export function addTodo(title: string): number { if (!title.trim()) throw new ApiError('BAD_REQUEST', 'Add a title') return Number(db.run('insert into todos (device_id, title) values (?, ?)', [caller().deviceId, title]).lastInsertRowid) } ``` ## Types that cross the wire `string`, `number`, `boolean`, arrays, interfaces, unions with `null`, `Record`, and `void` as a return type. Optional and default parameters work when they come last. `Date`, `Map`, classes, `any` and functions do not cross the wire; send timestamps as numbers and maps as records. Generate stops with `unsupported type` and names the parameter. Interfaces you define in the api file appear in the generated client with the same names, so the screen uses `Todo` too. ## Validation Before a function runs, the server checks the arguments against its signature. `addTodo(42)` fails with `400` and `args[0]: expected string, got number`, and `addTodo` never runs. ## Queries and mutations A function whose name starts with `get`, `list`, `find`, `search`, `count`, `has`, `is` or `load`, followed by an uppercase letter or the end of the name (`getMessages`, `isOnline`; not `getaway`), is a **query**. Everything else is a **mutation**. Queries can back [live data](/docs/client.md); after every mutation, live queries are re-run and changed results reach every screen. ## Who is calling `caller().deviceId` is a stable id of the calling device. Use it to keep data per device. It is sent by the app, so it identifies a device; it does not prove who the person is. `online()` lists the devices connected right now. ## State Keep state in SQLite. `app.db` lives in the app's own directory and survives deploys and restarts. Module-level variables start over on every deploy. Bun APIs, `fetch` and npm packages all work; packages are bundled on deploy. --- # Calling from ArkTS Source: https://arkapi.emincanozcan.com/docs/client.md Import functions and types from the generated client, using the same name as the `.api.ts` file: ```ts import { AsyncValue, LiveValue } from 'arkapi' import { addTodo, listTodos, Todo } from './todos.api' @Entry @Component struct TodosPage { @State todos: LiveValue = new LiveValue(listTodos) @State added: AsyncValue = new AsyncValue() @State draft: string = '' build() { Column({ space: 12 }) { ForEach(this.todos.data ?? [], (todo: Todo) => { Text(todo.title) }, (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 ?? '') } } } ``` ## Plain calls Every generated function returns a `Promise`. `await addTodo('Ship it')` works anywhere. A failed call rejects with `ApiError` from `arkapi`, which has a `code` and a `message`. ## AsyncValue for actions `run(promise)` sets `loading`, then `data`, or `error` and `errorCode`. Use it for buttons and forms. ## LiveValue for data on screen `new LiveValue(listTodos)` subscribes to a query over one shared connection. Its fields are `data` (null until the first value), `loaded`, `error`, `errorCode` and `connected`. `loaded` turns true with the first answer, so a screen can tell "still loading" from a query that returned `null`. The server re-runs live queries after every mutation, HTTP route, upload and job. It sends only results that changed; a growing list sends only its new items. So after `addTodo` there is nothing to refresh: every screen showing `listTodos`, on every device, updates. Nothing re-runs just because time passes. For text that depends on the clock, such as "5 minutes ago", return the timestamp and compute the text on the device. - For a query with arguments, use `new LiveValue(() => getTodo(id))`. The arguments are fixed; for others, create a new LiveValue. - When the connection drops, it reconnects by itself and keeps the last data. `connected` turns false after about three seconds. - `stop()` ends the subscription and keeps the last data. A screen that creates its own LiveValue calls it in `aboutToDisappear`. Keep LiveValues in `@State` and do not recreate them on every render. ## Events for moments 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 and send it to device ids: ```ts import { caller, event, online } from 'arkapi/server' export interface Typing { name: string } export const typing = event() export function setTyping(name: string): void { const me = caller().deviceId typing.send(online().filter((device) => device !== me), { name }) } ``` The generated client has a typed listener, `on` plus the event name. Start it when the screen appears and stop it when it goes away: ```ts import { Listening } from 'arkapi' import { onTyping, Typing } from './chat.api' // inside the @Component struct 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 that is offline or has the app closed when an event is sent never gets it, so anything it must see later belongs in the database and a LiveValue. The library declares the INTERNET permission itself. --- # Errors Source: https://arkapi.emincanozcan.com/docs/errors.md Throw `ApiError` with a code and a message: ```ts import { ApiError } from 'arkapi/server' export function setNickname(name: string): string { if (isTaken(name)) throw new ApiError('CONFLICT', 'That nickname is taken') return save(name) } ``` The code decides the HTTP status: | Code | Status | |---|---| | `BAD_REQUEST` | 400 | | `UNAUTHORIZED` | 401 | | `FORBIDDEN` | 403 | | `NOT_FOUND` | 404 | | `CONFLICT` | 409 | | `RATE_LIMITED` | 429 | | `INTERNAL` | 500 | Any other thrown error becomes `INTERNAL`, and its stack goes to the logs. On the device, `AsyncValue` and `LiveValue` expose the same code as `errorCode`. Check the code, not the message text: ```ts if (this.saved.errorCode === 'CONFLICT') { // ask for another nickname } ``` `NETWORK` means the device could not reach the backend. A successful result clears `error` and `errorCode`. --- # Photos and files Source: https://arkapi.emincanozcan.com/docs/files.md Every generated client has `uploadFile(uri)`. Pass a local file URI, for example from the photo picker. It returns a `FileRef` with `id` and `url`. ```ts import { photoAccessHelper } from '@kit.MediaLibraryKit' import { sendPhoto, uploadFile } from './chat.api' async function pickAndSend(): Promise { 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) } catch (e) { console.error(`Photo not sent: ${e}`) } } ``` Show it with `Image(photo.url)`. ## On the server The upload stores the bytes and nothing else. Your endpoint decides what the file belongs to: ```ts import { files } from 'arkapi/server' export async function sendPhoto(fileId: string): Promise { await files.read(fileId) // NOT_FOUND if there is no such upload return savePhotoMessage(fileId, files.url(fileId)) } ``` `files.write(data, type)` stores bytes or text and returns an id, `files.read(id)` returns the bytes, `files.list()` returns ids and sizes, and `files.remove(id)` deletes a file. ## Good to know - Files are at most 10 MB, survive deploys, and are public to anyone with the URL. - Uploading and using a file are two calls. Store ids in your database, and check ownership before removing a file. - `uploadFile` is reserved; do not name an endpoint that. --- # HTTP routes Source: https://arkapi.emincanozcan.com/docs/http.md Some callers are not your app: a payment provider, a form, a script. Export `routes` from any api file to accept plain HTTP requests. ```ts import { ApiError, type Routes } from 'arkapi/server' export const routes: Routes = { 'POST /announce': async (req) => { const token = process.env.ANNOUNCE_TOKEN if (!token || req.headers.get('Authorization') !== `Bearer ${token}`) { throw new ApiError('UNAUTHORIZED', 'Invalid token') } const text = await req.text() return Response.json({ accepted: text }) }, 'PUT /items/:id': async (req, params) => Response.json({ id: params.id }), } ``` Keys are `METHOD /path`; `:name` segments arrive in `params`. Handlers get the standard `Request` and return a `Response`. The URLs are `/http/announce` and `/http/items/123`, where `` is your app's URL (`BASE` in the generated client). A route refreshes live data like a mutation. ```sh curl -X POST https://arkapi.emincanozcan.com/apps//http/announce \ -H 'Authorization: Bearer your-token' -d 'Hello from outside' ``` Set secrets with `bunx arkapi env set ANNOUNCE_TOKEN=...`. Browser cookies are not forwarded; use the `Authorization` header. --- # Scheduled jobs Source: https://arkapi.emincanozcan.com/docs/jobs.md Register jobs at the top level of an api file: ```ts import { every, daily } from 'arkapi/server' every('1h', function cleanupHistory() { db.run('delete from messages where at < ?', [Date.now() - 7 * 86400000]) }) daily('02:30', async function nightlyDigest() { await fetch(process.env.DIGEST_URL!, { method: 'POST' }) }) ``` `every` takes milliseconds or `'30s'`, `'5m'`, `'1h'`. `daily` takes `HH:MM` in UTC. - A run is skipped while the previous one is still running. - Each run writes `job cleanupHistory ok 12ms`, or its error, to the logs, then refreshes live data. - Only the active version runs jobs, so a deploy never runs a job twice. - Jobs have no calling device; `caller()` does not work inside them. - Runs missed while the app was down are not repeated. ## Testing a job Put the logic in a plain module outside the `*.api.ts` files, with an explicit time, and call it from a Bun test. Exporting it from an api file would make it an endpoint. ```ts // retention.ts import { Database } from 'bun:sqlite' export function cleanupBefore(db: Database, cutoff: number): number { return db.run('DELETE FROM photos WHERE created_at < ?', [cutoff]).changes } ``` ```ts // photos.api.ts import { Database } from 'bun:sqlite' import { daily } from 'arkapi/server' import { cleanupBefore } from './retention' const db = new Database('app.db') daily('02:30', function cleanup() { cleanupBefore(db, Date.now() - 30 * 86400000) }) ``` ```ts // retention.test.ts: run with `bun test` import { expect, test } from 'bun:test' import { Database } from 'bun:sqlite' import { cleanupBefore } from './retention' test('removes photos older than the cutoff', () => { const db = new Database(':memory:') db.run('CREATE TABLE photos (id INTEGER PRIMARY KEY, created_at INTEGER)') db.run('INSERT INTO photos (created_at) VALUES (100), (300)') expect(cleanupBefore(db, 200)).toBe(1) }) ``` --- # Deploy and dashboard Source: https://arkapi.emincanozcan.com/docs/deploy.md ```sh bunx arkapi deploy ``` The first deploy creates the app and writes its id to `arkapi.config.ts`. Each deploy bundles the backend, uploads it and regenerates the client with the hosted URL. The host starts the new version next to the old one and switches traffic only when it answers. Open connections move over; a version that fails to start changes nothing. Build and install the app after a deploy that changed signatures: the URL and types are compiled into the client. An app built against an older backend still works for calls that match; others fail with a message that says to rebuild, and responses carry `X-ArkAPI-Stale: 1`. ## Dashboard `bunx arkapi open` opens the app's page: - requests and errors per minute, for the last hour; - endpoints with call counts and timings; - **Recent errors**, with endpoint, code and message; - **Data**: a read-only view of the tables in `app.db`; - **Logs**: everything the backend writes to the console (also `bunx arkapi logs -f`); - deployed versions with **Roll back**; - environment variables (also `bunx arkapi env set KEY=value`); - CPU, memory, disk and file usage against the [limits](/docs/limits.md). ## Local development `bunx arkapi watch` runs the backend on your machine and points the client at it. It regenerates the client and restarts when you save an api file. The emulator reaches it at `10.0.2.2`; for a phone on your network, set `deviceHost` in `arkapi.config.ts`. Run `deploy` again before building an app for the hosted backend. --- # Limits Source: https://arkapi.emincanozcan.com/docs/limits.md | Limit | Value | |---|---| | Apps per account | 3 | | Requests per app | 600 per minute | | Open connections per app | 50 | | Disk per app | 100 MB | | File size | 10 MB | | Bundle size | 5 MB | | Deploys | 30 per hour | | CPU and memory per app | 0.5 core, 256 MiB | | Response time | 5 s to start answering | A request is one call or one new LiveValue; pushed updates do not count. Over a limit, calls fail with `429` (`413` or `507` for files and deploys). A backend that runs out of memory is restarted; one that crashes five times in a minute is paused until the next deploy or rollback. The service is a development service on one machine. Before it opens to the public it needs a sandbox per app and a separate domain for apps. Device ids are not a login. --- # Test your backend Source: https://arkapi.emincanozcan.com/docs/testing.md Every endpoint is `POST /api/.` with the arguments as a JSON array. After a deploy, `` is `BASE` in the generated client. Under `watch`, use `http://localhost:3000` from this machine; `BASE` then holds the address the emulator or phone uses. If port 3000 is busy, `watch` takes the next free one and prints it. ```sh curl -X POST http://localhost:3000/api/pages.todos.addTodo \ -H 'X-ArkAPI-Device: test-device-1' -d '{"args": ["buy milk"]}' ``` The answer is the JSON result, or `{"error": "...", "code": "..."}` with the matching status. ## Live data in a test ```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.todos.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)`. To check that a change reaches every screen, open two sockets with different device ids, call a mutation, and expect both to receive the update. --- # Troubleshooting Source: https://arkapi.emincanozcan.com/docs/troubleshooting.md | You see | Do this | |---|---| | `unsupported type ...` from generate | Use [wire types](/docs/functions.md) in the signature. | | `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` | `bunx arkapi generate`, then rebuild and reinstall the app. | | `unknown endpoint` | Deploy after adding the function: `bunx arkapi deploy`. | | `LiveValue needs a query` | Back the LiveValue with a query (`get…`, `list…`); run mutations with `AsyncValue`. | | `errorCode === 'NETWORK'` | Check connectivity and the `BASE` URL in the generated client. | | `ArkAPI: not logged in` | `bunx arkapi login`. | | `bun add` installs an older ArkAPI, a new command is missing, or `no commit matching "v…" found` | Bun reuses its cached clone of the repository and does not fetch new commits or tags. Run `bun pm cache rm`, then `bun add` again. | | Build fails after generating | `ohpm install`, then build again. | | The app still calls an old backend | DevEco: Build → Clean Project, then build. | | A route returns 404 | Call `/http/` with the declared method, after a deploy. | | A job does not run | `bunx arkapi logs`; check the interval or the UTC time. | | `429` | The app passed 600 requests per minute; see [limits](/docs/limits.md). | | Backend crashes | `bunx arkapi logs`. The host restarts it; **Recent errors** shows what failed. | | `bun:sqlite` or `process` red in DevEco | Run `bunx arkapi init`, then reopen the project. | --- # API reference Source: https://arkapi.emincanozcan.com/docs/api.md ArkAPI code is imported from three places. Each one belongs to one kind of file. | File | Import from | Runs on | |---|---|---| | `x.api.ts` | `arkapi/server` | Bun, on the server | | `X.ets` screens | `arkapi` and the generated `./x.api` | The device | | `arkapi.config.ts` | `arkapi` | Your machine, for the CLI | ## Backend: `arkapi/server` ```ts import { ApiError, caller, online, event, files, every, daily, type Routes, } from 'arkapi/server' ``` | Name | What it does | |---|---| | `caller()` | `{ deviceId }` of the device making the current call. Not available in jobs. | | `online()` | Device ids with a live connection open right now. | | `event()` | Export it to create an event; `.send(deviceIds, payload)` pushes it to those devices. | | `ApiError` | `throw new ApiError(code, message)` fails a call with a code. See [Errors](/docs/errors.md). | | `files.write` | `write(data, contentType)` stores an `ArrayBuffer` or string and returns its id. | | `files.read(id)` | Returns the `ArrayBuffer`; `NOT_FOUND` if absent. | | `files.url(id)` | Public download URL. | | `files.list()` | `{ id, size }[]` | | `files.remove(id)` | Deletes the file. | | `every` | `every(interval, fn)` runs `fn` on an interval: milliseconds or `'30s'`, `'5m'`, `'1h'`. | | `daily` | `daily('HH:MM', fn)` runs `fn` once a day, in UTC. | | `Routes` | Type of `export const routes`: plain HTTP handlers. See [HTTP routes](/docs/http.md). | Types: `Caller`, `ErrorCode`. Also available in api files: `Database` from `bun:sqlite` for state, `process.env` for secrets, `fetch`, Bun APIs and npm packages. ## Rules for api files - Every exported function is an endpoint. Unexported functions stay private. - A name starting with `get`, `list`, `find`, `search`, `count`, `has`, `is` or `load`, followed by an uppercase letter or the end of the name, is a query. Everything else is a mutation. Only queries can back a `LiveValue`. - Arguments and return values: `string`, `number`, `boolean`, arrays, interfaces, `| null`, `Record`, and `void` as a return type. Not `any`, `unknown`, `Date`, `Map` or classes. - Reserved export names: `uploadFile`, `routes`, and `onX` when the file exports an event `x`. ## Screens: `arkapi` ```ts import { AsyncValue, LiveValue, ApiError, FileRef, Listening } from 'arkapi' ``` | Name | What it does | |---|---| | `LiveValue` | `new LiveValue(listTodos)`: data that stays current. Fields: `data`, `loaded`, `error`, `errorCode`, `connected`; `stop()` ends it. | | `AsyncValue` | For actions: `run(promise)` sets `loading`, then `data` or `error` and `errorCode`. | | `ApiError` | What a failed call rejects with: `code` and `message`. `NETWORK` is added on the device. | | `FileRef` | `{ id, url }`, returned by `uploadFile`. | | `Listening` | Returned by an event listener; call `stop()` when the screen goes away. | See [Calling from ArkTS](/docs/client.md). ## Screens: the generated `./x.api` ```ts import { listTodos, addTodo, Todo, uploadFile, onTyping } from './todo.api' ``` `arkapi generate`, `watch` and `deploy` write `x.api.ets` next to each `x.api.ts`. It exports: - every exported function, returning a `Promise`; - every interface those functions use; - `uploadFile(uri)`, returning a `FileRef`; - `on` + the name of every exported event, for example `onTyping(listener)`, returning a `Listening`. Never edit it; regenerate instead. ## Config: `arkapi` ```ts import type { Config } from 'arkapi' export const config: Config = {} ``` | Field | Default | Meaning | |---|---|---| | `app` | written by the first deploy | The hosted app id. | | `host` | `https://arkapi.emincanozcan.com` | ArkAPI host. | | `apiFiles` | `entry/src/main/ets/**/*.api.ts` | Where api files are. | | `port` | `3000` | Port of `watch`; if it is busy, `watch` takes the next free one. | | `deviceHost` | `10.0.2.2` | How the device reaches `watch`; the emulator default. Use your LAN IP for a phone. | ## CLI: `bunx arkapi` | Command | What it does | |---|---| | `init [--create] [--module entry] [--from ]` | Adds ArkAPI to the HarmonyOS project in this directory. `--create` first makes a blank phone project here (existing files are kept). `--from` installs the CLI from another spec, like a git URL. | | `signup`, `login [--email E --password P]`, `logout`, `whoami` | Account on the host. | | `watch` | Local server; stubs point at it while it runs. | | `deploy` | Bundles, uploads and points stubs at the hosted app. | | `generate [--local]` | Only regenerates the stubs. | | `logs [-f]` | Output of the deployed backend. | | `env [set KEY=VALUE…, unset KEY…]` | Environment variables of the deployed backend. | | `open` | Opens the app's dashboard. | | `build [--standalone]` | Bundles without deploying. | --- # The secret sauce Source: https://arkapi.emincanozcan.com/docs/secret-sauce.md You write a function, call it from a screen and run one command. Everything between those three steps is ArkAPI's job. These pages open it up: what happens, why it was built that way, and where to find it. Paths point into the `arkapi` repository unless they say *host*. ```diagram your project on the phone ──────────── ──────────── notes.api.ts ── generate ──► notes.api.ets ─► built into the app │ (typed client) │ │ deploy │ ▼ │ ┌─ ArkAPI host ────────────────────┐ │ │ your backend, bundled │◄── calls ──────┤ │ own process · own user │ │ │ SQLite · files · jobs │── live data ──►┘ └──────────────────────────────────┘ & events ``` ## The tricks | Page | The "wait, how?" moment | |---|---| | [From signature to client](/docs/sauce-types.md) | One import line means two different files, and your TypeScript types reach ArkTS without a schema file. | | [Live data without wiring](/docs/sauce-live.md) | A screen subscribes to a query without naming it, and updates without you saying what changed. | | [Teaching DevEco about Bun](/docs/sauce-deveco.md) | `bun:sqlite` autocompletes inside a HarmonyOS IDE that has never heard of Bun. | | [Deploys that keep the line open](/docs/sauce-deploys.md) | A deploy swaps the server under a live chat and nobody's screen notices. | | [Made for coding agents](/docs/sauce-agents.md) | The same docs URL answers a browser with HTML and an agent with Markdown. | ## The rules behind every trick - **One source of truth.** The function signature is the contract. Nothing is written twice, so nothing drifts. - **Fail on the laptop, not on the phone.** A wrong type stops `generate`; a renamed field stops the ArkTS build. - **Boring parts, clever seams.** SQLite, WebSockets, systemd and the TypeScript compiler do the heavy lifting. ArkAPI is mostly the glue between them. --- # From signature to client Source: https://arkapi.emincanozcan.com/docs/sauce-types.md ## One import, two files ```ts import { addNote } from './notes.api' ``` This one line means different things on each side. Bun loads `notes.api.ts`, your backend. ArkTS prefers `.ets` over `.ts`, so the device loads `notes.api.ets`, the client ArkAPI writes right next to it. The screen and the server share a name, never code. ```diagram pages/ ├── notes.api.ts ◄── Bun reads this (your backend) ├── notes.api.ets ◄── ArkTS reads this (generated client) └── Notes.ets import { addNote } from './notes.api' ``` ## Reading types with the real compiler `generate` opens every api file with [ts-morph](https://ts-morph.com), a wrapper around the TypeScript compiler API (`cli/src/generate.ts`). It asks the **type checker** for each exported function's parameters and return type. It never parses source text, so type aliases, interfaces imported from another file and inferred return types all work. Each type is then lowered to one ArkTS accepts (`cli/src/lower.ts`): - Interfaces defined in the api file are copied into the client. - Interfaces imported from another file are imported from that same file, so the screen and the server share one type, not two look-alikes. - `string | null`, arrays, `Record` and optional trailing parameters carry over. - `any`, `Date`, `Map`, classes and functions stop `generate`, naming the type and what to use instead (`Date` → epoch milliseconds). ## One analysis, three outputs ```diagram ┌─► notes.api.ets typed client for ArkTS notes.api.ts ─ ts-morph ┼─► arkapi-schema.json argument checks on the server └─► fingerprint "this app is out of date" ``` - **The client**: one async function per endpoint, one `onX` listener per event, the interfaces it needs and the backend address. - **The schema**: before your function runs, the server checks every argument against it. A wrong call never reaches your code; it gets `400 args[0].title: expected string, got number`, with the exact path. - **The fingerprint**: a hash of each file's schema, sent with every call. If you changed the backend but not the installed app, the server marks its answers and the device logs `this app was built against a different version of the backend`, once. ## Names do the configuration - **The endpoint id is the file path plus the name**: `pages/chat/chat.api.ts` → `pages.chat.chat.sendMessage` (`cli/src/namespace.ts`). No route table. - **The name decides the kind**: `get`, `list`, `find`, `search`, `count`, `has`, `is` or `load` followed by an uppercase letter is a query, anything else a mutation (`cli/src/query.ts`). `getMessages` can back a live screen; `getaway` cannot. - **An exported `event()` is named after its export** when the backend loads, the same way functions are, and the client gets `onTyping` for `typing`. ## The rename that breaks the build Because the client is generated from the signature, a backend change shows up where it matters: in the ArkTS compiler. ```diagram notes.api.ts notes.api.ets Notes.ets ──────────── ───────────── ───────── text ─► body ──gen──► interface Note { ──────► note.text body: string ✗ Property 'text' does } not exist on type 'Note' ``` With a hand-written client, the same rename compiles and every note shows up blank. --- # Live data without wiring Source: https://arkapi.emincanozcan.com/docs/sauce-live.md ## Subscribing to a function call ```ts @State messages: LiveValue = new LiveValue(() => listMessages(id)) ``` A LiveValue receives a function, not an endpoint name. So how does it know what to subscribe to? It runs that function once in **capture mode** (`runtime/arkapi/src/main/ets/runtime.ets`). While capture is on, the generated `listMessages` does not send a request: it records its endpoint and arguments and returns a promise that never settles. The LiveValue reads what was recorded and subscribes with it. ```diagram LiveValue generated client socket ───────── ──────────────── ────── capture on ──────► listMessages(7) records "chat.listMessages", [7] returns a promise that never settles capture off reads the record ──────────────────────────► {id: 3, name, args: [7]} ◄── {id: 3, data: [...]} ``` The subscription starts on the first read of `data` or `loaded`, not in the constructor. ArkUI only notices changes made after it has wrapped the object, and the constructor runs before that. ## One socket for the whole app Every LiveValue and every `onX` listener shares one WebSocket per backend. If it drops, the library reopens it every second and sends all open subscriptions again. A reconnect within about 3 seconds is invisible: `connected` stays true and the screen keeps its data. ## Updates without saying what changed You never tell ArkAPI which screens to refresh. After **anything that can change data** (a mutation, an HTTP route, an upload, a job, a device connecting or leaving), the server re-runs the open live queries (`cli/src/serve.ts`). ```diagram sendMessage() ┐ upload ├─► refresh ─► group by query + args ─► run once ─► diff ─► send job run │ ▲ │ device online ┘ └──── more changes meanwhile? ─────┘ one more round ``` What keeps that cheap: - **Batching.** Changes in the same event-loop turn share one refresh. Changes during a refresh cause exactly one more. - **Sharing.** Ten phones watching the same query with the same arguments cost one run, not ten. - **Knowing when not to share.** While a query runs, ArkAPI notes whether it called `caller()`. If it did, the result depends on who asks, so it runs per device. You never mark this; reading `caller()` is the mark. - **Silence.** A result that did not change is not sent. - **Diffs.** A list that only gained items at the end or lost items at the start is sent as `{drop, append}`. A chat with 100 messages that gets one more sends one message, not 101. ## Presence for free The server knows which devices have a socket open; `online()` returns them. Because a device connecting or leaving also triggers a refresh, an "online" dot computed from `online()` updates by itself. ## Events ride the same socket `event()` is for moments that are not state: someone is typing, a notification. `typing.send(devices, data)` pushes it only to those devices, over the socket they already have. Nothing is stored; a device that is offline misses it, by design. --- # Teaching DevEco about Bun Source: https://arkapi.emincanozcan.com/docs/sauce-deveco.md Your backend lives in `src/main/ets`, next to the screens. That is great for you and confusing for DevEco: it type-checks every `.ts` there with its own TypeScript 4.9, and it resolves packages from `oh_modules`, never `node_modules`. Out of the box, `import { Database } from 'bun:sqlite'` is a red line. ## A bridge through a relative path The ArkAPI library that DevEco installs ships a `server.d.ts`. DevEco resolves `arkapi/server` to it, and it points straight back at your project's real packages: ```diagram / ├── node_modules/ ◄──────────────────────────────┐ │ ├── arkapi/ the real server API │ │ └── bun-types/, @types/node/ │ 5 × ../ └── oh_modules/.ohpm//oh_modules/arkapi/ │ └── server.d.ts ─────────────────────────────┘ server.d.ts: /// ``` Five levels up from that file is always your project root, so a relative path reaches `node_modules` without DevEco ever searching it. The file also adds a few overloads TypeScript 4.9 needs for Bun's web and SQLite types. Only the editor reads it; Bun and the build use the npm package. If ohpm ever installs the library in a different layout, `generate` stops with `unsupported ohpm layout` instead of leaving you with silently broken types (`cli/src/editor-types.ts`). ## Editing your build file without breaking it The global Bun and Node declarations must be listed in `buildOption.arkOptions.types` of the module's `build-profile.json5`. That file is JSON5, with comments and your own settings. `init` does not rewrite it: it parses it with the TypeScript parser, finds the exact array, and inserts only the missing entries. Your comments, order and formatting stay. ## Hiding what you should not edit Every api file has a generated `*.api.ets` twin right next to it, and it has to sit there. A screen writes `import { addNote } from './notes.api'`: ArkTS resolves that line to `.ets` before `.ts`, and Bun resolves the same line to your `.ts` file ([From signature to client](/docs/sauce-types.md)). The twin cannot move to a hidden folder, so ArkAPI hides it from view instead. ```diagram On disk In DevEco's project tree pages/ pages/ ├── Notes.ets ├── Notes.ets ├── notes.api.ts └── notes.api.ts └── notes.api.ets (generated) ``` `init` writes three things into the DevEco project files (`cli/src/idea.ts`): - The module's `.iml` gets ``. It is one pattern, not a list of files, so an api file you add tomorrow is hidden too. If `modules.xml` or the `.iml` does not exist yet, `init` creates them, so the setting is in place before DevEco first opens the project. - `workspace.xml` gets "show excluded files" turned off. An existing `true` is switched to `false`; nothing else in the file changes. - Your root `.gitignore` stops ignoring `.idea`, so the exclude pattern reaches everyone who clones the project. `.idea/.gitignore` keeps the per-user files out: `/workspace.xml`, `/shelf/` and `/.deveco/`. That means the "show excluded files" switch stays each developer's own view setting. Running `init` again changes nothing, because each edit first checks whether it is already there. DevEco keeps these settings when it syncs. ## Command-click to the backend The optional DevEco plugin (`ide/deveco`) changes one thing: Command-click on `addNote(...)` in a screen opens the backend function in `notes.api.ts`, not the generated client. ```diagram Notes.ets notes.api.ets notes.api.ts addNote(this.draft) ──► (generated, skipped) ──► export function addNote(...) ⌘-click ``` It runs before Huawei's own handler and only redirects calls into generated ArkAPI clients. It finds the function by name in the live editor tree, so it works with unsaved edits, aliases and `async` functions; anything else falls through to the normal "go to declaration". --- # Deploys that keep the line open Source: https://arkapi.emincanozcan.com/docs/sauce-deploys.md ## One file to upload `deploy` writes a small entry file that imports every api file, registers each export under its endpoint id and starts the ArkAPI server. `Bun.build` turns that into one JavaScript file (`cli/src/bundle.ts`). Nothing changes until it builds and the upload succeeds: no app is created and the client is not pointed at the cloud before that. ## Swapping the server under a live chat The host (*host* `apps.ts`, `server.ts`) never stops the old version first: ```diagram time ─────────────────────────────────────────────────────► v3 ██████████████████████████████████▌ stopped v4 ░░ starting ░░░░█████████████████████████ ▲ │ v4 answers: traffic moves to v4 phone ══════════════════════════╪════════════════════════ socket (never closed) └ host attaches it to v4 and replays its subscriptions ``` 1. The bundle is stored as a new version and started on a free port, next to the running one. 2. Only when it answers does the host mark it active and send traffic to it. 3. Phones never connect to your backend directly; they connect to the host, which forwards. When the old version goes away, the host keeps the phone's socket open, connects it to the new version and **replays every subscription that phone had open**. The screen keeps updating as if nothing happened. 4. A version that fails to start changes nothing. Rollback re-activates an older stored version the same way. ## When the backend falls over - A version that exits is restarted after a second. Open sockets wait for it, up to about 6 seconds. - A request that has not started answering after 5 seconds gets `504`, and the stuck process is restarted. - Five exits within a minute pause the app instead of looping forever; the dashboard says why. Redeploy or roll back to resume. ## Jobs never run twice During a deploy two versions run side by side, and both loaded your `every('1h', ...)`. Each version knows its own id; before a job runs it checks the app's `.active` marker and skips if it is not the active one. A run still going when the next is due is skipped too. Intervals are aligned to the clock, so `every('1h')` fires on the hour, and live data refreshes after each run. ## Each app in its own box Apps are started through a small root-owned launcher (*host* `deploy/runner.ts`) as their own systemd units: - **Own user and directory.** The process can write only to its app directory (`ProtectSystem=strict`, `ReadWritePaths`), cannot gain privileges, has no capabilities and its own `/tmp`. - **Own budget.** 0.5 CPU core, 256 MiB memory, no swap, 64 tasks. One app spinning in a loop cannot slow down another. - **Clean environment.** Only `PORT`, `PATH`, `HOME`, the version id and your own variables. - **Logs that cannot fill the disk.** Each log is cut down to its last 256 KB once it passes 1 MB. --- # Made for coding agents Source: https://arkapi.emincanozcan.com/docs/sauce-agents.md Most ArkAPI apps are written with an agent in the loop. A few choices make that work. ## Less to write, less to get wrong There is no client to write, no URL to keep in sync and no JSON to parse. The measured result on the same notes app is on the [home page](/). Fewer lines means fewer tokens to generate and fewer places to make a mistake, and the mistakes that remain mostly fail the build instead of shipping. ## The guide lives in the project `init` writes the full guide into the project's `AGENTS.md`, between two markers, and adds `@AGENTS.md` to `CLAUDE.md`. Running `init` again replaces only the text between the markers, so the guide stays current and your own notes in the same file stay put. An agent opening the project reads the rules before it writes a line. ## Docs that answer in Markdown Every docs URL has two faces: ```diagram GET /docs/files Accept: text/html ──► the page you are reading GET /docs/files Accept: text/markdown ──► the same page as Markdown GET /docs/files.md ──► Markdown, always GET /llms.txt ──► index of every page for agents GET /llms-full.txt ──► all docs in one file ``` HTML pages also advertise their Markdown twin in a `Link` header, so an agent that fetched the HTML can find the cheaper version. ## Errors that say what to do - Wrong arguments: `args[0].title: expected string, got number`, with the path. - An endpoint name that collides with an event listener: `generate` names both and stops. - An app built against an older backend: the answer says to rebuild the app. - An unsupported type: `generate` names the type and what to use instead. An agent can fix each of these without guessing. ## Numbers that are checked The comparison on the home page comes from two real implementations of the same app in the `arkapi` repository, counted by a script. A host test reads that script's output and fails if the page shows different numbers. Canonical project guide: https://arkapi.emincanozcan.com/docs/guide.md