# Dict

> Dicts: a key-value store for small state that code and agents share.

```python
seen = noclick.Dict.from_name("processed-orders", create_if_missing=True)
if "o_1841" not in seen:
    seen["o_1841"] = {"status": "refunded"}
print(seen.increment("refunds-today"))
```

Keys are strings and values are JSON (a dict, list, string, number, bool or
`None`), never pickled, so a value your Python code writes reads the same from
TypeScript, an agent or the console. A dict works like Python's own: `d[key]`,
`d[key] = value`, `key in d`, `del d[key]`, `len(d)` and iterating its
keys, plus expiry (`ttl_s`), locks (`put_if_absent`) and atomic counters
(`increment`). Each of those reads or writes the API, so the `.aio` forms of
`get`, `put` and `pop` are how async code does the same.

## Dict

```typescript
class Dict
```

A key-value store: string keys, JSON values, optional expiry per key. `get`, `put`, `has`,
`remove` and `size` are what Python writes as `d[key]`, `d[key] = value`, `key in d`,
`del d[key]` and `len(d)`; each is a call to the API, so two processes see each other's
writes at once. `Dict.fromName("processed-orders", { createIfMissing: true })` is lazy.
There's no `Dict.get(id)`, since `get` reads a key: `Dict.fromId(id).hydrate()` loads one.

| Attribute | Type | Description |
| --- | --- | --- |
| `id` | `string` |  |
| `name` | `string` |  |
| `keyCount` | `number | null` | How many keys it holds, as of the last load; `size()` reads it fresh. |
| `sizeBytes` | `number | null` | The size of its keys and values as JSON. |
| `usedBy` | `UsedBy[]` | The apps that bind it. |
| `region` | `RegionName | null` | The region it keeps its data in, fixed when it was created. |
| `userId` | `string | null` |  |
| `createdAt` | `Date | null` |  |
| `consoleUrl` | `string | null` | This dict in the developer console (null off the hosted API). |

Types:

```typescript
/** An app that binds a database or a bucket, under its `binding` name. */
interface UsedBy {
  kind: string;
  id: string;
  name: string;
  binding: string | null;
}

type RegionName = "us-east" | "us-west" | "eu" | "ap" | "in";
```

### Dict.create

```typescript
static create(
  name: string,
  options?: CallOptions & PlacementOptions & AllowExisting,
): Promise<Dict>
```

Create a dict, unique by name per user (a taken name throws `Conflict` with `existingId`, or with
`allowExisting: true` returns the dict already there, as it is). `region` keeps its keys there for
good: `us-east` only for now (another, or a default elsewhere, throws `InvalidRequest`).

Parameters:

- `name` (`string`, required)
- `options.region` (`RegionName`): Where it runs or keeps its data (`regions()`); omitted, your account's default region.
- `options.allowExisting` (`boolean`): A taken name returns the object already there, as it is: nothing about it changes.
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: The new dict, empty.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

type RegionName = "us-east" | "us-west" | "eu" | "ap" | "in";
```

### Dict.fromName

```typescript
static fromName(
  name: string,
  options?: CallOptions & PlacementOptions & { createIfMissing?: boolean },
): Dict
```

A lazy reference to the dict called `name`; with `createIfMissing` it's created on first use.

Parameters:

- `name` (`string`, required)
- `options.createIfMissing` (`boolean`)
- `options.region` (`RegionName`): Where it runs or keeps its data (`regions()`); omitted, your account's default region.
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: A dict that loads (or is created) on first use. Nothing is sent yet.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

type RegionName = "us-east" | "us-west" | "eu" | "ap" | "in";
```

### Dict.fromId

```typescript
static fromId(dictId: string, options?: CallOptions): Dict
```

A lazy reference by id; `await Dict.fromId(id).hydrate()` loads it now.

Parameters:

- `dictId` (`string`, required)
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.

Returns: A dict that loads the first time you use it. Nothing is sent yet.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

### Dict.list

```typescript
static list(options?: ReadOptions & { limit?: number }): Promise<Dict[]>
```

