env

Development These docs follow the development version and change with every merge.

Last updated View as Markdown

Interfaces

AiBinding

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.

Methods

run()
run(model, input): Promise<AiTextEmbeddingsResponse>;

Run one model on one input.

Parameters
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.
Returns

Promise<AiTextEmbeddingsResponse>

The model's output.

Throws

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.


AiTextEmbeddingsRequest

Input of a text-embedding model on AiBinding.run.

Properties

role?
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
text: string | string[];

One text or a batch (at most MAX_AI_EMBED_TEXTS), none empty.


AiTextEmbeddingsResponse

Output of a text-embedding model on AiBinding.run.

Properties

data
data: number[][];

One vector per input text, in input order.

fallbacks
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
model: string;

Full name of the model that ran, also when an alias was asked for.

revision
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
shape: [number, number];

[number of texts, numbers per vector].


BookclerkEnv

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

Indexable

[binding: string]: unknown

Named [[databases]] bindings, [[queues.producers]] bindings, and any renamed binding = "..." entries.

Properties

AI?
AI?: AiBinding;

[ai].calls model runner.

CONFIG?
CONFIG?: JsonObject;

[vars] plus operator settings, decoded from the granted CONFIG payload.

EVENTS?
EVENTS?: EventPublisherBinding;

[[events.producers]] outbox publisher.

KV?
KV?: KvNamespaceBinding;

[[kv_namespaces]] durable KV binding (default name).

NETWORK?
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?
NOTIFY?: NotifyBinding;

[[notifications.types]] raiser.

OAUTH?
OAUTH?: unknown;

[oauth] loopback helper; surface reserved.

ORIGIN?
ORIGIN?: OriginBinding;

The library a relay ingress plugin serves; present only while this instance is the active ingress.

SECRETS?
SECRETS?: JsonObject;

[secrets] values, decoded from the granted SECRETS payload.

SOCKETS?
SOCKETS?: SocketsBinding;

[sockets] host-brokered WebSockets (default name).

WEBHOOKS?
WEBHOOKS?: WebhooksBinding;

[[webhooks]] inbound webhooks.

WORK_FS?
WORK_FS?: StorageBinding;

[work_fs] object storage.


EventPublisherBinding

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.

Methods

publish()
publish(event): Promise<PublishOk>;

Publish one domain event through the host outbox.

Parameters
Parameter Type Description
event PublishEvent Event type, schema version, payload, dedup key.
Returns

Promise<PublishOk>

Outbox row identity (duplicate when the dedup key matched).

read()
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.

Parameters
Parameter Type Description
options? EventReadOptions Start position, types, and page size.
Returns

Promise<EventReadPage>

One page of events and the cursor after it.

Throws

PluginError forbidden for a type that is not a granted consumer, invalid_cursor for a cursor the host did not issue.


EventReadOptions

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

Properties

after?
after?: string;

Opaque cursor from an earlier page's cursor: resume right after it.

limit?
limit?: number;

Most events in the page; 0 or omitted means the host maximum.

since?
since?: number | Date;

Start at this instant (a Date, or UTC unix milliseconds).

sinceUnixMs?
sinceUnixMs?: number;

The ABI spelling of since (UTC unix milliseconds), as the generated EventReadRequest names it; used when since is absent.

types?
types?: string[];

Event types to return; each must be a granted [[events.consumers]] type. Empty or omitted means every granted type.


HostWebSocket

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.

Properties

id
readonly id: string;

Host-minted id, stable for the socket's life and never reused.

protocol
readonly protocol: string;

Subprotocol the server chose; empty when none or unknown.

url
readonly url: string;

URL the socket was opened to, without credentials; empty in a handler.

Methods

close()
close(code?, reason?): Promise<void>;

Close the socket. Closing a closed socket is not an error.

Parameters
Parameter Type Description
code? number Close code; omitted sends 1000.
reason? string Close reason, at most 123 UTF-8 bytes.
Returns

Promise<void>

deserializeAttachment()
deserializeAttachment(): unknown;

The attachment as this handle last saw it.

Returns

unknown

The stored value, or null when none is set.

send()
send(message): Promise<void>;

Send one message.

Parameters
Parameter Type Description
message SocketSendData Text or bytes, at most MAX_SOCKET_FRAME_BYTES.
Returns

