feat: automatic doc generator for TS SDK (#3047)

* add: typedoc config

* refactor: typeconfig, name feature client modules

* add: custom hatchet md plugin, feature client docs

* docs: filters client

* docs: add worker, workflows defintions

* fix: client and context docs, update typedoc

* fix: lint, add runnables doc

* add: additional md formatter methods, module docs

* add: geneated mdx, core generate and format logic

* refactor: new function changes

* fix: lint, lockfile

* fix: lint, strip generics in classes for docs

* refactor: use single line comments for deprecated

* fix: markdown escaping by typedoc

* docs: regenerate docs with new changes

* docs: refactor methods on alphabetical order

* refactor: non method headers to normal text

* docs: regenerate docs with 3 type depth
This commit is contained in:
Jishnu
2026-03-03 22:37:41 +05:30
committed by GitHub
parent 7cc0dec126
commit 508edde607
39 changed files with 2985 additions and 62 deletions

View File

@@ -48,6 +48,11 @@ export default {
href: "/sdks/python/client",
type: "page",
},
typescript: {
title: "TypeScript",
href: "/sdks/typescript/client",
type: "page",
},
go: {
title: "Go",
href: "https://pkg.go.dev/github.com/hatchet-dev/hatchet/sdks/go",

View File

@@ -6,4 +6,11 @@ export default {
toc: true,
},
},
typescript: {
title: "TypeScript SDK",
type: "page",
theme: {
toc: true,
},
},
};

View File

