UNPKG

rivetkit

Version:

Lightweight libraries for building stateful actors on edge platforms

1,100 lines (1,082 loc) 30.2 kB
import { CachedSerializer, EncodingSchema, deserializeWithEncoding } from "./chunk-MLQIYKAZ.js"; import { LogLevelSchema } from "./chunk-7E5K3375.js"; import { assertUnreachable, bufferToArrayBuffer, deconstructError, getEnvUniversal } from "./chunk-HI55LHM3.js"; import { MalformedMessage, MessageTooLong, Unsupported } from "./chunk-YPZFLUO6.js"; // src/registry/run-config.ts import { z as z5 } from "zod"; // src/drivers/engine/config.ts import { z as z3 } from "zod"; // src/client/config.ts import z2 from "zod"; // src/actor/protocol/old.ts import * as cbor from "cbor-x"; import { z } from "zod"; // src/common/versioned-data.ts var VersionedDataHandler = class { constructor(config3) { this.config = config3; } serializeWithEmbeddedVersion(data) { const versioned = { version: this.config.currentVersion, data: this.config.serializeVersion(data) }; return this.embedVersion(versioned); } deserializeWithEmbeddedVersion(bytes) { const versioned = this.extractVersion(bytes); return this.deserialize(versioned.data, versioned.version); } serialize(data, version) { return this.config.serializeVersion(data); } deserialize(bytes, version) { if (version === this.config.currentVersion) { return this.config.deserializeVersion(bytes); } if (version > this.config.currentVersion) { throw new Error( `Cannot decode data from version ${version}, current version is ${this.config.currentVersion}` ); } let currentData = this.config.deserializeVersion(bytes); let currentVersion = version; while (currentVersion < this.config.currentVersion) { const migration = this.config.migrations.get(currentVersion); if (!migration) { throw new Error( `No migration found from version ${currentVersion} to ${currentVersion + 1}` ); } currentData = migration(currentData); currentVersion++; } return currentData; } embedVersion(data) { const versionBytes = new Uint8Array(2); new DataView(versionBytes.buffer).setUint16(0, data.version, true); const result = new Uint8Array(versionBytes.length + data.data.length); result.set(versionBytes); result.set(data.data, versionBytes.length); return result; } extractVersion(bytes) { if (bytes.length < 2) { throw new Error("Invalid versioned data: too short"); } const version = new DataView(bytes.buffer, bytes.byteOffset).getUint16( 0, true ); const data = bytes.slice(2); return { version, data }; } }; function createVersionedDataHandler(config3) { return new VersionedDataHandler(config3); } // dist/schemas/client-protocol/v1.ts import * as bare from "@bare-ts/lib"; var config = /* @__PURE__ */ bare.Config({}); function readInit(bc) { return { actorId: bare.readString(bc), connectionId: bare.readString(bc), connectionToken: bare.readString(bc) }; } function writeInit(bc, x) { bare.writeString(bc, x.actorId); bare.writeString(bc, x.connectionId); bare.writeString(bc, x.connectionToken); } function read0(bc) { return bare.readBool(bc) ? bare.readData(bc) : null; } function write0(bc, x) { bare.writeBool(bc, x !== null); if (x !== null) { bare.writeData(bc, x); } } function read1(bc) { return bare.readBool(bc) ? bare.readUint(bc) : null; } function write1(bc, x) { bare.writeBool(bc, x !== null); if (x !== null) { bare.writeUint(bc, x); } } function readError(bc) { return { group: bare.readString(bc), code: bare.readString(bc), message: bare.readString(bc), metadata: read0(bc), actionId: read1(bc) }; } function writeError(bc, x) { bare.writeString(bc, x.group); bare.writeString(bc, x.code); bare.writeString(bc, x.message); write0(bc, x.metadata); write1(bc, x.actionId); } function readActionResponse(bc) { return { id: bare.readUint(bc), output: bare.readData(bc) }; } function writeActionResponse(bc, x) { bare.writeUint(bc, x.id); bare.writeData(bc, x.output); } function readEvent(bc) { return { name: bare.readString(bc), args: bare.readData(bc) }; } function writeEvent(bc, x) { bare.writeString(bc, x.name); bare.writeData(bc, x.args); } function readToClientBody(bc) { const offset = bc.offset; const tag = bare.readU8(bc); switch (tag) { case 0: return { tag: "Init", val: readInit(bc) }; case 1: return { tag: "Error", val: readError(bc) }; case 2: return { tag: "ActionResponse", val: readActionResponse(bc) }; case 3: return { tag: "Event", val: readEvent(bc) }; default: { bc.offset = offset; throw new bare.BareError(offset, "invalid tag"); } } } function writeToClientBody(bc, x) { switch (x.tag) { case "Init": { bare.writeU8(bc, 0); writeInit(bc, x.val); break; } case "Error": { bare.writeU8(bc, 1); writeError(bc, x.val); break; } case "ActionResponse": { bare.writeU8(bc, 2); writeActionResponse(bc, x.val); break; } case "Event": { bare.writeU8(bc, 3); writeEvent(bc, x.val); break; } } } function readToClient(bc) { return { body: readToClientBody(bc) }; } function writeToClient(bc, x) { writeToClientBody(bc, x.body); } function encodeToClient(x) { const bc = new bare.ByteCursor( new Uint8Array(config.initialBufferLength), config ); writeToClient(bc, x); return new Uint8Array(bc.view.buffer, bc.view.byteOffset, bc.offset); } function decodeToClient(bytes) { const bc = new bare.ByteCursor(bytes, config); const result = readToClient(bc); if (bc.offset < bc.view.byteLength) { throw new bare.BareError(bc.offset, "remaining bytes"); } return result; } function readActionRequest(bc) { return { id: bare.readUint(bc), name: bare.readString(bc), args: bare.readData(bc) }; } function writeActionRequest(bc, x) { bare.writeUint(bc, x.id); bare.writeString(bc, x.name); bare.writeData(bc, x.args); } function readSubscriptionRequest(bc) { return { eventName: bare.readString(bc), subscribe: bare.readBool(bc) }; } function writeSubscriptionRequest(bc, x) { bare.writeString(bc, x.eventName); bare.writeBool(bc, x.subscribe); } function readToServerBody(bc) { const offset = bc.offset; const tag = bare.readU8(bc); switch (tag) { case 0: return { tag: "ActionRequest", val: readActionRequest(bc) }; case 1: return { tag: "SubscriptionRequest", val: readSubscriptionRequest(bc) }; default: { bc.offset = offset; throw new bare.BareError(offset, "invalid tag"); } } } function writeToServerBody(bc, x) { switch (x.tag) { case "ActionRequest": { bare.writeU8(bc, 0); writeActionRequest(bc, x.val); break; } case "SubscriptionRequest": { bare.writeU8(bc, 1); writeSubscriptionRequest(bc, x.val); break; } } } function readToServer(bc) { return { body: readToServerBody(bc) }; } function writeToServer(bc, x) { writeToServerBody(bc, x.body); } function encodeToServer(x) { const bc = new bare.ByteCursor( new Uint8Array(config.initialBufferLength), config ); writeToServer(bc, x); return new Uint8Array(bc.view.buffer, bc.view.byteOffset, bc.offset); } function decodeToServer(bytes) { const bc = new bare.ByteCursor(bytes, config); const result = readToServer(bc); if (bc.offset < bc.view.byteLength) { throw new bare.BareError(bc.offset, "remaining bytes"); } return result; } function readHttpActionRequest(bc) { return { args: bare.readData(bc) }; } function writeHttpActionRequest(bc, x) { bare.writeData(bc, x.args); } function encodeHttpActionRequest(x) { const bc = new bare.ByteCursor( new Uint8Array(config.initialBufferLength), config ); writeHttpActionRequest(bc, x); return new Uint8Array(bc.view.buffer, bc.view.byteOffset, bc.offset); } function decodeHttpActionRequest(bytes) { const bc = new bare.ByteCursor(bytes, config); const result = readHttpActionRequest(bc); if (bc.offset < bc.view.byteLength) { throw new bare.BareError(bc.offset, "remaining bytes"); } return result; } function readHttpActionResponse(bc) { return { output: bare.readData(bc) }; } function writeHttpActionResponse(bc, x) { bare.writeData(bc, x.output); } function encodeHttpActionResponse(x) { const bc = new bare.ByteCursor( new Uint8Array(config.initialBufferLength), config ); writeHttpActionResponse(bc, x); return new Uint8Array(bc.view.buffer, bc.view.byteOffset, bc.offset); } function decodeHttpActionResponse(bytes) { const bc = new bare.ByteCursor(bytes, config); const result = readHttpActionResponse(bc); if (bc.offset < bc.view.byteLength) { throw new bare.BareError(bc.offset, "remaining bytes"); } return result; } function readHttpResponseError(bc) { return { group: bare.readString(bc), code: bare.readString(bc), message: bare.readString(bc), metadata: read0(bc) }; } function writeHttpResponseError(bc, x) { bare.writeString(bc, x.group); bare.writeString(bc, x.code); bare.writeString(bc, x.message); write0(bc, x.metadata); } function encodeHttpResponseError(x) { const bc = new bare.ByteCursor( new Uint8Array(config.initialBufferLength), config ); writeHttpResponseError(bc, x); return new Uint8Array(bc.view.buffer, bc.view.byteOffset, bc.offset); } function decodeHttpResponseError(bytes) { const bc = new bare.ByteCursor(bytes, config); const result = readHttpResponseError(bc); if (bc.offset < bc.view.byteLength) { throw new bare.BareError(bc.offset, "remaining bytes"); } return result; } function readHttpResolveResponse(bc) { return { actorId: bare.readString(bc) }; } function writeHttpResolveResponse(bc, x) { bare.writeString(bc, x.actorId); } function encodeHttpResolveResponse(x) { const bc = new bare.ByteCursor( new Uint8Array(config.initialBufferLength), config ); writeHttpResolveResponse(bc, x); return new Uint8Array(bc.view.buffer, bc.view.byteOffset, bc.offset); } function decodeHttpResolveResponse(bytes) { const bc = new bare.ByteCursor(bytes, config); const result = readHttpResolveResponse(bc); if (bc.offset < bc.view.byteLength) { throw new bare.BareError(bc.offset, "remaining bytes"); } return result; } // src/schemas/client-protocol/versioned.ts var CURRENT_VERSION = 1; var migrations = /* @__PURE__ */ new Map(); var TO_SERVER_VERSIONED = createVersionedDataHandler({ currentVersion: CURRENT_VERSION, migrations, serializeVersion: (data) => encodeToServer(data), deserializeVersion: (bytes) => decodeToServer(bytes) }); var TO_CLIENT_VERSIONED = createVersionedDataHandler({ currentVersion: CURRENT_VERSION, migrations, serializeVersion: (data) => encodeToClient(data), deserializeVersion: (bytes) => decodeToClient(bytes) }); var HTTP_ACTION_REQUEST_VERSIONED = createVersionedDataHandler({ currentVersion: CURRENT_VERSION, migrations, serializeVersion: (data) => encodeHttpActionRequest(data), deserializeVersion: (bytes) => decodeHttpActionRequest(bytes) }); var HTTP_ACTION_RESPONSE_VERSIONED = createVersionedDataHandler({ currentVersion: CURRENT_VERSION, migrations, serializeVersion: (data) => encodeHttpActionResponse(data), deserializeVersion: (bytes) => decodeHttpActionResponse(bytes) }); var HTTP_RESPONSE_ERROR_VERSIONED = createVersionedDataHandler({ currentVersion: CURRENT_VERSION, migrations, serializeVersion: (data) => encodeHttpResponseError(data), deserializeVersion: (bytes) => decodeHttpResponseError(bytes) }); var HTTP_RESOLVE_REQUEST_VERSIONED = createVersionedDataHandler({ currentVersion: CURRENT_VERSION, migrations, serializeVersion: (_) => new Uint8Array(), deserializeVersion: (bytes) => null }); var HTTP_RESOLVE_RESPONSE_VERSIONED = createVersionedDataHandler({ currentVersion: CURRENT_VERSION, migrations, serializeVersion: (data) => encodeHttpResolveResponse(data), deserializeVersion: (bytes) => decodeHttpResolveResponse(bytes) }); // src/actor/action.ts var ActionContext = class { /** * Should not be called directly. * * @param actorContext - The actor context * @param conn - The connection associated with the action */ constructor(actorContext, conn) { this.conn = conn; this.#actorContext = actorContext; } #actorContext; /** * Get the actor state */ get state() { return this.#actorContext.state; } /** * Get the actor variables */ get vars() { return this.#actorContext.vars; } /** * Broadcasts an event to all connected clients. */ broadcast(name, ...args) { this.#actorContext.broadcast(name, ...args); } /** * Gets the logger instance. */ get log() { return this.#actorContext.log; } /** * Gets actor ID. */ get actorId() { return this.#actorContext.actorId; } /** * Gets the actor name. */ get name() { return this.#actorContext.name; } /** * Gets the actor key. */ get key() { return this.#actorContext.key; } /** * Gets the region. */ get region() { return this.#actorContext.region; } /** * Gets the scheduler. */ get schedule() { return this.#actorContext.schedule; } /** * Gets the map of connections. */ get conns() { return this.#actorContext.conns; } /** * Returns the client for the given registry. */ client() { return this.#actorContext.client(); } /** * @experimental */ get db() { return this.#actorContext.db; } /** * Forces the state to get saved. */ async saveState(opts) { return this.#actorContext.saveState(opts); } /** * Prevents the actor from sleeping until promise is complete. */ waitUntil(promise) { this.#actorContext.waitUntil(promise); } /** * AbortSignal that fires when the actor is stopping. */ get abortSignal() { return this.#actorContext.abortSignal; } /** * Forces the actor to sleep. * * Not supported on all drivers. * * @experimental */ sleep() { this.#actorContext.sleep(); } }; // src/actor/protocol/old.ts var TransportSchema = z.enum(["websocket", "sse"]); function getValueLength(value) { if (typeof value === "string") { return value.length; } else if (value instanceof Blob) { return value.size; } else if (value instanceof ArrayBuffer || value instanceof SharedArrayBuffer || value instanceof Uint8Array) { return value.byteLength; } else { assertUnreachable(value); } } async function inputDataToBuffer(data) { if (typeof data === "string") { return data; } else if (data instanceof Blob) { const arrayBuffer = await data.arrayBuffer(); return new Uint8Array(arrayBuffer); } else if (data instanceof Uint8Array) { return data; } else if (data instanceof ArrayBuffer || data instanceof SharedArrayBuffer) { return new Uint8Array(data); } else { throw new MalformedMessage(); } } async function parseMessage(value, opts) { const length = getValueLength(value); if (length > opts.maxIncomingMessageSize) { throw new MessageTooLong(); } let buffer = await inputDataToBuffer(value); if (buffer instanceof Buffer) { buffer = new Uint8Array(buffer); } return deserializeWithEncoding(opts.encoding, buffer, TO_SERVER_VERSIONED); } async function processMessage(message, actor, conn, handler) { let actionId; let actionName; try { if (message.body.tag === "ActionRequest") { if (handler.onExecuteAction === void 0) { throw new Unsupported("Action"); } const { id, name, args: argsRaw } = message.body.val; actionId = id; actionName = name; const args = cbor.decode(new Uint8Array(argsRaw)); actor.rLog.debug({ msg: "processing action request", actionId: id, actionName: name }); const ctx = new ActionContext( actor.actorContext, conn ); const output = await handler.onExecuteAction(ctx, name, args); actor.rLog.debug({ msg: "sending action response", actionId: id, actionName: name, outputType: typeof output, isPromise: output instanceof Promise }); conn._sendMessage( new CachedSerializer( { body: { tag: "ActionResponse", val: { id, output: bufferToArrayBuffer(cbor.encode(output)) } } }, TO_CLIENT_VERSIONED ) ); actor.rLog.debug({ msg: "action response sent", id, name }); } else if (message.body.tag === "SubscriptionRequest") { if (handler.onSubscribe === void 0 || handler.onUnsubscribe === void 0) { throw new Unsupported("Subscriptions"); } const { eventName, subscribe } = message.body.val; actor.rLog.debug({ msg: "processing subscription request", eventName, subscribe }); if (subscribe) { await handler.onSubscribe(eventName, conn); } else { await handler.onUnsubscribe(eventName, conn); } actor.rLog.debug({ msg: "subscription request completed", eventName, subscribe }); } else { assertUnreachable(message.body); } } catch (error) { const { group, code, message: message2, metadata } = deconstructError( error, actor.rLog, { connectionId: conn.id, actionId, actionName } ); actor.rLog.debug({ msg: "sending error response", actionId, actionName, code, message: message2 }); conn._sendMessage( new CachedSerializer( { body: { tag: "Error", val: { group, code, message: message2, metadata: bufferToArrayBuffer(cbor.encode(metadata)), actionId: actionId ?? null } } }, TO_CLIENT_VERSIONED ) ); actor.rLog.debug({ msg: "error response sent", actionId, actionName }); } } // src/client/config.ts var ClientConfigSchema = z2.object({ /** Endpoint to connect to for Rivet Engine or RivetKit manager API. */ endpoint: z2.string().optional().transform( (x) => x ?? getEnvUniversal("RIVET_ENGINE") ?? getEnvUniversal("RIVET_ENDPOINT") ), /** Token to use to authenticate with the API. */ token: z2.string().optional().transform((x) => x ?? getEnvUniversal("RIVET_TOKEN")), /** Namespace to connect to. */ namespace: z2.string().default(() => getEnvUniversal("RIVET_NAMESPACE") ?? "default"), /** Name of the runner. This is used to group together runners in to different pools. */ runnerName: z2.string().default(() => getEnvUniversal("RIVET_RUNNER") ?? "rivetkit"), encoding: EncodingSchema.default("bare"), transport: TransportSchema.default("websocket"), headers: z2.record(z2.string()).optional().default({}), // See RunConfig.getUpgradeWebSocket getUpgradeWebSocket: z2.custom().optional() }); // src/drivers/engine/config.ts var EngingConfigSchema = z3.object({ /** Unique key for this runner. Runners connecting a given key will replace any other runner connected with the same key. */ runnerKey: z3.string().default( () => getEnvUniversal("RIVET_RUNNER_KEY") ?? crypto.randomUUID() ), /** How many actors this runner can run. */ totalSlots: z3.number().default(1e5) }).merge(ClientConfigSchema).default({}); // src/inspector/config.ts import { z as z4 } from "zod"; var defaultTokenFn = () => { const envToken = getEnvUniversal("RIVETKIT_INSPECTOR_TOKEN"); if (envToken) { return envToken; } return ""; }; var defaultEnabled = () => { return getEnvUniversal("NODE_ENV") !== "production" || !getEnvUniversal("RIVETKIT_INSPECTOR_DISABLE"); }; var defaultInspectorOrigins = [ "http://localhost:43708", "http://localhost:43709", "https://studio.rivet.gg", "https://inspect.rivet.dev" ]; var defaultCors = { origin: (origin) => { if (defaultInspectorOrigins.includes(origin) || origin.startsWith("https://") && origin.endsWith("rivet-dev.vercel.app")) { return origin; } else { return null; } }, allowMethods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], allowHeaders: [ "Authorization", "Content-Type", "User-Agent", "baggage", "sentry-trace", "x-rivet-actor", "x-rivet-target" ], maxAge: 3600, credentials: true }; var InspectorConfigSchema = z4.object({ enabled: z4.boolean().or( z4.object({ actor: z4.boolean().optional().default(true), manager: z4.boolean().optional().default(true) }) ).optional().default(defaultEnabled), /** CORS configuration for the router. Uses Hono's CORS middleware options. */ cors: z4.custom().optional().default(() => defaultCors), /** * Token used to access the Inspector. */ token: z4.function().returns(z4.string()).optional().default(() => defaultTokenFn), /** * Default RivetKit server endpoint for Rivet Inspector to connect to. This should be the same endpoint as what you use for your Rivet client to connect to RivetKit. * * This is a convenience property just for printing out the inspector URL. */ defaultEndpoint: z4.string().optional() }).optional().default(() => ({ enabled: defaultEnabled(), token: defaultTokenFn, cors: defaultCors })); // src/registry/run-config.ts var DriverConfigSchema = z5.object({ /** Machine-readable name to identify this driver by. */ name: z5.string(), manager: z5.custom(), actor: z5.custom() }); var RunnerConfigSchema = z5.object({ driver: DriverConfigSchema.optional(), /** CORS configuration for the router. Uses Hono's CORS middleware options. */ cors: z5.custom().optional(), /** @experimental */ maxIncomingMessageSize: z5.number().optional().default(65536), /** @experimental */ inspector: InspectorConfigSchema, /** @experimental */ disableDefaultServer: z5.boolean().optional().default(false), /** @experimental */ defaultServerPort: z5.number().default(6420), /** @experimental */ runEngine: z5.boolean().optional().default(() => getEnvUniversal("RIVET_RUN_ENGINE") === "1"), /** @experimental */ runEngineVersion: z5.string().optional().default(() => getEnvUniversal("RIVET_RUN_ENGINE_VERSION") ?? "25.7.3"), /** @experimental */ overrideServerAddress: z5.string().optional(), /** @experimental */ disableActorDriver: z5.boolean().optional().default(false), /** * @experimental * * Whether to run runners normally or have them managed * serverlessly (by the Rivet Engine for example). */ runnerKind: z5.enum(["serverless", "normal"]).optional().default( () => getEnvUniversal("RIVET_RUNNER_KIND") === "serverless" ? "serverless" : "normal" ), totalSlots: z5.number().optional(), /** * @experimental * * Base path for the router. This is used to prefix all routes. * For example, if the base path is `/api`, then the route `/actors` will be * available at `/api/actors`. */ basePath: z5.string().optional().default("/"), /** * @experimental * * Disable welcome message. * */ noWelcome: z5.boolean().optional().default(false), /** * @experimental * */ logging: z5.object({ baseLogger: z5.custom().optional(), level: LogLevelSchema.optional() }).optional().default({}), /** * @experimental * * Automatically configure serverless runners in the engine. * Can only be used when runnerKind is "serverless". * If true, uses default configuration. Can also provide custom configuration. */ autoConfigureServerless: z5.union([ z5.boolean(), z5.object({ url: z5.string().optional(), headers: z5.record(z5.string(), z5.string()).optional(), maxRunners: z5.number().optional(), minRunners: z5.number().optional(), requestLifespan: z5.number().optional(), runnersMargin: z5.number().optional(), slotsPerRunner: z5.number().optional() }) ]).optional(), // This is a function to allow for lazy configuration of upgradeWebSocket on the // fly. This is required since the dependencies that upgradeWebSocket // (specifically Node.js) can sometimes only be specified after the router is // created or must be imported async using `await import(...)` getUpgradeWebSocket: z5.custom().optional() }).merge(EngingConfigSchema.removeDefault()).default({}); // src/driver-helpers/utils.ts import * as cbor2 from "cbor-x"; // dist/schemas/actor-persist/v1.ts import * as bare2 from "@bare-ts/lib"; var config2 = /* @__PURE__ */ bare2.Config({}); function readPersistedSubscription(bc) { return { eventName: bare2.readString(bc) }; } function writePersistedSubscription(bc, x) { bare2.writeString(bc, x.eventName); } function read02(bc) { const len = bare2.readUintSafe(bc); if (len === 0) { return []; } const result = [readPersistedSubscription(bc)]; for (let i = 1; i < len; i++) { result[i] = readPersistedSubscription(bc); } return result; } function write02(bc, x) { bare2.writeUintSafe(bc, x.length); for (let i = 0; i < x.length; i++) { writePersistedSubscription(bc, x[i]); } } function readPersistedConnection(bc) { return { id: bare2.readString(bc), token: bare2.readString(bc), parameters: bare2.readData(bc), state: bare2.readData(bc), subscriptions: read02(bc), lastSeen: bare2.readU64(bc) }; } function writePersistedConnection(bc, x) { bare2.writeString(bc, x.id); bare2.writeString(bc, x.token); bare2.writeData(bc, x.parameters); bare2.writeData(bc, x.state); write02(bc, x.subscriptions); bare2.writeU64(bc, x.lastSeen); } function read12(bc) { return bare2.readBool(bc) ? bare2.readData(bc) : null; } function write12(bc, x) { bare2.writeBool(bc, x !== null); if (x !== null) { bare2.writeData(bc, x); } } function readGenericPersistedScheduleEvent(bc) { return { action: bare2.readString(bc), args: read12(bc) }; } function writeGenericPersistedScheduleEvent(bc, x) { bare2.writeString(bc, x.action); write12(bc, x.args); } function readPersistedScheduleEventKind(bc) { const offset = bc.offset; const tag = bare2.readU8(bc); switch (tag) { case 0: return { tag: "GenericPersistedScheduleEvent", val: readGenericPersistedScheduleEvent(bc) }; default: { bc.offset = offset; throw new bare2.BareError(offset, "invalid tag"); } } } function writePersistedScheduleEventKind(bc, x) { switch (x.tag) { case "GenericPersistedScheduleEvent": { bare2.writeU8(bc, 0); writeGenericPersistedScheduleEvent(bc, x.val); break; } } } function readPersistedScheduleEvent(bc) { return { eventId: bare2.readString(bc), timestamp: bare2.readU64(bc), kind: readPersistedScheduleEventKind(bc) }; } function writePersistedScheduleEvent(bc, x) { bare2.writeString(bc, x.eventId); bare2.writeU64(bc, x.timestamp); writePersistedScheduleEventKind(bc, x.kind); } function read2(bc) { const len = bare2.readUintSafe(bc); if (len === 0) { return []; } const result = [readPersistedConnection(bc)]; for (let i = 1; i < len; i++) { result[i] = readPersistedConnection(bc); } return result; } function write2(bc, x) { bare2.writeUintSafe(bc, x.length); for (let i = 0; i < x.length; i++) { writePersistedConnection(bc, x[i]); } } function read3(bc) { const len = bare2.readUintSafe(bc); if (len === 0) { return []; } const result = [readPersistedScheduleEvent(bc)]; for (let i = 1; i < len; i++) { result[i] = readPersistedScheduleEvent(bc); } return result; } function write3(bc, x) { bare2.writeUintSafe(bc, x.length); for (let i = 0; i < x.length; i++) { writePersistedScheduleEvent(bc, x[i]); } } function readPersistedActor(bc) { return { input: read12(bc), hasInitialized: bare2.readBool(bc), state: bare2.readData(bc), connections: read2(bc), scheduledEvents: read3(bc) }; } function writePersistedActor(bc, x) { write12(bc, x.input); bare2.writeBool(bc, x.hasInitialized); bare2.writeData(bc, x.state); write2(bc, x.connections); write3(bc, x.scheduledEvents); } function encodePersistedActor(x) { const bc = new bare2.ByteCursor( new Uint8Array(config2.initialBufferLength), config2 ); writePersistedActor(bc, x); return new Uint8Array(bc.view.buffer, bc.view.byteOffset, bc.offset); } function decodePersistedActor(bytes) { const bc = new bare2.ByteCursor(bytes, config2); const result = readPersistedActor(bc); if (bc.offset < bc.view.byteLength) { throw new bare2.BareError(bc.offset, "remaining bytes"); } return result; } // src/schemas/actor-persist/versioned.ts var CURRENT_VERSION2 = 1; var migrations2 = /* @__PURE__ */ new Map(); var PERSISTED_ACTOR_VERSIONED = createVersionedDataHandler({ currentVersion: CURRENT_VERSION2, migrations: migrations2, serializeVersion: (data) => encodePersistedActor(data), deserializeVersion: (bytes) => decodePersistedActor(bytes) }); // src/driver-helpers/utils.ts function serializeEmptyPersistData(input) { const persistData = { input: input !== void 0 ? bufferToArrayBuffer(cbor2.encode(input)) : null, hasInitialized: false, state: bufferToArrayBuffer(cbor2.encode(void 0)), connections: [], scheduledEvents: [] }; return PERSISTED_ACTOR_VERSIONED.serializeWithEmbeddedVersion(persistData); } export { createVersionedDataHandler, TO_SERVER_VERSIONED, TO_CLIENT_VERSIONED, HTTP_ACTION_REQUEST_VERSIONED, HTTP_ACTION_RESPONSE_VERSIONED, HTTP_RESPONSE_ERROR_VERSIONED, PERSISTED_ACTOR_VERSIONED, ActionContext, inputDataToBuffer, parseMessage, processMessage, ClientConfigSchema, DriverConfigSchema, RunnerConfigSchema, serializeEmptyPersistData }; //# sourceMappingURL=chunk-QRFXXTLG.js.map