@dxos/effect 0.8.3 → 0.8.4-main.3a94e84

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxos/effect",
3
- "version": "0.8.3",
3
+ "version": "0.8.4-main.3a94e84",
4
4
  "description": "Effect utils.",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
@@ -24,13 +24,14 @@
24
24
  ],
25
25
  "dependencies": {
26
26
  "jsonpath-plus": "10.2.0",
27
- "@dxos/invariant": "0.8.3",
28
- "@dxos/node-std": "0.8.3",
29
- "@dxos/util": "0.8.3"
27
+ "@dxos/context": "0.8.4-main.3a94e84",
28
+ "@dxos/invariant": "0.8.4-main.3a94e84",
29
+ "@dxos/node-std": "0.8.4-main.3a94e84",
30
+ "@dxos/util": "0.8.4-main.3a94e84"
30
31
  },
31
32
  "devDependencies": {
32
- "effect": "3.14.21",
33
- "@dxos/log": "0.8.3"
33
+ "effect": "3.17.0",
34
+ "@dxos/log": "0.8.4-main.3a94e84"
34
35
  },
35
36
  "peerDependencies": {
36
37
  "effect": "^3.13.3"
package/src/ast.test.ts CHANGED
@@ -18,6 +18,7 @@ import {
18
18
  isOption,
19
19
  isSimpleType,
20
20
  visit,
21
+ isArrayType,
21
22
  } from './ast';
22
23
  import { type JsonPath, type JsonProp } from './jsonPath';
23
24
 
@@ -178,4 +179,20 @@ describe('AST', () => {
178
179
  );
179
180
  }
180
181
  });
182
+
183
+ test('Schema.pluck', ({ expect }) => {
184
+ const TestSchema = Schema.Struct({
185
+ name: Schema.String,
186
+ });
187
+
188
+ expect(TestSchema.pipe(Schema.pluck('name'), Schema.typeSchema).ast).toEqual(SchemaAST.stringKeyword);
189
+ expect(() => TestSchema.pipe(Schema.pluck('missing' as any), Schema.typeSchema)).to.throw();
190
+ });
191
+
192
+ test('isArray', ({ expect }) => {
193
+ expect(isArrayType(Schema.String.ast)).to.be.false;
194
+ expect(isArrayType(Schema.Array(Schema.String).ast)).to.be.true;
195
+ expect(isArrayType(findProperty(Schema.Struct({ a: Schema.Array(Schema.String) }), 'a' as JsonPath)!)).to.be.true;
196
+ expect(isArrayType(Schema.Union(Schema.String, Schema.Array(Schema.String)).ast)).to.be.false;
197
+ });
181
198
  });
package/src/ast.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  //
4
4
 
5
5
  import { Option, pipe, SchemaAST, Schema } from 'effect';
6
+ import { isUndefinedKeyword } from 'effect/SchemaAST';
6
7
 
7
8
  import { invariant } from '@dxos/invariant';
8
9
  import { isNonNullable } from '@dxos/util';
@@ -454,3 +455,16 @@ export const mapAst = (
454
455
  }
455
456
  }
456
457
  };
