@gravito/flux 1.0.0-alpha.5 → 1.0.0-beta.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.
Files changed (2) hide show
  1. package/package.json +4 -3
  2. package/dist/node/index.cjs +0 -651
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gravito/flux",
3
- "version": "1.0.0-alpha.5",
3
+ "version": "1.0.0-beta.1",
4
4
  "description": "Platform-agnostic workflow engine for Gravito",
5
5
  "type": "module",
6
6
  "main": "./dist/node/index.cjs",
@@ -38,7 +38,7 @@
38
38
  "test": "bun test"
39
39
  },
40
40
  "peerDependencies": {
41
- "gravito-core": "1.0.0-beta.4"
41
+ "gravito-core": "1.0.0-beta.6"
42
42
  },
43
43
  "peerDependenciesMeta": {
44
44
  "gravito-core": {
@@ -47,7 +47,8 @@
47
47
  },
48
48
  "devDependencies": {
49
49
  "bun-types": "latest",
50
- "gravito-core": "1.0.0-beta.4",
50
+ "gravito-core": "1.0.0-beta.6",
51
+ "tsup": "^8.5.1",
51
52
  "typescript": "^5.0.0"
52
53
  },
53
54
  "keywords": [
@@ -1,651 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropNames = Object.getOwnPropertyNames;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __moduleCache = /* @__PURE__ */ new WeakMap;
6
- var __toCommonJS = (from) => {
7
- var entry = __moduleCache.get(from), desc;
8
- if (entry)
9
- return entry;
10
- entry = __defProp({}, "__esModule", { value: true });
11
- if (from && typeof from === "object" || typeof from === "function")
12
- __getOwnPropNames(from).map((key) => !__hasOwnProp.call(entry, key) && __defProp(entry, key, {
13
- get: () => from[key],
14
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
- }));
16
- __moduleCache.set(from, entry);
17
- return entry;
18
- };
19
- var __export = (target, all) => {
20
- for (var name in all)
21
- __defProp(target, name, {
22
- get: all[name],
23
- enumerable: true,
24
- configurable: true,
25
- set: (newValue) => all[name] = () => newValue
26
- });
27
- };
28
-
29
- // src/index.node.ts
30
- var exports_index_node = {};
31
- __export(exports_index_node, {
32
- createWorkflow: () => createWorkflow,
33
- WorkflowBuilder: () => WorkflowBuilder,
34
- StepExecutor: () => StepExecutor,
35
- StateMachine: () => StateMachine,
36
- OrbitFlux: () => OrbitFlux,
37
- MemoryStorage: () => MemoryStorage,
38
- FluxSilentLogger: () => FluxSilentLogger,
39
- FluxEngine: () => FluxEngine,
40
- FluxConsoleLogger: () => FluxConsoleLogger,
41
- ContextManager: () => ContextManager
42
- });
43
- module.exports = __toCommonJS(exports_index_node);
44
-
45
- // src/builder/WorkflowBuilder.ts
46
- class WorkflowBuilder {
47
- _name;
48
- _steps = [];
49
- _validateInput;
50
- constructor(name) {
51
- this._name = name;
52
- }
53
- input() {
54
- return this;
55
- }
56
- validate(validator) {
57
- this._validateInput = validator;
58
- return this;
59
- }
60
- step(name, handler, options) {
61
- this._steps.push({
62
- name,
63
- handler,
64
- retries: options?.retries,
65
- timeout: options?.timeout,
66
- when: options?.when,
67
- commit: false
68
- });
69
- return this;
70
- }
71
- commit(name, handler, options) {
72
- this._steps.push({
73
- name,
74
- handler,
75
- retries: options?.retries,
76
- timeout: options?.timeout,
77
- when: options?.when,
78
- commit: true
79
- });
80
- return this;
81
- }
82
- build() {
83
- if (this._steps.length === 0) {
84
- throw new Error(`Workflow "${this._name}" has no steps`);
85
- }
86
- return {
87
- name: this._name,
88
- steps: [...this._steps],
89
- validateInput: this._validateInput
90
- };
91
- }
92
- get name() {
93
- return this._name;
94
- }
95
- get stepCount() {
96
- return this._steps.length;
97
- }
98
- }
99
- function createWorkflow(name) {
100
- return new WorkflowBuilder(name);
101
- }
102
- // src/core/ContextManager.ts
103
- function generateId() {
104
- return crypto.randomUUID();
105
- }
106
-
107
- class ContextManager {
108
- create(name, input, stepCount) {
109
- const history = Array.from({ length: stepCount }, (_, _i) => ({
110
- name: "",
111
- status: "pending",
112
- retries: 0
113
- }));
114
- return {
115
- id: generateId(),
116
- name,
117
- input,
118
- data: {},
119
- status: "pending",
120
- currentStep: 0,
121
- history
122
- };
123
- }
124
- restore(state) {
125
- return {
126
- id: state.id,
127
- name: state.name,
128
- input: state.input,
129
- data: { ...state.data },
130
- status: state.status,
131
- currentStep: state.currentStep,
132
- history: state.history.map((h) => ({ ...h }))
133
- };
134
- }
135
- toState(ctx) {
136
- return {
137
- id: ctx.id,
138
- name: ctx.name,
139
- status: ctx.status,
140
- input: ctx.input,
141
- data: { ...ctx.data },
142
- currentStep: ctx.currentStep,
143
- history: ctx.history.map((h) => ({ ...h })),
144
- createdAt: new Date,
145
- updatedAt: new Date
146
- };
147
- }
148
- updateStatus(ctx, status) {
149
- return {
150
- ...ctx,
151
- status
152
- };
153
- }
154
- advanceStep(ctx) {
155
- return {
156
- ...ctx,
157
- currentStep: ctx.currentStep + 1
158
- };
159
- }
160
- setStepName(ctx, index, name) {
161
- if (ctx.history[index]) {
162
- ctx.history[index].name = name;
163
- }
164
- }
165
- }
166
-
167
- // src/core/StateMachine.ts
168
- var TRANSITIONS = {
169
- pending: ["running", "failed"],
170
- running: ["paused", "completed", "failed"],
171
- paused: ["running", "failed"],
172
- completed: [],
173
- failed: ["pending"]
174
- };
175
-
176
- class StateMachine extends EventTarget {
177
- _status = "pending";
178
- get status() {
179
- return this._status;
180
- }
181
- canTransition(to) {
182
- return TRANSITIONS[this._status].includes(to);
183
- }
184
- transition(to) {
185
- if (!this.canTransition(to)) {
186
- throw new Error(`Invalid state transition: ${this._status} → ${to}`);
187
- }
188
- const from = this._status;
189
- this._status = to;
190
- this.dispatchEvent(new CustomEvent("transition", {
191
- detail: { from, to }
192
- }));
193
- }
194
- forceStatus(status) {
195
- this._status = status;
196
- }
197
- isTerminal() {
198
- return this._status === "completed" || this._status === "failed";
199
- }
200
- canExecute() {
201
- return this._status === "pending" || this._status === "paused";
202
- }
203
- }
204
-
205
- // src/core/StepExecutor.ts
206
- class StepExecutor {
207
- defaultRetries;
208
- defaultTimeout;
209
- constructor(options = {}) {
210
- this.defaultRetries = options.defaultRetries ?? 3;
211
- this.defaultTimeout = options.defaultTimeout ?? 30000;
212
- }
213
- async execute(step, ctx, execution) {
214
- const maxRetries = step.retries ?? this.defaultRetries;
215
- const timeout = step.timeout ?? this.defaultTimeout;
216
- const startTime = Date.now();
217
- if (step.when && !step.when(ctx)) {
218
- execution.status = "skipped";
219
- return {
220
- success: true,
221
- duration: 0
222
- };
223
- }
224
- execution.status = "running";
225
- execution.startedAt = new Date;
226
- let lastError;
227
- for (let attempt = 0;attempt <= maxRetries; attempt++) {
228
- execution.retries = attempt;
229
- try {
230
- await this.executeWithTimeout(step.handler, ctx, timeout);
231
- execution.status = "completed";
232
- execution.completedAt = new Date;
233
- execution.duration = Date.now() - startTime;
234
- return {
235
- success: true,
236
- duration: execution.duration
237
- };
238
- } catch (error) {
239
- lastError = error instanceof Error ? error : new Error(String(error));
240
- if (attempt < maxRetries) {
241
- await this.sleep(Math.min(1000 * 2 ** attempt, 1e4));
242
- }
243
- }
244
- }
245
- execution.status = "failed";
246
- execution.completedAt = new Date;
247
- execution.duration = Date.now() - startTime;
248
- execution.error = lastError?.message;
249
- return {
250
- success: false,
251
- error: lastError,
252
- duration: execution.duration
253
- };
254
- }
255
- async executeWithTimeout(handler, ctx, timeout) {
256
- const timeoutPromise = new Promise((_, reject) => {
257
- setTimeout(() => reject(new Error("Step timeout")), timeout);
258
- });
259
- await Promise.race([Promise.resolve(handler(ctx)), timeoutPromise]);
260
- }
261
- sleep(ms) {
262
- return new Promise((resolve) => setTimeout(resolve, ms));
263
- }
264
- }
265
-
266
- // src/storage/MemoryStorage.ts
267
- class MemoryStorage {
268
- store = new Map;
269
- async save(state) {
270
- this.store.set(state.id, {
271
- ...state,
272
- updatedAt: new Date
273
- });
274
- }
275
- async load(id) {
276
- return this.store.get(id) ?? null;
277
- }
278
- async list(filter) {
279
- let results = Array.from(this.store.values());
280
- if (filter?.name) {
281
- results = results.filter((s) => s.name === filter.name);
282
- }
283
- if (filter?.status) {
284
- const statuses = Array.isArray(filter.status) ? filter.status : [filter.status];
285
- results = results.filter((s) => statuses.includes(s.status));
286
- }
287
- results.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
288
- if (filter?.offset) {
289
- results = results.slice(filter.offset);
290
- }
291
- if (filter?.limit) {
292
- results = results.slice(0, filter.limit);
293
- }
294
- return results;
295
- }
296
- async delete(id) {
297
- this.store.delete(id);
298
- }
299
- async init() {}
300
- async close() {
301
- this.store.clear();
302
- }
303
- size() {
304
- return this.store.size;
305
- }
306
- }
307
-
308
- // src/engine/FluxEngine.ts
309
- class FluxEngine {
310
- storage;
311
- executor;
312
- contextManager;
313
- config;
314
- constructor(config = {}) {
315
- this.config = config;
316
- this.storage = config.storage ?? new MemoryStorage;
317
- this.executor = new StepExecutor({
318
- defaultRetries: config.defaultRetries,
319
- defaultTimeout: config.defaultTimeout
320
- });
321
- this.contextManager = new ContextManager;
322
- }
323
- async execute(workflow, input) {
324
- const startTime = Date.now();
325
- const definition = workflow instanceof WorkflowBuilder ? workflow.build() : workflow;
326
- if (definition.validateInput && !definition.validateInput(input)) {
327
- throw new Error(`Invalid input for workflow "${definition.name}"`);
328
- }
329
- const ctx = this.contextManager.create(definition.name, input, definition.steps.length);
330
- const stateMachine = new StateMachine;
331
- await this.storage.save(this.contextManager.toState(ctx));
332
- try {
333
- stateMachine.transition("running");
334
- Object.assign(ctx, { status: "running" });
335
- for (let i = 0;i < definition.steps.length; i++) {
336
- const step = definition.steps[i];
337
- const execution = ctx.history[i];
338
- this.contextManager.setStepName(ctx, i, step.name);
339
- Object.assign(ctx, { currentStep: i });
340
- this.config.on?.stepStart?.(step.name, ctx);
341
- const result = await this.executor.execute(step, ctx, execution);
342
- if (result.success) {
343
- this.config.on?.stepComplete?.(step.name, ctx, result);
344
- } else {
345
- this.config.on?.stepError?.(step.name, ctx, result.error);
346
- stateMachine.transition("failed");
347
- Object.assign(ctx, { status: "failed" });
348
- await this.storage.save({
349
- ...this.contextManager.toState(ctx),
350
- error: result.error?.message
351
- });
352
- return {
353
- id: ctx.id,
354
- status: "failed",
355
- data: ctx.data,
356
- history: ctx.history,
357
- duration: Date.now() - startTime,
358
- error: result.error
359
- };
360
- }
361
- await this.storage.save(this.contextManager.toState(ctx));
362
- }
363
- stateMachine.transition("completed");
364
- Object.assign(ctx, { status: "completed" });
365
- await this.storage.save({
366
- ...this.contextManager.toState(ctx),
367
- completedAt: new Date
368
- });
369
- this.config.on?.workflowComplete?.(ctx);
370
- return {
371
- id: ctx.id,
372
- status: "completed",
373
- data: ctx.data,
374
- history: ctx.history,
375
- duration: Date.now() - startTime
376
- };
377
- } catch (error) {
378
- const err = error instanceof Error ? error : new Error(String(error));
379
- this.config.on?.workflowError?.(ctx, err);
380
- stateMachine.forceStatus("failed");
381
- Object.assign(ctx, { status: "failed" });
382
- await this.storage.save({
383
- ...this.contextManager.toState(ctx),
384
- error: err.message
385
- });
386
- return {
387
- id: ctx.id,
388
- status: "failed",
389
- data: ctx.data,
390
- history: ctx.history,
391
- duration: Date.now() - startTime,
392
- error: err
393
- };
394
- }
395
- }
396
- async resume(workflowId) {
397
- const state = await this.storage.load(workflowId);
398
- if (!state) {
399
- return null;
400
- }
401
- throw new Error("Resume not yet implemented");
402
- }
403
- async get(workflowId) {
404
- return this.storage.load(workflowId);
405
- }
406
- async list(filter) {
407
- return this.storage.list(filter);
408
- }
409
- async init() {
410
- await this.storage.init?.();
411
- }
412
- async close() {
413
- await this.storage.close?.();
414
- }
415
- }
416
- // src/logger/FluxLogger.ts
417
- class FluxConsoleLogger {
418
- prefix;
419
- constructor(prefix = "[Flux]") {
420
- this.prefix = prefix;
421
- }
422
- debug(message, ...args) {
423
- console.debug(`${this.prefix} ${message}`, ...args);
424
- }
425
- info(message, ...args) {
426
- console.info(`${this.prefix} ${message}`, ...args);
427
- }
428
- warn(message, ...args) {
429
- console.warn(`${this.prefix} ${message}`, ...args);
430
- }
431
- error(message, ...args) {
432
- console.error(`${this.prefix} ${message}`, ...args);
433
- }
434
- }
435
-
436
- class FluxSilentLogger {
437
- debug() {}
438
- info() {}
439
- warn() {}
440
- error() {}
441
- }
442
- // src/storage/BunSQLiteStorage.ts
443
- var import_bun_sqlite = require("bun:sqlite");
444
-
445
- class BunSQLiteStorage {
446
- db;
447
- tableName;
448
- initialized = false;
449
- constructor(options = {}) {
450
- this.db = new import_bun_sqlite.Database(options.path ?? ":memory:");
451
- this.tableName = options.tableName ?? "flux_workflows";
452
- }
453
- async init() {
454
- if (this.initialized) {
455
- return;
456
- }
457
- this.db.run(`
458
- CREATE TABLE IF NOT EXISTS ${this.tableName} (
459
- id TEXT PRIMARY KEY,
460
- name TEXT NOT NULL,
461
- status TEXT NOT NULL,
462
- input TEXT NOT NULL,
463
- data TEXT NOT NULL,
464
- current_step INTEGER NOT NULL,
465
- history TEXT NOT NULL,
466
- error TEXT,
467
- created_at TEXT NOT NULL,
468
- updated_at TEXT NOT NULL,
469
- completed_at TEXT
470
- )
471
- `);
472
- this.db.run(`
473
- CREATE INDEX IF NOT EXISTS idx_${this.tableName}_name
474
- ON ${this.tableName}(name)
475
- `);
476
- this.db.run(`
477
- CREATE INDEX IF NOT EXISTS idx_${this.tableName}_status
478
- ON ${this.tableName}(status)
479
- `);
480
- this.db.run(`
481
- CREATE INDEX IF NOT EXISTS idx_${this.tableName}_created
482
- ON ${this.tableName}(created_at DESC)
483
- `);
484
- this.initialized = true;
485
- }
486
- async save(state) {
487
- await this.init();
488
- const stmt = this.db.prepare(`
489
- INSERT OR REPLACE INTO ${this.tableName}
490
- (id, name, status, input, data, current_step, history, error, created_at, updated_at, completed_at)
491
- VALUES ($id, $name, $status, $input, $data, $currentStep, $history, $error, $createdAt, $updatedAt, $completedAt)
492
- `);
493
- stmt.run({
494
- $id: state.id,
495
- $name: state.name,
496
- $status: state.status,
497
- $input: JSON.stringify(state.input),
498
- $data: JSON.stringify(state.data),
499
- $currentStep: state.currentStep,
500
- $history: JSON.stringify(state.history),
501
- $error: state.error ?? null,
502
- $createdAt: state.createdAt.toISOString(),
503
- $updatedAt: state.updatedAt.toISOString(),
504
- $completedAt: state.completedAt?.toISOString() ?? null
505
- });
506
- }
507
- async load(id) {
508
- await this.init();
509
- const stmt = this.db.prepare(`
510
- SELECT * FROM ${this.tableName} WHERE id = $id
511
- `);
512
- const row = stmt.get({ $id: id });
513
- if (!row) {
514
- return null;
515
- }
516
- return this.rowToState(row);
517
- }
518
- async list(filter) {
519
- await this.init();
520
- let query = `SELECT * FROM ${this.tableName} WHERE 1=1`;
521
- const params = {};
522
- if (filter?.name) {
523
- query += " AND name = $name";
524
- params.$name = filter.name;
525
- }
526
- if (filter?.status) {
527
- if (Array.isArray(filter.status)) {
528
- const placeholders = filter.status.map((_, i) => `$status${i}`).join(", ");
529
- query += ` AND status IN (${placeholders})`;
530
- filter.status.forEach((s, i) => {
531
- params[`$status${i}`] = s;
532
- });
533
- } else {
534
- query += " AND status = $status";
535
- params.$status = filter.status;
536
- }
537
- }
538
- query += " ORDER BY created_at DESC";
539
- if (filter?.limit) {
540
- query += " LIMIT $limit";
541
- params.$limit = filter.limit;
542
- }
543
- if (filter?.offset) {
544
- query += " OFFSET $offset";
545
- params.$offset = filter.offset;
546
- }
547
- const stmt = this.db.prepare(query);
548
- const rows = stmt.all(params);
549
- return rows.map((row) => this.rowToState(row));
550
- }
551
- async delete(id) {
552
- await this.init();
553
- const stmt = this.db.prepare(`
554
- DELETE FROM ${this.tableName} WHERE id = $id
555
- `);
556
- stmt.run({ $id: id });
557
- }
558
- async close() {
559
- this.db.close();
560
- this.initialized = false;
561
- }
562
- rowToState(row) {
563
- return {
564
- id: row.id,
565
- name: row.name,
566
- status: row.status,
567
- input: JSON.parse(row.input),
568
- data: JSON.parse(row.data),
569
- currentStep: row.current_step,
570
- history: JSON.parse(row.history),
571
- error: row.error ?? undefined,
572
- createdAt: new Date(row.created_at),
573
- updatedAt: new Date(row.updated_at),
574
- completedAt: row.completed_at ? new Date(row.completed_at) : undefined
575
- };
576
- }
577
- getDatabase() {
578
- return this.db;
579
- }
580
- vacuum() {
581
- this.db.run("VACUUM");
582
- }
583
- }
584
-
585
- // src/orbit/OrbitFlux.ts
586
- class OrbitFlux {
587
- options;
588
- engine;
589
- constructor(options = {}) {
590
- this.options = {
591
- storage: "memory",
592
- exposeAs: "flux",
593
- defaultRetries: 3,
594
- defaultTimeout: 30000,
595
- ...options
596
- };
597
- }
598
- static configure(options = {}) {
599
- return new OrbitFlux(options);
600
- }
601
- async install(core) {
602
- const { storage, dbPath, exposeAs, defaultRetries, defaultTimeout, logger } = this.options;
603
- let storageAdapter;
604
- if (typeof storage === "string") {
605
- switch (storage) {
606
- case "sqlite":
607
- storageAdapter = new BunSQLiteStorage({ path: dbPath });
608
- break;
609
- default:
610
- storageAdapter = new MemoryStorage;
611
- }
612
- } else {
613
- storageAdapter = storage;
614
- }
615
- await storageAdapter.init?.();
616
- const engineConfig = {
617
- storage: storageAdapter,
618
- defaultRetries,
619
- defaultTimeout,
620
- logger: logger ?? {
621
- debug: (msg) => core.logger.debug(`[Flux] ${msg}`),
622
- info: (msg) => core.logger.info(`[Flux] ${msg}`),
623
- warn: (msg) => core.logger.warn(`[Flux] ${msg}`),
624
- error: (msg) => core.logger.error(`[Flux] ${msg}`)
625
- },
626
- on: {
627
- stepStart: (step) => {
628
- core.hooks.doAction("flux:step:start", { step });
629
- },
630
- stepComplete: (step, ctx, result) => {
631
- core.hooks.doAction("flux:step:complete", { step, ctx, result });
632
- },
633
- stepError: (step, ctx, error) => {
634
- core.hooks.doAction("flux:step:error", { step, ctx, error });
635
- },
636
- workflowComplete: (ctx) => {
637
- core.hooks.doAction("flux:workflow:complete", { ctx });
638
- },
639
- workflowError: (ctx, error) => {
640
- core.hooks.doAction("flux:workflow:error", { ctx, error });
641
- }
642
- }
643
- };
644
- this.engine = new FluxEngine(engineConfig);
645
- core.services.set(exposeAs, this.engine);
646
- core.logger.info(`[OrbitFlux] Initialized (Storage: ${typeof storage === "string" ? storage : "custom"})`);
647
- }
648
- getEngine() {
649
- return this.engine;
650
- }
651
- }