env
AI binding, present when plugin.toml lists tasks under [ai].calls and
the operator approved them. The host routes each run to the deployed plugin
that serves the model; the shape follows the AI binding of Cloudflare
Workers.
run(model, input): Promise<AiTextEmbeddingsResponse>;
Run one model on one input.
| Parameter | Type | Description |
|---|---|---|
model |
string |
@<plugin id>/<model id>, or a task alias such as @library/text-embeddings for the model the library chose. |
input |
AiTextEmbeddingsRequest |
The input of the model's task. |
Promise<AiTextEmbeddingsResponse>
The model's output.
PluginError invalid_params for a malformed run, not_found when
nothing deployed serves the model, forbidden for a task that is not
granted, rate_limited past the plugin's budget (work over many items
belongs in a job), deadline_exceeded or unavailable when the model
plugin cannot answer.
Input of a text-embedding model on AiBinding.run.
role?: "document" | "query";
What the texts are: document (the default) for stored content, query
for a search query matched against documents. Some models embed the two
differently.
text: string | string[];
One text or a batch (at most MAX_AI_EMBED_TEXTS), none empty.
Output of a text-embedding model on AiBinding.run.
data: number[][];
One vector per input text, in input order.
fallbacks: number[];
Indexes of the texts the tokenizer could not cover with the loaded language packs; their vectors are worth recomputing once a pack is added.
model: string;
Full name of the model that ran, also when an alias was asked for.
revision: string;
Revision of the model that made the vectors. Vectors are comparable only when their model and revision match, so store both beside each vector.
shape: [number, number];
[number of texts, numbers per vector].
Guest env bindings for api_version = 3 manifests. Every host-provided
facility is a binding here; there is no HOST object. Bindings appear only
when plugin.toml declares them and the operator has consented.
Run bookclerk-plugin types to generate a precise Env for one manifest
(bookclerk-configuration.d.ts), then extends BookclerkEntrypoint<Env>.
[binding: string]: unknown
Named [[databases]] bindings, [[queues.producers]] bindings, and any
renamed binding = "..." entries.
AI?: AiBinding;
[ai].calls model runner.
CONFIG?: JsonObject;
[vars] plus operator settings, decoded from the granted CONFIG payload.
EVENTS?: EventPublisherBinding;
[[events.producers]] outbox publisher.
KV?: KvNamespaceBinding;
[[kv_namespaces]] durable KV binding (default name).
NETWORK?: NetworkGrant;
The network grant in effect: fetch hosts, TCP destinations, and each
network setting's destination with its approval state (pending until
the operator approves it). Read-only; the host enforces the grant.
NOTIFY?: NotifyBinding;
[[notifications.types]] raiser.
OAUTH?: unknown;
[oauth] loopback helper; surface reserved.
ORIGIN?: OriginBinding;
The library a relay ingress plugin serves; present only while this
instance is the active ingress.
SECRETS?: JsonObject;
[secrets] values, decoded from the granted SECRETS payload.
SOCKETS?: SocketsBinding;
[sockets] host-brokered WebSockets (default name).
WEBHOOKS?: WebhooksBinding;
[[webhooks]] inbound webhooks.
WORK_FS?: StorageBinding;
[work_fs] object storage.
EVENTS binding, present when a [[events.producers]] or
[[events.consumers]] entry is declared and granted. Publishing needs a
granted producer; reading needs a granted consumer.
publish(event): Promise<PublishOk>;
Publish one domain event through the host outbox.
| Parameter | Type | Description |
|---|---|---|
event |
PublishEvent |
Event type, schema version, payload, dedup key. |
Promise<PublishOk>
Outbox row identity (duplicate when the dedup key matched).
read(options?): Promise<EventReadPage>;
Read one page of past events the plugin's granted subscriptions match, oldest first, to catch up after its deliveries expired.
Pass the page's cursor back as after while more is true.
expiredEventIds names events in the page whose delivery to this
plugin expired unhandled, and truncated says the start was older
than the host keeps. Read events are not deliveries: deliveryAttempt
is 0 and deduplicationKey is the event id.
| Parameter | Type | Description |
|---|---|---|
options? |
EventReadOptions |
Start position, types, and page size. |
Promise<EventReadPage>
One page of events and the cursor after it.
PluginError forbidden for a type that is not a granted
consumer, invalid_cursor for a cursor the host did not issue.
Where an EventPublisherBinding.read starts and which events it
returns. Set at most one of after and since; with neither, the read
starts at the oldest event the host still keeps ([events].retention_days).
after?: string;
Opaque cursor from an earlier page's cursor: resume right after it.
limit?: number;
Most events in the page; 0 or omitted means the host maximum.
since?: number | Date;
Start at this instant (a Date, or UTC unix milliseconds).
sinceUnixMs?: number;
The ABI spelling of since (UTC unix milliseconds), as the generated
EventReadRequest names it; used when since is absent.
types?: string[];
Event types to return; each must be a granted [[events.consumers]]
type. Empty or omitted means every granted type.
One host-brokered WebSocket, shaped like a hibernatable Workers WebSocket.
The host holds the connection while the plugin sleeps and wakes the
plugin's webSocketMessage / webSocketClose handlers when something
arrives. The object is a handle: it carries the socket's id and the
attachment as it was when the handle was made, and each method is one call
to the host.
readonly id: string;
Host-minted id, stable for the socket's life and never reused.
readonly protocol: string;
Subprotocol the server chose; empty when none or unknown.
readonly url: string;
URL the socket was opened to, without credentials; empty in a handler.
close(code?, reason?): Promise<void>;
Close the socket. Closing a closed socket is not an error.
| Parameter | Type | Description |
|---|---|---|
code? |
number |
Close code; omitted sends 1000. |
reason? |
string |
Close reason, at most 123 UTF-8 bytes. |
Promise<void>
deserializeAttachment(): unknown;
The attachment as this handle last saw it.
unknown
The stored value, or null when none is set.
send(message): Promise<void>;
Send one message.
| Parameter | Type | Description |
|---|---|---|
message |
SocketSendData |
Text or bytes, at most MAX_SOCKET_FRAME_BYTES. |
Promise<void>
PluginError not_found when the socket has closed.
serializeAttachment(value): Promise<void>;
Replace the attachment the host keeps for this socket and hands back
with every message, so state survives the plugin sleeping. The value is
stored as JSON and must encode to at most MAX_SOCKET_ATTACHMENT_BYTES.
| Parameter | Type | Description |
|---|---|---|
value |
unknown |
JSON-serializable value; null or undefined clears it. |
Promise<void>
PluginError payload_too_large when it does not fit.
One key on a KvNamespaceBinding.list page.
expiration?: number;
Absolute expiry in seconds since the Unix epoch, when set.
metadata?: unknown;
Stored metadata, when set.
name: string;
Key name.
Page request for KvNamespaceBinding.list.
cursor?: string;
Cursor from a previous page.
limit?: number;
Most keys to return (host default when omitted, at most maxListPage).
prefix?: string;
Only keys starting with this prefix.
One page of KvNamespaceBinding.list.
cursor?: string;
Cursor for the next page; absent when list_complete.
keys: KvListKeyBinding[];
Keys in lexical order.
list_complete: boolean;
True when no further page exists.
[[kv_namespaces]] binding (env.<BINDING>, default KV): Workers
KVNamespace-shaped durable storage the host serves from the library
database, scoped to this plugin and the namespace the row names. Values
follow the instance across hosts.
delete(key): Promise<void>;
Delete one key; a missing key is not an error.
| Parameter | Type | Description |
|---|---|---|
key |
string |
Key to delete. |
Promise<void>
get(key, type?): Promise<string | null>;
Read one key.
| Parameter | Type | Description |
|---|---|---|
key |
string |
Key, at most maxKvKeyBytes UTF-8 bytes. |
type? |
"text" |
Decoding (text by default). |
Promise<string | null>
The value, or null when absent or expired.
get<T>(key, type): Promise<T | null>;
Read one key and parse it as JSON.
| Type Parameter | Default type |
|---|---|
<a id="type-parameter-t"></a> T |
unknown |
| Parameter | Type | Description |
|---|---|---|
key |
string |
Key, at most maxKvKeyBytes UTF-8 bytes. |
type |
"json" |
json. |
Promise<T | null>
The parsed value, or null when absent or expired.
get(key, type): Promise<ArrayBuffer | null>;
Read one key as bytes.
| Parameter | Type | Description |
|---|---|---|
key |
string |
Key, at most maxKvKeyBytes UTF-8 bytes. |
type |
"arrayBuffer" |
arrayBuffer. |
Promise<ArrayBuffer | null>
The bytes, or null when absent or expired.
getWithMetadata(key, type?): Promise<KvValueWithMetadata<string>>;
Read one key with its metadata.
| Parameter | Type | Description |
|---|---|---|
key |
string |
Key to read. |
type? |
"text" |
Decoding (text by default). |
Promise<KvValueWithMetadata<string>>
Value and metadata; both null when absent.
getWithMetadata<T>(key, type): Promise<KvValueWithMetadata<T>>;
Read one key as JSON with its metadata.
| Type Parameter | Default type |
|---|---|
<a id="type-parameter-t-1"></a> T |
unknown |
| Parameter | Type | Description |
|---|---|---|
key |
string |
Key to read. |
type |
"json" |
json. |
Promise<KvValueWithMetadata<T>>
Parsed value and metadata; both null when absent.
getWithMetadata(key, type): Promise<KvValueWithMetadata<ArrayBuffer>>;
Read one key as bytes with its metadata.
| Parameter | Type | Description |
|---|---|---|
key |
string |
Key to read. |
type |
"arrayBuffer" |
arrayBuffer. |
Promise<KvValueWithMetadata<ArrayBuffer>>
Bytes and metadata; both null when absent.
list(options?): Promise<KvListResultBinding>;
List keys in lexical order, one page at a time.
| Parameter | Type | Description |
|---|---|---|
options? |
KvListOptionsBinding |
Prefix, cursor, and page size. |
Promise<KvListResultBinding>
One page of keys.
put(
key,
value,
options?
): Promise<void>;
Write one key, replacing any previous value and metadata.
| Parameter | Type | Description |
|---|---|---|
key |
string |
Key to write. |
value |
string | ArrayBuffer | ArrayBufferView<ArrayBufferLike> |
String (stored as UTF-8) or bytes. |
options? |
KvPutOptionsBinding |
Expiration and metadata. |
Promise<void>
Options for KvNamespaceBinding.put (Workers KV names).
expiration?: number;
Absolute expiry in seconds since the Unix epoch.
expirationTtl?: number;
Relative expiry in seconds from the write; ignored when expiration is set.
metadata?: unknown;
JSON-serializable metadata, at most maxKvMetadataBytes once encoded.
Value plus metadata from KvNamespaceBinding.getWithMetadata.
| Type Parameter |
|---|
<a id="type-parameter-t-2"></a> T |
metadata: unknown;
Stored metadata, or null when none.
value: T | null;
Decoded value, or null when the key is absent or expired.
NOTIFY binding, present when plugin.toml declares
[[notifications.types]]. The host routes each raise by the
administrators' rules and each patron's preferences; the plugin never
learns where it went.
raise(raise): Promise<NotifyRaised>;
Raise one declared notification type.
| Parameter | Type | Description |
|---|---|---|
raise |
NotifyRaise |
Type, fields, optional patron, link path and alert. |
Promise<NotifyRaised>
The host's notification id.
PluginError invalid_params for an undeclared type or a malformed
raise, forbidden for a patron outside the account scope, rate_limited
past the per-instance raise budget.
One notification a plugin raises through NotifyBinding.raise.
alertAction?: "none" | "trigger" | "resolve";
Alert lifecycle step; none (the default) for a one-off notification.
alertKey?: string;
Alert to open or close; required unless alertAction is none.
fields?:
| Record<string, string>
| NotificationField[];
Labelled values shown with the notification, as { name, value } rows or
a plain object (at most MAX_NOTIFICATION_FIELDS).
groupKey?: string;
Notifications with one group key may be threaded or collapsed together.
linkPath?: string;
Path inside the library to link to (/books/42); the host adds its origin.
notificationType: string;
Type id from the plugin's [[notifications.types]], without a plugin prefix.
patronId?: string;
Patron the notification is for; required for a patron type and must be
inside the invocation's account scope.
[[queues.producers]] binding (env.<BINDING>): Workers Queue-shaped
producer into the queue the row names. The host assigns ids, stamps the
sending plugin as source, and bounds each body at maxEventPayloadBytes.
send(body, options?): Promise<QueueSendOk>;
Send one message.
| Parameter | Type | Description |
|---|---|---|
body |
unknown |
JSON value (default), string, or bytes per contentType. |
options? |
QueueSendOptions |
Encoding and delay. |
Promise<QueueSendOk>
The outbox id the host assigned.
sendBatch(messages, options?): Promise<QueueSendOk>;
Send up to maxListPage messages in order.
| Parameter | Type | Description |
|---|---|---|
messages |
readonly QueueSendBatchEntry[] |
Bodies with per-message options. |
options? |
Pick<QueueSendOptions, "delaySeconds"> |
Default delay for entries that carry none. |
Promise<QueueSendOk>
The outbox ids in send order.
One entry of QueueBinding.sendBatch.
body: unknown;
Message body (JSON value, string, or bytes per contentType).
contentType?: "text" | "bytes" | "json";
Body encoding: json (default; the body is JSON-encoded), text
(UTF-8 string), or bytes (raw Uint8Array).
delaySeconds?: number;
Seconds before the message may be delivered; 0 means now.
Per-send options for a QueueBinding.
contentType?: "text" | "bytes" | "json";
Body encoding: json (default; the body is JSON-encoded), text
(UTF-8 string), or bytes (raw Uint8Array).
delaySeconds?: number;
Seconds before the message may be delivered; 0 means now.
A heartbeat the host answers itself, like a Workers
WebSocketRequestResponsePair: when a message equal to request (same
kind, same bytes) arrives, the host sends response and does not wake the
plugin.
request: SocketSendData;
Message to match, 1 to MAX_SOCKET_AUTO_RESPONSE_BYTES bytes.
response: SocketSendData;
Message to send back, 1 to MAX_SOCKET_AUTO_RESPONSE_BYTES bytes.
Options for SocketsBinding.connect.
attachment?: unknown;
Initial attachment, as HostWebSocket.serializeAttachment would store it.
autoResponses?: SocketAutoResponsePair[];
Heartbeats the host answers without waking the plugin, at most 4.
headers?: Record<string, string> | [string, string][];
Extra request headers, at most 16. Values may be credentials; the host never logs them. Handshake and hop-by-hop headers are refused.
protocols?: string[];
Subprotocols to request (Sec-WebSocket-Protocol), at most 16.
SOCKETS binding ([sockets], renamed by binding = "..."): outbound
WebSockets the host holds open while the plugin sleeps. Messages and
closes reach the default entrypoint's webSocketMessage(ws, message) and
webSocketClose(ws, code, reason, wasClean).
connect(url, options?): Promise<HostWebSocket>;
Open a socket once the handshake finishes. It belongs to the plugin instance and outlives this invocation.
| Parameter | Type | Description |
|---|---|---|
url |
string |
wss:// or ws:// URL on the plugin's network grant. |
options? |
SocketConnectOptions |
Subprotocols, headers, heartbeats and attachment. |
Promise<HostWebSocket>
The open socket.
PluginError forbidden for a host outside the network grant,
limit_exceeded when the instance already holds MAX_SOCKETS_PER_INSTANCE
sockets.
getWebSockets(): Promise<HostWebSocket[]>;
The instance's open sockets, oldest first, for a plugin that just woke.
Promise<HostWebSocket[]>
One handle per open socket.
WORK_FS binding: host-granted object storage for durable plugin files.
Same surface as the storage entrypoint the host calls on storage plugins.
delete(key): Promise<void>;
Remove an object; missing keys are not an error.
| Parameter | Type | Description |
|---|---|---|
key |
string |
Object key. |
Promise<void>
Resolves when the delete is durable.
get(key, options?): Promise<{
body: ReadableStream<Uint8Array<ArrayBufferLike>>;
meta: {
key: string;
size: number;
};
}>;
Stream an object (optionally a byte range).
| Parameter | Type | Description |
|---|---|---|
key |
string |
Object key. |
options? |
{ range?: { length?: number; offset: number; }; } |
Optional byte range. |
options.range? |
{ length?: number; offset: number; } |
- |
options.range.length? |
number |
- |
options.range.offset |
number |
- |
Promise<{
body: ReadableStream<Uint8Array<ArrayBufferLike>>;
meta: {
key: string;
size: number;
};
}>
Metadata and the body stream.
head(key): Promise<
| {
contentType?: string;
etag?: string;
key: string;
size: number;
}
| null>;
Object metadata without the body.
| Parameter | Type | Description |
|---|---|---|
key |
string |
Object key. |
Promise<
| {
contentType?: string;
etag?: string;
key: string;
size: number;
}
| null>
Metadata, or null when the key does not exist.
list(options): Promise<{
nextCursor?: string;
objects: object[];
}>;
One page of keys under prefix.
| Parameter | Type | Description |
|---|---|---|
options |
{ cursor?: string; limit?: number; prefix?: string; } |
Prefix, continuation cursor, and page size. |
options.cursor? |
string |
- |
options.limit? |
number |
- |
options.prefix? |
string |
- |
Promise<{
nextCursor?: string;
objects: object[];
}>
Objects plus the cursor for the next page, when any.
put(
key,
body,
options?
): Promise<{
bytesWritten: number;
key: string;
}>;
Write an object from a stream.
| Parameter | Type | Description |
|---|---|---|
key |
string |
Object key. |
body |
ReadableStream<Uint8Array<ArrayBufferLike>> |
Body bytes. |
options? |
{ contentLength?: number; contentType?: string; } |
Content type and length hints. |
options.contentLength? |
number |
- |
options.contentType? |
string |
- |
Promise<{
bytesWritten: number;
key: string;
}>
Key and bytes written.
Argument of the default entrypoint's webhookDelivered(event).
name: string;
[[webhooks]] name.
waiting: number;
Requests waiting for this webhook when the host called.
One stored webhook request, leased to the plugin by WebhooksBinding.pull. Shaped like a pulled Workers Queue message: acknowledge it with WebhooksBinding.ack once handled, or it is offered again when its lease runs out.
attempts: number;
How many times the request has been pulled, counting this one.
body: Uint8Array;
Request body as received.
headers: Record<string, string>;
Kept request headers, lowercase names: those the [[webhooks]] row
lists, plus content-type.
leaseId: string;
Lease id for ack; a new one each time the request is pulled.
timestamp: Date;
When the host stored the request, as a Date.
Options for WebhooksBinding.pull.
batchSize?: number;
Most requests to lease, 1 to 100; defaults to 10.
visibilityTimeoutMs?: number;
How long leased requests stay hidden from the next pull, in milliseconds, at most 12 hours; defaults to one minute.
What one WebhooksBinding.pull leased.
messages: WebhookMessage[];
Leased requests, oldest first.
missed: boolean;
True when the host dropped requests for this webhook since the last pull (its waiting cap was full, or a request expired unacknowledged): treat what the requests describe as incomplete and fall back to a full listing.
WEBHOOKS binding ([[webhooks]]): the instance's inbound webhooks. The
host serves each row at a secret URL, checks each request's size, rate
and signature, and stores it until the plugin pulls and acknowledges it.
The default entrypoint's webhookDelivered(event) runs when requests
arrive.
ack(name, leases): Promise<void>;
Finish leased requests: acks are deleted, retries are offered again
on the next pull.
| Parameter | Type | Description |
|---|---|---|
name |
string |
[[webhooks]] name. |
leases |
{ acks?: string[]; retries?: string[]; } |
Lease ids to acknowledge and to retry. |
leases.acks? |
string[] |
- |
leases.retries? |
string[] |
- |
Promise<void>
Resolves when the host recorded both lists.
pull(name, options?): Promise<WebhookPullResult>;
Lease waiting requests for one webhook, oldest first.
| Parameter | Type | Description |
|---|---|---|
name |
string |
[[webhooks]] name. |
options? |
WebhookPullOptions |
Batch size and lease length. |
Promise<WebhookPullResult>
The leased requests and whether any were missed.
url(name): Promise<string | null>;
The URL to register with the outside service for one webhook.
| Parameter | Type | Description |
|---|---|---|
name |
string |
[[webhooks]] name. |
Promise<string | null>
The URL, or null when the library cannot be reached from the
Internet or webhooks are turned off; use the fallback then.
type JsonObject = Record<string, unknown>;
Plain JSON object (string keys, JSON values).
type KvValueType = "text" | "json" | "arrayBuffer";
How KvNamespaceBinding.get decodes a stored value.
type PublishEvent = Pick<PluginEvent, "eventType"> & Partial<Omit<PluginEvent, "eventType" | "payload">> & object;
Event a guest publishes; the host stamps id, source, and accountId.
| Name | Type | Description |
|---|---|---|
payload? |
Uint8Array | JsonObject | unknown[] | string |
Payload bytes or a JSON-serializable value encoded as UTF-8 JSON. |
type SocketMessageData = string | ArrayBuffer;
A message that arrived on a host-brokered socket: text as a string, binary
as an ArrayBuffer (as Workers delivers to webSocketMessage).
type SocketSendData = string | ArrayBuffer | ArrayBufferView;
A message to send on a host-brokered socket.
Generated from packages/plugin-sdk at main · View as Markdown