@gravito/flux 3.0.0 → 3.0.1
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/dist/bun.d.cts +1 -1
- package/dist/bun.d.ts +1 -1
- package/dist/{chunk-LULCFPIK.js → chunk-3JGQYHUN.js} +4 -2
- package/dist/chunk-3JGQYHUN.js.map +1 -0
- package/dist/{chunk-X3NC7HS4.cjs → chunk-5OXXH442.cjs} +10 -8
- package/dist/chunk-5OXXH442.cjs.map +1 -0
- package/dist/index.cjs +7 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +39 -5
- package/dist/index.d.ts +39 -5
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/index.node.cjs +2 -2
- package/dist/index.node.d.cts +59 -66
- package/dist/index.node.d.ts +59 -66
- package/dist/index.node.js +1 -1
- package/dist/types-CZwYGpou.d.cts +353 -0
- package/dist/types-CZwYGpou.d.ts +353 -0
- package/package.json +3 -3
- package/dist/chunk-LULCFPIK.js.map +0 -1
- package/dist/chunk-X3NC7HS4.cjs.map +0 -1
- package/dist/types-cnIU1O3n.d.cts +0 -250
- package/dist/types-cnIU1O3n.d.ts +0 -250
package/dist/index.d.ts
CHANGED
|
@@ -1,29 +1,63 @@
|
|
|
1
|
-
import { W as WorkflowDefinition, F as FluxWaitResult } from './types-
|
|
2
|
-
export { a as FluxConfig, b as FluxLogger, c as FluxResult, d as FluxTraceEvent, e as FluxTraceEventType, f as FluxTraceSink, S as StepDefinition, g as StepDescriptor, h as StepExecution, i as StepResult, j as WorkflowContext, k as WorkflowDescriptor, l as WorkflowFilter, m as WorkflowState, n as WorkflowStatus, o as WorkflowStorage } from './types-
|
|
1
|
+
import { W as WorkflowDefinition, F as FluxWaitResult } from './types-CZwYGpou.js';
|
|
2
|
+
export { a as FluxConfig, b as FluxLogger, c as FluxResult, d as FluxTraceEvent, e as FluxTraceEventType, f as FluxTraceSink, S as StepDefinition, g as StepDescriptor, h as StepExecution, i as StepResult, j as WorkflowContext, k as WorkflowDescriptor, l as WorkflowFilter, m as WorkflowState, n as WorkflowStatus, o as WorkflowStorage } from './types-CZwYGpou.js';
|
|
3
3
|
import { FluxEngine } from './index.node.js';
|
|
4
4
|
export { ContextManager, FluxConsoleLogger, FluxSilentLogger, JsonFileTraceSink, MemoryStorage, OrbitFlux, OrbitFluxOptions, StateMachine, StepExecutor, WorkflowBuilder, createWorkflow } from './index.node.js';
|
|
5
5
|
export { BunSQLiteStorage, BunSQLiteStorageOptions } from './bun.js';
|
|
6
|
+
import '@gravito/core';
|
|
6
7
|
import 'bun:sqlite';
|
|
7
8
|
|
|
9
|
+
/**
|
|
10
|
+
* Performance metrics captured during a workflow profiling session.
|
|
11
|
+
*
|
|
12
|
+
* @public
|
|
13
|
+
* @since 3.0.0
|
|
14
|
+
*/
|
|
8
15
|
interface ProfileMetrics {
|
|
16
|
+
/** Total wall-clock duration of the workflow execution in milliseconds. */
|
|
9
17
|
durationMs: number;
|
|
18
|
+
/** Amount of time spent in user-space CPU operations in milliseconds. */
|
|
10
19
|
cpuUserMs: number;
|
|
20
|
+
/** Amount of time spent in system-space CPU operations in milliseconds. */
|
|
11
21
|
cpuSysMs: number;
|
|
22
|
+
/** Estimated heap memory increase during execution in bytes. */
|
|
12
23
|
memDeltaBytes: number;
|
|
24
|
+
/** Ratio of CPU time to wall-clock time (0.0 to 1.0+). Higher values indicate CPU-bound tasks. */
|
|
13
25
|
cpuRatio: number;
|
|
14
26
|
}
|
|
27
|
+
/**
|
|
28
|
+
* Concurrency recommendations generated by the profiler.
|
|
29
|
+
*
|
|
30
|
+
* @public
|
|
31
|
+
* @since 3.0.0
|
|
32
|
+
*/
|
|
15
33
|
interface ProfileRecommendation {
|
|
34
|
+
/** The identified primary bottleneck type. */
|
|
16
35
|
type: 'IO_BOUND' | 'CPU_BOUND' | 'MEMORY_BOUND';
|
|
36
|
+
/** Maximum safe concurrency considering memory and system stability. */
|
|
17
37
|
safeConcurrency: number;
|
|
38
|
+
/** Most efficient concurrency level considering CPU utilization. */
|
|
18
39
|
efficientConcurrency: number;
|
|
40
|
+
/** A suggested range for worker concurrency configuration. */
|
|
19
41
|
suggestedConcurrency: string;
|
|
42
|
+
/** Detailed explanation for the recommendation. */
|
|
20
43
|
reason: string;
|
|
21
44
|
}
|
|
22
45
|
/**
|
|
23
|
-
*
|
|
46
|
+
* WorkflowProfiler analyzes workflow performance characteristics.
|
|
47
|
+
*
|
|
48
|
+
* It measures CPU usage, memory consumption, and execution duration to recommend
|
|
49
|
+
* optimal concurrency settings for Gravito Quasar workers or high-throughput consumers.
|
|
50
|
+
*
|
|
51
|
+
* @example
|
|
52
|
+
* ```typescript
|
|
53
|
+
* const profiler = new WorkflowProfiler();
|
|
54
|
+
* const metrics = await profiler.profile(myWorkflow, { input: 'data' });
|
|
55
|
+
* const advice = profiler.recommend(metrics);
|
|
56
|
+
* console.log(advice.suggestedConcurrency);
|
|
57
|
+
* ```
|
|
24
58
|
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
59
|
+
* @public
|
|
60
|
+
* @since 3.0.0
|
|
27
61
|
*/
|
|
28
62
|
declare class WorkflowProfiler {
|
|
29
63
|
private engine?;
|
package/dist/index.js
CHANGED
|
@@ -10,7 +10,7 @@ import {
|
|
|
10
10
|
StepExecutor,
|
|
11
11
|
WorkflowBuilder,
|
|
12
12
|
createWorkflow
|
|
13
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-3JGQYHUN.js";
|
|
14
14
|
import {
|
|
15
15
|
BunSQLiteStorage
|
|
16
16
|
} from "./chunk-ZAMVC732.js";
|
|
@@ -31,7 +31,7 @@ var WorkflowProfiler = class {
|
|
|
31
31
|
*/
|
|
32
32
|
async profile(workflow, input) {
|
|
33
33
|
try {
|
|
34
|
-
await this.engine
|
|
34
|
+
await this.engine?.execute(workflow, input);
|
|
35
35
|
} catch {
|
|
36
36
|
}
|
|
37
37
|
if (global.gc) {
|
|
@@ -40,7 +40,7 @@ var WorkflowProfiler = class {
|
|
|
40
40
|
const startCpu = process.cpuUsage();
|
|
41
41
|
const startMem = process.memoryUsage().heapUsed;
|
|
42
42
|
const startTime = process.hrtime.bigint();
|
|
43
|
-
await this.engine
|
|
43
|
+
await this.engine?.execute(workflow, input);
|
|
44
44
|
const endTime = process.hrtime.bigint();
|
|
45
45
|
const endCpu = process.cpuUsage(startCpu);
|
|
46
46
|
const endMem = process.memoryUsage().heapUsed;
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/profiler/WorkflowProfiler.ts","../src/index.ts"],"sourcesContent":["import * as os from 'os'\nimport { FluxEngine } from '../engine/FluxEngine'\nimport { FluxSilentLogger } from '../logger/FluxLogger'\nimport type { WorkflowDefinition } from '../types'\n\nexport interface ProfileMetrics {\n durationMs: number\n cpuUserMs: number\n cpuSysMs: number\n memDeltaBytes: number\n cpuRatio: number\n}\n\nexport interface ProfileRecommendation {\n type: 'IO_BOUND' | 'CPU_BOUND' | 'MEMORY_BOUND'\n safeConcurrency: number\n efficientConcurrency: number\n suggestedConcurrency: string\n reason: string\n}\n\n/**\n * Workflow Profiler\n *\n * Analyzes workflow performance characteristics to recommend\n * optimal concurrency settings for Consumer workers.\n */\nexport class WorkflowProfiler {\n constructor(private engine?: FluxEngine) {\n if (!this.engine) {\n // Default minimal engine for profiling (Silent)\n this.engine = new FluxEngine({\n logger: new FluxSilentLogger(),\n })\n }\n }\n\n /**\n * Run a profile session for a specific workflow\n */\n async profile<TInput>(\n workflow: WorkflowDefinition<TInput, any>,\n input: TInput\n ): Promise<ProfileMetrics> {\n // 1. Warmup (JIT)\n try {\n await this.engine!.execute(workflow, input)\n } catch {}\n\n // 2. Measure\n if (global.gc) {\n global.gc()\n }\n\n const startCpu = process.cpuUsage()\n const startMem = process.memoryUsage().heapUsed\n const startTime = process.hrtime.bigint()\n\n await this.engine!.execute(workflow, input)\n\n const endTime = process.hrtime.bigint()\n const endCpu = process.cpuUsage(startCpu)\n const endMem = process.memoryUsage().heapUsed\n\n // 3. Calculate\n const durationNs = Number(endTime - startTime)\n const durationMs = durationNs / 1_000_000\n const cpuUserMs = endCpu.user / 1000\n const cpuSysMs = endCpu.system / 1000\n const totalCpuMs = cpuUserMs + cpuSysMs\n const memDeltaBytes = Math.max(0, endMem - startMem) // Clamp to 0\n\n // CPU Ratio: How much % of the time was spent on CPU vs Waiting\n const cpuRatio = totalCpuMs / durationMs\n\n return {\n durationMs,\n cpuUserMs,\n cpuSysMs,\n memDeltaBytes,\n cpuRatio,\n }\n }\n\n /**\n * Generate recommendations based on metrics and current environment\n */\n recommend(\n metrics: ProfileMetrics,\n config?: { configuredConcurrency?: number }\n ): ProfileRecommendation {\n const totalMem = os.totalmem()\n const cpus = os.cpus().length\n\n // 1. Analyze Bottleneck Type\n let type: ProfileRecommendation['type'] = 'IO_BOUND'\n if (metrics.cpuRatio > 0.5) {\n type = 'CPU_BOUND'\n } else if (metrics.memDeltaBytes > 50 * 1024 * 1024) {\n // > 50MB per run\n type = 'MEMORY_BOUND'\n }\n\n // 2. Calculate Limits\n\n // Memory Limit: Keep 30% buffer for system, divide rest by per-workflow memory\n const safeMem = totalMem * 0.7\n // Use at least 1MB as baseline to avoid division by zero or huge numbers\n const perInstanceMem = Math.max(metrics.memDeltaBytes, 1024 * 1024)\n const maxMemConcurrency = Math.floor(safeMem / perInstanceMem)\n\n // CPU Limit:\n // If IO Bound (0.2% cpu), we can run many. 100% / 0.2% = 500 tasks per core.\n // We cap efficiency at a reasonable number to avoid Event Loop Lag density.\n const cpuEfficiencyFactor = 1 / Math.max(metrics.cpuRatio, 0.001) // Avoid div by 0\n const maxCpuConcurrency = Math.floor(cpus * cpuEfficiencyFactor)\n\n // 3. Synthesize Recommendation\n const safe = Math.min(maxMemConcurrency, 200) // Hard cap at 200 for sanity\n let efficient = Math.min(maxCpuConcurrency, 200)\n\n // If CPU bound, strict limit based on cores\n if (type === 'CPU_BOUND') {\n efficient = cpus // 1:1 mapping is best for CPU bound\n }\n\n const recommended = Math.min(safe, efficient)\n\n let reason = ''\n if (type === 'IO_BOUND') {\n reason = `Workflow is I/O intensive (CPU usage ${(metrics.cpuRatio * 100).toFixed(1)}%). It is safe to run high concurrency up to ${recommended}.`\n } else if (type === 'CPU_BOUND') {\n reason = `Workflow is CPU intensive. Limiting concurrency to match CPU cores (${cpus}) is recommended to prevent blocking.`\n } else {\n reason = `Workflow consumes significant memory (${(metrics.memDeltaBytes / 1024 / 1024).toFixed(1)}MB). Concurrency limited by available RAM.`\n }\n\n if (config?.configuredConcurrency && config.configuredConcurrency > recommended) {\n reason += ` \\n⚠️ Warning: Your current setting (${config.configuredConcurrency}) exceeds the recommended limit (${recommended}).`\n }\n\n return {\n type,\n safeConcurrency: safe,\n efficientConcurrency: efficient,\n suggestedConcurrency: `${Math.max(1, Math.floor(recommended * 0.5))} - ${recommended}`,\n reason,\n }\n }\n}\n","/**\n * @fileoverview @gravito/flux - Platform-agnostic Workflow Engine\n *\n * High-performance, type-safe workflow engine with Bun optimizations.\n *\n * @example Basic Usage\n * ```typescript\n * import { FluxEngine, createWorkflow } from '@gravito/flux'\n *\n * const workflow = createWorkflow('order-process')\n * .input<{ orderId: string }>()\n * .step('validate', async (ctx) => {\n * ctx.data.order = await fetchOrder(ctx.input.orderId)\n * })\n * .step('process', async (ctx) => {\n * await processPayment(ctx.data.order)\n * })\n * .commit('notify', async (ctx) => {\n * await sendEmail(ctx.data.order.email)\n * })\n *\n * const engine = new FluxEngine()\n * const result = await engine.execute(workflow, { orderId: '123' })\n * ```\n *\n * @module @gravito/flux\n */\n\n// Builder\nexport { createWorkflow, WorkflowBuilder } from './builder/WorkflowBuilder'\nexport { ContextManager } from './core/ContextManager'\n// Core (for advanced usage)\nexport { StateMachine } from './core/StateMachine'\nexport { StepExecutor } from './core/StepExecutor'\n// Core\nexport { FluxEngine } from './engine/FluxEngine'\n// Logger\nexport { FluxConsoleLogger, FluxSilentLogger } from './logger/FluxLogger'\n// Gravito Integration\nexport { OrbitFlux, type OrbitFluxOptions } from './orbit/OrbitFlux'\n// Profiler\nexport {\n type ProfileMetrics,\n type ProfileRecommendation,\n WorkflowProfiler,\n} from './profiler/WorkflowProfiler'\nexport { BunSQLiteStorage, type BunSQLiteStorageOptions } from './storage/BunSQLiteStorage'\n// Storage\nexport { MemoryStorage } from './storage/MemoryStorage'\n// Trace\nexport { JsonFileTraceSink } from './trace/JsonFileTraceSink'\n\n// Types\nexport type {\n // Config\n FluxConfig,\n // Logger\n FluxLogger,\n FluxResult,\n // Trace\n FluxTraceEvent,\n FluxTraceEventType,\n FluxTraceSink,\n // Helper\n FluxWaitResult,\n // Step types\n StepDefinition,\n StepDescriptor,\n StepExecution,\n StepResult,\n WorkflowContext,\n WorkflowDefinition,\n WorkflowDescriptor,\n WorkflowFilter,\n WorkflowState,\n // Core types\n WorkflowStatus,\n // Storage\n WorkflowStorage,\n} from './types'\n\n/**\n * Flux helper utilities\n */\nexport const Flux = {\n /**\n * Suspend workflow execution and wait for a signal\n *\n * @param signal - Signal name to wait for\n */\n wait: (signal: string): import('./types').FluxWaitResult => ({\n __kind: 'flux_wait',\n signal,\n }),\n}\n"],"mappings":"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","names":["cpus"]}
|
|
1
|
+
{"version":3,"sources":["../src/profiler/WorkflowProfiler.ts","../src/index.ts"],"sourcesContent":["import * as os from 'node:os'\nimport { FluxEngine } from '../engine/FluxEngine'\nimport { FluxSilentLogger } from '../logger/FluxLogger'\nimport type { WorkflowDefinition } from '../types'\n\n/**\n * Performance metrics captured during a workflow profiling session.\n *\n * @public\n * @since 3.0.0\n */\nexport interface ProfileMetrics {\n /** Total wall-clock duration of the workflow execution in milliseconds. */\n durationMs: number\n /** Amount of time spent in user-space CPU operations in milliseconds. */\n cpuUserMs: number\n /** Amount of time spent in system-space CPU operations in milliseconds. */\n cpuSysMs: number\n /** Estimated heap memory increase during execution in bytes. */\n memDeltaBytes: number\n /** Ratio of CPU time to wall-clock time (0.0 to 1.0+). Higher values indicate CPU-bound tasks. */\n cpuRatio: number\n}\n\n/**\n * Concurrency recommendations generated by the profiler.\n *\n * @public\n * @since 3.0.0\n */\nexport interface ProfileRecommendation {\n /** The identified primary bottleneck type. */\n type: 'IO_BOUND' | 'CPU_BOUND' | 'MEMORY_BOUND'\n /** Maximum safe concurrency considering memory and system stability. */\n safeConcurrency: number\n /** Most efficient concurrency level considering CPU utilization. */\n efficientConcurrency: number\n /** A suggested range for worker concurrency configuration. */\n suggestedConcurrency: string\n /** Detailed explanation for the recommendation. */\n reason: string\n}\n\n/**\n * WorkflowProfiler analyzes workflow performance characteristics.\n *\n * It measures CPU usage, memory consumption, and execution duration to recommend\n * optimal concurrency settings for Gravito Quasar workers or high-throughput consumers.\n *\n * @example\n * ```typescript\n * const profiler = new WorkflowProfiler();\n * const metrics = await profiler.profile(myWorkflow, { input: 'data' });\n * const advice = profiler.recommend(metrics);\n * console.log(advice.suggestedConcurrency);\n * ```\n *\n * @public\n * @since 3.0.0\n */\nexport class WorkflowProfiler {\n constructor(private engine?: FluxEngine) {\n if (!this.engine) {\n // Default minimal engine for profiling (Silent)\n this.engine = new FluxEngine({\n logger: new FluxSilentLogger(),\n })\n }\n }\n\n /**\n * Run a profile session for a specific workflow\n */\n async profile<TInput>(\n workflow: WorkflowDefinition<TInput, any>,\n input: TInput\n ): Promise<ProfileMetrics> {\n // 1. Warmup (JIT)\n try {\n await this.engine?.execute(workflow, input)\n } catch {}\n\n // 2. Measure\n if (global.gc) {\n global.gc()\n }\n\n const startCpu = process.cpuUsage()\n const startMem = process.memoryUsage().heapUsed\n const startTime = process.hrtime.bigint()\n\n await this.engine?.execute(workflow, input)\n\n const endTime = process.hrtime.bigint()\n const endCpu = process.cpuUsage(startCpu)\n const endMem = process.memoryUsage().heapUsed\n\n // 3. Calculate\n const durationNs = Number(endTime - startTime)\n const durationMs = durationNs / 1_000_000\n const cpuUserMs = endCpu.user / 1000\n const cpuSysMs = endCpu.system / 1000\n const totalCpuMs = cpuUserMs + cpuSysMs\n const memDeltaBytes = Math.max(0, endMem - startMem) // Clamp to 0\n\n // CPU Ratio: How much % of the time was spent on CPU vs Waiting\n const cpuRatio = totalCpuMs / durationMs\n\n return {\n durationMs,\n cpuUserMs,\n cpuSysMs,\n memDeltaBytes,\n cpuRatio,\n }\n }\n\n /**\n * Generate recommendations based on metrics and current environment\n */\n recommend(\n metrics: ProfileMetrics,\n config?: { configuredConcurrency?: number }\n ): ProfileRecommendation {\n const totalMem = os.totalmem()\n const cpus = os.cpus().length\n\n // 1. Analyze Bottleneck Type\n let type: ProfileRecommendation['type'] = 'IO_BOUND'\n if (metrics.cpuRatio > 0.5) {\n type = 'CPU_BOUND'\n } else if (metrics.memDeltaBytes > 50 * 1024 * 1024) {\n // > 50MB per run\n type = 'MEMORY_BOUND'\n }\n\n // 2. Calculate Limits\n\n // Memory Limit: Keep 30% buffer for system, divide rest by per-workflow memory\n const safeMem = totalMem * 0.7\n // Use at least 1MB as baseline to avoid division by zero or huge numbers\n const perInstanceMem = Math.max(metrics.memDeltaBytes, 1024 * 1024)\n const maxMemConcurrency = Math.floor(safeMem / perInstanceMem)\n\n // CPU Limit:\n // If IO Bound (0.2% cpu), we can run many. 100% / 0.2% = 500 tasks per core.\n // We cap efficiency at a reasonable number to avoid Event Loop Lag density.\n const cpuEfficiencyFactor = 1 / Math.max(metrics.cpuRatio, 0.001) // Avoid div by 0\n const maxCpuConcurrency = Math.floor(cpus * cpuEfficiencyFactor)\n\n // 3. Synthesize Recommendation\n const safe = Math.min(maxMemConcurrency, 200) // Hard cap at 200 for sanity\n let efficient = Math.min(maxCpuConcurrency, 200)\n\n // If CPU bound, strict limit based on cores\n if (type === 'CPU_BOUND') {\n efficient = cpus // 1:1 mapping is best for CPU bound\n }\n\n const recommended = Math.min(safe, efficient)\n\n let reason = ''\n if (type === 'IO_BOUND') {\n reason = `Workflow is I/O intensive (CPU usage ${(metrics.cpuRatio * 100).toFixed(1)}%). It is safe to run high concurrency up to ${recommended}.`\n } else if (type === 'CPU_BOUND') {\n reason = `Workflow is CPU intensive. Limiting concurrency to match CPU cores (${cpus}) is recommended to prevent blocking.`\n } else {\n reason = `Workflow consumes significant memory (${(metrics.memDeltaBytes / 1024 / 1024).toFixed(1)}MB). Concurrency limited by available RAM.`\n }\n\n if (config?.configuredConcurrency && config.configuredConcurrency > recommended) {\n reason += ` \\n⚠️ Warning: Your current setting (${config.configuredConcurrency}) exceeds the recommended limit (${recommended}).`\n }\n\n return {\n type,\n safeConcurrency: safe,\n efficientConcurrency: efficient,\n suggestedConcurrency: `${Math.max(1, Math.floor(recommended * 0.5))} - ${recommended}`,\n reason,\n }\n }\n}\n","/**\n * @fileoverview @gravito/flux - Platform-agnostic Workflow Engine\n *\n * High-performance, type-safe workflow engine with Bun optimizations.\n *\n * @example Basic Usage\n * ```typescript\n * import { FluxEngine, createWorkflow } from '@gravito/flux'\n *\n * const workflow = createWorkflow('order-process')\n * .input<{ orderId: string }>()\n * .step('validate', async (ctx) => {\n * ctx.data.order = await fetchOrder(ctx.input.orderId)\n * })\n * .step('process', async (ctx) => {\n * await processPayment(ctx.data.order)\n * })\n * .commit('notify', async (ctx) => {\n * await sendEmail(ctx.data.order.email)\n * })\n *\n * const engine = new FluxEngine()\n * const result = await engine.execute(workflow, { orderId: '123' })\n * ```\n *\n * @module @gravito/flux\n */\n\n// Builder\nexport { createWorkflow, WorkflowBuilder } from './builder/WorkflowBuilder'\nexport { ContextManager } from './core/ContextManager'\n// Core (for advanced usage)\nexport { StateMachine } from './core/StateMachine'\nexport { StepExecutor } from './core/StepExecutor'\n// Core\nexport { FluxEngine } from './engine/FluxEngine'\n// Logger\nexport { FluxConsoleLogger, FluxSilentLogger } from './logger/FluxLogger'\n// Gravito Integration\nexport { OrbitFlux, type OrbitFluxOptions } from './orbit/OrbitFlux'\n// Profiler\nexport {\n type ProfileMetrics,\n type ProfileRecommendation,\n WorkflowProfiler,\n} from './profiler/WorkflowProfiler'\nexport { BunSQLiteStorage, type BunSQLiteStorageOptions } from './storage/BunSQLiteStorage'\n// Storage\nexport { MemoryStorage } from './storage/MemoryStorage'\n// Trace\nexport { JsonFileTraceSink } from './trace/JsonFileTraceSink'\n\n// Types\nexport type {\n // Config\n FluxConfig,\n // Logger\n FluxLogger,\n FluxResult,\n // Trace\n FluxTraceEvent,\n FluxTraceEventType,\n FluxTraceSink,\n // Helper\n FluxWaitResult,\n // Step types\n StepDefinition,\n StepDescriptor,\n StepExecution,\n StepResult,\n WorkflowContext,\n WorkflowDefinition,\n WorkflowDescriptor,\n WorkflowFilter,\n WorkflowState,\n // Core types\n WorkflowStatus,\n // Storage\n WorkflowStorage,\n} from './types'\n\n/**\n * Flux helper utilities\n */\nexport const Flux = {\n /**\n * Suspend workflow execution and wait for a signal\n *\n * @param signal - Signal name to wait for\n */\n wait: (signal: string): import('./types').FluxWaitResult => ({\n __kind: 'flux_wait',\n signal,\n }),\n}\n"],"mappings":"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","names":["cpus"]}
|
package/dist/index.node.cjs
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
|
|
11
11
|
|
|
12
12
|
|
|
13
|
-
var
|
|
13
|
+
var _chunk5OXXH442cjs = require('./chunk-5OXXH442.cjs');
|
|
14
14
|
require('./chunk-SJSPR4ZU.cjs');
|
|
15
15
|
|
|
16
16
|
|
|
@@ -24,5 +24,5 @@ require('./chunk-SJSPR4ZU.cjs');
|
|
|
24
24
|
|
|
25
25
|
|
|
26
26
|
|
|
27
|
-
exports.ContextManager =
|
|
27
|
+
exports.ContextManager = _chunk5OXXH442cjs.ContextManager; exports.FluxConsoleLogger = _chunk5OXXH442cjs.FluxConsoleLogger; exports.FluxEngine = _chunk5OXXH442cjs.FluxEngine; exports.FluxSilentLogger = _chunk5OXXH442cjs.FluxSilentLogger; exports.JsonFileTraceSink = _chunk5OXXH442cjs.JsonFileTraceSink; exports.MemoryStorage = _chunk5OXXH442cjs.MemoryStorage; exports.OrbitFlux = _chunk5OXXH442cjs.OrbitFlux; exports.StateMachine = _chunk5OXXH442cjs.StateMachine; exports.StepExecutor = _chunk5OXXH442cjs.StepExecutor; exports.WorkflowBuilder = _chunk5OXXH442cjs.WorkflowBuilder; exports.createWorkflow = _chunk5OXXH442cjs.createWorkflow;
|
|
28
28
|
//# sourceMappingURL=index.node.cjs.map
|
package/dist/index.node.d.cts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { j as WorkflowContext, F as FluxWaitResult, W as WorkflowDefinition, k as WorkflowDescriptor, a as FluxConfig, c as FluxResult, m as WorkflowState, o as WorkflowStorage, l as WorkflowFilter, f as FluxTraceSink, d as FluxTraceEvent, n as WorkflowStatus, S as StepDefinition, h as StepExecution, i as StepResult, b as FluxLogger } from './types-
|
|
2
|
-
export { e as FluxTraceEventType, g as StepDescriptor } from './types-
|
|
1
|
+
import { j as WorkflowContext, F as FluxWaitResult, W as WorkflowDefinition, k as WorkflowDescriptor, a as FluxConfig, c as FluxResult, m as WorkflowState, o as WorkflowStorage, l as WorkflowFilter, f as FluxTraceSink, d as FluxTraceEvent, n as WorkflowStatus, S as StepDefinition, h as StepExecution, i as StepResult, b as FluxLogger } from './types-CZwYGpou.cjs';
|
|
2
|
+
export { e as FluxTraceEventType, g as StepDescriptor } from './types-CZwYGpou.cjs';
|
|
3
|
+
import { GravitoOrbit, PlanetCore } from '@gravito/core';
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* @fileoverview Workflow Builder - Fluent API for defining workflows
|
|
@@ -10,39 +11,34 @@ export { e as FluxTraceEventType, g as StepDescriptor } from './types-cnIU1O3n.c
|
|
|
10
11
|
*/
|
|
11
12
|
|
|
12
13
|
/**
|
|
13
|
-
*
|
|
14
|
+
* Options for configuring a single step in a workflow.
|
|
15
|
+
* @public
|
|
14
16
|
*/
|
|
15
17
|
interface StepOptions<TInput = any, TData = any> {
|
|
18
|
+
/** Maximum number of automatic retries on failure (default: 0) */
|
|
16
19
|
retries?: number;
|
|
20
|
+
/** Maximum execution time in milliseconds before timeout error */
|
|
17
21
|
timeout?: number;
|
|
22
|
+
/** Predicate to determine if the step should be executed or skipped */
|
|
18
23
|
when?: (ctx: WorkflowContext<TInput, TData>) => boolean;
|
|
24
|
+
/** Logic to undo the effects of this step if a later step fails */
|
|
19
25
|
compensate?: (ctx: WorkflowContext<TInput, TData>) => Promise<void> | void;
|
|
20
26
|
}
|
|
21
27
|
/**
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
* Provides fluent API for defining workflows with type inference.
|
|
28
|
+
* WorkflowBuilder provides a fluent, type-safe API for defining sequential logic.
|
|
25
29
|
*
|
|
26
30
|
* @example
|
|
27
31
|
* ```typescript
|
|
28
|
-
* const
|
|
32
|
+
* const myFlow = createWorkflow('process-order')
|
|
29
33
|
* .input<{ orderId: string }>()
|
|
30
|
-
* .step('validate', async (ctx) => {
|
|
31
|
-
*
|
|
32
|
-
* })
|
|
33
|
-
* .step('process', async (ctx) => {
|
|
34
|
-
* await processOrder(ctx.data.order)
|
|
35
|
-
* }, {
|
|
36
|
-
* compensate: async (ctx) => {
|
|
37
|
-
* await cancelOrder(ctx.data.order.id)
|
|
38
|
-
* }
|
|
39
|
-
* })
|
|
40
|
-
* .commit('notify', async (ctx) => {
|
|
41
|
-
* await sendEmail(ctx.data.order.email)
|
|
42
|
-
* })
|
|
34
|
+
* .step('validate', async (ctx) => { ... })
|
|
35
|
+
* .step('charge', async (ctx) => { ... }, { compensate: async (ctx) => { ... } })
|
|
36
|
+
* .commit('ship', async (ctx) => { ... });
|
|
43
37
|
* ```
|
|
38
|
+
* @public
|
|
44
39
|
*/
|
|
45
40
|
declare class WorkflowBuilder<TInput = unknown, TData = Record<string, unknown>> {
|
|
41
|
+
drum: any;
|
|
46
42
|
private _name;
|
|
47
43
|
private _steps;
|
|
48
44
|
private _validateInput?;
|
|
@@ -66,7 +62,7 @@ declare class WorkflowBuilder<TInput = unknown, TData = Record<string, unknown>>
|
|
|
66
62
|
/**
|
|
67
63
|
* Add a step to the workflow
|
|
68
64
|
*/
|
|
69
|
-
step(name: string, handler: (ctx: WorkflowContext<TInput, TData>) => Promise<void | FluxWaitResult> |
|
|
65
|
+
step(name: string, handler: (ctx: WorkflowContext<TInput, TData>) => void | Promise<void | undefined | FluxWaitResult> | undefined | FluxWaitResult, options?: StepOptions<TInput, TData>): this;
|
|
70
66
|
/**
|
|
71
67
|
* Add a commit step (always executes, even on replay)
|
|
72
68
|
*
|
|
@@ -120,22 +116,27 @@ declare function createWorkflow(name: string): WorkflowBuilder;
|
|
|
120
116
|
*/
|
|
121
117
|
|
|
122
118
|
/**
|
|
123
|
-
*
|
|
124
|
-
*
|
|
125
|
-
*
|
|
119
|
+
* FluxEngine is the primary execution orchestrator for workflows.
|
|
120
|
+
* It manages context lifecycle, persistence via storage adapters,
|
|
121
|
+
* step execution with retries, and transactional rollbacks (compensation).
|
|
126
122
|
*
|
|
127
123
|
* @example
|
|
128
124
|
* ```typescript
|
|
129
|
-
* const engine = new FluxEngine({
|
|
125
|
+
* const engine = new FluxEngine({
|
|
126
|
+
* storage: new BunSQLiteStorage(),
|
|
127
|
+
* logger: new FluxConsoleLogger()
|
|
128
|
+
* });
|
|
130
129
|
*
|
|
131
|
-
* const workflow = createWorkflow('
|
|
132
|
-
* .
|
|
133
|
-
* .step('
|
|
134
|
-
* .step('validate', async (ctx) => { ... })
|
|
135
|
-
* .commit('save', async (ctx) => { ... })
|
|
130
|
+
* const workflow = createWorkflow('onboard-user')
|
|
131
|
+
* .step('create-account', async (ctx) => { ... })
|
|
132
|
+
* .step('send-email', async (ctx) => { ... });
|
|
136
133
|
*
|
|
137
|
-
* const result = await engine.execute(workflow, {
|
|
134
|
+
* const result = await engine.execute(workflow, { email: 'user@example.com' });
|
|
135
|
+
* if (result.status === 'completed') {
|
|
136
|
+
* console.log('User onboarded successfully');
|
|
137
|
+
* }
|
|
138
138
|
* ```
|
|
139
|
+
* @public
|
|
139
140
|
*/
|
|
140
141
|
declare class FluxEngine {
|
|
141
142
|
private storage;
|
|
@@ -233,10 +234,35 @@ declare class MemoryStorage implements WorkflowStorage {
|
|
|
233
234
|
* Writes trace events to a newline-delimited JSON file.
|
|
234
235
|
*/
|
|
235
236
|
|
|
237
|
+
/**
|
|
238
|
+
* Options for configuring the `JsonFileTraceSink`.
|
|
239
|
+
*
|
|
240
|
+
* @public
|
|
241
|
+
* @since 3.0.0
|
|
242
|
+
*/
|
|
236
243
|
interface JsonFileTraceSinkOptions {
|
|
244
|
+
/** Absolute path where the trace file should be stored. */
|
|
237
245
|
path: string;
|
|
246
|
+
/** Whether to reset (clear) the file on initialization. @default true */
|
|
238
247
|
reset?: boolean;
|
|
239
248
|
}
|
|
249
|
+
/**
|
|
250
|
+
* A trace sink that writes events to a newline-delimited JSON (NDJSON) file.
|
|
251
|
+
*
|
|
252
|
+
* This sink is ideal for local development and debugging as it produces
|
|
253
|
+
* a human-readable and easily machine-parsable log of workflow events.
|
|
254
|
+
*
|
|
255
|
+
* @example
|
|
256
|
+
* ```typescript
|
|
257
|
+
* const sink = new JsonFileTraceSink({
|
|
258
|
+
* path: './traces/workflow.jsonl',
|
|
259
|
+
* reset: true
|
|
260
|
+
* });
|
|
261
|
+
* ```
|
|
262
|
+
*
|
|
263
|
+
* @public
|
|
264
|
+
* @since 3.0.0
|
|
265
|
+
*/
|
|
240
266
|
declare class JsonFileTraceSink implements FluxTraceSink {
|
|
241
267
|
private path;
|
|
242
268
|
private ready;
|
|
@@ -404,39 +430,6 @@ declare class FluxSilentLogger implements FluxLogger {
|
|
|
404
430
|
error(): void;
|
|
405
431
|
}
|
|
406
432
|
|
|
407
|
-
/**
|
|
408
|
-
* @fileoverview OrbitFlux - Gravito PlanetCore Integration
|
|
409
|
-
*
|
|
410
|
-
* Integrates FluxEngine with Gravito's PlanetCore for seamless workflow management.
|
|
411
|
-
*
|
|
412
|
-
* @module @gravito/flux
|
|
413
|
-
*/
|
|
414
|
-
|
|
415
|
-
/**
|
|
416
|
-
* Minimal PlanetCore interface for type compatibility
|
|
417
|
-
* (Avoids importing @gravito/core sources which causes rootDir issues)
|
|
418
|
-
*/
|
|
419
|
-
interface PlanetCore {
|
|
420
|
-
logger: {
|
|
421
|
-
debug(message: string, ...args: unknown[]): void;
|
|
422
|
-
info(message: string, ...args: unknown[]): void;
|
|
423
|
-
warn(message: string, ...args: unknown[]): void;
|
|
424
|
-
error(message: string, ...args: unknown[]): void;
|
|
425
|
-
};
|
|
426
|
-
services: {
|
|
427
|
-
set(key: string, value: unknown): void;
|
|
428
|
-
get<T>(key: string): T | undefined;
|
|
429
|
-
};
|
|
430
|
-
hooks: {
|
|
431
|
-
doAction(name: string, payload?: unknown): void;
|
|
432
|
-
};
|
|
433
|
-
}
|
|
434
|
-
/**
|
|
435
|
-
* GravitoOrbit interface
|
|
436
|
-
*/
|
|
437
|
-
interface GravitoOrbit {
|
|
438
|
-
install(core: PlanetCore): void | Promise<void>;
|
|
439
|
-
}
|
|
440
433
|
/**
|
|
441
434
|
* OrbitFlux configuration options
|
|
442
435
|
*/
|
|
@@ -484,8 +477,8 @@ interface OrbitFluxOptions {
|
|
|
484
477
|
* ]
|
|
485
478
|
* })
|
|
486
479
|
*
|
|
487
|
-
* // Access via
|
|
488
|
-
* const flux = core.
|
|
480
|
+
* // Access via container
|
|
481
|
+
* const flux = core.container.make<FluxEngine>('flux')
|
|
489
482
|
* await flux.execute(myWorkflow, input)
|
|
490
483
|
* ```
|
|
491
484
|
*/
|
package/dist/index.node.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { j as WorkflowContext, F as FluxWaitResult, W as WorkflowDefinition, k as WorkflowDescriptor, a as FluxConfig, c as FluxResult, m as WorkflowState, o as WorkflowStorage, l as WorkflowFilter, f as FluxTraceSink, d as FluxTraceEvent, n as WorkflowStatus, S as StepDefinition, h as StepExecution, i as StepResult, b as FluxLogger } from './types-
|
|
2
|
-
export { e as FluxTraceEventType, g as StepDescriptor } from './types-
|
|
1
|
+
import { j as WorkflowContext, F as FluxWaitResult, W as WorkflowDefinition, k as WorkflowDescriptor, a as FluxConfig, c as FluxResult, m as WorkflowState, o as WorkflowStorage, l as WorkflowFilter, f as FluxTraceSink, d as FluxTraceEvent, n as WorkflowStatus, S as StepDefinition, h as StepExecution, i as StepResult, b as FluxLogger } from './types-CZwYGpou.js';
|
|
2
|
+
export { e as FluxTraceEventType, g as StepDescriptor } from './types-CZwYGpou.js';
|
|
3
|
+
import { GravitoOrbit, PlanetCore } from '@gravito/core';
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* @fileoverview Workflow Builder - Fluent API for defining workflows
|
|
@@ -10,39 +11,34 @@ export { e as FluxTraceEventType, g as StepDescriptor } from './types-cnIU1O3n.j
|
|
|
10
11
|
*/
|
|
11
12
|
|
|
12
13
|
/**
|
|
13
|
-
*
|
|
14
|
+
* Options for configuring a single step in a workflow.
|
|
15
|
+
* @public
|
|
14
16
|
*/
|
|
15
17
|
interface StepOptions<TInput = any, TData = any> {
|
|
18
|
+
/** Maximum number of automatic retries on failure (default: 0) */
|
|
16
19
|
retries?: number;
|
|
20
|
+
/** Maximum execution time in milliseconds before timeout error */
|
|
17
21
|
timeout?: number;
|
|
22
|
+
/** Predicate to determine if the step should be executed or skipped */
|
|
18
23
|
when?: (ctx: WorkflowContext<TInput, TData>) => boolean;
|
|
24
|
+
/** Logic to undo the effects of this step if a later step fails */
|
|
19
25
|
compensate?: (ctx: WorkflowContext<TInput, TData>) => Promise<void> | void;
|
|
20
26
|
}
|
|
21
27
|
/**
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
* Provides fluent API for defining workflows with type inference.
|
|
28
|
+
* WorkflowBuilder provides a fluent, type-safe API for defining sequential logic.
|
|
25
29
|
*
|
|
26
30
|
* @example
|
|
27
31
|
* ```typescript
|
|
28
|
-
* const
|
|
32
|
+
* const myFlow = createWorkflow('process-order')
|
|
29
33
|
* .input<{ orderId: string }>()
|
|
30
|
-
* .step('validate', async (ctx) => {
|
|
31
|
-
*
|
|
32
|
-
* })
|
|
33
|
-
* .step('process', async (ctx) => {
|
|
34
|
-
* await processOrder(ctx.data.order)
|
|
35
|
-
* }, {
|
|
36
|
-
* compensate: async (ctx) => {
|
|
37
|
-
* await cancelOrder(ctx.data.order.id)
|
|
38
|
-
* }
|
|
39
|
-
* })
|
|
40
|
-
* .commit('notify', async (ctx) => {
|
|
41
|
-
* await sendEmail(ctx.data.order.email)
|
|
42
|
-
* })
|
|
34
|
+
* .step('validate', async (ctx) => { ... })
|
|
35
|
+
* .step('charge', async (ctx) => { ... }, { compensate: async (ctx) => { ... } })
|
|
36
|
+
* .commit('ship', async (ctx) => { ... });
|
|
43
37
|
* ```
|
|
38
|
+
* @public
|
|
44
39
|
*/
|
|
45
40
|
declare class WorkflowBuilder<TInput = unknown, TData = Record<string, unknown>> {
|
|
41
|
+
drum: any;
|
|
46
42
|
private _name;
|
|
47
43
|
private _steps;
|
|
48
44
|
private _validateInput?;
|
|
@@ -66,7 +62,7 @@ declare class WorkflowBuilder<TInput = unknown, TData = Record<string, unknown>>
|
|
|
66
62
|
/**
|
|
67
63
|
* Add a step to the workflow
|
|
68
64
|
*/
|
|
69
|
-
step(name: string, handler: (ctx: WorkflowContext<TInput, TData>) => Promise<void | FluxWaitResult> |
|
|
65
|
+
step(name: string, handler: (ctx: WorkflowContext<TInput, TData>) => void | Promise<void | undefined | FluxWaitResult> | undefined | FluxWaitResult, options?: StepOptions<TInput, TData>): this;
|
|
70
66
|
/**
|
|
71
67
|
* Add a commit step (always executes, even on replay)
|
|
72
68
|
*
|
|
@@ -120,22 +116,27 @@ declare function createWorkflow(name: string): WorkflowBuilder;
|
|
|
120
116
|
*/
|
|
121
117
|
|
|
122
118
|
/**
|
|
123
|
-
*
|
|
124
|
-
*
|
|
125
|
-
*
|
|
119
|
+
* FluxEngine is the primary execution orchestrator for workflows.
|
|
120
|
+
* It manages context lifecycle, persistence via storage adapters,
|
|
121
|
+
* step execution with retries, and transactional rollbacks (compensation).
|
|
126
122
|
*
|
|
127
123
|
* @example
|
|
128
124
|
* ```typescript
|
|
129
|
-
* const engine = new FluxEngine({
|
|
125
|
+
* const engine = new FluxEngine({
|
|
126
|
+
* storage: new BunSQLiteStorage(),
|
|
127
|
+
* logger: new FluxConsoleLogger()
|
|
128
|
+
* });
|
|
130
129
|
*
|
|
131
|
-
* const workflow = createWorkflow('
|
|
132
|
-
* .
|
|
133
|
-
* .step('
|
|
134
|
-
* .step('validate', async (ctx) => { ... })
|
|
135
|
-
* .commit('save', async (ctx) => { ... })
|
|
130
|
+
* const workflow = createWorkflow('onboard-user')
|
|
131
|
+
* .step('create-account', async (ctx) => { ... })
|
|
132
|
+
* .step('send-email', async (ctx) => { ... });
|
|
136
133
|
*
|
|
137
|
-
* const result = await engine.execute(workflow, {
|
|
134
|
+
* const result = await engine.execute(workflow, { email: 'user@example.com' });
|
|
135
|
+
* if (result.status === 'completed') {
|
|
136
|
+
* console.log('User onboarded successfully');
|
|
137
|
+
* }
|
|
138
138
|
* ```
|
|
139
|
+
* @public
|
|
139
140
|
*/
|
|
140
141
|
declare class FluxEngine {
|
|
141
142
|
private storage;
|
|
@@ -233,10 +234,35 @@ declare class MemoryStorage implements WorkflowStorage {
|
|
|
233
234
|
* Writes trace events to a newline-delimited JSON file.
|
|
234
235
|
*/
|
|
235
236
|
|
|
237
|
+
/**
|
|
238
|
+
* Options for configuring the `JsonFileTraceSink`.
|
|
239
|
+
*
|
|
240
|
+
* @public
|
|
241
|
+
* @since 3.0.0
|
|
242
|
+
*/
|
|
236
243
|
interface JsonFileTraceSinkOptions {
|
|
244
|
+
/** Absolute path where the trace file should be stored. */
|
|
237
245
|
path: string;
|
|
246
|
+
/** Whether to reset (clear) the file on initialization. @default true */
|
|
238
247
|
reset?: boolean;
|
|
239
248
|
}
|
|
249
|
+
/**
|
|
250
|
+
* A trace sink that writes events to a newline-delimited JSON (NDJSON) file.
|
|
251
|
+
*
|
|
252
|
+
* This sink is ideal for local development and debugging as it produces
|
|
253
|
+
* a human-readable and easily machine-parsable log of workflow events.
|
|
254
|
+
*
|
|
255
|
+
* @example
|
|
256
|
+
* ```typescript
|
|
257
|
+
* const sink = new JsonFileTraceSink({
|
|
258
|
+
* path: './traces/workflow.jsonl',
|
|
259
|
+
* reset: true
|
|
260
|
+
* });
|
|
261
|
+
* ```
|
|
262
|
+
*
|
|
263
|
+
* @public
|
|
264
|
+
* @since 3.0.0
|
|
265
|
+
*/
|
|
240
266
|
declare class JsonFileTraceSink implements FluxTraceSink {
|
|
241
267
|
private path;
|
|
242
268
|
private ready;
|
|
@@ -404,39 +430,6 @@ declare class FluxSilentLogger implements FluxLogger {
|
|
|
404
430
|
error(): void;
|
|
405
431
|
}
|
|
406
432
|
|
|
407
|
-
/**
|
|
408
|
-
* @fileoverview OrbitFlux - Gravito PlanetCore Integration
|
|
409
|
-
*
|
|
410
|
-
* Integrates FluxEngine with Gravito's PlanetCore for seamless workflow management.
|
|
411
|
-
*
|
|
412
|
-
* @module @gravito/flux
|
|
413
|
-
*/
|
|
414
|
-
|
|
415
|
-
/**
|
|
416
|
-
* Minimal PlanetCore interface for type compatibility
|
|
417
|
-
* (Avoids importing @gravito/core sources which causes rootDir issues)
|
|
418
|
-
*/
|
|
419
|
-
interface PlanetCore {
|
|
420
|
-
logger: {
|
|
421
|
-
debug(message: string, ...args: unknown[]): void;
|
|
422
|
-
info(message: string, ...args: unknown[]): void;
|
|
423
|
-
warn(message: string, ...args: unknown[]): void;
|
|
424
|
-
error(message: string, ...args: unknown[]): void;
|
|
425
|
-
};
|
|
426
|
-
services: {
|
|
427
|
-
set(key: string, value: unknown): void;
|
|
428
|
-
get<T>(key: string): T | undefined;
|
|
429
|
-
};
|
|
430
|
-
hooks: {
|
|
431
|
-
doAction(name: string, payload?: unknown): void;
|
|
432
|
-
};
|
|
433
|
-
}
|
|
434
|
-
/**
|
|
435
|
-
* GravitoOrbit interface
|
|
436
|
-
*/
|
|
437
|
-
interface GravitoOrbit {
|
|
438
|
-
install(core: PlanetCore): void | Promise<void>;
|
|
439
|
-
}
|
|
440
433
|
/**
|
|
441
434
|
* OrbitFlux configuration options
|
|
442
435
|
*/
|
|
@@ -484,8 +477,8 @@ interface OrbitFluxOptions {
|
|
|
484
477
|
* ]
|
|
485
478
|
* })
|
|
486
479
|
*
|
|
487
|
-
* // Access via
|
|
488
|
-
* const flux = core.
|
|
480
|
+
* // Access via container
|
|
481
|
+
* const flux = core.container.make<FluxEngine>('flux')
|
|
489
482
|
* await flux.execute(myWorkflow, input)
|
|
490
483
|
* ```
|
|
491
484
|
*/
|