Promise<void>

Throws

PluginError not_found when the socket has closed.

serializeAttachment()
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.

Parameters
Parameter Type Description
value unknown JSON-serializable value; null or undefined clears it.
Returns

Promise<void>

Throws

PluginError payload_too_large when it does not fit.


KvListKeyBinding

One key on a KvNamespaceBinding.list page.

Properties

expiration?
expiration?: number;

Absolute expiry in seconds since the Unix epoch, when set.

metadata?
metadata?: unknown;

Stored metadata, when set.

name
name: string;

Key name.


KvListOptionsBinding

Page request for KvNamespaceBinding.list.

Properties

cursor?
cursor?: string;

Cursor from a previous page.

limit?
limit?: number;

Most keys to return (host default when omitted, at most maxListPage).

prefix?
prefix?: string;

Only keys starting with this prefix.


KvListResultBinding

One page of KvNamespaceBinding.list.

Properties

cursor?
cursor?: string;

Cursor for the next page; absent when list_complete.

keys
keys: KvListKeyBinding[];

Keys in lexical order.

list_complete
list_complete: boolean;

True when no further page exists.


KvNamespaceBinding

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

Methods

delete()
delete(key): Promise<void>;

Delete one key; a missing key is not an error.

Parameters
Parameter Type Description
key string Key to delete.
Returns

Promise<void>

get()
Call Signature
get(key, type?): Promise<string | null>;

Read one key.

Parameters
Parameter Type Description
key string Key, at most maxKvKeyBytes UTF-8 bytes.
type? "text" Decoding (text by default).
Returns

Promise<string | null>

The value, or null when absent or expired.

Call Signature
get<T>(key, type): Promise<T | null>;

Read one key and parse it as JSON.

Type Parameters
Type Parameter Default type
<a id="type-parameter-t"></a> T unknown
Parameters
Parameter Type Description
key string Key, at most maxKvKeyBytes UTF-8 bytes.
type "json" json.
Returns

Promise<T | null>

The parsed value, or null when absent or expired.

Call Signature
get(key, type): Promise<ArrayBuffer | null>;

Read one key as bytes.

Parameters
Parameter Type Description
key string Key, at most maxKvKeyBytes UTF-8 bytes.
type "arrayBuffer" arrayBuffer.
Returns

Promise<ArrayBuffer | null>

The bytes, or null when absent or expired.

getWithMetadata()
Call Signature
getWithMetadata(key, type?): Promise<KvValueWithMetadata<string>>;

Read one key with its metadata.

Parameters
Parameter Type Description
key string Key to read.
type? "text" Decoding (text by default).
Returns

Promise<KvValueWithMetadata<string>>

Value and metadata; both null when absent.

Call Signature
getWithMetadata<T>(key, type): Promise<KvValueWithMetadata<T>>;

Read one key as JSON with its metadata.

Type Parameters
Type Parameter Default type
<a id="type-parameter-t-1"></a> T unknown
Parameters
Parameter Type Description
key string Key to read.
type "json" json.
Returns

Promise<KvValueWithMetadata<T>>

Parsed value and metadata; both null when absent.

Call Signature
getWithMetadata(key, type): Promise<KvValueWithMetadata<ArrayBuffer>>;

Read one key as bytes with its metadata.

Parameters
Parameter Type Description
key string Key to read.
type "arrayBuffer" arrayBuffer.
Returns

Promise<KvValueWithMetadata<ArrayBuffer>>

Bytes and metadata; both null when absent.

list()
list(options?): Promise<KvListResultBinding>;

List keys in lexical order, one page at a time.

Parameters
Parameter Type Description
options? KvListOptionsBinding Prefix, cursor, and page size.
Returns

Promise<KvListResultBinding>

One page of keys.

put()
put(
   key, 
   value, 
   options?
): Promise<void>;

Write one key, replacing any previous value and metadata.

Parameters
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.
Returns

Promise<void>


KvPutOptionsBinding

Options for KvNamespaceBinding.put (Workers KV names).

Properties

expiration?
expiration?: number;

Absolute expiry in seconds since the Unix epoch.

expirationTtl?
expirationTtl?: number;

Relative expiry in seconds from the write; ignored when expiration is set.

metadata?
metadata?: unknown;

JSON-serializable metadata, at most maxKvMetadataBytes once encoded.


