@pogodisco/task-runner 0.2.2 → 0.2.4

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.
@@ -0,0 +1,10 @@
1
+ import { TasksFromFns } from "../index.js";
2
+ declare const taskOne: () => Promise<import("@pogodisco/response").TResponse<never>>;
3
+ export declare const schema: import("../index.js").TaskSchemaWithContracts<TasksFromFns<{
4
+ t1: typeof taskOne;
5
+ }>, {
6
+ foo: string;
7
+ }, {
8
+ data: string;
9
+ }>;
10
+ export {};
@@ -0,0 +1,34 @@
1
+ import { isFailure, withResponse } from "@pogodisco/response";
2
+ import { createGraph, createGraphRegistrar, defineSchema, runGraph, wrapSchema, } from "../index.js";
3
+ import { useLogger } from "./logger.js";
4
+ const taskOne = withResponse(async () => {
5
+ // throw
6
+ //
7
+ throw Error("Task one resulted in error");
8
+ });
9
+ export const schema = defineSchema({
10
+ t1: {
11
+ fn: taskOne,
12
+ argMap: (r) => ({}),
13
+ },
14
+ _output: (r) => ({ data: r._init.foo }),
15
+ });
16
+ const graph = createGraph()
17
+ .node("one", wrapSchema(schema, { log: useLogger() }))
18
+ .build();
19
+ const graphWithResponse = withResponse(async () => {
20
+ const r = await runGraph(graph, { foo: "FOO ONE" });
21
+ });
22
+ const wg = await graphWithResponse();
23
+ console.log("wrapped graph result", wg);
24
+ const g = await runGraph(graph, { foo: "FOO TWO" });
25
+ console.log("graph one", g);
26
+ const r = {
27
+ test: graph,
28
+ };
29
+ const fromGraph = createGraphRegistrar(r);
30
+ const resFromGraph = await fromGraph("test", { foo: "BAR" });
31
+ if (isFailure(resFromGraph)) {
32
+ console.log("tresponse error", resFromGraph.error);
33
+ }
34
+ console.log("res from graph reg", resFromGraph);
@@ -0,0 +1,2 @@
1
+ import { TaskLogger } from "../types/index.js";
2
+ export declare const useLogger: () => TaskLogger;
@@ -0,0 +1,118 @@
1
+ import chalk from "chalk";
2
+ import { format } from "pretty-format";
3
+ const startTimes = new Map();
4
+ const advancedLogger = (event, key, meta = {}) => {
5
+ const now = Date.now();
6
+ const prefix = `[${new Date().toISOString()}]`;
7
+ const label = event.toUpperCase().padEnd(9);
8
+ const colored = colorize(event, label);
9
+ if (event === "start") {
10
+ startTimes.set(key, now);
11
+ console.group(`${prefix} ${colored} ${key}`);
12
+ if (meta && Object.keys(meta).length > 0) {
13
+ console.log(chalk.gray("↪ Args:"), format(meta, { indent: 2, maxDepth: 3 }));
14
+ }
15
+ return;
16
+ }
17
+ if (event === "success" || event === "fail") {
18
+ const start = startTimes.get(key) ?? now;
19
+ const duration = now - start;
20
+ console.log(`${prefix} ${colored} ${key} (${formatDuration(duration)})`);
21
+ if (meta !== undefined) {
22
+ logResult(meta);
23
+ }
24
+ console.groupEnd();
25
+ startTimes.delete(key);
26
+ return;
27
+ }
28
+ if (event === "skipped") {
29
+ console.log(`${prefix} ${colored} ${key} (skipped)`, meta);
30
+ return;
31
+ }
32
+ if (event === "finish") {
33
+ const prefix = `[${new Date().toISOString()}]`;
34
+ const colored = chalk.bgMagenta.white.bold(" FINISH ");
35
+ console.group(`${prefix} ${colored} ${key}`);
36
+ if (meta?.status) {
37
+ console.log(chalk.bold("Statuses:"));
38
+ for (const [task, st] of Object.entries(meta.status)) {
39
+ const stColored = st === "success"
40
+ ? chalk.green(st)
41
+ : st === "failed"
42
+ ? chalk.red(st)
43
+ : st === "skipped"
44
+ ? chalk.gray(st)
45
+ : chalk.yellow(st);
46
+ console.log(` ${task}: ${stColored}`);
47
+ }
48
+ }
49
+ if (meta?.results) {
50
+ console.log(chalk.bold("\nResults:"));
51
+ logResult(meta.results);
52
+ }
53
+ if (meta?.output !== undefined) {
54
+ console.log(chalk.bold("\nOutput:"));
55
+ logResult(meta.output);
56
+ }
57
+ console.groupEnd();
58
+ return;
59
+ }
60
+ if (event === "data" ||
61
+ event === "background" ||
62
+ event === "parallel" ||
63
+ event === "deferred") {
64
+ console.log(`${prefix} ${colored} ${key}`, meta);
65
+ }
66
+ };
67
+ // Color mapping utility
68
+ function colorize(event, label) {
69
+ switch (event) {
70
+ case "start":
71
+ return chalk.cyan(label);
72
+ case "finish":
73
+ return chalk.magentaBright(label);
74
+ case "success":
75
+ return chalk.green(label);
76
+ case "fail":
77
+ return chalk.red(label);
78
+ case "skipped":
79
+ return chalk.gray(label);
80
+ case "data":
81
+ return chalk.magenta(label);
82
+ case "background":
83
+ return chalk.blue(label);
84
+ case "parallel":
85
+ return chalk.yellow(label);
86
+ case "deferred":
87
+ return chalk.dim(label);
88
+ default:
89
+ return label;
90
+ }
91
+ }
92
+ // Fancy duration formatter
93
+ function formatDuration(ms) {
94
+ if (ms < 1000)
95
+ return `${ms}ms`;
96
+ const sec = (ms / 1000).toFixed(2);
97
+ return `${sec}s`;
98
+ }
99
+ // Clean, safe result logging
100
+ function logResult(result) {
101
+ try {
102
+ const output = format(result, {
103
+ indent: 2,
104
+ min: false,
105
+ maxDepth: 6,
106
+ callToJSON: false,
107
+ printFunctionName: false,
108
+ });
109
+ console.log(chalk.gray("↪ Result:"), output);
110
+ }
111
+ catch (err) {
112
+ console.warn(chalk.red("! Failed to format result:"), err);
113
+ console.dir(result); // fallback
114
+ }
115
+ }
116
+ export const useLogger = () => {
117
+ return advancedLogger;
118
+ };
@@ -1,3 +1,4 @@
1
- import { GraphBuilder, GraphNode, RuntimeCtx, SchemaGraph } from "./types/index.js";
1
+ import { GraphBuilder, GraphEdge, GraphNode, RuntimeCtx, SchemaGraph } from "./types/index.js";
2
+ export declare function edge<K extends keyof any>(from: K, to: K, when?: (ctx: any) => boolean): GraphEdge<K>;
2
3
  export declare function createGraph<Init = {}>(): GraphBuilder<{}, Init>;
