@dxos/effect 0.8.4-main.67995b8 → 0.8.4-main.a4bbb77

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.4-main.67995b8",
3
+ "version": "0.8.4-main.a4bbb77",
4
4
  "description": "Effect utils.",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
@@ -9,10 +9,10 @@
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
- "node": "./dist/lib/node-esm/index.mjs",
15
- "source": "./src/index.ts"
15
+ "node": "./dist/lib/node-esm/index.mjs"
16
16
  }
17
17
  },
18
18
  "types": "dist/types/src/index.d.ts",
@@ -24,15 +24,24 @@
24
24
  "src"
25
25
  ],
26
26
  "dependencies": {
27
+ "@effect/opentelemetry": "^0.58.0",
28
+ "@opentelemetry/api": "^1.9.0",
29
+ "@opentelemetry/core": "^2.1.0",
27
30
  "jsonpath-plus": "10.2.0",
28
- "@dxos/context": "0.8.4-main.67995b8",
29
- "@dxos/node-std": "0.8.4-main.67995b8",
30
- "@dxos/invariant": "0.8.4-main.67995b8",
31
- "@dxos/util": "0.8.4-main.67995b8"
31
+ "@dxos/context": "0.8.4-main.a4bbb77",
32
+ "@dxos/invariant": "0.8.4-main.a4bbb77",
33
+ "@dxos/node-std": "0.8.4-main.a4bbb77",
34
+ "@dxos/util": "0.8.4-main.a4bbb77"
32
35
  },
33
36
  "devDependencies": {
34
- "effect": "3.17.0",
35
- "@dxos/log": "0.8.4-main.67995b8"
37
+ "@opentelemetry/api-logs": "^0.203.0",
38
+ "@opentelemetry/resources": "^2.1.0",
39
+ "@opentelemetry/sdk-logs": "^0.203.0",
40
+ "@opentelemetry/sdk-node": "^0.203.0",
41
+ "@opentelemetry/sdk-trace-node": "^2.1.0",
42
+ "@opentelemetry/semantic-conventions": "^1.37.0",
43
+ "effect": "3.18.3",
44
+ "@dxos/log": "0.8.4-main.a4bbb77"
36
45
  },
37
46
  "peerDependencies": {
38
47
  "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,13 +12,13 @@ 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,
21
- isArrayType,
22
22
  } from './ast';
23
23
  import { type JsonPath, type JsonProp } from './jsonPath';
24
24
 
package/src/ast.ts CHANGED
@@ -2,7 +2,7 @@
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
6
  import { isUndefinedKeyword } from 'effect/SchemaAST';
7
7
 
8
8
  import { invariant } from '@dxos/invariant';
@@ -17,8 +17,14 @@ import { type JsonPath, type JsonProp } from './jsonPath';
17
17
  // https://effect-ts.github.io/effect/schema/SchemaAST.ts.html
18
18
  //
19
19
 
20
+ // TODO(wittjosiah): What is a "simple type"?
20
21
  export type SimpleType = 'object' | 'string' | 'number' | 'boolean' | 'enum' | 'literal';
21
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
+
22
28
  /**
23
29
  * Get the base type; e.g., traverse through refinements.
24
30
  */
