@dxos/effect 0.8.4-main.7ace549 → 0.8.4-main.8360d9e660

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 (52) hide show
  1. package/dist/lib/browser/chunk-CGS2ULMK.mjs +11 -0
  2. package/dist/lib/browser/chunk-CGS2ULMK.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +395 -238
  4. package/dist/lib/browser/index.mjs.map +4 -4
  5. package/dist/lib/browser/meta.json +1 -1
  6. package/dist/lib/browser/testing.mjs +39 -0
  7. package/dist/lib/browser/testing.mjs.map +7 -0
  8. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +11 -0
  9. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +7 -0
  10. package/dist/lib/node-esm/index.mjs +395 -238
  11. package/dist/lib/node-esm/index.mjs.map +4 -4
  12. package/dist/lib/node-esm/meta.json +1 -1
  13. package/dist/lib/node-esm/testing.mjs +39 -0
  14. package/dist/lib/node-esm/testing.mjs.map +7 -0
  15. package/dist/types/src/Performance.d.ts +25 -0
  16. package/dist/types/src/Performance.d.ts.map +1 -0
  17. package/dist/types/src/RuntimeProvider.d.ts +21 -0
  18. package/dist/types/src/RuntimeProvider.d.ts.map +1 -0
  19. package/dist/types/src/ast.d.ts +33 -20
  20. package/dist/types/src/ast.d.ts.map +1 -1
  21. package/dist/types/src/atom-kvs.d.ts +19 -0
  22. package/dist/types/src/atom-kvs.d.ts.map +1 -0
  23. package/dist/types/src/dynamic-runtime.d.ts +56 -0
  24. package/dist/types/src/dynamic-runtime.d.ts.map +1 -0
  25. package/dist/types/src/dynamic-runtime.test.d.ts +2 -0
  26. package/dist/types/src/dynamic-runtime.test.d.ts.map +1 -0
  27. package/dist/types/src/errors.d.ts +12 -0
  28. package/dist/types/src/errors.d.ts.map +1 -1
  29. package/dist/types/src/index.d.ts +6 -3
  30. package/dist/types/src/index.d.ts.map +1 -1
  31. package/dist/types/src/json-path.d.ts +2 -2
  32. package/dist/types/src/json-path.d.ts.map +1 -1
  33. package/dist/types/src/testing.d.ts +1 -0
  34. package/dist/types/src/testing.d.ts.map +1 -1
  35. package/dist/types/tsconfig.tsbuildinfo +1 -1
  36. package/package.json +30 -11
  37. package/src/Performance.ts +45 -0
  38. package/src/RuntimeProvider.ts +35 -0
  39. package/src/ast.test.ts +34 -7
  40. package/src/ast.ts +84 -90
  41. package/src/atom-kvs.ts +35 -0
  42. package/src/dynamic-runtime.test.ts +465 -0
  43. package/src/dynamic-runtime.ts +195 -0
  44. package/src/errors.ts +69 -8
  45. package/src/index.ts +6 -3
  46. package/src/interrupt.test.ts +3 -1
  47. package/src/json-path.test.ts +7 -7
  48. package/src/json-path.ts +9 -12
  49. package/src/layers.test.ts +4 -2
  50. package/src/resource.ts +2 -2
  51. package/src/sanity.test.ts +6 -4
  52. package/src/testing.ts +3 -1
package/src/errors.ts CHANGED
@@ -8,10 +8,10 @@ import * as Effect from 'effect/Effect';
8
8
  import * as Exit from 'effect/Exit';
9
9
  import * as GlobalValue from 'effect/GlobalValue';
10
10
  import * as Option from 'effect/Option';
11
+ import * as Runtime from 'effect/Runtime';
11
12
  import type * as Tracer from 'effect/Tracer';
12
13
 
13
14
  const spanSymbol = Symbol.for('effect/SpanAnnotation');
14
- const originalSymbol = Symbol.for('effect/OriginalAnnotation');
15
15
  const spanToTrace = GlobalValue.globalValue('effect/Tracer/spanToTrace', () => new WeakMap());
