@cloudflare/vitest-plugin 1.1.1 → 1.1.2

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.
@@ -277,6 +277,32 @@ function isCtxExportsEnabled(exports$1) {
277
277
  return globalThis.Cloudflare?.compatibilityFlags.enable_ctx_exports && exports$1 !== void 0;
278
278
  }
279
279
 
280
+ //#endregion
281
+ //#region src/worker/proxy-prototype.ts
282
+ const IGNORED_KEYS = ["self"];
283
+ /**
284
+ * Create a class extending `superClass` with a lazily installed `Proxy` as its
285
+ * `prototype`. Unknown prototype accesses defer to `getUnknownPrototypeKey()`.
286
+ */
287
+ function createProxyPrototypeClass(superClass, getUnknownPrototypeKey) {
288
+ let proxyInstalled = false;
289
+ function Class(...args) {
290
+ if (!proxyInstalled) {
291
+ Class.prototype = new Proxy(Class.prototype, { get(target, key, receiver) {
292
+ const value = Reflect.get(target, key, receiver);
293
+ if (value !== void 0) return value;
294
+ if (typeof key === "symbol" || IGNORED_KEYS.includes(key)) return;
295
+ return getUnknownPrototypeKey.call(receiver, key);
296
+ } });
297
+ proxyInstalled = true;
298
+ }
299
+ return Reflect.construct(superClass, args, Class);
300
+ }
301
+ Reflect.setPrototypeOf(Class.prototype, superClass.prototype);
302
+ Reflect.setPrototypeOf(Class, superClass);
303
+ return Class;
304
+ }
305
+
280
306
  //#endregion
281
307
  //#region src/worker/entrypoints.ts