KvValueWithMetadata

Value plus metadata from KvNamespaceBinding.getWithMetadata.

Type Parameters

Type Parameter
<a id="type-parameter-t-2"></a> T

Properties

metadata
metadata: unknown;

Stored metadata, or null when none.

value
value: T | null;

Decoded value, or null when the key is absent or expired.


NotifyBinding

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.

Methods

raise()
raise(raise): Promise<NotifyRaised>;

Raise one declared notification type.

Parameters
Parameter Type Description
raise NotifyRaise Type, fields, optional patron, link path and alert.
Returns

Promise<NotifyRaised>

The host's notification id.

Throws

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.


NotifyRaise

One notification a plugin raises through NotifyBinding.raise.

Properties

alertAction?
alertAction?: "none" | "trigger" | "resolve";

Alert lifecycle step; none (the default) for a one-off notification.

alertKey?
alertKey?: string;

Alert to open or close; required unless alertAction is none.

fields?
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?
groupKey?: string;

Notifications with one group key may be threaded or collapsed together.

linkPath?
linkPath?: string;

Path inside the library to link to (/books/42); the host adds its origin.

notificationType
notificationType: string;

Type id from the plugin's [[notifications.types]], without a plugin prefix.

patronId?
patronId?: string;

Patron the notification is for; required for a patron type and must be inside the invocation's account scope.


QueueBinding

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

Methods

send()
send(body, options?): Promise<QueueSendOk>;

Send one message.

Parameters
Parameter Type Description
body unknown JSON value (default), string, or bytes per contentType.
options? QueueSendOptions Encoding and delay.
Returns

Promise<QueueSendOk>

The outbox id the host assigned.

sendBatch()
sendBatch(messages, options?): Promise<QueueSendOk>;

Send up to maxListPage messages in order.

Parameters
Parameter Type Description
messages readonly QueueSendBatchEntry[] Bodies with per-message options.
options? Pick<QueueSendOptions, "delaySeconds"> Default delay for entries that carry none.
Returns

Promise<QueueSendOk>

The outbox ids in send order.


QueueSendBatchEntry

One entry of QueueBinding.sendBatch.

Extends

Properties

body
body: unknown;

Message body (JSON value, string, or bytes per contentType).

contentType?
contentType?: "text" | "bytes" | "json";

Body encoding: json (default; the body is JSON-encoded), text (UTF-8 string), or bytes (raw Uint8Array).

Inherited from

QueueSendOptions.contentType

delaySeconds?
delaySeconds?: number;

Seconds before the message may be delivered; 0 means now.

Inherited from

QueueSendOptions.delaySeconds


QueueSendOptions

Per-send options for a QueueBinding.

Extended by

Properties

contentType?
contentType?: "text" | "bytes" | "json";

Body encoding: json (default; the body is JSON-encoded), text (UTF-8 string), or bytes (raw Uint8Array).

delaySeconds?
delaySeconds?: number;

Seconds before the message may be delivered; 0 means now.


SocketAutoResponsePair

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.

Properties

request
request: SocketSendData;

Message to match, 1 to MAX_SOCKET_AUTO_RESPONSE_BYTES bytes.

response
response: SocketSendData;

Message to send back, 1 to MAX_SOCKET_AUTO_RESPONSE_BYTES bytes.


SocketConnectOptions

Options for SocketsBinding.connect.

Properties

attachment?
attachment?: unknown;

Initial attachment, as HostWebSocket.serializeAttachment would store it.

autoResponses?
autoResponses?: SocketAutoResponsePair[];

Heartbeats the host answers without waking the plugin, at most 4.

headers?
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?
protocols?: string[];

Subprotocols to request (Sec-WebSocket-Protocol), at most 16.


SocketsBinding

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

Methods

connect()
connect(url, options?): Promise<HostWebSocket>;

Open a socket once the handshake finishes. It belongs to the plugin instance and outlives this invocation.

Parameters
Parameter Type Description
url string wss:// or ws:// URL on the plugin's network grant.
options? SocketConnectOptions Subprotocols, headers, heartbeats and attachment.
Returns

Promise<HostWebSocket>

The open socket.

Throws

PluginError forbidden for a host outside the network grant, limit_exceeded when the instance already holds MAX_SOCKETS_PER_INSTANCE sockets.

