> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bijection.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Create your first app

> Create a live notes app, refuse a bad note, call it from the CLI, test it, protect it and deploy it

[Install the CLI](https://docs.bijection.com/start/install.md), then create the starter:

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
bijection create my-app
```

`create` writes the notes starter and installs its frontend packages with the
package manager on your `PATH`. It ends with the one command to run next:

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
cd my-app && bijection dev
```

`bijection dev` starts a local deployment, with no account, and serves the
page. Open the app URL it prints, add a note, and open a second tab: the list
updates live in both. Anyone who opens the page reads and writes the notes,
because the notes table has no label and its functions allow `role.anyone`.
Each note lasts a day.

A backend-only project uses `bijection create my-backend --template bare`; the
CLI manages its backend toolchain.

## Find the code

| Path | What it holds |
| - | - |
| `bijection/notes.ts` | The `items` table, the query `recentNotes` and the mutation `add` |
| `bijection/app.ts` | The app tree: every name in the app is a path in it |
| `bijection/bijection.lock` | Every path a caller can reach, written by `bijection dev` and `bijection check --write-lock` |
| `apps/main/src/main.tsx` | The React page, with a client typed from the tree |
| `.bijection/_generated/client.ts` | Browser binding generated from the app's contract |
| `tests/notes.test.ts` | A test on the real kernel |
| `bijection.json` | Project and frontend configuration |

`bijection/notes.ts` declares the table, query and mutation below.

```ts bijection/notes.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { mutation, query, role, t, table } from "@bijectionhq/bijection";

/** The notes. A table without a label is public: anyone who opens the app
 * reads it, and only `add` writes it from application code. Its
 * name is its path in the app tree: `notes.items`. */
export const items = table(
  { text: t.string, written: t.accepted() },
  { lifetime: { hours: 24 }, index: [["written"]], writers: (): readonly object[] => [add] },
);

/** The latest 20 notes, newest first. */
export const recentNotes = query({ allow: [role.anyone] }, (ctx) =>
  ctx.list(items.by("written").descending().first(20)),
);

/** Add a note. Answers its key. */
export const add = mutation(
  { allow: [role.anyone], args: { text: t.string } },
  (ctx, { text }) => ctx.insert(items, { text }),
);
```

* A **query** reads and commits nothing. A **mutation** runs as one
  transaction: its writes and its tasks commit together or not at all.
* `items.by("written").descending().first(20)` is a bounded **selection**:
  the latest 20, and `ctx.list` reads all of it. `.atMost(n)` reads all of a
  small selection, or refuses when it holds more. A sum or count over many
  facts is a declared `total`, read with `ctx.get`. The table's `index` serves
  the order; a selection that no index serves is an error naming the index
  to add.
* `ctx.insert(items, fact)` mints the key and returns it.
* The table's `lifetime: { hours: 24 }` makes each note expire one day
  after acceptance.

`bijection/app.ts` places the module in the app tree:

```ts bijection/app.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { app } from "@bijectionhq/bijection";
import * as notes from "./notes";

// The app tree: every name is a path in it (`notes.recentNotes`, `notes.items`).
// A function with `allow` is exposed at its path; one without is internal
// (only this app's own code reaches it).
// `bijection dev` and `bijection check --write-lock` derive bijection.lock from it.
export default app({ notes });
```

No declaration takes a string name. The table is `notes.items` and the
functions are `notes.recentNotes` and `notes.add`. A function with
`allow` is **exposed** at its path. A function without `allow` is
**internal**: only the app's own code reaches it.

## Read the page

The page imports `app` and `connect` from the generated browser client.
`bijection dev` writes it from the app's exposed schemas and contract digests
before starting the frontend. A renamed function or changed argument type
shows up in the frontend’s type checking.

```tsx apps/main/src/main.tsx theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { useState, type FormEvent } from "react";
import { createRoot } from "react-dom/client";
import { app, connect } from "../../../.bijection/_generated/client";
import { Bijection, useMutation, useWatch } from "@bijectionhq/bijection/react";
import "./style.css";

const client = connect(import.meta.env.VITE_BIJECTION_URL);

function Notes() {
  // `undefined` while loading, then the latest notes as a `Result`; it
  // updates live.
  const listed = useWatch(app.notes.recentNotes);
  const add = useMutation(app.notes.add);
  const [text, setText] = useState("");
  const [error, setError] = useState<string>();
  async function submit(event: FormEvent) {
    event.preventDefault();
    // A mutation answers a Result: `{ ok: true, value }`, or
    // `{ ok: false, code, message }` for a `ctx.refuse(code, message)` or
    // a host refusal.
    const added = await add({ text });
    setError(added.ok ? undefined : added.message);
    if (added.ok) setText("");
  }
  return (
    <main>
      <h1>Notes</h1>
      <p>Each note lasts a day.</p>
      <form onSubmit={(event) => void submit(event)}>
        <input aria-label="Note" value={text} onChange={(event) => setText(event.target.value)} />
        <button type="submit" disabled={add.pending}>Add note</button>
      </form>
      {error ? <p role="alert">{error}</p> : null}
      {listed === undefined ? (
        <p>Loading…</p>
      ) : !listed.ok ? (
        // `listed.code` is a host code: `Disallowed` once the notes are
        // protected and this caller holds no role that reads them.
        <p role="alert">{listed.code === "Disallowed" ? "Sign in as a member to read the notes." : listed.message}</p>
      ) : (
        <ul>
          {listed.value.map((note) => (
            <li key={note.id}>{note.text}</li>
          ))}
        </ul>
      )}
    </main>
  );
}

createRoot(document.getElementById("root")!).render(
  <Bijection client={client}>
    <Notes />
  </Bijection>,
);
```

`useWatch` holds a live watch of the query and answers a `Result`, or
`undefined` while it loads. `useMutation` answers a function that runs the
mutation and returns its `Result`. Every call ends as `{ ok: true, value }` or
`{ ok: false, code, message }`. The code is an app code the function declares
in `refuses`, or a host code such as `Disallowed` or `Absent`. An expected
refusal never throws. The `<Bijection client={client}>` provider at the root
of the page gives every hook its client. [React](https://docs.bijection.com/clients/react) covers the
hooks in full.

## Refuse an empty note

In `bijection/notes.ts`, make
`if (!text.trim()) return ctx.refuse("EmptyNote", "Write something.");` the
first line of `add`'s handler. Your editor answers
`Undeclared: add EmptyNote to this function's refuses`, and `bijection dev`,
which checks the source on every save, prints the same sentence at its
`path:line:col`. Declare the code beside `args`:

```ts bijection/notes.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
export const add = mutation(
  { allow: [role.anyone], args: { text: t.string }, refuses: { EmptyNote: null } },
  (ctx, { text }) => {
    if (!text.trim()) return ctx.refuse("EmptyNote", "Write something.");
    return ctx.insert(items, { text });
  },
);
```

`ctx.refuse(code, message)` ends the transaction with an app code, and the
caller receives it as a `Result`. In the page, `added.code` is now
`"EmptyNote"` or a host code, and only a host code carries a `reason`, its
precise cause.

## Call it from the terminal

The CLI speaks the same verbs at the same paths:

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
bijection query notes.recentNotes
bijection mutate notes.add text=Hello
bijection trial notes.add text=Draft    # what it would write; commits nothing
bijection list notes.items --first 5
```

`trial` runs a call in a discarded world and reports its result, writes and
tasks. Every verb takes `--as` (on whose behalf), `--under` (the label),
`--in` (a version or branch) and `--at` (the valid instant). `mutate` prints
the `once` it sent: if the reply is lost, run the command it prints, which
asks again with the same `once`.

## Test it

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
npm test
```

`vitest.config.ts` is `defineConfig(vitestPreset())`, and the test needs
nothing else:

```ts tests/notes.test.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { api as callableApi } from "@bijectionhq/bijection/client";
import { expect, it } from "vitest";
import { kernel } from "@bijectionhq/bijection/test";
import app from "../bijection/app";

it("expires notes a day after acceptance", async () => {
  const k = kernel(app);
  const alice = k.as("person:alice");

  const notes = callableApi<typeof app>().notes;
  const added = await alice.mutate(notes.add, { text: "Hello" });
  expect(added.ok).toBe(true);
  expect(await alice.query(notes.recentNotes, {})).toMatchObject({
    ok: true, value: [{ text: "Hello" }],
  });

  await k.advance({ days: 1 });
  expect(await alice.query(notes.recentNotes, {})).toEqual({ ok: true, value: [] });
});
```

`kernel(app)` runs the real kernel in memory, with one installation of the
app tree. `k.as("person:alice")` is the client a browser signed in as alice gets,
and its calls answer a `Result`. The kernel itself acts as the installation
and holds the clock. `k.advance` moves past the table lifetime so the next
read returns no notes. [Test library](https://docs.bijection.com/development/testing/test-library.md) covers
the rest.

## Protect the notes

To let only members read and write the notes, give `bijection/notes.ts` a
label and a role, label the table and run every function under the label:

```ts bijection/notes.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { label, mutation, query, role, t, table } from "@bijectionhq/bijection";

/** Who reads and writes the notes: a caller who holds `member`. */
export const team = label();
export const member = role({ clear: [team] });

export const items = table({ text: t.string, written: t.accepted() }, { label: team, lifetime: { hours: 24 } });

/** One page in fact-id order. Each note expires a day after it is written. */
export const recentNotes = query(
  { under: team, allow: [member], args: { size: t.number, cursor: t.cursor } },
  (ctx, { size, cursor }) => ctx.page(items.byId(), { size, cursor }),
);

export const add = mutation(
  { under: team, allow: [member], args: { text: t.string }, refuses: { EmptyNote: null } },
  (ctx, { text }) => {
    if (!text.trim()) return ctx.refuse("EmptyNote", "Write something.");
    return ctx.insert(items, { text });
  },
);
```

A labelled fact shows nothing to a caller whose role does not clear its label.
`under: team` is the label a function runs under, so it may read and write
the notes; `allow: [member]` lets in only callers who hold `member`.

A labelled table is [protected](https://docs.bijection.com/database/protected-tables.md).
The `written` field is stamped at acceptance, so the same newest-first
selection works after the table gets a label.

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
bijection check --write-lock
```

`bijection/bijection.lock` lists every path with its `allow` and `under`, the
grave acts it can perform and the guards on it. The diff names the label on
the table, the new role, and `under` and `allow` on each path, and nothing
else. Commit it: `bijection check` and `bijection deploy` refuse a lock that
no longer matches the source. The lock is the reviewable answer to "what can
a caller reach?"

No one holds `member` yet, so the page now answers `Disallowed`.
[Protect an app](https://docs.bijection.com/access/quickstart.md) adds the membership library, which
grants the first owner and lets owners invite members, and signs the page in.
For the local browser, select the same person you grant `member` to using
`bijection dev --as person:alice` and the
[development client adapter](https://docs.bijection.com/clients/react/configuration.md#use-a-local-development-principal).

## Deploy the app

Sign in to your Bijection account, then publish the checked source to a
deployment:

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
bijection login
bijection deploy --installation my-app:prod
```

An installation is named `<project>:<name>`. Deploy installs exactly what the
committed `bijection/bijection.lock` states, prints the table changes it
makes, and refuses a stale lock. The command prints a retained request handle.
If its reply is interrupted, inspect or resume that same request:

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
bijection status request get <request>
bijection status request resume <request>
```

[Installations](https://docs.bijection.com/operate/installations) covers configuration and deploys. To try
code and data changes in a writable world, use a [branch](https://docs.bijection.com/branches).

## Continue

The [customer workflow tutorial](https://docs.bijection.com/start/tutorial) adds a feed from an external
service, labelled customer data, roles and a rename sent to that service as a
task whose result the app records.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.