@@ -0,0 +1,505 @@
# Context
The Hatchet Context class provides helper methods and useful data to tasks at runtime. It is passed as the second argument to all tasks and durable tasks.
There are two types of context classes you'll encounter:
- Context - The standard context for regular tasks with methods for logging, task output retrieval, cancellation, and more.
- DurableContext - An extended context for durable tasks that includes additional methods for durable execution.
<a id="context"></a>
### Context
Extended by
- [`DurableContext`](#durablecontext)
#### Methods
<a id="additionalmetadata"></a>
##### `additionalMetadata()`
Retrieves additional metadata associated with the current workflow run.
Returns
`Record`\<`string`, `string`\>
A record of metadata key-value pairs.
<a id="bulkrunchildren"></a>
##### `bulkRunChildren()`
Runs multiple children workflows in parallel and waits for all results.
Parameters
| Parameter | Type | Description |
| ---------- | ---------- | -------------------------------------------------------------------------------------------- |
| `children` | `object`[] | An array of objects containing the workflow name, input data, and options for each workflow. |
Returns
`Promise`\<`P`[]\>
A list of results from the children workflows.
<a id="bulkrunnowaitchildren"></a>
##### `bulkRunNoWaitChildren()`
Runs multiple children workflows in parallel without waiting for their results.
Parameters
| Parameter | Type | Description |
| ---------- | ---------- | -------------------------------------------------------------------------------------------- |
| `children` | `object`[] | An array of objects containing the workflow name, input data, and options for each workflow. |
Returns
`Promise`\<`WorkflowRunRef`\<`P`\>[]\>
A list of workflow run references to the enqueued runs.
<a id="childindex"></a>
##### `childIndex()`
Gets the index of this workflow if it was spawned as part of a bulk operation.
Returns
`number` \| `undefined`
The child index number, or undefined if not set.
<a id="childkey"></a>
##### `childKey()`
Gets the key associated with this workflow if it was spawned as a child workflow.
Returns
`string` \| `undefined`
The child key, or undefined if not set.
<a id="errors"></a>
##### `errors()`
Returns errors from any task runs in the workflow.
Returns
`Record`\<`string`, `string`\>
A record mapping task names to error messages.
Throws
A warning if no errors are found (this method should be used in on-failure tasks).
<a id="filterpayload"></a>
##### `filterPayload()`
Gets the payload from the filter that matched when triggering the event.
Returns
`Record`\<`string`, `any`\>
The payload.
<a id="parentoutput"></a>
##### `parentOutput()`
Retrieves the output of a parent task.
Parameters
| Parameter | Type | Description |
| ------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------- |
| `parentTask` | \| `string` \| `CreateWorkflowTaskOpts`\<`any`, `L`\> \| `CreateWorkflowDurableTaskOpts`\<`any`, `L`\> | The a CreateTaskOpts or string of the parent task name. |
Returns
`Promise`\<`L`\>
The output of the specified parent task.
Throws
An error if the task output is not found.
<a id="parentworkflowrunid"></a>
##### `parentWorkflowRunId()`
Gets the ID of the parent workflow run if this workflow was spawned as a child.
Returns
`string` \| `undefined`
The parent workflow run ID, or undefined if not a child workflow.
<a id="putstream"></a>
##### `putStream()`
Streams data from the current task run.
Parameters
| Parameter | Type | Description |
| --------- | --------------------------------------------- | -------------------------------------- |
| `data` | `string` \| `Uint8Array`\<`ArrayBufferLike`\> | The data to stream (string or binary). |
Returns
`Promise`\<`void`\>
A promise that resolves when the data has been streamed.
<a id="refreshtimeout"></a>
##### `refreshTimeout()`
Refreshes the timeout for the current task.
Parameters
| Parameter | Type | Description |
| ------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `incrementBy` | `Duration` | The interval by which to increment the timeout. The interval should be specified in the format of '10s' for 10 seconds, '1m' for 1 minute, or '1d' for 1 day. |
Returns
`Promise`\<`void`\>
<a id="releaseslot"></a>
##### `releaseSlot()`
Releases a worker slot for a task run such that the worker can pick up another task.
Note: this is an advanced feature that may lead to unexpected behavior if used incorrectly.
Returns
`Promise`\<`void`\>
A promise that resolves when the slot has been released.
<a id="rethrowifcancelled"></a>
##### `rethrowIfCancelled()`
Helper for broad `catch` blocks so cancellation isn't accidentally swallowed.
Example:
```ts
try { ... } catch (e) { ctx.rethrowIfCancelled(e); ... }
```
Parameters
| Parameter | Type |
| --------- | --------- |
| `err` | `unknown` |
Returns
`void`
<a id="retrycount"></a>
##### `retryCount()`
Gets the number of times the current task has been retried.
Returns
`number`
The retry count.
<a id="runchild"></a>
##### `runChild()`
Runs a new workflow and waits for its result.
Parameters
| Parameter | Type | Description |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------- |
| `workflow` | \| `string` \| `BaseWorkflowDeclaration`\<`Q`, `P`\> \| [`TaskWorkflowDeclaration`](Runnables.mdx#taskworkflowdeclaration)\<`Q`, `P`, \{ \}, \{ \}, \{ \}, \{ \}\> | The workflow to run (name, Workflow instance, or WorkflowV1 instance). |
| `input` | `Q` | The input data for the workflow. |
| `options?` | `ChildRunOpts` | An options object containing key, sticky, priority, and additionalMetadata. |
Returns
`Promise`\<`P`\>
The result of the workflow.
<a id="runnowaitchild"></a>
##### `runNoWaitChild()`
Enqueues a new workflow without waiting for its result.
Parameters
| Parameter | Type | Description |
| ---------- | ------------------------------------------------- | --------------------------------------------------------------------------- |
| `workflow` | `string` \| `BaseWorkflowDeclaration`\<`Q`, `P`\> | The workflow to enqueue (name, Workflow instance, or WorkflowV1 instance). |
| `input` | `Q` | The input data for the workflow. |
| `options?` | `ChildRunOpts` | An options object containing key, sticky, priority, and additionalMetadata. |
Returns
`Promise`\<`WorkflowRunRef`\<`P`\>\>
A reference to the spawned workflow run.
<a id="taskname"></a>
##### `taskName()`
Gets the name of the current running task.
Returns
`string`
The name of the task.
<a id="taskrunexternalid"></a>
##### `taskRunExternalId()`
Gets the ID of the current task run.
Returns
`string`
The task run ID.
<a id="triggeredbyevent"></a>
##### `triggeredByEvent()`
Determines if the workflow was triggered by an event.
Returns
`boolean`
True if the workflow was triggered by an event, otherwise false.
<a id="triggers"></a>
##### `triggers()`
Gets the dag conditional triggers for the current workflow run.
Returns
`TriggerData`
The triggers for the current workflow.
<a id="userdata"></a>
##### `userData()`
Gets the user data associated with the workflow.
Returns
`K`
The user data.
<a id="workflowid"></a>
##### `workflowId()`
Gets the workflow ID of the currently running workflow.
Returns
`string` \| `undefined`
The workflow id.
<a id="workflowname"></a>
##### `workflowName()`
Gets the name of the current workflow.
Returns
`string`
The name of the workflow.
<a id="workflowrunid"></a>
##### `workflowRunId()`
Gets the ID of the current workflow run.
Returns
`string`
The workflow run ID.
<a id="workflowversionid"></a>
##### `workflowVersionId()`
Gets the workflow version ID of the currently running workflow.
Returns
`string` \| `undefined`
The workflow version ID.
---
<a id="contextworker"></a>
### ContextWorker
ContextWorker is a wrapper around the V1Worker class that provides a more user-friendly interface for the worker from the context of a run.
#### Methods
<a id="hasworkflow"></a>
##### `hasWorkflow()`
Checks if the worker has a registered workflow.
Parameters
| Parameter | Type | Description |
| -------------- | -------- | ---------------------------------- |
| `workflowName` | `string` | The name of the workflow to check. |
Returns
`boolean`
True if the workflow is registered, otherwise false.
<a id="id"></a>
##### `id()`
Gets the ID of the worker.
Returns
`string` \| `undefined`
The ID of the worker.
<a id="labels"></a>
##### `labels()`
Gets the current state of the worker labels.
Returns
`WorkerLabels`
The labels of the worker.
<a id="upsertlabels"></a>
##### `upsertLabels()`
Upserts the a set of labels on the worker.
Parameters
| Parameter | Type | Description |
| --------- | -------------- | --------------------- |
| `labels` | `WorkerLabels` | The labels to upsert. |
Returns
`Promise`\<`WorkerLabels`\>
A promise that resolves when the labels have been upserted.
---
<a id="durablecontext"></a>
### DurableContext
DurableContext provides helper methods and useful data to durable tasks at runtime.
It extends the Context class and includes additional methods for durable execution like sleepFor and waitFor.
Extends
- [`Context`](#context)\<`T`, `K`\>
#### Methods
<a id="sleepfor"></a>
##### `sleepFor()`
Pauses execution for the specified duration.
Duration is "global" meaning it will wait in real time regardless of transient failures like worker restarts.
Parameters
| Parameter | Type | Description |
| ------------------ | ---------- | -------------------------- |
| `duration` | `Duration` | The duration to sleep for. |
| `readableDataKey?` | `string` | - |
Returns
`Promise`\<`Record`\<`string`, `any`\>\>
A promise that resolves when the sleep duration has elapsed.
<a id="waitfor"></a>
##### `waitFor()`
Pauses execution until the specified conditions are met.
Conditions are "global" meaning they will wait in real time regardless of transient failures like worker restarts.
Parameters
| Parameter | Type | Description |
| ------------ | ------------------------------ | --------------------------- |
| `conditions` | `Conditions` \| `Conditions`[] | The conditions to wait for. |
Returns
`Promise`\<`Record`\<`string`, `any`\>\>
A promise that resolves with the event that satisfied the conditions.

View File

@@ -0,0 +1,394 @@
# Runnables
`Runnables` in the Hatchet TypeScript SDK are things that can be run, namely tasks and workflows. The two main types of runnables you'll encounter are:
- `WorkflowDeclaration`, returned by `hatchet.workflow(...)`, which lets you define tasks and call `run()`, `schedule()`, `cron()`, etc.
- `TaskWorkflowDeclaration`, returned by `hatchet.task(...)`, which is a single standalone task that exposes the same execution helpers as a workflow.
<a id="taskworkflowdeclaration"></a>
### TaskWorkflowDeclaration
A standalone task declaration that can be run like a workflow.
`TaskWorkflowDeclaration` is returned by `hatchet.task(...)` and wraps a single
task definition while exposing the same execution helpers as workflows, such as
`run()`, `runNoWait()`, `schedule()`, and `cron()` (inherited from
`BaseWorkflowDeclaration`).
Example:
```typescript
const greet = hatchet.task<{ name: string }, { message: string }>({
name: "greet",
fn: async (input) => ({ message: `Hello, ${input.name}!` }),
});
await greet.run({ name: "World" });
const ref = await greet.runNoWait({ name: "World" });
```
#### Methods
<a id="cron"></a>
##### `cron()`
Creates a cron schedule for the task.
Parameters
| Parameter | Type | Description |
| ------------ | ------------------- | ----------------------------------------------------------- |
| `name` | `string` | The name of the cron schedule. |
| `expression` | `string` | The cron expression defining the schedule. |
| `input` | `I` & `GlobalInput` | The input data for the task, including global input fields. |
| `options?` | `RunOpts` | Optional configuration for this task run. |
Returns
`Promise`\<`CronWorkflows`\>
A promise that resolves with the cron workflow details.
Overrides
```ts
BaseWorkflowDeclaration.cron;
```
<a id="delay"></a>
##### `delay()`
Schedules the task to run after a specified delay.
Parameters
| Parameter | Type | Description |
| ---------- | ------------------- | ----------------------------------------------------------- |
| `duration` | `number` | The delay in seconds before the task should run. |
| `input` | `I` & `GlobalInput` | The input data for the task, including global input fields. |
| `options?` | `RunOpts` | Optional configuration for this task run. |
Returns
`Promise`\<`ScheduledWorkflows`\>
A promise that resolves with the scheduled workflow details.
Overrides
```ts
BaseWorkflowDeclaration.delay;
```
<a id="run"></a>
##### `run()`
Triggers a task run and waits for the result.
Parameters
| Parameter | Type | Description |
| ---------- | ------------------- | ----------------------------------------------------------- |
| `input` | `I` & `GlobalInput` | The input data for the task, including global input fields. |
| `options?` | `RunOpts` | Optional configuration for this task run. |
Returns
`Promise`\<`O` & `Resolved`\<`GlobalOutput`, `MiddlewareAfter`\>\>
A promise that resolves with the task output merged with post-middleware fields.
Overrides
```ts
BaseWorkflowDeclaration.run;
```
<a id="runandwait"></a>
##### `runAndWait()`
Triggers a task run and waits for the result.
Parameters
| Parameter | Type | Description |
| ---------- | ------------------- | ----------------------------------------------------------- |
| `input` | `I` & `GlobalInput` | The input data for the task, including global input fields. |
| `options?` | `RunOpts` | Optional configuration for this task run. |
Returns
`Promise`\<`O` & `Resolved`\<`GlobalOutput`, `MiddlewareAfter`\>\>
A promise that resolves with the task output merged with post-middleware fields.
Overrides
```ts
BaseWorkflowDeclaration.runAndWait;
```
<a id="runnowait"></a>
##### `runNoWait()`
Triggers a task run without waiting for completion.
Parameters
| Parameter | Type | Description |
| ---------- | ------------------- | ----------------------------------------------------------- |
| `input` | `I` & `GlobalInput` | The input data for the task, including global input fields. |
| `options?` | `RunOpts` | Optional configuration for this task run. |
Returns
`Promise`\<`WorkflowRunRef`\<`O` & `Resolved`\<..., ...\>\>\>
A WorkflowRunRef containing the run ID and methods to get results.
Overrides
```ts
BaseWorkflowDeclaration.runNoWait;
```
Triggers a task run without waiting for completion.
Parameters
| Parameter | Type | Description |
| ---------- | --------------------- | ----------------------------------------------------------- |
| `input` | `I` & `GlobalInput`[] | The input data for the task, including global input fields. |
| `options?` | `RunOpts` | Optional configuration for this task run. |
Returns
`Promise`\<`WorkflowRunRef`\<... & ...\>[]\>
A WorkflowRunRef containing the run ID and methods to get results.
Overrides
```ts
BaseWorkflowDeclaration.runNoWait;
```
<a id="schedule"></a>
##### `schedule()`
Schedules the task to run at a specific date and time.
Parameters
| Parameter | Type | Description |
| ----------- | ------------------- | ----------------------------------------------------------- |
| `enqueueAt` | `Date` | The date when the task should be triggered. |
| `input` | `I` & `GlobalInput` | The input data for the task, including global input fields. |
| `options?` | `RunOpts` | Optional configuration for this task run. |
Returns
`Promise`\<`ScheduledWorkflows`\>
A promise that resolves with the scheduled workflow details.
Overrides
```ts
BaseWorkflowDeclaration.schedule;
```
---
<a id="workflowdeclaration"></a>
### WorkflowDeclaration
A Hatchet workflow, which lets you define tasks and perform actions on the workflow.
Workflows in Hatchet represent coordinated units of work that can be triggered,
scheduled, or run on a cron schedule. Each workflow can contain multiple tasks
that can be arranged in dependencies (DAGs), with customized retry behavior,
timeouts, concurrency controls, and more.
Example:
```typescript
import { hatchet } from "./hatchet-client";
type MyInput = { name: string };
const workflow = hatchet.workflow<MyInput>({
name: "my-workflow",
});
workflow.task({
name: "greet",
fn: async (input) => {
return { message: `Hello, ${input.name}!` };
},
});
// Run the workflow
await workflow.run({ name: "World" });
```
Workflows support various execution patterns, including:
- One-time execution with `run()` and `runNoWait()`
- Scheduled execution with `schedule()`
- Cron-based recurring execution with `cron()`
- Bulk execution by passing an array input to `run()` and `runNoWait()`
Tasks within workflows can be defined with `workflow.task()` or
`workflow.durableTask()` and arranged into complex dependency patterns.
#### Methods
<a id="durabletask"></a>
##### `durableTask()`
Adds a durable task to the workflow.
The return type will be either the property on O that corresponds to the task name,
or if there is no matching property, the inferred return type of the function.
Parameters
| Parameter | Type | Description |
| --------- | ------------------------------------------------------------------ | ------------------------------- |
| `options` | `Omit`\<`CreateWorkflowTaskOpts`\<`I`, `TO`\>, `"fn"`\> & `object` | The task configuration options. |
Returns
`CreateWorkflowDurableTaskOpts`\<`I`, `TO`\>
The task options that were added.
<a id="onfailure"></a>
##### `onFailure()`
Adds an onFailure task to the workflow.
This will only run if any task in the workflow fails.
Parameters
| Parameter | Type | Description |
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |
| `options` | \| `Omit`\<`CreateOnFailureTaskOpts`\<..., ...\>, `"fn"`\> & `object` \| [`TaskWorkflowDeclaration`](#taskworkflowdeclaration)\<`any`, `any`, \{ \}, \{ \}, \{ \}, \{ \}\> | The task configuration options. |
Returns
`CreateWorkflowTaskOpts`\<`I`, `TaskOutputType`\<`O`, `Name`, `L`\>\>
The task options that were added.
<a id="onsuccess"></a>
##### `onSuccess()`
Adds an onSuccess task to the workflow.
This will only run if all tasks in the workflow complete successfully.
Parameters
| Parameter | Type | Description |
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |
| `options` | \| [`TaskWorkflowDeclaration`](#taskworkflowdeclaration)\<`any`, `any`, \{ \}, \{ \}, \{ \}, \{ \}\> \| `Omit`\<`CreateOnSuccessTaskOpts`\<..., ...\>, `"fn"`\> & `object` | The task configuration options. |
Returns
`CreateWorkflowTaskOpts`\<`I`, `TaskOutputType`\<`O`, `Name`, `L`\>\>
The task options that were added.
<a id="task"></a>
##### `task()`
Adds a task to the workflow.
The return type will be either the property on O that corresponds to the task name,
or if there is no matching property, the inferred return type of the function.
Parameters
| Parameter | Type | Description |
| --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |
| `options` | \| `Omit`\<`CreateWorkflowTaskOpts`\<..., ...\>, `"fn"`\> & `object` \| [`TaskWorkflowDeclaration`](#taskworkflowdeclaration)\<`I`, `TO`, \{ \}, \{ \}, \{ \}, \{ \}\> | The task configuration options. |
Returns
`CreateWorkflowTaskOpts`\<`I`, `TO`\>
The task options that were added.
## Functions
<a id="createdurabletaskworkflow"></a>
### `CreateDurableTaskWorkflow()`
Creates a new durable task workflow declaration with types inferred from the function parameter.
Parameters
| Parameter | Type | Description |
| --------- | ------------------------------------------------------------------------ | --------------------------------------- |
| `options` | `object` & `Omit`\<`CreateWorkflowDurableTaskOpts`\<`I`, `O`\>, `"fn"`\> | The durable task configuration options. |
| `client?` | `IHatchetClient` | Optional Hatchet client instance. |
Returns
[`TaskWorkflowDeclaration`](#taskworkflowdeclaration)\<`I`, `O`\>
A new TaskWorkflowDeclaration with inferred types.
---
<a id="createtaskworkflow"></a>
### `CreateTaskWorkflow()`
Creates a new task workflow declaration with types inferred from the function parameter.
Parameters
| Parameter | Type | Description |
| --------- | ----------------------------------------------------------------- | --------------------------------- |
| `options` | `object` & `Omit`\<`CreateTaskWorkflowOpts`\<`I`, `O`\>, `"fn"`\> | The task configuration options. |
| `client?` | `IHatchetClient` | Optional Hatchet client instance. |
Returns
[`TaskWorkflowDeclaration`](#taskworkflowdeclaration)\<`I`, `O`\>
A new TaskWorkflowDeclaration with inferred types.
---
<a id="createworkflow"></a>
### `CreateWorkflow()`
Creates a new workflow instance.
Parameters
| Parameter | Type | Description |
| --------- | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `options` | `CreateWorkflowOpts` | The options for creating the workflow. Optionally include a Zod schema via the `input` field to generate a JSON Schema for the backend. |
| `client?` | `IHatchetClient` | Optional Hatchet client instance. |
Returns
[`WorkflowDeclaration`](#workflowdeclaration)\<`I`, `O`\>
A new Workflow instance.

View File

@@ -0,0 +1,29 @@
export default {
client: {
title: "Client",
theme: {
toc: true,
},
},
Context: {
title: "Context",
theme: {
toc: true,
},
},
"feature-clients": {
title: "Feature Clients",
theme: {
toc: true,
},
},
Runnables: {
title: "Runnables",
theme: {
toc: true,
},
},
};

View File

@@ -0,0 +1,439 @@
# Hatchet TypeScript SDK Reference
This is the TypeScript SDK reference, documenting methods available for interacting with Hatchet resources.
Check out the [user guide](https://docs.hatchet.run/home/) for an introduction to getting your first tasks running.
<a id="hatchetclient"></a>
### HatchetClient
HatchetV1 implements the main client interface for interacting with the Hatchet workflow engine.
It provides methods for creating and executing workflows, as well as managing workers.
Implements
- `IHatchetClient`
#### Properties
| Property | Type | Description |
| -------------------------------- | -------- | ------------------------------------ |
| <a id="tenantid"></a> `tenantId` | `string` | The tenant ID for the Hatchet client |
Accessors
<a id="api"></a>
##### `api`
Get Signature
Get the API client for making HTTP requests to the Hatchet API
Note: This is not recommended for general use, but is available for advanced scenarios
Returns
`Api`\<`unknown`\>
A API client instance
<a id="crons"></a>
##### `crons`
Get Signature
Get the cron client for creating and managing cron workflow runs
Returns
[`CronClient`](feature-clients/crons.mdx#cronclient)
A cron client instance
Implementation of
```ts
IHatchetClient.crons;
```
<a id="events"></a>
##### `events`
Get Signature
Get the event client for creating and managing event workflow runs
Returns
`EventClient`
A event client instance
Implementation of
```ts
IHatchetClient.events;
```
<a id="filters"></a>
##### `filters`
Get Signature
Get the filters client for creating and managing filters
Returns
[`FiltersClient`](feature-clients/filters.mdx#filtersclient)
A filters client instance
<a id="metrics"></a>
##### `metrics`
Get Signature
Get the metrics client for creating and managing metrics
Returns
[`MetricsClient`](feature-clients/metrics.mdx#metricsclient)
A metrics client instance
Implementation of
```ts
IHatchetClient.metrics;
```
<a id="ratelimits"></a>
##### `ratelimits`
Get Signature
Get the rate limits client for creating and managing rate limits
Returns
[`RatelimitsClient`](feature-clients/ratelimits.mdx#ratelimitsclient)
A rate limits client instance
<a id="runs"></a>
##### `runs`
Get Signature
Get the runs client for creating and managing runs
Returns
[`RunsClient`](feature-clients/runs.mdx#runsclient)
A runs client instance
Implementation of
```ts
IHatchetClient.runs;
```
<a id="scheduled"></a>
##### `scheduled`
Get Signature
Get the schedules client for creating and managing scheduled workflow runs
Returns
[`ScheduleClient`](feature-clients/schedules.mdx#scheduleclient)
A schedules client instance
Implementation of
```ts
IHatchetClient.scheduled;
```
<a id="schedules"></a>
##### `schedules`
Get Signature
Alias
scheduled
Returns
[`ScheduleClient`](feature-clients/schedules.mdx#scheduleclient)
<a id="tasks"></a>
##### `tasks`
Get Signature
Get the tasks client for creating and managing tasks
Returns
[`WorkflowsClient`](feature-clients/workflows.mdx#workflowsclient)
A tasks client instance
<a id="tenant"></a>
##### `tenant`
Get Signature
Get the tenant client for managing tenants
Returns
`TenantClient`
A tenant client instance
<a id="webhooks"></a>
##### `webhooks`
Get Signature
Get the webhooks client for creating and managing webhooks
Returns
[`WebhooksClient`](feature-clients/webhooks.mdx#webhooksclient)
A webhooks client instance
<a id="workers"></a>
##### `workers`
Get Signature
Get the workers client for creating and managing workers
Returns
[`WorkersClient`](feature-clients/workers.mdx#workersclient)
A workers client instance
Implementation of
```ts
IHatchetClient.workers;
```
<a id="workflows"></a>
##### `workflows`
Get Signature
Get the workflows client for creating and managing workflows
Returns
[`WorkflowsClient`](feature-clients/workflows.mdx#workflowsclient)
A workflows client instance
Implementation of
```ts
IHatchetClient.workflows;
```
#### Methods
<a id="durabletask"></a>
##### `durableTask()`
Implementation of the durableTask method.
Creates a new durable task workflow.
Types can be explicitly specified as generics or inferred from the function signature.
Parameters
| Parameter | Type | Description |
| --------- | ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- |
| `options` | `CreateDurableTaskWorkflowOpts`\<`I` & `Resolved`\<`GlobalInput`, `MiddlewareBefore`\>, `MergeIfNonEmpty`\<`O`, `GlobalOutput`\>\> | Durable task configuration options |
Returns
[`TaskWorkflowDeclaration`](Runnables.mdx#taskworkflowdeclaration)\<`I`, `O`, `GlobalInput`, `GlobalOutput`, `MiddlewareBefore`, `MiddlewareAfter`\>
A TaskWorkflowDeclaration instance for a durable task
Creates a new durable task workflow with types inferred from the function parameter.
Parameters
| Parameter | Type | Description |
| --------- | ------------------------------------------------------------------------ | ------------------------------------------------------------------- |
| `options` | `object` & `Omit`\<`CreateDurableTaskWorkflowOpts`\<`I`, `O`\>, `"fn"`\> | Durable task configuration options with function that defines types |
Returns
[`TaskWorkflowDeclaration`](Runnables.mdx#taskworkflowdeclaration)\<`I`, `O`, `GlobalInput`, `GlobalOutput`, `MiddlewareBefore`, `MiddlewareAfter`\>
A TaskWorkflowDeclaration instance with inferred types
<a id="run"></a>
##### `run()`
Triggers a workflow run and waits for the result.
Parameters
| Parameter | Type | Description |
| ---------- | --------------------------------------------------------------- | ------------------------------------------------------------------- |
| `workflow` | `string` \| `Workflow` \| `BaseWorkflowDeclaration`\<`I`, `O`\> | The workflow to run, either as a Workflow instance or workflow name |
| `input` | `I` | The input data for the workflow |
| `options` | `RunOpts` | Configuration options for the workflow run |
Returns
`Promise`\<`O`\>
A promise that resolves with the workflow result
<a id="runandwait"></a>
##### `runAndWait()`
Triggers a workflow run and waits for the result.
Parameters
| Parameter | Type | Description |
| ---------- | --------------------------------------------------------------- | ------------------------------------------------------------------- |
| `workflow` | `string` \| `Workflow` \| `BaseWorkflowDeclaration`\<`I`, `O`\> | The workflow to run, either as a Workflow instance or workflow name |
| `input` | `I` | The input data for the workflow |
| `options` | `RunOpts` | Configuration options for the workflow run |
Returns
`Promise`\<`O`\>
A promise that resolves with the workflow result
Alias
run
<a id="runnowait"></a>
##### `runNoWait()`
Triggers a workflow run without waiting for completion.
Parameters
| Parameter | Type | Description |
| ---------- | --------------------------------------------------------------- | ------------------------------------------------------------------- |
| `workflow` | `string` \| `Workflow` \| `BaseWorkflowDeclaration`\<`I`, `O`\> | The workflow to run, either as a Workflow instance or workflow name |
| `input` | `I` | The input data for the workflow |
| `options` | `RunOpts` | Configuration options for the workflow run |
Returns
`Promise`\<`WorkflowRunRef`\<`O`\>\>
A WorkflowRunRef containing the run ID and methods to interact with the run
<a id="task"></a>
##### `task()`
Implementation of the task method.
Creates a new task workflow.
Types can be explicitly specified as generics or inferred from the function signature.
Parameters
| Parameter | Type | Description |
| --------- | --------------------------------------------------------------------------------------------------------------------------- | -------------------------- |
| `options` | `CreateTaskWorkflowOpts`\<`I` & `Resolved`\<`GlobalInput`, `MiddlewareBefore`\>, `MergeIfNonEmpty`\<`O`, `GlobalOutput`\>\> | Task configuration options |
Returns
[`TaskWorkflowDeclaration`](Runnables.mdx#taskworkflowdeclaration)\<`I`, `O`, `GlobalInput`, `GlobalOutput`, `MiddlewareBefore`, `MiddlewareAfter`\>
A TaskWorkflowDeclaration instance
Creates a new task workflow with types inferred from the function parameter.
Parameters
| Parameter | Type | Description |
| --------- | ----------------------------------------------------------------- | ----------------------------------------------------------- |
| `options` | `object` & `Omit`\<`CreateTaskWorkflowOpts`\<`I`, `O`\>, `"fn"`\> | Task configuration options with function that defines types |
Returns
[`TaskWorkflowDeclaration`](Runnables.mdx#taskworkflowdeclaration)\<`I`, `O`, `GlobalInput`, `GlobalOutput`, `MiddlewareBefore`, `MiddlewareAfter`\>
A TaskWorkflowDeclaration instance with inferred types
<a id="worker"></a>
##### `worker()`
Creates a new worker instance for processing workflow tasks.
Parameters
| Parameter | Type | Description |
| ---------- | ------------------------------ | --------------------------------------------- |
| `name` | `string` | - |
| `options?` | `number` \| `CreateWorkerOpts` | Configuration options for creating the worker |
Returns
`Promise`\<`Worker`\>
A promise that resolves with a new HatchetWorker instance
<a id="workflow"></a>
##### `workflow()`
Creates a new workflow definition.
Parameters
| Parameter | Type | Description |
| --------- | -------------------- | ----------------------------------------------- |
| `options` | `CreateWorkflowOpts` | Configuration options for creating the workflow |
Returns
[`WorkflowDeclaration`](Runnables.mdx#workflowdeclaration)\<`I`, `O`, `Resolved`\<`GlobalInput`, `MiddlewareBefore`\>\>
A new Workflow instance
Note
It is possible to create an orphaned workflow if no client is available using @hatchet/client CreateWorkflow

View File

@@ -0,0 +1,64 @@
export default {
crons: {
title: "Crons",
theme: {
toc: true,
},
},
filters: {
title: "Filters",
theme: {
toc: true,
},
},
metrics: {
title: "Metrics",
theme: {
toc: true,
},
},
ratelimits: {
title: "Ratelimits",
theme: {
toc: true,
},
},
runs: {
title: "Runs",
theme: {
toc: true,
},
},
schedules: {
title: "Schedules",
theme: {
toc: true,
},
},
webhooks: {
title: "Webhooks",
theme: {
toc: true,
},
},
workers: {
title: "Workers",
theme: {
toc: true,
},
},
workflows: {
title: "Workflows",
theme: {
toc: true,
},
},
};

View File

@@ -0,0 +1,89 @@
<a id="cronclient"></a>
### Cron Client
The cron client is a client for managing cron workflows within Hatchet.
#### Methods
<a id="create"></a>
##### `create()`
Creates a new Cron workflow.
Parameters
| Parameter | Type | Description |
| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------- |
| `workflow` | `string` \| `BaseWorkflowDeclaration`\<`any`, `any`\> \| `Workflow` | The workflow identifier or Workflow object. |
| `cron` | \{ `additionalMetadata?`: `Record`\<`string`, `string`\>; `expression`: `string`; `input?`: `Record`\<`string`, `any`\>; `name`: `string`; `priority?`: `number`; \} | The input data for creating the Cron Trigger. |
| `cron.additionalMetadata?` | `Record`\<`string`, `string`\> | - |
| `cron.expression` | `string` | - |
| `cron.input?` | `Record`\<`string`, `any`\> | - |
| `cron.name` | `string` | - |
| `cron.priority?` | `number` | - |
Returns
`Promise`\<`CronWorkflows`\>
A promise that resolves to the created CronWorkflows object.
Throws
Will throw an error if the input is invalid or the API call fails.
<a id="delete"></a>
##### `delete()`
Deletes an existing Cron Trigger.
Parameters
| Parameter | Type | Description |
| --------- | --------------------------- | -------------------------------------------------------- |
| `cron` | `string` \| `CronWorkflows` | The Cron Trigger ID as a string or CronWorkflows object. |
Returns
`Promise`\<`void`\>
A promise that resolves when the Cron Trigger is deleted.
<a id="get"></a>
##### `get()`
Retrieves a specific Cron Trigger by its ID.
Parameters
| Parameter | Type | Description |
| --------- | --------------------------- | -------------------------------------------------------- |
| `cron` | `string` \| `CronWorkflows` | The Cron Trigger ID as a string or CronWorkflows object. |
Returns
`Promise`\<`CronWorkflows`\>
A promise that resolves to the CronWorkflows object.
<a id="list"></a>
##### `list()`
Lists all Cron Triggers based on the provided query parameters.
Parameters
| Parameter | Type | Description |
| --------- | ------------------- | ------------------------------------------- |
| `query` | `object` & `object` | Query parameters for listing Cron Triggers. |
Returns
`Promise`\<`CronWorkflowsList`\>
A promise that resolves to a CronWorkflowsList object.

View File

@@ -0,0 +1,102 @@
<a id="filtersclient"></a>
### Filters Client
The filters client is a client for interacting with Hatchet's filters API.
#### Methods
<a id="create"></a>
##### `create()`
Creates a new filter.
Parameters
| Parameter | Type | Description |
| --------- | ----------------------- | ------------------------------------- |
| `opts` | `V1CreateFilterRequest` | The options for the create operation. |
Returns
`Promise`\<`V1Filter`\>
A promise that resolves to the created filter.
<a id="delete"></a>
##### `delete()`
Deletes a filter by its ID.
Parameters
| Parameter | Type | Description |
| ---------- | -------- | ------------------------------- |
| `filterId` | `string` | The ID of the filter to delete. |
Returns
`Promise`\<`V1Filter`\>
A promise that resolves to the deleted filter.
<a id="get"></a>
##### `get()`
Gets a filter by its ID.
Parameters
| Parameter | Type | Description |
| ---------- | -------- | ---------------------------- |
| `filterId` | `string` | The ID of the filter to get. |
Returns
`Promise`\<`V1Filter`\>
A promise that resolves to the filter.
<a id="list"></a>
##### `list()`
Lists all filters.
Parameters
| Parameter | Type | Description |
| ------------------- | --------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
| `opts?` | \{ `limit?`: `number`; `offset?`: `number`; `scopes?`: ...[]; `workflowIds?`: ...[]; \} | The options for the list operation. |
| `opts.limit?` | `number` | The number of filters to return. |
| `opts.offset?` | `number` | The number of filters to skip before returning the result set. |
| `opts.scopes?` | ...[] | A list of scopes to filter by. |
| `opts.workflowIds?` | ...[] | A list of workflow IDs to filter by. |
Returns
`Promise`\<`V1FilterList`\>
A promise that resolves to the list of filters.
<a id="update"></a>
##### `update()`
Updates a filter by its ID.
Parameters
| Parameter | Type | Description |
| ---------- | ----------------------- | ----------------------------------- |
| `filterId` | `string` | The ID of the filter to update. |
| `updates` | `V1UpdateFilterRequest` | The updates to apply to the filter. |
Returns
`Promise`\<`V1Filter`\>
A promise that resolves to the updated filter.

View File

@@ -0,0 +1,50 @@
<a id="metricsclient"></a>
### Metrics Client
The metrics client is a client for reading metrics out of Hatchets metrics API.
#### Methods
<a id="getqueuemetrics"></a>
##### `getQueueMetrics()`
Returns the queue metrics for the current tenant.
Parameters
| Parameter | Type | Description |
| --------- | --------------- | ---------------------------- |
| `opts?` | `RequestParams` | The options for the request. |
Returns
`Promise`\<`TenantStepRunQueueMetrics`\>
The queue metrics for the current tenant.
<a id="gettaskstatusmetrics"></a>
##### `getTaskStatusMetrics()`
Returns aggregate task run counts grouped by status (queued, running, completed, failed, cancelled)
Parameters
| Parameter | Type | Description |
| ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `query` | \{ `additional_metadata?`: `string`[]; `parent_task_external_id?`: `string`; `since`: `string`; `triggering_event_external_id?`: `string`; `until?`: `string`; `workflow_ids?`: `string`[]; \} | Filters for the metrics query (e.g. `since`, `until`, `workflow_ids`). |
| `query.additional_metadata?` | `string`[] | Additional metadata k-v pairs to filter by |
| `query.parent_task_external_id?` | `string` | The parent task's external id **Format** uuid **Min Length** 36 **Max Length** 36 |
| `query.since?` | `string` | The start time to get metrics for **Format** date-time |
| `query.triggering_event_external_id?` | `string` | The id of the event that triggered the task **Format** uuid **Min Length** 36 **Max Length** 36 |
| `query.until?` | `string` | The end time to get metrics for **Format** date-time |
| `query.workflow_ids?` | `string`[] | The workflow id to find runs for |
| `requestParams?` | `RequestParams` | Optional request-level overrides (headers, signal, etc.). |
Returns
`Promise`\<`TaskStatusMetrics`\>
Counts per status for the matched task runs.

View File

@@ -0,0 +1,43 @@
<a id="ratelimitsclient"></a>
### RatelimitsClient
The rate limits client is a wrapper for Hatchets gRPC API that makes it easier to work with rate limits in Hatchet.
#### Methods
<a id="list"></a>
##### `list()`
Lists all rate limits for the current tenant.
Parameters
| Parameter | Type | Description |
| --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- |
| `opts` | \| \{ `limit?`: `number`; `offset?`: `number`; `orderByDirection?`: `RateLimitOrderByDirection`; `orderByField?`: `RateLimitOrderByField`; `search?`: `string`; \} \| `undefined` | The options for the list operation. |
Returns
`Promise`\<`RateLimitList`\>
A promise that resolves to the list of rate limits.
<a id="upsert"></a>
##### `upsert()`
Upserts a rate limit for the current tenant.
Parameters
| Parameter | Type | Description |
| --------- | --------------------- | ------------------------------------- |
| `opts` | `CreateRateLimitOpts` | The options for the upsert operation. |
Returns
`Promise`\<`string`\>
A promise that resolves to the key of the upserted rate limit.

View File

@@ -0,0 +1,135 @@
<a id="runsclient"></a>
### Runs Client
The runs client is a client for interacting with task and workflow runs within Hatchet.
#### Methods
<a id="cancel"></a>
##### `cancel()`
Cancels a task or workflow run by its ID.
Parameters
| Parameter | Type | Description |
| --------- | --------------- | ------------------------------------- |
| `opts` | `CancelRunOpts` | The options for the cancel operation. |
Returns
`Promise`\<`AxiosResponse`\<`V1CancelledTasks`, `any`, \{
\}\>\>
A promise that resolves to the cancelled run.
<a id="get"></a>
##### `get()`
Gets a task or workflow run by its ID.
Parameters
| Parameter | Type | Description |
| --------- | ----------------------------------- | ------------------------- |
| `run` | `string` \| `WorkflowRunRef`\<`T`\> | The ID of the run to get. |
Returns
`Promise`\<`V1WorkflowRunDetails`\>
A promise that resolves to the run.
<a id="get_status"></a>
##### `get_status()`
Gets the status of a task or workflow run by its ID.
Parameters
| Parameter | Type | Description |
| --------- | ----------------------------------- | --------------------------------------- |
| `run` | `string` \| `WorkflowRunRef`\<`T`\> | The ID of the run to get the status of. |
Returns
`Promise`\<`V1TaskStatus`\>
A promise that resolves to the status of the run.
<a id="list"></a>
##### `list()`
Lists all task and workflow runs for the current tenant.
Parameters
| Parameter | Type | Description |
| --------- | --------------------------- | ----------------------------------- |
| `opts?` | `Partial`\<`ListRunsOpts`\> | The options for the list operation. |
Returns
`Promise`\<`V1TaskSummaryList`\>
A promise that resolves to the list of runs.
<a id="replay"></a>
##### `replay()`
Replays a task or workflow run by its ID.
Parameters
| Parameter | Type | Description |
| --------- | --------------- | ------------------------------------- |
| `opts` | `ReplayRunOpts` | The options for the replay operation. |
Returns
`Promise`\<`AxiosResponse`\<`V1ReplayedTasks`, `any`, \{
\}\>\>
A promise that resolves to the replayed run.
<a id="runref"></a>
##### `runRef()`
Creates a run reference for a task or workflow run by its ID.
Parameters
| Parameter | Type | Description |
| --------- | -------- | -------------------------------------------- |
| `id` | `string` | The ID of the run to create a reference for. |
Returns
`WorkflowRunRef`\<`T`\>
A promise that resolves to the run reference.
<a id="subscribetostream"></a>
##### `subscribeToStream()`
Subscribes to a stream of events for a task or workflow run by its ID.
Parameters
| Parameter | Type | Description |
| --------------- | -------- | ---------------------------------- |
| `workflowRunId` | `string` | The ID of the run to subscribe to. |
Returns
`AsyncIterableIterator`\<`string`\>
A promise that resolves to the stream of events.

View File

@@ -0,0 +1,146 @@
<a id="scheduleclient"></a>
### ScheduleClient
The scheduled client is a client for managing scheduled workflows within Hatchet
#### Methods
<a id="bulkdelete"></a>
##### `bulkDelete()`
Bulk deletes scheduled runs (by explicit IDs and/or a filter).
Parameters
| Parameter | Type | Description |
| --------------------- | ---------------------------------------------------------------------------------------- | ----------------------------------------------------------------- |
| `opts` | \{ `filter?`: `ScheduledWorkflowsBulkDeleteFilter`; `scheduledRuns?`: (... \| ...)[]; \} | Either `scheduledRuns` (ids/objects) and/or a server-side filter. |
| `opts.filter?` | `ScheduledWorkflowsBulkDeleteFilter` | - |
| `opts.scheduledRuns?` | (... \| ...)[] | - |
Returns
`Promise`\<`ScheduledWorkflowsBulkDeleteResponse`\>
A promise that resolves to deleted ids + per-id errors.
<a id="bulkupdate"></a>
##### `bulkUpdate()`
Bulk updates (reschedules) scheduled runs.
Parameters
| Parameter | Type | Description |
| --------- | ---------- | ---------------------------------- |
| `updates` | `object`[] | List of id/object + new triggerAt. |
Returns
`Promise`\<`ScheduledWorkflowsBulkUpdateResponse`\>
A promise that resolves to updated ids + per-id errors.
<a id="create"></a>
##### `create()`
Creates a new Scheduled Run.
Parameters
| Parameter | Type | Description |
| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------- |
| `workflow` | `string` \| `Workflow` | The workflow name or Workflow object. |
| `cron` | \{ `additionalMetadata?`: `Record`\<`string`, `string`\>; `input?`: `Record`\<`string`, `any`\>; `priority?`: `number`; `triggerAt`: `Date`; \} | - |
| `cron.additionalMetadata?` | `Record`\<`string`, `string`\> | - |
| `cron.input?` | `Record`\<`string`, `any`\> | - |
| `cron.priority?` | `number` | - |
| `cron.triggerAt` | `Date` | - |
Returns
`Promise`\<`ScheduledWorkflows`\>
A promise that resolves to the created ScheduledWorkflows object.
Throws
Will throw an error if the input is invalid or the API call fails.
<a id="delete"></a>
##### `delete()`
Deletes an existing Scheduled Run.
Parameters
| Parameter | Type | Description |
| -------------- | -------------------------------- | -------------------------------------------------------------- |
| `scheduledRun` | `string` \| `ScheduledWorkflows` | The Scheduled Run ID as a string or ScheduledWorkflows object. |
Returns
`Promise`\<`void`\>
A promise that resolves when the Scheduled Run is deleted.
<a id="get"></a>
##### `get()`
Retrieves a specific Scheduled Run by its ID.
Parameters
| Parameter | Type | Description |
| -------------- | -------------------------------- | -------------------------------------------------------------- |
| `scheduledRun` | `string` \| `ScheduledWorkflows` | The Scheduled Run ID as a string or ScheduledWorkflows object. |
Returns
`Promise`\<`ScheduledWorkflows`\>
A promise that resolves to the ScheduledWorkflows object.
<a id="list"></a>
##### `list()`
Lists all Cron Triggers based on the provided query parameters.
Parameters
| Parameter | Type | Description |
| --------- | ------------------- | -------------------------------------------- |
| `query` | `object` & `object` | Query parameters for listing Scheduled Runs. |
Returns
`Promise`\<`ScheduledWorkflowsList`\>
A promise that resolves to a ScheduledWorkflowsList object.
<a id="update"></a>
##### `update()`
Updates (reschedules) an existing Scheduled Run.
Parameters
| Parameter | Type | Description |
| ------------------ | -------------------------------- | -------------------------------------------------------------- |
| `scheduledRun` | `string` \| `ScheduledWorkflows` | The Scheduled Run ID as a string or ScheduledWorkflows object. |
| `update` | \{ `triggerAt`: `Date`; \} | The update payload (currently only triggerAt). |
| `update.triggerAt` | `Date` | - |
Returns
`Promise`\<`ScheduledWorkflows`\>
A promise that resolves to the updated ScheduledWorkflows object.

View File

@@ -0,0 +1,107 @@
<a id="webhooksclient"></a>
### Webhooks Client
Client for managing incoming webhooks in Hatchet.
Webhooks allow external systems to trigger Hatchet workflows by sending
HTTP requests to dedicated endpoints. This enables real-time integration
with third-party services like GitHub, Stripe, Slack, or any system that
can send webhook events.
#### Methods
<a id="create"></a>
##### `create()`
Creates a new webhook.
Parameters
| Parameter | Type | Description |
| --------- | ---------------------- | --------------------------------------------- |
| `request` | `CreateWebhookOptions` | The request options for the create operation. |
Returns
`Promise`\<`V1Webhook`\>
A promise that resolves to the created webhook.
<a id="delete"></a>
##### `delete()`
Deletes a webhook by its name.
Parameters
| Parameter | Type | Description |
| ------------- | -------- | ---------------------------------- |
| `webhookName` | `string` | The name of the webhook to delete. |
Returns
`Promise`\<`V1Webhook`\>
A promise that resolves to the deleted webhook.
<a id="get"></a>
##### `get()`
Gets a webhook by its name.
Parameters
| Parameter | Type | Description |
| ------------- | -------- | ------------------------------- |
| `webhookName` | `string` | The name of the webhook to get. |
Returns
`Promise`\<`V1Webhook`\>
A promise that resolves to the webhook.
<a id="list"></a>
##### `list()`
Lists all webhooks for the current tenant.
Parameters
| Parameter | Type | Description |
| ----------------------- | --------------------------------------------------------------------------------------------- | ----------------------------------- |
| `options?` | \{ `limit?`: `number`; `offset?`: `number`; `sourceNames?`: ...[]; `webhookNames?`: ...[]; \} | The options for the list operation. |
| `options.limit?` | `number` | - |
| `options.offset?` | `number` | - |
| `options.sourceNames?` | ...[] | - |
| `options.webhookNames?` | ...[] | - |
Returns
`Promise`\<`V1WebhookList`\>
A promise that resolves to the list of webhooks.
<a id="update"></a>
##### `update()`
Updates a webhook by its name.
Parameters
| Parameter | Type | Description |
| ------------- | ------------------------------------- | ------------------------------------- |
| `webhookName` | `string` | The name of the webhook to update. |
| `options` | `Partial`\<`V1UpdateWebhookRequest`\> | The options for the update operation. |
Returns
`Promise`\<`V1Webhook`\>
A promise that resolves to the updated webhook.

View File

@@ -0,0 +1,91 @@
<a id="workersclient"></a>
### Workers Client
The workers client is a client for managing workers programmatically within Hatchet.
#### Methods
<a id="get"></a>
##### `get()`
Get a worker by its ID.
Parameters
| Parameter | Type | Description |
| ---------- | -------- | ---------------------------- |
| `workerId` | `string` | The ID of the worker to get. |
Returns
`Promise`\<`Worker`\>
A promise that resolves to the worker.
<a id="ispaused"></a>
##### `isPaused()`
Check if a worker is paused.
Parameters
| Parameter | Type | Description |
| ---------- | -------- | ------------------------------ |
| `workerId` | `string` | The ID of the worker to check. |
Returns
`Promise`\<`boolean`\>
A promise that resolves to true if the worker is paused, false otherwise.
<a id="list"></a>
##### `list()`
List all workers in the tenant.
Returns
`Promise`\<`WorkerList`\>
A promise that resolves to the list of workers.
<a id="pause"></a>
##### `pause()`
Pause a worker.
Parameters
| Parameter | Type | Description |
| ---------- | -------- | ------------------------------ |
| `workerId` | `string` | The ID of the worker to pause. |
Returns
`Promise`\<`Worker`\>
A promise that resolves to the paused worker.
<a id="unpause"></a>
##### `unpause()`
Unpause a worker.
Parameters
| Parameter | Type | Description |
| ---------- | -------- | -------------------------------- |
| `workerId` | `string` | The ID of the worker to unpause. |
Returns
`Promise`\<`Worker`\>
A promise that resolves to the unpaused worker.

View File

@@ -0,0 +1,85 @@
<a id="workflowsclient"></a>
### Workflows Client
The workflows client is a client for managing workflows programmatically within Hatchet.
NOTE: that workflows are the declaration, not the individual runs. If you're looking for runs, use the RunsClient instead.
#### Methods
<a id="delete"></a>
##### `delete()`
Delete a workflow by its name, ID, or object.
Parameters
| Parameter | Type | Description |
| ---------- | ------------------------------------------------------------------- | --------------------------------- |
| `workflow` | `string` \| `BaseWorkflowDeclaration`\<`any`, `any`\> \| `Workflow` | The workflow name, ID, or object. |
Returns
`Promise`\<`void`\>
A promise that resolves to the deleted workflow.
<a id="get"></a>
##### `get()`
Get a workflow by its name, ID, or object.
Parameters
| Parameter | Type | Description |
| ---------- | ------------------------------------------------------------------- | --------------------------------- |
| `workflow` | `string` \| `BaseWorkflowDeclaration`\<`any`, `any`\> \| `Workflow` | The workflow name, ID, or object. |
Returns
`Promise`\<`Workflow`\>
A promise that resolves to the workflow.
<a id="getworkflowidfromname"></a>
##### `getWorkflowIdFromName()`
Gets the workflow ID from a workflow name, ID, or object.
If the input is not a valid UUID, it will look up the workflow by name.
Parameters
| Parameter | Type | Description |
| ---------- | ---------------------------------------------------------------------------------------------- | --------------------------------- |
| `workflow` | \| `string` \| `WorkflowDefinition` \| `BaseWorkflowDeclaration`\<`any`, `any`\> \| `Workflow` | The workflow name, ID, or object. |
Returns
`Promise`\<`string`\>
The workflow ID as a string.
<a id="list"></a>
##### `list()`
List all workflows in the tenant.
Parameters
| Parameter | Type | Description |
| -------------- | ----------------------------------------------------------------- | ------------------------------------------------------ |
| `opts?` | \{ `limit?`: `number`; `name?`: `string`; `offset?`: `number`; \} | The options for the list operation. |
| `opts.limit?` | `number` | The number to limit by **Format** int **Default** `50` |
| `opts.name?` | `string` | Search by name |
| `opts.offset?` | `number` | The number to skip **Format** int **Default** `0` |
Returns
`Promise`\<`WorkflowList`\>
A promise that resolves to the list of workflows.

View File

@@ -2,9 +2,6 @@
/certs
.e2e-worker.pid
# ignore docs for now, because we manually use the docs output to construct docs
docs
node_modules/
openapi.yaml

View File

@@ -0,0 +1,77 @@
import path from 'path';
import { FRONTEND_DOCS_RELATIVE_PATH, MDX_EXTENSION } from './shared';
export interface Document {
sourcePath: string;
readableSourcePath: string;
mdxOutputPath: string;
mdxOutputMetaJsPath: string;
isIndex: boolean;
directory: string;
basename: string;
title: string;
metaJsEntry: string;
}
const FILENAME_REMAP: Record<string, string> = {
'Hatchet-TypeScript-SDK-Reference.mdx': 'client.mdx',
};
function remapFilename(filename: string): { outRelative: string; basename: string; directory: string } {
const remapped = FILENAME_REMAP[filename] ?? filename;
if (remapped.startsWith('client.features.')) {
const leafName = remapped.replace('client.features.', '');
return {
outRelative: 'feature-clients/' + leafName,
basename: path.basename(leafName, MDX_EXTENSION),
directory: '/feature-clients',
};
}
return {
outRelative: remapped,
basename: path.basename(remapped, MDX_EXTENSION),
directory: '',
};
}
function toTitle(basename: string): string {
return basename
.replace(/[-_.]/g, ' ')
.replace(/[^0-9a-zA-Z ]+/g, '')
.trim()
.replace(/\s+/g, ' ')
.split(' ')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join(' ');
}
export function documentFromPath(filePath: string): Document {
const filename = path.basename(filePath);
const { outRelative, basename, directory } = remapFilename(filename);
const title = toTitle(basename);
const outFull = path.join(FRONTEND_DOCS_RELATIVE_PATH, outRelative);
const outDir = path.dirname(outFull);
const metaJsEntry = ` "${basename}": {
title: "${title}",
theme: {
toc: true,
},
},`;
return {
directory,
basename,
title,
metaJsEntry,
sourcePath: filePath,
readableSourcePath: filename,
mdxOutputPath: outFull,
mdxOutputMetaJsPath: path.join(outDir, '_meta.js'),
isIndex: basename === 'index' || basename === 'README',
};
}

View File

@@ -0,0 +1,103 @@
import fs from 'fs';
import path from 'path';
import { execSync } from 'child_process';
import { Document } from './doc_types';
import { crawlDirectory } from './paths';
import { TMP_GEN_PATH } from './shared';
function rmrf(target: string) {
if (fs.existsSync(target)) {
fs.rmSync(target, { recursive: true, force: true });
}
}
function metaEntry(key: string, title: string): string {
return ` "${key}": {
title: "${title}",
theme: {
toc: true,
},
},`;
}
function generateMetaJs(docs: Document[], subDirs: string[]): string {
const docEntries = docs.map((d) => d.metaJsEntry);
const subDirEntries = subDirs.map((dir) => {
const name = dir.replace(/^\//, '');
const title = name.replace(/-/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
return metaEntry(name, title);
});
const all = [...docEntries, ...subDirEntries].sort((a, b) => {
const keyA = a.trim().split(':')[0].replace(/"/g, '').toLowerCase();
const keyB = b.trim().split(':')[0].replace(/"/g, '').toLowerCase();
return keyA.localeCompare(keyB);
});
return `export default {\n${all.join('\n\n')}\n};\n`;
}
function updateMetaJs(documents: Document[]) {
const metaJsPaths = new Set(documents.map((d) => d.mdxOutputMetaJsPath));
for (const metaJsPath of metaJsPaths) {
const relevantDocs = documents.filter((d) => d.mdxOutputMetaJsPath === metaJsPath);
const thisDir = relevantDocs[0].directory;
const subDirs = [
...new Set(
documents
.map((d) => d.directory)
.filter((dir) => dir !== thisDir && dir.startsWith(thisDir) && dir.split('/').length === thisDir.split('/').filter(Boolean).length + 2)
),
];
const meta = generateMetaJs(relevantDocs, subDirs);
fs.mkdirSync(path.dirname(metaJsPath), { recursive: true });
fs.writeFileSync(metaJsPath, meta, 'utf-8');
console.log('Wrote', metaJsPath);
}
}
function fixBrokenFeatureAnchorLinks(content: string): string {
return content.replace(/\(client\.features\.([^)\s#]+\.mdx)/g, '(feature-clients/$1');
}
function copyDoc(document: Document) {
const content = fixBrokenFeatureAnchorLinks(fs.readFileSync(document.sourcePath, 'utf-8'));
fs.mkdirSync(path.dirname(document.mdxOutputPath), { recursive: true });
fs.writeFileSync(document.mdxOutputPath, content, 'utf-8');
console.log('Wrote', document.mdxOutputPath);
}
function run() {
rmrf(TMP_GEN_PATH);
try {
console.log('Running typedoc...');
execSync('npx typedoc', { stdio: 'inherit' });
const documents = crawlDirectory(TMP_GEN_PATH);
console.log(`Found ${documents.length} documents`);
for (const doc of documents) {
copyDoc(doc);
}
updateMetaJs(documents);
console.log('Running prettier on frontend docs...');
execSync('pnpm lint:fix', {
stdio: 'inherit',
cwd: path.resolve(process.cwd(), '../../frontend/docs'),
shell: '/bin/bash',
});
} finally {
rmrf(TMP_GEN_PATH);
}
}
if (require.main === module) {
run();
}

View File

@@ -0,0 +1,93 @@
// @ts-check
import { MarkdownTheme, MarkdownThemeContext } from 'typedoc-plugin-markdown';
export function load(app) {
app.renderer.defineTheme('hatchet-ts-docs', HatchetDocsTheme);
}
const HEADING_RENAMES = {
CronClient: 'Cron Client',
FiltersClient: 'Filters Client',
MetricsClient: 'Metrics Client',
RateLimitsClient: 'Rate Limits Client',
RunsClient: 'Runs Client',
SchedulesClient: 'Schedules Client',
WorkersClient: 'Workers Client',
WorkflowsClient: 'Workflows Client',
WebhooksClient: 'Webhooks Client',
};
const HEADINGS_TO_REMOVE = [
'Type Parameters',
'Call Signature',
'Classes',
];
const HEADINGS_TO_BOLD = [
'Parameters',
'Returns',
'Extends',
'Throws',
'Overrides',
'Accessors',
'Get Signature',
'Implementation of',
'Note',
'Alias',
'Implements',
'Extended by'
];
class HatchetDocsTheme extends MarkdownTheme {
getRenderContext(page) {
return new HatchetDocsContext(this, page, this.application.options);
}
render(page) {
const transforms = [refactorHeadings, stripGenericTypeParams, unescapeHeadingUnderscores, spaceOutHeadings, codeWrapMethodHeadings];
return transforms.reduce((content, fn) => fn(content), super.render(page));
}
}
function refactorHeadings(content) {
let result = content.replace(/#{1,6}\s+client\/features\/\S+\n*/g, '');
for (const heading of HEADINGS_TO_REMOVE) {
result = result.replace(new RegExp(`#{1,6}\\s+${heading}\\n*`, 'g'), '');
}
for (const heading of HEADINGS_TO_BOLD) {
result = result.replace(new RegExp(`^#{1,6}\\s+(${heading})$`, 'gmi'), '$1');
}
return result;
}
function stripGenericTypeParams(content) {
return content.replace(/^(#{1,6} .+?)\\<[^>]*>/gm, '$1');
}
function unescapeHeadingUnderscores(content) {
return content.replace(/^(#{1,6} .+)$/gm, (match) => match.replace(/\\_/g, '_'));
}
function spaceOutHeadings(content) {
return content.replace(/^(#{1,6} )(\S+)$/gm, (match, hashes, name) =>
hashes + (HEADING_RENAMES[name] ?? name)
);
}
function codeWrapMethodHeadings(content) {
return content
.replace(/^(#{3,6} )(.+\(\))$/gm, (match, hashes, name) => `${hashes}\`${name}\``)
.replace(/^(#{4,6} )([a-z]\w*)$/gm, (match, hashes, name) => `${hashes}\`${name}\``);
}
class HatchetDocsContext extends MarkdownThemeContext {
/** @param {ConstructorParameters<typeof MarkdownThemeContext>} args */
constructor(...args) {
super(...args);
this.partials = {
...this.partials,
signatureTitle: () => '',
typeParametersTable: () => '',
};
}
}

View File

@@ -0,0 +1,11 @@
import fs from 'fs';
import path from 'path';
import { Document, documentFromPath } from './doc_types';
export function crawlDirectory(directory: string, onlyInclude: string[] = []): Document[] {
return fs
.readdirSync(directory, { withFileTypes: true })
.filter((entry) => entry.isFile() && entry.name.endsWith('.mdx') && entry.name !== 'README.mdx')
.map((entry) => documentFromPath(path.join(directory, entry.name)))
.filter((doc) => !onlyInclude.length || onlyInclude.includes(doc.readableSourcePath));
}

View File

@@ -0,0 +1,3 @@
export const TMP_GEN_PATH = '/tmp/hatchet-typescript/docs/gen';
export const FRONTEND_DOCS_RELATIVE_PATH = '../../frontend/docs/pages/sdks/typescript';
export const MDX_EXTENSION = '.mdx';

View File

@@ -36,7 +36,7 @@
"prepublish": "cp package.json dist/package.json; cp README.md dist/; cp -r scripts dist/",
"publish:ci": "rm -rf ./dist && pnpm run dump-version && pnpm run tsc:build && pnpm run prepublish && cd dist && pnpm publish --access public --no-git-checks",
"publish:ci:alpha": "rm -rf ./dist && pnpm run dump-version && pnpm run tsc:build && pnpm run prepublish && cd dist && pnpm publish --access public --no-git-checks --tag alpha",
"generate-docs": "typedoc",
"generate-docs": "ts-node docs/generate.ts",
"exec": "npx dotenv -- ts-node -r tsconfig-paths/register --project tsconfig.json"
},
"keywords": [],
@@ -73,8 +73,9 @@
"ts-jest": "^29.3.1",
"ts-node": "^10.9.2",
"ts-proto": "^2.7.0",
"typedoc": "^0.28.0",
"typedoc": "^0.28.17",
"typedoc-plugin-markdown": "^4.6.0",
"typedoc-plugin-no-inherit": "^1.6.1",
"typescript": "^5.8.2"
},
"dependencies": {

View File

@@ -144,11 +144,14 @@ importers:
specifier: ^2.7.0
version: 2.7.7
typedoc:
specifier: ^0.28.0
version: 0.28.10(typescript@5.9.2)
specifier: ^0.28.17
version: 0.28.17(typescript@5.9.2)
typedoc-plugin-markdown:
specifier: ^4.6.0
version: 4.8.1(typedoc@0.28.10(typescript@5.9.2))
version: 4.8.1(typedoc@0.28.17(typescript@5.9.2))
typedoc-plugin-no-inherit:
specifier: ^1.6.1
version: 1.6.1(typedoc@0.28.17(typescript@5.9.2))
typescript:
specifier: ^5.8.2
version: 5.9.2
@@ -362,8 +365,8 @@ packages:
resolution: {integrity: sha512-d9zaMRSTIKDLhctzH12MtXvJKSSUhaHcjV+2Z+GK+EEY7XKpP5yR4x+N3TAcHTcu963nIr+TMcCb4DBCYX1z6Q==}
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
'@gerrit0/mini-shiki@3.9.2':
resolution: {integrity: sha512-Tvsj+AOO4Z8xLRJK900WkyfxHsZQu+Zm1//oT1w443PO6RiYMoq/4NGOhaNuZoUMYsjKIAPVQ6eOFMddj6yphQ==}
'@gerrit0/mini-shiki@3.23.0':
resolution: {integrity: sha512-bEMORlG0cqdjVyCEuU0cDQbORWX+kYCeo0kV1lbxF5bt4r7SID2l9bqsxJEM0zndaxpOUT7riCyIVEuqq/Ynxg==}
'@grpc/grpc-js@1.13.4':
resolution: {integrity: sha512-GsFaMXCkMqkKIvwCQjCrwH+GHbPKBjhwo/8ZuUkWHqbI73Kky9I+pQltrlT0+MWpedCoosda53lgjYfyEPgxBg==}
@@ -548,17 +551,17 @@ packages:
'@rtsao/scc@1.1.0':
resolution: {integrity: sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==}
'@shikijs/engine-oniguruma@3.9.2':
resolution: {integrity: sha512-Vn/w5oyQ6TUgTVDIC/BrpXwIlfK6V6kGWDVVz2eRkF2v13YoENUvaNwxMsQU/t6oCuZKzqp9vqtEtEzKl9VegA==}
'@shikijs/engine-oniguruma@3.23.0':
resolution: {integrity: sha512-1nWINwKXxKKLqPibT5f4pAFLej9oZzQTsby8942OTlsJzOBZ0MWKiwzMsd+jhzu8YPCHAswGnnN1YtQfirL35g==}
'@shikijs/langs@3.9.2':
resolution: {integrity: sha512-X1Q6wRRQXY7HqAuX3I8WjMscjeGjqXCg/Sve7J2GWFORXkSrXud23UECqTBIdCSNKJioFtmUGJQNKtlMMZMn0w==}
'@shikijs/langs@3.23.0':
resolution: {integrity: sha512-2Ep4W3Re5aB1/62RSYQInK9mM3HsLeB91cHqznAJMuylqjzNVAVCMnNWRHFtcNHXsoNRayP9z1qj4Sq3nMqYXg==}
'@shikijs/themes@3.9.2':
resolution: {integrity: sha512-6z5lBPBMRfLyyEsgf6uJDHPa6NAGVzFJqH4EAZ+03+7sedYir2yJBRu2uPZOKmj43GyhVHWHvyduLDAwJQfDjA==}
'@shikijs/themes@3.23.0':
resolution: {integrity: sha512-5qySYa1ZgAT18HR/ypENL9cUSGOeI2x+4IvYJu4JgVJdizn6kG4ia5Q1jDEOi7gTbN4RbuYtmHh0W3eccOrjMA==}
'@shikijs/types@3.9.2':
resolution: {integrity: sha512-/M5L0Uc2ljyn2jKvj4Yiah7ow/W+DJSglVafvWAJ/b8AZDeeRAdMu3c2riDzB7N42VD+jSnWxeP9AKtd4TfYVw==}
'@shikijs/types@3.23.0':
resolution: {integrity: sha512-3JZ5HXOZfYjsYSk0yPwBrkupyYSLpAE26Qc0HLghhZNGTZg/SKxXIIgoxOpmmeQP0RRSDJTk1/vPfw9tbw+jSQ==}
'@shikijs/vscode-textmate@10.0.2':
resolution: {integrity: sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==}
@@ -2859,8 +2862,13 @@ packages:
peerDependencies:
typedoc: 0.28.x
typedoc@0.28.10:
resolution: {integrity: sha512-zYvpjS2bNJ30SoNYfHSRaFpBMZAsL7uwKbWwqoCNFWjcPnI3e/mPLh2SneH9mX7SJxtDpvDgvd9/iZxGbo7daw==}
typedoc-plugin-no-inherit@1.6.1:
resolution: {integrity: sha512-+qf0RkO5YR9kUBBS1HqzzDOsWOnLcXTtGL0f2ia4jDQAjGrtF0+po/0R8k3UNtBqyDzL273aaV3FIGHEX+U/tg==}
peerDependencies:
typedoc: 0.26.x || 0.27.x || 0.28.x
typedoc@0.28.17:
resolution: {integrity: sha512-ZkJ2G7mZrbxrKxinTQMjFqsCoYY6a5Luwv2GKbTnBCEgV2ihYm5CflA9JnJAwH0pZWavqfYxmDkFHPt4yx2oDQ==}
engines: {node: '>= 18', pnpm: '>= 10'}
hasBin: true
peerDependencies:
@@ -3240,12 +3248,12 @@ snapshots:
'@eslint/js@8.57.1': {}
'@gerrit0/mini-shiki@3.9.2':
'@gerrit0/mini-shiki@3.23.0':
dependencies:
'@shikijs/engine-oniguruma': 3.9.2
'@shikijs/langs': 3.9.2
'@shikijs/themes': 3.9.2
'@shikijs/types': 3.9.2
'@shikijs/engine-oniguruma': 3.23.0
'@shikijs/langs': 3.23.0
'@shikijs/themes': 3.23.0
'@shikijs/types': 3.23.0
'@shikijs/vscode-textmate': 10.0.2
'@grpc/grpc-js@1.13.4':
@@ -3535,20 +3543,20 @@ snapshots:
'@rtsao/scc@1.1.0': {}
'@shikijs/engine-oniguruma@3.9.2':
'@shikijs/engine-oniguruma@3.23.0':
dependencies:
'@shikijs/types': 3.9.2
'@shikijs/types': 3.23.0
'@shikijs/vscode-textmate': 10.0.2
'@shikijs/langs@3.9.2':
'@shikijs/langs@3.23.0':
dependencies:
'@shikijs/types': 3.9.2
'@shikijs/types': 3.23.0
'@shikijs/themes@3.9.2':
'@shikijs/themes@3.23.0':
dependencies:
'@shikijs/types': 3.9.2
'@shikijs/types': 3.23.0
'@shikijs/types@3.9.2':
'@shikijs/types@3.23.0':
dependencies:
'@shikijs/vscode-textmate': 10.0.2
'@types/hast': 3.0.4
@@ -6252,13 +6260,17 @@ snapshots:
possible-typed-array-names: 1.1.0
reflect.getprototypeof: 1.0.10
typedoc-plugin-markdown@4.8.1(typedoc@0.28.10(typescript@5.9.2)):
typedoc-plugin-markdown@4.8.1(typedoc@0.28.17(typescript@5.9.2)):
dependencies:
typedoc: 0.28.10(typescript@5.9.2)
typedoc: 0.28.17(typescript@5.9.2)
typedoc@0.28.10(typescript@5.9.2):
typedoc-plugin-no-inherit@1.6.1(typedoc@0.28.17(typescript@5.9.2)):
dependencies:
'@gerrit0/mini-shiki': 3.9.2
typedoc: 0.28.17(typescript@5.9.2)
typedoc@0.28.17(typescript@5.9.2):
dependencies:
'@gerrit0/mini-shiki': 3.23.0
lunr: 2.3.9
markdown-it: 14.1.0
minimatch: 9.0.5

View File

@@ -1,3 +1,9 @@
/**
* This is the TypeScript SDK reference, documenting methods available for interacting with Hatchet resources.
* Check out the [user guide](https://docs.hatchet.run/home/) for an introduction to getting your first tasks running.
*
* @module Hatchet TypeScript SDK Reference
*/
/* eslint-disable no-dupe-class-members */
/* eslint-disable no-underscore-dangle */
import {
@@ -88,6 +94,7 @@ export class HatchetClient<
/**
* @deprecated v0 client will be removed in a future release, please upgrade to v1
* @hidden
*/
get v0() {
if (!this._v0) {
@@ -122,6 +129,7 @@ export class HatchetClient<
* @param config - Optional configuration for the client
* @param options - Optional client options
* @param axiosConfig - Optional Axios configuration for HTTP requests
* @internal
*/
constructor(
config?: Partial<ClientConfig>,
@@ -200,6 +208,7 @@ export class HatchetClient<
* @param options - Optional client options.
* @param axiosConfig - Optional Axios configuration for HTTP requests.
* @returns A new Hatchet client instance. Chain `.withMiddleware()` to attach typed middleware.
* @internal
*/
static init<T extends Record<string, any> = {}, U extends Record<string, any> = {}>(
config?: Omit<Partial<ClientConfig>, 'middleware'>,
@@ -215,6 +224,7 @@ export class HatchetClient<
*
* Use this after `init<T, U>()` to get full middleware return-type inference
* that TypeScript can't provide when global types are explicitly set on `init`.
* @internal
*/
withMiddleware<
const M extends TaskMiddleware<
@@ -380,12 +390,12 @@ export class HatchetClient<
}
/**
* @alias run
* Triggers a workflow run and waits for the result.
* @template I - The input type for the workflow
* @template O - The return type of the workflow
* @param workflow - The workflow to run, either as a Workflow instance or workflow name
* @param input - The input data for the workflow
* @alias run
* @param options - Configuration options for the workflow run
* @returns A promise that resolves with the workflow result
*/
@@ -420,6 +430,7 @@ export class HatchetClient<
/**
* Get the CEL client for debugging CEL expressions
* @returns A CEL client instance
* @internal
*/
get cel() {
if (!this._cel) {
@@ -445,6 +456,7 @@ export class HatchetClient<
* Get the cron client for creating and managing cron workflow runs
* @returns A cron client instance
* @deprecated use client.crons instead
* @hidden
*/
get cron() {
return this.crons;
@@ -467,6 +479,7 @@ export class HatchetClient<
* Get the schedule client for creating and managing scheduled workflow runs
* @returns A schedule client instance
* @deprecated use client.scheduled instead
* @hidden
*/
get schedule() {
return this.scheduled;
@@ -484,6 +497,7 @@ export class HatchetClient<
/**
* Get the dispatcher client for sending action events and managing worker registration
* @returns A dispatcher client instance
* @internal
*/
get dispatcher() {
if (!this._dispatcher) {
@@ -519,6 +533,7 @@ export class HatchetClient<
/**
* Get the durable listener client for managing durable event subscriptions
* @returns A durable listener client instance
* @internal
*/
get durableListener() {
if (!this._durableListener) {
@@ -535,6 +550,7 @@ export class HatchetClient<
/**
* Get the run listener client for streaming workflow run results
* @returns A run listener client instance
* @internal
*/
get listener() {
return this._listener;
@@ -542,6 +558,7 @@ export class HatchetClient<
/**
* @deprecated use client.events instead
* @hidden
*/
get event() {
return this.events;
@@ -672,6 +689,7 @@ export class HatchetClient<
/**
* Get the admin client for creating and managing workflows
* @returns A admin client instance
* @internal
*/
get admin() {
if (!this._admin) {

View File

@@ -10,6 +10,7 @@ import { workflowNameString, WorkflowsClient } from './workflows';
/**
* Schema for creating a Cron Trigger.
* @internal
*/
export const CreateCronTriggerSchema = z.object({
name: z.string(),
@@ -21,11 +22,12 @@ export const CreateCronTriggerSchema = z.object({
/**
* Type representing the input for creating a Cron.
* @internal
*/
export type CreateCronInput = z.infer<typeof CreateCronTriggerSchema>;
/**
* Client for managing Cron Triggers.
* The cron client is a client for managing cron workflows within Hatchet.
*/
export class CronClient {
api: HatchetClient['api'];

View File

@@ -17,6 +17,15 @@ export class FiltersClient {
this.api = client.api;
}
/**
* Lists all filters.
* @param opts - The options for the list operation.
* @param opts.limit - The number of filters to return.
* @param opts.offset - The number of filters to skip before returning the result set.
* @param opts.workflowIds - A list of workflow IDs to filter by.
* @param opts.scopes - A list of scopes to filter by.
* @returns A promise that resolves to the list of filters.
*/
async list(opts?: {
limit?: number;
offset?: number;
@@ -33,21 +42,42 @@ export class FiltersClient {
return data;
}
/**
* Gets a filter by its ID.
* @param filterId - The ID of the filter to get.
* @returns A promise that resolves to the filter.
*/
async get(filterId: Parameters<typeof this.api.v1FilterGet>[1]) {
const { data } = await this.api.v1FilterGet(this.tenantId, filterId);
return data;
}
/**
* Creates a new filter.
* @param opts - The options for the create operation.
* @returns A promise that resolves to the created filter.
*/
async create(opts: Parameters<typeof this.api.v1FilterCreate>[1]) {
const { data } = await this.api.v1FilterCreate(this.tenantId, opts);
return data;
}
/**
* Deletes a filter by its ID.
* @param filterId - The ID of the filter to delete.
* @returns A promise that resolves to the deleted filter.
*/
async delete(filterId: Parameters<typeof this.api.v1FilterDelete>[1]) {
const { data } = await this.api.v1FilterDelete(this.tenantId, filterId);
return data;
}
/**
* Updates a filter by its ID.
* @param filterId - The ID of the filter to update.
* @param updates - The updates to apply to the filter.
* @returns A promise that resolves to the updated filter.
*/
async update(
filterId: Parameters<typeof this.api.v1FilterDelete>[1],
updates: Parameters<typeof this.api.v1FilterUpdate>[2]

View File

@@ -9,7 +9,7 @@ export type TaskStatusMetrics = {
};
/**
* MetricsClient is used to get metrics for workflows
* The metrics client is a client for reading metrics out of Hatchets metrics API.
*/
export class MetricsClient {
tenantId: string;
@@ -21,11 +21,10 @@ export class MetricsClient {
}
/**
* Get task/run status metrics for a tenant.
*
* This backs the dashboard "runs list" status count badges.
*
* Endpoint: GET /api/v1/stable/tenants/{tenant}/task-metrics
* Returns aggregate task run counts grouped by status (queued, running, completed, failed, cancelled)
* @param query - Filters for the metrics query (e.g. `since`, `until`, `workflow_ids`).
* @param requestParams - Optional request-level overrides (headers, signal, etc.).
* @returns Counts per status for the matched task runs.
*/
async getTaskStatusMetrics(
query: Parameters<typeof this.api.v1TaskListStatusMetrics>[1],
@@ -41,6 +40,11 @@ export class MetricsClient {
);
}
/**
* Returns the queue metrics for the current tenant.
* @param opts - The options for the request.
* @returns The queue metrics for the current tenant.
*/
async getQueueMetrics(opts?: Parameters<typeof this.api.tenantGetStepRunQueueMetrics>[1]) {
const { data } = await this.api.tenantGetStepRunQueueMetrics(this.tenantId, opts);
return data;

View File

@@ -20,7 +20,7 @@ export type CreateRateLimitOpts = {
};
/**
* RatelimitsClient is used to manage rate limits for the Hatchet
* The rate limits client is a wrapper for Hatchets gRPC API that makes it easier to work with rate limits in Hatchet.
*/
export class RatelimitsClient {
api: HatchetClient['api'];
@@ -33,11 +33,21 @@ export class RatelimitsClient {
this.tenantId = client.tenantId;
}
/**
* Upserts a rate limit for the current tenant.
* @param opts - The options for the upsert operation.
* @returns A promise that resolves to the key of the upserted rate limit.
*/
async upsert(opts: CreateRateLimitOpts): Promise<string> {
await this.admin.putRateLimit(opts.key, opts.limit, opts.duration);
return opts.key;
}
/**
* Lists all rate limits for the current tenant.
* @param opts - The options for the list operation.
* @returns A promise that resolves to the list of rate limits.
*/
async list(opts: Parameters<typeof this.api.rateLimitList>[1]) {
const { data } = await this.api.rateLimitList(this.tenantId, opts);
return data;

View File

@@ -78,7 +78,7 @@ export interface ListRunsOpts extends RunFilter {
}
/**
* RunsClient is used to list and manage runs
* The runs client is a client for interacting with task and workflow runs within Hatchet.
*/
export class RunsClient {
api: HatchetClient['api'];
@@ -95,6 +95,11 @@ export class RunsClient {
this.listener = client._listener;
}
/**
* Gets a task or workflow run by its ID.
* @param run - The ID of the run to get.
* @returns A promise that resolves to the run.
*/
async get<T = any>(run: string | WorkflowRunRef<T>) {
const runId = typeof run === 'string' ? run : await run.getWorkflowRunId();
@@ -102,6 +107,11 @@ export class RunsClient {
return data;
}
/**
* Gets the status of a task or workflow run by its ID.
* @param run - The ID of the run to get the status of.
* @returns A promise that resolves to the status of the run.
*/
async get_status<T = any>(run: string | WorkflowRunRef<T>) {
const runId = typeof run === 'string' ? run : await run.getWorkflowRunId();
@@ -109,6 +119,11 @@ export class RunsClient {
return data;
}
/**
* Lists all task and workflow runs for the current tenant.
* @param opts - The options for the list operation.
* @returns A promise that resolves to the list of runs.
*/
async list(opts?: Partial<ListRunsOpts>) {
const normalizedOpts =
opts?.parentTaskExternalId && !opts?.parentTaskRunExternalId
@@ -121,6 +136,11 @@ export class RunsClient {
return data;
}
/**
* Cancels a task or workflow run by its ID.
* @param opts - The options for the cancel operation.
* @returns A promise that resolves to the cancelled run.
*/
async cancel(opts: CancelRunOpts) {
const filter = await this.prepareFilter(opts.filters || {});
@@ -130,6 +150,11 @@ export class RunsClient {
});
}
/**
* Replays a task or workflow run by its ID.
* @param opts - The options for the replay operation.
* @returns A promise that resolves to the replayed run.
*/
async replay(opts: ReplayRunOpts) {
const filter = await this.prepareFilter(opts.filters || {});
return this.api.v1TaskReplay(this.tenantId, {
@@ -187,10 +212,20 @@ export class RunsClient {
};
}
/**
* Creates a run reference for a task or workflow run by its ID.
* @param id - The ID of the run to create a reference for.
* @returns A promise that resolves to the run reference.
*/
runRef<T extends Record<string, any> = any>(id: string): WorkflowRunRef<T> {
return new WorkflowRunRef<T>(id, this.listener, this);
}
/**
* Subscribes to a stream of events for a task or workflow run by its ID.
* @param workflowRunId - The ID of the run to subscribe to.
* @returns A promise that resolves to the stream of events.
*/
async *subscribeToStream(workflowRunId: string): AsyncIterableIterator<string> {
const ref = this.runRef(workflowRunId);
const stream = await ref.stream();

View File

@@ -15,6 +15,7 @@ import { HatchetClient } from '../client';
import { workflowNameString, WorkflowsClient } from './workflows';
/**
* Schema for creating a Scheduled Run Trigger.
* @internal
*/
export const CreateScheduledRunTriggerSchema = z.object({
triggerAt: z.coerce.date(),
@@ -25,11 +26,13 @@ export const CreateScheduledRunTriggerSchema = z.object({
/**
* Type representing the input for creating a Cron.
* @internal
*/
export type CreateScheduledRunInput = z.infer<typeof CreateScheduledRunTriggerSchema>;
/**
* Schema for updating (rescheduling) a Scheduled Run Trigger.
* @internal
*/
export const UpdateScheduledRunTriggerSchema = z.object({
triggerAt: z.coerce.date(),
@@ -38,7 +41,7 @@ export const UpdateScheduledRunTriggerSchema = z.object({
export type UpdateScheduledRunInput = z.infer<typeof UpdateScheduledRunTriggerSchema>;
/**
* Client for managing Scheduled Runs.
* The scheduled client is a client for managing scheduled workflows within Hatchet
*/
export class ScheduleClient {
api: HatchetClient['api'];

View File

@@ -1,3 +1,6 @@
/**
* @module Tenant Client
*/
import { Tenant } from '@hatchet/clients/rest/generated/data-contracts';
import { HatchetClient } from '../client';

View File

@@ -41,10 +41,10 @@ function toCreateWebhookRequest(options: CreateWebhookOptions): V1CreateWebhookR
/**
* Client for managing incoming webhooks in Hatchet.
*
* Webhooks allow external systems to trigger Hatchet workflows by sending HTTP
* requests to dedicated endpoints. This enables real-time integration with
* third-party services like GitHub, Stripe, Slack, or any system that can send
* webhook events.
* Webhooks allow external systems to trigger Hatchet workflows by sending
* HTTP requests to dedicated endpoints. This enables real-time integration
* with third-party services like GitHub, Stripe, Slack, or any system that
* can send webhook events.
*/
export class WebhooksClient {
api: HatchetClient['api'];
@@ -55,6 +55,11 @@ export class WebhooksClient {
this.tenantId = client.tenantId;
}
/**
* Lists all webhooks for the current tenant.
* @param options - The options for the list operation.
* @returns A promise that resolves to the list of webhooks.
*/
async list(options?: {
limit?: number;
offset?: number;
@@ -70,17 +75,33 @@ export class WebhooksClient {
return response.data;
}
/**
* Gets a webhook by its name.
* @param webhookName - The name of the webhook to get.
* @returns A promise that resolves to the webhook.
*/
async get(webhookName: string): Promise<V1Webhook> {
const response = await this.api.v1WebhookGet(this.tenantId, webhookName);
return response.data;
}
/**
* Creates a new webhook.
* @param request - The request options for the create operation.
* @returns A promise that resolves to the created webhook.
*/
async create(request: CreateWebhookOptions): Promise<V1Webhook> {
const payload = toCreateWebhookRequest(request);
const response = await this.api.v1WebhookCreate(this.tenantId, payload);
return response.data;
}
/**
* Updates a webhook by its name.
* @param webhookName - The name of the webhook to update.
* @param options - The options for the update operation.
* @returns A promise that resolves to the updated webhook.
*/
async update(
webhookName: string,
options: Partial<V1UpdateWebhookRequest> = {}
@@ -93,6 +114,11 @@ export class WebhooksClient {
return response.data;
}
/**
* Deletes a webhook by its name.
* @param webhookName - The name of the webhook to delete.
* @returns A promise that resolves to the deleted webhook.
*/
async delete(webhookName: string): Promise<V1Webhook> {
const response = await this.api.v1WebhookDelete(this.tenantId, webhookName);
return response.data;

View File

@@ -1,7 +1,7 @@
import { HatchetClient } from '../client';
/**
* WorkersClient is used to list and manage workers
* The workers client is a client for managing workers programmatically within Hatchet.
*/
export class WorkersClient {
api: HatchetClient['api'];
@@ -12,21 +12,40 @@ export class WorkersClient {
this.tenantId = client.tenantId;
}
/**
* Get a worker by its ID.
* @param workerId - The ID of the worker to get.
* @returns A promise that resolves to the worker.
*/
async get(workerId: string) {
const { data } = await this.api.workerGet(workerId);
return data;
}
/**
* List all workers in the tenant.
* @returns A promise that resolves to the list of workers.
*/
async list() {
const { data } = await this.api.workerList(this.tenantId);
return data;
}
/**
* Check if a worker is paused.
* @param workerId - The ID of the worker to check.
* @returns A promise that resolves to true if the worker is paused, false otherwise.
*/
async isPaused(workerId: string) {
const wf = await this.get(workerId);
return wf.status === 'PAUSED';
}
/**
* Pause a worker.
* @param workerId - The ID of the worker to pause.
* @returns A promise that resolves to the paused worker.
*/
async pause(workerId: string) {
const { data } = await this.api.workerUpdate(workerId, {
isPaused: true,
@@ -34,6 +53,11 @@ export class WorkersClient {
return data;
}
/**
* Unpause a worker.
* @param workerId - The ID of the worker to unpause.
* @returns A promise that resolves to the unpaused worker.
*/
async unpause(workerId: string) {
const { data } = await this.api.workerUpdate(workerId, {
isPaused: false,

View File

@@ -26,7 +26,10 @@ export const workflowNameString = (
};
/**
* WorkflowsClient is used to list and manage workflows
* The workflows client is a client for managing workflows programmatically within Hatchet.
*
* NOTE: that workflows are the declaration, not the individual runs. If you're looking for runs, use the RunsClient instead.
*
*/
export class WorkflowsClient {
api: HatchetClient['api'];
@@ -79,6 +82,11 @@ export class WorkflowsClient {
return str;
}
/**
* Get a workflow by its name, ID, or object.
* @param workflow - The workflow name, ID, or object.
* @returns A promise that resolves to the workflow.
*/
async get(workflow: string | BaseWorkflowDeclaration<any, any> | LegacyWorkflow) {
// Get workflow name string
const name = workflowNameString(workflow);
@@ -119,11 +127,21 @@ export class WorkflowsClient {
}
}
/**
* List all workflows in the tenant.
* @param opts - The options for the list operation.
* @returns A promise that resolves to the list of workflows.
*/
async list(opts?: Parameters<typeof this.api.workflowList>[1]) {
const { data } = await this.api.workflowList(this.tenantId, opts);
return data;
}
/**
* Delete a workflow by its name, ID, or object.
* @param workflow - The workflow name, ID, or object.
* @returns A promise that resolves to the deleted workflow.
*/
async delete(workflow: string | BaseWorkflowDeclaration<any, any> | LegacyWorkflow) {
const name = workflowNameString(workflow);

View File

@@ -1,3 +1,12 @@
/**
* The Hatchet Context class provides helper methods and useful data to tasks at runtime. It is passed as the second argument to all tasks and durable tasks.
*
* There are two types of context classes you'll encounter:
*
* - Context - The standard context for regular tasks with methods for logging, task output retrieval, cancellation, and more.
* - DurableContext - An extended context for durable tasks that includes additional methods for durable execution.
* @module Context
*/
/* eslint-disable no-underscore-dangle */
/* eslint-disable max-classes-per-file */
import {
@@ -193,6 +202,7 @@ export class Context<T, K = {}> {
* @returns A record mapping task names to error messages.
* @throws A warning if no errors are found (this method should be used in on-failure tasks).
* @deprecated use ctx.errors() instead
* @hidden
*/
stepRunErrors(): Record<string, string> {
return this.errors();
@@ -299,6 +309,7 @@ export class Context<T, K = {}> {
* Gets the ID of the current task run.
* @returns The task run ID.
* @deprecated use taskRunExternalId() instead
* @hidden
*/
taskRunId(): string {
return this.taskRunExternalId();
@@ -317,6 +328,7 @@ export class Context<T, K = {}> {
* @param message - The message to log.
* @param level - The log level (optional).
* @deprecated use ctx.logger.infoger.info, ctx.logger.infoger.debug, ctx.logger.infoger.warn, ctx.logger.infoger.error, ctx.logger.infoger.trace instead
* @hidden
*/
log(message: string, level?: LogLevel, extra?: LogExtra) {
const { taskRunExternalId } = this.action;
@@ -630,6 +642,7 @@ export class Context<T, K = {}> {
* @returns The output of the task.
* @throws An error if the task output is not found.
* @deprecated use ctx.parentOutput instead
* @hidden
*/
stepOutput<L = NextStep>(step: string): L {
if (!this.data.parents) {
@@ -645,6 +658,7 @@ export class Context<T, K = {}> {
* Gets the input data for the current workflow.
* @returns The input data for the workflow.
* @deprecated use task input parameter instead
* @hidden
*/
workflowInput(): T {
return this.input;
@@ -654,6 +668,7 @@ export class Context<T, K = {}> {
* Gets the name of the current task.
* @returns The name of the task.
* @deprecated use ctx.taskName instead
* @hidden
*/
stepName(): string {
return this.taskName();
@@ -665,6 +680,7 @@ export class Context<T, K = {}> {
* @param workflows - An array of objects containing the workflow name, input data, and options for each workflow.
* @returns A list of references to the spawned workflow runs.
* @deprecated Use bulkRunNoWaitChildren or bulkRunChildren instead.
* @hidden
*/
async spawnWorkflows<Q extends JsonObject = any, P extends JsonObject = any>(
workflows: Array<{
@@ -750,6 +766,7 @@ export class Context<T, K = {}> {
* @param options - Additional options for spawning the workflow.
* @returns A reference to the spawned workflow run.
* @deprecated Use runChild or runNoWaitChild instead.
* @hidden
*/
async spawnWorkflow<Q extends JsonObject, P extends JsonObject>(
workflow: string | WorkflowV1<Q, P> | TaskWorkflowDeclaration<Q, P>,
@@ -807,6 +824,10 @@ export class Context<T, K = {}> {
}
}
/**
* DurableContext provides helper methods and useful data to durable tasks at runtime.
* It extends the Context class and includes additional methods for durable execution like sleepFor and waitFor.
*/
export class DurableContext<T, K = {}> extends Context<T, K> {
waitKey: number = 0;

View File

@@ -1,3 +1,10 @@
/**
* `Runnables` in the Hatchet TypeScript SDK are things that can be run, namely tasks and workflows. The two main types of runnables you'll encounter are:
*
* - `WorkflowDeclaration`, returned by `hatchet.workflow(...)`, which lets you define tasks and call `run()`, `schedule()`, `cron()`, etc.
* - `TaskWorkflowDeclaration`, returned by `hatchet.task(...)`, which is a single standalone task that exposes the same execution helpers as a workflow.
* @module Runnables
*/
/* eslint-disable max-classes-per-file */
/* eslint-disable no-underscore-dangle */
/* eslint-disable no-dupe-class-members */
@@ -42,6 +49,7 @@ type AdditionalMetadata = Record<string, string>;
/**
* Options for running a workflow.
* @hidden
*/
export type RunOpts = {
/**
@@ -78,12 +86,14 @@ export type RunOpts = {
/**
* Helper type to safely extract output types from task results
* @hidden
*/
export type TaskOutput<O, Key extends string, Fallback> =
O extends Record<Key, infer Value> ? (Value extends OutputType ? Value : Fallback) : Fallback;
/**
* Extracts a property from an object type based on task name, or falls back to inferred type
* @hidden
*/
export type TaskOutputType<
O,
@@ -103,6 +113,7 @@ type DefaultFilter = Omit<V1CreateFilterRequest, 'workflowId'>;
* Prefer using `StickyStrategy.SOFT` / `StickyStrategy.HARD` (v1, non-protobuf).
* For backwards compatibility, the workflow/task `sticky` field also accepts legacy
* protobuf enum values (`0`/`1`) and strings (`'SOFT'`/`'HARD'`).
* @internal
*/
export const StickyStrategy = {
SOFT: 'soft',
@@ -183,6 +194,7 @@ export type CreateDurableTaskWorkflowOpts<
/**
* Options for creating a new workflow.
* @hidden
*/
export type CreateWorkflowOpts = CreateBaseWorkflowOpts & {
/**
@@ -194,6 +206,7 @@ export type CreateWorkflowOpts = CreateBaseWorkflowOpts & {
/**
* Default configuration for all tasks in the workflow.
* Can be overridden by task-specific options.
* @hidden
*/
export type TaskDefaults = {
/**
@@ -249,6 +262,7 @@ export type TaskDefaults = {
/**
* Internal definition of a workflow and its tasks.
* @hidden
*/
export type WorkflowDefinition = CreateWorkflowOpts & {
/**
@@ -280,6 +294,7 @@ export type WorkflowDefinition = CreateWorkflowOpts & {
* Represents a workflow that can be executed by Hatchet.
* @template I The input type for the workflow.
* @template O The return type of the workflow.
* @internal
*/
export class BaseWorkflowDeclaration<
I extends InputType = UnknownInputType,
@@ -287,11 +302,13 @@ export class BaseWorkflowDeclaration<
> {
/**
* The Hatchet client instance used to execute the workflow.
* @internal
*/
client: IHatchetClient | undefined;
/**
* The internal workflow definition.
* @internal
*/
definition: WorkflowDefinition;
@@ -299,6 +316,7 @@ export class BaseWorkflowDeclaration<
* Creates a new workflow instance.
* @param options The options for creating the workflow.
* @param client Optional Hatchet client instance.
* @internal
*/
constructor(options: CreateWorkflowOpts, client?: IHatchetClient) {
this.definition = {
@@ -311,7 +329,7 @@ export class BaseWorkflowDeclaration<
}
/**
* Triggers a workflow run without waiting for completion.
* Synchronously trigger a workflow run without waiting for it to complete. This method is useful for starting a workflow run and immediately returning a reference to the run without blocking while the workflow runs.
* @param input The input data for the workflow.
* @param options Optional configuration for this workflow run.
* @returns A WorkflowRunRef containing the run ID and methods to get results and interact with the run.
@@ -633,6 +651,7 @@ export class BaseWorkflowDeclaration<
/**
* @deprecated use definition.name instead
* @hidden
*/
get id() {
return this.definition.name;
@@ -647,6 +666,44 @@ export class BaseWorkflowDeclaration<
}
}
/**
* A Hatchet workflow, which lets you define tasks and perform actions on the workflow.
*
* Workflows in Hatchet represent coordinated units of work that can be triggered,
* scheduled, or run on a cron schedule. Each workflow can contain multiple tasks
* that can be arranged in dependencies (DAGs), with customized retry behavior,
* timeouts, concurrency controls, and more.
*
* Example:
* ```typescript
* import { hatchet } from './hatchet-client';
*
* type MyInput = { name: string };
*
* const workflow = hatchet.workflow<MyInput>({
* name: 'my-workflow',
* });
*
* workflow.task({
* name: 'greet',
* fn: async (input) => {
* return { message: `Hello, ${input.name}!` };
* },
* });
*
* // Run the workflow
* await workflow.run({ name: 'World' });
* ```
*
* Workflows support various execution patterns, including:
* - One-time execution with `run()` and `runNoWait()`
* - Scheduled execution with `schedule()`
* - Cron-based recurring execution with `cron()`
* - Bulk execution by passing an array input to `run()` and `runNoWait()`
*
* Tasks within workflows can be defined with `workflow.task()` or
* `workflow.durableTask()` and arranged into complex dependency patterns.
*/
export class WorkflowDeclaration<
I extends InputType = UnknownInputType,
O extends OutputType = void,
@@ -804,10 +861,26 @@ export class WorkflowDeclaration<
}
/**
* A standalone task workflow that can be run, scheduled, or triggered via cron.
* A standalone task declaration that can be run like a workflow.
*
* @template I - The task-specific input type.
* @template O - The task output type.
* `TaskWorkflowDeclaration` is returned by `hatchet.task(...)` and wraps a single
* task definition while exposing the same execution helpers as workflows, such as
* `run()`, `runNoWait()`, `schedule()`, and `cron()` (inherited from
* `BaseWorkflowDeclaration`).
*
* Example:
* ```typescript
* const greet = hatchet.task<{ name: string }, { message: string }>({
* name: 'greet',
* fn: async (input) => ({ message: `Hello, ${input.name}!` }),
* });
*
* await greet.run({ name: 'World' });
* const ref = await greet.runNoWait({ name: 'World' });
* ```
*
* @template I The input type for the standalone task.
* @template O The output type returned by the standalone task.
* @template GlobalInput - Global input type from the client, merged into all run/schedule/cron input signatures.
* @template MiddlewareBefore - Extra fields added to the task fn input by pre-middleware hooks.
* @template MiddlewareAfter - Extra fields merged into the task output by post-middleware hooks.
@@ -842,6 +915,7 @@ export class TaskWorkflowDeclaration<
input: I & GlobalInput,
options?: RunOpts
): Promise<O & Resolved<GlobalOutput, MiddlewareAfter>>;
/** @hidden */
async runAndWait(
input: (I & GlobalInput)[],
options?: RunOpts
@@ -871,6 +945,7 @@ export class TaskWorkflowDeclaration<
input: I & GlobalInput,
options?: RunOpts
): Promise<O & Resolved<GlobalOutput, MiddlewareAfter>>;
/** @hidden */
async run(
input: (I & GlobalInput)[],
options?: RunOpts
@@ -967,7 +1042,7 @@ export class TaskWorkflowDeclaration<
return super.cron(name, expression, input, options);
}
/** Returns the underlying task definition for this declaration. */
// Returns the underlying task definition for this declaration.
get taskDef() {
return this.definition._tasks[0];
}

View File

@@ -1,5 +1,5 @@
{
"include": ["src/**/*.ts"],
"include": ["src/**/*.ts", "docs/**/*.ts"],
"exclude": [
"./dist",
"**/*.test-d.ts" // NOTE: disable this if modifying types.test-d.ts

View File

@@ -1,6 +1,72 @@
{
"$schema": "https://typedoc.org/schema.json",
"entryPoints": ["./src/index.ts"],
"out": "docs",
"plugin": ["typedoc-plugin-markdown"]
"entryPoints": [
"./src/v1/client/client.ts",
"./src/v1/client/worker/context.ts",
"./src/v1/declaration.ts",
"./src/v1/client/features/crons.ts",
"./src/v1/client/features/filters.ts",
"./src/v1/client/features/metrics.ts",
"./src/v1/client/features/ratelimits.ts",
"./src/v1/client/features/runs.ts",
"./src/v1/client/features/schedules.ts",
"./src/v1/client/features/workers.ts",
"./src/v1/client/features/workflows.ts",
"./src/v1/client/features/webhooks.ts"
],
"entryPointStrategy": "expand",
"out": "/tmp/hatchet-typescript/docs/gen",
"plugin": ["typedoc-plugin-markdown", "typedoc-plugin-no-inherit", "./docs/markdown-theme.mjs"],
"name": "Hatchet TypeScript SDK",
"readme": "none",
"excludePrivate": true,
"excludeProtected": true,
"excludeInternal": true,
"excludeReferences": true,
"includeVersion": true,
"disableSources": true,
"excludeNotDocumented": true,
"excludeNotDocumentedKinds": [
"Namespace",
"Enum",
"EnumMember",
"Variable",
"Function",
"Interface",
"Constructor",
"Property",
"Method",
"CallSignature",
"IndexSignature",
"ConstructorSignature",
"Accessor",
"GetSignature",
"SetSignature",
"TypeAlias",
"Reference"
],
"sort": ["alphabetical"],
"hideGenerator": true,
"theme": "hatchet-ts-docs",
// typedoc-plugin-markdown options
"router": "module",
"flattenOutputFiles": true,
"fileExtension": ".mdx",
"hidePageHeader": true,
"hideBreadcrumbs": true,
"hidePageTitle": false,
"useCodeBlocks": true,
"useHTMLAnchors": true,
"expandObjects": false,
"hideGroupHeadings": false,
"maxTypeConversionDepth": 3,
"parametersFormat": "table",
"enumMembersFormat": "table",
"typeDeclarationFormat": "table",
"propertiesFormat": "table",
"classPropertiesFormat": "table",
"sanitizeComments": true,
// typedoc-plugin-no-inherit options
"inheritNone": true
}