@@ -27,6 +33,8 @@ export const getSimpleType = (node: SchemaAST.AST): SimpleType | undefined => {
27
33
  SchemaAST.isDeclaration(node) ||
28
34
  SchemaAST.isObjectKeyword(node) ||
29
35
  SchemaAST.isTypeLiteral(node) ||
36
+ // TODO(wittjosiah): Tuples are actually arrays.
37
+ isTupleType(node) ||
30
38
  isDiscriminatedUnion(node)
31
39
  ) {
32
40
  return 'object';
@@ -127,15 +135,15 @@ const visitNode = (
127
135
  path: Path = [],
128
136
  depth = 0,
129
137
  ): VisitResult | undefined => {
130
- const _result = test?.(node, path, depth);
138
+ const $result = test?.(node, path, depth);
131
139
  const result: VisitResult =
132
- _result === undefined
140
+ $result === undefined
133
141
  ? VisitResult.CONTINUE
134
- : typeof _result === 'boolean'
135
- ? _result
142
+ : typeof $result === 'boolean'
143
+ ? $result
136
144
  ? VisitResult.CONTINUE
137
145
  : VisitResult.SKIP
138
- : _result;
146
+ : $result;
139
147
 
140
148
  if (result === VisitResult.EXIT) {
141
149
  return result;
@@ -218,12 +226,14 @@ export const findNode = (node: SchemaAST.AST, test: (node: SchemaAST.AST) => boo
218
226
 
219
227
  // Branching union (e.g., optional, discriminated unions).
220
228
  else if (SchemaAST.isUnion(node)) {
221
- if (isOption(node)) {
222
- for (const type of node.types) {
223
- const child = findNode(type, test);
224
- if (child) {
225
- return child;
226
- }
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;
227
237
  }
228
238
  }
229
239
  }
package/src/errors.ts CHANGED
@@ -95,7 +95,7 @@ const prettyErrorStack = (error: any, appendStacks: string[] = []): any => {
95
95
  };
96
96
 
97
97
  /**
98
- * Runs the embedded effect asynchronously and throws any failures and defects as errors.
98
+ * Converts a cause to an error.
99
99
  * Inserts effect spans as stack frames.
100
100
  * The error will have stack frames of where the effect was run (if stack trace limit allows).
101
101
  * Removes effect runtime internal stack frames.
@@ -104,21 +104,13 @@ const prettyErrorStack = (error: any, appendStacks: string[] = []): any => {
104
104
  *
105
105
  * @throws AggregateError if there are multiple errors.
106
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');
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');
120
112
  } else {
121
- const errors = [...Chunk.toArray(Cause.failures(exit.cause)), ...Chunk.toArray(Cause.defects(exit.cause))];
113
+ const errors = [...Chunk.toArray(Cause.failures(cause)), ...Chunk.toArray(Cause.defects(cause))];
122
114
 
123
115
  const getStackFrames = (): string[] => {
124
116
  const o: { stack: string } = {} as any;
@@ -130,9 +122,65 @@ export const runAndForwardErrors = async <A, E>(
130
122
  const newErrors = errors.map((error) => prettyErrorStack(error, stackFrames));
131
123
 
132
124
  if (newErrors.length === 1) {
133
- throw newErrors[0];
125
+ return newErrors[0];
134
126
  } else {
135
- throw new AggregateError(newErrors);
127
+ return new AggregateError(newErrors);
136
128
  }
137
129
  }
138
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);
@@ -0,0 +1,31 @@
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
+ return 'work done';
11
+ });
12
+
13
+ it.effect.skip(
14
+ 'call a function to generate a research report',
15
+ Effect.fnUntraced(
16
+ function* (_) {
17
+ const resultFiber = yield* doWork().pipe(Effect.fork);
18
+ setTimeout(() => {
19
+ void Effect.runPromise(Fiber.interrupt(resultFiber));
20
+ }, 2_000);
21
+
22
+ const result = yield* resultFiber;
23
+ console.log({ result });
24
+ },
25
+ Effect.catchAllCause((cause) => {
26
+ // console.log(inspect(cause, { depth: null, colors: true }));
27
+ console.log(Cause.pretty(cause));
28
+ return Effect.failCause(cause);
29
+ }),
30
+ ),
31
+ );
@@ -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* (_) {
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,124 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { afterAll, beforeAll, it } from '@effect/vitest';
6
+ import { SpanStatusCode, trace } from '@opentelemetry/api';
7
+ import { type Logger, SeverityNumber, logs } from '@opentelemetry/api-logs';
8
+ import { resourceFromAttributes } from '@opentelemetry/resources';
9
+ import { ConsoleLogRecordExporter, LoggerProvider, SimpleLogRecordProcessor } from '@opentelemetry/sdk-logs';
10
+ import { NodeSDK } from '@opentelemetry/sdk-node';
11
+ import { ConsoleSpanExporter } from '@opentelemetry/sdk-trace-node';
12
+ import {
13
+ ATTR_CODE_FILE_PATH,
14
+ ATTR_CODE_LINE_NUMBER,
15
+ ATTR_CODE_STACKTRACE,
16
+ ATTR_SERVICE_NAME,
17
+ } from '@opentelemetry/semantic-conventions';
18
+ import { Duration, Effect } from 'effect';
19
+ import { beforeEach } from 'vitest';
20
+
21
+ import { LogLevel, type LogProcessor, log } from '@dxos/log';
22
+
23
+ import { layerOtel } from './otel';
24
+
25
+ const resource = resourceFromAttributes({
26
+ [ATTR_SERVICE_NAME]: 'test',
27
+ });
28
+
29
+ const sdk = new NodeSDK({
30
+ traceExporter: new ConsoleSpanExporter(),
31
+ resource,
32
+ });
33
+
34
+ // and add a processor to export log record
35
+ const loggerProvider = new LoggerProvider({
36
+ processors: [new SimpleLogRecordProcessor(new ConsoleLogRecordExporter())],
37
+ resource,
38
+ });
39
+ logs.setGlobalLoggerProvider(loggerProvider);
40
+
41
+ // You can also use global singleton
42
+ const logger = logs.getLogger('test');
43
+
44
+ const makeOtelLogProcessor = (logger: Logger): LogProcessor => {
45
+ return (config, entry) => {
46
+ let severity: SeverityNumber = SeverityNumber.UNSPECIFIED;
47
+ switch (entry.level) {
48
+ case LogLevel.DEBUG:
49
+ severity = SeverityNumber.DEBUG;
50
+ break;
51
+ case LogLevel.INFO:
52
+ severity = SeverityNumber.INFO;
53
+ break;
54
+ case LogLevel.WARN:
55
+ severity = SeverityNumber.WARN;
56
+ break;
57
+ case LogLevel.ERROR:
58
+ severity = SeverityNumber.ERROR;
59
+ break;
60
+ }
61
+
62
+ logger.emit({
63
+ body: entry.error ? ('stack' in entry.error ? entry.error.stack : String(entry.error)) : entry.message,
64
+ severityNumber: severity,
65
+ attributes: {
66
+ [ATTR_CODE_FILE_PATH]: entry.meta?.F,
67
+ [ATTR_CODE_LINE_NUMBER]: entry.meta?.L,
68
+ [ATTR_CODE_STACKTRACE]: entry.error?.stack,
69
+ ...(typeof entry.context === 'object'
70
+ ? entry.context
71
+ : {
72
+ ctx: entry.context,
73
+ }),
74
+ },
75
+ });
76
+ };
77
+ };
78
+ log.addProcessor(makeOtelLogProcessor(logger));
79
+
80
+ beforeAll(() => {
81
+ sdk.start();
82
+ });
83
+
84
+ afterAll(async () => {
85
+ await loggerProvider.shutdown();
86
+ await sdk.shutdown();
87
+ });
88
+
89
+ beforeEach((ctx) => {
90
+ const span = trace.getTracer('testing-framework').startSpan(ctx.task.name);
91
+ ctx.onTestFailed((ctx) => {
92
+ // TODO(dmaretskyi): Record result.
93
+ span.setStatus({ code: SpanStatusCode.ERROR });
94
+ span.end();
95
+ });
96
+ ctx.onTestFinished((ctx) => {
97
+ span.setStatus({ code: SpanStatusCode.OK });
98
+ span.end();
99
+ });
100
+ });
101
+
102
+ const foo = Effect.fn('foo')(function* () {
103
+ yield* Effect.sleep(Duration.millis(100));
104
+
105
+ log('log inside foo', { detail: 123 });
106
+ });
107
+
108
+ const bar = Effect.fn('bar')(function* () {
109
+ yield* foo();
110
+ });
111
+
112
+ const baz = Effect.fn('baz')(function* () {
113
+ yield* bar();
114
+ });
115
+
116
+ it.live(
117
+ 'Test Suite One',
118
+ Effect.fnUntraced(
119
+ function* () {
120
+ yield* baz();
121
+ },
122
+ Effect.provide(layerOtel(Effect.succeed({}))),
123
+ ),
124
+ );
package/src/otel.ts ADDED
@@ -0,0 +1,41 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { Resource, Tracer } from '@effect/opentelemetry';
6
+ import { type Attributes, trace } from '@opentelemetry/api';
7
+ import { Effect, Layer } from 'effect';
8
+ import { type LazyArg } from 'effect/Function';
9
+
10
+ export interface Configuration {
11
+ readonly resource?:
12
+ | {
13
+ readonly serviceName: string;
14
+ readonly serviceVersion?: string;
15
+ readonly attributes?: Attributes;
16
+ }
17
+ | undefined;
18
+ }
19
+
20
+ // Based on https://github.com/Effect-TS/effect/blob/main/packages/opentelemetry/src/NodeSdk.ts
21
+ export const layerOtel: {
22
+ (evaluate: LazyArg<Configuration>): Layer.Layer<Resource.Resource>;
23
+ <R, E>(evaluate: Effect.Effect<Configuration, E, R>): Layer.Layer<Resource.Resource, E, R>;
24
+ } = (evaluate: LazyArg<Configuration> | Effect.Effect<Configuration, any, any>): Layer.Layer<Resource.Resource> =>
25
+ Layer.unwrapEffect(
26
+ Effect.map(
27
+ Effect.isEffect(evaluate) ? (evaluate as Effect.Effect<Configuration>) : Effect.sync(evaluate),
28
+ (config) => {
29
+ const ResourceLive = Resource.layerFromEnv(config.resource && Resource.configToAttributes(config.resource));
30
+
31
+ const provider = trace.getTracerProvider();
32
+ const TracerLive = Layer.provide(Tracer.layer, Layer.succeed(Tracer.OtelTracerProvider, provider));
33
+
34
+ // TODO(wittjosiah): Add metrics and logger layers.
35
+ const MetricsLive = Layer.empty;
36
+ const LoggerLive = Layer.empty;
37
+
38
+ return Layer.mergeAll(TracerLive, MetricsLive, LoggerLive).pipe(Layer.provideMerge(ResourceLive));
39
+ },
40
+ ),
41
+ );
@@ -11,7 +11,6 @@ it.effect(
11
11
  'acquire-release',
12
12
  Effect.fn(function* ({ expect }) {
13
13
  const events: string[] = [];
14
-
15
14
  const makeResource = accuireReleaseResource(() => ({
16
15
  open: () => {
17
16
  events.push('open');
@@ -20,11 +19,13 @@ it.effect(
20
19
  events.push('close');
21
20
  },
22
21
  }));
22
+
23
23
  yield* Effect.gen(function* () {
24
24
  events.push('1');
25
25
  const _resource = yield* makeResource;
26
26
  events.push('2');
27
27
  }).pipe(Effect.scoped);
28
+
28
29
  events.push('3');
29
30
  expect(events).to.deep.equal(['1', 'open', '2', 'close', '3']);
30
31
  }),
package/src/testing.ts CHANGED
@@ -2,9 +2,15 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Effect } from 'effect';
5
+ import { Context, Effect } from 'effect';
6
6
  import type { TestContext } from 'vitest';
7
7
 
8
+ // TODO(dmaretskyi): Add all different test tags here.
9
+ export type TestTag =
10
+ | 'flaky' // Flaky tests.
11
+ | 'llm' // Tests with AI.
12
+ | 'sync'; // Sync with external services.
13
+
8
14
  export namespace TestHelpers {
9
15
  /**
10
16
  * Skip the test if the condition is false.
@@ -55,4 +61,49 @@ export namespace TestHelpers {
55
61
  return yield* effect;
56
62
  }
57
63
  });
64
+
65
+ /**
66
+ * Skips this test if the tag is not in the list of tags to run.
67
+ * Tags are specified in the `DX_TEST_TAGS` environment variable.
68
+ *
69
+ * @param tag
70
+ * @returns
71
+ */
72
+ export const taggedTest =
73
+ (tag: TestTag) =>
74
+ <A, E, R>(effect: Effect.Effect<A, E, R>, ctx: TestContext): Effect.Effect<A, E, R> =>
75
+ Effect.gen(function* () {
76
+ if (!process.env.DX_TEST_TAGS?.includes(tag)) {
77
+ ctx.skip();
78
+ } else {
79
+ return yield* effect;
80
+ }
81
+ });
82
+
83
+ /**
84
+ * Provide TestContext from test parameters.
85
+ *
86
+ * Exmaple:
87
+ * ```ts
88
+ * it.effect(
89
+ * 'with context',
90
+ * Effect.fn(function* ({ expect }) {
91
+ * const ctx = yield* TestContextService;
92
+ * }),
93
+ * TestHelpers.provideTestContext,
94
+ * );
95
+ * ```
96
+ */
97
+ export const provideTestContext = <A, E, R>(
98
+ effect: Effect.Effect<A, E, R>,
99
+ ctx: TestContext,
100
+ ): Effect.Effect<A, E, Exclude<R, TestContextService>> => Effect.provideService(effect, TestContextService, ctx);
58
101
  }
102
+
103
+ /**
104
+ * Exposes vitest test context as an effect service.
105
+ */
106
+ export class TestContextService extends Context.Tag('@dxos/effect/TestContextService')<
107
+ TestContextService,
108
+ TestContext
109
+ >() {}
package/src/url.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
- import { SchemaAST, type Schema, Option, pipe } from 'effect';
5
+ import { Option, type Schema, SchemaAST, pipe } from 'effect';
6
6
 
7
7
  import { decamelize } from '@dxos/util';
8
8