Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

fix(cli): make source-map enrichment best-effort end to end (#3963)

Alberto Schiabel24151cbe1497
diff --git a/ts/packages/cli/CHANGELOG.md b/ts/packages/cli/CHANGELOG.md
index 81e83d6b3..a8d90b62d 100644
--- a/ts/packages/cli/CHANGELOG.md
+++ b/ts/packages/cli/CHANGELOG.md
@@ -15,6 +15,8 @@
### Patch Changes
+- Preserve the original CLI diagnostic when an adjacent source map is malformed or unusable instead of letting optional source-map enrichment abort error capture. Source-map enrichment is now best-effort end to end: a malformed, invalid, or unreadable `.map`, and a valid map pointing at an original source that was never shipped, all degrade to the raw stack location. `captureErrors` can no longer fail.
+- Fix source-map resolution on Windows: original source paths are now resolved with the platform path separator instead of a hardcoded `/`, and the `node_modules` filter no longer mistakes directories such as `node_modules_local` for real dependency paths.
- Make `composio version --check` report `checkStatus: "unknown"` when GitHub cannot confirm the latest stable release, preserve the last successful cache on failed refreshes, and avoid racing the command with the startup update check.
- Make multi-account selection a stable CLI feature: `execute`, `listen`, and `link --alias` no longer honor the old experimental toggle; `proxy` now accepts `--account <alias|word_id|connected-account-id>`; and duplicate-alias link errors explain how to select the existing account.
- 8467efd: Fix `composio whoami` reporting the API key's home organization after `composio orgs switch`. Session info requests now forward the selected global organization.
diff --git a/ts/packages/cli/src/effect-errors/capture-errors.ts b/ts/packages/cli/src/effect-errors/capture-errors.ts
index 4a668c45a..91e0a58e4 100644
--- a/ts/packages/cli/src/effect-errors/capture-errors.ts
+++ b/ts/packages/cli/src/effect-errors/capture-errors.ts
@@ -1,10 +1,8 @@
-import type { PlatformError } from '@effect/platform/Error';
import type { FileSystem } from '@effect/platform/FileSystem';
import type { Path } from '@effect/platform/Path';
import { Effect } from 'effect';
import { type Cause, isInterruptedOnly } from 'effect/Cause';
-import type { JsonParsingError } from 'effect-errors/dependencies/fs';
import { captureErrorsFrom } from 'effect-errors/logic/errors';
import {
type ErrorLocation,
@@ -37,7 +35,7 @@ export const captureErrors = <E>(
options: CaptureErrorsOptions = {
stripCwd: true,
}
-): Effect.Effect<CapturedErrors, PlatformError | JsonParsingError, FileSystem | Path> =>
+): Effect.Effect<CapturedErrors, never, FileSystem | Path> =>
Effect.gen(function* () {
if (isInterruptedOnly(cause)) {
return {
diff --git a/ts/packages/cli/src/effect-errors/dependencies/fs/read-json/read-json.ts b/ts/packages/cli/src/effect-errors/dependencies/fs/read-json/read-json.ts
index 4b87e3bcf..63710886a 100644
--- a/ts/packages/cli/src/effect-errors/dependencies/fs/read-json/read-json.ts
+++ b/ts/packages/cli/src/effect-errors/dependencies/fs/read-json/read-json.ts
@@ -3,7 +3,7 @@ import { Effect, pipe } from 'effect';
import { parseJsonRecord } from 'src/utils/parse-json';
-export const readJsonEffect = <TJson>(filePath: string) =>
+export const readJsonEffect = (filePath: string) =>
pipe(
Effect.gen(function* () {
const { readFileString } = yield* FileSystem;
@@ -15,7 +15,7 @@ export const readJsonEffect = <TJson>(filePath: string) =>
const json = yield* parseJsonRecord(data);
- return json as TJson;
+ return json;
}),
Effect.withSpan('read-json', { attributes: { filePath } })
);
diff --git a/ts/packages/cli/src/effect-errors/sourcemaps/get-error-related-sources.ts b/ts/packages/cli/src/effect-errors/sourcemaps/get-error-related-sources.ts
index 8cf392a86..20a8b09e4 100644
--- a/ts/packages/cli/src/effect-errors/sourcemaps/get-error-related-sources.ts
+++ b/ts/packages/cli/src/effect-errors/sourcemaps/get-error-related-sources.ts
@@ -1,26 +1,16 @@
-import type { PlatformError } from '@effect/platform/Error';
-import type { FileSystem } from '@effect/platform/FileSystem';
-import type { Path } from '@effect/platform/Path';
+import { FileSystem } from '@effect/platform/FileSystem';
+import { Path } from '@effect/platform/Path';
import { Effect } from 'effect';
-import type { JsonParsingError } from 'effect-errors/dependencies/fs';
-
import { getErrorLocationFrom } from './get-error-location-from-file-path';
import { getSourceCode } from './get-source-code';
-import {
- type ErrorRelatedSources,
- getSourcesFromMapFile,
- type RawErrorLocation,
-} from './get-sources-from-map-file';
+import { getSourcesFromMapFile } from './get-sources-from-map-file';
+import { type ErrorRelatedSources, MappedSources, type RawErrorLocation } from './mapped-sources';
export const getErrorRelatedSources = (
name: string,
sourceFile: string
-): Effect.Effect<
- ErrorRelatedSources | RawErrorLocation | undefined,
- PlatformError | JsonParsingError,
- FileSystem | Path
-> =>
+): Effect.Effect<ErrorRelatedSources | RawErrorLocation | undefined, never, FileSystem | Path> =>
Effect.gen(function* () {
const location = getErrorLocationFrom(sourceFile);
if (location === undefined) {
@@ -31,15 +21,28 @@ export const getErrorRelatedSources = (
const isTypescriptFile = filePath.endsWith('.ts') || filePath.endsWith('.tsx');
if (isTypescriptFile) {
- const source = yield* getSourceCode(location);
+ const path = yield* Path;
+ const workingDirectory = path.resolve('.');
- return {
- _tag: 'sources' as const,
- name,
- runPath: `${filePath}:${line}:${column}`,
- sourcesPath: undefined,
- source,
- };
+ // Reading the source is best-effort enrichment, exactly as it is for the
+ // source-map branch below: an unreadable file falls back to the location.
+ return yield* getSourceCode(location).pipe(
+ Effect.map(source =>
+ MappedSources.sources({
+ name,
+ runPath: `${filePath}:${line}:${column}`,
+ sourcesPath: undefined,
+ source,
+ })
+ ),
+ Effect.orElseSucceed(() =>
+ MappedSources.location({
+ name,
+ ...location,
+ filePath: filePath.replace(workingDirectory, ''),
+ })
+ )
+ );
}
return yield* getSourcesFromMapFile(name, location);
diff --git a/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-map-file.ts b/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-map-file.ts
index 4172cf793..3e1e02a1e 100644
--- a/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-map-file.ts
+++ b/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-map-file.ts
@@ -1,88 +1,158 @@
import type { PlatformError } from '@effect/platform/Error';
import { FileSystem } from '@effect/platform/FileSystem';
import { Path } from '@effect/platform/Path';
-import { Effect, pipe } from 'effect';
-import { type RawSourceMap, SourceMapConsumer } from 'source-map-js';
+import { Data, Effect, Option, Schema, pipe } from 'effect';
+import { SourceMapConsumer } from 'source-map-js';
-import { type JsonParsingError, readJsonEffect } from 'effect-errors/dependencies/fs';
+import { readJsonEffect } from 'effect-errors/dependencies/fs';
import type { ErrorLocation } from './get-error-location-from-file-path';
-import { getSourceCode, type SourceCode } from './get-source-code';
+import { getSourceCode } from './get-source-code';
+import { type ErrorRelatedSources, MappedSources, type RawErrorLocation } from './mapped-sources';
-export interface ErrorRelatedSources {
- _tag: 'sources';
- name: string;
- source: SourceCode[];
- runPath: string;
- sourcesPath: string | undefined;
-}
+/**
+ * Structural subset of the Source Map v3 spec that `originalPositionFor` needs.
+ *
+ * `file` and `sourceRoot` are nullable, not merely absent: bundlers emitting a
+ * map with no output file name write `"file": null` rather than omitting the
+ * key, and `source-map-js` accepts both. Rejecting them here would silently
+ * downgrade a perfectly usable map to an unenriched location.
+ */
+const SourceMapSchema = Schema.Struct({
+ version: Schema.Literal(3, '3'),
+ sources: Schema.Array(Schema.String),
+ names: Schema.optionalWith(Schema.Array(Schema.String), { default: () => [] }),
+ mappings: Schema.String,
+ file: Schema.optional(Schema.NullOr(Schema.String)),
+ sourceRoot: Schema.optional(Schema.NullOr(Schema.String)),
+});
+const decodeSourceMap = Schema.decodeUnknownOption(SourceMapSchema);
-export interface RawErrorLocation extends ErrorLocation {
- _tag: 'location';
- name: string;
+class SourceMapResolutionError extends Data.TaggedError('SourceMapResolutionError')<{
+ readonly filePath: string;
+ readonly cause: unknown;
+}> {
+ override get message(): string {
+ return `Could not resolve source-map location for ${this.filePath}`;
+ }
}
-export const getSourcesFromMapFile = (
+const rawErrorLocation = (
name: string,
- location: ErrorLocation
+ location: ErrorLocation,
+ workingDirectory: string
+): RawErrorLocation =>
+ MappedSources.location({
+ name,
+ ...location,
+ filePath: location.filePath.replace(workingDirectory, ''),
+ });
+
+const resolveOriginalPosition = (sourceMap: typeof SourceMapSchema.Type, location: ErrorLocation) =>
+ Effect.try({
+ try: () =>
+ new SourceMapConsumer({
+ version: String(sourceMap.version),
+ sources: [...sourceMap.sources],
+ names: [...sourceMap.names],
+ mappings: sourceMap.mappings,
+ file: sourceMap.file ?? undefined,
+ sourceRoot: sourceMap.sourceRoot ?? undefined,
+ }).originalPositionFor({
+ column: location.column,
+ line: location.line,
+ }),
+ catch: cause => new SourceMapResolutionError({ filePath: location.filePath, cause }),
+ }).pipe(
+ Effect.map(Option.some),
+ Effect.catchTag('SourceMapResolutionError', () => Effect.succeed(Option.none()))
+ );
+
+/**
+ * Enriches `location` with the original source it maps to.
+ *
+ * Fails with a `PlatformError` when the map file, or the original source it
+ * points at, cannot be read; `getSourcesFromMapFile` turns that into the raw
+ * location.
+ */
+const enrichFromMapFile = (
+ name: string,
+ location: ErrorLocation,
+ workingDirectory: string
): Effect.Effect<
ErrorRelatedSources | RawErrorLocation | undefined,
- PlatformError | JsonParsingError,
+ PlatformError,
FileSystem | Path
> =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem;
+ const path = yield* Path;
+ const fileExists = yield* fs.exists(`${location.filePath}.map`);
+ if (!fileExists) {
+ return rawErrorLocation(name, location, workingDirectory);
+ }
+
+ const sourceMap = yield* readJsonEffect(`${location.filePath}.map`).pipe(
+ Effect.map(Option.fromNullable),
+ Effect.map(Option.flatMap(decodeSourceMap)),
+ Effect.catchTag('JsonParsingError', () => Effect.succeed(Option.none()))
+ );
+ if (Option.isNone(sourceMap)) {
+ return rawErrorLocation(name, location, workingDirectory);
+ }
+
+ const maybeSources = yield* resolveOriginalPosition(sourceMap.value, location);
+ if (Option.isNone(maybeSources)) {
+ return rawErrorLocation(name, location, workingDirectory);
+ }
+
+ const sources = maybeSources.value;
+ if (sources.source === null || sources.line === null || sources.column === null) {
+ return;
+ }
+
+ const absolutePath = path.resolve(path.dirname(location.filePath), sources.source);
+ const isNodeModules = absolutePath.startsWith(
+ `${path.join(workingDirectory, 'node_modules')}${path.sep}`
+ );
+ if (isNodeModules) {
+ return;
+ }
+ const source = yield* getSourceCode(
+ {
+ filePath: absolutePath,
+ line: sources.line,
+ column: sources.column,
+ },
+ true
+ );
+
+ return MappedSources.sources({
+ name,
+ runPath: `${location.filePath}:${location.line}:${location.column}`,
+ sourcesPath: `${absolutePath}:${sources.line}:${sources.column + 1}`,
+ source,
+ });
+ });
+
+/**
+ * Source maps are best-effort metadata. A missing, malformed, invalid, or
+ * unreadable map — or a map pointing at an original source that was never
+ * shipped — degrades to the raw stack location, and never destroys the
+ * diagnostic the user actually asked for. Hence the `never` error channel.
+ */
+export const getSourcesFromMapFile = (
+ name: string,
+ location: ErrorLocation
+): Effect.Effect<ErrorRelatedSources | RawErrorLocation | undefined, never, FileSystem | Path> =>
pipe(
Effect.gen(function* () {
- const fs = yield* FileSystem;
const path = yield* Path;
- const fileExists = yield* fs.exists(`${location.filePath}.map`);
- if (!fileExists) {
- return {
- _tag: 'location' as const,
- name,
- ...location,
- filePath: location.filePath.replace(process.cwd(), ''),
- };
- }
+ const workingDirectory = path.resolve('.');
- const data = yield* readJsonEffect<RawSourceMap>(`${location.filePath}.map`);
- const hasNoData = data?.version === undefined || data?.sources === undefined;
- if (hasNoData) {
- return;
- }
-
- const consumer = new SourceMapConsumer(data);
- const sources = consumer.originalPositionFor({
- column: location.column,
- line: location.line,
- });
- if (sources.source === null || sources.line === null || sources.column === null) {
- return;
- }
-
- const absolutePath = path.resolve(
- location.filePath.substring(0, location.filePath.lastIndexOf('/')),
- sources.source
- );
- const isNodeModules = absolutePath.startsWith(`${process.cwd()}/node_modules`);
- if (isNodeModules) {
- return;
- }
- const source = yield* getSourceCode(
- {
- filePath: absolutePath,
- line: sources.line,
- column: sources.column,
- },
- true
+ return yield* enrichFromMapFile(name, location, workingDirectory).pipe(
+ Effect.orElseSucceed(() => rawErrorLocation(name, location, workingDirectory))
);
-
- return {
- _tag: 'sources' as const,
- name,
- runPath: `${location.filePath}:${location.line}:${location.column}`,
- sourcesPath: `${absolutePath}:${sources.line}:${sources.column + 1}`,
- source,
- };
}),
Effect.withSpan('get-sources-from-map-file', {
attributes: { location: JSON.stringify(location) },
diff --git a/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-span.ts b/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-span.ts
index 28b7476ca..68ba6538a 100644
--- a/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-span.ts
+++ b/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-span.ts
@@ -3,12 +3,13 @@ import type { AnySpan, Span } from 'effect/Tracer';
import { splitSpansAttributesByTypes } from 'effect-errors/logic/spans';
-import type { ErrorRelatedSources, RawErrorLocation } from './get-sources-from-map-file';
import {
+ type ErrorRelatedSources,
isErrorRelatedSources,
isRawErrorLocation,
- maybeMapSourcemaps,
-} from './maybe-map-sourcemaps';
+ type RawErrorLocation,
+} from './mapped-sources';
+import { maybeMapSourcemaps } from './maybe-map-sourcemaps';
export const getSourcesFromSpan = ({
span,
diff --git a/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-stack.ts b/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-stack.ts
index bf28a73c0..052323496 100644
--- a/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-stack.ts
+++ b/ts/packages/cli/src/effect-errors/sourcemaps/get-sources-from-stack.ts
@@ -2,11 +2,8 @@ import { Effect, pipe } from 'effect';
import { removeNodeModulesEntriesFromStack } from 'effect-errors/logic/spans';
-import {
- isErrorRelatedSources,
- isRawErrorLocation,
- maybeMapSourcemaps,
-} from './maybe-map-sourcemaps';
+import { isErrorRelatedSources, isRawErrorLocation } from './mapped-sources';
+import { maybeMapSourcemaps } from './maybe-map-sourcemaps';
export const getSourcesFromStack = (maybeStack: string | undefined) =>
pipe(
diff --git a/ts/packages/cli/src/effect-errors/sourcemaps/index.ts b/ts/packages/cli/src/effect-errors/sourcemaps/index.ts
index c6c6b9333..9804505fb 100644
--- a/ts/packages/cli/src/effect-errors/sourcemaps/index.ts
+++ b/ts/packages/cli/src/effect-errors/sourcemaps/index.ts
@@ -1,4 +1,5 @@
export * from './get-error-location-from-file-path';
export * from './get-source-code';
export * from './get-sources-from-map-file';
+export * from './mapped-sources';
export * from './transform-raw-error';
diff --git a/ts/packages/cli/src/effect-errors/sourcemaps/mapped-sources.ts b/ts/packages/cli/src/effect-errors/sourcemaps/mapped-sources.ts
new file mode 100644
index 000000000..c2017f621
--- /dev/null
+++ b/ts/packages/cli/src/effect-errors/sourcemaps/mapped-sources.ts
@@ -0,0 +1,28 @@
+import { Data } from 'effect';
+
+import type { ErrorLocation } from './get-error-location-from-file-path';
+import type { SourceCode } from './get-source-code';
+
+export type MaybeMappedSources = Data.TaggedEnum<{
+ sources: {
+ readonly name: string;
+ readonly source: SourceCode[];
+ readonly runPath: string;
+ readonly sourcesPath: string | undefined;
+ };
+ location: ErrorLocation & {
+ readonly name: string;
+ };
+ 'stack-entry': {
+ readonly runPath: string;
+ };
+}>;
+
+export const MappedSources = Data.taggedEnum<MaybeMappedSources>();
+
+export type ErrorRelatedSources = Data.TaggedEnum.Value<MaybeMappedSources, 'sources'>;
+export type RawErrorLocation = Data.TaggedEnum.Value<MaybeMappedSources, 'location'>;
+export type StackEntry = Data.TaggedEnum.Value<MaybeMappedSources, 'stack-entry'>;
+
+export const isErrorRelatedSources = MappedSources.$is('sources');
+export const isRawErrorLocation = MappedSources.$is('location');
diff --git a/ts/packages/cli/src/effect-errors/sourcemaps/maybe-map-sourcemaps.ts b/ts/packages/cli/src/effect-errors/sourcemaps/maybe-map-sourcemaps.ts
index 966ba7ac9..7816a3a09 100644
--- a/ts/packages/cli/src/effect-errors/sourcemaps/maybe-map-sourcemaps.ts
+++ b/ts/packages/cli/src/effect-errors/sourcemaps/maybe-map-sourcemaps.ts
@@ -1,56 +1,32 @@
-import type { PlatformError } from '@effect/platform/Error';
import type { FileSystem } from '@effect/platform/FileSystem';
import type { Path } from '@effect/platform/Path';
-import { Effect, Predicate, pipe } from 'effect';
+import { Effect } from 'effect';
-import type { JsonParsingError } from 'effect-errors/dependencies/fs';
import { stackAtRegex } from 'effect-errors/logic/stack';
import { getErrorRelatedSources } from './get-error-related-sources';
-import type { ErrorRelatedSources, RawErrorLocation } from './get-sources-from-map-file';
-
-export type StackEntry = {
- _tag: 'stack-entry';
- runPath: string;
-};
-
-export type MaybeMappedSources = ErrorRelatedSources | RawErrorLocation | StackEntry;
-
-export const isErrorRelatedSources = (value: MaybeMappedSources): value is ErrorRelatedSources =>
- Predicate.isTagged(value, 'sources');
-
-export const isRawErrorLocation = (value: MaybeMappedSources): value is RawErrorLocation =>
- Predicate.isTagged(value, 'location');
+import { MappedSources, type MaybeMappedSources } from './mapped-sources';
export const maybeMapSourcemaps = (
name: string,
stacktrace: string[]
-): Effect.Effect<MaybeMappedSources[], PlatformError | JsonParsingError, FileSystem | Path> =>
- pipe(
- Effect.forEach(stacktrace, stackLine =>
- Effect.gen(function* () {
- const chunks = stackLine.trimStart().split(' ');
- const mapFileReportedPath =
- chunks.length === 2 ? chunks[1] : chunks[chunks.length - 1].slice(1, -1);
-
- const details = yield* getErrorRelatedSources(name, mapFileReportedPath);
- if (details === undefined) {
- return {
- _tag: 'stack-entry' as const,
- runPath: stackLine.replaceAll(stackAtRegex, 'at '),
- };
- }
- if (isRawErrorLocation(details)) {
- return details;
- }
-
- const regex = new RegExp(`${process.cwd()}/node_modules/`);
- if (details.sourcesPath?.match(regex)) {
- return undefined;
- }
-
- return details;
- })
- ),
- Effect.map(array => array.filter(maybeSources => maybeSources !== undefined))
+): Effect.Effect<MaybeMappedSources[], never, FileSystem | Path> =>
+ Effect.forEach(stacktrace, stackLine =>
+ Effect.gen(function* () {
+ const chunks = stackLine.trimStart().split(' ');
+ const mapFileReportedPath =
+ chunks.length === 2 ? chunks[1] : chunks[chunks.length - 1].slice(1, -1);
+
+ const details = yield* getErrorRelatedSources(name, mapFileReportedPath);
+ if (details === undefined) {
+ return MappedSources['stack-entry']({
+ runPath: stackLine.replaceAll(stackAtRegex, 'at '),
+ });
+ }
+
+ // `node_modules` frames are already dropped by `getSourcesFromMapFile`,
+ // which compares resolved paths through the `Path` service instead of
+ // interpolating the working directory into an unescaped `RegExp`.
+ return details;
+ })
);
diff --git a/ts/packages/cli/src/effect-errors/sourcemaps/transform-raw-error.ts b/ts/packages/cli/src/effect-errors/sourcemaps/transform-raw-error.ts
index a241072ac..e80be1e7d 100644
--- a/ts/packages/cli/src/effect-errors/sourcemaps/transform-raw-error.ts
+++ b/ts/packages/cli/src/effect-errors/sourcemaps/transform-raw-error.ts
@@ -1,4 +1,4 @@
-import { Effect, pipe } from 'effect';
+import { Effect, Struct, pipe } from 'effect';
import { stripCwdPath } from 'effect-errors/logic/path';
import { stackAtRegex } from 'effect-errors/logic/stack';
@@ -8,6 +8,8 @@ import type { PrettyError } from '../types/pretty-error.type';
import { getSourcesFromSpan } from './get-sources-from-span';
import { getSourcesFromStack } from './get-sources-from-stack';
+const dropTag = Struct.omit('_tag');
+
export const transformRawError =
({ stripCwd }: CaptureErrorsOptions) =>
({ message, stack: maybeStack, span, errorType, isPlainString }: PrettyError) =>
@@ -28,8 +30,10 @@ export const transformRawError =
errorType,
message,
stack: stack?.replaceAll(stackAtRegex, 'at ').split('\r\n'),
- sources: sources.length > 0 ? sources.map(({ _tag, ...data }) => data) : undefined,
- location: location.length > 0 ? location.map(({ _tag, ...data }) => data) : undefined,
+ // `Struct.omit` returns a plain object, dropping the `Data` prototype
+ // along with the tag: these values leave the source-map layer here.
+ sources: sources.length > 0 ? sources.map(dropTag) : undefined,
+ location: location.length > 0 ? location.map(dropTag) : undefined,
spans,
isPlainString,
};
diff --git a/ts/packages/cli/test/src/effect-errors/get-sources-from-map-file.test.ts b/ts/packages/cli/test/src/effect-errors/get-sources-from-map-file.test.ts
new file mode 100644
index 000000000..0136f4533
--- /dev/null
+++ b/ts/packages/cli/test/src/effect-errors/get-sources-from-map-file.test.ts
@@ -0,0 +1,304 @@
+import { FileSystem, Path } from '@effect/platform';
+import { BunFileSystem, BunPath } from '@effect/platform-bun';
+import { describe, expect, it } from '@effect/vitest';
+import { Cause, Effect, Layer, Scope } from 'effect';
+import { type RawSourceMap, SourceMapConsumer } from 'source-map-js';
+
+import { captureErrors } from 'src/effect-errors/capture-errors';
+import { getSourcesFromMapFile } from 'src/effect-errors/sourcemaps/get-sources-from-map-file';
+
+const TestPlatform = Layer.mergeAll(BunFileSystem.layer, BunPath.layer);
+const locationFor = (filePath: string) => ({ filePath, line: 1, column: 0 });
+
+const makeSourceMapFixture = (
+ mapContents: string,
+ options: { readonly directory?: string; readonly sourceContents?: string } = {}
+) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const directory = yield* fs.makeTempDirectoryScoped({
+ directory: options.directory,
+ prefix: 'composio-sourcemap-',
+ });
+ const generatedFile = path.join(directory, 'app.js');
+
+ yield* fs.writeFileString(`${generatedFile}.map`, mapContents);
+ if (options.sourceContents !== undefined) {
+ yield* fs.writeFileString(path.join(directory, 'app.ts'), options.sourceContents);
+ }
+
+ return { directory, generatedFile };
+ });
+
+const run = <A, E>(effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path | Scope.Scope>) =>
+ effect.pipe(Effect.provide(TestPlatform));
+
+describe('getSourcesFromMapFile', () => {
+ it.scoped('falls back to the full raw location when source-map JSON is malformed', () =>
+ run(
+ Effect.gen(function* () {
+ const { generatedFile } = yield* makeSourceMapFixture('{ this is not valid JSON');
+ const location = locationFor(generatedFile);
+
+ expect(yield* getSourcesFromMapFile('app.js', location)).toStrictEqual({
+ _tag: 'location',
+ name: 'app.js',
+ ...location,
+ });
+ })
+ )
+ );
+
+ it.scoped('falls back when valid JSON is not a usable source map', () =>
+ run(
+ Effect.gen(function* () {
+ const invalidSourceMap = JSON.stringify({
+ version: 2,
+ sources: [],
+ names: [],
+ mappings: '',
+ });
+ const { generatedFile } = yield* makeSourceMapFixture(invalidSourceMap);
+ const location = locationFor(generatedFile);
+
+ expect(yield* getSourcesFromMapFile('app.js', location)).toStrictEqual({
+ _tag: 'location',
+ name: 'app.js',
+ ...location,
+ });
+ })
+ )
+ );
+
+ it.scoped('falls back when source-map resolution rejects schema-valid data', () =>
+ run(
+ Effect.gen(function* () {
+ const invalidSourceMap = {
+ version: '3',
+ sources: ['app.ts'],
+ names: [],
+ mappings: '!',
+ } satisfies RawSourceMap;
+ expect(() =>
+ new SourceMapConsumer(invalidSourceMap).originalPositionFor({
+ line: 1,
+ column: 0,
+ })
+ ).toThrow('Invalid base64 digit');
+
+ const { generatedFile } = yield* makeSourceMapFixture(JSON.stringify(invalidSourceMap));
+ const location = locationFor(generatedFile);
+
+ expect(yield* getSourcesFromMapFile('app.js', location)).toStrictEqual({
+ _tag: 'location',
+ name: 'app.js',
+ ...location,
+ });
+ })
+ )
+ );
+
+ it.scoped('falls back when the map points at a source file that was never shipped', () =>
+ run(
+ Effect.gen(function* () {
+ const validSourceMap = JSON.stringify({
+ version: 3,
+ file: 'app.js',
+ sources: ['app.ts'],
+ names: [],
+ mappings: 'AAAA',
+ });
+ // No `sourceContents`, so `app.ts` does not exist next to the map.
+ const { generatedFile } = yield* makeSourceMapFixture(validSourceMap);
+ const location = locationFor(generatedFile);
+
+ expect(yield* getSourcesFromMapFile('app.js', location)).toStrictEqual({
+ _tag: 'location',
+ name: 'app.js',
+ ...location,
+ });
+ })
+ )
+ );
+
+ it.scoped('falls back when the .map path is a directory rather than a file', () =>
+ run(
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: 'composio-sourcemap-' });
+ const generatedFile = path.join(directory, 'app.js');
+ yield* fs.makeDirectory(`${generatedFile}.map`);
+ const location = locationFor(generatedFile);
+
+ expect(yield* getSourcesFromMapFile('app.js', location)).toStrictEqual({
+ _tag: 'location',
+ name: 'app.js',
+ ...location,
+ });
+ })
+ )
+ );
+
+ it.scoped('enriches maps that use null for the optional file and sourceRoot keys', () =>
+ run(
+ Effect.gen(function* () {
+ const sourceContents = "throw new Error('primary diagnostic');\n";
+ // `source-map-js` accepts both; rejecting them would silently drop
+ // enrichment for maps emitted without an output file name.
+ const nullableSourceMap = JSON.stringify({
+ version: 3,
+ file: null,
+ sourceRoot: null,
+ sources: ['app.ts'],
+ names: [],
+ mappings: 'AAAA',
+ });
+ const { directory, generatedFile } = yield* makeSourceMapFixture(nullableSourceMap, {
+ sourceContents,
+ });
+ const path = yield* Path.Path;
+
+ expect(yield* getSourcesFromMapFile('app.js', locationFor(generatedFile))).toMatchObject({
+ _tag: 'sources',
+ sourcesPath: `${path.join(directory, 'app.ts')}:1:1`,
+ });
+ })
+ )
+ );
+
+ it.scoped('still enriches locations from valid source maps', () =>
+ run(
+ Effect.gen(function* () {
+ const sourceContents = "throw new Error('primary diagnostic');\n";
+ const validSourceMap = JSON.stringify({
+ version: 3,
+ file: 'app.js',
+ sources: ['app.ts'],
+ names: [],
+ mappings: 'AAAA',
+ });
+ const { directory, generatedFile } = yield* makeSourceMapFixture(validSourceMap, {
+ sourceContents,
+ });
+ const path = yield* Path.Path;
+
+ expect(yield* getSourcesFromMapFile('app.js', locationFor(generatedFile))).toStrictEqual({
+ _tag: 'sources',
+ name: 'app.js',
+ runPath: `${generatedFile}:1:0`,
+ sourcesPath: `${path.join(directory, 'app.ts')}:1:1`,
+ source: [
+ { line: 1, code: "throw new Error('primary diagnostic');", column: 1 },
+ { line: 2, code: '', column: undefined },
+ ],
+ });
+ })
+ )
+ );
+
+ it.scoped('preserves the primary diagnostic through captureErrors', () =>
+ run(
+ Effect.gen(function* () {
+ const path = yield* Path.Path;
+ const workingDirectory = path.resolve('.');
+ const { generatedFile } = yield* makeSourceMapFixture('{ malformed', {
+ directory: workingDirectory,
+ });
+ const primary = new Error('primary diagnostic');
+ primary.stack = `Error: primary diagnostic\n at ${generatedFile}:1:0`;
+
+ const captured = yield* captureErrors(Cause.die(primary));
+
+ expect(captured.errors).toHaveLength(1);
+ expect(captured.errors[0]).toMatchObject({
+ errorType: 'Error',
+ message: ['primary diagnostic'],
+ location: [
+ {
+ name: '',
+ filePath: generatedFile.replace(workingDirectory, ''),
+ line: 1,
+ column: 0,
+ },
+ ],
+ });
+ })
+ )
+ );
+
+ it.scoped('preserves the primary diagnostic when the original source is missing', () =>
+ run(
+ Effect.gen(function* () {
+ const path = yield* Path.Path;
+ const workingDirectory = path.resolve('.');
+ const validSourceMap = JSON.stringify({
+ version: 3,
+ file: 'app.js',
+ sources: ['app.ts'],
+ names: [],
+ mappings: 'AAAA',
+ });
+ // A valid map whose original source was never shipped — the common
+ // shape for a compiled binary — must not abort error capture either.
+ const { generatedFile } = yield* makeSourceMapFixture(validSourceMap, {
+ directory: workingDirectory,
+ });
+ const primary = new Error('primary diagnostic');
+ primary.stack = `Error: primary diagnostic\n at ${generatedFile}:1:0`;
+
+ const captured = yield* captureErrors(Cause.die(primary));
+
+ expect(captured.errors).toHaveLength(1);
+ expect(captured.errors[0]).toMatchObject({
+ errorType: 'Error',
+ message: ['primary diagnostic'],
+ location: [
+ {
+ name: '',
+ filePath: generatedFile.replace(workingDirectory, ''),
+ line: 1,
+ column: 0,
+ },
+ ],
+ });
+ })
+ )
+ );
+
+ it.scoped('preserves the primary diagnostic when a .ts frame is unreadable', () =>
+ run(
+ Effect.gen(function* () {
+ const path = yield* Path.Path;
+ const fs = yield* FileSystem.FileSystem;
+ const workingDirectory = path.resolve('.');
+ const directory = yield* fs.makeTempDirectoryScoped({
+ directory: workingDirectory,
+ prefix: 'composio-sourcemap-',
+ });
+ // TypeScript frames skip source maps entirely and read the file
+ // directly; a deleted file must degrade rather than abort.
+ const missingSource = path.join(directory, 'missing.ts');
+ const primary = new Error('primary diagnostic');
+ primary.stack = `Error: primary diagnostic\n at ${missingSource}:1:0`;
+
+ const captured = yield* captureErrors(Cause.die(primary));
+
+ expect(captured.errors).toHaveLength(1);
+ expect(captured.errors[0]).toMatchObject({
+ errorType: 'Error',
+ message: ['primary diagnostic'],
+ location: [
+ {
+ name: '',
+ filePath: missingSource.replace(workingDirectory, ''),
+ line: 1,
+ column: 0,
+ },
+ ],
+ });
+ })
+ )
+ );
+});