The current user's dicts (or those `userFilter` covers), newest first.

Parameters:

- `options.limit` (`number`): Return at most this many.
- `options.userFilter` (`UserFilter`): Which users the read covers (`user_id` query), instead of acting as one (`user`).
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: Every matching dict, newest first, fetched page by page.

Types:

```typescript
/**
 * Which users a read covers: `ALL_USERS`, `NO_USER`, a `User` or your id for one. Sent as the
 * `user_id` query parameter, never as the `NoClick-User` header, so it filters without acting as the user.
 */
type UserFilter = typeof ALL_USERS | typeof NO_USER | UserRef;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;
```

### Dict.listPage

```typescript
static listPage(options?: ReadOptions & PageOptions): Promise<Page<Dict>>
```

One page of dicts; pass `nextCursor` back as `cursor`.

Parameters:

- `options.cursor` (`string | null`): The `next_cursor` of the page before; omit it for the first page.
- `options.limit` (`number`): Return at most this many.
- `options.userFilter` (`UserFilter`): Which users the read covers (`user_id` query), instead of acting as one (`user`).
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: A page whose `data` holds the dicts and whose `next_cursor` is `None` on the last page.

Types:

```typescript
/**
 * Which users a read covers: `ALL_USERS`, `NO_USER`, a `User` or your id for one. Sent as the
 * `user_id` query parameter, never as the `NoClick-User` header, so it filters without acting as the user.
 */
type UserFilter = typeof ALL_USERS | typeof NO_USER | UserRef;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;
```

### Dict.get

```typescript
get(key: string): Promise<T | undefined>
```

A key's value, or `undefined` when it's missing or expired (a stored `null` reads as `null`).

Parameters:

- `key` (`string`, required)

Returns: The value as the JSON it was stored as, or `default`.

### Dict.keys

```typescript
keys(options?: DictListOptions & { limit?: number }): Promise<string[]>
```

The keys in order (or those starting with `prefix`), fetched page by page.

Parameters:

- `options.limit` (`number`): Return at most this many.
- `options.prefix` (`string`)

Returns: Every matching key (or the first `limit`), fetched page by page.

### Dict.items

```typescript
items(options?: DictListOptions & { limit?: number }): Promise<DictItem[]>
```

The keys and their values, in key order (or those starting with `prefix`), with each key's expiry.

Parameters:

- `options.limit` (`number`): Return at most this many.
- `options.prefix` (`string`)

Returns: A `DictItem` per key (or for the first `limit`): it unpacks as `key, value` and
also carries `expires_at`, `updated_at` and `size_bytes`.

### Dict.itemsPage

```typescript
itemsPage(options?: DictListOptions & PageOptions): Promise<Page<DictItem>>
```

One page of items in key order; pass `nextCursor` back as `cursor`.

Parameters:

- `options.cursor` (`string | null`): The `next_cursor` of the page before; omit it for the first page.
- `options.limit` (`number`): Return at most this many.
- `options.prefix` (`string`)

Returns: A page whose `data` holds `DictItem`s and whose `next_cursor` is `None` on the last page.

### Dict.put

```typescript
put(key: string, value: unknown, options?: DictWriteOptions): Promise<void>
```

Write a key. With `ttlS` it expires then; without, it stays until removed (and loses any expiry).

Parameters:

- `key` (`string`, required)
- `value` (`unknown`, required)
- `options.ttlS` (`number`)

### Dict.putIfAbsent

```typescript
putIfAbsent(
  key: string,
  value: unknown,
  options?: DictWriteOptions,
): Promise<boolean>
```