3
- export declare function runGraph<Nodes extends Record<string, GraphNode<any>>, Init>(graph: SchemaGraph<Nodes, Init>, initArgs: Init): Promise<RuntimeCtx<Nodes, Init>>;
4
+ export declare const runGraph: <Nodes extends Record<string, GraphNode<any>>, Init>(graph: SchemaGraph<Nodes, Init>, initArgs: Init) => Promise<import("@pogodisco/response").TResponse<RuntimeCtx<Nodes, Init>>>;
@@ -1,10 +1,7 @@
1
- // function edge<K extends keyof any>(
2
- // from: K,
3
- // to: K,
4
- // when?: (ctx: any) => boolean,
5
- // ): GraphEdge<K> {
6
- // return { from, to, when };
7
- // }
1
+ import { withResponse } from "@pogodisco/response";
2
+ export function edge(from, to, when) {
3
+ return { from, to, when };
4
+ }
8
5
  export function createGraph() {
9
6
  const nodes = {};
10
7
  // const edges: GraphEdge<string>[] = [];
@@ -18,6 +15,10 @@ export function createGraph() {
18
15
  return builder;
19
16
  },
20
17
  edge(from, to, when) {
18
+ // if (!(from in nodes))
19
+ // throw new Error(`Edge 'from' node "${from}" does not exist`);
20
+ // if (!(to in nodes))
21
+ // throw new Error(`Edge 'to' node "${to}" does not exist`);
21
22
  edges.push({ from, to, when });
22
23
  return builder;
23
24
  },
@@ -33,7 +34,43 @@ export function createGraph() {
33
34
  };
34
35
  return builder;
35
36
  }
