@rivetkit/cloudflare-workers 2.2.2-rc.1 → 2.3.0-rc.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +44 -6
- package/dist/mod.d.mts +44 -0
- package/dist/mod.d.ts +37 -81
- package/dist/mod.js +123 -1064
- package/dist/mod.js.map +1 -1
- package/dist/mod.mjs +152 -0
- package/dist/mod.mjs.map +1 -0
- package/package.json +52 -56
- package/LICENSE +0 -203
- package/dist/mod.cjs +0 -1093
- package/dist/mod.cjs.map +0 -1
- package/dist/mod.d.cts +0 -88
- package/src/actor-driver.ts +0 -373
- package/src/actor-handler-do.ts +0 -440
- package/src/actor-id.ts +0 -38
- package/src/actor-kv.ts +0 -120
- package/src/config.ts +0 -22
- package/src/global-kv.ts +0 -6
- package/src/handler.ts +0 -150
- package/src/log.ts +0 -5
- package/src/manager-driver.ts +0 -444
- package/src/mod.ts +0 -11
- package/src/util.ts +0 -104
- package/src/websocket.ts +0 -81
package/dist/mod.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/actor-handler-do.ts","../src/actor-driver.ts","../src/log.ts","../src/actor-kv.ts","../src/global-kv.ts","../src/handler.ts","../src/config.ts","../src/manager-driver.ts","../src/actor-id.ts","../src/util.ts","../src/websocket.ts"],"sourcesContent":["import { DurableObject, env } from \"cloudflare:workers\";\nimport type { ExecutionContext } from \"hono\";\nimport invariant from \"invariant\";\nimport type { ActorKey, ActorRouter, Registry, RegistryConfig } from \"rivetkit\";\nimport { createActorRouter, createClientWithDriver } from \"rivetkit\";\nimport type { ActorDriver, ManagerDriver } from \"rivetkit/driver-helpers\";\nimport { getInitialActorKvState } from \"rivetkit/driver-helpers\";\nimport type { GetUpgradeWebSocket } from \"rivetkit/utils\";\nimport { stringifyError } from \"rivetkit/utils\";\nimport {\n\tActorGlobalState,\n\tCloudflareDurableObjectGlobalState,\n\tcreateCloudflareActorsActorDriverBuilder,\n} from \"./actor-driver\";\nimport { buildActorId, parseActorId } from \"./actor-id\";\nimport { kvGet, kvPut } from \"./actor-kv\";\nimport { GLOBAL_KV_KEYS } from \"./global-kv\";\nimport type { Bindings } from \"./handler\";\nimport { getCloudflareAmbientEnv } from \"./handler\";\nimport { logger } from \"./log\";\nimport { CloudflareActorsManagerDriver } from \"./manager-driver\";\n\nexport interface ActorHandlerInterface extends DurableObject {\n\tcreate(req: ActorInitRequest): Promise<ActorInitResponse>;\n\tgetMetadata(): Promise<\n\t\t| {\n\t\t\t\tactorId: string;\n\t\t\t\tname: string;\n\t\t\t\tkey: ActorKey;\n\t\t\t\tdestroying: boolean;\n\t\t }\n\t\t| undefined\n\t>;\n\tmanagerKvGet(key: Uint8Array): Promise<Uint8Array | null>;\n}\n\nexport interface ActorInitRequest {\n\tname: string;\n\tkey: ActorKey;\n\tinput?: unknown;\n\tallowExisting: boolean;\n}\nexport type ActorInitResponse =\n\t| { success: { actorId: string; created: boolean } }\n\t| { error: { actorAlreadyExists: true } };\n\nexport type DurableObjectConstructor = new (\n\t...args: ConstructorParameters<typeof DurableObject<Bindings>>\n) => DurableObject<Bindings>;\n\nexport function createActorDurableObject(\n\tregistry: Registry<any>,\n\tgetUpgradeWebSocket: GetUpgradeWebSocket,\n): DurableObjectConstructor {\n\tconst globalState = new CloudflareDurableObjectGlobalState();\n\tconst parsedConfig = registry.parseConfig();\n\n\t/**\n\t * Startup steps:\n\t * 1. If not already created call `initialize`, otherwise check KV to ensure it's initialized\n\t * 2. Load actor\n\t * 3. Start service requests\n\t */\n\treturn class ActorHandler\n\t\textends DurableObject<Bindings>\n\t\timplements ActorHandlerInterface\n\t{\n\t\t/**\n\t\t * This holds a strong reference to ActorGlobalState.\n\t\t * CloudflareDurableObjectGlobalState holds a weak reference so we can\n\t\t * access it elsewhere.\n\t\t **/\n\t\t#state: ActorGlobalState;\n\n\t\tconstructor(\n\t\t\t...args: ConstructorParameters<typeof DurableObject<Bindings>>\n\t\t) {\n\t\t\tsuper(...args);\n\n\t\t\t// Initialize SQL table for key-value storage\n\t\t\t//\n\t\t\t// We do this instead of using the native KV storage so we can store blob keys. The native CF KV API only supports string keys.\n\t\t\tthis.ctx.storage.sql.exec(`\n\t\t\t\tCREATE TABLE IF NOT EXISTS _rivetkit_kv_storage(\n\t\t\t\t\tkey BLOB PRIMARY KEY,\n\t\t\t\t\tvalue BLOB\n\t\t\t\t);\n\t\t\t`);\n\n\t\t\t// Initialize SQL table for actor metadata\n\t\t\t//\n\t\t\t// id always equals 1 in order to ensure that there's always exactly 1 row in this table\n\t\t\tthis.ctx.storage.sql.exec(`\n\t\t\t\tCREATE TABLE IF NOT EXISTS _rivetkit_metadata(\n\t\t\t\t\tid INTEGER PRIMARY KEY CHECK (id = 1),\n\t\t\t\t\tname TEXT NOT NULL,\n\t\t\t\t\tkey TEXT NOT NULL,\n\t\t\t\t\tdestroyed INTEGER DEFAULT 0,\n\t\t\t\t\tgeneration INTEGER DEFAULT 0\n\t\t\t\t);\n\t\t\t`);\n\n\t\t\t// Get or create the actor state from the global WeakMap\n\t\t\tconst state = globalState.getActorState(this.ctx);\n\t\t\tif (state) {\n\t\t\t\tthis.#state = state;\n\t\t\t} else {\n\t\t\t\tthis.#state = new ActorGlobalState();\n\t\t\t\tglobalState.setActorState(this.ctx, this.#state);\n\t\t\t}\n\t\t}\n\n\t\tasync #loadActor() {\n\t\t\tinvariant(this.#state, \"State should be initialized\");\n\n\t\t\t// Check if initialized\n\t\t\tif (!this.#state.initialized) {\n\t\t\t\t// Query SQL for initialization data\n\t\t\t\tconst cursor = this.ctx.storage.sql.exec(\n\t\t\t\t\t\"SELECT name, key, destroyed, generation FROM _rivetkit_metadata WHERE id = 1\",\n\t\t\t\t);\n\t\t\t\tconst result = cursor.raw().next();\n\n\t\t\t\tif (!result.done && result.value) {\n\t\t\t\t\tconst name = result.value[0] as string;\n\t\t\t\t\tconst key = JSON.parse(\n\t\t\t\t\t\tresult.value[1] as string,\n\t\t\t\t\t) as ActorKey;\n\t\t\t\t\tconst destroyed = result.value[2] as number;\n\t\t\t\t\tconst generation = result.value[3] as number;\n\n\t\t\t\t\t// Only initialize if not destroyed\n\t\t\t\t\tif (!destroyed) {\n\t\t\t\t\t\tlogger().debug({\n\t\t\t\t\t\t\tmsg: \"already initialized\",\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\tgeneration,\n\t\t\t\t\t\t});\n\n\t\t\t\t\t\tthis.#state.initialized = { name, key, generation };\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogger().debug(\"actor is destroyed, cannot load\");\n\t\t\t\t\t\tthrow new Error(\"Actor is destroyed\");\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlogger().debug(\"not initialized\");\n\t\t\t\t\tthrow new Error(\"Actor is not initialized\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Check if already loaded\n\t\t\tif (this.#state.actor) {\n\t\t\t\t// Assert that the cached actor has the correct generation\n\t\t\t\t// This will catch any cases where #state.actor has a stale generation\n\t\t\t\tinvariant(\n\t\t\t\t\t!this.#state.initialized ||\n\t\t\t\t\t\tthis.#state.actor.generation ===\n\t\t\t\t\t\t\tthis.#state.initialized.generation,\n\t\t\t\t\t`Stale actor cached: actor generation ${this.#state.actor.generation} != initialized generation ${this.#state.initialized?.generation}. This should not happen.`,\n\t\t\t\t);\n\t\t\t\treturn this.#state.actor;\n\t\t\t}\n\n\t\t\tif (!this.#state.initialized) throw new Error(\"Not initialized\");\n\n\t\t\t// Register DO with global state first\n\t\t\t// HACK: This leaks the DO context, but DO does not provide a native way\n\t\t\t// of knowing when the DO shuts down. We're making a broad assumption\n\t\t\t// that DO will boot a new isolate frequenlty enough that this is not an issue.\n\t\t\tconst actorId = this.ctx.id.toString();\n\t\t\tglobalState.setDOState(actorId, { ctx: this.ctx, env: env });\n\n\t\t\t// Create manager driver\n\t\t\tconst managerDriver = new CloudflareActorsManagerDriver();\n\n\t\t\t// Create inline client\n\t\t\t// Avoid expensive type expansion in downstream DTS generation.\n\t\t\tconst inlineClient: any = (createClientWithDriver as any)(\n\t\t\t\tmanagerDriver,\n\t\t\t);\n\n\t\t\t// Create actor driver builder\n\t\t\tconst actorDriverBuilder =\n\t\t\t\tcreateCloudflareActorsActorDriverBuilder(globalState);\n\n\t\t\t// Create actor driver\n\t\t\tconst actorDriver = actorDriverBuilder(\n\t\t\t\tparsedConfig,\n\t\t\t\tmanagerDriver,\n\t\t\t\tinlineClient,\n\t\t\t);\n\n\t\t\t// Create actor router\n\t\t\tconst actorRouter = createActorRouter(\n\t\t\t\tparsedConfig,\n\t\t\t\tactorDriver,\n\t\t\t\tgetUpgradeWebSocket,\n\t\t\t\tregistry.config.test?.enabled ?? false,\n\t\t\t);\n\n\t\t\t// Save actor with generation\n\t\t\tthis.#state.actor = {\n\t\t\t\tactorRouter,\n\t\t\t\tactorDriver,\n\t\t\t\tgeneration: this.#state.initialized.generation,\n\t\t\t};\n\n\t\t\t// Build actor ID with generation for loading\n\t\t\tconst actorIdWithGen = buildActorId(\n\t\t\t\tactorId,\n\t\t\t\tthis.#state.initialized.generation,\n\t\t\t);\n\n\t\t\t// Initialize the actor instance with proper metadata\n\t\t\t// This ensures the actor driver knows about this actor\n\t\t\tawait actorDriver.loadActor(actorIdWithGen);\n\n\t\t\treturn this.#state.actor;\n\t\t}\n\n\t\t/** RPC called to get actor metadata without creating it */\n\t\tasync getMetadata(): Promise<\n\t\t\t| {\n\t\t\t\t\tactorId: string;\n\t\t\t\t\tname: string;\n\t\t\t\t\tkey: ActorKey;\n\t\t\t\t\tdestroying: boolean;\n\t\t\t }\n\t\t\t| undefined\n\t\t> {\n\t\t\t// Query the metadata\n\t\t\tconst cursor = this.ctx.storage.sql.exec(\n\t\t\t\t\"SELECT name, key, destroyed, generation FROM _rivetkit_metadata WHERE id = 1\",\n\t\t\t);\n\t\t\tconst result = cursor.raw().next();\n\n\t\t\tif (!result.done && result.value) {\n\t\t\t\tconst name = result.value[0] as string;\n\t\t\t\tconst key = JSON.parse(result.value[1] as string) as ActorKey;\n\t\t\t\tconst destroyed = result.value[2] as number;\n\t\t\t\tconst generation = result.value[3] as number;\n\n\t\t\t\t// Check if destroyed\n\t\t\t\tif (destroyed) {\n\t\t\t\t\tlogger().debug({\n\t\t\t\t\t\tmsg: \"getMetadata: actor is destroyed\",\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\tgeneration,\n\t\t\t\t\t});\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\n\t\t\t\t// Build actor ID with generation\n\t\t\t\tconst doId = this.ctx.id.toString();\n\t\t\t\tconst actorId = buildActorId(doId, generation);\n\t\t\t\tconst destroying =\n\t\t\t\t\tglobalState.getActorState(this.ctx)?.destroying ?? false;\n\n\t\t\t\tlogger().debug({\n\t\t\t\t\tmsg: \"getMetadata: found actor metadata\",\n\t\t\t\t\tactorId,\n\t\t\t\t\tname,\n\t\t\t\t\tkey,\n\t\t\t\t\tgeneration,\n\t\t\t\t\tdestroying,\n\t\t\t\t});\n\n\t\t\t\treturn { actorId, name, key, destroying };\n\t\t\t}\n\n\t\t\tlogger().debug({\n\t\t\t\tmsg: \"getMetadata: no metadata found\",\n\t\t\t});\n\t\t\treturn undefined;\n\t\t}\n\n\t\t/** RPC called by ManagerDriver.kvGet to read from KV. */\n\t\tasync managerKvGet(key: Uint8Array): Promise<Uint8Array | null> {\n\t\t\treturn kvGet(this.ctx.storage.sql, key);\n\t\t}\n\n\t\t/** RPC called by the manager to create a DO. Can optionally allow existing actors. */\n\t\tasync create(req: ActorInitRequest): Promise<ActorInitResponse> {\n\t\t\t// Check if actor exists\n\t\t\tconst checkCursor = this.ctx.storage.sql.exec(\n\t\t\t\t\"SELECT destroyed, generation FROM _rivetkit_metadata WHERE id = 1\",\n\t\t\t);\n\t\t\tconst checkResult = checkCursor.raw().next();\n\n\t\t\tlet created = false;\n\t\t\tlet generation = 0;\n\n\t\t\tif (!checkResult.done && checkResult.value) {\n\t\t\t\tconst destroyed = checkResult.value[0] as number;\n\t\t\t\tgeneration = checkResult.value[1] as number;\n\n\t\t\t\tif (!destroyed) {\n\t\t\t\t\t// Actor exists and is not destroyed\n\t\t\t\t\tif (!req.allowExisting) {\n\t\t\t\t\t\t// Fail if not allowing existing actors\n\t\t\t\t\t\tlogger().debug({\n\t\t\t\t\t\t\tmsg: \"create failed: actor already exists\",\n\t\t\t\t\t\t\tname: req.name,\n\t\t\t\t\t\t\tkey: req.key,\n\t\t\t\t\t\t\tgeneration,\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn { error: { actorAlreadyExists: true } };\n\t\t\t\t\t}\n\n\t\t\t\t\t// Return existing actor\n\t\t\t\t\tlogger().debug({\n\t\t\t\t\t\tmsg: \"actor already exists\",\n\t\t\t\t\t\tkey: req.key,\n\t\t\t\t\t\tgeneration,\n\t\t\t\t\t});\n\t\t\t\t\tconst doId = this.ctx.id.toString();\n\t\t\t\t\tconst actorId = buildActorId(doId, generation);\n\t\t\t\t\treturn { success: { actorId, created: false } };\n\t\t\t\t}\n\n\t\t\t\t// Actor exists but is destroyed - resurrect with incremented generation\n\t\t\t\tgeneration = generation + 1;\n\t\t\t\tcreated = true;\n\n\t\t\t\t// Clear stale actor from previous generation\n\t\t\t\t// This is necessary because the DO instance may still be in memory\n\t\t\t\t// with the old #state.actor field from before the destroy\n\t\t\t\tif (this.#state) {\n\t\t\t\t\tthis.#state.actor = undefined;\n\t\t\t\t}\n\n\t\t\t\tlogger().debug({\n\t\t\t\t\tmsg: \"resurrecting destroyed actor\",\n\t\t\t\t\tkey: req.key,\n\t\t\t\t\toldGeneration: generation - 1,\n\t\t\t\t\tnewGeneration: generation,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\t// No actor exists - will create with generation 0\n\t\t\t\tgeneration = 0;\n\t\t\t\tcreated = true;\n\t\t\t\tlogger().debug({\n\t\t\t\t\tmsg: \"creating new actor\",\n\t\t\t\t\tkey: req.key,\n\t\t\t\t\tgeneration,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Perform upsert - either inserts new or updates destroyed actor\n\t\t\tthis.ctx.storage.sql.exec(\n\t\t\t\t`INSERT INTO _rivetkit_metadata (id, name, key, destroyed, generation)\n\t\t\t\tVALUES (1, ?, ?, 0, ?)\n\t\t\t\tON CONFLICT(id) DO UPDATE SET\n\t\t\t\t\tname = excluded.name,\n\t\t\t\t\tkey = excluded.key,\n\t\t\t\t\tdestroyed = 0,\n\t\t\t\t\tgeneration = excluded.generation`,\n\t\t\t\treq.name,\n\t\t\t\tJSON.stringify(req.key),\n\t\t\t\tgeneration,\n\t\t\t);\n\n\t\t\tthis.#state.initialized = {\n\t\t\t\tname: req.name,\n\t\t\t\tkey: req.key,\n\t\t\t\tgeneration,\n\t\t\t};\n\n\t\t\t// Build actor ID with generation\n\t\t\tconst doId = this.ctx.id.toString();\n\t\t\tconst actorId = buildActorId(doId, generation);\n\n\t\t\t// Initialize storage and update KV when created or resurrected\n\t\t\tif (created) {\n\t\t\t\t// Initialize persist data in KV storage\n\t\t\t\tinitializeActorKvStorage(this.ctx.storage.sql, req.input);\n\n\t\t\t\t// Update metadata in the background\n\t\t\t\tconst env = getCloudflareAmbientEnv();\n\t\t\t\tconst actorData = { name: req.name, key: req.key, generation };\n\t\t\t\tthis.ctx.waitUntil(\n\t\t\t\t\tenv.ACTOR_KV.put(\n\t\t\t\t\t\tGLOBAL_KV_KEYS.actorMetadata(actorId),\n\t\t\t\t\t\tJSON.stringify(actorData),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Preemptively load actor so the lifecycle hooks are called\n\t\t\tawait this.#loadActor();\n\n\t\t\tlogger().debug({\n\t\t\t\tmsg: created\n\t\t\t\t\t? \"actor created/resurrected\"\n\t\t\t\t\t: \"returning existing actor\",\n\t\t\t\tactorId,\n\t\t\t\tcreated,\n\t\t\t\tgeneration,\n\t\t\t});\n\n\t\t\treturn { success: { actorId, created } };\n\t\t}\n\n\t\tasync fetch(request: Request): Promise<Response> {\n\t\t\tconst { actorRouter, generation } = await this.#loadActor();\n\n\t\t\t// Build actor ID with generation\n\t\t\tconst doId = this.ctx.id.toString();\n\t\t\tconst actorId = buildActorId(doId, generation);\n\n\t\t\treturn await actorRouter.fetch(request, {\n\t\t\t\tactorId,\n\t\t\t});\n\t\t}\n\n\t\tasync alarm(): Promise<void> {\n\t\t\tconst { actorDriver, generation } = await this.#loadActor();\n\n\t\t\t// Build actor ID with generation\n\t\t\tconst doId = this.ctx.id.toString();\n\t\t\tconst actorId = buildActorId(doId, generation);\n\n\t\t\t// Load the actor instance and trigger alarm\n\t\t\tconst actor = await actorDriver.loadActor(actorId);\n\t\t\tawait actor.onAlarm();\n\t\t}\n\t};\n}\n\nfunction initializeActorKvStorage(\n\tsql: SqlStorage,\n\tinput: unknown | undefined,\n): void {\n\tconst initialKvState = getInitialActorKvState(input);\n\tfor (const [key, value] of initialKvState) {\n\t\tkvPut(sql, key, value);\n\t}\n}\n","import invariant from \"invariant\";\nimport type {\n\tActorKey,\n\tActorRouter,\n\tAnyActorInstance as CoreAnyActorInstance,\n\tRegistryConfig,\n} from \"rivetkit\";\nimport { lookupInRegistry } from \"rivetkit\";\nimport type {\n\tActorDriver,\n\tAnyActorInstance,\n\tManagerDriver,\n} from \"rivetkit/driver-helpers\";\nimport { promiseWithResolvers } from \"rivetkit/utils\";\nimport { logger } from \"./log\";\nimport {\n\tkvDelete,\n\tkvDeleteRange,\n\tkvGet,\n\tkvListPrefix,\n\tkvListRange,\n\tkvPut,\n} from \"./actor-kv\";\nimport { GLOBAL_KV_KEYS } from \"./global-kv\";\nimport { getCloudflareAmbientEnv } from \"./handler\";\nimport { parseActorId } from \"./actor-id\";\n\ninterface DurableObjectGlobalState {\n\tctx: DurableObjectState;\n\tenv: unknown;\n}\n\n/**\n * Cloudflare DO can have multiple DO running within the same global scope.\n *\n * This allows for storing the actor context globally and looking it up by ID in `CloudflareActorsActorDriver`.\n */\nexport class CloudflareDurableObjectGlobalState {\n\t// Map of actor ID -> DO state\n\t#dos: Map<string, DurableObjectGlobalState> = new Map();\n\n\t// WeakMap of DO state -> ActorGlobalState for proper GC\n\t#actors: WeakMap<DurableObjectState, ActorGlobalState> = new WeakMap();\n\n\tgetDOState(doId: string): DurableObjectGlobalState {\n\t\tconst state = this.#dos.get(doId);\n\t\tinvariant(\n\t\t\tstate !== undefined,\n\t\t\t\"durable object state not in global state\",\n\t\t);\n\t\treturn state;\n\t}\n\n\tsetDOState(doId: string, state: DurableObjectGlobalState) {\n\t\tthis.#dos.set(doId, state);\n\t}\n\n\tgetActorState(ctx: DurableObjectState): ActorGlobalState | undefined {\n\t\treturn this.#actors.get(ctx);\n\t}\n\n\tsetActorState(ctx: DurableObjectState, actorState: ActorGlobalState): void {\n\t\tthis.#actors.set(ctx, actorState);\n\t}\n}\n\nexport interface DriverContext {\n\tstate: DurableObjectState;\n}\n\ninterface InitializedData {\n\tname: string;\n\tkey: ActorKey;\n\tgeneration: number;\n}\n\ninterface LoadedActor {\n\tactorRouter: ActorRouter;\n\tactorDriver: ActorDriver;\n\tgeneration: number;\n}\n\n// Actor global state to track running instances\nexport class ActorGlobalState {\n\t// Initialization state\n\tinitialized?: InitializedData;\n\n\t// Loaded actor state\n\tactor?: LoadedActor;\n\tactorInstance?: AnyActorInstance;\n\tactorPromise?: ReturnType<typeof promiseWithResolvers<void>>;\n\n\t/**\n\t * Indicates if `startDestroy` has been called.\n\t *\n\t * This is stored in memory instead of SQLite since the destroy may be cancelled.\n\t *\n\t * See the corresponding `destroyed` property in SQLite metadata.\n\t */\n\tdestroying: boolean = false;\n\n\treset() {\n\t\tthis.initialized = undefined;\n\t\tthis.actor = undefined;\n\t\tthis.actorInstance = undefined;\n\t\tthis.actorPromise = undefined;\n\t\tthis.destroying = false;\n\t}\n}\n\nexport class CloudflareActorsActorDriver implements ActorDriver {\n\t#registryConfig: RegistryConfig;\n\t#managerDriver: ManagerDriver;\n\t#inlineClient: any;\n\t#globalState: CloudflareDurableObjectGlobalState;\n\n\tconstructor(\n\t\tregistryConfig: RegistryConfig,\n\t\tmanagerDriver: ManagerDriver,\n\t\tinlineClient: any,\n\t\tglobalState: CloudflareDurableObjectGlobalState,\n\t) {\n\t\tthis.#registryConfig = registryConfig;\n\t\tthis.#managerDriver = managerDriver;\n\t\tthis.#inlineClient = inlineClient;\n\t\tthis.#globalState = globalState;\n\t}\n\n\t#getDOCtx(actorId: string) {\n\t\t// Parse actor ID to get DO ID\n\t\tconst [doId] = parseActorId(actorId);\n\t\treturn this.#globalState.getDOState(doId).ctx;\n\t}\n\n\tasync loadActor(actorId: string): Promise<AnyActorInstance> {\n\t\t// Parse actor ID to get DO ID and generation\n\t\tconst [doId, expectedGeneration] = parseActorId(actorId);\n\n\t\t// Get the DO state\n\t\tconst doState = this.#globalState.getDOState(doId);\n\n\t\t// Check if actor is already loaded\n\t\tlet actorState = this.#globalState.getActorState(doState.ctx);\n\t\tif (actorState?.actorInstance) {\n\t\t\t// Actor is already loaded, return it\n\t\t\treturn actorState.actorInstance;\n\t\t}\n\n\t\t// Create new actor state if it doesn't exist\n\t\tif (!actorState) {\n\t\t\tactorState = new ActorGlobalState();\n\t\t\tactorState.actorPromise = promiseWithResolvers((reason) =>\n\t\t\t\tlogger().warn({\n\t\t\t\t\tmsg: \"unhandled actor promise rejection\",\n\t\t\t\t\treason,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tthis.#globalState.setActorState(doState.ctx, actorState);\n\t\t} else if (actorState.actorPromise) {\n\t\t\t// Another request is already loading this actor, wait for it\n\t\t\tawait actorState.actorPromise.promise;\n\t\t\tif (!actorState.actorInstance) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Actor ${actorId} failed to load in concurrent request`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn actorState.actorInstance;\n\t\t}\n\n\t\t// Load actor metadata\n\t\tconst sql = doState.ctx.storage.sql;\n\t\tconst cursor = sql.exec(\n\t\t\t\"SELECT name, key, destroyed, generation FROM _rivetkit_metadata LIMIT 1\",\n\t\t);\n\t\tconst result = cursor.raw().next();\n\n\t\tif (result.done || !result.value) {\n\t\t\tthrow new Error(\n\t\t\t\t`Actor ${actorId} is not initialized - missing metadata`,\n\t\t\t);\n\t\t}\n\n\t\tconst name = result.value[0] as string;\n\t\tconst key = JSON.parse(result.value[1] as string) as string[];\n\t\tconst destroyed = result.value[2] as number;\n\t\tconst generation = result.value[3] as number;\n\n\t\t// Check if actor is destroyed\n\t\tif (destroyed) {\n\t\t\tthrow new Error(`Actor ${actorId} is destroyed`);\n\t\t}\n\n\t\t// Check if generation matches\n\t\tif (generation !== expectedGeneration) {\n\t\t\tthrow new Error(\n\t\t\t\t`Actor ${actorId} generation mismatch - expected ${expectedGeneration}, got ${generation}`,\n\t\t\t);\n\t\t}\n\n\t\t// Create actor instance\n\t\tconst definition = lookupInRegistry(this.#registryConfig, name);\n\t\tactorState.actorInstance = definition.instantiate();\n\n\t\t// Start actor\n\t\tconst actorInstance = actorState.actorInstance as any;\n\t\tawait actorInstance.start(\n\t\t\tthis,\n\t\t\tthis.#inlineClient,\n\t\t\tactorId,\n\t\t\tname,\n\t\t\tkey,\n\t\t\t\"unknown\", // TODO: Support regions in Cloudflare\n\t\t);\n\n\t\t// Finish\n\t\tactorState.actorPromise?.resolve();\n\t\tactorState.actorPromise = undefined;\n\n\t\treturn actorState.actorInstance;\n\t}\n\n\tgetContext(actorId: string): DriverContext {\n\t\t// Parse actor ID to get DO ID\n\t\tconst [doId] = parseActorId(actorId);\n\t\tconst state = this.#globalState.getDOState(doId);\n\t\treturn { state: state.ctx };\n\t}\n\n\tasync setAlarm(actor: AnyActorInstance, timestamp: number): Promise<void> {\n\t\tawait this.#getDOCtx(actor.id).storage.setAlarm(timestamp);\n\t}\n\n\tasync getDatabase(actorId: string): Promise<unknown | undefined> {\n\t\treturn this.#getDOCtx(actorId).storage.sql;\n\t}\n\n\t// Batch KV operations\n\tasync kvBatchPut(\n\t\tactorId: string,\n\t\tentries: [Uint8Array, Uint8Array][],\n\t): Promise<void> {\n\t\tconst sql = this.#getDOCtx(actorId).storage.sql;\n\n\t\tfor (const [key, value] of entries) {\n\t\t\tkvPut(sql, key, value);\n\t\t}\n\t}\n\n\tasync kvBatchGet(\n\t\tactorId: string,\n\t\tkeys: Uint8Array[],\n\t): Promise<(Uint8Array | null)[]> {\n\t\tconst sql = this.#getDOCtx(actorId).storage.sql;\n\n\t\tconst results: (Uint8Array | null)[] = [];\n\t\tfor (const key of keys) {\n\t\t\tresults.push(kvGet(sql, key));\n\t\t}\n\n\t\treturn results;\n\t}\n\n\tasync kvBatchDelete(actorId: string, keys: Uint8Array[]): Promise<void> {\n\t\tconst sql = this.#getDOCtx(actorId).storage.sql;\n\n\t\tfor (const key of keys) {\n\t\t\tkvDelete(sql, key);\n\t\t}\n\t}\n\n\tasync kvDeleteRange(\n\t\tactorId: string,\n\t\tstart: Uint8Array,\n\t\tend: Uint8Array,\n\t): Promise<void> {\n\t\tconst sql = this.#getDOCtx(actorId).storage.sql;\n\t\tkvDeleteRange(sql, start, end);\n\t}\n\n\tasync kvListPrefix(\n\t\tactorId: string,\n\t\tprefix: Uint8Array,\n\t\toptions?: {\n\t\t\treverse?: boolean;\n\t\t\tlimit?: number;\n\t\t},\n\t): Promise<[Uint8Array, Uint8Array][]> {\n\t\tconst sql = this.#getDOCtx(actorId).storage.sql;\n\n\t\treturn kvListPrefix(sql, prefix, options);\n\t}\n\n\tasync kvListRange(\n\t\tactorId: string,\n\t\tstart: Uint8Array,\n\t\tend: Uint8Array,\n\t\toptions?: {\n\t\t\treverse?: boolean;\n\t\t\tlimit?: number;\n\t\t},\n\t): Promise<[Uint8Array, Uint8Array][]> {\n\t\tconst sql = this.#getDOCtx(actorId).storage.sql;\n\t\treturn kvListRange(sql, start, end, options);\n\t}\n\n\tstartDestroy(actorId: string): void {\n\t\t// Parse actor ID to get DO ID and generation\n\t\tconst [doId, generation] = parseActorId(actorId);\n\n\t\t// Get the DO state\n\t\tconst doState = this.#globalState.getDOState(doId);\n\t\tconst actorState = this.#globalState.getActorState(doState.ctx);\n\n\t\t// Actor not loaded, nothing to destroy\n\t\tif (!actorState?.actorInstance) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Check if already destroying\n\t\tif (actorState.destroying) {\n\t\t\treturn;\n\t\t}\n\t\tactorState.destroying = true;\n\n\t\t// Spawn onStop in background\n\t\tthis.#callOnStopAsync(actorId, doId, actorState.actorInstance);\n\t}\n\n\tasync #callOnStopAsync(\n\t\tactorId: string,\n\t\tdoId: string,\n\t\tactor: CoreAnyActorInstance,\n\t) {\n\t\t// Stop\n\t\tawait actor.onStop(\"destroy\");\n\n\t\t// Remove state\n\t\tconst doState = this.#globalState.getDOState(doId);\n\t\tconst sql = doState.ctx.storage.sql;\n\t\tsql.exec(\"UPDATE _rivetkit_metadata SET destroyed = 1 WHERE 1=1\");\n\t\tsql.exec(\"DELETE FROM _rivetkit_kv_storage\");\n\n\t\t// Clear any scheduled alarms\n\t\tawait doState.ctx.storage.deleteAlarm();\n\n\t\t// Delete from ACTOR_KV in the background - use full actorId including generation\n\t\tconst env = getCloudflareAmbientEnv();\n\t\tdoState.ctx.waitUntil(\n\t\t\tenv.ACTOR_KV.delete(GLOBAL_KV_KEYS.actorMetadata(actorId)),\n\t\t);\n\n\t\t// Reset global state using the DO context\n\t\tconst actorHandle = this.#globalState.getActorState(doState.ctx);\n\t\tactorHandle?.reset();\n\t}\n}\n\nexport function createCloudflareActorsActorDriverBuilder(\n\tglobalState: CloudflareDurableObjectGlobalState,\n) {\n\treturn (\n\t\tconfig: RegistryConfig,\n\t\tmanagerDriver: ManagerDriver,\n\t\tinlineClient: any,\n\t) => {\n\t\treturn new CloudflareActorsActorDriver(\n\t\t\tconfig,\n\t\t\tmanagerDriver,\n\t\t\tinlineClient,\n\t\t\tglobalState,\n\t\t);\n\t};\n}\n","import { getLogger } from \"rivetkit/log\";\n\nexport function logger() {\n\treturn getLogger(\"driver-cloudflare-workers\");\n}\n","const DEFAULT_LIST_LIMIT = 16_384;\n\nexport function kvGet(sql: SqlStorage, key: Uint8Array): Uint8Array | null {\n\tconst cursor = sql.exec(\n\t\t\"SELECT value FROM _rivetkit_kv_storage WHERE key = ?\",\n\t\tkey,\n\t);\n\tconst result = cursor.raw().next();\n\n\tif (!result.done && result.value) {\n\t\treturn toUint8Array(result.value[0]);\n\t}\n\treturn null;\n}\n\nexport function kvPut(\n\tsql: SqlStorage,\n\tkey: Uint8Array,\n\tvalue: Uint8Array,\n): void {\n\tsql.exec(\n\t\t\"INSERT OR REPLACE INTO _rivetkit_kv_storage (key, value) VALUES (?, ?)\",\n\t\tkey,\n\t\tvalue,\n\t);\n}\n\nexport function kvDelete(sql: SqlStorage, key: Uint8Array): void {\n\tsql.exec(\"DELETE FROM _rivetkit_kv_storage WHERE key = ?\", key);\n}\n\nexport function kvDeleteRange(\n\tsql: SqlStorage,\n\tstart: Uint8Array,\n\tend: Uint8Array,\n): void {\n\tsql.exec(\n\t\t\"DELETE FROM _rivetkit_kv_storage WHERE key >= ? AND key < ?\",\n\t\tstart,\n\t\tend,\n\t);\n}\n\nexport function kvListPrefix(\n\tsql: SqlStorage,\n\tprefix: Uint8Array,\n\toptions?: {\n\t\treverse?: boolean;\n\t\tlimit?: number;\n\t},\n): [Uint8Array, Uint8Array][] {\n\tconst upperBound = computePrefixUpperBound(prefix);\n\tif (upperBound) {\n\t\treturn kvListRange(sql, prefix, upperBound, options);\n\t}\n\n\tconst direction = options?.reverse ? \"DESC\" : \"ASC\";\n\tconst limit = options?.limit ?? DEFAULT_LIST_LIMIT;\n\tconst cursor = sql.exec(\n\t\t`SELECT key, value FROM _rivetkit_kv_storage WHERE key >= ? ORDER BY key ${direction} LIMIT ?`,\n\t\tprefix,\n\t\tlimit,\n\t);\n\treturn readEntries(cursor);\n}\n\nexport function kvListRange(\n\tsql: SqlStorage,\n\tstart: Uint8Array,\n\tend: Uint8Array,\n\toptions?: {\n\t\treverse?: boolean;\n\t\tlimit?: number;\n\t},\n): [Uint8Array, Uint8Array][] {\n\tconst direction = options?.reverse ? \"DESC\" : \"ASC\";\n\tconst limit = options?.limit ?? DEFAULT_LIST_LIMIT;\n\tconst cursor = sql.exec(\n\t\t`SELECT key, value FROM _rivetkit_kv_storage WHERE key >= ? AND key < ? ORDER BY key ${direction} LIMIT ?`,\n\t\tstart,\n\t\tend,\n\t\tlimit,\n\t);\n\treturn readEntries(cursor);\n}\n\nfunction toUint8Array(\n\tvalue: string | number | ArrayBuffer | Uint8Array | null,\n): Uint8Array {\n\tif (value instanceof Uint8Array) {\n\t\treturn value;\n\t}\n\tif (value instanceof ArrayBuffer) {\n\t\treturn new Uint8Array(value);\n\t}\n\tthrow new Error(\n\t\t`Unexpected SQL value type: ${typeof value} (${value?.constructor?.name})`,\n\t);\n}\n\nfunction readEntries(\n\tcursor: ReturnType<SqlStorage[\"exec\"]>,\n): [Uint8Array, Uint8Array][] {\n\tconst entries: [Uint8Array, Uint8Array][] = [];\n\tfor (const row of cursor.raw()) {\n\t\tentries.push([toUint8Array(row[0]), toUint8Array(row[1])]);\n\t}\n\treturn entries;\n}\n\nfunction computePrefixUpperBound(prefix: Uint8Array): Uint8Array | null {\n\tconst upperBound = prefix.slice();\n\tfor (let i = upperBound.length - 1; i >= 0; i--) {\n\t\tif (upperBound[i] !== 0xff) {\n\t\t\tupperBound[i]++;\n\t\t\treturn upperBound.slice(0, i + 1);\n\t\t}\n\t}\n\treturn null;\n}\n","/** KV keys for using Workers KV to store actor metadata globally. */\nexport const GLOBAL_KV_KEYS = {\n\tactorMetadata: (actorId: string): string => {\n\t\treturn `actor:${actorId}:metadata`;\n\t},\n};\n","import { env } from \"cloudflare:workers\";\nimport type { Client, Registry } from \"rivetkit\";\nimport { createClientWithDriver } from \"rivetkit\";\nimport { buildManagerRouter } from \"rivetkit/driver-helpers\";\nimport {\n\ttype ActorHandlerInterface,\n\tcreateActorDurableObject,\n\ttype DurableObjectConstructor,\n} from \"./actor-handler-do\";\nimport { type Config, ConfigSchema, type InputConfig } from \"./config\";\nimport { CloudflareActorsManagerDriver } from \"./manager-driver\";\nimport { upgradeWebSocket } from \"./websocket\";\n\n/** Cloudflare Workers env */\nexport interface Bindings {\n\tACTOR_KV: KVNamespace;\n\tACTOR_DO: DurableObjectNamespace<ActorHandlerInterface>;\n}\n\n/**\n * Stores the env for the current request. Required since some contexts like the inline client driver does not have access to the Hono context.\n *\n * Use getCloudflareAmbientEnv unless using CF_AMBIENT_ENV.run.\n */\nexport function getCloudflareAmbientEnv(): Bindings {\n\treturn env as unknown as Bindings;\n}\n\nexport interface InlineOutput<A extends Registry<any>> {\n\t/** Client to communicate with the actors. */\n\tclient: Client<A>;\n\n\t/** Fetch handler to manually route requests to the Rivet manager API. */\n\tfetch: (request: Request, ...args: any) => Response | Promise<Response>;\n\n\tconfig: Config;\n\n\tActorHandler: DurableObjectConstructor;\n}\n\nexport interface HandlerOutput {\n\thandler: ExportedHandler<Bindings>;\n\tActorHandler: DurableObjectConstructor;\n}\n\n/**\n * Creates an inline client for accessing Rivet Actors privately without a public manager API.\n *\n * If you want to expose a public manager API, either:\n *\n * - Use `createHandler` to expose the Rivet API on `/api/rivet`\n * - Forward Rivet API requests to `InlineOutput::fetch`\n */\nexport function createInlineClient<R extends Registry<any>>(\n\tregistry: R,\n\tinputConfig?: InputConfig,\n): InlineOutput<R> {\n\t// HACK: Cloudflare does not support using `crypto.randomUUID()` before start, so we pass a default value\n\t//\n\t// Runner key is not used on Cloudflare\n\tinputConfig = { ...inputConfig, runnerKey: \"\" };\n\n\t// Parse config\n\tconst config = ConfigSchema.parse(inputConfig);\n\n\t// Create Durable Object\n\tconst ActorHandler = createActorDurableObject(\n\t\tregistry,\n\t\t() => upgradeWebSocket,\n\t);\n\n\t// Configure registry for cloudflare-workers\n\tregistry.config.noWelcome = true;\n\t// Disable inspector since it's not supported on Cloudflare Workers\n\tregistry.config.inspector = {\n\t\tenabled: false,\n\t\ttoken: () => \"\",\n\t};\n\t// Set manager base path to \"/\" since the cloudflare handler strips the /api/rivet prefix\n\tregistry.config.managerBasePath = \"/\";\n\tconst parsedConfig = registry.parseConfig();\n\n\t// Create manager driver\n\tconst managerDriver = new CloudflareActorsManagerDriver();\n\n\t// Build the manager router (has actor management endpoints like /actors)\n\tconst { router } = buildManagerRouter(\n\t\tparsedConfig,\n\t\tmanagerDriver,\n\t\t() => upgradeWebSocket,\n\t);\n\n\t// Create client using the manager driver\n\t// Avoid excessive generic expansion in DTS generation.\n\tconst client = (createClientWithDriver as any)(managerDriver) as Client<R>;\n\n\treturn { client, fetch: router.fetch.bind(router), config, ActorHandler };\n}\n\n/**\n * Creates a handler to be exported from a Cloudflare Worker.\n *\n * This will automatically expose the Rivet manager API on `/api/rivet`.\n *\n * This includes a `fetch` handler and `ActorHandler` Durable Object.\n */\nexport function createHandler(\n\tregistry: Registry<any>,\n\tinputConfig?: InputConfig,\n): HandlerOutput {\n\tconst inline = (createInlineClient as any)(registry, inputConfig);\n\tconst client = inline.client as any;\n\tconst fetch = inline.fetch as (\n\t\trequest: Request,\n\t\t...args: any\n\t) => Response | Promise<Response>;\n\tconst config = inline.config as Config;\n\tconst ActorHandler = inline.ActorHandler as DurableObjectConstructor;\n\n\t// Create Cloudflare handler\n\tconst handler = {\n\t\tfetch: async (request, cfEnv, ctx) => {\n\t\t\tconst url = new URL(request.url);\n\n\t\t\t// Inject Rivet env\n\t\t\tconst env = Object.assign({ RIVET: client }, cfEnv);\n\n\t\t\t// Mount Rivet manager API\n\t\t\tif (url.pathname.startsWith(config.managerPath)) {\n\t\t\t\tconst strippedPath = url.pathname.substring(\n\t\t\t\t\tconfig.managerPath.length,\n\t\t\t\t);\n\t\t\t\turl.pathname = strippedPath;\n\t\t\t\tconst modifiedRequest = new Request(url.toString(), request);\n\t\t\t\treturn fetch(modifiedRequest, env, ctx);\n\t\t\t}\n\n\t\t\tif (config.fetch) {\n\t\t\t\treturn config.fetch(request, env, ctx);\n\t\t\t} else {\n\t\t\t\treturn new Response(\n\t\t\t\t\t\"This is a RivetKit server.\\n\\nLearn more at https://rivet.dev\\n\",\n\t\t\t\t\t{ status: 200 },\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t} satisfies ExportedHandler<Bindings>;\n\n\treturn { handler, ActorHandler };\n}\n","import type { Client } from \"rivetkit\";\nimport { z } from \"zod/v4\";\n\nconst ConfigSchemaBase = z.object({\n\t/** Path that the Rivet manager API will be mounted. */\n\tmanagerPath: z.string().optional().default(\"/api/rivet\"),\n\n\t/** Deprecated. Runner key for authentication. */\n\trunnerKey: z.string().optional(),\n\n\t/** Disable the welcome message. */\n\tnoWelcome: z.boolean().optional().default(false),\n\n\tfetch: z\n\t\t.custom<ExportedHandlerFetchHandler<{ RIVET: Client<any> }, unknown>>()\n\t\t.optional(),\n});\nexport const ConfigSchema = ConfigSchemaBase.default(() =>\n\tConfigSchemaBase.parse({}),\n);\nexport type InputConfig = z.input<typeof ConfigSchema>;\nexport type Config = z.infer<typeof ConfigSchema>;\n","import type { Hono, Context as HonoContext } from \"hono\";\nimport type { Encoding, RegistryConfig, UniversalWebSocket } from \"rivetkit\";\nimport {\n\ttype ActorOutput,\n\ttype CreateInput,\n\ttype GetForIdInput,\n\ttype GetOrCreateWithKeyInput,\n\ttype GetWithKeyInput,\n\ttype ListActorsInput,\n\ttype ManagerDisplayInformation,\n\ttype ManagerDriver,\n\tWS_PROTOCOL_ACTOR,\n\tWS_PROTOCOL_CONN_PARAMS,\n\tWS_PROTOCOL_ENCODING,\n\tWS_PROTOCOL_STANDARD,\n\tWS_PROTOCOL_TARGET,\n} from \"rivetkit/driver-helpers\";\nimport {\n\tActorDuplicateKey,\n\tActorNotFound,\n\tInternalError,\n} from \"rivetkit/errors\";\nimport { assertUnreachable } from \"rivetkit/utils\";\nimport { parseActorId } from \"./actor-id\";\nimport { getCloudflareAmbientEnv } from \"./handler\";\nimport { logger } from \"./log\";\nimport type { Bindings } from \"./mod\";\nimport { serializeNameAndKey } from \"./util\";\n\nconst STANDARD_WEBSOCKET_HEADERS = [\n\t\"connection\",\n\t\"upgrade\",\n\t\"sec-websocket-key\",\n\t\"sec-websocket-version\",\n\t\"sec-websocket-protocol\",\n\t\"sec-websocket-extensions\",\n];\n\nexport class CloudflareActorsManagerDriver implements ManagerDriver {\n\tasync sendRequest(\n\t\tactorId: string,\n\t\tactorRequest: Request,\n\t): Promise<Response> {\n\t\tconst env = getCloudflareAmbientEnv();\n\n\t\t// Parse actor ID to get DO ID\n\t\tconst [doId] = parseActorId(actorId);\n\n\t\tlogger().debug({\n\t\t\tmsg: \"sending request to durable object\",\n\t\t\tactorId,\n\t\t\tdoId,\n\t\t\tmethod: actorRequest.method,\n\t\t\turl: actorRequest.url,\n\t\t});\n\n\t\tconst id = env.ACTOR_DO.idFromString(doId);\n\t\tconst stub = env.ACTOR_DO.get(id);\n\n\t\treturn await stub.fetch(actorRequest);\n\t}\n\n\tasync openWebSocket(\n\t\tpath: string,\n\t\tactorId: string,\n\t\tencoding: Encoding,\n\t\tparams: unknown,\n\t): Promise<UniversalWebSocket> {\n\t\tconst env = getCloudflareAmbientEnv();\n\n\t\t// Parse actor ID to get DO ID\n\t\tconst [doId] = parseActorId(actorId);\n\n\t\tlogger().debug({\n\t\t\tmsg: \"opening websocket to durable object\",\n\t\t\tactorId,\n\t\t\tdoId,\n\t\t\tpath,\n\t\t});\n\n\t\t// Make a fetch request to the Durable Object with WebSocket upgrade\n\t\tconst id = env.ACTOR_DO.idFromString(doId);\n\t\tconst stub = env.ACTOR_DO.get(id);\n\n\t\tconst protocols: string[] = [];\n\t\tprotocols.push(WS_PROTOCOL_STANDARD);\n\t\tprotocols.push(`${WS_PROTOCOL_TARGET}actor`);\n\t\tprotocols.push(`${WS_PROTOCOL_ACTOR}${encodeURIComponent(actorId)}`);\n\t\tprotocols.push(`${WS_PROTOCOL_ENCODING}${encoding}`);\n\t\tif (params) {\n\t\t\tprotocols.push(\n\t\t\t\t`${WS_PROTOCOL_CONN_PARAMS}${encodeURIComponent(JSON.stringify(params))}`,\n\t\t\t);\n\t\t}\n\n\t\tconst headers: Record<string, string> = {\n\t\t\tUpgrade: \"websocket\",\n\t\t\tConnection: \"Upgrade\",\n\t\t\t\"sec-websocket-protocol\": protocols.join(\", \"),\n\t\t};\n\n\t\t// Use the path parameter to determine the URL\n\t\tconst normalizedPath = path.startsWith(\"/\") ? path : `/${path}`;\n\t\tconst url = `http://actor${normalizedPath}`;\n\n\t\tlogger().debug({ msg: \"rewriting websocket url\", from: path, to: url });\n\n\t\tconst response = await stub.fetch(url, {\n\t\t\theaders,\n\t\t});\n\t\tconst webSocket = response.webSocket;\n\n\t\tif (!webSocket) {\n\t\t\tthrow new InternalError(\n\t\t\t\t`missing websocket connection in response from DO\\n\\nStatus: ${response.status}\\nResponse: ${await response.text()}`,\n\t\t\t);\n\t\t}\n\n\t\tlogger().debug({\n\t\t\tmsg: \"durable object websocket connection open\",\n\t\t\tactorId,\n\t\t});\n\n\t\twebSocket.accept();\n\n\t\t// TODO: Is this still needed?\n\t\t// HACK: Cloudflare does not call onopen automatically, so we need\n\t\t// to call this on the next tick\n\t\tsetTimeout(() => {\n\t\t\tconst event = new Event(\"open\");\n\t\t\t(webSocket as any).onopen?.(event);\n\t\t\t(webSocket as any).dispatchEvent(event);\n\t\t}, 0);\n\n\t\treturn webSocket as unknown as UniversalWebSocket;\n\t}\n\n\tasync buildGatewayUrl(actorId: string): Promise<string> {\n\t\treturn `http://actor/gateway/${encodeURIComponent(actorId)}`;\n\t}\n\n\tasync proxyRequest(\n\t\tc: HonoContext<{ Bindings: Bindings }>,\n\t\tactorRequest: Request,\n\t\tactorId: string,\n\t): Promise<Response> {\n\t\tconst env = getCloudflareAmbientEnv();\n\n\t\t// Parse actor ID to get DO ID\n\t\tconst [doId] = parseActorId(actorId);\n\n\t\tlogger().debug({\n\t\t\tmsg: \"forwarding request to durable object\",\n\t\t\tactorId,\n\t\t\tdoId,\n\t\t\tmethod: actorRequest.method,\n\t\t\turl: actorRequest.url,\n\t\t});\n\n\t\tconst id = env.ACTOR_DO.idFromString(doId);\n\t\tconst stub = env.ACTOR_DO.get(id);\n\n\t\treturn await stub.fetch(actorRequest);\n\t}\n\n\tasync proxyWebSocket(\n\t\tc: HonoContext<{ Bindings: Bindings }>,\n\t\tpath: string,\n\t\tactorId: string,\n\t\tencoding: Encoding,\n\t\tparams: unknown,\n\t): Promise<Response> {\n\t\tlogger().debug({\n\t\t\tmsg: \"forwarding websocket to durable object\",\n\t\t\tactorId,\n\t\t\tpath,\n\t\t});\n\n\t\t// Validate upgrade\n\t\tconst upgradeHeader = c.req.header(\"Upgrade\");\n\t\tif (!upgradeHeader || upgradeHeader !== \"websocket\") {\n\t\t\treturn new Response(\"Expected Upgrade: websocket\", {\n\t\t\t\tstatus: 426,\n\t\t\t});\n\t\t}\n\n\t\tconst newUrl = new URL(`http://actor${path}`);\n\t\tconst actorRequest = new Request(newUrl, c.req.raw);\n\n\t\tlogger().debug({\n\t\t\tmsg: \"rewriting websocket url\",\n\t\t\tfrom: c.req.url,\n\t\t\tto: actorRequest.url,\n\t\t});\n\n\t\t// Always build fresh request to prevent forwarding unwanted headers\n\t\t// HACK: Since we can't build a new request, we need to remove\n\t\t// non-standard headers manually\n\t\tconst headerKeys: string[] = [];\n\t\tactorRequest.headers.forEach((v, k) => {\n\t\t\theaderKeys.push(k);\n\t\t});\n\t\tfor (const k of headerKeys) {\n\t\t\tif (!STANDARD_WEBSOCKET_HEADERS.includes(k)) {\n\t\t\t\tactorRequest.headers.delete(k);\n\t\t\t}\n\t\t}\n\n\t\t// Build protocols for WebSocket connection\n\t\tconst protocols: string[] = [];\n\t\tprotocols.push(WS_PROTOCOL_STANDARD);\n\t\tprotocols.push(`${WS_PROTOCOL_TARGET}actor`);\n\t\tprotocols.push(`${WS_PROTOCOL_ACTOR}${encodeURIComponent(actorId)}`);\n\t\tprotocols.push(`${WS_PROTOCOL_ENCODING}${encoding}`);\n\t\tif (params) {\n\t\t\tprotocols.push(\n\t\t\t\t`${WS_PROTOCOL_CONN_PARAMS}${encodeURIComponent(JSON.stringify(params))}`,\n\t\t\t);\n\t\t}\n\t\tactorRequest.headers.set(\n\t\t\t\"sec-websocket-protocol\",\n\t\t\tprotocols.join(\", \"),\n\t\t);\n\n\t\t// Parse actor ID to get DO ID\n\t\tconst env = getCloudflareAmbientEnv();\n\t\tconst [doId] = parseActorId(actorId);\n\t\tconst id = env.ACTOR_DO.idFromString(doId);\n\t\tconst stub = env.ACTOR_DO.get(id);\n\n\t\treturn await stub.fetch(actorRequest);\n\t}\n\n\tasync getForId({\n\t\tc,\n\t\tname,\n\t\tactorId,\n\t}: GetForIdInput<{ Bindings: Bindings }>): Promise<\n\t\tActorOutput | undefined\n\t> {\n\t\tconst env = getCloudflareAmbientEnv();\n\n\t\t// Parse actor ID to get DO ID and expected generation\n\t\tconst [doId, expectedGeneration] = parseActorId(actorId);\n\n\t\t// Get the Durable Object stub\n\t\tconst id = env.ACTOR_DO.idFromString(doId);\n\t\tconst stub = env.ACTOR_DO.get(id);\n\n\t\t// Call the DO's getMetadata method\n\t\tconst result = await stub.getMetadata();\n\n\t\tif (!result) {\n\t\t\tlogger().debug({\n\t\t\t\tmsg: \"getForId: actor not found\",\n\t\t\t\tactorId,\n\t\t\t});\n\t\t\treturn undefined;\n\t\t}\n\n\t\t// Check if the actor IDs match in order to check if the generation matches\n\t\tif (result.actorId !== actorId) {\n\t\t\tlogger().debug({\n\t\t\t\tmsg: \"getForId: generation mismatch\",\n\t\t\t\trequestedActorId: actorId,\n\t\t\t\tactualActorId: result.actorId,\n\t\t\t});\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (result.destroying) {\n\t\t\tthrow new ActorNotFound(actorId);\n\t\t}\n\n\t\treturn {\n\t\t\tactorId: result.actorId,\n\t\t\tname: result.name,\n\t\t\tkey: result.key,\n\t\t};\n\t}\n\n\tasync getWithKey({\n\t\tc,\n\t\tname,\n\t\tkey,\n\t}: GetWithKeyInput<{ Bindings: Bindings }>): Promise<\n\t\tActorOutput | undefined\n\t> {\n\t\tconst env = getCloudflareAmbientEnv();\n\n\t\tlogger().debug({ msg: \"getWithKey: searching for actor\", name, key });\n\n\t\t// Generate deterministic ID from the name and key\n\t\tconst nameKeyString = serializeNameAndKey(name, key);\n\t\tconst doId = env.ACTOR_DO.idFromName(nameKeyString).toString();\n\n\t\t// Try to get the Durable Object to see if it exists\n\t\tconst id = env.ACTOR_DO.idFromString(doId);\n\t\tconst stub = env.ACTOR_DO.get(id);\n\n\t\t// Check if actor exists without creating it\n\t\tconst result = await stub.getMetadata();\n\n\t\tif (result) {\n\t\t\tlogger().debug({\n\t\t\t\tmsg: \"getWithKey: found actor with matching name and key\",\n\t\t\t\tactorId: result.actorId,\n\t\t\t\tname: result.name,\n\t\t\t\tkey: result.key,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tactorId: result.actorId,\n\t\t\t\tname: result.name,\n\t\t\t\tkey: result.key,\n\t\t\t};\n\t\t} else {\n\t\t\tlogger().debug({\n\t\t\t\tmsg: \"getWithKey: no actor found with matching name and key\",\n\t\t\t\tname,\n\t\t\t\tkey,\n\t\t\t\tdoId,\n\t\t\t});\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tasync getOrCreateWithKey({\n\t\tc,\n\t\tname,\n\t\tkey,\n\t\tinput,\n\t}: GetOrCreateWithKeyInput<{ Bindings: Bindings }>): Promise<ActorOutput> {\n\t\tconst env = getCloudflareAmbientEnv();\n\n\t\t// Create a deterministic ID from the actor name and key\n\t\t// This ensures that actors with the same name and key will have the same ID\n\t\tconst nameKeyString = serializeNameAndKey(name, key);\n\t\tconst doId = env.ACTOR_DO.idFromName(nameKeyString);\n\n\t\t// Get or create actor using the Durable Object's method\n\t\tconst actor = env.ACTOR_DO.get(doId);\n\t\tconst result = await actor.create({\n\t\t\tname,\n\t\t\tkey,\n\t\t\tinput,\n\t\t\tallowExisting: true,\n\t\t});\n\t\tif (\"success\" in result) {\n\t\t\tconst { actorId, created } = result.success;\n\t\t\tlogger().debug({\n\t\t\t\tmsg: \"getOrCreateWithKey result\",\n\t\t\t\tactorId,\n\t\t\t\tname,\n\t\t\t\tkey,\n\t\t\t\tcreated,\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\tactorId,\n\t\t\t\tname,\n\t\t\t\tkey,\n\t\t\t};\n\t\t} else if (\"error\" in result) {\n\t\t\tthrow new Error(`Error: ${JSON.stringify(result.error)}`);\n\t\t} else {\n\t\t\tassertUnreachable(result);\n\t\t}\n\t}\n\n\tasync createActor({\n\t\tc,\n\t\tname,\n\t\tkey,\n\t\tinput,\n\t}: CreateInput<{ Bindings: Bindings }>): Promise<ActorOutput> {\n\t\tconst env = getCloudflareAmbientEnv();\n\n\t\t// Create a deterministic ID from the actor name and key\n\t\t// This ensures that actors with the same name and key will have the same ID\n\t\tconst nameKeyString = serializeNameAndKey(name, key);\n\t\tconst doId = env.ACTOR_DO.idFromName(nameKeyString);\n\n\t\t// Create actor - this will fail if it already exists\n\t\tconst actor = env.ACTOR_DO.get(doId);\n\t\tconst result = await actor.create({\n\t\t\tname,\n\t\t\tkey,\n\t\t\tinput,\n\t\t\tallowExisting: false,\n\t\t});\n\n\t\tif (\"success\" in result) {\n\t\t\tconst { actorId } = result.success;\n\t\t\treturn {\n\t\t\t\tactorId,\n\t\t\t\tname,\n\t\t\t\tkey,\n\t\t\t};\n\t\t} else if (\"error\" in result) {\n\t\t\tif (result.error.actorAlreadyExists) {\n\t\t\t\tthrow new ActorDuplicateKey(name, key);\n\t\t\t}\n\n\t\t\tthrow new InternalError(\n\t\t\t\t`Unknown error creating actor: ${JSON.stringify(result.error)}`,\n\t\t\t);\n\t\t} else {\n\t\t\tassertUnreachable(result);\n\t\t}\n\t}\n\n\tasync listActors({ c, name }: ListActorsInput): Promise<ActorOutput[]> {\n\t\tlogger().warn({\n\t\t\tmsg: \"listActors not fully implemented for Cloudflare Workers\",\n\t\t\tname,\n\t\t});\n\t\treturn [];\n\t}\n\n\tdisplayInformation(): ManagerDisplayInformation {\n\t\treturn {\n\t\t\tproperties: {\n\t\t\t\tDriver: \"Cloudflare Workers\",\n\t\t\t},\n\t\t};\n\t}\n\n\tsetGetUpgradeWebSocket(): void {\n\t\t// No-op for Cloudflare Workers - WebSocket upgrades are handled by the DO\n\t}\n\n\tasync kvGet(actorId: string, key: Uint8Array): Promise<string | null> {\n\t\tconst env = getCloudflareAmbientEnv();\n\n\t\t// Parse actor ID to get DO ID\n\t\tconst [doId] = parseActorId(actorId);\n\n\t\tconst id = env.ACTOR_DO.idFromString(doId);\n\t\tconst stub = env.ACTOR_DO.get(id);\n\n\t\tconst value = await stub.managerKvGet(key);\n\t\treturn value !== null ? new TextDecoder().decode(value) : null;\n\t}\n}\n","/**\n * Actor ID utilities for managing actor IDs with generation tracking.\n *\n * Actor IDs are formatted as: `{doId}:{generation}`\n * This allows tracking actor resurrection and preventing stale references.\n */\n\n/**\n * Build an actor ID from a Durable Object ID and generation number.\n * @param doId The Durable Object ID\n * @param generation The generation number (increments on resurrection)\n * @returns The formatted actor ID\n */\nexport function buildActorId(doId: string, generation: number): string {\n\treturn `${doId}:${generation}`;\n}\n\n/**\n * Parse an actor ID into its components.\n * @param actorId The actor ID to parse\n * @returns A tuple of [doId, generation]\n * @throws Error if the actor ID format is invalid\n */\nexport function parseActorId(actorId: string): [string, number] {\n\tconst parts = actorId.split(\":\");\n\tif (parts.length !== 2) {\n\t\tthrow new Error(`Invalid actor ID format: ${actorId}`);\n\t}\n\n\tconst [doId, generationStr] = parts;\n\tconst generation = parseInt(generationStr, 10);\n\n\tif (Number.isNaN(generation)) {\n\t\tthrow new Error(`Invalid generation number in actor ID: ${actorId}`);\n\t}\n\n\treturn [doId, generation];\n}\n","// Constants for key handling\nexport const EMPTY_KEY = \"(none)\";\nexport const KEY_SEPARATOR = \",\";\n\n/**\n * Serializes an array of key strings into a single string for use with idFromName\n *\n * @param name The actor name\n * @param key Array of key strings to serialize\n * @returns A single string containing the serialized name and key\n */\nexport function serializeNameAndKey(name: string, key: string[]): string {\n\t// Escape colons in the name\n\tconst escapedName = name.replace(/:/g, \"\\\\:\");\n\n\t// For empty keys, just return the name and a marker\n\tif (key.length === 0) {\n\t\treturn `${escapedName}:${EMPTY_KEY}`;\n\t}\n\n\t// Serialize the key array\n\tconst serializedKey = serializeKey(key);\n\n\t// Combine name and serialized key\n\treturn `${escapedName}:${serializedKey}`;\n}\n\n/**\n * Serializes an array of key strings into a single string\n *\n * @param key Array of key strings to serialize\n * @returns A single string containing the serialized key\n */\nexport function serializeKey(key: string[]): string {\n\t// Use a special marker for empty key arrays\n\tif (key.length === 0) {\n\t\treturn EMPTY_KEY;\n\t}\n\n\t// Escape each key part to handle the separator and the empty key marker\n\tconst escapedParts = key.map((part) => {\n\t\t// First check if it matches our empty key marker\n\t\tif (part === EMPTY_KEY) {\n\t\t\treturn `\\\\${EMPTY_KEY}`;\n\t\t}\n\n\t\t// Escape backslashes first, then commas\n\t\tlet escaped = part.replace(/\\\\/g, \"\\\\\\\\\");\n\t\tescaped = escaped.replace(/,/g, \"\\\\,\");\n\t\treturn escaped;\n\t});\n\n\treturn escapedParts.join(KEY_SEPARATOR);\n}\n\n/**\n * Deserializes a key string back into an array of key strings\n *\n * @param keyString The serialized key string\n * @returns Array of key strings\n */\nexport function deserializeKey(keyString: string): string[] {\n\t// Handle empty values\n\tif (!keyString) {\n\t\treturn [];\n\t}\n\n\t// Check for special empty key marker\n\tif (keyString === EMPTY_KEY) {\n\t\treturn [];\n\t}\n\n\t// Split by unescaped commas and unescape the escaped characters\n\tconst parts: string[] = [];\n\tlet currentPart = \"\";\n\tlet escaping = false;\n\n\tfor (let i = 0; i < keyString.length; i++) {\n\t\tconst char = keyString[i];\n\n\t\tif (escaping) {\n\t\t\t// This is an escaped character, add it directly\n\t\t\tcurrentPart += char;\n\t\t\tescaping = false;\n\t\t} else if (char === \"\\\\\") {\n\t\t\t// Start of an escape sequence\n\t\t\tescaping = true;\n\t\t} else if (char === KEY_SEPARATOR) {\n\t\t\t// This is a separator\n\t\t\tparts.push(currentPart);\n\t\t\tcurrentPart = \"\";\n\t\t} else {\n\t\t\t// Regular character\n\t\t\tcurrentPart += char;\n\t\t}\n\t}\n\n\t// Add the last part if it exists\n\tif (currentPart || parts.length > 0) {\n\t\tparts.push(currentPart);\n\t}\n\n\treturn parts;\n}\n","// Modified from https://github.com/honojs/hono/blob/40ea0eee58e39b31053a0246c595434f1094ad31/src/adapter/cloudflare-workers/websocket.ts#L17\n//\n// This version calls the open event by default\n\nimport type { UpgradeWebSocket, WSEvents, WSReadyState } from \"hono/ws\";\nimport { defineWebSocketHelper, WSContext } from \"hono/ws\";\nimport { WS_PROTOCOL_STANDARD } from \"rivetkit/driver-helpers\";\n\n// Based on https://github.com/honojs/hono/issues/1153#issuecomment-1767321332\nexport const upgradeWebSocket: UpgradeWebSocket<\n\tWebSocket,\n\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\tany,\n\tWSEvents<WebSocket>\n> = defineWebSocketHelper(async (c, events) => {\n\tconst upgradeHeader = c.req.header(\"Upgrade\");\n\tif (upgradeHeader !== \"websocket\") {\n\t\treturn;\n\t}\n\n\tconst webSocketPair = new WebSocketPair();\n\tconst client: WebSocket = webSocketPair[0];\n\tconst server: WebSocket = webSocketPair[1];\n\n\tconst wsContext = new WSContext<WebSocket>({\n\t\tclose: (code, reason) => server.close(code, reason),\n\t\tget protocol() {\n\t\t\treturn server.protocol;\n\t\t},\n\t\traw: server,\n\t\tget readyState() {\n\t\t\treturn server.readyState as WSReadyState;\n\t\t},\n\t\turl: server.url ? new URL(server.url) : null,\n\t\tsend: (source) => server.send(source),\n\t});\n\n\tif (events.onClose) {\n\t\tserver.addEventListener(\"close\", (evt: CloseEvent) =>\n\t\t\tevents.onClose?.(evt, wsContext),\n\t\t);\n\t}\n\tif (events.onMessage) {\n\t\tserver.addEventListener(\"message\", (evt: MessageEvent) =>\n\t\t\tevents.onMessage?.(evt, wsContext),\n\t\t);\n\t}\n\tif (events.onError) {\n\t\tserver.addEventListener(\"error\", (evt: Event) =>\n\t\t\tevents.onError?.(evt, wsContext),\n\t\t);\n\t}\n\n\tserver.accept?.();\n\n\t// note: cloudflare actors doesn't support 'open' event, so we call it immediately with a fake event\n\t//\n\t// we have to do this after `server.accept() is called`\n\tevents.onOpen?.(new Event(\"open\"), wsContext);\n\n\t// Build response headers\n\tconst headers: Record<string, string> = {};\n\n\t// Set Sec-WebSocket-Protocol if does not exist\n\tconst protocols = c.req.header(\"Sec-WebSocket-Protocol\");\n\tif (\n\t\ttypeof protocols === \"string\" &&\n\t\tprotocols\n\t\t\t.split(\",\")\n\t\t\t.map((x) => x.trim())\n\t\t\t.includes(WS_PROTOCOL_STANDARD)\n\t) {\n\t\theaders[\"Sec-WebSocket-Protocol\"] = WS_PROTOCOL_STANDARD;\n\t}\n\n\treturn new Response(null, {\n\t\tstatus: 101,\n\t\theaders,\n\t\twebSocket: client,\n\t});\n});\n"],"mappings":";AAAA,SAAS,eAAe,OAAAA,YAAW;AAEnC,OAAOC,gBAAe;AAEtB,SAAS,mBAAmB,0BAAAC,+BAA8B;AAE1D,SAAS,8BAA8B;;;ACNvC,OAAO,eAAe;AAOtB,SAAS,wBAAwB;AAMjC,SAAS,4BAA4B;;;ACbrC,SAAS,iBAAiB;AAEnB,SAAS,SAAS;AACxB,SAAO,UAAU,2BAA2B;AAC7C;;;ACJA,IAAM,qBAAqB;AAEpB,SAAS,MAAM,KAAiB,KAAoC;AAC1E,QAAM,SAAS,IAAI;AAAA,IAClB;AAAA,IACA;AAAA,EACD;AACA,QAAM,SAAS,OAAO,IAAI,EAAE,KAAK;AAEjC,MAAI,CAAC,OAAO,QAAQ,OAAO,OAAO;AACjC,WAAO,aAAa,OAAO,MAAM,CAAC,CAAC;AAAA,EACpC;AACA,SAAO;AACR;AAEO,SAAS,MACf,KACA,KACA,OACO;AACP,MAAI;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA,EACD;AACD;AAEO,SAAS,SAA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AAAA,QACH;AAAA,QACA;AAAA,QACA;AAAA,MACD,CAAC;AAED,aAAO,EAAE,SAAS,EAAE,SAAS,QAAQ,EAAE;AAAA,IACxC;AAAA,IAEA,MAAM,MAAM,SAAqC;AAChD,YAAM,EAAE,aAAa,WAAW,IAAI,MAAM,KAAK,WAAW;AAG1D,YAAM,OAAO,KAAK,IAAI,GAAG,SAAS;AAClC,YAAM,UAAU,aAAa,MAAM,UAAU;AAE7C,aAAO,MAAM,YAAY,MAAM,SAAS;AAAA,QACvC;AAAA,MACD,CAAC;AAAA,IACF;AAAA,IAEA,MAAM,QAAuB;AAC5B,YAAM,EAAE,aAAa,WAAW,IAAI,MAAM,KAAK,WAAW;AAG1D,YAAM,OAAO,KAAK,IAAI,GAAG,SAAS;AAClC,YAAM,UAAU,aAAa,MAAM,UAAU;AAG7C,YAAM,QAAQ,MAAM,YAAY,UAAU,OAAO;AACjD,YAAM,MAAM,QAAQ;AAAA,IACrB;AAAA,EACD;AACD;AAEA,SAAS,yBACR,KACA,OACO;AACP,QAAM,iBAAiB,uBAAuB,KAAK;AACnD,aAAW,CAAC,KAAK,KAAK,KAAK,gBAAgB;AAC1C,UAAM,KAAK,KAAK,KAAK;AAAA,EACtB;AACD;","names":["env","invariant","createClientWithDriver","env","WS_PROTOCOL_STANDARD","_a","env","env","invariant","env","createClientWithDriver","doId","actorId"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/rivet/rivet/rivetkit-typescript/packages/cloudflare-workers/dist/mod.js","../src/mod.ts","../src/websocket.ts"],"names":[],"mappings":"AAAA;ACAA,kHAA8B;AAC9B,iKAAuB;AACvB;AACC;AAGA;AAAS,oCACH;ADAP;AACA;AEGA,IAAM,eAAA,YAAN,MAAM,gBAAe;AAAA,EACpB,4BAAgB,WAAA,EAAa,EAAA;AAAA,EAC7B,6BAAgB,KAAA,EAAO,EAAA;AAAA,EACvB,6BAAgB,QAAA,EAAU,EAAA;AAAA,EAC1B,6BAAgB,OAAA,EAAS,EAA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D,IAAA;AACD,EAAA;AAEF;ADGA;AACA;AACA;AACA","file":"/home/runner/work/rivet/rivet/rivetkit-typescript/packages/cloudflare-workers/dist/mod.js","sourcesContent":[null,"import * as wasmBindings from \"@rivetkit/rivetkit-wasm\";\nimport wasmModule from \"@rivetkit/rivetkit-wasm/rivetkit_wasm_bg.wasm\";\nimport {\n\tRegistry,\n\ttype RegistryActors,\n\ttype RegistryConfigInput,\n\tsetup as rivetkitSetup,\n} from \"rivetkit\";\n// Installs the fetch-based `globalThis.WebSocket` shim required for the wasm\n// runtime's outbound tunnel to the Rivet engine. Imported for its side effect.\nimport \"./websocket\";\n\nconst DEFAULT_MANAGER_PATH = \"/api/rivet\";\n\n/** Config passed to `setup` / `createHandler`. The wasm runtime is wired automatically. */\nexport type CloudflareSetupConfig<A extends RegistryActors> = Omit<\n\tRegistryConfigInput<A>,\n\t\"runtime\" | \"wasm\"\n>;\n\n/**\n * Wraps rivetkit's `setup` with the Cloudflare Workers WebAssembly runtime wired\n * in. Returns a typed `Registry`, so you can derive a typed client with\n * `createClient<typeof registry>(...)` and pass the same registry to\n * `createHandler`.\n */\nexport function setup<A extends RegistryActors>(\n\tconfig: CloudflareSetupConfig<A>,\n): Registry<A> {\n\treturn rivetkitSetup<A>({\n\t\truntime: \"wasm\",\n\t\twasm: { bindings: wasmBindings, initInput: wasmModule },\n\t\tnoWelcome: true,\n\t\t...config,\n\t} as RegistryConfigInput<A>);\n}\n\nexport interface CreateHandlerOptions {\n\t/**\n\t * Path the Rivet manager API is mounted at. Defaults to `/api/rivet`.\n\t *\n\t * `rivet dev` and the engine poll `<managerPath>/metadata`, so changing this\n\t * also requires configuring the engine-side serverless runner URL to match.\n\t */\n\tmanagerPath?: string;\n\t/**\n\t * Handler for requests that fall outside the Rivet manager API path. Accepts\n\t * a plain `(request, env, ctx)` handler or a framework `fetch` such as\n\t * Hono's `app.fetch`.\n\t */\n\t// biome-ignore lint/suspicious/noExplicitAny: accept any fetch handler shape (e.g. Hono's app.fetch).\n\tfetch?: (request: Request, ...args: any[]) => Response | Promise<Response>;\n}\n\nexport interface CloudflareHandler {\n\tfetch(request: Request, env: unknown, ctx: unknown): Promise<Response>;\n}\n\ntype EnvRecord = Record<string, string | undefined>;\n\n// Fill connection config from the per-request `env` on first request. On\n// Cloudflare the env is not available at module scope, so values that were not\n// set explicitly in the config are sourced from `RIVET_*` Worker variables here.\nfunction applyEnv(\n\tregistry: Registry<RegistryActors>,\n\tenv: EnvRecord,\n\tmanagerPath: string,\n): void {\n\tconst config = registry.config as RegistryConfigInput<RegistryActors>;\n\tif (!config.endpoint && env.RIVET_ENDPOINT) {\n\t\tconfig.endpoint = env.RIVET_ENDPOINT;\n\t}\n\tif (!config.namespace && env.RIVET_NAMESPACE) {\n\t\tconfig.namespace = env.RIVET_NAMESPACE;\n\t}\n\tif (!config.token && env.RIVET_TOKEN) {\n\t\tconfig.token = env.RIVET_TOKEN;\n\t}\n\tif (env.RIVET_POOL && !config.envoy?.poolName) {\n\t\tconfig.envoy = { ...config.envoy, poolName: env.RIVET_POOL };\n\t}\n\tif (!config.serverless?.basePath) {\n\t\tconfig.serverless = { ...config.serverless, basePath: managerPath };\n\t}\n}\n\n/**\n * Creates a Cloudflare Workers handler that hosts Rivet Actors on the wasm\n * runtime. Accepts either a registry from this package's `setup` or a setup\n * config (which is wired through `setup` for you).\n *\n * The Rivet manager API is mounted at `managerPath` (default `/api/rivet`).\n * Requests outside that path are routed to `options.fetch` if provided, letting\n * you mount your own routes alongside Rivet. The engine endpoint is read from\n * `RIVET_ENDPOINT` (with `RIVET_NAMESPACE`, `RIVET_TOKEN`, `RIVET_POOL` optional)\n * unless set in the config.\n */\nexport function createHandler<A extends RegistryActors>(\n\tregistry: Registry<A>,\n\toptions?: CreateHandlerOptions,\n): CloudflareHandler;\nexport function createHandler<A extends RegistryActors>(\n\tconfig: CloudflareSetupConfig<A>,\n\toptions?: CreateHandlerOptions,\n): CloudflareHandler;\nexport function createHandler<A extends RegistryActors>(\n\tregistryOrConfig: Registry<A> | CloudflareSetupConfig<A>,\n\toptions: CreateHandlerOptions = {},\n): CloudflareHandler {\n\tconst managerPath = options.managerPath ?? DEFAULT_MANAGER_PATH;\n\tconst registry =\n\t\tregistryOrConfig instanceof Registry\n\t\t\t? registryOrConfig\n\t\t\t: setup(registryOrConfig);\n\tlet envApplied = false;\n\n\treturn {\n\t\tasync fetch(request, env, ctx) {\n\t\t\tif (!envApplied) {\n\t\t\t\tapplyEnv(\n\t\t\t\t\tregistry as Registry<RegistryActors>,\n\t\t\t\t\t(env ?? {}) as EnvRecord,\n\t\t\t\t\tmanagerPath,\n\t\t\t\t);\n\t\t\t\tenvApplied = true;\n\t\t\t}\n\n\t\t\tconst url = new URL(request.url);\n\t\t\tif (\n\t\t\t\turl.pathname === managerPath ||\n\t\t\t\turl.pathname.startsWith(`${managerPath}/`)\n\t\t\t) {\n\t\t\t\treturn registry.handler(request);\n\t\t\t}\n\n\t\t\tif (options.fetch) {\n\t\t\t\treturn options.fetch(request, env, ctx);\n\t\t\t}\n\n\t\t\treturn new Response(\n\t\t\t\t\"This is a RivetKit server.\\n\\nLearn more at https://rivet.dev\\n\",\n\t\t\t);\n\t\t},\n\t};\n}\n","// Cloudflare Workers do not implement an outbound `new WebSocket(url)` client\n// constructor, but the wasm actor runtime opens its tunnel to the Rivet engine\n// through `globalThis.WebSocket`. This shim translates that constructor into\n// Cloudflare's fetch-based upgrade (`fetch(url, { Upgrade })` + `response.webSocket`)\n// and installs itself on `globalThis` so both the wasm tunnel and the TypeScript\n// client path resolve a working implementation.\n\ntype WebSocketProtocolInput = string | string[] | undefined;\n\ntype CloudflareSocket = WebSocket & { accept(): void };\n\nclass FetchWebSocket {\n\tstatic readonly CONNECTING = 0;\n\tstatic readonly OPEN = 1;\n\tstatic readonly CLOSING = 2;\n\tstatic readonly CLOSED = 3;\n\n\tbinaryType: BinaryType = \"arraybuffer\";\n\tonopen: ((event: Event) => void) | null = null;\n\tonmessage: ((event: MessageEvent) => void) | null = null;\n\tonclose: ((event: CloseEvent) => void) | null = null;\n\tonerror: ((event: Event) => void) | null = null;\n\treadyState = FetchWebSocket.CONNECTING;\n\t#socket: CloudflareSocket | undefined;\n\t#pending: Array<string | ArrayBuffer | ArrayBufferView> = [];\n\n\tconstructor(url: string, protocols?: WebSocketProtocolInput) {\n\t\tvoid this.#connect(url, protocols);\n\t}\n\n\tasync #connect(url: string, protocols?: WebSocketProtocolInput) {\n\t\ttry {\n\t\t\tconst protocolList = Array.isArray(protocols)\n\t\t\t\t? protocols\n\t\t\t\t: protocols\n\t\t\t\t\t? [protocols]\n\t\t\t\t\t: [];\n\t\t\tconst headers = new Headers({ Upgrade: \"websocket\" });\n\t\t\tif (protocolList.length > 0) {\n\t\t\t\theaders.set(\"Sec-WebSocket-Protocol\", protocolList.join(\", \"));\n\t\t\t}\n\t\t\tconst response = await fetch(\n\t\t\t\turl.replace(/^ws:/, \"http:\").replace(/^wss:/, \"https:\"),\n\t\t\t\t{ headers },\n\t\t\t);\n\t\t\tconst socket = (\n\t\t\t\tresponse as unknown as { webSocket: CloudflareSocket | null }\n\t\t\t).webSocket;\n\t\t\tif (!socket) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`websocket upgrade failed with status ${response.status}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tsocket.accept();\n\t\t\tsocket.binaryType = this.binaryType;\n\t\t\tthis.#socket = socket;\n\t\t\tthis.readyState = FetchWebSocket.OPEN;\n\t\t\tsocket.addEventListener(\"message\", (event) => {\n\t\t\t\tthis.onmessage?.(event);\n\t\t\t});\n\t\t\tsocket.addEventListener(\"close\", (event) => {\n\t\t\t\tthis.readyState = FetchWebSocket.CLOSED;\n\t\t\t\tthis.onclose?.(event);\n\t\t\t});\n\t\t\tsocket.addEventListener(\"error\", (event) => {\n\t\t\t\tthis.onerror?.(event);\n\t\t\t});\n\t\t\tthis.onopen?.(new Event(\"open\"));\n\t\t\tfor (const data of this.#pending.splice(0)) {\n\t\t\t\tsocket.send(data);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconsole.error(\"rivetkit cloudflare websocket shim failed\", error);\n\t\t\tthis.readyState = FetchWebSocket.CLOSED;\n\t\t\tthis.onerror?.(error instanceof Event ? error : new Event(\"error\"));\n\t\t\tthis.onclose?.(new CloseEvent(\"close\", { code: 1006 }));\n\t\t}\n\t}\n\n\tsend(data: string | ArrayBuffer | ArrayBufferView) {\n\t\tif (this.readyState === FetchWebSocket.CONNECTING) {\n\t\t\tthis.#pending.push(data);\n\t\t\treturn;\n\t\t}\n\t\tthis.#socket?.send(data);\n\t}\n\n\tclose(code?: number, reason?: string) {\n\t\tthis.readyState = FetchWebSocket.CLOSING;\n\t\tthis.#socket?.close(code, reason);\n\t}\n}\n\nconst globalScope = globalThis as unknown as {\n\tWebSocket: typeof WebSocket;\n\t__RIVETKIT_CF_WEBSOCKET_INSTALLED__?: boolean;\n};\n\n// Install once per isolate.\nif (!globalScope.__RIVETKIT_CF_WEBSOCKET_INSTALLED__) {\n\tglobalScope.WebSocket = FetchWebSocket as unknown as typeof WebSocket;\n\tglobalScope.__RIVETKIT_CF_WEBSOCKET_INSTALLED__ = true;\n}\n\nexport { FetchWebSocket };\n"]}
|
package/dist/mod.mjs
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// src/mod.ts
|
|
2
|
+
import * as wasmBindings from "@rivetkit/rivetkit-wasm";
|
|
3
|
+
import wasmModule from "@rivetkit/rivetkit-wasm/rivetkit_wasm_bg.wasm";
|
|
4
|
+
import {
|
|
5
|
+
Registry,
|
|
6
|
+
setup as rivetkitSetup
|
|
7
|
+
} from "rivetkit";
|
|
8
|
+
|
|
9
|
+
// src/websocket.ts
|
|
10
|
+
var FetchWebSocket = class _FetchWebSocket {
|
|
11
|
+
static CONNECTING = 0;
|
|
12
|
+
static OPEN = 1;
|
|
13
|
+
static CLOSING = 2;
|
|
14
|
+
static CLOSED = 3;
|
|
15
|
+
binaryType = "arraybuffer";
|
|
16
|
+
onopen = null;
|
|
17
|
+
onmessage = null;
|
|
18
|
+
onclose = null;
|
|
19
|
+
onerror = null;
|
|
20
|
+
readyState = _FetchWebSocket.CONNECTING;
|
|
21
|
+
#socket;
|
|
22
|
+
#pending = [];
|
|
23
|
+
constructor(url, protocols) {
|
|
24
|
+
void this.#connect(url, protocols);
|
|
25
|
+
}
|
|
26
|
+
async #connect(url, protocols) {
|
|
27
|
+
var _a, _b, _c;
|
|
28
|
+
try {
|
|
29
|
+
const protocolList = Array.isArray(protocols) ? protocols : protocols ? [protocols] : [];
|
|
30
|
+
const headers = new Headers({ Upgrade: "websocket" });
|
|
31
|
+
if (protocolList.length > 0) {
|
|
32
|
+
headers.set("Sec-WebSocket-Protocol", protocolList.join(", "));
|
|
33
|
+
}
|
|
34
|
+
const response = await fetch(
|
|
35
|
+
url.replace(/^ws:/, "http:").replace(/^wss:/, "https:"),
|
|
36
|
+
{ headers }
|
|
37
|
+
);
|
|
38
|
+
const socket = response.webSocket;
|
|
39
|
+
if (!socket) {
|
|
40
|
+
throw new Error(
|
|
41
|
+
`websocket upgrade failed with status ${response.status}`
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
socket.accept();
|
|
45
|
+
socket.binaryType = this.binaryType;
|
|
46
|
+
this.#socket = socket;
|
|
47
|
+
this.readyState = _FetchWebSocket.OPEN;
|
|
48
|
+
socket.addEventListener("message", (event) => {
|
|
49
|
+
var _a2;
|
|
50
|
+
(_a2 = this.onmessage) == null ? void 0 : _a2.call(this, event);
|
|
51
|
+
});
|
|
52
|
+
socket.addEventListener("close", (event) => {
|
|
53
|
+
var _a2;
|
|
54
|
+
this.readyState = _FetchWebSocket.CLOSED;
|
|
55
|
+
(_a2 = this.onclose) == null ? void 0 : _a2.call(this, event);
|
|
56
|
+
});
|
|
57
|
+
socket.addEventListener("error", (event) => {
|
|
58
|
+
var _a2;
|
|
59
|
+
(_a2 = this.onerror) == null ? void 0 : _a2.call(this, event);
|
|
60
|
+
});
|
|
61
|
+
(_a = this.onopen) == null ? void 0 : _a.call(this, new Event("open"));
|
|
62
|
+
for (const data of this.#pending.splice(0)) {
|
|
63
|
+
socket.send(data);
|
|
64
|
+
}
|
|
65
|
+
} catch (error) {
|
|
66
|
+
console.error("rivetkit cloudflare websocket shim failed", error);
|
|
67
|
+
this.readyState = _FetchWebSocket.CLOSED;
|
|
68
|
+
(_b = this.onerror) == null ? void 0 : _b.call(this, error instanceof Event ? error : new Event("error"));
|
|
69
|
+
(_c = this.onclose) == null ? void 0 : _c.call(this, new CloseEvent("close", { code: 1006 }));
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
send(data) {
|
|
73
|
+
var _a;
|
|
74
|
+
if (this.readyState === _FetchWebSocket.CONNECTING) {
|
|
75
|
+
this.#pending.push(data);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
(_a = this.#socket) == null ? void 0 : _a.send(data);
|
|
79
|
+
}
|
|
80
|
+
close(code, reason) {
|
|
81
|
+
var _a;
|
|
82
|
+
this.readyState = _FetchWebSocket.CLOSING;
|
|
83
|
+
(_a = this.#socket) == null ? void 0 : _a.close(code, reason);
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
var globalScope = globalThis;
|
|
87
|
+
if (!globalScope.__RIVETKIT_CF_WEBSOCKET_INSTALLED__) {
|
|
88
|
+
globalScope.WebSocket = FetchWebSocket;
|
|
89
|
+
globalScope.__RIVETKIT_CF_WEBSOCKET_INSTALLED__ = true;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// src/mod.ts
|
|
93
|
+
var DEFAULT_MANAGER_PATH = "/api/rivet";
|
|
94
|
+
function setup(config) {
|
|
95
|
+
return rivetkitSetup({
|
|
96
|
+
runtime: "wasm",
|
|
97
|
+
wasm: { bindings: wasmBindings, initInput: wasmModule },
|
|
98
|
+
noWelcome: true,
|
|
99
|
+
...config
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
function applyEnv(registry, env, managerPath) {
|
|
103
|
+
var _a, _b;
|
|
104
|
+
const config = registry.config;
|
|
105
|
+
if (!config.endpoint && env.RIVET_ENDPOINT) {
|
|
106
|
+
config.endpoint = env.RIVET_ENDPOINT;
|
|
107
|
+
}
|
|
108
|
+
if (!config.namespace && env.RIVET_NAMESPACE) {
|
|
109
|
+
config.namespace = env.RIVET_NAMESPACE;
|
|
110
|
+
}
|
|
111
|
+
if (!config.token && env.RIVET_TOKEN) {
|
|
112
|
+
config.token = env.RIVET_TOKEN;
|
|
113
|
+
}
|
|
114
|
+
if (env.RIVET_POOL && !((_a = config.envoy) == null ? void 0 : _a.poolName)) {
|
|
115
|
+
config.envoy = { ...config.envoy, poolName: env.RIVET_POOL };
|
|
116
|
+
}
|
|
117
|
+
if (!((_b = config.serverless) == null ? void 0 : _b.basePath)) {
|
|
118
|
+
config.serverless = { ...config.serverless, basePath: managerPath };
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
function createHandler(registryOrConfig, options = {}) {
|
|
122
|
+
const managerPath = options.managerPath ?? DEFAULT_MANAGER_PATH;
|
|
123
|
+
const registry = registryOrConfig instanceof Registry ? registryOrConfig : setup(registryOrConfig);
|
|
124
|
+
let envApplied = false;
|
|
125
|
+
return {
|
|
126
|
+
async fetch(request, env, ctx) {
|
|
127
|
+
if (!envApplied) {
|
|
128
|
+
applyEnv(
|
|
129
|
+
registry,
|
|
130
|
+
env ?? {},
|
|
131
|
+
managerPath
|
|
132
|
+
);
|
|
133
|
+
envApplied = true;
|
|
134
|
+
}
|
|
135
|
+
const url = new URL(request.url);
|
|
136
|
+
if (url.pathname === managerPath || url.pathname.startsWith(`${managerPath}/`)) {
|
|
137
|
+
return registry.handler(request);
|
|
138
|
+
}
|
|
139
|
+
if (options.fetch) {
|
|
140
|
+
return options.fetch(request, env, ctx);
|
|
141
|
+
}
|
|
142
|
+
return new Response(
|
|
143
|
+
"This is a RivetKit server.\n\nLearn more at https://rivet.dev\n"
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
export {
|
|
149
|
+
createHandler,
|
|
150
|
+
setup
|
|
151
|
+
};
|
|
152
|
+
//# sourceMappingURL=mod.mjs.map
|
package/dist/mod.mjs.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/mod.ts","../src/websocket.ts"],"sourcesContent":["import * as wasmBindings from \"@rivetkit/rivetkit-wasm\";\nimport wasmModule from \"@rivetkit/rivetkit-wasm/rivetkit_wasm_bg.wasm\";\nimport {\n\tRegistry,\n\ttype RegistryActors,\n\ttype RegistryConfigInput,\n\tsetup as rivetkitSetup,\n} from \"rivetkit\";\n// Installs the fetch-based `globalThis.WebSocket` shim required for the wasm\n// runtime's outbound tunnel to the Rivet engine. Imported for its side effect.\nimport \"./websocket\";\n\nconst DEFAULT_MANAGER_PATH = \"/api/rivet\";\n\n/** Config passed to `setup` / `createHandler`. The wasm runtime is wired automatically. */\nexport type CloudflareSetupConfig<A extends RegistryActors> = Omit<\n\tRegistryConfigInput<A>,\n\t\"runtime\" | \"wasm\"\n>;\n\n/**\n * Wraps rivetkit's `setup` with the Cloudflare Workers WebAssembly runtime wired\n * in. Returns a typed `Registry`, so you can derive a typed client with\n * `createClient<typeof registry>(...)` and pass the same registry to\n * `createHandler`.\n */\nexport function setup<A extends RegistryActors>(\n\tconfig: CloudflareSetupConfig<A>,\n): Registry<A> {\n\treturn rivetkitSetup<A>({\n\t\truntime: \"wasm\",\n\t\twasm: { bindings: wasmBindings, initInput: wasmModule },\n\t\tnoWelcome: true,\n\t\t...config,\n\t} as RegistryConfigInput<A>);\n}\n\nexport interface CreateHandlerOptions {\n\t/**\n\t * Path the Rivet manager API is mounted at. Defaults to `/api/rivet`.\n\t *\n\t * `rivet dev` and the engine poll `<managerPath>/metadata`, so changing this\n\t * also requires configuring the engine-side serverless runner URL to match.\n\t */\n\tmanagerPath?: string;\n\t/**\n\t * Handler for requests that fall outside the Rivet manager API path. Accepts\n\t * a plain `(request, env, ctx)` handler or a framework `fetch` such as\n\t * Hono's `app.fetch`.\n\t */\n\t// biome-ignore lint/suspicious/noExplicitAny: accept any fetch handler shape (e.g. Hono's app.fetch).\n\tfetch?: (request: Request, ...args: any[]) => Response | Promise<Response>;\n}\n\nexport interface CloudflareHandler {\n\tfetch(request: Request, env: unknown, ctx: unknown): Promise<Response>;\n}\n\ntype EnvRecord = Record<string, string | undefined>;\n\n// Fill connection config from the per-request `env` on first request. On\n// Cloudflare the env is not available at module scope, so values that were not\n// set explicitly in the config are sourced from `RIVET_*` Worker variables here.\nfunction applyEnv(\n\tregistry: Registry<RegistryActors>,\n\tenv: EnvRecord,\n\tmanagerPath: string,\n): void {\n\tconst config = registry.config as RegistryConfigInput<RegistryActors>;\n\tif (!config.endpoint && env.RIVET_ENDPOINT) {\n\t\tconfig.endpoint = env.RIVET_ENDPOINT;\n\t}\n\tif (!config.namespace && env.RIVET_NAMESPACE) {\n\t\tconfig.namespace = env.RIVET_NAMESPACE;\n\t}\n\tif (!config.token && env.RIVET_TOKEN) {\n\t\tconfig.token = env.RIVET_TOKEN;\n\t}\n\tif (env.RIVET_POOL && !config.envoy?.poolName) {\n\t\tconfig.envoy = { ...config.envoy, poolName: env.RIVET_POOL };\n\t}\n\tif (!config.serverless?.basePath) {\n\t\tconfig.serverless = { ...config.serverless, basePath: managerPath };\n\t}\n}\n\n/**\n * Creates a Cloudflare Workers handler that hosts Rivet Actors on the wasm\n * runtime. Accepts either a registry from this package's `setup` or a setup\n * config (which is wired through `setup` for you).\n *\n * The Rivet manager API is mounted at `managerPath` (default `/api/rivet`).\n * Requests outside that path are routed to `options.fetch` if provided, letting\n * you mount your own routes alongside Rivet. The engine endpoint is read from\n * `RIVET_ENDPOINT` (with `RIVET_NAMESPACE`, `RIVET_TOKEN`, `RIVET_POOL` optional)\n * unless set in the config.\n */\nexport function createHandler<A extends RegistryActors>(\n\tregistry: Registry<A>,\n\toptions?: CreateHandlerOptions,\n): CloudflareHandler;\nexport function createHandler<A extends RegistryActors>(\n\tconfig: CloudflareSetupConfig<A>,\n\toptions?: CreateHandlerOptions,\n): CloudflareHandler;\nexport function createHandler<A extends RegistryActors>(\n\tregistryOrConfig: Registry<A> | CloudflareSetupConfig<A>,\n\toptions: CreateHandlerOptions = {},\n): CloudflareHandler {\n\tconst managerPath = options.managerPath ?? DEFAULT_MANAGER_PATH;\n\tconst registry =\n\t\tregistryOrConfig instanceof Registry\n\t\t\t? registryOrConfig\n\t\t\t: setup(registryOrConfig);\n\tlet envApplied = false;\n\n\treturn {\n\t\tasync fetch(request, env, ctx) {\n\t\t\tif (!envApplied) {\n\t\t\t\tapplyEnv(\n\t\t\t\t\tregistry as Registry<RegistryActors>,\n\t\t\t\t\t(env ?? {}) as EnvRecord,\n\t\t\t\t\tmanagerPath,\n\t\t\t\t);\n\t\t\t\tenvApplied = true;\n\t\t\t}\n\n\t\t\tconst url = new URL(request.url);\n\t\t\tif (\n\t\t\t\turl.pathname === managerPath ||\n\t\t\t\turl.pathname.startsWith(`${managerPath}/`)\n\t\t\t) {\n\t\t\t\treturn registry.handler(request);\n\t\t\t}\n\n\t\t\tif (options.fetch) {\n\t\t\t\treturn options.fetch(request, env, ctx);\n\t\t\t}\n\n\t\t\treturn new Response(\n\t\t\t\t\"This is a RivetKit server.\\n\\nLearn more at https://rivet.dev\\n\",\n\t\t\t);\n\t\t},\n\t};\n}\n","// Cloudflare Workers do not implement an outbound `new WebSocket(url)` client\n// constructor, but the wasm actor runtime opens its tunnel to the Rivet engine\n// through `globalThis.WebSocket`. This shim translates that constructor into\n// Cloudflare's fetch-based upgrade (`fetch(url, { Upgrade })` + `response.webSocket`)\n// and installs itself on `globalThis` so both the wasm tunnel and the TypeScript\n// client path resolve a working implementation.\n\ntype WebSocketProtocolInput = string | string[] | undefined;\n\ntype CloudflareSocket = WebSocket & { accept(): void };\n\nclass FetchWebSocket {\n\tstatic readonly CONNECTING = 0;\n\tstatic readonly OPEN = 1;\n\tstatic readonly CLOSING = 2;\n\tstatic readonly CLOSED = 3;\n\n\tbinaryType: BinaryType = \"arraybuffer\";\n\tonopen: ((event: Event) => void) | null = null;\n\tonmessage: ((event: MessageEvent) => void) | null = null;\n\tonclose: ((event: CloseEvent) => void) | null = null;\n\tonerror: ((event: Event) => void) | null = null;\n\treadyState = FetchWebSocket.CONNECTING;\n\t#socket: CloudflareSocket | undefined;\n\t#pending: Array<string | ArrayBuffer | ArrayBufferView> = [];\n\n\tconstructor(url: string, protocols?: WebSocketProtocolInput) {\n\t\tvoid this.#connect(url, protocols);\n\t}\n\n\tasync #connect(url: string, protocols?: WebSocketProtocolInput) {\n\t\ttry {\n\t\t\tconst protocolList = Array.isArray(protocols)\n\t\t\t\t? protocols\n\t\t\t\t: protocols\n\t\t\t\t\t? [protocols]\n\t\t\t\t\t: [];\n\t\t\tconst headers = new Headers({ Upgrade: \"websocket\" });\n\t\t\tif (protocolList.length > 0) {\n\t\t\t\theaders.set(\"Sec-WebSocket-Protocol\", protocolList.join(\", \"));\n\t\t\t}\n\t\t\tconst response = await fetch(\n\t\t\t\turl.replace(/^ws:/, \"http:\").replace(/^wss:/, \"https:\"),\n\t\t\t\t{ headers },\n\t\t\t);\n\t\t\tconst socket = (\n\t\t\t\tresponse as unknown as { webSocket: CloudflareSocket | null }\n\t\t\t).webSocket;\n\t\t\tif (!socket) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`websocket upgrade failed with status ${response.status}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tsocket.accept();\n\t\t\tsocket.binaryType = this.binaryType;\n\t\t\tthis.#socket = socket;\n\t\t\tthis.readyState = FetchWebSocket.OPEN;\n\t\t\tsocket.addEventListener(\"message\", (event) => {\n\t\t\t\tthis.onmessage?.(event);\n\t\t\t});\n\t\t\tsocket.addEventListener(\"close\", (event) => {\n\t\t\t\tthis.readyState = FetchWebSocket.CLOSED;\n\t\t\t\tthis.onclose?.(event);\n\t\t\t});\n\t\t\tsocket.addEventListener(\"error\", (event) => {\n\t\t\t\tthis.onerror?.(event);\n\t\t\t});\n\t\t\tthis.onopen?.(new Event(\"open\"));\n\t\t\tfor (const data of this.#pending.splice(0)) {\n\t\t\t\tsocket.send(data);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconsole.error(\"rivetkit cloudflare websocket shim failed\", error);\n\t\t\tthis.readyState = FetchWebSocket.CLOSED;\n\t\t\tthis.onerror?.(error instanceof Event ? error : new Event(\"error\"));\n\t\t\tthis.onclose?.(new CloseEvent(\"close\", { code: 1006 }));\n\t\t}\n\t}\n\n\tsend(data: string | ArrayBuffer | ArrayBufferView) {\n\t\tif (this.readyState === FetchWebSocket.CONNECTING) {\n\t\t\tthis.#pending.push(data);\n\t\t\treturn;\n\t\t}\n\t\tthis.#socket?.send(data);\n\t}\n\n\tclose(code?: number, reason?: string) {\n\t\tthis.readyState = FetchWebSocket.CLOSING;\n\t\tthis.#socket?.close(code, reason);\n\t}\n}\n\nconst globalScope = globalThis as unknown as {\n\tWebSocket: typeof WebSocket;\n\t__RIVETKIT_CF_WEBSOCKET_INSTALLED__?: boolean;\n};\n\n// Install once per isolate.\nif (!globalScope.__RIVETKIT_CF_WEBSOCKET_INSTALLED__) {\n\tglobalScope.WebSocket = FetchWebSocket as unknown as typeof WebSocket;\n\tglobalScope.__RIVETKIT_CF_WEBSOCKET_INSTALLED__ = true;\n}\n\nexport { FetchWebSocket };\n"],"mappings":";AAAA,YAAY,kBAAkB;AAC9B,OAAO,gBAAgB;AACvB;AAAA,EACC;AAAA,EAGA,SAAS;AAAA,OACH;;;ACIP,IAAM,iBAAN,MAAM,gBAAe;AAAA,EACpB,OAAgB,aAAa;AAAA,EAC7B,OAAgB,OAAO;AAAA,EACvB,OAAgB,UAAU;AAAA,EAC1B,OAAgB,SAAS;AAAA,EAEzB,aAAyB;AAAA,EACzB,SAA0C;AAAA,EAC1C,YAAoD;AAAA,EACpD,UAAgD;AAAA,EAChD,UAA2C;AAAA,EAC3C,aAAa,gBAAe;AAAA,E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-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
"check-types": "tsc --noEmit",
|
|
55
|
-
"test": "vitest run tests"
|
|
56
|
-
}
|
|
57
|
-
}
|
|
2
|
+
"name": "@rivetkit/cloudflare-workers",
|
|
3
|
+
"version": "2.3.0-rc.13",
|
|
4
|
+
"description": "Cloudflare Workers integration for RivetKit actors",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"rivetkit",
|
|
8
|
+
"cloudflare",
|
|
9
|
+
"cloudflare-workers",
|
|
10
|
+
"workers",
|
|
11
|
+
"workerd",
|
|
12
|
+
"serverless",
|
|
13
|
+
"edge",
|
|
14
|
+
"wasm",
|
|
15
|
+
"actor",
|
|
16
|
+
"microservices"
|
|
17
|
+
],
|
|
18
|
+
"sideEffects": [
|
|
19
|
+
"./dist/chunk-*.js",
|
|
20
|
+
"./dist/chunk-*.cjs",
|
|
21
|
+
"./src/websocket.ts"
|
|
22
|
+
],
|
|
23
|
+
"files": [
|
|
24
|
+
"dist",
|
|
25
|
+
"package.json"
|
|
26
|
+
],
|
|
27
|
+
"exports": {
|
|
28
|
+
".": {
|
|
29
|
+
"import": {
|
|
30
|
+
"types": "./dist/mod.d.mts",
|
|
31
|
+
"default": "./dist/mod.mjs"
|
|
32
|
+
},
|
|
33
|
+
"require": {
|
|
34
|
+
"types": "./dist/mod.d.ts",
|
|
35
|
+
"default": "./dist/mod.js"
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "tsup src/mod.ts",
|
|
41
|
+
"check-types": "tsc --noEmit"
|
|
42
|
+
},
|
|
43
|
+
"dependencies": {
|
|
44
|
+
"@rivetkit/rivetkit-wasm": "2.3.0-rc.13",
|
|
45
|
+
"rivetkit": "2.3.0-rc.13"
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"@types/node": "^22.0.0",
|
|
49
|
+
"tsup": "^8.4.0",
|
|
50
|
+
"typescript": "^5.5.2"
|
|
51
|
+
},
|
|
52
|
+
"stableVersion": "0.8.0"
|
|
53
|
+
}
|