# API Sequences

API Sequences are the API-only counterpart to browser workflows. Instead of
driving a browser node-by-node, an API sequence is a single node
(`nodeType: "api_sequence"`) inside an api-only workflow that executes an
ordered list of HTTP calls, chaining outputs from one step into the inputs
of the next.

## When to use

- Exercise an API without a UI (integration tests, fixture setup).
- Seed or tear down state via API before/after a browser run.
- Fast, deterministic smoke test of a critical flow.

## Config shape (ApiSequenceConfig)

```jsonc
{
  "steps":         [ ... ],       // ordered; required
  "description":   "...",         // optional
  "stopOnFailure": true,          // default: true
  "exports":       [ ... ]        // optional; see below
}
```

## Step shape (ApiSequenceStep)

The authoritative type is in `packages/types/src/api-sequence.ts`. Key fields:

```jsonc
{
  "stepId":         "createProject",      // optional; defaults to "step{index}"
  "apiRequestId":   "<catalog id>",       // required — points to api_requests row
  "credentialId":   "<uuid>" | null,      // null = unauthenticated
  "credentialTemplateId": "<uuid>" | null, // auth by persona/template (per-env); wins over credentialId
  "credentialTemplateName": "<persona>",   // author-friendly alias for the above; resolved to the id on save
  "method":         "POST",               // optional; falls back to catalog default
  "urlTemplate":    "/projects/{{createProject.response.id}}",
  "queryParams":    [ { "key": "limit", "value": "10" } ],
  "bodyTemplate":   "{\"name\": \"$EMAIL()\"}",   // STRING (JSON), not object
  "headersTemplate": { "X-Trace": "$UUID()" },    // optional
  "responseVariableName": "createProject",         // optional alias for stepId
  "expectedStatusCodes":  [200, 201],             // step fails if status is outside
  "description":    "...",                        // optional UI label
  "validations":    [ ... ],                      // assertions against the response
  "validationMode": "all"                         // "all" (default) or "any" validation must pass
}
```

### Credential roles

`credentialId` is overloaded; two distinct uses exist:

- Step-level `credentialId` (and a top-level/default credential on the
  sequence) is AUTH: it's what the api-sequence runner uses to
  authenticate each HTTP call. Editing this changes who is calling.

- Step-level `credentialTemplateId` is AUTH-by-persona: instead of a fixed
  credential id, name a credential template/persona and the runner resolves
  it to the credential bound for the run's environment (mirrors a login
  node's from_template). Takes precedence over `credentialId`. Use this when
  the same sequence must run across environments (e.g. Dev + a sandbox that
  mints its own per-instance credential) rather than a single static id.

- `credentialId` appearing INSIDE a step's `bodyTemplate` JSON string is
  DATA: it gets written into the request body and becomes part of the
  provisioned resource (e.g. the credential a created workflow logs in
  with). Editing this changes what the call creates.

The two are independent. Swapping the auth credential won't change what
the call provisions; swapping the body credential won't change auth.
Mixing them up silently produces confusing test failures.

`apiRequestId` references a row in the `api_requests` table. Discover IDs
from the API catalog for the target property. If `urlTemplate`, `method`,
or `bodyTemplate` are omitted, they are backfilled from the catalog entry's
defaults at execution time. A custom step that calls a URL directly uses
`"apiRequestId": ""` and sets `method` and `urlTemplate` itself.

`bodyTemplate` is a JSON *string*, not a JSON object — templates and macros
are interpolated into it as raw text before parsing.

### Multipart uploads

To send multipart/form-data instead of a raw body, set
`formParts` on the step and omit `bodyTemplate`. The two are mutually
exclusive; there is no separate mode field, a step is multipart exactly when
`formParts` is present. Each part is either text or file:

```json
"formParts": [
  { "kind": "text", "name": "projectId", "value": "$var.project_id" },
  { "kind": "file", "name": "file", "attachmentId": "<uuid>" }
]
```

A text part's `value` supports the same macro/variable/step-reference syntax
as `bodyTemplate`. A file part names an attachment by UUID; add `filename`
to override the name sent in Content-Disposition, otherwise the
attachment's own filename is used. Don't set a `Content-Type` header on a
multipart step: the transport generates its own boundary-bearing header at
request time, so any author-supplied `Content-Type` is stripped rather than
allowed to shadow it with a stale or missing boundary.

### API login credentials

Use these for token exchanges that precede the
sequence request. POST bodies support `application/json`,
`application/x-www-form-urlencoded`, and `text/xml`. With no body template,
form fields are URL-encoded automatically. JSON token responses use normal
dot paths such as `access_token`; XML/SOAP responses are parsed with namespace
prefixes removed, so a Salesforce session path is
`Envelope.Body.loginResponse.result.sessionId`. Keep returned tokens inside
the Credential boundary — do not export them as workflow variables. Token
request headers (for example Salesforce `SOAPAction=login`) are encrypted with
the Credential and apply only to the token exchange.

## Template syntax

Three ways to inject dynamic values. All three can appear in the same
string (`urlTemplate`, `bodyTemplate`, `headersTemplate` values, or `queryParams`
values).

### 1. Step references — outputs of prior steps

```text
{{stepId.response.path.to.value}}
```

The `.response.` segment is REQUIRED. This is the most common foot-gun:

```text
✓ {{createProject.response.data.id}}
✗ {{createProject.data.id}}       — missing .response., will warn at
                                    runtime and resolve to undefined
✗ {{projectId}}                   — no step reference at all
```

