import path from "path"; import { z } from "zod/v3"; import { DEV_SERVER_URL } from "./devServer.ts"; export function randomSuffix(value: string): string { return `${value}-${Math.random().toString(36).substring(2, 15)}`; } export function testNameFromFileUrl(fileUrl: string): string { const basename = path.basename(fileUrl).split(".")[0]; if (!basename) { throw new Error("unreachable"); } return basename; } export async function sleep(ms: number = 1000): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } /** * Poll a callback until it stops throwing, with a default 20s timeout. * Standalone implementation — no vitest dependency. */ export async function waitFor( callback: () => T | Promise, timeout = 20_000, ): Promise { const deadline = Date.now() + timeout; let lastError: unknown; while (Date.now() < deadline) { try { return await callback(); } catch (err) { lastError = err; } await sleep(200); } // Surface the timeout context while preserving the underlying cause. The // original message is kept verbatim in the text so callers asserting on it // (e.g. "runId not set yet") still match, but the real failure — often an // unstable dev server connection — is no longer hidden behind a bare rethrow. const detail = lastError instanceof Error ? lastError.message : String(lastError); throw new Error( `waitFor timed out after ${timeout}ms; last error: ${detail}`, { cause: lastError, }, ); } type RunResult = | { data: unknown; error?: undefined } | { data?: undefined; error: unknown }; const runTraceSchema = z.object({ data: z.object({ run: z .object({ trace: z .object({ status: z.string(), outputID: z.string().nullable(), }) .nullable(), }) .nullable(), }), }); const traceOutputSchema = z.object({ data: z.object({ runTraceSpanOutputByID: z .object({ data: z.string().nullable(), error: z .object({ message: z.string(), name: z.string().nullable(), }) .nullable(), }) .nullable(), }), }); const runMetadataEntrySchema = z.object({ scope: z.string(), kind: z.string(), values: z.record(z.unknown()), updatedAt: z.string(), }); export type RunMetadata = z.infer; export type TraceMetadataNode = { name: string; stepID: string | null; spanID: string; metadata: RunMetadata[]; childrenSpans: TraceMetadataNode[]; }; const traceMetadataNodeSchema: z.ZodType< TraceMetadataNode, z.ZodTypeDef, unknown > = z.lazy(() => z.object({ name: z.string(), stepID: z.string().nullable(), spanID: z.string(), metadata: z.array(runMetadataEntrySchema).optional().default([]), childrenSpans: z.array(traceMetadataNodeSchema).optional().default([]), }), ); const runTraceMetadataSchema = z.object({ data: z.object({ run: z .object({ trace: traceMetadataNodeSchema.nullable(), }) .nullable(), }), }); /** * Fetch the trace status and output ID for a run via the Dev Server's GQL API. * Uses `run.trace.status` instead of `run.status` because the top-level status * can be stale (e.g. stuck as QUEUED) for sync-mode durable endpoint runs. */ async function fetchRunTrace(runId: string): Promise<{ status: string; outputID: string | null; } | null> { const res = await fetch(`${DEV_SERVER_URL}/v0/gql`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ query: `query ($runId: String!) { run(runID: $runId) { status trace { status outputID } } }`, variables: { runId }, }), }); if (!res.ok) { throw new Error(await res.text()); } const parsed = runTraceSchema.safeParse(await res.json()); if (!parsed.success) { return null; } return parsed.data.data.run?.trace ?? null; } /** * Fetch the output data/error for a trace span by its output ID. */ async function fetchTraceOutput(outputID: string): Promise { const res = await fetch(`${DEV_SERVER_URL}/v0/gql`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ query: `query ($traceID: String!) { runTraceSpanOutputByID(outputID: $traceID) { data error { message name } } }`, variables: { traceID: outputID }, }), }); if (!res.ok) { throw new Error(await res.text()); } const parsed = traceOutputSchema.parse(await res.json()); const span = parsed.data.runTraceSpanOutputByID; if (span?.error) { return { error: span.error }; } if (span?.data) { try { return { data: JSON.parse(span.data) }; } catch { return { data: span.data }; } } return { data: null }; } /** * Fetch root and step trace metadata for assertions against visible spans. */ export async function getRunTraceMetadata( runId: string, ): Promise { const res = await fetch(`${DEV_SERVER_URL}/v0/gql`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ query: `fragment TraceMetadataFields on RunTraceSpan { name stepID spanID metadata { scope kind values updatedAt } } query ($runId: String!) { run(runID: $runId) { trace { ...TraceMetadataFields childrenSpans { ...TraceMetadataFields childrenSpans { ...TraceMetadataFields } } } } }`, variables: { runId }, }), }); if (!res.ok) { throw new Error(await res.text()); } const parsed = runTraceMetadataSchema.parse(await res.json()); const trace = parsed.data.run?.trace; if (!trace) { throw new Error(`Run ${runId} has no trace metadata`); } return trace; } /** * Fetch the metadata entries attached to a run's root trace. Returns the * raw list as the Dev Server reports it (e.g. `inngest.score`, * `inngest.usage`). Use to assert that side-effects like `client.score()` * landed on the expected run. */ export async function getRunMetadata(runId: string): Promise { const trace = await getRunTraceMetadata(runId); return trace.metadata; } async function fetchRunResult( runId: string, timeout = 20_000, ): Promise { const deadline = Date.now() + timeout; while (Date.now() < deadline) { const trace = await fetchRunTrace(runId); if (trace) { if (trace.status === "COMPLETED") { if (trace.outputID) { return fetchTraceOutput(trace.outputID); } return { data: null }; } if (trace.status === "FAILED") { if (trace.outputID) { return fetchTraceOutput(trace.outputID); } return { error: { message: "Run failed (no output)" } }; } } await sleep(400); } throw new Error(`Timed out waiting for run ${runId} to end`); } export class BaseState { runId: string | null = null; async waitForRunId(): Promise { return waitFor(async () => { if (this.runId === null || this.runId === undefined) { throw new Error("runId not set yet"); } return this.runId; }); } async waitForRunComplete(timeout?: number): Promise { const runId = await this.waitForRunId(); const result = await fetchRunResult(runId, timeout); if (result.error) { throw new Error( `Expected run ${runId} to complete, but it errored: ${JSON.stringify(result.error)}`, ); } return result.data; } async waitForRunFailed(timeout?: number): Promise { const runId = await this.waitForRunId(); const result = await fetchRunResult(runId, timeout); if (!result.error) { throw new Error( `Expected run ${runId} to fail, but it completed with: ${JSON.stringify(result.data)}`, ); } return result.error; } } export function createState>( initial?: T, ): BaseState & T { return Object.assign(new BaseState(), initial); }