import { HonoRequest } from "hono/request"; import { AuthenticationException, Controller, InertiaPageContractLike, InertiaResponseOptions, JsonResource, Resource, ServiceProvider, ValidationException, always, collect, defer, defineModule, definePlugin, formatValidationErrors, live } from "@guren/server/internal/testing"; import { Application, Authenticatable, Container, Context, DerivedAgentTool, EnvSchema, Event, EventClass, EventListener, EventSubscription, FailedJob, I18nPluginOptions, InertiaPagePayload, InertiaPropsInput, InertiaResponse, JobClass, ListenerOptions, MailMessage, MailTransport, QueueDriver, QueuedJob, ResolvedInertiaProps, ResolvedSharedInertiaProps, RouteDefinition, Router, SendResult, ToolCallOutcome } from "@guren/server"; import { Hono } from "hono"; import { Agent, AgentClass, AgentPrincipalInput, AgentResponse, AiEvaluationModel, AiEvaluationQuestions, AiManager, BoundAgentFactory, ConversationStore, bindAgent, resolveAgentName } from "@guren/plugin-ai"; import { EmbeddingModel, ImageModel, LanguageModel, experimental_evaluate, simulateStreamingMiddleware, wrapLanguageModel } from "ai"; import { Experimental_EvaluationMockModelV4, MockEmbeddingModelV4, MockImageModelV4, MockLanguageModelV4 } from "ai/test"; //#region src/auth.d.ts interface MockUser { id: number; email: string; password: string; emailVerifiedAt?: Date | null; getAuthIdentifier(): number; getAuthPassword(): string; } interface MockUserProvider { retrieveById: (id: unknown) => Promise; retrieveByCredentials: (credentials: Record) => Promise; validateCredentials: (user: T, credentials: Record) => Promise; getId: (user: T) => unknown; } interface MockAuthContext { check: () => Promise; guest: () => Promise; user: () => Promise; userOrFail: () => Promise; id: () => Promise; login: (user: T, remember?: boolean) => Promise; logout: () => Promise; attempt: (credentials: Record, remember?: boolean) => Promise; guard: (name?: string) => any; session: () => T | undefined; } declare function createMockUser(data: { id: number; email: string; password: string; emailVerifiedAt?: Date | null; }): MockUser; declare function createMockProvider(users: T[]): MockUserProvider; declare function createMockAuthContext(options: { isAuthenticated: boolean; user?: { id: number; name: string; }; }): MockAuthContext; //#endregion //#region src/inertia.d.ts interface MockInertiaPage> { component: string; props: TProps; url: string; version?: string; } declare function getInertiaPage(): MockInertiaPage; declare function setInertiaPage(page: Partial>): void; declare function resetInertiaPage(): void; declare function createInertiaReactMock(actual?: Record, overrides?: Record): { usePage: () => MockInertiaPage; }; //#endregion //#region src/controller.d.ts interface ControllerContext { var?: { container?: { make: (key: string) => T; has?: (key: string) => boolean; }; [key: string]: unknown; }; req: { raw: Request; path: string; url: string; method: string; query: (key?: string) => string | undefined | Record; queries: () => Record; param: (key?: string) => string | Record | undefined; header: (name: string) => string | undefined; json: HonoRequest['json']; parseBody: HonoRequest['parseBody']; }; get: (key: string) => unknown; set: (key: string, value: unknown) => void; header: (name: string, value: string) => void; status: (code: number) => void; } type InertiaPayload = InertiaPagePayload; /** * Context values that stand in for the route contract middleware, for a controller * action reading `this.validated()`: spread into `createControllerContext`'s * `contextValues`. Values are passed through as the schemas would have parsed them. */ declare function contractInput(input: { route?: string; params?: Record; query?: Record; body?: unknown; }): Record; declare function createControllerContext(url: string, init?: RequestInit, contextValues?: Record): ControllerContext; declare function createGurenControllerModule(): { Controller: { new (): { context: ControllerContext | undefined; setContext(context: ControllerContext): void; get ctx(): ControllerContext; make(key: string): T; text(body: string, init?: ResponseInit): Response; inertia(componentOrPage: string | { id: string; component?: string; }, props: Record, options?: Record): Promise; /** * Delegates to the real `renderDocument()` — the same engine `Controller.view()` * uses — so the mock cannot drift on escaping, the fragment guard or shaping. */ view(component: ((props: never) => unknown) & { displayName?: string; name?: string; }, props: unknown, options?: ResponseInit & { doctype?: boolean; }): Promise; }; }; /** * The real `viteAsset()`: under vitest it takes the dev branch, while a test that * forces production gets the real manifest lookup and its missing-entry throw. * Sync by contract, so it reads the lazily-primed memo (see `loadServer`). */ viteAsset: (entry: string, options?: { manifestPaths?: string[]; }) => string; parseRequestPayload: (ctx: ControllerContext) => Promise>; formatValidationErrors: typeof formatValidationErrors; always: typeof always; defer: typeof defer; live: typeof live; }; /** * The runtime's own `Controller`, so every request, validation and response helper is * the one production runs. Overridden only where the runtime needs a booted app. * Top-level rather than inside the factory: the declaration then names the base * class, which is what lets it keep its private members (TS4094). */ declare class TestController extends Controller { setContext(context: Context | ControllerContext): void; protected inertia>(component: Component, props: Props, options?: InertiaResponseOptions): Promise & ResolvedSharedInertiaProps>>; protected inertia(page: TPage, props: InertiaPropsInput>, options?: InertiaResponseOptions): Promise & ResolvedSharedInertiaProps>>; } declare function createControllerModuleMock(): { /** * The real `viteAsset()`: under vitest it takes the dev branch, while a test that * forces production gets the real manifest lookup and its missing-entry throw. * Sync by contract, so it reads the lazily-primed memo (see `loadServer`). */ viteAsset: (entry: string, options?: { manifestPaths?: string[]; }) => string; parseRequestPayload: (ctx: ControllerContext) => Promise>; formatValidationErrors: typeof formatValidationErrors; always: typeof always; defer: typeof defer; live: typeof live; Controller: typeof TestController; Event: { new (): {}; }; Listener: { new (): {}; }; Job: { new (): {}; }; AuthenticatableModel: { new (): {}; table: unknown; recordType: unknown; relationTypes: unknown; find(): Promise; where(): Promise; update(): Promise; hasMany(): void; hasOne(): void; belongsTo(): void; belongsToMany(): void; hasManyThrough(): void; morphMany(): void; morphTo(): void; with(): Promise; withCount(): Promise; findWith(): Promise; all(): Promise; create(): Promise; findOrFail(): Promise; first(): Promise; delete(): Promise; /** Chainable like the real query builder, and awaitable at any point. */ select(): Record; }; defineModel: (table: unknown, config?: Record) => { new (): {}; table: unknown; config: Record; recordType: unknown; relationTypes: unknown; find(): Promise; where(): Promise; update(): Promise; hasMany(): void; hasOne(): void; belongsTo(): void; belongsToMany(): void; hasManyThrough(): void; morphMany(): void; morphTo(): void; with(): Promise; withCount(): Promise; findWith(): Promise; all(): Promise; create(): Promise; findOrFail(): Promise; first(): Promise; delete(): Promise; /** Chainable like the real query builder, and awaitable at any point. */ select(): Record; }; Resource: typeof Resource; JsonResource: typeof JsonResource; collect: typeof collect; ValidationException: typeof ValidationException; AuthenticationException: typeof AuthenticationException; ServiceProvider: typeof ServiceProvider; defineModule: typeof defineModule; definePlugin: typeof definePlugin; MemoryApiTokenStore: { new (): { clear(): void; }; }; createApiToken: (_store: unknown, options: { name: string; userId: number | string; abilities: string[]; expiresIn?: number | null; }) => Promise<{ plainTextToken: string; token: { id: string; name: string; userId: number | string; abilities: string[]; createdAt: Date; lastUsedAt: Date | null; expiresAt: Date | null; }; }>; revokeApiToken: () => Promise; getUserApiTokens: () => Promise>; getApiToken: () => { userId: number | string; abilities: string[]; } | null; getApiTokenOrFail: (ctx: ControllerContext) => { token: unknown; userId: string | number; abilities: string[]; }; createEventManager: () => { on: () => void; emit: () => Promise; }; createMailManager: () => {}; setMailManager: () => void; setQueueDriver: () => void; registerJob: () => void; MemoryDriver: { new (): {}; }; createCacheManager: () => { store: () => { remember: (_key: string, _ttl: number, callback: () => Promise) => Promise; delete: () => Promise; clear: () => Promise; }; }; }; declare function readInertiaResponse(response: Response): Promise<{ format: 'json' | 'html'; payload: InertiaPayload; body?: string; }>; //#endregion //#region src/http.d.ts /** * Test response wrapper with assertion methods. */ declare class TestResponse { private response; private _body; private _json; constructor(response: Response); /** * Get the raw response. */ get raw(): Response; /** * Get the status code. */ get status(): number; /** * Get response headers. */ get headers(): Headers; /** * Get the response body as text. */ text(): Promise; /** * Get the response body as JSON. */ json(): Promise; /** * Assert the response status code. */ assertStatus(status: number): this; /** * Assert the response is OK (200). */ assertOk(): this; /** * Assert the response is Created (201). */ assertCreated(): this; /** * Assert the response is No Content (204). */ assertNoContent(): this; /** * Assert the response is Bad Request (400). */ assertBadRequest(): this; /** * Assert the response is Unauthorized (401). */ assertUnauthorized(): this; /** * Assert the response is Forbidden (403). */ assertForbidden(): this; /** * Assert the response is Not Found (404). */ assertNotFound(): this; /** * Assert the response is Unprocessable Entity (422). */ assertUnprocessable(): this; /** * Assert the response is Internal Server Error (500). */ assertServerError(): this; /** * Assert the response is a redirect. */ assertRedirect(url?: string): this; /** * Assert the response has a specific header. */ assertHeader(name: string, value?: string): this; /** * Assert the response does not have a specific header. */ assertHeaderMissing(name: string): this; /** * Assert the response body contains the expected JSON. */ assertJson(expected: unknown): Promise; /** * Assert the response JSON has a value at the given path. */ assertJsonPath(path: string, expected: unknown): Promise; /** * Assert the response JSON contains the expected data (partial match). */ assertJsonContains(expected: Record): Promise; /** * Assert the response body contains the expected text. */ assertBodyContains(text: string): Promise; /** * Assert the response is successful (2xx). */ assertSuccessful(): this; } /** * Test request builder for fluent API. */ declare class TestRequestBuilder { private url; private method; private _headers; private _body; private _cookies; private _session; private _user; private fetchFn; constructor(url: string, method: string, fetchFn: (request: Request) => Promise); /** * Set a header. */ withHeader(name: string, value: string): this; /** * Set multiple headers. */ withHeaders(headers: Record): this; /** * Set a cookie. */ withCookie(name: string, value: string): this; /** * Set multiple cookies. */ withCookies(cookies: Record): this; /** * Set session data. */ withSession(data: Record): this; /** * Set JSON body. */ withJson(data: unknown): this; /** * Set form data body. */ withForm(data: Record): this; /** * Set raw body. */ withBody(body: BodyInit, contentType?: string): this; /** * Set the authenticated user. */ actingAs(user: Authenticatable): this; /** * Accept JSON responses. */ acceptJson(): this; /** * Set as Inertia request. */ asInertia(version?: string): this; /** * Get request details for testing. */ getRequestDetails(): { user: Authenticatable | null; session: Record; }; /** * Send the request. */ send(): Promise; } /** * Test client for making requests. */ declare class TestClient { private baseUrl; private fetchFn; private defaultHeaders; constructor(baseUrl: string, fetchFn: (request: Request) => Promise); /** * Set default headers for all requests. */ setDefaultHeaders(headers: Record): this; /** * Create a GET request. */ get(path: string): TestRequestBuilder; /** * Create a POST request. */ post(path: string): TestRequestBuilder; /** * Create a PUT request. */ put(path: string): TestRequestBuilder; /** * Create a PATCH request. */ patch(path: string): TestRequestBuilder; /** * Create a DELETE request. */ delete(path: string): TestRequestBuilder; /** * Create a QUERY request (RFC 10008): safe and idempotent like GET, but * carries a request body like POST. */ query(path: string): TestRequestBuilder; /** * Create a request with any method. */ request(method: string, path: string): TestRequestBuilder; } /** * Create a test client from an application fetch function. */ declare function createTestClient(fetchFn: (request: Request) => Promise, baseUrl?: string): TestClient; //#endregion //#region src/queue.d.ts /** * Recorded job for testing. */ interface RecordedJob { jobClass?: JobClass; jobName: string; payload: T; options: { queue: string; delay: number; }; timestamp: Date; queuedJob: QueuedJob; } /** * Fake queue driver for testing. */ declare class FakeQueueDriver implements QueueDriver { private jobs; private failedJobs; private jobClasses; registerJobClass(jobClass: JobClass): void; push(job: QueuedJob): Promise; pop(queue: string): Promise; release(job: QueuedJob, delayMs?: number): Promise; delete(jobId: string): Promise; fail(job: QueuedJob, error: Error): Promise; size(queue: string): Promise; getFailedJobs(queue?: string): Promise; retryFailedJob(jobId: string): Promise; deleteFailedJob(jobId: string): Promise; clear(): Promise; /** * Get all recorded jobs. */ getJobs(): RecordedJob[]; /** * Get jobs of a specific type. */ getJobsOf(jobClass: JobClass): RecordedJob[]; } /** * Fake queue for testing job dispatches. */ declare class FakeQueue { private driver; constructor(); /** * Get the underlying driver. */ getDriver(): FakeQueueDriver; /** * Record a job dispatch. */ record(jobClass: JobClass, payload: T, options?: { queue?: string; delay?: number; }): void; /** * Assert a job was pushed. */ assertPushed(jobClass: JobClass, callback?: (payload: T) => boolean): void; /** * Assert a job was pushed a specific number of times. */ assertPushedTimes(jobClass: JobClass, times: number): void; /** * Assert a job was not pushed. */ assertNotPushed(jobClass: JobClass): void; /** * Assert no jobs were pushed. */ assertNothingPushed(): void; /** * Assert a job was pushed to a specific queue. */ assertPushedOn(queue: string, jobClass: JobClass): void; /** * Assert a job was pushed with a delay. */ assertPushedWithDelay(jobClass: JobClass, delay: number): void; /** * Get pushed jobs of a specific type. */ pushed(jobClass: JobClass): RecordedJob[]; /** * Get all pushed jobs. */ all(): RecordedJob[]; /** * Clear all recorded jobs. */ clear(): void; } /** * Create a fake queue for testing. */ declare function fakeQueue(): FakeQueue; //#endregion //#region src/mail.d.ts /** * Recorded mail for testing. */ interface RecordedMail { message: MailMessage; timestamp: Date; } /** * Fake mail transport for testing. */ declare class FakeMailTransport implements MailTransport { readonly name = "fake"; private mails; send(message: MailMessage): Promise; /** * Get all recorded mails. */ getMails(): RecordedMail[]; /** * Clear recorded mails. */ clear(): void; } /** * Fake mail for testing mail sending. */ declare class FakeMail { private transport; constructor(); /** * Get the underlying transport. */ getTransport(): FakeMailTransport; /** * Record a mail send. */ record(message: MailMessage): void; /** * Assert a mail was sent. */ assertSent(callback?: (message: MailMessage) => boolean): void; /** * Assert a mail was sent a specific number of times. */ assertSentTimes(times: number): void; /** * Assert no mails were sent. */ assertNothingSent(): void; /** * Assert a mail was sent to a specific address. */ assertSentTo(address: string): void; /** * Assert a mail was sent from a specific address. */ assertSentFrom(address: string): void; /** * Assert a mail with specific subject was sent. */ assertSentWithSubject(subject: string): void; /** * Assert a mail body contains text. */ assertSentWithBodyContaining(text: string): void; /** * Assert a mail was sent with CC. */ assertSentWithCc(address: string): void; /** * Assert a mail was sent with BCC. */ assertSentWithBcc(address: string): void; /** * Assert a mail was sent with attachment. */ assertSentWithAttachment(filename: string): void; /** * Get sent mails. */ sent(): RecordedMail[]; /** * Get mails sent to a specific address. */ sentTo(address: string): RecordedMail[]; /** * Clear all recorded mails. */ clear(): void; } /** * Create a fake mail for testing. */ declare function fakeMail(): FakeMail; //#endregion //#region src/lifecycle.d.ts type LifecycleHookFn = (fn: () => void | Promise) => void; /** * Test-runner lifecycle hooks used by helpers that register per-test setup, * such as `useDatabaseTransactions()` and `useTruncateTables()`. */ interface TestLifecycleHooks { beforeEach: LifecycleHookFn; afterEach: LifecycleHookFn; } /** * Register the lifecycle hooks of the active test runner. `@guren/testing/vitest` * does this automatically; bun:test globals are picked up without registration. */ declare function setTestLifecycleHooks(hooks: TestLifecycleHooks): void; /** * Resolve the lifecycle hooks to use: explicitly registered hooks first, * then runner-injected globals (bun:test always, vitest with `globals: true`). */ declare function getTestLifecycleHooks(): TestLifecycleHooks; //#endregion //#region src/database.d.ts /** * Database connection interface for testing. */ interface DatabaseConnection { query(sql: string, params?: unknown[]): Promise; execute(sql: string, params?: unknown[]): Promise; beginTransaction(): Promise; commit(): Promise; rollback(): Promise; } /** * Set the global database connection for testing. */ declare function setTestDatabase(db: DatabaseConnection): void; /** * Get the global database connection. */ declare function getTestDatabase(): DatabaseConnection; /** * Assert database has a record matching the criteria. */ declare function assertDatabaseHas(table: string, data: Record, db?: DatabaseConnection): Promise; /** * Assert database does not have a record matching the criteria. */ declare function assertDatabaseMissing(table: string, data: Record, db?: DatabaseConnection): Promise; /** * Assert database table has a specific count. */ declare function assertDatabaseCount(table: string, count: number, db?: DatabaseConnection): Promise; /** * Assert database table is empty. */ declare function assertDatabaseEmpty(table: string, db?: DatabaseConnection): Promise; /** * Assert a record is soft deleted (has deleted_at set). */ declare function assertSoftDeleted(table: string, data: Record, deletedAtColumn?: string, db?: DatabaseConnection): Promise; /** * Assert a record is not soft deleted. */ declare function assertNotSoftDeleted(table: string, data: Record, deletedAtColumn?: string, db?: DatabaseConnection): Promise; /** * Run each test in a transaction that is rolled back afterwards. Lifecycle hooks are * resolved via `getTestLifecycleHooks()` unless passed explicitly. */ declare function useDatabaseTransactions(db?: DatabaseConnection, hooks?: TestLifecycleHooks): void; /** * Truncate tables before each test. Lifecycle hooks are resolved via * `getTestLifecycleHooks()` unless passed explicitly. */ declare function useTruncateTables(tables: string[], db?: DatabaseConnection, hooks?: TestLifecycleHooks): void; /** * Refresh database (run migrations) before tests. */ declare function refreshDatabase(migrateFn: () => Promise): Promise; /** * Seed database with data. */ declare function seedDatabase(seedFn: () => Promise): Promise; /** * Database assertion helper class. */ declare class DatabaseAssertions { private db; constructor(db: DatabaseConnection); /** * Assert database has a record. */ assertHas(table: string, data: Record): Promise; /** * Assert database is missing a record. */ assertMissing(table: string, data: Record): Promise; /** * Assert database table has count. */ assertCount(table: string, count: number): Promise; /** * Assert database table is empty. */ assertEmpty(table: string): Promise; /** * Assert record is soft deleted. */ assertSoftDeleted(table: string, data: Record, deletedAtColumn?: string): Promise; /** * Assert record is not soft deleted. */ assertNotSoftDeleted(table: string, data: Record, deletedAtColumn?: string): Promise; } /** * Create database assertions helper. */ declare function createDatabaseAssertions(db: DatabaseConnection): DatabaseAssertions; //#endregion //#region src/event.d.ts /** * Recorded event for testing. */ interface RecordedEvent { eventClass: EventClass; event: T; timestamp: Date; } /** * Fake event manager for testing. * Captures all emitted events for assertions. */ declare class FakeEventManager { private events; private listeners; /** * Register a listener for an event. */ on(event: EventClass | string, listener: EventListener, _options?: ListenerOptions): EventSubscription; /** * Register a one-time listener for an event. */ once(event: EventClass | string, listener: EventListener, options?: Omit): EventSubscription; /** * Remove a listener for an event. */ off(event: EventClass | string, listener?: EventListener): void; /** * Emit an event (records it but does not call listeners by default). */ emit(event: T): Promise; /** * Emit an event in parallel (records it but does not call listeners by default). */ emitParallel(event: T): Promise; /** * Check if an event has any listeners registered. */ hasListeners(event: EventClass | string): boolean; /** * Get all listeners for an event. */ getListeners(event: EventClass | string): EventListener[]; /** * Get the count of listeners for an event. */ listenerCount(event: EventClass | string): number; /** * Get all registered event names. */ eventNames(): string[]; /** * Remove all listeners for all events. */ removeAllListeners(): void; /** * Get all recorded events. */ getEvents(): RecordedEvent[]; /** * Get events of a specific type. */ getEventsOf(eventClass: EventClass): RecordedEvent[]; /** * Clear all recorded events. */ clear(): void; } /** * Fake event for testing event dispatches. */ declare class FakeEvent { private manager; constructor(); /** * Get the underlying manager. */ getManager(): FakeEventManager; /** * Record an event dispatch. */ record(event: T): void; /** * Assert an event was dispatched. */ assertDispatched(eventClass: EventClass, callback?: (event: T) => boolean): void; /** * Assert an event was dispatched a specific number of times. */ assertDispatchedTimes(eventClass: EventClass, times: number): void; /** * Assert an event was not dispatched. */ assertNotDispatched(eventClass: EventClass): void; /** * Assert no events were dispatched. */ assertNothingDispatched(): void; /** * Assert multiple events were dispatched in a specific order. */ assertDispatchedInOrder(eventClasses: EventClass[]): void; /** * Assert an event was dispatched with specific data. */ assertDispatchedWith(eventClass: EventClass, data: Partial): void; /** * Get dispatched events of a specific type. */ dispatched(eventClass: EventClass): RecordedEvent[]; /** * Get all dispatched events. */ all(): RecordedEvent[]; /** * Clear all recorded events. */ clear(): void; } /** * Create a fake event for testing. */ declare function fakeEvent(): FakeEvent; /** * Create a fake event manager for testing. * Can be used as a drop-in replacement for EventManager. */ declare function fakeEventManager(): FakeEventManager; //#endregion //#region src/agent.d.ts /** * What a tool dispatch needs from the `TestApp` it belongs to. `routeDefinitions` * answers `undefined` (not an empty list) for a `TestApp` built from a bare * `fetch`, so {@link TestAgent} can name the constructor to use instead. */ interface AgentTestBridge { routeDefinitions(): readonly RouteDefinition[] | undefined; /** Origin the synthesized request is built on — the app's own `baseUrl`. */ baseUrl: string; /** Headers this `TestApp` sends on every request, `X-Testing-User` included. */ headers(): Record; dispatch(request: Request): Promise; /** A bridge for the same app authenticating as `user` — see `TestApp.actingAs`. */ actingAs(user: unknown): AgentTestBridge; } /** Options for one tool call. */ interface AgentCallOptions { /** * Authenticate the call as this user, exactly as `TestApp.actingAs(user)` does. * No token is involved, so bearer scopes are not part of this surface. */ as?: unknown; /** * Ask for a verdict instead of an execution (RFC 0016 §5.4): the request runs the * route's middleware and validates the contract, then stops before the handler. * MCP reaches the same seam through the `guren_preflight` companion tool instead. */ preflight?: boolean; } /** * The result of one tool call. Assertions here are synchronous; * {@link PendingAgentToolResult} carries the chainable spellings. */ declare class AgentToolResult { /** The derived tool this call dispatched to. */ readonly tool: DerivedAgentTool; /** The mapped outcome: content, structured content, error flag, status. */ readonly outcome: ToolCallOutcome; /** The raw HTTP response, for assertions this class does not cover. */ readonly response: Response; private readonly advertisesStructuredOutput; constructor( /** The derived tool this call dispatched to. */ tool: DerivedAgentTool, /** The mapped outcome: content, structured content, error flag, status. */ outcome: ToolCallOutcome, /** The raw HTTP response, for assertions this class does not cover. */ response: Response, advertisesStructuredOutput: (tool: DerivedAgentTool) => boolean); /** The HTTP status the dispatch resolved to. */ get status(): number; /** True when the call came back as an MCP error result (4xx/5xx, mostly). */ get isError(): boolean; /** Every text part of the result, joined — what an agent would read. */ get text(): string; /** The structured result, when the tool advertises an object output schema. */ get structuredContent(): Record | undefined; assertStatus(code: number): this; /** * Assert the call succeeded — not an error result. Deliberately not * `assertStatus(200)` (which is what `PendingTestResponse.assertOk()` means): a * 201 or 204 is a success, and MCP models the outcome as a boolean `isError`. */ assertOk(): this; /** * Assert the application answered 401 or 403. Not a scope denial: this surface * carries no bearer token, so assert scopes against the App MCP plugin's gate. * * A CSRF 403 is indistinguishable from a policy 403 — dispatch through * `(await app.withCsrf()).agent()` or this can pass with no policy consulted. */ assertDenied(): this; /** * Assert the call produced a structured result, and return it typed. The type * parameter is the author's assertion; the route's `output` schema is the check. */ assertStructured>(): T; /** The result body parsed as JSON — for a tool with no output schema. */ json(): T; } /** A promise-like {@link AgentToolResult}, so assertions chain on the call. */ declare class PendingAgentToolResult implements PromiseLike { private readonly promise; constructor(promise: Promise); then(onfulfilled?: ((value: AgentToolResult) => TResult1 | PromiseLike) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike) | null): PromiseLike; private chain; assertStatus(code: number): PendingAgentToolResult; assertOk(): PendingAgentToolResult; assertDenied(): PendingAgentToolResult; /** * Chainable form of {@link AgentToolResult.assertStructured}: returns the pending * result, not the payload. `await` the call to get the value. */ assertStructured(): PendingAgentToolResult; } /** The agent surface of a `TestApp` — reached through `app.agent()`. */ declare class TestAgent { private readonly bridge; constructor(bridge: AgentTestBridge); /** Every tool this app exposes, as an agent would see them. */ tools(): Promise; /** Call one tool by name, with a flat argument object. */ call(name: string, input?: Record, options?: AgentCallOptions): PendingAgentToolResult; private requireDefinitions; private dispatch; } //#endregion //#region src/ai.d.ts /** The model's final answer: plain text, or the value an agent's `output` schema parses. */ type FakeAiAnswer = string | { text: string; } | { output: unknown; }; /** One scripted prompt: an answer, or tool calls the model requests before answering. */ type FakeAiResponse = FakeAiAnswer | { toolCalls: FakeAiToolCall[]; then: FakeAiResponse; }; interface FakeAiToolCall { /** The tool's key in the agent's `tools()`. */ name: string; input?: Record; } /** A tool call the model made during a prompt, with what the real tool returned. */ interface FakeAiRecordedToolCall { name: string; input: unknown; /** Present when the tool returned. */ output?: unknown; /** Present when the tool threw, or its input failed validation: the error for `prompt()`, its message for `stream()`. */ error?: unknown; } interface FakeAiCall { input: string; principal: AgentPrincipalInput; /** Empty until the prompt settles (for `stream()`, until its body is read), and when no step finished. */ toolCalls: FakeAiRecordedToolCall[]; /** Set by `prompt()`; a `stream()` call answers with a `Response` instead. */ response?: AgentResponse; error?: unknown; } /** One value's vector. `respondEmbeddings` takes a queue of them, or a function answering every value. */ type FakeAiEmbeddings = ReadonlyArray | ((value: string) => readonly number[]); /** * What one `image()` call answers with: one image, or the several an `n > 1` call * asks for. A string is base64, which the SDK decodes to sniff the media type. */ type FakeAiImages = string | Uint8Array | readonly string[] | readonly Uint8Array[]; interface FakeAiEmbedCall { /** One for `embed()`, the batch for `embedMany()`; empty when the fake refused the call. */ values: string[]; /** The provider name resolved for the call, the config's `default` included. */ provider: string; } interface FakeAiImageCall { /** Absent when the call passed only input images, or when the fake refused it. */ prompt?: string; /** How many images were asked for; `0` when the fake refused the call. */ n: number; provider: string; } type FakeAiEvaluationAnswer = { type: 'choice'; choice: string; probabilities: Record; } | { type: 'score'; score: number; probabilities?: Record; } | { type: 'boolean'; probability: number; }; /** * One scripted evaluation, a value per question: a string is that choice at probability 1, a * number a boolean's probability or a score's position, an answer object passes through. * Checked against the questions when consumed, so a fake cannot answer what the real model could not. */ type FakeAiEvaluation = Record; interface FakeAiEvaluationCall { /** Absent when the fake refused the call before the SDK handed it the state (a provider with no `evaluationModel`). */ state?: Parameters[0]['state']; questions: AiEvaluationQuestions; /** The provider name resolved for the call, `defaultEvaluation` and `default` included. */ provider: string; answers?: Record; error?: unknown; } interface FakeAiRuntime { bindAgent: typeof bindAgent; resolveAgentName: typeof resolveAgentName; MockLanguageModelV4: typeof MockLanguageModelV4; MockEmbeddingModelV4: typeof MockEmbeddingModelV4; MockImageModelV4: typeof MockImageModelV4; EvaluationMockModelV4: typeof Experimental_EvaluationMockModelV4; wrapLanguageModel: typeof wrapLanguageModel; simulateStreamingMiddleware: typeof simulateStreamingMiddleware; } /** * The `ai` binding while faked. Scripts are keyed by agent wire name * (`resolveAgentName`), the identity audit lines and queued runs use. */ declare class FakeAi implements AiManager, Disposable { private readonly container; private readonly runtime; readonly config: AiManager['config']; private readonly scripts; private readonly recorded; private readonly failures; /** Consumed one vector per value; a function answers every value and is never exhausted. */ private readonly embeddings; private embedder?; private readonly images; private readonly embedRecords; private readonly imageRecords; private readonly evaluationScripts; private readonly evaluationRecords; /** One per scripted prompt, read on dispose: a loop `stopWhen` ended early never asks for the rest. */ private readonly progress; private readonly restore; private readonly real; constructor(container: Container, runtime: FakeAiRuntime); /** Queue one response per future prompt of `cls`, consumed in order. */ respond(cls: AgentClass, responses: FakeAiResponse[]): this; calls(cls: AgentClass): readonly FakeAiCall[]; assertPrompted(cls: AgentClass, predicate?: (input: string, call: FakeAiCall) => boolean): void; /** No prompt of `cls` matches `predicate`; use {@link assertNeverPrompted} for none at all. */ assertNotPrompted(cls: AgentClass, predicate: (input: string, call: FakeAiCall) => boolean): void; assertNeverPrompted(cls: AgentClass): void; /** * Answer future `embed()` / `embedMany()` calls. An array is a queue drawn one * vector per *value*, so a script does not depend on how the SDK batches a * large `embedMany()`; a function answers every value instead. */ respondEmbeddings(embeddings: FakeAiEmbeddings): this; /** Queue one entry per future `image()` call, consumed in order. */ respondImages(images: readonly FakeAiImages[]): this; embedCalls(): readonly FakeAiEmbedCall[]; imageCalls(): readonly FakeAiImageCall[]; assertEmbedded(predicate?: (call: FakeAiEmbedCall) => boolean): void; assertNeverEmbedded(): void; assertGeneratedImage(predicate?: (call: FakeAiImageCall) => boolean): void; assertNeverGeneratedImage(): void; /** Queue one answer set per future `evaluate()` call, consumed in order. */ respondEvaluations(evaluations: readonly FakeAiEvaluation[]): this; evaluationCalls(): readonly FakeAiEvaluationCall[]; assertEvaluated(predicate?: (call: FakeAiEvaluationCall) => boolean): void; assertNeverEvaluated(): void; agent(cls: AgentClass): BoundAgentFactory; model(provider?: string): LanguageModel; embeddingModel(provider?: string): EmbeddingModel; imageModel(provider?: string): ImageModel; evaluationModel(provider?: string): AiEvaluationModel; /** * Recorded before anything can refuse the call, as a prompt is: a call the fake * rejected was still a call, and an assertion saying it never happened would lie. */ private recordCall; private assertCalled; private assertNeverCalled; private vectorFor; /** Refuse a provider name config/ai.ts does not configure; shared with the prompt path. */ private checkConfigured; private checkProvider; /** The real manager's store: fakeAi() scripts the model, and conversations persist as configured. */ conversations(): ConversationStore; /** Restores the binding, then fails on any prompt that found nothing scripted or left steps unused. */ [Symbol.dispose](): void; private recording; private scriptedModel; private fail; private failureSuffix; private nameOf; } //#endregion //#region src/test-app.d.ts type BootCallback = (app: Hono) => void | Promise; type ProviderLike = { register?(): unknown; boot?(): unknown; }; /** * Constructor shape for a provider class passed to `TestApp.create()`. `any[]`, not * `unknown[]`: constructor parameters are contravariant, and every real * `ServiceProvider` subclass inherits a constructor taking a concrete `Container`. * Structural, so the published `.d.ts` resolves for an app depending only on * `@guren/core` instead of widening to `any` under `skipLibCheck`. */ type ProviderConstructor = new (...args: any[]) => ProviderLike; type RouteRegistration = (router: Router) => void | Promise; type ApplicationLike = { boot(): Promise; fetch(request: Request): Response | Promise; /** * The app-local route registry, read after `boot()` so `agent()` derives tools from * the graph this app serves. Optional: a `@guren/core` without the agent interface * has none, and `agent()` must say so rather than throw on an internal. */ readonly router?: { definitions(): RouteDefinition[]; }; /** What `fakeAi()` swaps the `ai` binding in. Optional for the same reason as `router`. */ readonly container?: Container; }; /** * Options for creating a TestApp instance. */ interface TestAppOptions { readonly boot?: BootCallback; readonly providers?: ProviderConstructor[]; readonly routes?: RouteRegistration; /** * Mirrors `createApp({ auth })`: pass `{}` (or full auth options) to mount * session + CSRF middleware so tests exercise production-like behavior. * Required for `withCsrf()` to work. Ignored by the Hono fallback used when * `@guren/server` is not installed. */ readonly auth?: Record; /** * Mirrors `createApp({ i18n })`: required when controllers under test use * `this.t()`/`this.tc()`. Ignored by the Hono fallback. */ readonly i18n?: I18nPluginOptions; /** Mirrors `createApp({ env })`: the schema `config/env.ts` exports, validated when the app boots. */ readonly env?: EnvSchema; /** * Values the schema reads ahead of `process.env`, bound as `env.source` before * boot, so a test overrides one variable without mutating the process. `''` * makes a variable unset; a missing key falls back to `process.env`. */ readonly envSource?: Readonly>; } /** * Fake ExecutionContext exposed by `TestApp.fromWorkers()`, so tests can * await promises the handler passed to `ctx.waitUntil()`. */ interface WorkersTestContext { /** Promises passed to ctx.waitUntil by the handler, for tests to await. */ readonly waitUntilPromises: Promise[]; } type WorkersExecutionContext = { waitUntil(promise: Promise): void; passThroughOnException?(): void; }; type WorkersHandler = { fetch(request: Request, env: unknown, ctx: WorkersExecutionContext): Response | Promise; }; interface WorkersTestAppOptions { readonly env?: unknown; readonly baseUrl?: string; } /** A promise-like TestResponse, so assertions chain on an HTTP method call. */ declare class PendingTestResponse implements PromiseLike { private promise; constructor(promise: Promise); then(onfulfilled?: ((value: TestResponse) => TResult1 | PromiseLike) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike) | null): PromiseLike; /** * Assert the response status code. */ assertStatus(code: number): PendingTestResponse; /** * Assert the response is OK (200). */ assertOk(): PendingTestResponse; /** * Assert the response is Created (201). */ assertCreated(): PendingTestResponse; /** * Assert the response is No Content (204). */ assertNoContent(): PendingTestResponse; /** * Assert the response is a redirect. */ assertRedirect(url?: string): PendingTestResponse; /** * Assert the response is Not Found (404). */ assertNotFound(): PendingTestResponse; /** * Assert the response is Forbidden (403). */ assertForbidden(): PendingTestResponse; /** * Assert the response is Unauthorized (401). */ assertUnauthorized(): PendingTestResponse; /** * Assert the response is Unprocessable Entity (422). */ assertUnprocessable(): PendingTestResponse; /** * Assert the response JSON matches the expected value. */ assertJson(expected: Record): PendingTestResponse; /** * Assert the response JSON array (or a nested key) has the expected count. */ assertJsonCount(count: number, key?: string): PendingTestResponse; /** * Assert the response JSON has the given keys. */ assertJsonStructure(keys: string[]): PendingTestResponse; /** * Assert a value at a dot-notation path in the JSON response. */ assertJsonPath(path: string, value: unknown): PendingTestResponse; /** * Assert the response is an Inertia response with the given component. */ assertInertia(component: string, props?: Record): PendingTestResponse; /** * Assert the response has a specific cookie. */ assertCookie(name: string, value?: string): PendingTestResponse; /** * Assert the response does not have a specific cookie. */ assertCookieMissing(name: string): PendingTestResponse; /** * Assert the response has a specific header. */ assertHeader(name: string, value?: string): PendingTestResponse; /** * Assert the response does not have a specific header. */ assertHeaderMissing(name: string): PendingTestResponse; } /** * Integrated HTTP test client wrapping the Application class. Uses `app.fetch()` * internally, so no running HTTP server is needed. * @example * await app.get('/posts').assertOk().assertJsonCount(1) * await app.actingAs(user).get('/dashboard').assertOk() */ declare class TestApp { private baseUrl; private fetchFn; private defaultHeaders; private authenticatedUser; /** * The app's route definitions when built from an Application. Undefined — never an * empty list — for `fromFetch`/`fromWorkers`, so `agent()` can tell "no tools" from * "this construction cannot see any routes". */ private routeDefinitions?; /** The booted app's container; undefined for `fromFetch`/`fromWorkers`, like `routeDefinitions`. */ private container?; /** Present when created via fromWorkers(); propagated across builder copies. */ workers?: WorkersTestContext; private constructor(); /** * Create a new TestApp by booting an Application instance. The Application is * imported dynamically; without `@guren/server` a Hono-based fallback is used. */ static create(options?: TestAppOptions): Promise; /** * Create a TestApp from an existing Application instance (typically `src/app.ts`'s * default export), booting it if it has not yet. `fetch` is bound internally, so no * `TestApp.fromFetch((request) => app.fetch(request))` wrapper is needed; `boot()` must * be idempotent (@guren/server's Application reuses its first boot), so several test * files may share one instance. * @example * import app from '../src/app' * const http = await TestApp.fromApp(app) * await http.get('/').assertOk() */ static fromApp(app: ApplicationLike, baseUrl?: string): Promise; /** * Create a TestApp from an existing fetch function. * Useful when you already have a Hono app or Application instance. */ static fromFetch(fetchFn: (request: Request) => Response | Promise, baseUrl?: string): TestApp; /** * Create a TestApp from a Cloudflare Workers-style fetch handler. One fake * ExecutionContext is shared across every request; promises passed to * `ctx.waitUntil()` are collected in `workers.waitUntilPromises` to await. */ static fromWorkers(handler: WorkersHandler, options?: WorkersTestAppOptions): TestApp & { workers: WorkersTestContext; }; /** * Return a new TestApp authenticated as this user, injected through a header the * auth middleware recognizes in test mode. */ actingAs(user: unknown): TestApp; /** * A copy carrying everything this TestApp was configured with. One place, because * every builder (`actingAs`, `withHeaders`, `withCsrf`) has to carry *all* of it — * a field one copies and another does not vanishes silently on the next builder. */ private clone; /** * The agent surface of this app (RFC 0016): the tools an MCP client would see, and a way * to call them through the framework's own dispatch contract and this app's `fetch`. * @example * const result = await app.agent().call('posts.store', { title: 'x' }, { as: user }) */ agent(): TestAgent; /** * Replace the app's `ai` binding with a scripted fake (RFC 0029 §7). Models are scripted * per agent with `respond()`; tools still run through `appTools()` and the pipeline. * Disposing restores the binding and fails if any prompt found nothing scripted. * @example * using ai = app.fakeAi() * ai.respond(SupportTriager, [{ output: { priority: 2 } }]) */ fakeAi(): FakeAi; private attachContainer; private agentBridge; /** * Prime the CSRF protection: GETs `path`, captures the session and XSRF-TOKEN * cookies, and returns a TestApp that sends them (plus the `X-XSRF-TOKEN` header) * on every later request, so mutating requests pass CSRF like a real browser. */ withCsrf(path?: string): Promise; /** * Return a new TestApp that sends `Accept: application/json` on every request. */ json(): TestApp; /** Return a new TestApp that sends the given headers on every request. */ withHeaders(headers: Record): TestApp; /** * Return a new TestApp that sends the given header on every request. */ withHeader(name: string, value: string): TestApp; /** * Make a GET request. */ get(path: string): PendingTestResponse; /** * Make a HEAD request. The app answers it with the GET route's action and * drops the body, so this shows what that action does for a monitor or a * link checker. */ head(path: string): PendingTestResponse; /** * Make a POST request. */ post(path: string, body?: unknown): PendingTestResponse; /** * Make a PUT request. */ put(path: string, body?: unknown): PendingTestResponse; /** * Make a PATCH request. */ patch(path: string, body?: unknown): PendingTestResponse; /** * Make a DELETE request. */ delete(path: string, body?: unknown): PendingTestResponse; /** * Make a QUERY request (RFC 10008): safe and idempotent like GET, but * carries a request body like POST. */ query(path: string, body?: unknown): PendingTestResponse; /** * The headers every request carries: whatever `withHeaders`/`withCsrf` parked, plus * the authenticated-user envelope. One spelling, shared with the agent dispatch. */ private requestHeaders; private request; } /** Factory helper for creating test model instances. */ declare function factory(factoryClass: new () => { create(overrides?: Partial): Promise; }, count?: number): Promise; //#endregion //#region src/plugin-test-utils.d.ts /** Boot a minimal test application with the given providers. */ declare function createPluginTestApp(providers: unknown[]): Promise; /** Assert a plugin bound the expected services in the container. */ declare function assertPluginRegisters(app: Application, services: string[]): void; /** Assert a plugin bound none of these services — e.g. a deferred provider. */ declare function assertPluginDoesNotRegister(app: Application, services: string[]): void; //#endregion export { type AgentCallOptions, type AgentTestBridge, AgentToolResult, ControllerContext, DatabaseAssertions, DatabaseConnection, FakeAi, type FakeAiAnswer, type FakeAiCall, type FakeAiEmbedCall, type FakeAiEmbeddings, type FakeAiEvaluation, type FakeAiEvaluationAnswer, type FakeAiEvaluationCall, type FakeAiImageCall, type FakeAiImages, type FakeAiRecordedToolCall, type FakeAiResponse, type FakeAiToolCall, FakeEvent, FakeEventManager, FakeMail, FakeMailTransport, FakeQueue, FakeQueueDriver, InertiaPayload, LifecycleHookFn, MockAuthContext, MockInertiaPage, MockUser, MockUserProvider, PendingAgentToolResult, PendingTestResponse, RecordedEvent, RecordedJob, RecordedMail, TestAgent, TestApp, type TestAppOptions, TestClient, TestLifecycleHooks, TestRequestBuilder, TestResponse, type WorkersTestAppOptions, type WorkersTestContext, assertDatabaseCount, assertDatabaseEmpty, assertDatabaseHas, assertDatabaseMissing, assertNotSoftDeleted, assertPluginDoesNotRegister, assertPluginRegisters, assertSoftDeleted, contractInput, createControllerContext, createControllerModuleMock, createDatabaseAssertions, createGurenControllerModule, createInertiaReactMock, createMockAuthContext, createMockProvider, createMockUser, createPluginTestApp, createTestClient, factory, fakeEvent, fakeEventManager, fakeMail, fakeQueue, getInertiaPage, getTestDatabase, getTestLifecycleHooks, readInertiaResponse, refreshDatabase, resetInertiaPage, seedDatabase, setInertiaPage, setTestDatabase, setTestLifecycleHooks, useDatabaseTransactions, useTruncateTables }; //# sourceMappingURL=index.d.ts.map