458
+
459
+ /**
460
+ * @returns true if AST is for Array(T) or optional(Array(T)).
461
+ */
462
+ export const isArrayType = (node: SchemaAST.AST): boolean => {
463
+ return (
464
+ SchemaAST.isTupleType(node) ||
465
+ (SchemaAST.isUnion(node) &&
466
+ node.types.some(isArrayType) &&
467
+ node.types.some(isUndefinedKeyword) &&
468
+ node.types.length === 2)
469
+ );
470
+ };
package/src/context.ts ADDED
@@ -0,0 +1,15 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { Effect, type Scope } from 'effect';
6
+
7
+ import { Context } from '@dxos/context';
8
+
9
+ // TODO(dmaretskyi): Error handling.
10
+ export const contextFromScope = (): Effect.Effect<Context, never, Scope.Scope> =>
11
+ Effect.gen(function* () {
12
+ const ctx = new Context();
13
+ yield* Effect.addFinalizer(() => Effect.promise(() => ctx.dispose()));
14
+ return ctx;
15
+ });
@@ -0,0 +1,22 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { Data } from 'effect';
6
+ import { test } from 'vitest';
7
+
8
+ class MyError extends Data.TaggedError('MyError')<{
9
+ message: string;
10
+ }> {
11
+ constructor() {
12
+ super({ message: 'My error message' });
13
+ }
14
+ }
15
+
16
+ // Experimenting with error formatting:
17
+ // - If the error doesn't have the message set, vitest will print the error as a JS object.
18
+ // - If the error has non-empty message, vitest will pretty-print the error.
19
+ test.skip('Data error formatting', () => {
20
+ console.log(JSON.stringify(new MyError(), null, 2));
21
+ throw new MyError();
22
+ });
package/src/errors.ts ADDED
@@ -0,0 +1,138 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { Cause, Chunk, Effect, Exit, GlobalValue, Option } from 'effect';
6
+ import type { AnySpan, Span } from 'effect/Tracer';
7
+
8
+ const spanSymbol = Symbol.for('effect/SpanAnnotation');
9
+ const originalSymbol = Symbol.for('effect/OriginalAnnotation');
10
+ const spanToTrace = GlobalValue.globalValue('effect/Tracer/spanToTrace', () => new WeakMap());
11
+ const locationRegex = /\((.*)\)/g;
12
+
13
+ /**
14
+ * Adds effect spans.
15
+ * Removes effect internal functions.
16
+ * Unwraps error proxy.
17
+ */
18
+ const prettyErrorStack = (error: any, appendStacks: string[] = []): any => {
19
+ const span = error[spanSymbol];
20
+
21
+ const lines = typeof error.stack === 'string' ? error.stack.split('\n') : [];
22
+ const out = [];
23
+
24
+ let atStack = false;
25
+ for (let i = 0; i < lines.length; i++) {
26
+ if (!atStack && !lines[i].startsWith(' at ')) {
27
+ out.push(lines[i]);
28
+ continue;
29
+ }
30
+ atStack = true;
31
+
32
+ if (lines[i].includes(' at new BaseEffectError') || lines[i].includes(' at new YieldableError')) {
33
+ i++;
34
+ continue;
35
+ }
36
+ if (lines[i].includes('Generator.next')) {
37
+ break;
38
+ }
39
+ if (lines[i].includes('effect_internal_function')) {
40
+ break;
41
+ }
42
+ out.push(
43
+ lines[i]
44
+ .replace(/at .*effect_instruction_i.*\((.*)\)/, 'at $1')
45
+ .replace(/EffectPrimitive\.\w+/, '<anonymous>')
46
+ .replace(/at Arguments\./, 'at '),
47
+ );
48
+ }
49
+
50
+ if (span) {
51
+ let current: Span | AnySpan | undefined = span;
52
+ let i = 0;
53
+ while (current && current._tag === 'Span' && i < 10) {
54
+ const stackFn = spanToTrace.get(current);
55
+ if (typeof stackFn === 'function') {
56
+ const stack = stackFn();
57
+ if (typeof stack === 'string') {
58
+ const locationMatchAll = stack.matchAll(locationRegex);
59
+ let match = false;
60
+ for (const [, location] of locationMatchAll) {
61
+ match = true;
62
+ out.push(` at ${current.name} (${location})`);
63
+ }
64
+ if (!match) {
65
+ out.push(` at ${current.name} (${stack.replace(/^at /, '')})`);
66
+ }
67
+ } else {
68
+ out.push(` at ${current.name}`);
69
+ }
70
+ } else {
71
+ out.push(` at ${current.name}`);
72
+ }
73
+ current = Option.getOrUndefined(current.parent);
74
+ i++;
75
+ }
76
+ }
77
+
78
+ out.push(...appendStacks);
79
+
80
+ if (error[originalSymbol]) {
81
+ error = error[originalSymbol];
82
+ }
83
+ if (error.cause) {
84
+ error.cause = prettyErrorStack(error.cause);
85
+ }
86
+
87
+ Object.defineProperty(error, 'stack', {
88
+ value: out.join('\n'),
89
+ writable: true,
90
+ enumerable: false,
91
+ configurable: true,
92
+ });
93
+
94
+ return error;
95
+ };
96
+
97
+ /**
98
+ * Runs the embedded effect asynchronously and throws any failures and defects as errors.
99
+ * Inserts effect spans as stack frames.
100
+ * The error will have stack frames of where the effect was run (if stack trace limit allows).
101
+ * Removes effect runtime internal stack frames.
102
+ *
103
+ * To be used in place of `Effect.runPromise`.
104
+ *
105
+ * @throws AggregateError if there are multiple errors.
106
+ */
107
+ export const runAndForwardErrors = async <A, E>(
108
+ effect: Effect.Effect<A, E, never>,
109
+ options?: { signal?: AbortSignal },
110
+ ): Promise<A> => {
111
+ const exit = await Effect.runPromiseExit(effect, options);
112
+ if (Exit.isSuccess(exit)) {
113
+ return exit.value;
114
+ }
115
+
116
+ if (Cause.isEmpty(exit.cause)) {
117
+ throw new Error('Fiber failed without a cause');
118
+ } else if (Cause.isInterrupted(exit.cause)) {
119
+ throw new Error('Fiber was interrupted');
120
+ } else {
121
+ const errors = [...Chunk.toArray(Cause.failures(exit.cause)), ...Chunk.toArray(Cause.defects(exit.cause))];
122
+
123
+ const getStackFrames = (): string[] => {
124
+ const o: { stack: string } = {} as any;
125
+ Error.captureStackTrace(o, getStackFrames);
126
+ return o.stack.split('\n').slice(1);
127
+ };
128
+
129
+ const stackFrames = getStackFrames();
130
+ const newErrors = errors.map((error) => prettyErrorStack(error, stackFrames));
131
+
132
+ if (newErrors.length === 1) {
133
+ throw newErrors[0];
134
+ } else {
135
+ throw new AggregateError(newErrors);
136
+ }
137
+ }
138
+ };
package/src/index.ts CHANGED
@@ -5,3 +5,7 @@
5
5
  export * from './ast';
