Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Mirrored from https://github.com/Camo67/composio.git
Synced Nov 22, 22:00 UTC
feat(cli): extract effect-errors into local src
jkomyno committed
Jul 29, 2025 at 03:07 UTC
333b03c3b688bd3850d34f6d8d00400f3047772a
61 files changed
+1139
-71
pnpm-lock.yaml
+25
-59
@@ -538,15 +538,15 @@ importers:
538
ansis:
539
specifier: ^4.1.0
540
version: 4.1.0
541
+ comment-json:
542
+ specifier: ^4.2.5
543
+ version: 4.2.5
544
decompress:
545
specifier: ^4.2.1
546
version: 4.2.1
547
effect:
548
specifier: ^3.16.16
549
version: 3.16.16
547
- effect-errors:
548
- specifier: ^1.10.11
549
- version: 1.10.11(aea1fe99f240c5dd77146c654a1423dd)
550
indent-string:
551
specifier: ^5.0.0
552
version: 5.0.0
@@ -559,6 +559,9 @@ importers:
559
semver:
560
specifier: ^7.7.2
561
version: 7.7.2
562
+ source-map-js:
563
+ specifier: ^1.2.1
564
+ version: 1.2.1
565
superjson:
566
specifier: ^2.2.2
567
version: 2.2.2
@@ -1240,15 +1243,6 @@ packages:
1243
'@effect/sql': ^0.38.2
1244
effect: ^3.16.8
1245
1243
- '@effect/platform-node@0.86.4':
1244
- resolution: {integrity: sha512-AImYc+Tg/EF0miKKgORgQEEZ1a6PpdqkH2ZU4wt0ChmWi1XFa1WF/NYzK5qRrtfSKF+ug6Vd/5/psWvZNJTdyw==}
1245
- peerDependencies:
1246
- '@effect/cluster': ^0.39.4
1247
- '@effect/platform': ^0.85.2
1248
- '@effect/rpc': ^0.62.4
1249
- '@effect/sql': ^0.38.2
1250
- effect: ^3.16.8
1251
-
1246
'@effect/platform@0.85.2':
1247
resolution: {integrity: sha512-zIRixbQeO6QniR0k2mwR7DmR2HO1w6+qQlzQ5nb8lyPyPgd1gV9wo/9yBeB6zRC+CGnxiUiYsRMamclVISuxLw==}
1248
peerDependencies:
@@ -3945,17 +3939,6 @@ packages:
3939
ee-first@1.1.1:
3940
resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==}
3941
3948
- effect-errors@1.10.11:
3949
- resolution: {integrity: sha512-lTktjnqeHfXSGQuhHm4jGWdZFfiWVZQP+szeEOuEmGEa2n4tNAu0FGO3LgS6Vp9nOatINYE3u65dFf28TtxxkQ==}
3950
- engines: {node: '>=20.x'}
3951
- peerDependencies:
3952
- '@effect/cluster': 0.x
3953
- '@effect/platform': 0.x
3954
- '@effect/platform-node': 0.x
3955
- '@effect/rpc': 0.x
3956
- '@effect/sql': 0.x
3957
- effect: 3.x
3958
-
3942
effect@3.16.16:
3943
resolution: {integrity: sha512-q8jsuAJykQJJ9jDkR9VaAR1JeHnEDn49g6+LkveIcfW3nIPUJw6BrC9ZPaVCJWmU23vKoVj9XqJmC/EW8kiI8g==}
3944
@@ -6173,10 +6156,6 @@ packages:
6156
resolution: {integrity: sha512-raqeBD6NQK4SkWhQzeYKd1KmIG6dllBOTt55Rmkt4HtI9mwdWtJljnrXjAFUBLTSN67HWrOIZ3EPF4kjUw80Bg==}
6157
engines: {node: '>=14.0'}
6158
6176
- undici@7.10.0:
6177
- resolution: {integrity: sha512-u5otvFBOBZvmdjWLVW+5DAc9Nkq8f24g0O9oY7qw2JVIF1VocIFoyz9JFkuVOS2j41AufeO0xnlweJ2RLT8nGw==}
6178
- engines: {node: '>=20.18.1'}
6179
-
6159
unenv@2.0.0-rc.17:
6160
resolution: {integrity: sha512-B06u0wXkEd+o5gOCMl/ZHl5cfpYbDZKAT+HWTL+Hws6jWu7dCiqBBXXXzMFcFVJb8D4ytAnYmxJA83uwOQRSsg==}
6161
@@ -7260,21 +7239,6 @@ snapshots:
7239
- bufferutil
7240
- utf-8-validate
7241
7263
- '@effect/platform-node@0.86.4(@effect/cluster@0.39.4(@effect/platform@0.85.2(effect@3.16.16))(@effect/rpc@0.62.4(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(@effect/sql@0.38.2(@effect/experimental@0.49.2(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(@effect/workflow@0.2.4(@effect/platform@0.85.2(effect@3.16.16))(@effect/rpc@0.62.4(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(effect@3.16.16))(effect@3.16.16))(@effect/platform@0.85.2(effect@3.16.16))(@effect/rpc@0.62.4(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(@effect/sql@0.38.2(@effect/experimental@0.49.2(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(effect@3.16.16)':
7264
- dependencies:
7265
- '@effect/cluster': 0.39.4(@effect/platform@0.85.2(effect@3.16.16))(@effect/rpc@0.62.4(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(@effect/sql@0.38.2(@effect/experimental@0.49.2(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(@effect/workflow@0.2.4(@effect/platform@0.85.2(effect@3.16.16))(@effect/rpc@0.62.4(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(effect@3.16.16))(effect@3.16.16)
7266
- '@effect/platform': 0.85.2(effect@3.16.16)
7267
- '@effect/platform-node-shared': 0.40.5(@effect/cluster@0.39.4(@effect/platform@0.85.2(effect@3.16.16))(@effect/rpc@0.62.4(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(@effect/sql@0.38.2(@effect/experimental@0.49.2(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(@effect/workflow@0.2.4(@effect/platform@0.85.2(effect@3.16.16))(@effect/rpc@0.62.4(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(effect@3.16.16))(effect@3.16.16))(@effect/platform@0.85.2(effect@3.16.16))(@effect/rpc@0.62.4(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(@effect/sql@0.38.2(@effect/experimental@0.49.2(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(effect@3.16.16)
7268
- '@effect/rpc': 0.62.4(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16)
7269
- '@effect/sql': 0.38.2(@effect/experimental@0.49.2(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16)
7270
- effect: 3.16.16
7271
- mime: 3.0.0
7272
- undici: 7.10.0
7273
- ws: 8.18.2
7274
- transitivePeerDependencies:
7275
- - bufferutil
7276
- - utf-8-validate
7277
-
7242
'@effect/platform@0.85.2(effect@3.16.16)':
7243
dependencies:
7244
effect: 3.16.16
@@ -9619,6 +9583,14 @@ snapshots:
9583
chai: 5.2.0
9584
tinyrainbow: 2.0.0
9585
9586
+ '@vitest/mocker@3.2.4(vite@6.3.5(@types/node@20.19.1)(jiti@1.21.7)(tsx@4.20.3)(yaml@2.8.0))':
9587
+ dependencies:
9588
+ '@vitest/spy': 3.2.4
9589
+ estree-walker: 3.0.3
9590
+ magic-string: 0.30.17
9591
+ optionalDependencies:
9592
+ vite: 6.3.5(@types/node@20.19.1)(jiti@1.21.7)(tsx@4.20.3)(yaml@2.8.0)
9593
+
9594
'@vitest/mocker@3.2.4(vite@6.3.5(@types/node@22.15.32)(jiti@1.21.7)(tsx@4.20.3)(yaml@2.8.0))':
9595
dependencies:
9596
'@vitest/spy': 3.2.4
@@ -9627,6 +9599,14 @@ snapshots:
9599
optionalDependencies:
9600
vite: 6.3.5(@types/node@22.15.32)(jiti@1.21.7)(tsx@4.20.3)(yaml@2.8.0)
9601
9602
+ '@vitest/mocker@3.2.4(vite@6.3.5(@types/node@24.0.3)(jiti@1.21.7)(tsx@4.20.3)(yaml@2.8.0))':
9603
+ dependencies:
9604
+ '@vitest/spy': 3.2.4
9605
+ estree-walker: 3.0.3
9606
+ magic-string: 0.30.17
9607
+ optionalDependencies:
9608
+ vite: 6.3.5(@types/node@24.0.3)(jiti@1.21.7)(tsx@4.20.3)(yaml@2.8.0)
9609
+
9610
'@vitest/pretty-format@3.2.4':
9611
dependencies:
9612
tinyrainbow: 2.0.0
@@ -9656,7 +9636,7 @@ snapshots:
9636
sirv: 3.0.1
9637
tinyglobby: 0.2.14
9638
tinyrainbow: 2.0.0
9659
- vitest: 3.2.4(@types/node@22.15.32)(@vitest/ui@3.2.4)(jiti@1.21.7)(tsx@4.20.3)(yaml@2.8.0)
9639
+ vitest: 3.2.4(@types/node@24.0.3)(@vitest/ui@3.2.4)(jiti@1.21.7)(tsx@4.20.3)(yaml@2.8.0)
9640
9641
'@vitest/utils@3.2.4':
9642
dependencies:
@@ -10245,18 +10225,6 @@ snapshots:
10225
10226
ee-first@1.1.1: {}
10227
10248
- effect-errors@1.10.11(aea1fe99f240c5dd77146c654a1423dd):
10249
- dependencies:
10250
- '@effect/cluster': 0.39.4(@effect/platform@0.85.2(effect@3.16.16))(@effect/rpc@0.62.4(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(@effect/sql@0.38.2(@effect/experimental@0.49.2(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(@effect/workflow@0.2.4(@effect/platform@0.85.2(effect@3.16.16))(@effect/rpc@0.62.4(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(effect@3.16.16))(effect@3.16.16)
10251
- '@effect/platform': 0.85.2(effect@3.16.16)
10252
- '@effect/platform-node': 0.86.4(@effect/cluster@0.39.4(@effect/platform@0.85.2(effect@3.16.16))(@effect/rpc@0.62.4(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(@effect/sql@0.38.2(@effect/experimental@0.49.2(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(@effect/workflow@0.2.4(@effect/platform@0.85.2(effect@3.16.16))(@effect/rpc@0.62.4(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(effect@3.16.16))(effect@3.16.16))(@effect/platform@0.85.2(effect@3.16.16))(@effect/rpc@0.62.4(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(@effect/sql@0.38.2(@effect/experimental@0.49.2(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(effect@3.16.16)
10253
- '@effect/rpc': 0.62.4(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16)
10254
- '@effect/sql': 0.38.2(@effect/experimental@0.49.2(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16))(@effect/platform@0.85.2(effect@3.16.16))(effect@3.16.16)
10255
- comment-json: 4.2.5
10256
- effect: 3.16.16
10257
- picocolors: 1.1.1
10258
- source-map-js: 1.2.1
10259
-
10228
effect@3.16.16:
10229
dependencies:
10230
'@standard-schema/spec': 1.0.0
@@ -12568,8 +12536,6 @@ snapshots:
12536
dependencies:
12537
'@fastify/busboy': 2.1.1
12538
12571
- undici@7.10.0: {}
12572
-
12539
unenv@2.0.0-rc.17:
12540
dependencies:
12541
defu: 6.1.4
@@ -12720,7 +12686,7 @@ snapshots:
12686
dependencies:
12687
'@types/chai': 5.2.2
12688
'@vitest/expect': 3.2.4
12723
- '@vitest/mocker': 3.2.4(vite@6.3.5(@types/node@22.15.32)(jiti@1.21.7)(tsx@4.20.3)(yaml@2.8.0))
12689
+ '@vitest/mocker': 3.2.4(vite@6.3.5(@types/node@20.19.1)(jiti@1.21.7)(tsx@4.20.3)(yaml@2.8.0))
12690
'@vitest/pretty-format': 3.2.4
12691
'@vitest/runner': 3.2.4
12692
'@vitest/snapshot': 3.2.4
@@ -12804,7 +12770,7 @@ snapshots:
12770
dependencies:
12771
'@types/chai': 5.2.2
12772
'@vitest/expect': 3.2.4
12807
- '@vitest/mocker': 3.2.4(vite@6.3.5(@types/node@22.15.32)(jiti@1.21.7)(tsx@4.20.3)(yaml@2.8.0))
12773
+ '@vitest/mocker': 3.2.4(vite@6.3.5(@types/node@24.0.3)(jiti@1.21.7)(tsx@4.20.3)(yaml@2.8.0))
12774
'@vitest/pretty-format': 3.2.4
12775
'@vitest/runner': 3.2.4
12776
'@vitest/snapshot': 3.2.4
ts/packages/cli/package.json
+2
-1
@@ -66,13 +66,14 @@
66
"@effect/platform-bun": "^0.70.4",
67
"@effect/platform-node-shared": "^0.40.4",
68
"ansis": "^4.1.0",
69
+ "comment-json": "^4.2.5",
70
"decompress": "^4.2.1",
71
"effect": "^3.16.16",
71
- "effect-errors": "^1.10.11",
72
"indent-string": "^5.0.0",
73
"open": "^10.2.0",
74
"picocolors": "^1.1.1",
75
"semver": "^7.7.2",
76
+ "source-map-js": "^1.2.1",
77
"superjson": "^2.2.2"
78
},
79
"gitHead": "4fae6e54d5c150fba955cc5fa314281da5a1e064"
ts/packages/cli/src/bin.ts
+1
-1
@@ -1,6 +1,6 @@
1
import process from 'node:process';
2
import { Cause, Console, Effect, Exit, Layer, Logger } from 'effect';
3
-import { captureErrors, prettyPrintFromCapturedErrors } from 'effect-errors';
3
+import { captureErrors, prettyPrintFromCapturedErrors } from 'effect-errors/index';
4
import { CliConfig } from '@effect/cli';
5
import { FetchHttpClient } from '@effect/platform';
6
import { BunContext, BunRuntime, BunFileSystem } from '@effect/platform-bun';
ts/packages/cli/src/effect-errors/README.md
new
+4
@@ -0,0 +1,4 @@
1
+The code in this folder is adapter from the `effect-errors` package published at https://github.com/jpb06/effect-errors/tree/d8bedbcb9e0506eabe396449cd16cd247eb55003.
2
+Compared to the original, it has been modified to work with custom colors.
3
+
4
+See the original [MIT License](https://github.com/jpb06/effect-errors/blob/d8bedbcb9e0506eabe396449cd16cd247eb55003/LICENSE).
ts/packages/cli/src/effect-errors/capture-errors.ts
new
+55
@@ -0,0 +1,55 @@
1
+import type { PlatformError } from '@effect/platform/Error';
2
+import type { FileSystem } from '@effect/platform/FileSystem';
3
+import { Effect } from 'effect';
4
+import { type Cause, isInterruptedOnly } from 'effect/Cause';
5
+
6
+import type { JsonParsingError } from 'effect-errors/dependencies/fs';
7
+import { captureErrorsFrom } from 'effect-errors/logic/errors';
8
+import {
9
+ type ErrorLocation,
10
+ type ErrorRelatedSources,
11
+ transformRawError,
12
+} from 'effect-errors/sourcemaps';
13
+import type { ErrorSpan } from 'effect-errors/types';
14
+
15
+export interface ErrorData {
16
+ errorType: unknown;
17
+ message: unknown;
18
+ stack: string[] | undefined;
19
+ sources: Omit<ErrorRelatedSources, '_tag'>[] | undefined;
20
+ location: Omit<ErrorLocation, '_tag'>[] | undefined;
21
+ spans: ErrorSpan[] | undefined;
22
+ isPlainString: boolean;
23
+}
24
+
25
+export interface CapturedErrors {
26
+ interrupted: boolean;
27
+ errors: ErrorData[];
28
+}
29
+
30
+export interface CaptureErrorsOptions {
31
+ stripCwd?: boolean;
32
+}
33
+
34
+export const captureErrors = <E>(
35
+ cause: Cause<E>,
36
+ options: CaptureErrorsOptions = {
37
+ stripCwd: true,
38
+ }
39
+): Effect.Effect<CapturedErrors, PlatformError | JsonParsingError, FileSystem> =>
40
+ Effect.gen(function* () {
41
+ if (isInterruptedOnly(cause)) {
42
+ return {
43
+ interrupted: true,
44
+ errors: [],
45
+ };
46
+ }
47
+
48
+ const rawErrors = captureErrorsFrom<E>(cause);
49
+ const errors = yield* Effect.forEach(rawErrors, transformRawError(options));
50
+
51
+ return {
52
+ interrupted: false,
53
+ errors,
54
+ };
55
+ });
ts/packages/cli/src/effect-errors/dependencies/fs/index.ts
new
+1
@@ -0,0 +1 @@
1
+export * from './read-json/index';
ts/packages/cli/src/effect-errors/dependencies/fs/read-json/index.ts
new
+2
@@ -0,0 +1,2 @@
1
+export * from './json-parsing.error';
2
+export * from './read-json';
ts/packages/cli/src/effect-errors/dependencies/fs/read-json/json-parsing.error.ts
new
+6
@@ -0,0 +1,6 @@
1
+import { TaggedError } from 'effect/Data';
2
+
3
+export class JsonParsingError extends TaggedError('json-parsing-error')<{
4
+ cause?: unknown;
5
+ message?: string;
6
+}> {}
ts/packages/cli/src/effect-errors/dependencies/fs/read-json/parse-json.ts
new
+21
@@ -0,0 +1,21 @@
1
+import { parse } from 'comment-json';
2
+import { Effect, pipe } from 'effect';
3
+
4
+import { JsonParsingError } from './json-parsing.error';
5
+
6
+export const parseJson = (data: string) =>
7
+ pipe(
8
+ Effect.sync(() => parse(data, null, true)),
9
+ Effect.catchAll(e =>
10
+ Effect.fail(
11
+ new JsonParsingError({
12
+ cause: e,
13
+ })
14
+ )
15
+ ),
16
+ Effect.withSpan('parse-json', {
17
+ attributes: {
18
+ data,
19
+ },
20
+ })
21
+ );
ts/packages/cli/src/effect-errors/dependencies/fs/read-json/read-json.ts
new
+21
@@ -0,0 +1,21 @@
1
+import { FileSystem } from '@effect/platform/FileSystem';
2
+import { Effect, pipe } from 'effect';
3
+
4
+import { parseJson } from './parse-json';
5
+
6
+export const readJsonEffect = <TJson>(filePath: string) =>
7
+ pipe(
8
+ Effect.gen(function* () {
9
+ const { readFileString } = yield* FileSystem;
10
+ const data = yield* readFileString(filePath, 'utf8');
11
+
12
+ if (data.length === 0) {
13
+ return null;
14
+ }
15
+
16
+ const json = yield* parseJson(data);
17
+
18
+ return json as TJson;
19
+ }),
20
+ Effect.withSpan('read-json', { attributes: { filePath } })
21
+ );
ts/packages/cli/src/effect-errors/index.ts
new
+5
@@ -0,0 +1,5 @@
1
+export * from './capture-errors.js';
2
+export * from './pretty-print-from-captured-errors.js';
3
+export type { ErrorLocation, ErrorRelatedSources, SourceCode } from './sourcemaps';
4
+export type { ErrorSpan } from './types/index';
5
+export * from './types/pretty-print-options.type';
ts/packages/cli/src/effect-errors/logic/errors/capture-errors-from-cause.ts
new
+15
@@ -0,0 +1,15 @@
1
+import { type Cause, reduceWithContext } from 'effect/Cause';
2
+
3
+import type { PrettyError } from 'effect-errors/types';
4
+
5
+import { parseError } from './parse-error';
6
+
7
+export const captureErrorsFrom = <E>(cause: Cause<E>): readonly PrettyError[] =>
8
+ reduceWithContext(cause, undefined, {
9
+ emptyCase: (): readonly PrettyError[] => [],
10
+ dieCase: (_, unknownError) => [parseError(unknownError)],
11
+ failCase: (_, error) => [parseError(error)],
12
+ interruptCase: () => [],
13
+ parallelCase: (_, l, r) => [...l, ...r],
14
+ sequentialCase: (_, l, r) => [...l, ...r],
15
+ });
ts/packages/cli/src/effect-errors/logic/errors/extract-error-details.test.ts
new
+105
@@ -0,0 +1,105 @@
1
+import { describe, expect, it } from 'vitest';
2
+
3
+import { extractErrorDetails } from './extract-error-details';
4
+
5
+describe('extractErrorDetails function', () => {
6
+ it('should handle plain strings', () => {
7
+ const error = 'Oh no';
8
+
9
+ const result = extractErrorDetails(error);
10
+
11
+ expect(result).toStrictEqual({ isPlainString: true, message: error });
12
+ });
13
+
14
+ it('should handle errors with cause', () => {
15
+ const _tag = 'MyError';
16
+ const message = 'Oh no!';
17
+ const cause = 'Some cause';
18
+
19
+ class MyError extends Error {
20
+ constructor(message: string, cause: string) {
21
+ super(message, { cause });
22
+ }
23
+
24
+ public _tag = _tag;
25
+ }
26
+ const error = new MyError(message, cause);
27
+
28
+ const result = extractErrorDetails(error);
29
+
30
+ expect(result).toStrictEqual({
31
+ isPlainString: false,
32
+ message: cause,
33
+ type: _tag,
34
+ });
35
+ });
36
+
37
+ it('should handle errors with Error ctor', () => {
38
+ const message = 'Oh no!';
39
+ const cause = 'Some cause';
40
+
41
+ class MyError extends Error {
42
+ constructor(message: string, cause: string) {
43
+ super(message, { cause });
44
+ }
45
+ }
46
+ const error = new MyError(message, cause);
47
+
48
+ const result = extractErrorDetails(error);
49
+
50
+ expect(result).toStrictEqual({
51
+ isPlainString: false,
52
+ message: [message],
53
+ type: 'Error',
54
+ });
55
+ });
56
+
57
+ it('should handle plain objects with tag attribute', () => {
58
+ const error = {
59
+ _tag: 'MyError',
60
+ message: 'Oh no!',
61
+ };
62
+
63
+ const result = extractErrorDetails(error);
64
+
65
+ expect(result).toStrictEqual({
66
+ isPlainString: false,
67
+ message: error.message,
68
+ type: error._tag,
69
+ });
70
+ });
71
+
72
+ it('should handle plain objects with toString impl', () => {
73
+ const errorType = 'MyError';
74
+ const error = {
75
+ message: 'Oh no!',
76
+ toString: () => `${errorType}: Oh no!`,
77
+ };
78
+
79
+ const result = extractErrorDetails(error);
80
+
81
+ expect(result).toStrictEqual({
82
+ isPlainString: false,
83
+ message: [error.message],
84
+ type: errorType,
85
+ });
86
+ });
87
+
88
+ it('should handle plain objects with toString impl and underlying type', () => {
89
+ const errorTypeWithUnderlyingType = 'MyError: Sucks to be you';
90
+ const error = {
91
+ message: 'Oh no!',
92
+ toString: () => `${errorTypeWithUnderlyingType}: Oh no!`,
93
+ };
94
+
95
+ const result = extractErrorDetails(error);
96
+
97
+ const [errorType, message] = errorTypeWithUnderlyingType.split(': ');
98
+
99
+ expect(result).toStrictEqual({
100
+ isPlainString: false,
101
+ message: [message, error.message],
102
+ type: errorType,
103
+ });
104
+ });
105
+});
ts/packages/cli/src/effect-errors/logic/errors/extract-error-details.ts
new
+70
@@ -0,0 +1,70 @@
1
+import { isFunction } from 'effect/Function';
2
+import { hasProperty } from 'effect/Predicate';
3
+
4
+interface ErrorDetails {
5
+ isPlainString: boolean;
6
+ type?: unknown;
7
+ message: unknown;
8
+}
9
+
10
+export const extractErrorDetails = (error: unknown): ErrorDetails => {
11
+ if (typeof error === 'string') {
12
+ return {
13
+ isPlainString: true,
14
+ message: error,
15
+ };
16
+ }
17
+
18
+ const isTaggedErrorWithCause =
19
+ error instanceof Error && hasProperty(error, 'cause') && hasProperty(error, '_tag');
20
+ if (isTaggedErrorWithCause) {
21
+ return {
22
+ isPlainString: false,
23
+ type: error._tag,
24
+ message: error.cause,
25
+ };
26
+ }
27
+
28
+ const isTaggedErrorWithErrorCtor = error instanceof Error && hasProperty(error, 'error');
29
+ if (isTaggedErrorWithErrorCtor) {
30
+ return {
31
+ isPlainString: false,
32
+ type: error.name,
33
+ message: error.error,
34
+ };
35
+ }
36
+
37
+ const isPlainObjectsWithTagAttribute =
38
+ hasProperty(error, '_tag') && hasProperty(error, 'message');
39
+ if (isPlainObjectsWithTagAttribute) {
40
+ return {
41
+ isPlainString: false,
42
+ type: error._tag,
43
+ message: error.message,
44
+ };
45
+ }
46
+
47
+ const isPlainObjectsWithToStringImpl =
48
+ hasProperty(error, 'toString') &&
49
+ isFunction(error.toString) &&
50
+ error.toString !== Object.prototype.toString &&
51
+ error.toString !== Array.prototype.toString;
52
+ if (isPlainObjectsWithToStringImpl) {
53
+ const message = (error as { toString: () => string }).toString();
54
+ const maybeWithUnderlyingType = message.split(': ');
55
+
56
+ if (maybeWithUnderlyingType.length > 1) {
57
+ const [type, ...message] = maybeWithUnderlyingType;
58
+
59
+ return {
60
+ isPlainString: false,
61
+ type,
62
+ message,
63
+ };
64
+ }
65
+
66
+ return { message, isPlainString: false };
67
+ }
68
+
69
+ return { message: `Error: ${JSON.stringify(error)}`, isPlainString: false };
70
+};
ts/packages/cli/src/effect-errors/logic/errors/index.ts
new
+2
@@ -0,0 +1,2 @@
1
+export * from './capture-errors-from-cause';
2
+export * from './parse-error';
ts/packages/cli/src/effect-errors/logic/errors/parse-error.ts
new
+28
@@ -0,0 +1,28 @@
1
+import { hasProperty } from 'effect/Predicate';
2
+import type { Span } from 'effect/Tracer';
3
+
4
+import { PrettyError } from 'effect-errors/types';
5
+
6
+import { extractErrorDetails } from './extract-error-details';
7
+
8
+const spanSymbol = Symbol.for('effect/SpanAnnotation');
9
+
10
+export const parseError = (error: unknown): PrettyError => {
11
+ const maybeSpan = hasProperty(error, spanSymbol) ? (error[spanSymbol] as Span) : undefined;
12
+ const { message, type, isPlainString } = extractErrorDetails(error);
13
+
14
+ if (error instanceof Error) {
15
+ return new PrettyError(
16
+ message,
17
+ error.stack
18
+ ?.split('\n')
19
+ .filter(el => /at (.*)/.exec(el))
20
+ .join('\r\n'),
21
+ maybeSpan,
22
+ false,
23
+ type
24
+ );
25
+ }
26
+
27
+ return new PrettyError(message, undefined, maybeSpan, isPlainString, type);
28
+};
ts/packages/cli/src/effect-errors/logic/path/index.ts
new
+1
@@ -0,0 +1 @@
1
+export * from './strip-cwd-path';
ts/packages/cli/src/effect-errors/logic/path/strip-cwd-path.ts
new
+4
@@ -0,0 +1,4 @@
1
+const cwdRegex = global.process !== undefined ? new RegExp(global.process.cwd(), 'g') : null;
2
+
3
+export const stripCwdPath = (path: string): string =>
4
+ cwdRegex === null ? path : path.replace(cwdRegex, '.');
ts/packages/cli/src/effect-errors/logic/spans/index.ts
new
+2
@@ -0,0 +1,2 @@
1
+export * from './maybe-add-error-to-spans-stack';
2
+export * from './split-spans-attributes-by-type';
ts/packages/cli/src/effect-errors/logic/spans/maybe-add-error-to-spans-stack.ts
new
+21
@@ -0,0 +1,21 @@
1
+export const removeNodeModulesEntriesFromStack = (stack: string) => {
2
+ const lines = stack.split('\r\n');
3
+
4
+ return lines.filter(line => line.includes(process.cwd()) && !line.includes('/node_modules/'));
5
+};
6
+
7
+export const maybeAddErrorToSpansStack = (
8
+ stack: string | undefined,
9
+ spanAttributesStack: string[] | undefined
10
+) => {
11
+ const effectStack: string[] = [];
12
+
13
+ if (stack && spanAttributesStack !== undefined) {
14
+ effectStack.push(...removeNodeModulesEntriesFromStack(stack));
15
+ }
16
+ if (spanAttributesStack !== undefined) {
17
+ effectStack.push(...spanAttributesStack);
18
+ }
19
+
20
+ return effectStack;
21
+};
ts/packages/cli/src/effect-errors/logic/spans/split-spans-attributes-by-type.ts
new
+25
@@ -0,0 +1,25 @@
1
+interface FilteredEffectAttributes {
2
+ stacktrace: string[];
3
+ attributes: ReadonlyMap<string, unknown>;
4
+}
5
+
6
+export const splitSpansAttributesByTypes = (attributes: ReadonlyMap<string, unknown>) =>
7
+ Array.from(attributes.entries()).reduce<FilteredEffectAttributes>(
8
+ (prev, [key, value]) => {
9
+ if (key === 'code.stacktrace') {
10
+ return {
11
+ attributes: prev.attributes,
12
+ stacktrace: [...prev.stacktrace, value] as string[],
13
+ };
14
+ }
15
+
16
+ return {
17
+ attributes: new Map([...prev.attributes, [key, value]]),
18
+ stacktrace: prev.stacktrace,
19
+ };
20
+ },
21
+ {
22
+ stacktrace: [],
23
+ attributes: new Map(),
24
+ }
25
+ );
ts/packages/cli/src/effect-errors/logic/stack/filter-stack.ts
new
+28
@@ -0,0 +1,28 @@
1
+import { Match } from 'effect';
2
+
3
+import { stripCwdPath } from 'effect-errors/logic/path';
4
+
5
+import { stackAtRegex } from './stack-regex';
6
+
7
+const match = Match.type<'node' | 'effect'>().pipe(
8
+ Match.when('effect', _ => 'at '),
9
+ Match.when('node', _ => '│ at '),
10
+ Match.exhaustive
11
+);
12
+
13
+export const filterStack = (stack: string, type: 'node' | 'effect', stripCwd: boolean) => {
14
+ const lines = stack.split('\r\n');
15
+ const out: string[] = [];
16
+
17
+ for (const line of lines) {
18
+ out.push(line.replace(/at .*effect_cutpoint.*\((.*)\)/, 'at $1'));
19
+
20
+ if (line.includes('effect_cutpoint')) {
21
+ return out.join('\r\n');
22
+ }
23
+ }
24
+
25
+ const final = out.join('\r\n').replace(stackAtRegex, match(type));
26
+
27
+ return stripCwd ? stripCwdPath(final) : final;
28
+};
ts/packages/cli/src/effect-errors/logic/stack/index.ts
new
+2
@@ -0,0 +1,2 @@
1
+export * from './filter-stack';
2
+export * from './stack-regex';
ts/packages/cli/src/effect-errors/logic/stack/stack-regex.ts
new
+2
@@ -0,0 +1,2 @@
1
+export const stackAtRegex = / {4}at /g;
2
+export const sourceFileWithMapPointerRegex = /^(file:\/\/)?(.*.([jt])sx?)(\?.*)?:(\d*):(\d*)$/;
ts/packages/cli/src/effect-errors/pretty-print-from-captured-errors.ts
new
+18
@@ -0,0 +1,18 @@
1
+import { formatCapturedError, formatTitle, interruptedMessage } from 'effect-errors/pretty-print';
2
+import { type PrettyPrintOptions, prettyPrintOptionsDefault } from 'effect-errors/types';
3
+
4
+import type { CapturedErrors } from './capture-errors';
5
+
6
+export const prettyPrintFromCapturedErrors = (
7
+ { errors, interrupted }: CapturedErrors,
8
+ options: PrettyPrintOptions = prettyPrintOptionsDefault
9
+) => {
10
+ if (interrupted) {
11
+ return interruptedMessage;
12
+ }
13
+
14
+ const title = formatTitle(errors.length);
15
+ const formattedFailures = errors.map(formatCapturedError(errors.length, options));
16
+
17
+ return [...title, ...formattedFailures].join('\r\n');
18
+};
ts/packages/cli/src/effect-errors/pretty-print/captured-errors/index.ts
new
+4
@@ -0,0 +1,4 @@
1
+export * from './maybe-advise-spans-usage';
2
+export * from './maybe-print-node-stacktrace';
3
+export * from './maybe-print-spans-timeline';
4
+export * from './print-effect-stacktrace';
ts/packages/cli/src/effect-errors/pretty-print/captured-errors/maybe-advice-spans-usage.ts
new
+11
@@ -0,0 +1,11 @@
1
+import color from 'picocolors';
2
+
3
+import type { ErrorSpan } from 'effect-errors/types';
4
+
5
+export const maybeAdviseSpansUsage = (spans: ErrorSpan[] | undefined): string[] => {
6
+ if (spans === undefined || spans.length === 0) {
7
+ return ['', color.gray('ℹ️ Consider using spans to improve errors reporting.')];
8
+ }
9
+
10
+ return [];
11
+};
ts/packages/cli/src/effect-errors/pretty-print/captured-errors/maybe-advise-spans-usage.ts
new
+11
@@ -0,0 +1,11 @@
1
+import color from 'picocolors';
2
+
3
+import type { ErrorSpan } from 'effect-errors/types';
4
+
5
+export const maybeAdviseSpansUsage = (spans: ErrorSpan[] | undefined): string[] => {
6
+ if (spans === undefined || spans.length === 0) {
7
+ return ['', color.gray('ℹ️ Consider using spans to improve errors reporting.')];
8
+ }
9
+
10
+ return [];
11
+};
ts/packages/cli/src/effect-errors/pretty-print/captured-errors/maybe-print-node-stacktrace.ts
new
+37
@@ -0,0 +1,37 @@
1
+import color from 'picocolors';
2
+
3
+import { stripCwdPath } from 'effect-errors/logic/path';
4
+import type { PrettyPrintOptions } from 'effect-errors/types';
5
+
6
+export const maybePrintNodeStacktrace = (
7
+ stack: string[] | undefined,
8
+ isPlainString: boolean,
9
+ { stripCwd, hideStackTrace }: PrettyPrintOptions
10
+): string[] => {
11
+ if (hideStackTrace) {
12
+ return [];
13
+ }
14
+
15
+ const stackHasNodes = stack !== undefined && stack.length > 0;
16
+ if (stackHasNodes) {
17
+ const nodes = stack.map(el => `│ ${stripCwd ? stripCwdPath(el) : el}`).join('\r\n');
18
+
19
+ return [
20
+ '',
21
+ `${color.bold(color.red('◯'))} ${color.redBright(color.underline('Node Stacktrace 🚨'))}`,
22
+ color.red(nodes),
23
+ color.red('┴'),
24
+ ];
25
+ }
26
+
27
+ if (!isPlainString) {
28
+ return [
29
+ '',
30
+ color.gray(
31
+ 'ℹ️ Consider using a yieldable error such as Data.TaggedError and Schema.TaggedError to get a stacktrace.'
32
+ ),
33
+ ];
34
+ }
35
+
36
+ return [];
37
+};
ts/packages/cli/src/effect-errors/pretty-print/captured-errors/maybe-print-spans-timeline.ts
new
+40
@@ -0,0 +1,40 @@
1
+import color from 'picocolors';
2
+
3
+import { stripCwdPath } from 'effect-errors/logic/path';
4
+import {
5
+ formatSpanAttributes,
6
+ formatSpanDuration,
7
+ missingSpansWarning,
8
+ spanStackTrailingChar,
9
+} from 'effect-errors/pretty-print/common';
10
+import type { ErrorSpan, PrettyPrintOptions } from 'effect-errors/types';
11
+
12
+export const maybePrintSpansTimeline = (
13
+ spans: ErrorSpan[] | undefined,
14
+ isPlainString: boolean,
15
+ { stripCwd }: PrettyPrintOptions
16
+): string[] => {
17
+ if (spans === undefined) {
18
+ return isPlainString === false ? ['', missingSpansWarning, ''] : [];
19
+ }
20
+
21
+ return spans.reduce<string[]>((output, { name, durationInMilliseconds, attributes }, index) => {
22
+ const isFirstEntry = index === 0;
23
+ const isLastEntry = index === spans.length - 1;
24
+
25
+ const maybeCircle = isFirstEntry ? `\r\n${color.gray('◯')}\r\n` : '';
26
+ const trailing = spanStackTrailingChar(isLastEntry);
27
+ const filePath = ` ${stripCwd !== undefined ? color.underline(color.bold(stripCwdPath(name))) : color.underline(name)}`;
28
+ const duration =
29
+ durationInMilliseconds !== undefined
30
+ ? color.gray(formatSpanDuration(durationInMilliseconds, isLastEntry))
31
+ : '';
32
+ const formattedAttributes = formatSpanAttributes(attributes, isLastEntry);
33
+
34
+ const timelineEntry = color.white(
35
+ `${maybeCircle}${trailing}${color.gray('─')}${filePath}${duration}${formattedAttributes}`
36
+ );
37
+
38
+ return [...output, timelineEntry];
39
+ }, []);
40
+};
ts/packages/cli/src/effect-errors/pretty-print/captured-errors/print-effect-stacktrace.ts
new
+30
@@ -0,0 +1,30 @@
1
+import color from 'picocolors';
2
+
3
+import { stripCwdPath } from 'effect-errors/logic/path';
4
+import type { ErrorRelatedSources } from 'effect-errors/sourcemaps';
5
+import type { ErrorSpan, PrettyPrintOptions } from 'effect-errors/types';
6
+
7
+export const printEffectStacktrace = (
8
+ sources: Omit<ErrorRelatedSources, '_tag'>[] | undefined,
9
+ spans: ErrorSpan[] | undefined,
10
+ { stripCwd }: PrettyPrintOptions
11
+) => {
12
+ const isEmpty =
13
+ spans === undefined || spans.length === 0 || sources === undefined || sources.length === 0;
14
+ if (isEmpty) {
15
+ return [];
16
+ }
17
+
18
+ const paths = sources.map(({ name, runPath, sourcesPath }) => {
19
+ const path = sourcesPath ?? runPath;
20
+ return { path: stripCwd ? stripCwdPath(path) : path, name };
21
+ });
22
+
23
+ return [
24
+ `${color.bold(color.red('◯'))} ${color.red('Sources')} 🕵️`,
25
+ ...paths.map(({ path, name }) =>
26
+ color.red(`│ at ${name.length === 0 ? 'module code' : color.underline(name)} (${path})`)
27
+ ),
28
+ color.red('┴'),
29
+ ];
30
+};
ts/packages/cli/src/effect-errors/pretty-print/common/constants/interrupted-message.ts
new
+1
@@ -0,0 +1 @@
1
+export const interruptedMessage = '✅ All fibers interrupted without errors.';
ts/packages/cli/src/effect-errors/pretty-print/common/constants/missing-spans-warning.ts
new
+3
@@ -0,0 +1,3 @@
1
+import color from 'picocolors';
2
+
3
+export const missingSpansWarning = `\r\n${color.gray('ℹ️ Consider using spans to improve errors reporting.')}`;
ts/packages/cli/src/effect-errors/pretty-print/common/format-error-title.ts
new
+17
@@ -0,0 +1,17 @@
1
+import color from 'picocolors';
2
+
3
+export const formatErrorTitle = (
4
+ errorType: unknown,
5
+ message: unknown,
6
+ failuresLength: number,
7
+ failureIndex: number
8
+): string[] => {
9
+ const failuresCount =
10
+ failuresLength > 1 ? color.bgRed(color.white(` #${failureIndex + 1} -`)) : '';
11
+ const type = color.bgRed(
12
+ color.white(` ${(errorType as string | undefined) ?? 'Unknown error'} `)
13
+ );
14
+ const formattedMessage = color.bold(color.white(` • ${message as string}`));
15
+
16
+ return [`💥 ${failuresCount}${type}${formattedMessage}`];
17
+};
ts/packages/cli/src/effect-errors/pretty-print/common/format-span-duration.ts
new
+4
@@ -0,0 +1,4 @@
1
+import color from 'picocolors';
2
+
3
+export const formatSpanDuration = (durationInMs: number | bigint, isLastEntry: boolean) =>
4
+ `\r\n${isLastEntry ? ' ' : color.gray('│')} ~ ${durationInMs}ms`;
ts/packages/cli/src/effect-errors/pretty-print/common/format-spans-attribute.ts
new
+17
@@ -0,0 +1,17 @@
1
+import color from 'picocolors';
2
+
3
+const maybePrintPipe = (isLastEntry: boolean) => (isLastEntry ? ' ' : color.gray('│'));
4
+
5
+export const formatSpanAttributes = (attributes: Record<string, unknown>, isLastEntry: boolean) => {
6
+ const entries = Object.entries(attributes);
7
+ if (entries.length === 0) {
8
+ return [];
9
+ }
10
+
11
+ const lines = Array.from(entries).map(
12
+ ([key, value]) =>
13
+ `${maybePrintPipe(isLastEntry)} ${color.blue(key)}${color.gray(':')} ${value}`
14
+ );
15
+
16
+ return `\r\n${lines.join('\r\n')}`;
17
+};
ts/packages/cli/src/effect-errors/pretty-print/common/format-title.ts
new
+14
@@ -0,0 +1,14 @@
1
+import color from 'picocolors';
2
+
3
+export const formatTitle = (errorsCount: number): string[] => {
4
+ if (errorsCount === 1) {
5
+ return [''];
6
+ }
7
+
8
+ const libName = color.bold(`${color.underline(color.redBright('effect-errors'))}`);
9
+ const title = color.bold(
10
+ color.cyanBright(`${errorsCount} error${errorsCount > 1 ? 's' : ''} occurred`)
11
+ );
12
+
13
+ return ['', `❌ ${libName} ❌ ${title}`, '', ''];
14
+};
ts/packages/cli/src/effect-errors/pretty-print/common/index.ts
new
+7
@@ -0,0 +1,7 @@
1
+export * from './constants/missing-spans-warning';
2
+export * from './format-error-title';
3
+export * from './format-span-duration';
4
+export * from './format-spans-attribute';
5
+export * from './format-title';
6
+export * from './maybe-warn-about-plain-strings';
7
+export * from './spans-stack-trailing-char';
ts/packages/cli/src/effect-errors/pretty-print/common/maybe-warn-about-plain-strings.ts
new
+14
@@ -0,0 +1,14 @@
1
+import color from 'picocolors';
2
+
3
+export const maybeWarnAboutPlainStrings = (isPlainString: boolean): string[] => {
4
+ if (!isPlainString) {
5
+ return [];
6
+ }
7
+
8
+ return [
9
+ '',
10
+ color.gray(
11
+ 'ℹ️ You used a plain string to represent a failure in the error channel (E). You should consider using tagged objects (with a _tag field), or yieldable errors such as Data.TaggedError and Schema.TaggedError for better handling experience.'
12
+ ),
13
+ ];
14
+};
ts/packages/cli/src/effect-errors/pretty-print/common/spans-stack-trailing-char.ts
new
+4
@@ -0,0 +1,4 @@
1
+import color from 'picocolors';
2
+
3
+export const spanStackTrailingChar = (isLastEntry: boolean) =>
4
+ isLastEntry ? color.gray('╰') : color.gray('├');
ts/packages/cli/src/effect-errors/pretty-print/format-captured-error.ts
new
+33
@@ -0,0 +1,33 @@
1
+import { formatErrorTitle, maybeWarnAboutPlainStrings } from 'effect-errors/pretty-print/common';
2
+import type { PrettyPrintOptions } from 'effect-errors/types';
3
+
4
+import type { ErrorData } from '../capture-errors';
5
+import {
6
+ maybeAdviseSpansUsage,
7
+ maybePrintNodeStacktrace,
8
+ maybePrintSpansTimeline,
9
+ printEffectStacktrace,
10
+} from './captured-errors';
11
+
12
+export const formatCapturedError =
13
+ (failuresCount: number, options: PrettyPrintOptions) =>
14
+ ({ errorType, message, stack, spans, sources, isPlainString }: ErrorData, index: number) => {
15
+ const title = formatErrorTitle(errorType, message, failuresCount, index);
16
+ const plainStringWarning = maybeWarnAboutPlainStrings(isPlainString);
17
+ const spansTimeline = maybePrintSpansTimeline(spans, isPlainString, options);
18
+ const spansUsageAdvice = maybeAdviseSpansUsage(spans);
19
+
20
+ const effectStacktrace = printEffectStacktrace(sources, spans, options);
21
+ const nodeStacktrace = maybePrintNodeStacktrace(stack, isPlainString, options);
22
+
23
+ return [
24
+ ...title,
25
+ ...plainStringWarning,
26
+ ...spansTimeline,
27
+ ...spansUsageAdvice,
28
+ '',
29
+ ...effectStacktrace,
30
+ ...nodeStacktrace,
31
+ '',
32
+ ].join('\r\n');
33
+ };
ts/packages/cli/src/effect-errors/pretty-print/index.ts
new
+3
@@ -0,0 +1,3 @@
1
+export * from './common/constants/interrupted-message';
2
+export * from './common/format-title';
3
+export * from './format-captured-error';
ts/packages/cli/src/effect-errors/sourcemaps/get-error-location-from-file-path.ts
new
+20
@@ -0,0 +1,20 @@
1
+import { sourceFileWithMapPointerRegex } from 'effect-errors/logic/stack';
2
+
3
+export interface ErrorLocation {
4
+ filePath: string;
5
+ line: number;
6
+ column: number;
7
+}
8
+
9
+export const getErrorLocationFrom = (sourceFile: string): ErrorLocation | undefined => {
10
+ const regex = sourceFileWithMapPointerRegex.exec(sourceFile);
11
+ if (regex === null || regex.length !== 7) {
12
+ return;
13
+ }
14
+
15
+ const filePath = regex[2];
16
+ const line = +regex[5];
17
+ const column = +regex[6];
18
+
19
+ return { filePath, line, column };
20
+};
ts/packages/cli/src/effect-errors/sourcemaps/get-error-related-sources.ts
new
+45
@@ -0,0 +1,45 @@
1
+import type { PlatformError } from '@effect/platform/Error';
2
+import type { FileSystem } from '@effect/platform/FileSystem';
3
+import { Effect } from 'effect';
4
+
5
+import type { JsonParsingError } from 'effect-errors/dependencies/fs';
6
+
7
+import { getErrorLocationFrom } from './get-error-location-from-file-path';
8
+import { getSourceCode } from './get-source-code';
9
+import {
10
+ type ErrorRelatedSources,
11
+ getSourcesFromMapFile,
12
+ type RawErrorLocation,
13
+} from './get-sources-from-map-file';
14
+
15
+export const getErrorRelatedSources = (
16
+ name: string,
17
+ sourceFile: string
18
+): Effect.Effect<
19
+ ErrorRelatedSources | RawErrorLocation | undefined,
20
+ PlatformError | JsonParsingError,
21
+ FileSystem
22
+> =>
23
+ Effect.gen(function* () {
24
+ const location = getErrorLocationFrom(sourceFile);
25
+ if (location === undefined) {
26
+ return;
27
+ }
28
+
29
+ const { filePath, line, column } = location;
30
+
31
+ const isTypescriptFile = filePath.endsWith('.ts') || filePath.endsWith('.tsx');
32
+ if (isTypescriptFile) {
33
+ const source = yield* getSourceCode(location);
34
+
35
+ return {
36
+ _tag: 'sources' as const,
37
+ name,
38
+ runPath: `${filePath}:${line}:${column}`,
39
+ sourcesPath: undefined,
40
+ source,
41
+ };
42
+ }
43
+
44
+ return yield* getSourcesFromMapFile(name, location);
45
+ });
ts/packages/cli/src/effect-errors/sourcemaps/get-source-code.ts
new
+39
@@ -0,0 +1,39 @@
1
+import type { PlatformError } from '@effect/platform/Error';
2
+import { FileSystem } from '@effect/platform/FileSystem';
3
+import { Effect } from 'effect';
4
+
5
+import type { ErrorLocation } from './get-error-location-from-file-path';
6
+
7
+export interface SourceCode {
8
+ line: number;
9
+ code: string;
10
+ column: number | undefined;
11
+}
12
+
13
+const numberOflinesToExtract = 7;
14
+
15
+export const getSourceCode = (
16
+ { filePath, line, column }: ErrorLocation,
17
+ isFromJs = false
18
+): Effect.Effect<SourceCode[], PlatformError, FileSystem> =>
19
+ Effect.gen(function* () {
20
+ const fs = yield* FileSystem;
21
+ const sourceCode = yield* fs.readFileString(filePath, 'utf8');
22
+
23
+ const start = line >= 4 ? line - 4 : 0;
24
+
25
+ return sourceCode
26
+ .split('\n')
27
+ .splice(start, numberOflinesToExtract)
28
+ .map((currentLine, index) => {
29
+ const currentLineNumber = index + start + 1;
30
+
31
+ const actualColumn = isFromJs ? column + 1 : column;
32
+
33
+ return {
34
+ line: currentLineNumber,
35
+ code: currentLine,
36
+ column: currentLineNumber === line ? actualColumn : undefined,
37
+ };
38
+ });
39
+ });
ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-map-file.ts
new
+90
@@ -0,0 +1,90 @@
1
+import path from 'node:path';
2
+
3
+import type { PlatformError } from '@effect/platform/Error';
4
+import { FileSystem } from '@effect/platform/FileSystem';
5
+import { Effect, pipe } from 'effect';
6
+import { type RawSourceMap, SourceMapConsumer } from 'source-map-js';
7
+
8
+import { type JsonParsingError, readJsonEffect } from 'effect-errors/dependencies/fs';
9
+
10
+import type { ErrorLocation } from './get-error-location-from-file-path';
11
+import { getSourceCode, type SourceCode } from './get-source-code';
12
+
13
+export interface ErrorRelatedSources {
14
+ _tag: 'sources';
15
+ name: string;
16
+ source: SourceCode[];
17
+ runPath: string;
18
+ sourcesPath: string | undefined;
19
+}
20
+
21
+export interface RawErrorLocation extends ErrorLocation {
22
+ _tag: 'location';
23
+ name: string;
24
+}
25
+
26
+export const getSourcesFromMapFile = (
27
+ name: string,
28
+ location: ErrorLocation
29
+): Effect.Effect<
30
+ ErrorRelatedSources | RawErrorLocation | undefined,
31
+ PlatformError | JsonParsingError,
32
+ FileSystem
33
+> =>
34
+ pipe(
35
+ Effect.gen(function* () {
36
+ const fs = yield* FileSystem;
37
+ const fileExists = yield* fs.exists(`${location.filePath}.map`);
38
+ if (!fileExists) {
39
+ return {
40
+ _tag: 'location' as const,
41
+ name,
42
+ ...location,
43
+ filePath: location.filePath.replace(process.cwd(), ''),
44
+ };
45
+ }
46
+
47
+ const data = yield* readJsonEffect<RawSourceMap>(`${location.filePath}.map`);
48
+ const hasNoData = data?.version === undefined || data?.sources === undefined;
49
+ if (hasNoData) {
50
+ return;
51
+ }
52
+
53
+ const consumer = new SourceMapConsumer(data);
54
+ const sources = consumer.originalPositionFor({
55
+ column: location.column,
56
+ line: location.line,
57
+ });
58
+ if (sources.source === null || sources.line === null || sources.column === null) {
59
+ return;
60
+ }
61
+
62
+ const absolutePath = path.resolve(
63
+ location.filePath.substring(0, location.filePath.lastIndexOf('/')),
64
+ sources.source
65
+ );
66
+ const isNodeModules = absolutePath.startsWith(`${process.cwd()}/node_modules`);
67
+ if (isNodeModules) {
68
+ return;
69
+ }
70
+ const source = yield* getSourceCode(
71
+ {
72
+ filePath: absolutePath,
73
+ line: sources.line,
74
+ column: sources.column,
75
+ },
76
+ true
77
+ );
78
+
79
+ return {
80
+ _tag: 'sources' as const,
81
+ name,
82
+ runPath: `${location.filePath}:${location.line}:${location.column}`,
83
+ sourcesPath: `${absolutePath}:${sources.line}:${sources.column + 1}`,
84
+ source,
85
+ };
86
+ }),
87
+ Effect.withSpan('get-sources-from-map-file', {
88
+ attributes: { location: JSON.stringify(location) },
89
+ })
90
+ );
ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-span.ts
new
+62
@@ -0,0 +1,62 @@
1
+import { Effect, Option, pipe } from 'effect';
2
+import type { AnySpan, Span } from 'effect/Tracer';
3
+
4
+import { splitSpansAttributesByTypes } from 'effect-errors/logic/spans';
5
+
6
+import type { ErrorRelatedSources, RawErrorLocation } from './get-sources-from-map-file';
7
+import { maybeMapSourcemaps } from './maybe-map-sourcemaps';
8
+
9
+export const getSourcesFromSpan = ({
10
+ span,
11
+ sources,
12
+ location,
13
+}: {
14
+ span: Span | undefined;
15
+ sources: ErrorRelatedSources[];
16
+ location: RawErrorLocation[];
17
+}) =>
18
+ pipe(
19
+ Effect.gen(function* () {
20
+ if (span === undefined) {
21
+ return {
22
+ spans: [],
23
+ sources,
24
+ location,
25
+ };
26
+ }
27
+
28
+ const spans = [];
29
+
30
+ let current: Span | AnySpan | undefined = span;
31
+ while (current !== undefined && current._tag === 'Span') {
32
+ const { name, attributes: allAttributes, status } = current;
33
+
34
+ const { attributes, stacktrace } = splitSpansAttributesByTypes(allAttributes);
35
+
36
+ const sourcesOrLocation = yield* maybeMapSourcemaps(name, stacktrace);
37
+ const duration =
38
+ status._tag === 'Ended'
39
+ ? +`${(status.endTime - status.startTime) / BigInt(1000000)}`
40
+ : undefined;
41
+
42
+ sources.push(...sourcesOrLocation.filter(el => el._tag === 'sources'));
43
+ location.push(...sourcesOrLocation.filter(el => el._tag === 'location'));
44
+ spans.push({
45
+ name,
46
+ attributes: Object.fromEntries(attributes),
47
+ durationInMilliseconds: duration,
48
+ startTime: status.startTime,
49
+ endTime: status._tag === 'Ended' ? status.endTime : undefined,
50
+ });
51
+
52
+ current = Option.getOrUndefined(current.parent);
53
+ }
54
+
55
+ return {
56
+ spans,
57
+ location,
58
+ sources,
59
+ };
60
+ }),
61
+ Effect.withSpan('get-sources-from-span')
62
+ );
ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-stack.ts
new
+26
@@ -0,0 +1,26 @@
1
+import { Effect, pipe } from 'effect';
2
+
3
+import { removeNodeModulesEntriesFromStack } from 'effect-errors/logic/spans';
4
+
5
+import { maybeMapSourcemaps } from './maybe-map-sourcemaps';
6
+
7
+export const getSourcesFromStack = (maybeStack: string | undefined) =>
8
+ pipe(
9
+ Effect.gen(function* () {
10
+ if (maybeStack === undefined) {
11
+ return {
12
+ sources: [],
13
+ location: [],
14
+ };
15
+ }
16
+
17
+ const relevantStackEntries = removeNodeModulesEntriesFromStack(maybeStack);
18
+ const sourcesOrLocation = yield* maybeMapSourcemaps('', relevantStackEntries);
19
+
20
+ return {
21
+ sources: sourcesOrLocation.filter(el => el._tag === 'sources'),
22
+ location: sourcesOrLocation.filter(el => el._tag === 'location'),
23
+ };
24
+ }),
25
+ Effect.withSpan('get-sources-from-stack')
26
+ );
ts/packages/cli/src/effect-errors/sourcemaps/index.ts
new
+4
@@ -0,0 +1,4 @@
1
+export * from './get-error-location-from-file-path';
2
+export * from './get-source-code';
3
+export * from './get-sources-from-map-file';
4
+export * from './transform-raw-error';
ts/packages/cli/src/effect-errors/sourcemaps/maybe-map-sourcemaps.ts
new
+49
@@ -0,0 +1,49 @@
1
+import type { PlatformError } from '@effect/platform/Error';
2
+import type { FileSystem } from '@effect/platform/FileSystem';
3
+import { Effect, pipe } from 'effect';
4
+
5
+import type { JsonParsingError } from 'effect-errors/dependencies/fs';
6
+import { stackAtRegex } from 'effect-errors/logic/stack';
7
+
8
+import { getErrorRelatedSources } from './get-error-related-sources';
9
+import type { ErrorRelatedSources, RawErrorLocation } from './get-sources-from-map-file';
10
+
11
+export type StackEntry = {
12
+ _tag: 'stack-entry';
13
+ runPath: string;
14
+};
15
+
16
+export type MaybeMappedSources = ErrorRelatedSources | RawErrorLocation | StackEntry;
17
+
18
+export const maybeMapSourcemaps = (
19
+ name: string,
20
+ stacktrace: string[]
21
+): Effect.Effect<MaybeMappedSources[], PlatformError | JsonParsingError, FileSystem> =>
22
+ pipe(
23
+ Effect.forEach(stacktrace, stackLine =>
24
+ Effect.gen(function* () {
25
+ const chunks = stackLine.trimStart().split(' ');
26
+ const mapFileReportedPath =
27
+ chunks.length === 2 ? chunks[1] : chunks[chunks.length - 1].slice(1, -1);
28
+
29
+ const details = yield* getErrorRelatedSources(name, mapFileReportedPath);
30
+ if (details === undefined) {
31
+ return {
32
+ _tag: 'stack-entry' as const,
33
+ runPath: stackLine.replaceAll(stackAtRegex, 'at '),
34
+ };
35
+ }
36
+ if (details._tag === 'location') {
37
+ return details;
38
+ }
39
+
40
+ const regex = new RegExp(`${process.cwd()}/node_modules/`);
41
+ if (details.sourcesPath?.match(regex)) {
42
+ return undefined;
43
+ }
44
+
45
+ return details;
46
+ })
47
+ ),
48
+ Effect.map(array => array.filter(maybeSources => maybeSources !== undefined))
49
+ );
ts/packages/cli/src/effect-errors/sourcemaps/transform-raw-error.ts
new
+38
@@ -0,0 +1,38 @@
1
+import { Effect, pipe } from 'effect';
2
+
3
+import { stripCwdPath } from 'effect-errors/logic/path';
4
+import { stackAtRegex } from 'effect-errors/logic/stack';
5
+
6
+import type { CaptureErrorsOptions } from '../capture-errors';
7
+import type { PrettyError } from '../types/pretty-error.type';
8
+import { getSourcesFromSpan } from './get-sources-from-span';
9
+import { getSourcesFromStack } from './get-sources-from-stack';
10
+
11
+export const transformRawError =
12
+ ({ stripCwd }: CaptureErrorsOptions) =>
13
+ ({ message, stack: maybeStack, span, errorType, isPlainString }: PrettyError) =>
14
+ pipe(
15
+ Effect.gen(function* () {
16
+ const data = yield* getSourcesFromStack(maybeStack);
17
+ const { spans, sources, location } = yield* getSourcesFromSpan({
18
+ span,
19
+ ...data,
20
+ });
21
+
22
+ let stack: string | undefined;
23
+ if (maybeStack !== undefined) {
24
+ stack = stripCwd === true ? stripCwdPath(maybeStack) : maybeStack;
25
+ }
26
+
27
+ return {
28
+ errorType,
29
+ message,
30
+ stack: stack?.replaceAll(stackAtRegex, 'at ').split('\r\n'),
31
+ sources: sources.length > 0 ? sources.map(({ _tag, ...data }) => data) : undefined,
32
+ location: location.length > 0 ? location.map(({ _tag, ...data }) => data) : undefined,
33
+ spans,
34
+ isPlainString,
35
+ };
36
+ }),
37
+ Effect.withSpan('transform-raw-error')
38
+ );
ts/packages/cli/src/effect-errors/types/error-span.type.ts
new
+7
@@ -0,0 +1,7 @@
1
+export interface ErrorSpan {
2
+ name: string;
3
+ attributes: Record<string, unknown>;
4
+ durationInMilliseconds: number | undefined;
5
+ startTime: bigint;
6
+ endTime: bigint | undefined;
7
+}
ts/packages/cli/src/effect-errors/types/index.ts
new
+3
@@ -0,0 +1,3 @@
1
+export * from './error-span.type';
2
+export * from './pretty-error.type';
3
+export * from './pretty-print-options.type';
ts/packages/cli/src/effect-errors/types/pretty-error.type.ts
new
+11
@@ -0,0 +1,11 @@
1
+import type { Span } from 'effect/Tracer';
2
+
3
+export class PrettyError {
4
+ constructor(
5
+ readonly message: unknown,
6
+ readonly stack: string | undefined,
7
+ readonly span: Span | undefined,
8
+ readonly isPlainString: boolean,
9
+ readonly errorType?: unknown
10
+ ) {}
11
+}
ts/packages/cli/src/effect-errors/types/pretty-print-options.type.ts
new
+11
@@ -0,0 +1,11 @@
1
+export interface PrettyPrintOptions {
2
+ enabled?: boolean;
3
+ stripCwd?: boolean | undefined;
4
+ hideStackTrace?: boolean;
5
+}
6
+
7
+export const prettyPrintOptionsDefault: PrettyPrintOptions = {
8
+ enabled: true,
9
+ stripCwd: true,
10
+ hideStackTrace: true,
11
+};
ts/packages/cli/src/models/utils/extract-actual.ts
+6
-4
@@ -1,13 +1,15 @@
1
import type { ParseIssue } from 'effect/ParseResult';
2
+import { inspect } from 'node:util';
3
4
export function extractActual({ actual }: ParseIssue, cap = 50) {
4
- // Cap the length of the actual value to 30 characters
5
- let str = undefined;
5
+ // Cap the length of the actual value to 50 characters
6
+ let str: string;
7
8
if (typeof actual === 'object') {
8
- str = JSON.stringify(actual);
9
+ str = inspect(actual, { depth: 2 });
10
+ } else {
11
+ str = String(actual);
12
}
13
11
- str = String(actual);
14
return str.slice(0, cap) + (str.length > cap ? '...' : '');
15
}
ts/packages/cli/src/services/utils/pretty-error.ts
+4
-4
@@ -15,18 +15,18 @@ function* renderPrettyErrorGen(
15
yield '';
16
} else if (errorLines.length <= 2) {
17
for (const [key, value] of errorLines) {
18
- yield `${colors.gray(S_BAR)} ${colors.blueBright(key)}: ${value}`;
18
+ yield `${colors.inverse(S_BAR)} ${colors.blueBright(key)}: ${value}`;
19
}
20
} else if (errorLines.length > 2) {
21
for (let i = 0; i < errorLines.length; i++) {
22
const [key, value] = errorLines[i];
23
24
if (i === 0) {
25
- yield `${colors.gray(`${S_CORNER_TOP_LEFT}${S_BAR_H}`)} ${colors.blueBright(key)}: ${value}`;
25
+ yield `${colors.inverse(`${S_CORNER_TOP_LEFT}${S_BAR_H}`)} ${colors.blueBright(key)}: ${value}`;
26
} else if (i === errorLines.length - 1) {
27
- yield `${colors.gray(`${S_CORNER_BOTTOM_LEFT}${S_BAR_H}`)} ${colors.blueBright(key)}: ${value}`;
27
+ yield `${colors.inverse(`${S_CORNER_BOTTOM_LEFT}${S_BAR_H}`)} ${colors.blueBright(key)}: ${value}`;
28
} else {
29
- yield `${colors.gray(S_BAR)} ${colors.blueBright(key)}: ${value}`;
29
+ yield `${colors.inverse(S_BAR)} ${colors.blueBright(key)}: ${value}`;
30
}
31
}
32
}
ts/packages/cli/tsconfig.json
+2
-1
@@ -6,7 +6,8 @@
6
"paths": {
7
"src/*": ["./src/*"],
8
"test/*": ["./test/*"],
9
- "~/*": ["./*"]
9
+ "~/*": ["./*"],
10
+ "effect-errors/*": ["./src/effect-errors/*"]
11
},
12
"types": ["@types/bun", "vitest/importMeta"]
13
},
ts/packages/cli/tsconfig.src.json
+3
-1
@@ -9,8 +9,10 @@
9
"compilerOptions": {
10
"outDir": "./dist",
11
"rootDir": ".",
12
+ "baseUrl": ".",
13
"paths": {
13
- "src/*": ["./src/*"]
14
+ "src/*": ["./src/*"],
15
+ "effect-errors/*": ["./src/effect-errors/*"]
16
},
17
"types": ["@types/bun"]
18
},
ts/packages/cli/tsconfig.test.json
+2
@@ -8,8 +8,10 @@
8
],
9
"compilerOptions": {
10
"rootDir": ".",
11
+ "baseUrl": ".",
12
"paths": {
13
"src/*": ["./src/*"],
14
+ "effect-errors/*": ["./src/effect-errors/*"],
15
"test/*": ["./test/*"]
16
},
17
"types": ["@types/bun", "vitest/importMeta"]
ts/packages/cli/vitest.config.ts
+1
@@ -9,6 +9,7 @@ export default defineConfig({
9
'~': path.resolve(__dirname, './'),
10
src: path.resolve(__dirname, './src'),
11
test: path.resolve(__dirname, './test'),
12
+ 'effect-errors/*': path.resolve(__dirname, './src/effect-errors'),
13
},
14
},
15
test: {