@dxos/effect 0.8.4-main.fd6878d → 0.8.4-staging.60fe92afc8

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 (98) hide show
  1. package/LICENSE +102 -5
  2. package/README.md +1 -1
  3. package/dist/lib/browser/chunk-CGS2ULMK.mjs +11 -0
  4. package/dist/lib/browser/chunk-CGS2ULMK.mjs.map +7 -0
  5. package/dist/lib/browser/index.mjs +568 -329
  6. package/dist/lib/browser/index.mjs.map +4 -4
  7. package/dist/lib/browser/meta.json +1 -1
  8. package/dist/lib/browser/testing.mjs +31 -0
  9. package/dist/lib/browser/testing.mjs.map +7 -0
  10. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +11 -0
  11. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +7 -0
  12. package/dist/lib/node-esm/index.mjs +568 -329
  13. package/dist/lib/node-esm/index.mjs.map +4 -4
  14. package/dist/lib/node-esm/meta.json +1 -1
  15. package/dist/lib/node-esm/testing.mjs +31 -0
  16. package/dist/lib/node-esm/testing.mjs.map +7 -0
  17. package/dist/types/src/EffectEx.d.ts +5 -0
  18. package/dist/types/src/EffectEx.d.ts.map +1 -0
  19. package/dist/types/src/Performance.d.ts +25 -0
  20. package/dist/types/src/Performance.d.ts.map +1 -0
  21. package/dist/types/src/RuntimeProvider.d.ts +21 -0
  22. package/dist/types/src/RuntimeProvider.d.ts.map +1 -0
  23. package/dist/types/src/SchemaEx.d.ts +4 -0
  24. package/dist/types/src/SchemaEx.d.ts.map +1 -0
  25. package/dist/types/src/atom-kvs.d.ts +19 -0
  26. package/dist/types/src/atom-kvs.d.ts.map +1 -0
  27. package/dist/types/src/dynamic-runtime.d.ts +56 -0
  28. package/dist/types/src/dynamic-runtime.d.ts.map +1 -0
  29. package/dist/types/src/dynamic-runtime.test.d.ts +2 -0
  30. package/dist/types/src/dynamic-runtime.test.d.ts.map +1 -0
  31. package/dist/types/src/index.d.ts +8 -7
  32. package/dist/types/src/index.d.ts.map +1 -1
  33. package/dist/types/src/{ast.d.ts → internal/ast.d.ts} +47 -22
  34. package/dist/types/src/internal/ast.d.ts.map +1 -0
  35. package/dist/types/src/internal/async-task-tagging.d.ts +6 -0
  36. package/dist/types/src/internal/async-task-tagging.d.ts.map +1 -0
  37. package/dist/types/src/{context.d.ts → internal/context.d.ts} +2 -1
  38. package/dist/types/src/internal/context.d.ts.map +1 -0
  39. package/dist/types/src/internal/errors.d.ts +61 -0
  40. package/dist/types/src/internal/errors.d.ts.map +1 -0
  41. package/dist/types/src/{jsonPath.d.ts → internal/json-path.d.ts} +12 -4
  42. package/dist/types/src/internal/json-path.d.ts.map +1 -0
  43. package/dist/types/src/internal/resource.d.ts +8 -0
  44. package/dist/types/src/internal/resource.d.ts.map +1 -0
  45. package/dist/types/src/{url.d.ts → internal/url.d.ts} +3 -1
  46. package/dist/types/src/internal/url.d.ts.map +1 -0
  47. package/dist/types/src/interrupt.test.d.ts +2 -0
  48. package/dist/types/src/interrupt.test.d.ts.map +1 -0
  49. package/dist/types/src/json-path.test.d.ts +2 -0
  50. package/dist/types/src/json-path.test.d.ts.map +1 -0
  51. package/dist/types/src/otel.d.ts +17 -0
  52. package/dist/types/src/otel.d.ts.map +1 -0
  53. package/dist/types/src/otel.test.d.ts +2 -0
  54. package/dist/types/src/otel.test.d.ts.map +1 -0
  55. package/dist/types/src/testing.d.ts +25 -11
  56. package/dist/types/src/testing.d.ts.map +1 -1
  57. package/dist/types/src/types.d.ts +8 -0
  58. package/dist/types/src/types.d.ts.map +1 -0
  59. package/dist/types/tsconfig.tsbuildinfo +1 -1
  60. package/package.json +33 -13
  61. package/src/EffectEx.ts +18 -0
  62. package/src/Performance.ts +45 -0
  63. package/src/RuntimeProvider.ts +35 -0
  64. package/src/SchemaEx.ts +46 -0
  65. package/src/ast.test.ts +38 -10
  66. package/src/atom-kvs.ts +35 -0
  67. package/src/dynamic-runtime.test.ts +465 -0
  68. package/src/dynamic-runtime.ts +195 -0
  69. package/src/errors.test.ts +1 -1
  70. package/src/index.ts +12 -7
  71. package/src/{ast.ts → internal/ast.ts} +161 -96
  72. package/src/internal/async-task-tagging.ts +51 -0
  73. package/src/{context.ts → internal/context.ts} +2 -1
  74. package/src/internal/errors.ts +255 -0
  75. package/src/{jsonPath.ts → internal/json-path.ts} +29 -4
  76. package/src/{resource.ts → internal/resource.ts} +10 -5
  77. package/src/{url.ts → internal/url.ts} +5 -2
  78. package/src/interrupt.test.ts +35 -0
  79. package/src/{jsonPath.test.ts → json-path.test.ts} +55 -8
  80. package/src/layers.test.ts +10 -4
  81. package/src/otel.test.ts +126 -0
  82. package/src/otel.ts +45 -0
  83. package/src/resource.test.ts +3 -3
  84. package/src/sanity.test.ts +30 -15
  85. package/src/testing.ts +29 -22
  86. package/src/types.ts +11 -0
  87. package/src/url.test.ts +2 -2
  88. package/dist/types/src/ast.d.ts.map +0 -1
  89. package/dist/types/src/context.d.ts.map +0 -1
  90. package/dist/types/src/errors.d.ts +0 -15
  91. package/dist/types/src/errors.d.ts.map +0 -1
  92. package/dist/types/src/jsonPath.d.ts.map +0 -1
  93. package/dist/types/src/jsonPath.test.d.ts +0 -2
  94. package/dist/types/src/jsonPath.test.d.ts.map +0 -1
  95. package/dist/types/src/resource.d.ts +0 -4
  96. package/dist/types/src/resource.d.ts.map +0 -1
  97. package/dist/types/src/url.d.ts.map +0 -1
  98. package/src/errors.ts +0 -138