6
6
  export * from './jsonPath';
7
7
  export * from './url';
8
+ export * from './context';
9
+ export * from './errors';
10
+ export * from './testing';
11
+ export * from './resource';
@@ -0,0 +1,31 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { it } from '@effect/vitest';
6
+ import { Effect } from 'effect';
7
+
8
+ import { accuireReleaseResource } from './resource';
9
+
10
+ it.effect(
11
+ 'acquire-release',
12
+ Effect.fn(function* ({ expect }) {
13
+ const events: string[] = [];
14
+
15
+ const makeResource = accuireReleaseResource(() => ({
16
+ open: () => {
17
+ events.push('open');
18
+ },
19
+ close: () => {
20
+ events.push('close');
21
+ },
22
+ }));
23
+ yield* Effect.gen(function* () {
24
+ events.push('1');
25
+ const _resource = yield* makeResource;
26
+ events.push('2');
27
+ }).pipe(Effect.scoped);
28
+ events.push('3');
29
+ expect(events).to.deep.equal(['1', 'open', '2', 'close', '3']);
30
+ }),
31
+ );
@@ -0,0 +1,25 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { Effect } from 'effect';
6
+
7
+ import type { Lifecycle } from '@dxos/context';
8
+
9
+ // TODO(dmaretskyi): Extract to effect-utils.
10
+ export const accuireReleaseResource = <T extends Lifecycle>(getResource: () => T) =>
11
+ Effect.acquireRelease(
12
+ Effect.gen(function* () {
13
+ const resource = getResource();
14
+ yield* Effect.promise(async () => {
15
+ resource.open?.();
16
+ return undefined;
17
+ });
18
+ return resource;
19
+ }),
20
+ (resource) =>
21
+ Effect.promise(async () => {
22
+ resource.close?.();
23
+ return undefined;
24
+ }),
25
+ );
package/src/testing.ts ADDED
@@ -0,0 +1,58 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { Effect } from 'effect';
6
+ import type { TestContext } from 'vitest';
7
+
8
+ export namespace TestHelpers {
9
+ /**
10
+ * Skip the test if the condition is false.
11
+ *
12
+ * Exmaple:
13
+ * ```ts
14
+ * it.effect(
15
+ * 'should process an agentic loop using Claude',
16
+ * Effect.fn(function* ({ expect }) {
17
+ * // ...
18
+ * }),
19
+ * TestHelpers.runIf(process.env.ANTHROPIC_API_KEY),
20
+ * );
21
+ * ```
22
+ */
23
+ export const runIf =
24
+ (condition: unknown) =>
25
+ <A, E, R>(effect: Effect.Effect<A, E, R>, ctx: TestContext): Effect.Effect<A, E, R> =>
26
+ Effect.gen(function* () {
27
+ if (!condition) {
28
+ ctx.skip();
29
+ } else {
30
+ return yield* effect;
31
+ }
32
+ });
33
+
34
+ /**
35
+ * Skip the test if the condition is true.
36
+ *
37
+ * Exmaple:
38
+ * ```ts
39
+ * it.effect(
40
+ * 'should process an agentic loop using Claude',
41
+ * Effect.fn(function* ({ expect }) {
42
+ * // ...
43
+ * }),
44
+ * TestHelpers.skipIf(!process.env.ANTHROPIC_API_KEY),
45
+ * );
46
+ * ```
47
+ */
48
+ export const skipIf =
49
+ (condition: unknown) =>
50
+ <A, E, R>(effect: Effect.Effect<A, E, R>, ctx: TestContext): Effect.Effect<A, E, R> =>
51
+ Effect.gen(function* () {
52
+ if (condition) {
53
+ ctx.skip();
54
+ } else {
55
+ return yield* effect;
56
+ }
57
+ });
58
+ }