@dxos/effect 0.8.3 → 0.8.4-main.1da679c

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 (48) hide show
  1. package/dist/lib/browser/index.mjs +231 -28
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/lib/node-esm/index.mjs +231 -28
  5. package/dist/lib/node-esm/index.mjs.map +4 -4
  6. package/dist/lib/node-esm/meta.json +1 -1
  7. package/dist/types/src/ast.d.ts +5 -1
  8. package/dist/types/src/ast.d.ts.map +1 -1
  9. package/dist/types/src/context.d.ts +4 -0
  10. package/dist/types/src/context.d.ts.map +1 -0
  11. package/dist/types/src/errors.d.ts +43 -0
  12. package/dist/types/src/errors.d.ts.map +1 -0
  13. package/dist/types/src/errors.test.d.ts +2 -0
  14. package/dist/types/src/errors.test.d.ts.map +1 -0
  15. package/dist/types/src/index.d.ts +4 -0
  16. package/dist/types/src/index.d.ts.map +1 -1
  17. package/dist/types/src/interrupt.test.d.ts +2 -0
  18. package/dist/types/src/interrupt.test.d.ts.map +1 -0
  19. package/dist/types/src/jsonPath.d.ts.map +1 -1
  20. package/dist/types/src/layers.test.d.ts +2 -0
  21. package/dist/types/src/layers.test.d.ts.map +1 -0
  22. package/dist/types/src/resource.d.ts +4 -0
  23. package/dist/types/src/resource.d.ts.map +1 -0
  24. package/dist/types/src/resource.test.d.ts +2 -0
  25. package/dist/types/src/resource.test.d.ts.map +1 -0
  26. package/dist/types/src/testing.d.ts +44 -0
  27. package/dist/types/src/testing.d.ts.map +1 -0
  28. package/dist/types/src/url.d.ts +1 -1
  29. package/dist/types/src/url.d.ts.map +1 -1
  30. package/dist/types/tsconfig.tsbuildinfo +1 -1
  31. package/package.json +8 -6
  32. package/src/ast.test.ts +19 -2
  33. package/src/ast.ts +36 -12
  34. package/src/context.ts +15 -0
  35. package/src/errors.test.ts +22 -0
  36. package/src/errors.ts +186 -0
  37. package/src/index.ts +4 -0
  38. package/src/interrupt.test.ts +34 -0
  39. package/src/jsonPath.test.ts +1 -1
  40. package/src/jsonPath.ts +1 -1
  41. package/src/layers.test.ts +106 -0
  42. package/src/resource.test.ts +32 -0
  43. package/src/resource.ts +25 -0
  44. package/src/testing.ts +82 -0
  45. package/src/url.ts +1 -1
  46. package/dist/lib/node/index.cjs +0 -487
  47. package/dist/lib/node/index.cjs.map +0 -7
  48. package/dist/lib/node/meta.json +0 -1
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.1da679c",
4
4
  "description": "Effect utils.",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
@@ -9,6 +9,7 @@
9
9
  "type": "module",
