> ## 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.

# Accept uploads

> Pass file bytes to a mutation or receive an upload on a webhook.

## Upload from a client

Declare a File argument on an exposed mutation. The typed client takes a
`Blob` or `Uint8Array`. The handler gets the stored `File` point and can use
it in fields declared with `t.file`.

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

export const finance = label();
export const submitter = role({ clear: [finance] });
export const receipts = table({ file: t.file }, { label: finance });

export const attach = mutation({
  under: finance,
  allow: [submitter],
  args: {
    file: t.file({
      accept: ["image/jpeg", "image/png", "application/pdf"],
      maxBytes: 512 * 1024,
      lifetime: { days: 30 },
    }),
  },
}, (ctx, { file }) => ctx.insert(receipts, { file }));
```

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const attached = await client.mutate(app.receipts.attach, { file }, { once: "receipt-7" });
```

The host checks the byte count and detects the media type from the body.
The File commits together with the mutation at its commit label and in its
data world. If the handler refuses, the File is rolled back as well. Use
the same `once` when retrying the same upload.

For mutations at head, the TypeScript HTTP client stages a File passed as a
`Blob` larger than 512 KiB. On native installations, this publishes the
body through the Files provider. The client can stage additional File
arguments to fit the call and its recovery request within the HTTP limits.
The generated client identifies File parameters from their runtime schemas,
so it can stage a `Uint8Array` as well as a `Blob`. A path-only reference
only stages a `Blob`. Calls in branches use inline arguments.

The server accepts parts of up to 512 KiB and up to 64 MiB per staged
File, subject to the argument's `maxBytes` and the label's staging quota.
Each upload needs staging headroom for its retained parts or its largest
individual File, whichever is larger. Staged Files publish before inline Files.
Retry with the same file, principal, frame and `once` to start at the next
missing part. A completed call can replay its result when the same File
content is sent inline or in parts. A pinned client uses the original
receipt slot when the request matches an earlier successful upload. If the
outcome is unknown, the client first tries to resolve the original receipt.
Recovering an unresolved call before changing plans requires that call's
original request body. The client keeps unresolved bodies for up to 15
minutes within a bounded cache.
If a changed plan returns `Unknown` asking for an exact retry, supply the
original arguments, transfer plan, `once`, and `seen` if one was used.

The `bijectionAuth()`, `authkit()`, and `clerk()` adapters keep recovery
bound to the same reported caller across token renewal. A token callback or
custom token adapter without a stable caller identity scopes recovery to the
original token. Signed-out callers use the same client instance to retain
their anonymous session. After its write window closes, repeat the original
transfer plan to recover its receipt. If the status still has no receipt,
the outcome remains unknown. After the recovery window closes, the client
can no longer establish the old result or guarantee anonymous deduplication.

A recorded refusal permits another attempt with the same `once` and a fresh
receipt slot. Use a generated or runtime reference when sending Files
entirely inline so the client can identify File arguments. Uncommitted parts
expire 15 minutes after the first part.

## Receive a webhook

Declare a mutation whose source is
`route.post(path, verifier)`. When a request's body is not JSON, the host
stores it as a file at the reaction's label before the handler runs, and
the handler receives its `File` point as `request.file`. The handler checks the file
and keeps it in a fact. The file and the fact commit together: if the
handler refuses, nothing is kept.

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

export const finance = label();
export const submitter = role({ clear: [finance] });

export const receipts = table(
  { file: t.file, owner: t.principal, size: t.number, contentType: t.maybe(t.string) },
  { label: finance, index: [["owner"]] },
);

const ACCEPT = ["image/jpeg", "image/png", "application/pdf"];
const MAX_BYTES = 10 * 1024 * 1024;

/** POST /receipts: the body is the receipt's bytes. */
export const admit = mutation(
  {
    under: finance,
    allow: [submitter],
    on: route.post("/receipts", verifier.session()),
    refuses: { Unaccepted: null, TooLarge: null },
  },
  async (ctx, request) => {
    const file = request.file;
    if (file === null) return ctx.refuse("Unaccepted", "send the receipt's bytes as the body.");
    const meta = await ctx.get(file);
    if (meta === null) return ctx.refuse("Unaccepted", "upload the receipt again.");
    if (!ACCEPT.includes(meta.contentType ?? "")) return ctx.refuse("Unaccepted", "upload a JPEG, PNG or PDF.");
    if (meta.size > MAX_BYTES) return ctx.refuse("TooLarge", "a receipt is at most 10 MB.");
    return await ctx.insert(receipts, {
      file,
      owner: ctx.frame.as.id,
      size: meta.size,
      contentType: meta.contentType,
    });
  },
);
```

* `verifier.session()` admits a caller with a session token, sent as
  `Authorization: Bearer <token>`. `allow: [submitter]` then admits only a
  caller holding `submitter`. Use `verifier.bearer(secret)` for a sender
  that presents a shared secret, such as a renderer or a camera gateway.
* The route declares no `args`: the handler reads the `Request`
  (`method`, `path`, `headers`, `query`, `body`, `file`). A JSON body
  arrives as `request.body`, with `request.file` `null`.
* The path is relative to the app that holds the reaction: placed in a
  mounted app at `billing`, `/receipts` serves `/billing/receipts`.
  `route.path(admit)` answers the full path.
* A stored file that no committed fact keeps is retired by the host.

### Send a webhook body

A client posts the bytes to the route with `fetch`. The reaction's value,
here the new receipt's key, is the reply. A refusal answers with its code
and message.

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const response = await fetch(`${siteUrl}/receipts`, {
  method: "POST",
  headers: { authorization: `Bearer ${token}`, "content-type": file.type },
  body: file,
});
```

## Capacity

An upload is charged as it moves:

* **While it streams**, the bytes are charged to the `staging` quota of the
  uploader's commit label, in the main history even inside a branch. That
  charge returns when the upload completes, is released or expires.
* **When the commit stores the File**, the same commit returns the staging
  charge and charges the File to the place it is stored at (`fileBytes`,
  `fileCount`). No instant holds the bytes twice or not at all.
  * Into a label the uploader clears, a full account refuses `Limit`.
  * Into a label above the uploader's, the host never reads that label's
    account. It writes an exact debit there and spends the uploader's
    `reach` flow.
* **After the File is retired or erased**, bytes a legal hold or provider
  cleanup still keeps sit in the host's custody reserve. They never refuse
  your writes.

Set a label's quotas with `label({ quotas: { staging, fileBytes, fileCount } })`.

## Test a webhook upload

`k.route` takes the file in place of a body, and the test kernel stores it at
ingress as the host does:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
const k = await kernel(app);
const stored = await k.route(app.receipts, {
  as: "person:alice",
  file: { bytes: new Uint8Array([0x25, 0x50, 0x44, 0x46]), contentType: "application/pdf" },
});
expect(stored.ok).toBe(true);
```

See [`k.route`](https://docs.bijection.com/development/testing/test-library#routes-k-route).


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