getWebSockets()
getWebSockets(): Promise<HostWebSocket[]>;

The instance's open sockets, oldest first, for a plugin that just woke.

Returns

Promise<HostWebSocket[]>

One handle per open socket.


StorageBinding

WORK_FS binding: host-granted object storage for durable plugin files. Same surface as the storage entrypoint the host calls on storage plugins.

Methods

delete()
delete(key): Promise<void>;

Remove an object; missing keys are not an error.

Parameters
Parameter Type Description
key string Object key.
Returns

Promise<void>

Resolves when the delete is durable.

get()
get(key, options?): Promise<{
  body: ReadableStream<Uint8Array<ArrayBufferLike>>;
  meta: {
     key: string;
     size: number;
  };
}>;

Stream an object (optionally a byte range).

Parameters
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 -
Returns

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.

Parameters
Parameter Type Description
key string Object key.
Returns

Promise< | { contentType?: string; etag?: string; key: string; size: number; } | null>

Metadata, or null when the key does not exist.

list()
list(options): Promise<{
  nextCursor?: string;
  objects: object[];
}>;

One page of keys under prefix.

Parameters
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 -
Returns

Promise<{ nextCursor?: string; objects: object[]; }>

Objects plus the cursor for the next page, when any.

put()
put(
   key, 
   body, 
   options?
): Promise<{
  bytesWritten: number;
  key: string;
}>;

Write an object from a stream.

Parameters
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 -
Returns

Promise<{ bytesWritten: number; key: string; }>

Key and bytes written.


WebhookDeliveredEvent

Argument of the default entrypoint's webhookDelivered(event).

Properties

name
name: string;

[[webhooks]] name.

waiting
waiting: number;

Requests waiting for this webhook when the host called.


WebhookMessage

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.

Properties

attempts
attempts: number;

How many times the request has been pulled, counting this one.

body
body: Uint8Array;

Request body as received.

headers
headers: Record<string, string>;

Kept request headers, lowercase names: those the [[webhooks]] row lists, plus content-type.

leaseId
leaseId: string;

Lease id for ack; a new one each time the request is pulled.

timestamp
timestamp: Date;

When the host stored the request, as a Date.


WebhookPullOptions

Options for WebhooksBinding.pull.

Properties

batchSize?
batchSize?: number;

Most requests to lease, 1 to 100; defaults to 10.

visibilityTimeoutMs?
visibilityTimeoutMs?: number;

How long leased requests stay hidden from the next pull, in milliseconds, at most 12 hours; defaults to one minute.


WebhookPullResult

What one WebhooksBinding.pull leased.

Properties

messages
messages: WebhookMessage[];

Leased requests, oldest first.

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


WebhooksBinding

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.

Methods

ack()
ack(name, leases): Promise<void>;

Finish leased requests: acks are deleted, retries are offered again on the next pull.

Parameters
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[] -
Returns

Promise<void>

Resolves when the host recorded both lists.

pull()
pull(name, options?): Promise<WebhookPullResult>;

Lease waiting requests for one webhook, oldest first.

Parameters
Parameter Type Description
name string [[webhooks]] name.
options? WebhookPullOptions Batch size and lease length.
Returns

Promise<WebhookPullResult>

The leased requests and whether any were missed.

url()
url(name): Promise<string | null>;

The URL to register with the outside service for one webhook.

Parameters
Parameter Type Description
name string [[webhooks]] name.
Returns

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 Aliases

JsonObject

type JsonObject = Record<string, unknown>;

Plain JSON object (string keys, JSON values).


KvValueType

type KvValueType = "text" | "json" | "arrayBuffer";

How KvNamespaceBinding.get decodes a stored value.


PublishEvent

type PublishEvent = Pick<PluginEvent, "eventType"> & Partial<Omit<PluginEvent, "eventType" | "payload">> & object;

Event a guest publishes; the host stamps id, source, and accountId.

Type Declaration

Name Type Description
payload? Uint8Array | JsonObject | unknown[] | string Payload bytes or a JSON-serializable value encoded as UTF-8 JSON.

SocketMessageData

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


SocketSendData

type SocketSendData = string | ArrayBuffer | ArrayBufferView;

A message to send on a host-brokered socket.

Generated from packages/plugin-sdk at main · View as Markdown