cliodot 1.0.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +751 -13
- package/dist/ConnectorBuilder.js +1 -1
- package/dist/Flosync.d.ts +11 -0
- package/dist/Flosync.d.ts.map +1 -1
- package/dist/Flosync.js +1 -1
- package/dist/FlosyncClient.d.ts +2 -0
- package/dist/FlosyncClient.d.ts.map +1 -1
- package/dist/FlosyncClient.js +1 -1
- package/dist/FunctionBuilder.js +1 -1
- package/dist/OAuthAppClient.d.ts +17 -0
- package/dist/OAuthAppClient.d.ts.map +1 -0
- package/dist/OAuthAppClient.js +1 -0
- package/dist/ValidatorBuilder.js +1 -1
- package/dist/WorkflowBuilder.d.ts +6 -3
- package/dist/WorkflowBuilder.d.ts.map +1 -1
- package/dist/WorkflowBuilder.js +1 -1
- package/dist/__tests__/OAuthAppClient.test.d.ts +2 -0
- package/dist/__tests__/OAuthAppClient.test.d.ts.map +1 -0
- package/dist/__tests__/OAuthAppClient.test.js +1 -0
- package/dist/__tests__/function.test.js +1 -1
- package/dist/__tests__/parse-api-error.test.d.ts +2 -0
- package/dist/__tests__/parse-api-error.test.d.ts.map +1 -0
- package/dist/__tests__/parse-api-error.test.js +1 -0
- package/dist/__tests__/runner.test.js +1 -1
- package/dist/connectors/builtin.d.ts +30 -0
- package/dist/connectors/builtin.d.ts.map +1 -1
- package/dist/connectors/builtin.js +1 -1
- package/dist/connectors/registry.d.ts +396 -18
- package/dist/connectors/registry.d.ts.map +1 -1
- package/dist/connectors/registry.js +1 -1
- package/dist/decorators/build.d.ts +1 -0
- package/dist/decorators/build.d.ts.map +1 -1
- package/dist/decorators/build.js +1 -1
- package/dist/decorators/connector.d.ts +14 -0
- package/dist/decorators/connector.d.ts.map +1 -0
- package/dist/decorators/connector.js +1 -0
- package/dist/decorators/index.d.ts +4 -3
- package/dist/decorators/index.d.ts.map +1 -1
- package/dist/decorators/index.js +1 -1
- package/dist/decorators/metadata.d.ts +44 -7
- package/dist/decorators/metadata.d.ts.map +1 -1
- package/dist/decorators/metadata.js +1 -1
- package/dist/decorators/steps.d.ts +31 -11
- package/dist/decorators/steps.d.ts.map +1 -1
- package/dist/decorators/steps.js +1 -1
- package/dist/decorators/workflow.js +1 -1
- package/dist/errors.d.ts +3 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +1 -1
- package/dist/http/parse-api-error.d.ts +4 -0
- package/dist/http/parse-api-error.d.ts.map +1 -0
- package/dist/http/parse-api-error.js +1 -0
- package/dist/http/sanitize-execution-headers.d.ts +7 -0
- package/dist/http/sanitize-execution-headers.d.ts.map +1 -0
- package/dist/http/sanitize-execution-headers.js +1 -0
- package/dist/index.d.ts +8 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/runner/ProcessorEngine.d.ts.map +1 -1
- package/dist/runner/ProcessorEngine.js +1 -1
- package/dist/runner/connector.executor.d.ts.map +1 -1
- package/dist/runner/connector.executor.js +1 -1
- package/dist/runner/utilities/math.executor.js +1 -1
- package/dist/runner/utilities/random.executor.js +1 -1
- package/dist/runner/utilities/string.executor.js +1 -1
- package/dist/template.js +1 -1
- package/dist/transformers/StepsToNodesTransformer.d.ts.map +1 -1
- package/dist/transformers/StepsToNodesTransformer.js +1 -1
- package/dist/transformers/WorkflowTransformer.d.ts.map +1 -1
- package/dist/transformers/WorkflowTransformer.js +1 -1
- package/dist/types/builtin.d.ts +92 -3
- package/dist/types/builtin.d.ts.map +1 -1
- package/dist/types/builtin.js +1 -1
- package/dist/types/client.api.d.ts +11 -4
- package/dist/types/client.api.d.ts.map +1 -1
- package/dist/types/client.api.js +1 -1
- package/dist/types/connector.js +1 -1
- package/dist/types/context.d.ts +75 -0
- package/dist/types/context.d.ts.map +1 -0
- package/dist/types/context.js +1 -0
- package/dist/types/function.js +1 -1
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js +1 -1
- package/dist/types/oauth-app.api.d.ts +138 -0
- package/dist/types/oauth-app.api.d.ts.map +1 -0
- package/dist/types/oauth-app.api.js +1 -0
- package/dist/types/validator.js +1 -1
- package/dist/types/workflow.d.ts +132 -7
- package/dist/types/workflow.d.ts.map +1 -1
- package/dist/types/workflow.js +1 -1
- package/dist/validators/validators.d.ts +16 -1
- package/dist/validators/validators.d.ts.map +1 -1
- package/dist/validators/validators.js +1 -1
- package/dist/variable.d.ts +11 -0
- package/dist/variable.d.ts.map +1 -1
- package/dist/variable.js +1 -1
- package/package.json +8 -5
package/README.md
CHANGED
|
@@ -79,7 +79,8 @@ Pass a `body` (or plain object) as the trigger; the engine treats it as `trigger
|
|
|
79
79
|
| Field | Description |
|
|
80
80
|
|-------|-------------|
|
|
81
81
|
| `body` / `data` | Request body; use `v.body('account')`, `v.body('email')` |
|
|
82
|
-
| `headers` | HTTP headers (`v.header('x-api-key')`) |
|
|
82
|
+
| `headers` | Simulated HTTP headers for the run (`v.header('x-api-key')`); merged with `executionHeaders` (see below) |
|
|
83
|
+
| `executionHeaders` | Extra headers merged after `headers` (same sanitization); useful to separate trigger data from auth headers |
|
|
83
84
|
| `pathParams` | Route params (`v.pathParam('id')`) |
|
|
84
85
|
| `params` | Extra params (`v.param('page')`) |
|
|
85
86
|
| `query` | Query string params (`v.query('filter')`) |
|
|
@@ -91,6 +92,32 @@ flosync.run('my-workflow', { body: { id: 1 } });
|
|
|
91
92
|
flosync.run('my-workflow', { body: { id: 1 }, headers: { 'x-request-id': 'abc' }, pathParams: { id: '123' }, query: { page: 1 } });
|
|
92
93
|
```
|
|
93
94
|
|
|
95
|
+
### Execution headers (local and remote)
|
|
96
|
+
|
|
97
|
+
Workflow steps read `state.headers` (for example `v.header('authorization')`). You control what appears there via the run payload and, for remote runs, the client options below.
|
|
98
|
+
|
|
99
|
+
Local runs (`flosync.run` with a registered workflow): `headers` and `executionHeaders` on the payload are merged (after sanitization) into `state.headers`. You can also pass `executionHeaders` as the third argument to `flosync.run`, which merges on top of the payload.
|
|
100
|
+
|
|
101
|
+
```javascript
|
|
102
|
+
await flosync.run('my-workflow', { body: { id: 1 }, headers: { 'x-request-id': 'a' } }, {
|
|
103
|
+
executionHeaders: { authorization: `Bearer ${integrationToken}` },
|
|
104
|
+
});
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Remote runs (`flosync.run` / `flosync.runById` with `apiKey` and `apiSecret`, or `FlosyncClient`): the SDK sends its own `Authorization` header to the Cliodot API (session JWT). That value is not copied into the workflow `state.headers`, since it is not the same credential your integration steps expect.
|
|
108
|
+
|
|
109
|
+
To give the server workflow the bearer or other headers it was designed for, pass them explicitly:
|
|
110
|
+
|
|
111
|
+
- In the payload: `headers` or `executionHeaders` on the object you pass to `run` / `runById` (both are merged into the test payload the API receives).
|
|
112
|
+
- On the client: `client.workflows.run(groupId, triggerId, { payload, executionHeaders })` — `executionHeaders` is sent in the JSON body and merged last on the server.
|
|
113
|
+
- Webhook test: `client.workflows.runByWebhook(path, method, { body, executionHeaders })`.
|
|
114
|
+
|
|
115
|
+
Merge order on the server is: sanitized real incoming HTTP headers (transport), then `payload.headers`, then `executionHeaders` from the body. Later keys win. Cookies, hop-by-hop headers, `sec-*`, `proxy-*`, and `proxy-authorization` are dropped from user-supplied maps. `authorization` is allowed in `headers` / `executionHeaders` so you can supply an integration bearer; it is still stripped from the raw request line so the Cliodot session token does not overwrite your value.
|
|
116
|
+
|
|
117
|
+
`sanitizeExecutionHeaders` is exported if you want to preview what will be sent; the same rules apply on the server.
|
|
118
|
+
|
|
119
|
+
Public webhooks (unauthenticated URL): the server does not apply an `executionHeaders` field from the JSON body for merging. Use normal request headers or put values in the webhook payload and map them in the workflow.
|
|
120
|
+
|
|
94
121
|
## Configuration
|
|
95
122
|
|
|
96
123
|
```javascript
|
|
@@ -99,6 +126,7 @@ flosync.configure({
|
|
|
99
126
|
apiSecret: process.env.FLOSYNC_API_SECRET,
|
|
100
127
|
baseUrl: 'http://localhost:8080' //optional,
|
|
101
128
|
projectId: process.env.FLOSYNC_PROJECT_ID,
|
|
129
|
+
debug: false, // Enable to include stepResults in every response
|
|
102
130
|
connectors: {
|
|
103
131
|
'mongodb.system': { uri: process.env.MONGO_URI, database: 'myapp' },
|
|
104
132
|
'mysql.system': { uri: process.env.MYSQL_URI },
|
|
@@ -156,10 +184,46 @@ s.validator({ amount: v.body('amount'), email: v.body('email') });
|
|
|
156
184
|
s.transform({ total: v.stepResult('calculate', 'total'), id: v.stepResult('charge', 'id') });
|
|
157
185
|
```
|
|
158
186
|
|
|
187
|
+
### Typed `stepResult` paths (`defineStepVars`)
|
|
188
|
+
|
|
189
|
+
`v.stepResult(stepId, ...pathParts)` treats every segment as a plain `string`, so your editor cannot suggest valid fields from a connector response or from another step’s output.
|
|
190
|
+
|
|
191
|
+
Use **`defineStepVars`** to describe, once per workflow file, a map from **step id** (the decorated **method name**) to that step’s **result type**. The returned **`stepResult`** then constrains the first argument to those keys and each following argument to the next key along a valid path into that type (nested objects supported up to a fixed depth). Import **`ConnectorResponse`** (and your **`defineTypedConnector`** value) so connector steps reuse the same response shape you already declared for typing.
|
|
192
|
+
|
|
193
|
+
```typescript
|
|
194
|
+
import { defineStepVars, v, defineTypedConnector } from "cliodot";
|
|
195
|
+
import type { ConnectorResponse } from "cliodot";
|
|
196
|
+
|
|
197
|
+
const Api = defineTypedConnector("my-api", { pay: "pay" }, {
|
|
198
|
+
pay: {
|
|
199
|
+
body: {} as { amount: number },
|
|
200
|
+
response: { status: "", data: { id: "", link: "" } },
|
|
201
|
+
},
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
const steps = defineStepVars<{
|
|
205
|
+
pay: ConnectorResponse<typeof Api, "pay">;
|
|
206
|
+
validate: { errors?: Record<string, unknown> };
|
|
207
|
+
}>();
|
|
208
|
+
|
|
209
|
+
steps.stepResult("pay", "data", "link");
|
|
210
|
+
steps.stepResult("validate", "errors");
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
The type **`StepKeyPath<T>`** is exported if you want to reuse the path-tuple logic elsewhere. Plain **`v.stepResult`** remains available for ad hoc strings and for code that does not need completions.
|
|
214
|
+
|
|
215
|
+
### Class decorators (`buildWorkflowFromClass`)
|
|
216
|
+
|
|
217
|
+
For `@Connector`, you can target a connector that exists only on Flowsync in three ways: pass the published connector id and action as strings (`@Connector('my-connector', 'charge', { installation_id: '...', connector_version: '1.2.0' })`); use `defineCustomConnector` / `defineCustomConnectorFromList` with that same id; or use `defineRemoteConnectorRef('my-connector', { pay: 'charge' })` and `@Connector(MyRef, 'pay', config)` for a clearer name. With `apiKey` and `apiSecret` set, the local runner loads REST definitions through `client.connectors.get` and respects `connector_version` on the step when fetching.
|
|
218
|
+
|
|
219
|
+
**`@CallWorkflow` by webhook path** — Use `@CallWorkflow({ webhookPath: '/orders', webhookMethod: 'POST' }, payload)` where `webhookPath` and `webhookMethod` match the child workflow’s HTTP trigger (same values as `@Http('POST', '/orders')` on that workflow). You do **not** pass a workflow group id for this mode: the platform finds the child by path and method for the tenant. When the local runner calls Flowsync with `apiKey` / `apiSecret`, it uses **`POST /workflows/test/webhook`** with a JSON body `{ webhookPath, webhookMethod, payload, ... }` (`client.workflows.runByWebhook`). On the server, `call_workflow` resolves the child the same way as a real webhook (including route patterns) and merges path params into the child’s `pathParams`. The second decorator argument is the child payload; optional fields on that object include `environment` (`dev` / `prod`), `executionHeaders`, and `remote: true` to skip the in-memory registry and always hit the API. `webhookPath` / `webhookMethod` may be templated with `{{ }}` and are rendered before lookup.
|
|
220
|
+
|
|
221
|
+
**`@CallWorkflow` by group id** — `@CallWorkflow('my-group-id', payload)` runs the child via **`POST /workflows/:groupId/test/trigger/:triggerId`** (see `client.workflows.run`). Use this when you target a specific group and trigger explicitly. You can combine `workflow_id` with a webhook path in the serialized step only when you need both; the path-only flow above stays independent of group ids.
|
|
222
|
+
|
|
159
223
|
### Step Types
|
|
160
224
|
|
|
161
|
-
- `connector(id, action, config)` - REST/API call
|
|
162
|
-
- `db(engine, action, config)` - MongoDB, MySQL, PostgreSQL, or Redis
|
|
225
|
+
- `connector(id, action, config)` - REST/API call (optional `connector_version` in `config` for versioned tenant connectors when syncing workflows to Flowsync)
|
|
226
|
+
- `db(engine, action, config)` - MongoDB, MySQL, PostgreSQL, or Redis (optional `connector_version` when relevant)
|
|
163
227
|
- `validator(fields)` - Validate input
|
|
164
228
|
- `condition(expr)` - Branch on expression (use `.then()` and `.else()`)
|
|
165
229
|
- `transform(mapping)` - Map or transform data
|
|
@@ -235,15 +299,190 @@ The overridden output becomes the value of `v.stepResult("<stepId>")` for subseq
|
|
|
235
299
|
|
|
236
300
|
In `stage: "post"`, `ctx.input` is the decorated step output produced by the connector/function call.
|
|
237
301
|
|
|
238
|
-
|
|
302
|
+
#### `stage: "post"` in depth
|
|
303
|
+
|
|
304
|
+
`post` is the hook that runs **after** the decorated step’s primary work finishes. For `@Connector`, `@Db`, and other steps that call out to a runtime implementation, the sequence is: resolve inputs → run the connector or database action (or built-in executor) → take the returned payload as the step output → **then** run your method body with `ctx.input` set to that output. Anything you return as `{ out }` replaces what gets stored in `stepResults` for that step id, so the rest of the workflow sees your transformed value. Use `setVars` in the same return value to publish workflow variables without changing the step output. Failures and HTTP error handling still apply to the primary step; the post hook is for normalization (mapping provider DTOs to your domain shape), redacting fields, enriching derived properties, or turning awkward API responses into a stable contract for later steps and responders. `@Step` defaults to `stage: "post"` so standalone code steps behave like “compute output from prior context” without injecting an extra predecessor code step.
|
|
305
|
+
|
|
306
|
+
### `WorkflowContext<TInput, TSteps, TVars>`
|
|
307
|
+
|
|
308
|
+
Instead of using `ctx: any`, you can type the context object passed to step methods. Import `WorkflowContext` from `cliodot`:
|
|
309
|
+
|
|
310
|
+
```typescript
|
|
311
|
+
import type { WorkflowContext } from "cliodot";
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
`WorkflowContext` is generic with three optional type parameters:
|
|
315
|
+
|
|
316
|
+
| Parameter | Default | Description |
|
|
317
|
+
|-----------|---------|-------------|
|
|
318
|
+
| `TInput` | `Record<string, any>` | Shape of `ctx.input` (previous step output or trigger data) |
|
|
319
|
+
| `TSteps` | `Record<string, any>` | Shape of `ctx.steps` (accumulated step results) |
|
|
320
|
+
| `TVars` | `Record<string, any>` | Shape of `ctx.vars` (workflow-level variables) |
|
|
321
|
+
|
|
322
|
+
The full context object includes:
|
|
323
|
+
|
|
324
|
+
| Property | Type | Description |
|
|
325
|
+
|----------|------|-------------|
|
|
326
|
+
| `input` | `TInput` | Input data for this step |
|
|
327
|
+
| `trigger` | `any` | Raw trigger payload |
|
|
328
|
+
| `steps` | `TSteps` | All step results keyed by step ID |
|
|
329
|
+
| `vars` | `TVars` | Workflow variables (read/write via `setVars`) |
|
|
330
|
+
| `headers` | `Record<string, string>` | HTTP headers from the request |
|
|
331
|
+
| `params` | `Record<string, any>` | Merged query + route params |
|
|
332
|
+
| `pathParams` | `Record<string, any>` | URL path parameters |
|
|
333
|
+
| `query` | `Record<string, any>` | Query string parameters |
|
|
334
|
+
| `body` | `any` | Raw request body |
|
|
335
|
+
| `env` | `Record<string, string>` | Environment variables |
|
|
336
|
+
|
|
337
|
+
The interface also has an index signature (`[key: string]: any`) so users can attach custom properties.
|
|
338
|
+
|
|
339
|
+
### `StepOutput<T>`
|
|
340
|
+
|
|
341
|
+
The return type for step methods that produce output. Import from `cliodot`:
|
|
342
|
+
|
|
343
|
+
```typescript
|
|
344
|
+
import type { StepOutput } from "cliodot";
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
```typescript
|
|
348
|
+
export interface StepOutput<T = any> {
|
|
349
|
+
/** The output payload — stored in stepResults[stepId] */
|
|
350
|
+
out: T;
|
|
351
|
+
/** Optional: update workflow variables */
|
|
352
|
+
setVars?: Record<string, any>;
|
|
353
|
+
}
|
|
354
|
+
```
|
|
355
|
+
|
|
356
|
+
Usage:
|
|
357
|
+
|
|
358
|
+
```typescript
|
|
359
|
+
@Connector(MyStore.id, MyStore.actions.list, {}, { order: 0, stage: "post" })
|
|
360
|
+
list(ctx: WorkflowContext<{ items: Item[] }>): StepOutput<{ sorted: Item[] }> {
|
|
361
|
+
const sorted = [...ctx.input.items].sort((a, b) => a.id - b.id);
|
|
362
|
+
return { out: { sorted } };
|
|
363
|
+
}
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
> **Note:** `StepOutput` is different from the `StepResult` exported by `WorkflowBuilder` (which is the builder-pattern return type with `.then()` / `.else()` chaining). Use `StepOutput` for decorator workflow method return types.
|
|
367
|
+
|
|
368
|
+
### `@Step` — Custom Step Decorator
|
|
369
|
+
|
|
370
|
+
`@Step` is a generic decorator for writing custom workflow step logic without needing to pair it with a connector, database, or other built-in step type. The method body is extracted at build time and executed as a code step with access to the full `WorkflowContext`.
|
|
371
|
+
|
|
372
|
+
```typescript
|
|
373
|
+
import { Workflow, Http, Step, Responder, buildWorkflowFromClass, v } from "cliodot";
|
|
374
|
+
import type { WorkflowContext, StepOutput } from "cliodot";
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
**Options** (same as other step decorators):
|
|
378
|
+
|
|
379
|
+
| Option | Type | Default | Description |
|
|
380
|
+
|--------|------|---------|-------------|
|
|
381
|
+
| `id` | `string` | method name | Custom step ID |
|
|
382
|
+
| `order` | `number` | auto | Execution order |
|
|
383
|
+
| `stage` | `"pre" \| "post"` | `"post"` | When the method body runs |
|
|
384
|
+
| `then` | `string` | — | Step ID to jump to on success |
|
|
385
|
+
| `else` | `string` | — | Step ID to jump to on failure |
|
|
386
|
+
|
|
387
|
+
**Basic example:**
|
|
388
|
+
|
|
389
|
+
```typescript
|
|
390
|
+
@Workflow("greet-user", "Greet User")
|
|
391
|
+
@Http("POST", "/greet")
|
|
392
|
+
class GreetWorkflow {
|
|
393
|
+
@Step({ order: 0 })
|
|
394
|
+
greet(ctx: WorkflowContext<{ name: string }>): StepOutput<{ greeting: string }> {
|
|
395
|
+
const name = ctx.input.name || "World";
|
|
396
|
+
return { out: { greeting: `Hello, ${name}!` } };
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
@Responder("json", { body: { message: v.stepResult("greet", "greeting") } }, { order: 1 })
|
|
400
|
+
respond() {}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
export const greetWorkflow = buildWorkflowFromClass(GreetWorkflow);
|
|
404
|
+
```
|
|
405
|
+
|
|
406
|
+
**With `setVars` and branching:**
|
|
407
|
+
|
|
408
|
+
```typescript
|
|
409
|
+
@Workflow("process-order", "Process Order")
|
|
410
|
+
@Http("POST", "/orders/process")
|
|
411
|
+
class ProcessOrderWorkflow {
|
|
412
|
+
@Step({ order: 0, then: "finalize", else: "reject" })
|
|
413
|
+
validate(ctx: WorkflowContext<{ amount: number; currency: string }>): StepOutput<{ valid: boolean }> {
|
|
414
|
+
const { amount, currency } = ctx.input;
|
|
415
|
+
const valid = amount > 0 && ["USD", "EUR", "GBP"].includes(currency);
|
|
416
|
+
return {
|
|
417
|
+
out: { valid },
|
|
418
|
+
setVars: { processedAt: new Date().toISOString() },
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
@Responder("json", { body: { ok: true, processedAt: v.vars("processedAt") } }, { order: 1 })
|
|
423
|
+
finalize() {}
|
|
424
|
+
|
|
425
|
+
@Responder("json", { statusCode: 400, body: { ok: false, error: "Invalid order" } }, { order: 2 })
|
|
426
|
+
reject() {}
|
|
427
|
+
}
|
|
428
|
+
```
|
|
429
|
+
|
|
430
|
+
**Combining `@Step` with other decorators:**
|
|
431
|
+
|
|
432
|
+
`@Step` can be freely combined with `@Connector`, `@Db`, `@Condition`, `@Responder`, etc. in the same workflow class:
|
|
433
|
+
|
|
434
|
+
```typescript
|
|
435
|
+
@Workflow("mixed-workflow", "Mixed Workflow")
|
|
436
|
+
@Http("POST", "/mixed")
|
|
437
|
+
class MixedWorkflow {
|
|
438
|
+
@Step({ order: 0 })
|
|
439
|
+
prepare(ctx: WorkflowContext<{ email: string }>): StepOutput<{ normalized: string }> {
|
|
440
|
+
return { out: { normalized: ctx.input.email.toLowerCase().trim() } };
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
@Db("mongodb", "findOne", { collection: "users", query: { email: v.stepResult("prepare", "normalized") } }, { order: 1 })
|
|
444
|
+
findUser() {}
|
|
445
|
+
|
|
446
|
+
@Condition(v.expr("stepResults.findUser != null"), { then: "found", else: "notFound", order: 2 })
|
|
447
|
+
check() {}
|
|
448
|
+
|
|
449
|
+
@Responder("json", { body: { user: v.stepResult("findUser") } }, { order: 3 })
|
|
450
|
+
found() {}
|
|
451
|
+
|
|
452
|
+
@Responder("json", { statusCode: 404, body: { error: "User not found" } }, { order: 4 })
|
|
453
|
+
notFound() {}
|
|
454
|
+
}
|
|
455
|
+
```
|
|
456
|
+
|
|
457
|
+
### Decorator example: list todos with typed context
|
|
239
458
|
|
|
240
459
|
```typescript
|
|
241
460
|
import { flosync, v, Workflow, Http, Connector, Condition, Responder, buildWorkflowFromClass, defineCustomConnector } from "cliodot";
|
|
461
|
+
import type { WorkflowContext, StepOutput } from "cliodot";
|
|
242
462
|
|
|
243
463
|
const CarrierStore = defineCustomConnector("carrier.store", {
|
|
244
464
|
listTodos: "listTodos",
|
|
245
465
|
});
|
|
246
466
|
|
|
467
|
+
interface TodoItem {
|
|
468
|
+
title?: string;
|
|
469
|
+
completed?: boolean;
|
|
470
|
+
createdAt?: string;
|
|
471
|
+
[key: string]: any;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
interface ListInput {
|
|
475
|
+
todos?: TodoItem[];
|
|
476
|
+
[key: string]: any;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
interface ListOutput {
|
|
480
|
+
todos: Array<TodoItem & { title_upper: string; completed_label: string }>;
|
|
481
|
+
completedTodos: TodoItem[];
|
|
482
|
+
pendingTodos: TodoItem[];
|
|
483
|
+
stats: { total: number; completed: number; pending: number };
|
|
484
|
+
}
|
|
485
|
+
|
|
247
486
|
@Workflow("todos-list-decorators", "Todos List (Decorators)")
|
|
248
487
|
@Http("GET", "/todos")
|
|
249
488
|
class TodosListDecoratorsWorkflow {
|
|
@@ -253,13 +492,38 @@ class TodosListDecoratorsWorkflow {
|
|
|
253
492
|
{ params: { limit: 10 } },
|
|
254
493
|
{ order: 0, stage: "post" }
|
|
255
494
|
)
|
|
256
|
-
list(ctx:
|
|
257
|
-
const
|
|
258
|
-
const
|
|
495
|
+
list(ctx: WorkflowContext<ListInput>): StepOutput<ListOutput> {
|
|
496
|
+
const input = ctx?.input ?? {};
|
|
497
|
+
const todos = Array.isArray(input.todos) ? input.todos : [];
|
|
498
|
+
const sorted = [...todos].sort((a, b) =>
|
|
499
|
+
new Date(b?.createdAt ?? 0).getTime() - new Date(a?.createdAt ?? 0).getTime()
|
|
500
|
+
);
|
|
501
|
+
const completedTodos = sorted.filter((t) => Boolean(t?.completed));
|
|
502
|
+
const pendingTodos = sorted.filter((t) => !Boolean(t?.completed));
|
|
503
|
+
|
|
504
|
+
const decoratedTodos = sorted.map((t) => {
|
|
259
505
|
const title = String(t?.title ?? "").trim();
|
|
260
|
-
return {
|
|
506
|
+
return {
|
|
507
|
+
...t,
|
|
508
|
+
title,
|
|
509
|
+
title_upper: title.toUpperCase(),
|
|
510
|
+
completed_label: t?.completed ? "done" as const : "todo" as const,
|
|
511
|
+
};
|
|
261
512
|
});
|
|
262
|
-
|
|
513
|
+
|
|
514
|
+
return {
|
|
515
|
+
out: {
|
|
516
|
+
...input,
|
|
517
|
+
todos: decoratedTodos,
|
|
518
|
+
completedTodos,
|
|
519
|
+
pendingTodos,
|
|
520
|
+
stats: {
|
|
521
|
+
total: sorted.length,
|
|
522
|
+
completed: completedTodos.length,
|
|
523
|
+
pending: pendingTodos.length,
|
|
524
|
+
},
|
|
525
|
+
},
|
|
526
|
+
};
|
|
263
527
|
}
|
|
264
528
|
|
|
265
529
|
@Condition(v.stepResult("list", "valid"), { then: "ok", else: "unauth", order: 1 })
|
|
@@ -421,6 +685,123 @@ Example validation failure response body:
|
|
|
421
685
|
|
|
422
686
|
`@Util` is typed the same way as `s.util(ConnectorId.Utility.String, "slugify", { ... })` in the fluent builder. `@Db` supports the `mongodb` and `mysql` engines (see [Database](#database)). Step IDs in `v.stepResult("slugify", "value")` refer to the **method name** you put on each decorated step (after sanitization, dots and hyphens in custom IDs become underscores).
|
|
423
687
|
|
|
688
|
+
### Decorator Connectors
|
|
689
|
+
|
|
690
|
+
For ultimate flexibility, you can define your own **Connectors** using class-based decorators instead of using the generic `defineCustomConnector` pattern.
|
|
691
|
+
|
|
692
|
+
Use the `@ConnectorClass` decorator and map endpoints instantly without rewriting HTTP loops or complex REST logic!
|
|
693
|
+
|
|
694
|
+
```typescript
|
|
695
|
+
import { ConnectorClass, ActionEndpoint, ActionCustom, buildConnectorFromClass, flosync } from "cliodot";
|
|
696
|
+
|
|
697
|
+
// You can pass configuration mimicking flosync REST definition payloads directly into the class decorator:
|
|
698
|
+
@ConnectorClass("paystack", "Paystack Integrations", {
|
|
699
|
+
type: "REST",
|
|
700
|
+
base_url: "https://api.paystack.co",
|
|
701
|
+
auth: { type: "bearer", token: process.env.PAYSTACK_SECRET_KEY }
|
|
702
|
+
})
|
|
703
|
+
export class Paystack {
|
|
704
|
+
|
|
705
|
+
// Handled entirely by Flosync's underlying REST connector automatically!
|
|
706
|
+
@ActionEndpoint("initializeTransaction", "POST", "/transaction/initialize", {
|
|
707
|
+
headers: { "Content-Type": "application/json" }
|
|
708
|
+
})
|
|
709
|
+
initializeTransaction() {}
|
|
710
|
+
|
|
711
|
+
// Paths parameter resolution happens completely implicitly via the REST connector.
|
|
712
|
+
@ActionEndpoint("verifyTransaction", "GET", "/transaction/verify/:reference")
|
|
713
|
+
verifyTransaction() {}
|
|
714
|
+
|
|
715
|
+
// Or, run a completely custom code execution if you need SDKs or Database integrations
|
|
716
|
+
@ActionCustom("generateSignature")
|
|
717
|
+
async generateSignature(payload: any) {
|
|
718
|
+
const crypto = require("crypto");
|
|
719
|
+
return { signature: crypto.createHmac('sha512', process.env.SECRET).update(payload.body.data).digest('hex') };
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
// Convert class into standard flosync connector schema
|
|
724
|
+
export const paystackConfig = buildConnectorFromClass(Paystack);
|
|
725
|
+
|
|
726
|
+
export const PaystackConnector = {
|
|
727
|
+
id: PaystackImplementation.id,
|
|
728
|
+
actions: PaystackImplementation.actions
|
|
729
|
+
};
|
|
730
|
+
|
|
731
|
+
// Register it natively just like any built-in module
|
|
732
|
+
flosync.registerConnector(paystackConfig.id, paystackConfig);
|
|
733
|
+
```
|
|
734
|
+
|
|
735
|
+
#### Authentication Options
|
|
736
|
+
|
|
737
|
+
Flosync supports built-in, natively executed REST authentication blocks inside the `@ConnectorClass` config object. You do not need to write boilerplate header injection code!
|
|
738
|
+
|
|
739
|
+
1. **Bearer Token (*Default*)**
|
|
740
|
+
```typescript
|
|
741
|
+
auth: { type: "bearer", token: "your-token", header_name: "Authorization", prefix: "Bearer " }
|
|
742
|
+
```
|
|
743
|
+
2. **API Key**
|
|
744
|
+
```typescript
|
|
745
|
+
auth: { type: "api_key", api_key: "your-api-key", key_name: "x-api-key" }
|
|
746
|
+
```
|
|
747
|
+
3. **No Auth**
|
|
748
|
+
```typescript
|
|
749
|
+
auth: { type: "none" }
|
|
750
|
+
```
|
|
751
|
+
|
|
752
|
+
Then hook it right into your workflows! This example uses `@Validator` for type-safe input checking, generates a unique payment reference using the built-in `utility.random` connector, and passes it to the Paystack API:
|
|
753
|
+
|
|
754
|
+
```typescript
|
|
755
|
+
import { Workflow, Http, Connector, Responder, Validator, v } from "cliodot";
|
|
756
|
+
|
|
757
|
+
@Workflow("payment-initialize", "Initialize Payment")
|
|
758
|
+
@Http("POST", "/payment/initialize")
|
|
759
|
+
export class PaymentInitializeWorkflow {
|
|
760
|
+
|
|
761
|
+
@Validator([
|
|
762
|
+
{
|
|
763
|
+
fields: [v.body("email")],
|
|
764
|
+
validators: [{ name: "required" }, { name: "is_email" }]
|
|
765
|
+
},
|
|
766
|
+
{
|
|
767
|
+
fields: [v.body("amount")],
|
|
768
|
+
validators: [{ name: "required" }]
|
|
769
|
+
}
|
|
770
|
+
], { order: 0, then: "generateReference", else: "invalid" })
|
|
771
|
+
validate() {}
|
|
772
|
+
|
|
773
|
+
@Responder("json", {
|
|
774
|
+
statusCode: 400,
|
|
775
|
+
body: {
|
|
776
|
+
ok: false,
|
|
777
|
+
message: "Validation failed",
|
|
778
|
+
errors: v.stepResult("validate", "errors")
|
|
779
|
+
}
|
|
780
|
+
}, { order: 1 })
|
|
781
|
+
invalid() {}
|
|
782
|
+
|
|
783
|
+
@Connector("utility.random", "random_uuid", {}, { order: 2 })
|
|
784
|
+
generateReference() {}
|
|
785
|
+
|
|
786
|
+
@Connector(
|
|
787
|
+
PaystackConnector.id,
|
|
788
|
+
PaystackConnector.actions.initializeTransaction,
|
|
789
|
+
{
|
|
790
|
+
body: {
|
|
791
|
+
email: v.body("email"),
|
|
792
|
+
amount: v.body("amount"),
|
|
793
|
+
reference: v.stepResult("generateReference", "value"),
|
|
794
|
+
}
|
|
795
|
+
},
|
|
796
|
+
{ order: 3 }
|
|
797
|
+
)
|
|
798
|
+
initialize() {}
|
|
799
|
+
|
|
800
|
+
@Responder("json", { body: { message: "Payment initialized successfully", data: v.stepResult("initialize") } }, { order: 4 })
|
|
801
|
+
respond() {}
|
|
802
|
+
}
|
|
803
|
+
```
|
|
804
|
+
|
|
424
805
|
### Custom `execute` connector plus decorators (catalog sample)
|
|
425
806
|
|
|
426
807
|
For behavior that is not a REST template (in-memory demo data, your own SDK, legacy SOAP adapter, etc.), register a connector with an `execute` function, then call it from decorators with `@Connector` exactly like a built-in connector. This mirrors the `carrier.store` pattern: actions such as `listProducts` and `createProduct`, `options.body` / `options.params` / `options.pathParams` passed from the step config.
|
|
@@ -503,10 +884,10 @@ class CatalogListDecoratorsWorkflow {
|
|
|
503
884
|
{ params: { limit: v.query("limit") } },
|
|
504
885
|
{ order: 0, stage: "post" }
|
|
505
886
|
)
|
|
506
|
-
list(ctx: any) {
|
|
887
|
+
list(ctx: WorkflowContext<{ products?: CatalogProduct[]; [k: string]: any }>): StepOutput<{ products: any[]; count: number }> {
|
|
507
888
|
const input = ctx?.input ?? {};
|
|
508
889
|
const items = Array.isArray(input.products) ? input.products : [];
|
|
509
|
-
const withLabels = items.map((p
|
|
890
|
+
const withLabels = items.map((p) => ({
|
|
510
891
|
...p,
|
|
511
892
|
price_display: `$${Number(p.price).toFixed(2)}`,
|
|
512
893
|
}));
|
|
@@ -540,7 +921,7 @@ class CatalogCreateDecoratorsWorkflow {
|
|
|
540
921
|
{ body: { name: v.body("name"), price: v.body("price") } },
|
|
541
922
|
{ order: 0, stage: "post" }
|
|
542
923
|
)
|
|
543
|
-
save(ctx: any) {
|
|
924
|
+
save(ctx: WorkflowContext<{ ok?: boolean; product?: CatalogProduct; [k: string]: any }>): StepOutput<any> {
|
|
544
925
|
const input = ctx?.input ?? {};
|
|
545
926
|
if (!input.ok) return { out: input };
|
|
546
927
|
const p = input.product as CatalogProduct;
|
|
@@ -636,6 +1017,40 @@ await flosync.runFunctionById('function-id', { amount: 100 });
|
|
|
636
1017
|
|
|
637
1018
|
If a workflow/function is registered locally, `run` / `runFunction` use the local version. If not found and the client is configured, they run remotely. Pass `{ remote: false }` to disable remote fallback.
|
|
638
1019
|
|
|
1020
|
+
### Connector versioning (REST connectors)
|
|
1021
|
+
|
|
1022
|
+
Tenant REST connectors can have **published semver snapshots**. The SDK and API use that version when loading connector definitions for workflow runs and for direct execute calls.
|
|
1023
|
+
|
|
1024
|
+
**Workflow steps (fluent builder and `@Connector` config)**
|
|
1025
|
+
Include an optional semver string on the step config so pushed workflows pin the same snapshot the runner expects:
|
|
1026
|
+
|
|
1027
|
+
```typescript
|
|
1028
|
+
s.connector("paystack_conn_id", "initializeTransaction", {
|
|
1029
|
+
connector_version: "1.2.0",
|
|
1030
|
+
body: { email: v.body("email"), amount: v.body("amount") },
|
|
1031
|
+
});
|
|
1032
|
+
```
|
|
1033
|
+
|
|
1034
|
+
Event triggers can pin the source connector the same way on the workflow object: `trigger.source_connector_id` and `trigger.source_connector_version` (see types in `IWorkflowTrigger`).
|
|
1035
|
+
|
|
1036
|
+
**`flosync.runConnector` (remote)**
|
|
1037
|
+
Pass `connector_version` in the options object. Non-owners must match their **installed** version; owners may use other published versions or `draft` per API rules.
|
|
1038
|
+
|
|
1039
|
+
```typescript
|
|
1040
|
+
await flosync.runConnector(Paystack, "initializeTransaction", {
|
|
1041
|
+
connector_version: "1.2.0",
|
|
1042
|
+
body: { email: "a@b.com", amount: 100 },
|
|
1043
|
+
});
|
|
1044
|
+
```
|
|
1045
|
+
|
|
1046
|
+
**`FlosyncClient`** (after `configure` with `apiKey` / `apiSecret`):
|
|
1047
|
+
|
|
1048
|
+
- `client.connectors.get(connectorId, { semver: "1.2.0" })` or `{ version: "1.2.0" }` — same query params as the Flowsync GET connector API.
|
|
1049
|
+
- `client.connectors.install(connectorId, { auth, base_url, version: "latest" })` — `version` is optional (body or query on the server).
|
|
1050
|
+
- `client.connectors.execute(connectorId, action, { connector_version: "1.2.0", body, params, ... })` — sent as `connector_version` on the execute request body.
|
|
1051
|
+
|
|
1052
|
+
Workflows built with `WorkflowBuilder` / decorators serialize `connector_version` onto nodes when you `workflows.push`, so pulls round-trip the field.
|
|
1053
|
+
|
|
639
1054
|
## Database
|
|
640
1055
|
|
|
641
1056
|
Use `s.db(engine, action, config)` or `s.connector(connectorId, action, config)` with built-in database connectors.
|
|
@@ -699,6 +1114,192 @@ s.responder('redirect', { location: 'https://example.com', statusCode: 301 });
|
|
|
699
1114
|
s.responder('empty', { statusCode: 202 });
|
|
700
1115
|
```
|
|
701
1116
|
|
|
1117
|
+
## Validation
|
|
1118
|
+
|
|
1119
|
+
The `@Validator` decorator provides type-safe input validation for workflow steps. Validators use a `ValidationRule` union type that gives you full IDE auto-completion for all available rules and their configuration options.
|
|
1120
|
+
|
|
1121
|
+
### Basic usage
|
|
1122
|
+
|
|
1123
|
+
```typescript
|
|
1124
|
+
import { Validator, v } from "cliodot";
|
|
1125
|
+
|
|
1126
|
+
@Validator([
|
|
1127
|
+
{
|
|
1128
|
+
fields: [v.body("email")],
|
|
1129
|
+
validators: [{ name: "required" }, { name: "is_email" }]
|
|
1130
|
+
},
|
|
1131
|
+
{
|
|
1132
|
+
fields: [v.body("amount")],
|
|
1133
|
+
validators: [{ name: "required" }, { name: "is_number" }]
|
|
1134
|
+
}
|
|
1135
|
+
], { order: 0, then: "process", else: "error" })
|
|
1136
|
+
validate() {}
|
|
1137
|
+
```
|
|
1138
|
+
|
|
1139
|
+
### Available validators
|
|
1140
|
+
|
|
1141
|
+
| Validator | Config | Description |
|
|
1142
|
+
|-----------|--------|-------------|
|
|
1143
|
+
| `required` | `{ message? }` | Field must be present and non-null |
|
|
1144
|
+
| `not_empty` | `{ message? }` | Field must not be empty |
|
|
1145
|
+
| `is_empty` | `{ message? }` | Field must be empty |
|
|
1146
|
+
| `is_email` | `{ message? }` | Valid email format |
|
|
1147
|
+
| `is_number` | `{ message? }` | Must be a number |
|
|
1148
|
+
| `is_string` | `{ message? }` | Must be a string |
|
|
1149
|
+
| `is_boolean` | `{ message? }` | Must be a boolean |
|
|
1150
|
+
| `is_array` | `{ message? }` | Must be an array |
|
|
1151
|
+
| `is_object` | `{ message? }` | Must be an object |
|
|
1152
|
+
| `is_url` | `{ message? }` | Valid URL format |
|
|
1153
|
+
| `is_date` | `{ message? }` | Valid date format |
|
|
1154
|
+
| `is_uuid` | `{ message? }` | Valid UUID (v1-v5) |
|
|
1155
|
+
| `is_cuid` | `{ message? }` | Valid CUID |
|
|
1156
|
+
| `is_jwt` | `{ message? }` | Valid JWT structure (`header.payload.signature`) |
|
|
1157
|
+
| `is_json` | `{ message? }` | Valid parseable JSON string |
|
|
1158
|
+
| `is_alphanumeric` | `{ message? }` | Letters and numbers only |
|
|
1159
|
+
| `is_alpha` | `{ message? }` | Letters only |
|
|
1160
|
+
| `is_numeric_string` | `{ message? }` | Numeric digits only |
|
|
1161
|
+
| `is_hex_color` | `{ message? }` | Valid hex color (`#FFF` or `#123456`) |
|
|
1162
|
+
| `is_base64` | `{ message? }` | Valid base64 encoded string |
|
|
1163
|
+
| `is_credit_card` | `{ message? }` | Valid credit card (Luhn algorithm) |
|
|
1164
|
+
| `is_lowercase` | `{ message? }` | Must be all lowercase |
|
|
1165
|
+
| `is_uppercase` | `{ message? }` | Must be all uppercase |
|
|
1166
|
+
| `is_slug` | `{ message? }` | Valid URL slug (`my-cool-slug`) |
|
|
1167
|
+
| `is_mac_address` | `{ message? }` | Valid MAC address |
|
|
1168
|
+
| `is_port` | `{ message? }` | Valid TCP/UDP port (0-65535) |
|
|
1169
|
+
| `is_currency` | `{ message? }` | Valid currency format |
|
|
1170
|
+
| `is_latitude` | `{ message? }` | Valid latitude (-90 to 90) |
|
|
1171
|
+
| `is_longitude` | `{ message? }` | Valid longitude (-180 to 180) |
|
|
1172
|
+
| `is_strong_password` | `{ minLength?, minLowercase?, minUppercase?, minNumbers?, minSymbols?, message? }` | Configurable password strength |
|
|
1173
|
+
| `is_ip` | `{ version?: 4 \| 6, message? }` | Valid IPv4 or IPv6 address |
|
|
1174
|
+
| `is_phone` | `{ pattern?, message? }` | Phone number format |
|
|
1175
|
+
| `is_address` | `{ minLength?, maxLength?, message? }` | Address string checks |
|
|
1176
|
+
| `contains` / `not_contains` | `{ search, caseSensitive?, message? }` | String contains/excludes a value |
|
|
1177
|
+
| `begins_with` | `{ prefix, caseSensitive?, message? }` | String starts with prefix |
|
|
1178
|
+
| `ends_with` | `{ suffix, caseSensitive?, message? }` | String ends with suffix |
|
|
1179
|
+
| `is_in` / `not_in` | `{ values: any[], caseSensitive?, message? }` | Value is/isn't in a list |
|
|
1180
|
+
| `length` | `{ min?, max?, exact?, message? }` | String/array length bounds |
|
|
1181
|
+
| `range` | `{ min?, max?, message? }` | Numeric range bounds |
|
|
1182
|
+
| `matches` | `{ pattern, flags?, message? }` | Regex pattern match |
|
|
1183
|
+
| `equals` / `not_equals` | `{ value, message? }` | Strict equality check |
|
|
1184
|
+
| `greater_than` / `less_than` | `{ value: number, message? }` | Numeric comparison |
|
|
1185
|
+
| `greater_than_or_equal` / `less_than_or_equal` | `{ value: number, message? }` | Inclusive numeric comparison |
|
|
1186
|
+
|
|
1187
|
+
### Configurable validators
|
|
1188
|
+
|
|
1189
|
+
Some validators accept rich configuration objects with IDE autocomplete:
|
|
1190
|
+
|
|
1191
|
+
```typescript
|
|
1192
|
+
// Strong password with custom constraints
|
|
1193
|
+
@Validator([
|
|
1194
|
+
{
|
|
1195
|
+
fields: [v.body("password")],
|
|
1196
|
+
validators: [{
|
|
1197
|
+
name: "is_strong_password",
|
|
1198
|
+
config: { minLength: 12, minUppercase: 2, minSymbols: 1 }
|
|
1199
|
+
}]
|
|
1200
|
+
}
|
|
1201
|
+
], { order: 0, then: "register", else: "invalid" })
|
|
1202
|
+
validatePassword() {}
|
|
1203
|
+
|
|
1204
|
+
// IP address with version lock
|
|
1205
|
+
@Validator([
|
|
1206
|
+
{
|
|
1207
|
+
fields: [v.body("server_ip")],
|
|
1208
|
+
validators: [{ name: "is_ip", config: { version: 4 } }]
|
|
1209
|
+
}
|
|
1210
|
+
], { order: 0, then: "connect", else: "invalid" })
|
|
1211
|
+
validateIP() {}
|
|
1212
|
+
|
|
1213
|
+
// Range + custom message
|
|
1214
|
+
@Validator([
|
|
1215
|
+
{
|
|
1216
|
+
fields: [v.body("age")],
|
|
1217
|
+
validators: [{
|
|
1218
|
+
name: "range",
|
|
1219
|
+
config: { min: 18, max: 120, message: "Age must be between 18 and 120" }
|
|
1220
|
+
}]
|
|
1221
|
+
}
|
|
1222
|
+
], { order: 0, then: "proceed", else: "invalid" })
|
|
1223
|
+
validateAge() {}
|
|
1224
|
+
```
|
|
1225
|
+
|
|
1226
|
+
### Validation branching
|
|
1227
|
+
|
|
1228
|
+
Use `then` and `else` to route the workflow based on validation results:
|
|
1229
|
+
|
|
1230
|
+
```typescript
|
|
1231
|
+
@Validator([
|
|
1232
|
+
{ fields: [v.body("email")], validators: [{ name: "required" }, { name: "is_email" }] }
|
|
1233
|
+
], { order: 0, then: "process", else: "validationError" })
|
|
1234
|
+
validate() {}
|
|
1235
|
+
|
|
1236
|
+
@Responder("json", {
|
|
1237
|
+
statusCode: 400,
|
|
1238
|
+
body: { ok: false, errors: v.stepResult("validate", "errors") }
|
|
1239
|
+
}, { order: 1 })
|
|
1240
|
+
validationError() {}
|
|
1241
|
+
```
|
|
1242
|
+
|
|
1243
|
+
When validation fails, the `errors` object is populated with field-level error messages that the responder can return to the client.
|
|
1244
|
+
|
|
1245
|
+
## Debug Mode
|
|
1246
|
+
|
|
1247
|
+
Flosync includes a built-in debug mode that injects a `_debug` object into workflow responses, containing the full `stepResults` map of every step that executed. This is invaluable for development and troubleshooting without adding `console.log` statements.
|
|
1248
|
+
|
|
1249
|
+
### Enabling debug
|
|
1250
|
+
|
|
1251
|
+
**1. Global (via config)** — applies to all workflow runs:
|
|
1252
|
+
|
|
1253
|
+
```typescript
|
|
1254
|
+
flosync.configure({
|
|
1255
|
+
debug: true,
|
|
1256
|
+
connectors: { ... },
|
|
1257
|
+
});
|
|
1258
|
+
```
|
|
1259
|
+
|
|
1260
|
+
**2. Per-request (via header)** — enable for a single call:
|
|
1261
|
+
|
|
1262
|
+
```bash
|
|
1263
|
+
curl -X POST http://localhost:3384/payment/initialize \
|
|
1264
|
+
-H "Content-Type: application/json" \
|
|
1265
|
+
-H "x-flosync-debug: true" \
|
|
1266
|
+
-d '{"email": "user@example.com", "amount": 5000}'
|
|
1267
|
+
```
|
|
1268
|
+
|
|
1269
|
+
**3. Per-request (via query param):**
|
|
1270
|
+
|
|
1271
|
+
```bash
|
|
1272
|
+
curl "http://localhost:3384/books?debug=true"
|
|
1273
|
+
```
|
|
1274
|
+
|
|
1275
|
+
### Debug output
|
|
1276
|
+
|
|
1277
|
+
When debug mode is active, a `_debug` key is appended to the response body:
|
|
1278
|
+
|
|
1279
|
+
```json
|
|
1280
|
+
{
|
|
1281
|
+
"message": "Payment initialized successfully",
|
|
1282
|
+
"data": {
|
|
1283
|
+
"authorization_url": "https://checkout.paystack.com/abc123",
|
|
1284
|
+
"reference": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
|
1285
|
+
},
|
|
1286
|
+
"_debug": {
|
|
1287
|
+
"stepResults": {
|
|
1288
|
+
"validate": { "valid": true },
|
|
1289
|
+
"generateReference": { "value": "a1b2c3d4-e5f6-7890-abcd-ef1234567890" },
|
|
1290
|
+
"initialize": {
|
|
1291
|
+
"authorization_url": "https://checkout.paystack.com/abc123",
|
|
1292
|
+
"reference": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
```
|
|
1298
|
+
|
|
1299
|
+
When debug mode is **off** (default), the `_debug` key is completely absent — zero overhead and no payload pollution.
|
|
1300
|
+
|
|
1301
|
+
> **Note:** Debug mode works for both local workflow execution (`flosync.run()`) and remote execution via `client.workflows.run()` / `client.workflows.runByWebhook()`.
|
|
1302
|
+
|
|
702
1303
|
## Encryption
|
|
703
1304
|
|
|
704
1305
|
Use `s.encrypt(connectorId, action, config)` with built-in encryption connectors. All use Node `crypto`; Argon2 and bcrypt require optional packages.
|
|
@@ -785,6 +1386,143 @@ import { defineCustomConnectorFromList } from 'cliodot';
|
|
|
785
1386
|
const MyStore = defineCustomConnectorFromList('my.store', ['login', 'listItems', 'createItem']);
|
|
786
1387
|
```
|
|
787
1388
|
|
|
1389
|
+
### Typed connectors (for remote connectors)
|
|
1390
|
+
|
|
1391
|
+
When using remote connectors, you do not have the implementation locally. `defineTypedConnector` lets you define per-action schema so TypeScript can infer request/response shapes across decorators, builder calls, and `runConnector`.
|
|
1392
|
+
|
|
1393
|
+
```typescript
|
|
1394
|
+
import { defineTypedConnector } from "cliodot";
|
|
1395
|
+
|
|
1396
|
+
const Paystack = defineTypedConnector("paystack", {
|
|
1397
|
+
initializeTransaction: "Initialize Transaction",
|
|
1398
|
+
verifyTransaction: "Verify Transaction",
|
|
1399
|
+
listTransactions: "List Transactions",
|
|
1400
|
+
}, {
|
|
1401
|
+
initializeTransaction: {
|
|
1402
|
+
body: {} as { email: string; amount: number; reference?: string; callback_url?: string },
|
|
1403
|
+
headers: {} as { "Idempotency-Key"?: string },
|
|
1404
|
+
vars: {} as { traceId?: string },
|
|
1405
|
+
response: {} as { authorization_url: string; access_code: string; reference: string },
|
|
1406
|
+
},
|
|
1407
|
+
verifyTransaction: {
|
|
1408
|
+
pathParams: {} as { reference: string },
|
|
1409
|
+
response: {} as { status: string; amount: number; currency: string; paid_at: string },
|
|
1410
|
+
},
|
|
1411
|
+
listTransactions: {
|
|
1412
|
+
params: {} as { page?: number; perPage?: number; status?: string },
|
|
1413
|
+
response: {} as { data: Array<{ reference: string; amount: number; status: string }> },
|
|
1414
|
+
},
|
|
1415
|
+
});
|
|
1416
|
+
```
|
|
1417
|
+
|
|
1418
|
+
Schema fields:
|
|
1419
|
+
|
|
1420
|
+
| Field | Description |
|
|
1421
|
+
|-------|-------------|
|
|
1422
|
+
| `body` | Shape of request body |
|
|
1423
|
+
| `params` | Shape of query/params |
|
|
1424
|
+
| `pathParams` | Shape of URL path params |
|
|
1425
|
+
| `headers` | Shape of custom headers |
|
|
1426
|
+
| `vars` | Shape of step-level vars merged before execution |
|
|
1427
|
+
| `response` | Shape of expected response |
|
|
1428
|
+
|
|
1429
|
+
Use `{} as YourType` to define each shape without runtime values.
|
|
1430
|
+
|
|
1431
|
+
**Extracting types with helper utilities:**
|
|
1432
|
+
|
|
1433
|
+
```typescript
|
|
1434
|
+
import type {
|
|
1435
|
+
ConnectorBody,
|
|
1436
|
+
ConnectorParams,
|
|
1437
|
+
ConnectorPathParams,
|
|
1438
|
+
ConnectorHeaders,
|
|
1439
|
+
ConnectorVars,
|
|
1440
|
+
ConnectorResponse,
|
|
1441
|
+
} from "cliodot";
|
|
1442
|
+
|
|
1443
|
+
type InitBody = ConnectorBody<typeof Paystack, "initializeTransaction">;
|
|
1444
|
+
type InitHeaders = ConnectorHeaders<typeof Paystack, "initializeTransaction">;
|
|
1445
|
+
type InitVars = ConnectorVars<typeof Paystack, "initializeTransaction">;
|
|
1446
|
+
type VerifyPath = ConnectorPathParams<typeof Paystack, "verifyTransaction">;
|
|
1447
|
+
type ListParams = ConnectorParams<typeof Paystack, "listTransactions">;
|
|
1448
|
+
type VerifyResponse = ConnectorResponse<typeof Paystack, "verifyTransaction">;
|
|
1449
|
+
```
|
|
1450
|
+
|
|
1451
|
+
**Using in decorators (typed action key + typed config):**
|
|
1452
|
+
|
|
1453
|
+
```typescript
|
|
1454
|
+
import { Workflow, Http, Connector, Responder, v } from "cliodot";
|
|
1455
|
+
import type { WorkflowContext, StepOutput, ConnectorResponse } from "cliodot";
|
|
1456
|
+
|
|
1457
|
+
type InitResponse = ConnectorResponse<typeof Paystack, "initializeTransaction">;
|
|
1458
|
+
|
|
1459
|
+
@Workflow("paystack-init", "Initialize Paystack Payment")
|
|
1460
|
+
@Http("POST", "/pay")
|
|
1461
|
+
class PaystackInitWorkflow {
|
|
1462
|
+
@Connector(
|
|
1463
|
+
Paystack,
|
|
1464
|
+
"initializeTransaction",
|
|
1465
|
+
{
|
|
1466
|
+
body: { email: v.body("email"), amount: v.body("amount"), callback_url: v.body("callback_url") },
|
|
1467
|
+
headers: { "Idempotency-Key": "{{ trigger.idempotencyKey }}" },
|
|
1468
|
+
vars: { traceId: "{{ trigger.traceId }}" },
|
|
1469
|
+
},
|
|
1470
|
+
{ order: 0, stage: "post" }
|
|
1471
|
+
)
|
|
1472
|
+
init(ctx: WorkflowContext<InitResponse>): StepOutput<{ url: string; ref: string }> {
|
|
1473
|
+
return {
|
|
1474
|
+
out: {
|
|
1475
|
+
url: ctx.input.authorization_url,
|
|
1476
|
+
ref: ctx.input.reference,
|
|
1477
|
+
},
|
|
1478
|
+
};
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
@Responder("json", {
|
|
1482
|
+
body: { url: v.stepResult("init", "url"), reference: v.stepResult("init", "ref") },
|
|
1483
|
+
}, { order: 1 })
|
|
1484
|
+
respond() {}
|
|
1485
|
+
}
|
|
1486
|
+
```
|
|
1487
|
+
|
|
1488
|
+
You can still use the classic style (`Paystack.id` + `Paystack.actions.someAction`) if you prefer.
|
|
1489
|
+
|
|
1490
|
+
**Typed connectors also work in builder and direct runs:**
|
|
1491
|
+
|
|
1492
|
+
```typescript
|
|
1493
|
+
// Builder
|
|
1494
|
+
workflow.step("init", (s) =>
|
|
1495
|
+
s.connector(Paystack, "initializeTransaction", {
|
|
1496
|
+
body: { email: "{{ trigger.email }}", amount: "{{ trigger.amount }}" },
|
|
1497
|
+
headers: { "Idempotency-Key": "{{ trigger.idempotencyKey }}" },
|
|
1498
|
+
})
|
|
1499
|
+
);
|
|
1500
|
+
|
|
1501
|
+
// Direct connector execution
|
|
1502
|
+
await flosync.runConnector(Paystack, "verifyTransaction", {
|
|
1503
|
+
pathParams: { reference: "ref_123" },
|
|
1504
|
+
});
|
|
1505
|
+
```
|
|
1506
|
+
|
|
1507
|
+
Template strings are accepted in typed request fields (`body`, `params`, `pathParams`, `headers`, `vars`) so workflow expressions continue to work with strong typing.
|
|
1508
|
+
|
|
1509
|
+
Available type helpers:
|
|
1510
|
+
|
|
1511
|
+
| Helper | Description |
|
|
1512
|
+
|--------|-------------|
|
|
1513
|
+
| `ConnectorBody<TDef, TAction>` | Extracts `body` type |
|
|
1514
|
+
| `ConnectorParams<TDef, TAction>` | Extracts `params` type |
|
|
1515
|
+
| `ConnectorPathParams<TDef, TAction>` | Extracts `pathParams` type |
|
|
1516
|
+
| `ConnectorHeaders<TDef, TAction>` | Extracts `headers` type |
|
|
1517
|
+
| `ConnectorVars<TDef, TAction>` | Extracts `vars` type |
|
|
1518
|
+
| `ConnectorResponse<TDef, TAction>` | Extracts `response` type |
|
|
1519
|
+
| `ConnectorActionRequest<TDef, TAction>` | Extracts full request shape |
|
|
1520
|
+
| `ConnectorTypedRequestConfig<TDef, TAction>` | Typed decorator/builder request config |
|
|
1521
|
+
|
|
1522
|
+
Examples-first guide:
|
|
1523
|
+
|
|
1524
|
+
- [`Typed Connector End-to-End Samples`](./TYPED_CONNECTOR_EXAMPLES.md)
|
|
1525
|
+
|
|
788
1526
|
## Connectors by ID
|
|
789
1527
|
|
|
790
1528
|
Use `s.connector(connectorId, action, config)` with any connector ID. For remote runs, connectors are resolved from your account. For local runs, register connectors first with `flosync.registerConnector(id, connector)` or pass config in `configure({ connectors: { 'connector-id': { ... } } })`.
|
|
@@ -849,7 +1587,7 @@ const data = await client.connectors.execute('paystack', 'Verify Transaction', {
|
|
|
849
1587
|
| `client.workflows.pull(groupId)` | Fetch workflow as IWorkflow |
|
|
850
1588
|
| `client.workflows.list(options?)` | List workflow groups |
|
|
851
1589
|
| `client.workflows.run(groupId, triggerId, payload)` | Run by trigger ID (payload may include `environment: "dev" \| "prod"`) |
|
|
852
|
-
| `client.workflows.runByWebhook(path, method, payload)` |
|
|
1590
|
+
| `client.workflows.runByWebhook(path, method, payload)` | **`POST /workflows/test/webhook`** — run the workflow whose HTTP trigger matches `path` and `method` (no group id in the request). Payload may include `environment`, `executionHeaders`, and the child body fields (merged into `payload` for the API). |
|
|
853
1591
|
| `client.workflows.promote(groupId)` | Promote to production |
|
|
854
1592
|
|
|
855
1593
|
See [Workflows](../docs/WORKFLOWS.md) for full documentation. See [Building and Pushing Custom Connectors](../docs/BUILDING_CONNECTORS.md) for connectors.
|