### Example: Start a Workflow Source: https://workflow-sdk.dev/docs/how-it-works/framework-integrations An example demonstrating how to start a workflow using a GET request. ```APIDOC ## Example: Start a Workflow ### Description An example demonstrating how to start a workflow using a GET request. ### Method GET ### Endpoint `/` ### Request Body ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **email** (string) - Description ``` -------------------------------- ### Example: Start a Workflow via GET Request Source: https://workflow-sdk.dev/docs/how-it-works/framework-integrations Illustrates how to initiate a workflow using a GET request to a specific webhook endpoint. This example shows how to extract data from the request. ```javascript async (req) => { { const email = ``` -------------------------------- ### Saga Setup Example Source: https://workflow-sdk.dev/cookbook/common-patterns/saga Demonstrates the basic setup for a saga, including the use of the 'workflow' directive. ```typescript export async function subscriptionUpgradeSaga(accountId: string, seats: number) { "use workflow"; ``` -------------------------------- ### Global Setup Script for Server Lifecycle Management Source: https://workflow-sdk.dev/docs/testing/server-based The globalSetup script is responsible for starting a dev server before tests begin and tearing it down once tests are complete. This example demonstrates the basic structure for such a script. ```typescript import { setup, teardown } from "@workflow/vitest"; export default { setup, teardown, }; ``` -------------------------------- ### Vite Configuration Example Source: https://workflow-sdk.dev/docs/getting-started/vite This snippet shows a basic configuration for Vite, including plugin setup. ```javascript import react from "@vitejs/plugin-react"; import { defineConfig } from "vite"; // https://vitejs.dev/config/ export default defineConfig({ plugins: [react()], }); ``` -------------------------------- ### Setup Server for Testing Source: https://workflow-sdk.dev/docs/testing/server-based Starts a server process, monitors its output for readiness, and sets the `WORKFLOW_LOCAL_BASE_URL` environment variable. Includes logging for server status and errors. Throws an error if the server fails to start within 15 seconds. ```typescript import { spawn } from "node:child_process"; import { setTimeout as delay } from "node:timers/promises"; import type { ChildProcess } from "node:child_process"; let server: ChildProcess | null = null; const PORT = "4000"; function emitSetupLog(event: string, fields: Record = {}) { console.log( JSON.stringify({ scope: "workflow-server-test", event, port: PORT, ...fields, }) ); } export async function setup() { const stdout: string[] = []; const stderr: string[] = []; emitSetupLog("server_starting", { command: `npx nitro dev --port ${PORT}`, }); server = spawn("npx", ["nitro", "dev", "--port", PORT], { stdio: "pipe", detached: false, env: process.env, }); const ready = await new Promise((resolve) => { const timeout = setTimeout(() => resolve(false), 15_000); server?.stdout?.on("data", (data) => { const output = data.toString(); stdout.push(output); emitSetupLog("server_stdout", { message: output.trim() }); if (output.includes("listening") || output.includes("ready")) { clearTimeout(timeout); resolve(true); } }); server?.stderr?.on("data", (data) => { const output = data.toString(); stderr.push(output); emitSetupLog("server_stderr", { message: output.trim() }); }); server?.on("error", (error) => { emitSetupLog("server_process_error", { name: error.name, message: error.message, }); clearTimeout(timeout); resolve(false); }); server?.on("exit", (code, signal) => { emitSetupLog("server_exit", { code, signal }); }); }); if (!ready) { const recentStdout = stdout.join("").trim().slice(-2000); const recentStderr = stderr.join("").trim().slice(-2000); throw new Error( [ "Server failed to start within 15 seconds.", `Command: npx nitro dev --port ${PORT}`, `WORKFLOW_LOCAL_BASE_URL: http://localhost:${PORT}`, `Recent stdout:\n${recentStdout || "(empty)"}`, `Recent stderr:\n${recentStderr || "(empty)"}`, ].join("\n\n") ); } await delay(2_000); process.env.WORKFLOW_LOCAL_BASE_URL = `http://localhost:${PORT}`; emitSetupLog("server_ready", { baseUrl: process.env.WORKFLOW_LOCAL_BASE_URL, }); } ``` -------------------------------- ### Clone Example App Source: https://workflow-sdk.dev/docs/ai Clone the example application repository to get a project with a chat interface and an API route for LLM calls. This serves as a starting point for integrating the Workflow SDK. ```bash git clone https://github.com/vercel/workflow-examples -b plain-ai-sdk cd workflow-examples/flight-booking-app ``` -------------------------------- ### Starting a Workflow Source: https://workflow-sdk.dev/docs/foundations/starting-workflows This example demonstrates how to start a workflow named 'handleUserSignup' from an API route. It takes an email address as an argument and returns a JSON response containing a message and the workflow's run ID. ```APIDOC ## POST /api/start-workflow ### Description Starts a new workflow execution for user signup and returns its run ID. ### Method POST ### Endpoint `/api/start-workflow` ### Parameters #### Request Body - **email** (string) - Required - The email address of the user to sign up. ### Request Example ```json { "email": "user@example.com" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message that the workflow has started. - **runId** (string) - The unique identifier for the started workflow run. #### Response Example ```json { "message": "Workflow started", "runId": "run_abc123" } ``` ``` -------------------------------- ### Importing Framework Components for Getting Started Page Source: https://workflow-sdk.dev/llms.txt This import statement is used on the 'Getting Started' page to bring in various framework components for display. ```javascript import { Next, Nitro, SvelteKit, Nuxt, Hono, Bun, AstroDark, AstroLight, TanStack, Vite, Express, Nest, Fastify, Python } from "@/app/[lang]/(home)/components/frameworks"; ``` -------------------------------- ### Starting a Workflow with Arguments Source: https://workflow-sdk.dev/docs/api-reference/workflow-api/start Use the `start` function to initiate a workflow. Pass the workflow definition and an array of arguments. This example starts `myWorkflow` with the argument 'arg1'. ```javascript const run = await start(myWorkflow, ["arg1"]); ``` -------------------------------- ### Configure Global Setup for Server-Based Tests Source: https://workflow-sdk.dev/docs/testing/server-based Configure your testing framework to use a global setup script for starting and stopping a development server. This ensures the server is ready before tests run and cleaned up afterward. ```javascript globalSetup: "./vitest.server.setup.ts", env: { WORKFLOW_LOCAL_BASE_URL: "http://localhost:4000", } ``` -------------------------------- ### Resume or Start Workflow Example Source: https://workflow-sdk.dev/docs/api-reference/workflow-api/resume-hook Demonstrates how to use resumeHook to either resume an existing workflow instance or start a new one if it doesn't exist. This is achieved by checking the result of the resume operation. ```javascript import { resumeHook, startWorkflow } from "@/lib/workflow-sdk"; async function handleResumeOrStart(workflowId, stepId, initialData) { try { // Attempt to resume the workflow const result = await resumeHook(workflowId, stepId); console.log("Workflow resumed:", result); return result; } catch (error) { // If resuming fails (e.g., workflow not found or already completed), start a new one console.warn("Could not resume workflow, attempting to start:", error); if (error.message.includes("not found")) { const newResult = await startWorkflow(stepId, initialData); console.log("Workflow started:", newResult); return newResult; } else { throw error; // Re-throw other errors } } } // Example usage: handleResumeOrStart("my-workflow-id", "initial-step", { data: "some initial data" }); ``` -------------------------------- ### Starting a Workflow and Streaming Output Source: https://workflow-sdk.dev/docs/foundations/starting-workflows This snippet demonstrates how to start a workflow, get a writable stream for its output, and then stream the updates as they become available. It's useful for real-time monitoring of workflow execution. ```typescript const writable = await workflow.start( "my-workflow-id", { prompt: "string" }, ); const writer = writable.getWriter(); // Stream updates as they become available for (let i = 0; i < 10; i++) { const chunk = await reader.read(); if (chunk.done) { break; } console.log(chunk.value); } ``` -------------------------------- ### Create a New Vite Project Source: https://workflow-sdk.dev/docs/getting-started/vite Use this command to initialize a new Vite project. It creates a directory with a minimal setup and installs Vite. ```bash npm create vite@latest my-workflow-app --template react ``` -------------------------------- ### Example Step with Logging Source: https://workflow-sdk.dev/docs/getting-started/vite This JavaScript code demonstrates a custom step within a workflow. It logs a message to the console, indicating the start of a process. ```javascript console.log(`Sending welcome email to user: ${user.id}`); ``` -------------------------------- ### Basic Resumable Stream Example Source: https://workflow-sdk.dev/docs/ai/resumable-streams Demonstrates the fundamental setup for a resumable stream. Ensure you have the necessary imports and context for this to function correctly. ```typescript const stream = new Stream(); stream.onData((data) => { console.log(data); }); stream.onError((error) => { console.error(error); }); stream.onComplete(() => { console.log('Stream completed'); }); // ... render your chat UI }); ``` -------------------------------- ### Streaming Updates from Tools Source: https://workflow-sdk.dev/docs/ai/streaming-updates-from-tools This example demonstrates how to stream updates from a tool. It shows how to get a writable stream, write data in chunks, and release the lock when done. ```typescript const generatedFlights = await getWritable(MessageChunk.Flights); // Sort by price generatedFlights.sort((a, b) => a.price - b.price); }; ``` -------------------------------- ### Install Dependencies Source: https://workflow-sdk.dev/docs/getting-started/vite After creating the project, navigate into the project directory and install the necessary dependencies. ```bash cd my-vite-app npm install # or yarn # or pnpm install ``` -------------------------------- ### Get Step Metadata Example Source: https://workflow-sdk.dev/docs/api-reference/workflow/get-step-metadata Demonstrates how to import and use the getStepMetadata function to retrieve information about a workflow step. Ensure the 'workflow' package is installed. ```typescript import { getStepMetadata } from "workflow"; async function chargeUser(userId: string): Promise { const metadata = await getStepMetadata(userId); // Use metadata here } ``` -------------------------------- ### Manual Setup for Testing Source: https://workflow-sdk.dev/docs/testing Use this section for manual setup if automatic configuration is insufficient. It outlines the necessary steps to prepare your environment for testing. ```markdown ### Manual Setup If you need more control over the test lifecycle, the plugin also exports the individual setup functions: ``` -------------------------------- ### Expose Workflow HTTP Endpoints with Bun.serve Source: https://workflow-sdk.dev/docs/how-it-works/framework-integrations Sets up HTTP endpoints for workflow, step, and webhook handlers using Bun.serve. Includes an example of starting a workflow via a GET request. ```typescript import flow from "./.well-known/workflow/v1/flow.js"; import step from "./.well-known/workflow/v1/step.js"; import * as webhook from "./.well-known/workflow/v1/webhook.js"; import { start } from "workflow/api"; import { handleUserSignup } from "./workflows/user-signup.js"; const server = Bun.serve({ port: process.env.PORT, routes: { "/.well-known/workflow/v1/flow": { POST: (req) => flow.POST(req), }, "/.well-known/workflow/v1/step": { POST: (req) => step.POST(req), }, // webhook exports handlers for GET, POST, DELETE, etc. "/.well-known/workflow/v1/webhook/:token": webhook, // Example: Start a workflow "/": { GET: async (req) => { const email = `test-${crypto.randomUUID()}@test.com`; const run = await start(handleUserSignup, [email]); return Response.json({ message: "User signup workflow started", runId: run.runId, }); }, }, }, }); console.log(`Server listening on http://localhost:${server.port}`); ``` -------------------------------- ### AI SDK Setup vs. Manual Source: https://workflow-sdk.dev/cookbook/integrations/ai-sdk The AI SDK offers automatic setup, contrasting with manual stream piping and turn slicing. ```text Automatic ``` -------------------------------- ### Fetching World Data Source: https://workflow-sdk.dev/worlds/postgres Example of fetching world data using `getWorld()` and starting the process with `start()`. ```javascript await world = getWorld(); await world.start?.(); ``` -------------------------------- ### Initialize npm Project Source: https://workflow-sdk.dev/llms.txt Initialize your project with npm. This creates a `package.json` file. ```bash npm init --y ``` -------------------------------- ### Getting a Writable Stream Source: https://workflow-sdk.dev/docs/api-reference/workflow/get-writable This example demonstrates how to get a writable stream for sending messages to a workflow. It shows the function signature and how to use it. ```APIDOC ## async function startStream(writable: WritableStream) { "use strict"; const writer = ``` -------------------------------- ### Start Workflow for Report Generation Source: https://workflow-sdk.dev/docs/foundations/starting-workflows Initiates a workflow designed for report generation. This example demonstrates starting a workflow with a different function name. ```typescript await start("generateReport", ``` -------------------------------- ### Starting a Workflow Source: https://workflow-sdk.dev/docs/api-reference/workflow-api/start Demonstrates how to import the start function and use it to run a workflow with arguments. ```APIDOC ## Start Workflow ### Description This function starts a workflow execution. It takes the workflow definition and an array of arguments as input. ### Method `start` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **workflow** (object) - Required - The workflow definition. * **args** (array) - Optional - An array of arguments to pass to the workflow. ### Request Example ```javascript import { start } from "workflow/api"; import { myWorkflow } from "./workflows/my-workflow"; const run = async () => { const result = await start(myWorkflow, ["arg1", "arg2"]); console.log(result); }; run(); ``` ### Response #### Success Response (200) * **result** (any) - The result of the workflow execution. ``` -------------------------------- ### Starting a Workflow with `start()` Source: https://workflow-sdk.dev/llms.txt Demonstrates how to use the `start()` function to initiate a workflow execution from a server-side context, such as an API route. It shows how to pass arguments to the workflow and retrieve the `runId` from the returned `Run` object. ```APIDOC ## start() ### Description Initiates a new workflow run by enqueuing it. This function is designed to be called from server-side code, such as API routes or Server Actions. ### Method `start(workflowFunction, args)` ### Parameters #### Workflow Function - **workflowFunction**: The workflow function to execute. - **args**: An array of serializable arguments to pass to the workflow function. This is optional if the workflow takes no arguments. ### Returns - **Run**: An object that can be used to track the workflow's progress and retrieve its results. ### Example ```typescript import { start } from "workflow/api"; import { handleUserSignup } from "./workflows/user-signup"; export async function POST(request: Request) { const { email } = await request.json(); // Start the workflow const run = await start(handleUserSignup, [email]); return Response.json({ message: "Workflow started", runId: run.runId }); } ``` ``` -------------------------------- ### Start a Child Workflow Source: https://workflow-sdk.dev/cookbook/advanced/child-workflows Use `start()` to spawn a new workflow run and get its run ID. This is the primary method for initiating child workflows. ```typescript import { start } from "@temporalio/workflow"; // ... inside a parent workflow const childRunId = await start("MyChildWorkflow", { args: ["some input"], // Use stable hook keys for deterministic tokens // e.g., document ID, job ID, or index workflowId: `child-${index}`, }); ``` -------------------------------- ### Create Webhook Example Source: https://workflow-sdk.dev/docs/api-reference/workflow/create-webhook Demonstrates how to import and use the `createWebhook` function to set up a webhook. The `using` keyword ensures the webhook is disposed of when it goes out of scope. ```APIDOC ## createWebhook ### Description Creates a webhook that can be used to trigger workflows. The webhook is automatically disposed of when it goes out of scope. ### Method ```javascript createWebhook() ``` ### Usage ```javascript import { createWebhook } from "workflow" // `using` automatically disposes the webhook when it goes out of scope using webhook = createWebhook(); console.log("Webhook URL:", webhook.url); ``` ### Response - **url** (string) - The URL of the created webhook. ``` -------------------------------- ### Get Writable Stream for UI Message Chunks Source: https://workflow-sdk.dev/docs/api-reference/workflow/get-writable This snippet demonstrates how to get a typed writable stream for UI message chunks and then start streaming messages. ```APIDOC ## Get Writable Stream ### Description Obtain a typed writable stream for UI message chunks. ### Method ```javascript getWritable() ``` ### Parameters None ### Returns A writable stream of type `UIMessageChunk`. ### Example ```javascript const writable = getWritable(); ``` ## Start Stream ### Description Starts streaming messages to the provided writable stream. ### Method ```javascript startStream(writable: Writable) ``` ### Parameters - **writable** (Writable) - The writable stream to send messages to. ### Example ```javascript await startStream(writable); ``` ## Example Usage ### Description This example shows how to get a writable stream, start the stream, and then process messages. ### Code ```javascript // Get typed writable stream for UI message chunks const writable = getWritable(); // Start the stream await startStream(writable); let currentMessages = []; // ... further message processing ... ``` ``` -------------------------------- ### Create Astro Project Source: https://workflow-sdk.dev/llms.txt Initializes a new Astro project with a minimal template. Navigate into the created directory to proceed. ```bash npm create astro@latest my-workflow-app -- --template minimal --install --yes cd my-workflow-app ``` -------------------------------- ### Start and Run Workflow in Integration Test Source: https://workflow-sdk.dev/docs/testing Use `start()` to trigger a workflow and `run.returnValue` to get its result. `returnValue` is a promise that blocks until the workflow completes or throws an error. ```typescript import { describe, it, expect } from "vitest"; import { start } from "workflow/api"; // [!code highlight] import { calculateWorkflow } from "./calculate"; describe("calculateWorkflow", () => { it("should compute the correct result", async () => { const run = await start(calculateWorkflow, [2, 7]); // [!code highlight] expect(run.runId).toMatch(/^wrun_/); // Blocks until the workflow completes or fails const result = await run.returnValue; // [!code highlight] expect(result).toEqual({ sum: 9, product: 14, combined: 23, }); const status = await run.status; // [!code highlight] expect(status).toEqual("completed"); }); }); ``` -------------------------------- ### Basic Webhook Workflow Example Source: https://workflow-sdk.dev/docs/api-reference/workflow/create-webhook This example demonstrates how to set up a basic workflow that utilizes a webhook. Ensure you have the necessary imports from the 'workflow' package. ```typescript import { createWebhook } from "workflow" export async function basicWebhookWorkflow() { "use workflow"; const webhook = createWebhook(); } ``` -------------------------------- ### Importing Start Function and Workflow Source: https://workflow-sdk.dev/docs/foundations/starting-workflows Import the `start` function from the workflow API and the specific workflow function (e.g., `processOrder`) from its module. This setup is required before you can initiate a workflow. ```typescript import { start } from "workflow/api"; import { processOrder } from "./workflows/process-order"; ``` -------------------------------- ### Next.js Configuration Example Source: https://workflow-sdk.dev/docs/errors/start-invalid-workflow-function Example of a next.config.ts file. This configuration is standard for Next.js projects and does not directly relate to workflow function validation but is often part of the project setup. ```typescript import type { NextConfig } from "next" const nextConfig: NextConfig = {}; export default nextConfig; ``` -------------------------------- ### Fix: Pass imported workflow directly to start() Source: https://workflow-sdk.dev/docs/errors/start-invalid-workflow-function This example shows the correct way to call `start()`, by passing the imported workflow function directly and providing arguments separately. ```typescript import { start } from "workflow/api"; import { sendReminder } from "./workflows/send-reminder"; export async function POST() { await start(sendReminder, ["hello@example.com"]); // [!code highlight] return new Response("ok"); } ``` -------------------------------- ### Example Workflow Execution in Next.js Source: https://workflow-sdk.dev/docs/getting-started/next Demonstrates a typical workflow sequence including user creation, sending welcome and onboarding emails, and a timed pause. This example assumes the existence of `createUser`, `sendWelcomeEmail`, and `sendOnboardingEmail` functions. ```javascript import { NextResponse, NextRequest } from 'next/server'; // Assume these functions are defined elsewhere and imported // async function createUser(email: string): Promise { ... } // async function sendWelcomeEmail(user: User): Promise { ... } // async function sendOnboardingEmail(user: User): Promise { ... } // async function sleep(ms: number): Promise { ... } export async function POST(request: Request) { const { email } = await request.json(); const user = await createUser(email); await sendWelcomeEmail(user); // Pause for 5s - doesn't consume any resources await sleep(5000); await sendOnboardingEmail(user); console.log(`Workflow completed for ${email}`); return NextResponse.json({ message: 'Workflow initiated' }); } ``` -------------------------------- ### Get Workflow Run and Stream Data Source: https://workflow-sdk.dev/llms.txt Retrieves a workflow run by ID and gets a readable stream of data, optionally starting from a specific index. Used for streaming chat responses. ```typescript import { createUIMessageStreamResponse } from "ai"; import { getRun } from "workflow/api"; export async function GET( request: Request, { params }: { params: Promise<{ id: string }> } ) { const { id } = await params; const { searchParams } = new URL(request.url); const startIndex = searchParams.get("startIndex"); const run = getRun(id); // [!code highlight] const stream = run.getReadable({ // [!code highlight] startIndex: startIndex ? parseInt(startIndex, 10) : undefined, // [!code highlight] }); // [!code highlight] return createUIMessageStreamResponse({ stream }); } ``` -------------------------------- ### Webhook Handler Example Source: https://workflow-sdk.dev/docs/api-reference/workflow-api/resume-hook Example of setting up a webhook handler for the resumeHook functionality. ```APIDOC ## Webhook Handler ### Description This example demonstrates how to create a webhook handler that can receive and process resume hook requests. ### Code ```javascript // Example using Express.js const express = require('express'); const app = express(); app.use(express.json()); app.post('/api/workflows/resume-hook', async (req, res) => { const { workflowId, payload } = req.body; if (!workflowId) { return res.status(400).json({ error: 'workflowId is required' }); } try { // Replace with your actual workflow resuming logic console.log(`Received resume hook for workflow: ${workflowId}`); const result = { status: 'resumed', workflowRunId: `wr_${Date.now()}`, }; res.status(200).json(result); } catch (error) { console.error('Error processing resume hook:', error); res.status(500).json({ error: 'Internal server error' }); } }); // const PORT = process.env.PORT || 3000; // app.listen(PORT, () => { // console.log(`Server listening on port ${PORT}`); // }); ``` ``` -------------------------------- ### start() Source: https://workflow-sdk.dev/docs/api-reference/workflow-api Start/enqueue a new workflow run. ```APIDOC ## start() ### Description Start/enqueue a new workflow run. ### Method [Method not specified in source] ### Endpoint [Endpoint not specified in source] ### Parameters [No parameters specified in source] ### Request Example [No request example specified in source] ### Response #### Success Response (200) [No success response details specified in source] #### Response Example [No response example specified in source] ``` -------------------------------- ### Export Async Function Setup Source: https://workflow-sdk.dev/docs/testing/server-based This snippet shows the basic structure for an asynchronous setup function in JavaScript. It initializes variables for stdout and stderr. ```javascript export async function setup() { const stdout: string[] = []; const stderr: string[] = []; emitSetupLog("server_starting"); ``` -------------------------------- ### Example Usage of getStepMetadata Source: https://workflow-sdk.dev/docs/api-reference/workflow/get-step-metadata Demonstrates how to call the getStepMetadata function. Ensure you have the necessary client setup. ```javascript self.__next_f.push([1,"5e:I[40250,[\"/_next/static/chunks/0qs5sowui9xr2.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/15hit21bg0wdy.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0-ir4kwojlcdw.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0rxm00td_u9mq.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0oiu4twmay7bv.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0z7l__jcmmlq.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0-n8_x_wmwf2p.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0q0f9q81hw9rn.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0d7weeegfku5q.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/03el6cdbmy7ia.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0dh0q._ne2rhg.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0r.-tc7m55jhy.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0yf5qep~r9u3a.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0p.-n-r893ft2.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0hdi6~5e1fjca.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0z5h~r__glxrp.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/066m2iazrur4i.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0kt48zxch3rbs.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0v~bxxhdasdbo.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\"],"OpenInT3"\]\n"]) ``` ```javascript self.__next_f.push([1,"5f:I[40250,[\"/_next/static/chunks/0qs5sowui9xr2.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/15hit21bg0wdy.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0-ir4kwojlcdw.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0rxm00td_u9mq.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0oiu4twmay7bv.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0z7l__jcmmlq.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0-n8_x_wmwf2p.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0q0f9q81hw9rn.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0d7weeegfku5q.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/03el6cdbmy7ia.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0dh0q._ne2rhg.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0r.-tc7m55jhy.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0yf5qep~r9u3a.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0p.-n-r893ft2.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0hdi6~5e1fjca.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0z5h~r__glxrp.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/066m2iazrur4i.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0kt48zxch3rbs.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\",\"/_next/static/chunks/0v~bxxhdasdbo.js?dpl=dpl_FxmrsSYTmrGYRR8XfavKTNikmtMa\"],"OpenInScira"\]\n"]) ``` ```javascript self.__next_f.push([1,"3c:[\"$\",\"span\",null,{\"style\":{\"--shiki-light\":\"#6F42C1\",\"--shiki-dark\":\"#B392F0\"},\"children\":\" getStepMetadata\"}\]\n3d:[\"$\",\"span\",null,{\"style\":{\"--shiki-light\":\"#24292E\",\"--shiki-dark\":\"#E1E4E8\"},\"children\":\"();\"}\]\n3e:[\"$\",\"span\",null,{\"className\":\"line\"}\]\n3f:[\"$\",\"span\",null,{\"className\":\"line\",\"children\":[[\"$\",\"span\",null,{\"style\":{\"--shiki-light\":\"#D73A49\",\"--shiki-dark\":\"#F97583\"},\"children\":\" await\"}],[\"$\",\"span\",null,{\"style\":{\"--shiki-light\":\"#24292E\",\"--shiki-dark\":\"#E1E4E8\"},\"children\":\" stripe.charges.\"}],[\"$\",\"span\",null,{\"style\":{\"--shiki-light\":\"#6F42C1\",\"--shiki-dark\":\"#B392F0\"},\"children\":\"create\"}],[\"$\",\"span\",null,{\"style\":{\"--shiki-light\":\"#24292E\",\"--shiki-dark\":\"#E1E4E8\"},\"children\":\"(\"}\]]}\]\n40:[\"$\",\"span\",null,{\"className\":\"line\",\"children\":[\"$\",\"span\",null,{\"style\":{\"--shiki-light\":\"#24292E\",\"--shiki-dark\":\"#E1E4E8\"},\"children\":\" {\"}\]]}\]\n41:[\"$\",\"span\",null,{\"className\":\"line\",\"children\":[\"$\",\"span\",null,{\"style\":{\"--shiki-light\":\"#24292E\",\"--shiki-dark\":\"#E1E4E8\"},\"children\":\" "}]}\]\n"]) ``` ```javascript self.__next_f.push([1,"3c:[\"$\",\"span\",null,{\"style\":{\"--shiki-light\":\"#6F42C1\",\"--shiki-dark\":\"#B392F0\"},\"children\":\" getStepMetadata\"}\]\n3d:[\"$\",\"span\",null,{\"style\":{\"--shiki-light\":\"#24292E\",\"--shiki-dark\":\"#E1E4E8\"},\"children\":\"();\"}\]\n3e:[\"$\",\"span\",null,{\"className\":\"line\"}\]\n3f:[\"$\",\"span\",null,{\"className\":\"line\",\"children\":[[\"$\",\"span\",null,{\"style\":{\"--shiki-light\":\"#D73A49\",\"--shiki-dark\":\"#F97583\"},\"children\":\" await\"}],[\"$\",\"span\",null,{\"style\":{\"--shiki-light\":\"#24292E\",\"--shiki-dark\":\"#E1E4E8\"},\"children\":\" stripe.charges.\"}],[\"$\",\"span\",null,{\"style\":{\"--shiki-light\":\"#6F42C1\",\"--shiki-dark\":\"#B392F0\"},\"children\":\"create\"}],[\"$\",\"span\",null,{\"style\":{\"--shiki-light\":\"#24292E\",\"--shiki-dark\":\"#E1E4E8\"},\"children\":\"(\"}\]]}\]\n40:[\"$\",\"span\",null,{\"className\":\"line\",\"children\":[\"$\",\"span\",null,{\"style\":{\"--shiki-light\":\"#24292E\",\"--shiki-dark\":\"#E1E4E8\"},\"children\":\" {\"}\]]}\]\n41:[\"$\",\"span\",null,{\"className\":\"line\",\"children\":[\"$\",\"span\",null,{\"style\":{\"--shiki-light\":\"#24292E\",\"--shiki-dark\":\"#E1E4E8\"},\"children\":\" "}]}\]\n"]) ``` -------------------------------- ### Create a New Library Source: https://workflow-sdk.dev/cookbook/advanced/publishing-libraries Use this command to initialize a new library package. Ensure you have the necessary permissions and that the library name is unique. ```bash npx @temporalio/create-starter@latest@latest --template library my-library ``` -------------------------------- ### Self-Upgrading Workflow Example Source: https://workflow-sdk.dev/docs/foundations/versioning This pattern models long-running workflows as a sequence of runs, where each run performs a bounded task and then starts the next run on the latest deployment. It uses explicit recursion through `start()`. ```typescript import { sleep } from "workflow"; import { start } from "workflow/api"; type DigestState = { userId: string; lastSentAt?: string; }; export async function dailyDigest(state: DigestState) { "use workflow"; const sentAt = await sendDigest(state.userId); await sleep("1d"); const nextRunId = await continueDigest({ ...state, lastSentAt: sentAt, }); return { continuedAs: nextRunId }; } async function continueDigest(state: DigestState) { "use step"; const run = await start(dailyDigest, [state], { deploymentId: "latest", }); return run.runId; } async function sendDigest(userId: string) { "use step"; // ... return new Date().toISOString(); } ``` -------------------------------- ### Starting a Workflow Source: https://workflow-sdk.dev/docs/api-reference/workflow-api/start This snippet demonstrates how to start a workflow with specific arguments and deployment configuration. ```APIDOC ## Starting a Workflow ### Description This operation starts a workflow execution. You can provide arguments for the workflow and specify the deployment ID. ### Method `start` (SDK function) ### Parameters #### Workflow Definition - `myWorkflow` (object) - The workflow definition to execute. #### Arguments - `args` (array) - An array of arguments to pass to the workflow. Example: `["arg1", "arg2"]`. #### Options - `deploymentId` (string) - Specifies the deployment to use. Currently, this is a Vercel-specific feature. Example: `"latest"`. ### Request Example ```javascript import { myWorkflow } from "./workflows/my-workflow"; const run = async () => { await start(myWorkflow, ["arg1", "arg2"], { deploymentId: "latest" }); }; ``` ### Response This function does not return a value directly but initiates an asynchronous workflow execution. ``` -------------------------------- ### Define Nitro Plugin to Start Postgres World Source: https://workflow-sdk.dev/worlds/postgres Register a Nitro plugin to ensure the Postgres World starts when the server initializes. This is useful for integrating the world with your server-side rendering or API setup. ```typescript import { defineNitroPlugin } from "nitro/~internal/runtime/plugin"; export default defineNitroPlugin(async () => { const { getWorld } = await import("workflow/runtime"); const world = await getWorld(); await world.start?.(); }); ``` -------------------------------- ### Starting a Workflow with start() Source: https://workflow-sdk.dev/docs/foundations/starting-workflows Use the `start()` function to enqueue and begin a workflow execution. It returns immediately without waiting for the workflow to complete. The first argument is the workflow function, and the second is an array of arguments for that function. ```javascript const run = await start(handleUserSignup, [email]); return { message: "Workflow started" }; ``` -------------------------------- ### Create SvelteKit Project Source: https://workflow-sdk.dev/llms.txt Use this command to scaffold a new SvelteKit project with a minimal setup. Navigate into the created directory to proceed. ```bash npx sv create my-workflow-app --template=minimal --types=ts --no-add-ons cd my-workflow-app ``` -------------------------------- ### Get Readable Stream Source: https://workflow-sdk.dev/docs/ai/resumable-streams Use this method to check if a stream is readable. It takes a start index as an argument. ```typescript const readable = run.getReadable({ startIndex }); ``` -------------------------------- ### Getting a Writable Stream Source: https://workflow-sdk.dev/docs/api-reference/workflow/get-writable This example demonstrates how to import and use the `getWritable` function to obtain a writable stream in your workflow. ```APIDOC ## Getting a Writable Stream ### Description This example demonstrates how to import and use the `getWritable` function to obtain a writable stream in your workflow. ### Method ```javascript getWritable() ``` ### Parameters None ### Request Example ```javascript import { sleep, getWritable } from "workflow" export async function outputStreamWorkflow() { "use workflow" const writable = getWritable(); await } ``` ### Response #### Success Response (Writable Stream) - **writable** (WritableStream) - A stream object that allows writing data. #### Response Example ```json { "writable": "" } ``` ``` -------------------------------- ### Basic API Route Example Source: https://workflow-sdk.dev/docs/api-reference/workflow-api/resume-hook A simple example demonstrating how to call the resumeHook API. ```APIDOC ## Basic API Route ### Description This example shows a basic implementation of calling the resumeHook API. ### Code ```javascript async function resumeWorkflow(workflowId, payload) { const response = await fetch('/api/workflows/resume-hook', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ workflowId, payload }), }); return await response.json(); } // Example usage: // resumeWorkflow('wf_123abc', { data: 'initial data' }).then(console.log); ``` ``` -------------------------------- ### Create Webhook Example Source: https://workflow-sdk.dev/docs/api-reference/workflow/create-webhook Demonstrates how to create a webhook that responds manually. This is useful for custom webhook behavior. ```javascript const webhook = await createWebhook({ respondWith: "manual" }); ``` -------------------------------- ### Example Event Payload Source: https://workflow-sdk.dev/docs/how-it-works/event-sourcing This JSON payload represents a step started event, including correlation and request IDs for tracking. ```json { "eventType": "step_started", "correlationId": "step_01JQEXAMPLE1234567890", "requestId": "iad1::abc123-1712345678901-xyz987" } ``` -------------------------------- ### Get World Information Source: https://workflow-sdk.dev/docs/api-reference/workflow-runtime/world/storage Retrieves information about the current world. This is typically used at the start of a workflow to access world-specific data. ```javascript import { getWorld } from "workflow/runtime" const world = await getWorld(); ``` -------------------------------- ### Create and Send Webhook Source: https://workflow-sdk.dev/docs/how-it-works/framework-integrations Example of creating a webhook and sending an onboarding email to a user. ```javascript const webhook = createWebhook(); await sendOnboardingEmail(user, webhook.url); console.log("Webhook Resolved"); return { userId: user.id, status: "onboarded" }; ``` -------------------------------- ### Get a specific workflow run Source: https://workflow-sdk.dev/docs/api-reference/workflow-api/get-run This example demonstrates how to import and use the `getRun` function to retrieve a workflow run by its ID. ```APIDOC ## Get a specific workflow run ### Description Retrieves the details of a specific workflow run using its unique identifier. ### Method `getRun(runId: string)` ### Parameters #### Path Parameters - **runId** (string) - Required - The unique identifier of the workflow run to retrieve. ### Request Example ```javascript import { getRun } from "workflow/api"; const run = getRun("my-run-id"); // Example of accessing run data (assuming 'run' is a promise that resolves to the run object) // const { stoppedCount } = await run; // console.log(stoppedCount); ``` ### Response #### Success Response (200) - **run object** - Contains details about the workflow run, including its status, start time, and any associated data. #### Response Example ```json { "runId": "my-run-id", "status": "completed", "startTime": "2023-10-27T10:00:00Z", "endTime": "2023-10-27T10:05:00Z", "correlationIds": [] } ``` ``` -------------------------------- ### Basic Text Streaming Source: https://workflow-sdk.dev/docs/api-reference/workflow/get-writable This example demonstrates how to get a writable stream and use it to output text data from a workflow and its steps. ```APIDOC ## Basic Text Streaming This example demonstrates how to get a writable stream and use it to output text data from a workflow and its steps. ### Method ```typescript import { sleep, getWritable } from "workflow"; export async function outputStreamWorkflow() { "use workflow"; const writable = getWritable(); await sleep("1s"); await stepWithOutputStream(writable); await sleep("1s"); await stepCloseOutputStream(writable); return "done"; } async function stepWithOutputStream(writable: WritableStream) { "use step"; const writer = writable.getWriter(); // Write binary data using TextEncoder await writer.write(new TextEncoder().encode("Hello, world!")); writer.releaseLock(); } async function stepCloseOutputStream(writable: WritableStream) { "use step"; // Close the stream to signal completion await writable.close(); } ``` ``` -------------------------------- ### Basic Workflow SDK Tool Usage Example Source: https://workflow-sdk.dev/cookbook/integrations/ai-sdk Illustrates a basic tool call within a workflow, showing the 'runTurn' concept and potential retry behavior. ```javascript runTurn ```