@mcp-b/do-runtime 0.6.1 → 0.7.0

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.
@@ -1 +0,0 @@
1
- {"version":3,"file":"web-socket-W63BdFn5.js","names":["#channel","#id","#fetcher","#idFactory","#getImpl","#channel","#fetcher","#loopbackClass","#pull","#columnNames","#rawRows","#rowsWritten","#nextRow","#position","#nextRaw","#ctx","#owner","#getPageSize","#pageSize","#ctx","#kv","#getOne","#getMultiple","#putOne","#putMultiple","#cache","#sql","#cacheTxn","#rolledBack","#facetManager","#parentId","#getFacetManager","#options","#facets","#request","#response","#sentClose","#socket","#pairState","#ctx","#enableClassic","#receive","#readyState","#binaryType","#delivery","#ownClose","#peerClose","#markPairUsed","#enqueue","#activateHibernation","#pending","#deliverClassic","#receiveClose","#pump","#dispatch","#host","#entries","#rehydrate","#pairConstructor","#createPair","#listenRaw","#autoResponse","#eventTimeout","#schedule","#remove"],"sources":["../../src/api/actor.ts","../../src/api/export-loopback.ts","../../src/api/sql.ts","../../src/api/actor-state.ts","../../src/api/web-socket.ts"],"sourcesContent":["/**\n * ← workerd `src/workerd/api/actor.{h,c++}`\n *\n * Upstream's own opening comment is the best summary of why this file is named\n * what it is: \"'Actors' are the internal name for Durable Objects, because they\n * implement a sort of actor model. We ended up not calling the product 'Actors'\n * publicly because we found that people who were familiar with actor-model\n * programming were more confused than helped by it.\"\n *\n * Five classes and three outgoing factories. The five are here:\n * `ColoLocalActorNamespace` (`actor.h:25`), `DurableObjectId` (`:42`),\n * `DurableObject` (`:87`), `DurableObjectNamespace` (`:142`) and\n * `DurableObjectClass` (`:367`). The three factories — `GlobalActorOutgoingFactory`\n * (`:293`), `LocalActorOutgoingFactory` (`:331`) and `ReplicaActorOutgoingFactory`\n * (`:352`) — are **not**, and their absence is the whole of this file's seam:\n * every one of them is a bag of addressing data plus a lazily-created actor\n * channel, and `newSingleUseClient` returns a `WorkerInterface`, which is capnp\n * dispatch with no port. `ActorChannelFactory` and `ColoLocalActorChannelFactory`\n * below are the shape they plug into, holding exactly the fields the two\n * reachable factories' constructors capture.\n * `ActorRetryRequestMetadata` stays on that same omitted transport seam:\n * upstream passes it from an outgoing factory to `ActorChannel`, while the\n * host-provided `Fetcher` here already owns retry policy and exposes no metadata.\n *\n * **`ColoLocalActorNamespace` is ported, not treated as a substrate boundary**,\n * and the reason is worth stating because the opposite call is easy to defend\n * badly. It is the pre-SQLite, non-durable actor namespace, and this host cannot\n * host one — there is no storage-less actor kind here, and `createActorContainer`\n * requires a `SqlDatabaseProvider`. But *hosting* is not in this file. What is in\n * this file is the JS-facing half: one argument check and one outgoing-stub\n * request, which has precisely the same substrate needs as\n * `DurableObjectNamespace.get()`, which nobody proposes cutting. The boundary, if\n * there is one, sits in `server/` at the point something has to place an\n * ephemeral actor — so there is nothing here to cut, and cutting it would be the\n * feature subset the package README forbids.\n *\n * It is also not idle, though an earlier revision of this comment gave the wrong\n * reason. It claimed `ctx.exports` surfaces a storage-less actor class as a\n * `LoopbackColoLocalActorNamespace`; upstream's own comment\n * (`api/export-loopback.h:111-115`) says that case is a\n * `LoopbackDurableObjectClass`. `LoopbackColoLocalActorNamespace` is \"for\n * colo-local (ephemeral) actor namespaces\" (`:191`) and is built from a\n * *configured* binding, `Global::LoopbackEphemeralActorNamespace`\n * (`server/workerd-api.c++:666-670`) — reachable through configuration rather\n * than through a bare export. The conclusion stands; the path to it is that one.\n *\n * Two things are absent because there is nothing to resolve them against:\n *\n * - **The numbered-channel arm of every binding.** Each of upstream's\n * `kj::OneOf<uint, IoOwn<...>>` keeps only its object arm. Upstream resolves a\n * binding to a `uint` at configuration time; here a binding is a property of\n * the `env` object the consumer supplies, and there is no channel table for a\n * number to index. The object arm is upstream's own alternative, offered on\n * `DurableObjectNamespace` for the case where one \"is constructed dynamically\n * within an execution context, rather than being a long-lived binding\" — which\n * is every binding here.\n * - **Compatibility flags.** `getEnableVersionApi`, `getReplicaRouting`,\n * `getDurableObjectGetExisting` and `getDurableObjectFetchRequiresSchemeAuthority`\n * are read four times in `actor.c++`. A runtime with no deployed history takes\n * the current behaviour, which is the same judgment `deleteAll()`'s\n * `deleteAllDeletesAlarm` row already records. The one that is not a flag\n * decision is `enableReplicaRouting`, which is `false` because replication is a\n * named substrate boundary in `io/actor-cache.ts`.\n *\n * `serialize`/`deserialize` on `DurableObjectClass` are a boundary of their own:\n * they are built on `jsg::Serializer`, `Frankenvalue`, capnp `rpc::JsValue::External`\n * and channel tokens, none of which has a port. Both throw one named message.\n *\n * Spec: §1.10, §1.11 in docs/decisions.md.\n */\n\nimport type { ActorGetMode, ActorId, ActorIdFactory, ActorRoutingMode, ActorVersion } from \"../io/actor-id\";\nimport type { ActorClassChannel } from \"../io/io-channels\";\n\n// =======================================================================================\n// Constants\n\n/**\n * ← the `[1, 2048]` bound in `ColoLocalActorNamespace::get`.\n *\n * Upstream compares `actorId.size()`, which for a `kj::String` is **bytes**, so\n * this is measured in UTF-8 bytes rather than in UTF-16 code units. That costs\n * one `TextEncoder` pass and buys an exact match on a bound a caller can hit.\n */\nexport const MAX_COLO_LOCAL_ACTOR_ID_BYTES = 2048;\n\n/**\n * Upstream never faces this: JSG unwraps a `jsg::Ref<DurableObjectId>` parameter\n * and throws a `TypeError` before the method body runs, so `getInner()` cannot be\n * reached on something that is not one. Here the parameter type is\n * workers-types' structural `DurableObjectId` interface, which any object with a\n * `toString` and an `equals` satisfies — so the unwrap has to be written, and it\n * fails closed rather than guessing at the string form.\n */\nexport const FOREIGN_ACTOR_ID_MESSAGE =\n \"This DurableObjectId was not created by this runtime, so its underlying actor id cannot be \" +\n \"read. Ids must come from newUniqueId(), idFromName() or idFromString() on a \" +\n \"DurableObjectNamespace.\";\n\n/** Substrate boundary: `jsg::Serializer`, `Frankenvalue` and channel tokens have no port. */\nexport const ACTOR_CLASS_SERIALIZATION_UNIMPLEMENTED_MESSAGE =\n \"DurableObjectClass cannot be serialized in this runtime: upstream writes a channel token \" +\n \"through jsg::Serializer and Frankenvalue, and neither the token nor the serializer has an \" +\n \"equivalent here.\";\n\n/**\n * Replication is a named substrate boundary (`io/actor-cache.ts`), so no request\n * this file builds asks for replica routing. Upstream reads\n * `FeatureFlags::get(js).getReplicaRouting()` here.\n */\nconst ENABLE_REPLICA_ROUTING = false;\n\n// =======================================================================================\n// The outgoing seam — the shape the three factories plug into\n\n/**\n * ← what `GlobalActorOutgoingFactory`'s constructor captures (`actor.h:297-303`),\n * one field per constructor parameter minus the channel number.\n */\nexport type GlobalActorRequest = {\n readonly id: ActorId;\n readonly locationHint: string | undefined;\n readonly mode: ActorGetMode;\n readonly enableReplicaRouting: boolean;\n readonly routingMode: ActorRoutingMode;\n readonly version: ActorVersion | undefined;\n};\n\n/**\n * ← `DurableObjectNamespace::ActorChannelFactory` (`actor.h:147-157`) composed\n * with `IoChannelFactory::getGlobalActor`, which is what its one implementation\n * forwards to.\n *\n * The composition is not a shortcut. Upstream's `getGlobalActor` returns an\n * `ActorChannel`, and the only thing done with one is `startRequest(...)` →\n * `WorkerInterface`, which the `Fetcher` then drives. `WorkerInterface` has no\n * port and `Fetcher` construction is `api/http.{h,c++}`'s, which is not ported,\n * so the channel and the stub it produces are one object here — the same collapse\n * `io/worker.ts`'s `FacetManager.getFacet` and `server/actor-container.ts`'s\n * `FacetHandle.stub` already make.\n *\n * Section 7 implements this. The laziness upstream's factory has — \"Lazily\n * initialize actorChannel\" — belongs to the implementation, not to the interface,\n * because upstream's own laziness is per-`newSingleUseClient` and there is no\n * per-request client here to be lazy about.\n */\nexport interface ActorChannelFactory {\n getGlobalActor(request: GlobalActorRequest): Fetcher;\n}\n\n/** ← what `LocalActorOutgoingFactory`'s constructor captures (`actor.h:333-335`). */\nexport type ColoLocalActorRequest = {\n readonly actorId: string;\n};\n\n/**\n * ← `IoChannelFactory::getColoLocalActor`, reached through\n * `LocalActorOutgoingFactory`.\n *\n * Upstream gives `ColoLocalActorNamespace` only the numbered-channel arm, because\n * an ephemeral namespace is always a configured binding there. With no channel\n * table the factory arm is the only one available, so this is the same\n * substitution upstream itself offers `DurableObjectNamespace` — applied to the\n * one constructor that did not already have it.\n */\nexport interface ColoLocalActorChannelFactory {\n getColoLocalActor(request: ColoLocalActorRequest): Fetcher;\n}\n\n// =======================================================================================\n// ColoLocalActorNamespace\n\n/**\n * ← `ColoLocalActorNamespace` (`actor.h:25-37`). \"A capability to an ephemeral\n * Actor namespace.\"\n */\nexport class ColoLocalActorNamespace implements globalThis.ColoLocalActorNamespace {\n readonly #channel: ColoLocalActorChannelFactory;\n\n constructor(channel: ColoLocalActorChannelFactory) {\n this.#channel = channel;\n }\n\n /** ← `ColoLocalActorNamespace::get` (`actor.c++:116-129`). */\n get(actorId: string): Fetcher {\n const bytes = utf8Length(actorId);\n if (!(bytes > 0 && bytes <= MAX_COLO_LOCAL_ACTOR_ID_BYTES)) {\n throw new TypeError(\n `Actor ID length must be in the range [1, ${MAX_COLO_LOCAL_ACTOR_ID_BYTES}].`,\n );\n }\n return this.#channel.getColoLocalActor({ actorId });\n }\n}\n\nconst textEncoder = new TextEncoder();\n\n/** `kj::String::size()` is bytes; `String.prototype.length` is UTF-16 code units. */\nfunction utf8Length(value: string): number {\n return textEncoder.encode(value).length;\n}\n\n// =======================================================================================\n// DurableObjectId\n\n/**\n * ← `DurableObjectId` (`actor.h:42-84`). \"DurableObjectId type seen by\n * JavaScript.\"\n *\n * `name` and `jurisdiction` are read from the inner id **once, at construction**,\n * where upstream's are `JSG_READONLY_INSTANCE_PROPERTY`s that re-read it on every\n * access. That is not a preference: `@cloudflare/workers-types` declares both\n * `readonly name?: string`, and under `exactOptionalPropertyTypes` a getter\n * returning `string | undefined` does not satisfy an optional `string`. An own\n * property assigned only when the value exists does, and it is what keeps this\n * class assignable to the interface with no cast (§2.4). The one behaviour lost\n * is `ActorIdImpl::clearName()` (`server/actor-id-impl.h`) taking effect on an\n * already-wrapped id — a `server/`-internal that runs before the id reaches JS.\n */\nexport class DurableObjectId implements globalThis.DurableObjectId {\n readonly #id: ActorId;\n readonly name?: string;\n readonly jurisdiction?: string;\n\n constructor(id: ActorId) {\n this.#id = id;\n const name = id.getName();\n if (name !== undefined) this.name = name;\n const jurisdiction = id.getJurisdiction();\n if (jurisdiction !== undefined) this.jurisdiction = jurisdiction;\n }\n\n /** ← `getInner()`. Not JS-visible upstream either; the outgoing factories take it. */\n getInner(): ActorId {\n return this.#id;\n }\n\n /** \"Converts to a string which can be passed back to the constructor to reproduce the same ID.\" */\n toString(): string {\n return this.#id.toString();\n }\n\n equals(other: globalThis.DurableObjectId): boolean {\n return this.#id.equals(innerIdOf(other));\n }\n}\n\n/** The unwrap JSG performs for a `jsg::Ref<DurableObjectId>` parameter. */\nfunction requireDurableObjectId(id: globalThis.DurableObjectId): DurableObjectId {\n if (id instanceof DurableObjectId) return id;\n throw new TypeError(FOREIGN_ACTOR_ID_MESSAGE);\n}\n\nfunction innerIdOf(id: globalThis.DurableObjectId): ActorId {\n return requireDurableObjectId(id).getInner();\n}\n\n// =======================================================================================\n// The DurableObject stub\n\n/**\n * ← `DurableObject` (`actor.h:87-139`). \"Stub object used to send messages to a\n * remote durable object.\"\n *\n * Upstream's carries its whole behaviour by `JSG_INHERIT(Fetcher)` and adds\n * exactly two readonly properties. So does this: the `Fetcher` is the transport's\n * and everything except `id` and `name` belongs to it. `asDurableObjectStub`\n * below is where the inheritance goes.\n */\nexport class DurableObject {\n readonly #id: DurableObjectId;\n readonly #fetcher: Fetcher;\n\n constructor(id: DurableObjectId, fetcher: Fetcher) {\n this.#id = id;\n this.#fetcher = fetcher;\n }\n\n /** ← `JSG_READONLY_INSTANCE_PROPERTY(id, getId)`. */\n getId(): DurableObjectId {\n return this.#id;\n }\n\n /** ← `JSG_READONLY_INSTANCE_PROPERTY(name, getName)`. */\n getName(): string | undefined {\n return this.#id.name;\n }\n\n /** The `Fetcher` upstream inherits from rather than holds. */\n getFetcher(): Fetcher {\n return this.#fetcher;\n }\n}\n\n/**\n * ← `js.alloc<DurableObject>(...)` plus `JSG_INHERIT(Fetcher)` plus the\n * `JSG_TS_OVERRIDE` that renames the resource type to `DurableObjectStub`.\n *\n * The named assertion is the same one `io/worker.ts`'s `asFacetStub` makes and\n * for the same reason: `DurableObjectStub<T>` is `Fetcher<T, …> & { id, name }`,\n * and `Fetcher<T>` for an unresolved `T` is `Rpc.Provider<T, …>`, a conditional\n * type TypeScript defers until `T` is known — where `T` is the caller's claim\n * about a class it named, which no value can confirm. Upstream is in the same\n * position and answers it the same way, with the parameter living only inside a\n * `JSG_TS_OVERRIDE`.\n *\n * The `Proxy` is what JSG inheritance costs in JS. Two properties have to answer\n * from the id and every other property — `fetch`, `connect`, and every RPC method\n * name, which are the whole point of a stub — has to reach the transport with\n * `this` still bound to it. Bound methods are memoised so `stub.foo === stub.foo`,\n * which upstream gets for free by there being one object rather than two.\n */\nexport function asDurableObjectStub<T extends Rpc.DurableObjectBranded | undefined>(\n object: DurableObject,\n): DurableObjectStub<T> {\n const fetcher = object.getFetcher();\n const bound = new Map<string | symbol, unknown>();\n\n const stub = new Proxy(fetcher, {\n get(target, property): unknown {\n if (property === \"id\") return object.getId();\n if (property === \"name\") return object.getName();\n const cached = bound.get(property);\n if (cached !== undefined) return cached;\n const value: unknown = Reflect.get(target, property, target);\n if (typeof value !== \"function\") return value;\n const method: unknown = value.bind(target);\n bound.set(property, method);\n return method;\n },\n\n has(target, property): boolean {\n if (property === \"id\" || property === \"name\") return true;\n return Reflect.has(target, property);\n },\n\n ownKeys(target): ArrayLike<string | symbol> {\n const keys = Reflect.ownKeys(target).filter((key) => key !== \"id\" && key !== \"name\");\n return [\"id\", \"name\", ...keys];\n },\n\n getOwnPropertyDescriptor(target, property): PropertyDescriptor | undefined {\n if (property === \"id\" || property === \"name\") {\n return {\n value: property === \"id\" ? object.getId() : object.getName(),\n writable: false,\n enumerable: true,\n // Configurable, because the target does not have these keys and a Proxy may not\n // report a non-configurable descriptor for a property its target lacks.\n configurable: true,\n };\n }\n return Reflect.getOwnPropertyDescriptor(target, property);\n },\n });\n\n return stub as DurableObjectStub<T>;\n}\n\n// =======================================================================================\n// DurableObjectNamespace\n\n/** ← `DurableObjectNamespace::NewUniqueIdOptions` (`actor.h:166-177`). */\nexport type NewUniqueIdOptions = {\n /** \"Restricts the new unique ID to a set of colos within a jurisdiction.\" */\n readonly jurisdiction?: string | null;\n};\n\n/** ← `DurableObjectNamespace::GetDurableObjectOptions` (`actor.h:193-234`). */\nexport type GetDurableObjectOptions = {\n readonly locationHint?: string;\n /**\n * \"`routingMode` may be be of interest to applications using Durable Objects\n * replicas. It can be one of the following options: none: the default,\n * indicates we will pick for the application. 'primary-only': guarantees we\n * route directly to the primary (skip any replicas).\"\n */\n readonly routingMode?: string;\n readonly version?: { readonly cohort?: string };\n};\n\n/**\n * ← `DurableObjectNamespace` (`actor.h:142-291`). \"Global durable object class\n * binding type.\"\n */\nexport class DurableObjectNamespace<T extends Rpc.DurableObjectBranded | undefined = undefined>\n implements globalThis.DurableObjectNamespace<T>\n{\n readonly #channel: ActorChannelFactory;\n readonly #idFactory: ActorIdFactory;\n\n constructor(channel: ActorChannelFactory, idFactory: ActorIdFactory) {\n this.#channel = channel;\n this.#idFactory = idFactory;\n }\n\n /**\n * \"Create a new unique ID for a durable object that will be allocated nearby\n * the calling colo.\"\n */\n newUniqueId(options?: NewUniqueIdOptions): DurableObjectId {\n return new DurableObjectId(this.#idFactory.newUniqueId(options?.jurisdiction ?? undefined));\n }\n\n /**\n * \"Create a name-derived ID. Passing in the same `name` (to the same class)\n * will always produce the same ID.\"\n */\n idFromName(name: string): DurableObjectId {\n return new DurableObjectId(this.#idFactory.idFromName(name));\n }\n\n /**\n * \"Create a DurableObjectId from the stringified form of the ID (as produced by\n * calling `toString()` on a durable object ID). Throws if the ID is not a\n * 64-digit hex number, or if the ID was not originally created for this class.\"\n */\n idFromString(id: string): DurableObjectId {\n return new DurableObjectId(this.#idFactory.idFromString(id));\n }\n\n /** \"Gets a durable object by ID or creates it if it doesn't already exist.\" */\n get(id: globalThis.DurableObjectId, options?: GetDurableObjectOptions): DurableObjectStub<T> {\n return this.#getImpl(\"GET_OR_CREATE\", id, options);\n }\n\n /**\n * \"Gets a durable object by name or creates it if it doesn't already exist.\n * Short for `idFromName()` followed by `get()`.\"\n */\n getByName(name: string, options?: GetDurableObjectOptions): DurableObjectStub<T> {\n return this.#getImpl(\"GET_OR_CREATE\", this.idFromName(name), options);\n }\n\n /**\n * \"Experimental. Gets a durable object by ID if it already exists. Currently,\n * gated for use by cloudflare only.\"\n *\n * Upstream exposes it only when the `durableObjectGetExisting` compat flag is\n * on, and `@cloudflare/workers-types` 4.20260702.1 does not declare it. It is\n * exposed unconditionally here, which is the current-behaviour reading every\n * other compat flag in this file gets.\n */\n getExisting(\n id: globalThis.DurableObjectId,\n options?: GetDurableObjectOptions,\n ): DurableObjectStub<T> {\n return this.#getImpl(\"GET_EXISTING\", id, options);\n }\n\n /**\n * \"Creates a subnamespace with the jurisdiction hardcoded.\"\n *\n * The argument is optional because upstream's is a\n * `jsg::Optional<kj::Maybe<kj::String>>`, so both \"omitted\" and \"null\" mean the\n * same thing — `cloneWithJurisdiction(kj::none)`, a subnamespace with none.\n */\n jurisdiction(jurisdiction?: string | null): DurableObjectNamespace<T> {\n return new DurableObjectNamespace<T>(\n this.#channel,\n this.#idFactory.cloneWithJurisdiction(jurisdiction ?? undefined),\n );\n }\n\n /** ← `DurableObjectNamespace::getImpl` (`actor.c++:167-213`). */\n #getImpl(\n mode: ActorGetMode,\n id: globalThis.DurableObjectId,\n options: GetDurableObjectOptions | undefined,\n ): DurableObjectStub<T> {\n const durableObjectId = requireDurableObjectId(id);\n const inner = durableObjectId.getInner();\n if (!this.#idFactory.matchesJurisdiction(inner)) {\n throw new TypeError(\n \"get called on jurisdictional subnamespace with an ID from a different jurisdiction\",\n );\n }\n\n let routingMode: ActorRoutingMode = \"DEFAULT\";\n const requestedRoutingMode = options?.routingMode;\n if (requestedRoutingMode !== undefined) {\n if (requestedRoutingMode !== \"primary-only\") {\n throw new RangeError(`unknown routingMode: ${requestedRoutingMode}`);\n }\n routingMode = \"PRIMARY_ONLY\";\n }\n\n const fetcher = this.#channel.getGlobalActor({\n id: inner,\n locationHint: options?.locationHint,\n mode,\n enableReplicaRouting: ENABLE_REPLICA_ROUTING,\n routingMode,\n version: actorVersionOf(options?.version),\n });\n\n // The id handed to the stub is the one the caller passed, as upstream's `id.addRef()` is.\n return asDurableObjectStub<T>(new DurableObject(durableObjectId, fetcher));\n }\n}\n\n/**\n * ← `version = ActorVersion{.cohort = kj::mv(v.cohort)}` (`actor.c++:186-190`),\n * behind `FeatureFlags::get(js).getEnableVersionApi()` which this file reads as\n * on. A version with no cohort is still a version, which is why the empty object\n * is not collapsed to `undefined`.\n */\nfunction actorVersionOf(version: { readonly cohort?: string } | undefined): ActorVersion | undefined {\n if (version === undefined) return undefined;\n return version.cohort === undefined ? {} : { cohort: version.cohort };\n}\n\n// =======================================================================================\n// DurableObjectClass\n\n/**\n * ← `DurableObjectClass` (`actor.h:367-393`). \"DurableObjectClass represents a\n * binding to a Durable Object class that can be used as a facet. The only use of\n * this type is to pass to `ctx.facets.get()`.\"\n *\n * `getChannel()` takes no `IoContext` because the parameter existed to resolve the\n * numbered-channel arm, and there is no numbered-channel arm here.\n */\nexport class DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined>\n implements globalThis.DurableObjectClass<_T>\n{\n readonly #channel: ActorClassChannel;\n\n constructor(channel: ActorClassChannel) {\n this.#channel = channel;\n }\n\n /** ← `DurableObjectClass::getChannel` (`actor.c++:232-242`). */\n getChannel(): ActorClassChannel {\n return this.#channel;\n }\n\n /**\n * ← `DurableObjectClass::serialize` (`actor.c++:244-306`). Substrate boundary.\n *\n * `requireAllowsTransfer()` runs first, exactly as upstream's does, so a class\n * that refuses transfer reports that rather than the boundary — the refusal is\n * the more specific answer and it is the one upstream would give too.\n */\n serialize(): never {\n this.#channel.requireAllowsTransfer();\n throw new Error(ACTOR_CLASS_SERIALIZATION_UNIMPLEMENTED_MESSAGE);\n }\n\n /** ← `DurableObjectClass::deserialize` (`actor.c++:308-359`). Substrate boundary. */\n static deserialize(): never {\n throw new Error(ACTOR_CLASS_SERIALIZATION_UNIMPLEMENTED_MESSAGE);\n }\n}\n","/**\n * ← workerd `src/workerd/api/export-loopback.{h,c++}`\n *\n * The four types `ctx.exports` is made of. Upstream's own comment on the first\n * says what they all are: \"the type of a property of `ctx.exports` which points\n * back at a … entrypoint of this Worker\", specialized by *invoking* it.\n *\n * - `LoopbackServiceStub` (`export-loopback.h:18`) — a stateless entrypoint. A\n * `Fetcher` with empty props, callable to get one with props.\n * - `LoopbackDurableObjectClass` (`:116`) — an actor class with **no storage\n * configured**. A `DurableObjectClass`, callable to get a specialized one.\n * - `LoopbackDurableObjectNamespace` (`:155`) — an actor class **with** storage:\n * \"we want a binding that behaves *both* like a LoopbackDurableObjectClass\n * *and* like a DurableObjectNamespace binding.\"\n * - `LoopbackColoLocalActorNamespace` (`:192`) — the same, for a colo-local\n * (ephemeral) namespace binding.\n *\n * The third is why this file blocks `server/`. The vendored consumer reads\n * `ctx.exports[className]` and needs one value to answer both `idFromName`\n * (`vendor/agents/packages/agents/src/index.ts:10829`, `:10855`) and\n * `ctx.facets.get`'s class check (`:10857`) — namespace-shaped and class-shaped\n * at once, which is exactly what `LoopbackDurableObjectNamespace` is for.\n * Upstream's own `api/tests/worker-loader-test.js:449-450` pins the same pair.\n *\n * **`JSG_CALLABLE` becomes a `Proxy` with an `apply` trap.** A JS value can only\n * be invoked if it is a function, and a class instance is not one; the private\n * fields these classes inherit mean the callable cannot simply be a function\n * whose prototype is the instance, because an inherited method would then run\n * with `this` set to the function. So each class keeps its behaviour and an\n * `asLoopback…` function produces the JS-visible value — the same split, for the\n * same reason, that `asDurableObjectStub` already makes for `JSG_INHERIT`.\n * `getPrototypeOf` is what keeps `instanceof` answering, which is how\n * `DurableObjectFacets.get` discriminates the three arms of its class switch.\n *\n * **Two `IoChannelFactory` methods are declared here rather than in\n * `io/io-channels.ts`.** `getSubrequestChannel` and `getActorClass` are what\n * `export-loopback.c++` reaches for, and both take a channel *number* upstream —\n * which this package does not have (`io/io-channels.ts`'s header: there is no\n * numbered channel table). So each collapses into a factory taking an object\n * request, exactly as `api/actor.ts` already does for `IoChannelFactory`'s\n * `getGlobalActor` and `getColoLocalActor`, and each is declared beside its one\n * consumer for the same reason `ActorChannelFactory` is. Section 7 fills them.\n *\n * **Non-serializability survives, and Section 7b is where it is enforced.**\n * Upstream is explicit that `LoopbackServiceStub` is \"intentionally NOT\n * serializable, unlike its parent class Fetcher\", and\n * `api/tests/worker-loader-test.js:104` asserts the message;\n * `LoopbackDurableObjectClass` likewise declares no `JSG_SERIALIZABLE` where\n * `DurableObjectClass` (`actor.h:389`) does, and neither namespace type declares\n * one either — `JSG_INHERIT` does not carry serializability, which is what the\n * test's own comment says it is checking.\n *\n * An earlier revision of this paragraph said the refusal did not survive, and\n * named `src/transport/` as the layer that would have to make it. Both halves\n * were wrong about *where*: the test reaches the refusal through\n * `worker.getEntrypoint(name, {props})`, and `WorkerStub::getEntrypoint`'s first\n * act is `Frankenvalue::fromJs`, which runs `jsg::Serializer` inside\n * `api/worker-loader.c++`. So `api/worker-loader.ts`'s `requireSerializableProps`\n * refuses all four of these in `props` and in `env`, with upstream's message and\n * a `DataCloneError`. `DurableObjectClass.serialize` remains a separate named\n * substrate boundary that throws for every class, loopback or not.\n *\n * The version half of `LoopbackServiceStub` is present and `Options`, the\n * flag-off form, is not: `FeatureFlags::getEnableVersionApi()` is read as on\n * here, the same current-behaviour reading `api/actor.ts` gives the four\n * compatibility flags it meets. That makes this a superset of\n * `@cloudflare/workers-types` 4.20260702.1, which generated the flag-off\n * signature — the same relationship `DurableObjectNamespace.getExisting` has.\n *\n * Spec: §1.10, §1.11, decisions 14 and 16 in\n * docs/decisions.md.\n */\n\nimport type { ActorIdFactory } from \"../io/actor-id\";\nimport type { ActorClassChannel } from \"../io/io-channels\";\nimport {\n ColoLocalActorNamespace,\n DurableObjectClass,\n DurableObjectNamespace,\n type ActorChannelFactory,\n type ColoLocalActorChannelFactory,\n} from \"./actor\";\n\n// =======================================================================================\n// Constants\n\n/**\n * ← what JSG's struct unwrapper does with a value that is not an object\n * (`jsg/struct.h:246`). Undefined and null are **not** in that set: a struct\n * whose every field is optional — which both option structs here are — unwraps\n * from either as an empty struct (`jsg/struct.h:236-243`), so `ctx.exports.Foo()`\n * is upstream's own empty-options call and not an error.\n */\nexport const LOOPBACK_OPTIONS_NOT_AN_OBJECT_MESSAGE =\n \"A ctx.exports binding is invoked with an options object: pass { props }, or nothing at all.\";\n\n/** ← what JSG does unwrapping a `jsg::JsRef<jsg::JsObject>` from a non-object. */\nexport const LOOPBACK_PROPS_NOT_AN_OBJECT_MESSAGE =\n \"`props` must be an object. Upstream unwraps it as a jsg::JsObject, which refuses anything else.\";\n\n// =======================================================================================\n// The outgoing seam — the two IoChannelFactory methods this file reaches\n\n/** ← `IoChannelFactory::VersionRequest` (`io/io-channels.h:123-131`). */\nexport type VersionRequest = {\n /** \"Request a version within the given cohort.\" */\n readonly cohort: string | undefined;\n};\n\n/**\n * ← the two arguments `IoChannelFactory::getSubrequestChannel` takes besides the\n * channel number (`io/io-channels.h:243-245`). Upstream: \"`props` and\n * `versionRequest` can only be specified if this is a loopback channel (i.e.\n * from ctx.exports).\"\n */\nexport type SubrequestChannelRequest = {\n /** ← `kj::Maybe<Frankenvalue> props`. */\n readonly props: unknown;\n readonly version: VersionRequest | undefined;\n};\n\n/**\n * ← `IoChannelFactory::getSubrequestChannel` composed with the `Fetcher` upstream\n * builds over the `SubrequestChannel` it returns.\n *\n * The composition is `api/actor.ts`'s: a `SubrequestChannel` is only ever driven\n * through `startRequest()` → `WorkerInterface`, which has no port, while the\n * JS-visible product is a `Fetcher` — so the channel and the stub it produces are\n * one object here.\n */\nexport interface SubrequestChannelFactory {\n getSubrequestChannel(request: SubrequestChannelRequest): Fetcher;\n}\n\n/** ← the `props` argument of `IoChannelFactory::getActorClass` (`io/io-channels.h:315`). */\nexport type ActorClassRequest = {\n readonly props: unknown;\n};\n\n/** ← `IoChannelFactory::getActorClass`, which returns the token `io/io-channels.ts` ports. */\nexport interface ActorClassChannelFactory {\n getActorClass(request: ActorClassRequest): ActorClassChannel;\n}\n\n// =======================================================================================\n// The option structs\n\n/** ← `LoopbackServiceStub::OptionsWithVersion::Version` (`export-loopback.h:32-36`). */\nexport type LoopbackServiceStubVersion = {\n /** `jsg::Optional<kj::Maybe<kj::String>>`: omitted and null are the same request. */\n readonly cohort?: string | null;\n};\n\n/** ← `LoopbackServiceStub::OptionsWithVersion` (`export-loopback.h:31-42`). */\nexport type LoopbackServiceStubOptions = {\n readonly props?: unknown;\n readonly version?: LoopbackServiceStubVersion;\n};\n\n/** ← `LoopbackDurableObjectClass::Options` (`export-loopback.h:120-124`). */\nexport type LoopbackDurableObjectClassOptions = {\n readonly props?: unknown;\n};\n\n// =======================================================================================\n// LoopbackServiceStub\n\n/**\n * ← `LoopbackServiceStub` (`export-loopback.h:18-109`).\n *\n * Upstream is a `Fetcher` on the loopback channel and holds the channel number a\n * second time so `callImpl` can re-specialize it. Here the `Fetcher` is the\n * transport's — `api/http.{h,c++}` is not ported — so the unspecialized stub is\n * what the factory returns for a request with no props and no version, and the\n * factory is the thing held twice over.\n */\nexport class LoopbackServiceStub {\n readonly #channel: SubrequestChannelFactory;\n readonly #fetcher: Fetcher;\n\n constructor(channel: SubrequestChannelFactory) {\n this.#channel = channel;\n this.#fetcher = channel.getSubrequestChannel({ props: undefined, version: undefined });\n }\n\n /** The `Fetcher` upstream inherits from rather than holds, as `DurableObject`'s is. */\n getFetcher(): Fetcher {\n return this.#fetcher;\n }\n\n /**\n * ← `LoopbackServiceStub::callImpl` (`export-loopback.c++:11-29`) reached\n * through `callWithVersion` (`export-loopback.h:53-55`), which is the callable\n * when `enableVersionApi` is on. \"Create a specialized Fetcher which can be\n * passed over RPC.\"\n */\n callWithVersion(options: LoopbackServiceStubOptions): Fetcher {\n return this.#channel.getSubrequestChannel({\n props: requireProps(options.props),\n version: versionRequestOf(options.version),\n });\n }\n}\n\n/**\n * ← `js.alloc<LoopbackServiceStub>(…)` plus `JSG_CALLABLE(callWithVersion)`.\n *\n * The declared type is a superset of `@cloudflare/workers-types`' by exactly the\n * `version` field, for the reason in this module's header.\n */\nexport type LoopbackServiceStubValue<\n T extends Rpc.WorkerEntrypointBranded | undefined = undefined,\n> = Fetcher<T> & ((options?: LoopbackServiceStubOptions) => Fetcher<T>);\n\nexport function asLoopbackServiceStub<\n T extends Rpc.WorkerEntrypointBranded | undefined = undefined,\n>(stub: LoopbackServiceStub): LoopbackServiceStubValue<T> {\n return asCallable({\n properties: stub.getFetcher(),\n prototype: LoopbackServiceStub.prototype,\n call: (options) => stub.callWithVersion(requireOptions(options)),\n });\n}\n\n// =======================================================================================\n// LoopbackDurableObjectClass\n\n/**\n * ← `LoopbackDurableObjectClass` (`export-loopback.h:116-148`). \"Similar to\n * LoopbackServiceStub, but for actor classes … this is used for actor classes\n * that do *not* have any storage configured. If you simply export a class\n * extending `DurableObject` but you don't configure storage for it, it shows up\n * in `ctx.exports` as this type. This can be used to create a Durable Object\n * facet.\"\n *\n * Upstream's base `DurableObjectClass` holds the channel *number*, and\n * `getChannel(ioctx)` resolves it lazily. There is no numbered arm here, so the\n * unspecialized channel is requested once, in the constructor — which is the same\n * value `getActorClass(channel)` with default props would have produced.\n */\nexport class LoopbackDurableObjectClass<\n T extends Rpc.DurableObjectBranded | undefined = undefined,\n> extends DurableObjectClass<T> {\n readonly #channel: ActorClassChannelFactory;\n\n constructor(channel: ActorClassChannelFactory) {\n super(channel.getActorClass({ props: undefined }));\n this.#channel = channel;\n }\n\n /**\n * ← `LoopbackDurableObjectClass::call` (`export-loopback.c++:31-40`). \"Create a\n * specialized DurableObjectClass which can be passed over RPC.\"\n *\n * The result is a plain `DurableObjectClass`, as `js.alloc<DurableObjectClass>`\n * is: specializing a loopback class does not produce another loopback class.\n */\n call(options: LoopbackDurableObjectClassOptions): DurableObjectClass<T> {\n return new DurableObjectClass<T>(\n this.#channel.getActorClass({ props: requireProps(options.props) }),\n );\n }\n}\n\n/** ← `js.alloc<LoopbackDurableObjectClass>(…)` plus `JSG_CALLABLE(call)`. */\nexport type LoopbackDurableObjectClassValue<\n T extends Rpc.DurableObjectBranded | undefined = undefined,\n> = DurableObjectClass<T> &\n ((options?: LoopbackDurableObjectClassOptions) => DurableObjectClass<T>);\n\nexport function asLoopbackDurableObjectClass<\n T extends Rpc.DurableObjectBranded | undefined = undefined,\n>(actorClass: LoopbackDurableObjectClass<T>): LoopbackDurableObjectClassValue<T> {\n return asCallable({\n properties: actorClass,\n prototype: Object.getPrototypeOf(actorClass),\n call: (options) => actorClass.call(requireOptions(options)),\n });\n}\n\n// =======================================================================================\n// LoopbackDurableObjectNamespace\n\n/**\n * ← `LoopbackDurableObjectNamespace` (`export-loopback.h:155-189`).\n *\n * Upstream: \"used when the class has storage configured. In this case, we want a\n * binding that behaves *both* like a LoopbackDurableObjectClass *and* like a\n * DurableObjectNamespace binding. Easy enough, we'll inherit\n * DurableObjectNamespace, but also make the binding invokable as a function like\n * LoopbackDurableObjectClass.\"\n */\nexport class LoopbackDurableObjectNamespace<\n T extends Rpc.DurableObjectBranded | undefined = undefined,\n> extends DurableObjectNamespace<T> {\n readonly #loopbackClass: LoopbackDurableObjectClass<T>;\n\n constructor(\n channel: ActorChannelFactory,\n idFactory: ActorIdFactory,\n loopbackClass: LoopbackDurableObjectClass<T>,\n ) {\n super(channel, idFactory);\n this.#loopbackClass = loopbackClass;\n }\n\n /** ← `getClass()`. \"getClass() accessor for use from C++ only.\" */\n getClass(): LoopbackDurableObjectClass<T> {\n return this.#loopbackClass;\n }\n\n /** ← `call`. \"Invoking the binding creates a specialization of the class -- not the namespace.\" */\n call(options: LoopbackDurableObjectClassOptions): DurableObjectClass<T> {\n return this.#loopbackClass.call(options);\n }\n}\n\n/**\n * ← `js.alloc<LoopbackDurableObjectNamespace>(…)` plus `JSG_CALLABLE(call)`.\n *\n * This is the type of a `ctx.exports` entry for a Durable Object class with\n * storage, and the reason it is stated in terms of this package's classes rather\n * than `@cloudflare/workers-types`' `LoopbackDurableObjectNamespace` is that the\n * pinned interface is `interface LoopbackDurableObjectNamespace extends\n * DurableObjectNamespace {}` — no call signature, because that resource type\n * carries no `JSG_TS_OVERRIDE` to generate one from. `Cloudflare.Exports`\n * describes the same value correctly, as `LoopbackDurableObjectClass<T> &\n * DurableObjectNamespace<T>`, and `PinnedLoopbackTypes` below checks against\n * that rather than against the interface.\n *\n * `call` is omitted because `JSG_CALLABLE` registers it as the object's call\n * behaviour rather than as a property: on the value, `.call` is\n * `Function.prototype.call`, which is what `asCallable`'s `get` trap answers.\n */\nexport type LoopbackDurableObjectNamespaceValue<\n T extends Rpc.DurableObjectBranded | undefined = undefined,\n> = Omit<LoopbackDurableObjectNamespace<T>, \"call\"> &\n ((options?: LoopbackDurableObjectClassOptions) => DurableObjectClass<T>);\n\nexport function asLoopbackDurableObjectNamespace<\n T extends Rpc.DurableObjectBranded | undefined = undefined,\n>(namespace: LoopbackDurableObjectNamespace<T>): LoopbackDurableObjectNamespaceValue<T> {\n return asCallable({\n properties: namespace,\n prototype: Object.getPrototypeOf(namespace),\n call: (options) => namespace.call(requireOptions(options)),\n });\n}\n\n// =======================================================================================\n// LoopbackColoLocalActorNamespace\n\n/**\n * ← `LoopbackColoLocalActorNamespace` (`export-loopback.h:192-220`). \"Like\n * LoopbackDurableObjectNamespace, but for colo-local (ephemeral) actor\n * namespaces.\"\n */\nexport class LoopbackColoLocalActorNamespace extends ColoLocalActorNamespace {\n readonly #loopbackClass: LoopbackDurableObjectClass;\n\n constructor(channel: ColoLocalActorChannelFactory, loopbackClass: LoopbackDurableObjectClass) {\n super(channel);\n this.#loopbackClass = loopbackClass;\n }\n\n /** ← `getClass()`. \"getClass() accessor for use from C++ only.\" */\n getClass(): LoopbackDurableObjectClass {\n return this.#loopbackClass;\n }\n\n /** ← `call`. \"Invoking the binding creates a specialization of the class -- not the namespace.\" */\n call(options: LoopbackDurableObjectClassOptions): DurableObjectClass {\n return this.#loopbackClass.call(options);\n }\n}\n\n/**\n * ← `js.alloc<LoopbackColoLocalActorNamespace>(…)` plus `JSG_CALLABLE(call)`,\n * with `call` omitted for the reason given on the durable namespace above.\n */\nexport type LoopbackColoLocalActorNamespaceValue = Omit<LoopbackColoLocalActorNamespace, \"call\"> &\n ((options?: LoopbackDurableObjectClassOptions) => DurableObjectClass);\n\nexport function asLoopbackColoLocalActorNamespace(\n namespace: LoopbackColoLocalActorNamespace,\n): LoopbackColoLocalActorNamespaceValue {\n return asCallable({\n properties: namespace,\n prototype: Object.getPrototypeOf(namespace),\n call: (options) => namespace.call(requireOptions(options)),\n });\n}\n\n// =======================================================================================\n// The pinned-types check\n\n/** `Value` must be assignable to `Declared`; declaring the constraint is the check. */\ntype Assignable<Value extends Declared, Declared> = Value;\n\n/**\n * Checked rather than claimed: every value this module produces satisfies the\n * shape `@cloudflare/workers-types` 4.20260702.1 declares for it. The last two\n * are checked against `Cloudflare.Exports`' own description of a `ctx.exports`\n * entry — `LoopbackForExport<T>` intersected with the namespace — because the\n * two named interfaces there are call-signature-less, per the note above.\n */\ntype PinnedLoopbackTypes = [\n Assignable<LoopbackServiceStubValue, globalThis.LoopbackServiceStub>,\n Assignable<LoopbackDurableObjectClassValue, globalThis.LoopbackDurableObjectClass>,\n Assignable<\n LoopbackDurableObjectNamespaceValue,\n globalThis.LoopbackDurableObjectClass & globalThis.DurableObjectNamespace\n >,\n Assignable<\n LoopbackColoLocalActorNamespaceValue,\n globalThis.LoopbackDurableObjectClass & globalThis.ColoLocalActorNamespace\n >,\n];\n\n// =======================================================================================\n// The mechanics JSG supplies\n\n/**\n * ← `JSG_CALLABLE`, which makes a JSG resource object invocable while leaving\n * every other property answering from the resource type.\n *\n * `properties` is where reads land, with `this` bound to it so a method reaching\n * a private field still finds one — the same binding, memoised the same way,\n * that `asDurableObjectStub` performs for `JSG_INHERIT`. `prototype` is what\n * `instanceof` sees, and it is separate from `properties` because\n * `LoopbackServiceStub` is one object with two halves: upstream's identity is the\n * resource type while its behaviour is the inherited `Fetcher`'s.\n *\n * The target is an arrow function rather than a plain one because a plain\n * function has a non-configurable own `prototype` property, which a Proxy may not\n * hide from `ownKeys`.\n *\n * This is the one assertion the four producers above need, made once here. It is\n * `asDurableObjectStub`'s, for `asDurableObjectStub`'s reason: the declared value\n * is a `Fetcher<T>` or a `DurableObjectClass<T>` intersected with a call\n * signature, and `T` is the caller's claim about a class it named, which no value\n * can confirm. Upstream states the same shapes the same way, in a\n * `JSG_TS_OVERRIDE` that no C++ value is checked against either.\n */\nconst INVOCATION_METHODS = new Set<string | symbol>([\"call\", \"apply\", \"bind\"]);\n\nfunction asCallable<Value>(facade: {\n readonly properties: object;\n readonly prototype: object | null;\n readonly call: (options: unknown) => unknown;\n}): Value {\n const bound = new Map<string | symbol, unknown>();\n const target = (): never => {\n throw new Error(\"unreachable: the apply trap answers every invocation\");\n };\n\n return new Proxy(target, {\n apply(_target, _thisArg, args: readonly unknown[]): unknown {\n return facade.call(args[0]);\n },\n\n get(target, property, receiver): unknown {\n // `call`, `apply` and `bind` belong to the callable rather than to the property source.\n // Upstream's object is a function and answers all three from `Function.prototype`, and\n // `call` is also the C++ method name `JSG_CALLABLE` registers — which is the object's call\n // behaviour there and not a JS property, so it must not become one here. Answering from\n // the target keeps `foo.call(thisArg, options)` meaning `foo(options)`, as it does upstream.\n if (INVOCATION_METHODS.has(property)) return Reflect.get(target, property, receiver);\n\n const cached = bound.get(property);\n if (cached !== undefined) return cached;\n const value: unknown = Reflect.get(facade.properties, property, facade.properties);\n if (typeof value !== \"function\") return value;\n const method: unknown = value.bind(facade.properties);\n bound.set(property, method);\n return method;\n },\n\n has(_target, property): boolean {\n return Reflect.has(facade.properties, property);\n },\n\n ownKeys(): ArrayLike<string | symbol> {\n return Reflect.ownKeys(facade.properties);\n },\n\n getOwnPropertyDescriptor(_target, property): PropertyDescriptor | undefined {\n const descriptor = Reflect.getOwnPropertyDescriptor(facade.properties, property);\n if (descriptor === undefined) return undefined;\n // Configurable, because the target does not have this key and a Proxy may not report a\n // non-configurable descriptor for a property its target lacks.\n return { ...descriptor, configurable: true };\n },\n\n getPrototypeOf(): object | null {\n return facade.prototype;\n },\n }) as Value;\n}\n\n/**\n * ← JSG's struct unwrapper (`jsg/struct.h:236-246`), for the two option structs\n * here: every field of both is optional, so undefined and null yield an empty\n * struct and anything that is not an object is a `TypeError`. V8's `IsObject()`\n * is true for functions, which is why one is not refused here either.\n *\n * `cohort` is not checked, because upstream does not check it: JSG's `kj::String`\n * unwrapper calls `ToString` on whatever it is given (`jsg/value.h:501-506`), so\n * refusing a non-string here would refuse what workerd coerces. That is the same\n * reading `api/actor.ts`'s `actorVersionOf` already takes of the same field.\n */\nfunction requireOptions<Options extends object>(options: unknown): Options {\n if (\n options !== undefined &&\n options !== null &&\n typeof options !== \"object\" &&\n typeof options !== \"function\"\n ) {\n throw new TypeError(LOOPBACK_OPTIONS_NOT_AN_OBJECT_MESSAGE);\n }\n return (options ?? {}) as Options;\n}\n\n/** ← `jsg::Optional<jsg::JsRef<jsg::JsObject>> props` — present means an object. */\nfunction requireProps(props: unknown): unknown {\n if (props === undefined) return undefined;\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) {\n throw new TypeError(LOOPBACK_PROPS_NOT_AN_OBJECT_MESSAGE);\n }\n return props;\n}\n\n/** ← `.cohort = kj::mv(version.cohort).orDefault(kj::none)` (`export-loopback.c++:19-23`). */\nfunction versionRequestOf(\n version: LoopbackServiceStubVersion | undefined,\n): VersionRequest | undefined {\n if (version === undefined) return undefined;\n return { cohort: version.cohort ?? undefined };\n}\n","/**\n * ← workerd `src/workerd/api/sql.{h,c++}`\n *\n * `SqlStorage` and its two nested types. ~330 call sites depend on this — it is\n * the real storage layer, not KV.\n *\n * Four things about the translation, in descending order of how much they cost:\n *\n * 1. **The cursor is materialised, not live.** Upstream's `Cursor` owns a\n * running `SqliteDatabase::Query` and pulls one row at a time; the backend\n * seam this package chose (`SqlDatabase.exec` → `SqlResult`) has already\n * collected every row before a cursor exists. Everything downstream of that\n * follows: there is no statement cache, so `CachedStatement`, the 1 MiB LRU\n * and `reusedCachedQueryForTest` are absent with it; there is no live\n * statement to cancel, so `Cursor::canceled` and `selfRef` — both already\n * dead upstream, written but never assigned — have nothing to guard; and\n * `endQuery`'s job of returning a statement to the cache is nothing here, so\n * the counters it saves off are simply the counters. What is kept is every\n * observable: the position is shared across `next`/`toArray`/`one`/`raw`,\n * and a drained cursor keeps yielding done.\n * 2. **`Cursor` and `Statement` must be constructible with no arguments**, or\n * `SqlStorage` cannot satisfy workers-types without a cast: the interface\n * types them `typeof SqlStorageCursor` / `typeof SqlStorageStatement`, and\n * both are `abstract` there, so their construct signatures take none.\n * Upstream's are unconstructible from JS for the same reason they are\n * `abstract` in the types — JSG nested types have no JS constructor — so the\n * faithful shape is a constructor that refuses. `sql.Cursor` exists for\n * `instanceof`, which is all upstream exposes it for.\n * 3. **The regulator is ported whole, and that is not the whole authorizer.**\n * Four of its five members are here as callbacks, and none needed the\n * authorizer to compute anything — `isAllowedName` is a prefix test,\n * `isAllowedTrigger` is `return true`, `allowTransactions` throws,\n * `shouldAddQueryStats` is a constant. The fifth, `onError`, is not a\n * callback at all in this port: it is every `throw new Error(message)`\n * below, which is all its upstream body does with a refusal message.\n * For those, what the authorizer supplied was the *identifiers*:\n * with none, the statement text is the only source, so `exec` tokenizes it\n * and runs `isAllowedName` over every identifier-shaped token. That is\n * deliberately STRICTER than upstream — see `SQL_RESERVED_PREFIX_MESSAGE`.\n *\n * But the authorizer also makes decisions no callback ever sees, and those\n * do NOT arrive with the regulator: `SQLITE_ATTACH` / `SQLITE_DETACH`, the\n * `SQLITE_CREATE_TEMP_*` family and the `temp` schema, `SQLITE_PRAGMA`, and\n * the `SQLITE_CREATE_VTABLE` module list. Each is refused from the text in\n * `refuseUnauthorizedForms` and `requireAllowedPragmas`. `SQLITE_FUNCTION`\n * is the one still unported — see the README divergence row.\n * 4. **`ingest` stays at upstream's SQLite seam.** `SqliteDatabase.ingest()`\n * executes every complete statement and returns the partial tail, using the\n * same compiled boundaries and regulator as `exec`.\n *\n * Spec: §1.4, §2.4 in docs/decisions.md.\n */\n\nimport { requireInputLock } from \"../io/io-context\";\nimport type { IoContext } from \"../io/io-context\";\nimport type { SqlIngestResult, SqliteDatabase, SqlValue } from \"../util/sqlite\";\n\n/**\n * ← `SqlStorage::BindingValue`. JSG converts these public JavaScript values\n * to workerd's `Maybe<OneOf<Array<byte>, String, double>>` before C++ sees them;\n * `toSqlBindingValue()` is that conversion for this no-isolate runtime.\n */\nexport type BindingValue =\n | ArrayBuffer\n | ArrayBufferView\n | string\n | number\n | boolean\n | null\n | undefined;\n\n/** ← the `SqlStorageValue` `JSG_TS_DEFINE` on `Cursor`. */\nexport type SqlRow = Record<string, SqlStorageValue>;\n\n/** ← `SqlStorage::IngestResult`. */\nexport type SqlStorageIngestResult = SqlIngestResult;\n\n/**\n * ← `SqlStorageRegulator::allowTransactions()`, copied verbatim. Users match on\n * it and it is the one regulator callback our substrate can still answer.\n */\nexport const SQL_TRANSACTION_REFUSED_MESSAGE =\n \"To execute a transaction, please use the state.storage.transaction() or \" +\n \"state.storage.transactionSync() APIs instead of the SQL BEGIN TRANSACTION or SAVEPOINT \" +\n \"statements. The JavaScript API is safer because it will automatically roll back on \" +\n \"exceptions, and because it interacts correctly with Durable Objects' automatic atomic \" +\n \"write coalescing.\";\n\n/** See translation 2 in the header: the class is exposed for `instanceof` only. */\nexport const CURSOR_NOT_CONSTRUCTIBLE_MESSAGE =\n \"Illegal invocation: SqlStorage.Cursor cannot be constructed directly. Use sql.exec().\";\n\n/** Same, for the prepared-statement compatibility shim. */\nexport const STATEMENT_NOT_CONSTRUCTIBLE_MESSAGE =\n \"Illegal invocation: SqlStorage.Statement cannot be constructed directly. Use sql.prepare().\";\n\n/**\n * ← SQLite's own denial text, with the reason appended.\n *\n * There is no upstream string to copy here: `SqlStorageRegulator::onError` just\n * rethrows whatever SQLite produced, and SQLite produces `not authorized` for an\n * authorizer denial (`access to X.Y is prohibited` for the column-read case,\n * which needs a resolved identifier we do not have). The prefix is kept so that\n * anything matching upstream still matches; the rest is here because a bare\n * `not authorized` is not debuggable.\n */\nexport const SQL_RESERVED_PREFIX_MESSAGE =\n \"not authorized: a SQL statement may not name the reserved _cf_ prefix, which is where this \" +\n \"Durable Object keeps its own KV and metadata tables.\";\n\n/**\n * ← the five transaction-control forms `sqlite3_stmt_readonly()` reports\n * read-only and the authorizer reports as `SQLITE_TRANSACTION` /\n * `SQLITE_SAVEPOINT`. The same set `util/sqlite.ts` classifies, read here from\n * the leading keyword because the untrusted path has to refuse them before the\n * trusted one applies them.\n *\n * `;` counts as leading trivia here and in every other leading-keyword refusal\n * below. A statement boundary comes from the backend, and `node:sqlite` reports\n * an empty leading statement as part of the span it compiled: the `sourceSQL`\n * for `;ATTACH ...` is the whole string, so an anchor of `^\\s*` would read the\n * keyword as `;` and let the compiled ATTACH through. The browser backend cuts\n * the same input at the first `;` and refuses the empty statement instead.\n */\nconst TRANSACTION_CONTROL = /^[\\s;]*(?:BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\\b/i;\n\n/** Cheap pre-test, so the tokenizer below runs only on a statement that could fail it. */\nconst RESERVED_PREFIX_HINT = /_cf_/i;\n\n/** A SQL identifier. Double-quoted and bracketed forms are still identifiers, so only the\n * delimiters are stripped and the word inside is scanned like any other. */\nconst IDENTIFIER = /[A-Za-z_][A-Za-z0-9_$]*/g;\n\n/**\n * Everything in a statement an identifier cannot come from: single-quoted string\n * literals (SQLite escapes an embedded quote by doubling it), `--` line comments,\n * and `/* *\\/` block comments. Replaced with a space before tokenizing, so what is\n * left is code.\n *\n * Backtick-quoted names are NOT here: MySQL-compatible quoting produces an\n * identifier, exactly as the double-quoted form does.\n */\nconst NOT_CODE = /'(?:[^']|'')*'|--[^\\n]*|\\/\\*[\\s\\S]*?\\*\\//g;\n\n/**\n * Comments are never code. String literals STAY, for both of this regex's callers: pragma\n * arguments may be quoted, and SQLite's misquoting feature reads a single-quoted string as an\n * identifier — `CREATE TABLE 'temp'.t(x)` really creates a temp-schema table — so the checks\n * that read identifier positions must still see it. `NOT_CODE` blanks literals, which is right\n * for the token scans and would be a bypass for these callers.\n */\nconst NOT_COMMENT = /--[^\\n]*|\\/\\*[\\s\\S]*?\\*\\//g;\n\n/**\n * ← `SqlStorageRegulator` (`sql.h:15-22`, `sql.c++:141-165`), whole.\n *\n * Upstream reaches these through the SQLite authorizer while a statement is\n * being compiled. `exec` calls them from the statement text instead, which is\n * the same translation Section 3 made for the write classifier and for\n * transaction state.\n */\nexport const SqlStorageRegulator = {\n /**\n * Upstream's body is `return !name.startsWith(\"_cf_\")`, with an autogate that\n * makes the comparison case-insensitive and logs a warning until it lands. The\n * case-insensitive form is taken here: it is the direction upstream is moving,\n * and there is no logger for the warning half.\n */\n isAllowedName(name: string): boolean {\n return name.length < 4 || name.slice(0, 4).toLowerCase() !== \"_cf_\";\n },\n\n /** Upstream's body is `return true`. */\n isAllowedTrigger(_name: string): boolean {\n return true;\n },\n\n /** Upstream's body is a `JSG_FAIL_REQUIRE` with this message. */\n allowTransactions(): never {\n throw new Error(SQL_TRANSACTION_REFUSED_MESSAGE);\n },\n\n /** \"Bill for queries executed from JavaScript.\" Nothing reads it — `SqliteObserver` has no port. */\n shouldAddQueryStats(): boolean {\n return true;\n },\n};\n\n/**\n * The text-level stand-in for the authorizer's `isAllowedName` calls — see\n * `SQL_RESERVED_PREFIX_MESSAGE` and the README row.\n *\n * Upstream refuses a *resolved identifier* that starts with `_cf_`, because it\n * reaches `isAllowedName` through the SQLite authorizer while the statement is\n * being compiled. There is no authorizer here, so this tokenizes the statement\n * text instead, over everything that is not a string literal or a comment —\n * which is the same set of characters an identifier can come from.\n *\n * **The literals were once refused too, and that was wrong.** The first draft\n * scanned the whole statement on the reasoning that no legitimate consumer\n * statement contains the token, so being stricter than upstream was the safe\n * direction. A retained conformance case uses `_cf_keepAliveHeartbeat` as a\n * bound value: real workerd accepts it, so this parser must distinguish data\n * from identifiers. `conformance/suite/sql.spec.ts` pins the rule: refused as a\n * table name and as a quoted identifier, allowed as data.\n *\n * A name that merely CONTAINS the token — `my_cf_thing` — stays allowed, because\n * `isAllowedName` tests a prefix.\n */\nfunction requireAllowedNames(query: string): void {\n if (!RESERVED_PREFIX_HINT.test(query)) return;\n const code = query.replace(NOT_CODE, \" \");\n for (const [token] of code.matchAll(IDENTIFIER)) {\n if (!SqlStorageRegulator.isAllowedName(token)) throw new Error(SQL_RESERVED_PREFIX_MESSAGE);\n }\n}\n\n/** Refuse transaction control against one SQLite-decided statement boundary. */\nfunction refuseTransactionControl(statement: string): void {\n const code = statement.replace(NOT_CODE, \" \");\n if (TRANSACTION_CONTROL.test(code)) SqlStorageRegulator.allowTransactions();\n}\n\n/**\n * ← the message a `SQLITE_DENY` from the authorizer surfaces to JavaScript,\n * byte-identical so a caller matching on it ports unchanged.\n */\nexport const SQL_NOT_AUTHORIZED_MESSAGE = \"not authorized: SQLITE_AUTH\";\n\n/**\n * The forms neither the regulator nor any callback sees: the authorizer's own\n * action codes, plus `VACUUM`, which SQLite itself refuses by precondition.\n *\n * Porting `SqlStorageRegulator` whole (point 3 in the file header) carried over its members, but\n * not the authorizer's own action codes: `SQLITE_ATTACH`, `SQLITE_DETACH`, `SQLITE_CREATE_TEMP_*`\n * and `SQLITE_CREATE_VTABLE` consult no callback, so nothing here refused them. Every form below\n * was measured on real workerd through the conformance oracle, not inferred.\n *\n * `ATTACH` and `DETACH` are also the isolation boundary rather than a fidelity detail: both\n * backends open a real file, so on `node:sqlite` an `ATTACH` reads another actor's database and\n * a `VACUUM INTO` writes anywhere the process can. The reserved-name scan does not cover it,\n * because that scan tokenizes the SUBMITTED statement — `other._cf_KV` is caught, and every\n * application table in the same attached database is not.\n */\nconst DATABASE_ATTACHMENT = /^[\\s;]*(?:ATTACH|DETACH)\\b/i;\n\n/**\n * ← the `SQLITE_CREATE_TEMP_*` denials (`sqlite.c++:1323`) and the `dbName == temp` rule\n * (`sqlite.c++:1073`), which permits a temp-schema database name only `READ` and `UPDATE`.\n * Upstream's own reason to deny them applies here unchanged: a temporary table makes SQLite\n * open a separate temporary file that the storage engine knows nothing about.\n *\n * Two spellings, one refusal each by its own upstream path: `CREATE TEMP TABLE t(x)` is the\n * keyword and hits the action codes; `CREATE TABLE temp.t(x)` is the schema qualifier and hits\n * the `dbName` rule — and the qualifier was the live gap, where the table was created, written\n * and read back here while workerd refused it outright. The qualifier accepts every quoting\n * SQLite does, single quotes included, with or without whitespace after the keyword (measured:\n * workerd refuses `CREATE TABLE 'temp'.t(x)` and `CREATE TABLE\"temp\".t(x)` the same way), and\n * is matched only in the object-name position, so an application table merely NAMED `tempest`\n * or `temporary_log` is untouched. The keyword spelling needs no qualifier arm of its own here:\n * `TEMP_SCHEMA` already refuses every `CREATE TEMP…` before this pattern is consulted.\n *\n * The rest of the `dbName` rule goes unported on purpose: with no way to create a temp-schema\n * object, `INSERT`/`DELETE`/`DROP` against one die in SQLite as `no such table`, and the one\n * silent form measures identically — workerd allows `DROP TABLE IF EXISTS temp.ghost` too.\n */\nconst TEMP_SCHEMA = /^[\\s;]*CREATE\\s+(?:TEMP|TEMPORARY)\\b/i;\nconst TEMP_QUALIFIED =\n /^[\\s;]*CREATE\\s+(?:UNIQUE\\s+|VIRTUAL\\s+)?(?:TABLE|VIEW|TRIGGER|INDEX)\\s*(?:IF\\s+NOT\\s+EXISTS\\s*)?(?:\"temp\"|'temp'|`temp`|\\[temp\\]|temp)\\s*\\./i;\n\n/**\n * ← `SQLITE_CREATE_VTABLE` (`sqlite.c++:1298-1316`): a virtual table is native-code callbacks, so\n * upstream allows exactly four modules — FTS5 and its `fts5vocab` companion, R*Tree and its\n * `rtree_i32` variant — and denies every other module SQLite was compiled with.\n *\n * `dbstat` is why this is not only fidelity: it reports a row per table with page counts and\n * byte sizes, so `SELECT name FROM d` enumerates `_cf_KV` and the rest of the runtime's own\n * tables without the statement ever naming them — around `requireAllowedNames`, which can only\n * see the text it was given.\n *\n * The table name and the module accept every quoting SQLite does — double quotes, backticks,\n * brackets, and the misquoting feature's single-quoted string, with or without whitespace\n * before them — because the module has to be read from PAST the name, and a guessed name\n * boundary is a bypass in both directions: an unparseable name skipped the check, and\n * `\"a USING fts5 b\" USING dbstat` read its module out of the quoted name. Measured: workerd\n * refuses both, refuses `CREATE VIRTUAL TABLE\"d\"USING dbstat`, resolves `USING \"dbstat\"` to\n * the same denial, and allows `USING 'fts5'`. A `CREATE VIRTUAL TABLE` whose module the\n * pattern cannot read is refused outright — the deliberately stricter direction the\n * unparseable-PRAGMA fallback below already takes.\n */\n// The bare arm takes what SQLite's tokenizer does: alphanumerics, `_`, `$`, and any\n// character past ASCII — a table named `résumé` is legal and workerd allows it.\nconst SQL_IDENTIFIER_SOURCE =\n /\"(?:[^\"]|\"\")*\"|'(?:[^']|'')*'|`(?:[^`]|``)*`|\\[[^\\]]*\\]|[A-Za-z_\\u0080-\\uffff][A-Za-z0-9_$\\u0080-\\uffff]*/\n .source;\nconst VIRTUAL_TABLE = /^[\\s;]*CREATE\\s+VIRTUAL\\s+TABLE\\b/i;\nconst VIRTUAL_TABLE_MODULE = new RegExp(\n String.raw`^[\\s;]*CREATE\\s+VIRTUAL\\s+TABLE\\s*(?:IF\\s+NOT\\s+EXISTS\\s*)?(?:${SQL_IDENTIFIER_SOURCE})\\s*(?:\\.\\s*(?:${SQL_IDENTIFIER_SOURCE})\\s*)?USING\\s*(${SQL_IDENTIFIER_SOURCE})`,\n \"i\",\n);\nconst ALLOWED_VIRTUAL_TABLE_MODULES = new Set([\"fts5\", \"fts5vocab\", \"rtree\", \"rtree_i32\"]);\n\n/**\n * `VACUUM` has no action code of its own, so the authorizer never sees it. What refuses it\n * upstream is SQLite's own `cannot VACUUM from within a transaction` precondition, against the\n * transaction a Durable Object always has open — and that message is what the oracle returned,\n * for `VACUUM`, `VACUUM main` and `VACUUM INTO` alike. Byte-identical for the same reason\n * `SQL_NOT_AUTHORIZED_MESSAGE` is: a caller matching on it ports unchanged.\n *\n * Refused here unconditionally rather than by transaction state, which is a divergence only in\n * mechanism: this runtime never runs a statement where upstream would have allowed it.\n */\nconst VACUUM_STATEMENT = /^[\\s;]*VACUUM\\b/i;\nexport const SQL_VACUUM_REFUSED_MESSAGE = \"cannot VACUUM from within a transaction: SQLITE_ERROR\";\n\n/** Refuse the authorizer-only forms against one SQLite-decided statement boundary. */\nfunction refuseUnauthorizedForms(statement: string): void {\n const code = statement.replace(NOT_COMMENT, \" \");\n if (VACUUM_STATEMENT.test(code)) throw new Error(SQL_VACUUM_REFUSED_MESSAGE);\n if (DATABASE_ATTACHMENT.test(code) || TEMP_SCHEMA.test(code) || TEMP_QUALIFIED.test(code)) {\n throw new Error(SQL_NOT_AUTHORIZED_MESSAGE);\n }\n if (VIRTUAL_TABLE.test(code)) {\n const moduleName = VIRTUAL_TABLE_MODULE.exec(code)?.[1];\n if (\n moduleName === undefined ||\n !ALLOWED_VIRTUAL_TABLE_MODULES.has(unquoted(moduleName).toLowerCase())\n ) {\n throw new Error(SQL_NOT_AUTHORIZED_MESSAGE);\n }\n }\n}\n\n/** Cheap pre-test; `PRAGMA` and the `pragma_` functions both contain it. */\nconst PRAGMA_HINT = /pragma/i;\n\n/** `PRAGMA [schema.]name`, then `= value`, `(argument)`, or nothing. */\nconst PRAGMA_STATEMENT =\n /^[\\s;]*PRAGMA\\s+(?:[A-Za-z_][A-Za-z0-9_$]*\\s*\\.\\s*)?([A-Za-z_][A-Za-z0-9_$]*)(?:\\s*=\\s*([\\s\\S]+?)|\\s*\\(\\s*([\\s\\S]*?)\\s*\\))?\\s*;?\\s*$/i;\n\n/**\n * ← `ALLOWED_PRAGMAS` (`util/sqlite.c++:543-571`) and `PragmaSignature` (`:528-535`),\n * verbatim. `table_list`, `table_info`, and `table_xinfo` are special-cased\n * ahead of the table in the authorizer, exactly as upstream's `SQLITE_PRAGMA`\n * case does (`util/sqlite.c++:1194-1273`).\n */\nconst ALLOWED_PRAGMAS = new Map<\n string,\n \"NO_ARG\" | \"BOOLEAN\" | \"OBJECT_NAME\" | \"OPTIONAL_OBJECT_NAME\" | \"NULL_OR_NUMBER\" | \"NULL_NUMBER_OR_OBJECT_NAME\"\n>([\n [\"data_version\", \"NO_ARG\"],\n // Upstream's own comment: \"The R*Tree module issues `PRAGMA page_size` (with no argument)\n // internally to read the current page size. `PRAGMA page_size=N`, which would attempt to\n // change the page size, is still rejected.\" `NO_ARG` is what rejects the assignment.\n [\"page_size\", \"NO_ARG\"],\n [\"case_sensitive_like\", \"BOOLEAN\"],\n [\"foreign_keys\", \"BOOLEAN\"],\n [\"defer_foreign_keys\", \"BOOLEAN\"],\n [\"ignore_check_constraints\", \"BOOLEAN\"],\n [\"legacy_alter_table\", \"BOOLEAN\"],\n [\"recursive_triggers\", \"BOOLEAN\"],\n [\"reverse_unordered_selects\", \"BOOLEAN\"],\n [\"foreign_key_check\", \"OPTIONAL_OBJECT_NAME\"],\n [\"foreign_key_list\", \"OBJECT_NAME\"],\n [\"index_info\", \"OBJECT_NAME\"],\n [\"index_list\", \"OBJECT_NAME\"],\n [\"index_xinfo\", \"OBJECT_NAME\"],\n [\"quick_check\", \"NULL_NUMBER_OR_OBJECT_NAME\"],\n [\"optimize\", \"NULL_OR_NUMBER\"],\n]);\n\n/** Upstream compares the eight literal forms as PREFIXES, case-insensitively. */\nconst BOOLEAN_PRAGMA_VALUE = /^(?:true|false|yes|no|on|off|1|0)/i;\n\n/**\n * The pragmas SQLite ships (https://www.sqlite.org/pragma.html), so a\n * `pragma_X` identifier can be told apart: `X` here means the table-valued\n * pragma function and follows the allowlist; any other `pragma_`-prefixed\n * identifier is an ordinary application name, which upstream's authorizer\n * distinguishes by resolution and the conformance suite pins.\n */\nconst SQLITE_PRAGMA_NAMES = new Set([\n \"analysis_limit\", \"application_id\", \"auto_vacuum\", \"automatic_index\",\n \"busy_timeout\", \"cache_size\", \"cache_spill\", \"case_sensitive_like\",\n \"cell_size_check\", \"checkpoint_fullfsync\", \"collation_list\",\n \"compile_options\", \"data_version\", \"database_list\", \"defer_foreign_keys\",\n \"encoding\", \"foreign_key_check\", \"foreign_key_list\", \"foreign_keys\",\n \"freelist_count\", \"full_column_names\", \"fullfsync\", \"function_list\",\n \"hard_heap_limit\", \"ignore_check_constraints\", \"incremental_vacuum\",\n \"index_info\", \"index_list\", \"index_xinfo\", \"integrity_check\",\n \"journal_mode\", \"journal_size_limit\", \"legacy_alter_table\",\n \"legacy_file_format\", \"locking_mode\", \"max_page_count\", \"mmap_size\",\n \"module_list\", \"optimize\", \"page_count\", \"page_size\", \"pragma_list\",\n \"query_only\", \"quick_check\", \"read_uncommitted\", \"recursive_triggers\",\n \"reverse_unordered_selects\", \"schema_version\", \"secure_delete\",\n \"short_column_names\", \"shrink_memory\", \"soft_heap_limit\", \"synchronous\",\n \"table_info\", \"table_list\", \"table_xinfo\", \"temp_store\", \"threads\",\n \"trusted_schema\", \"user_version\", \"wal_autocheckpoint\", \"wal_checkpoint\",\n \"writable_schema\",\n]);\n\n/** kj's `tryParseAs` is decimal; keep the same acceptance. */\nconst DECIMAL = /^[+-]?\\d+$/;\n\n/**\n * One layer of SQL quoting, any of the four forms — a pragma argument, or the module token\n * `VIRTUAL_TABLE_MODULE` captured. Doubled inner quotes stay doubled, which cannot change a\n * verdict here: no allowlisted comparison target contains a quote character.\n */\nfunction unquoted(argument: string): string {\n const first = argument[0];\n const last = argument[argument.length - 1];\n if (argument.length >= 2) {\n if ((first === \"'\" || first === '\"' || first === \"`\") && last === first) {\n return argument.slice(1, -1);\n }\n if (first === \"[\" && last === \"]\") return argument.slice(1, -1);\n }\n return argument;\n}\n\n/** ← the `SQLITE_PRAGMA` authorizer case (`util/sqlite.c++:1194-1273`), whole. */\nfunction isAllowedPragma(name: string, argument: string | undefined): boolean {\n const pragma = name.toLowerCase();\n if (pragma === \"table_list\") return true;\n if (pragma === \"table_info\" || pragma === \"table_xinfo\") {\n // \"Allow if the specific named table is not protected.\"\n if (argument === undefined) return false;\n return SqlStorageRegulator.isAllowedName(unquoted(argument));\n }\n const signature = ALLOWED_PRAGMAS.get(pragma);\n if (signature === undefined) return false;\n switch (signature) {\n case \"NO_ARG\":\n return argument === undefined;\n case \"BOOLEAN\":\n // \"We allow omitting the argument in order to read back the current value.\"\n return argument === undefined || BOOLEAN_PRAGMA_VALUE.test(unquoted(argument));\n case \"OBJECT_NAME\":\n return argument !== undefined && SqlStorageRegulator.isAllowedName(unquoted(argument));\n case \"OPTIONAL_OBJECT_NAME\":\n return argument === undefined || SqlStorageRegulator.isAllowedName(unquoted(argument));\n case \"NULL_OR_NUMBER\":\n return argument === undefined || DECIMAL.test(argument);\n case \"NULL_NUMBER_OR_OBJECT_NAME\":\n return (\n argument === undefined ||\n DECIMAL.test(argument) ||\n SqlStorageRegulator.isAllowedName(unquoted(argument))\n );\n }\n}\n\n/**\n * The text-level stand-in for the authorizer's `SQLITE_PRAGMA` case, against\n * one SQLite-decided statement boundary. Load-bearing beyond fidelity:\n * `user_version` is where runtime storage versioning keeps its per-file stamp\n * (`util/sqlite-migrations.ts`), and `writable_schema` would let application\n * SQL rewrite `sqlite_master` out from under the `_cf_` reservation.\n *\n * The `pragma_` table-valued functions reach the same authorizer path\n * upstream, so they follow the same allowlist here — by pragma NAME only. An\n * argument the text cannot see (a string literal or a binding) goes unchecked\n * where upstream's authorizer sees the resolved value; a `_cf_` name smuggled\n * that way reads schema whose shape is public source anyway, while identifier\n * arguments stay covered by `requireAllowedNames`. The README divergence row\n * records this.\n */\nfunction requireAllowedPragmas(statement: string): void {\n if (!PRAGMA_HINT.test(statement)) return;\n const code = statement.replace(NOT_COMMENT, \" \");\n const direct = code.match(PRAGMA_STATEMENT);\n if (direct !== null) {\n const [, name = \"\", assigned, called] = direct;\n const argument = (assigned ?? called)?.trim();\n if (!isAllowedPragma(name, argument === \"\" ? undefined : argument)) {\n throw new Error(SQL_NOT_AUTHORIZED_MESSAGE);\n }\n return;\n }\n // A statement that leads with PRAGMA but does not parse as one is refused —\n // the deliberately stricter direction the reserved-name check already takes.\n if (/^[\\s;]*PRAGMA\\b/i.test(code)) throw new Error(SQL_NOT_AUTHORIZED_MESSAGE);\n const literalFree = code.replace(NOT_CODE, \" \");\n for (const [token] of literalFree.matchAll(IDENTIFIER)) {\n if (token.length <= 7 || token.slice(0, 7).toLowerCase() !== \"pragma_\") continue;\n const name = token.slice(7).toLowerCase();\n if (!SQLITE_PRAGMA_NAMES.has(name)) continue;\n if (\n name !== \"table_list\" &&\n name !== \"table_info\" &&\n name !== \"table_xinfo\" &&\n !ALLOWED_PRAGMAS.has(name)\n ) {\n throw new Error(SQL_NOT_AUTHORIZED_MESSAGE);\n }\n }\n}\n\n/** Everything the untrusted path refuses at one statement boundary. */\nfunction regulateUntrustedStatement(statement: string): void {\n refuseTransactionControl(statement);\n refuseUnauthorizedForms(statement);\n requireAllowedPragmas(statement);\n}\n\n/**\n * ← the `jsg::Ref<DurableObjectStorage>` `SqlStorage` holds, narrowed to the one\n * member it reaches through (`SqlStorage::getDb`). `DurableObjectStorage`\n * satisfies it; narrowing is what keeps this file free of a value-level import\n * cycle, which upstream tolerates because C++ headers do not have one.\n */\nexport interface SqlStorageOwner {\n /** ← `DurableObjectStorage::getSqliteDb`. Throws if not SQLite-backed. */\n getSqliteDb(): SqliteDatabase;\n}\n\n/** The rows a cursor walks, plus the counters that outlive them. */\ntype CursorState = {\n readonly columnNames: string[];\n readonly rawRows: readonly (readonly SqlStorageValue[])[];\n readonly rowsWritten: number;\n};\n\n/** ← `JSG_INHERIT_INTRINSIC(v8::kIteratorPrototype)` (`jsg/iterator.h:1044`). */\nconst IteratorPrototype: object = Object.getPrototypeOf(\n Object.getPrototypeOf([][Symbol.iterator]()),\n) as object;\n\n/**\n * ← the `JSG_ITERATOR` types (`jsg/iterator.h:1036-1050`): `next` and\n * self-iterability on `%IteratorPrototype%` — which is what carries the ES\n * iterator helpers; `raw().toArray()` is what Drizzle's durable-sqlite driver\n * calls — and NOTHING else. No `return`, no `throw` (only the async variant\n * registers `return_`, `:1069-1085`), so `IteratorClose` after a `break`, a\n * partial destructuring, or a `take()` is a no-op and a retained iterator\n * resumes. Results are `JSG_STRUCT(done, value)` in that key order\n * (`jsg/iterator.h:706-710`).\n */\nclass RawIterator<U extends SqlStorageValue[]> implements IterableIterator<U> {\n readonly #pull: () => readonly SqlStorageValue[] | undefined;\n\n constructor(pull: () => readonly SqlStorageValue[] | undefined) {\n this.#pull = pull;\n }\n\n next(): { done: false; value: U } | { done: true; value: undefined } {\n const raw = this.#pull();\n if (raw === undefined) return { done: true, value: undefined };\n return { done: false, value: asRawRow<U>([...raw]) };\n }\n\n [Symbol.iterator](): IterableIterator<U> {\n return this;\n }\n}\nObject.setPrototypeOf(RawIterator.prototype, IteratorPrototype);\nObject.defineProperty(RawIterator.prototype, Symbol.toStringTag, {\n value: \"RawIterator\",\n configurable: true,\n});\n\n/** ← `RowIterator`, shaped exactly as `RawIterator` above. */\nclass RowIterator<T extends SqlRow> implements IterableIterator<T> {\n readonly #pull: () => T | undefined;\n\n constructor(pull: () => T | undefined) {\n this.#pull = pull;\n }\n\n next(): { done: false; value: T } | { done: true; value: undefined } {\n const row = this.#pull();\n if (row === undefined) return { done: true, value: undefined };\n return { done: false, value: row };\n }\n\n [Symbol.iterator](): IterableIterator<T> {\n return this;\n }\n}\nObject.setPrototypeOf(RowIterator.prototype, IteratorPrototype);\nObject.defineProperty(RowIterator.prototype, Symbol.toStringTag, {\n value: \"RowIterator\",\n configurable: true,\n});\n\n/**\n * ← `SqlStorage::Cursor`.\n *\n * `rowsRead` is the one counter that is not upstream's. Upstream reads\n * `Query::getRowsRead()`, a billing counter sourced from libsql's\n * `STMTSTATUS_ROWS_READ` that counts index rows and that neither backend\n * exposes — the same absence the README already records for `SqlResult`. The\n * interface requires a number, so this returns the rows the cursor has yielded,\n * which is what today's browser host returns and what its tests assert. It\n * undercounts any query that scans more rows than it returns.\n */\nexport class Cursor<T extends SqlRow = SqlRow> implements SqlStorageCursor<T> {\n readonly #columnNames: string[];\n readonly #rawRows: readonly (readonly SqlStorageValue[])[];\n readonly #rowsWritten: number;\n #position = 0;\n\n constructor(state?: CursorState) {\n if (state === undefined) throw new Error(CURSOR_NOT_CONSTRUCTIBLE_MESSAGE);\n this.#columnNames = state.columnNames;\n this.#rawRows = state.rawRows;\n this.#rowsWritten = state.rowsWritten;\n }\n\n /**\n * ← `JSG_READONLY_PROTOTYPE_PROPERTY(columnNames)` (`sql.h:210`): a\n * prototype accessor, not an own field, so a cursor JSON-stringifies to `{}`.\n */\n get columnNames(): string[] {\n return this.#columnNames;\n }\n\n /** ← `Cursor::next`, whose `RowIterator::Next` is this exact shape. */\n next(): { done?: false; value: T } | { done: true; value?: never } {\n const row = this.#nextRow();\n if (row === undefined) {\n // ← `JSG_STRUCT(done, value)` serializes an OWN `value: undefined` on\n // the done result; the published type says the key is absent. Callers\n // observe the runtime shape, so it wins — on workerd exactly the same.\n return { done: true, value: undefined } as unknown as { done: true; value?: never };\n }\n return { done: false, value: row };\n }\n\n /** ← `Cursor::toArray`, which drains from the current position. */\n toArray(): T[] {\n const rows: T[] = [];\n for (;;) {\n const row = this.#nextRow();\n if (row === undefined) return rows;\n rows.push(row);\n }\n }\n\n /** ← `Cursor::one`. Both messages are upstream's, verbatim. */\n one(): T {\n const row = this.#nextRow();\n if (row === undefined) {\n throw new Error(\"Expected exactly one result from SQL query, but got no results.\");\n }\n if (this.#position < this.#rawRows.length) {\n // Upstream drops the query here before throwing, so the statement cannot be reused.\n this.#position = this.#rawRows.length;\n throw new Error(\"Expected exactly one result from SQL query, but got multiple results.\");\n }\n return row;\n }\n\n /**\n * ← `Cursor::raw`, which shares this cursor's position rather than\n * restarting. The iterator's shape is `RawIterator`'s whole doc comment.\n */\n raw<U extends SqlStorageValue[]>(): IterableIterator<U> {\n return new RawIterator<U>(() => this.#nextRaw());\n }\n\n /** ← `JSG_ITERABLE(rows)`, yielding through the same shared position. */\n [Symbol.iterator](): IterableIterator<T> {\n return new RowIterator<T>(() => this.#nextRow());\n }\n\n get rowsRead(): number {\n return this.#position;\n }\n\n /** ← `Cursor::getRowsWritten`, which is `SqlResult.rowsWritten` here. */\n get rowsWritten(): number {\n return this.#rowsWritten;\n }\n\n #nextRaw(): readonly SqlStorageValue[] | undefined {\n const raw = this.#rawRows[this.#position];\n if (raw === undefined) return undefined;\n this.#position += 1;\n return raw;\n }\n\n /** ← `Cursor::rowIteratorNext`: zip the column names onto the row. */\n #nextRow(): T | undefined {\n const raw = this.#nextRaw();\n if (raw === undefined) return undefined;\n const row: SqlRow = {};\n this.#columnNames.forEach((name, index) => {\n row[name] = raw[index] ?? null;\n });\n return asRow<T>(row);\n }\n}\n/** ← the jsg resource-type tag every workerd API object carries (`resource.h`). */\nObject.defineProperty(Cursor.prototype, Symbol.toStringTag, {\n value: \"Cursor\",\n configurable: true,\n});\n\n/**\n * ← `SqlStorage::Statement`, which upstream describes as \"supported only for\n * backwards compatibility ... it is actually just a wrapper around `exec()`\".\n * `JSG_CALLABLE(run)` makes the object itself callable, so `prepare()` returns a\n * function wearing this prototype rather than an object with a `run` method.\n */\nexport class Statement {\n constructor() {\n throw new Error(STATEMENT_NOT_CONSTRUCTIBLE_MESSAGE);\n }\n}\n\n/** What `prepare()` hands back: `Statement::run`, reachable by calling it. */\nexport interface PreparedStatement {\n <T extends SqlRow = SqlRow>(...bindings: BindingValue[]): Cursor<T>;\n}\n\nexport class SqlStorage implements globalThis.SqlStorage {\n readonly #ctx: IoContext;\n readonly #owner: SqlStorageOwner;\n /** ← `kj::Maybe<uint> pageSize`, memoized for the same reason. */\n #pageSize: number | undefined;\n\n constructor(ctx: IoContext, owner: SqlStorageOwner) {\n this.#ctx = ctx;\n this.#owner = owner;\n }\n\n /** ← `JSG_NESTED_TYPE(Cursor)`. Exposed so `instanceof` works, as upstream's is. */\n readonly Cursor = Cursor;\n /** ← `JSG_NESTED_TYPE(Statement)`. */\n readonly Statement = Statement;\n\n exec<T extends SqlRow = SqlRow>(query: string, ...bindings: BindingValue[]): Cursor<T> {\n requireInputLock(this.#ctx, \"sql.exec()\");\n const db = this.#owner.getSqliteDb();\n const sqlBindings = bindings.map(toSqlBindingValue);\n\n // Name checks stay a preflight because the backend cannot return a compiled\n // statement for a missing reserved table. This text-level check is the\n // deliberately stricter authorizer substitute documented above.\n requireAllowedNames(query);\n\n // The backend supplies the same statement boundary SQLite compiled. That is\n // load-bearing for CREATE TRIGGER, whose body legitimately contains semicolons.\n const result = db.run({ regulate: regulateUntrustedStatement }, query, ...sqlBindings);\n return new Cursor<T>({\n columnNames: [...result.columnNames],\n rawRows: result.rawRows.map((row) => row.map(toSqlStorageValue)),\n rowsWritten: result.rowsWritten,\n });\n }\n\n /**\n * ← `SqlStorage::getDatabaseSize`.\n *\n * Upstream's second query is `PRAGMA page_size;`, which `sqlite3_stmt_readonly()`\n * reports read-only. With no such call the text is the only source and §1.7.1's\n * rule is write-unless-provably-a-read, so a bare `PRAGMA` would open a\n * transaction and take an output-gate lock to answer a size question. The\n * `pragma_page_size` table-valued function is the same value read through the\n * `SELECT` upstream already uses for the page count.\n */\n get databaseSize(): number {\n requireInputLock(this.#ctx, \"sql.databaseSize\");\n const db = this.#owner.getSqliteDb();\n const pages = db.run(\n \"select (select * from pragma_page_count) - (select * from pragma_freelist_count);\",\n );\n return readNumber(pages, \"page count\") * this.#getPageSize(db);\n }\n\n /** ← `SqlStorage::prepare`. Experimental and deprecated upstream; `exec` caches for you. */\n prepare(query: string): PreparedStatement {\n requireInputLock(this.#ctx, \"sql.prepare()\");\n const run = <T extends SqlRow = SqlRow>(...bindings: BindingValue[]): Cursor<T> =>\n this.exec<T>(query, ...bindings);\n Object.setPrototypeOf(run, Statement.prototype);\n return run;\n }\n\n /** ← `SqlStorage::ingest`. */\n ingest(query: string): SqlStorageIngestResult {\n requireInputLock(this.#ctx, \"sql.ingest()\");\n requireAllowedNames(query);\n return this.#owner.getSqliteDb().ingest(query, regulateUntrustedStatement);\n }\n\n /** ← `SqlStorage::setMaxPageCountForTest`, which is what its name says. */\n setMaxPageCountForTest(count: number): void {\n requireInputLock(this.#ctx, \"sql.setMaxPageCountForTest()\");\n this.#owner.getSqliteDb().run(`PRAGMA max_page_count = ${count}`);\n }\n\n /** ← `SqlStorage::getPageSize`. */\n #getPageSize(db: SqliteDatabase): number {\n const cached = this.#pageSize;\n if (cached !== undefined) return cached;\n const size = readNumber(db.run(\"select * from pragma_page_size;\"), \"page size\");\n this.#pageSize = size;\n return size;\n }\n}\n\nfunction readNumber(result: { readonly rawRows: readonly (readonly unknown[])[] }, what: string): number {\n const value = result.rawRows[0]?.[0];\n if (typeof value === \"number\") return value;\n if (typeof value === \"bigint\") return Number(value);\n throw new Error(`Expected a number for the database's ${what}.`);\n}\n\n/** ← JSG's conversion from JavaScript arguments to `SqlStorage::BindingValue`. */\nfunction toSqlBindingValue(value: unknown): SqlValue {\n if (value === null || value === undefined) return null;\n if (typeof value === \"string\" || typeof value === \"number\") return value;\n if (typeof value === \"boolean\") return String(value);\n if (typeof value === \"bigint\") {\n throw new TypeError(\"Cannot convert a BigInt value to a number\");\n }\n if (value instanceof ArrayBuffer) return copyBytes(new Uint8Array(value));\n if (ArrayBuffer.isView(value)) {\n return copyBytes(new Uint8Array(value.buffer, value.byteOffset, value.byteLength));\n }\n throw new TypeError(`Cannot convert ${Object.prototype.toString.call(value)} to a SQL value`);\n}\n\nfunction copyBytes(bytes: Uint8Array): Uint8Array {\n const copy = new Uint8Array(bytes.byteLength);\n copy.set(bytes);\n return copy;\n}\n\n/**\n * ← `SqlStorage::wrapSqlValue` plus the `Query::getValue` switch above it.\n *\n * Upstream's int64 arm carries its own comment: \"int64 will become BigInt, but\n * most applications won't want all their integers to be BigInt. We will coerce\n * to a double here.\" That coercion is kept rather than refused, because it is\n * the documented behaviour of `sql.exec` and a caller storing an id larger than\n * 2^53 has already lost on workerd.\n */\nfunction toSqlStorageValue(value: unknown): SqlStorageValue {\n if (value === null || value === undefined) return null;\n if (typeof value === \"string\" || typeof value === \"number\") return value;\n if (typeof value === \"bigint\") return Number(value);\n if (typeof value === \"boolean\") return value ? 1 : 0;\n if (value instanceof Uint8Array) {\n const copy = new ArrayBuffer(value.byteLength);\n new Uint8Array(copy).set(value);\n return copy;\n }\n throw new Error(`SQL returned a ${typeof value}, which is not a SqlStorageValue.`);\n}\n\n/**\n * The two narrowings a generic row type needs. `T` is the caller's claim about\n * the shape of a row SQLite produced at runtime, so no check can confirm it and\n * upstream does not try — its `Cursor<T>` is the same claim written in a\n * `JSG_TS_OVERRIDE`. Confined to these two functions so the claim is one place\n * rather than sprinkled through the cursor.\n */\nfunction asRow<T extends SqlRow>(row: SqlRow): T {\n return row as T;\n}\n\nfunction asRawRow<U extends SqlStorageValue[]>(values: SqlStorageValue[]): U {\n return values as U;\n}\n","/**\n * ← workerd `src/workerd/api/actor-state.{h,c++}`\n *\n * The JS-facing storage objects: `DurableObjectStorageOperations` and its two\n * subclasses, `DurableObjectFacets`, and `DurableObjectState`. Everything below\n * this file is reached through one of them.\n *\n * **`DurableObjectStorage` satisfies workers-types with no cast (§2.4).** That\n * was checked rather than asserted, and two shapes here exist only because it\n * has to: `sql.Cursor` and `sql.Statement` must be constructible with no\n * arguments (see `sql.ts`), and `storage.kv` is required. The narrowings that\n * remain are all one thing —\n * `get<T>` returns the caller's claim about the shape of a value SQLite handed\n * back as bytes, which no check can confirm and which upstream states the same\n * way, as a `jsg::JsRef<jsg::JsValue>` behind a `JSG_TS_OVERRIDE`'d\n * `Promise<T>`. There is no `as unknown as` anywhere in this layer.\n *\n * **Every throw is synchronous, including from the promise-returning methods.**\n * That is upstream's: a `JSG_REQUIRE` inside a method returning `jsg::Promise`\n * throws into the isolate before the promise exists, so `put(k, undefined)`\n * throws rather than rejecting. The same goes for a value that will not decode,\n * because §1.4 makes the SQLite path run the decoder before `Promise.resolve`.\n *\n * **What the input gate does and does not do here.** Every entry point calls\n * `requireInputLock` — see its comment in `io/io-context.ts`, which is the one\n * place this package decides what an empty invocation stack means. Nothing else\n * takes a lock: a read returns a value, a write returns a resolved promise, and\n * `atCheckpointEnd` is what keeps the whole chain inside one transaction\n * (§1.7.1). The two exceptions are upstream's own — `sync()` and the bookmark\n * pair release the gate via `awaitIo`, and `transaction()` takes a critical\n * section.\n *\n * **Decision 2's branch has one reachable site**, and it is not where upstream's\n * is. §1.4 measures that SQLite cache operations are immediate, so their\n * `kj::OneOf<T, kj::Promise<T>>` branch has nothing to select between.\n * `transformMaybeBackpressure` keeps the branch because\n * `DeleteAllResults.backpressure` is still a promise in `io/actor-cache.ts`.\n *\n * Not ported, because the substrate has no equivalent: V8's private wire bytes,\n * replaced by a browser-safe structured-clone encoding with the same public\n * value semantics; the billing counters\n * (`billingUnits`, `ActorObserver`, `updateStorageWriteUnit`) and the trace\n * spans, both already absent throughout; `enableSql`, a workerd namespace option\n * that exists to simulate a non-SQLite Durable Object; and `ReplicaActorOutgoingFactory`,\n * whose replication half is a named boundary in `io/actor-cache.ts`.\n *\n * Spec: §1.4, §1.5, §1.10, §2.4, §2.5, decisions 2, 4 and 14 in\n * docs/decisions.md.\n */\n\nimport {\n deserialize as deserializeStructuredClone,\n serialize as serializeStructuredClone,\n} from \"@ungap/structured-clone\";\nimport type {\n ActorCacheInterface,\n ActorCacheOps,\n ActorCacheTransaction,\n GetResultList,\n ReadOptions,\n WriteOptions,\n} from \"../io/actor-cache\";\nimport type { IoContext } from \"../io/io-context\";\nimport { requireInputLock, setUserErrorDetail } from \"../io/io-context\";\nimport type { FacetManager, FacetStartInfo } from \"../io/worker\";\nimport type { SqliteKv, SqliteKvListCursor } from \"../util/sqlite-kv\";\nimport type { SqliteDatabase } from \"../util/sqlite\";\nimport { DurableObjectClass } from \"./actor\";\nimport { LoopbackColoLocalActorNamespace, LoopbackDurableObjectNamespace } from \"./export-loopback\";\nimport type { ActorScopeBindings } from \"./global-scope\";\nimport { SqlStorage } from \"./sql\";\nimport type { HibernatableWebSocketRegistry } from \"./web-socket\";\n\n// =======================================================================================\n// Constants\n\n/**\n * ← `MAX_FACET_NAME_LENGTH` / `MAX_FACET_TREE_DEPTH`\n * (`actor-state.c++:943,947`), in the anonymous namespace beside the facet code\n * that enforces them. The scaffolding had them in `server/`, which is neither\n * where upstream puts them nor where they are checked.\n */\nexport const FACET_NAME_MAX_LENGTH = 256;\n/** Root is at depth 0, so the deepest allowed facet is at depth 3. */\nexport const FACET_TREE_MAX_DEPTH = 4;\n\n/**\n * ← what falls off the end of `DurableObjectFacets::get`'s class switch\n * (`actor-state.c++:1029-1043`).\n *\n * Upstream accepts three things as `FacetStartupOptions.class`: a bare\n * `DurableObjectClass`, a `LoopbackDurableObjectNamespace`, or a\n * `LoopbackColoLocalActorNamespace`, unwrapping the last two through\n * `getClass()`. All three are ported — the loopback pair by\n * `api/export-loopback.ts` — and `KJ_UNREACHABLE` is the fourth case there\n * because JSG has already refused anything else while unwrapping the\n * `kj::OneOf`. The check has to be written here because\n * `@cloudflare/workers-types` declares `interface DurableObjectClass<_T> {}`,\n * which every object satisfies, so nothing refuses it before the method body.\n */\nexport const FACET_CLASS_UNSUPPORTED_MESSAGE =\n \"facets.get() was given a class this runtime cannot resolve. `class` must be a \" +\n \"DurableObjectClass, a LoopbackDurableObjectNamespace or a LoopbackColoLocalActorNamespace — \" +\n \"which is what a ctx.exports entry for a Durable Object class is.\";\n\n/** ← `DurableObjectStorageOperations::OpName`. Named only where an error quotes them. */\nconst OP_GET = \"get()\";\nconst OP_GET_ALARM = \"getAlarm()\";\nconst OP_LIST = \"list()\";\nconst OP_PUT = \"put()\";\nconst OP_PUT_ALARM = \"setAlarm()\";\nconst OP_DELETE = \"delete()\";\nconst OP_DELETE_ALARM = \"deleteAlarm()\";\nconst OP_ROLLBACK = \"rollback()\";\n\n/** ← `actor-state.c++:455`, verbatim: the one message both overloads' misuse produces. */\nconst PUT_OVERLOAD_MESSAGE =\n \"put() may only be called with a single key-value pair and optional options as \" +\n \"put(key, value, options) or with multiple key-value pairs and optional options as \" +\n \"put(entries, options)\";\n\n/**\n * ← the `kj::OneOf<kj::String, jsg::Dict<…>>` unwrap on put()'s first parameter: `jsg::Dict`\n * takes any JS object except an Array — functions and Maps included — and `kj::String` takes\n * everything else by coercion. A type predicate, so the overload split narrows without a cast.\n */\nfunction isEntriesArgument<T>(value: string | Record<string, T>): value is Record<string, T> {\n return (\n (typeof value === \"object\" || typeof value === \"function\") &&\n value !== null &&\n !Array.isArray(value)\n );\n}\n\n/**\n * ← the struct wrapper (`jsg/struct.h:246-258`), which is NOT the Dict wrapper: `PutOptions` is\n * all-optional fields, so `null` unwraps to default options, and any object does — arrays and\n * functions included, because the wrapper checks `IsObject()` with no Array exclusion. Only a\n * non-null primitive fails to unwrap. Measured on real workerd: `put({k: 1}, null)`, `…, [])`\n * and `…, function () {})` all write, and `put({k: 1}, \"v\")` alone is the overload error.\n */\nfunction isPutOptions(value: unknown): boolean {\n return value === null || typeof value === \"object\" || typeof value === \"function\";\n}\n\n/** The key immediately after `k` in byte order is `k` plus this. */\nconst NULL_CHARACTER = \"\\u0000\";\n/** ← the `0xff` upstream strips from the tail of a prefix, in UTF-16 code units. */\nconst MAX_CODE_UNIT = 0xffff;\n\n// =======================================================================================\n// The value codec\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n/** A byte JSON could never begin with, `DO`, and the local codec version. */\nconst VALUE_CODEC_HEADER = new Uint8Array([0, 0x44, 0x4f, 1]);\n\n/**\n * ← `serializeV8Value`. The wire bytes differ because V8's serializer is not\n * available in browsers; the public structured-clone value semantics do not.\n * The short header keeps the new representation unambiguous while old JSON rows\n * remain readable.\n */\nexport function serializeValue(value: unknown): Uint8Array {\n const body = textEncoder.encode(JSON.stringify(serializeStructuredClone(value)));\n const encoded = new Uint8Array(VALUE_CODEC_HEADER.byteLength + body.byteLength);\n encoded.set(VALUE_CODEC_HEADER);\n encoded.set(body, VALUE_CODEC_HEADER.byteLength);\n return encoded;\n}\n\n/**\n * ← `deserializeV8Value`.\n *\n * Upstream logs \"the key (to help find the data in the database if it hasn't\n * been deleted), the length of the value, and the first three bytes of the value\n * (which is just the v8-internal version header and the tag that indicates the\n * type of the value, but not its contents)\". Our four-byte header carries only\n * a marker and version for the same reason.\n */\nexport function deserializeValue<T = unknown>(key: string, buffer: Uint8Array): T {\n if (buffer.byteLength === 0) {\n throw new Error(`unexpectedly empty value buffer; key = ${key}`);\n }\n try {\n const structured = VALUE_CODEC_HEADER.every((byte, index) => buffer[index] === byte);\n const bytes = structured ? buffer.subarray(VALUE_CODEC_HEADER.byteLength) : buffer;\n const parsed = JSON.parse(textDecoder.decode(bytes)) as unknown;\n const value = structured\n ? deserializeStructuredClone(parsed as ReturnType<typeof serializeStructuredClone>)\n : parsed;\n return value as T;\n } catch (exception) {\n throw new Error(\n \"actor storage deserialization failed: failed to deserialize stored value; \" +\n `key = ${key}; size = ${buffer.byteLength}`,\n { cause: exception },\n );\n }\n}\n\n// =======================================================================================\n// The option transforms\n\n/**\n * ← `transformMaybeBackpressure` (`actor-state.c++:103-119`). THIS is decision\n * 2's live site: `DeleteAllResults.backpressure` is still `Promise<void> |\n * undefined`, so the branch has something to select between.\n *\n * Upstream's own note, kept because it is the reason the flag is threaded here\n * at all: \"In practice `allowConcurrency` will have no effect on a backpressure\n * promise since backpressure blocks everything anyway, but we pass the option\n * through for consistency in case of future changes.\"\n */\nfunction transformMaybeBackpressure(\n ctx: IoContext,\n options: { readonly allowConcurrency?: boolean },\n maybeBackpressure: Promise<void> | undefined,\n): Promise<void> {\n if (maybeBackpressure === undefined) return Promise.resolve();\n if (options.allowConcurrency === true) return ctx.awaitIo(maybeBackpressure);\n return ctx.awaitIoWithInputLock(maybeBackpressure, () => {});\n}\n\n// =======================================================================================\n// compileListOptions\n\n/** ← `DurableObjectStorageOperations::CompiledListOptions`. */\ntype CompiledListOptions = {\n readonly start: string;\n readonly end: string | undefined;\n readonly reverse: boolean;\n readonly limit: number | undefined;\n};\n\n/**\n * ← `DurableObjectStorageOperations::compileListOptions`\n * (`actor-state.c++:314-417`). Returns undefined if the list operation would\n * provably return no results. `SyncKvStorage` reuses it, exactly as upstream's\n * comment says it must.\n *\n * Two translations. `startAfter` gains ONE null character where upstream's\n * `kj::String` gains two, because the second of upstream's is the terminator and\n * a JS string has none. And every comparison here is on UTF-16 code units where\n * upstream's is on UTF-8 bytes, while the range the database actually applies is\n * SQLite's `BINARY` collation over UTF-8 — the two orders agree for every key\n * outside the astral planes, and a key that mixes astral characters with a\n * prefix can land on the wrong side of a clamp this function computes.\n */\nfunction compileListOptions(\n options: DurableObjectListOptions | undefined,\n): CompiledListOptions | undefined {\n let start = \"\";\n let end: string | undefined;\n let reverse = false;\n let limit: number | undefined;\n\n if (options !== undefined) {\n if (options.start !== undefined) {\n if (options.startAfter !== undefined) {\n throw new TypeError(\"list() cannot be called with both start and startAfter values.\");\n }\n start = options.start;\n }\n if (options.startAfter !== undefined) {\n // Convert an exclusive startAfter into an inclusive start key, so the implementation below\n // does not have to handle both. ONE null character, not upstream's two: the second of\n // upstream's is `kj::String`'s terminator, and a JS string has none.\n start = options.startAfter + NULL_CHARACTER;\n }\n if (options.end !== undefined) end = options.end;\n if (options.reverse !== undefined) reverse = options.reverse;\n if (options.limit !== undefined) {\n if (!(options.limit > 0)) throw new TypeError(\"List limit must be positive.\");\n limit = options.limit;\n }\n\n const prefix = options.prefix;\n if (prefix !== undefined && prefix.length > 0) {\n // Let's clamp `start` and `end` to include only keys with the given prefix.\n if (start < prefix) {\n // `start` is before `prefix`, so listing should actually start at `prefix`.\n start = prefix;\n } else if (start.startsWith(prefix)) {\n // `start` is within the prefix, so need not be modified.\n } else {\n // `start` comes after the last value with the prefix, so there's no overlap.\n return undefined;\n }\n\n const keyAfterPrefix = firstKeyAfterPrefix(prefix);\n if (keyAfterPrefix === undefined) {\n // The prefix is a run of maximal code units, so it includes the entire key space through\n // the last possible key. Hence there is no end — but an end specified earlier still holds.\n } else if (end === undefined) {\n // We didn't have any end set, so use the end of the prefix range.\n end = keyAfterPrefix;\n } else if (end <= prefix) {\n // No keys could possibly match both the end and the prefix.\n return undefined;\n } else if (end.startsWith(prefix)) {\n // `end` is within the prefix, so need not be modified.\n } else {\n // `end` comes after all keys with the prefix, so stop at the end of the prefix.\n end = keyAfterPrefix;\n }\n }\n }\n\n if (end !== undefined && end <= start) {\n // Key range is empty.\n return undefined;\n }\n\n return { start, end, reverse, limit };\n}\n\n/**\n * ← the `keyAfterPrefix` vector: strip maximal trailing units, then increment.\n *\n * Returns undefined when the prefix is nothing but maximal units, which is\n * upstream's \"the prefix is a string of some number of 0xff bytes, so includes\n * the entire key space up through the last possible key\".\n */\nfunction firstKeyAfterPrefix(prefix: string): string | undefined {\n let head = prefix;\n while (head.length > 0 && head.charCodeAt(head.length - 1) === MAX_CODE_UNIT) {\n head = head.slice(0, -1);\n }\n if (head.length === 0) return undefined;\n return head.slice(0, -1) + String.fromCharCode(head.charCodeAt(head.length - 1) + 1);\n}\n\n// =======================================================================================\n// SyncKvStorage\n\n/**\n * ← workerd `src/workerd/api/sync-kv.{h,c++}`. The synchronous surface lives\n * beside the asynchronous storage owner because both share the same codec and\n * list-option compiler over one `SqliteKv`.\n */\nclass SyncKvStorage implements globalThis.SyncKvStorage {\n readonly #ctx: IoContext;\n readonly #kv: SqliteKv;\n\n constructor(ctx: IoContext, kv: SqliteKv) {\n this.#ctx = ctx;\n this.#kv = kv;\n }\n\n get<T = unknown>(key: string): T | undefined {\n requireInputLock(this.#ctx, \"kv.get()\");\n const value = this.#kv.get(key);\n if (value === undefined) return undefined;\n return deserializeValue<T>(key, value);\n }\n\n list<T = unknown>(options?: globalThis.SyncKvListOptions): Iterable<[string, T]> {\n requireInputLock(this.#ctx, \"kv.list()\");\n const compiled = compileListOptions(options);\n if (compiled === undefined) {\n // Key range is empty. Upstream allocates a cursor over a null query for exactly this.\n return [];\n }\n\n const cursor = this.#kv.list(\n compiled.start,\n compiled.end,\n compiled.limit,\n compiled.reverse ? \"REVERSE\" : \"FORWARD\",\n );\n return listIterator<T>(cursor);\n }\n\n put<T>(key: string, value: T): void {\n requireInputLock(this.#ctx, \"kv.put()\");\n this.#kv.put(key, serializeValue(value));\n }\n\n delete(key: string): boolean {\n requireInputLock(this.#ctx, \"kv.delete()\");\n return this.#kv.delete(key);\n }\n}\n\n/** ← `SyncKvStorage::listNext`, whose cancellation branch is the reason it is not a plain loop. */\nfunction* listIterator<T>(cursor: SqliteKvListCursor): IterableIterator<[string, T]> {\n for (;;) {\n const pair = cursor.next();\n if (pair !== undefined) {\n yield [pair.key, deserializeValue<T>(pair.key, pair.value)];\n continue;\n }\n if (cursor.wasCanceled()) {\n throw new Error(\n \"kv.list() iterator was invalidated because a new call to kv.list() was started. \" +\n \"Only one kv.list() iterator can exist at a time.\",\n );\n }\n return;\n }\n}\n\n// =======================================================================================\n// DurableObjectStorageOperations\n\n/**\n * ← `DurableObjectStorageOperations`. \"Common implementation of\n * DurableObjectStorage and DurableObjectTransaction. This class is designed to\n * be used as a mixin.\"\n */\nabstract class DurableObjectStorageOperations {\n protected readonly ctx: IoContext;\n\n constructor(ctx: IoContext) {\n this.ctx = ctx;\n }\n\n protected abstract getCache(op: string): ActorCacheOps;\n\n get<T = unknown>(key: string, options?: DurableObjectGetOptions): Promise<T | undefined>;\n get<T = unknown>(keys: string[], options?: DurableObjectGetOptions): Promise<Map<string, T>>;\n get<T = unknown>(\n keyOrKeys: string | string[],\n maybeOptions?: DurableObjectGetOptions,\n ): Promise<T | undefined> | Promise<Map<string, T>> {\n requireInputLock(this.ctx, OP_GET);\n const options = { ...maybeOptions };\n if (typeof keyOrKeys === \"string\") return this.#getOne<T>(keyOrKeys, options);\n return this.#getMultiple<T>(keyOrKeys, options);\n }\n\n getAlarm(maybeOptions?: DurableObjectGetAlarmOptions): Promise<number | null> {\n requireInputLock(this.ctx, OP_GET_ALARM);\n // Even if we do not have an alarm handler, we might once have had one. It's fine to return\n // whatever a previous alarm setting or a falsy result.\n const options = { ...maybeOptions, noCache: false };\n return Promise.resolve(this.getCache(OP_GET_ALARM).getAlarm(options));\n }\n\n list<T = unknown>(maybeOptions?: DurableObjectListOptions): Promise<Map<string, T>> {\n requireInputLock(this.ctx, OP_LIST);\n const compiled = compileListOptions(maybeOptions);\n if (compiled === undefined) return Promise.resolve(new Map<string, T>());\n\n const options = { ...maybeOptions };\n const cache = this.getCache(OP_LIST);\n const result = compiled.reverse\n ? cache.listReverse(compiled.start, compiled.end, compiled.limit, options)\n : cache.list(compiled.start, compiled.end, compiled.limit, options);\n return Promise.resolve(listResultsToMap<T>(result));\n }\n\n put<T>(key: string, value: T, options?: DurableObjectPutOptions): Promise<void>;\n put<T>(entries: Record<string, T>, options?: DurableObjectPutOptions): Promise<void>;\n put<T>(\n keyOrEntries: string | Record<string, T>,\n valueOrOptions?: T | DurableObjectPutOptions,\n maybeOptions?: DurableObjectPutOptions,\n ): Promise<void> {\n requireInputLock(this.ctx, OP_PUT);\n // The second parameter carries a value in one overload and the options bag in the other, and\n // which it is follows from the first — so `isEntriesArgument` below is the parameter-1\n // unwrap, and the guard after it is `optionsTypeHandler.tryUnwrap` on parameter 2. Two\n // upstream steps, in that order: which overload, then whether the rest of the call agrees\n // with it.\n //\n // ← the `kj::OneOf<kj::String, jsg::Dict<...>>` unwrap, which picks the overload by which\n // alternative accepts the argument. `jsg::Dict` takes a plain object and refuses an Array;\n // `kj::String` takes everything else by stringifying it — so a non-string key is NOT a\n // mistake upstream, it is the single-key overload with a coerced key. Reading one as entries\n // instead is a silently dropped write, because `Object.entries` on a primitive is `[]`: the\n // call resolves having written nothing.\n //\n // Measured on real workerd: `put(123, \"v\")` writes `\"123\"`, `put(null, \"v\")` writes `\"null\"`,\n // `put(10n, \"v\")` writes `\"10\"`, `put([[\"a\", 1]], \"v\")` writes `\"a,1\"`, and a symbol key\n // throws V8's own conversion error. That last one is why the coercion below is a template\n // literal: `String(symbol)` is the one form that returns a description instead of throwing,\n // so it would swallow the case upstream refuses. `put(new Map(...))` reaches the Dict\n // alternative and writes nothing, which the entries branch already reproduces.\n //\n // A function reaches the `Dict` alternative too, so it is entries here rather than a key\n // stringified to its own source text.\n if (!isEntriesArgument(keyOrEntries)) {\n if (valueOrOptions === undefined) {\n throw new TypeError(\"put() called with undefined value.\");\n }\n return this.#putOne(`${keyOrEntries}`, valueOrOptions as T, { ...maybeOptions });\n }\n // ← the `else` of `optionsTypeHandler.tryUnwrap` (`actor-state.c++:449-456`): once the key\n // unwrapped as a `Dict`, a second argument can only be the options bag, and a non-null\n // primitive there is the caller mixing the two overloads. Without this the value spreads\n // into the options — `put({a: 1}, \"v\")` wrote key `a` with `{0: \"v\"}` for options.\n if (valueOrOptions !== undefined && !isPutOptions(valueOrOptions)) {\n throw new TypeError(PUT_OVERLOAD_MESSAGE);\n }\n return this.#putMultiple(keyOrEntries, {\n ...(valueOrOptions as DurableObjectPutOptions | undefined),\n });\n }\n\n delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>;\n delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>;\n delete(\n keyOrKeys: string | string[],\n maybeOptions?: DurableObjectPutOptions,\n ): Promise<boolean> | Promise<number> {\n requireInputLock(this.ctx, OP_DELETE);\n const options = { ...maybeOptions };\n if (typeof keyOrKeys === \"string\") {\n return Promise.resolve(this.getCache(OP_DELETE).delete(keyOrKeys, options));\n }\n return Promise.resolve(this.getCache(OP_DELETE).deleteMultiple(keyOrKeys, options));\n }\n\n setAlarm(scheduledTime: number | Date, maybeOptions?: DurableObjectSetAlarmOptions): Promise<void> {\n requireInputLock(this.ctx, OP_PUT_ALARM);\n const when = scheduledTime instanceof Date ? scheduledTime.getTime() : scheduledTime;\n if (!(when > 0)) {\n throw new TypeError(\"setAlarm() cannot be called with an alarm time <= 0\");\n }\n\n // \"This doesn't check if we have an alarm handler per say. It checks if we have an initialized\n // (post-ctor) JS durable object with an alarm handler.\"\n this.ctx.getActorOrThrow().assertCanSetAlarm();\n\n const options = { ...maybeOptions, noCache: false };\n\n // \"We fudge times set in the past to Date.now() to ensure that any one user can't DDOS the\n // alarm polling system by putting dates far in the past and therefore getting sorted earlier by\n // the index. This also ensures uniqueness of alarm times (which is required for correctness).\"\n this.getCache(OP_PUT_ALARM).setAlarm(Math.max(when, this.ctx.now()), options);\n return Promise.resolve();\n }\n\n deleteAlarm(maybeOptions?: DurableObjectSetAlarmOptions): Promise<void> {\n requireInputLock(this.ctx, OP_DELETE_ALARM);\n // Even if we do not have an alarm handler, we might once have had one. It's fine to remove that\n // alarm or noop on the absence of one.\n const options = { ...maybeOptions, noCache: false };\n this.getCache(OP_DELETE_ALARM).setAlarm(null, options);\n return Promise.resolve();\n }\n\n #getOne<T>(key: string, options: ReadOptions): Promise<T | undefined> {\n const value = this.getCache(OP_GET).get(key, options);\n return Promise.resolve(value === undefined ? undefined : deserializeValue<T>(key, value));\n }\n\n #getMultiple<T>(keys: string[], options: ReadOptions): Promise<Map<string, T>> {\n const result = this.getCache(OP_GET).getMultiple(keys, options);\n return Promise.resolve(listResultsToMap<T>(result));\n }\n\n #putOne<T>(key: string, value: T, options: WriteOptions): Promise<void> {\n this.getCache(OP_PUT).put(key, serializeValue(value), options);\n return Promise.resolve();\n }\n\n #putMultiple<T>(entries: Record<string, T>, options: WriteOptions): Promise<void> {\n const pairs: { key: string; value: Uint8Array }[] = [];\n for (const [key, value] of Object.entries(entries)) {\n // \"We silently drop fields with value=undefined in putMultiple. There aren't many good\n // options here, as deleting an undefined field is confusing, throwing could break otherwise\n // working code, and a stray undefined here or there is probably closer to what the user\n // desires.\"\n if (value === undefined) continue;\n pairs.push({ key, value: serializeValue(value) });\n }\n this.getCache(OP_PUT).putMultiple(pairs, options);\n return Promise.resolve();\n }\n}\n\n/** ← `listResultsToMap` and `getMultipleResultsToMap`, minus the billing halves. */\nfunction listResultsToMap<T>(rows: GetResultList): Map<string, T> {\n const map = new Map<string, T>();\n for (const entry of rows) {\n map.set(entry.key, deserializeValue<T>(entry.key, entry.value));\n }\n return map;\n}\n\n// =======================================================================================\n// DurableObjectStorage\n\n/**\n * The engine `DurableObjectStorage` drives.\n *\n * Upstream holds an `ActorCacheInterface` and reaches `getSqliteDatabase()` /\n * `getSqliteKv()` through it, both `kj::Maybe`s that are non-null exactly when\n * the actor is SQLite-backed — which here it always is. `transactionSync` is the\n * third member and is one layer lower than upstream's for the reason\n * `io/actor-sqlite.ts` records: the savepoint depth counter and `notifyWrite`\n * both live there, so this file's is a one-line forward the way\n * `blockConcurrencyWhile` already is.\n */\nexport type StorageCache = ActorCacheInterface & {\n getSqliteDatabase(): SqliteDatabase;\n getSqliteKv(): SqliteKv;\n transactionSync<T>(callback: () => T): T;\n};\n\nexport class DurableObjectStorage\n extends DurableObjectStorageOperations\n implements globalThis.DurableObjectStorage\n{\n readonly #cache: StorageCache;\n #sql: SqlStorage | undefined;\n #kv: globalThis.SyncKvStorage | undefined;\n\n constructor(ctx: IoContext, cache: StorageCache) {\n super(ctx);\n this.#cache = cache;\n }\n\n /** ← `DurableObjectStorage::getActorCacheInterface`, which `DurableObjectState::abort` needs. */\n getActorCacheInterface(): StorageCache {\n return this.#cache;\n }\n\n /** ← `DurableObjectStorage::getSqliteDb`. Always SQLite-backed here; see the header. */\n getSqliteDb(): SqliteDatabase {\n return this.#cache.getSqliteDatabase();\n }\n\n protected override getCache(): ActorCacheOps {\n return this.#cache;\n }\n\n /** ← `JSG_LAZY_INSTANCE_PROPERTY(sql, getSql)`. */\n get sql(): SqlStorage {\n this.#sql ??= new SqlStorage(this.ctx, this);\n return this.#sql;\n }\n\n /** ← `JSG_LAZY_INSTANCE_PROPERTY(kv, getKv)`. */\n get kv(): globalThis.SyncKvStorage {\n this.#kv ??= new SyncKvStorage(this.ctx, this.#cache.getSqliteKv());\n return this.#kv;\n }\n\n /**\n * ← `DurableObjectStorage::deleteAll`.\n *\n * `deleteAlarm` is upstream's `FeatureFlags::get(js).getDeleteAllDeletesAlarm()`,\n * a compatibility flag that exists so Workers published before it keep the old\n * behaviour. A runtime with no deployed history takes the current behaviour.\n */\n deleteAll(maybeOptions?: DurableObjectPutOptions): Promise<void> {\n requireInputLock(this.ctx, \"deleteAll()\");\n const options = { ...maybeOptions };\n const result = this.#cache.deleteAll(options, { deleteAlarm: true });\n return transformMaybeBackpressure(this.ctx, options, result.backpressure);\n }\n\n /**\n * ← `DurableObjectStorage::transaction`.\n *\n * The critical section is load bearing and upstream says why: \"the call to\n * `startTransaction()` is when the SQLite-backed implementation will actually\n * invoke `BEGIN TRANSACTION`, so it's important that we're inside the\n * blockConcurrencyWhile block before that point so we don't accidentally catch\n * some other asynchronous event in our transaction.\"\n *\n * The exception is packed into the result rather than thrown out of the\n * section, and then rethrown outside it. Upstream's reason: \"We don't actually\n * want to reset the object, we only want to roll back the transaction and\n * propagate the exception.\" A throw out of a critical section permanently\n * breaks the input gate (§1.5), so a failing transaction callback would\n * destroy the actor.\n */\n transaction<T>(closure: (txn: DurableObjectTransaction) => Promise<T>): Promise<T> {\n requireInputLock(this.ctx, \"transaction()\");\n type TxnResult =\n | { readonly isError: false; readonly value: T }\n | { readonly isError: true; readonly exception: unknown };\n\n return this.ctx\n .blockConcurrencyWhile(async (): Promise<TxnResult> => {\n const txn = new DurableObjectTransaction(this.ctx, this.#cache.startTransaction());\n try {\n const value = await closure(txn);\n txn.maybeCommit();\n return { isError: false, value };\n } catch (exception) {\n txn.maybeRollback();\n return { isError: true, exception };\n }\n })\n .then((result) => {\n if (result.isError) throw result.exception;\n return result.value;\n });\n }\n\n /** ← `DurableObjectStorage::transactionSync`, a forward for the reason above. */\n transactionSync<T>(callback: () => T): T {\n requireInputLock(this.ctx, \"transactionSync()\");\n return this.#cache.transactionSync(callback);\n }\n\n /**\n * ← `DurableObjectStorage::sync`.\n *\n * Upstream's `awaitIo` rather than `awaitIoWithInputLock`, which is the one\n * storage method that deliberately opens the gate: \"we're merely checking if\n * we have any pending or in-flight operations, and providing a promise that\n * resolves when they succeed.\"\n */\n sync(): Promise<void> {\n requireInputLock(this.ctx, \"sync()\");\n return this.ctx.awaitIo(this.#cache.onNoPendingFlush());\n }\n\n /**\n * Real, not a boundary: `ActorSqlite`'s is \"an ersatz implementation that's\n * good enough for local dev with D1's Session API\", built on the metadata\n * table's local-development bookmark. Anything above this package that\n * surfaces it to an application should know it is a counter and not a\n * recovery point — as it is on workerd.\n */\n getCurrentBookmark(): Promise<string> {\n requireInputLock(this.ctx, \"getCurrentBookmark()\");\n return this.ctx.awaitIo(this.#cache.getCurrentBookmark());\n }\n\n waitForBookmark(bookmark: string): Promise<void> {\n requireInputLock(this.ctx, \"waitForBookmark()\");\n return this.ctx.awaitIo(this.#cache.waitForBookmark(bookmark));\n }\n\n /** Substrate boundary: point-in-time recovery. Upstream reaches the cache directly, as this does. */\n getBookmarkForTime(timestamp: number | Date): Promise<string> {\n return this.#cache.getBookmarkForTime(\n timestamp instanceof Date ? timestamp.getTime() : timestamp,\n );\n }\n\n /** Substrate boundary: point-in-time recovery. */\n onNextSessionRestoreBookmark(bookmark: string): Promise<string> {\n return this.#cache.onNextSessionRestoreBookmark(bookmark);\n }\n\n /** Substrate boundary: replication. */\n ensureReplicas(): void {\n this.#cache.ensureReplicas();\n }\n\n /** Substrate boundary: replication. */\n disableReplicas(): void {\n this.#cache.disableReplicas();\n }\n\n /**\n * ← `DurableObjectStorage::getPrimary` / `isReplica`. `maybePrimary` is set\n * only by the replica constructor, and nothing constructs a replica here, so\n * these answer upstream's own non-replica case rather than a stubbed one.\n */\n getPrimary(): undefined {\n return undefined;\n }\n\n isReplica(): boolean {\n return false;\n }\n}\n\n// =======================================================================================\n// DurableObjectTransaction\n\nclass DurableObjectTransaction\n extends DurableObjectStorageOperations\n implements globalThis.DurableObjectTransaction\n{\n /** Becomes undefined when committed or rolled back. */\n #cacheTxn: ActorCacheTransaction | undefined;\n #rolledBack = false;\n\n constructor(ctx: IoContext, cacheTxn: ActorCacheTransaction) {\n super(ctx);\n this.#cacheTxn = cacheTxn;\n }\n\n protected override getCache(op: string): ActorCacheOps {\n if (this.#rolledBack) throw new Error(`Cannot ${op} on rolled back transaction`);\n const txn = this.#cacheTxn;\n if (txn === undefined) {\n throw new Error(\n `Cannot call ${op} on transaction that has already committed: ` +\n \"did you move `txn` outside of the closure?\",\n );\n }\n return txn;\n }\n\n /** Called from JS. */\n rollback(): void {\n if (this.#rolledBack) return; // allow multiple calls to rollback()\n this.getCache(OP_ROLLBACK); // just for the checks\n const txn = this.#cacheTxn;\n if (txn !== undefined) {\n txn.rollback();\n // ← the `IoContext::addWaitUntil(prom.attach(mv(cacheTxn)))`, whose attach is the\n // destruction Section 1 turned into an explicit drop.\n txn.drop();\n this.#cacheTxn = undefined;\n }\n this.#rolledBack = true;\n }\n\n /** Just throws an exception saying this isn't supported. */\n deleteAll(): never {\n throw new Error(\"Cannot call deleteAll() within a transaction\");\n }\n\n /**\n * Called from the runtime, not JS, after the transaction callback has\n * completed. Does nothing if the transaction is already committed or rolled\n * back. Synchronous, because `ActorCacheTransaction::commit` is (§1.4).\n */\n maybeCommit(): void {\n const txn = this.#cacheTxn;\n if (txn === undefined) return;\n this.#cacheTxn = undefined;\n txn.commit();\n txn.drop();\n }\n\n /** Same, for the failure path. Upstream's drops the transaction, whose destructor rolls back. */\n maybeRollback(): void {\n const txn = this.#cacheTxn;\n this.#cacheTxn = undefined;\n this.#rolledBack = true;\n txn?.drop();\n }\n}\n\n// =======================================================================================\n// DurableObjectFacets\n\n/**\n * ← `requireValidFacetName` (`actor-state.c++:949-952`).\n *\n * The comparison is `name.size()` on a `kj::StringPtr`, which is **UTF-8 bytes**,\n * so it is measured in bytes here too — the same `TextEncoder` pass, for the same\n * reason, that `ColoLocalActorNamespace.get`'s `[1, 2048]` bound already costs.\n * Comparing `name.length` accepts a 256-character non-ASCII name that upstream\n * refuses, which is a bound a caller can hit.\n */\nfunction requireValidFacetName(name: string): void {\n if (textEncoder.encode(name).length > FACET_NAME_MAX_LENGTH) {\n throw new TypeError(`Facet name is too long (max ${FACET_NAME_MAX_LENGTH} characters).`);\n }\n}\n\n/**\n * ← the `KJ_SWITCH_ONEOF(options.$class)` lambda (`actor-state.c++:1029-1043`).\n *\n * Three arms, and the order matters for the same reason it does upstream: a\n * `LoopbackDurableObjectClass` *is* a `DurableObjectClass`, so it takes the bare\n * arm here exactly as JSG's `kj::OneOf` unwraps it into the first alternative.\n * The two loopback namespaces are not classes and carry one, which `getClass()`\n * hands back.\n *\n * A `ctx.exports` entry is the callable façade `api/export-loopback.ts` produces\n * rather than the instance itself, and every check below is an `instanceof` that\n * the façade's `getPrototypeOf` answers — which is why that trap exists.\n */\nfunction requireFacetClass(actorClass: unknown): DurableObjectClass {\n if (actorClass instanceof DurableObjectClass) return actorClass;\n if (actorClass instanceof LoopbackDurableObjectNamespace) return actorClass.getClass();\n if (actorClass instanceof LoopbackColoLocalActorNamespace) return actorClass.getClass();\n throw new TypeError(FACET_CLASS_UNSUPPORTED_MESSAGE);\n}\n\n/**\n * ← `DurableObjectFacets`.\n *\n * **`clone` is the fourth method, and the vendored C++ snapshot does not have\n * it.** The design record cites `actor-state.h:431-497` and\n * `server.c++:721-749`; neither line range contains it, `DurableObjectFacets`\n * there exposes exactly `get`, `abort` and `delete`, and\n * `Worker::Actor::FacetManager` has exactly `getDepth`, `getFacet`, `abortFacet`\n * and `deleteFacet`. It is real all the same: `@cloudflare/workers-types`\n * 4.20260702.1 — a month newer than the snapshot — declares\n * `clone(src: string, dst: string): void` on `DurableObjectFacets`. So the\n * signature comes from the types and the semantics from §1.10 (abort dst, delete\n * dst storage, recursive copy of the src subtree), and the orchestration is\n * `server/`'s `cloneFacet`. There is nothing upstream to check the body against,\n * which makes it the one method here with no reference — worth knowing when it\n * is wrong.\n */\nexport class DurableObjectFacets implements globalThis.DurableObjectFacets {\n readonly #ctx: IoContext;\n readonly #facetManager: FacetManager | undefined;\n readonly #parentId: string;\n\n constructor(ctx: IoContext, facetManager: FacetManager | undefined, parentId: string) {\n this.#ctx = ctx;\n this.#facetManager = facetManager;\n this.#parentId = parentId;\n }\n\n /**\n * Get a facet by name, starting it if it isn't already running.\n * `getStartupOptions` is invoked only if the facet wasn't already running.\n *\n * Returns a `Fetcher` instead of a `DurableObject` because the returned stub\n * does not have the `id` or `name` methods that a DO stub normally has.\n */\n get<T extends Rpc.DurableObjectBranded | undefined = undefined>(\n name: string,\n getStartupOptions: () => FacetStartupOptions<T> | Promise<FacetStartupOptions<T>>,\n ): Fetcher<T> {\n requireValidFacetName(name);\n const facetManager = this.#getFacetManager();\n\n if (facetManager.getDepth() + 1 >= FACET_TREE_MAX_DEPTH) {\n throw new Error(\n \"Facet nesting depth limit exceeded. The maximum depth including the root Durable \" +\n `Object is ${FACET_TREE_MAX_DEPTH}.`,\n );\n }\n\n // Where upstream reads `IoContext::current()`, which is after both checks above.\n requireInputLock(this.#ctx, \"facets.get()\");\n\n // ← `ioCtx.makeReentryCallback(...)` (`actor-state.c++:1011`), which is decision 13: without\n // it a facet started from inside blockConcurrencyWhile() would queue behind the section that\n // is waiting for it.\n const getStartInfo = this.#ctx.makeReentryCallback(async (): Promise<FacetStartInfo> => {\n const options = await getStartupOptions();\n const id = options.id;\n return {\n // ← `actorClass.getChannel(ioCtx)` (`actor-state.c++:1045`).\n actorClass: requireFacetClass(options.class).getChannel(),\n // Child inherits parent ID.\n id:\n id === undefined\n ? this.#parentId\n : typeof id === \"string\"\n ? id\n : id.name ?? id.toString(),\n };\n });\n\n return facetManager.getFacet<T>(name, getStartInfo);\n }\n\n abort(name: string, reason: unknown): void {\n requireValidFacetName(name);\n this.#getFacetManager().abortFacet(name, reason);\n }\n\n delete(name: string): void {\n requireValidFacetName(name);\n this.#getFacetManager().deleteFacet(name);\n }\n\n clone(src: string, dst: string): void {\n requireValidFacetName(src);\n requireValidFacetName(dst);\n this.#getFacetManager().cloneFacet(src, dst);\n }\n\n #getFacetManager(): FacetManager {\n const facetManager = this.#facetManager;\n if (facetManager === undefined) {\n throw new Error(\"This Durable Object does not support creating facets.\");\n }\n return facetManager;\n }\n}\n\n// =======================================================================================\n// DurableObjectState\n\nexport type DurableObjectStateOptions = {\n id: DurableObjectId;\n /** The `ctx.exports` class registry. */\n exports: Record<string, unknown>;\n props: unknown;\n storage?: DurableObjectStorage;\n /** Absent for an actor whose host offers no facets, as upstream's `kj::Maybe` is. */\n facets?: FacetManager;\n /** ← `ActorVersion`, a deployment cohort with nothing to read it here. */\n version?: { cohort?: string };\n /**\n * This actor's `ServiceWorkerGlobalScope` half — the container's own\n * `globals`. Required, unlike `storage` and `facets`: a host that offers no\n * storage is a real posture upstream has, but an actor with no gated timers\n * is not, and the failure of a missing one is an ungated timer that WORKS\n * until a continuation after it touches storage. See\n * `DurableObjectState.globals`.\n */\n globals: ActorScopeBindings;\n webSockets: HibernatableWebSocketRegistry;\n};\n\n/** The type passed as the first parameter to a Durable Object class's constructor. */\nexport class DurableObjectState implements globalThis.DurableObjectState {\n readonly #ctx: IoContext;\n readonly #options: DurableObjectStateOptions;\n #facets: DurableObjectFacets | undefined;\n\n constructor(ctx: IoContext, options: DurableObjectStateOptions) {\n this.#ctx = ctx;\n this.#options = options;\n }\n\n get id(): DurableObjectId {\n return this.#options.id;\n }\n\n get props(): unknown {\n return this.#options.props;\n }\n\n /** ← `JSG_LAZY_INSTANCE_PROPERTY(exports, getExports)`, behind `enableCtxExports` upstream. */\n get exports(): Record<string, unknown> {\n return this.#options.exports;\n }\n\n get version(): { cohort?: string } | undefined {\n return this.#options.version;\n }\n\n /**\n * NO upstream correspondence, because upstream needs none: a\n * `ServiceWorkerGlobalScope` IS the isolate's global object there, so an\n * actor's class reaches its gated `setTimeout` by writing `setTimeout`.\n *\n * Here one realm hosts several actors, so the names on `globalThis` can only\n * be bound to one of them and a continuation cannot be asked which one it\n * belongs to. `ctx` is the one reference every Durable Object class already\n * holds and that already means exactly one actor — the constructor was handed\n * it — so it is where the scope goes. An actor's method writes\n * `this.ctx.globals.setTimeout(…)`; a free function it calls takes the scope\n * as a parameter.\n *\n * `installActorScope` still exists and is still what a host uses for a\n * dynamically-loaded Worker source, which has no `ctx` to reach through and\n * its own module scope to destructure into. The two are the same object.\n */\n get globals(): ActorScopeBindings {\n return this.#options.globals;\n }\n\n get storage(): DurableObjectStorage {\n const storage = this.#options.storage;\n if (storage === undefined) {\n throw new Error(\"This Durable Object does not have storage.\");\n }\n return storage;\n }\n\n /** ← `JSG_LAZY_INSTANCE_PROPERTY(facets, getFacets)`. */\n get facets(): DurableObjectFacets {\n this.#facets ??= new DurableObjectFacets(\n this.#ctx,\n this.#options.facets,\n this.#options.id.toString(),\n );\n return this.#facets;\n }\n\n waitUntil(promise: Promise<unknown>): void {\n this.#ctx.addWaitUntil(promise.then(() => {}));\n }\n\n /**\n * ← `DurableObjectState::blockConcurrencyWhile` (`actor-state.c++:1128-1131`),\n * which is a one-line forward and nothing else. The 30-second deadline, the\n * brokenness annotation and the never-settled promise on failure all live in\n * `IoContext::blockConcurrencyWhile`, which Section 2 already implements.\n *\n * Its precondition comes with it: `IoContext::blockConcurrencyWhile` calls\n * `getInputLock()`, which asserts, so this is reachable only from inside a\n * gated slice.\n */\n blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T> {\n return this.#ctx.blockConcurrencyWhile(callback);\n }\n\n /**\n * ← `DurableObjectState::abort`. Reset the object, including breaking the\n * output gate and canceling any writes that haven't been committed yet.\n *\n * `js.terminateExecutionNow()` has no port — there is no isolate to terminate —\n * so the caller's own slice keeps running to its next await, where `IoContext`\n * refuses to re-enter.\n */\n abort(reason?: string): void {\n const description =\n reason === undefined\n ? \"broken.outputGateBroken; jsg.Error: Application called abort() to reset Durable Object.\"\n : `broken.outputGateBroken; jsg.Error: ${reason}`;\n const error = new Error(description);\n // ← `error.setDetail(jsg::EXCEPTION_IS_USER_ERROR, ...)` (`actor-state.c++:1143`). It is what\n // tells `isAlarmFailureUserError` that this reset was the application's doing, so an alarm\n // handler that aborts is retried a bounded number of times rather than forever.\n setUserErrorDetail(error);\n\n // \"Make sure we _synchronously_ break storage so that there's no chance our promise fulfilling\n // will race against the output gate, possibly allowing writes to complete before being\n // canceled.\"\n this.#options.storage?.getActorCacheInterface().shutdown(error);\n\n this.#ctx.abort(error);\n }\n\n /** ← `DurableObjectState::getPrimaryStub`. Non-null only for a replica; see the storage note. */\n get primaryStub(): undefined {\n return this.#options.storage?.getPrimary();\n }\n\n /** Substrate boundary: replication. */\n configureReadReplication(options: { mode: string }): Promise<void> {\n const storage = this.#options.storage;\n if (storage === undefined) {\n throw new TypeError(\"This actor does not support read replication.\");\n }\n if (storage.isReplica()) {\n throw new Error(\"Replica Durable Objects cannot call configureReadReplication().\");\n }\n if (options.mode !== \"auto\" && options.mode !== \"disabled\") {\n throw new TypeError(\n `configureReadReplication() called with unknown mode setting: ${options.mode}.`,\n );\n }\n return this.#ctx.awaitIo(\n storage.getActorCacheInterface().configureReadReplication(options.mode === \"auto\"),\n );\n }\n\n acceptWebSocket(ws: WebSocket, tags?: string[]): void {\n this.#options.webSockets.acceptWebSocket(ws, tags);\n }\n\n getWebSockets(tag?: string): WebSocket[] {\n return tag === undefined\n ? this.#options.webSockets.getWebSockets()\n : this.#options.webSockets.getWebSockets(tag);\n }\n\n setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void {\n this.#options.webSockets.setWebSocketAutoResponse(maybeReqResp);\n }\n\n getWebSocketAutoResponse(): WebSocketRequestResponsePair | null {\n return this.#options.webSockets.getWebSocketAutoResponse();\n }\n\n getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null {\n return this.#options.webSockets.getWebSocketAutoResponseTimestamp(ws);\n }\n\n setHibernatableWebSocketEventTimeout(timeoutMs?: number): void {\n this.#options.webSockets.setHibernatableWebSocketEventTimeout(timeoutMs);\n }\n\n getHibernatableWebSocketEventTimeout(): number | null {\n return this.#options.webSockets.getHibernatableWebSocketEventTimeout();\n }\n\n getTags(ws: WebSocket): string[] {\n return this.#options.webSockets.getTags(ws);\n }\n}\n","/**\n * ← workerd `src/workerd/api/web-socket.{h,c++}` — classic and hibernatable\n * socket delivery over the actor's input/output gates.\n *\n * The runtime owns the WebSocket object produced by `WebSocketPair`; embedders\n * still own network transports supplied as `RawWebSocket`s. Hibernation state is\n * per container and can be mirrored through `HibernationHost` for reconstruction.\n */\n\nimport type { IoContext } from \"../io/io-context\";\nimport type { CriticalSection } from \"../io/io-gate\";\nimport { deserializeValue, serializeValue } from \"./actor-state\";\n\nexport interface RawWebSocket {\n addEventListener(type: string, listener: (event: Event) => void): void;\n send(data: string | ArrayBufferLike | ArrayBufferView | Blob): void;\n close(code?: number, reason?: string): void;\n readonly readyState?: number;\n binaryType?: string;\n}\n\nexport interface HibernationHost {\n accepted(socket: RawWebSocket, tags: readonly string[]): void;\n attachment(socket: RawWebSocket, bytes: Uint8Array | null): void;\n autoResponse(pair: { request: string; response: string } | null): void;\n closed(socket: RawWebSocket): void;\n}\n\nexport type RehydratedWebSocket = {\n socket: RawWebSocket;\n tags?: readonly string[];\n attachment?: Uint8Array;\n autoResponseTimestamp?: number;\n};\n\ntype WebSocketPairConstructor = typeof WebSocketPair;\n\nclass WebSocketRequestResponsePairImpl implements WebSocketRequestResponsePair {\n readonly #request: string;\n readonly #response: string;\n\n constructor(request: string, response: string) {\n this.#request = String(request);\n this.#response = String(response);\n }\n\n get request(): string {\n return this.#request;\n }\n\n get response(): string {\n return this.#response;\n }\n}\n\nconst RuntimeWebSocketRequestResponsePair: typeof WebSocketRequestResponsePair =\n new Proxy(WebSocketRequestResponsePairImpl, {\n apply(): never {\n throw new TypeError(\n \"Failed to construct 'WebSocketRequestResponsePair': Please use the 'new' operator, this DOM object constructor cannot be called as a function.\",\n );\n },\n });\n\nexport { RuntimeWebSocketRequestResponsePair as WebSocketRequestResponsePair };\n\ntype RuntimeWebSocketPair = {\n 0: AcceptedWebSocket;\n 1: AcceptedWebSocket;\n};\n\n/** ← the `JSG_REQUIRE(!native.state.is<Accepted>(), ...)` at the head of `accept()`. */\nexport const ALREADY_ACCEPTED_MESSAGE =\n \"acceptWebSocket(): this socket has already been accepted by an actor. A socket's frames are \" +\n \"delivered by exactly one read loop, and a second accept would deliver them under two gates.\";\n\nexport const HIBERNATION_ALREADY_ACCEPTED_MESSAGE =\n \"Cannot call `acceptWebSocket()` if the WebSocket was already accepted via `accept()`\";\nexport const HIBERNATION_AFTER_ACCEPT_MESSAGE =\n \"Can't accept() WebSocket after enabling hibernation.\";\nexport const HIBERNATION_PAIR_USED_MESSAGE =\n \"Cannot call `acceptWebSocket()` on this WebSocket because its pair has already been accepted or used in a Response.\";\n\nconst MAX_HIBERNATABLE_SOCKETS = 32_768;\nconst MAX_TAGS = 10;\nconst MAX_TAG_LENGTH = 256;\nconst MAX_ATTACHMENT_BYTES = 16_384;\nconst MAX_AUTO_RESPONSE_BYTES = 2_048;\nconst MAX_EVENT_TIMEOUT = 604_800_000;\nconst MAX_CLOSE_REASON_BYTES = 123;\n\nconst WEB_SOCKET_READY_STATES = {\n READY_STATE_CONNECTING: 0,\n READY_STATE_OPEN: 1,\n READY_STATE_CLOSING: 2,\n READY_STATE_CLOSED: 3,\n CONNECTING: 0,\n OPEN: 1,\n CLOSING: 2,\n CLOSED: 3,\n} as const;\n\nconst textEncoder = new TextEncoder();\n\nconst SOCKET_EVENTS = [\"open\", \"message\", \"close\", \"error\"] as const;\ntype SocketEvent = (typeof SOCKET_EVENTS)[number];\n\ntype PairState = {\n used: boolean;\n hibernationAccepted: boolean;\n};\n\ntype SocketAcceptance =\n | { mode: \"classic\" }\n | { mode: \"hibernatable\"; registry: HibernatableWebSocketRegistry };\n\ntype SocketDelivery =\n | { mode: \"pending\" }\n | { mode: \"classic\"; criticalSection: CriticalSection | undefined }\n | { mode: \"hibernatable\"; registry: HibernatableWebSocketRegistry };\n\ntype SocketMetadata = {\n accepted?: SocketAcceptance;\n attachment?: Uint8Array;\n rawListenersInstalled?: true;\n};\n\nconst metadata = new WeakMap<object, SocketMetadata>();\n\nfunction socketMetadata(socket: object): SocketMetadata {\n let value = metadata.get(socket);\n if (value === undefined) {\n value = {};\n metadata.set(socket, value);\n }\n return value;\n}\n\nfunction isRawWebSocket(value: unknown): value is RawWebSocket {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"addEventListener\" in value &&\n typeof value.addEventListener === \"function\" &&\n \"send\" in value &&\n typeof value.send === \"function\" &&\n \"close\" in value &&\n typeof value.close === \"function\"\n );\n}\n\nfunction requireWebSocket(value: unknown, operation: string): RawWebSocket {\n if (!isRawWebSocket(value)) {\n throw new TypeError(\n `Failed to execute '${operation}' on 'WebSocket': parameter 1 is not of type 'WebSocket'.`,\n );\n }\n return value;\n}\n\nfunction serializeAttachment(socket: RawWebSocket, value: unknown): void {\n try {\n structuredClone(value);\n } catch (error) {\n if (error instanceof DOMException && error.name === \"DataCloneError\") {\n throw new DOMException(\n error.message.replace(/^Failed to execute 'structuredClone' on '[^']+': /, \"\"),\n \"DataCloneError\",\n );\n }\n throw error;\n }\n const bytes = serializeValue(value);\n // ponytail: the local codec's string envelope is seven bytes wider than V8's;\n // replace this size adapter if the package adopts V8 wire bytes.\n const measuredBytes =\n typeof value === \"string\" ? textEncoder.encode(value).byteLength + 5 : bytes.byteLength;\n if (measuredBytes > MAX_ATTACHMENT_BYTES) {\n throw new Error(\n `A WebSocket 'attachment' cannot be larger than ${MAX_ATTACHMENT_BYTES} bytes.'attachment' was ${measuredBytes} bytes.`,\n );\n }\n const state = socketMetadata(socket);\n state.attachment = bytes;\n if (state.accepted?.mode === \"hibernatable\") {\n state.accepted.registry.attachmentChanged(socket, bytes);\n }\n}\n\nfunction deserializeAttachment(socket: RawWebSocket): unknown {\n const attachment = socketMetadata(socket).attachment;\n if (attachment === undefined) return null;\n return deserializeValue(\"WebSocket attachment\", attachment);\n}\n\nfunction serializeAttachmentMethod(this: unknown, value?: unknown): void {\n if (arguments.length === 0) {\n throw new TypeError(\n \"Failed to execute 'serializeAttachment' on 'WebSocket': parameter 1 is not of type 'Value'.\",\n );\n }\n serializeAttachment(requireWebSocket(this, \"serializeAttachment\"), value);\n}\n\nfunction deserializeAttachmentMethod(this: unknown): unknown {\n return deserializeAttachment(requireWebSocket(this, \"deserializeAttachment\"));\n}\n\nfunction cloneMessageData(data: unknown): string | ArrayBuffer | Blob {\n if (typeof data === \"string\" || data instanceof Blob) return data;\n if (data instanceof ArrayBuffer) return data.slice(0);\n if (ArrayBuffer.isView(data)) {\n return new Uint8Array(data.buffer, data.byteOffset, data.byteLength).slice().buffer;\n }\n return String(data);\n}\n\nclass MemoryWebSocketEndpoint extends EventTarget implements RawWebSocket {\n peer!: MemoryWebSocketEndpoint;\n #sentClose = false;\n\n send(data: string | ArrayBufferLike | ArrayBufferView | Blob): void {\n this.peer.dispatchEvent(new MessageEvent(\"message\", { data: cloneMessageData(data) }));\n }\n\n close(code = 1000, reason = \"\"): void {\n if (this.#sentClose) return;\n this.#sentClose = true;\n this.peer.dispatchEvent(new CloseEvent(\"close\", { code, reason, wasClean: true }));\n }\n}\n\n/** One public socket identity, in classic or hibernatable mode after acceptance. */\nexport class AcceptedWebSocket extends EventTarget implements RawWebSocket, WebSocket {\n static readonly READY_STATE_CONNECTING = WEB_SOCKET_READY_STATES.READY_STATE_CONNECTING;\n static readonly READY_STATE_OPEN = WEB_SOCKET_READY_STATES.READY_STATE_OPEN;\n static readonly READY_STATE_CLOSING = WEB_SOCKET_READY_STATES.READY_STATE_CLOSING;\n static readonly READY_STATE_CLOSED = WEB_SOCKET_READY_STATES.READY_STATE_CLOSED;\n static readonly CONNECTING = WEB_SOCKET_READY_STATES.CONNECTING;\n static readonly OPEN = WEB_SOCKET_READY_STATES.OPEN;\n static readonly CLOSING = WEB_SOCKET_READY_STATES.CLOSING;\n static readonly CLOSED = WEB_SOCKET_READY_STATES.CLOSED;\n\n declare readonly READY_STATE_CONNECTING: 0;\n declare readonly READY_STATE_OPEN: 1;\n declare readonly READY_STATE_CLOSING: 2;\n declare readonly READY_STATE_CLOSED: 3;\n declare readonly CONNECTING: 0;\n declare readonly OPEN: 1;\n declare readonly CLOSING: 2;\n declare readonly CLOSED: 3;\n readonly bufferedAmount = 0;\n readonly extensions = \"\";\n readonly protocol = \"\";\n readonly url = \"\";\n\n #ctx: IoContext;\n readonly #socket: RawWebSocket;\n readonly #pairState: PairState | undefined;\n #delivery: SocketDelivery = { mode: \"pending\" };\n #pump: Promise<void> = Promise.resolve();\n #pending: { type: SocketEvent; event: Event }[] = [];\n #readyState: number = AcceptedWebSocket.OPEN;\n #ownClose = false;\n #peerClose = false;\n #binaryType: \"blob\" | \"arraybuffer\" = \"blob\";\n\n onopen: ((event: Event) => void) | null = null;\n onmessage: ((event: MessageEvent) => void) | null = null;\n onclose: ((event: CloseEvent) => void) | null = null;\n onerror: ((event: Event) => void) | null = null;\n\n constructor(ctx: IoContext, socket: RawWebSocket, pairState?: PairState) {\n super();\n this.#ctx = ctx;\n this.#socket = socket;\n this.#pairState = pairState;\n if (pairState === undefined) this.#enableClassic();\n for (const type of SOCKET_EVENTS) {\n socket.addEventListener(type, (event: Event) => {\n this.#receive(type, event);\n });\n }\n }\n\n get readyState(): number {\n return this.#readyState;\n }\n\n get binaryType(): \"blob\" | \"arraybuffer\" {\n return this.#binaryType;\n }\n\n set binaryType(value: \"blob\" | \"arraybuffer\") {\n this.#binaryType = value;\n }\n\n accept(): void {\n if (this.#delivery.mode === \"hibernatable\") {\n throw new TypeError(HIBERNATION_AFTER_ACCEPT_MESSAGE);\n }\n if (this.#delivery.mode === \"classic\") throw new Error(ALREADY_ACCEPTED_MESSAGE);\n if (this.#pairState !== undefined) this.#pairState.used = true;\n this.#enableClassic();\n }\n\n send(data: string | ArrayBufferLike | ArrayBufferView | Blob): void {\n if (this.#delivery.mode === \"hibernatable\" && this.#ownClose) {\n throw new TypeError(\"Can't call WebSocket send() after close().\");\n }\n if (this.#peerClose || this.#readyState === AcceptedWebSocket.CLOSED) return;\n this.#markPairUsed();\n this.#enqueue(() => this.#socket.send(data));\n }\n\n close(code?: number, reason = \"\"): void {\n if (this.#readyState === AcceptedWebSocket.CLOSED || this.#ownClose) return;\n if (this.#delivery.mode === \"hibernatable\" || this.#pairState !== undefined) {\n validateClose(code, reason);\n }\n this.#markPairUsed();\n this.#ownClose = true;\n this.#readyState = this.#peerClose ? AcceptedWebSocket.CLOSED : AcceptedWebSocket.CLOSING;\n this.#enqueue(() => this.#socket.close(code, reason));\n }\n\n serializeAttachment(value: unknown): void {\n if (arguments.length === 0) serializeAttachmentMethod.call(this);\n else serializeAttachment(this, value);\n }\n\n deserializeAttachment(): unknown {\n return deserializeAttachment(this);\n }\n\n acceptHibernation(registry: HibernatableWebSocketRegistry): void {\n if (this.#delivery.mode !== \"pending\") {\n throw new Error(HIBERNATION_ALREADY_ACCEPTED_MESSAGE);\n }\n if (this.#pairState?.used === true && !this.#pairState.hibernationAccepted) {\n throw new Error(HIBERNATION_PAIR_USED_MESSAGE);\n }\n if (this.#pairState !== undefined) {\n this.#pairState.used = true;\n this.#pairState.hibernationAccepted = true;\n }\n this.#activateHibernation(registry, this.#ctx);\n }\n\n rehydrateHibernation(registry: HibernatableWebSocketRegistry, ctx: IoContext): void {\n this.#activateHibernation(registry, ctx);\n }\n\n #activateHibernation(registry: HibernatableWebSocketRegistry, ctx: IoContext): void {\n this.#ctx = ctx;\n this.#delivery = { mode: \"hibernatable\", registry };\n this.#pending = [];\n }\n\n markPairUsed(): void {\n this.#markPairUsed();\n }\n\n #markPairUsed(): void {\n if (this.#pairState !== undefined) this.#pairState.used = true;\n }\n\n #enableClassic(): void {\n const delivery: SocketDelivery = {\n mode: \"classic\",\n criticalSection: this.#ctx.getCriticalSection(),\n };\n this.#delivery = delivery;\n socketMetadata(this).accepted = { mode: \"classic\" };\n const pending = this.#pending;\n this.#pending = [];\n for (const item of pending) {\n this.#deliverClassic(item.type, item.event, delivery.criticalSection);\n }\n }\n\n #receive(type: SocketEvent, event: Event): void {\n if (type === \"close\") {\n this.#receiveClose(event as CloseEvent);\n return;\n }\n const delivery = this.#delivery;\n if (delivery.mode === \"pending\") this.#pending.push({ type, event });\n else if (delivery.mode === \"classic\") {\n this.#deliverClassic(type, event, delivery.criticalSection);\n } else delivery.registry.receive(this, type, event);\n }\n\n #receiveClose(event: CloseEvent): void {\n if (this.#ownClose) {\n this.#readyState = AcceptedWebSocket.CLOSED;\n } else {\n this.#peerClose = true;\n this.#readyState = AcceptedWebSocket.CLOSING;\n if (this.#delivery.mode === \"classic\" && this.#pairState !== undefined) {\n // Pair halves perform the WebSocket close handshake in-memory. An\n // embedder-supplied raw socket owns its own protocol and only reports.\n if (event.code === 1005 || event.code === 1006 || event.code === 1015) {\n this.#readyState = AcceptedWebSocket.CLOSED;\n } else {\n this.close(event.code, event.reason);\n }\n }\n }\n const delivery = this.#delivery;\n if (delivery.mode === \"pending\") this.#pending.push({ type: \"close\", event });\n else if (delivery.mode === \"classic\") {\n this.#deliverClassic(\"close\", event, delivery.criticalSection);\n } else delivery.registry.receive(this, \"close\", event);\n }\n\n #deliverClassic(\n type: SocketEvent,\n event: Event,\n criticalSection: CriticalSection | undefined,\n ): void {\n this.#ctx.addWaitUntil(\n this.#ctx.run(() => {\n const delivered = cloneEventFor(type, event);\n this.dispatchEvent(delivered);\n const handler = this[`on${type}`] as ((event: Event) => void) | null;\n handler?.(delivered);\n }, { input: criticalSection }),\n );\n }\n\n #enqueue(write: () => void): void {\n const outputLock = this.#ctx.waitForOutputLocks();\n this.#pump = this.#pump.then(async () => {\n await outputLock;\n write();\n });\n this.#ctx.addWaitUntil(this.#pump);\n }\n}\n\nfor (const [name, value] of Object.entries(WEB_SOCKET_READY_STATES)) {\n Object.defineProperty(AcceptedWebSocket.prototype, name, { value, enumerable: true });\n}\n\ntype HandlerDispatch = {\n message(socket: RawWebSocket, message: string | ArrayBuffer): unknown;\n close(socket: RawWebSocket, code: number, reason: string, wasClean: boolean): unknown;\n error(socket: RawWebSocket, error: unknown): unknown;\n};\n\ntype RegistryEntry = {\n readonly socket: RawWebSocket;\n readonly tags: string[];\n autoResponseTimestamp?: number;\n};\n\nexport class HibernatableWebSocketRegistry {\n readonly #ctx: IoContext;\n readonly #dispatch: HandlerDispatch;\n readonly #host: HibernationHost | undefined;\n readonly #entries: RegistryEntry[] = [];\n #autoResponse: WebSocketRequestResponsePair | null = null;\n #eventTimeout: number | null = null;\n #pairConstructor: WebSocketPairConstructor | undefined;\n\n constructor(\n ctx: IoContext,\n dispatch: HandlerDispatch,\n host?: HibernationHost,\n rehydrated: readonly RehydratedWebSocket[] = [],\n ) {\n this.#ctx = ctx;\n this.#dispatch = dispatch;\n this.#host = host;\n for (const value of rehydrated) this.#rehydrate(value);\n }\n\n get WebSocketPair(): WebSocketPairConstructor {\n const registry = this;\n this.#pairConstructor ??= new Proxy(\n class WebSocketPair {\n declare readonly 0: WebSocket;\n declare readonly 1: WebSocket;\n },\n { construct: () => registry.#createPair() },\n );\n return this.#pairConstructor;\n }\n\n acceptWebSocket(socket: RawWebSocket, tags?: string[]): void {\n if (!isRawWebSocket(socket)) {\n throw new TypeError(\n \"Failed to execute 'acceptWebSocket' on 'DurableObjectState': parameter 1 is not of type 'WebSocket'.\",\n );\n }\n const state = socketMetadata(socket);\n if (state.accepted !== undefined) throw new Error(HIBERNATION_ALREADY_ACCEPTED_MESSAGE);\n if (this.#entries.length >= MAX_HIBERNATABLE_SOCKETS) {\n throw new Error(\n `only ${MAX_HIBERNATABLE_SOCKETS} websockets can be accepted on a single Durable Object instance`,\n );\n }\n const normalizedTags = normalizeTags(tags);\n if (socket instanceof AcceptedWebSocket) socket.acceptHibernation(this);\n else this.#listenRaw(socket);\n state.accepted = { mode: \"hibernatable\", registry: this };\n this.#entries.push({ socket, tags: normalizedTags });\n this.#host?.accepted(socket, normalizedTags);\n }\n\n getWebSockets(tag?: string): WebSocket[] {\n if (arguments.length > 0) {\n if (typeof tag !== \"string\") return [];\n return this.#entries\n .filter((entry) => entry.tags.includes(tag))\n .map((entry) => entry.socket as WebSocket);\n }\n return this.#entries.map((entry) => entry.socket as WebSocket).reverse();\n }\n\n getTags(socket: RawWebSocket): string[] {\n const state = isRawWebSocket(socket) ? metadata.get(socket) : undefined;\n if (state?.accepted === undefined) {\n throw new Error(\n \"you must call 'acceptWebSocket()' before attempting to access the tags of a WebSocket.\",\n );\n }\n if (state.accepted.mode !== \"hibernatable\") {\n throw new Error(\"only hibernatable websockets can have tags.\");\n }\n const entry = this.#entries.find((candidate) => candidate.socket === socket);\n if (entry === undefined) {\n throw new Error(\n \"you must call 'acceptWebSocket()' before attempting to access the tags of a WebSocket.\",\n );\n }\n return [...entry.tags];\n }\n\n setWebSocketAutoResponse(pair?: WebSocketRequestResponsePair): void {\n if (pair === undefined) {\n this.#autoResponse = null;\n this.#host?.autoResponse(null);\n return;\n }\n if (!(pair instanceof WebSocketRequestResponsePairImpl)) {\n throw new TypeError(\n \"Failed to execute 'setWebSocketAutoResponse' on 'DurableObjectState': parameter 1 is not of type 'WebSocketRequestResponsePair'.\",\n );\n }\n validateAutoResponseSize(\"Request\", pair.request);\n validateAutoResponseSize(\"Response\", pair.response);\n this.#autoResponse = pair;\n this.#host?.autoResponse({ request: pair.request, response: pair.response });\n }\n\n getWebSocketAutoResponse(): WebSocketRequestResponsePair | null {\n const pair = this.#autoResponse;\n return pair === null\n ? null\n : new RuntimeWebSocketRequestResponsePair(pair.request, pair.response);\n }\n\n getWebSocketAutoResponseTimestamp(socket: RawWebSocket): Date | null {\n if (!isRawWebSocket(socket)) {\n throw new TypeError(\n \"Failed to execute 'getWebSocketAutoResponseTimestamp' on 'DurableObjectState': parameter 1 is not of type 'WebSocket'.\",\n );\n }\n const timestamp = this.#entries.find((entry) => entry.socket === socket)?.autoResponseTimestamp;\n return timestamp === undefined ? null : new Date(timestamp);\n }\n\n setHibernatableWebSocketEventTimeout(value?: number): void {\n if (value === undefined || Number(value) === 0) {\n this.#eventTimeout = null;\n return;\n }\n const number = Number(value);\n if (Number.isNaN(number)) {\n throw new TypeError(\"The value cannot be converted because it is not an integer.\");\n }\n if (number < 0) {\n throw new TypeError(\n \"The value cannot be converted because it is negative and this API expects a positive number.\",\n );\n }\n if (number > 0xffff_ffff) {\n throw new TypeError(\"Value out of range. Must be less than or equal to 4294967295.\");\n }\n const timeout = Math.trunc(number);\n if (timeout > MAX_EVENT_TIMEOUT) {\n throw new Error(`Event timeout should not exceed ${MAX_EVENT_TIMEOUT} ms.`);\n }\n this.#eventTimeout = timeout;\n }\n\n getHibernatableWebSocketEventTimeout(): number | null {\n return this.#eventTimeout;\n }\n\n attachmentChanged(socket: RawWebSocket, bytes: Uint8Array): void {\n if (this.#entries.some((entry) => entry.socket === socket)) {\n this.#host?.attachment(socket, bytes);\n }\n }\n\n receive(socket: RawWebSocket, type: SocketEvent, event: Event): void {\n const entry = this.#entries.find((candidate) => candidate.socket === socket);\n if (entry === undefined) return;\n if (type === \"message\") {\n const data = (event as MessageEvent).data as unknown;\n if (typeof data === \"string\" && data === this.#autoResponse?.request) {\n entry.autoResponseTimestamp = this.#ctx.now();\n socket.send(this.#autoResponse.response);\n return;\n }\n const message = cloneMessageData(data);\n if (message instanceof Blob) {\n this.#ctx.addWaitUntil(\n message.arrayBuffer().then((buffer) => {\n this.#schedule(() => this.#dispatch.message(socket, buffer));\n }),\n );\n return;\n }\n this.#schedule(() => this.#dispatch.message(socket, message));\n return;\n }\n if (type === \"close\") {\n this.#remove(entry);\n const close = event as CloseEvent;\n this.#schedule(() =>\n this.#dispatch.close(socket, close.code, close.reason, close.wasClean),\n );\n return;\n }\n if (type === \"error\") this.#schedule(() => this.#dispatch.error(socket, event));\n }\n\n #schedule(handler: () => unknown): void {\n this.#ctx.addWaitUntil(this.#ctx.run(handler).then(() => {}));\n }\n\n #remove(entry: RegistryEntry): void {\n const index = this.#entries.indexOf(entry);\n if (index === -1) return;\n this.#entries.splice(index, 1);\n this.#host?.closed(entry.socket);\n }\n\n #listenRaw(socket: RawWebSocket): void {\n const state = socketMetadata(socket);\n if (state.rawListenersInstalled === true) return;\n state.rawListenersInstalled = true;\n for (const type of [\"message\", \"close\", \"error\"] as const) {\n socket.addEventListener(type, (event) => {\n const accepted = socketMetadata(socket).accepted;\n if (accepted?.mode === \"hibernatable\") {\n accepted.registry.receive(socket, type, event);\n }\n });\n }\n }\n\n #rehydrate(value: RehydratedWebSocket): void {\n const socket = value.socket;\n if (!isRawWebSocket(socket)) {\n throw new TypeError(\"ActorContainerOptions.webSockets contains a non-WebSocket value.\");\n }\n const tags = normalizeTags(value.tags);\n const state = socketMetadata(socket);\n state.accepted = { mode: \"hibernatable\", registry: this };\n if (value.attachment !== undefined) {\n state.attachment = value.attachment.slice();\n }\n if (socket instanceof AcceptedWebSocket) socket.rehydrateHibernation(this, this.#ctx);\n else this.#listenRaw(socket);\n const entry: RegistryEntry = { socket, tags };\n if (value.autoResponseTimestamp !== undefined) {\n entry.autoResponseTimestamp = value.autoResponseTimestamp;\n }\n this.#entries.push(entry);\n }\n\n #createPair(): RuntimeWebSocketPair {\n const pairState: PairState = { used: false, hibernationAccepted: false };\n const left = new MemoryWebSocketEndpoint();\n const right = new MemoryWebSocketEndpoint();\n left.peer = right;\n right.peer = left;\n return {\n 0: new AcceptedWebSocket(this.#ctx, left, pairState),\n 1: new AcceptedWebSocket(this.#ctx, right, pairState),\n };\n }\n}\n\nexport function acceptWebSocket(ctx: IoContext, socket: RawWebSocket): AcceptedWebSocket {\n const state = socketMetadata(socket);\n if (state.accepted !== undefined) throw new Error(ALREADY_ACCEPTED_MESSAGE);\n if (socket instanceof AcceptedWebSocket) {\n socket.accept();\n return socket;\n }\n state.accepted = { mode: \"classic\" };\n const accepted = new AcceptedWebSocket(ctx, socket);\n return accepted;\n}\n\nexport function markWebSocketUsed(socket: RawWebSocket): void {\n if (socket instanceof AcceptedWebSocket) socket.markPairUsed();\n}\n\nexport function installWebSocketGlobals(\n target: object,\n pairConstructor: WebSocketPairConstructor,\n): void {\n const constructor = globalThis.WebSocket;\n for (const [name, value] of Object.entries(WEB_SOCKET_READY_STATES)) {\n defineValue(constructor, name, value);\n defineValue(constructor.prototype, name, value);\n }\n defineValue(constructor.prototype, \"serializeAttachment\", serializeAttachmentMethod);\n defineValue(constructor.prototype, \"deserializeAttachment\", deserializeAttachmentMethod);\n defineValue(target, \"WebSocket\", constructor);\n defineValue(target, \"WebSocketPair\", pairConstructor);\n defineValue(target, \"WebSocketRequestResponsePair\", RuntimeWebSocketRequestResponsePair);\n}\n\nfunction defineValue(target: object, name: string, value: unknown): void {\n const current = Object.getOwnPropertyDescriptor(target, name);\n if (current?.configurable === false) return;\n Object.defineProperty(target, name, { configurable: true, writable: true, value });\n}\n\nfunction normalizeTags(tags: unknown): string[] {\n if (tags === undefined) return [];\n if (!Array.isArray(tags)) {\n throw new TypeError(\n \"Failed to execute 'acceptWebSocket' on 'DurableObjectState': parameter 2 is not of type 'Array'.\",\n );\n }\n if (tags.length > MAX_TAGS) {\n throw new Error(`a Hibernatable WebSocket cannot have more than ${MAX_TAGS} tags`);\n }\n const normalized = [...new Set(tags.map(String))];\n for (const tag of normalized) {\n if (tag.length > MAX_TAG_LENGTH) {\n throw new Error(\n `\"${tag}\" is longer than the max tag length (${MAX_TAG_LENGTH} characters).`,\n );\n }\n }\n return normalized;\n}\n\nfunction validateAutoResponseSize(side: \"Request\" | \"Response\", value: string): void {\n const bytes = textEncoder.encode(value).byteLength;\n if (bytes > MAX_AUTO_RESPONSE_BYTES) {\n throw new RangeError(\n `${side} cannot be larger than ${MAX_AUTO_RESPONSE_BYTES} bytes. A ${side.toLowerCase()} of size ${bytes} was provided.`,\n );\n }\n}\n\nfunction validateClose(code: number | undefined, reason: string): void {\n if (code !== undefined && code !== 1000 && (code < 3000 || code > 4999)) {\n throw new DOMException(`Invalid WebSocket close code: ${code}.`, \"InvalidAccessError\");\n }\n if (textEncoder.encode(reason).byteLength > MAX_CLOSE_REASON_BYTES) {\n throw new DOMException(\n `WebSocket close reason must not be longer than ${MAX_CLOSE_REASON_BYTES} bytes when UTF-8 encoded.`,\n \"SyntaxError\",\n );\n }\n}\n\nfunction cloneEventFor(type: SocketEvent, event: Event): Event {\n if (type === \"message\") {\n const source = event as MessageEvent;\n return new MessageEvent(\"message\", {\n data: source.data,\n origin: source.origin,\n lastEventId: source.lastEventId,\n });\n }\n if (type === \"close\") {\n const source = event as CloseEvent;\n return new CloseEvent(\"close\", {\n code: source.code,\n reason: source.reason,\n wasClean: source.wasClean,\n });\n }\n return new Event(type);\n}\n"],"mappings":";;;;;;;;;;AAoFA,IAAa,gCAAgC;;;;;;;;;AAU7C,IAAa,2BACX;;AAKF,IAAa,kDACX;;;;;;AASF,IAAM,yBAAyB;;;;;AAkE/B,IAAa,0BAAb,MAAmF;CACjF;CAEA,YAAY,SAAuC;EACjD,KAAKA,WAAW;CAClB;;CAGA,IAAI,SAA0B;EAC5B,MAAM,QAAQ,WAAW,OAAO;EAChC,IAAI,EAAE,QAAQ,KAAK,SAAA,OACjB,MAAM,IAAI,UACR,4CAA4C,8BAA8B,GAC5E;EAEF,OAAO,KAAKA,SAAS,kBAAkB,EAAE,QAAQ,CAAC;CACpD;AACF;AAEA,IAAM,gBAAc,IAAI,YAAY;;AAGpC,SAAS,WAAW,OAAuB;CACzC,OAAO,cAAY,OAAO,KAAK,CAAC,CAAC;AACnC;;;;;;;;;;;;;;;AAmBA,IAAa,kBAAb,MAAmE;CACjE;CACA;CACA;CAEA,YAAY,IAAa;EACvB,KAAKC,MAAM;EACX,MAAM,OAAO,GAAG,QAAQ;EACxB,IAAI,SAAS,KAAA,GAAW,KAAK,OAAO;EACpC,MAAM,eAAe,GAAG,gBAAgB;EACxC,IAAI,iBAAiB,KAAA,GAAW,KAAK,eAAe;CACtD;;CAGA,WAAoB;EAClB,OAAO,KAAKA;CACd;;CAGA,WAAmB;EACjB,OAAO,KAAKA,IAAI,SAAS;CAC3B;CAEA,OAAO,OAA4C;EACjD,OAAO,KAAKA,IAAI,OAAO,UAAU,KAAK,CAAC;CACzC;AACF;;AAGA,SAAS,uBAAuB,IAAiD;CAC/E,IAAI,cAAc,iBAAiB,OAAO;CAC1C,MAAM,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