### Clone and install dependencies Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/CONTRIBUTING.md Initial steps to fork, clone the repository, and install necessary project dependencies. ```bash git clone https://github.com/your-username/nestjs-temporal-core.git cd nestjs-temporal-core npm install ``` -------------------------------- ### Install MCP SDK and zod Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/mcp-server.md Install the optional peer dependencies required for TemporalMcpModule. ```bash npm install @modelcontextprotocol/sdk zod ``` -------------------------------- ### Conventional commit examples Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/CONTRIBUTING.md Examples of commit messages following the conventional commits standard. ```text feat: add new feature fix: resolve bug docs: update documentation test: add tests refactor: improve code structure ``` -------------------------------- ### Install nestjs-temporal-core and Temporal packages Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/getting-started.md Run this command to install the core package and the required Temporal.io client, worker, workflow, and common packages. ```bash npm install nestjs-temporal-core @temporalio/client @temporalio/worker @temporalio/workflow @temporalio/common ``` -------------------------------- ### Claude Desktop config for MCP server Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/mcp-server.md Example claude_desktop_config.json that spawns the standalone CLI with environment variables for Temporal connection. ```json { "mcpServers": { "temporal": { "command": "npx", "args": ["nestjs-temporal-core-mcp"], "env": { "TEMPORAL_ADDRESS": "localhost:7233", "TEMPORAL_NAMESPACE": "default", "TEMPORAL_TASK_QUEUE": "my-queue" } } } } ``` -------------------------------- ### Run standalone MCP CLI Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/mcp-server.md Start the bundled MCP server CLI for clients that spawn their own process. ```bash npx nestjs-temporal-core-mcp ``` -------------------------------- ### Before: untyped workflow start and query Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/core-concepts.md Shows the untyped approach where workflow names and arguments are strings/unknown, requiring manual casts on query results. ```typescript // Before: string names, unknown args, manual casts on query results const handle = await this.temporal.startWorkflow('orderWorkflow', [orderId, customerId]); const status = await this.temporal.queryWorkflow(workflowId, 'getStatus'); ``` -------------------------------- ### Install nestjs-temporal-core and peer dependencies Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/README.md Install the nestjs-temporal-core package along with the required Temporal and NestJS peer dependencies using npm. ```bash npm install nestjs-temporal-core @temporalio/client @temporalio/worker @temporalio/workflow @temporalio/common npm install @nestjs/common @nestjs/core reflect-metadata rxjs # peer dependencies ``` -------------------------------- ### TLS Configuration for Temporal Cloud Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/configuration.md Use this TypeScript example to configure a secure connection to Temporal Cloud. It requires client certificate and key files, and sets the address, namespace, task queue, and worker settings. ```typescript import * as fs from 'fs'; TemporalModule.register({ connection: { address: 'your-namespace.your-account.tmprl.cloud:7233', namespace: 'your-namespace.your-account', tls: { clientCertPair: { crt: fs.readFileSync('/path/to/client.crt'), key: fs.readFileSync('/path/to/client.key'), }, }, }, taskQueue: 'my-task-queue', worker: { workflowsPath: require.resolve('./workflows'), activityClasses: [PaymentActivity], }, }) ``` -------------------------------- ### Install peer dependencies Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/getting-started.md Install the peer dependencies required by nestjs-temporal-core: @nestjs/common, @nestjs/core, reflect-metadata, and rxjs. ```bash npm install @nestjs/common @nestjs/core reflect-metadata rxjs ``` -------------------------------- ### signalWithStart via typed proxy Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/core-concepts.md Use this snippet to atomically start a workflow and send a signal using the typed proxy. The signal arguments are typed from the SignalDefinition, and workflow arguments are typed as Parameters. This is recommended for type safety. ```typescript // in workflows/cart.workflow.ts: // export const addItemSignal = defineSignal<[CartItem]>('addItem'); // export async function cartWorkflow(userId: string) { ... } await this.cartProxy.signalWithStart( addItemSignal, [{ sku: 'SKU-123', qty: 2 }], // signal args — typed from SignalDefinition [userId], // workflow args — typed as Parameters { workflowId: `cart-${userId}`, taskQueue: 'carts' }, ); ``` -------------------------------- ### Execute Standalone Activities from the Client Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/advanced-configuration.md Demonstrates running durable, retryable activities directly from the client without a workflow. Includes starting and awaiting a standalone activity, and querying executions. Note: This is a Public Preview feature; the API may change. ```typescript const result = await this.clientService.executeStandaloneActivity('sendEmail', { id: 'email-123', taskQueue: 'emails', args: ['user@example.com'], startToCloseTimeout: '1m', }); // Or start it and await the result later const handle = await this.clientService.startStandaloneActivity('sendEmail', { id: 'email-124', taskQueue: 'emails', startToCloseTimeout: '1m', }); const outcome = await handle.result(); // Query executions const info = await this.clientService.countStandaloneActivities('ActivityType="sendEmail"'); ``` -------------------------------- ### Define a Workflow with proxyActivities, signals, and queries Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/core-concepts.md Workflows are pure Temporal functions, not NestJS services. They must be deterministic and use Temporal's workflow APIs. This example shows defining activity proxies, signals, queries, and the workflow function with signal and query handlers. ```typescript // order.workflow.ts import { proxyActivities, defineSignal, defineQuery, setHandler } from '@temporalio/workflow'; import type { OrderActivity } from './order.activity'; // Create activity proxies with proper typing const { createOrder, validateInventory } = proxyActivities({ startToCloseTimeout: '5m', retry: { maximumAttempts: 3, initialInterval: '1s', maximumInterval: '30s', }, }); // Define signals and queries at module level export const cancelOrderSignal = defineSignal<[string]>('cancelOrder'); export const getOrderStatusQuery = defineQuery('getOrderStatus'); // Workflow function (exported, not a class) export async function processOrderWorkflow(orderData: CreateOrderData): Promise { let status = 'pending'; // Set up signal handler setHandler(cancelOrderSignal, (reason: string) => { status = 'cancelled'; }); // Set up query handler setHandler(getOrderStatusQuery, () => status); try { // Validate inventory const isValid = await validateInventory(orderData.items); if (!isValid) { throw new Error('Insufficient inventory'); } // Create order status = 'processing'; const order = await createOrder(orderData); status = 'completed'; return { orderId: order.id, status, }; } catch (error) { status = 'failed'; throw error; } } ``` -------------------------------- ### Configure workflowsPath and export workflow functions Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/troubleshooting.md This snippet shows how to set the workflowsPath in the worker configuration and export workflow functions from an index file. It also demonstrates starting a workflow with the correct name. ```typescript // 1. Ensure workflowsPath is correct TemporalModule.register({ worker: { workflowsPath: require.resolve('./workflows'), // Must resolve to workflows file/directory }, }) // 2. Export workflow function properly // workflows/index.ts export { processOrderWorkflow } from './order.workflow'; export { reportWorkflow } from './report.workflow'; // 3. Use correct workflow name when starting await temporal.startWorkflow( 'processOrderWorkflow', // Must match exported function name [args], options ); ``` -------------------------------- ### Call update from service using TemporalClientService Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/core-concepts.md Shows two ways to call an update from a service: waiting for the result with updateWorkflow, or starting it and awaiting the result later with startUpdateWorkflow. ```typescript // Wait for the update to complete and get its result const newBalance = await this.clientService.updateWorkflow( 'account-123', 'deposit', [100], ); // Or start it and only wait for it to be accepted, then await the result later const updateHandle = await this.clientService.startUpdateWorkflow( 'account-123', 'deposit', [100], ); const result = await updateHandle.result(); ``` -------------------------------- ### Use TemporalService in a NestJS service Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/getting-started.md Shows how to inject TemporalService to start workflows, query status, and send signals. Includes methods for processing payments, checking status, and cancelling. ```typescript // payment.service.ts import { Injectable } from '@nestjs/common'; import { TemporalService } from 'nestjs-temporal-core'; @Injectable() export class PaymentService { constructor(private readonly temporal: TemporalService) {} async processPayment(paymentData: any) { // Start workflow const result = await this.temporal.startWorkflow( 'processPaymentWorkflow', [paymentData], { workflowId: `payment-${Date.now()}`, taskQueue: 'my-task-queue', } ); return { workflowId: result.result.workflowId, runId: result.result.runId, }; } async checkPaymentStatus(workflowId: string) { // Query workflow const statusResult = await this.temporal.queryWorkflow( workflowId, 'getPaymentStatus' ); return { status: statusResult.result }; } async cancelPayment(workflowId: string, reason: string) { // Send signal await this.temporal.signalWorkflow( workflowId, 'cancelPayment', [reason] ); } } ``` -------------------------------- ### Client-Only Module Registration Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/getting-started.md Registers the TemporalClientModule for services that only need to start or query workflows. Requires connection address and optional namespace. ```typescript import { TemporalClientModule } from 'nestjs-temporal-core/client'; TemporalClientModule.register({ connection: { address: 'localhost:7233' }, namespace: 'default', }) ``` -------------------------------- ### Register TemporalModule in AppModule Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/README.md Example of registering the TemporalModule in a NestJS application module, configuring the Temporal connection, task queue, and worker options. The module is configured with a workflows path and activity classes, and autoStart is enabled. The PaymentActivity is provided for dependency injection. ```typescript // app.module.ts import { Module } from '@nestjs/common'; import { TemporalModule } from 'nestjs-temporal-core'; import { PaymentActivity } from './activities/payment.activity'; @Module({ imports: [ TemporalModule.register({ connection: { address: 'localhost:7233', namespace: 'default' }, taskQueue: 'my-task-queue', worker: { workflowsPath: require.resolve('./workflows'), activityClasses: [PaymentActivity], autoStart: true, }, }), ], providers: [PaymentActivity], }) export class AppModule {} ``` -------------------------------- ### Manual Worker Creation with Native Temporal SDK Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/configuration.md Use this snippet to create a custom Temporal worker with full control over the connection and worker options. It accesses the native connection via the TemporalService's worker manager and throws an error if no connection is available. The worker is created with a custom task queue, namespace, workflows path, and activities, then started with run(). ```typescript import { Injectable, OnModuleInit } from '@nestjs/common'; import { TemporalService } from 'nestjs-temporal-core'; import { Worker } from '@temporalio/worker'; @Injectable() export class CustomWorkerService implements OnModuleInit { private customWorker: Worker; constructor(private readonly temporal: TemporalService) {} async onModuleInit() { const workerManager = this.temporal.getWorkerManager(); const connection = workerManager.getConnection(); if (!connection) { throw new Error('No connection available'); } // Create your custom worker using the native Temporal SDK this.customWorker = await Worker.create({ connection, taskQueue: 'custom-task-queue', namespace: 'default', workflowsPath: require.resolve('./workflows/custom'), activities: { myCustomActivity: async (data: string) => { return `Processed: ${data}`; }, }, }); // Start the worker await this.customWorker.run(); } } ``` -------------------------------- ### Inject and use typed workflow proxy in NestJS service Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/core-concepts.md Shows a NestJS service injecting a typed workflow proxy via a custom token. Methods demonstrate typed start, signal, query, getHandle, and signalWithStart calls with full type inference from the workflow and signal definitions. ```typescript // order.service.ts import { Injectable, Inject } from '@nestjs/common'; import { IWorkflowProxy } from 'nestjs-temporal-core'; import { orderWorkflow, approveSignal, cancelSignal, statusQuery, OrderStatus, } from './workflows/order.workflow'; import { ORDER_WORKFLOW } from './order.module'; @Injectable() export class OrderService { constructor( @Inject(ORDER_WORKFLOW) private readonly orderProxy: IWorkflowProxy, ) {} async createOrder(orderId: string, customerId: number) { // start() args are typed as Parameters = [string, number] const handle = await this.orderProxy.start([orderId, customerId], { workflowId: `order-${orderId}`, }); return { workflowId: handle.workflowId }; } async approve(workflowId: string, approver: string) { // signal() infers TArgs from approveSignal — passing a number here is a compile error await this.orderProxy.signal(workflowId, approveSignal, approver); } async getStatus(workflowId: string): Promise { // query() return type is inferred from statusQuery return this.orderProxy.query(workflowId, statusQuery); } async waitForCompletion(workflowId: string): Promise { const handle = await this.orderProxy.getHandle(workflowId); // handle.result() is Promise, not Promise return handle.result(); } async cancelOrder(orderId: string, reason: string) { // signalWithStart: atomically starts the workflow and signals it await this.orderProxy.signalWithStart( cancelSignal, [reason], // signal args — typed [orderId, 0], // workflow args — typed as Parameters { workflowId: `order-${orderId}` }, ); } } ``` -------------------------------- ### Build and test commands Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/AGENTS.md Standard npm scripts for building, testing, linting, formatting, and type-checking the library. Use these in the repository root. ```bash npm run build # tsc → dist/ npm run test # jest npm run lint # eslint src/**/*.ts npm run format # prettier npm run type-check # tsc --noEmit ``` -------------------------------- ### Async Configuration with useClass (TemporalConfigService) Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/configuration.md This snippet shows how to provide dynamic Temporal options using a config service that reads from environment variables. It defines a TemporalConfigService implementing TemporalOptionsFactory and registers it in the module with registerAsync. The configuration includes connection address, namespace, task queue, and worker settings with defaults. ```typescript // config/temporal.config.ts import { Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { TemporalOptionsFactory, TemporalOptions } from 'nestjs-temporal-core'; @Injectable() export class TemporalConfigService implements TemporalOptionsFactory { constructor(private configService: ConfigService) {} createTemporalOptions(): TemporalOptions { return { connection: { address: this.configService.get('TEMPORAL_ADDRESS', 'localhost:7233'), namespace: this.configService.get('TEMPORAL_NAMESPACE', 'default'), }, taskQueue: this.configService.get('TEMPORAL_TASK_QUEUE', 'default'), worker: { workflowsPath: require.resolve('../workflows'), activityClasses: [], // Populated by module maxConcurrentActivityExecutions: 100, }, }; } } // app.module.ts import { ConfigModule } from '@nestjs/config'; @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true }), TemporalModule.registerAsync({ imports: [ConfigModule], useClass: TemporalConfigService, }), ], }) export class AppModule {} ``` -------------------------------- ### Run linting Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/CONTRIBUTING.md Command to execute linting checks on the codebase. ```bash npm run lint ``` -------------------------------- ### signalWithStart via TemporalClientService Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/core-concepts.md Use this snippet to call signalWithStart through TemporalClientService, which returns a raw workflow handle. This allows advanced options like workflowIdReusePolicy, workflowExecutionTimeout, and memo. ```typescript const handle = await this.clientService.signalWithStart( 'orderWorkflow', 'approve', ['manager-approval'], [orderId, customerId], { workflowId: `order-${orderId}`, taskQueue: 'orders', workflowIdReusePolicy: 'ALLOW_DUPLICATE', workflowExecutionTimeout: '1h', memo: { source: 'api' }, }, ); ``` -------------------------------- ### New APIs in v3.3.0: Typed Workflow Proxy and signalWithStart Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/migration-guide.md Use this snippet to leverage the new typed workflow proxy and atomic signalWithStart introduced in v3.3.0. It imports the new APIs, creates a typed workflow provider for 'orderWorkflow', and demonstrates signalWithStart on 'cartWorkflow'. The workflowId and taskQueue are required for the signalWithStart call. ```typescript import { IWorkflowProxy, WorkflowProxyFactory, createWorkflowToken, createWorkflowProvider, } from 'nestjs-temporal-core'; // Typed proxy — see "Core Concepts" for the full pattern const ORDER_WORKFLOW = createWorkflowToken('orderWorkflow'); const provider = createWorkflowProvider(ORDER_WORKFLOW, { workflowType: 'orderWorkflow', taskQueue: 'orders', }); // Atomic start + signal — see "Core Concepts" > Signal-with-Start await temporal.signalWithStart( 'cartWorkflow', 'addItem', [{ sku: 'SKU-123', qty: 2 }], [userId], { workflowId: `cart-${userId}`, taskQueue: 'carts' }, ); ``` -------------------------------- ### Basic TemporalModule.register() configuration Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/configuration.md Configures the Temporal module with a connection address, namespace, task queue, and worker settings. The worker uses a workflows path and activity classes, with autoStart enabled and a maximum of 100 concurrent activity executions. Logging is enabled at 'info' level. ```typescript TemporalModule.register({ connection: { address: 'localhost:7233', namespace: 'default', }, taskQueue: 'my-task-queue', worker: { workflowsPath: require.resolve('./workflows'), activityClasses: [PaymentActivity, EmailActivity], autoStart: true, maxConcurrentActivityExecutions: 100, }, logLevel: 'info', enableLogger: true, }) ``` -------------------------------- ### Define activities with @Activity and @ActivityMethod Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/getting-started.md Shows how to create a NestJS injectable activity class with methods decorated for Temporal. Includes simulated payment processing and refund logic. ```typescript // payment.activity.ts import { Injectable } from '@nestjs/common'; import { Activity, ActivityMethod } from 'nestjs-temporal-core'; export interface PaymentData { amount: number; currency: string; customerId: string; } @Injectable() @Activity({ name: 'payment-activities' }) export class PaymentActivity { @ActivityMethod('processPayment') async processPayment(data: PaymentData): Promise<{ transactionId: string }> { // Payment processing logic with full NestJS DI support console.log(`Processing payment: $${data.amount} ${data.currency}`); // Simulate payment processing await new Promise(resolve => setTimeout(resolve, 1000)); return { transactionId: `txn_${Date.now()}` }; } @ActivityMethod('refundPayment') async refundPayment(transactionId: string): Promise<{ refundId: string }> { // Refund logic console.log(`Refunding transaction: ${transactionId}`); return { refundId: `ref_${Date.now()}` }; } } ``` -------------------------------- ### Define and handle signals and queries in a workflow Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/core-concepts.md Shows how to define signals and queries at module level and set up handlers inside a workflow. The workflow waits for a completion signal using condition(). ```typescript import { defineSignal, defineQuery, setHandler, condition } from '@temporalio/workflow'; // Define at module level export const updateStatusSignal = defineSignal<[string]>('updateStatus'); export const addItemSignal = defineSignal<[Item]>('addItem'); export const getItemsQuery = defineQuery('getItems'); export const getStatusQuery = defineQuery('getStatus'); export async function myWorkflow(): Promise { let status = 'pending'; const items: Item[] = []; // Set up handlers setHandler(updateStatusSignal, (newStatus: string) => { status = newStatus; }); setHandler(addItemSignal, (item: Item) => { items.push(item); }); setHandler(getItemsQuery, () => items); setHandler(getStatusQuery, () => status); // Wait for completion signal await condition(() => status === 'completed'); } ``` -------------------------------- ### Define and handle a workflow update Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/core-concepts.md Shows how to define an update and set its handler. The update mutates balance and returns the new balance. The workflow runs indefinitely with condition(() => false). ```typescript import { defineUpdate, setHandler } from '@temporalio/workflow'; export const depositUpdate = defineUpdate('deposit'); export async function accountWorkflow(initialBalance: number): Promise { let balance = initialBalance; setHandler(depositUpdate, (amount: number) => { balance += amount; return balance; }); await condition(() => false); // keep running } ``` -------------------------------- ### Create a new feature branch Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/CONTRIBUTING.md Command to create and switch to a new branch for your feature development. ```bash git checkout -b feature/your-feature-name ``` -------------------------------- ### Configure timeouts for activities and workflows Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/troubleshooting.md This snippet shows how to set appropriate timeouts for activities using proxyActivities and for workflows using startWorkflow options. It includes startToCloseTimeout, scheduleToCloseTimeout, scheduleToStartTimeout, workflowExecutionTimeout, workflowRunTimeout, and workflowTaskTimeout. ```typescript // Configure appropriate timeouts const activities = proxyActivities({ startToCloseTimeout: '10m', // Increase for long-running activities scheduleToCloseTimeout: '15m', // Total time including queuing scheduleToStartTimeout: '5m', // Time waiting in queue }); // For workflows await temporal.startWorkflow('myWorkflow', [args], { workflowExecutionTimeout: '24h', // Max total execution time workflowRunTimeout: '12h', // Max single run time workflowTaskTimeout: '10s', // Decision task timeout }); ``` -------------------------------- ### Check connection configuration and register TemporalModule Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/troubleshooting.md Use this snippet to diagnose connection errors by checking the health status and verifying the Temporal server is running. It also shows the recommended connection settings for TemporalModule.register, including the address and namespace. ```typescript // Check connection configuration const health = temporalService.getHealth(); console.log('Connection status:', health.client.connectionStatus); // Verify Temporal server is running // docker ps | grep temporal // Check connection settings TemporalModule.register({ connection: { address: process.env.TEMPORAL_ADDRESS || 'localhost:7233', namespace: 'default', }, }) ``` -------------------------------- ### signalWithStart via TemporalService Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/core-concepts.md Use this snippet to call signalWithStart through TemporalService, which returns a structured result. Check result.success to confirm delivery and access result.signalName and result.workflowId for logging. ```typescript const result = await this.temporal.signalWithStart( 'cartWorkflow', 'addItem', [{ sku: 'SKU-123', qty: 2 }], [userId], { workflowId: `cart-${userId}`, taskQueue: 'carts' }, ); if (result.success) { this.logger.log(`Signal '${result.signalName}' delivered to ${result.workflowId}`); } ``` -------------------------------- ### Define signals and queries in workflow file Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/core-concepts.md Shows how to define signals and queries in a Temporal workflow file, including the use of setHandler and condition to manage workflow state. ```typescript // workflows/order.workflow.ts import { defineSignal, defineQuery, setHandler, condition } from '@temporalio/workflow'; export interface OrderStatus { orderId: string; state: 'pending' | 'approved' | 'shipped' | 'cancelled'; } export const approveSignal = defineSignal<[string]>('approve'); // signal takes one string arg export const cancelSignal = defineSignal<[string]>('cancel'); export const statusQuery = defineQuery('getStatus'); // query returns OrderStatus export async function orderWorkflow(orderId: string, customerId: number): Promise { let status: OrderStatus = { orderId, state: 'pending' }; setHandler(approveSignal, (approver) => { status = { ...status, state: 'approved' }; }); setHandler(cancelSignal, (reason) => { status = { ...status, state: 'cancelled' }; }); setHandler(statusQuery, () => status); await condition(() => status.state !== 'pending'); return status; } ``` -------------------------------- ### Complete Activities Asynchronously with Task Tokens Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/advanced-configuration.md Shows how to use task-token-based methods on TemporalClientService to heartbeat, complete, or fail an activity from outside its handler, such as in human-in-the-loop approvals or callbacks from another process. ```typescript await this.clientService.heartbeatActivity(taskToken, { progress: 50 }); await this.clientService.completeActivity(taskToken, { approved: true }); // or, on failure: await this.clientService.failActivity(taskToken, new Error('rejected by approver')); ``` -------------------------------- ### New APIs for Workflow Updates, Async Activity Completion, Standalone Activities, and Schedule Lifecycle Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/migration-guide.md Demonstrates the new APIs introduced in this upgrade: @UpdateMethod decorator for workflow update handlers, client-side update calls, async activity completion, standalone activities, and schedule lifecycle management. Use these to leverage the new features. Note that standalone activities are in Public Preview. ```typescript import { UpdateMethod } from 'nestjs-temporal-core'; // Workflow Update handler (mirrors @SignalMethod/@QueryMethod) @UpdateMethod('deposit') async handleDeposit(amount: number): Promise { /* ... */ } // Client-side Update calls await clientService.updateWorkflow('account-123', 'deposit', [100]); await clientService.startUpdateWorkflow('account-123', 'deposit', [100]); // Async Activity Completion await clientService.completeActivity(taskToken, result); await clientService.failActivity(taskToken, error); // Standalone Activities (Public Preview) await clientService.executeStandaloneActivity('sendEmail', { id: 'e-1', taskQueue: 'q' }); // Schedule lifecycle await scheduleService.pauseSchedule('daily-report'); await scheduleService.triggerSchedule('daily-report'); await scheduleService.deleteSchedule('daily-report'); ``` -------------------------------- ### Define workflow with signals and queries Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/getting-started.md Shows a pure Temporal workflow function using proxyActivities, defineSignal, defineQuery, and setHandler. Handles cancellation and status queries. ```typescript // payment.workflow.ts import { proxyActivities, defineSignal, defineQuery, setHandler } from '@temporalio/workflow'; import type { PaymentActivity } from './payment.activity'; // Create activity proxies const { processPayment, refundPayment } = proxyActivities({ startToCloseTimeout: '5m', retry: { maximumAttempts: 3, initialInterval: '1s', }, }); // Define signals and queries export const cancelPaymentSignal = defineSignal<[string]>('cancelPayment'); export const getPaymentStatusQuery = defineQuery('getPaymentStatus'); export async function processPaymentWorkflow(data: PaymentData): Promise { let status = 'processing'; let transactionId: string | undefined; // Set up signal and query handlers setHandler(cancelPaymentSignal, (reason: string) => { status = 'cancelled'; }); setHandler(getPaymentStatusQuery, () => status); try { // Execute payment activity const result = await processPayment(data); transactionId = result.transactionId; status = 'completed'; return { success: true, transactionId, status, }; } catch (error) { status = 'failed'; // Compensate if needed if (transactionId) { await refundPayment(transactionId); } throw error; } } ``` -------------------------------- ### Test Workflow with TestWorkflowEnvironment Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/advanced-usage.md Use this snippet to test a Temporal workflow by mocking activities and running the workflow in a time-skipping test environment. ```typescript import { TestWorkflowEnvironment } from '@temporalio/testing'; import { Worker } from '@temporalio/worker'; import { processOrderWorkflow } from './order.workflow'; describe('Order Workflow', () => { let testEnv: TestWorkflowEnvironment; beforeAll(async () => { testEnv = await TestWorkflowEnvironment.createTimeSkipping(); }); afterAll(async () => { await testEnv?.teardown(); }); it('should process order successfully', async () => { const { client, nativeConnection } = testEnv; // Mock activities const mockOrderActivity = { validatePayment: async () => ({ valid: true }), reserveInventory: async () => ({ reservationId: 'res-123' }), chargePayment: async () => ({ transactionId: 'txn-123' }), sendConfirmationEmail: async () => {}, }; const worker = await Worker.create({ connection: nativeConnection, taskQueue: 'test', workflowsPath: require.resolve('./order.workflow'), activities: mockOrderActivity, }); await worker.runUntil(async () => { const result = await client.workflow.execute(processOrderWorkflow, { workflowId: 'test-order-1', taskQueue: 'test', args: [{ orderId: 'order-123', payment: { amount: 100, currency: 'USD' }, items: [{ id: '1', quantity: 1 }], }], }); expect(result.status).toBe('completed'); expect(result.transactionId).toBe('txn-123'); }); }); }); ``` -------------------------------- ### Configure Worker Versioning with workerDeploymentOptions Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/advanced-configuration.md Sets up worker versioning by passing workerDeploymentOptions with a buildId and deploymentName, and enabling useWorkerVersioning. This is a GA feature in SDK 1.16+. ```typescript worker: { workflowsPath: './dist/workflows', workerOptions: { workerDeploymentOptions: { version: { buildId: 'v1.2.0', deploymentName: 'my-service' }, useWorkerVersioning: true, }, }, }, ``` -------------------------------- ### Schedule Lifecycle Operations with TemporalScheduleService Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/advanced-configuration.md Demonstrates the full schedule lifecycle: pause, unpause, trigger, delete, update, describe, and list schedules. Use these methods to manage schedules programmatically. The updateSchedule callback receives the previous schedule and returns the updated spec. ```typescript await this.scheduleService.pauseSchedule('daily-report', 'investigating an incident'); await this.scheduleService.unpauseSchedule('daily-report'); await this.scheduleService.triggerSchedule('daily-report', 'ALLOW_ALL'); await this.scheduleService.deleteSchedule('daily-report'); await this.scheduleService.updateSchedule('daily-report', (previous) => ({ ...previous, spec: { ...previous.spec, cronExpressions: ['0 9 * * *'] }, })); const { description } = await this.scheduleService.describeSchedule('daily-report'); const { schedules } = this.scheduleService.listSchedules(); for await (const schedule of schedules ?? []) { console.log(schedule.scheduleId, schedule.info.numActions); } ``` -------------------------------- ### Accessing and managing multiple workers with TemporalService Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/configuration.md Shows how to use TemporalService to check worker status, control workers, and register new workers at runtime. Methods include getAllWorkers(), getWorkerStatusByTaskQueue(), startWorkerByTaskQueue(), stopWorkerByTaskQueue(), and registerWorker(). ```typescript import { Injectable } from '@nestjs/common'; import { TemporalService } from 'nestjs-temporal-core'; @Injectable() export class WorkerManagementService { constructor(private readonly temporal: TemporalService) {} async checkWorkerStatus() { // Get all workers info const workersInfo = this.temporal.getAllWorkers(); console.log(`Total workers: ${workersInfo.totalWorkers}`); console.log(`Running workers: ${workersInfo.runningWorkers}`); // Get specific worker status const paymentWorkerStatus = this.temporal.getWorkerStatusByTaskQueue('payments-queue'); if (paymentWorkerStatus?.isHealthy) { console.log('Payment worker is healthy'); } } async controlWorkers() { // Start a specific worker await this.temporal.startWorkerByTaskQueue('background-jobs'); // Stop a specific worker await this.temporal.stopWorkerByTaskQueue('notifications-queue'); } async registerNewWorker() { // Dynamically register a new worker at runtime const result = await this.temporal.registerWorker({ taskQueue: 'new-queue', workflowsPath: require.resolve('./workflows/new'), activityClasses: [NewActivity], autoStart: true, }); if (result.success) { console.log(`Worker registered for queue: ${result.taskQueue}`); } } } ``` -------------------------------- ### Alternative Async Pattern with useFactory Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/configuration.md Use this snippet to configure Temporal asynchronously using a factory function that reads from the ConfigService. It provides inline connection, task queue, and worker options, including activity classes. The inject array supplies the ConfigService to the factory. ```typescript TemporalModule.registerAsync({ imports: [ConfigModule], useFactory: (configService: ConfigService) => ({ connection: { address: configService.get('TEMPORAL_ADDRESS', 'localhost:7233'), namespace: configService.get('TEMPORAL_NAMESPACE', 'default'), }, taskQueue: configService.get('TEMPORAL_TASK_QUEUE', 'default'), worker: { workflowsPath: require.resolve('./workflows'), activityClasses: [PaymentActivity, EmailActivity], }, }), inject: [ConfigService], }) ``` -------------------------------- ### Multiple workers configuration with TemporalModule.register() Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/configuration.md Configures multiple workers with different task queues in the same process, a feature new in 3.0.12. Global defaults for autoRestart and maxRestarts are set, and each worker can override them. Workers can have different activity classes, autoStart settings, and worker options. ```typescript TemporalModule.register({ connection: { address: 'localhost:7233', namespace: 'default', }, autoRestart: true, // Global default for all workers maxRestarts: 3, // Global default for all workers workers: [ { taskQueue: 'payments-queue', workflowsPath: require.resolve('./workflows/payments'), activityClasses: [PaymentActivity, RefundActivity], autoStart: true, maxRestarts: 5, // Override for this critical worker workerOptions: { maxConcurrentActivityTaskExecutions: 100, }, }, { taskQueue: 'notifications-queue', workflowsPath: require.resolve('./workflows/notifications'), activityClasses: [EmailActivity, SmsActivity], autoStart: true, workerOptions: { maxConcurrentActivityTaskExecutions: 50, }, }, { taskQueue: 'background-jobs', workflowsPath: require.resolve('./workflows/jobs'), activityClasses: [DataProcessingActivity], autoStart: false, // Start manually later autoRestart: false, // Disable auto-restart for this worker }, ], logLevel: 'info', enableLogger: true, }) ``` -------------------------------- ### Use typed workflow proxy for update Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/core-concepts.md Shows how to call an update through the typed workflow proxy with full type inference. ```typescript const newBalance = await this.accountProxy.update('account-123', depositUpdate, 100); ``` -------------------------------- ### Register typed proxy as NestJS provider Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/core-concepts.md Shows how to register a typed workflow proxy as a NestJS provider using createWorkflowToken and createWorkflowProvider from 'nestjs-temporal-core'. ```typescript // order.module.ts import { Module } from '@nestjs/common'; import { createWorkflowToken, createWorkflowProvider } from 'nestjs-temporal-core'; import { orderWorkflow } from './workflows/order.workflow'; import { OrderService } from './order.service'; export const ORDER_WORKFLOW = createWorkflowToken('orderWorkflow'); @Module({ providers: [ OrderService, createWorkflowProvider(ORDER_WORKFLOW, { workflowType: 'orderWorkflow', taskQueue: 'orders', }), ], exports: [ORDER_WORKFLOW], }) export class OrderModule {} ``` -------------------------------- ### Configure TemporalModule in app.module.ts Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/getting-started.md Imports and configures TemporalModule with connection details, task queue, and worker settings. Registers activity classes as providers. ```typescript // app.module.ts import { Module } from '@nestjs/common'; import { TemporalModule } from 'nestjs-temporal-core'; import { PaymentActivity } from './activities/payment.activity'; import { EmailActivity } from './activities/email.activity'; @Module({ imports: [ TemporalModule.register({ connection: { address: 'localhost:7233', namespace: 'default', }, taskQueue: 'my-task-queue', worker: { workflowsPath: require.resolve('./workflows'), activityClasses: [PaymentActivity, EmailActivity], autoStart: true, }, }), ], providers: [PaymentActivity, EmailActivity], }) export class AppModule {} ``` -------------------------------- ### Define an Activity with @Activity() and @ActivityMethod() Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/core-concepts.md Activities are NestJS services decorated with @Activity() at class level and @ActivityMethod() on methods. They have full access to NestJS dependency injection and should be idempotent and handle retries gracefully. ```typescript @Injectable() @Activity({ name: 'order-activities' }) export class OrderActivity { constructor( private readonly orderRepository: OrderRepository, private readonly emailService: EmailService, ) {} @ActivityMethod('createOrder') async createOrder(orderData: CreateOrderData): Promise { // Database operations with full DI support const order = await this.orderRepository.create(orderData); await this.emailService.sendConfirmation(order); return order; } @ActivityMethod('validateInventory') async validateInventory(items: OrderItem[]): Promise { // Business logic with injected services return await this.orderRepository.checkInventory(items); } } ``` -------------------------------- ### Enable debug mode and check health and statistics Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/troubleshooting.md This snippet shows how to enable debug logging and debug mode in TemporalModule.register, and how to retrieve detailed health and statistics information using getHealth() and getStatistics(). ```typescript TemporalModule.register({ logLevel: 'debug', enableLogger: true, connection: { address: 'localhost:7233', }, worker: { debugMode: true, // If available }, }) // Check detailed health and statistics const health = temporalService.getHealth(); const stats = temporalService.getStatistics(); console.log('Health:', JSON.stringify(health, null, 2)); console.log('Stats:', JSON.stringify(stats, null, 2)); ``` -------------------------------- ### After: typed workflow proxy Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/core-concepts.md Shows the typed proxy approach where method signatures are inferred from the workflow type, providing end-to-end type safety. ```typescript // After: fully typed against the workflow signature const handle = await this.orderProxy.start([orderId, customerId]); // args typed as Parameters const status = await this.orderProxy.query(workflowId, statusQuery); // return type inferred from QueryDefinition ``` -------------------------------- ### Configure Worker-Side Interceptors via workerOptions.interceptors Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/advanced-configuration.md Use this snippet to register worker-side interceptors (e.g., activityInbound) by passing them through workerOptions.interceptors. This option is spread wholesale into Worker.create(), so any interceptor accepted by @temporalio/worker works. ```typescript TemporalModule.register({ connection: { address: 'localhost:7233' }, worker: { workflowsPath: './dist/workflows', workerOptions: { interceptors: { activityInbound: [(ctx) => new MyActivityInterceptor(ctx)], }, }, }, }); ``` -------------------------------- ### Ensure activity is registered in activityClasses and providers Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/troubleshooting.md This snippet shows how to register an activity class in the worker's activityClasses array and as a provider in the module. It also includes the activity decorator and method decorator, and how to check discovery status. ```typescript // 1. Ensure activity is in activityClasses array TemporalModule.register({ worker: { activityClasses: [MyActivity], // Must include the activity class }, }) // 2. Verify activity is registered as provider @Module({ providers: [MyActivity], // Must be in providers array }) // 3. Check activity decorator @Activity({ name: 'my-activities' }) export class MyActivity { @ActivityMethod('myActivity') async myActivity() { } } // 4. Check discovery status const health = temporalService.getHealth(); console.log('Activities discovered:', health.discovery.activitiesDiscovered); ``` -------------------------------- ### Unified Module Registration Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/getting-started.md Registers the TemporalModule with both client and worker capabilities. Requires connection address, task queue, and worker configuration with workflows path and activity classes. ```typescript import { TemporalModule } from 'nestjs-temporal-core'; TemporalModule.register({ connection: { address: 'localhost:7233' }, taskQueue: 'my-queue', worker: { workflowsPath: require.resolve('./workflows'), activityClasses: [PaymentActivity, EmailActivity], }, }) ``` -------------------------------- ### Multiple Workers Configuration (v3.0.12) Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/migration-guide.md Migrate to multiple workers by replacing the single 'worker' option with a 'workers' array. Each worker specifies its own taskQueue, workflowsPath, and activityClasses. ```typescript TemporalModule.register({ connection: { address: 'localhost:7233' }, workers: [ { taskQueue: 'main-queue', workflowsPath: require.resolve('./workflows/main'), activityClasses: [MainActivity], }, { taskQueue: 'schedule-queue', workflowsPath: require.resolve('./workflows/schedule'), activityClasses: [ScheduleActivity], }, ], }) ``` -------------------------------- ### TemporalOptions Interface Reference Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/configuration.md This TypeScript interface defines all available configuration options for the Temporal module. It includes connection settings, task queue, worker configuration, logging, auto-restart, and advanced options with their defaults. ```typescript interface TemporalOptions { // Connection settings connection: { address: string; // Temporal server address (default: 'localhost:7233') namespace?: string; // Temporal namespace (default: 'default') tls?: TLSConfig; // TLS configuration for secure connections }; // Task queue name taskQueue?: string; // Default task queue (default: 'default') // Worker configuration worker?: { workflowsPath?: string; // Path to workflow definitions (use require.resolve) activityClasses?: any[]; // Array of activity classes to register autoStart?: boolean; // Auto-start worker on module init (default: true) autoRestart?: boolean; // Auto-restart on failure (inherits from global) maxRestarts?: number; // Max restart attempts (inherits from global) maxConcurrentActivityExecutions?: number; // Max concurrent activities (default: 100) maxActivitiesPerSecond?: number; // Rate limit for activities }; // Logging logLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error'; // Log level (default: 'info') enableLogger?: boolean; // Enable logging (default: true) // Auto-restart configuration autoRestart?: boolean; // Auto-restart worker on failure (default: true) maxRestarts?: number; // Max restart attempts before giving up (default: 3) // Advanced isGlobal?: boolean; // Make module global (default: false) } ``` -------------------------------- ### Disable gRPC Compression with grpcCompression: { codec: 'none' } Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/advanced-configuration.md Use this snippet to opt out of gRPC gzip compression for the worker's native connection, which is enabled by default in Temporal SDK 1.19. Set grpcCompression to { codec: 'none' } if your server cannot decompress the compressed data. ```typescript TemporalModule.register({ connection: { address: 'localhost:7233', grpcCompression: { codec: 'none' }, }, }); ``` -------------------------------- ### Activity-Only Module Registration Source: https://github.com/hmake98/nestjs-temporal-core/blob/main/website/docs/getting-started.md Registers the TemporalActivityModule for standalone activity management. Requires activity classes to be provided. ```typescript import { TemporalActivityModule } from 'nestjs-temporal-core/activity'; TemporalActivityModule.register({ activityClasses: [DataProcessingActivity], }) ```