The executor logs a warning for malformed references but does NOT
block execution — a malformed template resolves to an empty string and
the request goes out anyway. Always run once and check the run log.

### 2. Macros — dynamic data generated fresh per run

```text
$UUID()                 Random UUID v4
$NOW()                  ISO 8601 timestamp (UTC)
$NOW(+5m)               ISO timestamp shifted by +5m / -2h / 30s / 1d
$NOW(+5m, 'm H * * *')  Shifted time rendered in UTC (see macros guide);
                        single-quote the format inside a JSON bodyTemplate
$TODAY()                YYYY-MM-DD
$DATE(N)                Date offset by N days
$TIMESTAMP()            Unix ms
$RANDOM_INT(min,max)    Random integer in range
$PICK(a,b,c)            One listed value at random
$RANDOM_STRING(N)       Alphanumeric string of length N
$EMAIL()                test-<rand>@example-test.com
$FIRST_NAME()           Random first name
$LAST_NAME()            Random last name
$PHONE()                +1-555-...
$SEQUENCE("name")       Per-run auto-increment counter
```

Each run resolves macros independently. `$SEQUENCE` counters persist
across steps within a single run.

### 3. Workflow variables — values injected by the workflow runtime

```text
$var.<name>
```

These come from two places:

- a) Upstream credential variables — pre-provisioned before the
  sequence runs. Typical names: `$var.credential.username`,
  `$var.credential.password`, `$var.credential.email`. If the
  workflow has a credential, USE these for the matching fields
  instead of `$EMAIL()` / `$RANDOM_STRING(6)` — the values must
  match the already-provisioned account.

- b) Upstream exports — values exported by earlier nodes in the same
  workflow (e.g. a seed step produced `$var.project_id`).

Naming convention for exported variables: `resource_field` with
underscores (e.g. `project_id`, `user_email`).

## Exports

After all steps finish, the sequence can register values from the final
state into the workflow variable registry for downstream nodes:

```jsonc
{
  "exports": [
    {
      "variableName": "project_id",        // appears as $var.project_id
      "stepId":       "createProject",
      "responsePath": "data.id",
      "source":       "response",           // "response" (default) | "request"
      "description":  "..."                 // optional UI label
    }
  ]
}
```

Only export fields downstream nodes actually need. Use the
`resource_field` naming convention.

## Validations

`validationMode` is "all" by default: every configured validation must pass.
Set it to "any" to require at least one configured validation. The expected
HTTP status requirement must still pass independently. Individual validation
results retain their pass/fail values even when another alternative passes.

Per-step assertions against the response. Each validation:

```jsonc
{
  "left":     "createProject.response.data.status",  // "stepId.path" form
  "operator": "equals",                              // see list
  "right":    "active",                              // omit for is_set/is_not_set
  "description": "..."
}
```

Operators: `equals`, `not_equals`, `gt`, `lt`, `gte`, `lte`, `contains`, `not_contains`,
`is_set`, `is_not_set`.

## What is validated at commit time

Save/update routes reject malformed step fields, unknown validation modes,
invalid HTTP status codes, duplicate step IDs, invalid step references,
unknown macros, and invalid exports. `validationMode` accepts only "all"
or "any"; omitting it keeps all-checks behavior.

Saving does not call the target API or prove its response. Smoke-test the
sequence before relying on it in a workflow.

CLI users: see `cofactor workflow guide cli-api-sequences` for command usage.

## Example (3-step sequence, correct shape)

```json
{
  "description": "Create an item, fetch it, delete it",
  "stopOnFailure": true,
  "steps": [
    {
      "stepId":       "create",
      "apiRequestId": "<POST /items id>",
      "credentialId": null,
      "method":       "POST",
      "bodyTemplate": "{\"name\": \"item-$RANDOM_STRING(6)\"}",
      "expectedStatusCodes": [201]
    },
    {
      "stepId":       "fetch",
      "apiRequestId": "<GET /items/:id id>",
      "credentialId": null,
      "method":       "GET",
      "urlTemplate":  "/items/{{create.response.id}}",
      "expectedStatusCodes": [200],
      "validations": [
        { "left": "fetch.response.name", "operator": "is_set" }
      ]
    },
    {
      "stepId":       "remove",
      "apiRequestId": "<DELETE /items/:id id>",
      "credentialId": null,
      "method":       "DELETE",
      "urlTemplate":  "/items/{{create.response.id}}",
      "expectedStatusCodes": [200, 204]
    }
  ],
  "exports": [
    { "variableName": "item_id", "stepId": "create", "responsePath": "id" }
  ]
}
```

## Tips

- Give every step a short, stable `stepId`. Later steps and exports
  reference it; the default `stepN` label is brittle to reordering.
- Always include `.response.` in step references. The runtime won't
  error out, but values will silently resolve to empty strings.
- Prefer `$EMAIL()`, `$UUID()`, `$RANDOM_STRING(6)` for fields that must
  be unique per run — unless the workflow has an upstream credential,
  in which case use `$var.credential.username` / `.password` / `.email`.
- Set `expectedStatusCodes` on every step so unexpected 4xx/5xx fails
  the step instead of silently flowing into the next template.
- `bodyTemplate` is a JSON STRING. Escape inner quotes.
- `workflow api-sequence generate` can AI-draft a config from a prompt
  or a prior browser run; refine with `update`. The generated output is
  just JSON — review it before committing.
