pure-effect 0.2.0 → 0.3.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 CHANGED
@@ -58,7 +58,7 @@ async function registerUser() {
58
58
  const logic = registerUserFlow(input);
59
59
 
60
60
  // runEffect performs the actual async work
61
- const result = await runEffect(logic);
61
+ const result = await runEffect(logic, 'registerUser');
62
62
 
63
63
  if (result.type === 'Success') {
64
64
  console.log('User created:', result.value);
@@ -77,7 +77,7 @@ The biggest benefit of **Pure Effect** is testability. Because `registerUserFlow
77
77
  const badInput = { email: 'bad-email', password: '123' };
78
78
  const result = registerUserFlow(badInput);
79
79
 
80
- assert.deepEqual(result, Failure('Invalid email.'));
80
+ assert.deepEqual(result, Failure('Invalid email format.', badInput));
81
81
  // ✅ Logic tested instantly, no async needed.
82
82
 
83
83
  // 2. Test Flow Intent (Introspection)
@@ -103,7 +103,7 @@ Returns an object `{ type: 'Success', value }`. Represents a successful computat
103
103
 
104
104
  ### `Failure(error)`
105
105
 
106
- Returns an object `{ type: 'Failure', error }`. Represents a failed computation. Stops the pipeline immediately.
106
+ Returns an object `{ type: 'Failure', error, initialInput }`. Represents a failed computation. Stops the pipeline immediately.
107
107
 
108
108
  ### `Command(cmdFn, nextFn)`
109
109
 
@@ -116,6 +116,27 @@ Returns an object `{ type: 'Command', cmd, next }`.
116
116
 
117
117
  A combinator that runs functions in sequence. It automatically handles unpacking `Success` values and passing them to the next function. If a `Failure` occurs, the pipe stops.
118
118
 
119
- ### `runEffect(effect)`
119
+ ### `runEffect(effect, flowName = '')`
120
120
 
121
- The interpreter. It takes an `effect` object, executes any nested Commands recursively using `async/await`, and returns the final `Success` or `Failure`.
121
+ The interpreter. It takes an `effect` object, executes any nested Commands recursively using `async/await`, and returns the final `Success` or `Failure`. It also accepts an optional `flowName` that comes in handy for telemetry.
122
+
123
+ ---
124
+
125
+ ### `configureTelemetry(options)`
126
+
127
+ A configuration function that injects observability, tracing, or logging interceptors into the `runEffect` interpreter. By default, **Pure Effect** executes with zero overhead. By providing `onRun` and `onStep` callbacks, you can wrap pipeline executions and individual commands (e.g., inside OpenTelemetry spans).
128
+
129
+ Please see **opentelemetry-example.js** to see a quick example.
130
+
131
+ - `onRun (effect, pipeline, flowName)`
132
+ Fires once per `runEffect` call. It wraps the entire workflow execution.
133
+
134
+ - `effect`: The initial state of the effect tree (useful for extracting `initialInput`).
135
+ - `pipeline`: The actual interpreter. You must `await pipeline()` inside this callback to run the logic.
136
+ - `flowName`: The optional name of the workflow passed to runEffect.
137
+
138
+ - `onStep (name, type, op)`
139
+ Fires every time a `Command` is executed.
140
+ - `name`: The name of the command function (e.g., `cmdFindUser`).
141
+ - `type`: Effect type.
142
+ - `op`: The actual side-effect function. You must `await op()` inside this callback and return its result.
package/index.js CHANGED
@@ -1,12 +1,13 @@
1
1
  // @ts-check
2
2
 
3
- /** @typedef {{ type: 'Success', value: any }} SuccessState */
4
- /** @typedef {{ type: 'Failure', error: any }} FailureState */
3
+ /** @typedef {{ type: 'Success', value: any, initialInput?: any }} SuccessState */
4
+ /** @typedef {{ type: 'Failure', error: any, initialInput?: any }} FailureState */
5
5
  /**
6
6
  * @typedef {{
7
7
  * type: 'Command',
8
8
  * cmd: () => Promise<any>|any,
9
- * next: (result: any) => Effect
9
+ * next: (result: any) => Effect,
10
+ * initialInput?: any
10
11
  * }} CommandState
11
12
  */
12
13
 
@@ -25,9 +26,10 @@ const Success = (value) => ({ type: 'Success', value });
25
26
  /**
26
27
  * Represents a failed computation. Stops the pipeline execution
27
28
  * @param {any} error - The error reason (string, Error object, etc).
29
+ * @param {any} [initialInput] - initial input passed to the flow (optional)
28
30
  * @returns {FailureState}
29
31
  */
30
- const Failure = (error) => ({ type: 'Failure', error });
32
+ const Failure = (error, initialInput) => ({ type: 'Failure', error, initialInput });
31
33
 
32
34
  /**
33
35
  * Represents a side effect to be executed later
@@ -65,7 +67,31 @@ const chain = (effect, fn) => {
65
67
  * @returns {(start: any) => Effect} A function that accepts an initial input and returns the final Effect tree.
66
68
  */
67
69
  const effectPipe = (...fns) => {
68
- return (start) => fns.reduce(chain, Success(start));
70
+ return (start) => {
71
+ const effect = fns.reduce(chain, Success(start));
72
+ effect.initialInput = start;
73
+ return effect;
74
+ };
75
+ };
76
+
77
+ /** @type {(name: string, type: string, op: function) => Promise<any>} */
78
+ const defaultStepRunner = async (name, type, op) => await op();
79
+
80
+ /** @type {(effect: Effect, op: function, flowName?: string) => Promise<any>} */
81
+ const defaultRunWrapper = async (effect, op, flowName) => await op();
82
+
83
+ let stepRunner = defaultStepRunner;
84
+ let runWrapper = defaultRunWrapper;
85
+
86
+ /**
87
+ * Enables OpenTelemetry support if it receives an OpenTelemetry onStep option.
88
+ * Otherwise OpenTelemetry support is disabled.
89
+ *
90
+ * @param {any} options
91
+ */
92
+ const configureTelemetry = (/** @type any **/ options) => {
93
+ stepRunner = options.onStep ? options.onStep : defaultStepRunner;
94
+ runWrapper = options.onRun ? options.onRun : defaultRunWrapper;
69
95
  };
70
96
 
71
97
  /**
@@ -73,17 +99,29 @@ const effectPipe = (...fns) => {
73
99
  * Iterates through the Effect tree, executing Commands and handling async flow.
74
100
  *
75
101
  * @param {Effect} effect - The Effect tree returned by a pipeline
102
+ * @param {string} flowName - Name of the workflow
76
103
  * @returns {Promise<SuccessState | FailureState>}
77
104
  */
78
- async function runEffect(effect) {
79
- while (effect.type === 'Command') {
80
- try {
81
- effect = effect.next(await effect.cmd());
82
- } catch (e) {
83
- return Failure(e);
84
- }
85
- }
86
- return effect;
105
+ async function runEffect(effect, flowName = '') {
106
+ return runWrapper(
107
+ effect,
108
+ async () => {
109
+ while (effect.type === 'Command') {
110
+ const currentCmd = effect.cmd;
111
+ const cmdName = currentCmd.name || 'anonymous';
112
+
113
+ try {
114
+ const result = await stepRunner(cmdName, 'Command', currentCmd);
115
+ effect = effect.next(result);
116
+ } catch (e) {
117
+ return Failure(e, effect.initialInput);
118
+ }
119
+ }
120
+
121
+ return effect;
122
+ },
123
+ flowName || ''
124
+ );
87
125
  }
88
126
 
89
- export { Success, Failure, Command, effectPipe, runEffect };
127
+ export { Success, Failure, Command, effectPipe, runEffect, configureTelemetry };
@@ -0,0 +1,88 @@
1
+ // @ts-check
2
+
3
+ import { NodeSDK } from '@opentelemetry/sdk-node';
4
+ import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';
5
+ import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
6
+ import { trace, SpanStatusCode } from '@opentelemetry/api';
7
+ import { configureTelemetry } from './index.js';
8
+
9
+ const traceExporter = new OTLPTraceExporter({
10
+ url: 'http://localhost:4318/v1/traces',
11
+ });
12
+
13
+ const sdk = new NodeSDK({
14
+ serviceName: 'pure-effect-test',
15
+ traceExporter,
16
+ spanProcessor: new SimpleSpanProcessor(traceExporter),
17
+ instrumentations: [],
18
+ });
19
+
20
+ sdk.start();
21
+
22
+ process.on('SIGTERM', () => {
23
+ sdk.shutdown()
24
+ .then(() => console.log('Tracing terminated'))
25
+ .catch((error) => console.log('Error terminating tracing', error))
26
+ .finally(() => process.exit(0));
27
+ });
28
+
29
+ export function enableTelemetry() {
30
+ const tracer = trace.getTracer('pure-effect-test');
31
+ configureTelemetry({
32
+ onRun: (/** @type any */ effect, /** @type any */ pipeline, /** @type string */ flowName) => {
33
+ return tracer.startActiveSpan('Effect Pipeline', async (rootSpan) => {
34
+ try {
35
+ rootSpan.setAttribute('effect.initialInput', JSON.stringify(effect.initialInput));
36
+ rootSpan.setAttribute('effect.flow', flowName);
37
+
38
+ const result = await pipeline();
39
+
40
+ if (result.type === 'Failure') {
41
+ rootSpan.setStatus({
42
+ code: SpanStatusCode.ERROR,
43
+ message: String(result.error),
44
+ });
45
+ } else {
46
+ rootSpan.setStatus({ code: SpanStatusCode.OK });
47
+ }
48
+
49
+ return result;
50
+ } catch (/** @type any */ err) {
51
+ rootSpan.recordException(err);
52
+ rootSpan.setStatus({ code: SpanStatusCode.ERROR, message: err.message });
53
+ throw err;
54
+ } finally {
55
+ rootSpan.end();
56
+ }
57
+ });
58
+ },
59
+
60
+ onStep: (/** @type string */ name, /** @type string */ type, /** @type function */ op) => {
61
+ return tracer.startActiveSpan(name, async (span) => {
62
+ span.setAttribute('effect.type', type);
63
+ try {
64
+ const result = await op();
65
+ try {
66
+ if (result !== undefined) {
67
+ const outputString = typeof result === 'object' ? JSON.stringify(result) : String(result);
68
+ span.setAttribute('effect.output', outputString);
69
+ }
70
+ } catch (serializationError) {
71
+ span.setAttribute('effect.output', '[Circular or Non-Serializable Data]');
72
+ }
73
+ span.setStatus({ code: SpanStatusCode.OK });
74
+ return result;
75
+ } catch (/** @type any */ err) {
76
+ span.recordException(err);
77
+ span.setStatus({
78
+ code: SpanStatusCode.ERROR,
79
+ message: err.message,
80
+ });
81
+ throw err;
82
+ } finally {
83
+ span.end();
84
+ }
85
+ });
86
+ },
87
+ });
88
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pure-effect",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "A tiny, zero-dependency effect system for writing pure, testable JavaScript without mocks.",
5
5
  "type": "module",
6
6
  "exports": "./index.js",
@@ -11,6 +11,7 @@
11
11
  "homepage": "https://github.com/aycangulez/pure-effect",
12
12
  "license": "MIT",
13
13
  "devDependencies": {
14
+ "@opentelemetry/sdk-node": "^0.211.0",
14
15
  "@types/mocha": "^10.0.10",
15
16
  "@types/node": "^24.10.1",
16
17
  "mocha": "^11.7.5"
package/test/all.js CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  import { strict as assert } from 'assert';
4
4
  import { Success, Failure, Command, effectPipe, runEffect } from '../index.js';
5
+ import { enableTelemetry } from '../opentelemetry-example.js';
5
6
 
6
7
  /** @typedef {{id?: number, email: string, password: string}} User */
7
8
 
@@ -56,14 +57,14 @@ const registerUserFlow = (/** @type {User} */ input) =>
56
57
  )(input);
57
58
 
58
59
  async function registerUser(/** @type {User} */ input) {
59
- return await runEffect(registerUserFlow(input));
60
+ return await runEffect(registerUserFlow(input), 'registerUser');
60
61
  }
61
62
 
62
63
  describe('Pure Effect', function () {
63
64
  it('should return Failure when e-mail is invalid', async function () {
64
- const input = { email: 'bad-email', password: '123' };
65
- const effect = await registerUser(input);
66
- assert.deepEqual(effect, Failure('Invalid email format.'));
65
+ const badInput = { email: 'bad-email', password: '123' };
66
+ const result = registerUserFlow(badInput);
67
+ assert.deepEqual(result, Failure('Invalid email format.', badInput));
67
68
  });
68
69
 
69
70
  it('should walk through the call tree', async function () {
@@ -76,4 +77,17 @@ describe('Pure Effect', function () {
76
77
  assert.equal(step2.type, 'Command');
77
78
  assert.equal(step2.cmd.name, 'cmdSaveUser');
78
79
  });
80
+
81
+ it('should return Success after runEffect with telemetry disabled', async function () {
82
+ const input = { email: 'test-no-telemetry@test.com', password: 'password123' };
83
+ const result = await registerUser(input);
84
+ assert.equal(result.type, 'Success');
85
+ });
86
+
87
+ it('should return Success after runEffect with telemetry enabled', async function () {
88
+ enableTelemetry();
89
+ const input = { email: 'test-telemetry@test.com', password: 'password123' };
90
+ const result = await registerUser(input);
91
+ assert.equal(result.type, 'Success');
92
+ });
79
93
  });