Write a key only if it isn't there, atomically: of any number of callers racing, exactly
one wins. A lock (with `ttlS`, so a crashed holder's lock frees itself) or a run-once check.
Whether this call wrote it.

Parameters:

- `key` (`string`, required)
- `value` (`unknown`, required)
- `options.ttlS` (`number`)

Returns: `True` if this call wrote it, `False` if the key was already there.

### Dict.increment

```typescript
increment(
  key: string,
  options?: DictWriteOptions & { by?: number },
): Promise<number>
```

Add `by` (default 1, may be negative) to a counter, atomically; a missing key starts at 0.
`ttlS` sets its expiry only when this call creates it. The value after the increment.

Parameters:

- `key` (`string`, required)
- `options.ttlS` (`number`)
- `options.by` (`number`, default `1`)

Returns: The counter's value after this increment.

### Dict.update

```typescript
update(
  items: Readonly<Record<string, unknown>> | ReadonlyMap<string, unknown>,
  options?: DictWriteOptions,
): Promise<void>
```

Write up to 1,000 keys in one call, all or none; `ttlS` applies to each.

Parameters:

- `items` (`Readonly<Record<string, unknown>> | ReadonlyMap<string, unknown>`, required)
- `options.ttlS` (`number`)

### Dict.pop

```typescript
pop(key: string): Promise<T | undefined>
```

Remove a key and return its value, or `undefined` if it wasn't there.

Parameters:

- `key` (`string`, required)

Returns: The value the key held, or `default`.

### Dict.remove

```typescript
remove(key: string): Promise<boolean>
```

Remove a key; whether it was there. (`delete()` deletes the whole dict.)

Parameters:

- `key` (`string`, required)

Returns: Whether the key was there to remove.

### Dict.clear

```typescript
clear(): Promise<Operation>
```

Remove every key; the dict stays, empty. Its operation's `undo()` puts back what it removed.

Returns: The clear's operation: `undo()` puts back every key it removed that nothing has written since.

### Dict.history

```typescript
history(key?: string, options?: { limit?: number }): Promise<DictChange[]>
```

Its writes of the last 30 days, newest first, each with the value it replaced; `key` keeps one key's.

Parameters:

- `key` (`string`)
- `options.limit` (`number`): Return at most this many.

Returns: Each change.

### Dict.restoreChange

```typescript
restoreChange(change: DictChange | string): Promise<void>
```

Put the key back as `change` found it: the value it replaced, or gone, when the change created
the key. A value that has expired since throws `Conflict`.

Parameters:

- `change` (`DictChange | string`, required)

### Dict.export

```typescript
export(): Promise<Operation<ExportBundle>>
```

Export every key as it stands at one moment, as JSON Lines: one `{"key", "value", "expires_at"}`
per line, in key order. `wait()` resolves to an `ExportBundle`: a zip at `url` holding the file.

Returns: An operation whose `wait()` gives an `ExportBundle`: a zip at `url` holding the file.

### Dict.delete

```typescript
delete(): Promise<TrashItem>
```

Delete the dict and every key in it: it goes to the trash, restorable for 30 days. One an app
binds goes to the trash too: the app keeps its binding, reaching nothing until you restore the
dict. Returns its `TrashItem`: `restore()` puts it back, keys and all.

Returns: Its `TrashItem`: `restore()` puts it back, keys and all.

### Dict.has

```typescript
has(key: string): Promise<boolean>
```

Whether the key is there (and hasn't expired).

Parameters:

- `key` (`string`, required)

### Dict.size

```typescript
size(): Promise<number>
```

How many keys it holds, read now.

## DictItem

```typescript
interface DictItem
```

One key of a dict as `items()` reads it: its value, when it expires (null if it doesn't),
when it was last written and the size of its value as JSON.

| Attribute | Type | Description |
| --- | --- | --- |
| `key` | `string` |  |
| `value` | `unknown` |  |
| `expiresAt` | `Date | null` |  |
| `updatedAt` | `Date | null` |  |
| `sizeBytes` | `number | null` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## DictChange

```typescript
interface DictChange
```

One write to a dict, from its history: `op` is `created` (the key was new), `changed` or `deleted`,
and `previous` the value it replaced (null for a new key). A key changed again within a minute adds
none, so a busy key keeps one a minute.

| Attribute | Type | Description |
| --- | --- | --- |
| `id` | `string` |  |
| `key` | `string` |  |
| `op` | `"created" | "changed" | "deleted"` |  |
| `previous` | `unknown` |  |
| `previousExpiresAt` | `Date | null` |  |
| `at` | `Date | null` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```
