# In-page JavaScript API

Source: https://dropshelf.ai/docs/reference/javascript-api

Every method and object of dropshelf.js, the module a drop's page loads to know its visitor, store data, accept uploaded assets and read company data.

This page lists everything `dropshelf.js` offers a drop's own page: its methods, arguments, answers
and errors. For tasks and worked examples, read [Build on the drop platform](/docs/agents/platform).

## Loading the module [#loading-the-module]

Every drop host serves the module at `/_dropshelf/dropshelf.js` on the drop's own address. It is a
plain ES module with no dependencies. A page imports its default export from a module script:

```html
<script type="module">
  import dropshelf from '/_dropshelf/dropshelf.js';

  const me = await dropshelf.me();
  document.querySelector('h1').textContent = `Hi ${me.name}`;
</script>
```

The module also exports `DropshelfError` by name:

```js
import dropshelf, { DropshelfError } from '/_dropshelf/dropshelf.js';
```

The path `/_dropshelf/` is reserved on every drop host, and no deploy can place files under it. Every
request the module sends is same-origin and carries the visitor's own sign-in.

## The dropshelf object [#the-dropshelf-object]

The default export holds the following:

| Member | Arguments | Returns | Needs |
| --- | --- | --- | --- |
| `me(opts?)` | `opts.signal`, an `AbortSignal` | `Promise<Me>` | Nothing |
| `users(ids)` | An array of member ids | `Promise<Record<string, Person>>` | Nothing |
| `db.collection(name)` | A collection name | `Collection` | `platform.db.enabled` |
| `assets` | | The `AssetsApi` object | `platform.assets.enabled` |
| `limits(opts?)` | `opts.signal` | `Promise<Limits>` | Nothing |
| `connect(source)` | A connector source's name | `Connection` | `connectors.enabled` |

The Needs column names the instance setting an admin turns on, described in
[Turn on optional features](/docs/self-host/configure/features). While a feature is off, its routes
answer 404. A page checks the switches in `platform` on `GET /api/v1/instance`, or reads
`dropshelf.limits()`, which leaves out a feature that is off.

## Errors [#errors]

Every refusal rejects with a `DropshelfError`, which extends `Error`:

