import { randomUUID } from 'crypto'; import type { ExecutionContext } from 'ava'; import type { WorkflowHandleWithFirstExecutionRunId, WorkflowStartOptions } from '@temporalio/client'; import type { TestWorkflowEnvironment as RealTestWorkflowEnvironment } from '@temporalio/testing'; import type { WorkerOptions, WorkflowBundle } from '@temporalio/worker'; import type * as workflow from '@temporalio/workflow'; import type { TestWorkflowEnvironment } from './wrappers'; import { Worker } from './wrappers'; export const isBun = typeof (globalThis as any).Bun !== 'undefined'; /** Union type for all supported test environment types */ export type AnyTestWorkflowEnvironment = TestWorkflowEnvironment | RealTestWorkflowEnvironment; /** * Base context interface for test environments. * Generic parameter allows specifying a more specific environment type. * Defaults to TestWorkflowEnvironment since that's the most common case. */ export interface BaseContext { env: TEnv; workflowBundle: WorkflowBundle; } /** * Base helpers interface providing common test utilities. * Packages can extend this interface with additional methods. */ export interface BaseHelpers { readonly taskQueue: string; createWorker(opts?: Partial): Promise; executeWorkflow Promise>(workflowType: T): Promise>; executeWorkflow( fn: T, opts: Omit & Partial> ): Promise>; startWorkflow Promise>(workflowType: T): Promise>; startWorkflow( fn: T, opts: Omit & Partial> ): Promise>; } /** * Default task queue transform function that converts test title to a valid task queue name. */ export function defaultTaskQueueTransform(title: string): string { return title .toLowerCase() .replaceAll(/[ _()'-]+/g, '-') .replace(/^[-]?(.+?)[-]?$/, '$1'); } /** * Create helpers for a test. * * When called with just `t`, extracts env and workflowBundle from `t.context`. * When called with `t` and `env`, uses the provided env with workflowBundle from context. * * @param t - The test execution context * @param env - Optional environment override (defaults to t.context.env) * @returns BaseHelpers instance */ export function helpers( t: ExecutionContext>, env: AnyTestWorkflowEnvironment = t.context.env ): BaseHelpers { // createBaseHelpers(t.title, env, t.context.workflowBundle); const taskQueue = defaultTaskQueueTransform(t.title); const workflowBundle = t.context.workflowBundle; return { taskQueue, async createWorker(workerOpts?: Partial): Promise { return await Worker.create({ connection: env.nativeConnection, namespace: env.namespace, workflowBundle, taskQueue, showStackTraceSources: true, ...workerOpts, }); }, async executeWorkflow( fn: workflow.Workflow, workflowOpts?: Omit & Partial> ): Promise { return await env.client.workflow.execute(fn, { taskQueue, workflowId: randomUUID(), ...workflowOpts, }); }, async startWorkflow( fn: workflow.Workflow, workflowOpts?: Omit & Partial> ): Promise> { return await env.client.workflow.start(fn, { taskQueue, workflowId: randomUUID(), ...workflowOpts, }); }, }; }