282
308
  /**
@@ -294,28 +320,6 @@ async function importModule(specifier) {
294
320
  return __vitest_mocker__.moduleRunner.import(specifier);
295
321
  });
296
322
  }
297
- const IGNORED_KEYS = ["self"];
298
- /**
299
- * Create a class extending `superClass` with a `Proxy` as a `prototype`.
300
- * Unknown accesses on the `prototype` will defer to `getUnknownPrototypeKey()`.
301
- * `workerd` will only look for RPC methods/properties on the prototype, not the
302
- * instance. This helps avoid accidentally exposing things over RPC, but makes
303
- * things a little trickier for us...
304
- */
305
- function createProxyPrototypeClass(superClass, getUnknownPrototypeKey) {
306
- function Class(...args) {
307
- Class.prototype = new Proxy(Class.prototype, { get(target, key, receiver) {
308
- const value = Reflect.get(target, key, receiver);
309
- if (value !== void 0) return value;
310
- if (typeof key === "symbol" || IGNORED_KEYS.includes(key)) return;
311
- return getUnknownPrototypeKey.call(receiver, key);
312
- } });
313
- return Reflect.construct(superClass, args, Class);
314
- }
315
- Reflect.setPrototypeOf(Class.prototype, superClass.prototype);
316
- Reflect.setPrototypeOf(Class, superClass);
317
- return Class;
318
- }
319
323
  /**
320
324
  * Only properties and methods declared on the prototype can be accessed over
321
325
  * RPC. This function throws a helpful error message if a property isn't
@@ -1 +1 @@
1
- {"version":3,"file":"test-internal.mjs","names":["DEFAULT_EVICTION_OPTIONS: DurableObjectEvictionOptions","sameIsolatedNamespaces: DurableObjectNamespace[] | undefined","env","DEFAULT_EVICTION_OPTIONS","errors: unknown[]","timeoutId: ReturnType<typeof setTimeout> | undefined","globalWaitUntil: unknown[]","exports","releaseStarted: (() => void) | undefined","OPTIONAL_DURABLE_OBJECT_KEYS: ReadonlySet<\n\t(typeof DURABLE_OBJECT_KEYS)[number]\n>","runtimeEnv","env","DurableObjectClass","#controller","timestamp: Date","attempts: number","metadata: MessageBatchMetadata","retryMessages: QueueRetryMessage[]","explicitAcks: string[]","DEFAULT_EVICTION_OPTIONS: DurableObjectEvictionOptions","chunks: Uint8Array[]","operations: WorkflowIntrospectionOperation[]","streamResult: WorkflowIntrospectionStreamResult","workflow: WorkflowBinding","#sessionId","#operations","#instanceIntrospectors","#disposed","instanceId: string","#instanceModifierPromise","#instanceModifier"],"sources":["../../../../src/worker/d1.ts","../../../../src/worker/env.ts","../../../../src/worker/durable-objects.ts","../../../../src/worker/wait-until.ts","../../../../src/worker/patch-ctx.ts","../../../../src/worker/entrypoints.ts","../../../../src/worker/events.ts","../../../../src/worker/reset.ts","../../../../src/worker/secrets-store.ts","../../../../../workflows-shared/src/introspection.ts","../../../../src/worker/workflows.ts"],"sourcesContent":["import type { D1Migration } from \"../shared/d1\";\n\nfunction isD1Database(v: unknown): v is D1Database {\n\treturn (\n\t\ttypeof v === \"object\" &&\n\t\tv !== null &&\n\t\tv.constructor.name === \"D1Database\" &&\n\t\t\"prepare\" in v &&\n\t\ttypeof v.prepare === \"function\" &&\n\t\t\"batch\" in v &&\n\t\ttypeof v.batch === \"function\" &&\n\t\t\"exec\" in v &&\n\t\ttypeof v.exec === \"function\"\n\t);\n}\n\nfunction isD1Migration(v: unknown): v is D1Migration {\n\treturn (\n\t\ttypeof v === \"object\" &&\n\t\tv !== null &&\n\t\t\"name\" in v &&\n\t\ttypeof v.name === \"string\" &&\n\t\t\"queries\" in v &&\n\t\tArray.isArray(v.queries) &&\n\t\tv.queries.every((query) => typeof query === \"string\")\n\t);\n}\nfunction isD1Migrations(v: unknown): v is D1Migration[] {\n\treturn Array.isArray(v) && v.every(isD1Migration);\n}\n\nexport async function applyD1Migrations(\n\tdb: D1Database,\n\tmigrations: D1Migration[],\n\tmigrationsTableName = \"d1_migrations\"\n) {\n\tif (!isD1Database(db)) {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'applyD1Migrations': parameter 1 is not of type 'D1Database'.\"\n\t\t);\n\t}\n\tif (!isD1Migrations(migrations)) {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'applyD1Migrations': parameter 2 is not of type 'D1Migration[]'.\"\n\t\t);\n\t}\n\t// noinspection SuspiciousTypeOfGuard\n\tif (typeof migrationsTableName !== \"string\") {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'applyD1Migrations': parameter 3 is not of type 'string'.\"\n\t\t);\n\t}\n\n\tconst escapeId = (id: string) => `\"${id.replace(/\"/g, '\"\"')}\"`;\n\tconst escapedTableName = escapeId(migrationsTableName);\n\n\t// Create migrations table if it doesn't exist\n\tconst schema = `CREATE TABLE IF NOT EXISTS ${escapedTableName} (\n\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\tname TEXT UNIQUE,\n\t\tapplied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL\n\t);`;\n\tawait db.prepare(schema).run();\n\n\t// Find applied migrations\n\tconst appliedMigrationNamesResult = await db\n\t\t.prepare(`SELECT name FROM ${escapedTableName};`)\n\t\t.all<{ name: string }>();\n\tconst appliedMigrationNames = appliedMigrationNamesResult.results.map(\n\t\t({ name }) => name\n\t);\n\n\t// Apply un-applied migrations\n\tconst insertMigrationStmt = db.prepare(\n\t\t`INSERT INTO ${escapedTableName} (name) VALUES (?);`\n\t);\n\tfor (const migration of migrations) {\n\t\tif (appliedMigrationNames.includes(migration.name)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst queries = migration.queries.map((query) => db.prepare(query));\n\t\tqueries.push(insertMigrationStmt.bind(migration.name));\n\t\tawait db.batch(queries);\n\t}\n}\n","import assert from \"node:assert\";\nimport { exports } from \"cloudflare:workers\";\n\nexport { env } from \"cloudflare:workers\";\n\n/**\n * For reasons that aren't clear to me, just `SELF = exports.default` ends up with SELF being\n * undefined in a test. This Proxy solution works.\n */\nexport const SELF = new Proxy(\n\t{},\n\t{\n\t\tget(_, p) {\n\t\t\tconst target = exports.default as unknown as Record<\n\t\t\t\tstring | symbol,\n\t\t\t\tunknown\n\t\t\t>;\n\t\t\tconst value = target[p];\n\t\t\treturn typeof value === \"function\" ? value.bind(target) : value;\n\t\t},\n\t}\n);\n\nexport function getSerializedOptions(): SerializedOptions {\n\tassert(typeof __vitest_worker__ === \"object\", \"Expected global Vitest state\");\n\tconst options = __vitest_worker__.providedContext.cloudflarePoolOptions;\n\t// `options` should always be defined when running tests\n\n\tassert(\n\t\toptions !== undefined,\n\t\t\"Expected serialised options, got keys: \" +\n\t\t\tObject.keys(__vitest_worker__.providedContext).join(\", \")\n\t);\n\tconst parsedOptions = JSON.parse(options);\n\treturn {\n\t\t...parsedOptions,\n\t\tdurableObjectBindingDesignators: new Map(\n\t\t\tparsedOptions.durableObjectBindingDesignators\n\t\t),\n\t};\n}\n\nexport function getResolvedMainPath(\n\tforBindingType: \"service\" | \"Durable Object\"\n): string {\n\tconst options = getSerializedOptions();\n\tif (options.main === undefined) {\n\t\tthrow new Error(\n\t\t\t`Using ${forBindingType} bindings to the current worker requires \\`poolOptions.workers.main\\` to be set to your worker's entrypoint: ${JSON.stringify(options)}`\n\t\t);\n\t}\n\treturn options.main;\n}\n","import assert from \"node:assert\";\nimport { env, exports } from \"cloudflare:workers\";\nimport workerdUnsafe from \"workerd:unsafe\";\nimport { getSerializedOptions } from \"./env\";\nimport type { __VITEST_POOL_WORKERS_RUNNER_DURABLE_OBJECT__ } from \"./index\";\nimport type { DurableObjectEvictionOptions } from \"workerd:unsafe\";\n\nconst DEFAULT_EVICTION_OPTIONS: DurableObjectEvictionOptions = {\n\twebSockets: \"hibernate\",\n};\n\nconst CF_KEY_ACTION = \"vitestPoolWorkersDurableObjectAction\";\n\nlet nextActionId = 0;\nconst kUseResponse = Symbol(\"kUseResponse\");\nconst actionResults = new Map<number /* id */, unknown>();\n\nfunction isDurableObjectNamespace(v: unknown): v is DurableObjectNamespace {\n\treturn (\n\t\tv instanceof Object &&\n\t\t/^(?:Loopback)?DurableObjectNamespace$/.test(v.constructor.name) &&\n\t\t\"newUniqueId\" in v &&\n\t\ttypeof v.newUniqueId === \"function\" &&\n\t\t\"idFromName\" in v &&\n\t\ttypeof v.idFromName === \"function\" &&\n\t\t\"idFromString\" in v &&\n\t\ttypeof v.idFromString === \"function\" &&\n\t\t\"get\" in v &&\n\t\ttypeof v.get === \"function\"\n\t);\n}\nfunction isDurableObjectStub(v: unknown): v is DurableObjectStub {\n\treturn (\n\t\ttypeof v === \"object\" &&\n\t\tv !== null &&\n\t\t(v.constructor.name === \"DurableObject\" ||\n\t\t\tv.constructor.name === \"WorkerRpc\") &&\n\t\t\"fetch\" in v &&\n\t\ttypeof v.fetch === \"function\" &&\n\t\t\"id\" in v &&\n\t\ttypeof v.id === \"object\"\n\t);\n}\n\n// Whilst `sameIsolatedNamespaces` depends on `getSerializedOptions()`,\n// `durableObjectBindingDesignators` is derived from the user Durable Object\n// config. If this were to change, the Miniflare options would change too\n// restarting this worker. This means we only need to compute this once, as it\n// will automatically invalidate when needed.\nlet sameIsolatedNamespaces: DurableObjectNamespace[] | undefined;\nfunction getSameIsolateNamespaces(): DurableObjectNamespace[] {\n\tif (sameIsolatedNamespaces !== undefined) {\n\t\treturn sameIsolatedNamespaces;\n\t}\n\tsameIsolatedNamespaces = [];\n\n\tconst options = getSerializedOptions();\n\tif (options.durableObjectBindingDesignators === undefined) {\n\t\treturn sameIsolatedNamespaces;\n\t}\n\n\tfor (const [key, designator] of options.durableObjectBindingDesignators) {\n\t\t// We're assuming the user isn't able to guess the current worker name, so\n\t\t// if a `scriptName` is set, the designator is for another worker.\n\t\tif (designator.scriptName !== undefined) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst namespace = env[key] ?? (exports as Record<string, unknown>)?.[key];\n\t\tassert(\n\t\t\tisDurableObjectNamespace(namespace),\n\t\t\t`Expected ${key} to be a DurableObjectNamespace binding`\n\t\t);\n\t\tsameIsolatedNamespaces.push(namespace);\n\t}\n\n\treturn sameIsolatedNamespaces;\n}\n\nfunction assertSameIsolate(stub: DurableObjectStub) {\n\t// Make sure our special `cf` requests get handled correctly and aren't\n\t// routed to user fetch handlers\n\tconst idString = stub.id.toString();\n\tconst namespaces = getSameIsolateNamespaces();\n\t// Try to recreate the stub's ID using each same-isolate namespace.\n\t// `idFromString()` will throw if the ID is not for that namespace.\n\t// If a call succeeds, we know the ID is for an object in this isolate.\n\tfor (const namespace of namespaces) {\n\t\ttry {\n\t\t\tnamespace.idFromString(idString);\n\t\t\treturn;\n\t\t} catch {}\n\t}\n\t// If no calls succeed, we know the ID is for an object outside this isolate,\n\t// and we won't be able to use the `actionResults` map to share data.\n\tthrow new Error(\n\t\t\"Durable Object test helpers can only be used with stubs pointing to objects defined within the same worker.\"\n\t);\n}\n\nasync function runInStub<O extends DurableObject, R>(\n\tstub: Fetcher,\n\tcallback: (instance: O, state: DurableObjectState) => R | Promise<R>\n): Promise<R> {\n\tconst id = nextActionId++;\n\tactionResults.set(id, callback);\n\n\tconst response = await stub.fetch(\"http://x\", {\n\t\tcf: { [CF_KEY_ACTION]: id },\n\t\t// Prevent the runtime from following redirects returned by the callback,\n\t\t// which would re-enter `maybeHandleRunRequest` with a consumed action ID.\n\t\tredirect: \"manual\",\n\t});\n\n\t// `result` may be `undefined`\n\tassert(actionResults.has(id), `Expected action result for ${id}`);\n\tconst result = actionResults.get(id);\n\tactionResults.delete(id);\n\n\tif (result === kUseResponse) {\n\t\treturn response as R;\n\t} else if (response.ok) {\n\t\treturn result as R;\n\t} else {\n\t\tthrow result;\n\t}\n}\n\n// See public facing `cloudflare:test` types for docs\n// (`async` so it throws asynchronously/rejects)\nexport async function runInDurableObject<O extends DurableObject, R>(\n\tstub: DurableObjectStub,\n\tcallback: (instance: O, state: DurableObjectState) => R | Promise<R>\n): Promise<R> {\n\tif (!isDurableObjectStub(stub)) {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'runInDurableObject': parameter 1 is not of type 'DurableObjectStub'.\"\n\t\t);\n\t}\n\tif (typeof callback !== \"function\") {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'runInDurableObject': parameter 2 is not of type 'function'.\"\n\t\t);\n\t}\n\n\tassertSameIsolate(stub);\n\treturn runInStub(stub, callback);\n}\n\nasync function runAlarm(instance: DurableObject, state: DurableObjectState) {\n\tconst alarm = await state.storage.getAlarm();\n\tif (alarm === null) {\n\t\treturn false;\n\t}\n\tawait state.storage.deleteAlarm();\n\tawait instance.alarm?.();\n\treturn true;\n}\n// See public facing `cloudflare:test` types for docs\n// (`async` so it throws asynchronously/rejects)\nexport async function runDurableObjectAlarm(\n\tstub: DurableObjectStub\n): Promise<boolean /* ran */> {\n\tif (!isDurableObjectStub(stub)) {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'runDurableObjectAlarm': parameter 1 is not of type 'DurableObjectStub'.\"\n\t\t);\n\t}\n\treturn await runInDurableObject(stub, runAlarm);\n}\n\n// See public facing `cloudflare:test` types for docs\n// (`async` so it throws asynchronously/rejects)\nexport async function evictDurableObject(\n\tstub: DurableObjectStub,\n\toptions: DurableObjectEvictionOptions = DEFAULT_EVICTION_OPTIONS\n): Promise<void> {\n\tif (!isDurableObjectStub(stub)) {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'evictDurableObject': parameter 1 is not of type 'DurableObjectStub'.\"\n\t\t);\n\t}\n\tawait workerdUnsafe.evict(stub, options);\n}\n\n/**\n * Internal method for running `callback` inside the I/O context of the\n * Runner Durable Object.\n *\n * Tests run in this context by default. This is required for performing\n * operations that use Vitest's RPC mechanism as the Durable Object\n * owns the RPC WebSocket. For example, importing modules or sending logs.\n * Trying to perform those operations from a different context (e.g. within\n * a `export default { fetch() {} }` handler or user Durable Object's `fetch()`\n * handler) without using this function will result in a `Cannot perform I/O on\n * behalf of a different request` error.\n */\nexport function runInRunnerObject<R>(\n\tcallback: (\n\t\tinstance: __VITEST_POOL_WORKERS_RUNNER_DURABLE_OBJECT__\n\t) => R | Promise<R>\n): Promise<R> {\n\t// Runner DO is ephemeral (ColoLocalActorNamespace), which has .get(name)\n\t// instead of the standard idFromName()/get(id) API.\n\tconst ns = env[\"__VITEST_POOL_WORKERS_RUNNER_OBJECT\"] as unknown as {\n\t\tget(name: string): Fetcher;\n\t};\n\tconst stub = ns.get(\"singleton\");\n\treturn runInStub(stub, callback);\n}\n\nexport async function maybeHandleRunRequest(\n\trequest: Request,\n\tinstance: unknown,\n\tstate?: DurableObjectState\n): Promise<Response | undefined> {\n\tconst actionId = request.cf?.[CF_KEY_ACTION];\n\tif (actionId === undefined) {\n\t\treturn;\n\t}\n\n\tassert(typeof actionId === \"number\", `Expected numeric ${CF_KEY_ACTION}`);\n\ttry {\n\t\tconst callback = actionResults.get(actionId);\n\t\tassert(typeof callback === \"function\", `Expected callback for ${actionId}`);\n\t\tconst result = await callback(instance, state);\n\t\t// If the callback returns a `Response`, we can't pass it back to the\n\t\t// caller through `actionResults`. If we did that, we'd get a `Cannot\n\t\t// perform I/O on behalf of a different Durable Object` error if we\n\t\t// tried to use it. Instead, we set a flag in `actionResults` that\n\t\t// instructs the caller to use the `Response` returned by\n\t\t// `DurableObjectStub#fetch()` directly.\n\t\tif (result instanceof Response) {\n\t\t\tactionResults.set(actionId, kUseResponse);\n\t\t\treturn result;\n\t\t} else {\n\t\t\tactionResults.set(actionId, result);\n\t\t}\n\t\treturn new Response(null, { status: 204 });\n\t} catch (e) {\n\t\tactionResults.set(actionId, e);\n\t\treturn new Response(null, { status: 500 });\n\t}\n}\n\nexport async function listDurableObjectIds(\n\tnamespace: DurableObjectNamespace\n): Promise<DurableObjectId[]> {\n\tif (!isDurableObjectNamespace(namespace)) {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'listDurableObjectIds': parameter 1 is not of type 'DurableObjectNamespace'.\"\n\t\t);\n\t}\n\n\t// To get an instance of `DurableObjectNamespace`, the user must've bound the\n\t// namespace to the test runner worker, since `DurableObjectNamespace` has no\n\t// user-accessible constructor. This means `namespace` must be in `globalEnv`.\n\t// We can use this to find the bound name for this binding. We inject a\n\t// mapping between bound names and Durable Object designators. We pass the\n\t// bound name to Miniflare's Node-side loopback to find all IDs on disk.\n\tconst boundName = Object.entries(env).find(\n\t\t(entry) => namespace === entry[1]\n\t)?.[0];\n\tassert(boundName !== undefined, \"Expected to find bound name for namespace\");\n\n\tconst options = getSerializedOptions();\n\tconst searchParams = new URLSearchParams({ binding_name: boundName });\n\tif (options.selfName !== undefined) {\n\t\tsearchParams.set(\"worker_name\", options.selfName);\n\t}\n\n\tconst url = `http://placeholder/durable-objects?${searchParams.toString()}`;\n\tconst res = await env.__VITEST_POOL_WORKERS_LOOPBACK_SERVICE.fetch(url);\n\tassert.strictEqual(res.status, 200);\n\tconst ids = await res.json();\n\tassert(Array.isArray(ids));\n\treturn ids.map((id) => {\n\t\tassert(typeof id === \"string\");\n\t\treturn namespace.idFromString(id);\n\t});\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\n/**\n * In production, Workers have a 30-second limit for `waitUntil` promises.\n * We use the same limit here. If promises are still pending after this,\n * they almost certainly indicate a bug (e.g. a `waitUntil` promise that\n * will never resolve). We log a warning and move on so the test suite\n * doesn't hang indefinitely.\n */\nlet WAIT_UNTIL_TIMEOUT = 30_000;\n\n/** @internal — only exposed for tests */\nexport function setWaitUntilTimeout(ms: number): void {\n\tWAIT_UNTIL_TIMEOUT = ms;\n}\n\nconst kTimedOut = Symbol(\"kTimedOut\");\n\n/**\n * Empty array and wait for all promises to resolve until no more added.\n * If a single promise rejects, the rejection will be passed-through.\n * If multiple promises reject, the rejections will be aggregated.\n *\n * If any batch of promises hasn't settled after {@link WAIT_UNTIL_TIMEOUT}ms,\n * a warning is logged and the remaining promises are abandoned.\n */\nexport async function waitForWaitUntil(\n\t/* mut */ waitUntil: unknown[]\n): Promise<void> {\n\tconst errors: unknown[] = [];\n\n\twhile (waitUntil.length > 0) {\n\t\tconst batch = waitUntil.splice(0);\n\t\tlet timeoutId: ReturnType<typeof setTimeout> | undefined;\n\t\tconst result = await Promise.race([\n\t\t\tPromise.allSettled(batch).then((results) => ({ results })),\n\t\t\tnew Promise<typeof kTimedOut>(\n\t\t\t\t(resolve) =>\n\t\t\t\t\t(timeoutId = setTimeout(() => resolve(kTimedOut), WAIT_UNTIL_TIMEOUT))\n\t\t\t),\n\t\t]);\n\t\tclearTimeout(timeoutId);\n\n\t\tif (result === kTimedOut) {\n\t\t\t__console.warn(\n\t\t\t\t`[vitest-plugin] ${batch.length} waitUntil promise(s) did not ` +\n\t\t\t\t\t`resolve within ${WAIT_UNTIL_TIMEOUT / 1000}s and will be abandoned. ` +\n\t\t\t\t\t`This normally means your Worker's waitUntil handler has a bug ` +\n\t\t\t\t\t`that prevents it from settling (e.g. a fetch that never completes ` +\n\t\t\t\t\t`or a missing resolve/reject call).`\n\t\t\t);\n\t\t\t// Stop draining — any promises added during this batch are also abandoned\n\t\t\twaitUntil.length = 0;\n\t\t\tbreak;\n\t\t}\n\n\t\t// Record all rejected promises\n\t\tfor (const settled of result.results) {\n\t\t\tif (settled.status === \"rejected\") {\n\t\t\t\terrors.push(settled.reason);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (errors.length === 1) {\n\t\t// If there was only one rejection, rethrow it\n\t\tthrow errors[0];\n\t} else if (errors.length > 1) {\n\t\t// If there were more rejections, rethrow them all\n\t\tthrow new AggregateError(errors);\n\t}\n}\n\n// If isolated storage is enabled, we ensure all `waitUntil()`s are `await`ed at\n// the end of each test, as these may contain storage calls (e.g. caching\n// responses). Note we can't wait at the end of `.concurrent` tests, as we can't\n// track which `waitUntil()`s belong to which tests.\n//\n// If isolated storage is disabled, we ensure all `waitUntil()`s are `await`ed\n// at the end of each test *file*. This ensures we don't try to dispose the\n// runtime until all `waitUntil()`s complete.\nconst globalWaitUntil: unknown[] = [];\nexport function registerGlobalWaitUntil(promise: unknown) {\n\tglobalWaitUntil.push(promise);\n}\nexport function waitForGlobalWaitUntil(): Promise<void> {\n\treturn waitForWaitUntil(globalWaitUntil);\n}\n\nexport const handlerContextStore = new AsyncLocalStorage<ExecutionContext>();\nexport function registerHandlerAndGlobalWaitUntil(promise: Promise<unknown>) {\n\tconst handlerContext = handlerContextStore.getStore();\n\tif (handlerContext === undefined) {\n\t\tregisterGlobalWaitUntil(promise);\n\t} else {\n\t\t// `patchAndRunWithHandlerContext()` ensures handler `waitUntil()` calls\n\t\t// `registerGlobalWaitUntil()` too\n\t\thandlerContext.waitUntil(promise);\n\t}\n}\n","import { handlerContextStore, registerGlobalWaitUntil } from \"./wait-until\";\n\nconst patchedHandlerContexts = new WeakSet<ExecutionContext>();\n\n/**\n * Executes the given callback within the provided ExecutionContext,\n * patching the context to ensure that:\n *\n * - waitUntil calls are registered globally\n * - ctx.exports shows a warning if accessing missing exports\n */\nexport function patchAndRunWithHandlerContext<T>(\n\t/* mut */ ctx: ExecutionContext,\n\tcallback: () => T\n): T {\n\t// Ensure calls to `ctx.waitUntil()` registered with global wait-until\n\tif (!patchedHandlerContexts.has(ctx)) {\n\t\tpatchedHandlerContexts.add(ctx);\n\n\t\t// Patch `ctx.waitUntil()`\n\t\tconst originalWaitUntil = ctx.waitUntil;\n\t\tctx.waitUntil = (promise: Promise<unknown>) => {\n\t\t\tregisterGlobalWaitUntil(promise);\n\t\t\treturn originalWaitUntil.call(ctx, promise);\n\t\t};\n\n\t\t// Patch `ctx.exports`\n\t\tif (isCtxExportsEnabled(ctx.exports)) {\n\t\t\tObject.defineProperty(ctx, \"exports\", {\n\t\t\t\tvalue: getCtxExportsProxy(ctx.exports),\n\t\t\t});\n\t\t}\n\t}\n\treturn handlerContextStore.run(ctx, callback);\n}\n\n/**\n * Creates a proxy to the `ctx.exports` object that will warn the user if they attempt\n * to access an undefined property. This could be a valid mistake by the user or\n * it could mean that our static analysis of the main Worker's exports missed something.\n */\nexport function getCtxExportsProxy(\n\texports: Cloudflare.Exports\n): Cloudflare.Exports {\n\treturn new Proxy(exports, {\n\t\tget(target, p: keyof Cloudflare.Exports) {\n\t\t\tif (p in target) {\n\t\t\t\treturn target[p];\n\t\t\t}\n\t\t\tconsole.warn(\n\t\t\t\t`Attempted to access 'ctx.exports.${p}', which was not defined for the main Worker.\\n` +\n\t\t\t\t\t`Check that '${p}' is exported as an entry-point from the Worker.\\n` +\n\t\t\t\t\t`The '@cloudflare/vitest-plugin' integration tries to infer these exports by analyzing the source code of the main Worker.\\n`\n\t\t\t);\n\t\t\treturn undefined;\n\t\t},\n\t});\n}\n\n/**\n * Returns true if `ctx.exports` is enabled via compatibility flags.\n */\nexport function isCtxExportsEnabled(\n\texports: Cloudflare.Exports | undefined\n): exports is Cloudflare.Exports {\n\treturn (\n\t\t(globalThis as unknown as { Cloudflare: Cloudflare }).Cloudflare\n\t\t\t?.compatibilityFlags.enable_ctx_exports && exports !== undefined\n\t);\n}\n","import assert from \"node:assert\";\nimport {\n\tDurableObject as DurableObjectClass,\n\tenv as runtimeEnv,\n\tWorkerEntrypoint,\n\tWorkflowEntrypoint,\n} from \"cloudflare:workers\";\nimport { maybeHandleRunRequest, runInRunnerObject } from \"./durable-objects\";\nimport { getResolvedMainPath } from \"./env\";\nimport { patchAndRunWithHandlerContext } from \"./patch-ctx\";\n\n// =============================================================================\n// Common Entrypoint Helpers\n// =============================================================================\n\n/**\n * Internal method for importing a module using Vite's transformation and\n * execution pipeline. Can be called from any I/O context, and will ensure the\n * request is run from within the `__VITEST_POOL_WORKERS_RUNNER_DURABLE_OBJECT__`.\n */\nasync function importModule(\n\tspecifier: string\n): Promise<Record<string, unknown>> {\n\t/**\n\t * We need to run this import inside the Runner Object, or we get errors like:\n\t * - The Workers runtime canceled this request because it detected that your Worker's code had hung and would never generate a response. Refer to: https://developers.cloudflare.com/workers/observability/errors/\n\t * - Cannot perform I/O on behalf of a different Durable Object. I/O objects (such as streams, request/response bodies, and others) created in the context of one Durable Object cannot be accessed from a different Durable Object in the same isolate. This is a limitation of Cloudflare Workers which allows us to improve overall performance.\n\t */\n\treturn runInRunnerObject(() => {\n\t\treturn __vitest_mocker__.moduleRunner.import(specifier);\n\t});\n}\n\nconst IGNORED_KEYS = [\"self\"];\n\n/**\n * Create a class extending `superClass` with a `Proxy` as a `prototype`.\n * Unknown accesses on the `prototype` will defer to `getUnknownPrototypeKey()`.\n * `workerd` will only look for RPC methods/properties on the prototype, not the\n * instance. This helps avoid accidentally exposing things over RPC, but makes\n * things a little trickier for us...\n */\nfunction createProxyPrototypeClass<\n\tT extends\n\t\t| typeof WorkerEntrypoint\n\t\t| typeof DurableObjectClass\n\t\t| typeof WorkflowEntrypoint,\n\tExtraPrototype = unknown,\n>(\n\tsuperClass: T,\n\tgetUnknownPrototypeKey: (key: string) => unknown\n): T & { prototype: ExtraPrototype } {\n\t// Build a class with a \"Proxy\"-prototype, so we can intercept RPC calls\n\tfunction Class(...args: ConstructorParameters<typeof superClass>) {\n\t\t// Delay proxying prototype until construction, so workerd sees this as a\n\t\t// regular class when introspecting it. This check fails if we don't do this:\n\t\t// https://github.com/cloudflare/workerd/blob/9e915ed637d65adb3c57522607d2cd8b8d692b6b/src/workerd/io/worker.c%2B%2B#L1920-L1921\n\t\tClass.prototype = new Proxy(Class.prototype, {\n\t\t\tget(target, key, receiver) {\n\t\t\t\tconst value = Reflect.get(target, key, receiver);\n\t\t\t\tif (value !== undefined) {\n\t\t\t\t\treturn value;\n\t\t\t\t}\n\t\t\t\t// noinspection SuspiciousTypeOfGuard\n\t\t\t\tif (typeof key === \"symbol\" || IGNORED_KEYS.includes(key)) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn getUnknownPrototypeKey.call(receiver, key as string);\n\t\t\t},\n\t\t});\n\n\t\treturn Reflect.construct(superClass, args, Class);\n\t}\n\n\tReflect.setPrototypeOf(Class.prototype, superClass.prototype);\n\tReflect.setPrototypeOf(Class, superClass);\n\n\treturn Class as unknown as T & { prototype: ExtraPrototype };\n}\n\n/**\n * Only properties and methods declared on the prototype can be accessed over\n * RPC. This function throws a helpful error message if a property isn't\n * defined. Note we need to distinguish between a property that returns\n * `undefined` and something not being defined at all.\n */\nfunction assertRPCPropertyAccessible(\n\tctor: WorkerEntrypointConstructor | DurableObjectConstructor,\n\tinstance:\n\t\t| WorkerEntrypoint<Record<string, unknown> | Cloudflare.Env>\n\t\t| DurableObjectClass<Record<string, unknown> | Cloudflare.Env>,\n\tkey: string\n): void {\n\tconst prototypeHasKey = Reflect.has(ctor.prototype, key);\n\tif (!prototypeHasKey) {\n\t\tconst quotedKey = JSON.stringify(key);\n\t\tconst instanceHasKey = Reflect.has(instance, key);\n\t\tlet message = \"\";\n\t\tif (instanceHasKey) {\n\t\t\tmessage = [\n\t\t\t\t`The RPC receiver's prototype does not implement ${quotedKey}, but the receiver instance does.`,\n\t\t\t\t\"Only properties and methods defined on the prototype can be accessed over RPC.\",\n\t\t\t\t`Ensure properties are declared like \\`get ${key}() { ... }\\` instead of \\`${key} = ...\\`,`,\n\t\t\t\t`and methods are declared like \\`${key}() { ... }\\` instead of \\`${key} = () => { ... }\\`.`,\n\t\t\t].join(\"\\n\");\n\t\t} else {\n\t\t\tmessage = `The RPC receiver does not implement ${quotedKey}.`;\n\t\t}\n\t\tthrow new TypeError(message);\n\t}\n}\n\nfunction getRPCProperty(\n\tctor: WorkerEntrypointConstructor | DurableObjectConstructor,\n\tinstance:\n\t\t| WorkerEntrypoint<Record<string, unknown> | Cloudflare.Env>\n\t\t| DurableObjectClass<Record<string, unknown> | Cloudflare.Env>,\n\tkey: string\n): unknown {\n\tassertRPCPropertyAccessible(ctor, instance, key);\n\t// `receiver` is the value of `this` provided if a getter is encountered\n\treturn Reflect.get(/* target */ ctor.prototype, key, /* receiver */ instance);\n}\n\ntype InvocationQueueOwner =\n\t| WorkerEntrypoint<Cloudflare.Env>\n\t| DurableObjectClass<Cloudflare.Env>\n\t| WorkflowEntrypoint<Cloudflare.Env>;\n\n/**\n * When calling RPC methods dynamically, we don't know whether the `property`\n * returned from `getSELFRPCProperty()` or `getDurableObjectRPCProperty()` below\n * is just a property or a method. If we just returned `property`, but the\n * client tried to call it as a method, `workerd` would throw an \"x is not a\n * function\" error.\n *\n * Instead, we return a *callable, custom thenable*. This behaves like a\n * function and a `Promise`! If `workerd` calls it, we'll wait for the promise\n * to resolve then forward the call. Otherwise, this just appears like a regular\n * async property. Note all client calls are async, so converting sync\n * properties and methods to async is fine here.\n *\n * Unfortunately, wrapping `property` with a `Proxy` and an `apply()` trap gives\n * `TypeError: Method Promise.prototype.then called on incompatible receiver #<Promise>`. :(\n */\nfunction getRPCPropertyCallableThenable(\n\tkey: string,\n\tproperty: Promise<unknown>,\n\tqueueOwner: InvocationQueueOwner\n) {\n\tconst fn = async function (...args: unknown[]) {\n\t\treturn enqueueInvocation(queueOwner, async (release) => {\n\t\t\ttry {\n\t\t\t\tconst maybeFn = await property;\n\t\t\t\tif (typeof maybeFn === \"function\") {\n\t\t\t\t\treturn maybeFn(...args);\n\t\t\t\t} else {\n\t\t\t\t\tthrow new TypeError(`${JSON.stringify(key)} is not a function.`);\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\trelease();\n\t\t\t}\n\t\t});\n\t} as Promise<unknown> & ((...args: unknown[]) => Promise<unknown>);\n\tfn.then = (onFulfilled, onRejected) => property.then(onFulfilled, onRejected);\n\tfn.catch = (onRejected) => property.catch(onRejected);\n\tfn.finally = (onFinally) => property.finally(onFinally);\n\treturn fn;\n}\n\nconst invocationQueues = new WeakMap<InvocationQueueOwner, Promise<void>>();\n\n/**\n * Preserve the order in which async wrapper invocations begin executing.\n *\n * Resolving a property like `stub.method`, or ensuring a Durable Object handler\n * instance, may need to import user modules or instantiate wrapper objects. If\n * several calls are fired synchronously, those async steps can otherwise\n * complete out of order before the actual user code is invoked. The queue is\n * released as soon as invocation starts, so async completions can still run\n * concurrently.\n */\nasync function enqueueInvocation<T>(\n\towner: InvocationQueueOwner,\n\tcallback: (release: () => void) => Promise<T>\n): Promise<T> {\n\tconst previous = invocationQueues.get(owner) ?? Promise.resolve();\n\tlet releaseStarted: (() => void) | undefined;\n\tconst started = new Promise<void>((resolve) => {\n\t\treleaseStarted = resolve;\n\t});\n\tconst release = () => {\n\t\tconst releaseStartedFn = releaseStarted;\n\t\tif (releaseStartedFn !== undefined) {\n\t\t\treleaseStartedFn();\n\t\t}\n\t};\n\tconst result = previous.catch(() => {}).then(() => callback(release));\n\tinvocationQueues.set(owner, started);\n\treturn result;\n}\n\n/**\n * `ctx` and `env` are defined as `protected` within `WorkerEntrypoint` and\n * `DurableObjectClass`. Usually this isn't a problem, as `protected` members\n * can be accessed from subclasses defined with `class extends` keywords.\n * Unfortunately, we have to define our classes with a `Proxy` prototype to\n * support forwarding RPC. This prevents us accessing `protected` members.\n * Instead, we define this function to extract these members, and provide type\n * safety for callers.\n */\nfunction getEntrypointState(instance: WorkerEntrypoint<Cloudflare.Env>): {\n\tctx: ExecutionContext;\n\tenv: Cloudflare.Env;\n};\nfunction getEntrypointState(instance: DurableObjectClass<Cloudflare.Env>): {\n\tctx: DurableObjectState;\n\tenv: Cloudflare.Env;\n};\nfunction getEntrypointState(\n\tinstance:\n\t\t| WorkerEntrypoint<Cloudflare.Env>\n\t\t| DurableObjectClass<Cloudflare.Env>\n) {\n\treturn instance as unknown as {\n\t\tctx: ExecutionContext | DurableObjectState;\n\t\tenv: Cloudflare.Env;\n\t};\n}\n\nconst WORKER_ENTRYPOINT_KEYS = [\n\t\"connect\",\n\t\"tailStream\",\n\t\"fetch\",\n\t\"tail\",\n\t\"trace\",\n\t\"scheduled\",\n\t\"queue\",\n\t\"test\",\n\t\"email\",\n] as const;\nconst DURABLE_OBJECT_KEYS = [\n\t\"connect\",\n\t\"fetch\",\n\t\"alarm\",\n\t\"webSocketMessage\",\n\t\"webSocketClose\",\n\t\"webSocketError\",\n] as const;\n// Handlers `workerd` treats as optional: when a Durable Object doesn't define\n// one, the corresponding event is silently dropped. We can't leave them off the\n// wrapper's prototype to get that behaviour for free — the prototype is built\n// before user code is loaded, so `workerd` always sees a handler and always\n// dispatches. The no-op has to be reproduced here instead.\n//\n// `alarm()` deliberately isn't in this set: `workerd` rejects `setAlarm()` up\n// front on a class with no `alarm()` handler, so a missing one is a real error.\nconst OPTIONAL_DURABLE_OBJECT_KEYS: ReadonlySet<\n\t(typeof DURABLE_OBJECT_KEYS)[number]\n> = new Set([\"webSocketMessage\", \"webSocketClose\", \"webSocketError\"] as const);\n\n// This type will grab the keys from T and remove \"branded\" keys\ntype UnbrandedKeys<T> = Exclude<keyof T, `__${string}_BRAND`>;\n\n// Check that we've included all possible keys\n// noinspection JSUnusedLocalSymbols\nconst _workerEntrypointExhaustive: (typeof WORKER_ENTRYPOINT_KEYS)[number] =\n\tundefined as unknown as UnbrandedKeys<WorkerEntrypoint<Cloudflare.Env>>;\n// noinspection JSUnusedLocalSymbols\nconst _durableObjectExhaustive: (typeof DURABLE_OBJECT_KEYS)[number] =\n\tundefined as unknown as UnbrandedKeys<DurableObjectClass<Cloudflare.Env>>;\n\n// =============================================================================\n// `WorkerEntrypoint` wrappers\n// =============================================================================\n\n// `WorkerEntrypoint` is `abstract`, so we need to cast before constructing\ntype WorkerEntrypointConstructor = {\n\tnew (\n\t\t...args: ConstructorParameters<typeof WorkerEntrypoint>\n\t): WorkerEntrypoint;\n};\n\n/**\n * Get the export to use for `entrypoint`. This is used for the `SELF` service\n * binding in `cloudflare:test`, which sets `entrypoint` to \"default\".\n * This requires importing the `main` module with Vite.\n */\nasync function getWorkerEntrypointExport(\n\tenv: Cloudflare.Env,\n\tentrypoint: string\n): Promise<{ mainPath: string; entrypointValue: unknown }> {\n\tconst mainPath = getResolvedMainPath(\"service\");\n\tconst mainModule = await importModule(mainPath);\n\tconst entrypointValue =\n\t\ttypeof mainModule === \"object\" &&\n\t\tmainModule !== null &&\n\t\tentrypoint in mainModule &&\n\t\tmainModule[entrypoint];\n\tif (!entrypointValue) {\n\t\tconst message =\n\t\t\t`${mainPath} does not export a ${entrypoint} entrypoint. \\`@cloudflare/vitest-plugin\\` does not support service workers or named entrypoints for \\`SELF\\`.\\n` +\n\t\t\t\"If you're using service workers, please migrate to the modules format: https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/\";\n\t\tthrow new TypeError(message);\n\t}\n\treturn { mainPath, entrypointValue };\n}\n\n/**\n * Get a property named `key` from the user's `WorkerEntrypoint`. `wrapper` here\n * is an instance of a `WorkerEntrypoint` wrapper (i.e. the return value of\n * `createWorkerEntrypointWrapper()`). This requires importing the `main` module\n * with Vite, so will always return a `Promise.`\n */\nasync function getWorkerEntrypointRPCProperty(\n\twrapper: WorkerEntrypoint<Cloudflare.Env>,\n\tentrypoint: string,\n\tkey: string\n): Promise<unknown> {\n\tconst { ctx } = getEntrypointState(wrapper);\n\tconst { mainPath, entrypointValue } = await getWorkerEntrypointExport(\n\t\truntimeEnv as Cloudflare.Env,\n\t\tentrypoint\n\t);\n\t// Ensure constructor and properties execute with ctx `AsyncLocalStorage` set\n\treturn patchAndRunWithHandlerContext(ctx, () => {\n\t\t// Use the dynamic env from `cloudflare:workers` to respect `withEnv()`\n\t\tconst env = runtimeEnv as Cloudflare.Env;\n\t\tconst expectedWorkerEntrypointMessage = `Expected ${entrypoint} export of ${mainPath} to be a subclass of \\`WorkerEntrypoint\\` for RPC`;\n\t\tif (typeof entrypointValue !== \"function\") {\n\t\t\tthrow new TypeError(expectedWorkerEntrypointMessage);\n\t\t}\n\t\tconst ctor = entrypointValue as WorkerEntrypointConstructor;\n\t\tconst instance = new ctor(ctx, env);\n\t\t// noinspection SuspiciousTypeOfGuard\n\t\tif (!(instance instanceof WorkerEntrypoint)) {\n\t\t\tthrow new TypeError(expectedWorkerEntrypointMessage);\n\t\t}\n\n\t\tconst value = getRPCProperty(ctor, instance, key);\n\t\tif (typeof value === \"function\") {\n\t\t\t// If this is a function, ensure it executes with ctx `AsyncLocalStorage`\n\t\t\t// set, and with a correctly bound `this`\n\t\t\treturn (...args: unknown[]) =>\n\t\t\t\tpatchAndRunWithHandlerContext(ctx, () => value.apply(instance, args));\n\t\t} else {\n\t\t\treturn value;\n\t\t}\n\t});\n}\n\nexport function createWorkerEntrypointWrapper(\n\tentrypoint: string\n): typeof WorkerEntrypoint {\n\tconst Wrapper = createProxyPrototypeClass(\n\t\tWorkerEntrypoint,\n\t\tfunction (this: WorkerEntrypoint<Cloudflare.Env>, key) {\n\t\t\t// All `ExportedHandler` keys are reserved and cannot be called over RPC\n\t\t\tif ((DURABLE_OBJECT_KEYS as readonly string[]).includes(key)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst property = getWorkerEntrypointRPCProperty(this, entrypoint, key);\n\t\t\treturn getRPCPropertyCallableThenable(key, property, this);\n\t\t}\n\t);\n\n\t// Add prototype methods for all default handlers\n\tfor (const key of WORKER_ENTRYPOINT_KEYS) {\n\t\tWrapper.prototype[key] = async function (\n\t\t\tthis: WorkerEntrypoint<Cloudflare.Env>,\n\t\t\tthing: unknown\n\t\t) {\n\t\t\tconst { mainPath, entrypointValue } = await getWorkerEntrypointExport(\n\t\t\t\tthis.env,\n\t\t\t\tentrypoint\n\t\t\t);\n\n\t\t\treturn patchAndRunWithHandlerContext(this.ctx, () => {\n\t\t\t\tif (typeof entrypointValue === \"object\" && entrypointValue !== null) {\n\t\t\t\t\t// Assuming the user has defined an `ExportedHandler`\n\t\t\t\t\tconst maybeFn = (entrypointValue as Record<string, unknown>)[key];\n\t\t\t\t\tif (typeof maybeFn === \"function\") {\n\t\t\t\t\t\treturn maybeFn.call(entrypointValue, thing, runtimeEnv, this.ctx);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst message = `Expected ${entrypoint} export of ${mainPath} to define a \\`${key}()\\` function`;\n\t\t\t\t\t\tthrow new TypeError(message);\n\t\t\t\t\t}\n\t\t\t\t} else if (typeof entrypointValue === \"function\") {\n\t\t\t\t\t// Assuming the user has defined a `WorkerEntrypoint` subclass\n\t\t\t\t\tconst ctor = entrypointValue as WorkerEntrypointConstructor;\n\t\t\t\t\tconst instance = new ctor(this.ctx, runtimeEnv);\n\t\t\t\t\t// noinspection SuspiciousTypeOfGuard\n\t\t\t\t\tif (!(instance instanceof WorkerEntrypoint)) {\n\t\t\t\t\t\tconst message = `Expected ${entrypoint} export of ${mainPath} to be a subclass of \\`WorkerEntrypoint\\``;\n\t\t\t\t\t\tthrow new TypeError(message);\n\t\t\t\t\t}\n\t\t\t\t\tconst maybeFn = instance[key];\n\t\t\t\t\tif (typeof maybeFn === \"function\") {\n\t\t\t\t\t\treturn (maybeFn as (arg: unknown) => unknown).call(instance, thing);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst message = `Expected ${entrypoint} export of ${mainPath} to define a \\`${key}()\\` method`;\n\t\t\t\t\t\tthrow new TypeError(message);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Assuming the user has messed up\n\t\t\t\t\tconst message = `Expected ${entrypoint} export of ${mainPath} to be an object or a class, got ${entrypointValue}`;\n\t\t\t\t\tthrow new TypeError(message);\n\t\t\t\t}\n\t\t\t});\n\t\t};\n\t}\n\treturn Wrapper;\n}\n\n// =============================================================================\n// `DurableObject` wrappers\n// =============================================================================\n\ntype DurableObjectConstructor = {\n\tnew (\n\t\t...args: ConstructorParameters<typeof DurableObjectClass>\n\t): DurableObject | DurableObjectClass;\n};\n\nconst kInstanceConstructor = Symbol(\"kInstanceConstructor\");\nconst kInstance = Symbol(\"kInstance\");\nconst kEnsureInstance = Symbol(\"kEnsureInstance\");\ntype DurableObjectWrapperExtraPrototype = {\n\t[kInstanceConstructor]: DurableObjectConstructor;\n\t[kInstance]:\n\t\t| DurableObject\n\t\t| DurableObjectClass<Record<string, unknown> | Cloudflare.Env>;\n\t[kEnsureInstance](): Promise<{\n\t\tmainPath: string;\n\t\tinstanceCtor: DurableObjectConstructor;\n\t\tinstance:\n\t\t\t| DurableObject\n\t\t\t| DurableObjectClass<Record<string, unknown> | Cloudflare.Env>;\n\t}>;\n};\ntype DurableObjectWrapper = DurableObjectClass<Cloudflare.Env> &\n\tDurableObjectWrapperExtraPrototype;\n\nasync function getDurableObjectRPCProperty(\n\twrapper: DurableObjectWrapper,\n\tclassName: string,\n\tkey: string\n): Promise<unknown> {\n\tconst { mainPath, instanceCtor, instance } = await wrapper[kEnsureInstance]();\n\tif (!(instance instanceof DurableObjectClass)) {\n\t\tconst message = `Expected ${className} exported by ${mainPath} be a subclass of \\`DurableObject\\` for RPC`;\n\t\tthrow new TypeError(message);\n\t}\n\tassertRPCPropertyAccessible(instanceCtor, instance, key);\n\t// `workerd` rejects constructor-assigned overrides of RPC methods, but a\n\t// constructor may return a Proxy that wraps a method from its prototype.\n\tif (Object.hasOwn(instance, key)) {\n\t\tthrow new TypeError(\n\t\t\t`The RPC receiver does not implement the method ${JSON.stringify(key)}.`\n\t\t);\n\t}\n\tconst value = Reflect.get(instance, key, instance);\n\tif (typeof value === \"function\") {\n\t\t// If this is a function, ensure correctly bound `this`\n\t\treturn value.bind(instance);\n\t} else {\n\t\treturn value;\n\t}\n}\n\nexport function createDurableObjectWrapper(\n\tclassName: string\n): typeof DurableObjectClass {\n\tconst Wrapper = createProxyPrototypeClass<\n\t\ttypeof DurableObjectClass,\n\t\tDurableObjectWrapperExtraPrototype\n\t>(DurableObjectClass, function (this: DurableObjectWrapper, key) {\n\t\t// All `ExportedHandler` keys are reserved and cannot be called over RPC\n\t\tif ((WORKER_ENTRYPOINT_KEYS as readonly string[]).includes(key)) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst property = getDurableObjectRPCProperty(this, className, key);\n\t\treturn getRPCPropertyCallableThenable(key, property, this);\n\t});\n\n\tWrapper.prototype[kEnsureInstance] = async function (\n\t\tthis: DurableObjectWrapper\n\t) {\n\t\tconst { ctx, env } = getEntrypointState(this);\n\t\tconst mainPath = getResolvedMainPath(\"Durable Object\");\n\t\t// `ensureInstance()` may be called multiple times concurrently.\n\t\t// We're assuming `importModule()` will only import the module once.\n\t\tconst mainModule = await importModule(mainPath);\n\t\tconst constructor = mainModule[className];\n\t\tif (typeof constructor !== \"function\") {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${mainPath} does not export a ${className} Durable Object`\n\t\t\t);\n\t\t}\n\t\tthis[kInstanceConstructor] ??= constructor as DurableObjectConstructor;\n\t\tif (this[kInstanceConstructor] !== constructor) {\n\t\t\t// This would be if the module was invalidated\n\t\t\t// (i.e. source file changed), then the Durable Object was `fetch()`ed\n\t\t\t// again. We reset all Durable Object instances between each test, so it's\n\t\t\t// unlikely multiple constructors would be used by the same instance,\n\t\t\t// unless the user did something funky with Durable Objects outside tests.\n\t\t\tawait ctx.blockConcurrencyWhile<never>(() => {\n\t\t\t\t// Throw inside `blockConcurrencyWhile()` to abort this object\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`${mainPath} changed, invalidating this Durable Object. ` +\n\t\t\t\t\t\t\"Please retry the `DurableObjectStub#fetch()` call.\"\n\t\t\t\t);\n\t\t\t});\n\t\t\tassert.fail(\"Unreachable\");\n\t\t}\n\t\tif (this[kInstance] === undefined) {\n\t\t\tthis[kInstance] = new this[kInstanceConstructor](ctx, env);\n\t\t\t// Wait for any `blockConcurrencyWhile()`s in the constructor to complete\n\t\t\tawait ctx.blockConcurrencyWhile(async () => {});\n\t\t}\n\t\treturn {\n\t\t\tmainPath,\n\t\t\tinstanceCtor: this[kInstanceConstructor],\n\t\t\tinstance: this[kInstance],\n\t\t};\n\t};\n\n\t// Add prototype method for `fetch` handler to handle `runInDurableObject()`s\n\tWrapper.prototype.fetch = async function (\n\t\tthis: DurableObjectWrapper,\n\t\trequest: Request\n\t) {\n\t\tconst { ctx } = getEntrypointState(this);\n\n\t\t// Make sure we've initialised user code\n\t\tconst { mainPath, instance } = await this[kEnsureInstance]();\n\n\t\t// If this is an internal Durable Object action, handle it...\n\t\tconst response = await maybeHandleRunRequest(request, instance, ctx);\n\t\tif (response !== undefined) {\n\t\t\treturn response;\n\t\t}\n\n\t\t// Otherwise, pass through to the user code\n\t\tif (instance.fetch === undefined) {\n\t\t\tconst message = `${className} exported by ${mainPath} does not define a \\`fetch()\\` method`;\n\t\t\tthrow new TypeError(message);\n\t\t}\n\t\treturn instance.fetch(request);\n\t};\n\n\t// Add prototype methods for all other default handlers\n\tfor (const key of DURABLE_OBJECT_KEYS) {\n\t\tif (key === \"fetch\") {\n\t\t\tcontinue;\n\t\t} // `fetch()` has special handling above\n\t\tWrapper.prototype[key] = async function (\n\t\t\tthis: DurableObjectWrapper,\n\t\t\t...args: unknown[]\n\t\t) {\n\t\t\treturn enqueueInvocation(this, async (release) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst { mainPath, instance } = await this[kEnsureInstance]();\n\t\t\t\t\tconst maybeFn = instance[key];\n\t\t\t\t\tif (typeof maybeFn === \"function\") {\n\t\t\t\t\t\treturn (maybeFn as (...a: unknown[]) => void).apply(instance, args);\n\t\t\t\t\t} else if (OPTIONAL_DURABLE_OBJECT_KEYS.has(key)) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst message = `${className} exported by ${mainPath} does not define a \\`${key}()\\` method`;\n\t\t\t\t\t\tthrow new TypeError(message);\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\trelease();\n\t\t\t\t}\n\t\t\t});\n\t\t};\n\t}\n\n\treturn Wrapper;\n}\n\n// =============================================================================\n// `WorkflowEntrypoint` wrappers\n// =============================================================================\n\ntype WorkflowEntrypointConstructor = {\n\tnew (\n\t\t...args: ConstructorParameters<typeof WorkflowEntrypoint>\n\t): WorkflowEntrypoint;\n};\n\nexport function createWorkflowEntrypointWrapper(entrypoint: string) {\n\tconst Wrapper = createProxyPrototypeClass(\n\t\tWorkflowEntrypoint,\n\t\tfunction (this: WorkflowEntrypoint<Cloudflare.Env>, key) {\n\t\t\t// only Workflow `run` should be exposed over RPC\n\t\t\tif (![\"run\"].includes(key)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst property = getWorkerEntrypointRPCProperty(\n\t\t\t\tthis as unknown as WorkerEntrypoint<Cloudflare.Env>,\n\t\t\t\tentrypoint,\n\t\t\t\tkey\n\t\t\t);\n\t\t\treturn getRPCPropertyCallableThenable(key, property, this);\n\t\t}\n\t);\n\n\tWrapper.prototype.run = async function (\n\t\tthis: WorkflowEntrypoint<Cloudflare.Env>,\n\t\t...args\n\t) {\n\t\tconst { mainPath, entrypointValue } = await getWorkerEntrypointExport(\n\t\t\truntimeEnv,\n\t\t\tentrypoint\n\t\t);\n\t\t// workflow entrypoint value should always be a constructor\n\t\tif (typeof entrypointValue === \"function\") {\n\t\t\t// Assuming the user has defined a `WorkflowEntrypoint` subclass\n\t\t\tconst ctor = entrypointValue as WorkflowEntrypointConstructor;\n\t\t\tconst instance = new ctor(this.ctx, runtimeEnv);\n\t\t\t// noinspection SuspiciousTypeOfGuard\n\t\t\tif (!(instance instanceof WorkflowEntrypoint)) {\n\t\t\t\tconst message = `Expected ${entrypoint} export of ${mainPath} to be a subclass of \\`WorkflowEntrypoint\\``;\n\t\t\t\tthrow new TypeError(message);\n\t\t\t}\n\t\t\tconst maybeFn = instance[\"run\"];\n\t\t\tif (typeof maybeFn === \"function\") {\n\t\t\t\treturn patchAndRunWithHandlerContext(this.ctx, () =>\n\t\t\t\t\tmaybeFn.call(instance, ...args)\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tconst message = `Expected ${entrypoint} export of ${mainPath} to define a \\`run()\\` method, but got ${typeof maybeFn}`;\n\t\t\t\tthrow new TypeError(message);\n\t\t\t}\n\t\t} else {\n\t\t\t// Assuming the user has messed up\n\t\t\tconst message = `Expected ${entrypoint} export of ${mainPath} to be a subclass of \\`WorkflowEntrypoint\\`, but got ${entrypointValue}`;\n\t\t\tthrow new TypeError(message);\n\t\t}\n\t};\n\n\treturn Wrapper;\n}\n","import { exports } from \"cloudflare:workers\";\nimport { env } from \"./env\";\nimport { getCtxExportsProxy, isCtxExportsEnabled } from \"./patch-ctx\";\nimport { registerGlobalWaitUntil, waitForWaitUntil } from \"./wait-until\";\n\n// `workerd` doesn't allow these internal classes to be constructed directly.\n// To replicate this behaviour require this unique symbol to be specified as the\n// first constructor argument. If this is missing, throw `Illegal invocation`.\nconst kConstructFlag = Symbol(\"kConstructFlag\");\n\n// See public facing `cloudflare:test` types for docs.\n\n// =============================================================================\n// `ExecutionContext`\n// =============================================================================\n\nconst kWaitUntil = Symbol(\"kWaitUntil\");\nclass ExecutionContext {\n\t// https://github.com/cloudflare/workerd/blob/v1.20231218.0/src/workerd/api/global-scope.h#L168\n\t[kWaitUntil]: unknown[] = [];\n\n\tconstructor(flag: typeof kConstructFlag) {\n\t\tif (flag !== kConstructFlag) {\n\t\t\tthrow new TypeError(\"Illegal constructor\");\n\t\t}\n\t}\n\n\t// Expose the ctx.exports from the main \"SELF\" Worker if there is one.\n\treadonly exports = isCtxExportsEnabled(exports)\n\t\t? getCtxExportsProxy(exports)\n\t\t: undefined;\n\n\twaitUntil(promise: unknown) {\n\t\tif (!(this instanceof ExecutionContext)) {\n\t\t\tthrow new TypeError(\"Illegal invocation\");\n\t\t}\n\t\tthis[kWaitUntil].push(promise);\n\t\tregisterGlobalWaitUntil(promise);\n\t}\n\n\tpassThroughOnException(): void {}\n}\nexport function createExecutionContext(): ExecutionContext {\n\treturn new ExecutionContext(kConstructFlag);\n}\n\nfunction isExecutionContextLike(v: unknown): v is { [kWaitUntil]: unknown[] } {\n\treturn (\n\t\ttypeof v === \"object\" &&\n\t\tv !== null &&\n\t\tkWaitUntil in v &&\n\t\tArray.isArray(v[kWaitUntil])\n\t);\n}\nexport async function waitOnExecutionContext(ctx: unknown): Promise<void> {\n\tif (!isExecutionContextLike(ctx)) {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'getWaitUntil': parameter 1 is not of type 'ExecutionContext'.\\n\" +\n\t\t\t\t\"You must call 'createExecutionContext()' or 'createPagesEventContext()' to get an 'ExecutionContext' instance.\"\n\t\t);\n\t}\n\treturn waitForWaitUntil(ctx[kWaitUntil]);\n}\n\n// =============================================================================\n// `ScheduledController`\n// =============================================================================\n\nclass ScheduledController {\n\t// https://github.com/cloudflare/workerd/blob/v1.20231218.0/src/workerd/api/scheduled.h#L35\n\treadonly scheduledTime!: number;\n\treadonly cron!: string;\n\n\tconstructor(flag: typeof kConstructFlag, options?: FetcherScheduledOptions) {\n\t\tif (flag !== kConstructFlag) {\n\t\t\tthrow new TypeError(\"Illegal constructor\");\n\t\t}\n\n\t\tconst scheduledTime = Number(options?.scheduledTime ?? Date.now());\n\t\tconst cron = String(options?.cron ?? \"\");\n\n\t\t// Match `JSG_READONLY_INSTANCE_PROPERTY` behaviour\n\t\tObject.defineProperties(this, {\n\t\t\tscheduledTime: {\n\t\t\t\tget() {\n\t\t\t\t\treturn scheduledTime;\n\t\t\t\t},\n\t\t\t},\n\t\t\tcron: {\n\t\t\t\tget() {\n\t\t\t\t\treturn cron;\n\t\t\t\t},\n\t\t\t},\n\t\t});\n\t}\n\n\tnoRetry(): void {\n\t\tif (!(this instanceof ScheduledController)) {\n\t\t\tthrow new TypeError(\"Illegal invocation\");\n\t\t}\n\t}\n}\nexport function createScheduledController(\n\toptions?: FetcherScheduledOptions\n): ScheduledController {\n\tif (options !== undefined && typeof options !== \"object\") {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'createScheduledController': parameter 1 is not of type 'ScheduledOptions'.\"\n\t\t);\n\t}\n\treturn new ScheduledController(kConstructFlag, options);\n}\n\n// =============================================================================\n// `MessageBatch`\n// =============================================================================\n\nconst kRetry = Symbol(\"kRetry\");\nconst kAck = Symbol(\"kAck\");\nconst kRetryAll = Symbol(\"kRetryAll\");\nconst kAckAll = Symbol(\"kAckAll\");\nclass QueueMessage<Body = unknown> /* Message */ {\n\t// https://github.com/cloudflare/workerd/blob/v1.20231218.0/src/workerd/api/queue.h#L113\n\treadonly #controller: QueueController;\n\treadonly id!: string;\n\treadonly timestamp!: Date;\n\treadonly body!: Body;\n\treadonly attempts!: number;\n\t[kRetry] = false;\n\t[kAck] = false;\n\n\tconstructor(\n\t\tflag: typeof kConstructFlag,\n\t\tcontroller: QueueController,\n\t\tmessage: ServiceBindingQueueMessage<Body>\n\t) {\n\t\tif (flag !== kConstructFlag) {\n\t\t\tthrow new TypeError(\"Illegal constructor\");\n\t\t}\n\t\tthis.#controller = controller;\n\n\t\tconst id = String(message.id);\n\n\t\tlet timestamp: Date;\n\t\t// noinspection SuspiciousTypeOfGuard\n\t\tif (typeof message.timestamp === \"number\") {\n\t\t\ttimestamp = new Date(message.timestamp);\n\t\t} else if (message.timestamp instanceof Date) {\n\t\t\ttimestamp = new Date(message.timestamp.getTime()); // Prevent external mutations\n\t\t} else {\n\t\t\tthrow new TypeError(\n\t\t\t\t\"Incorrect type for the 'timestamp' field on 'ServiceBindingQueueMessage': the provided value is not of type 'date'.\"\n\t\t\t);\n\t\t}\n\n\t\tlet attempts: number;\n\t\t// noinspection SuspiciousTypeOfGuard\n\t\tif (typeof message.attempts === \"number\") {\n\t\t\tattempts = message.attempts;\n\t\t} else {\n\t\t\tthrow new TypeError(\n\t\t\t\t\"Incorrect type for the 'attempts' field on 'ServiceBindingQueueMessage': the provided value is not of type 'number'.\"\n\t\t\t);\n\t\t}\n\n\t\tif (\"serializedBody\" in message) {\n\t\t\tthrow new TypeError(\n\t\t\t\t\"Cannot use `serializedBody` with `createMessageBatch()`\"\n\t\t\t);\n\t\t}\n\t\tconst body = structuredClone(message.body); // Prevent external mutations\n\n\t\t// Match `JSG_READONLY_INSTANCE_PROPERTY` behaviour\n\t\tObject.defineProperties(this, {\n\t\t\tid: {\n\t\t\t\tget() {\n\t\t\t\t\treturn id;\n\t\t\t\t},\n\t\t\t},\n\t\t\ttimestamp: {\n\t\t\t\tget() {\n\t\t\t\t\treturn timestamp;\n\t\t\t\t},\n\t\t\t},\n\t\t\tbody: {\n\t\t\t\tget() {\n\t\t\t\t\treturn body;\n\t\t\t\t},\n\t\t\t},\n\t\t\tattempts: {\n\t\t\t\tget() {\n\t\t\t\t\treturn attempts;\n\t\t\t\t},\n\t\t\t},\n\t\t});\n\t}\n\n\tretry() {\n\t\tif (!(this instanceof QueueMessage)) {\n\t\t\tthrow new TypeError(\"Illegal invocation\");\n\t\t}\n\t\tif (this.#controller[kRetryAll]) {\n\t\t\treturn;\n\t\t}\n\t\tif (this.#controller[kAckAll]) {\n\t\t\tconsole.warn(\n\t\t\t\t`Received a call to retry() on message ${this.id} after ackAll() was already called. ` +\n\t\t\t\t\t\"Calling retry() on a message after calling ackAll() has no effect.\"\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (this[kAck]) {\n\t\t\tconsole.warn(\n\t\t\t\t`Received a call to retry() on message ${this.id} after ack() was already called. ` +\n\t\t\t\t\t\"Calling retry() on a message after calling ack() has no effect.\"\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tthis[kRetry] = true;\n\t}\n\n\tack() {\n\t\tif (!(this instanceof QueueMessage)) {\n\t\t\tthrow new TypeError(\"Illegal invocation\");\n\t\t}\n\t\tif (this.#controller[kAckAll]) {\n\t\t\treturn;\n\t\t}\n\t\tif (this.#controller[kRetryAll]) {\n\t\t\tconsole.warn(\n\t\t\t\t`Received a call to ack() on message ${this.id} after retryAll() was already called. ` +\n\t\t\t\t\t\"Calling ack() on a message after calling retryAll() has no effect.\"\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (this[kRetry]) {\n\t\t\tconsole.warn(\n\t\t\t\t`Received a call to ack() on message ${this.id} after retry() was already called. ` +\n\t\t\t\t\t\"Calling ack() on a message after calling retry() has no effect.\"\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tthis[kAck] = true;\n\t}\n}\nclass QueueController<Body = unknown> /* MessageBatch */ {\n\t// https://github.com/cloudflare/workerd/blob/v1.20231218.0/src/workerd/api/queue.h#L198\n\treadonly queue!: string;\n\treadonly messages!: QueueMessage<Body>[];\n\treadonly metadata!: MessageBatchMetadata;\n\t[kRetryAll] = false;\n\t[kAckAll] = false;\n\n\tconstructor(\n\t\tflag: typeof kConstructFlag,\n\t\tqueueOption: string,\n\t\tmessagesOption: ServiceBindingQueueMessage<Body>[]\n\t) {\n\t\tif (flag !== kConstructFlag) {\n\t\t\tthrow new TypeError(\"Illegal constructor\");\n\t\t}\n\n\t\tconst queue = String(queueOption);\n\t\tconst messages = messagesOption.map(\n\t\t\t(message) => new QueueMessage(kConstructFlag, this, message)\n\t\t);\n\t\tconst metadata: MessageBatchMetadata = {\n\t\t\tmetrics: {\n\t\t\t\tbacklogCount: 0,\n\t\t\t\tbacklogBytes: 0,\n\t\t\t\toldestMessageTimestamp: new Date(0),\n\t\t\t},\n\t\t};\n\n\t\t// Match `JSG_READONLY_INSTANCE_PROPERTY` behaviour\n\t\tObject.defineProperties(this, {\n\t\t\tqueue: {\n\t\t\t\tget() {\n\t\t\t\t\treturn queue;\n\t\t\t\t},\n\t\t\t},\n\t\t\tmessages: {\n\t\t\t\tget() {\n\t\t\t\t\treturn messages;\n\t\t\t\t},\n\t\t\t},\n\t\t\tmetadata: {\n\t\t\t\tget() {\n\t\t\t\t\treturn metadata;\n\t\t\t\t},\n\t\t\t},\n\t\t});\n\t}\n\n\tretryAll() {\n\t\tif (!(this instanceof QueueController)) {\n\t\t\tthrow new TypeError(\"Illegal invocation\");\n\t\t}\n\t\tif (this[kAckAll]) {\n\t\t\tconsole.warn(\n\t\t\t\t\"Received a call to retryAll() after ackAll() was already called. \" +\n\t\t\t\t\t\"Calling retryAll() after calling ackAll() has no effect.\"\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tthis[kRetryAll] = true;\n\t}\n\n\tackAll() {\n\t\tif (!(this instanceof QueueController)) {\n\t\t\tthrow new TypeError(\"Illegal invocation\");\n\t\t}\n\t\tif (this[kRetryAll]) {\n\t\t\tconsole.warn(\n\t\t\t\t\"Received a call to ackAll() after retryAll() was already called. \" +\n\t\t\t\t\t\"Calling ackAll() after calling retryAll() has no effect.\"\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tthis[kAckAll] = true;\n\t}\n}\nexport function createMessageBatch<Body = unknown>(\n\tqueueName: string,\n\tmessages: ServiceBindingQueueMessage<Body>[]\n): MessageBatch<Body> {\n\tif (arguments.length === 0) {\n\t\t// `queueName` will be coerced to a `string`, but it must be defined\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'createMessageBatch': parameter 1 is not of type 'string'.\"\n\t\t);\n\t}\n\tif (!Array.isArray(messages)) {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'createMessageBatch': parameter 2 is not of type 'Array'.\"\n\t\t);\n\t}\n\treturn new QueueController(kConstructFlag, queueName, messages);\n}\nexport async function getQueueResult(\n\tbatch: QueueController,\n\tctx: ExecutionContext\n): Promise<FetcherQueueResult> {\n\t// noinspection SuspiciousTypeOfGuard\n\tif (!(batch instanceof QueueController)) {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'getQueueResult': parameter 1 is not of type 'MessageBatch'.\\n\" +\n\t\t\t\t\"You must call 'createMessageBatch()' to get a 'MessageBatch' instance.\"\n\t\t);\n\t}\n\t// noinspection SuspiciousTypeOfGuard\n\tif (!(ctx instanceof ExecutionContext)) {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'getQueueResult': parameter 2 is not of type 'ExecutionContext'.\\n\" +\n\t\t\t\t\"You must call 'createExecutionContext()' to get an 'ExecutionContext' instance.\"\n\t\t);\n\t}\n\tawait waitOnExecutionContext(ctx);\n\n\tconst retryMessages: QueueRetryMessage[] = [];\n\tconst explicitAcks: string[] = [];\n\tfor (const message of batch.messages) {\n\t\tif (message[kRetry]) {\n\t\t\tretryMessages.push({ msgId: message.id });\n\t\t}\n\t\tif (message[kAck]) {\n\t\t\texplicitAcks.push(message.id);\n\t\t}\n\t}\n\treturn {\n\t\toutcome: \"ok\",\n\t\tretryBatch: {\n\t\t\tretry: batch[kRetryAll],\n\t\t},\n\t\tackAll: batch[kAckAll],\n\t\tretryMessages,\n\t\texplicitAcks,\n\t};\n}\n\n// =============================================================================\n// Pages Functions `EventContext`\n// =============================================================================\n\nfunction hasASSETSServiceBinding(\n\tvalue: Record<string, unknown>\n): value is Record<string, unknown> & { ASSETS: Fetcher } {\n\treturn (\n\t\t\"ASSETS\" in value &&\n\t\ttypeof value.ASSETS === \"object\" &&\n\t\tvalue.ASSETS !== null &&\n\t\t\"fetch\" in value.ASSETS &&\n\t\ttypeof value.ASSETS.fetch === \"function\"\n\t);\n}\n\ninterface EventContextInit {\n\trequest: Request<unknown, IncomingRequestCfProperties>;\n\tfunctionPath?: string;\n\tnext?(request: Request): Response | Promise<Response>;\n\tparams?: Record<string, string | string[]>;\n\tdata?: Record<string, unknown>;\n}\n\nexport function createPagesEventContext<F extends PagesFunction>(\n\topts: EventContextInit\n): Parameters<F>[0] & { [kWaitUntil]: unknown[] } {\n\tif (typeof opts !== \"object\" || opts === null) {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'createPagesEventContext': parameter 1 is not of type 'EventContextInit'.\"\n\t\t);\n\t}\n\tif (!(opts.request instanceof Request)) {\n\t\tthrow new TypeError(\n\t\t\t\"Incorrect type for the 'request' field on 'EventContextInit': the provided value is not of type 'Request'.\"\n\t\t);\n\t}\n\t// noinspection SuspiciousTypeOfGuard\n\tif (\n\t\topts.functionPath !== undefined &&\n\t\ttypeof opts.functionPath !== \"string\"\n\t) {\n\t\tthrow new TypeError(\n\t\t\t\"Incorrect type for the 'functionPath' field on 'EventContextInit': the provided value is not of type 'string'.\"\n\t\t);\n\t}\n\tif (opts.next !== undefined && typeof opts.next !== \"function\") {\n\t\tthrow new TypeError(\n\t\t\t\"Incorrect type for the 'next' field on 'EventContextInit': the provided value is not of type 'function'.\"\n\t\t);\n\t}\n\tif (\n\t\topts.params !== undefined &&\n\t\t!(typeof opts.params === \"object\" && opts.params !== null)\n\t) {\n\t\tthrow new TypeError(\n\t\t\t\"Incorrect type for the 'params' field on 'EventContextInit': the provided value is not of type 'object'.\"\n\t\t);\n\t}\n\tif (\n\t\topts.data !== undefined &&\n\t\t!(typeof opts.data === \"object\" && opts.data !== null)\n\t) {\n\t\tthrow new TypeError(\n\t\t\t\"Incorrect type for the 'data' field on 'EventContextInit': the provided value is not of type 'object'.\"\n\t\t);\n\t}\n\n\tif (!hasASSETSServiceBinding(env)) {\n\t\tthrow new TypeError(\n\t\t\t\"Cannot call `createPagesEventContext()` without defining `ASSETS` service binding\"\n\t\t);\n\t}\n\n\tconst ctx = createExecutionContext();\n\treturn {\n\t\t// If we might need to re-use this request, clone it\n\t\trequest: opts.next ? opts.request.clone() : opts.request,\n\t\tfunctionPath: opts.functionPath ?? \"\",\n\t\t[kWaitUntil]: ctx[kWaitUntil],\n\t\twaitUntil: ctx.waitUntil.bind(ctx),\n\t\tpassThroughOnException: ctx.passThroughOnException.bind(ctx),\n\t\tasync next(nextInput, nextInit) {\n\t\t\tif (opts.next === undefined) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t\"Cannot call `EventContext#next()` without including `next` property in 2nd argument to `createPagesEventContext()`\"\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (nextInput === undefined) {\n\t\t\t\treturn opts.next(opts.request);\n\t\t\t} else {\n\t\t\t\tif (typeof nextInput === \"string\") {\n\t\t\t\t\tnextInput = new URL(nextInput, opts.request.url).toString();\n\t\t\t\t}\n\t\t\t\tconst nextRequest = new Request(nextInput, nextInit);\n\t\t\t\treturn opts.next(nextRequest);\n\t\t\t}\n\t\t},\n\t\tenv,\n\t\tparams: opts.params ?? {},\n\t\tdata: opts.data ?? {},\n\t};\n}\n","import workerdUnsafe from \"workerd:unsafe\";\nimport type { DurableObjectEvictionOptions } from \"workerd:unsafe\";\n\nconst DEFAULT_EVICTION_OPTIONS: DurableObjectEvictionOptions = {\n\twebSockets: \"hibernate\",\n};\n\nexport async function reset(): Promise<void> {\n\tawait workerdUnsafe.deleteAllDurableObjects();\n}\n\nexport async function abortAllDurableObjects(): Promise<void> {\n\tawait workerdUnsafe.abortAllDurableObjects();\n}\n\n// See public facing `cloudflare:test` types for docs\nexport async function evictAllDurableObjects(\n\toptions: DurableObjectEvictionOptions = DEFAULT_EVICTION_OPTIONS\n): Promise<void> {\n\tawait workerdUnsafe.evictAllDurableObjects(options);\n}\n","import type { SecretsStoreSecretAdmin } from \"miniflare\";\n\n// Must match ADMIN_API in miniflare/src/workers/secrets-store/constants.ts\nconst ADMIN_API = \"SecretsStoreSecret::admin_api\";\n\n/**\n * Returns the admin API for a secrets store binding, allowing tests to\n * create, update, and delete secrets that would otherwise be read-only.\n *\n * ```ts\n * import { adminSecretsStore } from \"cloudflare:test\";\n *\n * const admin = adminSecretsStore(env.MY_SECRET);\n * await admin.create(\"my-secret-value\");\n * ```\n */\nexport function adminSecretsStore(binding: unknown): SecretsStoreSecretAdmin {\n\tif (\n\t\ttypeof binding !== \"object\" ||\n\t\tbinding === null ||\n\t\ttypeof (binding as Record<string, unknown>)[ADMIN_API] !== \"function\"\n\t) {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'adminSecretsStore': parameter 1 is not a secrets store binding.\"\n\t\t);\n\t}\n\n\treturn (binding as Record<string, (...args: unknown[]) => unknown>)[\n\t\tADMIN_API\n\t]() as SecretsStoreSecretAdmin;\n}\n","import type {\n\tModifierCallback,\n\tWorkflowBinding,\n\tWorkflowInstanceIntrospector,\n\tWorkflowInstanceModifier,\n\tWorkflowIntrospectionOperation,\n\tWorkflowIntrospectionStreamResult,\n\tWorkflowIntrospector,\n\tWorkflowStepSelector,\n} from \"./types\";\n\nfunction normalizeStreamMockChunk(value: unknown): Uint8Array {\n\tif (value instanceof Uint8Array) {\n\t\treturn value;\n\t}\n\n\tif (value instanceof ArrayBuffer) {\n\t\treturn new Uint8Array(value);\n\t}\n\n\tif (ArrayBuffer.isView(value) && !(value instanceof DataView)) {\n\t\treturn new Uint8Array(value.buffer, value.byteOffset, value.byteLength);\n\t}\n\n\tthrow new TypeError(\n\t\t\"Workflow mockStepResult() ReadableStream chunks must be ArrayBuffer or TypedArray values.\"\n\t);\n}\n\nasync function readStreamMockChunks(\n\tstream: ReadableStream<unknown>\n): Promise<Uint8Array[]> {\n\tif (stream.locked) {\n\t\tthrow new TypeError(\n\t\t\t\"Workflow mockStepResult() received a locked or unreadable ReadableStream.\"\n\t\t);\n\t}\n\n\tconst chunks: Uint8Array[] = [];\n\tconst reader = stream.getReader();\n\tlet fullyRead = false;\n\ttry {\n\t\twhile (true) {\n\t\t\tconst result = await reader.read();\n\t\t\tif (result.done) {\n\t\t\t\tfullyRead = true;\n\t\t\t\treturn chunks;\n\t\t\t}\n\n\t\t\tconst chunk = normalizeStreamMockChunk(result.value);\n\t\t\tif (chunk.byteLength === 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tchunks.push(chunk.slice());\n\t\t}\n\t} finally {\n\t\tif (!fullyRead) {\n\t\t\tawait reader\n\t\t\t\t.cancel(\"stream mock consumption stopped before completion\")\n\t\t\t\t.catch(() => {});\n\t\t}\n\t\ttry {\n\t\t\treader.releaseLock();\n\t\t} catch {\n\t\t\t/** Reader may still be processing cancel(). */\n\t\t}\n\t}\n}\n\nexport class WorkflowInstanceModificationRecorder implements WorkflowInstanceModifier {\n\tconstructor(private readonly operations: WorkflowIntrospectionOperation[]) {}\n\n\tasync disableSleeps(steps?: WorkflowStepSelector[]): Promise<void> {\n\t\tthis.operations.push({ type: \"disableSleeps\", steps });\n\t}\n\n\tasync disableRetryDelays(steps?: WorkflowStepSelector[]): Promise<void> {\n\t\tthis.operations.push({ type: \"disableRetryDelays\", steps });\n\t}\n\n\tasync mockStepResult(\n\t\tstep: WorkflowStepSelector,\n\t\tstepResult: unknown\n\t): Promise<void> {\n\t\tif (stepResult instanceof ReadableStream) {\n\t\t\tconst streamResult: WorkflowIntrospectionStreamResult = {\n\t\t\t\t__workflowIntrospectionStreamResult: true,\n\t\t\t\tchunks: await readStreamMockChunks(stepResult),\n\t\t\t};\n\t\t\tthis.operations.push({\n\t\t\t\ttype: \"mockStepResult\",\n\t\t\t\tstep,\n\t\t\t\tstepResult: streamResult,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tthis.operations.push({ type: \"mockStepResult\", step, stepResult });\n\t}\n\n\tasync mockStepError(\n\t\tstep: WorkflowStepSelector,\n\t\terror: Error,\n\t\ttimes?: number\n\t): Promise<void> {\n\t\tthis.operations.push({\n\t\t\ttype: \"mockStepError\",\n\t\t\tstep,\n\t\t\terror: { name: error.name, message: error.message },\n\t\t\ttimes,\n\t\t});\n\t}\n\n\tasync forceStepTimeout(\n\t\tstep: WorkflowStepSelector,\n\t\ttimes?: number\n\t): Promise<void> {\n\t\tthis.operations.push({ type: \"forceStepTimeout\", step, times });\n\t}\n\n\tasync mockEvent(event: { type: string; payload: unknown }): Promise<void> {\n\t\tthis.operations.push({ type: \"mockEvent\", event });\n\t}\n\n\tasync forceEventTimeout(step: WorkflowStepSelector): Promise<void> {\n\t\tthis.operations.push({ type: \"forceEventTimeout\", step });\n\t}\n}\n\nexport class WorkflowIntrospectorHandle implements WorkflowIntrospector {\n\t#disposed = false;\n\t#sessionId: string | undefined;\n\t#instanceIntrospectors = new Map<string, WorkflowInstanceIntrospector>();\n\t#operations: WorkflowIntrospectionOperation[] = [];\n\n\tconstructor(private readonly workflow: WorkflowBinding) {}\n\n\tasync start(): Promise<void> {\n\t\tthis.#sessionId = await this.workflow.unsafeStartIntrospection();\n\t}\n\n\tprivate getSessionId(): string {\n\t\tif (this.#sessionId === undefined) {\n\t\t\tthrow new Error(\"Workflow introspection has not started.\");\n\t\t}\n\t\treturn this.#sessionId;\n\t}\n\n\tasync modifyAll(fn: ModifierCallback): Promise<void> {\n\t\tconst sessionId = this.getSessionId();\n\t\tawait fn(new WorkflowInstanceModificationRecorder(this.#operations));\n\t\tawait this.workflow.unsafeSetIntrospectionOperations(\n\t\t\tsessionId,\n\t\t\tthis.#operations\n\t\t);\n\t}\n\n\tasync get(): Promise<WorkflowInstanceIntrospector[]> {\n\t\tconst sessionId = this.getSessionId();\n\t\tawait this.syncInstanceIntrospectors(sessionId);\n\n\t\treturn Array.from(this.#instanceIntrospectors.values());\n\t}\n\n\tprivate async syncInstanceIntrospectors(sessionId: string): Promise<void> {\n\t\tconst instanceIds =\n\t\t\tawait this.workflow.unsafeGetIntrospectionInstances(sessionId);\n\n\t\tfor (const instanceId of instanceIds) {\n\t\t\tif (!this.#instanceIntrospectors.has(instanceId)) {\n\t\t\t\tthis.#instanceIntrospectors.set(\n\t\t\t\t\tinstanceId,\n\t\t\t\t\tnew WorkflowInstanceIntrospectorHandle(this.workflow, instanceId)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async stopIntrospectionSession(sessionId: string): Promise<void> {\n\t\ttry {\n\t\t\tawait this.syncInstanceIntrospectors(sessionId);\n\t\t} finally {\n\t\t\tawait this.workflow.unsafeStopIntrospection(sessionId);\n\t\t}\n\t}\n\n\tprivate async disposeInstanceIntrospectors(): Promise<void> {\n\t\ttry {\n\t\t\tawait Promise.all(\n\t\t\t\tArray.from(this.#instanceIntrospectors.values(), (introspector) =>\n\t\t\t\t\tintrospector.dispose()\n\t\t\t\t)\n\t\t\t);\n\t\t} finally {\n\t\t\tthis.#instanceIntrospectors.clear();\n\t\t}\n\t}\n\n\t/** Keep this bound; explicit resource management may call the disposer unbound. */\n\tdispose = async (): Promise<void> => {\n\t\tif (this.#disposed) {\n\t\t\treturn;\n\t\t}\n\t\tthis.#disposed = true;\n\t\tconst sessionId = this.#sessionId;\n\n\t\ttry {\n\t\t\tif (sessionId !== undefined) {\n\t\t\t\tawait this.stopIntrospectionSession(sessionId);\n\t\t\t}\n\t\t} finally {\n\t\t\tawait this.disposeInstanceIntrospectors();\n\t\t}\n\t};\n\n\tasync [Symbol.asyncDispose](): Promise<void> {\n\t\tawait this.dispose();\n\t}\n}\n\nexport class WorkflowInstanceIntrospectorHandle implements WorkflowInstanceIntrospector {\n\t#instanceModifier: WorkflowInstanceModifier | undefined;\n\t#instanceModifierPromise: Promise<WorkflowInstanceModifier> | undefined;\n\n\tconstructor(\n\t\tprivate readonly workflow: WorkflowBinding,\n\t\tprivate readonly instanceId: string\n\t) {\n\t\tthis.#instanceModifierPromise = workflow\n\t\t\t.unsafeGetInstanceModifier(instanceId)\n\t\t\t.then((modifier) => {\n\t\t\t\tthis.#instanceModifier = modifier as WorkflowInstanceModifier;\n\t\t\t\tthis.#instanceModifierPromise = undefined;\n\t\t\t\treturn this.#instanceModifier;\n\t\t\t});\n\n\t\t// To avoid an unhandled rejection when the handle is used without modify()\n\t\tvoid this.#instanceModifierPromise.catch(() => {});\n\t}\n\n\tasync modify(fn: ModifierCallback): Promise<WorkflowInstanceIntrospector> {\n\t\tif (this.#instanceModifierPromise !== undefined) {\n\t\t\tthis.#instanceModifier = await this.#instanceModifierPromise;\n\t\t}\n\t\tif (this.#instanceModifier === undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t\"could not apply modifications due to internal error. Retrying the test may resolve the issue.\"\n\t\t\t);\n\t\t}\n\n\t\tawait fn(this.#instanceModifier);\n\n\t\treturn this;\n\t}\n\n\tasync waitForStepResult(step: WorkflowStepSelector): Promise<unknown> {\n\t\treturn await this.workflow.unsafeWaitForStepResult(\n\t\t\tthis.instanceId,\n\t\t\tstep.name,\n\t\t\tstep.index\n\t\t);\n\t}\n\n\tasync waitForStatus(status: string): Promise<void> {\n\t\tif (status === \"queued\") {\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.workflow.unsafeWaitForStatus(this.instanceId, status);\n\t}\n\n\tasync getOutput(): Promise<unknown> {\n\t\treturn await this.workflow.unsafeGetOutputOrError(this.instanceId, true);\n\t}\n\n\tasync getError(): Promise<{ name: string; message: string }> {\n\t\treturn (await this.workflow.unsafeGetOutputOrError(\n\t\t\tthis.instanceId,\n\t\t\tfalse\n\t\t)) as { name: string; message: string };\n\t}\n\n\t/** Keep this bound; explicit resource management may call the disposer unbound. */\n\tdispose = async (): Promise<void> => {\n\t\tawait this.workflow.unsafeAbort(this.instanceId, \"Instance dispose\");\n\t};\n\n\tasync [Symbol.asyncDispose](): Promise<void> {\n\t\tawait this.dispose();\n\t}\n}\n","import {\n\tWorkflowInstanceIntrospectorHandle,\n\tWorkflowIntrospectorHandle,\n} from \"@cloudflare/workflows-shared/src/introspection\";\nimport type {\n\tWorkflowBinding,\n\tWorkflowInstanceIntrospector,\n\tWorkflowIntrospector,\n} from \"@cloudflare/workflows-shared/src/types\";\n\n// Note(osilva): `introspectWorkflowInstance()` doesn’t need to be async, but we keep it that way\n// to avoid potential breaking changes later and to stay consistent with `introspectWorkflow`.\n\n// In the \"cloudflare:test\" module, the exposed type is `Workflow`. Here we use `WorkflowBinding`\n// (which implements `Workflow`) to access unsafe functions.\nexport async function introspectWorkflowInstance(\n\tworkflow: WorkflowBinding,\n\tinstanceId: string\n): Promise<WorkflowInstanceIntrospector> {\n\tif (!workflow || !instanceId) {\n\t\tthrow new Error(\n\t\t\t\"[WorkflowIntrospector] Workflow binding and instance id are required.\"\n\t\t);\n\t}\n\treturn new WorkflowInstanceIntrospectorHandle(workflow, instanceId);\n}\n\n// Note(osilva): `introspectWorkflow` could be sync with some changes, but we keep it async\n// to avoid potential breaking changes later.\n\n// In the \"cloudflare:test\" module, the exposed type is `Workflow`. Here we use `WorkflowBinding`\n// (which implements `Workflow`) to access unsafe functions.\nexport async function introspectWorkflow(\n\tworkflow: WorkflowBinding\n): Promise<WorkflowIntrospector> {\n\tif (!workflow) {\n\t\tthrow new Error(\"[WorkflowIntrospector] Workflow binding is required.\");\n\t}\n\n\tconst introspector = new WorkflowIntrospectorHandle(workflow);\n\tawait introspector.start();\n\treturn introspector;\n}\n"],"mappings":";;;;;;AAEA,SAAS,aAAa,GAA6B;AAClD,QACC,OAAO,MAAM,YACb,MAAM,QACN,EAAE,YAAY,SAAS,gBACvB,aAAa,KACb,OAAO,EAAE,YAAY,cACrB,WAAW,KACX,OAAO,EAAE,UAAU,cACnB,UAAU,KACV,OAAO,EAAE,SAAS;;AAIpB,SAAS,cAAc,GAA8B;AACpD,QACC,OAAO,MAAM,YACb,MAAM,QACN,UAAU,KACV,OAAO,EAAE,SAAS,YAClB,aAAa,KACb,MAAM,QAAQ,EAAE,QAAQ,IACxB,EAAE,QAAQ,OAAO,UAAU,OAAO,UAAU,SAAS;;AAGvD,SAAS,eAAe,GAAgC;AACvD,QAAO,MAAM,QAAQ,EAAE,IAAI,EAAE,MAAM,cAAc;;AAGlD,eAAsB,kBACrB,IACA,YACA,sBAAsB,iBACrB;AACD,KAAI,CAAC,aAAa,GAAG,CACpB,OAAM,IAAI,UACT,kFACA;AAEF,KAAI,CAAC,eAAe,WAAW,CAC9B,OAAM,IAAI,UACT,qFACA;AAGF,KAAI,OAAO,wBAAwB,SAClC,OAAM,IAAI,UACT,8EACA;CAGF,MAAM,YAAY,OAAe,IAAI,GAAG,QAAQ,MAAM,OAAK,CAAC;CAC5D,MAAM,mBAAmB,SAAS,oBAAoB;CAGtD,MAAM,SAAS,8BAA8B,iBAAiB;;;;;AA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,eAAsB,mBACrB,UACgC;AAChC,KAAI,CAAC,SACJ,OAAM,IAAI,MAAM,uDAAuD;CAGxE,MAAM,eAAe,IAAI,2BAA2B,SAAS;AAC7D,OAAM,aAAa,OAAO;AAC1B,QAAO"}
1
+ {"version":3,"file":"test-internal.mjs","names":["DEFAULT_EVICTION_OPTIONS: DurableObjectEvictionOptions","sameIsolatedNamespaces: DurableObjectNamespace[] | undefined","env","DEFAULT_EVICTION_OPTIONS","errors: unknown[]","timeoutId: ReturnType<typeof setTimeout> | undefined","globalWaitUntil: unknown[]","exports","releaseStarted: (() => void) | undefined","OPTIONAL_DURABLE_OBJECT_KEYS: ReadonlySet<\n\t(typeof DURABLE_OBJECT_KEYS)[number]\n>","runtimeEnv","env","DurableObjectClass","#controller","timestamp: Date","attempts: number","metadata: MessageBatchMetadata","retryMessages: QueueRetryMessage[]","explicitAcks: string[]","DEFAULT_EVICTION_OPTIONS: DurableObjectEvictionOptions","chunks: Uint8Array[]","operations: WorkflowIntrospectionOperation[]","streamResult: WorkflowIntrospectionStreamResult","workflow: WorkflowBinding","#sessionId","#operations","#instanceIntrospectors","#disposed","instanceId: string","#instanceModifierPromise","#instanceModifier"],"sources":["../../../../src/worker/d1.ts","../../../../src/worker/env.ts","../../../../src/worker/durable-objects.ts","../../../../src/worker/wait-until.ts","../../../../src/worker/patch-ctx.ts","../../../../src/worker/proxy-prototype.ts","../../../../src/worker/entrypoints.ts","../../../../src/worker/events.ts","../../../../src/worker/reset.ts","../../../../src/worker/secrets-store.ts","../../../../../workflows-shared/src/introspection.ts","../../../../src/worker/workflows.ts"],"sourcesContent":["import type { D1Migration } from \"../shared/d1\";\n\nfunction isD1Database(v: unknown): v is D1Database {\n\treturn (\n\t\ttypeof v === \"object\" &&\n\t\tv !== null &&\n\t\tv.constructor.name === \"D1Database\" &&\n\t\t\"prepare\" in v &&\n\t\ttypeof v.prepare === \"function\" &&\n\t\t\"batch\" in v &&\n\t\ttypeof v.batch === \"function\" &&\n\t\t\"exec\" in v &&\n\t\ttypeof v.exec === \"function\"\n\t);\n}\n\nfunction isD1Migration(v: unknown): v is D1Migration {\n\treturn (\n\t\ttypeof v === \"object\" &&\n\t\tv !== null &&\n\t\t\"name\" in v &&\n\t\ttypeof v.name === \"string\" &&\n\t\t\"queries\" in v &&\n\t\tArray.isArray(v.queries) &&\n\t\tv.queries.every((query) => typeof query === \"string\")\n\t);\n}\nfunction isD1Migrations(v: unknown): v is D1Migration[] {\n\treturn Array.isArray(v) && v.every(isD1Migration);\n}\n\nexport async function applyD1Migrations(\n\tdb: D1Database,\n\tmigrations: D1Migration[],\n\tmigrationsTableName = \"d1_migrations\"\n) {\n\tif (!isD1Database(db)) {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'applyD1Migrations': parameter 1 is not of type 'D1Database'.\"\n\t\t);\n\t}\n\tif (!isD1Migrations(migrations)) {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'applyD1Migrations': parameter 2 is not of type 'D1Migration[]'.\"\n\t\t);\n\t}\n\t// noinspection SuspiciousTypeOfGuard\n\tif (typeof migrationsTableName !== \"string\") {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'applyD1Migrations': parameter 3 is not of type 'string'.\"\n\t\t);\n\t}\n\n\tconst escapeId = (id: string) => `\"${id.replace(/\"/g, '\"\"')}\"`;\n\tconst escapedTableName = escapeId(migrationsTableName);\n\n\t// Create migrations table if it doesn't exist\n\tconst schema = `CREATE TABLE IF NOT EXISTS ${escapedTableName} (\n\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\tname TEXT UNIQUE,\n\t\tapplied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL\n\t);`;\n\tawait db.prepare(schema).run();\n\n\t// Find applied migrations\n\tconst appliedMigrationNamesResult = await db\n\t\t.prepare(`SELECT name FROM ${escapedTableName};`)\n\t\t.all<{ name: string }>();\n\tconst appliedMigrationNames = appliedMigrationNamesResult.results.map(\n\t\t({ name }) => name\n\t);\n\n\t// Apply un-applied migrations\n\tconst insertMigrationStmt = db.prepare(\n\t\t`INSERT INTO ${escapedTableName} (name) VALUES (?);`\n\t);\n\tfor (const migration of migrations) {\n\t\tif (appliedMigrationNames.includes(migration.name)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst queries = migration.queries.map((query) => db.prepare(query));\n\t\tqueries.push(insertMigrationStmt.bind(migration.name));\n\t\tawait db.batch(queries);\n\t}\n}\n","import assert from \"node:assert\";\nimport { exports } from \"cloudflare:workers\";\n\nexport { env } from \"cloudflare:workers\";\n\n/**\n * For reasons that aren't clear to me, just `SELF = exports.default` ends up with SELF being\n * undefined in a test. This Proxy solution works.\n */\nexport const SELF = new Proxy(\n\t{},\n\t{\n\t\tget(_, p) {\n\t\t\tconst target = exports.default as unknown as Record<\n\t\t\t\tstring | symbol,\n\t\t\t\tunknown\n\t\t\t>;\n\t\t\tconst value = target[p];\n\t\t\treturn typeof value === \"function\" ? value.bind(target) : value;\n\t\t},\n\t}\n);\n\nexport function getSerializedOptions(): SerializedOptions {\n\tassert(typeof __vitest_worker__ === \"object\", \"Expected global Vitest state\");\n\tconst options = __vitest_worker__.providedContext.cloudflarePoolOptions;\n\t// `options` should always be defined when running tests\n\n\tassert(\n\t\toptions !== undefined,\n\t\t\"Expected serialised options, got keys: \" +\n\t\t\tObject.keys(__vitest_worker__.providedContext).join(\", \")\n\t);\n\tconst parsedOptions = JSON.parse(options);\n\treturn {\n\t\t...parsedOptions,\n\t\tdurableObjectBindingDesignators: new Map(\n\t\t\tparsedOptions.durableObjectBindingDesignators\n\t\t),\n\t};\n}\n\nexport function getResolvedMainPath(\n\tforBindingType: \"service\" | \"Durable Object\"\n): string {\n\tconst options = getSerializedOptions();\n\tif (options.main === undefined) {\n\t\tthrow new Error(\n\t\t\t`Using ${forBindingType} bindings to the current worker requires \\`poolOptions.workers.main\\` to be set to your worker's entrypoint: ${JSON.stringify(options)}`\n\t\t);\n\t}\n\treturn options.main;\n}\n","import assert from \"node:assert\";\nimport { env, exports } from \"cloudflare:workers\";\nimport workerdUnsafe from \"workerd:unsafe\";\nimport { getSerializedOptions } from \"./env\";\nimport type { __VITEST_POOL_WORKERS_RUNNER_DURABLE_OBJECT__ } from \"./index\";\nimport type { DurableObjectEvictionOptions } from \"workerd:unsafe\";\n\nconst DEFAULT_EVICTION_OPTIONS: DurableObjectEvictionOptions = {\n\twebSockets: \"hibernate\",\n};\n\nconst CF_KEY_ACTION = \"vitestPoolWorkersDurableObjectAction\";\n\nlet nextActionId = 0;\nconst kUseResponse = Symbol(\"kUseResponse\");\nconst actionResults = new Map<number /* id */, unknown>();\n\nfunction isDurableObjectNamespace(v: unknown): v is DurableObjectNamespace {\n\treturn (\n\t\tv instanceof Object &&\n\t\t/^(?:Loopback)?DurableObjectNamespace$/.test(v.constructor.name) &&\n\t\t\"newUniqueId\" in v &&\n\t\ttypeof v.newUniqueId === \"function\" &&\n\t\t\"idFromName\" in v &&\n\t\ttypeof v.idFromName === \"function\" &&\n\t\t\"idFromString\" in v &&\n\t\ttypeof v.idFromString === \"function\" &&\n\t\t\"get\" in v &&\n\t\ttypeof v.get === \"function\"\n\t);\n}\nfunction isDurableObjectStub(v: unknown): v is DurableObjectStub {\n\treturn (\n\t\ttypeof v === \"object\" &&\n\t\tv !== null &&\n\t\t(v.constructor.name === \"DurableObject\" ||\n\t\t\tv.constructor.name === \"WorkerRpc\") &&\n\t\t\"fetch\" in v &&\n\t\ttypeof v.fetch === \"function\" &&\n\t\t\"id\" in v &&\n\t\ttypeof v.id === \"object\"\n\t);\n}\n\n// Whilst `sameIsolatedNamespaces` depends on `getSerializedOptions()`,\n// `durableObjectBindingDesignators` is derived from the user Durable Object\n// config. If this were to change, the Miniflare options would change too\n// restarting this worker. This means we only need to compute this once, as it\n// will automatically invalidate when needed.\nlet sameIsolatedNamespaces: DurableObjectNamespace[] | undefined;\nfunction getSameIsolateNamespaces(): DurableObjectNamespace[] {\n\tif (sameIsolatedNamespaces !== undefined) {\n\t\treturn sameIsolatedNamespaces;\n\t}\n\tsameIsolatedNamespaces = [];\n\n\tconst options = getSerializedOptions();\n\tif (options.durableObjectBindingDesignators === undefined) {\n\t\treturn sameIsolatedNamespaces;\n\t}\n\n\tfor (const [key, designator] of options.durableObjectBindingDesignators) {\n\t\t// We're assuming the user isn't able to guess the current worker name, so\n\t\t// if a `scriptName` is set, the designator is for another worker.\n\t\tif (designator.scriptName !== undefined) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst namespace = env[key] ?? (exports as Record<string, unknown>)?.[key];\n\t\tassert(\n\t\t\tisDurableObjectNamespace(namespace),\n\t\t\t`Expected ${key} to be a DurableObjectNamespace binding`\n\t\t);\n\t\tsameIsolatedNamespaces.push(namespace);\n\t}\n\n\treturn sameIsolatedNamespaces;\n}\n\nfunction assertSameIsolate(stub: DurableObjectStub) {\n\t// Make sure our special `cf` requests get handled correctly and aren't\n\t// routed to user fetch handlers\n\tconst idString = stub.id.toString();\n\tconst namespaces = getSameIsolateNamespaces();\n\t// Try to recreate the stub's ID using each same-isolate namespace.\n\t// `idFromString()` will throw if the ID is not for that namespace.\n\t// If a call succeeds, we know the ID is for an object in this isolate.\n\tfor (const namespace of namespaces) {\n\t\ttry {\n\t\t\tnamespace.idFromString(idString);\n\t\t\treturn;\n\t\t} catch {}\n\t}\n\t// If no calls succeed, we know the ID is for an object outside this isolate,\n\t// and we won't be able to use the `actionResults` map to share data.\n\tthrow new Error(\n\t\t\"Durable Object test helpers can only be used with stubs pointing to objects defined within the same worker.\"\n\t);\n}\n\nasync function runInStub<O extends DurableObject, R>(\n\tstub: Fetcher,\n\tcallback: (instance: O, state: DurableObjectState) => R | Promise<R>\n): Promise<R> {\n\tconst id = nextActionId++;\n\tactionResults.set(id, callback);\n\n\tconst response = await stub.fetch(\"http://x\", {\n\t\tcf: { [CF_KEY_ACTION]: id },\n\t\t// Prevent the runtime from following redirects returned by the callback,\n\t\t// which would re-enter `maybeHandleRunRequest` with a consumed action ID.\n\t\tredirect: \"manual\",\n\t});\n\n\t// `result` may be `undefined`\n\tassert(actionResults.has(id), `Expected action result for ${id}`);\n\tconst result = actionResults.get(id);\n\tactionResults.delete(id);\n\n\tif (result === kUseResponse) {\n\t\treturn response as R;\n\t} else if (response.ok) {\n\t\treturn result as R;\n\t} else {\n\t\tthrow result;\n\t}\n}\n\n// See public facing `cloudflare:test` types for docs\n// (`async` so it throws asynchronously/rejects)\nexport async function runInDurableObject<O extends DurableObject, R>(\n\tstub: DurableObjectStub,\n\tcallback: (instance: O, state: DurableObjectState) => R | Promise<R>\n): Promise<R> {\n\tif (!isDurableObjectStub(stub)) {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'runInDurableObject': parameter 1 is not of type 'DurableObjectStub'.\"\n\t\t);\n\t}\n\tif (typeof callback !== \"function\") {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'runInDurableObject': parameter 2 is not of type 'function'.\"\n\t\t);\n\t}\n\n\tassertSameIsolate(stub);\n\treturn runInStub(stub, callback);\n}\n\nasync function runAlarm(instance: DurableObject, state: DurableObjectState) {\n\tconst alarm = await state.storage.getAlarm();\n\tif (alarm === null) {\n\t\treturn false;\n\t}\n\tawait state.storage.deleteAlarm();\n\tawait instance.alarm?.();\n\treturn true;\n}\n// See public facing `cloudflare:test` types for docs\n// (`async` so it throws asynchronously/rejects)\nexport async function runDurableObjectAlarm(\n\tstub: DurableObjectStub\n): Promise<boolean /* ran */> {\n\tif (!isDurableObjectStub(stub)) {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'runDurableObjectAlarm': parameter 1 is not of type 'DurableObjectStub'.\"\n\t\t);\n\t}\n\treturn await runInDurableObject(stub, runAlarm);\n}\n\n// See public facing `cloudflare:test` types for docs\n// (`async` so it throws asynchronously/rejects)\nexport async function evictDurableObject(\n\tstub: DurableObjectStub,\n\toptions: DurableObjectEvictionOptions = DEFAULT_EVICTION_OPTIONS\n): Promise<void> {\n\tif (!isDurableObjectStub(stub)) {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'evictDurableObject': parameter 1 is not of type 'DurableObjectStub'.\"\n\t\t);\n\t}\n\tawait workerdUnsafe.evict(stub, options);\n}\n\n/**\n * Internal method for running `callback` inside the I/O context of the\n * Runner Durable Object.\n *\n * Tests run in this context by default. This is required for performing\n * operations that use Vitest's RPC mechanism as the Durable Object\n * owns the RPC WebSocket. For example, importing modules or sending logs.\n * Trying to perform those operations from a different context (e.g. within\n * a `export default { fetch() {} }` handler or user Durable Object's `fetch()`\n * handler) without using this function will result in a `Cannot perform I/O on\n * behalf of a different request` error.\n */\nexport function runInRunnerObject<R>(\n\tcallback: (\n\t\tinstance: __VITEST_POOL_WORKERS_RUNNER_DURABLE_OBJECT__\n\t) => R | Promise<R>\n): Promise<R> {\n\t// Runner DO is ephemeral (ColoLocalActorNamespace), which has .get(name)\n\t// instead of the standard idFromName()/get(id) API.\n\tconst ns = env[\"__VITEST_POOL_WORKERS_RUNNER_OBJECT\"] as unknown as {\n\t\tget(name: string): Fetcher;\n\t};\n\tconst stub = ns.get(\"singleton\");\n\treturn runInStub(stub, callback);\n}\n\nexport async function maybeHandleRunRequest(\n\trequest: Request,\n\tinstance: unknown,\n\tstate?: DurableObjectState\n): Promise<Response | undefined> {\n\tconst actionId = request.cf?.[CF_KEY_ACTION];\n\tif (actionId === undefined) {\n\t\treturn;\n\t}\n\n\tassert(typeof actionId === \"number\", `Expected numeric ${CF_KEY_ACTION}`);\n\ttry {\n\t\tconst callback = actionResults.get(actionId);\n\t\tassert(typeof callback === \"function\", `Expected callback for ${actionId}`);\n\t\tconst result = await callback(instance, state);\n\t\t// If the callback returns a `Response`, we can't pass it back to the\n\t\t// caller through `actionResults`. If we did that, we'd get a `Cannot\n\t\t// perform I/O on behalf of a different Durable Object` error if we\n\t\t// tried to use it. Instead, we set a flag in `actionResults` that\n\t\t// instructs the caller to use the `Response` returned by\n\t\t// `DurableObjectStub#fetch()` directly.\n\t\tif (result instanceof Response) {\n\t\t\tactionResults.set(actionId, kUseResponse);\n\t\t\treturn result;\n\t\t} else {\n\t\t\tactionResults.set(actionId, result);\n\t\t}\n\t\treturn new Response(null, { status: 204 });\n\t} catch (e) {\n\t\tactionResults.set(actionId, e);\n\t\treturn new Response(null, { status: 500 });\n\t}\n}\n\nexport async function listDurableObjectIds(\n\tnamespace: DurableObjectNamespace\n): Promise<DurableObjectId[]> {\n\tif (!isDurableObjectNamespace(namespace)) {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'listDurableObjectIds': parameter 1 is not of type 'DurableObjectNamespace'.\"\n\t\t);\n\t}\n\n\t// To get an instance of `DurableObjectNamespace`, the user must've bound the\n\t// namespace to the test runner worker, since `DurableObjectNamespace` has no\n\t// user-accessible constructor. This means `namespace` must be in `globalEnv`.\n\t// We can use this to find the bound name for this binding. We inject a\n\t// mapping between bound names and Durable Object designators. We pass the\n\t// bound name to Miniflare's Node-side loopback to find all IDs on disk.\n\tconst boundName = Object.entries(env).find(\n\t\t(entry) => namespace === entry[1]\n\t)?.[0];\n\tassert(boundName !== undefined, \"Expected to find bound name for namespace\");\n\n\tconst options = getSerializedOptions();\n\tconst searchParams = new URLSearchParams({ binding_name: boundName });\n\tif (options.selfName !== undefined) {\n\t\tsearchParams.set(\"worker_name\", options.selfName);\n\t}\n\n\tconst url = `http://placeholder/durable-objects?${searchParams.toString()}`;\n\tconst res = await env.__VITEST_POOL_WORKERS_LOOPBACK_SERVICE.fetch(url);\n\tassert.strictEqual(res.status, 200);\n\tconst ids = await res.json();\n\tassert(Array.isArray(ids));\n\treturn ids.map((id) => {\n\t\tassert(typeof id === \"string\");\n\t\treturn namespace.idFromString(id);\n\t});\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\n/**\n * In production, Workers have a 30-second limit for `waitUntil` promises.\n * We use the same limit here. If promises are still pending after this,\n * they almost certainly indicate a bug (e.g. a `waitUntil` promise that\n * will never resolve). We log a warning and move on so the test suite\n * doesn't hang indefinitely.\n */\nlet WAIT_UNTIL_TIMEOUT = 30_000;\n\n/** @internal — only exposed for tests */\nexport function setWaitUntilTimeout(ms: number): void {\n\tWAIT_UNTIL_TIMEOUT = ms;\n}\n\nconst kTimedOut = Symbol(\"kTimedOut\");\n\n/**\n * Empty array and wait for all promises to resolve until no more added.\n * If a single promise rejects, the rejection will be passed-through.\n * If multiple promises reject, the rejections will be aggregated.\n *\n * If any batch of promises hasn't settled after {@link WAIT_UNTIL_TIMEOUT}ms,\n * a warning is logged and the remaining promises are abandoned.\n */\nexport async function waitForWaitUntil(\n\t/* mut */ waitUntil: unknown[]\n): Promise<void> {\n\tconst errors: unknown[] = [];\n\n\twhile (waitUntil.length > 0) {\n\t\tconst batch = waitUntil.splice(0);\n\t\tlet timeoutId: ReturnType<typeof setTimeout> | undefined;\n\t\tconst result = await Promise.race([\n\t\t\tPromise.allSettled(batch).then((results) => ({ results })),\n\t\t\tnew Promise<typeof kTimedOut>(\n\t\t\t\t(resolve) =>\n\t\t\t\t\t(timeoutId = setTimeout(() => resolve(kTimedOut), WAIT_UNTIL_TIMEOUT))\n\t\t\t),\n\t\t]);\n\t\tclearTimeout(timeoutId);\n\n\t\tif (result === kTimedOut) {\n\t\t\t__console.warn(\n\t\t\t\t`[vitest-plugin] ${batch.length} waitUntil promise(s) did not ` +\n\t\t\t\t\t`resolve within ${WAIT_UNTIL_TIMEOUT / 1000}s and will be abandoned. ` +\n\t\t\t\t\t`This normally means your Worker's waitUntil handler has a bug ` +\n\t\t\t\t\t`that prevents it from settling (e.g. a fetch that never completes ` +\n\t\t\t\t\t`or a missing resolve/reject call).`\n\t\t\t);\n\t\t\t// Stop draining — any promises added during this batch are also abandoned\n\t\t\twaitUntil.length = 0;\n\t\t\tbreak;\n\t\t}\n\n\t\t// Record all rejected promises\n\t\tfor (const settled of result.results) {\n\t\t\tif (settled.status === \"rejected\") {\n\t\t\t\terrors.push(settled.reason);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (errors.length === 1) {\n\t\t// If there was only one rejection, rethrow it\n\t\tthrow errors[0];\n\t} else if (errors.length > 1) {\n\t\t// If there were more rejections, rethrow them all\n\t\tthrow new AggregateError(errors);\n\t}\n}\n\n// If isolated storage is enabled, we ensure all `waitUntil()`s are `await`ed at\n// the end of each test, as these may contain storage calls (e.g. caching\n// responses). Note we can't wait at the end of `.concurrent` tests, as we can't\n// track which `waitUntil()`s belong to which tests.\n//\n// If isolated storage is disabled, we ensure all `waitUntil()`s are `await`ed\n// at the end of each test *file*. This ensures we don't try to dispose the\n// runtime until all `waitUntil()`s complete.\nconst globalWaitUntil: unknown[] = [];\nexport function registerGlobalWaitUntil(promise: unknown) {\n\tglobalWaitUntil.push(promise);\n}\nexport function waitForGlobalWaitUntil(): Promise<void> {\n\treturn waitForWaitUntil(globalWaitUntil);\n}\n\nexport const handlerContextStore = new AsyncLocalStorage<ExecutionContext>();\nexport function registerHandlerAndGlobalWaitUntil(promise: Promise<unknown>) {\n\tconst handlerContext = handlerContextStore.getStore();\n\tif (handlerContext === undefined) {\n\t\tregisterGlobalWaitUntil(promise);\n\t} else {\n\t\t// `patchAndRunWithHandlerContext()` ensures handler `waitUntil()` calls\n\t\t// `registerGlobalWaitUntil()` too\n\t\thandlerContext.waitUntil(promise);\n\t}\n}\n","import { handlerContextStore, registerGlobalWaitUntil } from \"./wait-until\";\n\nconst patchedHandlerContexts = new WeakSet<ExecutionContext>();\n\n/**\n * Executes the given callback within the provided ExecutionContext,\n * patching the context to ensure that:\n *\n * - waitUntil calls are registered globally\n * - ctx.exports shows a warning if accessing missing exports\n */\nexport function patchAndRunWithHandlerContext<T>(\n\t/* mut */ ctx: ExecutionContext,\n\tcallback: () => T\n): T {\n\t// Ensure calls to `ctx.waitUntil()` registered with global wait-until\n\tif (!patchedHandlerContexts.has(ctx)) {\n\t\tpatchedHandlerContexts.add(ctx);\n\n\t\t// Patch `ctx.waitUntil()`\n\t\tconst originalWaitUntil = ctx.waitUntil;\n\t\tctx.waitUntil = (promise: Promise<unknown>) => {\n\t\t\tregisterGlobalWaitUntil(promise);\n\t\t\treturn originalWaitUntil.call(ctx, promise);\n\t\t};\n\n\t\t// Patch `ctx.exports`\n\t\tif (isCtxExportsEnabled(ctx.exports)) {\n\t\t\tObject.defineProperty(ctx, \"exports\", {\n\t\t\t\tvalue: getCtxExportsProxy(ctx.exports),\n\t\t\t});\n\t\t}\n\t}\n\treturn handlerContextStore.run(ctx, callback);\n}\n\n/**\n * Creates a proxy to the `ctx.exports` object that will warn the user if they attempt\n * to access an undefined property. This could be a valid mistake by the user or\n * it could mean that our static analysis of the main Worker's exports missed something.\n */\nexport function getCtxExportsProxy(\n\texports: Cloudflare.Exports\n): Cloudflare.Exports {\n\treturn new Proxy(exports, {\n\t\tget(target, p: keyof Cloudflare.Exports) {\n\t\t\tif (p in target) {\n\t\t\t\treturn target[p];\n\t\t\t}\n\t\t\tconsole.warn(\n\t\t\t\t`Attempted to access 'ctx.exports.${p}', which was not defined for the main Worker.\\n` +\n\t\t\t\t\t`Check that '${p}' is exported as an entry-point from the Worker.\\n` +\n\t\t\t\t\t`The '@cloudflare/vitest-plugin' integration tries to infer these exports by analyzing the source code of the main Worker.\\n`\n\t\t\t);\n\t\t\treturn undefined;\n\t\t},\n\t});\n}\n\n/**\n * Returns true if `ctx.exports` is enabled via compatibility flags.\n */\nexport function isCtxExportsEnabled(\n\texports: Cloudflare.Exports | undefined\n): exports is Cloudflare.Exports {\n\treturn (\n\t\t(globalThis as unknown as { Cloudflare: Cloudflare }).Cloudflare\n\t\t\t?.compatibilityFlags.enable_ctx_exports && exports !== undefined\n\t);\n}\n","const IGNORED_KEYS = [\"self\"];\n\ntype Constructor = {\n\treadonly prototype: object;\n} & (abstract new (...args: never[]) => object);\n\n/**\n * Create a class extending `superClass` with a lazily installed `Proxy` as its\n * `prototype`. Unknown prototype accesses defer to `getUnknownPrototypeKey()`.\n */\nexport function createProxyPrototypeClass<\n\tT extends Constructor,\n\tExtraPrototype = unknown,\n>(\n\tsuperClass: T,\n\tgetUnknownPrototypeKey: (key: string) => unknown\n): T & { prototype: ExtraPrototype } {\n\tlet proxyInstalled = false;\n\n\tfunction Class(...args: ConstructorParameters<T>) {\n\t\t// Delay proxying the prototype until construction, so workerd sees this as a\n\t\t// regular class when introspecting it. Install it only once: the prototype is\n\t\t// shared by every instance, so wrapping it again would stack proxy traps.\n\t\t// https://github.com/cloudflare/workerd/blob/9e915ed637d65adb3c57522607d2cd8b8d692b6b/src/workerd/io/worker.c%2B%2B#L1920-L1921\n\t\tif (!proxyInstalled) {\n\t\t\tClass.prototype = new Proxy(Class.prototype, {\n\t\t\t\tget(target, key, receiver) {\n\t\t\t\t\tconst value = Reflect.get(target, key, receiver);\n\t\t\t\t\tif (value !== undefined) {\n\t\t\t\t\t\treturn value;\n\t\t\t\t\t}\n\t\t\t\t\tif (typeof key === \"symbol\" || IGNORED_KEYS.includes(key)) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\treturn getUnknownPrototypeKey.call(receiver, key as string);\n\t\t\t\t},\n\t\t\t});\n\t\t\tproxyInstalled = true;\n\t\t}\n\n\t\treturn Reflect.construct(superClass, args, Class);\n\t}\n\n\tReflect.setPrototypeOf(Class.prototype, superClass.prototype);\n\tReflect.setPrototypeOf(Class, superClass);\n\n\treturn Class as unknown as T & { prototype: ExtraPrototype };\n}\n","import assert from \"node:assert\";\nimport {\n\tDurableObject as DurableObjectClass,\n\tenv as runtimeEnv,\n\tWorkerEntrypoint,\n\tWorkflowEntrypoint,\n} from \"cloudflare:workers\";\nimport { maybeHandleRunRequest, runInRunnerObject } from \"./durable-objects\";\nimport { getResolvedMainPath } from \"./env\";\nimport { patchAndRunWithHandlerContext } from \"./patch-ctx\";\nimport { createProxyPrototypeClass } from \"./proxy-prototype\";\n\n// =============================================================================\n// Common Entrypoint Helpers\n// =============================================================================\n\n/**\n * Internal method for importing a module using Vite's transformation and\n * execution pipeline. Can be called from any I/O context, and will ensure the\n * request is run from within the `__VITEST_POOL_WORKERS_RUNNER_DURABLE_OBJECT__`.\n */\nasync function importModule(\n\tspecifier: string\n): Promise<Record<string, unknown>> {\n\t/**\n\t * We need to run this import inside the Runner Object, or we get errors like:\n\t * - The Workers runtime canceled this request because it detected that your Worker's code had hung and would never generate a response. Refer to: https://developers.cloudflare.com/workers/observability/errors/\n\t * - Cannot perform I/O on behalf of a different Durable Object. I/O objects (such as streams, request/response bodies, and others) created in the context of one Durable Object cannot be accessed from a different Durable Object in the same isolate. This is a limitation of Cloudflare Workers which allows us to improve overall performance.\n\t */\n\treturn runInRunnerObject(() => {\n\t\treturn __vitest_mocker__.moduleRunner.import(specifier);\n\t});\n}\n\n/**\n * Only properties and methods declared on the prototype can be accessed over\n * RPC. This function throws a helpful error message if a property isn't\n * defined. Note we need to distinguish between a property that returns\n * `undefined` and something not being defined at all.\n */\nfunction assertRPCPropertyAccessible(\n\tctor: WorkerEntrypointConstructor | DurableObjectConstructor,\n\tinstance:\n\t\t| WorkerEntrypoint<Record<string, unknown> | Cloudflare.Env>\n\t\t| DurableObjectClass<Record<string, unknown> | Cloudflare.Env>,\n\tkey: string\n): void {\n\tconst prototypeHasKey = Reflect.has(ctor.prototype, key);\n\tif (!prototypeHasKey) {\n\t\tconst quotedKey = JSON.stringify(key);\n\t\tconst instanceHasKey = Reflect.has(instance, key);\n\t\tlet message = \"\";\n\t\tif (instanceHasKey) {\n\t\t\tmessage = [\n\t\t\t\t`The RPC receiver's prototype does not implement ${quotedKey}, but the receiver instance does.`,\n\t\t\t\t\"Only properties and methods defined on the prototype can be accessed over RPC.\",\n\t\t\t\t`Ensure properties are declared like \\`get ${key}() { ... }\\` instead of \\`${key} = ...\\`,`,\n\t\t\t\t`and methods are declared like \\`${key}() { ... }\\` instead of \\`${key} = () => { ... }\\`.`,\n\t\t\t].join(\"\\n\");\n\t\t} else {\n\t\t\tmessage = `The RPC receiver does not implement ${quotedKey}.`;\n\t\t}\n\t\tthrow new TypeError(message);\n\t}\n}\n\nfunction getRPCProperty(\n\tctor: WorkerEntrypointConstructor | DurableObjectConstructor,\n\tinstance:\n\t\t| WorkerEntrypoint<Record<string, unknown> | Cloudflare.Env>\n\t\t| DurableObjectClass<Record<string, unknown> | Cloudflare.Env>,\n\tkey: string\n): unknown {\n\tassertRPCPropertyAccessible(ctor, instance, key);\n\t// `receiver` is the value of `this` provided if a getter is encountered\n\treturn Reflect.get(/* target */ ctor.prototype, key, /* receiver */ instance);\n}\n\ntype InvocationQueueOwner =\n\t| WorkerEntrypoint<Cloudflare.Env>\n\t| DurableObjectClass<Cloudflare.Env>\n\t| WorkflowEntrypoint<Cloudflare.Env>;\n\n/**\n * When calling RPC methods dynamically, we don't know whether the `property`\n * returned from `getSELFRPCProperty()` or `getDurableObjectRPCProperty()` below\n * is just a property or a method. If we just returned `property`, but the\n * client tried to call it as a method, `workerd` would throw an \"x is not a\n * function\" error.\n *\n * Instead, we return a *callable, custom thenable*. This behaves like a\n * function and a `Promise`! If `workerd` calls it, we'll wait for the promise\n * to resolve then forward the call. Otherwise, this just appears like a regular\n * async property. Note all client calls are async, so converting sync\n * properties and methods to async is fine here.\n *\n * Unfortunately, wrapping `property` with a `Proxy` and an `apply()` trap gives\n * `TypeError: Method Promise.prototype.then called on incompatible receiver #<Promise>`. :(\n */\nfunction getRPCPropertyCallableThenable(\n\tkey: string,\n\tproperty: Promise<unknown>,\n\tqueueOwner: InvocationQueueOwner\n) {\n\tconst fn = async function (...args: unknown[]) {\n\t\treturn enqueueInvocation(queueOwner, async (release) => {\n\t\t\ttry {\n\t\t\t\tconst maybeFn = await property;\n\t\t\t\tif (typeof maybeFn === \"function\") {\n\t\t\t\t\treturn maybeFn(...args);\n\t\t\t\t} else {\n\t\t\t\t\tthrow new TypeError(`${JSON.stringify(key)} is not a function.`);\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\trelease();\n\t\t\t}\n\t\t});\n\t} as Promise<unknown> & ((...args: unknown[]) => Promise<unknown>);\n\tfn.then = (onFulfilled, onRejected) => property.then(onFulfilled, onRejected);\n\tfn.catch = (onRejected) => property.catch(onRejected);\n\tfn.finally = (onFinally) => property.finally(onFinally);\n\treturn fn;\n}\n\nconst invocationQueues = new WeakMap<InvocationQueueOwner, Promise<void>>();\n\n/**\n * Preserve the order in which async wrapper invocations begin executing.\n *\n * Resolving a property like `stub.method`, or ensuring a Durable Object handler\n * instance, may need to import user modules or instantiate wrapper objects. If\n * several calls are fired synchronously, those async steps can otherwise\n * complete out of order before the actual user code is invoked. The queue is\n * released as soon as invocation starts, so async completions can still run\n * concurrently.\n */\nasync function enqueueInvocation<T>(\n\towner: InvocationQueueOwner,\n\tcallback: (release: () => void) => Promise<T>\n): Promise<T> {\n\tconst previous = invocationQueues.get(owner) ?? Promise.resolve();\n\tlet releaseStarted: (() => void) | undefined;\n\tconst started = new Promise<void>((resolve) => {\n\t\treleaseStarted = resolve;\n\t});\n\tconst release = () => {\n\t\tconst releaseStartedFn = releaseStarted;\n\t\tif (releaseStartedFn !== undefined) {\n\t\t\treleaseStartedFn();\n\t\t}\n\t};\n\tconst result = previous.catch(() => {}).then(() => callback(release));\n\tinvocationQueues.set(owner, started);\n\treturn result;\n}\n\n/**\n * `ctx` and `env` are defined as `protected` within `WorkerEntrypoint` and\n * `DurableObjectClass`. Usually this isn't a problem, as `protected` members\n * can be accessed from subclasses defined with `class extends` keywords.\n * Unfortunately, we have to define our classes with a `Proxy` prototype to\n * support forwarding RPC. This prevents us accessing `protected` members.\n * Instead, we define this function to extract these members, and provide type\n * safety for callers.\n */\nfunction getEntrypointState(instance: WorkerEntrypoint<Cloudflare.Env>): {\n\tctx: ExecutionContext;\n\tenv: Cloudflare.Env;\n};\nfunction getEntrypointState(instance: DurableObjectClass<Cloudflare.Env>): {\n\tctx: DurableObjectState;\n\tenv: Cloudflare.Env;\n};\nfunction getEntrypointState(\n\tinstance:\n\t\t| WorkerEntrypoint<Cloudflare.Env>\n\t\t| DurableObjectClass<Cloudflare.Env>\n) {\n\treturn instance as unknown as {\n\t\tctx: ExecutionContext | DurableObjectState;\n\t\tenv: Cloudflare.Env;\n\t};\n}\n\nconst WORKER_ENTRYPOINT_KEYS = [\n\t\"connect\",\n\t\"tailStream\",\n\t\"fetch\",\n\t\"tail\",\n\t\"trace\",\n\t\"scheduled\",\n\t\"queue\",\n\t\"test\",\n\t\"email\",\n] as const;\nconst DURABLE_OBJECT_KEYS = [\n\t\"connect\",\n\t\"fetch\",\n\t\"alarm\",\n\t\"webSocketMessage\",\n\t\"webSocketClose\",\n\t\"webSocketError\",\n] as const;\n// Handlers `workerd` treats as optional: when a Durable Object doesn't define\n// one, the corresponding event is silently dropped. We can't leave them off the\n// wrapper's prototype to get that behaviour for free — the prototype is built\n// before user code is loaded, so `workerd` always sees a handler and always\n// dispatches. The no-op has to be reproduced here instead.\n//\n// `alarm()` deliberately isn't in this set: `workerd` rejects `setAlarm()` up\n// front on a class with no `alarm()` handler, so a missing one is a real error.\nconst OPTIONAL_DURABLE_OBJECT_KEYS: ReadonlySet<\n\t(typeof DURABLE_OBJECT_KEYS)[number]\n> = new Set([\"webSocketMessage\", \"webSocketClose\", \"webSocketError\"] as const);\n\n// This type will grab the keys from T and remove \"branded\" keys\ntype UnbrandedKeys<T> = Exclude<keyof T, `__${string}_BRAND`>;\n\n// Check that we've included all possible keys\n// noinspection JSUnusedLocalSymbols\nconst _workerEntrypointExhaustive: (typeof WORKER_ENTRYPOINT_KEYS)[number] =\n\tundefined as unknown as UnbrandedKeys<WorkerEntrypoint<Cloudflare.Env>>;\n// noinspection JSUnusedLocalSymbols\nconst _durableObjectExhaustive: (typeof DURABLE_OBJECT_KEYS)[number] =\n\tundefined as unknown as UnbrandedKeys<DurableObjectClass<Cloudflare.Env>>;\n\n// =============================================================================\n// `WorkerEntrypoint` wrappers\n// =============================================================================\n\n// `WorkerEntrypoint` is `abstract`, so we need to cast before constructing\ntype WorkerEntrypointConstructor = {\n\tnew (\n\t\t...args: ConstructorParameters<typeof WorkerEntrypoint>\n\t): WorkerEntrypoint;\n};\n\n/**\n * Get the export to use for `entrypoint`. This is used for the `SELF` service\n * binding in `cloudflare:test`, which sets `entrypoint` to \"default\".\n * This requires importing the `main` module with Vite.\n */\nasync function getWorkerEntrypointExport(\n\tenv: Cloudflare.Env,\n\tentrypoint: string\n): Promise<{ mainPath: string; entrypointValue: unknown }> {\n\tconst mainPath = getResolvedMainPath(\"service\");\n\tconst mainModule = await importModule(mainPath);\n\tconst entrypointValue =\n\t\ttypeof mainModule === \"object\" &&\n\t\tmainModule !== null &&\n\t\tentrypoint in mainModule &&\n\t\tmainModule[entrypoint];\n\tif (!entrypointValue) {\n\t\tconst message =\n\t\t\t`${mainPath} does not export a ${entrypoint} entrypoint. \\`@cloudflare/vitest-plugin\\` does not support service workers or named entrypoints for \\`SELF\\`.\\n` +\n\t\t\t\"If you're using service workers, please migrate to the modules format: https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/\";\n\t\tthrow new TypeError(message);\n\t}\n\treturn { mainPath, entrypointValue };\n}\n\n/**\n * Get a property named `key` from the user's `WorkerEntrypoint`. `wrapper` here\n * is an instance of a `WorkerEntrypoint` wrapper (i.e. the return value of\n * `createWorkerEntrypointWrapper()`). This requires importing the `main` module\n * with Vite, so will always return a `Promise.`\n */\nasync function getWorkerEntrypointRPCProperty(\n\twrapper: WorkerEntrypoint<Cloudflare.Env>,\n\tentrypoint: string,\n\tkey: string\n): Promise<unknown> {\n\tconst { ctx } = getEntrypointState(wrapper);\n\tconst { mainPath, entrypointValue } = await getWorkerEntrypointExport(\n\t\truntimeEnv as Cloudflare.Env,\n\t\tentrypoint\n\t);\n\t// Ensure constructor and properties execute with ctx `AsyncLocalStorage` set\n\treturn patchAndRunWithHandlerContext(ctx, () => {\n\t\t// Use the dynamic env from `cloudflare:workers` to respect `withEnv()`\n\t\tconst env = runtimeEnv as Cloudflare.Env;\n\t\tconst expectedWorkerEntrypointMessage = `Expected ${entrypoint} export of ${mainPath} to be a subclass of \\`WorkerEntrypoint\\` for RPC`;\n\t\tif (typeof entrypointValue !== \"function\") {\n\t\t\tthrow new TypeError(expectedWorkerEntrypointMessage);\n\t\t}\n\t\tconst ctor = entrypointValue as WorkerEntrypointConstructor;\n\t\tconst instance = new ctor(ctx, env);\n\t\t// noinspection SuspiciousTypeOfGuard\n\t\tif (!(instance instanceof WorkerEntrypoint)) {\n\t\t\tthrow new TypeError(expectedWorkerEntrypointMessage);\n\t\t}\n\n\t\tconst value = getRPCProperty(ctor, instance, key);\n\t\tif (typeof value === \"function\") {\n\t\t\t// If this is a function, ensure it executes with ctx `AsyncLocalStorage`\n\t\t\t// set, and with a correctly bound `this`\n\t\t\treturn (...args: unknown[]) =>\n\t\t\t\tpatchAndRunWithHandlerContext(ctx, () => value.apply(instance, args));\n\t\t} else {\n\t\t\treturn value;\n\t\t}\n\t});\n}\n\nexport function createWorkerEntrypointWrapper(\n\tentrypoint: string\n): typeof WorkerEntrypoint {\n\tconst Wrapper = createProxyPrototypeClass(\n\t\tWorkerEntrypoint,\n\t\tfunction (this: WorkerEntrypoint<Cloudflare.Env>, key) {\n\t\t\t// All `ExportedHandler` keys are reserved and cannot be called over RPC\n\t\t\tif ((DURABLE_OBJECT_KEYS as readonly string[]).includes(key)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst property = getWorkerEntrypointRPCProperty(this, entrypoint, key);\n\t\t\treturn getRPCPropertyCallableThenable(key, property, this);\n\t\t}\n\t);\n\n\t// Add prototype methods for all default handlers\n\tfor (const key of WORKER_ENTRYPOINT_KEYS) {\n\t\tWrapper.prototype[key] = async function (\n\t\t\tthis: WorkerEntrypoint<Cloudflare.Env>,\n\t\t\tthing: unknown\n\t\t) {\n\t\t\tconst { mainPath, entrypointValue } = await getWorkerEntrypointExport(\n\t\t\t\tthis.env,\n\t\t\t\tentrypoint\n\t\t\t);\n\n\t\t\treturn patchAndRunWithHandlerContext(this.ctx, () => {\n\t\t\t\tif (typeof entrypointValue === \"object\" && entrypointValue !== null) {\n\t\t\t\t\t// Assuming the user has defined an `ExportedHandler`\n\t\t\t\t\tconst maybeFn = (entrypointValue as Record<string, unknown>)[key];\n\t\t\t\t\tif (typeof maybeFn === \"function\") {\n\t\t\t\t\t\treturn maybeFn.call(entrypointValue, thing, runtimeEnv, this.ctx);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst message = `Expected ${entrypoint} export of ${mainPath} to define a \\`${key}()\\` function`;\n\t\t\t\t\t\tthrow new TypeError(message);\n\t\t\t\t\t}\n\t\t\t\t} else if (typeof entrypointValue === \"function\") {\n\t\t\t\t\t// Assuming the user has defined a `WorkerEntrypoint` subclass\n\t\t\t\t\tconst ctor = entrypointValue as WorkerEntrypointConstructor;\n\t\t\t\t\tconst instance = new ctor(this.ctx, runtimeEnv);\n\t\t\t\t\t// noinspection SuspiciousTypeOfGuard\n\t\t\t\t\tif (!(instance instanceof WorkerEntrypoint)) {\n\t\t\t\t\t\tconst message = `Expected ${entrypoint} export of ${mainPath} to be a subclass of \\`WorkerEntrypoint\\``;\n\t\t\t\t\t\tthrow new TypeError(message);\n\t\t\t\t\t}\n\t\t\t\t\tconst maybeFn = instance[key];\n\t\t\t\t\tif (typeof maybeFn === \"function\") {\n\t\t\t\t\t\treturn (maybeFn as (arg: unknown) => unknown).call(instance, thing);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst message = `Expected ${entrypoint} export of ${mainPath} to define a \\`${key}()\\` method`;\n\t\t\t\t\t\tthrow new TypeError(message);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Assuming the user has messed up\n\t\t\t\t\tconst message = `Expected ${entrypoint} export of ${mainPath} to be an object or a class, got ${entrypointValue}`;\n\t\t\t\t\tthrow new TypeError(message);\n\t\t\t\t}\n\t\t\t});\n\t\t};\n\t}\n\treturn Wrapper;\n}\n\n// =============================================================================\n// `DurableObject` wrappers\n// =============================================================================\n\ntype DurableObjectConstructor = {\n\tnew (\n\t\t...args: ConstructorParameters<typeof DurableObjectClass>\n\t): DurableObject | DurableObjectClass;\n};\n\nconst kInstanceConstructor = Symbol(\"kInstanceConstructor\");\nconst kInstance = Symbol(\"kInstance\");\nconst kEnsureInstance = Symbol(\"kEnsureInstance\");\ntype DurableObjectWrapperExtraPrototype = {\n\t[kInstanceConstructor]: DurableObjectConstructor;\n\t[kInstance]:\n\t\t| DurableObject\n\t\t| DurableObjectClass<Record<string, unknown> | Cloudflare.Env>;\n\t[kEnsureInstance](): Promise<{\n\t\tmainPath: string;\n\t\tinstanceCtor: DurableObjectConstructor;\n\t\tinstance:\n\t\t\t| DurableObject\n\t\t\t| DurableObjectClass<Record<string, unknown> | Cloudflare.Env>;\n\t}>;\n};\ntype DurableObjectWrapper = DurableObjectClass<Cloudflare.Env> &\n\tDurableObjectWrapperExtraPrototype;\n\nasync function getDurableObjectRPCProperty(\n\twrapper: DurableObjectWrapper,\n\tclassName: string,\n\tkey: string\n): Promise<unknown> {\n\tconst { mainPath, instanceCtor, instance } = await wrapper[kEnsureInstance]();\n\tif (!(instance instanceof DurableObjectClass)) {\n\t\tconst message = `Expected ${className} exported by ${mainPath} be a subclass of \\`DurableObject\\` for RPC`;\n\t\tthrow new TypeError(message);\n\t}\n\tassertRPCPropertyAccessible(instanceCtor, instance, key);\n\t// `workerd` rejects constructor-assigned overrides of RPC methods, but a\n\t// constructor may return a Proxy that wraps a method from its prototype.\n\tif (Object.hasOwn(instance, key)) {\n\t\tthrow new TypeError(\n\t\t\t`The RPC receiver does not implement the method ${JSON.stringify(key)}.`\n\t\t);\n\t}\n\tconst value = Reflect.get(instance, key, instance);\n\tif (typeof value === \"function\") {\n\t\t// If this is a function, ensure correctly bound `this`\n\t\treturn value.bind(instance);\n\t} else {\n\t\treturn value;\n\t}\n}\n\nexport function createDurableObjectWrapper(\n\tclassName: string\n): typeof DurableObjectClass {\n\tconst Wrapper = createProxyPrototypeClass<\n\t\ttypeof DurableObjectClass,\n\t\tDurableObjectWrapperExtraPrototype\n\t>(DurableObjectClass, function (this: DurableObjectWrapper, key) {\n\t\t// All `ExportedHandler` keys are reserved and cannot be called over RPC\n\t\tif ((WORKER_ENTRYPOINT_KEYS as readonly string[]).includes(key)) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst property = getDurableObjectRPCProperty(this, className, key);\n\t\treturn getRPCPropertyCallableThenable(key, property, this);\n\t});\n\n\tWrapper.prototype[kEnsureInstance] = async function (\n\t\tthis: DurableObjectWrapper\n\t) {\n\t\tconst { ctx, env } = getEntrypointState(this);\n\t\tconst mainPath = getResolvedMainPath(\"Durable Object\");\n\t\t// `ensureInstance()` may be called multiple times concurrently.\n\t\t// We're assuming `importModule()` will only import the module once.\n\t\tconst mainModule = await importModule(mainPath);\n\t\tconst constructor = mainModule[className];\n\t\tif (typeof constructor !== \"function\") {\n\t\t\tthrow new TypeError(\n\t\t\t\t`${mainPath} does not export a ${className} Durable Object`\n\t\t\t);\n\t\t}\n\t\tthis[kInstanceConstructor] ??= constructor as DurableObjectConstructor;\n\t\tif (this[kInstanceConstructor] !== constructor) {\n\t\t\t// This would be if the module was invalidated\n\t\t\t// (i.e. source file changed), then the Durable Object was `fetch()`ed\n\t\t\t// again. We reset all Durable Object instances between each test, so it's\n\t\t\t// unlikely multiple constructors would be used by the same instance,\n\t\t\t// unless the user did something funky with Durable Objects outside tests.\n\t\t\tawait ctx.blockConcurrencyWhile<never>(() => {\n\t\t\t\t// Throw inside `blockConcurrencyWhile()` to abort this object\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`${mainPath} changed, invalidating this Durable Object. ` +\n\t\t\t\t\t\t\"Please retry the `DurableObjectStub#fetch()` call.\"\n\t\t\t\t);\n\t\t\t});\n\t\t\tassert.fail(\"Unreachable\");\n\t\t}\n\t\tif (this[kInstance] === undefined) {\n\t\t\tthis[kInstance] = new this[kInstanceConstructor](ctx, env);\n\t\t\t// Wait for any `blockConcurrencyWhile()`s in the constructor to complete\n\t\t\tawait ctx.blockConcurrencyWhile(async () => {});\n\t\t}\n\t\treturn {\n\t\t\tmainPath,\n\t\t\tinstanceCtor: this[kInstanceConstructor],\n\t\t\tinstance: this[kInstance],\n\t\t};\n\t};\n\n\t// Add prototype method for `fetch` handler to handle `runInDurableObject()`s\n\tWrapper.prototype.fetch = async function (\n\t\tthis: DurableObjectWrapper,\n\t\trequest: Request\n\t) {\n\t\tconst { ctx } = getEntrypointState(this);\n\n\t\t// Make sure we've initialised user code\n\t\tconst { mainPath, instance } = await this[kEnsureInstance]();\n\n\t\t// If this is an internal Durable Object action, handle it...\n\t\tconst response = await maybeHandleRunRequest(request, instance, ctx);\n\t\tif (response !== undefined) {\n\t\t\treturn response;\n\t\t}\n\n\t\t// Otherwise, pass through to the user code\n\t\tif (instance.fetch === undefined) {\n\t\t\tconst message = `${className} exported by ${mainPath} does not define a \\`fetch()\\` method`;\n\t\t\tthrow new TypeError(message);\n\t\t}\n\t\treturn instance.fetch(request);\n\t};\n\n\t// Add prototype methods for all other default handlers\n\tfor (const key of DURABLE_OBJECT_KEYS) {\n\t\tif (key === \"fetch\") {\n\t\t\tcontinue;\n\t\t} // `fetch()` has special handling above\n\t\tWrapper.prototype[key] = async function (\n\t\t\tthis: DurableObjectWrapper,\n\t\t\t...args: unknown[]\n\t\t) {\n\t\t\treturn enqueueInvocation(this, async (release) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst { mainPath, instance } = await this[kEnsureInstance]();\n\t\t\t\t\tconst maybeFn = instance[key];\n\t\t\t\t\tif (typeof maybeFn === \"function\") {\n\t\t\t\t\t\treturn (maybeFn as (...a: unknown[]) => void).apply(instance, args);\n\t\t\t\t\t} else if (OPTIONAL_DURABLE_OBJECT_KEYS.has(key)) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst message = `${className} exported by ${mainPath} does not define a \\`${key}()\\` method`;\n\t\t\t\t\t\tthrow new TypeError(message);\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\trelease();\n\t\t\t\t}\n\t\t\t});\n\t\t};\n\t}\n\n\treturn Wrapper;\n}\n\n// =============================================================================\n// `WorkflowEntrypoint` wrappers\n// =============================================================================\n\ntype WorkflowEntrypointConstructor = {\n\tnew (\n\t\t...args: ConstructorParameters<typeof WorkflowEntrypoint>\n\t): WorkflowEntrypoint;\n};\n\nexport function createWorkflowEntrypointWrapper(entrypoint: string) {\n\tconst Wrapper = createProxyPrototypeClass(\n\t\tWorkflowEntrypoint,\n\t\tfunction (this: WorkflowEntrypoint<Cloudflare.Env>, key) {\n\t\t\t// only Workflow `run` should be exposed over RPC\n\t\t\tif (![\"run\"].includes(key)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst property = getWorkerEntrypointRPCProperty(\n\t\t\t\tthis as unknown as WorkerEntrypoint<Cloudflare.Env>,\n\t\t\t\tentrypoint,\n\t\t\t\tkey\n\t\t\t);\n\t\t\treturn getRPCPropertyCallableThenable(key, property, this);\n\t\t}\n\t);\n\n\tWrapper.prototype.run = async function (\n\t\tthis: WorkflowEntrypoint<Cloudflare.Env>,\n\t\t...args\n\t) {\n\t\tconst { mainPath, entrypointValue } = await getWorkerEntrypointExport(\n\t\t\truntimeEnv,\n\t\t\tentrypoint\n\t\t);\n\t\t// workflow entrypoint value should always be a constructor\n\t\tif (typeof entrypointValue === \"function\") {\n\t\t\t// Assuming the user has defined a `WorkflowEntrypoint` subclass\n\t\t\tconst ctor = entrypointValue as WorkflowEntrypointConstructor;\n\t\t\tconst instance = new ctor(this.ctx, runtimeEnv);\n\t\t\t// noinspection SuspiciousTypeOfGuard\n\t\t\tif (!(instance instanceof WorkflowEntrypoint)) {\n\t\t\t\tconst message = `Expected ${entrypoint} export of ${mainPath} to be a subclass of \\`WorkflowEntrypoint\\``;\n\t\t\t\tthrow new TypeError(message);\n\t\t\t}\n\t\t\tconst maybeFn = instance[\"run\"];\n\t\t\tif (typeof maybeFn === \"function\") {\n\t\t\t\treturn patchAndRunWithHandlerContext(this.ctx, () =>\n\t\t\t\t\tmaybeFn.call(instance, ...args)\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tconst message = `Expected ${entrypoint} export of ${mainPath} to define a \\`run()\\` method, but got ${typeof maybeFn}`;\n\t\t\t\tthrow new TypeError(message);\n\t\t\t}\n\t\t} else {\n\t\t\t// Assuming the user has messed up\n\t\t\tconst message = `Expected ${entrypoint} export of ${mainPath} to be a subclass of \\`WorkflowEntrypoint\\`, but got ${entrypointValue}`;\n\t\t\tthrow new TypeError(message);\n\t\t}\n\t};\n\n\treturn Wrapper;\n}\n","import { exports } from \"cloudflare:workers\";\nimport { env } from \"./env\";\nimport { getCtxExportsProxy, isCtxExportsEnabled } from \"./patch-ctx\";\nimport { registerGlobalWaitUntil, waitForWaitUntil } from \"./wait-until\";\n\n// `workerd` doesn't allow these internal classes to be constructed directly.\n// To replicate this behaviour require this unique symbol to be specified as the\n// first constructor argument. If this is missing, throw `Illegal invocation`.\nconst kConstructFlag = Symbol(\"kConstructFlag\");\n\n// See public facing `cloudflare:test` types for docs.\n\n// =============================================================================\n// `ExecutionContext`\n// =============================================================================\n\nconst kWaitUntil = Symbol(\"kWaitUntil\");\nclass ExecutionContext {\n\t// https://github.com/cloudflare/workerd/blob/v1.20231218.0/src/workerd/api/global-scope.h#L168\n\t[kWaitUntil]: unknown[] = [];\n\n\tconstructor(flag: typeof kConstructFlag) {\n\t\tif (flag !== kConstructFlag) {\n\t\t\tthrow new TypeError(\"Illegal constructor\");\n\t\t}\n\t}\n\n\t// Expose the ctx.exports from the main \"SELF\" Worker if there is one.\n\treadonly exports = isCtxExportsEnabled(exports)\n\t\t? getCtxExportsProxy(exports)\n\t\t: undefined;\n\n\twaitUntil(promise: unknown) {\n\t\tif (!(this instanceof ExecutionContext)) {\n\t\t\tthrow new TypeError(\"Illegal invocation\");\n\t\t}\n\t\tthis[kWaitUntil].push(promise);\n\t\tregisterGlobalWaitUntil(promise);\n\t}\n\n\tpassThroughOnException(): void {}\n}\nexport function createExecutionContext(): ExecutionContext {\n\treturn new ExecutionContext(kConstructFlag);\n}\n\nfunction isExecutionContextLike(v: unknown): v is { [kWaitUntil]: unknown[] } {\n\treturn (\n\t\ttypeof v === \"object\" &&\n\t\tv !== null &&\n\t\tkWaitUntil in v &&\n\t\tArray.isArray(v[kWaitUntil])\n\t);\n}\nexport async function waitOnExecutionContext(ctx: unknown): Promise<void> {\n\tif (!isExecutionContextLike(ctx)) {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'getWaitUntil': parameter 1 is not of type 'ExecutionContext'.\\n\" +\n\t\t\t\t\"You must call 'createExecutionContext()' or 'createPagesEventContext()' to get an 'ExecutionContext' instance.\"\n\t\t);\n\t}\n\treturn waitForWaitUntil(ctx[kWaitUntil]);\n}\n\n// =============================================================================\n// `ScheduledController`\n// =============================================================================\n\nclass ScheduledController {\n\t// https://github.com/cloudflare/workerd/blob/v1.20231218.0/src/workerd/api/scheduled.h#L35\n\treadonly scheduledTime!: number;\n\treadonly cron!: string;\n\n\tconstructor(flag: typeof kConstructFlag, options?: FetcherScheduledOptions) {\n\t\tif (flag !== kConstructFlag) {\n\t\t\tthrow new TypeError(\"Illegal constructor\");\n\t\t}\n\n\t\tconst scheduledTime = Number(options?.scheduledTime ?? Date.now());\n\t\tconst cron = String(options?.cron ?? \"\");\n\n\t\t// Match `JSG_READONLY_INSTANCE_PROPERTY` behaviour\n\t\tObject.defineProperties(this, {\n\t\t\tscheduledTime: {\n\t\t\t\tget() {\n\t\t\t\t\treturn scheduledTime;\n\t\t\t\t},\n\t\t\t},\n\t\t\tcron: {\n\t\t\t\tget() {\n\t\t\t\t\treturn cron;\n\t\t\t\t},\n\t\t\t},\n\t\t});\n\t}\n\n\tnoRetry(): void {\n\t\tif (!(this instanceof ScheduledController)) {\n\t\t\tthrow new TypeError(\"Illegal invocation\");\n\t\t}\n\t}\n}\nexport function createScheduledController(\n\toptions?: FetcherScheduledOptions\n): ScheduledController {\n\tif (options !== undefined && typeof options !== \"object\") {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'createScheduledController': parameter 1 is not of type 'ScheduledOptions'.\"\n\t\t);\n\t}\n\treturn new ScheduledController(kConstructFlag, options);\n}\n\n// =============================================================================\n// `MessageBatch`\n// =============================================================================\n\nconst kRetry = Symbol(\"kRetry\");\nconst kAck = Symbol(\"kAck\");\nconst kRetryAll = Symbol(\"kRetryAll\");\nconst kAckAll = Symbol(\"kAckAll\");\nclass QueueMessage<Body = unknown> /* Message */ {\n\t// https://github.com/cloudflare/workerd/blob/v1.20231218.0/src/workerd/api/queue.h#L113\n\treadonly #controller: QueueController;\n\treadonly id!: string;\n\treadonly timestamp!: Date;\n\treadonly body!: Body;\n\treadonly attempts!: number;\n\t[kRetry] = false;\n\t[kAck] = false;\n\n\tconstructor(\n\t\tflag: typeof kConstructFlag,\n\t\tcontroller: QueueController,\n\t\tmessage: ServiceBindingQueueMessage<Body>\n\t) {\n\t\tif (flag !== kConstructFlag) {\n\t\t\tthrow new TypeError(\"Illegal constructor\");\n\t\t}\n\t\tthis.#controller = controller;\n\n\t\tconst id = String(message.id);\n\n\t\tlet timestamp: Date;\n\t\t// noinspection SuspiciousTypeOfGuard\n\t\tif (typeof message.timestamp === \"number\") {\n\t\t\ttimestamp = new Date(message.timestamp);\n\t\t} else if (message.timestamp instanceof Date) {\n\t\t\ttimestamp = new Date(message.timestamp.getTime()); // Prevent external mutations\n\t\t} else {\n\t\t\tthrow new TypeError(\n\t\t\t\t\"Incorrect type for the 'timestamp' field on 'ServiceBindingQueueMessage': the provided value is not of type 'date'.\"\n\t\t\t);\n\t\t}\n\n\t\tlet attempts: number;\n\t\t// noinspection SuspiciousTypeOfGuard\n\t\tif (typeof message.attempts === \"number\") {\n\t\t\tattempts = message.attempts;\n\t\t} else {\n\t\t\tthrow new TypeError(\n\t\t\t\t\"Incorrect type for the 'attempts' field on 'ServiceBindingQueueMessage': the provided value is not of type 'number'.\"\n\t\t\t);\n\t\t}\n\n\t\tif (\"serializedBody\" in message) {\n\t\t\tthrow new TypeError(\n\t\t\t\t\"Cannot use `serializedBody` with `createMessageBatch()`\"\n\t\t\t);\n\t\t}\n\t\tconst body = structuredClone(message.body); // Prevent external mutations\n\n\t\t// Match `JSG_READONLY_INSTANCE_PROPERTY` behaviour\n\t\tObject.defineProperties(this, {\n\t\t\tid: {\n\t\t\t\tget() {\n\t\t\t\t\treturn id;\n\t\t\t\t},\n\t\t\t},\n\t\t\ttimestamp: {\n\t\t\t\tget() {\n\t\t\t\t\treturn timestamp;\n\t\t\t\t},\n\t\t\t},\n\t\t\tbody: {\n\t\t\t\tget() {\n\t\t\t\t\treturn body;\n\t\t\t\t},\n\t\t\t},\n\t\t\tattempts: {\n\t\t\t\tget() {\n\t\t\t\t\treturn attempts;\n\t\t\t\t},\n\t\t\t},\n\t\t});\n\t}\n\n\tretry() {\n\t\tif (!(this instanceof QueueMessage)) {\n\t\t\tthrow new TypeError(\"Illegal invocation\");\n\t\t}\n\t\tif (this.#controller[kRetryAll]) {\n\t\t\treturn;\n\t\t}\n\t\tif (this.#controller[kAckAll]) {\n\t\t\tconsole.warn(\n\t\t\t\t`Received a call to retry() on message ${this.id} after ackAll() was already called. ` +\n\t\t\t\t\t\"Calling retry() on a message after calling ackAll() has no effect.\"\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (this[kAck]) {\n\t\t\tconsole.warn(\n\t\t\t\t`Received a call to retry() on message ${this.id} after ack() was already called. ` +\n\t\t\t\t\t\"Calling retry() on a message after calling ack() has no effect.\"\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tthis[kRetry] = true;\n\t}\n\n\tack() {\n\t\tif (!(this instanceof QueueMessage)) {\n\t\t\tthrow new TypeError(\"Illegal invocation\");\n\t\t}\n\t\tif (this.#controller[kAckAll]) {\n\t\t\treturn;\n\t\t}\n\t\tif (this.#controller[kRetryAll]) {\n\t\t\tconsole.warn(\n\t\t\t\t`Received a call to ack() on message ${this.id} after retryAll() was already called. ` +\n\t\t\t\t\t\"Calling ack() on a message after calling retryAll() has no effect.\"\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (this[kRetry]) {\n\t\t\tconsole.warn(\n\t\t\t\t`Received a call to ack() on message ${this.id} after retry() was already called. ` +\n\t\t\t\t\t\"Calling ack() on a message after calling retry() has no effect.\"\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tthis[kAck] = true;\n\t}\n}\nclass QueueController<Body = unknown> /* MessageBatch */ {\n\t// https://github.com/cloudflare/workerd/blob/v1.20231218.0/src/workerd/api/queue.h#L198\n\treadonly queue!: string;\n\treadonly messages!: QueueMessage<Body>[];\n\treadonly metadata!: MessageBatchMetadata;\n\t[kRetryAll] = false;\n\t[kAckAll] = false;\n\n\tconstructor(\n\t\tflag: typeof kConstructFlag,\n\t\tqueueOption: string,\n\t\tmessagesOption: ServiceBindingQueueMessage<Body>[]\n\t) {\n\t\tif (flag !== kConstructFlag) {\n\t\t\tthrow new TypeError(\"Illegal constructor\");\n\t\t}\n\n\t\tconst queue = String(queueOption);\n\t\tconst messages = messagesOption.map(\n\t\t\t(message) => new QueueMessage(kConstructFlag, this, message)\n\t\t);\n\t\tconst metadata: MessageBatchMetadata = {\n\t\t\tmetrics: {\n\t\t\t\tbacklogCount: 0,\n\t\t\t\tbacklogBytes: 0,\n\t\t\t\toldestMessageTimestamp: new Date(0),\n\t\t\t},\n\t\t};\n\n\t\t// Match `JSG_READONLY_INSTANCE_PROPERTY` behaviour\n\t\tObject.defineProperties(this, {\n\t\t\tqueue: {\n\t\t\t\tget() {\n\t\t\t\t\treturn queue;\n\t\t\t\t},\n\t\t\t},\n\t\t\tmessages: {\n\t\t\t\tget() {\n\t\t\t\t\treturn messages;\n\t\t\t\t},\n\t\t\t},\n\t\t\tmetadata: {\n\t\t\t\tget() {\n\t\t\t\t\treturn metadata;\n\t\t\t\t},\n\t\t\t},\n\t\t});\n\t}\n\n\tretryAll() {\n\t\tif (!(this instanceof QueueController)) {\n\t\t\tthrow new TypeError(\"Illegal invocation\");\n\t\t}\n\t\tif (this[kAckAll]) {\n\t\t\tconsole.warn(\n\t\t\t\t\"Received a call to retryAll() after ackAll() was already called. \" +\n\t\t\t\t\t\"Calling retryAll() after calling ackAll() has no effect.\"\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tthis[kRetryAll] = true;\n\t}\n\n\tackAll() {\n\t\tif (!(this instanceof QueueController)) {\n\t\t\tthrow new TypeError(\"Illegal invocation\");\n\t\t}\n\t\tif (this[kRetryAll]) {\n\t\t\tconsole.warn(\n\t\t\t\t\"Received a call to ackAll() after retryAll() was already called. \" +\n\t\t\t\t\t\"Calling ackAll() after calling retryAll() has no effect.\"\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tthis[kAckAll] = true;\n\t}\n}\nexport function createMessageBatch<Body = unknown>(\n\tqueueName: string,\n\tmessages: ServiceBindingQueueMessage<Body>[]\n): MessageBatch<Body> {\n\tif (arguments.length === 0) {\n\t\t// `queueName` will be coerced to a `string`, but it must be defined\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'createMessageBatch': parameter 1 is not of type 'string'.\"\n\t\t);\n\t}\n\tif (!Array.isArray(messages)) {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'createMessageBatch': parameter 2 is not of type 'Array'.\"\n\t\t);\n\t}\n\treturn new QueueController(kConstructFlag, queueName, messages);\n}\nexport async function getQueueResult(\n\tbatch: QueueController,\n\tctx: ExecutionContext\n): Promise<FetcherQueueResult> {\n\t// noinspection SuspiciousTypeOfGuard\n\tif (!(batch instanceof QueueController)) {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'getQueueResult': parameter 1 is not of type 'MessageBatch'.\\n\" +\n\t\t\t\t\"You must call 'createMessageBatch()' to get a 'MessageBatch' instance.\"\n\t\t);\n\t}\n\t// noinspection SuspiciousTypeOfGuard\n\tif (!(ctx instanceof ExecutionContext)) {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'getQueueResult': parameter 2 is not of type 'ExecutionContext'.\\n\" +\n\t\t\t\t\"You must call 'createExecutionContext()' to get an 'ExecutionContext' instance.\"\n\t\t);\n\t}\n\tawait waitOnExecutionContext(ctx);\n\n\tconst retryMessages: QueueRetryMessage[] = [];\n\tconst explicitAcks: string[] = [];\n\tfor (const message of batch.messages) {\n\t\tif (message[kRetry]) {\n\t\t\tretryMessages.push({ msgId: message.id });\n\t\t}\n\t\tif (message[kAck]) {\n\t\t\texplicitAcks.push(message.id);\n\t\t}\n\t}\n\treturn {\n\t\toutcome: \"ok\",\n\t\tretryBatch: {\n\t\t\tretry: batch[kRetryAll],\n\t\t},\n\t\tackAll: batch[kAckAll],\n\t\tretryMessages,\n\t\texplicitAcks,\n\t};\n}\n\n// =============================================================================\n// Pages Functions `EventContext`\n// =============================================================================\n\nfunction hasASSETSServiceBinding(\n\tvalue: Record<string, unknown>\n): value is Record<string, unknown> & { ASSETS: Fetcher } {\n\treturn (\n\t\t\"ASSETS\" in value &&\n\t\ttypeof value.ASSETS === \"object\" &&\n\t\tvalue.ASSETS !== null &&\n\t\t\"fetch\" in value.ASSETS &&\n\t\ttypeof value.ASSETS.fetch === \"function\"\n\t);\n}\n\ninterface EventContextInit {\n\trequest: Request<unknown, IncomingRequestCfProperties>;\n\tfunctionPath?: string;\n\tnext?(request: Request): Response | Promise<Response>;\n\tparams?: Record<string, string | string[]>;\n\tdata?: Record<string, unknown>;\n}\n\nexport function createPagesEventContext<F extends PagesFunction>(\n\topts: EventContextInit\n): Parameters<F>[0] & { [kWaitUntil]: unknown[] } {\n\tif (typeof opts !== \"object\" || opts === null) {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'createPagesEventContext': parameter 1 is not of type 'EventContextInit'.\"\n\t\t);\n\t}\n\tif (!(opts.request instanceof Request)) {\n\t\tthrow new TypeError(\n\t\t\t\"Incorrect type for the 'request' field on 'EventContextInit': the provided value is not of type 'Request'.\"\n\t\t);\n\t}\n\t// noinspection SuspiciousTypeOfGuard\n\tif (\n\t\topts.functionPath !== undefined &&\n\t\ttypeof opts.functionPath !== \"string\"\n\t) {\n\t\tthrow new TypeError(\n\t\t\t\"Incorrect type for the 'functionPath' field on 'EventContextInit': the provided value is not of type 'string'.\"\n\t\t);\n\t}\n\tif (opts.next !== undefined && typeof opts.next !== \"function\") {\n\t\tthrow new TypeError(\n\t\t\t\"Incorrect type for the 'next' field on 'EventContextInit': the provided value is not of type 'function'.\"\n\t\t);\n\t}\n\tif (\n\t\topts.params !== undefined &&\n\t\t!(typeof opts.params === \"object\" && opts.params !== null)\n\t) {\n\t\tthrow new TypeError(\n\t\t\t\"Incorrect type for the 'params' field on 'EventContextInit': the provided value is not of type 'object'.\"\n\t\t);\n\t}\n\tif (\n\t\topts.data !== undefined &&\n\t\t!(typeof opts.data === \"object\" && opts.data !== null)\n\t) {\n\t\tthrow new TypeError(\n\t\t\t\"Incorrect type for the 'data' field on 'EventContextInit': the provided value is not of type 'object'.\"\n\t\t);\n\t}\n\n\tif (!hasASSETSServiceBinding(env)) {\n\t\tthrow new TypeError(\n\t\t\t\"Cannot call `createPagesEventContext()` without defining `ASSETS` service binding\"\n\t\t);\n\t}\n\n\tconst ctx = createExecutionContext();\n\treturn {\n\t\t// If we might need to re-use this request, clone it\n\t\trequest: opts.next ? opts.request.clone() : opts.request,\n\t\tfunctionPath: opts.functionPath ?? \"\",\n\t\t[kWaitUntil]: ctx[kWaitUntil],\n\t\twaitUntil: ctx.waitUntil.bind(ctx),\n\t\tpassThroughOnException: ctx.passThroughOnException.bind(ctx),\n\t\tasync next(nextInput, nextInit) {\n\t\t\tif (opts.next === undefined) {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t\"Cannot call `EventContext#next()` without including `next` property in 2nd argument to `createPagesEventContext()`\"\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (nextInput === undefined) {\n\t\t\t\treturn opts.next(opts.request);\n\t\t\t} else {\n\t\t\t\tif (typeof nextInput === \"string\") {\n\t\t\t\t\tnextInput = new URL(nextInput, opts.request.url).toString();\n\t\t\t\t}\n\t\t\t\tconst nextRequest = new Request(nextInput, nextInit);\n\t\t\t\treturn opts.next(nextRequest);\n\t\t\t}\n\t\t},\n\t\tenv,\n\t\tparams: opts.params ?? {},\n\t\tdata: opts.data ?? {},\n\t};\n}\n","import workerdUnsafe from \"workerd:unsafe\";\nimport type { DurableObjectEvictionOptions } from \"workerd:unsafe\";\n\nconst DEFAULT_EVICTION_OPTIONS: DurableObjectEvictionOptions = {\n\twebSockets: \"hibernate\",\n};\n\nexport async function reset(): Promise<void> {\n\tawait workerdUnsafe.deleteAllDurableObjects();\n}\n\nexport async function abortAllDurableObjects(): Promise<void> {\n\tawait workerdUnsafe.abortAllDurableObjects();\n}\n\n// See public facing `cloudflare:test` types for docs\nexport async function evictAllDurableObjects(\n\toptions: DurableObjectEvictionOptions = DEFAULT_EVICTION_OPTIONS\n): Promise<void> {\n\tawait workerdUnsafe.evictAllDurableObjects(options);\n}\n","import type { SecretsStoreSecretAdmin } from \"miniflare\";\n\n// Must match ADMIN_API in miniflare/src/workers/secrets-store/constants.ts\nconst ADMIN_API = \"SecretsStoreSecret::admin_api\";\n\n/**\n * Returns the admin API for a secrets store binding, allowing tests to\n * create, update, and delete secrets that would otherwise be read-only.\n *\n * ```ts\n * import { adminSecretsStore } from \"cloudflare:test\";\n *\n * const admin = adminSecretsStore(env.MY_SECRET);\n * await admin.create(\"my-secret-value\");\n * ```\n */\nexport function adminSecretsStore(binding: unknown): SecretsStoreSecretAdmin {\n\tif (\n\t\ttypeof binding !== \"object\" ||\n\t\tbinding === null ||\n\t\ttypeof (binding as Record<string, unknown>)[ADMIN_API] !== \"function\"\n\t) {\n\t\tthrow new TypeError(\n\t\t\t\"Failed to execute 'adminSecretsStore': parameter 1 is not a secrets store binding.\"\n\t\t);\n\t}\n\n\treturn (binding as Record<string, (...args: unknown[]) => unknown>)[\n\t\tADMIN_API\n\t]() as SecretsStoreSecretAdmin;\n}\n","import type {\n\tModifierCallback,\n\tWorkflowBinding,\n\tWorkflowInstanceIntrospector,\n\tWorkflowInstanceModifier,\n\tWorkflowIntrospectionOperation,\n\tWorkflowIntrospectionStreamResult,\n\tWorkflowIntrospector,\n\tWorkflowStepSelector,\n} from \"./types\";\n\nfunction normalizeStreamMockChunk(value: unknown): Uint8Array {\n\tif (value instanceof Uint8Array) {\n\t\treturn value;\n\t}\n\n\tif (value instanceof ArrayBuffer) {\n\t\treturn new Uint8Array(value);\n\t}\n\n\tif (ArrayBuffer.isView(value) && !(value instanceof DataView)) {\n\t\treturn new Uint8Array(value.buffer, value.byteOffset, value.byteLength);\n\t}\n\n\tthrow new TypeError(\n\t\t\"Workflow mockStepResult() ReadableStream chunks must be ArrayBuffer or TypedArray values.\"\n\t);\n}\n\nasync function readStreamMockChunks(\n\tstream: ReadableStream<unknown>\n): Promise<Uint8Array[]> {\n\tif (stream.locked) {\n\t\tthrow new TypeError(\n\t\t\t\"Workflow mockStepResult() received a locked or unreadable ReadableStream.\"\n\t\t);\n\t}\n\n\tconst chunks: Uint8Array[] = [];\n\tconst reader = stream.getReader();\n\tlet fullyRead = false;\n\ttry {\n\t\twhile (true) {\n\t\t\tconst result = await reader.read();\n\t\t\tif (result.done) {\n\t\t\t\tfullyRead = true;\n\t\t\t\treturn chunks;\n\t\t\t}\n\n\t\t\tconst chunk = normalizeStreamMockChunk(result.value);\n\t\t\tif (chunk.byteLength === 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tchunks.push(chunk.slice());\n\t\t}\n\t} finally {\n\t\tif (!fullyRead) {\n\t\t\tawait reader\n\t\t\t\t.cancel(\"stream mock consumption stopped before completion\")\n\t\t\t\t.catch(() => {});\n\t\t}\n\t\ttry {\n\t\t\treader.releaseLock();\n\t\t} catch {\n\t\t\t/** Reader may still be processing cancel(). */\n\t\t}\n\t}\n}\n\nexport class WorkflowInstanceModificationRecorder implements WorkflowInstanceModifier {\n\tconstructor(private readonly operations: WorkflowIntrospectionOperation[]) {}\n\n\tasync disableSleeps(steps?: WorkflowStepSelector[]): Promise<void> {\n\t\tthis.operations.push({ type: \"disableSleeps\", steps });\n\t}\n\n\tasync disableRetryDelays(steps?: WorkflowStepSelector[]): Promise<void> {\n\t\tthis.operations.push({ type: \"disableRetryDelays\", steps });\n\t}\n\n\tasync mockStepResult(\n\t\tstep: WorkflowStepSelector,\n\t\tstepResult: unknown\n\t): Promise<void> {\n\t\tif (stepResult instanceof ReadableStream) {\n\t\t\tconst streamResult: WorkflowIntrospectionStreamResult = {\n\t\t\t\t__workflowIntrospectionStreamResult: true,\n\t\t\t\tchunks: await readStreamMockChunks(stepResult),\n\t\t\t};\n\t\t\tthis.operations.push({\n\t\t\t\ttype: \"mockStepResult\",\n\t\t\t\tstep,\n\t\t\t\tstepResult: streamResult,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tthis.operations.push({ type: \"mockStepResult\", step, stepResult });\n\t}\n\n\tasync mockStepError(\n\t\tstep: WorkflowStepSelector,\n\t\terror: Error,\n\t\ttimes?: number\n\t): Promise<void> {\n\t\tthis.operations.push({\n\t\t\ttype: \"mockStepError\",\n\t\t\tstep,\n\t\t\terror: { name: error.name, message: error.message },\n\t\t\ttimes,\n\t\t});\n\t}\n\n\tasync forceStepTimeout(\n\t\tstep: WorkflowStepSelector,\n\t\ttimes?: number\n\t): Promise<void> {\n\t\tthis.operations.push({ type: \"forceStepTimeout\", step, times });\n\t}\n\n\tasync mockEvent(event: { type: string; payload: unknown }): Promise<void> {\n\t\tthis.operations.push({ type: \"mockEvent\", event });\n\t}\n\n\tasync forceEventTimeout(step: WorkflowStepSelector): Promise<void> {\n\t\tthis.operations.push({ type: \"forceEventTimeout\", step });\n\t}\n}\n\nexport class WorkflowIntrospectorHandle implements WorkflowIntrospector {\n\t#disposed = false;\n\t#sessionId: string | undefined;\n\t#instanceIntrospectors = new Map<string, WorkflowInstanceIntrospector>();\n\t#operations: WorkflowIntrospectionOperation[] = [];\n\n\tconstructor(private readonly workflow: WorkflowBinding) {}\n\n\tasync start(): Promise<void> {\n\t\tthis.#sessionId = await this.workflow.unsafeStartIntrospection();\n\t}\n\n\tprivate getSessionId(): string {\n\t\tif (this.#sessionId === undefined) {\n\t\t\tthrow new Error(\"Workflow introspection has not started.\");\n\t\t}\n\t\treturn this.#sessionId;\n\t}\n\n\tasync modifyAll(fn: ModifierCallback): Promise<void> {\n\t\tconst sessionId = this.getSessionId();\n\t\tawait fn(new WorkflowInstanceModificationRecorder(this.#operations));\n\t\tawait this.workflow.unsafeSetIntrospectionOperations(\n\t\t\tsessionId,\n\t\t\tthis.#operations\n\t\t);\n\t}\n\n\tasync get(): Promise<WorkflowInstanceIntrospector[]> {\n\t\tconst sessionId = this.getSessionId();\n\t\tawait this.syncInstanceIntrospectors(sessionId);\n\n\t\treturn Array.from(this.#instanceIntrospectors.values());\n\t}\n\n\tprivate async syncInstanceIntrospectors(sessionId: string): Promise<void> {\n\t\tconst instanceIds =\n\t\t\tawait this.workflow.unsafeGetIntrospectionInstances(sessionId);\n\n\t\tfor (const instanceId of instanceIds) {\n\t\t\tif (!this.#instanceIntrospectors.has(instanceId)) {\n\t\t\t\tthis.#instanceIntrospectors.set(\n\t\t\t\t\tinstanceId,\n\t\t\t\t\tnew WorkflowInstanceIntrospectorHandle(this.workflow, instanceId)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async stopIntrospectionSession(sessionId: string): Promise<void> {\n\t\ttry {\n\t\t\tawait this.syncInstanceIntrospectors(sessionId);\n\t\t} finally {\n\t\t\tawait this.workflow.unsafeStopIntrospection(sessionId);\n\t\t}\n\t}\n\n\tprivate async disposeInstanceIntrospectors(): Promise<void> {\n\t\ttry {\n\t\t\tawait Promise.all(\n\t\t\t\tArray.from(this.#instanceIntrospectors.values(), (introspector) =>\n\t\t\t\t\tintrospector.dispose()\n\t\t\t\t)\n\t\t\t);\n\t\t} finally {\n\t\t\tthis.#instanceIntrospectors.clear();\n\t\t}\n\t}\n\n\t/** Keep this bound; explicit resource management may call the disposer unbound. */\n\tdispose = async (): Promise<void> => {\n\t\tif (this.#disposed) {\n\t\t\treturn;\n\t\t}\n\t\tthis.#disposed = true;\n\t\tconst sessionId = this.#sessionId;\n\n\t\ttry {\n\t\t\tif (sessionId !== undefined) {\n\t\t\t\tawait this.stopIntrospectionSession(sessionId);\n\t\t\t}\n\t\t} finally {\n\t\t\tawait this.disposeInstanceIntrospectors();\n\t\t}\n\t};\n\n\tasync [Symbol.asyncDispose](): Promise<void> {\n\t\tawait this.dispose();\n\t}\n}\n\nexport class WorkflowInstanceIntrospectorHandle implements WorkflowInstanceIntrospector {\n\t#instanceModifier: WorkflowInstanceModifier | undefined;\n\t#instanceModifierPromise: Promise<WorkflowInstanceModifier> | undefined;\n\n\tconstructor(\n\t\tprivate readonly workflow: WorkflowBinding,\n\t\tprivate readonly instanceId: string\n\t) {\n\t\tthis.#instanceModifierPromise = workflow\n\t\t\t.unsafeGetInstanceModifier(instanceId)\n\t\t\t.then((modifier) => {\n\t\t\t\tthis.#instanceModifier = modifier as WorkflowInstanceModifier;\n\t\t\t\tthis.#instanceModifierPromise = undefined;\n\t\t\t\treturn this.#instanceModifier;\n\t\t\t});\n\n\t\t// To avoid an unhandled rejection when the handle is used without modify()\n\t\tvoid this.#instanceModifierPromise.catch(() => {});\n\t}\n\n\tasync modify(fn: ModifierCallback): Promise<WorkflowInstanceIntrospector> {\n\t\tif (this.#instanceModifierPromise !== undefined) {\n\t\t\tthis.#instanceModifier = await this.#instanceModifierPromise;\n\t\t}\n\t\tif (this.#instanceModifier === undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t\"could not apply modifications due to internal error. Retrying the test may resolve the issue.\"\n\t\t\t);\n\t\t}\n\n\t\tawait fn(this.#instanceModifier);\n\n\t\treturn this;\n\t}\n\n\tasync waitForStepResult(step: WorkflowStepSelector): Promise<unknown> {\n\t\treturn await this.workflow.unsafeWaitForStepResult(\n\t\t\tthis.instanceId,\n\t\t\tstep.name,\n\t\t\tstep.index\n\t\t);\n\t}\n\n\tasync waitForStatus(status: string): Promise<void> {\n\t\tif (status === \"queued\") {\n\t\t\treturn;\n\t\t}\n\n\t\tawait this.workflow.unsafeWaitForStatus(this.instanceId, status);\n\t}\n\n\tasync getOutput(): Promise<unknown> {\n\t\treturn await this.workflow.unsafeGetOutputOrError(this.instanceId, true);\n\t}\n\n\tasync getError(): Promise<{ name: string; message: string }> {\n\t\treturn (await this.workflow.unsafeGetOutputOrError(\n\t\t\tthis.instanceId,\n\t\t\tfalse\n\t\t)) as { name: string; message: string };\n\t}\n\n\t/** Keep this bound; explicit resource management may call the disposer unbound. */\n\tdispose = async (): Promise<void> => {\n\t\tawait this.workflow.unsafeAbort(this.instanceId, \"Instance dispose\");\n\t};\n\n\tasync [Symbol.asyncDispose](): Promise<void> {\n\t\tawait this.dispose();\n\t}\n}\n","import {\n\tWorkflowInstanceIntrospectorHandle,\n\tWorkflowIntrospectorHandle,\n} from \"@cloudflare/workflows-shared/src/introspection\";\nimport type {\n\tWorkflowBinding,\n\tWorkflowInstanceIntrospector,\n\tWorkflowIntrospector,\n} from \"@cloudflare/workflows-shared/src/types\";\n\n// Note(osilva): `introspectWorkflowInstance()` doesn’t need to be async, but we keep it that way\n// to avoid potential breaking changes later and to stay consistent with `introspectWorkflow`.\n\n// In the \"cloudflare:test\" module, the exposed type is `Workflow`. Here we use `WorkflowBinding`\n// (which implements `Workflow`) to access unsafe functions.\nexport async function introspectWorkflowInstance(\n\tworkflow: WorkflowBinding,\n\tinstanceId: string\n): Promise<WorkflowInstanceIntrospector> {\n\tif (!workflow || !instanceId) {\n\t\tthrow new Error(\n\t\t\t\"[WorkflowIntrospector] Workflow binding and instance id are required.\"\n\t\t);\n\t}\n\treturn new WorkflowInstanceIntrospectorHandle(workflow, instanceId);\n}\n\n// Note(osilva): `introspectWorkflow` could be sync with some changes, but we keep it async\n// to avoid potential breaking changes later.\n\n// In the \"cloudflare:test\" module, the exposed type is `Workflow`. Here we use `WorkflowBinding`\n// (which implements `Workflow`) to access unsafe functions.\nexport async function introspectWorkflow(\n\tworkflow: WorkflowBinding\n): Promise<WorkflowIntrospector> {\n\tif (!workflow) {\n\t\tthrow new Error(\"[WorkflowIntrospector] Workflow binding is required.\");\n\t}\n\n\tconst introspector = new WorkflowIntrospectorHandle(workflow);\n\tawait introspector.start();\n\treturn introspector;\n}\n"],"mappings":";;;;;;AAEA,SAAS,aAAa,GAA6B;AAClD,QACC,OAAO,MAAM,YACb,MAAM,QACN,EAAE,YAAY,SAAS,gBACvB,aAAa,KACb,OAAO,EAAE,YAAY,cACrB,WAAW,KACX,OAAO,EAAE,UAAU,cACnB,UAAU,KACV,OAAO,EAAE,SAAS;;AAIpB,SAAS,cAAc,GAA8B;AACpD,QACC,OAAO,MAAM,YACb,MAAM,QACN,UAAU,KACV,OAAO,EAAE,SAAS,YAClB,aAAa,KACb,MAAM,QAAQ,EAAE,QAAQ,IACxB,EAAE,QAAQ,OAAO,UAAU,OAAO,UAAU,SAAS;;AAGvD,SAAS,eAAe,GAAgC;AACvD,QAAO,MAAM,QAAQ,EAAE,IAAI,EAAE,MAAM,cAAc;;AAGlD,eAAsB,kBACrB,IACA,YACA,sBAAsB,iBACrB;AACD,KAAI,CAAC,aAAa,GAAG,CACpB,OAAM,IAAI,UACT,kFACA;AAEF,KAAI,CAAC,eAAe,WAAW,CAC9B,OAAM,IAAI,UACT,qFACA;AAGF,KAAI,OAAO,wBAAwB,SAClC,OAAM,IAAI,UACT,8EACA;CAGF,MAAM,YAAY,OAAe,IAAI,GAAG,QAAQ,MAAM,OAAK,CAAC;CAC5D,MAAM,mBAAmB,SAAS,oBAAoB;CAGtD,MAAM,SAAS,8BAA8B,iBAAiB;;;;;AAK9D,OAAM,GAAG,QAAQ,OAAO,CAAC,KAAK;CAM9B,MAAM,yBAH8B,MAAM,GACxC,QAAQ,oBAAoB,iBAAiB,GAAG,CAChD,KAAuB,EACiC,QAAQ,KAChE,EAAE,WAAW,KACd;CAGD,MAAM,sBAAsB,GAAG,QAC9B,eAAe,iBAAiB,qBAChC;AACD,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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/vitest-plugin",
3
- "version": "1.1.1",
3
+ "version": "1.1.2",
4
4
  "description": "Workers Vitest integration for writing Vitest unit and integration tests that run inside the Workers runtime",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -45,11 +45,11 @@
45
45
  "cjs-module-lexer": "1.2.3",
46
46
  "esbuild": "0.28.1",
47
47
  "zod": "4.4.3",
48
- "miniflare": "5.20260826.0-alpha",
49
- "wrangler": "4.127.0"
48
+ "miniflare": "5.20260828.0-alpha",
49
+ "wrangler": "4.127.1"
50
50
  },
51
51
  "devDependencies": {
52
- "@cloudflare/workers-types": "^5.20260826.1",
52
+ "@cloudflare/workers-types": "^5.20260828.1",
53
53
  "@types/node": "22.15.17",
54
54
  "@types/semver": "^7.5.1",
55
55
  "@vitest/runner": "4.1.0",
@@ -66,11 +66,11 @@
66
66
  "typescript": "5.8.3",
67
67
  "undici": "7.29.0",
68
68
  "vitest": "4.1.0",
69
- "@cloudflare/config": "0.8.0",
70
69
  "@cloudflare/mock-npm-registry": "0.0.0",
71
- "@cloudflare/workers-utils": "0.34.0",
70
+ "@cloudflare/config": "0.9.0",
71
+ "@cloudflare/remote-bindings": "0.0.17",
72
72
  "@cloudflare/workers-tsconfig": "0.0.0",
73
- "@cloudflare/remote-bindings": "0.0.16",
73
+ "@cloudflare/workers-utils": "0.34.0",
74
74
  "@cloudflare/workflows-shared": "0.13.0"
75
75
  },
76
76
  "peerDependencies": {