| Field | Type | Description |
| --- | --- | --- |
| `status` | number | The HTTP status, or `0` for a network error during an upload with progress. |
| `title` | string | A short title for the refusal. |
| `detail` | string | What to change, when there is something to change. Read it first. |
| `reason` | string | Set by `subscribe` and `sync` only: `unauthenticated` or `refused`. |
| `code` | string | Set by `connect(...).run` only: a short name for the refusal, listed under [Query errors](#query-errors). |
| `message` | string | The title and the detail together. |

An aborted call rejects with the signal's reason, as `fetch` does. A visitor who may not open the drop
gets a 404 on every route.

## Visitors [#visitors]

### me [#me]

`dropshelf.me()` answers the signed-in member opening the drop, or the owner of the token the request
carries:

| Field | Type | Description |
| --- | --- | --- |
| `id` | string | The member's id. |
| `email` | string | The member's email address. |
| `name` | string | The member's name. |
| `picture` | string | The identity provider's picture URL. Absent when there is none. |
| `avatarUrl` | string or null | The member's uploaded avatar, served by the drop host, or `null`. |
| `admin` | boolean | Whether the member is an admin on this instance. |
| `canEdit` | boolean | Whether the member may change what other members stored in this drop: its owner, an editor or an admin. |

The dashboard shows `avatarUrl ?? picture` as the member's picture. No other identity provider claims
are exposed.

`canEdit` is the same decision the drop host makes when a member changes or deletes another member's
document or asset. It is read when the page calls `me()`, and the drop host still decides every
change when it is made.

### users [#users]

`dropshelf.users(ids)` answers `{ name, picture?, avatarUrl }` for each id, keyed by id. Unknown ids
are left out. The module sends up to 100 ids per request and caches answers for the page's lifetime.

## Documents [#documents]

### Collection [#collection]

`dropshelf.db.collection(name)` returns a `Collection`. A name matches `[a-z0-9][a-z0-9_-]{0,63}`,
and an invalid name throws at once. A `Collection` has these methods:

| Method | Arguments | Returns |
| --- | --- | --- |
| `create(data, opts?)` | A JSON object; `opts.id` to choose the id; `opts.signal` | `Promise<Doc>`, the new document |
| `get(id, opts?)` | A document id; `opts.signal` | `Promise<Doc>` |
| `patch(id, merge, opts?)` | A document id; an object of fields to set, with `null` removing a field; `opts.signal` | `Promise<Doc>` |
| `put(id, data, opts?)` | A document id; the whole new document; `opts.signal` | `Promise<Doc>`, created or replaced |
| `delete(id, opts?)` | A document id; `opts.signal` | `Promise<null>` |
| `list(params?)` | `ListParams` | `Promise<{ items: Doc[], next: string \| null }>` |
| `all(params?)` | `ListParams` without `after` | `Promise<Doc[]>`, every page |
| `subscribe(opts?)` | `SubscribeOptions` | A function that stops the stream |
| `sync(opts)` | `SyncOptions` | A function that stops syncing |

### Doc [#doc]

A document is the JSON object you stored, plus six fields the server sets:

| Field | Type | Description |
| --- | --- | --- |
| `id` | string | Matches `[A-Za-z0-9][A-Za-z0-9_-]{0,127}`. |
| `rev` | number | Goes up with every write. |
| `createdBy` | string | The id of the member who created it. |
| `updatedBy` | string | The id of the member who wrote it last. |
| `createdAt` | string | RFC 3339 time, in UTC. |
| `updatedAt` | string | RFC 3339 time, in UTC. |

A body that names one of these six fields is refused with a 400. An id that is a member's id belongs
to that member: only they may create a document under it.

Anyone who can open the drop can read and create documents. Only a document's creator, the drop's
owner, an editor or an admin can change or delete it. In a shared collection anyone who can open the
drop can, except for a document under another member's own id. The drop's owner or an editor shares a
collection with `dropshelf db share <collection>`. The data belongs to the drop, not to a version,
so publishing or rolling back keeps it.

### ListParams [#listparams]

`list` and `all` take these parameters:

| Parameter | Type | Default | Description |
| --- | --- | --- | --- |
| `where` | array | none | Up to 8 conditions, each `[field, op, value]`. |
| `orderBy` | string | `createdAt` | A top-level field, `rev`, `createdAt` or `updatedAt`. |
| `order` | string | `asc` | `asc` or `desc`. |
| `limit` | number | `50` | 1 to 200 per page. `all` uses 200. |
| `after` | string | none | The previous page's `next`, with the same query. |
| `signal` | `AbortSignal` | none | Aborts the call. |

The ops are `eq`, `ne`, `gt`, `gte`, `lt`, `lte` and `in`. `in` takes an array of up to 100 values. A
condition names a top-level field or one of the six server fields, and a missing field equals `null`.

### subscribe [#subscribe]

`subscribe(opts)` opens a live stream of the collection's changes. The page shares one stream for
each collection and filter.

| Option | Type | Description |
| --- | --- | --- |
| `where` | array | Conditions, as for `list`. |
| `onReady` | `(seq) => void` | The stream is live. |
| `onChange` | `(doc) => void` | A document's current state after a write. |
| `onDelete` | `(id) => void` | A document was deleted. The id may be one the page never saw. |
| `onReset` | `() => void` | The stream lost track. List the collection again. |
| `onError` | `(err) => void` | An error. A `reason` of `unauthenticated` or `refused` ends the stream. |

The stream reconnects on its own after a dropped connection, with backoff up to 30 seconds.

### sync [#sync]

`sync(opts)` keeps a full copy of the collection, or of its filtered part, and calls `onChange` with
every document after each change.

| Option | Type | Description |
| --- | --- | --- |
| `where` | array | Conditions, as for `list`. |
| `orderBy` | string | The field that orders the documents `onChange` receives, as for `list`. A document that arrives later takes its place in that order. |
| `order` | string | `asc` or `desc`. |
| `onChange` | `(items) => void` | Required. The current documents. |
| `onError` | `(err) => void` | An error. Syncing stops after an `unauthenticated` or `refused` error. |

Each synced collection holds one connection. Browsers allow about six HTTP/1.1 connections per host,
so keep the number of streams small.

### Document errors [#document-errors]

A document call can reject with these statuses:

| Status | Meaning |
| --- | --- |
| 400 | An invalid collection name, id, filter, cursor or limit, malformed JSON, or a body naming a server field. |
| 403 | The visitor may not change this document, or the id is another member's. |
| 404 | No such document, or the instance has the drop database off. |
| 409 | `create` named an id that exists. |
| 413 | The document is larger than the instance allows, 64 KB by default. |
| 422 | The body is not a JSON object. |
| 429 | Too many writes this minute, 300 per member by default. Wait `Retry-After` seconds. |
| 501 | Live streams are not available on this server. |
| 503 | The store could not answer, or the server holds as many streams as it may. Retry after `Retry-After`. |
| 507 | A storage limit is full: documents or bytes per drop, or documents per member. |

The instance's document limits are under `platform.db.limits` on `GET /api/v1/instance`. The
[limits reference](/docs/reference/limits) lists the defaults.

## Uploaded assets [#uploaded-assets]

### AssetsApi [#assetsapi]

`dropshelf.assets` has these methods:

| Method | Arguments | Returns |
| --- | --- | --- |
| `upload(file, opts?)` | A `File` or `Blob`; `opts.name` to override its name; `opts.onProgress(fraction)`; `opts.signal` | `Promise<Asset>` |
| `list(params?)` | `params.createdBy`, a member id; `params.limit`, 1 to 100, default 50; `params.after`; `params.signal` | `Promise<{ items: Asset[], next: string \| null }>` |
| `all(params?)` | `params.createdBy`; `params.signal` | `Promise<Asset[]>`, every page |
| `info(id, opts?)` | An asset id; `opts.signal` | `Promise<Asset>` |
| `delete(id, opts?)` | An asset id; `opts.signal` | `Promise<null>` |
| `url(id)` | An asset id | The asset's relative URL, a string |

`upload` sends the file itself as the request body. It reads `dropshelf.limits()` first, so a file
that is too large, or a drop that is full, rejects before a byte is sent. It sends at most two
uploads at a time from one page, and later calls wait their turn.

### Asset [#asset]

An asset answers these fields:

| Field | Type | Description |
| --- | --- | --- |
| `id` | string | The asset's id. Keep it in a document to find the asset again. |
| `url` | string | A relative URL, which works on the drop's address and its version previews. |
| `name` | string | The file name. |
| `type` | string | The media type. |
| `size` | number | The size in bytes. |
| `createdBy` | string | The id of the member who uploaded it. |
| `createdAt` | string | RFC 3339 time, in UTC. |

Anyone who can open the drop can upload, list and open assets. The uploader, the drop's owner, an
editor or an admin can delete one. PNG, JPEG, GIF, WebP and AVIF images, audio and video open in the
page. Every other asset, SVG, HTML and PDF included, downloads when opened in a tab.

### Asset errors [#asset-errors]

An asset call can reject with these statuses:

| Status | Meaning |
| --- | --- |
| 0 | A network error during an upload with `onProgress`. |
| 400 | The body ended early, or an invalid limit or cursor. |
| 403 | The visitor may not delete this asset. |
| 404 | No such asset, or the instance has uploaded assets off. |
| 409 | The upload took longer than the server holds its place. Upload it again. |
| 413 | The file is larger than `maxFileBytes`, 25 MB by default. |
| 429 | Too many uploads at once, or too many uploads and deletes this minute, 30 per member by default. |
| 503 | The server is taking as many uploads as it can, or could not store the file. Retry after `Retry-After`. |
| 507 | The drop's assets would exceed `maxBytes`, 500 MB by default. |

## Limits [#limits]

`dropshelf.limits()` answers this drop's limits and usage. A feature that is off is left out:

| Field | Type | Description |
| --- | --- | --- |
| `db.maxBytes` | number | The most bytes of documents the drop may hold. |
| `db.usedBytes` | number | The bytes of documents the drop holds. |
| `assets.maxFileBytes` | number | The largest one asset may be. |
| `assets.maxBytes` | number | The most bytes of assets the drop may hold. |
| `assets.usedBytes` | number | The bytes of assets the drop holds. |

## Company data [#company-data]

### Connection [#connection]

`dropshelf.connect(source)` returns a `Connection` for a connector source. Its one method runs a
query the drop declares in `_dropshelf/queries.yaml`:

| Method | Arguments | Returns |
| --- | --- | --- |
| `run(name, params?, opts?)` | The query's name; an object of parameter values; `opts.signal` | `Promise<QueryResult>`, or `Promise<CallResult>` for a tool call |

Parameters travel in the query string. A value of `undefined` or `null` is left out, and the query's
default applies. The page never sends SQL or names a tool. [Company data in a drop](/docs/use/company-data)
explains the queries file, and [Use an MCP server's data in a drop](/docs/use/mcp-data) explains
tool calls.

### QueryResult [#queryresult]

A query answers these fields:

| Field | Type | Description |
| --- | --- | --- |
| `columns` | array | Each column as `{ name, type }`. |
| `rows` | array | Each row as an array of values, in column order. |
| `fetchedAt` | string | When the source was read, in RFC 3339. |
| `cachedUntil` | string | When the cached answer expires, in RFC 3339. |
| `objects()` | function | The rows as objects keyed by column name. |

Column types are `string`, `int`, `number`, `bool`, `date`, `timestamp`, `json` and `bytes`, which
arrives as base64. Every decimal, and every integer beyond JavaScript's safe range, arrives as a string
so no digit is lost.

### CallResult [#callresult]

A query that calls an MCP server's tool answers these fields:

| Field | Type | Description |
| --- | --- | --- |
| `result` | any | What the tool returned: its structured content, or its text, parsed when the text is JSON. |
| `access` | string | Whose access ran the call: `viewer` for the visitor's own, `none` for a server that asks nobody to sign in. |
| `fetchedAt` | string | When the server was called, in RFC 3339. |
| `cachedUntil` | string | When the cached answer expires, in RFC 3339. |
| `objects()` | function | The result, when it is a list of objects. Otherwise it throws a `TypeError`. |

In TypeScript, name the type on the call: `run<CallResult>('open_tickets')`.

### Query errors [#query-errors]

`run` can reject with these statuses:

| Status | Meaning |
| --- | --- |
| 400 | A parameter is missing or has the wrong type. `detail` names it. |
| 403 | The query may not run for visitors. `detail` says why. |
| 404 | This version of the drop has no such query, or the instance has connectors off. |
| 422 | The answer has too many rows or is too large. Aggregate or add a `LIMIT`. |
| 429 | The drop ran too many queries this minute, 120 by default. Retry after `Retry-After`. |
| 502 | The source failed. |
| 503 | The source is answering as many queries as it may. Retry after `Retry-After`. |
| 504 | The query ran longer than the source allows. |

The error's `code` field names the refusal, so a page can tell them apart without reading the text:

| Code | Status | Meaning |
| --- | --- | --- |
| `bad_parameter` | 400 | A parameter is missing or has the wrong type. |
| `pending` | 403 | The query waits for an admin. |
| `denied` | 403 | An admin denied the query. |
| `blocked` | 403 | The access the query runs with no longer covers it, or its source does not allow the tool it calls. |
| `connect_required` | 403 | The visitor is not connected to the MCP server the call runs on. |
| `reconnect_required` | 403 | The visitor must sign in to the MCP server again. |
| `too_large` | 422 | The answer has too many rows or is too large. |
| `rate_limited` | 429 | The drop ran too many queries this minute. |
| `source_failed` | 502 | The source could not be reached or failed. |
| `tool_error` | 502 | The MCP server's tool reported an error. |
| `busy` | 503 | The source is answering as many queries as it may. |
| `timeout` | 504 | The query ran longer than the source allows. |

## Rules the drop host enforces [#rules-the-drop-host-enforces]

- Requests under `/_dropshelf/` must come from the drop's own page. A request from another origin, a
  write whose `Origin` is not the drop's, or a write whose body is not `application/json` is refused.
  An asset upload, whose body is the file, is the exception.
- There is no CORS on `/_dropshelf/`, so another drop cannot call it.
- On a version preview, such as `v3--team-lunch`, only the drop's owner, editors and admins reach the
  platform. They read and write the same data as the live drop.
- A personal access token works on a drop host too, attributed to the token's owner.