36
- export async function runGraph(graph, initArgs) {
37
+ // export async function runGraph<
38
+ // Nodes extends Record<string, GraphNode<any>>,
39
+ // Init,
40
+ // >(
41
+ // graph: SchemaGraph<Nodes, Init>,
42
+ // initArgs: Init,
43
+ // ): Promise<RuntimeCtx<Nodes, Init>> {
44
+ // const ctx: RuntimeCtx<Nodes, Init> = {
45
+ // _init: initArgs,
46
+ // results: {} as any,
47
+ // };
48
+ //
49
+ // const queue: (keyof Nodes)[] = [graph.entry];
50
+ // const visited = new Set<keyof Nodes>();
51
+ //
52
+ // while (queue.length) {
53
+ // const nodeName = queue.shift()!;
54
+ // if (visited.has(nodeName)) continue;
55
+ //
56
+ // const node = graph.nodes[nodeName];
57
+ // const input = node.mapInput ? node.mapInput(ctx) : ctx._init;
58
+ // const res = await node.schema(input);
59
+ // if (!res.ok) throw res;
60
+ //
61
+ // ctx.results[nodeName] = res.data;
62
+ // visited.add(nodeName);
63
+ //
64
+ // const nextEdges = graph.edges.filter(
65
+ // (e) => e.from === nodeName && (!e.when || e.when(ctx)),
66
+ // );
67
+ //
68
+ // for (const e of nextEdges) queue.push(e.to);
69
+ // }
70
+ //
71
+ // return ctx;
72
+ // }
73
+ export const runGraph = withResponse(async (graph, initArgs) => {
37
74
  const ctx = {
38
75
  _init: initArgs,
39
76
  results: {},
@@ -56,4 +93,4 @@ export async function runGraph(graph, initArgs) {
56
93
  queue.push(e.to);
57
94
  }
58
95
  return ctx;
59
- }
96
+ });
@@ -1,5 +1,6 @@
1
+ import { TResponse } from "@pogodisco/response";
1
2
  import { RuntimeCtx, SchemaGraph } from "./types/index.js";
2
3
  export type GraphInputFor<R extends Record<string, SchemaGraph<any, any>>, K extends keyof R> = R[K] extends SchemaGraph<any, infer I> ? I : never;
3
4
  export type GraphOutputFor<R extends Record<string, SchemaGraph<any, any>>, K extends keyof R> = R[K] extends SchemaGraph<infer N, infer I> ? RuntimeCtx<N, I> : never;
4
- export type GraphRegistrar<R extends Record<string, SchemaGraph<any, any>>> = <K extends keyof R & string>(name: K, params: GraphInputFor<R, K>) => Promise<GraphOutputFor<R, K>>;
5
+ export type GraphRegistrar<R extends Record<string, SchemaGraph<any, any>>> = <K extends keyof R & string>(name: K, params: GraphInputFor<R, K>) => Promise<TResponse<GraphOutputFor<R, K>>>;
5
6
  export declare function createGraphRegistrar<R extends Record<string, SchemaGraph<any, any>>>(registry: R): GraphRegistrar<R>;
@@ -2,6 +2,14 @@ import { runGraph } from "./main.js";
2
2
  // -----------------------------
3
3
  // Factory
4
4
  // -----------------------------
5
+ // export function createGraphRegistrar<
6
+ // R extends Record<string, SchemaGraph<any, any>>,
7
+ // >(registry: R): GraphRegistrar<R> {
8
+ // return async (name, params) => {
9
+ // const graph = registry[name];
10
+ // return runGraph(graph, params) as any;
11
+ // };
12
+ // }
5
13
  export function createGraphRegistrar(registry) {
6
14
  return async (name, params) => {
7
15
  const graph = registry[name];
@@ -12,20 +12,20 @@ export type RuntimeCtx<Nodes extends Record<string, GraphNode<any>>, Init> = {
12
12
  [K in keyof Nodes]: ExtractOutput<Nodes[K]["schema"]>;
13
13
  };
14
14
  };
15
- export type GraphEdge<Nodes extends Record<string, GraphNode<any>>, Init> = {
16
- from: keyof Nodes;
17
- to: keyof Nodes;
18
- when?: (ctx: RuntimeCtx<Nodes, Init>) => boolean;
15
+ export type GraphEdge<NodeKeys extends keyof any> = {
16
+ from: NodeKeys;
17
+ to: NodeKeys;
18
+ when?: (ctx: any) => boolean;
19
19
  };
20
20
  export type BuiltNode<FN extends WrappedSchema<any, any>, Nodes extends Record<string, GraphNode<any>>> = GraphNode<FN>;
21
21
  export type SchemaGraph<Nodes extends Record<string, GraphNode<any>>, Init> = {
22
22
  entry: keyof Nodes;
23
23
  nodes: Nodes;
24
- edges: GraphEdge<Nodes, Init>[];
24
+ edges: GraphEdge<keyof Nodes>[];
25
25
  };
26
26
  export type GraphBuilder<Nodes extends Record<string, GraphNode<any>> = {}, Init = {}> = {
27
27
  node<K extends string, FN extends WrappedSchema<any, any>>(key: K, schema: FN, mapInput?: (ctx: RuntimeCtx<Nodes & Record<K, GraphNode<FN>>, Init>) => ExtractInput<FN>): GraphBuilder<Nodes & Record<K, GraphNode<FN>>, Init>;
28
- edge<From extends keyof Nodes, To extends keyof Nodes>(from: From, to: To, when?: (ctx: RuntimeCtx<Nodes, Init>) => boolean): GraphBuilder<Nodes, Init>;
28
+ edge<From extends keyof Nodes, To extends keyof Nodes>(from: From, to: To, when?: (ctx: any) => boolean): GraphBuilder<Nodes, Init>;
29
29
  build(): SchemaGraph<Nodes, Init>;
30
30
  };
31
31
  export type GraphEntryInput<G extends SchemaGraph<any, any>> = G extends SchemaGraph<infer Nodes, any> ? RuntimeCtx<Nodes, any>["_init"] : never;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pogodisco/task-runner",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -28,7 +28,11 @@
28
28
  "scripts": {
29
29
  "prepublishOnly": "npm run build",
30
30
  "build": "tsc -p tsconfig.build.json",
31
- "dev": "tsc -w -p tsconfig.json"
31
+ "dev": "tsc -w -p tsconfig.json",
32
+ "test:types": "tsd"
33
+ },
34
+ "tsd": {
35
+ "directory": "test-dts"
32
36
  },
33
37
  "peerDependencies": {
34
38
  "@pogodisco/response": "~0.0.1",
@@ -37,6 +41,7 @@
37
41
  "devDependencies": {
38
42
  "@pogodisco/response": "~0.0.1",
39
43
  "chalk": "^5.6.2",
40
- "pretty-format": "^30.2.0"
44
+ "pretty-format": "^30.2.0",
45
+ "tsd": "^0.33.0"
41
46
  }
42
47
  }