10
10
  "exports": {
11
11
  ".": {
12
+ "source": "./src/index.ts",
12
13
  "types": "./dist/types/src/index.d.ts",
13
14
  "browser": "./dist/lib/browser/index.mjs",
14
15
  "node": "./dist/lib/node-esm/index.mjs"
@@ -24,13 +25,14 @@
24
25
  ],
25
26
  "dependencies": {
26
27
  "jsonpath-plus": "10.2.0",
27
- "@dxos/invariant": "0.8.3",
28
- "@dxos/node-std": "0.8.3",
29
- "@dxos/util": "0.8.3"
28
+ "@dxos/context": "0.8.4-main.1da679c",
29
+ "@dxos/invariant": "0.8.4-main.1da679c",
30
+ "@dxos/node-std": "0.8.4-main.1da679c",
31
+ "@dxos/util": "0.8.4-main.1da679c"
30
32
  },
31
33
  "devDependencies": {
32
- "effect": "3.14.21",
33
- "@dxos/log": "0.8.3"
34
+ "effect": "3.17.7",
35
+ "@dxos/log": "0.8.4-main.1da679c"
34
36
  },
35
37
  "peerDependencies": {
36
38
  "effect": "^3.13.3"
package/src/ast.test.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
- import { SchemaAST, Schema } from 'effect';
5
+ import { Schema, SchemaAST } from 'effect';
6
6
  import { describe, test } from 'vitest';
7
7
 
8
8
  import { invariant } from '@dxos/invariant';
@@ -12,9 +12,10 @@ import {
12
12
  findNode,
13
13
  findProperty,
14
14
  getAnnotation,
15
- getDiscriminatingProps,
16
15
  getDiscriminatedType,
16
+ getDiscriminatingProps,
17
17
  getSimpleType,
18
+ isArrayType,
18
19
  isOption,
19
20
  isSimpleType,
20
21
  visit,
@@ -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
@@ -2,7 +2,8 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
- import { Option, pipe, SchemaAST, Schema } from 'effect';
5
+ import { Option, Schema, SchemaAST, pipe } from 'effect';
6
+ import { isUndefinedKeyword } from 'effect/SchemaAST';
6
7
 
7
8
  import { invariant } from '@dxos/invariant';
8
9
  import { isNonNullable } from '@dxos/util';
@@ -16,8 +17,14 @@ import { type JsonPath, type JsonProp } from './jsonPath';
16
17
  // https://effect-ts.github.io/effect/schema/SchemaAST.ts.html
17
18
  //
18
19
 
20
+ // TODO(wittjosiah): What is a "simple type"?
19
21
  export type SimpleType = 'object' | 'string' | 'number' | 'boolean' | 'enum' | 'literal';
20
22
 
23
+ const isTupleType = (node: SchemaAST.AST): boolean => {
24
+ // NOTE: Arrays are represented as tuples with no elements and a rest part.
25
+ return SchemaAST.isTupleType(node) && node.elements.length > 0;
26
+ };
27
+
21
28
  /**
22
29
  * Get the base type; e.g., traverse through refinements.
23
30
  */
@@ -26,6 +33,8 @@ export const getSimpleType = (node: SchemaAST.AST): SimpleType | undefined => {
26
33
  SchemaAST.isDeclaration(node) ||
27
34
  SchemaAST.isObjectKeyword(node) ||
28
35
  SchemaAST.isTypeLiteral(node) ||
36
+ // TODO(wittjosiah): Tuples are actually arrays.
37
+ isTupleType(node) ||
29
38
  isDiscriminatedUnion(node)
30
39
  ) {
31
40
  return 'object';
@@ -126,15 +135,15 @@ const visitNode = (
126
135
  path: Path = [],
127
136
  depth = 0,
128
137
  ): VisitResult | undefined => {
129
- const _result = test?.(node, path, depth);
138
+ const $result = test?.(node, path, depth);
130
139
  const result: VisitResult =
131
- _result === undefined
140
+ $result === undefined
132
141
  ? VisitResult.CONTINUE
133
- : typeof _result === 'boolean'
134
- ? _result
142
+ : typeof $result === 'boolean'
143
+ ? $result
135
144
  ? VisitResult.CONTINUE
136
145
  : VisitResult.SKIP
137
- : _result;
146
+ : $result;
138
147
 
139
148
  if (result === VisitResult.EXIT) {
140
149
  return result;
@@ -217,12 +226,14 @@ export const findNode = (node: SchemaAST.AST, test: (node: SchemaAST.AST) => boo
217
226
 
218
227
  // Branching union (e.g., optional, discriminated unions).
219
228
  else if (SchemaAST.isUnion(node)) {
220
- if (isOption(node)) {
221
- for (const type of node.types) {
222
- const child = findNode(type, test);
223
- if (child) {
224
- return child;
225
- }
229
+ if (isLiteralUnion(node)) {
230
+ return undefined;
231
+ }
232
+
233
+ for (const type of node.types) {
234
+ const child = findNode(type, test);
235
+ if (child) {
236
+ return child;
226
237
  }
227
238
  }
228
239
  }
@@ -454,3 +465,16 @@ export const mapAst = (
454
465
  }
455
466
  }
456
467
  };
468
+
469
+ /**
470
+ * @returns true if AST is for Array(T) or optional(Array(T)).
471
+ */
472
+ export const isArrayType = (node: SchemaAST.AST): boolean => {
473
+ return (
474
+ SchemaAST.isTupleType(node) ||
475
+ (SchemaAST.isUnion(node) &&
476
+ node.types.some(isArrayType) &&
477
+ node.types.some(isUndefinedKeyword) &&
478
+ node.types.length === 2)
479
+ );
480
+ };
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,186 @@
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
+ * Converts a cause to an error.
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 causeToError = (cause: Cause.Cause<any>): Error => {
108
+ if (Cause.isEmpty(cause)) {
109
+ return new Error('Fiber failed without a cause');
110
+ } else if (Cause.isInterruptedOnly(cause)) {
111
+ return new Error('Fiber was interrupted');
112
+ } else {
113
+ const errors = [...Chunk.toArray(Cause.failures(cause)), ...Chunk.toArray(Cause.defects(cause))];
114
+
115
+ const getStackFrames = (): string[] => {
116
+ const o: { stack: string } = {} as any;
117
+ Error.captureStackTrace(o, getStackFrames);
118
+ return o.stack.split('\n').slice(1);
119
+ };
120
+
121
+ const stackFrames = getStackFrames();
122
+ const newErrors = errors.map((error) => prettyErrorStack(error, stackFrames));
123
+
124
+ if (newErrors.length === 1) {
125
+ return newErrors[0];
126
+ } else {
127
+ return new AggregateError(newErrors);
128
+ }
129
+ }
130
+ };
131
+
132
+ /**
133
+ * Throws an error based on the cause.
134
+ * Inserts effect spans as stack frames.
135
+ * The error will have stack frames of where the effect was run (if stack trace limit allows).
136
+ * Removes effect runtime internal stack frames.
137
+ *
138
+ * To be used in place of `Effect.runPromise`.
139
+ *
140
+ * @throws AggregateError if there are multiple errors.
141
+ */
142
+ export const throwCause = (cause: Cause.Cause<any>): never => {
143
+ throw causeToError(cause);
144
+ };
145
+
146
+ export const unwrapExit = <A>(exit: Exit.Exit<A, any>): A => {
147
+ if (Exit.isSuccess(exit)) {
148
+ return exit.value;
149
+ }
150
+
151
+ return throwCause(exit.cause);
152
+ };
153
+
154
+ /**
155
+ * Runs the embedded effect asynchronously and throws any failures and defects as errors.
156
+ * Inserts effect spans as stack frames.
157
+ * The error will have stack frames of where the effect was run (if stack trace limit allows).
158
+ * Removes effect runtime internal stack frames.
159
+ *
160
+ * To be used in place of `Effect.runPromise`.
161
+ *
162
+ * @throws AggregateError if there are multiple errors.
163
+ */
164
+ export const runAndForwardErrors = async <A, E>(
165
+ effect: Effect.Effect<A, E, never>,
166
+ options?: { signal?: AbortSignal },
167
+ ): Promise<A> => {
168
+ const exit = await Effect.runPromiseExit(effect, options);
169
+ return unwrapExit(exit);
170
+ };
171
+
172
+ /**
173
+ * Like `Effect.promise` but also caputes spans for defects.
174
+ * Workaround for: https://github.com/Effect-TS/effect/issues/5436
175
+ */
176
+ export const promiseWithCauseCapture: <A>(evaluate: (signal: AbortSignal) => PromiseLike<A>) => Effect.Effect<A> = (
177
+ evaluate,
178
+ ) =>
179
+ Effect.promise(async (signal) => {
180
+ try {
181
+ const result = await evaluate(signal);
182
+ return Effect.succeed(result);
183
+ } catch (err) {
184
+ return Effect.die(err);
185
+ }
186
+ }).pipe(Effect.flatten);
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,34 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { it } from '@effect/vitest';
6
+ import { Cause, Effect, Fiber } from 'effect';
7
+
8
+ const doWork = Effect.fn('doWork')(function* () {
9
+ yield* Effect.sleep('1 minute');
10
+
11
+ return 'work done';
12
+ });
13
+
14
+ it.effect.skip(
15
+ 'call a function to generate a research report',
16
+ Effect.fnUntraced(
17
+ function* ({ expect: _ }) {
18
+ const resultFiber = yield* doWork().pipe(Effect.fork);
19
+
20
+ setTimeout(() => {
21
+ void Effect.runPromise(Fiber.interrupt(resultFiber));
22
+ }, 2_000);
23
+
24
+ const result = yield* resultFiber;
25
+
26
+ console.log({ result });
27
+ },
28
+ Effect.catchAllCause((cause) => {
29
+ // console.log(inspect(cause, { depth: null, colors: true }));
30
+ console.log(Cause.pretty(cause));
31
+ return Effect.failCause(cause);
32
+ }),
33
+ ),
34
+ );
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { describe, expect, test } from 'vitest';
6
6
 
7
- import { createJsonPath, getField, isJsonPath, type JsonPath, splitJsonPath } from './jsonPath';
7
+ import { type JsonPath, createJsonPath, getField, isJsonPath, splitJsonPath } from './jsonPath';
8
8
 
9
9
  describe('createJsonPath', () => {
10
10
  test('supported path subset', () => {
package/src/jsonPath.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Schema, Option } from 'effect';
5
+ import { Option, Schema } from 'effect';
6
6
  import { JSONPath } from 'jsonpath-plus';
7
7
 
8
8
  import { invariant } from '@dxos/invariant';
@@ -0,0 +1,106 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { it } from '@effect/vitest';
6
+ import { Context, Duration, Effect, Layer, ManagedRuntime } from 'effect';
7
+ import { test } from 'vitest';
8
+
9
+ class ClientConfig extends Context.Tag('ClientConfig')<ClientConfig, { endpoint: string }>() {}
10
+
11
+ class Client extends Context.Tag('Client')<Client, { call: () => Effect.Effect<void> }>() {
12
+ static layer = Layer.effect(
13
+ Client,
14
+ Effect.gen(function* () {
15
+ const config = yield* ClientConfig;
16
+ return {
17
+ call: () => {
18
+ console.log('called', config.endpoint);
19
+ return Effect.void;
20
+ },
21
+ };
22
+ }),
23
+ );
24
+ }
25
+
26
+ const ServerLive = Layer.scoped(
27
+ ClientConfig,
28
+ Effect.gen(function* () {
29
+ console.log('start server');
30
+
31
+ yield* Effect.sleep(Duration.millis(100));
32
+
33
+ yield* Effect.addFinalizer(
34
+ Effect.fn(function* () {
35
+ yield* Effect.sleep(Duration.millis(100));
36
+ console.log('stop server');
37
+ }),
38
+ );
39
+
40
+ return {
41
+ endpoint: 'http://localhost:8080',
42
+ };
43
+ }),
44
+ );
45
+
46
+ it.effect.skip(
47
+ 'test',
48
+ Effect.fn(
49
+ function* ({ expect: _ }) {
50
+ const client = yield* Client;
51
+ yield* client.call();
52
+ },
53
+ Effect.provide(Layer.provide(Client.layer, ServerLive)),
54
+ ),
55
+ );
56
+
57
+ class ServerPlugin {
58
+ #runtime = ManagedRuntime.make(ServerLive);
59
+
60
+ readonly clientConfigLayer = Layer.effectContext(
61
+ this.#runtime.runtimeEffect.pipe(Effect.map((rt) => rt.context.pipe(Context.pick(ClientConfig)))),
62
+ );
63
+
64
+ async dispose() {
65
+ await this.#runtime.dispose();
66
+ }
67
+ }
68
+
69
+ class ClientPlugin {
70
+ constructor(private readonly _serverPlugin: ServerPlugin) {}
71
+
72
+ async run() {
73
+ const layer = Layer.provide(Client.layer, this._serverPlugin.clientConfigLayer);
74
+
75
+ await Effect.runPromise(
76
+ Effect.gen(function* () {
77
+ const client = yield* Client;
78
+ yield* client.call();
79
+ }).pipe(Effect.provide(layer)),
80
+ );
81
+ }
82
+ }
83
+
84
+ test.skip('plugins', async () => {
85
+ const serverPlugin = new ServerPlugin();
86
+ console.log('ServerPlugin created');
87
+
88
+ await Effect.runPromise(Effect.sleep(Duration.millis(500)));
89
+ console.log('wake up');
90
+
91
+ {
92
+ const clientPlugin1 = new ClientPlugin(serverPlugin);
93
+ console.log('ClientPlugin1 created');
94
+ await clientPlugin1.run();
95
+ console.log('client1 run');
96
+ }
97
+
98
+ {
99
+ const clientPlugin2 = new ClientPlugin(serverPlugin);
100
+ console.log('ClientPlugin2 created');
101
+ await clientPlugin2.run();
102
+ console.log('client2 run');
103
+ }
104
+
105
+ await serverPlugin.dispose();
106
+ });
@@ -0,0 +1,32 @@
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
+ const makeResource = accuireReleaseResource(() => ({
15
+ open: () => {
16
+ events.push('open');
17
+ },
18
+ close: () => {
19
+ events.push('close');
20
+ },
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
+
29
+ events.push('3');
30
+ expect(events).to.deep.equal(['1', 'open', '2', 'close', '3']);
31
+ }),
32
+ );
@@ -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
+ );