16
16
  const locationRegex = /\((.*)\)/g;
17
17
 
@@ -21,12 +21,19 @@ const locationRegex = /\((.*)\)/g;
21
21
  * Unwraps error proxy.
22
22
  */
23
23
  const prettyErrorStack = (error: any, appendStacks: string[] = []): any => {
24
+ if (typeof error !== 'object' || error === null) {
25
+ return error;
26
+ }
27
+
24
28
  const span = error[spanSymbol];
25
29
 
26
30
  const lines = typeof error.stack === 'string' ? error.stack.split('\n') : [];
27
31
  const out = [];
28
32
 
29
- let atStack = false;
33
+ // Very hacky way to remove effect runtime internal stack frames.
34
+ let atStack = false,
35
+ inCore = false,
36
+ passedScheduler = false;
30
37
  for (let i = 0; i < lines.length; i++) {
31
38
  if (!atStack && !lines[i].startsWith(' at ')) {
32
39
  out.push(lines[i]);
@@ -44,6 +51,26 @@ const prettyErrorStack = (error: any, appendStacks: string[] = []): any => {
44
51
  if (lines[i].includes('effect_internal_function')) {
45
52
  break;
46
53
  }
54
+
55
+ const filename = lines[i].match(/\/([a-zA-Z0-9_\-.]+):\d+:\d+\)$/)?.[1];
56
+
57
+ if (!inCore && ['core-effect.ts'].includes(filename)) {
58
+ inCore = true;
59
+ }
60
+
61
+ if (inCore && !passedScheduler && ['Scheduler.ts'].includes(filename)) {
62
+ passedScheduler = true;
63
+ continue;
64
+ }
65
+
66
+ if (passedScheduler && !['Scheduler.ts'].includes(filename)) {
67
+ inCore = false;
68
+ }
69
+
70
+ if (inCore) {
71
+ continue;
72
+ }
73
+
47
74
  out.push(
48
75
  lines[i]
49
76
  .replace(/at .*effect_instruction_i.*\((.*)\)/, 'at $1')
@@ -82,9 +109,7 @@ const prettyErrorStack = (error: any, appendStacks: string[] = []): any => {
82
109
 
83
110
  out.push(...appendStacks);
84
111
 
85
- if (error[originalSymbol]) {
86
- error = error[originalSymbol];
87
- }
112
+ error = Cause.originalError(error);
88
113
  if (error.cause) {
89
114
  error.cause = prettyErrorStack(error.cause);
90
115
  }
@@ -118,9 +143,10 @@ export const causeToError = (cause: Cause.Cause<any>): Error => {
118
143
  const errors = [...Chunk.toArray(Cause.failures(cause)), ...Chunk.toArray(Cause.defects(cause))];
119
144
 
120
145
  const getStackFrames = (): string[] => {
121
- const o: { stack: string } = {} as any;
122
- Error.captureStackTrace(o, getStackFrames);
123
- return o.stack.split('\n').slice(1);
146
+ // Bun requies the target object for `captureStackTrace` to be an Error.
147
+ const o = new Error();
148
+ Error.captureStackTrace(o, causeToError);
149
+ return o.stack!.split('\n').slice(1);
124
150
  };
125
151
 
126
152
  const stackFrames = getStackFrames();
@@ -174,6 +200,41 @@ export const runAndForwardErrors = async <A, E>(
174
200
  return unwrapExit(exit);
175
201
  };
176
202
 
203
+ /**
204
+ * Runs the embedded effect asynchronously and throws any failures and defects as errors.
205
+ */
206
+ export const runInRuntime: {
207
+ <R>(
208
+ runtime: Runtime.Runtime<R>,
209
+ ): <A, E>(effect: Effect.Effect<A, E, R>, options?: { signal?: AbortSignal } | undefined) => Promise<A>;
210
+ <R, A, E>(
211
+ runtime: Runtime.Runtime<R>,
212
+ effect: Effect.Effect<A, E, R>,
213
+ options?: { signal?: AbortSignal } | undefined,
214
+ ): Promise<A>;
215
+ } = (...args: any[]): any => {
216
+ if (args.length === 1) {
217
+ const [runtime] = args as [Runtime.Runtime<any>];
218
+ return async (
219
+ effect: Effect.Effect<any, any, any>,
220
+ options?: { signal?: AbortSignal } | undefined,
221
+ ): Promise<any> => {
222
+ const exit = await Runtime.runPromiseExit(runtime, effect, options);
223
+ return unwrapExit(exit);
224
+ };
225
+ } else {
226
+ const [runtime, effect, options] = args as [
227
+ Runtime.Runtime<any>,
228
+ Effect.Effect<any, any, any>,
229
+ { signal?: AbortSignal } | undefined,
230
+ ];
231
+ return (async () => {
232
+ const exit = await Runtime.runPromiseExit(runtime, effect, options);
233
+ return unwrapExit(exit);
234
+ })();
235
+ }
236
+ };
237
+
177
238
  /**
178
239
  * Like `Effect.promise` but also caputes spans for defects.
179
240
  * Workaround for: https://github.com/Effect-TS/effect/issues/5436
package/src/index.ts CHANGED
@@ -3,9 +3,12 @@
3
3
  //
4
4
 
5
5
  export * from './ast';
6
- export * from './json-path';
7
- export * from './url';
6
+ export * from './atom-kvs';
8
7
  export * from './context';
8
+ export * as DynamicRuntime from './dynamic-runtime';
9
9
  export * from './errors';
10
- export * from './testing';
10
+ export * from './json-path';
11
11
  export * from './resource';
12
+ export * from './url';
13
+ export * as RuntimeProvider from './RuntimeProvider';
14
+ export * as Performance from './Performance';
@@ -7,6 +7,8 @@ import * as Cause from 'effect/Cause';
7
7
  import * as Effect from 'effect/Effect';
8
8
  import * as Fiber from 'effect/Fiber';
9
9
 
10
+ import { runAndForwardErrors } from './errors';
11
+
10
12
  const doWork = Effect.fn('doWork')(function* () {
11
13
  yield* Effect.sleep('1 minute');
12
14
  return 'work done';
@@ -18,7 +20,7 @@ it.effect.skip(
18
20
  function* (_) {
19
21
  const resultFiber = yield* doWork().pipe(Effect.fork);
20
22
  setTimeout(() => {
21
- void Effect.runPromise(Fiber.interrupt(resultFiber));
23
+ void runAndForwardErrors(Fiber.interrupt(resultFiber));
22
24
  }, 2_000);
23
25
 
24
26
  const result = yield* resultFiber;
@@ -32,9 +32,9 @@ describe('createJsonPath', () => {
32
32
 
33
33
  test('path splitting', () => {
34
34
  const cases = [
35
- ['foo.bar[0].baz', ['foo', 'bar', '0', 'baz']],
36
- ['users[1].name', ['users', '1', 'name']],
37
- ['data[0][1]', ['data', '0', '1']],
35
+ ['foo.bar[0].baz', ['foo', 'bar', 0, 'baz']],
36
+ ['users[1].name', ['users', 1, 'name']],
37
+ ['data[0][1]', ['data', 0, 1]],
38
38
  ['simple.path', ['simple', 'path']],
39
39
  ['root', ['root']],
40
40
  ] as const;
@@ -47,15 +47,15 @@ describe('createJsonPath', () => {
47
47
  test('path splitting - extended cases', () => {
48
48
  const cases = [
49
49
  // Multiple consecutive array indices.
50
- ['matrix[0][1][2]', ['matrix', '0', '1', '2']],
50
+ ['matrix[0][1][2]', ['matrix', 0, 1, 2]],
51
51
  // Properties with underscores and $.
52
52
  ['$_foo.bar_baz', ['$_foo', 'bar_baz']],
53
53
  // Deep nesting.
54
- ['very.deep.nested[0].property.path[5]', ['very', 'deep', 'nested', '0', 'property', 'path', '5']],
54
+ ['very.deep.nested[0].property.path[5]', ['very', 'deep', 'nested', 0, 'property', 'path', 5]],
55
55
  // Single character properties.
56
- ['a[0].b.c', ['a', '0', 'b', 'c']],
56
+ ['a[0].b.c', ['a', 0, 'b', 'c']],
57
57
  // Properties containing numbers.
58
- ['prop123.item456[7]', ['prop123', 'item456', '7']],
58
+ ['prop123.item456[7]', ['prop123', 'item456', 7]],
59
59
  ] as const;
60
60
 
61
61
  cases.forEach(([input, expected]) => {
package/src/json-path.ts CHANGED
@@ -55,7 +55,7 @@ export const isJsonPath = (value: unknown): value is JsonPath => {
55
55
  * @param path Array of string or number segments
56
56
  * @returns Valid JsonPath or undefined if invalid
57
57
  */
58
- export const createJsonPath = (path: (string | number)[]): JsonPath => {
58
+ export const createJsonPath = (path: readonly (string | number)[]): JsonPath => {
59
59
  const candidatePath = path
60
60
  .map((p, i) => {
61
61
  if (typeof p === 'number') {
@@ -85,7 +85,7 @@ export const fromEffectValidationPath = (effectPath: string): JsonPath => {
85
85
  * Splits a JsonPath into its constituent parts.
86
86
  * Handles property access and array indexing.
87
87
  */
88
- export const splitJsonPath = (path: JsonPath): string[] => {
88
+ export const splitJsonPath = (path: JsonPath): (string | number)[] => {
89
89
  if (!isJsonPath(path)) {
90
90
  return [];
91
91
  }
@@ -93,7 +93,11 @@ export const splitJsonPath = (path: JsonPath): string[] => {
93
93
  return (
94
94
  path
95
95
  .match(/[a-zA-Z_$][\w$]*|\[\d+\]/g)
96
- ?.map((part) => (part.startsWith('[') ? part.replace(/[[\]]/g, '') : part)) ?? []
96
+ ?.map((part) => part.replace(/[[\]]/g, ''))
97
+ .map((part) => {
98
+ const parsed = Number.parseInt(part, 10);
99
+ return Number.isNaN(parsed) ? part : parsed;
100
+ }) ?? []
97
101
  );
98
102
  };
99
103
 
@@ -110,19 +114,12 @@ export const getField = (object: any, path: JsonPath): any => {
110
114
  * Get value from object using JsonPath.
111
115
  */
112
116
  export const getValue = <T extends object>(obj: T, path: JsonPath): any => {
113
- return getDeep(
114
- obj,
115
- splitJsonPath(path).map((p) => p.replace(/[[\]]/g, '')),
116
- );
117
+ return getDeep(obj, splitJsonPath(path));
117
118
  };
118
119
 
119
120
  /**
120
121
  * Set value on object using JsonPath.
121
122
  */
122
123
  export const setValue = <T extends object>(obj: T, path: JsonPath, value: any): T => {
123
- return setDeep(
124
- obj,
125
- splitJsonPath(path).map((p) => p.replace(/[[\]]/g, '')),
126
- value,
127
- );
124
+ return setDeep(obj, splitJsonPath(path), value);
128
125
  };
@@ -10,6 +10,8 @@ import * as Layer from 'effect/Layer';
10
10
  import * as ManagedRuntime from 'effect/ManagedRuntime';
11
11
  import { test } from 'vitest';
12
12
 
13
+ import { runAndForwardErrors } from './errors';
14
+
13
15
  class ClientConfig extends Context.Tag('ClientConfig')<ClientConfig, { endpoint: string }>() {}
14
16
 
15
17
  class Client extends Context.Tag('Client')<Client, { call: () => Effect.Effect<void> }>() {
@@ -76,7 +78,7 @@ class ClientPlugin {
76
78
  async run() {
77
79
  const layer = Layer.provide(Client.layer, this._serverPlugin.clientConfigLayer);
78
80
 
79
- await Effect.runPromise(
81
+ await runAndForwardErrors(
80
82
  Effect.gen(function* () {
81
83
  const client = yield* Client;
82
84
  yield* client.call();
@@ -89,7 +91,7 @@ test.skip('plugins', async () => {
89
91
  const serverPlugin = new ServerPlugin();
90
92
  console.log('ServerPlugin created');
91
93
 
92
- await Effect.runPromise(Effect.sleep(Duration.millis(500)));
94
+ await runAndForwardErrors(Effect.sleep(Duration.millis(500)));
93
95
  console.log('wake up');
94
96
 
95
97
  {
package/src/resource.ts CHANGED
@@ -17,14 +17,14 @@ export const acquireReleaseResource = <T extends Lifecycle>(
17
17
  Effect.gen(function* () {
18
18
  const resource = getResource();
19
19
  yield* Effect.promise(async () => {
20
- resource.open?.();
20
+ await resource.open?.();
21
21
  return undefined;
22
22
  });
23
23
  return resource;
24
24
  }),
25
25
  (resource) =>
26
26
  Effect.promise(async () => {
27
- resource.close?.();
27
+ await resource.close?.();
28
28
  return undefined;
29
29
  }),
30
30
  );
@@ -8,6 +8,8 @@ import { describe, test } from 'vitest';
8
8
 
9
9
  import { log } from '@dxos/log';
10
10
 
11
+ import { runAndForwardErrors } from './errors';
12
+
11
13
  describe('sanity tests', () => {
12
14
  test('function pipeline', async ({ expect }) => {
13
15
  const result = Function.pipe(
@@ -19,7 +21,7 @@ describe('sanity tests', () => {
19
21
  });
20
22
 
21
23
  test('effect pipeline (mixing types)', async ({ expect }) => {
22
- const result = await Effect.runPromise(
24
+ const result = await runAndForwardErrors(
23
25
  Function.pipe(
24
26
  Effect.promise(() => Promise.resolve(100)),
25
27
  Effect.tap((value) => {
@@ -39,7 +41,7 @@ describe('sanity tests', () => {
39
41
  });
40
42
 
41
43
  test('effect pipeline (mixing sync/async)', async ({ expect }) => {
42
- const result = await Effect.runPromise(
44
+ const result = await runAndForwardErrors(
43
45
  Function.pipe(
44
46
  Effect.succeed(100),
45
47
  Effect.tap((value) => {
@@ -59,7 +61,7 @@ describe('sanity tests', () => {
59
61
  });
60
62
 
61
63
  test('error handling', async ({ expect }) => {
62
- Effect.runPromise(
64
+ runAndForwardErrors(
63
65
  Function.pipe(
64
66
  Effect.succeed(10),
65
67
  Effect.map((value) => value * 2),
@@ -75,7 +77,7 @@ describe('sanity tests', () => {
75
77
  ),
76
78
  )
77
79
  .then(() => expect.fail())
78
- .catch((error) => {
80
+ .catch((error: any) => {
79
81
  expect(error).to.be.instanceOf(Error);
80
82
  });
81
83
  });
package/src/testing.ts CHANGED
@@ -63,6 +63,8 @@ export namespace TestHelpers {
63
63
  }
64
64
  });
65
65
 
66
+ export const tagEnabled = (tag: TestTag) => process.env.DX_TEST_TAGS?.includes(tag);
67
+
66
68
  /**
67
69
  * Skips this test if the tag is not in the list of tags to run.
68
70
  * Tags are specified in the `DX_TEST_TAGS` environment variable.
@@ -74,7 +76,7 @@ export namespace TestHelpers {
74
76
  (tag: TestTag) =>
75
77
  <A, E, R>(effect: Effect.Effect<A, E, R>, ctx: TestContext): Effect.Effect<A, E, R> =>
76
78
  Effect.gen(function* () {
77
- if (!process.env.DX_TEST_TAGS?.includes(tag)) {
79
+ if (!tagEnabled(tag)) {
78
80
  ctx.skip();
79
81
  } else {
80
82
  return yield* effect;