@devries-cameron20 / composio Mirror · read-only
Fork 0

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 21, 04:45 UTC

next
ts 160 lines 5.43 KB
Raw
1 import { FileSystem } from 'effect/FileSystem';
2 import { Path } from 'effect/Path';
3 import type { PlatformError } from 'effect/PlatformError';
4 import { Data, Effect, Option, Schema, pipe } from 'effect';
5 import { SourceMapConsumer } from 'source-map-js';
6
7 import { readJsonEffect } from 'effect-errors/dependencies/fs';
8
9 import type { ErrorLocation } from './get-error-location-from-file-path';
10 import { getSourceCode } from './get-source-code';
11 import { type ErrorRelatedSources, MappedSources, type RawErrorLocation } from './mapped-sources';
12
13 /**
14 * Structural subset of the Source Map v3 spec that `originalPositionFor` needs.
15 *
16 * `file` and `sourceRoot` are nullable, not merely absent: bundlers emitting a
17 * map with no output file name write `"file": null` rather than omitting the
18 * key, and `source-map-js` accepts both. Rejecting them here would silently
19 * downgrade a perfectly usable map to an unenriched location.
20 */
21 const SourceMapSchema = Schema.Struct({
22 version: Schema.Literals([3, '3']),
23 sources: Schema.Array(Schema.String),
24 names: Schema.optional(Schema.Array(Schema.String)),
25 mappings: Schema.String,
26 file: Schema.optional(Schema.NullOr(Schema.String)),
27 sourceRoot: Schema.optional(Schema.NullOr(Schema.String)),
28 });
29 const decodeSourceMap = Schema.decodeUnknownOption(SourceMapSchema);
30
31 class SourceMapResolutionError extends Data.TaggedError('SourceMapResolutionError')<{
32 readonly filePath: string;
33 readonly cause: unknown;
34 }> {
35 override get message(): string {
36 return `Could not resolve source-map location for ${this.filePath}`;
37 }
38 }
39
40 const rawErrorLocation = (
41 name: string,
42 location: ErrorLocation,
43 workingDirectory: string
44 ): RawErrorLocation =>
45 MappedSources.location({
46 name,
47 ...location,
48 filePath: location.filePath.replace(workingDirectory, ''),
49 });
50
51 const resolveOriginalPosition = (sourceMap: typeof SourceMapSchema.Type, location: ErrorLocation) =>
52 Effect.try({
53 try: () =>
54 new SourceMapConsumer({
55 version: String(sourceMap.version),
56 sources: [...sourceMap.sources],
57 names: [...(sourceMap.names ?? [])],
58 mappings: sourceMap.mappings,
59 file: sourceMap.file ?? undefined,
60 sourceRoot: sourceMap.sourceRoot ?? undefined,
61 }).originalPositionFor({
62 column: location.column,
63 line: location.line,
64 }),
65 catch: cause => new SourceMapResolutionError({ filePath: location.filePath, cause }),
66 }).pipe(
67 Effect.map(Option.some),
68 Effect.catchTag('SourceMapResolutionError', () => Effect.succeed(Option.none()))
69 );
70
71 /**
72 * Enriches `location` with the original source it maps to.
73 *
74 * Fails with a `PlatformError` when the map file, or the original source it
75 * points at, cannot be read; `getSourcesFromMapFile` turns that into the raw
76 * location.
77 */
78 const enrichFromMapFile = (
79 name: string,
80 location: ErrorLocation,
81 workingDirectory: string
82 ): Effect.Effect<
83 ErrorRelatedSources | RawErrorLocation | undefined,
84 PlatformError,
85 FileSystem | Path
86 > =>
87 Effect.gen(function* () {
88 const fs = yield* FileSystem;
89 const path = yield* Path;
90 const fileExists = yield* fs.exists(`${location.filePath}.map`);
91 if (!fileExists) {
92 return rawErrorLocation(name, location, workingDirectory);
93 }
94
95 const sourceMap = yield* readJsonEffect(`${location.filePath}.map`).pipe(
96 Effect.map(Option.fromNullOr),
97 Effect.map(Option.flatMap(decodeSourceMap)),
98 Effect.catchTag('JsonParsingError', () => Effect.succeed(Option.none()))
99 );
100 if (Option.isNone(sourceMap)) {
101 return rawErrorLocation(name, location, workingDirectory);
102 }
103
104 const maybeSources = yield* resolveOriginalPosition(sourceMap.value, location);
105 if (Option.isNone(maybeSources)) {
106 return rawErrorLocation(name, location, workingDirectory);
107 }
108
109 const sources = maybeSources.value;
110 if (sources.source === null || sources.line === null || sources.column === null) {
111 return;
112 }
113
114 const absolutePath = path.resolve(path.dirname(location.filePath), sources.source);
115 const isNodeModules = absolutePath.startsWith(
116 `${path.join(workingDirectory, 'node_modules')}${path.sep}`
117 );
118 if (isNodeModules) {
119 return;
120 }
121 const source = yield* getSourceCode(
122 {
123 filePath: absolutePath,
124 line: sources.line,
125 column: sources.column,
126 },
127 true
128 );
129
130 return MappedSources.sources({
131 name,
132 runPath: `${location.filePath}:${location.line}:${location.column}`,
133 sourcesPath: `${absolutePath}:${sources.line}:${sources.column + 1}`,
134 source,
135 });
136 });
137
138 /**
139 * Source maps are best-effort metadata. A missing, malformed, invalid, or
140 * unreadable map — or a map pointing at an original source that was never
141 * shipped — degrades to the raw stack location, and never destroys the
142 * diagnostic the user actually asked for. Hence the `never` error channel.
143 */
144 export const getSourcesFromMapFile = (
145 name: string,
146 location: ErrorLocation
147 ): Effect.Effect<ErrorRelatedSources | RawErrorLocation | undefined, never, FileSystem | Path> =>
148 pipe(
149 Effect.gen(function* () {
150 const path = yield* Path;
151 const workingDirectory = path.resolve('.');
152
153 return yield* enrichFromMapFile(name, location, workingDirectory).pipe(
154 Effect.orElseSucceed(() => rawErrorLocation(name, location, workingDirectory))
155 );
156 }),
157 Effect.withSpan('get-sources-from-map-file', {
158 attributes: { location: JSON.stringify(location) },
159 })
160 );