@@ -2,13 +2,15 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
- import { Option, Schema, SchemaAST, pipe } from 'effect';
6
- import { isUndefinedKeyword } from 'effect/SchemaAST';
5
+ import * as Function from 'effect/Function';
6
+ import * as Option from 'effect/Option';
7
+ import * as Schema from 'effect/Schema';
8
+ import * as SchemaAST from 'effect/SchemaAST';
7
9
 
8
10
  import { invariant } from '@dxos/invariant';
9
11
  import { isNonNullable } from '@dxos/util';
10
12
 
11
- import { type JsonPath, type JsonProp } from './jsonPath';
13
+ import { type JsonPath, type JsonProp } from './json-path';
12
14
 
13
15
  //
14
16
  // Refs
@@ -17,67 +19,66 @@ import { type JsonPath, type JsonProp } from './jsonPath';
17
19
  // https://effect-ts.github.io/effect/schema/SchemaAST.ts.html
18
20
  //
19
21
 
20
- export type SimpleType = 'object' | 'string' | 'number' | 'boolean' | 'enum' | 'literal';
21
-
22
22
  /**
23
- * Get the base type; e.g., traverse through refinements.
23
+ * Unwraps and collects refinement filters.
24
24
  */
25
- export const getSimpleType = (node: SchemaAST.AST): SimpleType | undefined => {
26
- if (
27
- SchemaAST.isDeclaration(node) ||
28
- SchemaAST.isObjectKeyword(node) ||
29
- SchemaAST.isTypeLiteral(node) ||
30
- isDiscriminatedUnion(node)
31
- ) {
32
- return 'object';
25
+ const reduceRefinements = (
26
+ type: SchemaAST.AST,
27
+ refinements: SchemaAST.Refinement['filter'][] = [],
28
+ ): { type: SchemaAST.AST; refinements: SchemaAST.Refinement['filter'][] } => {
29
+ if (SchemaAST.isRefinement(type)) {
30
+ const filter = type.filter;
31
+ const nextType = {
32
+ ...type.from,
33
+ annotations: { ...type.from.annotations, ...type.annotations },
34
+ } as SchemaAST.AST;
35
+ return reduceRefinements(nextType, [...refinements, filter]);
33
36
  }
34
37
 
35
- if (SchemaAST.isStringKeyword(node)) {
36
- return 'string';
37
- }
38
- if (SchemaAST.isNumberKeyword(node)) {
39
- return 'number';
40
- }
41
- if (SchemaAST.isBooleanKeyword(node)) {
42
- return 'boolean';
43
- }
44
-
45
- if (SchemaAST.isEnums(node)) {
46
- return 'enum';
47
- }
38
+ return { type, refinements };
39
+ };
48
40
 
49
- if (SchemaAST.isLiteral(node)) {
50
- return 'literal';
51
- }
41
+ /**
42
+ * Get the base type of a property.
43
+ *
44
+ * Unwraps refinements and optional unions.
45
+ */
46
+ export const getBaseType = (
47
+ prop: SchemaAST.PropertySignature | SchemaProperty,
48
+ ): { type: SchemaAST.AST; refinements: SchemaAST.Refinement['filter'][] } => {
49
+ const encoded = SchemaAST.encodedBoundAST(prop.type);
50
+ // Extract property ast from optional union.
51
+ const unwrapped = prop.isOptional && encoded._tag === 'Union' ? encoded.types[0] : encoded;
52
+ return reduceRefinements(unwrapped);
52
53
  };
53
54
 
54
- export const isSimpleType = (node: SchemaAST.AST): boolean => !!getSimpleType(node);
55
+ export type SchemaProperty = Pick<SchemaAST.PropertySignature, 'name' | 'type' | 'isOptional' | 'isReadonly'> & {
56
+ /** Can be used to validate the property to the spec of the initial AST. */
57
+ refinements: SchemaAST.Refinement['filter'][];
58
+ };
55
59
 
56
- export namespace SimpleType {
57
- /**
58
- * Returns the default empty value for a given SimpleType.
59
- * Used for initializing new array values etc.
60
- */
61
- export const getDefaultValue = (type: SimpleType): any => {
62
- switch (type) {
63
- case 'string': {
64
- return '';
65
- }
66
- case 'number': {
67
- return 0;
68
- }
69
- case 'boolean': {
70
- return false;
71
- }
72
- case 'object': {
73
- return {};
74
- }
75
- default: {
76
- throw new Error(`Unsupported type for default value: ${type}`);
77
- }
78
- }
79
- };
80
- }
60
+ /**
61
+ * Get the property types of an AST.
62
+ */
63
+ export const getProperties = (ast: SchemaAST.AST): SchemaProperty[] => {
64
+ const properties = SchemaAST.getPropertySignatures(ast);
65
+ return properties.map((prop) => {
66
+ const { type, refinements } = getBaseType(prop);
67
+ // Merge PropertySignature-level annotations (e.g., title, description set via .annotations())
68
+ // onto the unwrapped base type so downstream consumers see them.
69
+ const mergedType =
70
+ prop.annotations && Reflect.ownKeys(prop.annotations).length > 0
71
+ ? ({ ...type, annotations: { ...type.annotations, ...prop.annotations } } as SchemaAST.AST)
72
+ : type;
73
+ return {
74
+ type: mergedType,
75
+ refinements,
76
+ name: prop.name,
77
+ isOptional: prop.isOptional,
78
+ isReadonly: prop.isReadonly,
79
+ };
80
+ });
81
+ };
81
82
 
82
83
  //
83
84
  // Branded types
@@ -101,23 +102,14 @@ export type TestFn = (node: SchemaAST.AST, path: Path, depth: number) => VisitRe
101
102
 
102
103
  export type VisitorFn = (node: SchemaAST.AST, path: Path, depth: number) => void;
103
104
 
104
- const defaultTest: TestFn = isSimpleType;
105
-
106
105
  /**
107
106
  * Visit leaf nodes.
108
107
  * Refs:
109
108
  * - https://github.com/syntax-tree/unist-util-visit?tab=readme-ov-file#visitor
110
109
  * - https://github.com/syntax-tree/unist-util-is?tab=readme-ov-file#test
111
110
  */
112
- export const visit: {
113
- (node: SchemaAST.AST, visitor: VisitorFn): void;
114
- (node: SchemaAST.AST, test: TestFn, visitor: VisitorFn): void;
115
- } = (node: SchemaAST.AST, testOrVisitor: TestFn | VisitorFn, visitor?: VisitorFn): void => {
116
- if (!visitor) {
117
- visitNode(node, defaultTest, testOrVisitor);
118
- } else {
119
- visitNode(node, testOrVisitor as TestFn, visitor);
120
- }
111
+ export const visit = (node: SchemaAST.AST, testOrVisitor: TestFn | VisitorFn, visitor: VisitorFn): void => {
112
+ visitNode(node, testOrVisitor as TestFn, visitor);
121
113
  };
122
114
 
123
115
  const visitNode = (
@@ -127,15 +119,15 @@ const visitNode = (
127
119
  path: Path = [],
128
120
  depth = 0,
129
121
  ): VisitResult | undefined => {
130
- const _result = test?.(node, path, depth);
122
+ const $result = test?.(node, path, depth);
131
123
  const result: VisitResult =
132
- _result === undefined
124
+ $result === undefined
133
125
  ? VisitResult.CONTINUE
134
- : typeof _result === 'boolean'
135
- ? _result
126
+ : typeof $result === 'boolean'
127
+ ? $result
136
128
  ? VisitResult.CONTINUE
137
129
  : VisitResult.SKIP
138
- : _result;
130
+ : $result;
139
131
 
140
132
  if (result === VisitResult.EXIT) {
141
133
  return result;
@@ -204,6 +196,12 @@ export const findNode = (node: SchemaAST.AST, test: (node: SchemaAST.AST) => boo
204
196
  return child;
205
197
  }
206
198
  }
199
+ for (const prop of getIndexSignatures(node)) {
200
+ const child = findNode(prop.type, test);
201
+ if (child) {
202
+ return child;
203
+ }
204
+ }
207
205
  }
208
206
 
209
207
  // Tuple.
@@ -218,12 +216,14 @@ export const findNode = (node: SchemaAST.AST, test: (node: SchemaAST.AST) => boo
218
216
 
219
217
  // Branching union (e.g., optional, discriminated unions).
220
218
  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
- }
219
+ if (isLiteralUnion(node)) {
220
+ return undefined;
221
+ }
222
+
223
+ for (const type of node.types) {
224
+ const child = findNode(type, test);
225
+ if (child) {
226
+ return child;
227
227
  }
228
228
  }
229
229
  }
@@ -264,10 +264,10 @@ export const findProperty = (
264
264
  //
265
265
 
266
266
  const defaultAnnotations: Record<string, SchemaAST.Annotated> = {
267
- ['ObjectKeyword' as const]: SchemaAST.objectKeyword,
268
- ['StringKeyword' as const]: SchemaAST.stringKeyword,
269
- ['NumberKeyword' as const]: SchemaAST.numberKeyword,
270
- ['BooleanKeyword' as const]: SchemaAST.booleanKeyword,
267
+ ObjectKeyword: SchemaAST.objectKeyword,
268
+ StringKeyword: SchemaAST.stringKeyword,
269
+ NumberKeyword: SchemaAST.numberKeyword,
270
+ BooleanKeyword: SchemaAST.booleanKeyword,
271
271
  };
272
272
 
273
273
  /**
@@ -279,8 +279,8 @@ export const getAnnotation =
279
279
  <T>(annotationId: symbol, noDefault = true) =>
280
280
  (node: SchemaAST.AST): T | undefined => {
281
281
  // Title fallback seems to be the identifier.
282
- const id = pipe(SchemaAST.getIdentifierAnnotation(node), Option.getOrUndefined);
283
- const value = pipe(SchemaAST.getAnnotation<T>(annotationId)(node), Option.getOrUndefined);
282
+ const id = Function.pipe(SchemaAST.getIdentifierAnnotation(node), Option.getOrUndefined);
283
+ const value = Function.pipe(SchemaAST.getAnnotation<T>(annotationId)(node), Option.getOrUndefined);
284
284
  if (noDefault && (value === defaultAnnotations[node._tag]?.annotations[annotationId] || value === id)) {
285
285
  return undefined;
286
286
  }
@@ -326,10 +326,45 @@ export const isOption = (node: SchemaAST.AST): boolean => {
326
326
  /**
327
327
  * Determines if the node is a union of literal types.
328
328
  */
329
- export const isLiteralUnion = (node: SchemaAST.AST): boolean => {
329
+ export const isLiteralUnion = (node: SchemaAST.AST): node is SchemaAST.Union<SchemaAST.Literal> => {
330
330
  return SchemaAST.isUnion(node) && node.types.every(SchemaAST.isLiteral);
331
331
  };
332
332
 
333
+ /**
334
+ * Extracts the literal values from a schema that is a union of literals
335
+ * (e.g. `Schema.Literal('a', 'b')` or `Schema.Union(Schema.Literal('a'), Schema.Literal('b'))`).
336
+ * Returns an empty array if the schema is not a literal union.
337
+ */
338
+ export const getLiteralValues = <S extends Schema.Schema<any, any, any>>(
339
+ schema: S,
340
+ ): ReadonlyArray<Schema.Schema.Type<S>> => {
341
+ if (!isLiteralUnion(schema.ast)) {
342
+ return [];
343
+ }
344
+ return schema.ast.types.map((node) => node.literal as Schema.Schema.Type<S>);
345
+ };
346
+
347
+ /**
348
+ * Determines if the node is an array type.
349
+ */
350
+ export const isArrayType = (node: SchemaAST.AST): node is SchemaAST.TupleType => {
351
+ return SchemaAST.isTupleType(node) && node.elements.length === 0 && node.rest.length === 1;
352
+ };
353
+
354
+ /**
355
+ * Get the type of the array elements.
356
+ */
357
+ export const getArrayElementType = (node: SchemaAST.AST): SchemaAST.AST | undefined => {
358
+ return isArrayType(node) ? node.rest.at(0)?.type : undefined;
359
+ };
360
+
361
+ /**
362
+ * Determines if the node is a tuple type.
363
+ */
364
+ export const isTupleType = (node: SchemaAST.AST): boolean => {
365
+ return SchemaAST.isTupleType(node) && node.elements.length > 0;
366
+ };
367
+
333
368
  /**
334
369
  * Determines if the node is a discriminated union.
335
370
  */
@@ -409,6 +444,32 @@ export const getDiscriminatedType = (
409
444
  return schema.ast;
410
445
  };
411
446
 
447
+ /**
448
+ * If a property signature is optional (T | undefined), returns the inner non-undefined AST node.
449
+ * Otherwise returns the property signature unchanged, preserving its annotations.
450
+ */
451
+ export const unwrapOptional = (property: SchemaAST.PropertySignature): SchemaAST.PropertySignature | SchemaAST.AST => {
452
+ if (!property.isOptional || !SchemaAST.isUnion(property.type) || !isOption(property.type)) {
453
+ return property;
454
+ }
455
+
456
+ return property.type.types[0];
457
+ };
458
+
459
+ /**
460
+ * Determines if the node is a nested object type.
461
+ */
462
+ export const isNestedType = (node: SchemaAST.AST): boolean => {
463
+ return (
464
+ SchemaAST.isDeclaration(node) ||
465
+ SchemaAST.isObjectKeyword(node) ||
466
+ SchemaAST.isTypeLiteral(node) ||
467
+ // TODO(wittjosiah): Tuples are actually arrays.
468
+ isTupleType(node) ||
469
+ isDiscriminatedUnion(node)
470
+ );
471
+ };
472
+
412
473
  /**
413
474
  * Maps AST nodes.
414
475
  * The user is responsible for recursively calling {@link mapAst} on the SchemaAST.
@@ -432,6 +493,7 @@ export const mapAst = (
432
493
  ),
433
494
  ),
434
495
  ast.indexSignatures,
496
+ ast.annotations,
435
497
  );
436
498
  }
437
499
  case 'Union': {
@@ -456,15 +518,18 @@ export const mapAst = (
456
518
  }
457
519
  };
458
520
 
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
- );
521
+ const getIndexSignatures = (ast: SchemaAST.AST): Array<SchemaAST.IndexSignature> => {
522
+ const annotation = SchemaAST.getSurrogateAnnotation(ast);
523
+ if (Option.isSome(annotation)) {
524
+ return getIndexSignatures(annotation.value);
525
+ }
526
+ switch (ast._tag) {
527
+ case 'TypeLiteral':
528
+ return ast.indexSignatures.slice();
529
+ case 'Suspend':
530
+ return getIndexSignatures(ast.f());
531
+ case 'Refinement':
532
+ return getIndexSignatures(ast.from);
533
+ }
534
+ return [];
470
535
  };
@@ -0,0 +1,51 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as Context from 'effect/Context';
6
+ import * as Effect from 'effect/Effect';
7
+ import { pipe } from 'effect/Function';
8
+ import * as Layer from 'effect/Layer';
9
+ import * as Predicate from 'effect/Predicate';
10
+ import * as Tracer from 'effect/Tracer';
11
+
12
+ const runInTask = Symbol('runInTask');
13
+
14
+ /**
15
+ * Traces effect frames using console.createTask so that the proper stack-trace is visible in Chrome Devtools debugger.
16
+ */
17
+ export const asyncTaskTaggingLayer = () => {
18
+ if (Predicate.hasProperty(console, 'createTask') === false) {
19
+ return Layer.empty;
20
+ }
21
+
22
+ const makeTracer = Effect.gen(function* () {
23
+ const oldTracer = yield* Effect.tracer;
24
+ return Tracer.make({
25
+ span: (name, ...args) => {
26
+ const span = oldTracer.span(name, ...args);
27
+ const trace = (console as any).createTask(name);
28
+ (span as any)[runInTask] = (f: any) => trace.run(f);
29
+ return span;
30
+ },
31
+ context: (f, fiber) => {
32
+ const maybeParentSpan = Context.getOption(Tracer.ParentSpan)(fiber.currentContext);
33
+
34
+ if (maybeParentSpan._tag === 'None') {
35
+ return oldTracer.context(f, fiber);
36
+ }
37
+ const parentSpan = maybeParentSpan.value;
38
+ if (parentSpan._tag === 'ExternalSpan') {
39
+ return oldTracer.context(f, fiber);
40
+ }
41
+ const span = parentSpan;
42
+ if (runInTask in span && typeof span[runInTask] === 'function') {
43
+ return span[runInTask](() => oldTracer.context(f, fiber));
44
+ }
45
+
46
+ return oldTracer.context(f, fiber);
47
+ },
48
+ });
49
+ });
50
+ return pipe(makeTracer, Effect.map(Layer.setTracer), Layer.unwrapEffect);
51
+ };
@@ -2,7 +2,8 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Effect, type Scope } from 'effect';
5
+ import * as Effect from 'effect/Effect';
6
+ import type * as Scope from 'effect/Scope';
6
7
 
7
8
  import { Context } from '@dxos/context';
8
9
 
@@ -0,0 +1,255 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as Cause from 'effect/Cause';
6
+ import * as Chunk from 'effect/Chunk';
7
+ import * as Effect from 'effect/Effect';
8
+ import * as Exit from 'effect/Exit';
9
+ import * as GlobalValue from 'effect/GlobalValue';
10
+ import * as Option from 'effect/Option';
11
+ import * as Runtime from 'effect/Runtime';
12
+ import type * as Tracer from 'effect/Tracer';
13
+
14
+ const spanSymbol = Symbol.for('effect/SpanAnnotation');
15
+ const spanToTrace = GlobalValue.globalValue('effect/Tracer/spanToTrace', () => new WeakMap());
16
+ const locationRegex = /\((.*)\)/g;
17
+
18
+ /**
19
+ * Adds effect spans.
20
+ * Removes effect internal functions.
21
+ * Unwraps error proxy.
22
+ */
23
+ const prettyErrorStack = (error: any, appendStacks: string[] = []): any => {
24
+ if (typeof error !== 'object' || error === null) {
25
+ return error;
26
+ }
27
+
28
+ const span = error[spanSymbol];
29
+
30
+ const lines = typeof error.stack === 'string' ? error.stack.split('\n') : [];
31
+ const out = [];
32
+
33
+ // Very hacky way to remove effect runtime internal stack frames.
34
+ let atStack = false,
35
+ inCore = false,
36
+ passedScheduler = false;
37
+ for (let i = 0; i < lines.length; i++) {
38
+ if (!atStack && !lines[i].startsWith(' at ')) {
39
+ out.push(lines[i]);
40
+ continue;
41
+ }
42
+ atStack = true;
43
+
44
+ if (lines[i].includes(' at new BaseEffectError') || lines[i].includes(' at new YieldableError')) {
45
+ i++;
46
+ continue;
47
+ }
48
+ if (lines[i].includes('Generator.next')) {
49
+ break;
50
+ }
51
+ if (lines[i].includes('effect_internal_function')) {
52
+ break;
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
+
74
+ out.push(
75
+ lines[i]
76
+ .replace(/at .*effect_instruction_i.*\((.*)\)/, 'at $1')
77
+ .replace(/EffectPrimitive\.\w+/, '<anonymous>')
78
+ .replace(/at Arguments\./, 'at '),
79
+ );
80
+ }
81
+
82
+ if (span) {
83
+ let current: Tracer.Span | Tracer.AnySpan | undefined = span;
84
+ let i = 0;
85
+ while (current && current._tag === 'Span' && i < 10) {
86
+ const stackFn = spanToTrace.get(current);
87
+ if (typeof stackFn === 'function') {
88
+ const stack = stackFn();
89
+ if (typeof stack === 'string') {
90
+ const locationMatchAll = stack.matchAll(locationRegex);
91
+ let match = false;
92
+ for (const [, location] of locationMatchAll) {
93
+ match = true;
94
+ out.push(` at ${current.name} (${location})`);
95
+ }
96
+ if (!match) {
97
+ out.push(` at ${current.name} (${stack.replace(/^at /, '')})`);
98
+ }
99
+ } else {
100
+ out.push(` at ${current.name}`);
101
+ }
102
+ } else {
103
+ out.push(` at ${current.name}`);
104
+ }
105
+ current = Option.getOrUndefined(current.parent);
106
+ i++;
107
+ }
108
+ }
109
+
110
+ out.push(...appendStacks);
111
+
112
+ error = Cause.originalError(error);
113
+ if (error.cause) {
114
+ error.cause = prettyErrorStack(error.cause);
115
+ }
116
+
117
+ Object.defineProperty(error, 'stack', {
118
+ value: out.join('\n'),
119
+ writable: true,
120
+ enumerable: false,
121
+ configurable: true,
122
+ });
123
+
124
+ return error;
125
+ };
126
+
127
+ /**
128
+ * Converts a cause to an error.
129
+ * Inserts effect spans as stack frames.
130
+ * The error will have stack frames of where the effect was run (if stack trace limit allows).
131
+ * Removes effect runtime internal stack frames.
132
+ *
133
+ * To be used in place of `Effect.runPromise`.
134
+ *
135
+ * @throws AggregateError if there are multiple errors.
136
+ */
137
+ export const causeToError = (cause: Cause.Cause<any>): Error => {
138
+ if (Cause.isEmpty(cause)) {
139
+ return new Error('Fiber failed without a cause');
140
+ } else if (Cause.isInterruptedOnly(cause)) {
141
+ return new Error('Fiber was interrupted');
142
+ } else {
143
+ const errors = [...Chunk.toArray(Cause.failures(cause)), ...Chunk.toArray(Cause.defects(cause))];
144
+
145
+ const getStackFrames = (): string[] => {
146
+ // Bun requies the target object for `captureStackTrace` to be an Error.
147
+ const err = new Error();
148
+ Error.captureStackTrace(err, causeToError);
149
+ return err.stack!.split('\n').slice(1);
150
+ };
151
+
152
+ const stackFrames = getStackFrames();
153
+ const newErrors = errors.map((error) => prettyErrorStack(error, stackFrames));
154
+
155
+ if (newErrors.length === 1) {
156
+ return newErrors[0];
157
+ } else {
158
+ return new AggregateError(newErrors);
159
+ }
160
+ }
161
+ };
162
+
163
+ /**
164
+ * Throws an error based on the cause.
165
+ * Inserts effect spans as stack frames.
166
+ * The error will have stack frames of where the effect was run (if stack trace limit allows).
167
+ * Removes effect runtime internal stack frames.
168
+ *
169
+ * To be used in place of `Effect.runPromise`.
170
+ *
171
+ * @throws AggregateError if there are multiple errors.
172
+ */
173
+ export const throwCause = (cause: Cause.Cause<any>): never => {
174
+ throw causeToError(cause);
175
+ };
176
+
177
+ export const unwrapExit = <A>(exit: Exit.Exit<A, any>): A => {
178
+ if (Exit.isSuccess(exit)) {
179
+ return exit.value;
180
+ }
181
+
182
+ return throwCause(exit.cause);
183
+ };
184
+
185
+ /**
186
+ * Runs the embedded effect asynchronously and throws any failures and defects as errors.
187
+ * Inserts effect spans as stack frames.
188
+ * The error will have stack frames of where the effect was run (if stack trace limit allows).
189
+ * Removes effect runtime internal stack frames.
190
+ *
191
+ * To be used in place of `Effect.runPromise`.
192
+ *
193
+ * @throws AggregateError if there are multiple errors.
194
+ */
195
+ export const runAndForwardErrors = async <A, E>(
196
+ effect: Effect.Effect<A, E, never>,
197
+ options?: { signal?: AbortSignal },
198
+ ): Promise<A> => {
199
+ const exit = await Effect.runPromiseExit(effect, options);
200
+ return unwrapExit(exit);
201
+ };
202
+
203
+ /** Alias for {@link runAndForwardErrors} — preferred name when accessed via `EffectEx.runPromise`. */
204
+ export const runPromise = runAndForwardErrors;
205
+
206
+ /**
207
+ * Runs the embedded effect asynchronously and throws any failures and defects as errors.
208
+ */
209
+ export const runInRuntime: {
210
+ <R>(
211
+ runtime: Runtime.Runtime<R>,
212
+ ): <A, E>(effect: Effect.Effect<A, E, R>, options?: { signal?: AbortSignal } | undefined) => Promise<A>;
213
+ <R, A, E>(
214
+ runtime: Runtime.Runtime<R>,
215
+ effect: Effect.Effect<A, E, R>,
216
+ options?: { signal?: AbortSignal } | undefined,
217
+ ): Promise<A>;
218
+ } = (...args: any[]): any => {
219
+ if (args.length === 1) {
220
+ const [runtime] = args as [Runtime.Runtime<any>];
221
+ return async (
222
+ effect: Effect.Effect<any, any, any>,
223
+ options?: { signal?: AbortSignal } | undefined,
224
+ ): Promise<any> => {
225
+ const exit = await Runtime.runPromiseExit(runtime, effect, options);
226
+ return unwrapExit(exit);
227
+ };
228
+ } else {
229
+ const [runtime, effect, options] = args as [
230
+ Runtime.Runtime<any>,
231
+ Effect.Effect<any, any, any>,
232
+ { signal?: AbortSignal } | undefined,
233
+ ];
234
+ return (async () => {
235
+ const exit = await Runtime.runPromiseExit(runtime, effect, options);
236
+ return unwrapExit(exit);
237
+ })();
238
+ }
239
+ };
240
+
241
+ /**
242
+ * Like `Effect.promise` but also caputes spans for defects.
243
+ * Workaround for: https://github.com/Effect-TS/effect/issues/5436
244
+ */
245
+ export const promiseWithCauseCapture: <A>(evaluate: (signal: AbortSignal) => PromiseLike<A>) => Effect.Effect<A> = (
246
+ evaluate,
247
+ ) =>
248
+ Effect.promise(async (signal) => {
249
+ try {
250
+ const result = await evaluate(signal);
251
+ return Effect.succeed(result);
252
+ } catch (err) {
253
+ return Effect.die(err);
254
+ }
255
+ }).pipe(Effect.flatten);